2 * Copyright (c) 1995-2003, Index Data
3 * See the file LICENSE for details.
5 * $Id: seshigh.c,v 1.147 2003-02-23 20:39:31 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 if (!assoc->init->bend_fetch)
513 (*assoc->init->bend_fetch)(assoc->backend, &rr);
517 record->recordData_buf = rr.record;
518 record->recordData_len = rr.len;
519 record->recordPosition = odr_intdup(o, pos);
520 record->recordSchema = 0;
521 if (srw_req->recordSchema)
522 record->recordSchema = odr_strdup(o, srw_req->recordSchema);
527 static void srw_bend_search(association *assoc, request *req,
528 Z_SRW_searchRetrieveRequest *srw_req,
529 Z_SRW_searchRetrieveResponse *srw_res)
535 yaz_log(LOG_LOG, "Got SRW SearchRetrieveRequest");
538 if (!srw_bend_init(assoc))
540 srw_error = 3; /* assume Authentication error */
542 srw_res->num_diagnostics = 1;
543 srw_res->diagnostics = (Z_SRW_diagnostic *)
544 odr_malloc(assoc->encode, sizeof(*srw_res->diagnostics));
545 srw_res->diagnostics[0].code =
546 odr_intdup(assoc->encode, srw_error);
547 srw_res->diagnostics[0].details = 0;
552 rr.setname = "default";
555 rr.basenames = &srw_req->database;
558 rr.query = (Z_Query *) odr_malloc (assoc->decode, sizeof(*rr.query));
560 if (srw_req->query_type == Z_SRW_query_type_cql)
562 ext = (Z_External *) odr_malloc(assoc->decode, sizeof(*ext));
563 ext->direct_reference = odr_getoidbystr(assoc->decode,
564 "1.2.840.10003.16.2");
565 ext->indirect_reference = 0;
567 ext->which = Z_External_CQL;
568 ext->u.cql = srw_req->query.cql;
570 rr.query->which = Z_Query_type_104;
571 rr.query->u.type_104 = ext;
573 else if (srw_req->query_type == Z_SRW_query_type_pqf)
575 Z_RPNQuery *RPNquery;
576 YAZ_PQF_Parser pqf_parser;
578 pqf_parser = yaz_pqf_create ();
580 RPNquery = yaz_pqf_parse (pqf_parser, assoc->decode,
586 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
587 yaz_log(LOG_LOG, "%*s^\n", off+4, "");
588 yaz_log(LOG_LOG, "Bad PQF: %s (code %d)\n", pqf_msg, code);
593 rr.query->which = Z_Query_type_1;
594 rr.query->u.type_1 = RPNquery;
596 yaz_pqf_destroy (pqf_parser);
601 if (!srw_error && srw_req->sort_type != Z_SRW_sort_type_none)
604 if (!srw_error && !assoc->init->bend_search)
609 srw_res->num_diagnostics = 1;
610 srw_res->diagnostics = (Z_SRW_diagnostic *)
611 odr_malloc(assoc->encode, sizeof(*srw_res->diagnostics));
612 srw_res->diagnostics[0].code =
613 odr_intdup(assoc->encode, srw_error);
614 srw_res->diagnostics[0].details = 0;
618 rr.stream = assoc->encode;
619 rr.decode = assoc->decode;
620 rr.print = assoc->print;
622 rr.association = assoc;
628 yaz_log_zquery(rr.query);
629 (assoc->init->bend_search)(assoc->backend, &rr);
630 srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
633 srw_res->num_diagnostics = 1;
634 srw_res->diagnostics = (Z_SRW_diagnostic *)
635 odr_malloc(assoc->encode, sizeof(*srw_res->diagnostics));
636 srw_res->diagnostics[0].code =
637 odr_intdup(assoc->encode,
638 yaz_diag_bib1_to_srw (rr.errcode));
639 srw_res->diagnostics[0].details = rr.errstring;
643 srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
644 if (srw_req->maximumRecords && *srw_req->maximumRecords > 0)
646 int number = *srw_req->maximumRecords;
649 if (srw_req->startRecord)
650 start = *srw_req->startRecord;
651 if (start <= rr.hits)
654 if (start + number > rr.hits)
655 number = rr.hits - start + 1;
656 srw_res->records = (Z_SRW_record *)
657 odr_malloc(assoc->encode,
658 number * sizeof(*srw_res->records));
659 for (i = 0; i<number; i++)
662 srw_res->records[j].recordData_buf = 0;
663 errcode = srw_bend_fetch(assoc, i+start, srw_req,
664 srw_res->records + j);
667 srw_res->num_diagnostics = 1;
668 srw_res->diagnostics = (Z_SRW_diagnostic *)
669 odr_malloc(assoc->encode,
670 sizeof(*srw_res->diagnostics));
671 srw_res->diagnostics[0].code =
672 odr_intdup(assoc->encode,
673 yaz_diag_bib1_to_srw (errcode));
674 srw_res->diagnostics[0].details = rr.errstring;
677 if (srw_res->records[j].recordData_buf)
680 srw_res->num_records = j;
682 srw_res->records = 0;
688 static void process_http_request(association *assoc, request *req)
690 Z_HTTP_Request *hreq = req->gdu_request->u.HTTP_Request;
691 ODR o = assoc->encode;
693 Z_HTTP_Response *hres = 0;
696 if (!strcmp(hreq->method, "GET"))
699 if (strlen(hreq->path) >= 5 && strlen(hreq->path) < 80 &&
700 !memcmp(hreq->path, "/doc/", 5))
705 strcpy(fpath, DOCDIR);
706 strcat(fpath, hreq->path+4);
707 f = fopen(fpath, "rb");
710 if (fstat(fileno(f), &sbuf) || !S_ISREG(sbuf.st_mode))
719 fseek(f, 0L, SEEK_END);
721 if (sz >= 0 && sz < 500000)
723 const char *ctype = "application/octet-stream";
726 p = z_get_HTTP_Response(o, 200);
727 hres = p->u.HTTP_Response;
728 hres->content_buf = (char *) odr_malloc(o, sz + 1);
729 hres->content_len = sz;
730 fseek(f, 0L, SEEK_SET);
731 fread(hres->content_buf, 1, sz, f);
732 if ((cp = strrchr(fpath, '.'))) {
734 if (!strcmp(cp, "png"))
736 else if (!strcmp(cp, "gif"))
738 else if (!strcmp(cp, "xml"))
740 else if (!strcmp(cp, "html"))
743 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
749 if (!strcmp(hreq->path, "/"))
754 const char *doclink = "";
755 p = z_get_HTTP_Response(o, 200);
756 hres = p->u.HTTP_Response;
757 hres->content_buf = (char *) odr_malloc(o, 400);
759 if (stat(DOCDIR "/yaz.html", &sbuf) == 0 && S_ISREG(sbuf.st_mode))
760 doclink = "<P><A HREF=\"/doc/yaz.html\">Documentation</A></P>";
762 sprintf (hres->content_buf,
763 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n"
766 " <TITLE>YAZ " YAZ_VERSION "</TITLE>\n"
769 " <P><A HREF=\"http://www.indexdata.dk/yaz/\">YAZ</A> "
773 "</HTML>\n", doclink);
774 hres->content_len = strlen(hres->content_buf);
775 z_HTTP_header_add(o, &hres->headers, "Content-Type", "text/html");
779 p = z_get_HTTP_Response(o, 404);
782 else if (!strcmp(hreq->method, "POST"))
784 const char *content_type = z_HTTP_header_lookup(hreq->headers,
786 const char *soap_action = z_HTTP_header_lookup(hreq->headers,
788 if (content_type && soap_action &&
789 !yaz_strcmp_del("text/xml", content_type, "; "))
791 Z_SOAP *soap_package = 0;
795 static Z_SOAP_Handler soap_handlers[2] = {
797 {"http://www.loc.gov/zing/srw/v1.0/", 0,
798 (Z_SOAP_fun) yaz_srw_codec},
802 ret = z_soap_codec(assoc->decode, &soap_package,
803 &hreq->content_buf, &hreq->content_len,
807 if (!ret && soap_package->which == Z_SOAP_generic &&
808 soap_package->u.generic->no == 0)
811 Z_SRW_PDU *sr = soap_package->u.generic->p;
813 if (sr->which == Z_SRW_searchRetrieve_request)
816 yaz_srw_get(assoc->encode,
817 Z_SRW_searchRetrieve_response);
819 if (!sr->u.request->database)
821 const char *p0 = hreq->path, *p1;
824 p1 = strchr(p0, '?');
826 p1 = p0 + strlen(p0);
829 sr->u.request->database =
830 odr_malloc(assoc->decode, p1 - p0 + 1);
831 memcpy (sr->u.request->database, p0, p1 - p0);
832 sr->u.request->database[p1 - p0] = '\0';
835 sr->u.request->database = "Default";
837 srw_bend_search(assoc, req, sr->u.request,
840 soap_package->u.generic->p = res;
845 p = z_get_HTTP_Response(o, 200);
846 hres = p->u.HTTP_Response;
847 ret = z_soap_codec(assoc->encode, &soap_package,
848 &hres->content_buf, &hres->content_len,
850 hres->code = http_code;
851 z_HTTP_header_add(o, &hres->headers, "Content-Type", "text/xml");
853 if (!p) /* still no response ? */
854 p = z_get_HTTP_Response(o, 500);
858 p = z_get_HTTP_Response(o, 405);
859 hres = p->u.HTTP_Response;
861 z_HTTP_header_add(o, &hres->headers, "Allow", "GET, POST");
863 hres = p->u.HTTP_Response;
864 if (!strcmp(hreq->version, "1.0"))
866 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
867 if (v && !strcmp(v, "Keep-Alive"))
871 hres->version = "1.0";
875 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
876 if (v && !strcmp(v, "close"))
880 hres->version = "1.1";
884 z_HTTP_header_add(o, &hres->headers, "Connection", "close");
885 assoc->state = ASSOC_DEAD;
890 const char *alive = z_HTTP_header_lookup(hreq->headers, "Keep-Alive");
892 if (alive && isdigit(*alive))
896 if (t < 0 || t > 3600)
898 iochan_settimeout(assoc->client_chan,t);
899 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
901 process_gdu_response(assoc, req, p);
904 static void process_gdu_request(association *assoc, request *req)
906 if (req->gdu_request->which == Z_GDU_Z3950)
909 req->apdu_request = req->gdu_request->u.z3950;
910 if (process_z_request(assoc, req, &msg) < 0)
911 do_close_req(assoc, Z_Close_systemProblem, msg, req);
913 else if (req->gdu_request->which == Z_GDU_HTTP_Request)
914 process_http_request(assoc, req);
917 do_close_req(assoc, Z_Close_systemProblem, "bad protocol packet", req);
922 * Initiate request processing.
924 static int process_z_request(association *assoc, request *req, char **msg)
930 *msg = "Unknown Error";
931 assert(req && req->state == REQUEST_IDLE);
932 if (req->apdu_request->which != Z_APDU_initRequest && !assoc->init)
934 *msg = "Missing InitRequest";
937 switch (req->apdu_request->which)
939 case Z_APDU_initRequest:
940 iochan_settimeout(assoc->client_chan,
941 statserv_getcontrol()->idle_timeout * 60);
942 res = process_initRequest(assoc, req); break;
943 case Z_APDU_searchRequest:
944 res = process_searchRequest(assoc, req, &fd); break;
945 case Z_APDU_presentRequest:
946 res = process_presentRequest(assoc, req, &fd); break;
947 case Z_APDU_scanRequest:
948 if (assoc->init->bend_scan)
949 res = process_scanRequest(assoc, req, &fd);
952 *msg = "Cannot handle Scan APDU";
956 case Z_APDU_extendedServicesRequest:
957 if (assoc->init->bend_esrequest)
958 res = process_ESRequest(assoc, req, &fd);
961 *msg = "Cannot handle Extended Services APDU";
965 case Z_APDU_sortRequest:
966 if (assoc->init->bend_sort)
967 res = process_sortRequest(assoc, req, &fd);
970 *msg = "Cannot handle Sort APDU";
975 process_close(assoc, req);
977 case Z_APDU_deleteResultSetRequest:
978 if (assoc->init->bend_delete)
979 res = process_deleteRequest(assoc, req, &fd);
982 *msg = "Cannot handle Delete APDU";
986 case Z_APDU_segmentRequest:
987 if (assoc->init->bend_segment)
989 res = process_segmentRequest (assoc, req);
993 *msg = "Cannot handle Segment APDU";
998 *msg = "Bad APDU received";
1003 yaz_log(LOG_DEBUG, " result immediately available");
1004 retval = process_z_response(assoc, req, res);
1008 yaz_log(LOG_DEBUG, " result unavailble");
1011 else /* no result yet - one will be provided later */
1015 /* Set up an I/O handler for the fd supplied by the backend */
1017 yaz_log(LOG_DEBUG, " establishing handler for result");
1018 req->state = REQUEST_PENDING;
1019 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT)))
1021 iochan_setdata(chan, assoc);
1028 * Handle message from the backend.
1030 void backend_response(IOCHAN i, int event)
1032 association *assoc = (association *)iochan_getdata(i);
1033 request *req = request_head(&assoc->incoming);
1037 yaz_log(LOG_DEBUG, "backend_response");
1038 assert(assoc && req && req->state != REQUEST_IDLE);
1039 /* determine what it is we're waiting for */
1040 switch (req->apdu_request->which)
1042 case Z_APDU_searchRequest:
1043 res = response_searchRequest(assoc, req, 0, &fd); break;
1045 case Z_APDU_presentRequest:
1046 res = response_presentRequest(assoc, req, 0, &fd); break;
1047 case Z_APDU_scanRequest:
1048 res = response_scanRequest(assoc, req, 0, &fd); break;
1051 yaz_log(LOG_WARN, "Serious programmer's lapse or bug");
1054 if ((res && process_z_response(assoc, req, res) < 0) || fd < 0)
1056 yaz_log(LOG_LOG, "Fatal error when talking to backend");
1057 do_close(assoc, Z_Close_systemProblem, 0);
1061 else if (!res) /* no result yet - try again later */
1063 yaz_log(LOG_DEBUG, " no result yet");
1064 iochan_setfd(i, fd); /* in case fd has changed */
1069 * Encode response, and transfer the request structure to the outgoing queue.
1071 static int process_gdu_response(association *assoc, request *req, Z_GDU *res)
1073 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
1075 if (assoc->print && !z_GDU(assoc->print, &res, 0, 0))
1077 yaz_log(LOG_WARN, "ODR print error: %s",
1078 odr_errmsg(odr_geterror(assoc->print)));
1079 odr_reset(assoc->print);
1081 if (!z_GDU(assoc->encode, &res, 0, 0))
1083 yaz_log(LOG_WARN, "ODR error when encoding response: %s",
1084 odr_errmsg(odr_geterror(assoc->decode)));
1087 req->response = odr_getbuf(assoc->encode, &req->len_response,
1088 &req->size_response);
1089 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
1090 odr_reset(assoc->encode);
1091 req->state = REQUEST_IDLE;
1092 request_enq(&assoc->outgoing, req);
1093 /* turn the work over to the ir_session handler */
1094 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
1095 assoc->cs_put_mask = EVENT_OUTPUT;
1096 /* Is there more work to be done? give that to the input handler too */
1098 if (request_head(&assoc->incoming))
1100 yaz_log (LOG_DEBUG, "more work to be done");
1101 iochan_setevent(assoc->client_chan, EVENT_WORK);
1108 * Encode response, and transfer the request structure to the outgoing queue.
1110 static int process_z_response(association *assoc, request *req, Z_APDU *res)
1112 Z_GDU *gres = (Z_GDU *) odr_malloc(assoc->encode, sizeof(*res));
1113 gres->which = Z_GDU_Z3950;
1114 gres->u.z3950 = res;
1116 return process_gdu_response(assoc, req, gres);
1121 * Handle init request.
1122 * At the moment, we don't check the options
1123 * anywhere else in the code - we just try not to do anything that would
1124 * break a naive client. We'll toss 'em into the association block when
1125 * we need them there.
1127 static Z_APDU *process_initRequest(association *assoc, request *reqb)
1129 statserv_options_block *cb = statserv_getcontrol();
1130 Z_InitRequest *req = reqb->apdu_request->u.initRequest;
1131 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
1132 Z_InitResponse *resp = apdu->u.initResponse;
1133 bend_initresult *binitres;
1137 yaz_log(LOG_LOG, "Got initRequest");
1138 if (req->implementationId)
1139 yaz_log(LOG_LOG, "Id: %s", req->implementationId);
1140 if (req->implementationName)
1141 yaz_log(LOG_LOG, "Name: %s", req->implementationName);
1142 if (req->implementationVersion)
1143 yaz_log(LOG_LOG, "Version: %s", req->implementationVersion);
1145 assoc_init_reset(assoc);
1147 assoc->init->auth = req->idAuthentication;
1148 assoc->init->referenceId = req->referenceId;
1150 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
1152 Z_CharSetandLanguageNegotiation *negotiation =
1153 yaz_get_charneg_record (req->otherInfo);
1154 if (negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
1155 assoc->init->charneg_request = negotiation;
1158 if (!(binitres = (*cb->bend_init)(assoc->init)))
1160 yaz_log(LOG_WARN, "Bad response from backend.");
1164 assoc->backend = binitres->handle;
1165 if ((assoc->init->bend_sort))
1166 yaz_log (LOG_DEBUG, "Sort handler installed");
1167 if ((assoc->init->bend_search))
1168 yaz_log (LOG_DEBUG, "Search handler installed");
1169 if ((assoc->init->bend_present))
1170 yaz_log (LOG_DEBUG, "Present handler installed");
1171 if ((assoc->init->bend_esrequest))
1172 yaz_log (LOG_DEBUG, "ESRequest handler installed");
1173 if ((assoc->init->bend_delete))
1174 yaz_log (LOG_DEBUG, "Delete handler installed");
1175 if ((assoc->init->bend_scan))
1176 yaz_log (LOG_DEBUG, "Scan handler installed");
1177 if ((assoc->init->bend_segment))
1178 yaz_log (LOG_DEBUG, "Segment handler installed");
1180 resp->referenceId = req->referenceId;
1182 /* let's tell the client what we can do */
1183 if (ODR_MASK_GET(req->options, Z_Options_search))
1185 ODR_MASK_SET(resp->options, Z_Options_search);
1186 strcat(options, "srch");
1188 if (ODR_MASK_GET(req->options, Z_Options_present))
1190 ODR_MASK_SET(resp->options, Z_Options_present);
1191 strcat(options, " prst");
1193 if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
1194 assoc->init->bend_delete)
1196 ODR_MASK_SET(resp->options, Z_Options_delSet);
1197 strcat(options, " del");
1199 if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
1200 assoc->init->bend_esrequest)
1202 ODR_MASK_SET(resp->options, Z_Options_extendedServices);
1203 strcat (options, " extendedServices");
1205 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
1207 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
1208 strcat(options, " namedresults");
1210 if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
1212 ODR_MASK_SET(resp->options, Z_Options_scan);
1213 strcat(options, " scan");
1215 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
1217 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
1218 strcat(options, " concurrop");
1220 if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
1222 ODR_MASK_SET(resp->options, Z_Options_sort);
1223 strcat(options, " sort");
1226 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel)
1227 && assoc->init->charneg_response)
1229 Z_OtherInformation **p;
1230 Z_OtherInformationUnit *p0;
1232 yaz_oi_APDU(apdu, &p);
1234 if ((p0=yaz_oi_update(p, assoc->encode, NULL, 0, 0))) {
1235 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
1237 p0->which = Z_OtherInfo_externallyDefinedInfo;
1238 p0->information.externallyDefinedInfo =
1239 assoc->init->charneg_response;
1241 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
1242 strcat(options, " negotiation");
1245 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
1247 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
1248 assoc->version = 2; /* 1 & 2 are equivalent */
1250 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
1252 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
1255 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
1257 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
1261 yaz_log(LOG_LOG, "Negotiated to v%d: %s", assoc->version, options);
1262 assoc->maximumRecordSize = *req->maximumRecordSize;
1263 if (assoc->maximumRecordSize > control_block->maxrecordsize)
1264 assoc->maximumRecordSize = control_block->maxrecordsize;
1265 assoc->preferredMessageSize = *req->preferredMessageSize;
1266 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
1267 assoc->preferredMessageSize = assoc->maximumRecordSize;
1269 resp->preferredMessageSize = &assoc->preferredMessageSize;
1270 resp->maximumRecordSize = &assoc->maximumRecordSize;
1272 resp->implementationName = "GFS/YAZ";
1274 if (assoc->init->implementation_id)
1277 odr_malloc (assoc->encode,
1278 strlen(assoc->init->implementation_id) + 10 +
1279 strlen(resp->implementationId));
1280 sprintf (nv, "%s / %s",
1281 resp->implementationId, assoc->init->implementation_id);
1282 resp->implementationId = nv;
1284 if (assoc->init->implementation_name)
1287 odr_malloc (assoc->encode,
1288 strlen(assoc->init->implementation_name) + 10 +
1289 strlen(resp->implementationName));
1290 sprintf (nv, "%s / %s",
1291 resp->implementationName, assoc->init->implementation_name);
1292 resp->implementationName = nv;
1294 if (assoc->init->implementation_version)
1297 odr_malloc (assoc->encode,
1298 strlen(assoc->init->implementation_version) + 10 +
1299 strlen(resp->implementationVersion));
1300 sprintf (nv, "YAZ %s / %s",
1301 resp->implementationVersion,
1302 assoc->init->implementation_version);
1303 resp->implementationVersion = nv;
1306 if (binitres->errcode)
1308 yaz_log(LOG_LOG, "Connection rejected by backend.");
1310 assoc->state = ASSOC_DEAD;
1313 assoc->state = ASSOC_UP;
1318 * These functions should be merged.
1321 static void set_addinfo (Z_DefaultDiagFormat *dr, char *addinfo, ODR odr)
1323 dr->which = Z_DefaultDiagFormat_v2Addinfo;
1324 dr->u.v2Addinfo = odr_strdup (odr, addinfo ? addinfo : "");
1328 * nonsurrogate diagnostic record.
1330 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
1332 Z_Records *rec = (Z_Records *)
1333 odr_malloc (assoc->encode, sizeof(*rec));
1334 int *err = odr_intdup(assoc->encode, error);
1335 Z_DiagRec *drec = (Z_DiagRec *)
1336 odr_malloc (assoc->encode, sizeof(*drec));
1337 Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
1338 odr_malloc (assoc->encode, sizeof(*dr));
1340 yaz_log(LOG_LOG, "[%d] %s %s%s", error, diagbib1_str(error),
1341 addinfo ? " -- " : "", addinfo ? addinfo : "");
1342 rec->which = Z_Records_NSD;
1343 rec->u.nonSurrogateDiagnostic = dr;
1344 dr->diagnosticSetId =
1345 yaz_oidval_to_z3950oid (assoc->encode, CLASS_DIAGSET, VAL_BIB1);
1346 dr->condition = err;
1347 set_addinfo (dr, addinfo, assoc->encode);
1352 * surrogate diagnostic.
1354 static Z_NamePlusRecord *surrogatediagrec(association *assoc, char *dbname,
1355 int error, char *addinfo)
1357 Z_NamePlusRecord *rec = (Z_NamePlusRecord *)
1358 odr_malloc (assoc->encode, sizeof(*rec));
1359 int *err = odr_intdup(assoc->encode, error);
1360 Z_DiagRec *drec = (Z_DiagRec *)odr_malloc (assoc->encode, sizeof(*drec));
1361 Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
1362 odr_malloc (assoc->encode, sizeof(*dr));
1364 yaz_log(LOG_DEBUG, "SurrogateDiagnotic: %d -- %s", error, addinfo);
1365 rec->databaseName = dbname;
1366 rec->which = Z_NamePlusRecord_surrogateDiagnostic;
1367 rec->u.surrogateDiagnostic = drec;
1368 drec->which = Z_DiagRec_defaultFormat;
1369 drec->u.defaultFormat = dr;
1370 dr->diagnosticSetId =
1371 yaz_oidval_to_z3950oid (assoc->encode, CLASS_DIAGSET, VAL_BIB1);
1372 dr->condition = err;
1373 set_addinfo (dr, addinfo, assoc->encode);
1379 * multiple nonsurrogate diagnostics.
1381 static Z_DiagRecs *diagrecs(association *assoc, int error, char *addinfo)
1383 Z_DiagRecs *recs = (Z_DiagRecs *)odr_malloc (assoc->encode, sizeof(*recs));
1384 int *err = odr_intdup(assoc->encode, error);
1385 Z_DiagRec **recp = (Z_DiagRec **)odr_malloc (assoc->encode, sizeof(*recp));
1386 Z_DiagRec *drec = (Z_DiagRec *)odr_malloc (assoc->encode, sizeof(*drec));
1387 Z_DefaultDiagFormat *rec = (Z_DefaultDiagFormat *)
1388 odr_malloc (assoc->encode, sizeof(*rec));
1390 yaz_log(LOG_DEBUG, "DiagRecs: %d -- %s", error, addinfo ? addinfo : "");
1392 recs->num_diagRecs = 1;
1393 recs->diagRecs = recp;
1395 drec->which = Z_DiagRec_defaultFormat;
1396 drec->u.defaultFormat = rec;
1398 rec->diagnosticSetId =
1399 yaz_oidval_to_z3950oid (assoc->encode, CLASS_DIAGSET, VAL_BIB1);
1400 rec->condition = err;
1402 rec->which = Z_DefaultDiagFormat_v2Addinfo;
1403 rec->u.v2Addinfo = odr_strdup (assoc->encode, addinfo ? addinfo : "");
1407 static Z_Records *pack_records(association *a, char *setname, int start,
1408 int *num, Z_RecordComposition *comp,
1409 int *next, int *pres, oid_value format,
1410 Z_ReferenceId *referenceId,
1413 int recno, total_length = 0, toget = *num, dumped_records = 0;
1414 Z_Records *records =
1415 (Z_Records *) odr_malloc (a->encode, sizeof(*records));
1416 Z_NamePlusRecordList *reclist =
1417 (Z_NamePlusRecordList *) odr_malloc (a->encode, sizeof(*reclist));
1418 Z_NamePlusRecord **list =
1419 (Z_NamePlusRecord **) odr_malloc (a->encode, sizeof(*list) * toget);
1421 records->which = Z_Records_DBOSD;
1422 records->u.databaseOrSurDiagnostics = reclist;
1423 reclist->num_records = 0;
1424 reclist->records = list;
1425 *pres = Z_PRES_SUCCESS;
1429 yaz_log(LOG_LOG, "Request to pack %d+%d+%s", start, toget, setname);
1430 yaz_log(LOG_DEBUG, "pms=%d, mrs=%d", a->preferredMessageSize,
1431 a->maximumRecordSize);
1432 for (recno = start; reclist->num_records < toget; recno++)
1435 Z_NamePlusRecord *thisrec;
1436 int this_length = 0;
1438 * we get the number of bytes allocated on the stream before any
1439 * allocation done by the backend - this should give us a reasonable
1440 * idea of the total size of the data so far.
1442 total_length = odr_total(a->encode) - dumped_records;
1448 freq.last_in_set = 0;
1449 freq.setname = setname;
1450 freq.surrogate_flag = 0;
1451 freq.number = recno;
1453 freq.request_format = format;
1454 freq.request_format_raw = oid;
1455 freq.output_format = format;
1456 freq.output_format_raw = 0;
1457 freq.stream = a->encode;
1458 freq.print = a->print;
1459 freq.surrogate_flag = 0;
1460 freq.referenceId = referenceId;
1461 (*a->init->bend_fetch)(a->backend, &freq);
1462 /* backend should be able to signal whether error is system-wide
1463 or only pertaining to current record */
1466 if (!freq.surrogate_flag)
1469 *pres = Z_PRES_FAILURE;
1470 /* for 'present request out of range',
1471 set addinfo to record position if not set */
1472 if (freq.errcode == 13 && freq.errstring == 0)
1474 sprintf (s, "%d", recno);
1477 return diagrec(a, freq.errcode, freq.errstring);
1479 reclist->records[reclist->num_records] =
1480 surrogatediagrec(a, freq.basename, freq.errcode,
1482 reclist->num_records++;
1483 *next = freq.last_in_set ? 0 : recno + 1;
1487 this_length = freq.len;
1489 this_length = odr_total(a->encode) - total_length;
1490 yaz_log(LOG_DEBUG, " fetched record, len=%d, total=%d",
1491 this_length, total_length);
1492 if (this_length + total_length > a->preferredMessageSize)
1494 /* record is small enough, really */
1495 if (this_length <= a->preferredMessageSize)
1497 yaz_log(LOG_DEBUG, " Dropped last normal-sized record");
1498 *pres = Z_PRES_PARTIAL_2;
1501 /* record can only be fetched by itself */
1502 if (this_length < a->maximumRecordSize)
1504 yaz_log(LOG_DEBUG, " Record > prefmsgsz");
1507 yaz_log(LOG_DEBUG, " Dropped it");
1508 reclist->records[reclist->num_records] =
1509 surrogatediagrec(a, freq.basename, 16, 0);
1510 reclist->num_records++;
1511 *next = freq.last_in_set ? 0 : recno + 1;
1512 dumped_records += this_length;
1516 else /* too big entirely */
1518 yaz_log(LOG_LOG, "Record > maxrcdsz this=%d max=%d", this_length, a->maximumRecordSize);
1519 reclist->records[reclist->num_records] =
1520 surrogatediagrec(a, freq.basename, 17, 0);
1521 reclist->num_records++;
1522 *next = freq.last_in_set ? 0 : recno + 1;
1523 dumped_records += this_length;
1528 if (!(thisrec = (Z_NamePlusRecord *)
1529 odr_malloc(a->encode, sizeof(*thisrec))))
1531 if (!(thisrec->databaseName = (char *)odr_malloc(a->encode,
1532 strlen(freq.basename) + 1)))
1534 strcpy(thisrec->databaseName, freq.basename);
1535 thisrec->which = Z_NamePlusRecord_databaseRecord;
1537 if (freq.output_format_raw)
1539 struct oident *ident = oid_getentbyoid(freq.output_format_raw);
1540 freq.output_format = ident->value;
1542 thisrec->u.databaseRecord = z_ext_record(a->encode, freq.output_format,
1543 freq.record, freq.len);
1544 if (!thisrec->u.databaseRecord)
1546 reclist->records[reclist->num_records] = thisrec;
1547 reclist->num_records++;
1548 *next = freq.last_in_set ? 0 : recno + 1;
1550 *num = reclist->num_records;
1554 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
1557 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
1558 bend_search_rr *bsrr =
1559 (bend_search_rr *)nmem_malloc (reqb->request_mem, sizeof(*bsrr));
1561 yaz_log(LOG_LOG, "Got SearchRequest.");
1563 bsrr->request = reqb;
1564 bsrr->association = assoc;
1565 bsrr->referenceId = req->referenceId;
1566 save_referenceId (reqb, bsrr->referenceId);
1568 yaz_log (LOG_LOG, "ResultSet '%s'", req->resultSetName);
1569 if (req->databaseNames)
1572 for (i = 0; i < req->num_databaseNames; i++)
1573 yaz_log (LOG_LOG, "Database '%s'", req->databaseNames[i]);
1575 yaz_log_zquery(req->query);
1577 if (assoc->init->bend_search)
1579 bsrr->setname = req->resultSetName;
1580 bsrr->replace_set = *req->replaceIndicator;
1581 bsrr->num_bases = req->num_databaseNames;
1582 bsrr->basenames = req->databaseNames;
1583 bsrr->query = req->query;
1584 bsrr->stream = assoc->encode;
1585 bsrr->decode = assoc->decode;
1586 bsrr->print = assoc->print;
1589 bsrr->errstring = NULL;
1590 bsrr->search_info = NULL;
1591 (assoc->init->bend_search)(assoc->backend, bsrr);
1595 return response_searchRequest(assoc, reqb, bsrr, fd);
1598 int bend_searchresponse(void *handle, bend_search_rr *bsrr) {return 0;}
1601 * Prepare a searchresponse based on the backend results. We probably want
1602 * to look at making the fetching of records nonblocking as well, but
1603 * so far, we'll keep things simple.
1604 * If bsrt is null, that means we're called in response to a communications
1605 * event, and we'll have to get the response for ourselves.
1607 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
1608 bend_search_rr *bsrt, int *fd)
1610 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
1611 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1612 Z_SearchResponse *resp = (Z_SearchResponse *)
1613 odr_malloc (assoc->encode, sizeof(*resp));
1614 int *nulint = odr_intdup (assoc->encode, 0);
1615 bool_t *sr = odr_intdup(assoc->encode, 1);
1616 int *next = odr_intdup(assoc->encode, 0);
1617 int *none = odr_intdup(assoc->encode, Z_RES_NONE);
1619 apdu->which = Z_APDU_searchResponse;
1620 apdu->u.searchResponse = resp;
1621 resp->referenceId = req->referenceId;
1622 resp->additionalSearchInfo = 0;
1623 resp->otherInfo = 0;
1625 if (!bsrt && !bend_searchresponse(assoc->backend, bsrt))
1627 yaz_log(LOG_FATAL, "Bad result from backend");
1630 else if (bsrt->errcode)
1632 resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
1633 resp->resultCount = nulint;
1634 resp->numberOfRecordsReturned = nulint;
1635 resp->nextResultSetPosition = nulint;
1636 resp->searchStatus = nulint;
1637 resp->resultSetStatus = none;
1638 resp->presentStatus = 0;
1642 int *toget = odr_intdup(assoc->encode, 0);
1643 int *presst = odr_intdup(assoc->encode, 0);
1644 Z_RecordComposition comp, *compp = 0;
1646 yaz_log (LOG_LOG, "resultCount: %d", bsrt->hits);
1649 resp->resultCount = &bsrt->hits;
1651 comp.which = Z_RecordComp_simple;
1652 /* how many records does the user agent want, then? */
1653 if (bsrt->hits <= *req->smallSetUpperBound)
1655 *toget = bsrt->hits;
1656 if ((comp.u.simple = req->smallSetElementSetNames))
1659 else if (bsrt->hits < *req->largeSetLowerBound)
1661 *toget = *req->mediumSetPresentNumber;
1662 if (*toget > bsrt->hits)
1663 *toget = bsrt->hits;
1664 if ((comp.u.simple = req->mediumSetElementSetNames))
1670 if (*toget && !resp->records)
1675 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
1678 form = prefformat->value;
1679 resp->records = pack_records(assoc, req->resultSetName, 1,
1680 toget, compp, next, presst, form, req->referenceId,
1681 req->preferredRecordSyntax);
1684 resp->numberOfRecordsReturned = toget;
1685 resp->nextResultSetPosition = next;
1686 resp->searchStatus = sr;
1687 resp->resultSetStatus = 0;
1688 resp->presentStatus = presst;
1692 if (*resp->resultCount)
1694 resp->numberOfRecordsReturned = nulint;
1695 resp->nextResultSetPosition = next;
1696 resp->searchStatus = sr;
1697 resp->resultSetStatus = 0;
1698 resp->presentStatus = 0;
1701 resp->additionalSearchInfo = bsrt->search_info;
1706 * Maybe we got a little over-friendly when we designed bend_fetch to
1707 * get only one record at a time. Some backends can optimise multiple-record
1708 * fetches, and at any rate, there is some overhead involved in
1709 * all that selecting and hopping around. Problem is, of course, that the
1710 * frontend can't know ahead of time how many records it'll need to
1711 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
1712 * is downright lousy as a bulk data transfer protocol.
1714 * To start with, we'll do the fetching of records from the backend
1715 * in one operation: To save some trips in and out of the event-handler,
1716 * and to simplify the interface to pack_records. At any rate, asynch
1717 * operation is more fun in operations that have an unpredictable execution
1718 * speed - which is normally more true for search than for present.
1720 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
1723 Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
1727 Z_PresentResponse *resp;
1731 yaz_log(LOG_LOG, "Got PresentRequest.");
1733 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
1736 form = prefformat->value;
1737 resp = (Z_PresentResponse *)odr_malloc (assoc->encode, sizeof(*resp));
1739 resp->presentStatus = odr_intdup(assoc->encode, 0);
1740 if (assoc->init->bend_present)
1742 bend_present_rr *bprr = (bend_present_rr *)
1743 nmem_malloc (reqb->request_mem, sizeof(*bprr));
1744 bprr->setname = req->resultSetId;
1745 bprr->start = *req->resultSetStartPoint;
1746 bprr->number = *req->numberOfRecordsRequested;
1747 bprr->format = form;
1748 bprr->comp = req->recordComposition;
1749 bprr->referenceId = req->referenceId;
1750 bprr->stream = assoc->encode;
1751 bprr->print = assoc->print;
1752 bprr->request = reqb;
1753 bprr->association = assoc;
1755 bprr->errstring = NULL;
1756 (*assoc->init->bend_present)(assoc->backend, bprr);
1762 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
1763 *resp->presentStatus = Z_PRES_FAILURE;
1766 apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1767 next = odr_intdup(assoc->encode, 0);
1768 num = odr_intdup(assoc->encode, 0);
1770 apdu->which = Z_APDU_presentResponse;
1771 apdu->u.presentResponse = resp;
1772 resp->referenceId = req->referenceId;
1773 resp->otherInfo = 0;
1777 *num = *req->numberOfRecordsRequested;
1779 pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
1780 num, req->recordComposition, next, resp->presentStatus,
1781 form, req->referenceId, req->preferredRecordSyntax);
1785 resp->numberOfRecordsReturned = num;
1786 resp->nextResultSetPosition = next;
1792 * Scan was implemented rather in a hurry, and with support for only the basic
1793 * elements of the service in the backend API. Suggestions are welcome.
1795 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
1797 Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
1798 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1799 Z_ScanResponse *res = (Z_ScanResponse *)
1800 odr_malloc (assoc->encode, sizeof(*res));
1801 int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
1802 int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
1803 Z_ListEntries *ents = (Z_ListEntries *)
1804 odr_malloc (assoc->encode, sizeof(*ents));
1805 Z_DiagRecs *diagrecs_p = NULL;
1807 bend_scan_rr *bsrr = (bend_scan_rr *)
1808 odr_malloc (assoc->encode, sizeof(*bsrr));
1810 yaz_log(LOG_LOG, "Got ScanRequest");
1812 apdu->which = Z_APDU_scanResponse;
1813 apdu->u.scanResponse = res;
1814 res->referenceId = req->referenceId;
1816 /* if step is absent, set it to 0 */
1817 res->stepSize = odr_intdup(assoc->encode, 0);
1819 *res->stepSize = *req->stepSize;
1821 res->scanStatus = scanStatus;
1822 res->numberOfEntriesReturned = numberOfEntriesReturned;
1823 res->positionOfTerm = 0;
1824 res->entries = ents;
1825 ents->num_entries = 0;
1826 ents->entries = NULL;
1827 ents->num_nonsurrogateDiagnostics = 0;
1828 ents->nonsurrogateDiagnostics = NULL;
1829 res->attributeSet = 0;
1832 if (req->databaseNames)
1835 for (i = 0; i < req->num_databaseNames; i++)
1836 yaz_log (LOG_LOG, "Database '%s'", req->databaseNames[i]);
1838 bsrr->num_bases = req->num_databaseNames;
1839 bsrr->basenames = req->databaseNames;
1840 bsrr->num_entries = *req->numberOfTermsRequested;
1841 bsrr->term = req->termListAndStartPoint;
1842 bsrr->referenceId = req->referenceId;
1843 bsrr->stream = assoc->encode;
1844 bsrr->print = assoc->print;
1845 bsrr->step_size = res->stepSize;
1846 if (req->attributeSet &&
1847 (attset = oid_getentbyoid(req->attributeSet)) &&
1848 (attset->oclass == CLASS_ATTSET || attset->oclass == CLASS_GENERAL))
1849 bsrr->attributeset = attset->value;
1851 bsrr->attributeset = VAL_NONE;
1852 log_scan_term (req->termListAndStartPoint, bsrr->attributeset);
1853 bsrr->term_position = req->preferredPositionInResponse ?
1854 *req->preferredPositionInResponse : 1;
1855 ((int (*)(void *, bend_scan_rr *))
1856 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1858 diagrecs_p = diagrecs(assoc, bsrr->errcode, bsrr->errstring);
1862 Z_Entry **tab = (Z_Entry **)
1863 odr_malloc (assoc->encode, sizeof(*tab) * bsrr->num_entries);
1865 if (bsrr->status == BEND_SCAN_PARTIAL)
1866 *scanStatus = Z_Scan_partial_5;
1868 *scanStatus = Z_Scan_success;
1869 ents->entries = tab;
1870 ents->num_entries = bsrr->num_entries;
1871 res->numberOfEntriesReturned = &ents->num_entries;
1872 res->positionOfTerm = &bsrr->term_position;
1873 for (i = 0; i < bsrr->num_entries; i++)
1879 tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
1880 if (bsrr->entries[i].occurrences >= 0)
1882 e->which = Z_Entry_termInfo;
1883 e->u.termInfo = t = (Z_TermInfo *)
1884 odr_malloc(assoc->encode, sizeof(*t));
1885 t->suggestedAttributes = 0;
1887 t->alternativeTerm = 0;
1888 t->byAttributes = 0;
1889 t->otherTermInfo = 0;
1890 t->globalOccurrences = &bsrr->entries[i].occurrences;
1891 t->term = (Z_Term *)
1892 odr_malloc(assoc->encode, sizeof(*t->term));
1893 t->term->which = Z_Term_general;
1894 t->term->u.general = o =
1895 (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
1896 o->buf = (unsigned char *)
1897 odr_malloc(assoc->encode, o->len = o->size =
1898 strlen(bsrr->entries[i].term));
1899 memcpy(o->buf, bsrr->entries[i].term, o->len);
1900 yaz_log(LOG_DEBUG, " term #%d: '%s' (%d)", i,
1901 bsrr->entries[i].term, bsrr->entries[i].occurrences);
1905 Z_DiagRecs *drecs = diagrecs (assoc,
1906 bsrr->entries[i].errcode,
1907 bsrr->entries[i].errstring);
1908 assert (drecs->num_diagRecs == 1);
1909 e->which = Z_Entry_surrogateDiagnostic;
1910 assert (drecs->diagRecs[0]);
1911 e->u.surrogateDiagnostic = drecs->diagRecs[0];
1917 ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
1918 ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
1923 static Z_APDU *process_sortRequest(association *assoc, request *reqb,
1926 Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
1927 Z_SortResponse *res = (Z_SortResponse *)
1928 odr_malloc (assoc->encode, sizeof(*res));
1929 bend_sort_rr *bsrr = (bend_sort_rr *)
1930 odr_malloc (assoc->encode, sizeof(*bsrr));
1932 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1934 yaz_log(LOG_LOG, "Got SortRequest.");
1936 bsrr->num_input_setnames = req->num_inputResultSetNames;
1937 bsrr->input_setnames = req->inputResultSetNames;
1938 bsrr->referenceId = req->referenceId;
1939 bsrr->output_setname = req->sortedResultSetName;
1940 bsrr->sort_sequence = req->sortSequence;
1941 bsrr->stream = assoc->encode;
1942 bsrr->print = assoc->print;
1944 bsrr->sort_status = Z_SortStatus_failure;
1946 bsrr->errstring = 0;
1948 (*assoc->init->bend_sort)(assoc->backend, bsrr);
1950 res->referenceId = bsrr->referenceId;
1951 res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
1952 res->resultSetStatus = 0;
1955 Z_DiagRecs *dr = diagrecs (assoc, bsrr->errcode, bsrr->errstring);
1956 res->diagnostics = dr->diagRecs;
1957 res->num_diagnostics = dr->num_diagRecs;
1961 res->num_diagnostics = 0;
1962 res->diagnostics = 0;
1966 apdu->which = Z_APDU_sortResponse;
1967 apdu->u.sortResponse = res;
1971 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
1974 Z_DeleteResultSetRequest *req =
1975 reqb->apdu_request->u.deleteResultSetRequest;
1976 Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
1977 odr_malloc (assoc->encode, sizeof(*res));
1978 bend_delete_rr *bdrr = (bend_delete_rr *)
1979 odr_malloc (assoc->encode, sizeof(*bdrr));
1980 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1982 yaz_log(LOG_LOG, "Got DeleteRequest.");
1984 bdrr->num_setnames = req->num_resultSetList;
1985 bdrr->setnames = req->resultSetList;
1986 bdrr->stream = assoc->encode;
1987 bdrr->print = assoc->print;
1988 bdrr->function = *req->deleteFunction;
1989 bdrr->referenceId = req->referenceId;
1991 if (bdrr->num_setnames > 0)
1994 bdrr->statuses = (int*)
1995 odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
1996 bdrr->num_setnames);
1997 for (i = 0; i < bdrr->num_setnames; i++)
1998 bdrr->statuses[i] = 0;
2000 (*assoc->init->bend_delete)(assoc->backend, bdrr);
2002 res->referenceId = req->referenceId;
2004 res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
2006 res->deleteListStatuses = 0;
2007 if (bdrr->num_setnames > 0)
2010 res->deleteListStatuses = (Z_ListStatuses *)
2011 odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
2012 res->deleteListStatuses->num = bdrr->num_setnames;
2013 res->deleteListStatuses->elements =
2015 odr_malloc (assoc->encode,
2016 sizeof(*res->deleteListStatuses->elements) *
2017 bdrr->num_setnames);
2018 for (i = 0; i<bdrr->num_setnames; i++)
2020 res->deleteListStatuses->elements[i] =
2022 odr_malloc (assoc->encode,
2023 sizeof(**res->deleteListStatuses->elements));
2024 res->deleteListStatuses->elements[i]->status = bdrr->statuses+i;
2025 res->deleteListStatuses->elements[i]->id =
2026 odr_strdup (assoc->encode, bdrr->setnames[i]);
2030 res->numberNotDeleted = 0;
2031 res->bulkStatuses = 0;
2032 res->deleteMessage = 0;
2035 apdu->which = Z_APDU_deleteResultSetResponse;
2036 apdu->u.deleteResultSetResponse = res;
2040 static void process_close(association *assoc, request *reqb)
2042 Z_Close *req = reqb->apdu_request->u.close;
2043 static char *reasons[] =
2050 "securityViolation",
2057 yaz_log(LOG_LOG, "Got Close, reason %s, message %s",
2058 reasons[*req->closeReason], req->diagnosticInformation ?
2059 req->diagnosticInformation : "NULL");
2060 if (assoc->version < 3) /* to make do_force respond with close */
2062 do_close_req(assoc, Z_Close_finished,
2063 "Association terminated by client", reqb);
2066 void save_referenceId (request *reqb, Z_ReferenceId *refid)
2070 reqb->len_refid = refid->len;
2071 reqb->refid = (char *)nmem_malloc (reqb->request_mem, refid->len);
2072 memcpy (reqb->refid, refid->buf, refid->len);
2076 reqb->len_refid = 0;
2081 void bend_request_send (bend_association a, bend_request req, Z_APDU *res)
2083 process_z_response (a, req, res);
2086 bend_request bend_request_mk (bend_association a)
2088 request *nreq = request_get (&a->outgoing);
2089 nreq->request_mem = nmem_create ();
2093 Z_ReferenceId *bend_request_getid (ODR odr, bend_request req)
2098 id = (Odr_oct *)odr_malloc (odr, sizeof(*odr));
2099 id->buf = (unsigned char *)odr_malloc (odr, req->len_refid);
2100 id->len = id->size = req->len_refid;
2101 memcpy (id->buf, req->refid, req->len_refid);
2105 void bend_request_destroy (bend_request *req)
2107 nmem_destroy((*req)->request_mem);
2108 request_release(*req);
2112 int bend_backend_respond (bend_association a, bend_request req)
2116 r = process_z_request (a, req, &msg);
2118 yaz_log (LOG_WARN, "%s", msg);
2122 void bend_request_setdata(bend_request r, void *p)
2127 void *bend_request_getdata(bend_request r)
2129 return r->clientData;
2132 static Z_APDU *process_segmentRequest (association *assoc, request *reqb)
2134 bend_segment_rr req;
2136 req.segment = reqb->apdu_request->u.segmentRequest;
2137 req.stream = assoc->encode;
2138 req.decode = assoc->decode;
2139 req.print = assoc->print;
2140 req.association = assoc;
2142 (*assoc->init->bend_segment)(assoc->backend, &req);
2147 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd)
2149 bend_esrequest_rr esrequest;
2151 Z_ExtendedServicesRequest *req =
2152 reqb->apdu_request->u.extendedServicesRequest;
2153 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
2155 Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
2157 yaz_log(LOG_DEBUG,"inside Process esRequest");
2159 esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
2160 esrequest.stream = assoc->encode;
2161 esrequest.decode = assoc->decode;
2162 esrequest.print = assoc->print;
2163 esrequest.errcode = 0;
2164 esrequest.errstring = NULL;
2165 esrequest.request = reqb;
2166 esrequest.association = assoc;
2167 esrequest.taskPackage = 0;
2168 esrequest.referenceId = req->referenceId;
2170 (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
2172 /* If the response is being delayed, return NULL */
2173 if (esrequest.request == NULL)
2176 resp->referenceId = req->referenceId;
2178 if (esrequest.errcode == -1)
2180 /* Backend service indicates request will be processed */
2181 yaz_log(LOG_DEBUG,"Request could be processed...Accepted !");
2182 *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
2184 else if (esrequest.errcode == 0)
2186 /* Backend service indicates request will be processed */
2187 yaz_log(LOG_DEBUG,"Request could be processed...Done !");
2188 *resp->operationStatus = Z_ExtendedServicesResponse_done;
2192 Z_DiagRecs *diagRecs = diagrecs (assoc, esrequest.errcode,
2193 esrequest.errstring);
2195 /* Backend indicates error, request will not be processed */
2196 yaz_log(LOG_DEBUG,"Request could not be processed...failure !");
2197 *resp->operationStatus = Z_ExtendedServicesResponse_failure;
2198 resp->num_diagnostics = diagRecs->num_diagRecs;
2199 resp->diagnostics = diagRecs->diagRecs;
2201 /* Do something with the members of bend_extendedservice */
2202 if (esrequest.taskPackage)
2203 resp->taskPackage = z_ext_record (assoc->encode, VAL_EXTENDED,
2204 (const char *) esrequest.taskPackage,
2206 yaz_log(LOG_DEBUG,"Send the result apdu");