2 * Copyright (c) 1995-2003, Index Data
3 * See the file LICENSE for details.
5 * $Id: seshigh.c,v 1.152 2003-03-25 09:55:11 adam Exp $
9 * Frontend server logic.
11 * This code receives incoming APDUs, and handles client requests by means
14 * Some of the code is getting quite involved, compared to simpler servers -
15 * primarily because it is asynchronous both in the communication with
16 * the user and the backend. We think the complexity will pay off in
17 * the form of greater flexibility when more asynchronous facilities
20 * Memory management has become somewhat involved. In the simple case, where
21 * only one PDU is pending at a time, it will simply reuse the same memory,
22 * once it has found its working size. When we enable multiple concurrent
23 * operations, perhaps even with multiple parallel calls to the backend, it
24 * will maintain a pool of buffers for encoding and decoding, trying to
25 * minimize memory allocation/deallocation during normal operation.
31 #include <sys/types.h>
34 #define S_ISREG(x) (x & _S_IFREG)
44 #include <yaz/yconfig.h>
45 #include <yaz/xmalloc.h>
46 #include <yaz/comstack.h>
49 #include <yaz/proto.h>
52 #include <yaz/logrpn.h>
53 #include <yaz/statserv.h>
54 #include <yaz/diagbib1.h>
55 #include <yaz/charneg.h>
56 #include <yaz/otherinfo.h>
57 #include <yaz/yaz-util.h>
58 #include <yaz/pquery.h>
61 #include <yaz/backend.h>
63 static void process_gdu_request(association *assoc, request *req);
64 static int process_z_request(association *assoc, request *req, char **msg);
65 void backend_response(IOCHAN i, int event);
66 static int process_gdu_response(association *assoc, request *req, Z_GDU *res);
67 static int process_z_response(association *assoc, request *req, Z_APDU *res);
68 static Z_APDU *process_initRequest(association *assoc, request *reqb);
69 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
71 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
72 bend_search_rr *bsrr, int *fd);
73 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
75 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
76 static Z_APDU *process_sortRequest(association *assoc, request *reqb, int *fd);
77 static void process_close(association *assoc, request *reqb);
78 void save_referenceId (request *reqb, Z_ReferenceId *refid);
79 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
81 static Z_APDU *process_segmentRequest (association *assoc, request *reqb);
83 static FILE *apduf = 0; /* for use in static mode */
84 static statserv_options_block *control_block = 0;
86 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd);
89 * Create and initialize a new association-handle.
90 * channel : iochannel for the current line.
91 * link : communications channel.
92 * Returns: 0 or a new association handle.
94 association *create_association(IOCHAN channel, COMSTACK link)
99 control_block = statserv_getcontrol();
100 if (!(anew = (association *)xmalloc(sizeof(*anew))))
104 anew->client_chan = channel;
105 anew->client_link = link;
106 anew->cs_get_mask = 0;
107 anew->cs_put_mask = 0;
108 anew->cs_accept_mask = 0;
109 if (!(anew->decode = odr_createmem(ODR_DECODE)) ||
110 !(anew->encode = odr_createmem(ODR_ENCODE)))
112 if (*control_block->apdufile)
117 strcpy(filename, control_block->apdufile);
118 if (!(anew->print = odr_createmem(ODR_PRINT)))
120 if (*control_block->apdufile == '@')
122 odr_setprint(anew->print, yaz_log_file());
124 else if (*control_block->apdufile != '-')
126 strcpy(filename, control_block->apdufile);
127 if (!control_block->dynamic)
131 if (!(apduf = fopen(filename, "w")))
133 yaz_log(LOG_WARN|LOG_ERRNO, "%s", filename);
136 setvbuf(apduf, 0, _IONBF, 0);
142 sprintf(filename + strlen(filename), ".%d", getpid());
143 if (!(f = fopen(filename, "w")))
145 yaz_log(LOG_WARN|LOG_ERRNO, "%s", filename);
148 setvbuf(f, 0, _IONBF, 0);
150 odr_setprint(anew->print, f);
155 anew->input_buffer = 0;
156 anew->input_buffer_len = 0;
158 anew->state = ASSOC_NEW;
159 request_initq(&anew->incoming);
160 request_initq(&anew->outgoing);
161 anew->proto = cs_getproto(link);
166 * Free association and release resources.
168 void destroy_association(association *h)
170 statserv_options_block *cb = statserv_getcontrol();
173 odr_destroy(h->decode);
174 odr_destroy(h->encode);
176 odr_destroy(h->print);
178 xfree(h->input_buffer);
180 (*cb->bend_close)(h->backend);
181 while (request_deq(&h->incoming));
182 while (request_deq(&h->outgoing));
183 request_delq(&h->incoming);
184 request_delq(&h->outgoing);
186 xmalloc_trav("session closed");
187 if (control_block && control_block->one_shot)
193 static void do_close_req(association *a, int reason, char *message,
197 Z_Close *cls = zget_Close(a->encode);
199 /* Purge request queue */
200 while (request_deq(&a->incoming));
201 while (request_deq(&a->outgoing));
204 yaz_log(LOG_LOG, "Sending Close PDU, reason=%d, message=%s",
205 reason, message ? message : "none");
206 apdu.which = Z_APDU_close;
208 *cls->closeReason = reason;
209 cls->diagnosticInformation = message;
210 process_z_response(a, req, &apdu);
211 iochan_settimeout(a->client_chan, 20);
215 yaz_log(LOG_DEBUG, "v2 client. No Close PDU");
216 iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
218 a->state = ASSOC_DEAD;
221 static void do_close(association *a, int reason, char *message)
223 do_close_req (a, reason, message, request_get(&a->outgoing));
227 * This is where PDUs from the client are read and the further
228 * processing is initiated. Flow of control moves down through the
229 * various process_* functions below, until the encoded result comes back up
230 * to the output handler in here.
232 * h : the I/O channel that has an outstanding event.
233 * event : the current outstanding event.
235 void ir_session(IOCHAN h, int event)
238 association *assoc = (association *)iochan_getdata(h);
239 COMSTACK conn = assoc->client_link;
242 assert(h && conn && assoc);
243 if (event == EVENT_TIMEOUT)
245 if (assoc->state != ASSOC_UP)
247 yaz_log(LOG_LOG, "Final timeout - closing connection.");
249 destroy_association(assoc);
254 yaz_log(LOG_LOG, "Session idle too long. Sending close.");
255 do_close(assoc, Z_Close_lackOfActivity, 0);
259 if (event & assoc->cs_accept_mask)
261 yaz_log (LOG_DEBUG, "ir_session (accept)");
262 if (!cs_accept (conn))
264 yaz_log (LOG_LOG, "accept failed");
265 destroy_association(assoc);
268 iochan_clearflag (h, EVENT_OUTPUT|EVENT_OUTPUT);
269 if (conn->io_pending)
270 { /* cs_accept didn't complete */
271 assoc->cs_accept_mask =
272 ((conn->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
273 ((conn->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
275 iochan_setflag (h, assoc->cs_accept_mask);
278 { /* cs_accept completed. Prepare for reading (cs_get) */
279 assoc->cs_accept_mask = 0;
280 assoc->cs_get_mask = EVENT_INPUT;
281 iochan_setflag (h, assoc->cs_get_mask);
285 if ((event & assoc->cs_get_mask) || (event & EVENT_WORK)) /* input */
287 if ((assoc->cs_put_mask & EVENT_INPUT) == 0 && (event & assoc->cs_get_mask))
289 yaz_log(LOG_DEBUG, "ir_session (input)");
290 /* We aren't speaking to this fellow */
291 if (assoc->state == ASSOC_DEAD)
293 yaz_log(LOG_LOG, "Connection closed - end of session");
295 destroy_association(assoc);
299 assoc->cs_get_mask = EVENT_INPUT;
300 if ((res = cs_get(conn, &assoc->input_buffer,
301 &assoc->input_buffer_len)) <= 0)
303 yaz_log(LOG_LOG, "Connection closed by client");
305 destroy_association(assoc);
309 else if (res == 1) /* incomplete read - wait for more */
311 if (conn->io_pending & CS_WANT_WRITE)
312 assoc->cs_get_mask |= EVENT_OUTPUT;
313 iochan_setflag(h, assoc->cs_get_mask);
316 if (cs_more(conn)) /* more stuff - call us again later, please */
317 iochan_setevent(h, EVENT_INPUT);
319 /* we got a complete PDU. Let's decode it */
320 yaz_log(LOG_DEBUG, "Got PDU, %d bytes: lead=%02X %02X %02X", res,
321 assoc->input_buffer[0] & 0xff,
322 assoc->input_buffer[1] & 0xff,
323 assoc->input_buffer[2] & 0xff);
324 req = request_get(&assoc->incoming); /* get a new request */
325 odr_reset(assoc->decode);
326 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
327 if (!z_GDU(assoc->decode, &req->gdu_request, 0, 0))
329 yaz_log(LOG_LOG, "ODR error on incoming PDU: %s [near byte %d] ",
330 odr_errmsg(odr_geterror(assoc->decode)),
331 odr_offset(assoc->decode));
332 if (assoc->decode->error != OHTTP)
334 yaz_log(LOG_LOG, "PDU dump:");
335 odr_dumpBER(yaz_log_file(), assoc->input_buffer, res);
336 do_close(assoc, Z_Close_protocolError, "Malformed package");
340 Z_GDU *p = z_get_HTTP_Response(assoc->encode, 400);
341 assoc->state = ASSOC_DEAD;
342 process_gdu_response(assoc, req, p);
346 req->request_mem = odr_extract_mem(assoc->decode);
347 if (assoc->print && !z_GDU(assoc->print, &req->gdu_request, 0, 0))
349 yaz_log(LOG_WARN, "ODR print error: %s",
350 odr_errmsg(odr_geterror(assoc->print)));
351 odr_reset(assoc->print);
353 request_enq(&assoc->incoming, req);
356 /* can we do something yet? */
357 req = request_head(&assoc->incoming);
358 if (req->state == REQUEST_IDLE)
360 request_deq(&assoc->incoming);
361 process_gdu_request(assoc, req);
364 if (event & assoc->cs_put_mask)
366 request *req = request_head(&assoc->outgoing);
368 assoc->cs_put_mask = 0;
369 yaz_log(LOG_DEBUG, "ir_session (output)");
370 req->state = REQUEST_PENDING;
371 switch (res = cs_put(conn, req->response, req->len_response))
374 yaz_log(LOG_LOG, "Connection closed by client");
376 destroy_association(assoc);
379 case 0: /* all sent - release the request structure */
380 yaz_log(LOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
382 yaz_log(LOG_DEBUG, "HTTP out:\n%.*s", req->len_response,
385 nmem_destroy(req->request_mem);
386 request_deq(&assoc->outgoing);
387 request_release(req);
388 if (!request_head(&assoc->outgoing))
389 { /* restore mask for cs_get operation ... */
390 iochan_clearflag(h, EVENT_OUTPUT|EVENT_INPUT);
391 iochan_setflag(h, assoc->cs_get_mask);
392 if (assoc->state == ASSOC_DEAD)
393 iochan_setevent(assoc->client_chan, EVENT_TIMEOUT);
397 assoc->cs_put_mask = EVENT_OUTPUT;
401 if (conn->io_pending & CS_WANT_WRITE)
402 assoc->cs_put_mask |= EVENT_OUTPUT;
403 if (conn->io_pending & CS_WANT_READ)
404 assoc->cs_put_mask |= EVENT_INPUT;
405 iochan_setflag(h, assoc->cs_put_mask);
408 if (event & EVENT_EXCEPT)
410 yaz_log(LOG_LOG, "ir_session (exception)");
412 destroy_association(assoc);
417 static int process_z_request(association *assoc, request *req, char **msg);
419 static void assoc_init_reset(association *assoc)
422 assoc->init = (bend_initrequest *) xmalloc (sizeof(*assoc->init));
424 assoc->init->stream = assoc->encode;
425 assoc->init->print = assoc->print;
426 assoc->init->auth = 0;
427 assoc->init->referenceId = 0;
428 assoc->init->implementation_version = 0;
429 assoc->init->implementation_id = 0;
430 assoc->init->implementation_name = 0;
431 assoc->init->bend_sort = NULL;
432 assoc->init->bend_search = NULL;
433 assoc->init->bend_present = NULL;
434 assoc->init->bend_esrequest = NULL;
435 assoc->init->bend_delete = NULL;
436 assoc->init->bend_scan = NULL;
437 assoc->init->bend_segment = NULL;
438 assoc->init->bend_fetch = NULL;
439 assoc->init->bend_explain = NULL;
441 assoc->init->charneg_request = NULL;
442 assoc->init->charneg_response = NULL;
444 assoc->init->decode = assoc->decode;
445 assoc->init->peer_name =
446 odr_strdup (assoc->encode, cs_addrstr(assoc->client_link));
449 static int srw_bend_init(association *assoc)
451 const char *encoding = "UTF-8";
453 bend_initresult *binitres;
454 statserv_options_block *cb = statserv_getcontrol();
456 assoc_init_reset(assoc);
458 assoc->maximumRecordSize = 3000000;
459 assoc->preferredMessageSize = 3000000;
461 ce = yaz_set_proposal_charneg(assoc->decode, &encoding, 1, 0, 0, 1);
462 assoc->init->charneg_request = ce->u.charNeg3;
464 if (!(binitres = (*cb->bend_init)(assoc->init)))
466 yaz_log(LOG_WARN, "Bad response from backend.");
469 assoc->backend = binitres->handle;
473 static int srw_bend_fetch(association *assoc, int pos,
474 Z_SRW_searchRetrieveRequest *srw_req,
475 Z_SRW_record *record)
478 ODR o = assoc->encode;
480 rr.setname = "default";
483 rr.request_format = VAL_TEXT_XML;
484 rr.request_format_raw = yaz_oidval_to_z3950oid(assoc->decode,
487 rr.comp = (Z_RecordComposition *)
488 odr_malloc(assoc->decode, sizeof(*rr.comp));
489 rr.comp->which = Z_RecordComp_complex;
490 rr.comp->u.complex = (Z_CompSpec *)
491 odr_malloc(assoc->decode, sizeof(Z_CompSpec));
492 rr.comp->u.complex->selectAlternativeSyntax = (bool_t *)
493 odr_malloc(assoc->encode, sizeof(bool_t));
494 *rr.comp->u.complex->selectAlternativeSyntax = 0;
495 rr.comp->u.complex->num_dbSpecific = 0;
496 rr.comp->u.complex->dbSpecific = 0;
497 rr.comp->u.complex->num_recordSyntax = 0;
498 rr.comp->u.complex->recordSyntax = 0;
500 rr.comp->u.complex->generic = (Z_Specification *)
501 odr_malloc(assoc->decode, sizeof(Z_Specification));
502 rr.comp->u.complex->generic->which = Z_Schema_uri;
503 rr.comp->u.complex->generic->schema.uri = srw_req->recordSchema;
504 rr.comp->u.complex->generic->elementSpec = 0;
506 rr.stream = assoc->encode;
507 rr.print = assoc->print;
513 rr.output_format = VAL_TEXT_XML;
514 rr.output_format_raw = 0;
517 rr.surrogate_flag = 0;
519 if (!assoc->init->bend_fetch)
522 (*assoc->init->bend_fetch)(assoc->backend, &rr);
526 record->recordData_buf = rr.record;
527 record->recordData_len = rr.len;
528 record->recordPosition = odr_intdup(o, pos);
529 record->recordSchema = 0;
530 if (srw_req->recordSchema)
531 record->recordSchema = odr_strdup(o, srw_req->recordSchema);
536 static void srw_bend_search(association *assoc, request *req,
537 Z_SRW_searchRetrieveRequest *srw_req,
538 Z_SRW_searchRetrieveResponse *srw_res)
544 yaz_log(LOG_LOG, "Got SRW SearchRetrieveRequest");
545 yaz_log(LOG_DEBUG, "srw_bend_search");
548 yaz_log(LOG_DEBUG, "srw_bend_init");
549 if (!srw_bend_init(assoc))
551 srw_error = 3; /* assume Authentication error */
553 srw_res->num_diagnostics = 1;
554 srw_res->diagnostics = (Z_SRW_diagnostic *)
555 odr_malloc(assoc->encode, sizeof(*srw_res->diagnostics));
556 srw_res->diagnostics[0].code =
557 odr_intdup(assoc->encode, srw_error);
558 srw_res->diagnostics[0].details = 0;
563 rr.setname = "default";
566 rr.basenames = &srw_req->database;
569 rr.query = (Z_Query *) odr_malloc (assoc->decode, sizeof(*rr.query));
571 if (srw_req->query_type == Z_SRW_query_type_cql)
573 ext = (Z_External *) odr_malloc(assoc->decode, sizeof(*ext));
574 ext->direct_reference = odr_getoidbystr(assoc->decode,
575 "1.2.840.10003.16.2");
576 ext->indirect_reference = 0;
578 ext->which = Z_External_CQL;
579 ext->u.cql = srw_req->query.cql;
581 rr.query->which = Z_Query_type_104;
582 rr.query->u.type_104 = ext;
584 else if (srw_req->query_type == Z_SRW_query_type_pqf)
586 Z_RPNQuery *RPNquery;
587 YAZ_PQF_Parser pqf_parser;
589 pqf_parser = yaz_pqf_create ();
591 RPNquery = yaz_pqf_parse (pqf_parser, assoc->decode,
597 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
598 yaz_log(LOG_LOG, "%*s^\n", off+4, "");
599 yaz_log(LOG_LOG, "Bad PQF: %s (code %d)\n", pqf_msg, code);
604 rr.query->which = Z_Query_type_1;
605 rr.query->u.type_1 = RPNquery;
607 yaz_pqf_destroy (pqf_parser);
612 if (!srw_error && srw_req->sort_type != Z_SRW_sort_type_none)
615 if (!srw_error && !assoc->init->bend_search)
620 yaz_log(LOG_DEBUG, "srw_bend_search returned SRW error %d", srw_error);
621 srw_res->num_diagnostics = 1;
622 srw_res->diagnostics = (Z_SRW_diagnostic *)
623 odr_malloc(assoc->encode, sizeof(*srw_res->diagnostics));
624 srw_res->diagnostics[0].code =
625 odr_intdup(assoc->encode, srw_error);
626 srw_res->diagnostics[0].details = 0;
630 rr.stream = assoc->encode;
631 rr.decode = assoc->decode;
632 rr.print = assoc->print;
634 rr.association = assoc;
640 yaz_log_zquery(rr.query);
641 (assoc->init->bend_search)(assoc->backend, &rr);
642 srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
645 yaz_log(LOG_DEBUG, "bend_search returned Bib-1 code %d", rr.errcode);
646 srw_res->num_diagnostics = 1;
647 srw_res->diagnostics = (Z_SRW_diagnostic *)
648 odr_malloc(assoc->encode, sizeof(*srw_res->diagnostics));
649 srw_res->diagnostics[0].code =
650 odr_intdup(assoc->encode,
651 yaz_diag_bib1_to_srw (rr.errcode));
652 srw_res->diagnostics[0].details = rr.errstring;
653 yaz_log(LOG_DEBUG, "srw_bend_search returned SRW error %d",
654 srw_res->diagnostics[0].code);
659 srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
660 if (srw_req->maximumRecords && *srw_req->maximumRecords > 0)
662 int number = *srw_req->maximumRecords;
666 if (srw_req->startRecord)
667 start = *srw_req->startRecord;
669 yaz_log(LOG_DEBUG, "srw_bend_search. start=%d max=%d",
670 start, *srw_req->maximumRecords);
672 if (start <= rr.hits)
675 int packing = Z_SRW_recordPacking_string;
676 if (start + number > rr.hits)
677 number = rr.hits - start + 1;
678 if (srw_req->recordPacking &&
679 !strcmp(srw_req->recordPacking, "xml"))
680 packing = Z_SRW_recordPacking_XML;
681 srw_res->records = (Z_SRW_record *)
682 odr_malloc(assoc->encode,
683 number * sizeof(*srw_res->records));
684 for (i = 0; i<number; i++)
688 srw_res->records[j].recordPacking = packing;
689 srw_res->records[j].recordData_buf = 0;
690 yaz_log(LOG_DEBUG, "srw_bend_fetch %d", i+start);
691 errcode = srw_bend_fetch(assoc, i+start, srw_req,
692 srw_res->records + j);
695 srw_res->num_diagnostics = 1;
696 srw_res->diagnostics = (Z_SRW_diagnostic *)
697 odr_malloc(assoc->encode,
698 sizeof(*srw_res->diagnostics));
699 srw_res->diagnostics[0].code =
700 odr_intdup(assoc->encode,
701 yaz_diag_bib1_to_srw (errcode));
702 srw_res->diagnostics[0].details = rr.errstring;
705 if (srw_res->records[j].recordData_buf)
708 srw_res->num_records = j;
710 srw_res->records = 0;
717 static void srw_bend_explain(association *assoc, request *req,
718 Z_SRW_explainRequest *srw_req,
719 Z_SRW_explainResponse *srw_res)
721 yaz_log(LOG_LOG, "Got SRW ExplainRequest");
724 yaz_log(LOG_DEBUG, "srw_bend_init");
725 if (!srw_bend_init(assoc))
728 if (assoc->init && assoc->init->bend_explain)
732 rr.stream = assoc->encode;
733 rr.decode = assoc->decode;
734 rr.print = assoc->print;
736 (*assoc->init->bend_explain)(assoc->backend, &rr);
739 srw_res->explainData_buf = rr.explain_buf;
740 srw_res->explainData_len = strlen(rr.explain_buf);
745 static int hex_digit (int ch)
747 if (ch >= '0' && ch <= '9')
749 else if (ch >= 'a' && ch <= 'f')
751 else if (ch >= 'A' && ch <= 'F')
756 static char *uri_val(const char *path, const char *name, ODR o)
758 size_t nlen = strlen(name);
762 while (path && *path)
764 const char *p1 = strchr(path, '=');
767 if (p1 - path == nlen && !memcmp(path, name, nlen))
773 p1 = strchr(path, '&');
775 p1 = strlen(path) + path;
776 ret = odr_malloc(o, p1 - path + 1);
777 while (*path && *path != '&')
784 else if (*path == '%' && path[1] && path[2])
786 ret[i++] = hex_digit (path[1])*16 + hex_digit (path[2]);
795 path = strchr(p1, '&');
802 void uri_val_int(const char *path, const char *name, ODR o, int **intp)
804 const char *v = uri_val(path, name, o);
806 *intp = odr_intdup(o, atoi(v));
809 static void process_http_request(association *assoc, request *req)
811 Z_HTTP_Request *hreq = req->gdu_request->u.HTTP_Request;
812 ODR o = assoc->encode;
814 Z_HTTP_Response *hres = 0;
817 if (!strcmp(hreq->method, "GET"))
821 Z_SOAP *soap_package = 0;
822 char *db = "Default";
823 const char *p0 = hreq->path, *p1;
824 static Z_SOAP_Handler soap_handlers[2] = {
826 {"http://www.loc.gov/zing/srw/v1.0/", 0,
827 (Z_SOAP_fun) yaz_srw_codec},
834 p1 = strchr(p0, '?');
836 p1 = p0 + strlen(p0);
839 db = odr_malloc(assoc->decode, p1 - p0 + 1);
840 memcpy (db, p0, p1 - p0);
844 if (p1 && *p1 == '?' && p1[1])
846 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_searchRetrieve_response);
847 Z_SRW_PDU *sr = yaz_srw_get(o, Z_SRW_searchRetrieve_request);
848 char *query = uri_val(p1, "query", o);
849 char *pQuery = uri_val(p1, "pQuery", o);
850 char *sortKeys = uri_val(p1, "sortKeys", o);
854 sr->u.request->query_type = Z_SRW_query_type_cql;
855 sr->u.request->query.cql = query;
859 sr->u.request->query_type = Z_SRW_query_type_pqf;
860 sr->u.request->query.pqf = pQuery;
864 sr->u.request->sort_type = Z_SRW_sort_type_sort;
865 sr->u.request->sort.sortKeys = sortKeys;
867 sr->u.request->recordSchema = uri_val(p1, "recordSchema", o);
868 sr->u.request->recordPacking = uri_val(p1, "recordPacking", o);
869 uri_val_int(p1, "maximumRecords", o,
870 &sr->u.request->maximumRecords);
871 uri_val_int(p1, "startRecord", o,
872 &sr->u.request->startRecord);
873 if (sr->u.request->startRecord)
874 yaz_log(LOG_LOG, "startRecord=%d", *sr->u.request->startRecord);
875 sr->u.request->database = db;
876 srw_bend_search(assoc, req, sr->u.request, res->u.response);
878 soap_package = odr_malloc(o, sizeof(*soap_package));
879 soap_package->which = Z_SOAP_generic;
881 soap_package->u.generic =
882 odr_malloc(o, sizeof(*soap_package->u.generic));
884 soap_package->u.generic->p = res;
885 soap_package->u.generic->ns = soap_handlers[0].ns;
886 soap_package->u.generic->no = 0;
888 soap_package->ns = "SRU";
890 p = z_get_HTTP_Response(o, 200);
891 hres = p->u.HTTP_Response;
893 ret = z_soap_codec_enc(assoc->encode, &soap_package,
894 &hres->content_buf, &hres->content_len,
895 soap_handlers, charset);
897 z_HTTP_header_add(o, &hres->headers, "Content-Type", "text/xml");
901 strcpy(ctype, "text/xml; charset=");
902 strcat(ctype, charset);
903 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
909 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_explain_response);
910 Z_SRW_PDU *sr = yaz_srw_get(o, Z_SRW_explain_request);
912 srw_bend_explain(assoc, req, sr->u.explain_request,
913 res->u.explain_response);
915 if (res->u.explain_response->explainData_buf)
917 soap_package = odr_malloc(o, sizeof(*soap_package));
918 soap_package->which = Z_SOAP_generic;
920 soap_package->u.generic =
921 odr_malloc(o, sizeof(*soap_package->u.generic));
923 soap_package->u.generic->p = res;
924 soap_package->u.generic->ns = soap_handlers[0].ns;
925 soap_package->u.generic->no = 0;
927 soap_package->ns = "SRU";
929 p = z_get_HTTP_Response(o, 200);
930 hres = p->u.HTTP_Response;
932 ret = z_soap_codec_enc(assoc->encode, &soap_package,
933 &hres->content_buf, &hres->content_len,
934 soap_handlers, charset);
936 z_HTTP_header_add(o, &hres->headers, "Content-Type", "text/xml");
940 strcpy(ctype, "text/xml; charset=");
941 strcat(ctype, charset);
942 z_HTTP_header_add(o, &hres->headers, "Content-Type",
949 if (strlen(hreq->path) >= 5 && strlen(hreq->path) < 80 &&
950 !memcmp(hreq->path, "/doc/", 5))
955 strcpy(fpath, DOCDIR);
956 strcat(fpath, hreq->path+4);
957 f = fopen(fpath, "rb");
960 if (fstat(fileno(f), &sbuf) || !S_ISREG(sbuf.st_mode))
969 fseek(f, 0L, SEEK_END);
971 if (sz >= 0 && sz < 500000)
973 const char *ctype = "application/octet-stream";
976 p = z_get_HTTP_Response(o, 200);
977 hres = p->u.HTTP_Response;
978 hres->content_buf = (char *) odr_malloc(o, sz + 1);
979 hres->content_len = sz;
980 fseek(f, 0L, SEEK_SET);
981 fread(hres->content_buf, 1, sz, f);
982 if ((cp = strrchr(fpath, '.'))) {
984 if (!strcmp(cp, "png"))
986 else if (!strcmp(cp, "gif"))
988 else if (!strcmp(cp, "xml"))
990 else if (!strcmp(cp, "html"))
993 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1001 if (!strcmp(hreq->path, "/"))
1006 const char *doclink = "";
1007 p = z_get_HTTP_Response(o, 200);
1008 hres = p->u.HTTP_Response;
1009 hres->content_buf = (char *) odr_malloc(o, 400);
1011 if (stat(DOCDIR "/yaz.html", &sbuf) == 0 && S_ISREG(sbuf.st_mode))
1012 doclink = "<P><A HREF=\"/doc/yaz.html\">Documentation</A></P>";
1014 sprintf (hres->content_buf,
1015 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n"
1018 " <TITLE>YAZ " YAZ_VERSION "</TITLE>\n"
1021 " <P><A HREF=\"http://www.indexdata.dk/yaz/\">YAZ</A> "
1022 YAZ_VERSION "</P>\n"
1025 "</HTML>\n", doclink);
1026 hres->content_len = strlen(hres->content_buf);
1027 z_HTTP_header_add(o, &hres->headers, "Content-Type", "text/html");
1033 p = z_get_HTTP_Response(o, 404);
1036 else if (!strcmp(hreq->method, "POST"))
1038 const char *content_type = z_HTTP_header_lookup(hreq->headers,
1040 if (content_type && !yaz_strcmp_del("text/xml", content_type, "; "))
1042 Z_SOAP *soap_package = 0;
1044 int http_code = 500;
1045 const char *charset_p = 0;
1048 static Z_SOAP_Handler soap_handlers[2] = {
1050 {"http://www.loc.gov/zing/srw/v1.0/", 0,
1051 (Z_SOAP_fun) yaz_srw_codec},
1055 if ((charset_p = strstr(content_type, "; charset=")))
1059 while (i < 20 && charset_p[i] &&
1060 !strchr("; \n\r", charset_p[i]))
1062 charset = odr_malloc(assoc->encode, i+1);
1063 memcpy(charset, charset_p, i);
1065 yaz_log(LOG_LOG, "SOAP encoding %s", charset);
1067 ret = z_soap_codec(assoc->decode, &soap_package,
1068 &hreq->content_buf, &hreq->content_len,
1071 if (!ret && soap_package->which == Z_SOAP_generic &&
1072 soap_package->u.generic->no == 0)
1075 Z_SRW_PDU *sr = soap_package->u.generic->p;
1077 if (sr->which == Z_SRW_searchRetrieve_request)
1080 yaz_srw_get(assoc->encode,
1081 Z_SRW_searchRetrieve_response);
1083 if (!sr->u.request->database)
1085 const char *p0 = hreq->path, *p1;
1088 p1 = strchr(p0, '?');
1090 p1 = p0 + strlen(p0);
1093 sr->u.request->database =
1094 odr_malloc(assoc->decode, p1 - p0 + 1);
1095 memcpy (sr->u.request->database, p0, p1 - p0);
1096 sr->u.request->database[p1 - p0] = '\0';
1099 sr->u.request->database = "Default";
1101 srw_bend_search(assoc, req, sr->u.request,
1104 soap_package->u.generic->p = res;
1107 else if (sr->which == Z_SRW_explain_request)
1110 yaz_srw_get(assoc->encode, Z_SRW_explain_response);
1112 srw_bend_explain(assoc, req, sr->u.explain_request,
1113 res->u.explain_response);
1114 if (!res->u.explain_response->explainData_buf)
1116 z_soap_error(assoc->encode, soap_package,
1117 "SOAP-ENV:Client", "Explain Not Supported", 0);
1121 soap_package->u.generic->p = res;
1127 z_soap_error(assoc->encode, soap_package,
1128 "SOAP-ENV:Client", "Bad method", 0);
1132 p = z_get_HTTP_Response(o, 200);
1133 hres = p->u.HTTP_Response;
1134 ret = z_soap_codec_enc(assoc->encode, &soap_package,
1135 &hres->content_buf, &hres->content_len,
1136 soap_handlers, charset);
1137 hres->code = http_code;
1139 z_HTTP_header_add(o, &hres->headers, "Content-Type", "text/xml");
1143 strcpy(ctype, "text/xml; charset=");
1144 strcat(ctype, charset);
1145 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1148 if (!p) /* still no response ? */
1149 p = z_get_HTTP_Response(o, 500);
1153 p = z_get_HTTP_Response(o, 405);
1154 hres = p->u.HTTP_Response;
1156 z_HTTP_header_add(o, &hres->headers, "Allow", "GET, POST");
1158 hres = p->u.HTTP_Response;
1159 if (!strcmp(hreq->version, "1.0"))
1161 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1162 if (v && !strcmp(v, "Keep-Alive"))
1166 hres->version = "1.0";
1170 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1171 if (v && !strcmp(v, "close"))
1175 hres->version = "1.1";
1179 z_HTTP_header_add(o, &hres->headers, "Connection", "close");
1180 assoc->state = ASSOC_DEAD;
1185 const char *alive = z_HTTP_header_lookup(hreq->headers, "Keep-Alive");
1187 if (alive && isdigit(*alive))
1191 if (t < 0 || t > 3600)
1193 iochan_settimeout(assoc->client_chan,t);
1194 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1196 process_gdu_response(assoc, req, p);
1199 static void process_gdu_request(association *assoc, request *req)
1201 if (req->gdu_request->which == Z_GDU_Z3950)
1204 req->apdu_request = req->gdu_request->u.z3950;
1205 if (process_z_request(assoc, req, &msg) < 0)
1206 do_close_req(assoc, Z_Close_systemProblem, msg, req);
1208 else if (req->gdu_request->which == Z_GDU_HTTP_Request)
1209 process_http_request(assoc, req);
1212 do_close_req(assoc, Z_Close_systemProblem, "bad protocol packet", req);
1217 * Initiate request processing.
1219 static int process_z_request(association *assoc, request *req, char **msg)
1225 *msg = "Unknown Error";
1226 assert(req && req->state == REQUEST_IDLE);
1227 if (req->apdu_request->which != Z_APDU_initRequest && !assoc->init)
1229 *msg = "Missing InitRequest";
1232 switch (req->apdu_request->which)
1234 case Z_APDU_initRequest:
1235 iochan_settimeout(assoc->client_chan,
1236 statserv_getcontrol()->idle_timeout * 60);
1237 res = process_initRequest(assoc, req); break;
1238 case Z_APDU_searchRequest:
1239 res = process_searchRequest(assoc, req, &fd); break;
1240 case Z_APDU_presentRequest:
1241 res = process_presentRequest(assoc, req, &fd); break;
1242 case Z_APDU_scanRequest:
1243 if (assoc->init->bend_scan)
1244 res = process_scanRequest(assoc, req, &fd);
1247 *msg = "Cannot handle Scan APDU";
1251 case Z_APDU_extendedServicesRequest:
1252 if (assoc->init->bend_esrequest)
1253 res = process_ESRequest(assoc, req, &fd);
1256 *msg = "Cannot handle Extended Services APDU";
1260 case Z_APDU_sortRequest:
1261 if (assoc->init->bend_sort)
1262 res = process_sortRequest(assoc, req, &fd);
1265 *msg = "Cannot handle Sort APDU";
1270 process_close(assoc, req);
1272 case Z_APDU_deleteResultSetRequest:
1273 if (assoc->init->bend_delete)
1274 res = process_deleteRequest(assoc, req, &fd);
1277 *msg = "Cannot handle Delete APDU";
1281 case Z_APDU_segmentRequest:
1282 if (assoc->init->bend_segment)
1284 res = process_segmentRequest (assoc, req);
1288 *msg = "Cannot handle Segment APDU";
1293 *msg = "Bad APDU received";
1298 yaz_log(LOG_DEBUG, " result immediately available");
1299 retval = process_z_response(assoc, req, res);
1303 yaz_log(LOG_DEBUG, " result unavailble");
1306 else /* no result yet - one will be provided later */
1310 /* Set up an I/O handler for the fd supplied by the backend */
1312 yaz_log(LOG_DEBUG, " establishing handler for result");
1313 req->state = REQUEST_PENDING;
1314 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT)))
1316 iochan_setdata(chan, assoc);
1323 * Handle message from the backend.
1325 void backend_response(IOCHAN i, int event)
1327 association *assoc = (association *)iochan_getdata(i);
1328 request *req = request_head(&assoc->incoming);
1332 yaz_log(LOG_DEBUG, "backend_response");
1333 assert(assoc && req && req->state != REQUEST_IDLE);
1334 /* determine what it is we're waiting for */
1335 switch (req->apdu_request->which)
1337 case Z_APDU_searchRequest:
1338 res = response_searchRequest(assoc, req, 0, &fd); break;
1340 case Z_APDU_presentRequest:
1341 res = response_presentRequest(assoc, req, 0, &fd); break;
1342 case Z_APDU_scanRequest:
1343 res = response_scanRequest(assoc, req, 0, &fd); break;
1346 yaz_log(LOG_WARN, "Serious programmer's lapse or bug");
1349 if ((res && process_z_response(assoc, req, res) < 0) || fd < 0)
1351 yaz_log(LOG_LOG, "Fatal error when talking to backend");
1352 do_close(assoc, Z_Close_systemProblem, 0);
1356 else if (!res) /* no result yet - try again later */
1358 yaz_log(LOG_DEBUG, " no result yet");
1359 iochan_setfd(i, fd); /* in case fd has changed */
1364 * Encode response, and transfer the request structure to the outgoing queue.
1366 static int process_gdu_response(association *assoc, request *req, Z_GDU *res)
1368 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
1370 if (assoc->print && !z_GDU(assoc->print, &res, 0, 0))
1372 yaz_log(LOG_WARN, "ODR print error: %s",
1373 odr_errmsg(odr_geterror(assoc->print)));
1374 odr_reset(assoc->print);
1376 if (!z_GDU(assoc->encode, &res, 0, 0))
1378 yaz_log(LOG_WARN, "ODR error when encoding response: %s",
1379 odr_errmsg(odr_geterror(assoc->decode)));
1382 req->response = odr_getbuf(assoc->encode, &req->len_response,
1383 &req->size_response);
1384 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
1385 odr_reset(assoc->encode);
1386 req->state = REQUEST_IDLE;
1387 request_enq(&assoc->outgoing, req);
1388 /* turn the work over to the ir_session handler */
1389 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
1390 assoc->cs_put_mask = EVENT_OUTPUT;
1391 /* Is there more work to be done? give that to the input handler too */
1393 if (request_head(&assoc->incoming))
1395 yaz_log (LOG_DEBUG, "more work to be done");
1396 iochan_setevent(assoc->client_chan, EVENT_WORK);
1403 * Encode response, and transfer the request structure to the outgoing queue.
1405 static int process_z_response(association *assoc, request *req, Z_APDU *res)
1407 Z_GDU *gres = (Z_GDU *) odr_malloc(assoc->encode, sizeof(*res));
1408 gres->which = Z_GDU_Z3950;
1409 gres->u.z3950 = res;
1411 return process_gdu_response(assoc, req, gres);
1416 * Handle init request.
1417 * At the moment, we don't check the options
1418 * anywhere else in the code - we just try not to do anything that would
1419 * break a naive client. We'll toss 'em into the association block when
1420 * we need them there.
1422 static Z_APDU *process_initRequest(association *assoc, request *reqb)
1424 statserv_options_block *cb = statserv_getcontrol();
1425 Z_InitRequest *req = reqb->apdu_request->u.initRequest;
1426 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
1427 Z_InitResponse *resp = apdu->u.initResponse;
1428 bend_initresult *binitres;
1432 yaz_log(LOG_LOG, "Got initRequest");
1433 if (req->implementationId)
1434 yaz_log(LOG_LOG, "Id: %s", req->implementationId);
1435 if (req->implementationName)
1436 yaz_log(LOG_LOG, "Name: %s", req->implementationName);
1437 if (req->implementationVersion)
1438 yaz_log(LOG_LOG, "Version: %s", req->implementationVersion);
1440 assoc_init_reset(assoc);
1442 assoc->init->auth = req->idAuthentication;
1443 assoc->init->referenceId = req->referenceId;
1445 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
1447 Z_CharSetandLanguageNegotiation *negotiation =
1448 yaz_get_charneg_record (req->otherInfo);
1449 if (negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
1450 assoc->init->charneg_request = negotiation;
1453 if (!(binitres = (*cb->bend_init)(assoc->init)))
1455 yaz_log(LOG_WARN, "Bad response from backend.");
1459 assoc->backend = binitres->handle;
1460 if ((assoc->init->bend_sort))
1461 yaz_log (LOG_DEBUG, "Sort handler installed");
1462 if ((assoc->init->bend_search))
1463 yaz_log (LOG_DEBUG, "Search handler installed");
1464 if ((assoc->init->bend_present))
1465 yaz_log (LOG_DEBUG, "Present handler installed");
1466 if ((assoc->init->bend_esrequest))
1467 yaz_log (LOG_DEBUG, "ESRequest handler installed");
1468 if ((assoc->init->bend_delete))
1469 yaz_log (LOG_DEBUG, "Delete handler installed");
1470 if ((assoc->init->bend_scan))
1471 yaz_log (LOG_DEBUG, "Scan handler installed");
1472 if ((assoc->init->bend_segment))
1473 yaz_log (LOG_DEBUG, "Segment handler installed");
1475 resp->referenceId = req->referenceId;
1477 /* let's tell the client what we can do */
1478 if (ODR_MASK_GET(req->options, Z_Options_search))
1480 ODR_MASK_SET(resp->options, Z_Options_search);
1481 strcat(options, "srch");
1483 if (ODR_MASK_GET(req->options, Z_Options_present))
1485 ODR_MASK_SET(resp->options, Z_Options_present);
1486 strcat(options, " prst");
1488 if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
1489 assoc->init->bend_delete)
1491 ODR_MASK_SET(resp->options, Z_Options_delSet);
1492 strcat(options, " del");
1494 if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
1495 assoc->init->bend_esrequest)
1497 ODR_MASK_SET(resp->options, Z_Options_extendedServices);
1498 strcat (options, " extendedServices");
1500 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
1502 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
1503 strcat(options, " namedresults");
1505 if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
1507 ODR_MASK_SET(resp->options, Z_Options_scan);
1508 strcat(options, " scan");
1510 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
1512 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
1513 strcat(options, " concurrop");
1515 if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
1517 ODR_MASK_SET(resp->options, Z_Options_sort);
1518 strcat(options, " sort");
1521 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel)
1522 && assoc->init->charneg_response)
1524 Z_OtherInformation **p;
1525 Z_OtherInformationUnit *p0;
1527 yaz_oi_APDU(apdu, &p);
1529 if ((p0=yaz_oi_update(p, assoc->encode, NULL, 0, 0))) {
1530 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
1532 p0->which = Z_OtherInfo_externallyDefinedInfo;
1533 p0->information.externallyDefinedInfo =
1534 assoc->init->charneg_response;
1536 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
1537 strcat(options, " negotiation");
1540 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
1542 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
1543 assoc->version = 2; /* 1 & 2 are equivalent */
1545 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
1547 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
1550 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
1552 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
1556 yaz_log(LOG_LOG, "Negotiated to v%d: %s", assoc->version, options);
1557 assoc->maximumRecordSize = *req->maximumRecordSize;
1558 if (assoc->maximumRecordSize > control_block->maxrecordsize)
1559 assoc->maximumRecordSize = control_block->maxrecordsize;
1560 assoc->preferredMessageSize = *req->preferredMessageSize;
1561 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
1562 assoc->preferredMessageSize = assoc->maximumRecordSize;
1564 resp->preferredMessageSize = &assoc->preferredMessageSize;
1565 resp->maximumRecordSize = &assoc->maximumRecordSize;
1567 resp->implementationName = "GFS/YAZ";
1569 if (assoc->init->implementation_id)
1572 odr_malloc (assoc->encode,
1573 strlen(assoc->init->implementation_id) + 10 +
1574 strlen(resp->implementationId));
1575 sprintf (nv, "%s / %s",
1576 resp->implementationId, assoc->init->implementation_id);
1577 resp->implementationId = nv;
1579 if (assoc->init->implementation_name)
1582 odr_malloc (assoc->encode,
1583 strlen(assoc->init->implementation_name) + 10 +
1584 strlen(resp->implementationName));
1585 sprintf (nv, "%s / %s",
1586 resp->implementationName, assoc->init->implementation_name);
1587 resp->implementationName = nv;
1589 if (assoc->init->implementation_version)
1592 odr_malloc (assoc->encode,
1593 strlen(assoc->init->implementation_version) + 10 +
1594 strlen(resp->implementationVersion));
1595 sprintf (nv, "YAZ %s / %s",
1596 resp->implementationVersion,
1597 assoc->init->implementation_version);
1598 resp->implementationVersion = nv;
1601 if (binitres->errcode)
1603 yaz_log(LOG_LOG, "Connection rejected by backend.");
1605 assoc->state = ASSOC_DEAD;
1608 assoc->state = ASSOC_UP;
1613 * These functions should be merged.
1616 static void set_addinfo (Z_DefaultDiagFormat *dr, char *addinfo, ODR odr)
1618 dr->which = Z_DefaultDiagFormat_v2Addinfo;
1619 dr->u.v2Addinfo = odr_strdup (odr, addinfo ? addinfo : "");
1623 * nonsurrogate diagnostic record.
1625 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
1627 Z_Records *rec = (Z_Records *)
1628 odr_malloc (assoc->encode, sizeof(*rec));
1629 int *err = odr_intdup(assoc->encode, error);
1630 Z_DiagRec *drec = (Z_DiagRec *)
1631 odr_malloc (assoc->encode, sizeof(*drec));
1632 Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
1633 odr_malloc (assoc->encode, sizeof(*dr));
1635 yaz_log(LOG_LOG, "[%d] %s %s%s", error, diagbib1_str(error),
1636 addinfo ? " -- " : "", addinfo ? addinfo : "");
1637 rec->which = Z_Records_NSD;
1638 rec->u.nonSurrogateDiagnostic = dr;
1639 dr->diagnosticSetId =
1640 yaz_oidval_to_z3950oid (assoc->encode, CLASS_DIAGSET, VAL_BIB1);
1641 dr->condition = err;
1642 set_addinfo (dr, addinfo, assoc->encode);
1647 * surrogate diagnostic.
1649 static Z_NamePlusRecord *surrogatediagrec(association *assoc, char *dbname,
1650 int error, char *addinfo)
1652 Z_NamePlusRecord *rec = (Z_NamePlusRecord *)
1653 odr_malloc (assoc->encode, sizeof(*rec));
1654 int *err = odr_intdup(assoc->encode, error);
1655 Z_DiagRec *drec = (Z_DiagRec *)odr_malloc (assoc->encode, sizeof(*drec));
1656 Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
1657 odr_malloc (assoc->encode, sizeof(*dr));
1659 yaz_log(LOG_DEBUG, "SurrogateDiagnotic: %d -- %s", error, addinfo);
1660 rec->databaseName = dbname;
1661 rec->which = Z_NamePlusRecord_surrogateDiagnostic;
1662 rec->u.surrogateDiagnostic = drec;
1663 drec->which = Z_DiagRec_defaultFormat;
1664 drec->u.defaultFormat = dr;
1665 dr->diagnosticSetId =
1666 yaz_oidval_to_z3950oid (assoc->encode, CLASS_DIAGSET, VAL_BIB1);
1667 dr->condition = err;
1668 set_addinfo (dr, addinfo, assoc->encode);
1674 * multiple nonsurrogate diagnostics.
1676 static Z_DiagRecs *diagrecs(association *assoc, int error, char *addinfo)
1678 Z_DiagRecs *recs = (Z_DiagRecs *)odr_malloc (assoc->encode, sizeof(*recs));
1679 int *err = odr_intdup(assoc->encode, error);
1680 Z_DiagRec **recp = (Z_DiagRec **)odr_malloc (assoc->encode, sizeof(*recp));
1681 Z_DiagRec *drec = (Z_DiagRec *)odr_malloc (assoc->encode, sizeof(*drec));
1682 Z_DefaultDiagFormat *rec = (Z_DefaultDiagFormat *)
1683 odr_malloc (assoc->encode, sizeof(*rec));
1685 yaz_log(LOG_DEBUG, "DiagRecs: %d -- %s", error, addinfo ? addinfo : "");
1687 recs->num_diagRecs = 1;
1688 recs->diagRecs = recp;
1690 drec->which = Z_DiagRec_defaultFormat;
1691 drec->u.defaultFormat = rec;
1693 rec->diagnosticSetId =
1694 yaz_oidval_to_z3950oid (assoc->encode, CLASS_DIAGSET, VAL_BIB1);
1695 rec->condition = err;
1697 rec->which = Z_DefaultDiagFormat_v2Addinfo;
1698 rec->u.v2Addinfo = odr_strdup (assoc->encode, addinfo ? addinfo : "");
1702 static Z_Records *pack_records(association *a, char *setname, int start,
1703 int *num, Z_RecordComposition *comp,
1704 int *next, int *pres, oid_value format,
1705 Z_ReferenceId *referenceId,
1708 int recno, total_length = 0, toget = *num, dumped_records = 0;
1709 Z_Records *records =
1710 (Z_Records *) odr_malloc (a->encode, sizeof(*records));
1711 Z_NamePlusRecordList *reclist =
1712 (Z_NamePlusRecordList *) odr_malloc (a->encode, sizeof(*reclist));
1713 Z_NamePlusRecord **list =
1714 (Z_NamePlusRecord **) odr_malloc (a->encode, sizeof(*list) * toget);
1716 records->which = Z_Records_DBOSD;
1717 records->u.databaseOrSurDiagnostics = reclist;
1718 reclist->num_records = 0;
1719 reclist->records = list;
1720 *pres = Z_PRES_SUCCESS;
1724 yaz_log(LOG_LOG, "Request to pack %d+%d+%s", start, toget, setname);
1725 yaz_log(LOG_DEBUG, "pms=%d, mrs=%d", a->preferredMessageSize,
1726 a->maximumRecordSize);
1727 for (recno = start; reclist->num_records < toget; recno++)
1730 Z_NamePlusRecord *thisrec;
1731 int this_length = 0;
1733 * we get the number of bytes allocated on the stream before any
1734 * allocation done by the backend - this should give us a reasonable
1735 * idea of the total size of the data so far.
1737 total_length = odr_total(a->encode) - dumped_records;
1743 freq.last_in_set = 0;
1744 freq.setname = setname;
1745 freq.surrogate_flag = 0;
1746 freq.number = recno;
1748 freq.request_format = format;
1749 freq.request_format_raw = oid;
1750 freq.output_format = format;
1751 freq.output_format_raw = 0;
1752 freq.stream = a->encode;
1753 freq.print = a->print;
1754 freq.surrogate_flag = 0;
1755 freq.referenceId = referenceId;
1756 (*a->init->bend_fetch)(a->backend, &freq);
1757 /* backend should be able to signal whether error is system-wide
1758 or only pertaining to current record */
1761 if (!freq.surrogate_flag)
1764 *pres = Z_PRES_FAILURE;
1765 /* for 'present request out of range',
1766 set addinfo to record position if not set */
1767 if (freq.errcode == 13 && freq.errstring == 0)
1769 sprintf (s, "%d", recno);
1772 return diagrec(a, freq.errcode, freq.errstring);
1774 reclist->records[reclist->num_records] =
1775 surrogatediagrec(a, freq.basename, freq.errcode,
1777 reclist->num_records++;
1778 *next = freq.last_in_set ? 0 : recno + 1;
1782 this_length = freq.len;
1784 this_length = odr_total(a->encode) - total_length;
1785 yaz_log(LOG_DEBUG, " fetched record, len=%d, total=%d",
1786 this_length, total_length);
1787 if (this_length + total_length > a->preferredMessageSize)
1789 /* record is small enough, really */
1790 if (this_length <= a->preferredMessageSize)
1792 yaz_log(LOG_DEBUG, " Dropped last normal-sized record");
1793 *pres = Z_PRES_PARTIAL_2;
1796 /* record can only be fetched by itself */
1797 if (this_length < a->maximumRecordSize)
1799 yaz_log(LOG_DEBUG, " Record > prefmsgsz");
1802 yaz_log(LOG_DEBUG, " Dropped it");
1803 reclist->records[reclist->num_records] =
1804 surrogatediagrec(a, freq.basename, 16, 0);
1805 reclist->num_records++;
1806 *next = freq.last_in_set ? 0 : recno + 1;
1807 dumped_records += this_length;
1811 else /* too big entirely */
1813 yaz_log(LOG_LOG, "Record > maxrcdsz this=%d max=%d", this_length, a->maximumRecordSize);
1814 reclist->records[reclist->num_records] =
1815 surrogatediagrec(a, freq.basename, 17, 0);
1816 reclist->num_records++;
1817 *next = freq.last_in_set ? 0 : recno + 1;
1818 dumped_records += this_length;
1823 if (!(thisrec = (Z_NamePlusRecord *)
1824 odr_malloc(a->encode, sizeof(*thisrec))))
1826 if (!(thisrec->databaseName = (char *)odr_malloc(a->encode,
1827 strlen(freq.basename) + 1)))
1829 strcpy(thisrec->databaseName, freq.basename);
1830 thisrec->which = Z_NamePlusRecord_databaseRecord;
1832 if (freq.output_format_raw)
1834 struct oident *ident = oid_getentbyoid(freq.output_format_raw);
1835 freq.output_format = ident->value;
1837 thisrec->u.databaseRecord = z_ext_record(a->encode, freq.output_format,
1838 freq.record, freq.len);
1839 if (!thisrec->u.databaseRecord)
1841 reclist->records[reclist->num_records] = thisrec;
1842 reclist->num_records++;
1843 *next = freq.last_in_set ? 0 : recno + 1;
1845 *num = reclist->num_records;
1849 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
1852 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
1853 bend_search_rr *bsrr =
1854 (bend_search_rr *)nmem_malloc (reqb->request_mem, sizeof(*bsrr));
1856 yaz_log(LOG_LOG, "Got SearchRequest.");
1858 bsrr->request = reqb;
1859 bsrr->association = assoc;
1860 bsrr->referenceId = req->referenceId;
1861 save_referenceId (reqb, bsrr->referenceId);
1863 yaz_log (LOG_LOG, "ResultSet '%s'", req->resultSetName);
1864 if (req->databaseNames)
1867 for (i = 0; i < req->num_databaseNames; i++)
1868 yaz_log (LOG_LOG, "Database '%s'", req->databaseNames[i]);
1870 yaz_log_zquery(req->query);
1872 if (assoc->init->bend_search)
1874 bsrr->setname = req->resultSetName;
1875 bsrr->replace_set = *req->replaceIndicator;
1876 bsrr->num_bases = req->num_databaseNames;
1877 bsrr->basenames = req->databaseNames;
1878 bsrr->query = req->query;
1879 bsrr->stream = assoc->encode;
1880 bsrr->decode = assoc->decode;
1881 bsrr->print = assoc->print;
1884 bsrr->errstring = NULL;
1885 bsrr->search_info = NULL;
1886 (assoc->init->bend_search)(assoc->backend, bsrr);
1890 return response_searchRequest(assoc, reqb, bsrr, fd);
1893 int bend_searchresponse(void *handle, bend_search_rr *bsrr) {return 0;}
1896 * Prepare a searchresponse based on the backend results. We probably want
1897 * to look at making the fetching of records nonblocking as well, but
1898 * so far, we'll keep things simple.
1899 * If bsrt is null, that means we're called in response to a communications
1900 * event, and we'll have to get the response for ourselves.
1902 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
1903 bend_search_rr *bsrt, int *fd)
1905 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
1906 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1907 Z_SearchResponse *resp = (Z_SearchResponse *)
1908 odr_malloc (assoc->encode, sizeof(*resp));
1909 int *nulint = odr_intdup (assoc->encode, 0);
1910 bool_t *sr = odr_intdup(assoc->encode, 1);
1911 int *next = odr_intdup(assoc->encode, 0);
1912 int *none = odr_intdup(assoc->encode, Z_RES_NONE);
1914 apdu->which = Z_APDU_searchResponse;
1915 apdu->u.searchResponse = resp;
1916 resp->referenceId = req->referenceId;
1917 resp->additionalSearchInfo = 0;
1918 resp->otherInfo = 0;
1920 if (!bsrt && !bend_searchresponse(assoc->backend, bsrt))
1922 yaz_log(LOG_FATAL, "Bad result from backend");
1925 else if (bsrt->errcode)
1927 resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
1928 resp->resultCount = nulint;
1929 resp->numberOfRecordsReturned = nulint;
1930 resp->nextResultSetPosition = nulint;
1931 resp->searchStatus = nulint;
1932 resp->resultSetStatus = none;
1933 resp->presentStatus = 0;
1937 int *toget = odr_intdup(assoc->encode, 0);
1938 int *presst = odr_intdup(assoc->encode, 0);
1939 Z_RecordComposition comp, *compp = 0;
1941 yaz_log (LOG_LOG, "resultCount: %d", bsrt->hits);
1944 resp->resultCount = &bsrt->hits;
1946 comp.which = Z_RecordComp_simple;
1947 /* how many records does the user agent want, then? */
1948 if (bsrt->hits <= *req->smallSetUpperBound)
1950 *toget = bsrt->hits;
1951 if ((comp.u.simple = req->smallSetElementSetNames))
1954 else if (bsrt->hits < *req->largeSetLowerBound)
1956 *toget = *req->mediumSetPresentNumber;
1957 if (*toget > bsrt->hits)
1958 *toget = bsrt->hits;
1959 if ((comp.u.simple = req->mediumSetElementSetNames))
1965 if (*toget && !resp->records)
1970 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
1973 form = prefformat->value;
1974 resp->records = pack_records(assoc, req->resultSetName, 1,
1975 toget, compp, next, presst, form, req->referenceId,
1976 req->preferredRecordSyntax);
1979 resp->numberOfRecordsReturned = toget;
1980 resp->nextResultSetPosition = next;
1981 resp->searchStatus = sr;
1982 resp->resultSetStatus = 0;
1983 resp->presentStatus = presst;
1987 if (*resp->resultCount)
1989 resp->numberOfRecordsReturned = nulint;
1990 resp->nextResultSetPosition = next;
1991 resp->searchStatus = sr;
1992 resp->resultSetStatus = 0;
1993 resp->presentStatus = 0;
1996 resp->additionalSearchInfo = bsrt->search_info;
2001 * Maybe we got a little over-friendly when we designed bend_fetch to
2002 * get only one record at a time. Some backends can optimise multiple-record
2003 * fetches, and at any rate, there is some overhead involved in
2004 * all that selecting and hopping around. Problem is, of course, that the
2005 * frontend can't know ahead of time how many records it'll need to
2006 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
2007 * is downright lousy as a bulk data transfer protocol.
2009 * To start with, we'll do the fetching of records from the backend
2010 * in one operation: To save some trips in and out of the event-handler,
2011 * and to simplify the interface to pack_records. At any rate, asynch
2012 * operation is more fun in operations that have an unpredictable execution
2013 * speed - which is normally more true for search than for present.
2015 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
2018 Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
2022 Z_PresentResponse *resp;
2026 yaz_log(LOG_LOG, "Got PresentRequest.");
2028 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
2031 form = prefformat->value;
2032 resp = (Z_PresentResponse *)odr_malloc (assoc->encode, sizeof(*resp));
2034 resp->presentStatus = odr_intdup(assoc->encode, 0);
2035 if (assoc->init->bend_present)
2037 bend_present_rr *bprr = (bend_present_rr *)
2038 nmem_malloc (reqb->request_mem, sizeof(*bprr));
2039 bprr->setname = req->resultSetId;
2040 bprr->start = *req->resultSetStartPoint;
2041 bprr->number = *req->numberOfRecordsRequested;
2042 bprr->format = form;
2043 bprr->comp = req->recordComposition;
2044 bprr->referenceId = req->referenceId;
2045 bprr->stream = assoc->encode;
2046 bprr->print = assoc->print;
2047 bprr->request = reqb;
2048 bprr->association = assoc;
2050 bprr->errstring = NULL;
2051 (*assoc->init->bend_present)(assoc->backend, bprr);
2057 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2058 *resp->presentStatus = Z_PRES_FAILURE;
2061 apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2062 next = odr_intdup(assoc->encode, 0);
2063 num = odr_intdup(assoc->encode, 0);
2065 apdu->which = Z_APDU_presentResponse;
2066 apdu->u.presentResponse = resp;
2067 resp->referenceId = req->referenceId;
2068 resp->otherInfo = 0;
2072 *num = *req->numberOfRecordsRequested;
2074 pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
2075 num, req->recordComposition, next, resp->presentStatus,
2076 form, req->referenceId, req->preferredRecordSyntax);
2080 resp->numberOfRecordsReturned = num;
2081 resp->nextResultSetPosition = next;
2087 * Scan was implemented rather in a hurry, and with support for only the basic
2088 * elements of the service in the backend API. Suggestions are welcome.
2090 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
2092 Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
2093 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2094 Z_ScanResponse *res = (Z_ScanResponse *)
2095 odr_malloc (assoc->encode, sizeof(*res));
2096 int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
2097 int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
2098 Z_ListEntries *ents = (Z_ListEntries *)
2099 odr_malloc (assoc->encode, sizeof(*ents));
2100 Z_DiagRecs *diagrecs_p = NULL;
2102 bend_scan_rr *bsrr = (bend_scan_rr *)
2103 odr_malloc (assoc->encode, sizeof(*bsrr));
2105 yaz_log(LOG_LOG, "Got ScanRequest");
2107 apdu->which = Z_APDU_scanResponse;
2108 apdu->u.scanResponse = res;
2109 res->referenceId = req->referenceId;
2111 /* if step is absent, set it to 0 */
2112 res->stepSize = odr_intdup(assoc->encode, 0);
2114 *res->stepSize = *req->stepSize;
2116 res->scanStatus = scanStatus;
2117 res->numberOfEntriesReturned = numberOfEntriesReturned;
2118 res->positionOfTerm = 0;
2119 res->entries = ents;
2120 ents->num_entries = 0;
2121 ents->entries = NULL;
2122 ents->num_nonsurrogateDiagnostics = 0;
2123 ents->nonsurrogateDiagnostics = NULL;
2124 res->attributeSet = 0;
2127 if (req->databaseNames)
2130 for (i = 0; i < req->num_databaseNames; i++)
2131 yaz_log (LOG_LOG, "Database '%s'", req->databaseNames[i]);
2133 bsrr->num_bases = req->num_databaseNames;
2134 bsrr->basenames = req->databaseNames;
2135 bsrr->num_entries = *req->numberOfTermsRequested;
2136 bsrr->term = req->termListAndStartPoint;
2137 bsrr->referenceId = req->referenceId;
2138 bsrr->stream = assoc->encode;
2139 bsrr->print = assoc->print;
2140 bsrr->step_size = res->stepSize;
2141 if (req->attributeSet &&
2142 (attset = oid_getentbyoid(req->attributeSet)) &&
2143 (attset->oclass == CLASS_ATTSET || attset->oclass == CLASS_GENERAL))
2144 bsrr->attributeset = attset->value;
2146 bsrr->attributeset = VAL_NONE;
2147 log_scan_term (req->termListAndStartPoint, bsrr->attributeset);
2148 bsrr->term_position = req->preferredPositionInResponse ?
2149 *req->preferredPositionInResponse : 1;
2150 ((int (*)(void *, bend_scan_rr *))
2151 (*assoc->init->bend_scan))(assoc->backend, bsrr);
2153 diagrecs_p = diagrecs(assoc, bsrr->errcode, bsrr->errstring);
2157 Z_Entry **tab = (Z_Entry **)
2158 odr_malloc (assoc->encode, sizeof(*tab) * bsrr->num_entries);
2160 if (bsrr->status == BEND_SCAN_PARTIAL)
2161 *scanStatus = Z_Scan_partial_5;
2163 *scanStatus = Z_Scan_success;
2164 ents->entries = tab;
2165 ents->num_entries = bsrr->num_entries;
2166 res->numberOfEntriesReturned = &ents->num_entries;
2167 res->positionOfTerm = &bsrr->term_position;
2168 for (i = 0; i < bsrr->num_entries; i++)
2174 tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
2175 if (bsrr->entries[i].occurrences >= 0)
2177 e->which = Z_Entry_termInfo;
2178 e->u.termInfo = t = (Z_TermInfo *)
2179 odr_malloc(assoc->encode, sizeof(*t));
2180 t->suggestedAttributes = 0;
2182 t->alternativeTerm = 0;
2183 t->byAttributes = 0;
2184 t->otherTermInfo = 0;
2185 t->globalOccurrences = &bsrr->entries[i].occurrences;
2186 t->term = (Z_Term *)
2187 odr_malloc(assoc->encode, sizeof(*t->term));
2188 t->term->which = Z_Term_general;
2189 t->term->u.general = o =
2190 (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
2191 o->buf = (unsigned char *)
2192 odr_malloc(assoc->encode, o->len = o->size =
2193 strlen(bsrr->entries[i].term));
2194 memcpy(o->buf, bsrr->entries[i].term, o->len);
2195 yaz_log(LOG_DEBUG, " term #%d: '%s' (%d)", i,
2196 bsrr->entries[i].term, bsrr->entries[i].occurrences);
2200 Z_DiagRecs *drecs = diagrecs (assoc,
2201 bsrr->entries[i].errcode,
2202 bsrr->entries[i].errstring);
2203 assert (drecs->num_diagRecs == 1);
2204 e->which = Z_Entry_surrogateDiagnostic;
2205 assert (drecs->diagRecs[0]);
2206 e->u.surrogateDiagnostic = drecs->diagRecs[0];
2212 ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
2213 ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
2218 static Z_APDU *process_sortRequest(association *assoc, request *reqb,
2221 Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
2222 Z_SortResponse *res = (Z_SortResponse *)
2223 odr_malloc (assoc->encode, sizeof(*res));
2224 bend_sort_rr *bsrr = (bend_sort_rr *)
2225 odr_malloc (assoc->encode, sizeof(*bsrr));
2227 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2229 yaz_log(LOG_LOG, "Got SortRequest.");
2231 bsrr->num_input_setnames = req->num_inputResultSetNames;
2232 bsrr->input_setnames = req->inputResultSetNames;
2233 bsrr->referenceId = req->referenceId;
2234 bsrr->output_setname = req->sortedResultSetName;
2235 bsrr->sort_sequence = req->sortSequence;
2236 bsrr->stream = assoc->encode;
2237 bsrr->print = assoc->print;
2239 bsrr->sort_status = Z_SortStatus_failure;
2241 bsrr->errstring = 0;
2243 (*assoc->init->bend_sort)(assoc->backend, bsrr);
2245 res->referenceId = bsrr->referenceId;
2246 res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
2247 res->resultSetStatus = 0;
2250 Z_DiagRecs *dr = diagrecs (assoc, bsrr->errcode, bsrr->errstring);
2251 res->diagnostics = dr->diagRecs;
2252 res->num_diagnostics = dr->num_diagRecs;
2256 res->num_diagnostics = 0;
2257 res->diagnostics = 0;
2261 apdu->which = Z_APDU_sortResponse;
2262 apdu->u.sortResponse = res;
2266 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
2269 Z_DeleteResultSetRequest *req =
2270 reqb->apdu_request->u.deleteResultSetRequest;
2271 Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
2272 odr_malloc (assoc->encode, sizeof(*res));
2273 bend_delete_rr *bdrr = (bend_delete_rr *)
2274 odr_malloc (assoc->encode, sizeof(*bdrr));
2275 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2277 yaz_log(LOG_LOG, "Got DeleteRequest.");
2279 bdrr->num_setnames = req->num_resultSetList;
2280 bdrr->setnames = req->resultSetList;
2281 bdrr->stream = assoc->encode;
2282 bdrr->print = assoc->print;
2283 bdrr->function = *req->deleteFunction;
2284 bdrr->referenceId = req->referenceId;
2286 if (bdrr->num_setnames > 0)
2289 bdrr->statuses = (int*)
2290 odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
2291 bdrr->num_setnames);
2292 for (i = 0; i < bdrr->num_setnames; i++)
2293 bdrr->statuses[i] = 0;
2295 (*assoc->init->bend_delete)(assoc->backend, bdrr);
2297 res->referenceId = req->referenceId;
2299 res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
2301 res->deleteListStatuses = 0;
2302 if (bdrr->num_setnames > 0)
2305 res->deleteListStatuses = (Z_ListStatuses *)
2306 odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
2307 res->deleteListStatuses->num = bdrr->num_setnames;
2308 res->deleteListStatuses->elements =
2310 odr_malloc (assoc->encode,
2311 sizeof(*res->deleteListStatuses->elements) *
2312 bdrr->num_setnames);
2313 for (i = 0; i<bdrr->num_setnames; i++)
2315 res->deleteListStatuses->elements[i] =
2317 odr_malloc (assoc->encode,
2318 sizeof(**res->deleteListStatuses->elements));
2319 res->deleteListStatuses->elements[i]->status = bdrr->statuses+i;
2320 res->deleteListStatuses->elements[i]->id =
2321 odr_strdup (assoc->encode, bdrr->setnames[i]);
2325 res->numberNotDeleted = 0;
2326 res->bulkStatuses = 0;
2327 res->deleteMessage = 0;
2330 apdu->which = Z_APDU_deleteResultSetResponse;
2331 apdu->u.deleteResultSetResponse = res;
2335 static void process_close(association *assoc, request *reqb)
2337 Z_Close *req = reqb->apdu_request->u.close;
2338 static char *reasons[] =
2345 "securityViolation",
2352 yaz_log(LOG_LOG, "Got Close, reason %s, message %s",
2353 reasons[*req->closeReason], req->diagnosticInformation ?
2354 req->diagnosticInformation : "NULL");
2355 if (assoc->version < 3) /* to make do_force respond with close */
2357 do_close_req(assoc, Z_Close_finished,
2358 "Association terminated by client", reqb);
2361 void save_referenceId (request *reqb, Z_ReferenceId *refid)
2365 reqb->len_refid = refid->len;
2366 reqb->refid = (char *)nmem_malloc (reqb->request_mem, refid->len);
2367 memcpy (reqb->refid, refid->buf, refid->len);
2371 reqb->len_refid = 0;
2376 void bend_request_send (bend_association a, bend_request req, Z_APDU *res)
2378 process_z_response (a, req, res);
2381 bend_request bend_request_mk (bend_association a)
2383 request *nreq = request_get (&a->outgoing);
2384 nreq->request_mem = nmem_create ();
2388 Z_ReferenceId *bend_request_getid (ODR odr, bend_request req)
2393 id = (Odr_oct *)odr_malloc (odr, sizeof(*odr));
2394 id->buf = (unsigned char *)odr_malloc (odr, req->len_refid);
2395 id->len = id->size = req->len_refid;
2396 memcpy (id->buf, req->refid, req->len_refid);
2400 void bend_request_destroy (bend_request *req)
2402 nmem_destroy((*req)->request_mem);
2403 request_release(*req);
2407 int bend_backend_respond (bend_association a, bend_request req)
2411 r = process_z_request (a, req, &msg);
2413 yaz_log (LOG_WARN, "%s", msg);
2417 void bend_request_setdata(bend_request r, void *p)
2422 void *bend_request_getdata(bend_request r)
2424 return r->clientData;
2427 static Z_APDU *process_segmentRequest (association *assoc, request *reqb)
2429 bend_segment_rr req;
2431 req.segment = reqb->apdu_request->u.segmentRequest;
2432 req.stream = assoc->encode;
2433 req.decode = assoc->decode;
2434 req.print = assoc->print;
2435 req.association = assoc;
2437 (*assoc->init->bend_segment)(assoc->backend, &req);
2442 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd)
2444 bend_esrequest_rr esrequest;
2446 Z_ExtendedServicesRequest *req =
2447 reqb->apdu_request->u.extendedServicesRequest;
2448 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
2450 Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
2452 yaz_log(LOG_DEBUG,"inside Process esRequest");
2454 esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
2455 esrequest.stream = assoc->encode;
2456 esrequest.decode = assoc->decode;
2457 esrequest.print = assoc->print;
2458 esrequest.errcode = 0;
2459 esrequest.errstring = NULL;
2460 esrequest.request = reqb;
2461 esrequest.association = assoc;
2462 esrequest.taskPackage = 0;
2463 esrequest.referenceId = req->referenceId;
2465 (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
2467 /* If the response is being delayed, return NULL */
2468 if (esrequest.request == NULL)
2471 resp->referenceId = req->referenceId;
2473 if (esrequest.errcode == -1)
2475 /* Backend service indicates request will be processed */
2476 yaz_log(LOG_DEBUG,"Request could be processed...Accepted !");
2477 *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
2479 else if (esrequest.errcode == 0)
2481 /* Backend service indicates request will be processed */
2482 yaz_log(LOG_DEBUG,"Request could be processed...Done !");
2483 *resp->operationStatus = Z_ExtendedServicesResponse_done;
2487 Z_DiagRecs *diagRecs = diagrecs (assoc, esrequest.errcode,
2488 esrequest.errstring);
2490 /* Backend indicates error, request will not be processed */
2491 yaz_log(LOG_DEBUG,"Request could not be processed...failure !");
2492 *resp->operationStatus = Z_ExtendedServicesResponse_failure;
2493 resp->num_diagnostics = diagRecs->num_diagRecs;
2494 resp->diagnostics = diagRecs->diagRecs;
2496 /* Do something with the members of bend_extendedservice */
2497 if (esrequest.taskPackage)
2498 resp->taskPackage = z_ext_record (assoc->encode, VAL_EXTENDED,
2499 (const char *) esrequest.taskPackage,
2501 yaz_log(LOG_DEBUG,"Send the result apdu");