2 * Copyright (c) 1995-2003, Index Data
3 * See the file LICENSE for details.
5 * $Id: seshigh.c,v 1.141 2003-02-18 14:28:52 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>
59 #include <yaz/backend.h>
61 static void process_gdu_request(association *assoc, request *req);
62 static int process_z_request(association *assoc, request *req, char **msg);
63 void backend_response(IOCHAN i, int event);
64 static int process_gdu_response(association *assoc, request *req, Z_GDU *res);
65 static int process_z_response(association *assoc, request *req, Z_APDU *res);
66 static Z_APDU *process_initRequest(association *assoc, request *reqb);
67 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
69 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
70 bend_search_rr *bsrr, int *fd);
71 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
73 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
74 static Z_APDU *process_sortRequest(association *assoc, request *reqb, int *fd);
75 static void process_close(association *assoc, request *reqb);
76 void save_referenceId (request *reqb, Z_ReferenceId *refid);
77 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
79 static Z_APDU *process_segmentRequest (association *assoc, request *reqb);
81 static FILE *apduf = 0; /* for use in static mode */
82 static statserv_options_block *control_block = 0;
84 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd);
87 * Create and initialize a new association-handle.
88 * channel : iochannel for the current line.
89 * link : communications channel.
90 * Returns: 0 or a new association handle.
92 association *create_association(IOCHAN channel, COMSTACK link)
97 control_block = statserv_getcontrol();
98 if (!(anew = (association *)xmalloc(sizeof(*anew))))
101 anew->client_chan = channel;
102 anew->client_link = link;
103 anew->cs_get_mask = 0;
104 anew->cs_put_mask = 0;
105 anew->cs_accept_mask = 0;
106 if (!(anew->decode = odr_createmem(ODR_DECODE)) ||
107 !(anew->encode = odr_createmem(ODR_ENCODE)))
109 if (*control_block->apdufile)
114 strcpy(filename, control_block->apdufile);
115 if (!(anew->print = odr_createmem(ODR_PRINT)))
117 if (*control_block->apdufile == '@')
119 odr_setprint(anew->print, yaz_log_file());
121 else if (*control_block->apdufile != '-')
123 strcpy(filename, control_block->apdufile);
124 if (!control_block->dynamic)
128 if (!(apduf = fopen(filename, "w")))
130 yaz_log(LOG_WARN|LOG_ERRNO, "%s", filename);
133 setvbuf(apduf, 0, _IONBF, 0);
139 sprintf(filename + strlen(filename), ".%d", getpid());
140 if (!(f = fopen(filename, "w")))
142 yaz_log(LOG_WARN|LOG_ERRNO, "%s", filename);
145 setvbuf(f, 0, _IONBF, 0);
147 odr_setprint(anew->print, f);
152 anew->input_buffer = 0;
153 anew->input_buffer_len = 0;
155 anew->state = ASSOC_NEW;
156 request_initq(&anew->incoming);
157 request_initq(&anew->outgoing);
158 anew->proto = cs_getproto(link);
163 * Free association and release resources.
165 void destroy_association(association *h)
167 statserv_options_block *cb = statserv_getcontrol();
170 odr_destroy(h->decode);
171 odr_destroy(h->encode);
173 odr_destroy(h->print);
175 xfree(h->input_buffer);
177 (*cb->bend_close)(h->backend);
178 while (request_deq(&h->incoming));
179 while (request_deq(&h->outgoing));
180 request_delq(&h->incoming);
181 request_delq(&h->outgoing);
183 xmalloc_trav("session closed");
184 if (control_block && control_block->one_shot)
190 static void do_close_req(association *a, int reason, char *message,
194 Z_Close *cls = zget_Close(a->encode);
196 /* Purge request queue */
197 while (request_deq(&a->incoming));
198 while (request_deq(&a->outgoing));
201 yaz_log(LOG_LOG, "Sending Close PDU, reason=%d, message=%s",
202 reason, message ? message : "none");
203 apdu.which = Z_APDU_close;
205 *cls->closeReason = reason;
206 cls->diagnosticInformation = message;
207 process_z_response(a, req, &apdu);
208 iochan_settimeout(a->client_chan, 20);
212 yaz_log(LOG_DEBUG, "v2 client. No Close PDU");
213 iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
215 a->state = ASSOC_DEAD;
218 static void do_close(association *a, int reason, char *message)
220 do_close_req (a, reason, message, request_get(&a->outgoing));
224 * This is where PDUs from the client are read and the further
225 * processing is initiated. Flow of control moves down through the
226 * various process_* functions below, until the encoded result comes back up
227 * to the output handler in here.
229 * h : the I/O channel that has an outstanding event.
230 * event : the current outstanding event.
232 void ir_session(IOCHAN h, int event)
235 association *assoc = (association *)iochan_getdata(h);
236 COMSTACK conn = assoc->client_link;
239 assert(h && conn && assoc);
240 if (event == EVENT_TIMEOUT)
242 if (assoc->state != ASSOC_UP)
244 yaz_log(LOG_LOG, "Final timeout - closing connection.");
246 destroy_association(assoc);
251 yaz_log(LOG_LOG, "Session idle too long. Sending close.");
252 do_close(assoc, Z_Close_lackOfActivity, 0);
256 if (event & assoc->cs_accept_mask)
258 yaz_log (LOG_DEBUG, "ir_session (accept)");
259 if (!cs_accept (conn))
261 yaz_log (LOG_LOG, "accept failed");
262 destroy_association(assoc);
265 iochan_clearflag (h, EVENT_OUTPUT|EVENT_OUTPUT);
266 if (conn->io_pending)
267 { /* cs_accept didn't complete */
268 assoc->cs_accept_mask =
269 ((conn->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
270 ((conn->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
272 iochan_setflag (h, assoc->cs_accept_mask);
275 { /* cs_accept completed. Prepare for reading (cs_get) */
276 assoc->cs_accept_mask = 0;
277 assoc->cs_get_mask = EVENT_INPUT;
278 iochan_setflag (h, assoc->cs_get_mask);
282 if ((event & assoc->cs_get_mask) || (event & EVENT_WORK)) /* input */
284 if ((assoc->cs_put_mask & EVENT_INPUT) == 0 && (event & assoc->cs_get_mask))
286 yaz_log(LOG_DEBUG, "ir_session (input)");
287 /* We aren't speaking to this fellow */
288 if (assoc->state == ASSOC_DEAD)
290 yaz_log(LOG_LOG, "Connection closed - end of session");
292 destroy_association(assoc);
296 assoc->cs_get_mask = EVENT_INPUT;
297 if ((res = cs_get(conn, &assoc->input_buffer,
298 &assoc->input_buffer_len)) <= 0)
300 yaz_log(LOG_LOG, "Connection closed by client");
302 destroy_association(assoc);
306 else if (res == 1) /* incomplete read - wait for more */
308 if (conn->io_pending & CS_WANT_WRITE)
309 assoc->cs_get_mask |= EVENT_OUTPUT;
310 iochan_setflag(h, assoc->cs_get_mask);
313 if (cs_more(conn)) /* more stuff - call us again later, please */
314 iochan_setevent(h, EVENT_INPUT);
316 /* we got a complete PDU. Let's decode it */
317 yaz_log(LOG_DEBUG, "Got PDU, %d bytes: lead=%02X %02X %02X", res,
318 assoc->input_buffer[0] & 0xff,
319 assoc->input_buffer[1] & 0xff,
320 assoc->input_buffer[2] & 0xff);
321 req = request_get(&assoc->incoming); /* get a new request structure */
322 odr_reset(assoc->decode);
323 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
324 if (!z_GDU(assoc->decode, &req->gdu_request, 0, 0))
326 yaz_log(LOG_LOG, "ODR error on incoming PDU: %s [near byte %d] ",
327 odr_errmsg(odr_geterror(assoc->decode)),
328 odr_offset(assoc->decode));
329 if (assoc->decode->error != OHTTP)
331 yaz_log(LOG_LOG, "PDU dump:");
332 odr_dumpBER(yaz_log_file(), assoc->input_buffer, res);
333 do_close(assoc, Z_Close_protocolError, "Malformed package");
337 Z_GDU *p = z_get_HTTP_Response(assoc->encode, 400);
338 assoc->state = ASSOC_DEAD;
339 process_gdu_response(assoc, req, p);
343 req->request_mem = odr_extract_mem(assoc->decode);
344 if (assoc->print && !z_GDU(assoc->print, &req->gdu_request, 0, 0))
346 yaz_log(LOG_WARN, "ODR print error: %s",
347 odr_errmsg(odr_geterror(assoc->print)));
348 odr_reset(assoc->print);
350 request_enq(&assoc->incoming, req);
353 /* can we do something yet? */
354 req = request_head(&assoc->incoming);
355 if (req->state == REQUEST_IDLE)
357 request_deq(&assoc->incoming);
358 process_gdu_request(assoc, req);
361 if (event & assoc->cs_put_mask)
363 request *req = request_head(&assoc->outgoing);
365 assoc->cs_put_mask = 0;
366 yaz_log(LOG_DEBUG, "ir_session (output)");
367 req->state = REQUEST_PENDING;
368 switch (res = cs_put(conn, req->response, req->len_response))
371 yaz_log(LOG_LOG, "Connection closed by client");
373 destroy_association(assoc);
376 case 0: /* all sent - release the request structure */
377 yaz_log(LOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
379 yaz_log(LOG_DEBUG, "HTTP out:\n%.*s", req->len_response,
382 nmem_destroy(req->request_mem);
383 request_deq(&assoc->outgoing);
384 request_release(req);
385 if (!request_head(&assoc->outgoing))
386 { /* restore mask for cs_get operation ... */
387 iochan_clearflag(h, EVENT_OUTPUT|EVENT_INPUT);
388 iochan_setflag(h, assoc->cs_get_mask);
389 if (assoc->state == ASSOC_DEAD)
390 iochan_setevent(assoc->client_chan, EVENT_TIMEOUT);
394 assoc->cs_put_mask = EVENT_OUTPUT;
398 if (conn->io_pending & CS_WANT_WRITE)
399 assoc->cs_put_mask |= EVENT_OUTPUT;
400 if (conn->io_pending & CS_WANT_READ)
401 assoc->cs_put_mask |= EVENT_INPUT;
402 iochan_setflag(h, assoc->cs_put_mask);
405 if (event & EVENT_EXCEPT)
407 yaz_log(LOG_LOG, "ir_session (exception)");
409 destroy_association(assoc);
414 static int process_z_request(association *assoc, request *req, char **msg);
416 static int srw_bend_init(association *assoc)
418 bend_initresult *binitres;
419 statserv_options_block *cb = statserv_getcontrol();
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;
442 assoc->init->peer_name =
443 odr_strdup (assoc->encode, cs_addrstr(assoc->client_link));
444 if (!(binitres = (*cb->bend_init)(assoc->init)))
446 yaz_log(LOG_WARN, "Bad response from backend.");
449 assoc->backend = binitres->handle;
453 static void srw_bend_fetch(association *assoc, int pos,
454 Z_SRW_searchRetrieveRequest *srw_req,
455 Z_SRW_record *record)
458 ODR o = assoc->encode;
460 rr.setname = "default";
463 rr.request_format = VAL_TEXT_XML;
464 rr.request_format_raw = yaz_oidval_to_z3950oid(assoc->decode,
467 rr.comp = (Z_RecordComposition *)
468 odr_malloc(assoc->decode, sizeof(*rr.comp));
469 rr.comp->which = Z_RecordComp_complex;
470 rr.comp->u.complex = (Z_CompSpec *)
471 odr_malloc(assoc->decode, sizeof(Z_CompSpec));
472 rr.comp->u.complex->selectAlternativeSyntax = (bool_t *)
473 odr_malloc(assoc->encode, sizeof(bool_t));
474 *rr.comp->u.complex->selectAlternativeSyntax = 0;
475 rr.comp->u.complex->num_dbSpecific = 0;
476 rr.comp->u.complex->dbSpecific = 0;
477 rr.comp->u.complex->num_recordSyntax = 0;
478 rr.comp->u.complex->recordSyntax = 0;
480 rr.comp->u.complex->generic = (Z_Specification *)
481 odr_malloc(assoc->decode, sizeof(Z_Specification));
482 rr.comp->u.complex->generic->which = Z_Schema_uri;
483 rr.comp->u.complex->generic->schema.uri = srw_req->recordSchema;
484 rr.comp->u.complex->generic->elementSpec = 0;
486 rr.stream = assoc->encode;
487 rr.print = assoc->print;
493 rr.output_format = VAL_TEXT_XML;
494 rr.output_format_raw = 0;
497 rr.surrogate_flag = 0;
499 (*assoc->init->bend_fetch)(assoc->backend, &rr);
503 record->recordData_buf = rr.record;
504 record->recordData_len = rr.len;
505 record->recordPosition = odr_intdup(o, pos);
506 record->recordSchema = 0;
507 if (srw_req->recordSchema)
508 record->recordSchema = odr_strdup(o, srw_req->recordSchema);
512 static void srw_bend_search(association *assoc, request *req,
513 Z_SRW_searchRetrieveRequest *srw_req,
514 Z_SRW_searchRetrieveResponse *srw_res)
516 char *base = "Default";
520 yaz_log(LOG_LOG, "Got SRW SearchRetrieveRequest");
523 srw_bend_init(assoc);
525 rr.setname = "default";
528 rr.basenames = &srw_req->database;
531 ext = (Z_External *) odr_malloc(assoc->decode, sizeof(*ext));
532 ext->direct_reference = odr_getoidbystr(assoc->decode,
533 "1.2.840.10003.16.2");
534 ext->indirect_reference = 0;
536 ext->which = Z_External_CQL;
538 ext->u.cql = srw_req->query;
540 ext->u.cql = "noterm";
542 rr.query = (Z_Query *) odr_malloc (assoc->decode, sizeof(*rr.query));
543 rr.query->which = Z_Query_type_104;
544 rr.query->u.type_104 = ext;
546 rr.stream = assoc->encode;
547 rr.decode = assoc->decode;
548 rr.print = assoc->print;
550 rr.association = assoc;
556 yaz_log_zquery(rr.query);
557 (assoc->init->bend_search)(assoc->backend, &rr);
558 srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
561 srw_res->num_diagnostics = 1;
562 srw_res->diagnostics = (Z_SRW_diagnostic *)
563 odr_malloc(assoc->encode, sizeof(*srw_res->diagnostics));
564 srw_res->diagnostics[0].code =
565 odr_intdup(assoc->encode, rr.errcode);
566 srw_res->diagnostics[0].details = rr.errstring;
570 srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
571 if (srw_req->maximumRecords && *srw_req->maximumRecords > 0)
573 int number = *srw_req->maximumRecords;
576 if (srw_req->startRecord)
577 start = *srw_req->startRecord;
578 if (start <= rr.hits)
581 if (start + number > rr.hits)
582 number = rr.hits - start + 1;
583 srw_res->records = (Z_SRW_record *)
584 odr_malloc(assoc->encode,
585 number * sizeof(*srw_res->records));
586 for (i = 0; i<number; i++)
588 srw_res->records[j].recordData_buf = 0;
589 srw_bend_fetch(assoc, i+start, srw_req,
590 srw_res->records + j);
591 if (srw_res->records[j].recordData_buf)
594 srw_res->num_records = j;
596 srw_res->records = 0;
602 static void process_http_request(association *assoc, request *req)
604 Z_HTTP_Request *hreq = req->gdu_request->u.HTTP_Request;
605 ODR o = assoc->encode;
607 Z_HTTP_Response *hres = 0;
610 if (!strcmp(hreq->method, "GET"))
613 if (strlen(hreq->path) >= 5 && strlen(hreq->path) < 80 &&
614 !memcmp(hreq->path, "/doc/", 5))
619 strcpy(fpath, DOCDIR);
620 strcat(fpath, hreq->path+4);
621 f = fopen(fpath, "rb");
624 if (fstat(fileno(f), &sbuf) || !S_ISREG(sbuf.st_mode))
633 fseek(f, 0L, SEEK_END);
635 if (sz >= 0 && sz < 500000)
637 const char *ctype = "application/octet-stream";
640 p = z_get_HTTP_Response(o, 200);
641 hres = p->u.HTTP_Response;
642 hres->content_buf = (char *) odr_malloc(o, sz + 1);
643 hres->content_len = sz;
644 fseek(f, 0L, SEEK_SET);
645 fread(hres->content_buf, 1, sz, f);
646 if ((cp = strrchr(fpath, '.'))) {
648 if (!strcmp(cp, "png"))
650 else if (!strcmp(cp, "gif"))
652 else if (!strcmp(cp, "xml"))
654 else if (!strcmp(cp, "html"))
657 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
663 if (!strcmp(hreq->path, "/"))
668 const char *doclink = "";
669 p = z_get_HTTP_Response(o, 200);
670 hres = p->u.HTTP_Response;
671 hres->content_buf = (char *) odr_malloc(o, 400);
673 if (stat(DOCDIR "/yaz.html", &sbuf) == 0 && S_ISREG(sbuf.st_mode))
674 doclink = "<P><A HREF=\"/doc/yaz.html\">Documentation</A></P>";
676 sprintf (hres->content_buf,
677 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n"
680 " <TITLE>YAZ " YAZ_VERSION "</TITLE>\n"
683 " <P><A HREF=\"http://www.indexdata.dk/yaz/\">YAZ</A> "
687 "</HTML>\n", doclink);
688 hres->content_len = strlen(hres->content_buf);
689 z_HTTP_header_add(o, &hres->headers, "Content-Type", "text/html");
693 p = z_get_HTTP_Response(o, 404);
696 else if (!strcmp(hreq->method, "POST"))
698 const char *content_type = z_HTTP_header_lookup(hreq->headers,
700 const char *soap_action = z_HTTP_header_lookup(hreq->headers,
702 if (content_type && soap_action &&
703 !yaz_strcmp_del("text/xml", content_type, "; "))
705 Z_SOAP *soap_package = 0;
709 static Z_SOAP_Handler soap_handlers[2] = {
710 {"http://www.loc.gov/zing/srw/v1.0/", 0,
711 (Z_SOAP_fun) yaz_srw_codec},
715 ret = z_soap_codec(assoc->decode, &soap_package,
716 &hreq->content_buf, &hreq->content_len,
719 if (!ret && soap_package->which == Z_SOAP_generic &&
720 soap_package->u.generic->no == 0)
723 Z_SRW_searchRetrieve *sr = soap_package->u.generic->p;
725 if (sr->which == Z_SRW_searchRetrieve_request)
727 Z_SRW_searchRetrieve *res =
728 yaz_srw_get(assoc->encode,
729 Z_SRW_searchRetrieve_response);
731 if (!sr->u.request->database)
733 const char *p0 = hreq->path, *p1;
736 p1 = strchr(p0, '?');
738 p1 = p0 + strlen(p0);
741 sr->u.request->database =
742 odr_malloc(assoc->decode, p1 - p0 + 1);
743 memcpy (sr->u.request->database, p0, p1 - p0);
744 sr->u.request->database[p1 - p0] = '\0';
747 sr->u.request->database = "Default";
749 srw_bend_search(assoc, req, sr->u.request,
752 soap_package->u.generic->p = res;
757 p = z_get_HTTP_Response(o, 200);
758 hres = p->u.HTTP_Response;
759 ret = z_soap_codec(assoc->encode, &soap_package,
760 &hres->content_buf, &hres->content_len,
762 hres->code = http_code;
763 z_HTTP_header_add(o, &hres->headers, "Content-Type", "text/xml");
765 if (!p) /* still no response ? */
766 p = z_get_HTTP_Response(o, 500);
770 p = z_get_HTTP_Response(o, 405);
771 hres = p->u.HTTP_Response;
773 z_HTTP_header_add(o, &hres->headers, "Allow", "GET, POST");
775 hres = p->u.HTTP_Response;
776 if (!strcmp(hreq->version, "1.0"))
778 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
779 if (v && !strcmp(v, "Keep-Alive"))
783 hres->version = "1.0";
787 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
788 if (v && !strcmp(v, "close"))
792 hres->version = "1.1";
796 z_HTTP_header_add(o, &hres->headers, "Connection", "close");
797 assoc->state = ASSOC_DEAD;
802 const char *alive = z_HTTP_header_lookup(hreq->headers, "Keep-Alive");
804 if (alive && isdigit(*alive))
808 if (t < 0 || t > 3600)
810 iochan_settimeout(assoc->client_chan,t);
811 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
813 process_gdu_response(assoc, req, p);
816 static void process_gdu_request(association *assoc, request *req)
818 if (req->gdu_request->which == Z_GDU_Z3950)
821 req->apdu_request = req->gdu_request->u.z3950;
822 if (process_z_request(assoc, req, &msg) < 0)
823 do_close_req(assoc, Z_Close_systemProblem, msg, req);
825 else if (req->gdu_request->which == Z_GDU_HTTP_Request)
826 process_http_request(assoc, req);
829 do_close_req(assoc, Z_Close_systemProblem, "bad protocol packet", req);
834 * Initiate request processing.
836 static int process_z_request(association *assoc, request *req, char **msg)
842 *msg = "Unknown Error";
843 assert(req && req->state == REQUEST_IDLE);
844 if (req->apdu_request->which != Z_APDU_initRequest && !assoc->init)
846 *msg = "Missing InitRequest";
849 switch (req->apdu_request->which)
851 case Z_APDU_initRequest:
852 iochan_settimeout(assoc->client_chan,
853 statserv_getcontrol()->idle_timeout * 60);
854 res = process_initRequest(assoc, req); break;
855 case Z_APDU_searchRequest:
856 res = process_searchRequest(assoc, req, &fd); break;
857 case Z_APDU_presentRequest:
858 res = process_presentRequest(assoc, req, &fd); break;
859 case Z_APDU_scanRequest:
860 if (assoc->init->bend_scan)
861 res = process_scanRequest(assoc, req, &fd);
864 *msg = "Cannot handle Scan APDU";
868 case Z_APDU_extendedServicesRequest:
869 if (assoc->init->bend_esrequest)
870 res = process_ESRequest(assoc, req, &fd);
873 *msg = "Cannot handle Extended Services APDU";
877 case Z_APDU_sortRequest:
878 if (assoc->init->bend_sort)
879 res = process_sortRequest(assoc, req, &fd);
882 *msg = "Cannot handle Sort APDU";
887 process_close(assoc, req);
889 case Z_APDU_deleteResultSetRequest:
890 if (assoc->init->bend_delete)
891 res = process_deleteRequest(assoc, req, &fd);
894 *msg = "Cannot handle Delete APDU";
898 case Z_APDU_segmentRequest:
899 if (assoc->init->bend_segment)
901 res = process_segmentRequest (assoc, req);
905 *msg = "Cannot handle Segment APDU";
910 *msg = "Bad APDU received";
915 yaz_log(LOG_DEBUG, " result immediately available");
916 retval = process_z_response(assoc, req, res);
920 yaz_log(LOG_DEBUG, " result unavailble");
923 else /* no result yet - one will be provided later */
927 /* Set up an I/O handler for the fd supplied by the backend */
929 yaz_log(LOG_DEBUG, " establishing handler for result");
930 req->state = REQUEST_PENDING;
931 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT)))
933 iochan_setdata(chan, assoc);
940 * Handle message from the backend.
942 void backend_response(IOCHAN i, int event)
944 association *assoc = (association *)iochan_getdata(i);
945 request *req = request_head(&assoc->incoming);
949 yaz_log(LOG_DEBUG, "backend_response");
950 assert(assoc && req && req->state != REQUEST_IDLE);
951 /* determine what it is we're waiting for */
952 switch (req->apdu_request->which)
954 case Z_APDU_searchRequest:
955 res = response_searchRequest(assoc, req, 0, &fd); break;
957 case Z_APDU_presentRequest:
958 res = response_presentRequest(assoc, req, 0, &fd); break;
959 case Z_APDU_scanRequest:
960 res = response_scanRequest(assoc, req, 0, &fd); break;
963 yaz_log(LOG_WARN, "Serious programmer's lapse or bug");
966 if ((res && process_z_response(assoc, req, res) < 0) || fd < 0)
968 yaz_log(LOG_LOG, "Fatal error when talking to backend");
969 do_close(assoc, Z_Close_systemProblem, 0);
973 else if (!res) /* no result yet - try again later */
975 yaz_log(LOG_DEBUG, " no result yet");
976 iochan_setfd(i, fd); /* in case fd has changed */
981 * Encode response, and transfer the request structure to the outgoing queue.
983 static int process_gdu_response(association *assoc, request *req, Z_GDU *res)
985 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
987 if (assoc->print && !z_GDU(assoc->print, &res, 0, 0))
989 yaz_log(LOG_WARN, "ODR print error: %s",
990 odr_errmsg(odr_geterror(assoc->print)));
991 odr_reset(assoc->print);
993 if (!z_GDU(assoc->encode, &res, 0, 0))
995 yaz_log(LOG_WARN, "ODR error when encoding response: %s",
996 odr_errmsg(odr_geterror(assoc->decode)));
999 req->response = odr_getbuf(assoc->encode, &req->len_response,
1000 &req->size_response);
1001 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
1002 odr_reset(assoc->encode);
1003 req->state = REQUEST_IDLE;
1004 request_enq(&assoc->outgoing, req);
1005 /* turn the work over to the ir_session handler */
1006 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
1007 assoc->cs_put_mask = EVENT_OUTPUT;
1008 /* Is there more work to be done? give that to the input handler too */
1010 if (request_head(&assoc->incoming))
1012 yaz_log (LOG_DEBUG, "more work to be done");
1013 iochan_setevent(assoc->client_chan, EVENT_WORK);
1020 * Encode response, and transfer the request structure to the outgoing queue.
1022 static int process_z_response(association *assoc, request *req, Z_APDU *res)
1024 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
1026 if (assoc->print && !z_APDU(assoc->print, &res, 0, 0))
1028 yaz_log(LOG_WARN, "ODR print error: %s",
1029 odr_errmsg(odr_geterror(assoc->print)));
1030 odr_reset(assoc->print);
1032 if (!z_APDU(assoc->encode, &res, 0, 0))
1034 yaz_log(LOG_WARN, "ODR error when encoding response: %s",
1035 odr_errmsg(odr_geterror(assoc->decode)));
1038 req->response = odr_getbuf(assoc->encode, &req->len_response,
1039 &req->size_response);
1040 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
1041 odr_reset(assoc->encode);
1042 req->state = REQUEST_IDLE;
1043 request_enq(&assoc->outgoing, req);
1044 /* turn the work over to the ir_session handler */
1045 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
1046 assoc->cs_put_mask = EVENT_OUTPUT;
1047 /* Is there more work to be done? give that to the input handler too */
1049 if (request_head(&assoc->incoming))
1051 yaz_log (LOG_DEBUG, "more work to be done");
1052 iochan_setevent(assoc->client_chan, EVENT_WORK);
1059 * Handle init request.
1060 * At the moment, we don't check the options
1061 * anywhere else in the code - we just try not to do anything that would
1062 * break a naive client. We'll toss 'em into the association block when
1063 * we need them there.
1065 static Z_APDU *process_initRequest(association *assoc, request *reqb)
1067 statserv_options_block *cb = statserv_getcontrol();
1068 Z_InitRequest *req = reqb->apdu_request->u.initRequest;
1069 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
1070 Z_InitResponse *resp = apdu->u.initResponse;
1071 bend_initresult *binitres;
1075 xfree (assoc->init);
1076 assoc->init = (bend_initrequest *) xmalloc (sizeof(*assoc->init));
1078 yaz_log(LOG_LOG, "Got initRequest");
1079 if (req->implementationId)
1080 yaz_log(LOG_LOG, "Id: %s", req->implementationId);
1081 if (req->implementationName)
1082 yaz_log(LOG_LOG, "Name: %s", req->implementationName);
1083 if (req->implementationVersion)
1084 yaz_log(LOG_LOG, "Version: %s", req->implementationVersion);
1086 assoc->init->stream = assoc->encode;
1087 assoc->init->print = assoc->print;
1088 assoc->init->auth = req->idAuthentication;
1089 assoc->init->referenceId = req->referenceId;
1090 assoc->init->implementation_version = 0;
1091 assoc->init->implementation_id = 0;
1092 assoc->init->implementation_name = 0;
1093 assoc->init->bend_sort = NULL;
1094 assoc->init->bend_search = NULL;
1095 assoc->init->bend_present = NULL;
1096 assoc->init->bend_esrequest = NULL;
1097 assoc->init->bend_delete = NULL;
1098 assoc->init->bend_scan = NULL;
1099 assoc->init->bend_segment = NULL;
1100 assoc->init->bend_fetch = NULL;
1101 assoc->init->charneg_request = NULL;
1102 assoc->init->charneg_response = NULL;
1103 assoc->init->decode = assoc->decode;
1105 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
1107 Z_CharSetandLanguageNegotiation *negotiation =
1108 yaz_get_charneg_record (req->otherInfo);
1109 if (negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
1110 assoc->init->charneg_request = negotiation;
1113 assoc->init->peer_name =
1114 odr_strdup (assoc->encode, cs_addrstr(assoc->client_link));
1115 if (!(binitres = (*cb->bend_init)(assoc->init)))
1117 yaz_log(LOG_WARN, "Bad response from backend.");
1121 assoc->backend = binitres->handle;
1122 if ((assoc->init->bend_sort))
1123 yaz_log (LOG_DEBUG, "Sort handler installed");
1124 if ((assoc->init->bend_search))
1125 yaz_log (LOG_DEBUG, "Search handler installed");
1126 if ((assoc->init->bend_present))
1127 yaz_log (LOG_DEBUG, "Present handler installed");
1128 if ((assoc->init->bend_esrequest))
1129 yaz_log (LOG_DEBUG, "ESRequest handler installed");
1130 if ((assoc->init->bend_delete))
1131 yaz_log (LOG_DEBUG, "Delete handler installed");
1132 if ((assoc->init->bend_scan))
1133 yaz_log (LOG_DEBUG, "Scan handler installed");
1134 if ((assoc->init->bend_segment))
1135 yaz_log (LOG_DEBUG, "Segment handler installed");
1137 resp->referenceId = req->referenceId;
1139 /* let's tell the client what we can do */
1140 if (ODR_MASK_GET(req->options, Z_Options_search))
1142 ODR_MASK_SET(resp->options, Z_Options_search);
1143 strcat(options, "srch");
1145 if (ODR_MASK_GET(req->options, Z_Options_present))
1147 ODR_MASK_SET(resp->options, Z_Options_present);
1148 strcat(options, " prst");
1150 if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
1151 assoc->init->bend_delete)
1153 ODR_MASK_SET(resp->options, Z_Options_delSet);
1154 strcat(options, " del");
1156 if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
1157 assoc->init->bend_esrequest)
1159 ODR_MASK_SET(resp->options, Z_Options_extendedServices);
1160 strcat (options, " extendedServices");
1162 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
1164 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
1165 strcat(options, " namedresults");
1167 if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
1169 ODR_MASK_SET(resp->options, Z_Options_scan);
1170 strcat(options, " scan");
1172 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
1174 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
1175 strcat(options, " concurrop");
1177 if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
1179 ODR_MASK_SET(resp->options, Z_Options_sort);
1180 strcat(options, " sort");
1183 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel)
1184 && assoc->init->charneg_response)
1186 Z_OtherInformation **p;
1187 Z_OtherInformationUnit *p0;
1189 yaz_oi_APDU(apdu, &p);
1191 if ((p0=yaz_oi_update(p, assoc->encode, NULL, 0, 0))) {
1192 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
1194 p0->which = Z_OtherInfo_externallyDefinedInfo;
1195 p0->information.externallyDefinedInfo =
1196 assoc->init->charneg_response;
1198 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
1199 strcat(options, " negotiation");
1202 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
1204 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
1205 assoc->version = 2; /* 1 & 2 are equivalent */
1207 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
1209 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
1212 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
1214 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
1218 yaz_log(LOG_LOG, "Negotiated to v%d: %s", assoc->version, options);
1219 assoc->maximumRecordSize = *req->maximumRecordSize;
1220 if (assoc->maximumRecordSize > control_block->maxrecordsize)
1221 assoc->maximumRecordSize = control_block->maxrecordsize;
1222 assoc->preferredMessageSize = *req->preferredMessageSize;
1223 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
1224 assoc->preferredMessageSize = assoc->maximumRecordSize;
1227 assoc->maximumRecordSize = 3000000;
1228 assoc->preferredMessageSize = 3000000;
1231 resp->preferredMessageSize = &assoc->preferredMessageSize;
1232 resp->maximumRecordSize = &assoc->maximumRecordSize;
1234 resp->implementationName = "GFS/YAZ";
1236 if (assoc->init->implementation_id)
1239 odr_malloc (assoc->encode,
1240 strlen(assoc->init->implementation_id) + 10 +
1241 strlen(resp->implementationId));
1242 sprintf (nv, "%s / %s",
1243 resp->implementationId, assoc->init->implementation_id);
1244 resp->implementationId = nv;
1246 if (assoc->init->implementation_name)
1249 odr_malloc (assoc->encode,
1250 strlen(assoc->init->implementation_name) + 10 +
1251 strlen(resp->implementationName));
1252 sprintf (nv, "%s / %s",
1253 resp->implementationName, assoc->init->implementation_name);
1254 resp->implementationName = nv;
1256 if (assoc->init->implementation_version)
1259 odr_malloc (assoc->encode,
1260 strlen(assoc->init->implementation_version) + 10 +
1261 strlen(resp->implementationVersion));
1262 sprintf (nv, "YAZ %s / %s",
1263 resp->implementationVersion,
1264 assoc->init->implementation_version);
1265 resp->implementationVersion = nv;
1268 if (binitres->errcode)
1270 yaz_log(LOG_LOG, "Connection rejected by backend.");
1272 assoc->state = ASSOC_DEAD;
1275 assoc->state = ASSOC_UP;
1280 * These functions should be merged.
1283 static void set_addinfo (Z_DefaultDiagFormat *dr, char *addinfo, ODR odr)
1285 dr->which = Z_DefaultDiagFormat_v2Addinfo;
1286 dr->u.v2Addinfo = odr_strdup (odr, addinfo ? addinfo : "");
1290 * nonsurrogate diagnostic record.
1292 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
1294 Z_Records *rec = (Z_Records *)
1295 odr_malloc (assoc->encode, sizeof(*rec));
1296 int *err = odr_intdup(assoc->encode, error);
1297 Z_DiagRec *drec = (Z_DiagRec *)
1298 odr_malloc (assoc->encode, sizeof(*drec));
1299 Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
1300 odr_malloc (assoc->encode, sizeof(*dr));
1302 yaz_log(LOG_LOG, "[%d] %s %s%s", error, diagbib1_str(error),
1303 addinfo ? " -- " : "", addinfo ? addinfo : "");
1304 rec->which = Z_Records_NSD;
1305 rec->u.nonSurrogateDiagnostic = dr;
1306 dr->diagnosticSetId =
1307 yaz_oidval_to_z3950oid (assoc->encode, CLASS_DIAGSET, VAL_BIB1);
1308 dr->condition = err;
1309 set_addinfo (dr, addinfo, assoc->encode);
1314 * surrogate diagnostic.
1316 static Z_NamePlusRecord *surrogatediagrec(association *assoc, char *dbname,
1317 int error, char *addinfo)
1319 Z_NamePlusRecord *rec = (Z_NamePlusRecord *)
1320 odr_malloc (assoc->encode, sizeof(*rec));
1321 int *err = odr_intdup(assoc->encode, error);
1322 Z_DiagRec *drec = (Z_DiagRec *)odr_malloc (assoc->encode, sizeof(*drec));
1323 Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
1324 odr_malloc (assoc->encode, sizeof(*dr));
1326 yaz_log(LOG_DEBUG, "SurrogateDiagnotic: %d -- %s", error, addinfo);
1327 rec->databaseName = dbname;
1328 rec->which = Z_NamePlusRecord_surrogateDiagnostic;
1329 rec->u.surrogateDiagnostic = drec;
1330 drec->which = Z_DiagRec_defaultFormat;
1331 drec->u.defaultFormat = dr;
1332 dr->diagnosticSetId =
1333 yaz_oidval_to_z3950oid (assoc->encode, CLASS_DIAGSET, VAL_BIB1);
1334 dr->condition = err;
1335 set_addinfo (dr, addinfo, assoc->encode);
1341 * multiple nonsurrogate diagnostics.
1343 static Z_DiagRecs *diagrecs(association *assoc, int error, char *addinfo)
1345 Z_DiagRecs *recs = (Z_DiagRecs *)odr_malloc (assoc->encode, sizeof(*recs));
1346 int *err = odr_intdup(assoc->encode, error);
1347 Z_DiagRec **recp = (Z_DiagRec **)odr_malloc (assoc->encode, sizeof(*recp));
1348 Z_DiagRec *drec = (Z_DiagRec *)odr_malloc (assoc->encode, sizeof(*drec));
1349 Z_DefaultDiagFormat *rec = (Z_DefaultDiagFormat *)
1350 odr_malloc (assoc->encode, sizeof(*rec));
1352 yaz_log(LOG_DEBUG, "DiagRecs: %d -- %s", error, addinfo ? addinfo : "");
1354 recs->num_diagRecs = 1;
1355 recs->diagRecs = recp;
1357 drec->which = Z_DiagRec_defaultFormat;
1358 drec->u.defaultFormat = rec;
1360 rec->diagnosticSetId =
1361 yaz_oidval_to_z3950oid (assoc->encode, CLASS_DIAGSET, VAL_BIB1);
1362 rec->condition = err;
1364 rec->which = Z_DefaultDiagFormat_v2Addinfo;
1365 rec->u.v2Addinfo = odr_strdup (assoc->encode, addinfo ? addinfo : "");
1369 static Z_Records *pack_records(association *a, char *setname, int start,
1370 int *num, Z_RecordComposition *comp,
1371 int *next, int *pres, oid_value format,
1372 Z_ReferenceId *referenceId,
1375 int recno, total_length = 0, toget = *num, dumped_records = 0;
1376 Z_Records *records =
1377 (Z_Records *) odr_malloc (a->encode, sizeof(*records));
1378 Z_NamePlusRecordList *reclist =
1379 (Z_NamePlusRecordList *) odr_malloc (a->encode, sizeof(*reclist));
1380 Z_NamePlusRecord **list =
1381 (Z_NamePlusRecord **) odr_malloc (a->encode, sizeof(*list) * toget);
1383 records->which = Z_Records_DBOSD;
1384 records->u.databaseOrSurDiagnostics = reclist;
1385 reclist->num_records = 0;
1386 reclist->records = list;
1387 *pres = Z_PRES_SUCCESS;
1391 yaz_log(LOG_LOG, "Request to pack %d+%d+%s", start, toget, setname);
1392 yaz_log(LOG_DEBUG, "pms=%d, mrs=%d", a->preferredMessageSize,
1393 a->maximumRecordSize);
1394 for (recno = start; reclist->num_records < toget; recno++)
1397 Z_NamePlusRecord *thisrec;
1398 int this_length = 0;
1400 * we get the number of bytes allocated on the stream before any
1401 * allocation done by the backend - this should give us a reasonable
1402 * idea of the total size of the data so far.
1404 total_length = odr_total(a->encode) - dumped_records;
1410 freq.last_in_set = 0;
1411 freq.setname = setname;
1412 freq.surrogate_flag = 0;
1413 freq.number = recno;
1415 freq.request_format = format;
1416 freq.request_format_raw = oid;
1417 freq.output_format = format;
1418 freq.output_format_raw = 0;
1419 freq.stream = a->encode;
1420 freq.print = a->print;
1421 freq.surrogate_flag = 0;
1422 freq.referenceId = referenceId;
1423 (*a->init->bend_fetch)(a->backend, &freq);
1424 /* backend should be able to signal whether error is system-wide
1425 or only pertaining to current record */
1428 if (!freq.surrogate_flag)
1431 *pres = Z_PRES_FAILURE;
1432 /* for 'present request out of range',
1433 set addinfo to record position if not set */
1434 if (freq.errcode == 13 && freq.errstring == 0)
1436 sprintf (s, "%d", recno);
1439 return diagrec(a, freq.errcode, freq.errstring);
1441 reclist->records[reclist->num_records] =
1442 surrogatediagrec(a, freq.basename, freq.errcode,
1444 reclist->num_records++;
1445 *next = freq.last_in_set ? 0 : recno + 1;
1449 this_length = freq.len;
1451 this_length = odr_total(a->encode) - total_length;
1452 yaz_log(LOG_DEBUG, " fetched record, len=%d, total=%d",
1453 this_length, total_length);
1454 if (this_length + total_length > a->preferredMessageSize)
1456 /* record is small enough, really */
1457 if (this_length <= a->preferredMessageSize)
1459 yaz_log(LOG_DEBUG, " Dropped last normal-sized record");
1460 *pres = Z_PRES_PARTIAL_2;
1463 /* record can only be fetched by itself */
1464 if (this_length < a->maximumRecordSize)
1466 yaz_log(LOG_DEBUG, " Record > prefmsgsz");
1469 yaz_log(LOG_DEBUG, " Dropped it");
1470 reclist->records[reclist->num_records] =
1471 surrogatediagrec(a, freq.basename, 16, 0);
1472 reclist->num_records++;
1473 *next = freq.last_in_set ? 0 : recno + 1;
1474 dumped_records += this_length;
1478 else /* too big entirely */
1480 yaz_log(LOG_LOG, "Record > maxrcdsz this=%d max=%d", this_length, a->maximumRecordSize);
1481 reclist->records[reclist->num_records] =
1482 surrogatediagrec(a, freq.basename, 17, 0);
1483 reclist->num_records++;
1484 *next = freq.last_in_set ? 0 : recno + 1;
1485 dumped_records += this_length;
1490 if (!(thisrec = (Z_NamePlusRecord *)
1491 odr_malloc(a->encode, sizeof(*thisrec))))
1493 if (!(thisrec->databaseName = (char *)odr_malloc(a->encode,
1494 strlen(freq.basename) + 1)))
1496 strcpy(thisrec->databaseName, freq.basename);
1497 thisrec->which = Z_NamePlusRecord_databaseRecord;
1499 if (freq.output_format_raw)
1501 struct oident *ident = oid_getentbyoid(freq.output_format_raw);
1502 freq.output_format = ident->value;
1504 thisrec->u.databaseRecord = z_ext_record(a->encode, freq.output_format,
1505 freq.record, freq.len);
1506 if (!thisrec->u.databaseRecord)
1508 reclist->records[reclist->num_records] = thisrec;
1509 reclist->num_records++;
1510 *next = freq.last_in_set ? 0 : recno + 1;
1512 *num = reclist->num_records;
1516 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
1519 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
1520 bend_search_rr *bsrr =
1521 (bend_search_rr *)nmem_malloc (reqb->request_mem, sizeof(*bsrr));
1523 yaz_log(LOG_LOG, "Got SearchRequest.");
1525 bsrr->request = reqb;
1526 bsrr->association = assoc;
1527 bsrr->referenceId = req->referenceId;
1528 save_referenceId (reqb, bsrr->referenceId);
1530 yaz_log (LOG_LOG, "ResultSet '%s'", req->resultSetName);
1531 if (req->databaseNames)
1534 for (i = 0; i < req->num_databaseNames; i++)
1535 yaz_log (LOG_LOG, "Database '%s'", req->databaseNames[i]);
1537 yaz_log_zquery(req->query);
1539 if (assoc->init->bend_search)
1541 bsrr->setname = req->resultSetName;
1542 bsrr->replace_set = *req->replaceIndicator;
1543 bsrr->num_bases = req->num_databaseNames;
1544 bsrr->basenames = req->databaseNames;
1545 bsrr->query = req->query;
1546 bsrr->stream = assoc->encode;
1547 bsrr->decode = assoc->decode;
1548 bsrr->print = assoc->print;
1551 bsrr->errstring = NULL;
1552 bsrr->search_info = NULL;
1553 (assoc->init->bend_search)(assoc->backend, bsrr);
1557 return response_searchRequest(assoc, reqb, bsrr, fd);
1560 int bend_searchresponse(void *handle, bend_search_rr *bsrr) {return 0;}
1563 * Prepare a searchresponse based on the backend results. We probably want
1564 * to look at making the fetching of records nonblocking as well, but
1565 * so far, we'll keep things simple.
1566 * If bsrt is null, that means we're called in response to a communications
1567 * event, and we'll have to get the response for ourselves.
1569 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
1570 bend_search_rr *bsrt, int *fd)
1572 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
1573 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1574 Z_SearchResponse *resp = (Z_SearchResponse *)
1575 odr_malloc (assoc->encode, sizeof(*resp));
1576 int *nulint = odr_intdup (assoc->encode, 0);
1577 bool_t *sr = odr_intdup(assoc->encode, 1);
1578 int *next = odr_intdup(assoc->encode, 0);
1579 int *none = odr_intdup(assoc->encode, Z_RES_NONE);
1581 apdu->which = Z_APDU_searchResponse;
1582 apdu->u.searchResponse = resp;
1583 resp->referenceId = req->referenceId;
1584 resp->additionalSearchInfo = 0;
1585 resp->otherInfo = 0;
1587 if (!bsrt && !bend_searchresponse(assoc->backend, bsrt))
1589 yaz_log(LOG_FATAL, "Bad result from backend");
1592 else if (bsrt->errcode)
1594 resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
1595 resp->resultCount = nulint;
1596 resp->numberOfRecordsReturned = nulint;
1597 resp->nextResultSetPosition = nulint;
1598 resp->searchStatus = nulint;
1599 resp->resultSetStatus = none;
1600 resp->presentStatus = 0;
1604 int *toget = odr_intdup(assoc->encode, 0);
1605 int *presst = odr_intdup(assoc->encode, 0);
1606 Z_RecordComposition comp, *compp = 0;
1608 yaz_log (LOG_LOG, "resultCount: %d", bsrt->hits);
1611 resp->resultCount = &bsrt->hits;
1613 comp.which = Z_RecordComp_simple;
1614 /* how many records does the user agent want, then? */
1615 if (bsrt->hits <= *req->smallSetUpperBound)
1617 *toget = bsrt->hits;
1618 if ((comp.u.simple = req->smallSetElementSetNames))
1621 else if (bsrt->hits < *req->largeSetLowerBound)
1623 *toget = *req->mediumSetPresentNumber;
1624 if (*toget > bsrt->hits)
1625 *toget = bsrt->hits;
1626 if ((comp.u.simple = req->mediumSetElementSetNames))
1632 if (*toget && !resp->records)
1637 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
1640 form = prefformat->value;
1641 resp->records = pack_records(assoc, req->resultSetName, 1,
1642 toget, compp, next, presst, form, req->referenceId,
1643 req->preferredRecordSyntax);
1646 resp->numberOfRecordsReturned = toget;
1647 resp->nextResultSetPosition = next;
1648 resp->searchStatus = sr;
1649 resp->resultSetStatus = 0;
1650 resp->presentStatus = presst;
1654 if (*resp->resultCount)
1656 resp->numberOfRecordsReturned = nulint;
1657 resp->nextResultSetPosition = next;
1658 resp->searchStatus = sr;
1659 resp->resultSetStatus = 0;
1660 resp->presentStatus = 0;
1663 resp->additionalSearchInfo = bsrt->search_info;
1668 * Maybe we got a little over-friendly when we designed bend_fetch to
1669 * get only one record at a time. Some backends can optimise multiple-record
1670 * fetches, and at any rate, there is some overhead involved in
1671 * all that selecting and hopping around. Problem is, of course, that the
1672 * frontend can't know ahead of time how many records it'll need to
1673 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
1674 * is downright lousy as a bulk data transfer protocol.
1676 * To start with, we'll do the fetching of records from the backend
1677 * in one operation: To save some trips in and out of the event-handler,
1678 * and to simplify the interface to pack_records. At any rate, asynch
1679 * operation is more fun in operations that have an unpredictable execution
1680 * speed - which is normally more true for search than for present.
1682 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
1685 Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
1689 Z_PresentResponse *resp;
1693 yaz_log(LOG_LOG, "Got PresentRequest.");
1695 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
1698 form = prefformat->value;
1699 resp = (Z_PresentResponse *)odr_malloc (assoc->encode, sizeof(*resp));
1701 resp->presentStatus = odr_intdup(assoc->encode, 0);
1702 if (assoc->init->bend_present)
1704 bend_present_rr *bprr = (bend_present_rr *)
1705 nmem_malloc (reqb->request_mem, sizeof(*bprr));
1706 bprr->setname = req->resultSetId;
1707 bprr->start = *req->resultSetStartPoint;
1708 bprr->number = *req->numberOfRecordsRequested;
1709 bprr->format = form;
1710 bprr->comp = req->recordComposition;
1711 bprr->referenceId = req->referenceId;
1712 bprr->stream = assoc->encode;
1713 bprr->print = assoc->print;
1714 bprr->request = reqb;
1715 bprr->association = assoc;
1717 bprr->errstring = NULL;
1718 (*assoc->init->bend_present)(assoc->backend, bprr);
1724 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
1725 *resp->presentStatus = Z_PRES_FAILURE;
1728 apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1729 next = odr_intdup(assoc->encode, 0);
1730 num = odr_intdup(assoc->encode, 0);
1732 apdu->which = Z_APDU_presentResponse;
1733 apdu->u.presentResponse = resp;
1734 resp->referenceId = req->referenceId;
1735 resp->otherInfo = 0;
1739 *num = *req->numberOfRecordsRequested;
1741 pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
1742 num, req->recordComposition, next, resp->presentStatus,
1743 form, req->referenceId, req->preferredRecordSyntax);
1747 resp->numberOfRecordsReturned = num;
1748 resp->nextResultSetPosition = next;
1754 * Scan was implemented rather in a hurry, and with support for only the basic
1755 * elements of the service in the backend API. Suggestions are welcome.
1757 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
1759 Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
1760 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1761 Z_ScanResponse *res = (Z_ScanResponse *)
1762 odr_malloc (assoc->encode, sizeof(*res));
1763 int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
1764 int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
1765 Z_ListEntries *ents = (Z_ListEntries *)
1766 odr_malloc (assoc->encode, sizeof(*ents));
1767 Z_DiagRecs *diagrecs_p = NULL;
1769 bend_scan_rr *bsrr = (bend_scan_rr *)
1770 odr_malloc (assoc->encode, sizeof(*bsrr));
1772 yaz_log(LOG_LOG, "Got ScanRequest");
1774 apdu->which = Z_APDU_scanResponse;
1775 apdu->u.scanResponse = res;
1776 res->referenceId = req->referenceId;
1778 /* if step is absent, set it to 0 */
1779 res->stepSize = odr_intdup(assoc->encode, 0);
1781 *res->stepSize = *req->stepSize;
1783 res->scanStatus = scanStatus;
1784 res->numberOfEntriesReturned = numberOfEntriesReturned;
1785 res->positionOfTerm = 0;
1786 res->entries = ents;
1787 ents->num_entries = 0;
1788 ents->entries = NULL;
1789 ents->num_nonsurrogateDiagnostics = 0;
1790 ents->nonsurrogateDiagnostics = NULL;
1791 res->attributeSet = 0;
1794 if (req->databaseNames)
1797 for (i = 0; i < req->num_databaseNames; i++)
1798 yaz_log (LOG_LOG, "Database '%s'", req->databaseNames[i]);
1800 bsrr->num_bases = req->num_databaseNames;
1801 bsrr->basenames = req->databaseNames;
1802 bsrr->num_entries = *req->numberOfTermsRequested;
1803 bsrr->term = req->termListAndStartPoint;
1804 bsrr->referenceId = req->referenceId;
1805 bsrr->stream = assoc->encode;
1806 bsrr->print = assoc->print;
1807 bsrr->step_size = res->stepSize;
1808 if (req->attributeSet &&
1809 (attset = oid_getentbyoid(req->attributeSet)) &&
1810 (attset->oclass == CLASS_ATTSET || attset->oclass == CLASS_GENERAL))
1811 bsrr->attributeset = attset->value;
1813 bsrr->attributeset = VAL_NONE;
1814 log_scan_term (req->termListAndStartPoint, bsrr->attributeset);
1815 bsrr->term_position = req->preferredPositionInResponse ?
1816 *req->preferredPositionInResponse : 1;
1817 ((int (*)(void *, bend_scan_rr *))
1818 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1820 diagrecs_p = diagrecs(assoc, bsrr->errcode, bsrr->errstring);
1824 Z_Entry **tab = (Z_Entry **)
1825 odr_malloc (assoc->encode, sizeof(*tab) * bsrr->num_entries);
1827 if (bsrr->status == BEND_SCAN_PARTIAL)
1828 *scanStatus = Z_Scan_partial_5;
1830 *scanStatus = Z_Scan_success;
1831 ents->entries = tab;
1832 ents->num_entries = bsrr->num_entries;
1833 res->numberOfEntriesReturned = &ents->num_entries;
1834 res->positionOfTerm = &bsrr->term_position;
1835 for (i = 0; i < bsrr->num_entries; i++)
1841 tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
1842 if (bsrr->entries[i].occurrences >= 0)
1844 e->which = Z_Entry_termInfo;
1845 e->u.termInfo = t = (Z_TermInfo *)
1846 odr_malloc(assoc->encode, sizeof(*t));
1847 t->suggestedAttributes = 0;
1849 t->alternativeTerm = 0;
1850 t->byAttributes = 0;
1851 t->otherTermInfo = 0;
1852 t->globalOccurrences = &bsrr->entries[i].occurrences;
1853 t->term = (Z_Term *)
1854 odr_malloc(assoc->encode, sizeof(*t->term));
1855 t->term->which = Z_Term_general;
1856 t->term->u.general = o =
1857 (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
1858 o->buf = (unsigned char *)
1859 odr_malloc(assoc->encode, o->len = o->size =
1860 strlen(bsrr->entries[i].term));
1861 memcpy(o->buf, bsrr->entries[i].term, o->len);
1862 yaz_log(LOG_DEBUG, " term #%d: '%s' (%d)", i,
1863 bsrr->entries[i].term, bsrr->entries[i].occurrences);
1867 Z_DiagRecs *drecs = diagrecs (assoc,
1868 bsrr->entries[i].errcode,
1869 bsrr->entries[i].errstring);
1870 assert (drecs->num_diagRecs == 1);
1871 e->which = Z_Entry_surrogateDiagnostic;
1872 assert (drecs->diagRecs[0]);
1873 e->u.surrogateDiagnostic = drecs->diagRecs[0];
1879 ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
1880 ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
1885 static Z_APDU *process_sortRequest(association *assoc, request *reqb,
1888 Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
1889 Z_SortResponse *res = (Z_SortResponse *)
1890 odr_malloc (assoc->encode, sizeof(*res));
1891 bend_sort_rr *bsrr = (bend_sort_rr *)
1892 odr_malloc (assoc->encode, sizeof(*bsrr));
1894 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1896 yaz_log(LOG_LOG, "Got SortRequest.");
1898 bsrr->num_input_setnames = req->num_inputResultSetNames;
1899 bsrr->input_setnames = req->inputResultSetNames;
1900 bsrr->referenceId = req->referenceId;
1901 bsrr->output_setname = req->sortedResultSetName;
1902 bsrr->sort_sequence = req->sortSequence;
1903 bsrr->stream = assoc->encode;
1904 bsrr->print = assoc->print;
1906 bsrr->sort_status = Z_SortStatus_failure;
1908 bsrr->errstring = 0;
1910 (*assoc->init->bend_sort)(assoc->backend, bsrr);
1912 res->referenceId = bsrr->referenceId;
1913 res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
1914 res->resultSetStatus = 0;
1917 Z_DiagRecs *dr = diagrecs (assoc, bsrr->errcode, bsrr->errstring);
1918 res->diagnostics = dr->diagRecs;
1919 res->num_diagnostics = dr->num_diagRecs;
1923 res->num_diagnostics = 0;
1924 res->diagnostics = 0;
1928 apdu->which = Z_APDU_sortResponse;
1929 apdu->u.sortResponse = res;
1933 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
1936 Z_DeleteResultSetRequest *req =
1937 reqb->apdu_request->u.deleteResultSetRequest;
1938 Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
1939 odr_malloc (assoc->encode, sizeof(*res));
1940 bend_delete_rr *bdrr = (bend_delete_rr *)
1941 odr_malloc (assoc->encode, sizeof(*bdrr));
1942 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1944 yaz_log(LOG_LOG, "Got DeleteRequest.");
1946 bdrr->num_setnames = req->num_resultSetList;
1947 bdrr->setnames = req->resultSetList;
1948 bdrr->stream = assoc->encode;
1949 bdrr->print = assoc->print;
1950 bdrr->function = *req->deleteFunction;
1951 bdrr->referenceId = req->referenceId;
1953 if (bdrr->num_setnames > 0)
1956 bdrr->statuses = (int*)
1957 odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
1958 bdrr->num_setnames);
1959 for (i = 0; i < bdrr->num_setnames; i++)
1960 bdrr->statuses[i] = 0;
1962 (*assoc->init->bend_delete)(assoc->backend, bdrr);
1964 res->referenceId = req->referenceId;
1966 res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
1968 res->deleteListStatuses = 0;
1969 if (bdrr->num_setnames > 0)
1972 res->deleteListStatuses = (Z_ListStatuses *)
1973 odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
1974 res->deleteListStatuses->num = bdrr->num_setnames;
1975 res->deleteListStatuses->elements =
1977 odr_malloc (assoc->encode,
1978 sizeof(*res->deleteListStatuses->elements) *
1979 bdrr->num_setnames);
1980 for (i = 0; i<bdrr->num_setnames; i++)
1982 res->deleteListStatuses->elements[i] =
1984 odr_malloc (assoc->encode,
1985 sizeof(**res->deleteListStatuses->elements));
1986 res->deleteListStatuses->elements[i]->status = bdrr->statuses+i;
1987 res->deleteListStatuses->elements[i]->id =
1988 odr_strdup (assoc->encode, bdrr->setnames[i]);
1992 res->numberNotDeleted = 0;
1993 res->bulkStatuses = 0;
1994 res->deleteMessage = 0;
1997 apdu->which = Z_APDU_deleteResultSetResponse;
1998 apdu->u.deleteResultSetResponse = res;
2002 static void process_close(association *assoc, request *reqb)
2004 Z_Close *req = reqb->apdu_request->u.close;
2005 static char *reasons[] =
2012 "securityViolation",
2019 yaz_log(LOG_LOG, "Got Close, reason %s, message %s",
2020 reasons[*req->closeReason], req->diagnosticInformation ?
2021 req->diagnosticInformation : "NULL");
2022 if (assoc->version < 3) /* to make do_force respond with close */
2024 do_close_req(assoc, Z_Close_finished,
2025 "Association terminated by client", reqb);
2028 void save_referenceId (request *reqb, Z_ReferenceId *refid)
2032 reqb->len_refid = refid->len;
2033 reqb->refid = (char *)nmem_malloc (reqb->request_mem, refid->len);
2034 memcpy (reqb->refid, refid->buf, refid->len);
2038 reqb->len_refid = 0;
2043 void bend_request_send (bend_association a, bend_request req, Z_APDU *res)
2045 process_z_response (a, req, res);
2048 bend_request bend_request_mk (bend_association a)
2050 request *nreq = request_get (&a->outgoing);
2051 nreq->request_mem = nmem_create ();
2055 Z_ReferenceId *bend_request_getid (ODR odr, bend_request req)
2060 id = (Odr_oct *)odr_malloc (odr, sizeof(*odr));
2061 id->buf = (unsigned char *)odr_malloc (odr, req->len_refid);
2062 id->len = id->size = req->len_refid;
2063 memcpy (id->buf, req->refid, req->len_refid);
2067 void bend_request_destroy (bend_request *req)
2069 nmem_destroy((*req)->request_mem);
2070 request_release(*req);
2074 int bend_backend_respond (bend_association a, bend_request req)
2078 r = process_z_request (a, req, &msg);
2080 yaz_log (LOG_WARN, "%s", msg);
2084 void bend_request_setdata(bend_request r, void *p)
2089 void *bend_request_getdata(bend_request r)
2091 return r->clientData;
2094 static Z_APDU *process_segmentRequest (association *assoc, request *reqb)
2096 bend_segment_rr req;
2098 req.segment = reqb->apdu_request->u.segmentRequest;
2099 req.stream = assoc->encode;
2100 req.decode = assoc->decode;
2101 req.print = assoc->print;
2102 req.association = assoc;
2104 (*assoc->init->bend_segment)(assoc->backend, &req);
2109 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd)
2111 bend_esrequest_rr esrequest;
2113 Z_ExtendedServicesRequest *req =
2114 reqb->apdu_request->u.extendedServicesRequest;
2115 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
2117 Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
2119 yaz_log(LOG_DEBUG,"inside Process esRequest");
2121 esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
2122 esrequest.stream = assoc->encode;
2123 esrequest.decode = assoc->decode;
2124 esrequest.print = assoc->print;
2125 esrequest.errcode = 0;
2126 esrequest.errstring = NULL;
2127 esrequest.request = reqb;
2128 esrequest.association = assoc;
2129 esrequest.taskPackage = 0;
2130 esrequest.referenceId = req->referenceId;
2132 (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
2134 /* If the response is being delayed, return NULL */
2135 if (esrequest.request == NULL)
2138 resp->referenceId = req->referenceId;
2140 if (esrequest.errcode == -1)
2142 /* Backend service indicates request will be processed */
2143 yaz_log(LOG_DEBUG,"Request could be processed...Accepted !");
2144 *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
2146 else if (esrequest.errcode == 0)
2148 /* Backend service indicates request will be processed */
2149 yaz_log(LOG_DEBUG,"Request could be processed...Done !");
2150 *resp->operationStatus = Z_ExtendedServicesResponse_done;
2154 Z_DiagRecs *diagRecs = diagrecs (assoc, esrequest.errcode,
2155 esrequest.errstring);
2157 /* Backend indicates error, request will not be processed */
2158 yaz_log(LOG_DEBUG,"Request could not be processed...failure !");
2159 *resp->operationStatus = Z_ExtendedServicesResponse_failure;
2160 resp->num_diagnostics = diagRecs->num_diagRecs;
2161 resp->diagnostics = diagRecs->diagRecs;
2163 /* Do something with the members of bend_extendedservice */
2164 if (esrequest.taskPackage)
2165 resp->taskPackage = z_ext_record (assoc->encode, VAL_EXTENDED,
2166 (const char *) esrequest.taskPackage,
2168 yaz_log(LOG_DEBUG,"Send the result apdu");