2 * Copyright (c) 1995-2003, Index Data
3 * See the file LICENSE for details.
5 * $Id: seshigh.c,v 1.146 2003-02-23 14:26:57 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))))
103 anew->client_chan = channel;
104 anew->client_link = link;
105 anew->cs_get_mask = 0;
106 anew->cs_put_mask = 0;
107 anew->cs_accept_mask = 0;
108 if (!(anew->decode = odr_createmem(ODR_DECODE)) ||
109 !(anew->encode = odr_createmem(ODR_ENCODE)))
111 if (*control_block->apdufile)
116 strcpy(filename, control_block->apdufile);
117 if (!(anew->print = odr_createmem(ODR_PRINT)))
119 if (*control_block->apdufile == '@')
121 odr_setprint(anew->print, yaz_log_file());
123 else if (*control_block->apdufile != '-')
125 strcpy(filename, control_block->apdufile);
126 if (!control_block->dynamic)
130 if (!(apduf = fopen(filename, "w")))
132 yaz_log(LOG_WARN|LOG_ERRNO, "%s", filename);
135 setvbuf(apduf, 0, _IONBF, 0);
141 sprintf(filename + strlen(filename), ".%d", getpid());
142 if (!(f = fopen(filename, "w")))
144 yaz_log(LOG_WARN|LOG_ERRNO, "%s", filename);
147 setvbuf(f, 0, _IONBF, 0);
149 odr_setprint(anew->print, f);
154 anew->input_buffer = 0;
155 anew->input_buffer_len = 0;
157 anew->state = ASSOC_NEW;
158 request_initq(&anew->incoming);
159 request_initq(&anew->outgoing);
160 anew->proto = cs_getproto(link);
165 * Free association and release resources.
167 void destroy_association(association *h)
169 statserv_options_block *cb = statserv_getcontrol();
172 odr_destroy(h->decode);
173 odr_destroy(h->encode);
175 odr_destroy(h->print);
177 xfree(h->input_buffer);
179 (*cb->bend_close)(h->backend);
180 while (request_deq(&h->incoming));
181 while (request_deq(&h->outgoing));
182 request_delq(&h->incoming);
183 request_delq(&h->outgoing);
185 xmalloc_trav("session closed");
186 if (control_block && control_block->one_shot)
192 static void do_close_req(association *a, int reason, char *message,
196 Z_Close *cls = zget_Close(a->encode);
198 /* Purge request queue */
199 while (request_deq(&a->incoming));
200 while (request_deq(&a->outgoing));
203 yaz_log(LOG_LOG, "Sending Close PDU, reason=%d, message=%s",
204 reason, message ? message : "none");
205 apdu.which = Z_APDU_close;
207 *cls->closeReason = reason;
208 cls->diagnosticInformation = message;
209 process_z_response(a, req, &apdu);
210 iochan_settimeout(a->client_chan, 20);
214 yaz_log(LOG_DEBUG, "v2 client. No Close PDU");
215 iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
217 a->state = ASSOC_DEAD;
220 static void do_close(association *a, int reason, char *message)
222 do_close_req (a, reason, message, request_get(&a->outgoing));
226 * This is where PDUs from the client are read and the further
227 * processing is initiated. Flow of control moves down through the
228 * various process_* functions below, until the encoded result comes back up
229 * to the output handler in here.
231 * h : the I/O channel that has an outstanding event.
232 * event : the current outstanding event.
234 void ir_session(IOCHAN h, int event)
237 association *assoc = (association *)iochan_getdata(h);
238 COMSTACK conn = assoc->client_link;
241 assert(h && conn && assoc);
242 if (event == EVENT_TIMEOUT)
244 if (assoc->state != ASSOC_UP)
246 yaz_log(LOG_LOG, "Final timeout - closing connection.");
248 destroy_association(assoc);
253 yaz_log(LOG_LOG, "Session idle too long. Sending close.");
254 do_close(assoc, Z_Close_lackOfActivity, 0);
258 if (event & assoc->cs_accept_mask)
260 yaz_log (LOG_DEBUG, "ir_session (accept)");
261 if (!cs_accept (conn))
263 yaz_log (LOG_LOG, "accept failed");
264 destroy_association(assoc);
267 iochan_clearflag (h, EVENT_OUTPUT|EVENT_OUTPUT);
268 if (conn->io_pending)
269 { /* cs_accept didn't complete */
270 assoc->cs_accept_mask =
271 ((conn->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
272 ((conn->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
274 iochan_setflag (h, assoc->cs_accept_mask);
277 { /* cs_accept completed. Prepare for reading (cs_get) */
278 assoc->cs_accept_mask = 0;
279 assoc->cs_get_mask = EVENT_INPUT;
280 iochan_setflag (h, assoc->cs_get_mask);
284 if ((event & assoc->cs_get_mask) || (event & EVENT_WORK)) /* input */
286 if ((assoc->cs_put_mask & EVENT_INPUT) == 0 && (event & assoc->cs_get_mask))
288 yaz_log(LOG_DEBUG, "ir_session (input)");
289 /* We aren't speaking to this fellow */
290 if (assoc->state == ASSOC_DEAD)
292 yaz_log(LOG_LOG, "Connection closed - end of session");
294 destroy_association(assoc);
298 assoc->cs_get_mask = EVENT_INPUT;
299 if ((res = cs_get(conn, &assoc->input_buffer,
300 &assoc->input_buffer_len)) <= 0)
302 yaz_log(LOG_LOG, "Connection closed by client");
304 destroy_association(assoc);
308 else if (res == 1) /* incomplete read - wait for more */
310 if (conn->io_pending & CS_WANT_WRITE)
311 assoc->cs_get_mask |= EVENT_OUTPUT;
312 iochan_setflag(h, assoc->cs_get_mask);
315 if (cs_more(conn)) /* more stuff - call us again later, please */
316 iochan_setevent(h, EVENT_INPUT);
318 /* we got a complete PDU. Let's decode it */
319 yaz_log(LOG_DEBUG, "Got PDU, %d bytes: lead=%02X %02X %02X", res,
320 assoc->input_buffer[0] & 0xff,
321 assoc->input_buffer[1] & 0xff,
322 assoc->input_buffer[2] & 0xff);
323 req = request_get(&assoc->incoming); /* get a new request */
324 odr_reset(assoc->decode);
325 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
326 if (!z_GDU(assoc->decode, &req->gdu_request, 0, 0))
328 yaz_log(LOG_LOG, "ODR error on incoming PDU: %s [near byte %d] ",
329 odr_errmsg(odr_geterror(assoc->decode)),
330 odr_offset(assoc->decode));
331 if (assoc->decode->error != OHTTP)
333 yaz_log(LOG_LOG, "PDU dump:");
334 odr_dumpBER(yaz_log_file(), assoc->input_buffer, res);
335 do_close(assoc, Z_Close_protocolError, "Malformed package");
339 Z_GDU *p = z_get_HTTP_Response(assoc->encode, 400);
340 assoc->state = ASSOC_DEAD;
341 process_gdu_response(assoc, req, p);
345 req->request_mem = odr_extract_mem(assoc->decode);
346 if (assoc->print && !z_GDU(assoc->print, &req->gdu_request, 0, 0))
348 yaz_log(LOG_WARN, "ODR print error: %s",
349 odr_errmsg(odr_geterror(assoc->print)));
350 odr_reset(assoc->print);
352 request_enq(&assoc->incoming, req);
355 /* can we do something yet? */
356 req = request_head(&assoc->incoming);
357 if (req->state == REQUEST_IDLE)
359 request_deq(&assoc->incoming);
360 process_gdu_request(assoc, req);
363 if (event & assoc->cs_put_mask)
365 request *req = request_head(&assoc->outgoing);
367 assoc->cs_put_mask = 0;
368 yaz_log(LOG_DEBUG, "ir_session (output)");
369 req->state = REQUEST_PENDING;
370 switch (res = cs_put(conn, req->response, req->len_response))
373 yaz_log(LOG_LOG, "Connection closed by client");
375 destroy_association(assoc);
378 case 0: /* all sent - release the request structure */
379 yaz_log(LOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
381 yaz_log(LOG_DEBUG, "HTTP out:\n%.*s", req->len_response,
384 nmem_destroy(req->request_mem);
385 request_deq(&assoc->outgoing);
386 request_release(req);
387 if (!request_head(&assoc->outgoing))
388 { /* restore mask for cs_get operation ... */
389 iochan_clearflag(h, EVENT_OUTPUT|EVENT_INPUT);
390 iochan_setflag(h, assoc->cs_get_mask);
391 if (assoc->state == ASSOC_DEAD)
392 iochan_setevent(assoc->client_chan, EVENT_TIMEOUT);
396 assoc->cs_put_mask = EVENT_OUTPUT;
400 if (conn->io_pending & CS_WANT_WRITE)
401 assoc->cs_put_mask |= EVENT_OUTPUT;
402 if (conn->io_pending & CS_WANT_READ)
403 assoc->cs_put_mask |= EVENT_INPUT;
404 iochan_setflag(h, assoc->cs_put_mask);
407 if (event & EVENT_EXCEPT)
409 yaz_log(LOG_LOG, "ir_session (exception)");
411 destroy_association(assoc);
416 static int process_z_request(association *assoc, request *req, char **msg);
418 static void assoc_init_reset(association *assoc)
421 assoc->init = (bend_initrequest *) xmalloc (sizeof(*assoc->init));
423 assoc->init->stream = assoc->encode;
424 assoc->init->print = assoc->print;
425 assoc->init->auth = 0;
426 assoc->init->referenceId = 0;
427 assoc->init->implementation_version = 0;
428 assoc->init->implementation_id = 0;
429 assoc->init->implementation_name = 0;
430 assoc->init->bend_sort = NULL;
431 assoc->init->bend_search = NULL;
432 assoc->init->bend_present = NULL;
433 assoc->init->bend_esrequest = NULL;
434 assoc->init->bend_delete = NULL;
435 assoc->init->bend_scan = NULL;
436 assoc->init->bend_segment = NULL;
437 assoc->init->bend_fetch = NULL;
438 assoc->init->charneg_request = NULL;
439 assoc->init->charneg_response = NULL;
440 assoc->init->decode = assoc->decode;
441 assoc->init->peer_name =
442 odr_strdup (assoc->encode, cs_addrstr(assoc->client_link));
445 static int srw_bend_init(association *assoc)
447 bend_initresult *binitres;
448 statserv_options_block *cb = statserv_getcontrol();
450 assoc_init_reset(assoc);
452 assoc->maximumRecordSize = 3000000;
453 assoc->preferredMessageSize = 3000000;
455 if (!(binitres = (*cb->bend_init)(assoc->init)))
457 yaz_log(LOG_WARN, "Bad response from backend.");
460 assoc->backend = binitres->handle;
464 static int srw_bend_fetch(association *assoc, int pos,
465 Z_SRW_searchRetrieveRequest *srw_req,
466 Z_SRW_record *record)
469 ODR o = assoc->encode;
471 rr.setname = "default";
474 rr.request_format = VAL_TEXT_XML;
475 rr.request_format_raw = yaz_oidval_to_z3950oid(assoc->decode,
478 rr.comp = (Z_RecordComposition *)
479 odr_malloc(assoc->decode, sizeof(*rr.comp));
480 rr.comp->which = Z_RecordComp_complex;
481 rr.comp->u.complex = (Z_CompSpec *)
482 odr_malloc(assoc->decode, sizeof(Z_CompSpec));
483 rr.comp->u.complex->selectAlternativeSyntax = (bool_t *)
484 odr_malloc(assoc->encode, sizeof(bool_t));
485 *rr.comp->u.complex->selectAlternativeSyntax = 0;
486 rr.comp->u.complex->num_dbSpecific = 0;
487 rr.comp->u.complex->dbSpecific = 0;
488 rr.comp->u.complex->num_recordSyntax = 0;
489 rr.comp->u.complex->recordSyntax = 0;
491 rr.comp->u.complex->generic = (Z_Specification *)
492 odr_malloc(assoc->decode, sizeof(Z_Specification));
493 rr.comp->u.complex->generic->which = Z_Schema_uri;
494 rr.comp->u.complex->generic->schema.uri = srw_req->recordSchema;
495 rr.comp->u.complex->generic->elementSpec = 0;
497 rr.stream = assoc->encode;
498 rr.print = assoc->print;
504 rr.output_format = VAL_TEXT_XML;
505 rr.output_format_raw = 0;
508 rr.surrogate_flag = 0;
510 (*assoc->init->bend_fetch)(assoc->backend, &rr);
514 record->recordData_buf = rr.record;
515 record->recordData_len = rr.len;
516 record->recordPosition = odr_intdup(o, pos);
517 record->recordSchema = 0;
518 if (srw_req->recordSchema)
519 record->recordSchema = odr_strdup(o, srw_req->recordSchema);
524 static void srw_bend_search(association *assoc, request *req,
525 Z_SRW_searchRetrieveRequest *srw_req,
526 Z_SRW_searchRetrieveResponse *srw_res)
532 yaz_log(LOG_LOG, "Got SRW SearchRetrieveRequest");
534 srw_bend_init(assoc);
536 rr.setname = "default";
539 rr.basenames = &srw_req->database;
542 rr.query = (Z_Query *) odr_malloc (assoc->decode, sizeof(*rr.query));
544 if (srw_req->query_type == Z_SRW_query_type_cql)
546 ext = (Z_External *) odr_malloc(assoc->decode, sizeof(*ext));
547 ext->direct_reference = odr_getoidbystr(assoc->decode,
548 "1.2.840.10003.16.2");
549 ext->indirect_reference = 0;
551 ext->which = Z_External_CQL;
552 ext->u.cql = srw_req->query.cql;
554 rr.query->which = Z_Query_type_104;
555 rr.query->u.type_104 = ext;
557 else if (srw_req->query_type == Z_SRW_query_type_pqf)
559 Z_RPNQuery *RPNquery;
560 YAZ_PQF_Parser pqf_parser;
562 pqf_parser = yaz_pqf_create ();
564 RPNquery = yaz_pqf_parse (pqf_parser, assoc->decode,
570 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
571 yaz_log(LOG_LOG, "%*s^\n", off+4, "");
572 yaz_log(LOG_LOG, "Bad PQF: %s (code %d)\n", pqf_msg, code);
577 rr.query->which = Z_Query_type_1;
578 rr.query->u.type_1 = RPNquery;
580 yaz_pqf_destroy (pqf_parser);
585 if (srw_req->sort_type != Z_SRW_sort_type_none)
590 srw_res->num_diagnostics = 1;
591 srw_res->diagnostics = (Z_SRW_diagnostic *)
592 odr_malloc(assoc->encode, sizeof(*srw_res->diagnostics));
593 srw_res->diagnostics[0].code =
594 odr_intdup(assoc->encode, srw_error);
595 srw_res->diagnostics[0].details = 0;
600 rr.stream = assoc->encode;
601 rr.decode = assoc->decode;
602 rr.print = assoc->print;
604 rr.association = assoc;
610 yaz_log_zquery(rr.query);
611 (assoc->init->bend_search)(assoc->backend, &rr);
612 srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
615 srw_res->num_diagnostics = 1;
616 srw_res->diagnostics = (Z_SRW_diagnostic *)
617 odr_malloc(assoc->encode, sizeof(*srw_res->diagnostics));
618 srw_res->diagnostics[0].code =
619 odr_intdup(assoc->encode,
620 yaz_diag_bib1_to_srw (rr.errcode));
621 srw_res->diagnostics[0].details = rr.errstring;
625 srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
626 if (srw_req->maximumRecords && *srw_req->maximumRecords > 0)
628 int number = *srw_req->maximumRecords;
631 if (srw_req->startRecord)
632 start = *srw_req->startRecord;
633 if (start <= rr.hits)
636 if (start + number > rr.hits)
637 number = rr.hits - start + 1;
638 srw_res->records = (Z_SRW_record *)
639 odr_malloc(assoc->encode,
640 number * sizeof(*srw_res->records));
641 for (i = 0; i<number; i++)
644 srw_res->records[j].recordData_buf = 0;
645 errcode = srw_bend_fetch(assoc, i+start, srw_req,
646 srw_res->records + j);
649 srw_res->num_diagnostics = 1;
650 srw_res->diagnostics = (Z_SRW_diagnostic *)
651 odr_malloc(assoc->encode,
652 sizeof(*srw_res->diagnostics));
653 srw_res->diagnostics[0].code =
654 odr_intdup(assoc->encode,
655 yaz_diag_bib1_to_srw (errcode));
656 srw_res->diagnostics[0].details = rr.errstring;
659 if (srw_res->records[j].recordData_buf)
662 srw_res->num_records = j;
664 srw_res->records = 0;
670 static void process_http_request(association *assoc, request *req)
672 Z_HTTP_Request *hreq = req->gdu_request->u.HTTP_Request;
673 ODR o = assoc->encode;
675 Z_HTTP_Response *hres = 0;
678 if (!strcmp(hreq->method, "GET"))
681 if (strlen(hreq->path) >= 5 && strlen(hreq->path) < 80 &&
682 !memcmp(hreq->path, "/doc/", 5))
687 strcpy(fpath, DOCDIR);
688 strcat(fpath, hreq->path+4);
689 f = fopen(fpath, "rb");
692 if (fstat(fileno(f), &sbuf) || !S_ISREG(sbuf.st_mode))
701 fseek(f, 0L, SEEK_END);
703 if (sz >= 0 && sz < 500000)
705 const char *ctype = "application/octet-stream";
708 p = z_get_HTTP_Response(o, 200);
709 hres = p->u.HTTP_Response;
710 hres->content_buf = (char *) odr_malloc(o, sz + 1);
711 hres->content_len = sz;
712 fseek(f, 0L, SEEK_SET);
713 fread(hres->content_buf, 1, sz, f);
714 if ((cp = strrchr(fpath, '.'))) {
716 if (!strcmp(cp, "png"))
718 else if (!strcmp(cp, "gif"))
720 else if (!strcmp(cp, "xml"))
722 else if (!strcmp(cp, "html"))
725 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
731 if (!strcmp(hreq->path, "/"))
736 const char *doclink = "";
737 p = z_get_HTTP_Response(o, 200);
738 hres = p->u.HTTP_Response;
739 hres->content_buf = (char *) odr_malloc(o, 400);
741 if (stat(DOCDIR "/yaz.html", &sbuf) == 0 && S_ISREG(sbuf.st_mode))
742 doclink = "<P><A HREF=\"/doc/yaz.html\">Documentation</A></P>";
744 sprintf (hres->content_buf,
745 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n"
748 " <TITLE>YAZ " YAZ_VERSION "</TITLE>\n"
751 " <P><A HREF=\"http://www.indexdata.dk/yaz/\">YAZ</A> "
755 "</HTML>\n", doclink);
756 hres->content_len = strlen(hres->content_buf);
757 z_HTTP_header_add(o, &hres->headers, "Content-Type", "text/html");
761 p = z_get_HTTP_Response(o, 404);
764 else if (!strcmp(hreq->method, "POST"))
766 const char *content_type = z_HTTP_header_lookup(hreq->headers,
768 const char *soap_action = z_HTTP_header_lookup(hreq->headers,
770 if (content_type && soap_action &&
771 !yaz_strcmp_del("text/xml", content_type, "; "))
773 Z_SOAP *soap_package = 0;
777 static Z_SOAP_Handler soap_handlers[2] = {
779 {"http://www.loc.gov/zing/srw/v1.0/", 0,
780 (Z_SOAP_fun) yaz_srw_codec},
784 ret = z_soap_codec(assoc->decode, &soap_package,
785 &hreq->content_buf, &hreq->content_len,
789 if (!ret && soap_package->which == Z_SOAP_generic &&
790 soap_package->u.generic->no == 0)
793 Z_SRW_PDU *sr = soap_package->u.generic->p;
795 if (sr->which == Z_SRW_searchRetrieve_request)
798 yaz_srw_get(assoc->encode,
799 Z_SRW_searchRetrieve_response);
801 if (!sr->u.request->database)
803 const char *p0 = hreq->path, *p1;
806 p1 = strchr(p0, '?');
808 p1 = p0 + strlen(p0);
811 sr->u.request->database =
812 odr_malloc(assoc->decode, p1 - p0 + 1);
813 memcpy (sr->u.request->database, p0, p1 - p0);
814 sr->u.request->database[p1 - p0] = '\0';
817 sr->u.request->database = "Default";
819 srw_bend_search(assoc, req, sr->u.request,
822 soap_package->u.generic->p = res;
827 p = z_get_HTTP_Response(o, 200);
828 hres = p->u.HTTP_Response;
829 ret = z_soap_codec(assoc->encode, &soap_package,
830 &hres->content_buf, &hres->content_len,
832 hres->code = http_code;
833 z_HTTP_header_add(o, &hres->headers, "Content-Type", "text/xml");
835 if (!p) /* still no response ? */
836 p = z_get_HTTP_Response(o, 500);
840 p = z_get_HTTP_Response(o, 405);
841 hres = p->u.HTTP_Response;
843 z_HTTP_header_add(o, &hres->headers, "Allow", "GET, POST");
845 hres = p->u.HTTP_Response;
846 if (!strcmp(hreq->version, "1.0"))
848 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
849 if (v && !strcmp(v, "Keep-Alive"))
853 hres->version = "1.0";
857 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
858 if (v && !strcmp(v, "close"))
862 hres->version = "1.1";
866 z_HTTP_header_add(o, &hres->headers, "Connection", "close");
867 assoc->state = ASSOC_DEAD;
872 const char *alive = z_HTTP_header_lookup(hreq->headers, "Keep-Alive");
874 if (alive && isdigit(*alive))
878 if (t < 0 || t > 3600)
880 iochan_settimeout(assoc->client_chan,t);
881 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
883 process_gdu_response(assoc, req, p);
886 static void process_gdu_request(association *assoc, request *req)
888 if (req->gdu_request->which == Z_GDU_Z3950)
891 req->apdu_request = req->gdu_request->u.z3950;
892 if (process_z_request(assoc, req, &msg) < 0)
893 do_close_req(assoc, Z_Close_systemProblem, msg, req);
895 else if (req->gdu_request->which == Z_GDU_HTTP_Request)
896 process_http_request(assoc, req);
899 do_close_req(assoc, Z_Close_systemProblem, "bad protocol packet", req);
904 * Initiate request processing.
906 static int process_z_request(association *assoc, request *req, char **msg)
912 *msg = "Unknown Error";
913 assert(req && req->state == REQUEST_IDLE);
914 if (req->apdu_request->which != Z_APDU_initRequest && !assoc->init)
916 *msg = "Missing InitRequest";
919 switch (req->apdu_request->which)
921 case Z_APDU_initRequest:
922 iochan_settimeout(assoc->client_chan,
923 statserv_getcontrol()->idle_timeout * 60);
924 res = process_initRequest(assoc, req); break;
925 case Z_APDU_searchRequest:
926 res = process_searchRequest(assoc, req, &fd); break;
927 case Z_APDU_presentRequest:
928 res = process_presentRequest(assoc, req, &fd); break;
929 case Z_APDU_scanRequest:
930 if (assoc->init->bend_scan)
931 res = process_scanRequest(assoc, req, &fd);
934 *msg = "Cannot handle Scan APDU";
938 case Z_APDU_extendedServicesRequest:
939 if (assoc->init->bend_esrequest)
940 res = process_ESRequest(assoc, req, &fd);
943 *msg = "Cannot handle Extended Services APDU";
947 case Z_APDU_sortRequest:
948 if (assoc->init->bend_sort)
949 res = process_sortRequest(assoc, req, &fd);
952 *msg = "Cannot handle Sort APDU";
957 process_close(assoc, req);
959 case Z_APDU_deleteResultSetRequest:
960 if (assoc->init->bend_delete)
961 res = process_deleteRequest(assoc, req, &fd);
964 *msg = "Cannot handle Delete APDU";
968 case Z_APDU_segmentRequest:
969 if (assoc->init->bend_segment)
971 res = process_segmentRequest (assoc, req);
975 *msg = "Cannot handle Segment APDU";
980 *msg = "Bad APDU received";
985 yaz_log(LOG_DEBUG, " result immediately available");
986 retval = process_z_response(assoc, req, res);
990 yaz_log(LOG_DEBUG, " result unavailble");
993 else /* no result yet - one will be provided later */
997 /* Set up an I/O handler for the fd supplied by the backend */
999 yaz_log(LOG_DEBUG, " establishing handler for result");
1000 req->state = REQUEST_PENDING;
1001 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT)))
1003 iochan_setdata(chan, assoc);
1010 * Handle message from the backend.
1012 void backend_response(IOCHAN i, int event)
1014 association *assoc = (association *)iochan_getdata(i);
1015 request *req = request_head(&assoc->incoming);
1019 yaz_log(LOG_DEBUG, "backend_response");
1020 assert(assoc && req && req->state != REQUEST_IDLE);
1021 /* determine what it is we're waiting for */
1022 switch (req->apdu_request->which)
1024 case Z_APDU_searchRequest:
1025 res = response_searchRequest(assoc, req, 0, &fd); break;
1027 case Z_APDU_presentRequest:
1028 res = response_presentRequest(assoc, req, 0, &fd); break;
1029 case Z_APDU_scanRequest:
1030 res = response_scanRequest(assoc, req, 0, &fd); break;
1033 yaz_log(LOG_WARN, "Serious programmer's lapse or bug");
1036 if ((res && process_z_response(assoc, req, res) < 0) || fd < 0)
1038 yaz_log(LOG_LOG, "Fatal error when talking to backend");
1039 do_close(assoc, Z_Close_systemProblem, 0);
1043 else if (!res) /* no result yet - try again later */
1045 yaz_log(LOG_DEBUG, " no result yet");
1046 iochan_setfd(i, fd); /* in case fd has changed */
1051 * Encode response, and transfer the request structure to the outgoing queue.
1053 static int process_gdu_response(association *assoc, request *req, Z_GDU *res)
1055 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
1057 if (assoc->print && !z_GDU(assoc->print, &res, 0, 0))
1059 yaz_log(LOG_WARN, "ODR print error: %s",
1060 odr_errmsg(odr_geterror(assoc->print)));
1061 odr_reset(assoc->print);
1063 if (!z_GDU(assoc->encode, &res, 0, 0))
1065 yaz_log(LOG_WARN, "ODR error when encoding response: %s",
1066 odr_errmsg(odr_geterror(assoc->decode)));
1069 req->response = odr_getbuf(assoc->encode, &req->len_response,
1070 &req->size_response);
1071 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
1072 odr_reset(assoc->encode);
1073 req->state = REQUEST_IDLE;
1074 request_enq(&assoc->outgoing, req);
1075 /* turn the work over to the ir_session handler */
1076 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
1077 assoc->cs_put_mask = EVENT_OUTPUT;
1078 /* Is there more work to be done? give that to the input handler too */
1080 if (request_head(&assoc->incoming))
1082 yaz_log (LOG_DEBUG, "more work to be done");
1083 iochan_setevent(assoc->client_chan, EVENT_WORK);
1090 * Encode response, and transfer the request structure to the outgoing queue.
1092 static int process_z_response(association *assoc, request *req, Z_APDU *res)
1094 Z_GDU *gres = (Z_GDU *) odr_malloc(assoc->encode, sizeof(*res));
1095 gres->which = Z_GDU_Z3950;
1096 gres->u.z3950 = res;
1098 return process_gdu_response(assoc, req, gres);
1103 * Handle init request.
1104 * At the moment, we don't check the options
1105 * anywhere else in the code - we just try not to do anything that would
1106 * break a naive client. We'll toss 'em into the association block when
1107 * we need them there.
1109 static Z_APDU *process_initRequest(association *assoc, request *reqb)
1111 statserv_options_block *cb = statserv_getcontrol();
1112 Z_InitRequest *req = reqb->apdu_request->u.initRequest;
1113 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
1114 Z_InitResponse *resp = apdu->u.initResponse;
1115 bend_initresult *binitres;
1119 yaz_log(LOG_LOG, "Got initRequest");
1120 if (req->implementationId)
1121 yaz_log(LOG_LOG, "Id: %s", req->implementationId);
1122 if (req->implementationName)
1123 yaz_log(LOG_LOG, "Name: %s", req->implementationName);
1124 if (req->implementationVersion)
1125 yaz_log(LOG_LOG, "Version: %s", req->implementationVersion);
1127 assoc_init_reset(assoc);
1129 assoc->init->auth = req->idAuthentication;
1130 assoc->init->referenceId = req->referenceId;
1132 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
1134 Z_CharSetandLanguageNegotiation *negotiation =
1135 yaz_get_charneg_record (req->otherInfo);
1136 if (negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
1137 assoc->init->charneg_request = negotiation;
1140 if (!(binitres = (*cb->bend_init)(assoc->init)))
1142 yaz_log(LOG_WARN, "Bad response from backend.");
1146 assoc->backend = binitres->handle;
1147 if ((assoc->init->bend_sort))
1148 yaz_log (LOG_DEBUG, "Sort handler installed");
1149 if ((assoc->init->bend_search))
1150 yaz_log (LOG_DEBUG, "Search handler installed");
1151 if ((assoc->init->bend_present))
1152 yaz_log (LOG_DEBUG, "Present handler installed");
1153 if ((assoc->init->bend_esrequest))
1154 yaz_log (LOG_DEBUG, "ESRequest handler installed");
1155 if ((assoc->init->bend_delete))
1156 yaz_log (LOG_DEBUG, "Delete handler installed");
1157 if ((assoc->init->bend_scan))
1158 yaz_log (LOG_DEBUG, "Scan handler installed");
1159 if ((assoc->init->bend_segment))
1160 yaz_log (LOG_DEBUG, "Segment handler installed");
1162 resp->referenceId = req->referenceId;
1164 /* let's tell the client what we can do */
1165 if (ODR_MASK_GET(req->options, Z_Options_search))
1167 ODR_MASK_SET(resp->options, Z_Options_search);
1168 strcat(options, "srch");
1170 if (ODR_MASK_GET(req->options, Z_Options_present))
1172 ODR_MASK_SET(resp->options, Z_Options_present);
1173 strcat(options, " prst");
1175 if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
1176 assoc->init->bend_delete)
1178 ODR_MASK_SET(resp->options, Z_Options_delSet);
1179 strcat(options, " del");
1181 if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
1182 assoc->init->bend_esrequest)
1184 ODR_MASK_SET(resp->options, Z_Options_extendedServices);
1185 strcat (options, " extendedServices");
1187 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
1189 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
1190 strcat(options, " namedresults");
1192 if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
1194 ODR_MASK_SET(resp->options, Z_Options_scan);
1195 strcat(options, " scan");
1197 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
1199 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
1200 strcat(options, " concurrop");
1202 if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
1204 ODR_MASK_SET(resp->options, Z_Options_sort);
1205 strcat(options, " sort");
1208 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel)
1209 && assoc->init->charneg_response)
1211 Z_OtherInformation **p;
1212 Z_OtherInformationUnit *p0;
1214 yaz_oi_APDU(apdu, &p);
1216 if ((p0=yaz_oi_update(p, assoc->encode, NULL, 0, 0))) {
1217 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
1219 p0->which = Z_OtherInfo_externallyDefinedInfo;
1220 p0->information.externallyDefinedInfo =
1221 assoc->init->charneg_response;
1223 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
1224 strcat(options, " negotiation");
1227 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
1229 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
1230 assoc->version = 2; /* 1 & 2 are equivalent */
1232 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
1234 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
1237 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
1239 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
1243 yaz_log(LOG_LOG, "Negotiated to v%d: %s", assoc->version, options);
1244 assoc->maximumRecordSize = *req->maximumRecordSize;
1245 if (assoc->maximumRecordSize > control_block->maxrecordsize)
1246 assoc->maximumRecordSize = control_block->maxrecordsize;
1247 assoc->preferredMessageSize = *req->preferredMessageSize;
1248 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
1249 assoc->preferredMessageSize = assoc->maximumRecordSize;
1251 resp->preferredMessageSize = &assoc->preferredMessageSize;
1252 resp->maximumRecordSize = &assoc->maximumRecordSize;
1254 resp->implementationName = "GFS/YAZ";
1256 if (assoc->init->implementation_id)
1259 odr_malloc (assoc->encode,
1260 strlen(assoc->init->implementation_id) + 10 +
1261 strlen(resp->implementationId));
1262 sprintf (nv, "%s / %s",
1263 resp->implementationId, assoc->init->implementation_id);
1264 resp->implementationId = nv;
1266 if (assoc->init->implementation_name)
1269 odr_malloc (assoc->encode,
1270 strlen(assoc->init->implementation_name) + 10 +
1271 strlen(resp->implementationName));
1272 sprintf (nv, "%s / %s",
1273 resp->implementationName, assoc->init->implementation_name);
1274 resp->implementationName = nv;
1276 if (assoc->init->implementation_version)
1279 odr_malloc (assoc->encode,
1280 strlen(assoc->init->implementation_version) + 10 +
1281 strlen(resp->implementationVersion));
1282 sprintf (nv, "YAZ %s / %s",
1283 resp->implementationVersion,
1284 assoc->init->implementation_version);
1285 resp->implementationVersion = nv;
1288 if (binitres->errcode)
1290 yaz_log(LOG_LOG, "Connection rejected by backend.");
1292 assoc->state = ASSOC_DEAD;
1295 assoc->state = ASSOC_UP;
1300 * These functions should be merged.
1303 static void set_addinfo (Z_DefaultDiagFormat *dr, char *addinfo, ODR odr)
1305 dr->which = Z_DefaultDiagFormat_v2Addinfo;
1306 dr->u.v2Addinfo = odr_strdup (odr, addinfo ? addinfo : "");
1310 * nonsurrogate diagnostic record.
1312 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
1314 Z_Records *rec = (Z_Records *)
1315 odr_malloc (assoc->encode, sizeof(*rec));
1316 int *err = odr_intdup(assoc->encode, error);
1317 Z_DiagRec *drec = (Z_DiagRec *)
1318 odr_malloc (assoc->encode, sizeof(*drec));
1319 Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
1320 odr_malloc (assoc->encode, sizeof(*dr));
1322 yaz_log(LOG_LOG, "[%d] %s %s%s", error, diagbib1_str(error),
1323 addinfo ? " -- " : "", addinfo ? addinfo : "");
1324 rec->which = Z_Records_NSD;
1325 rec->u.nonSurrogateDiagnostic = dr;
1326 dr->diagnosticSetId =
1327 yaz_oidval_to_z3950oid (assoc->encode, CLASS_DIAGSET, VAL_BIB1);
1328 dr->condition = err;
1329 set_addinfo (dr, addinfo, assoc->encode);
1334 * surrogate diagnostic.
1336 static Z_NamePlusRecord *surrogatediagrec(association *assoc, char *dbname,
1337 int error, char *addinfo)
1339 Z_NamePlusRecord *rec = (Z_NamePlusRecord *)
1340 odr_malloc (assoc->encode, sizeof(*rec));
1341 int *err = odr_intdup(assoc->encode, error);
1342 Z_DiagRec *drec = (Z_DiagRec *)odr_malloc (assoc->encode, sizeof(*drec));
1343 Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
1344 odr_malloc (assoc->encode, sizeof(*dr));
1346 yaz_log(LOG_DEBUG, "SurrogateDiagnotic: %d -- %s", error, addinfo);
1347 rec->databaseName = dbname;
1348 rec->which = Z_NamePlusRecord_surrogateDiagnostic;
1349 rec->u.surrogateDiagnostic = drec;
1350 drec->which = Z_DiagRec_defaultFormat;
1351 drec->u.defaultFormat = dr;
1352 dr->diagnosticSetId =
1353 yaz_oidval_to_z3950oid (assoc->encode, CLASS_DIAGSET, VAL_BIB1);
1354 dr->condition = err;
1355 set_addinfo (dr, addinfo, assoc->encode);
1361 * multiple nonsurrogate diagnostics.
1363 static Z_DiagRecs *diagrecs(association *assoc, int error, char *addinfo)
1365 Z_DiagRecs *recs = (Z_DiagRecs *)odr_malloc (assoc->encode, sizeof(*recs));
1366 int *err = odr_intdup(assoc->encode, error);
1367 Z_DiagRec **recp = (Z_DiagRec **)odr_malloc (assoc->encode, sizeof(*recp));
1368 Z_DiagRec *drec = (Z_DiagRec *)odr_malloc (assoc->encode, sizeof(*drec));
1369 Z_DefaultDiagFormat *rec = (Z_DefaultDiagFormat *)
1370 odr_malloc (assoc->encode, sizeof(*rec));
1372 yaz_log(LOG_DEBUG, "DiagRecs: %d -- %s", error, addinfo ? addinfo : "");
1374 recs->num_diagRecs = 1;
1375 recs->diagRecs = recp;
1377 drec->which = Z_DiagRec_defaultFormat;
1378 drec->u.defaultFormat = rec;
1380 rec->diagnosticSetId =
1381 yaz_oidval_to_z3950oid (assoc->encode, CLASS_DIAGSET, VAL_BIB1);
1382 rec->condition = err;
1384 rec->which = Z_DefaultDiagFormat_v2Addinfo;
1385 rec->u.v2Addinfo = odr_strdup (assoc->encode, addinfo ? addinfo : "");
1389 static Z_Records *pack_records(association *a, char *setname, int start,
1390 int *num, Z_RecordComposition *comp,
1391 int *next, int *pres, oid_value format,
1392 Z_ReferenceId *referenceId,
1395 int recno, total_length = 0, toget = *num, dumped_records = 0;
1396 Z_Records *records =
1397 (Z_Records *) odr_malloc (a->encode, sizeof(*records));
1398 Z_NamePlusRecordList *reclist =
1399 (Z_NamePlusRecordList *) odr_malloc (a->encode, sizeof(*reclist));
1400 Z_NamePlusRecord **list =
1401 (Z_NamePlusRecord **) odr_malloc (a->encode, sizeof(*list) * toget);
1403 records->which = Z_Records_DBOSD;
1404 records->u.databaseOrSurDiagnostics = reclist;
1405 reclist->num_records = 0;
1406 reclist->records = list;
1407 *pres = Z_PRES_SUCCESS;
1411 yaz_log(LOG_LOG, "Request to pack %d+%d+%s", start, toget, setname);
1412 yaz_log(LOG_DEBUG, "pms=%d, mrs=%d", a->preferredMessageSize,
1413 a->maximumRecordSize);
1414 for (recno = start; reclist->num_records < toget; recno++)
1417 Z_NamePlusRecord *thisrec;
1418 int this_length = 0;
1420 * we get the number of bytes allocated on the stream before any
1421 * allocation done by the backend - this should give us a reasonable
1422 * idea of the total size of the data so far.
1424 total_length = odr_total(a->encode) - dumped_records;
1430 freq.last_in_set = 0;
1431 freq.setname = setname;
1432 freq.surrogate_flag = 0;
1433 freq.number = recno;
1435 freq.request_format = format;
1436 freq.request_format_raw = oid;
1437 freq.output_format = format;
1438 freq.output_format_raw = 0;
1439 freq.stream = a->encode;
1440 freq.print = a->print;
1441 freq.surrogate_flag = 0;
1442 freq.referenceId = referenceId;
1443 (*a->init->bend_fetch)(a->backend, &freq);
1444 /* backend should be able to signal whether error is system-wide
1445 or only pertaining to current record */
1448 if (!freq.surrogate_flag)
1451 *pres = Z_PRES_FAILURE;
1452 /* for 'present request out of range',
1453 set addinfo to record position if not set */
1454 if (freq.errcode == 13 && freq.errstring == 0)
1456 sprintf (s, "%d", recno);
1459 return diagrec(a, freq.errcode, freq.errstring);
1461 reclist->records[reclist->num_records] =
1462 surrogatediagrec(a, freq.basename, freq.errcode,
1464 reclist->num_records++;
1465 *next = freq.last_in_set ? 0 : recno + 1;
1469 this_length = freq.len;
1471 this_length = odr_total(a->encode) - total_length;
1472 yaz_log(LOG_DEBUG, " fetched record, len=%d, total=%d",
1473 this_length, total_length);
1474 if (this_length + total_length > a->preferredMessageSize)
1476 /* record is small enough, really */
1477 if (this_length <= a->preferredMessageSize)
1479 yaz_log(LOG_DEBUG, " Dropped last normal-sized record");
1480 *pres = Z_PRES_PARTIAL_2;
1483 /* record can only be fetched by itself */
1484 if (this_length < a->maximumRecordSize)
1486 yaz_log(LOG_DEBUG, " Record > prefmsgsz");
1489 yaz_log(LOG_DEBUG, " Dropped it");
1490 reclist->records[reclist->num_records] =
1491 surrogatediagrec(a, freq.basename, 16, 0);
1492 reclist->num_records++;
1493 *next = freq.last_in_set ? 0 : recno + 1;
1494 dumped_records += this_length;
1498 else /* too big entirely */
1500 yaz_log(LOG_LOG, "Record > maxrcdsz this=%d max=%d", this_length, a->maximumRecordSize);
1501 reclist->records[reclist->num_records] =
1502 surrogatediagrec(a, freq.basename, 17, 0);
1503 reclist->num_records++;
1504 *next = freq.last_in_set ? 0 : recno + 1;
1505 dumped_records += this_length;
1510 if (!(thisrec = (Z_NamePlusRecord *)
1511 odr_malloc(a->encode, sizeof(*thisrec))))
1513 if (!(thisrec->databaseName = (char *)odr_malloc(a->encode,
1514 strlen(freq.basename) + 1)))
1516 strcpy(thisrec->databaseName, freq.basename);
1517 thisrec->which = Z_NamePlusRecord_databaseRecord;
1519 if (freq.output_format_raw)
1521 struct oident *ident = oid_getentbyoid(freq.output_format_raw);
1522 freq.output_format = ident->value;
1524 thisrec->u.databaseRecord = z_ext_record(a->encode, freq.output_format,
1525 freq.record, freq.len);
1526 if (!thisrec->u.databaseRecord)
1528 reclist->records[reclist->num_records] = thisrec;
1529 reclist->num_records++;
1530 *next = freq.last_in_set ? 0 : recno + 1;
1532 *num = reclist->num_records;
1536 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
1539 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
1540 bend_search_rr *bsrr =
1541 (bend_search_rr *)nmem_malloc (reqb->request_mem, sizeof(*bsrr));
1543 yaz_log(LOG_LOG, "Got SearchRequest.");
1545 bsrr->request = reqb;
1546 bsrr->association = assoc;
1547 bsrr->referenceId = req->referenceId;
1548 save_referenceId (reqb, bsrr->referenceId);
1550 yaz_log (LOG_LOG, "ResultSet '%s'", req->resultSetName);
1551 if (req->databaseNames)
1554 for (i = 0; i < req->num_databaseNames; i++)
1555 yaz_log (LOG_LOG, "Database '%s'", req->databaseNames[i]);
1557 yaz_log_zquery(req->query);
1559 if (assoc->init->bend_search)
1561 bsrr->setname = req->resultSetName;
1562 bsrr->replace_set = *req->replaceIndicator;
1563 bsrr->num_bases = req->num_databaseNames;
1564 bsrr->basenames = req->databaseNames;
1565 bsrr->query = req->query;
1566 bsrr->stream = assoc->encode;
1567 bsrr->decode = assoc->decode;
1568 bsrr->print = assoc->print;
1571 bsrr->errstring = NULL;
1572 bsrr->search_info = NULL;
1573 (assoc->init->bend_search)(assoc->backend, bsrr);
1577 return response_searchRequest(assoc, reqb, bsrr, fd);
1580 int bend_searchresponse(void *handle, bend_search_rr *bsrr) {return 0;}
1583 * Prepare a searchresponse based on the backend results. We probably want
1584 * to look at making the fetching of records nonblocking as well, but
1585 * so far, we'll keep things simple.
1586 * If bsrt is null, that means we're called in response to a communications
1587 * event, and we'll have to get the response for ourselves.
1589 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
1590 bend_search_rr *bsrt, int *fd)
1592 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
1593 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1594 Z_SearchResponse *resp = (Z_SearchResponse *)
1595 odr_malloc (assoc->encode, sizeof(*resp));
1596 int *nulint = odr_intdup (assoc->encode, 0);
1597 bool_t *sr = odr_intdup(assoc->encode, 1);
1598 int *next = odr_intdup(assoc->encode, 0);
1599 int *none = odr_intdup(assoc->encode, Z_RES_NONE);
1601 apdu->which = Z_APDU_searchResponse;
1602 apdu->u.searchResponse = resp;
1603 resp->referenceId = req->referenceId;
1604 resp->additionalSearchInfo = 0;
1605 resp->otherInfo = 0;
1607 if (!bsrt && !bend_searchresponse(assoc->backend, bsrt))
1609 yaz_log(LOG_FATAL, "Bad result from backend");
1612 else if (bsrt->errcode)
1614 resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
1615 resp->resultCount = nulint;
1616 resp->numberOfRecordsReturned = nulint;
1617 resp->nextResultSetPosition = nulint;
1618 resp->searchStatus = nulint;
1619 resp->resultSetStatus = none;
1620 resp->presentStatus = 0;
1624 int *toget = odr_intdup(assoc->encode, 0);
1625 int *presst = odr_intdup(assoc->encode, 0);
1626 Z_RecordComposition comp, *compp = 0;
1628 yaz_log (LOG_LOG, "resultCount: %d", bsrt->hits);
1631 resp->resultCount = &bsrt->hits;
1633 comp.which = Z_RecordComp_simple;
1634 /* how many records does the user agent want, then? */
1635 if (bsrt->hits <= *req->smallSetUpperBound)
1637 *toget = bsrt->hits;
1638 if ((comp.u.simple = req->smallSetElementSetNames))
1641 else if (bsrt->hits < *req->largeSetLowerBound)
1643 *toget = *req->mediumSetPresentNumber;
1644 if (*toget > bsrt->hits)
1645 *toget = bsrt->hits;
1646 if ((comp.u.simple = req->mediumSetElementSetNames))
1652 if (*toget && !resp->records)
1657 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
1660 form = prefformat->value;
1661 resp->records = pack_records(assoc, req->resultSetName, 1,
1662 toget, compp, next, presst, form, req->referenceId,
1663 req->preferredRecordSyntax);
1666 resp->numberOfRecordsReturned = toget;
1667 resp->nextResultSetPosition = next;
1668 resp->searchStatus = sr;
1669 resp->resultSetStatus = 0;
1670 resp->presentStatus = presst;
1674 if (*resp->resultCount)
1676 resp->numberOfRecordsReturned = nulint;
1677 resp->nextResultSetPosition = next;
1678 resp->searchStatus = sr;
1679 resp->resultSetStatus = 0;
1680 resp->presentStatus = 0;
1683 resp->additionalSearchInfo = bsrt->search_info;
1688 * Maybe we got a little over-friendly when we designed bend_fetch to
1689 * get only one record at a time. Some backends can optimise multiple-record
1690 * fetches, and at any rate, there is some overhead involved in
1691 * all that selecting and hopping around. Problem is, of course, that the
1692 * frontend can't know ahead of time how many records it'll need to
1693 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
1694 * is downright lousy as a bulk data transfer protocol.
1696 * To start with, we'll do the fetching of records from the backend
1697 * in one operation: To save some trips in and out of the event-handler,
1698 * and to simplify the interface to pack_records. At any rate, asynch
1699 * operation is more fun in operations that have an unpredictable execution
1700 * speed - which is normally more true for search than for present.
1702 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
1705 Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
1709 Z_PresentResponse *resp;
1713 yaz_log(LOG_LOG, "Got PresentRequest.");
1715 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
1718 form = prefformat->value;
1719 resp = (Z_PresentResponse *)odr_malloc (assoc->encode, sizeof(*resp));
1721 resp->presentStatus = odr_intdup(assoc->encode, 0);
1722 if (assoc->init->bend_present)
1724 bend_present_rr *bprr = (bend_present_rr *)
1725 nmem_malloc (reqb->request_mem, sizeof(*bprr));
1726 bprr->setname = req->resultSetId;
1727 bprr->start = *req->resultSetStartPoint;
1728 bprr->number = *req->numberOfRecordsRequested;
1729 bprr->format = form;
1730 bprr->comp = req->recordComposition;
1731 bprr->referenceId = req->referenceId;
1732 bprr->stream = assoc->encode;
1733 bprr->print = assoc->print;
1734 bprr->request = reqb;
1735 bprr->association = assoc;
1737 bprr->errstring = NULL;
1738 (*assoc->init->bend_present)(assoc->backend, bprr);
1744 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
1745 *resp->presentStatus = Z_PRES_FAILURE;
1748 apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1749 next = odr_intdup(assoc->encode, 0);
1750 num = odr_intdup(assoc->encode, 0);
1752 apdu->which = Z_APDU_presentResponse;
1753 apdu->u.presentResponse = resp;
1754 resp->referenceId = req->referenceId;
1755 resp->otherInfo = 0;
1759 *num = *req->numberOfRecordsRequested;
1761 pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
1762 num, req->recordComposition, next, resp->presentStatus,
1763 form, req->referenceId, req->preferredRecordSyntax);
1767 resp->numberOfRecordsReturned = num;
1768 resp->nextResultSetPosition = next;
1774 * Scan was implemented rather in a hurry, and with support for only the basic
1775 * elements of the service in the backend API. Suggestions are welcome.
1777 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
1779 Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
1780 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1781 Z_ScanResponse *res = (Z_ScanResponse *)
1782 odr_malloc (assoc->encode, sizeof(*res));
1783 int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
1784 int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
1785 Z_ListEntries *ents = (Z_ListEntries *)
1786 odr_malloc (assoc->encode, sizeof(*ents));
1787 Z_DiagRecs *diagrecs_p = NULL;
1789 bend_scan_rr *bsrr = (bend_scan_rr *)
1790 odr_malloc (assoc->encode, sizeof(*bsrr));
1792 yaz_log(LOG_LOG, "Got ScanRequest");
1794 apdu->which = Z_APDU_scanResponse;
1795 apdu->u.scanResponse = res;
1796 res->referenceId = req->referenceId;
1798 /* if step is absent, set it to 0 */
1799 res->stepSize = odr_intdup(assoc->encode, 0);
1801 *res->stepSize = *req->stepSize;
1803 res->scanStatus = scanStatus;
1804 res->numberOfEntriesReturned = numberOfEntriesReturned;
1805 res->positionOfTerm = 0;
1806 res->entries = ents;
1807 ents->num_entries = 0;
1808 ents->entries = NULL;
1809 ents->num_nonsurrogateDiagnostics = 0;
1810 ents->nonsurrogateDiagnostics = NULL;
1811 res->attributeSet = 0;
1814 if (req->databaseNames)
1817 for (i = 0; i < req->num_databaseNames; i++)
1818 yaz_log (LOG_LOG, "Database '%s'", req->databaseNames[i]);
1820 bsrr->num_bases = req->num_databaseNames;
1821 bsrr->basenames = req->databaseNames;
1822 bsrr->num_entries = *req->numberOfTermsRequested;
1823 bsrr->term = req->termListAndStartPoint;
1824 bsrr->referenceId = req->referenceId;
1825 bsrr->stream = assoc->encode;
1826 bsrr->print = assoc->print;
1827 bsrr->step_size = res->stepSize;
1828 if (req->attributeSet &&
1829 (attset = oid_getentbyoid(req->attributeSet)) &&
1830 (attset->oclass == CLASS_ATTSET || attset->oclass == CLASS_GENERAL))
1831 bsrr->attributeset = attset->value;
1833 bsrr->attributeset = VAL_NONE;
1834 log_scan_term (req->termListAndStartPoint, bsrr->attributeset);
1835 bsrr->term_position = req->preferredPositionInResponse ?
1836 *req->preferredPositionInResponse : 1;
1837 ((int (*)(void *, bend_scan_rr *))
1838 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1840 diagrecs_p = diagrecs(assoc, bsrr->errcode, bsrr->errstring);
1844 Z_Entry **tab = (Z_Entry **)
1845 odr_malloc (assoc->encode, sizeof(*tab) * bsrr->num_entries);
1847 if (bsrr->status == BEND_SCAN_PARTIAL)
1848 *scanStatus = Z_Scan_partial_5;
1850 *scanStatus = Z_Scan_success;
1851 ents->entries = tab;
1852 ents->num_entries = bsrr->num_entries;
1853 res->numberOfEntriesReturned = &ents->num_entries;
1854 res->positionOfTerm = &bsrr->term_position;
1855 for (i = 0; i < bsrr->num_entries; i++)
1861 tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
1862 if (bsrr->entries[i].occurrences >= 0)
1864 e->which = Z_Entry_termInfo;
1865 e->u.termInfo = t = (Z_TermInfo *)
1866 odr_malloc(assoc->encode, sizeof(*t));
1867 t->suggestedAttributes = 0;
1869 t->alternativeTerm = 0;
1870 t->byAttributes = 0;
1871 t->otherTermInfo = 0;
1872 t->globalOccurrences = &bsrr->entries[i].occurrences;
1873 t->term = (Z_Term *)
1874 odr_malloc(assoc->encode, sizeof(*t->term));
1875 t->term->which = Z_Term_general;
1876 t->term->u.general = o =
1877 (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
1878 o->buf = (unsigned char *)
1879 odr_malloc(assoc->encode, o->len = o->size =
1880 strlen(bsrr->entries[i].term));
1881 memcpy(o->buf, bsrr->entries[i].term, o->len);
1882 yaz_log(LOG_DEBUG, " term #%d: '%s' (%d)", i,
1883 bsrr->entries[i].term, bsrr->entries[i].occurrences);
1887 Z_DiagRecs *drecs = diagrecs (assoc,
1888 bsrr->entries[i].errcode,
1889 bsrr->entries[i].errstring);
1890 assert (drecs->num_diagRecs == 1);
1891 e->which = Z_Entry_surrogateDiagnostic;
1892 assert (drecs->diagRecs[0]);
1893 e->u.surrogateDiagnostic = drecs->diagRecs[0];
1899 ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
1900 ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
1905 static Z_APDU *process_sortRequest(association *assoc, request *reqb,
1908 Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
1909 Z_SortResponse *res = (Z_SortResponse *)
1910 odr_malloc (assoc->encode, sizeof(*res));
1911 bend_sort_rr *bsrr = (bend_sort_rr *)
1912 odr_malloc (assoc->encode, sizeof(*bsrr));
1914 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1916 yaz_log(LOG_LOG, "Got SortRequest.");
1918 bsrr->num_input_setnames = req->num_inputResultSetNames;
1919 bsrr->input_setnames = req->inputResultSetNames;
1920 bsrr->referenceId = req->referenceId;
1921 bsrr->output_setname = req->sortedResultSetName;
1922 bsrr->sort_sequence = req->sortSequence;
1923 bsrr->stream = assoc->encode;
1924 bsrr->print = assoc->print;
1926 bsrr->sort_status = Z_SortStatus_failure;
1928 bsrr->errstring = 0;
1930 (*assoc->init->bend_sort)(assoc->backend, bsrr);
1932 res->referenceId = bsrr->referenceId;
1933 res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
1934 res->resultSetStatus = 0;
1937 Z_DiagRecs *dr = diagrecs (assoc, bsrr->errcode, bsrr->errstring);
1938 res->diagnostics = dr->diagRecs;
1939 res->num_diagnostics = dr->num_diagRecs;
1943 res->num_diagnostics = 0;
1944 res->diagnostics = 0;
1948 apdu->which = Z_APDU_sortResponse;
1949 apdu->u.sortResponse = res;
1953 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
1956 Z_DeleteResultSetRequest *req =
1957 reqb->apdu_request->u.deleteResultSetRequest;
1958 Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
1959 odr_malloc (assoc->encode, sizeof(*res));
1960 bend_delete_rr *bdrr = (bend_delete_rr *)
1961 odr_malloc (assoc->encode, sizeof(*bdrr));
1962 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1964 yaz_log(LOG_LOG, "Got DeleteRequest.");
1966 bdrr->num_setnames = req->num_resultSetList;
1967 bdrr->setnames = req->resultSetList;
1968 bdrr->stream = assoc->encode;
1969 bdrr->print = assoc->print;
1970 bdrr->function = *req->deleteFunction;
1971 bdrr->referenceId = req->referenceId;
1973 if (bdrr->num_setnames > 0)
1976 bdrr->statuses = (int*)
1977 odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
1978 bdrr->num_setnames);
1979 for (i = 0; i < bdrr->num_setnames; i++)
1980 bdrr->statuses[i] = 0;
1982 (*assoc->init->bend_delete)(assoc->backend, bdrr);
1984 res->referenceId = req->referenceId;
1986 res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
1988 res->deleteListStatuses = 0;
1989 if (bdrr->num_setnames > 0)
1992 res->deleteListStatuses = (Z_ListStatuses *)
1993 odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
1994 res->deleteListStatuses->num = bdrr->num_setnames;
1995 res->deleteListStatuses->elements =
1997 odr_malloc (assoc->encode,
1998 sizeof(*res->deleteListStatuses->elements) *
1999 bdrr->num_setnames);
2000 for (i = 0; i<bdrr->num_setnames; i++)
2002 res->deleteListStatuses->elements[i] =
2004 odr_malloc (assoc->encode,
2005 sizeof(**res->deleteListStatuses->elements));
2006 res->deleteListStatuses->elements[i]->status = bdrr->statuses+i;
2007 res->deleteListStatuses->elements[i]->id =
2008 odr_strdup (assoc->encode, bdrr->setnames[i]);
2012 res->numberNotDeleted = 0;
2013 res->bulkStatuses = 0;
2014 res->deleteMessage = 0;
2017 apdu->which = Z_APDU_deleteResultSetResponse;
2018 apdu->u.deleteResultSetResponse = res;
2022 static void process_close(association *assoc, request *reqb)
2024 Z_Close *req = reqb->apdu_request->u.close;
2025 static char *reasons[] =
2032 "securityViolation",
2039 yaz_log(LOG_LOG, "Got Close, reason %s, message %s",
2040 reasons[*req->closeReason], req->diagnosticInformation ?
2041 req->diagnosticInformation : "NULL");
2042 if (assoc->version < 3) /* to make do_force respond with close */
2044 do_close_req(assoc, Z_Close_finished,
2045 "Association terminated by client", reqb);
2048 void save_referenceId (request *reqb, Z_ReferenceId *refid)
2052 reqb->len_refid = refid->len;
2053 reqb->refid = (char *)nmem_malloc (reqb->request_mem, refid->len);
2054 memcpy (reqb->refid, refid->buf, refid->len);
2058 reqb->len_refid = 0;
2063 void bend_request_send (bend_association a, bend_request req, Z_APDU *res)
2065 process_z_response (a, req, res);
2068 bend_request bend_request_mk (bend_association a)
2070 request *nreq = request_get (&a->outgoing);
2071 nreq->request_mem = nmem_create ();
2075 Z_ReferenceId *bend_request_getid (ODR odr, bend_request req)
2080 id = (Odr_oct *)odr_malloc (odr, sizeof(*odr));
2081 id->buf = (unsigned char *)odr_malloc (odr, req->len_refid);
2082 id->len = id->size = req->len_refid;
2083 memcpy (id->buf, req->refid, req->len_refid);
2087 void bend_request_destroy (bend_request *req)
2089 nmem_destroy((*req)->request_mem);
2090 request_release(*req);
2094 int bend_backend_respond (bend_association a, bend_request req)
2098 r = process_z_request (a, req, &msg);
2100 yaz_log (LOG_WARN, "%s", msg);
2104 void bend_request_setdata(bend_request r, void *p)
2109 void *bend_request_getdata(bend_request r)
2111 return r->clientData;
2114 static Z_APDU *process_segmentRequest (association *assoc, request *reqb)
2116 bend_segment_rr req;
2118 req.segment = reqb->apdu_request->u.segmentRequest;
2119 req.stream = assoc->encode;
2120 req.decode = assoc->decode;
2121 req.print = assoc->print;
2122 req.association = assoc;
2124 (*assoc->init->bend_segment)(assoc->backend, &req);
2129 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd)
2131 bend_esrequest_rr esrequest;
2133 Z_ExtendedServicesRequest *req =
2134 reqb->apdu_request->u.extendedServicesRequest;
2135 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
2137 Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
2139 yaz_log(LOG_DEBUG,"inside Process esRequest");
2141 esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
2142 esrequest.stream = assoc->encode;
2143 esrequest.decode = assoc->decode;
2144 esrequest.print = assoc->print;
2145 esrequest.errcode = 0;
2146 esrequest.errstring = NULL;
2147 esrequest.request = reqb;
2148 esrequest.association = assoc;
2149 esrequest.taskPackage = 0;
2150 esrequest.referenceId = req->referenceId;
2152 (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
2154 /* If the response is being delayed, return NULL */
2155 if (esrequest.request == NULL)
2158 resp->referenceId = req->referenceId;
2160 if (esrequest.errcode == -1)
2162 /* Backend service indicates request will be processed */
2163 yaz_log(LOG_DEBUG,"Request could be processed...Accepted !");
2164 *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
2166 else if (esrequest.errcode == 0)
2168 /* Backend service indicates request will be processed */
2169 yaz_log(LOG_DEBUG,"Request could be processed...Done !");
2170 *resp->operationStatus = Z_ExtendedServicesResponse_done;
2174 Z_DiagRecs *diagRecs = diagrecs (assoc, esrequest.errcode,
2175 esrequest.errstring);
2177 /* Backend indicates error, request will not be processed */
2178 yaz_log(LOG_DEBUG,"Request could not be processed...failure !");
2179 *resp->operationStatus = Z_ExtendedServicesResponse_failure;
2180 resp->num_diagnostics = diagRecs->num_diagRecs;
2181 resp->diagnostics = diagRecs->diagRecs;
2183 /* Do something with the members of bend_extendedservice */
2184 if (esrequest.taskPackage)
2185 resp->taskPackage = z_ext_record (assoc->encode, VAL_EXTENDED,
2186 (const char *) esrequest.taskPackage,
2188 yaz_log(LOG_DEBUG,"Send the result apdu");