2 * Copyright (c) 1995-2003, Index Data
3 * See the file LICENSE for details.
5 * $Id: seshigh.c,v 1.144 2003-02-20 15:15:04 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)
43 #include <yaz/yconfig.h>
44 #include <yaz/xmalloc.h>
45 #include <yaz/comstack.h>
48 #include <yaz/proto.h>
51 #include <yaz/logrpn.h>
52 #include <yaz/statserv.h>
53 #include <yaz/diagbib1.h>
54 #include <yaz/charneg.h>
55 #include <yaz/otherinfo.h>
56 #include <yaz/yaz-util.h>
57 #include <yaz/pquery.h>
60 #include <yaz/backend.h>
62 static void process_gdu_request(association *assoc, request *req);
63 static int process_z_request(association *assoc, request *req, char **msg);
64 void backend_response(IOCHAN i, int event);
65 static int process_gdu_response(association *assoc, request *req, Z_GDU *res);
66 static int process_z_response(association *assoc, request *req, Z_APDU *res);
67 static Z_APDU *process_initRequest(association *assoc, request *reqb);
68 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
70 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
71 bend_search_rr *bsrr, int *fd);
72 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
74 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
75 static Z_APDU *process_sortRequest(association *assoc, request *reqb, int *fd);
76 static void process_close(association *assoc, request *reqb);
77 void save_referenceId (request *reqb, Z_ReferenceId *refid);
78 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
80 static Z_APDU *process_segmentRequest (association *assoc, request *reqb);
82 static FILE *apduf = 0; /* for use in static mode */
83 static statserv_options_block *control_block = 0;
85 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd);
88 * Create and initialize a new association-handle.
89 * channel : iochannel for the current line.
90 * link : communications channel.
91 * Returns: 0 or a new association handle.
93 association *create_association(IOCHAN channel, COMSTACK link)
98 control_block = statserv_getcontrol();
99 if (!(anew = (association *)xmalloc(sizeof(*anew))))
102 anew->client_chan = channel;
103 anew->client_link = link;
104 anew->cs_get_mask = 0;
105 anew->cs_put_mask = 0;
106 anew->cs_accept_mask = 0;
107 if (!(anew->decode = odr_createmem(ODR_DECODE)) ||
108 !(anew->encode = odr_createmem(ODR_ENCODE)))
110 if (*control_block->apdufile)
115 strcpy(filename, control_block->apdufile);
116 if (!(anew->print = odr_createmem(ODR_PRINT)))
118 if (*control_block->apdufile == '@')
120 odr_setprint(anew->print, yaz_log_file());
122 else if (*control_block->apdufile != '-')
124 strcpy(filename, control_block->apdufile);
125 if (!control_block->dynamic)
129 if (!(apduf = fopen(filename, "w")))
131 yaz_log(LOG_WARN|LOG_ERRNO, "%s", filename);
134 setvbuf(apduf, 0, _IONBF, 0);
140 sprintf(filename + strlen(filename), ".%d", getpid());
141 if (!(f = fopen(filename, "w")))
143 yaz_log(LOG_WARN|LOG_ERRNO, "%s", filename);
146 setvbuf(f, 0, _IONBF, 0);
148 odr_setprint(anew->print, f);
153 anew->input_buffer = 0;
154 anew->input_buffer_len = 0;
156 anew->state = ASSOC_NEW;
157 request_initq(&anew->incoming);
158 request_initq(&anew->outgoing);
159 anew->proto = cs_getproto(link);
164 * Free association and release resources.
166 void destroy_association(association *h)
168 statserv_options_block *cb = statserv_getcontrol();
171 odr_destroy(h->decode);
172 odr_destroy(h->encode);
174 odr_destroy(h->print);
176 xfree(h->input_buffer);
178 (*cb->bend_close)(h->backend);
179 while (request_deq(&h->incoming));
180 while (request_deq(&h->outgoing));
181 request_delq(&h->incoming);
182 request_delq(&h->outgoing);
184 xmalloc_trav("session closed");
185 if (control_block && control_block->one_shot)
191 static void do_close_req(association *a, int reason, char *message,
195 Z_Close *cls = zget_Close(a->encode);
197 /* Purge request queue */
198 while (request_deq(&a->incoming));
199 while (request_deq(&a->outgoing));
202 yaz_log(LOG_LOG, "Sending Close PDU, reason=%d, message=%s",
203 reason, message ? message : "none");
204 apdu.which = Z_APDU_close;
206 *cls->closeReason = reason;
207 cls->diagnosticInformation = message;
208 process_z_response(a, req, &apdu);
209 iochan_settimeout(a->client_chan, 20);
213 yaz_log(LOG_DEBUG, "v2 client. No Close PDU");
214 iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
216 a->state = ASSOC_DEAD;
219 static void do_close(association *a, int reason, char *message)
221 do_close_req (a, reason, message, request_get(&a->outgoing));
225 * This is where PDUs from the client are read and the further
226 * processing is initiated. Flow of control moves down through the
227 * various process_* functions below, until the encoded result comes back up
228 * to the output handler in here.
230 * h : the I/O channel that has an outstanding event.
231 * event : the current outstanding event.
233 void ir_session(IOCHAN h, int event)
236 association *assoc = (association *)iochan_getdata(h);
237 COMSTACK conn = assoc->client_link;
240 assert(h && conn && assoc);
241 if (event == EVENT_TIMEOUT)
243 if (assoc->state != ASSOC_UP)
245 yaz_log(LOG_LOG, "Final timeout - closing connection.");
247 destroy_association(assoc);
252 yaz_log(LOG_LOG, "Session idle too long. Sending close.");
253 do_close(assoc, Z_Close_lackOfActivity, 0);
257 if (event & assoc->cs_accept_mask)
259 yaz_log (LOG_DEBUG, "ir_session (accept)");
260 if (!cs_accept (conn))
262 yaz_log (LOG_LOG, "accept failed");
263 destroy_association(assoc);
266 iochan_clearflag (h, EVENT_OUTPUT|EVENT_OUTPUT);
267 if (conn->io_pending)
268 { /* cs_accept didn't complete */
269 assoc->cs_accept_mask =
270 ((conn->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
271 ((conn->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
273 iochan_setflag (h, assoc->cs_accept_mask);
276 { /* cs_accept completed. Prepare for reading (cs_get) */
277 assoc->cs_accept_mask = 0;
278 assoc->cs_get_mask = EVENT_INPUT;
279 iochan_setflag (h, assoc->cs_get_mask);
283 if ((event & assoc->cs_get_mask) || (event & EVENT_WORK)) /* input */
285 if ((assoc->cs_put_mask & EVENT_INPUT) == 0 && (event & assoc->cs_get_mask))
287 yaz_log(LOG_DEBUG, "ir_session (input)");
288 /* We aren't speaking to this fellow */
289 if (assoc->state == ASSOC_DEAD)
291 yaz_log(LOG_LOG, "Connection closed - end of session");
293 destroy_association(assoc);
297 assoc->cs_get_mask = EVENT_INPUT;
298 if ((res = cs_get(conn, &assoc->input_buffer,
299 &assoc->input_buffer_len)) <= 0)
301 yaz_log(LOG_LOG, "Connection closed by client");
303 destroy_association(assoc);
307 else if (res == 1) /* incomplete read - wait for more */
309 if (conn->io_pending & CS_WANT_WRITE)
310 assoc->cs_get_mask |= EVENT_OUTPUT;
311 iochan_setflag(h, assoc->cs_get_mask);
314 if (cs_more(conn)) /* more stuff - call us again later, please */
315 iochan_setevent(h, EVENT_INPUT);
317 /* we got a complete PDU. Let's decode it */
318 yaz_log(LOG_DEBUG, "Got PDU, %d bytes: lead=%02X %02X %02X", res,
319 assoc->input_buffer[0] & 0xff,
320 assoc->input_buffer[1] & 0xff,
321 assoc->input_buffer[2] & 0xff);
322 req = request_get(&assoc->incoming); /* get a new request */
323 odr_reset(assoc->decode);
324 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
325 if (!z_GDU(assoc->decode, &req->gdu_request, 0, 0))
327 yaz_log(LOG_LOG, "ODR error on incoming PDU: %s [near byte %d] ",
328 odr_errmsg(odr_geterror(assoc->decode)),
329 odr_offset(assoc->decode));
330 if (assoc->decode->error != OHTTP)
332 yaz_log(LOG_LOG, "PDU dump:");
333 odr_dumpBER(yaz_log_file(), assoc->input_buffer, res);
334 do_close(assoc, Z_Close_protocolError, "Malformed package");
338 Z_GDU *p = z_get_HTTP_Response(assoc->encode, 400);
339 assoc->state = ASSOC_DEAD;
340 process_gdu_response(assoc, req, p);
344 req->request_mem = odr_extract_mem(assoc->decode);
345 if (assoc->print && !z_GDU(assoc->print, &req->gdu_request, 0, 0))
347 yaz_log(LOG_WARN, "ODR print error: %s",
348 odr_errmsg(odr_geterror(assoc->print)));
349 odr_reset(assoc->print);
351 request_enq(&assoc->incoming, req);
354 /* can we do something yet? */
355 req = request_head(&assoc->incoming);
356 if (req->state == REQUEST_IDLE)
358 request_deq(&assoc->incoming);
359 process_gdu_request(assoc, req);
362 if (event & assoc->cs_put_mask)
364 request *req = request_head(&assoc->outgoing);
366 assoc->cs_put_mask = 0;
367 yaz_log(LOG_DEBUG, "ir_session (output)");
368 req->state = REQUEST_PENDING;
369 switch (res = cs_put(conn, req->response, req->len_response))
372 yaz_log(LOG_LOG, "Connection closed by client");
374 destroy_association(assoc);
377 case 0: /* all sent - release the request structure */
378 yaz_log(LOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
380 yaz_log(LOG_DEBUG, "HTTP out:\n%.*s", req->len_response,
383 nmem_destroy(req->request_mem);
384 request_deq(&assoc->outgoing);
385 request_release(req);
386 if (!request_head(&assoc->outgoing))
387 { /* restore mask for cs_get operation ... */
388 iochan_clearflag(h, EVENT_OUTPUT|EVENT_INPUT);
389 iochan_setflag(h, assoc->cs_get_mask);
390 if (assoc->state == ASSOC_DEAD)
391 iochan_setevent(assoc->client_chan, EVENT_TIMEOUT);
395 assoc->cs_put_mask = EVENT_OUTPUT;
399 if (conn->io_pending & CS_WANT_WRITE)
400 assoc->cs_put_mask |= EVENT_OUTPUT;
401 if (conn->io_pending & CS_WANT_READ)
402 assoc->cs_put_mask |= EVENT_INPUT;
403 iochan_setflag(h, assoc->cs_put_mask);
406 if (event & EVENT_EXCEPT)
408 yaz_log(LOG_LOG, "ir_session (exception)");
410 destroy_association(assoc);
415 static int process_z_request(association *assoc, request *req, char **msg);
417 static void assoc_init_reset(association *assoc)
420 assoc->init = (bend_initrequest *) xmalloc (sizeof(*assoc->init));
422 assoc->init->stream = assoc->encode;
423 assoc->init->print = assoc->print;
424 assoc->init->auth = 0;
425 assoc->init->referenceId = 0;
426 assoc->init->implementation_version = 0;
427 assoc->init->implementation_id = 0;
428 assoc->init->implementation_name = 0;
429 assoc->init->bend_sort = NULL;
430 assoc->init->bend_search = NULL;
431 assoc->init->bend_present = NULL;
432 assoc->init->bend_esrequest = NULL;
433 assoc->init->bend_delete = NULL;
434 assoc->init->bend_scan = NULL;
435 assoc->init->bend_segment = NULL;
436 assoc->init->bend_fetch = NULL;
437 assoc->init->charneg_request = NULL;
438 assoc->init->charneg_response = NULL;
439 assoc->init->decode = assoc->decode;
440 assoc->init->peer_name =
441 odr_strdup (assoc->encode, cs_addrstr(assoc->client_link));
444 static int srw_bend_init(association *assoc)
446 bend_initresult *binitres;
447 statserv_options_block *cb = statserv_getcontrol();
449 assoc_init_reset(assoc);
451 assoc->maximumRecordSize = 3000000;
452 assoc->preferredMessageSize = 3000000;
454 if (!(binitres = (*cb->bend_init)(assoc->init)))
456 yaz_log(LOG_WARN, "Bad response from backend.");
459 assoc->backend = binitres->handle;
463 static int srw_bend_fetch(association *assoc, int pos,
464 Z_SRW_searchRetrieveRequest *srw_req,
465 Z_SRW_record *record)
468 ODR o = assoc->encode;
470 rr.setname = "default";
473 rr.request_format = VAL_TEXT_XML;
474 rr.request_format_raw = yaz_oidval_to_z3950oid(assoc->decode,
477 rr.comp = (Z_RecordComposition *)
478 odr_malloc(assoc->decode, sizeof(*rr.comp));
479 rr.comp->which = Z_RecordComp_complex;
480 rr.comp->u.complex = (Z_CompSpec *)
481 odr_malloc(assoc->decode, sizeof(Z_CompSpec));
482 rr.comp->u.complex->selectAlternativeSyntax = (bool_t *)
483 odr_malloc(assoc->encode, sizeof(bool_t));
484 *rr.comp->u.complex->selectAlternativeSyntax = 0;
485 rr.comp->u.complex->num_dbSpecific = 0;
486 rr.comp->u.complex->dbSpecific = 0;
487 rr.comp->u.complex->num_recordSyntax = 0;
488 rr.comp->u.complex->recordSyntax = 0;
490 rr.comp->u.complex->generic = (Z_Specification *)
491 odr_malloc(assoc->decode, sizeof(Z_Specification));
492 rr.comp->u.complex->generic->which = Z_Schema_uri;
493 rr.comp->u.complex->generic->schema.uri = srw_req->recordSchema;
494 rr.comp->u.complex->generic->elementSpec = 0;
496 rr.stream = assoc->encode;
497 rr.print = assoc->print;
503 rr.output_format = VAL_TEXT_XML;
504 rr.output_format_raw = 0;
507 rr.surrogate_flag = 0;
509 (*assoc->init->bend_fetch)(assoc->backend, &rr);
513 record->recordData_buf = rr.record;
514 record->recordData_len = rr.len;
515 record->recordPosition = odr_intdup(o, pos);
516 record->recordSchema = 0;
517 if (srw_req->recordSchema)
518 record->recordSchema = odr_strdup(o, srw_req->recordSchema);
523 static void srw_bend_search(association *assoc, request *req,
524 Z_SRW_searchRetrieveRequest *srw_req,
525 Z_SRW_searchRetrieveResponse *srw_res)
527 char *base = "Default";
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));
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;
554 rr.query->which = Z_Query_type_104;
555 rr.query->u.type_104 = ext;
557 else if (srw_req->pQuery)
559 Z_RPNQuery *RPNquery;
560 YAZ_PQF_Parser pqf_parser;
562 pqf_parser = yaz_pqf_create ();
564 yaz_log(LOG_LOG, "PQF: %s", srw_req->pQuery);
566 RPNquery = yaz_pqf_parse (pqf_parser, assoc->decode, srw_req->pQuery);
571 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
572 yaz_log(LOG_LOG, "%*s^\n", off+4, "");
573 yaz_log(LOG_LOG, "Bad PQF: %s (code %d)\n", pqf_msg, code);
578 rr.query->which = Z_Query_type_1;
579 rr.query->u.type_1 = RPNquery;
581 yaz_pqf_destroy (pqf_parser);
586 if (srw_req->sortKeys || srw_req->xSortKeys)
591 srw_res->num_diagnostics = 1;
592 srw_res->diagnostics = (Z_SRW_diagnostic *)
593 odr_malloc(assoc->encode, sizeof(*srw_res->diagnostics));
594 srw_res->diagnostics[0].code =
595 odr_intdup(assoc->encode, srw_error);
596 srw_res->diagnostics[0].details = 0;
601 rr.stream = assoc->encode;
602 rr.decode = assoc->decode;
603 rr.print = assoc->print;
605 rr.association = assoc;
611 yaz_log_zquery(rr.query);
612 (assoc->init->bend_search)(assoc->backend, &rr);
613 srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
616 srw_res->num_diagnostics = 1;
617 srw_res->diagnostics = (Z_SRW_diagnostic *)
618 odr_malloc(assoc->encode, sizeof(*srw_res->diagnostics));
619 srw_res->diagnostics[0].code =
620 odr_intdup(assoc->encode,
621 yaz_diag_bib1_to_srw (rr.errcode));
622 srw_res->diagnostics[0].details = rr.errstring;
626 srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
627 if (srw_req->maximumRecords && *srw_req->maximumRecords > 0)
629 int number = *srw_req->maximumRecords;
632 if (srw_req->startRecord)
633 start = *srw_req->startRecord;
634 if (start <= rr.hits)
637 if (start + number > rr.hits)
638 number = rr.hits - start + 1;
639 srw_res->records = (Z_SRW_record *)
640 odr_malloc(assoc->encode,
641 number * sizeof(*srw_res->records));
642 for (i = 0; i<number; i++)
645 srw_res->records[j].recordData_buf = 0;
646 errcode = srw_bend_fetch(assoc, i+start, srw_req,
647 srw_res->records + j);
650 srw_res->num_diagnostics = 1;
651 srw_res->diagnostics = (Z_SRW_diagnostic *)
652 odr_malloc(assoc->encode,
653 sizeof(*srw_res->diagnostics));
654 srw_res->diagnostics[0].code =
655 odr_intdup(assoc->encode,
656 yaz_diag_bib1_to_srw (errcode));
657 srw_res->diagnostics[0].details = rr.errstring;
660 if (srw_res->records[j].recordData_buf)
663 srw_res->num_records = j;
665 srw_res->records = 0;
671 static void process_http_request(association *assoc, request *req)
673 Z_HTTP_Request *hreq = req->gdu_request->u.HTTP_Request;
674 ODR o = assoc->encode;
676 Z_HTTP_Response *hres = 0;
679 if (!strcmp(hreq->method, "GET"))
682 if (strlen(hreq->path) >= 5 && strlen(hreq->path) < 80 &&
683 !memcmp(hreq->path, "/doc/", 5))
688 strcpy(fpath, DOCDIR);
689 strcat(fpath, hreq->path+4);
690 f = fopen(fpath, "rb");
693 if (fstat(fileno(f), &sbuf) || !S_ISREG(sbuf.st_mode))
702 fseek(f, 0L, SEEK_END);
704 if (sz >= 0 && sz < 500000)
706 const char *ctype = "application/octet-stream";
709 p = z_get_HTTP_Response(o, 200);
710 hres = p->u.HTTP_Response;
711 hres->content_buf = (char *) odr_malloc(o, sz + 1);
712 hres->content_len = sz;
713 fseek(f, 0L, SEEK_SET);
714 fread(hres->content_buf, 1, sz, f);
715 if ((cp = strrchr(fpath, '.'))) {
717 if (!strcmp(cp, "png"))
719 else if (!strcmp(cp, "gif"))
721 else if (!strcmp(cp, "xml"))
723 else if (!strcmp(cp, "html"))
726 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
732 if (!strcmp(hreq->path, "/"))
737 const char *doclink = "";
738 p = z_get_HTTP_Response(o, 200);
739 hres = p->u.HTTP_Response;
740 hres->content_buf = (char *) odr_malloc(o, 400);
742 if (stat(DOCDIR "/yaz.html", &sbuf) == 0 && S_ISREG(sbuf.st_mode))
743 doclink = "<P><A HREF=\"/doc/yaz.html\">Documentation</A></P>";
745 sprintf (hres->content_buf,
746 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n"
749 " <TITLE>YAZ " YAZ_VERSION "</TITLE>\n"
752 " <P><A HREF=\"http://www.indexdata.dk/yaz/\">YAZ</A> "
756 "</HTML>\n", doclink);
757 hres->content_len = strlen(hres->content_buf);
758 z_HTTP_header_add(o, &hres->headers, "Content-Type", "text/html");
762 p = z_get_HTTP_Response(o, 404);
765 else if (!strcmp(hreq->method, "POST"))
767 const char *content_type = z_HTTP_header_lookup(hreq->headers,
769 const char *soap_action = z_HTTP_header_lookup(hreq->headers,
771 if (content_type && soap_action &&
772 !yaz_strcmp_del("text/xml", content_type, "; "))
774 Z_SOAP *soap_package = 0;
778 static Z_SOAP_Handler soap_handlers[2] = {
780 {"http://www.loc.gov/zing/srw/v1.0/", 0,
781 (Z_SOAP_fun) yaz_srw_codec},
785 ret = z_soap_codec(assoc->decode, &soap_package,
786 &hreq->content_buf, &hreq->content_len,
790 if (!ret && soap_package->which == Z_SOAP_generic &&
791 soap_package->u.generic->no == 0)
794 Z_SRW_searchRetrieve *sr = soap_package->u.generic->p;
796 if (sr->which == Z_SRW_searchRetrieve_request)
798 Z_SRW_searchRetrieve *res =
799 yaz_srw_get(assoc->encode,
800 Z_SRW_searchRetrieve_response);
802 if (!sr->u.request->database)
804 const char *p0 = hreq->path, *p1;
807 p1 = strchr(p0, '?');
809 p1 = p0 + strlen(p0);
812 sr->u.request->database =
813 odr_malloc(assoc->decode, p1 - p0 + 1);
814 memcpy (sr->u.request->database, p0, p1 - p0);
815 sr->u.request->database[p1 - p0] = '\0';
818 sr->u.request->database = "Default";
820 srw_bend_search(assoc, req, sr->u.request,
823 soap_package->u.generic->p = res;
828 p = z_get_HTTP_Response(o, 200);
829 hres = p->u.HTTP_Response;
830 ret = z_soap_codec(assoc->encode, &soap_package,
831 &hres->content_buf, &hres->content_len,
833 hres->code = http_code;
834 z_HTTP_header_add(o, &hres->headers, "Content-Type", "text/xml");
836 if (!p) /* still no response ? */
837 p = z_get_HTTP_Response(o, 500);
841 p = z_get_HTTP_Response(o, 405);
842 hres = p->u.HTTP_Response;
844 z_HTTP_header_add(o, &hres->headers, "Allow", "GET, POST");
846 hres = p->u.HTTP_Response;
847 if (!strcmp(hreq->version, "1.0"))
849 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
850 if (v && !strcmp(v, "Keep-Alive"))
854 hres->version = "1.0";
858 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
859 if (v && !strcmp(v, "close"))
863 hres->version = "1.1";
867 z_HTTP_header_add(o, &hres->headers, "Connection", "close");
868 assoc->state = ASSOC_DEAD;
873 const char *alive = z_HTTP_header_lookup(hreq->headers, "Keep-Alive");
875 if (alive && isdigit(*alive))
879 if (t < 0 || t > 3600)
881 iochan_settimeout(assoc->client_chan,t);
882 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
884 process_gdu_response(assoc, req, p);
887 static void process_gdu_request(association *assoc, request *req)
889 if (req->gdu_request->which == Z_GDU_Z3950)
892 req->apdu_request = req->gdu_request->u.z3950;
893 if (process_z_request(assoc, req, &msg) < 0)
894 do_close_req(assoc, Z_Close_systemProblem, msg, req);
896 else if (req->gdu_request->which == Z_GDU_HTTP_Request)
897 process_http_request(assoc, req);
900 do_close_req(assoc, Z_Close_systemProblem, "bad protocol packet", req);
905 * Initiate request processing.
907 static int process_z_request(association *assoc, request *req, char **msg)
913 *msg = "Unknown Error";
914 assert(req && req->state == REQUEST_IDLE);
915 if (req->apdu_request->which != Z_APDU_initRequest && !assoc->init)
917 *msg = "Missing InitRequest";
920 switch (req->apdu_request->which)
922 case Z_APDU_initRequest:
923 iochan_settimeout(assoc->client_chan,
924 statserv_getcontrol()->idle_timeout * 60);
925 res = process_initRequest(assoc, req); break;
926 case Z_APDU_searchRequest:
927 res = process_searchRequest(assoc, req, &fd); break;
928 case Z_APDU_presentRequest:
929 res = process_presentRequest(assoc, req, &fd); break;
930 case Z_APDU_scanRequest:
931 if (assoc->init->bend_scan)
932 res = process_scanRequest(assoc, req, &fd);
935 *msg = "Cannot handle Scan APDU";
939 case Z_APDU_extendedServicesRequest:
940 if (assoc->init->bend_esrequest)
941 res = process_ESRequest(assoc, req, &fd);
944 *msg = "Cannot handle Extended Services APDU";
948 case Z_APDU_sortRequest:
949 if (assoc->init->bend_sort)
950 res = process_sortRequest(assoc, req, &fd);
953 *msg = "Cannot handle Sort APDU";
958 process_close(assoc, req);
960 case Z_APDU_deleteResultSetRequest:
961 if (assoc->init->bend_delete)
962 res = process_deleteRequest(assoc, req, &fd);
965 *msg = "Cannot handle Delete APDU";
969 case Z_APDU_segmentRequest:
970 if (assoc->init->bend_segment)
972 res = process_segmentRequest (assoc, req);
976 *msg = "Cannot handle Segment APDU";
981 *msg = "Bad APDU received";
986 yaz_log(LOG_DEBUG, " result immediately available");
987 retval = process_z_response(assoc, req, res);
991 yaz_log(LOG_DEBUG, " result unavailble");
994 else /* no result yet - one will be provided later */
998 /* Set up an I/O handler for the fd supplied by the backend */
1000 yaz_log(LOG_DEBUG, " establishing handler for result");
1001 req->state = REQUEST_PENDING;
1002 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT)))
1004 iochan_setdata(chan, assoc);
1011 * Handle message from the backend.
1013 void backend_response(IOCHAN i, int event)
1015 association *assoc = (association *)iochan_getdata(i);
1016 request *req = request_head(&assoc->incoming);
1020 yaz_log(LOG_DEBUG, "backend_response");
1021 assert(assoc && req && req->state != REQUEST_IDLE);
1022 /* determine what it is we're waiting for */
1023 switch (req->apdu_request->which)
1025 case Z_APDU_searchRequest:
1026 res = response_searchRequest(assoc, req, 0, &fd); break;
1028 case Z_APDU_presentRequest:
1029 res = response_presentRequest(assoc, req, 0, &fd); break;
1030 case Z_APDU_scanRequest:
1031 res = response_scanRequest(assoc, req, 0, &fd); break;
1034 yaz_log(LOG_WARN, "Serious programmer's lapse or bug");
1037 if ((res && process_z_response(assoc, req, res) < 0) || fd < 0)
1039 yaz_log(LOG_LOG, "Fatal error when talking to backend");
1040 do_close(assoc, Z_Close_systemProblem, 0);
1044 else if (!res) /* no result yet - try again later */
1046 yaz_log(LOG_DEBUG, " no result yet");
1047 iochan_setfd(i, fd); /* in case fd has changed */
1052 * Encode response, and transfer the request structure to the outgoing queue.
1054 static int process_gdu_response(association *assoc, request *req, Z_GDU *res)
1056 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
1058 if (assoc->print && !z_GDU(assoc->print, &res, 0, 0))
1060 yaz_log(LOG_WARN, "ODR print error: %s",
1061 odr_errmsg(odr_geterror(assoc->print)));
1062 odr_reset(assoc->print);
1064 if (!z_GDU(assoc->encode, &res, 0, 0))
1066 yaz_log(LOG_WARN, "ODR error when encoding response: %s",
1067 odr_errmsg(odr_geterror(assoc->decode)));
1070 req->response = odr_getbuf(assoc->encode, &req->len_response,
1071 &req->size_response);
1072 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
1073 odr_reset(assoc->encode);
1074 req->state = REQUEST_IDLE;
1075 request_enq(&assoc->outgoing, req);
1076 /* turn the work over to the ir_session handler */
1077 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
1078 assoc->cs_put_mask = EVENT_OUTPUT;
1079 /* Is there more work to be done? give that to the input handler too */
1081 if (request_head(&assoc->incoming))
1083 yaz_log (LOG_DEBUG, "more work to be done");
1084 iochan_setevent(assoc->client_chan, EVENT_WORK);
1091 * Encode response, and transfer the request structure to the outgoing queue.
1093 static int process_z_response(association *assoc, request *req, Z_APDU *res)
1095 Z_GDU *gres = (Z_GDU *) odr_malloc(assoc->encode, sizeof(*res));
1096 gres->which = Z_GDU_Z3950;
1097 gres->u.z3950 = res;
1099 return process_gdu_response(assoc, req, gres);
1104 * Handle init request.
1105 * At the moment, we don't check the options
1106 * anywhere else in the code - we just try not to do anything that would
1107 * break a naive client. We'll toss 'em into the association block when
1108 * we need them there.
1110 static Z_APDU *process_initRequest(association *assoc, request *reqb)
1112 statserv_options_block *cb = statserv_getcontrol();
1113 Z_InitRequest *req = reqb->apdu_request->u.initRequest;
1114 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
1115 Z_InitResponse *resp = apdu->u.initResponse;
1116 bend_initresult *binitres;
1120 yaz_log(LOG_LOG, "Got initRequest");
1121 if (req->implementationId)
1122 yaz_log(LOG_LOG, "Id: %s", req->implementationId);
1123 if (req->implementationName)
1124 yaz_log(LOG_LOG, "Name: %s", req->implementationName);
1125 if (req->implementationVersion)
1126 yaz_log(LOG_LOG, "Version: %s", req->implementationVersion);
1128 assoc_init_reset(assoc);
1130 assoc->init->auth = req->idAuthentication;
1131 assoc->init->referenceId = req->referenceId;
1133 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
1135 Z_CharSetandLanguageNegotiation *negotiation =
1136 yaz_get_charneg_record (req->otherInfo);
1137 if (negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
1138 assoc->init->charneg_request = negotiation;
1141 if (!(binitres = (*cb->bend_init)(assoc->init)))
1143 yaz_log(LOG_WARN, "Bad response from backend.");
1147 assoc->backend = binitres->handle;
1148 if ((assoc->init->bend_sort))
1149 yaz_log (LOG_DEBUG, "Sort handler installed");
1150 if ((assoc->init->bend_search))
1151 yaz_log (LOG_DEBUG, "Search handler installed");
1152 if ((assoc->init->bend_present))
1153 yaz_log (LOG_DEBUG, "Present handler installed");
1154 if ((assoc->init->bend_esrequest))
1155 yaz_log (LOG_DEBUG, "ESRequest handler installed");
1156 if ((assoc->init->bend_delete))
1157 yaz_log (LOG_DEBUG, "Delete handler installed");
1158 if ((assoc->init->bend_scan))
1159 yaz_log (LOG_DEBUG, "Scan handler installed");
1160 if ((assoc->init->bend_segment))
1161 yaz_log (LOG_DEBUG, "Segment handler installed");
1163 resp->referenceId = req->referenceId;
1165 /* let's tell the client what we can do */
1166 if (ODR_MASK_GET(req->options, Z_Options_search))
1168 ODR_MASK_SET(resp->options, Z_Options_search);
1169 strcat(options, "srch");
1171 if (ODR_MASK_GET(req->options, Z_Options_present))
1173 ODR_MASK_SET(resp->options, Z_Options_present);
1174 strcat(options, " prst");
1176 if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
1177 assoc->init->bend_delete)
1179 ODR_MASK_SET(resp->options, Z_Options_delSet);
1180 strcat(options, " del");
1182 if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
1183 assoc->init->bend_esrequest)
1185 ODR_MASK_SET(resp->options, Z_Options_extendedServices);
1186 strcat (options, " extendedServices");
1188 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
1190 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
1191 strcat(options, " namedresults");
1193 if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
1195 ODR_MASK_SET(resp->options, Z_Options_scan);
1196 strcat(options, " scan");
1198 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
1200 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
1201 strcat(options, " concurrop");
1203 if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
1205 ODR_MASK_SET(resp->options, Z_Options_sort);
1206 strcat(options, " sort");
1209 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel)
1210 && assoc->init->charneg_response)
1212 Z_OtherInformation **p;
1213 Z_OtherInformationUnit *p0;
1215 yaz_oi_APDU(apdu, &p);
1217 if ((p0=yaz_oi_update(p, assoc->encode, NULL, 0, 0))) {
1218 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
1220 p0->which = Z_OtherInfo_externallyDefinedInfo;
1221 p0->information.externallyDefinedInfo =
1222 assoc->init->charneg_response;
1224 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
1225 strcat(options, " negotiation");
1228 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
1230 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
1231 assoc->version = 2; /* 1 & 2 are equivalent */
1233 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
1235 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
1238 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
1240 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
1244 yaz_log(LOG_LOG, "Negotiated to v%d: %s", assoc->version, options);
1245 assoc->maximumRecordSize = *req->maximumRecordSize;
1246 if (assoc->maximumRecordSize > control_block->maxrecordsize)
1247 assoc->maximumRecordSize = control_block->maxrecordsize;
1248 assoc->preferredMessageSize = *req->preferredMessageSize;
1249 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
1250 assoc->preferredMessageSize = assoc->maximumRecordSize;
1252 resp->preferredMessageSize = &assoc->preferredMessageSize;
1253 resp->maximumRecordSize = &assoc->maximumRecordSize;
1255 resp->implementationName = "GFS/YAZ";
1257 if (assoc->init->implementation_id)
1260 odr_malloc (assoc->encode,
1261 strlen(assoc->init->implementation_id) + 10 +
1262 strlen(resp->implementationId));
1263 sprintf (nv, "%s / %s",
1264 resp->implementationId, assoc->init->implementation_id);
1265 resp->implementationId = nv;
1267 if (assoc->init->implementation_name)
1270 odr_malloc (assoc->encode,
1271 strlen(assoc->init->implementation_name) + 10 +
1272 strlen(resp->implementationName));
1273 sprintf (nv, "%s / %s",
1274 resp->implementationName, assoc->init->implementation_name);
1275 resp->implementationName = nv;
1277 if (assoc->init->implementation_version)
1280 odr_malloc (assoc->encode,
1281 strlen(assoc->init->implementation_version) + 10 +
1282 strlen(resp->implementationVersion));
1283 sprintf (nv, "YAZ %s / %s",
1284 resp->implementationVersion,
1285 assoc->init->implementation_version);
1286 resp->implementationVersion = nv;
1289 if (binitres->errcode)
1291 yaz_log(LOG_LOG, "Connection rejected by backend.");
1293 assoc->state = ASSOC_DEAD;
1296 assoc->state = ASSOC_UP;
1301 * These functions should be merged.
1304 static void set_addinfo (Z_DefaultDiagFormat *dr, char *addinfo, ODR odr)
1306 dr->which = Z_DefaultDiagFormat_v2Addinfo;
1307 dr->u.v2Addinfo = odr_strdup (odr, addinfo ? addinfo : "");
1311 * nonsurrogate diagnostic record.
1313 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
1315 Z_Records *rec = (Z_Records *)
1316 odr_malloc (assoc->encode, sizeof(*rec));
1317 int *err = odr_intdup(assoc->encode, error);
1318 Z_DiagRec *drec = (Z_DiagRec *)
1319 odr_malloc (assoc->encode, sizeof(*drec));
1320 Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
1321 odr_malloc (assoc->encode, sizeof(*dr));
1323 yaz_log(LOG_LOG, "[%d] %s %s%s", error, diagbib1_str(error),
1324 addinfo ? " -- " : "", addinfo ? addinfo : "");
1325 rec->which = Z_Records_NSD;
1326 rec->u.nonSurrogateDiagnostic = dr;
1327 dr->diagnosticSetId =
1328 yaz_oidval_to_z3950oid (assoc->encode, CLASS_DIAGSET, VAL_BIB1);
1329 dr->condition = err;
1330 set_addinfo (dr, addinfo, assoc->encode);
1335 * surrogate diagnostic.
1337 static Z_NamePlusRecord *surrogatediagrec(association *assoc, char *dbname,
1338 int error, char *addinfo)
1340 Z_NamePlusRecord *rec = (Z_NamePlusRecord *)
1341 odr_malloc (assoc->encode, sizeof(*rec));
1342 int *err = odr_intdup(assoc->encode, error);
1343 Z_DiagRec *drec = (Z_DiagRec *)odr_malloc (assoc->encode, sizeof(*drec));
1344 Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
1345 odr_malloc (assoc->encode, sizeof(*dr));
1347 yaz_log(LOG_DEBUG, "SurrogateDiagnotic: %d -- %s", error, addinfo);
1348 rec->databaseName = dbname;
1349 rec->which = Z_NamePlusRecord_surrogateDiagnostic;
1350 rec->u.surrogateDiagnostic = drec;
1351 drec->which = Z_DiagRec_defaultFormat;
1352 drec->u.defaultFormat = dr;
1353 dr->diagnosticSetId =
1354 yaz_oidval_to_z3950oid (assoc->encode, CLASS_DIAGSET, VAL_BIB1);
1355 dr->condition = err;
1356 set_addinfo (dr, addinfo, assoc->encode);
1362 * multiple nonsurrogate diagnostics.
1364 static Z_DiagRecs *diagrecs(association *assoc, int error, char *addinfo)
1366 Z_DiagRecs *recs = (Z_DiagRecs *)odr_malloc (assoc->encode, sizeof(*recs));
1367 int *err = odr_intdup(assoc->encode, error);
1368 Z_DiagRec **recp = (Z_DiagRec **)odr_malloc (assoc->encode, sizeof(*recp));
1369 Z_DiagRec *drec = (Z_DiagRec *)odr_malloc (assoc->encode, sizeof(*drec));
1370 Z_DefaultDiagFormat *rec = (Z_DefaultDiagFormat *)
1371 odr_malloc (assoc->encode, sizeof(*rec));
1373 yaz_log(LOG_DEBUG, "DiagRecs: %d -- %s", error, addinfo ? addinfo : "");
1375 recs->num_diagRecs = 1;
1376 recs->diagRecs = recp;
1378 drec->which = Z_DiagRec_defaultFormat;
1379 drec->u.defaultFormat = rec;
1381 rec->diagnosticSetId =
1382 yaz_oidval_to_z3950oid (assoc->encode, CLASS_DIAGSET, VAL_BIB1);
1383 rec->condition = err;
1385 rec->which = Z_DefaultDiagFormat_v2Addinfo;
1386 rec->u.v2Addinfo = odr_strdup (assoc->encode, addinfo ? addinfo : "");
1390 static Z_Records *pack_records(association *a, char *setname, int start,
1391 int *num, Z_RecordComposition *comp,
1392 int *next, int *pres, oid_value format,
1393 Z_ReferenceId *referenceId,
1396 int recno, total_length = 0, toget = *num, dumped_records = 0;
1397 Z_Records *records =
1398 (Z_Records *) odr_malloc (a->encode, sizeof(*records));
1399 Z_NamePlusRecordList *reclist =
1400 (Z_NamePlusRecordList *) odr_malloc (a->encode, sizeof(*reclist));
1401 Z_NamePlusRecord **list =
1402 (Z_NamePlusRecord **) odr_malloc (a->encode, sizeof(*list) * toget);
1404 records->which = Z_Records_DBOSD;
1405 records->u.databaseOrSurDiagnostics = reclist;
1406 reclist->num_records = 0;
1407 reclist->records = list;
1408 *pres = Z_PRES_SUCCESS;
1412 yaz_log(LOG_LOG, "Request to pack %d+%d+%s", start, toget, setname);
1413 yaz_log(LOG_DEBUG, "pms=%d, mrs=%d", a->preferredMessageSize,
1414 a->maximumRecordSize);
1415 for (recno = start; reclist->num_records < toget; recno++)
1418 Z_NamePlusRecord *thisrec;
1419 int this_length = 0;
1421 * we get the number of bytes allocated on the stream before any
1422 * allocation done by the backend - this should give us a reasonable
1423 * idea of the total size of the data so far.
1425 total_length = odr_total(a->encode) - dumped_records;
1431 freq.last_in_set = 0;
1432 freq.setname = setname;
1433 freq.surrogate_flag = 0;
1434 freq.number = recno;
1436 freq.request_format = format;
1437 freq.request_format_raw = oid;
1438 freq.output_format = format;
1439 freq.output_format_raw = 0;
1440 freq.stream = a->encode;
1441 freq.print = a->print;
1442 freq.surrogate_flag = 0;
1443 freq.referenceId = referenceId;
1444 (*a->init->bend_fetch)(a->backend, &freq);
1445 /* backend should be able to signal whether error is system-wide
1446 or only pertaining to current record */
1449 if (!freq.surrogate_flag)
1452 *pres = Z_PRES_FAILURE;
1453 /* for 'present request out of range',
1454 set addinfo to record position if not set */
1455 if (freq.errcode == 13 && freq.errstring == 0)
1457 sprintf (s, "%d", recno);
1460 return diagrec(a, freq.errcode, freq.errstring);
1462 reclist->records[reclist->num_records] =
1463 surrogatediagrec(a, freq.basename, freq.errcode,
1465 reclist->num_records++;
1466 *next = freq.last_in_set ? 0 : recno + 1;
1470 this_length = freq.len;
1472 this_length = odr_total(a->encode) - total_length;
1473 yaz_log(LOG_DEBUG, " fetched record, len=%d, total=%d",
1474 this_length, total_length);
1475 if (this_length + total_length > a->preferredMessageSize)
1477 /* record is small enough, really */
1478 if (this_length <= a->preferredMessageSize)
1480 yaz_log(LOG_DEBUG, " Dropped last normal-sized record");
1481 *pres = Z_PRES_PARTIAL_2;
1484 /* record can only be fetched by itself */
1485 if (this_length < a->maximumRecordSize)
1487 yaz_log(LOG_DEBUG, " Record > prefmsgsz");
1490 yaz_log(LOG_DEBUG, " Dropped it");
1491 reclist->records[reclist->num_records] =
1492 surrogatediagrec(a, freq.basename, 16, 0);
1493 reclist->num_records++;
1494 *next = freq.last_in_set ? 0 : recno + 1;
1495 dumped_records += this_length;
1499 else /* too big entirely */
1501 yaz_log(LOG_LOG, "Record > maxrcdsz this=%d max=%d", this_length, a->maximumRecordSize);
1502 reclist->records[reclist->num_records] =
1503 surrogatediagrec(a, freq.basename, 17, 0);
1504 reclist->num_records++;
1505 *next = freq.last_in_set ? 0 : recno + 1;
1506 dumped_records += this_length;
1511 if (!(thisrec = (Z_NamePlusRecord *)
1512 odr_malloc(a->encode, sizeof(*thisrec))))
1514 if (!(thisrec->databaseName = (char *)odr_malloc(a->encode,
1515 strlen(freq.basename) + 1)))
1517 strcpy(thisrec->databaseName, freq.basename);
1518 thisrec->which = Z_NamePlusRecord_databaseRecord;
1520 if (freq.output_format_raw)
1522 struct oident *ident = oid_getentbyoid(freq.output_format_raw);
1523 freq.output_format = ident->value;
1525 thisrec->u.databaseRecord = z_ext_record(a->encode, freq.output_format,
1526 freq.record, freq.len);
1527 if (!thisrec->u.databaseRecord)
1529 reclist->records[reclist->num_records] = thisrec;
1530 reclist->num_records++;
1531 *next = freq.last_in_set ? 0 : recno + 1;
1533 *num = reclist->num_records;
1537 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
1540 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
1541 bend_search_rr *bsrr =
1542 (bend_search_rr *)nmem_malloc (reqb->request_mem, sizeof(*bsrr));
1544 yaz_log(LOG_LOG, "Got SearchRequest.");
1546 bsrr->request = reqb;
1547 bsrr->association = assoc;
1548 bsrr->referenceId = req->referenceId;
1549 save_referenceId (reqb, bsrr->referenceId);
1551 yaz_log (LOG_LOG, "ResultSet '%s'", req->resultSetName);
1552 if (req->databaseNames)
1555 for (i = 0; i < req->num_databaseNames; i++)
1556 yaz_log (LOG_LOG, "Database '%s'", req->databaseNames[i]);
1558 yaz_log_zquery(req->query);
1560 if (assoc->init->bend_search)
1562 bsrr->setname = req->resultSetName;
1563 bsrr->replace_set = *req->replaceIndicator;
1564 bsrr->num_bases = req->num_databaseNames;
1565 bsrr->basenames = req->databaseNames;
1566 bsrr->query = req->query;
1567 bsrr->stream = assoc->encode;
1568 bsrr->decode = assoc->decode;
1569 bsrr->print = assoc->print;
1572 bsrr->errstring = NULL;
1573 bsrr->search_info = NULL;
1574 (assoc->init->bend_search)(assoc->backend, bsrr);
1578 return response_searchRequest(assoc, reqb, bsrr, fd);
1581 int bend_searchresponse(void *handle, bend_search_rr *bsrr) {return 0;}
1584 * Prepare a searchresponse based on the backend results. We probably want
1585 * to look at making the fetching of records nonblocking as well, but
1586 * so far, we'll keep things simple.
1587 * If bsrt is null, that means we're called in response to a communications
1588 * event, and we'll have to get the response for ourselves.
1590 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
1591 bend_search_rr *bsrt, int *fd)
1593 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
1594 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1595 Z_SearchResponse *resp = (Z_SearchResponse *)
1596 odr_malloc (assoc->encode, sizeof(*resp));
1597 int *nulint = odr_intdup (assoc->encode, 0);
1598 bool_t *sr = odr_intdup(assoc->encode, 1);
1599 int *next = odr_intdup(assoc->encode, 0);
1600 int *none = odr_intdup(assoc->encode, Z_RES_NONE);
1602 apdu->which = Z_APDU_searchResponse;
1603 apdu->u.searchResponse = resp;
1604 resp->referenceId = req->referenceId;
1605 resp->additionalSearchInfo = 0;
1606 resp->otherInfo = 0;
1608 if (!bsrt && !bend_searchresponse(assoc->backend, bsrt))
1610 yaz_log(LOG_FATAL, "Bad result from backend");
1613 else if (bsrt->errcode)
1615 resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
1616 resp->resultCount = nulint;
1617 resp->numberOfRecordsReturned = nulint;
1618 resp->nextResultSetPosition = nulint;
1619 resp->searchStatus = nulint;
1620 resp->resultSetStatus = none;
1621 resp->presentStatus = 0;
1625 int *toget = odr_intdup(assoc->encode, 0);
1626 int *presst = odr_intdup(assoc->encode, 0);
1627 Z_RecordComposition comp, *compp = 0;
1629 yaz_log (LOG_LOG, "resultCount: %d", bsrt->hits);
1632 resp->resultCount = &bsrt->hits;
1634 comp.which = Z_RecordComp_simple;
1635 /* how many records does the user agent want, then? */
1636 if (bsrt->hits <= *req->smallSetUpperBound)
1638 *toget = bsrt->hits;
1639 if ((comp.u.simple = req->smallSetElementSetNames))
1642 else if (bsrt->hits < *req->largeSetLowerBound)
1644 *toget = *req->mediumSetPresentNumber;
1645 if (*toget > bsrt->hits)
1646 *toget = bsrt->hits;
1647 if ((comp.u.simple = req->mediumSetElementSetNames))
1653 if (*toget && !resp->records)
1658 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
1661 form = prefformat->value;
1662 resp->records = pack_records(assoc, req->resultSetName, 1,
1663 toget, compp, next, presst, form, req->referenceId,
1664 req->preferredRecordSyntax);
1667 resp->numberOfRecordsReturned = toget;
1668 resp->nextResultSetPosition = next;
1669 resp->searchStatus = sr;
1670 resp->resultSetStatus = 0;
1671 resp->presentStatus = presst;
1675 if (*resp->resultCount)
1677 resp->numberOfRecordsReturned = nulint;
1678 resp->nextResultSetPosition = next;
1679 resp->searchStatus = sr;
1680 resp->resultSetStatus = 0;
1681 resp->presentStatus = 0;
1684 resp->additionalSearchInfo = bsrt->search_info;
1689 * Maybe we got a little over-friendly when we designed bend_fetch to
1690 * get only one record at a time. Some backends can optimise multiple-record
1691 * fetches, and at any rate, there is some overhead involved in
1692 * all that selecting and hopping around. Problem is, of course, that the
1693 * frontend can't know ahead of time how many records it'll need to
1694 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
1695 * is downright lousy as a bulk data transfer protocol.
1697 * To start with, we'll do the fetching of records from the backend
1698 * in one operation: To save some trips in and out of the event-handler,
1699 * and to simplify the interface to pack_records. At any rate, asynch
1700 * operation is more fun in operations that have an unpredictable execution
1701 * speed - which is normally more true for search than for present.
1703 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
1706 Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
1710 Z_PresentResponse *resp;
1714 yaz_log(LOG_LOG, "Got PresentRequest.");
1716 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
1719 form = prefformat->value;
1720 resp = (Z_PresentResponse *)odr_malloc (assoc->encode, sizeof(*resp));
1722 resp->presentStatus = odr_intdup(assoc->encode, 0);
1723 if (assoc->init->bend_present)
1725 bend_present_rr *bprr = (bend_present_rr *)
1726 nmem_malloc (reqb->request_mem, sizeof(*bprr));
1727 bprr->setname = req->resultSetId;
1728 bprr->start = *req->resultSetStartPoint;
1729 bprr->number = *req->numberOfRecordsRequested;
1730 bprr->format = form;
1731 bprr->comp = req->recordComposition;
1732 bprr->referenceId = req->referenceId;
1733 bprr->stream = assoc->encode;
1734 bprr->print = assoc->print;
1735 bprr->request = reqb;
1736 bprr->association = assoc;
1738 bprr->errstring = NULL;
1739 (*assoc->init->bend_present)(assoc->backend, bprr);
1745 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
1746 *resp->presentStatus = Z_PRES_FAILURE;
1749 apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1750 next = odr_intdup(assoc->encode, 0);
1751 num = odr_intdup(assoc->encode, 0);
1753 apdu->which = Z_APDU_presentResponse;
1754 apdu->u.presentResponse = resp;
1755 resp->referenceId = req->referenceId;
1756 resp->otherInfo = 0;
1760 *num = *req->numberOfRecordsRequested;
1762 pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
1763 num, req->recordComposition, next, resp->presentStatus,
1764 form, req->referenceId, req->preferredRecordSyntax);
1768 resp->numberOfRecordsReturned = num;
1769 resp->nextResultSetPosition = next;
1775 * Scan was implemented rather in a hurry, and with support for only the basic
1776 * elements of the service in the backend API. Suggestions are welcome.
1778 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
1780 Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
1781 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1782 Z_ScanResponse *res = (Z_ScanResponse *)
1783 odr_malloc (assoc->encode, sizeof(*res));
1784 int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
1785 int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
1786 Z_ListEntries *ents = (Z_ListEntries *)
1787 odr_malloc (assoc->encode, sizeof(*ents));
1788 Z_DiagRecs *diagrecs_p = NULL;
1790 bend_scan_rr *bsrr = (bend_scan_rr *)
1791 odr_malloc (assoc->encode, sizeof(*bsrr));
1793 yaz_log(LOG_LOG, "Got ScanRequest");
1795 apdu->which = Z_APDU_scanResponse;
1796 apdu->u.scanResponse = res;
1797 res->referenceId = req->referenceId;
1799 /* if step is absent, set it to 0 */
1800 res->stepSize = odr_intdup(assoc->encode, 0);
1802 *res->stepSize = *req->stepSize;
1804 res->scanStatus = scanStatus;
1805 res->numberOfEntriesReturned = numberOfEntriesReturned;
1806 res->positionOfTerm = 0;
1807 res->entries = ents;
1808 ents->num_entries = 0;
1809 ents->entries = NULL;
1810 ents->num_nonsurrogateDiagnostics = 0;
1811 ents->nonsurrogateDiagnostics = NULL;
1812 res->attributeSet = 0;
1815 if (req->databaseNames)
1818 for (i = 0; i < req->num_databaseNames; i++)
1819 yaz_log (LOG_LOG, "Database '%s'", req->databaseNames[i]);
1821 bsrr->num_bases = req->num_databaseNames;
1822 bsrr->basenames = req->databaseNames;
1823 bsrr->num_entries = *req->numberOfTermsRequested;
1824 bsrr->term = req->termListAndStartPoint;
1825 bsrr->referenceId = req->referenceId;
1826 bsrr->stream = assoc->encode;
1827 bsrr->print = assoc->print;
1828 bsrr->step_size = res->stepSize;
1829 if (req->attributeSet &&
1830 (attset = oid_getentbyoid(req->attributeSet)) &&
1831 (attset->oclass == CLASS_ATTSET || attset->oclass == CLASS_GENERAL))
1832 bsrr->attributeset = attset->value;
1834 bsrr->attributeset = VAL_NONE;
1835 log_scan_term (req->termListAndStartPoint, bsrr->attributeset);
1836 bsrr->term_position = req->preferredPositionInResponse ?
1837 *req->preferredPositionInResponse : 1;
1838 ((int (*)(void *, bend_scan_rr *))
1839 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1841 diagrecs_p = diagrecs(assoc, bsrr->errcode, bsrr->errstring);
1845 Z_Entry **tab = (Z_Entry **)
1846 odr_malloc (assoc->encode, sizeof(*tab) * bsrr->num_entries);
1848 if (bsrr->status == BEND_SCAN_PARTIAL)
1849 *scanStatus = Z_Scan_partial_5;
1851 *scanStatus = Z_Scan_success;
1852 ents->entries = tab;
1853 ents->num_entries = bsrr->num_entries;
1854 res->numberOfEntriesReturned = &ents->num_entries;
1855 res->positionOfTerm = &bsrr->term_position;
1856 for (i = 0; i < bsrr->num_entries; i++)
1862 tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
1863 if (bsrr->entries[i].occurrences >= 0)
1865 e->which = Z_Entry_termInfo;
1866 e->u.termInfo = t = (Z_TermInfo *)
1867 odr_malloc(assoc->encode, sizeof(*t));
1868 t->suggestedAttributes = 0;
1870 t->alternativeTerm = 0;
1871 t->byAttributes = 0;
1872 t->otherTermInfo = 0;
1873 t->globalOccurrences = &bsrr->entries[i].occurrences;
1874 t->term = (Z_Term *)
1875 odr_malloc(assoc->encode, sizeof(*t->term));
1876 t->term->which = Z_Term_general;
1877 t->term->u.general = o =
1878 (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
1879 o->buf = (unsigned char *)
1880 odr_malloc(assoc->encode, o->len = o->size =
1881 strlen(bsrr->entries[i].term));
1882 memcpy(o->buf, bsrr->entries[i].term, o->len);
1883 yaz_log(LOG_DEBUG, " term #%d: '%s' (%d)", i,
1884 bsrr->entries[i].term, bsrr->entries[i].occurrences);
1888 Z_DiagRecs *drecs = diagrecs (assoc,
1889 bsrr->entries[i].errcode,
1890 bsrr->entries[i].errstring);
1891 assert (drecs->num_diagRecs == 1);
1892 e->which = Z_Entry_surrogateDiagnostic;
1893 assert (drecs->diagRecs[0]);
1894 e->u.surrogateDiagnostic = drecs->diagRecs[0];
1900 ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
1901 ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
1906 static Z_APDU *process_sortRequest(association *assoc, request *reqb,
1909 Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
1910 Z_SortResponse *res = (Z_SortResponse *)
1911 odr_malloc (assoc->encode, sizeof(*res));
1912 bend_sort_rr *bsrr = (bend_sort_rr *)
1913 odr_malloc (assoc->encode, sizeof(*bsrr));
1915 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1917 yaz_log(LOG_LOG, "Got SortRequest.");
1919 bsrr->num_input_setnames = req->num_inputResultSetNames;
1920 bsrr->input_setnames = req->inputResultSetNames;
1921 bsrr->referenceId = req->referenceId;
1922 bsrr->output_setname = req->sortedResultSetName;
1923 bsrr->sort_sequence = req->sortSequence;
1924 bsrr->stream = assoc->encode;
1925 bsrr->print = assoc->print;
1927 bsrr->sort_status = Z_SortStatus_failure;
1929 bsrr->errstring = 0;
1931 (*assoc->init->bend_sort)(assoc->backend, bsrr);
1933 res->referenceId = bsrr->referenceId;
1934 res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
1935 res->resultSetStatus = 0;
1938 Z_DiagRecs *dr = diagrecs (assoc, bsrr->errcode, bsrr->errstring);
1939 res->diagnostics = dr->diagRecs;
1940 res->num_diagnostics = dr->num_diagRecs;
1944 res->num_diagnostics = 0;
1945 res->diagnostics = 0;
1949 apdu->which = Z_APDU_sortResponse;
1950 apdu->u.sortResponse = res;
1954 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
1957 Z_DeleteResultSetRequest *req =
1958 reqb->apdu_request->u.deleteResultSetRequest;
1959 Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
1960 odr_malloc (assoc->encode, sizeof(*res));
1961 bend_delete_rr *bdrr = (bend_delete_rr *)
1962 odr_malloc (assoc->encode, sizeof(*bdrr));
1963 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1965 yaz_log(LOG_LOG, "Got DeleteRequest.");
1967 bdrr->num_setnames = req->num_resultSetList;
1968 bdrr->setnames = req->resultSetList;
1969 bdrr->stream = assoc->encode;
1970 bdrr->print = assoc->print;
1971 bdrr->function = *req->deleteFunction;
1972 bdrr->referenceId = req->referenceId;
1974 if (bdrr->num_setnames > 0)
1977 bdrr->statuses = (int*)
1978 odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
1979 bdrr->num_setnames);
1980 for (i = 0; i < bdrr->num_setnames; i++)
1981 bdrr->statuses[i] = 0;
1983 (*assoc->init->bend_delete)(assoc->backend, bdrr);
1985 res->referenceId = req->referenceId;
1987 res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
1989 res->deleteListStatuses = 0;
1990 if (bdrr->num_setnames > 0)
1993 res->deleteListStatuses = (Z_ListStatuses *)
1994 odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
1995 res->deleteListStatuses->num = bdrr->num_setnames;
1996 res->deleteListStatuses->elements =
1998 odr_malloc (assoc->encode,
1999 sizeof(*res->deleteListStatuses->elements) *
2000 bdrr->num_setnames);
2001 for (i = 0; i<bdrr->num_setnames; i++)
2003 res->deleteListStatuses->elements[i] =
2005 odr_malloc (assoc->encode,
2006 sizeof(**res->deleteListStatuses->elements));
2007 res->deleteListStatuses->elements[i]->status = bdrr->statuses+i;
2008 res->deleteListStatuses->elements[i]->id =
2009 odr_strdup (assoc->encode, bdrr->setnames[i]);
2013 res->numberNotDeleted = 0;
2014 res->bulkStatuses = 0;
2015 res->deleteMessage = 0;
2018 apdu->which = Z_APDU_deleteResultSetResponse;
2019 apdu->u.deleteResultSetResponse = res;
2023 static void process_close(association *assoc, request *reqb)
2025 Z_Close *req = reqb->apdu_request->u.close;
2026 static char *reasons[] =
2033 "securityViolation",
2040 yaz_log(LOG_LOG, "Got Close, reason %s, message %s",
2041 reasons[*req->closeReason], req->diagnosticInformation ?
2042 req->diagnosticInformation : "NULL");
2043 if (assoc->version < 3) /* to make do_force respond with close */
2045 do_close_req(assoc, Z_Close_finished,
2046 "Association terminated by client", reqb);
2049 void save_referenceId (request *reqb, Z_ReferenceId *refid)
2053 reqb->len_refid = refid->len;
2054 reqb->refid = (char *)nmem_malloc (reqb->request_mem, refid->len);
2055 memcpy (reqb->refid, refid->buf, refid->len);
2059 reqb->len_refid = 0;
2064 void bend_request_send (bend_association a, bend_request req, Z_APDU *res)
2066 process_z_response (a, req, res);
2069 bend_request bend_request_mk (bend_association a)
2071 request *nreq = request_get (&a->outgoing);
2072 nreq->request_mem = nmem_create ();
2076 Z_ReferenceId *bend_request_getid (ODR odr, bend_request req)
2081 id = (Odr_oct *)odr_malloc (odr, sizeof(*odr));
2082 id->buf = (unsigned char *)odr_malloc (odr, req->len_refid);
2083 id->len = id->size = req->len_refid;
2084 memcpy (id->buf, req->refid, req->len_refid);
2088 void bend_request_destroy (bend_request *req)
2090 nmem_destroy((*req)->request_mem);
2091 request_release(*req);
2095 int bend_backend_respond (bend_association a, bend_request req)
2099 r = process_z_request (a, req, &msg);
2101 yaz_log (LOG_WARN, "%s", msg);
2105 void bend_request_setdata(bend_request r, void *p)
2110 void *bend_request_getdata(bend_request r)
2112 return r->clientData;
2115 static Z_APDU *process_segmentRequest (association *assoc, request *reqb)
2117 bend_segment_rr req;
2119 req.segment = reqb->apdu_request->u.segmentRequest;
2120 req.stream = assoc->encode;
2121 req.decode = assoc->decode;
2122 req.print = assoc->print;
2123 req.association = assoc;
2125 (*assoc->init->bend_segment)(assoc->backend, &req);
2130 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd)
2132 bend_esrequest_rr esrequest;
2134 Z_ExtendedServicesRequest *req =
2135 reqb->apdu_request->u.extendedServicesRequest;
2136 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
2138 Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
2140 yaz_log(LOG_DEBUG,"inside Process esRequest");
2142 esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
2143 esrequest.stream = assoc->encode;
2144 esrequest.decode = assoc->decode;
2145 esrequest.print = assoc->print;
2146 esrequest.errcode = 0;
2147 esrequest.errstring = NULL;
2148 esrequest.request = reqb;
2149 esrequest.association = assoc;
2150 esrequest.taskPackage = 0;
2151 esrequest.referenceId = req->referenceId;
2153 (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
2155 /* If the response is being delayed, return NULL */
2156 if (esrequest.request == NULL)
2159 resp->referenceId = req->referenceId;
2161 if (esrequest.errcode == -1)
2163 /* Backend service indicates request will be processed */
2164 yaz_log(LOG_DEBUG,"Request could be processed...Accepted !");
2165 *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
2167 else if (esrequest.errcode == 0)
2169 /* Backend service indicates request will be processed */
2170 yaz_log(LOG_DEBUG,"Request could be processed...Done !");
2171 *resp->operationStatus = Z_ExtendedServicesResponse_done;
2175 Z_DiagRecs *diagRecs = diagrecs (assoc, esrequest.errcode,
2176 esrequest.errstring);
2178 /* Backend indicates error, request will not be processed */
2179 yaz_log(LOG_DEBUG,"Request could not be processed...failure !");
2180 *resp->operationStatus = Z_ExtendedServicesResponse_failure;
2181 resp->num_diagnostics = diagRecs->num_diagRecs;
2182 resp->diagnostics = diagRecs->diagRecs;
2184 /* Do something with the members of bend_extendedservice */
2185 if (esrequest.taskPackage)
2186 resp->taskPackage = z_ext_record (assoc->encode, VAL_EXTENDED,
2187 (const char *) esrequest.taskPackage,
2189 yaz_log(LOG_DEBUG,"Send the result apdu");