2 * Copyright (c) 1995-2003, Index Data
3 * See the file LICENSE for details.
5 * $Id: seshigh.c,v 1.134 2003-02-12 15:06:43 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.
38 #include <yaz/yconfig.h>
39 #include <yaz/xmalloc.h>
40 #include <yaz/comstack.h>
43 #include <yaz/proto.h>
46 #include <yaz/logrpn.h>
47 #include <yaz/statserv.h>
48 #include <yaz/diagbib1.h>
49 #include <yaz/charneg.h>
50 #include <yaz/otherinfo.h>
51 #include <yaz/yaz-util.h>
54 #include <yaz/backend.h>
56 static void process_gdu_request(association *assoc, request *req);
57 static int process_z_request(association *assoc, request *req, char **msg);
58 void backend_response(IOCHAN i, int event);
59 static int process_gdu_response(association *assoc, request *req, Z_GDU *res);
60 static int process_z_response(association *assoc, request *req, Z_APDU *res);
61 static Z_APDU *process_initRequest(association *assoc, request *reqb);
62 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
64 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
65 bend_search_rr *bsrr, int *fd);
66 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
68 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
69 static Z_APDU *process_sortRequest(association *assoc, request *reqb, int *fd);
70 static void process_close(association *assoc, request *reqb);
71 void save_referenceId (request *reqb, Z_ReferenceId *refid);
72 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
74 static Z_APDU *process_segmentRequest (association *assoc, request *reqb);
76 static FILE *apduf = 0; /* for use in static mode */
77 static statserv_options_block *control_block = 0;
79 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd);
82 * Create and initialize a new association-handle.
83 * channel : iochannel for the current line.
84 * link : communications channel.
85 * Returns: 0 or a new association handle.
87 association *create_association(IOCHAN channel, COMSTACK link)
92 control_block = statserv_getcontrol();
93 if (!(anew = (association *)xmalloc(sizeof(*anew))))
96 anew->client_chan = channel;
97 anew->client_link = link;
98 anew->cs_get_mask = 0;
99 anew->cs_put_mask = 0;
100 anew->cs_accept_mask = 0;
101 if (!(anew->decode = odr_createmem(ODR_DECODE)) ||
102 !(anew->encode = odr_createmem(ODR_ENCODE)))
104 if (*control_block->apdufile)
109 strcpy(filename, control_block->apdufile);
110 if (!(anew->print = odr_createmem(ODR_PRINT)))
112 if (*control_block->apdufile == '@')
114 odr_setprint(anew->print, yaz_log_file());
116 else if (*control_block->apdufile != '-')
118 strcpy(filename, control_block->apdufile);
119 if (!control_block->dynamic)
123 if (!(apduf = fopen(filename, "w")))
125 yaz_log(LOG_WARN|LOG_ERRNO, "%s", filename);
128 setvbuf(apduf, 0, _IONBF, 0);
134 sprintf(filename + strlen(filename), ".%d", getpid());
135 if (!(f = fopen(filename, "w")))
137 yaz_log(LOG_WARN|LOG_ERRNO, "%s", filename);
140 setvbuf(f, 0, _IONBF, 0);
142 odr_setprint(anew->print, f);
147 anew->input_buffer = 0;
148 anew->input_buffer_len = 0;
150 anew->state = ASSOC_NEW;
151 request_initq(&anew->incoming);
152 request_initq(&anew->outgoing);
153 anew->proto = cs_getproto(link);
158 * Free association and release resources.
160 void destroy_association(association *h)
162 statserv_options_block *cb = statserv_getcontrol();
165 odr_destroy(h->decode);
166 odr_destroy(h->encode);
168 odr_destroy(h->print);
170 xfree(h->input_buffer);
172 (*cb->bend_close)(h->backend);
173 while (request_deq(&h->incoming));
174 while (request_deq(&h->outgoing));
175 request_delq(&h->incoming);
176 request_delq(&h->outgoing);
178 xmalloc_trav("session closed");
179 if (control_block && control_block->one_shot)
183 static void do_close_req(association *a, int reason, char *message,
187 Z_Close *cls = zget_Close(a->encode);
189 /* Purge request queue */
190 while (request_deq(&a->incoming));
191 while (request_deq(&a->outgoing));
194 yaz_log(LOG_LOG, "Sending Close PDU, reason=%d, message=%s",
195 reason, message ? message : "none");
196 apdu.which = Z_APDU_close;
198 *cls->closeReason = reason;
199 cls->diagnosticInformation = message;
200 process_z_response(a, req, &apdu);
201 iochan_settimeout(a->client_chan, 60);
205 yaz_log(LOG_DEBUG, "v2 client. No Close PDU");
206 iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
208 a->state = ASSOC_DEAD;
211 static void do_close(association *a, int reason, char *message)
213 do_close_req (a, reason, message, request_get(&a->outgoing));
217 * This is where PDUs from the client are read and the further
218 * processing is initiated. Flow of control moves down through the
219 * various process_* functions below, until the encoded result comes back up
220 * to the output handler in here.
222 * h : the I/O channel that has an outstanding event.
223 * event : the current outstanding event.
225 void ir_session(IOCHAN h, int event)
228 association *assoc = (association *)iochan_getdata(h);
229 COMSTACK conn = assoc->client_link;
232 assert(h && conn && assoc);
233 if (event == EVENT_TIMEOUT)
235 if (assoc->state != ASSOC_UP)
237 yaz_log(LOG_LOG, "Final timeout - closing connection.");
239 destroy_association(assoc);
244 yaz_log(LOG_LOG, "Session idle too long. Sending close.");
245 do_close(assoc, Z_Close_lackOfActivity, 0);
249 if (event & assoc->cs_accept_mask)
251 yaz_log (LOG_DEBUG, "ir_session (accept)");
252 if (!cs_accept (conn))
254 yaz_log (LOG_LOG, "accept failed");
255 destroy_association(assoc);
258 iochan_clearflag (h, EVENT_OUTPUT|EVENT_OUTPUT);
259 if (conn->io_pending)
260 { /* cs_accept didn't complete */
261 assoc->cs_accept_mask =
262 ((conn->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
263 ((conn->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
265 iochan_setflag (h, assoc->cs_accept_mask);
268 { /* cs_accept completed. Prepare for reading (cs_get) */
269 assoc->cs_accept_mask = 0;
270 assoc->cs_get_mask = EVENT_INPUT;
271 iochan_setflag (h, assoc->cs_get_mask);
275 if ((event & assoc->cs_get_mask) || (event & EVENT_WORK)) /* input */
277 if ((assoc->cs_put_mask & EVENT_INPUT) == 0 && (event & assoc->cs_get_mask))
279 yaz_log(LOG_DEBUG, "ir_session (input)");
280 /* We aren't speaking to this fellow */
281 if (assoc->state == ASSOC_DEAD)
283 yaz_log(LOG_LOG, "Closed connection after reject");
285 destroy_association(assoc);
289 assoc->cs_get_mask = EVENT_INPUT;
290 if ((res = cs_get(conn, &assoc->input_buffer,
291 &assoc->input_buffer_len)) <= 0)
293 yaz_log(LOG_LOG, "Connection closed by client");
295 destroy_association(assoc);
299 else if (res == 1) /* incomplete read - wait for more */
301 if (conn->io_pending & CS_WANT_WRITE)
302 assoc->cs_get_mask |= EVENT_OUTPUT;
303 iochan_setflag(h, assoc->cs_get_mask);
306 if (cs_more(conn)) /* more stuff - call us again later, please */
307 iochan_setevent(h, EVENT_INPUT);
309 /* we got a complete PDU. Let's decode it */
310 yaz_log(LOG_DEBUG, "Got PDU, %d bytes: lead=%02X %02X %02X", res,
311 assoc->input_buffer[0] & 0xff,
312 assoc->input_buffer[1] & 0xff,
313 assoc->input_buffer[2] & 0xff);
314 req = request_get(&assoc->incoming); /* get a new request structure */
315 odr_reset(assoc->decode);
316 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
317 if (!z_GDU(assoc->decode, &req->gdu_request, 0, 0))
319 yaz_log(LOG_LOG, "ODR error on incoming PDU: %s [near byte %d] ",
320 odr_errmsg(odr_geterror(assoc->decode)),
321 odr_offset(assoc->decode));
322 if (assoc->decode->error != OHTTP)
324 yaz_log(LOG_LOG, "PDU dump:");
325 odr_dumpBER(yaz_log_file(), assoc->input_buffer, res);
326 do_close(assoc, Z_Close_protocolError, "Malformed package");
330 Z_GDU *p = z_get_HTTP_Response(assoc->encode, 400);
331 assoc->state = ASSOC_DEAD;
332 process_gdu_response(assoc, req, p);
336 req->request_mem = odr_extract_mem(assoc->decode);
337 if (assoc->print && !z_GDU(assoc->print, &req->gdu_request, 0, 0))
339 yaz_log(LOG_WARN, "ODR print error: %s",
340 odr_errmsg(odr_geterror(assoc->print)));
341 odr_reset(assoc->print);
343 request_enq(&assoc->incoming, req);
346 /* can we do something yet? */
347 req = request_head(&assoc->incoming);
348 if (req->state == REQUEST_IDLE)
350 request_deq(&assoc->incoming);
351 process_gdu_request(assoc, req);
354 if (event & assoc->cs_put_mask)
356 request *req = request_head(&assoc->outgoing);
358 assoc->cs_put_mask = 0;
359 yaz_log(LOG_DEBUG, "ir_session (output)");
360 req->state = REQUEST_PENDING;
361 switch (res = cs_put(conn, req->response, req->len_response))
364 yaz_log(LOG_LOG, "Connection closed by client");
366 destroy_association(assoc);
369 case 0: /* all sent - release the request structure */
370 yaz_log(LOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
372 yaz_log(LOG_DEBUG, "HTTP out:\n%.*s", req->len_response,
375 nmem_destroy(req->request_mem);
376 request_deq(&assoc->outgoing);
377 request_release(req);
378 if (!request_head(&assoc->outgoing))
379 { /* restore mask for cs_get operation ... */
380 iochan_clearflag(h, EVENT_OUTPUT|EVENT_INPUT);
381 iochan_setflag(h, assoc->cs_get_mask);
382 yaz_log(LOG_LOG, "queue empty mask=%d", assoc->cs_get_mask);
383 if (assoc->state == ASSOC_DEAD)
384 iochan_setevent(assoc->client_chan, EVENT_TIMEOUT);
388 assoc->cs_put_mask = EVENT_OUTPUT;
389 yaz_log(LOG_LOG, "queue not empty");
393 if (conn->io_pending & CS_WANT_WRITE)
394 assoc->cs_put_mask |= EVENT_OUTPUT;
395 if (conn->io_pending & CS_WANT_READ)
396 assoc->cs_put_mask |= EVENT_INPUT;
397 iochan_setflag(h, assoc->cs_put_mask);
400 if (event & EVENT_EXCEPT)
402 yaz_log(LOG_LOG, "ir_session (exception)");
404 destroy_association(assoc);
409 static int process_z_request(association *assoc, request *req, char **msg);
411 static int srw_bend_init(association *assoc)
413 bend_initresult *binitres;
414 statserv_options_block *cb = statserv_getcontrol();
416 assoc->init = (bend_initrequest *) xmalloc (sizeof(*assoc->init));
418 assoc->init->stream = assoc->encode;
419 assoc->init->print = assoc->print;
420 assoc->init->auth = 0;
421 assoc->init->referenceId = 0;
422 assoc->init->implementation_version = 0;
423 assoc->init->implementation_id = 0;
424 assoc->init->implementation_name = 0;
425 assoc->init->bend_sort = NULL;
426 assoc->init->bend_search = NULL;
427 assoc->init->bend_present = NULL;
428 assoc->init->bend_esrequest = NULL;
429 assoc->init->bend_delete = NULL;
430 assoc->init->bend_scan = NULL;
431 assoc->init->bend_segment = NULL;
432 assoc->init->bend_fetch = NULL;
433 assoc->init->charneg_request = NULL;
434 assoc->init->charneg_response = NULL;
435 assoc->init->decode = assoc->decode;
437 assoc->init->peer_name =
438 odr_strdup (assoc->encode, cs_addrstr(assoc->client_link));
439 if (!(binitres = (*cb->bend_init)(assoc->init)))
441 yaz_log(LOG_WARN, "Bad response from backend.");
444 assoc->backend = binitres->handle;
448 static void srw_bend_fetch(association *assoc, int pos,
449 Z_SRW_searchRetrieveRequest *srw_req,
450 Z_SRW_record *record)
453 ODR o = assoc->encode;
455 rr.setname = "default";
458 rr.request_format = VAL_TEXT_XML;
459 rr.request_format_raw = yaz_oidval_to_z3950oid(assoc->decode,
462 rr.comp = odr_malloc(assoc->decode, sizeof(*rr.comp));
463 rr.comp->which = Z_RecordComp_complex;
464 rr.comp->u.complex = odr_malloc(assoc->decode, sizeof(Z_CompSpec));
465 rr.comp->u.complex->selectAlternativeSyntax = (bool_t *)
466 odr_malloc(assoc->encode, sizeof(bool_t));
467 *rr.comp->u.complex->selectAlternativeSyntax = 0;
468 rr.comp->u.complex->num_dbSpecific = 0;
469 rr.comp->u.complex->dbSpecific = 0;
470 rr.comp->u.complex->num_recordSyntax = 0;
471 rr.comp->u.complex->recordSyntax = 0;
473 rr.comp->u.complex->generic = odr_malloc(assoc->decode,
474 sizeof(Z_Specification));
475 rr.comp->u.complex->generic->which = Z_Specification_uri;
476 rr.comp->u.complex->generic->u.uri = srw_req->recordSchema;
477 rr.comp->u.complex->generic->elementSpec = 0;
479 rr.stream = assoc->encode;
480 rr.print = assoc->print;
486 rr.output_format = VAL_TEXT_XML;
487 rr.output_format_raw = 0;
490 rr.surrogate_flag = 0;
492 (*assoc->init->bend_fetch)(assoc->backend, &rr);
496 record->recordData_buf = rr.record;
497 record->recordData_len = rr.len;
498 record->recordPosition = odr_intdup(o, pos);
499 record->recordSchema = odr_strdup(o, srw_req->recordSchema);
503 static void srw_bend_search(association *assoc, request *req,
504 Z_SRW_searchRetrieveRequest *srw_req,
505 Z_SRW_searchRetrieveResponse *srw_res)
507 char *base = "Default";
512 srw_bend_init(assoc);
514 rr.setname = "default";
517 rr.basenames = &base;
520 ext = (Z_External *) odr_malloc(assoc->decode, sizeof(*ext));
521 ext->direct_reference = odr_getoidbystr(assoc->decode,
522 "1.2.840.10003.16.2");
523 ext->indirect_reference = 0;
525 ext->which = Z_External_CQL;
527 ext->u.cql = srw_req->query;
529 ext->u.cql = "noterm";
531 rr.query = (Z_Query *) odr_malloc (assoc->decode, sizeof(*rr.query));
532 rr.query->which = Z_Query_type_104;
533 rr.query->u.type_104 = ext;
535 rr.stream = assoc->encode;
536 rr.decode = assoc->decode;
537 rr.print = assoc->print;
539 rr.association = assoc;
545 (assoc->init->bend_search)(assoc->backend, &rr);
546 srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
549 srw_res->num_diagnostics = 1;
550 srw_res->diagnostics =
551 odr_malloc(assoc->encode, sizeof(*srw_res->diagnostics));
552 srw_res->diagnostics[0].code =
553 odr_intdup(assoc->encode, rr.errcode);
557 srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
558 if (srw_req->maximumRecords && *srw_req->maximumRecords > 0)
560 int number = *srw_req->maximumRecords;
563 if (srw_req->startRecord)
564 start = *srw_req->startRecord;
565 if (start <= rr.hits)
568 if (start + number > rr.hits)
569 number = rr.hits - start + 1;
571 odr_malloc(assoc->encode,
572 number * sizeof(*srw_res->records));
573 for (i = 0; i<number; i++)
575 srw_res->records[j].recordData_buf = 0;
576 srw_bend_fetch(assoc, i+start, srw_req,
577 srw_res->records + j);
578 if (srw_res->records[j].recordData_buf)
581 srw_res->num_records = j;
583 srw_res->records = 0;
584 yaz_log(LOG_LOG, "got %d records", j);
590 static void process_http_request(association *assoc, request *req)
592 Z_HTTP_Request *hreq = req->gdu_request->u.HTTP_Request;
594 ODR o = assoc->encode;
596 Z_HTTP_Response *hres = 0;
600 yaz_log(LOG_LOG, "HTTP Request. method=%s Version=%s Path=%s",
601 hreq->method, hreq->version, hreq->path);
603 for (hp = hreq->headers; hp; hp = hp->next)
604 yaz_log(LOG_LOG, "%s: %s", hp->name, hp->value);
607 if (!strcmp(hreq->method, "GET"))
609 if (!strcmp(hreq->path, "/"))
611 p = z_get_HTTP_Response(o, 200);
612 hres = p->u.HTTP_Response;
613 hres->content_buf = odr_malloc(o, 400);
614 sprintf (hres->content_buf,
615 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n"
618 " <TITLE>YAZ " YAZ_VERSION "</TITLE>\n"
621 " <P><A HREF=\"http://www.indexdata.dk/yaz/\">YAZ</A> "
625 hres->content_len = strlen(hres->content_buf);
626 z_HTTP_header_add(o, &hres->headers, "Content-Type", "text/html");
630 p = z_get_HTTP_Response(o, 404);
633 else if (!strcmp(hreq->method, "POST"))
635 const char *content_type = z_HTTP_header_lookup(hreq->headers,
637 const char *soap_action = z_HTTP_header_lookup(hreq->headers,
639 p = 0; /* no response yet */
640 if (content_type && soap_action &&
641 !yaz_strcmp_del("text/xml", content_type, "; "))
643 Z_SOAP *soap_package = 0;
647 static Z_SOAP_Handler soap_handlers[2] = {
648 {"http://www.loc.gov/zing/srw/v1.0/", 0, yaz_srw_codec},
652 ret = z_soap_codec(assoc->decode, &soap_package,
653 &hreq->content_buf, &hreq->content_len,
656 if (!ret && soap_package->which == Z_SOAP_generic &&
657 soap_package->u.generic->no == 0)
660 Z_SRW_searchRetrieve *sr = soap_package->u.generic->p;
662 if (sr->which == Z_SRW_searchRetrieve_request)
664 Z_SRW_searchRetrieve *res =
665 yaz_srw_get(assoc->encode,
666 Z_SRW_searchRetrieve_response);
668 srw_bend_search(assoc, req, sr->u.request, res->u.response);
670 soap_package->u.generic->p = res;
675 p = z_get_HTTP_Response(o, 200);
676 hres = p->u.HTTP_Response;
677 ret = z_soap_codec(assoc->encode, &soap_package,
678 &hres->content_buf, &hres->content_len,
680 hres->code = http_code;
682 if (!p) /* still no response ? */
683 p = z_get_HTTP_Response(o, 500);
687 p = z_get_HTTP_Response(o, 405);
688 hres = p->u.HTTP_Response;
690 z_HTTP_header_add(o, &hres->headers, "Allow", "GET, POST");
692 hres = p->u.HTTP_Response;
693 if (!strcmp(hreq->version, "1.0"))
695 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
696 if (v && !strcmp(v, "Keep-Alive"))
700 hres->version = "1.0";
704 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
705 if (v && !strcmp(v, "close"))
709 hres->version = "1.1";
713 z_HTTP_header_add(o, &hres->headers, "Connection", "close");
714 assoc->state = ASSOC_DEAD;
718 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
720 process_gdu_response(assoc, req, p);
723 static void process_gdu_request(association *assoc, request *req)
725 if (req->gdu_request->which == Z_GDU_Z3950)
728 req->apdu_request = req->gdu_request->u.z3950;
729 if (process_z_request(assoc, req, &msg) < 0)
730 do_close_req(assoc, Z_Close_systemProblem, msg, req);
732 else if (req->gdu_request->which == Z_GDU_HTTP_Request)
733 process_http_request(assoc, req);
736 do_close_req(assoc, Z_Close_systemProblem, "bad protocol packet", req);
741 * Initiate request processing.
743 static int process_z_request(association *assoc, request *req, char **msg)
749 *msg = "Unknown Error";
750 assert(req && req->state == REQUEST_IDLE);
751 if (req->apdu_request->which != Z_APDU_initRequest && !assoc->init)
753 *msg = "Missing InitRequest";
756 switch (req->apdu_request->which)
758 case Z_APDU_initRequest:
759 res = process_initRequest(assoc, req); break;
760 case Z_APDU_searchRequest:
761 res = process_searchRequest(assoc, req, &fd); break;
762 case Z_APDU_presentRequest:
763 res = process_presentRequest(assoc, req, &fd); break;
764 case Z_APDU_scanRequest:
765 if (assoc->init->bend_scan)
766 res = process_scanRequest(assoc, req, &fd);
769 *msg = "Cannot handle Scan APDU";
773 case Z_APDU_extendedServicesRequest:
774 if (assoc->init->bend_esrequest)
775 res = process_ESRequest(assoc, req, &fd);
778 *msg = "Cannot handle Extended Services APDU";
782 case Z_APDU_sortRequest:
783 if (assoc->init->bend_sort)
784 res = process_sortRequest(assoc, req, &fd);
787 *msg = "Cannot handle Sort APDU";
792 process_close(assoc, req);
794 case Z_APDU_deleteResultSetRequest:
795 if (assoc->init->bend_delete)
796 res = process_deleteRequest(assoc, req, &fd);
799 *msg = "Cannot handle Delete APDU";
803 case Z_APDU_segmentRequest:
804 if (assoc->init->bend_segment)
806 res = process_segmentRequest (assoc, req);
810 *msg = "Cannot handle Segment APDU";
815 *msg = "Bad APDU received";
820 yaz_log(LOG_DEBUG, " result immediately available");
821 retval = process_z_response(assoc, req, res);
825 yaz_log(LOG_DEBUG, " result unavailble");
828 else /* no result yet - one will be provided later */
832 /* Set up an I/O handler for the fd supplied by the backend */
834 yaz_log(LOG_DEBUG, " establishing handler for result");
835 req->state = REQUEST_PENDING;
836 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT)))
838 iochan_setdata(chan, assoc);
845 * Handle message from the backend.
847 void backend_response(IOCHAN i, int event)
849 association *assoc = (association *)iochan_getdata(i);
850 request *req = request_head(&assoc->incoming);
854 yaz_log(LOG_DEBUG, "backend_response");
855 assert(assoc && req && req->state != REQUEST_IDLE);
856 /* determine what it is we're waiting for */
857 switch (req->apdu_request->which)
859 case Z_APDU_searchRequest:
860 res = response_searchRequest(assoc, req, 0, &fd); break;
862 case Z_APDU_presentRequest:
863 res = response_presentRequest(assoc, req, 0, &fd); break;
864 case Z_APDU_scanRequest:
865 res = response_scanRequest(assoc, req, 0, &fd); break;
868 yaz_log(LOG_WARN, "Serious programmer's lapse or bug");
871 if ((res && process_z_response(assoc, req, res) < 0) || fd < 0)
873 yaz_log(LOG_LOG, "Fatal error when talking to backend");
874 do_close(assoc, Z_Close_systemProblem, 0);
878 else if (!res) /* no result yet - try again later */
880 yaz_log(LOG_DEBUG, " no result yet");
881 iochan_setfd(i, fd); /* in case fd has changed */
886 * Encode response, and transfer the request structure to the outgoing queue.
888 static int process_gdu_response(association *assoc, request *req, Z_GDU *res)
890 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
892 if (assoc->print && !z_GDU(assoc->print, &res, 0, 0))
894 yaz_log(LOG_WARN, "ODR print error: %s",
895 odr_errmsg(odr_geterror(assoc->print)));
896 odr_reset(assoc->print);
898 if (!z_GDU(assoc->encode, &res, 0, 0))
900 yaz_log(LOG_WARN, "ODR error when encoding response: %s",
901 odr_errmsg(odr_geterror(assoc->decode)));
904 req->response = odr_getbuf(assoc->encode, &req->len_response,
905 &req->size_response);
906 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
907 odr_reset(assoc->encode);
908 req->state = REQUEST_IDLE;
909 request_enq(&assoc->outgoing, req);
910 /* turn the work over to the ir_session handler */
911 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
912 assoc->cs_put_mask = EVENT_OUTPUT;
913 /* Is there more work to be done? give that to the input handler too */
915 if (request_head(&assoc->incoming))
917 yaz_log (LOG_DEBUG, "more work to be done");
918 iochan_setevent(assoc->client_chan, EVENT_WORK);
925 * Encode response, and transfer the request structure to the outgoing queue.
927 static int process_z_response(association *assoc, request *req, Z_APDU *res)
929 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
931 if (assoc->print && !z_APDU(assoc->print, &res, 0, 0))
933 yaz_log(LOG_WARN, "ODR print error: %s",
934 odr_errmsg(odr_geterror(assoc->print)));
935 odr_reset(assoc->print);
937 if (!z_APDU(assoc->encode, &res, 0, 0))
939 yaz_log(LOG_WARN, "ODR error when encoding response: %s",
940 odr_errmsg(odr_geterror(assoc->decode)));
943 req->response = odr_getbuf(assoc->encode, &req->len_response,
944 &req->size_response);
945 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
946 odr_reset(assoc->encode);
947 req->state = REQUEST_IDLE;
948 request_enq(&assoc->outgoing, req);
949 /* turn the work over to the ir_session handler */
950 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
951 assoc->cs_put_mask = EVENT_OUTPUT;
952 /* Is there more work to be done? give that to the input handler too */
954 if (request_head(&assoc->incoming))
956 yaz_log (LOG_DEBUG, "more work to be done");
957 iochan_setevent(assoc->client_chan, EVENT_WORK);
964 * Handle init request.
965 * At the moment, we don't check the options
966 * anywhere else in the code - we just try not to do anything that would
967 * break a naive client. We'll toss 'em into the association block when
968 * we need them there.
970 static Z_APDU *process_initRequest(association *assoc, request *reqb)
972 statserv_options_block *cb = statserv_getcontrol();
973 Z_InitRequest *req = reqb->apdu_request->u.initRequest;
974 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
975 Z_InitResponse *resp = apdu->u.initResponse;
976 bend_initresult *binitres;
981 assoc->init = (bend_initrequest *) xmalloc (sizeof(*assoc->init));
983 yaz_log(LOG_LOG, "Got initRequest");
984 if (req->implementationId)
985 yaz_log(LOG_LOG, "Id: %s", req->implementationId);
986 if (req->implementationName)
987 yaz_log(LOG_LOG, "Name: %s", req->implementationName);
988 if (req->implementationVersion)
989 yaz_log(LOG_LOG, "Version: %s", req->implementationVersion);
991 assoc->init->stream = assoc->encode;
992 assoc->init->print = assoc->print;
993 assoc->init->auth = req->idAuthentication;
994 assoc->init->referenceId = req->referenceId;
995 assoc->init->implementation_version = 0;
996 assoc->init->implementation_id = 0;
997 assoc->init->implementation_name = 0;
998 assoc->init->bend_sort = NULL;
999 assoc->init->bend_search = NULL;
1000 assoc->init->bend_present = NULL;
1001 assoc->init->bend_esrequest = NULL;
1002 assoc->init->bend_delete = NULL;
1003 assoc->init->bend_scan = NULL;
1004 assoc->init->bend_segment = NULL;
1005 assoc->init->bend_fetch = NULL;
1006 assoc->init->charneg_request = NULL;
1007 assoc->init->charneg_response = NULL;
1008 assoc->init->decode = assoc->decode;
1010 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
1012 Z_CharSetandLanguageNegotiation *negotiation =
1013 yaz_get_charneg_record (req->otherInfo);
1014 if (negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
1015 assoc->init->charneg_request = negotiation;
1018 assoc->init->peer_name =
1019 odr_strdup (assoc->encode, cs_addrstr(assoc->client_link));
1020 if (!(binitres = (*cb->bend_init)(assoc->init)))
1022 yaz_log(LOG_WARN, "Bad response from backend.");
1026 assoc->backend = binitres->handle;
1027 if ((assoc->init->bend_sort))
1028 yaz_log (LOG_DEBUG, "Sort handler installed");
1029 if ((assoc->init->bend_search))
1030 yaz_log (LOG_DEBUG, "Search handler installed");
1031 if ((assoc->init->bend_present))
1032 yaz_log (LOG_DEBUG, "Present handler installed");
1033 if ((assoc->init->bend_esrequest))
1034 yaz_log (LOG_DEBUG, "ESRequest handler installed");
1035 if ((assoc->init->bend_delete))
1036 yaz_log (LOG_DEBUG, "Delete handler installed");
1037 if ((assoc->init->bend_scan))
1038 yaz_log (LOG_DEBUG, "Scan handler installed");
1039 if ((assoc->init->bend_segment))
1040 yaz_log (LOG_DEBUG, "Segment handler installed");
1042 resp->referenceId = req->referenceId;
1044 /* let's tell the client what we can do */
1045 if (ODR_MASK_GET(req->options, Z_Options_search))
1047 ODR_MASK_SET(resp->options, Z_Options_search);
1048 strcat(options, "srch");
1050 if (ODR_MASK_GET(req->options, Z_Options_present))
1052 ODR_MASK_SET(resp->options, Z_Options_present);
1053 strcat(options, " prst");
1055 if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
1056 assoc->init->bend_delete)
1058 ODR_MASK_SET(resp->options, Z_Options_delSet);
1059 strcat(options, " del");
1061 if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
1062 assoc->init->bend_esrequest)
1064 ODR_MASK_SET(resp->options, Z_Options_extendedServices);
1065 strcat (options, " extendedServices");
1067 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
1069 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
1070 strcat(options, " namedresults");
1072 if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
1074 ODR_MASK_SET(resp->options, Z_Options_scan);
1075 strcat(options, " scan");
1077 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
1079 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
1080 strcat(options, " concurrop");
1082 if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
1084 ODR_MASK_SET(resp->options, Z_Options_sort);
1085 strcat(options, " sort");
1088 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel)
1089 && assoc->init->charneg_response)
1091 Z_OtherInformation **p;
1092 Z_OtherInformationUnit *p0;
1094 yaz_oi_APDU(apdu, &p);
1096 if ((p0=yaz_oi_update(p, assoc->encode, NULL, 0, 0))) {
1097 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
1099 p0->which = Z_OtherInfo_externallyDefinedInfo;
1100 p0->information.externallyDefinedInfo =
1101 assoc->init->charneg_response;
1103 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
1104 strcat(options, " negotiation");
1107 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
1109 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
1110 assoc->version = 2; /* 1 & 2 are equivalent */
1112 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
1114 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
1117 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
1119 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
1123 yaz_log(LOG_LOG, "Negotiated to v%d: %s", assoc->version, options);
1124 assoc->maximumRecordSize = *req->maximumRecordSize;
1125 if (assoc->maximumRecordSize > control_block->maxrecordsize)
1126 assoc->maximumRecordSize = control_block->maxrecordsize;
1127 assoc->preferredMessageSize = *req->preferredMessageSize;
1128 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
1129 assoc->preferredMessageSize = assoc->maximumRecordSize;
1132 assoc->maximumRecordSize = 3000000;
1133 assoc->preferredMessageSize = 3000000;
1136 resp->preferredMessageSize = &assoc->preferredMessageSize;
1137 resp->maximumRecordSize = &assoc->maximumRecordSize;
1139 resp->implementationName = "GFS/YAZ";
1141 if (assoc->init->implementation_id)
1144 odr_malloc (assoc->encode,
1145 strlen(assoc->init->implementation_id) + 10 +
1146 strlen(resp->implementationId));
1147 sprintf (nv, "%s / %s",
1148 resp->implementationId, assoc->init->implementation_id);
1149 resp->implementationId = nv;
1151 if (assoc->init->implementation_name)
1154 odr_malloc (assoc->encode,
1155 strlen(assoc->init->implementation_name) + 10 +
1156 strlen(resp->implementationName));
1157 sprintf (nv, "%s / %s",
1158 resp->implementationName, assoc->init->implementation_name);
1159 resp->implementationName = nv;
1161 if (assoc->init->implementation_version)
1164 odr_malloc (assoc->encode,
1165 strlen(assoc->init->implementation_version) + 10 +
1166 strlen(resp->implementationVersion));
1167 sprintf (nv, "YAZ %s / %s",
1168 resp->implementationVersion,
1169 assoc->init->implementation_version);
1170 resp->implementationVersion = nv;
1173 if (binitres->errcode)
1175 yaz_log(LOG_LOG, "Connection rejected by backend.");
1177 assoc->state = ASSOC_DEAD;
1180 assoc->state = ASSOC_UP;
1185 * These functions should be merged.
1188 static void set_addinfo (Z_DefaultDiagFormat *dr, char *addinfo, ODR odr)
1190 dr->which = Z_DefaultDiagFormat_v2Addinfo;
1191 dr->u.v2Addinfo = odr_strdup (odr, addinfo ? addinfo : "");
1195 * nonsurrogate diagnostic record.
1197 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
1199 Z_Records *rec = (Z_Records *)
1200 odr_malloc (assoc->encode, sizeof(*rec));
1201 int *err = odr_intdup(assoc->encode, error);
1202 Z_DiagRec *drec = (Z_DiagRec *)
1203 odr_malloc (assoc->encode, sizeof(*drec));
1204 Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
1205 odr_malloc (assoc->encode, sizeof(*dr));
1207 yaz_log(LOG_LOG, "[%d] %s %s%s", error, diagbib1_str(error),
1208 addinfo ? " -- " : "", addinfo ? addinfo : "");
1209 rec->which = Z_Records_NSD;
1210 rec->u.nonSurrogateDiagnostic = dr;
1211 dr->diagnosticSetId =
1212 yaz_oidval_to_z3950oid (assoc->encode, CLASS_DIAGSET, VAL_BIB1);
1213 dr->condition = err;
1214 set_addinfo (dr, addinfo, assoc->encode);
1219 * surrogate diagnostic.
1221 static Z_NamePlusRecord *surrogatediagrec(association *assoc, char *dbname,
1222 int error, char *addinfo)
1224 Z_NamePlusRecord *rec = (Z_NamePlusRecord *)
1225 odr_malloc (assoc->encode, sizeof(*rec));
1226 int *err = odr_intdup(assoc->encode, error);
1227 Z_DiagRec *drec = (Z_DiagRec *)odr_malloc (assoc->encode, sizeof(*drec));
1228 Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
1229 odr_malloc (assoc->encode, sizeof(*dr));
1231 yaz_log(LOG_DEBUG, "SurrogateDiagnotic: %d -- %s", error, addinfo);
1232 rec->databaseName = dbname;
1233 rec->which = Z_NamePlusRecord_surrogateDiagnostic;
1234 rec->u.surrogateDiagnostic = drec;
1235 drec->which = Z_DiagRec_defaultFormat;
1236 drec->u.defaultFormat = dr;
1237 dr->diagnosticSetId =
1238 yaz_oidval_to_z3950oid (assoc->encode, CLASS_DIAGSET, VAL_BIB1);
1239 dr->condition = err;
1240 set_addinfo (dr, addinfo, assoc->encode);
1246 * multiple nonsurrogate diagnostics.
1248 static Z_DiagRecs *diagrecs(association *assoc, int error, char *addinfo)
1250 Z_DiagRecs *recs = (Z_DiagRecs *)odr_malloc (assoc->encode, sizeof(*recs));
1251 int *err = odr_intdup(assoc->encode, error);
1252 Z_DiagRec **recp = (Z_DiagRec **)odr_malloc (assoc->encode, sizeof(*recp));
1253 Z_DiagRec *drec = (Z_DiagRec *)odr_malloc (assoc->encode, sizeof(*drec));
1254 Z_DefaultDiagFormat *rec = (Z_DefaultDiagFormat *)
1255 odr_malloc (assoc->encode, sizeof(*rec));
1257 yaz_log(LOG_DEBUG, "DiagRecs: %d -- %s", error, addinfo ? addinfo : "");
1259 recs->num_diagRecs = 1;
1260 recs->diagRecs = recp;
1262 drec->which = Z_DiagRec_defaultFormat;
1263 drec->u.defaultFormat = rec;
1265 rec->diagnosticSetId =
1266 yaz_oidval_to_z3950oid (assoc->encode, CLASS_DIAGSET, VAL_BIB1);
1267 rec->condition = err;
1269 rec->which = Z_DefaultDiagFormat_v2Addinfo;
1270 rec->u.v2Addinfo = odr_strdup (assoc->encode, addinfo ? addinfo : "");
1274 static Z_Records *pack_records(association *a, char *setname, int start,
1275 int *num, Z_RecordComposition *comp,
1276 int *next, int *pres, oid_value format,
1277 Z_ReferenceId *referenceId,
1280 int recno, total_length = 0, toget = *num, dumped_records = 0;
1281 Z_Records *records =
1282 (Z_Records *) odr_malloc (a->encode, sizeof(*records));
1283 Z_NamePlusRecordList *reclist =
1284 (Z_NamePlusRecordList *) odr_malloc (a->encode, sizeof(*reclist));
1285 Z_NamePlusRecord **list =
1286 (Z_NamePlusRecord **) odr_malloc (a->encode, sizeof(*list) * toget);
1288 records->which = Z_Records_DBOSD;
1289 records->u.databaseOrSurDiagnostics = reclist;
1290 reclist->num_records = 0;
1291 reclist->records = list;
1292 *pres = Z_PRES_SUCCESS;
1296 yaz_log(LOG_LOG, "Request to pack %d+%d+%s", start, toget, setname);
1297 yaz_log(LOG_DEBUG, "pms=%d, mrs=%d", a->preferredMessageSize,
1298 a->maximumRecordSize);
1299 for (recno = start; reclist->num_records < toget; recno++)
1302 Z_NamePlusRecord *thisrec;
1303 int this_length = 0;
1305 * we get the number of bytes allocated on the stream before any
1306 * allocation done by the backend - this should give us a reasonable
1307 * idea of the total size of the data so far.
1309 total_length = odr_total(a->encode) - dumped_records;
1315 freq.last_in_set = 0;
1316 freq.setname = setname;
1317 freq.surrogate_flag = 0;
1318 freq.number = recno;
1320 freq.request_format = format;
1321 freq.request_format_raw = oid;
1322 freq.output_format = format;
1323 freq.output_format_raw = 0;
1324 freq.stream = a->encode;
1325 freq.print = a->print;
1326 freq.surrogate_flag = 0;
1327 freq.referenceId = referenceId;
1328 (*a->init->bend_fetch)(a->backend, &freq);
1329 /* backend should be able to signal whether error is system-wide
1330 or only pertaining to current record */
1333 if (!freq.surrogate_flag)
1336 *pres = Z_PRES_FAILURE;
1337 /* for 'present request out of range',
1338 set addinfo to record position if not set */
1339 if (freq.errcode == 13 && freq.errstring == 0)
1341 sprintf (s, "%d", recno);
1344 return diagrec(a, freq.errcode, freq.errstring);
1346 reclist->records[reclist->num_records] =
1347 surrogatediagrec(a, freq.basename, freq.errcode,
1349 reclist->num_records++;
1350 *next = freq.last_in_set ? 0 : recno + 1;
1354 this_length = freq.len;
1356 this_length = odr_total(a->encode) - total_length;
1357 yaz_log(LOG_DEBUG, " fetched record, len=%d, total=%d",
1358 this_length, total_length);
1359 if (this_length + total_length > a->preferredMessageSize)
1361 /* record is small enough, really */
1362 if (this_length <= a->preferredMessageSize)
1364 yaz_log(LOG_DEBUG, " Dropped last normal-sized record");
1365 *pres = Z_PRES_PARTIAL_2;
1368 /* record can only be fetched by itself */
1369 if (this_length < a->maximumRecordSize)
1371 yaz_log(LOG_DEBUG, " Record > prefmsgsz");
1374 yaz_log(LOG_DEBUG, " Dropped it");
1375 reclist->records[reclist->num_records] =
1376 surrogatediagrec(a, freq.basename, 16, 0);
1377 reclist->num_records++;
1378 *next = freq.last_in_set ? 0 : recno + 1;
1379 dumped_records += this_length;
1383 else /* too big entirely */
1385 yaz_log(LOG_LOG, "Record > maxrcdsz this=%d max=%d", this_length, a->maximumRecordSize);
1386 reclist->records[reclist->num_records] =
1387 surrogatediagrec(a, freq.basename, 17, 0);
1388 reclist->num_records++;
1389 *next = freq.last_in_set ? 0 : recno + 1;
1390 dumped_records += this_length;
1395 if (!(thisrec = (Z_NamePlusRecord *)
1396 odr_malloc(a->encode, sizeof(*thisrec))))
1398 if (!(thisrec->databaseName = (char *)odr_malloc(a->encode,
1399 strlen(freq.basename) + 1)))
1401 strcpy(thisrec->databaseName, freq.basename);
1402 thisrec->which = Z_NamePlusRecord_databaseRecord;
1404 if (freq.output_format_raw)
1406 struct oident *ident = oid_getentbyoid(freq.output_format_raw);
1407 freq.output_format = ident->value;
1409 thisrec->u.databaseRecord = z_ext_record(a->encode, freq.output_format,
1410 freq.record, freq.len);
1411 if (!thisrec->u.databaseRecord)
1413 reclist->records[reclist->num_records] = thisrec;
1414 reclist->num_records++;
1415 *next = freq.last_in_set ? 0 : recno + 1;
1417 *num = reclist->num_records;
1421 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
1424 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
1425 bend_search_rr *bsrr =
1426 (bend_search_rr *)nmem_malloc (reqb->request_mem, sizeof(*bsrr));
1428 yaz_log(LOG_LOG, "Got SearchRequest.");
1430 bsrr->request = reqb;
1431 bsrr->association = assoc;
1432 bsrr->referenceId = req->referenceId;
1433 save_referenceId (reqb, bsrr->referenceId);
1435 yaz_log (LOG_LOG, "ResultSet '%s'", req->resultSetName);
1436 if (req->databaseNames)
1439 for (i = 0; i < req->num_databaseNames; i++)
1440 yaz_log (LOG_LOG, "Database '%s'", req->databaseNames[i]);
1442 yaz_log_zquery(req->query);
1444 if (assoc->init->bend_search)
1446 bsrr->setname = req->resultSetName;
1447 bsrr->replace_set = *req->replaceIndicator;
1448 bsrr->num_bases = req->num_databaseNames;
1449 bsrr->basenames = req->databaseNames;
1450 bsrr->query = req->query;
1451 bsrr->stream = assoc->encode;
1452 bsrr->decode = assoc->decode;
1453 bsrr->print = assoc->print;
1456 bsrr->errstring = NULL;
1457 bsrr->search_info = NULL;
1458 (assoc->init->bend_search)(assoc->backend, bsrr);
1462 return response_searchRequest(assoc, reqb, bsrr, fd);
1465 int bend_searchresponse(void *handle, bend_search_rr *bsrr) {return 0;}
1468 * Prepare a searchresponse based on the backend results. We probably want
1469 * to look at making the fetching of records nonblocking as well, but
1470 * so far, we'll keep things simple.
1471 * If bsrt is null, that means we're called in response to a communications
1472 * event, and we'll have to get the response for ourselves.
1474 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
1475 bend_search_rr *bsrt, int *fd)
1477 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
1478 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1479 Z_SearchResponse *resp = (Z_SearchResponse *)
1480 odr_malloc (assoc->encode, sizeof(*resp));
1481 int *nulint = odr_intdup (assoc->encode, 0);
1482 bool_t *sr = odr_intdup(assoc->encode, 1);
1483 int *next = odr_intdup(assoc->encode, 0);
1484 int *none = odr_intdup(assoc->encode, Z_RES_NONE);
1486 apdu->which = Z_APDU_searchResponse;
1487 apdu->u.searchResponse = resp;
1488 resp->referenceId = req->referenceId;
1489 resp->additionalSearchInfo = 0;
1490 resp->otherInfo = 0;
1492 if (!bsrt && !bend_searchresponse(assoc->backend, bsrt))
1494 yaz_log(LOG_FATAL, "Bad result from backend");
1497 else if (bsrt->errcode)
1499 resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
1500 resp->resultCount = nulint;
1501 resp->numberOfRecordsReturned = nulint;
1502 resp->nextResultSetPosition = nulint;
1503 resp->searchStatus = nulint;
1504 resp->resultSetStatus = none;
1505 resp->presentStatus = 0;
1509 int *toget = odr_intdup(assoc->encode, 0);
1510 int *presst = odr_intdup(assoc->encode, 0);
1511 Z_RecordComposition comp, *compp = 0;
1513 yaz_log (LOG_LOG, "resultCount: %d", bsrt->hits);
1516 resp->resultCount = &bsrt->hits;
1518 comp.which = Z_RecordComp_simple;
1519 /* how many records does the user agent want, then? */
1520 if (bsrt->hits <= *req->smallSetUpperBound)
1522 *toget = bsrt->hits;
1523 if ((comp.u.simple = req->smallSetElementSetNames))
1526 else if (bsrt->hits < *req->largeSetLowerBound)
1528 *toget = *req->mediumSetPresentNumber;
1529 if (*toget > bsrt->hits)
1530 *toget = bsrt->hits;
1531 if ((comp.u.simple = req->mediumSetElementSetNames))
1537 if (*toget && !resp->records)
1542 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
1545 form = prefformat->value;
1546 resp->records = pack_records(assoc, req->resultSetName, 1,
1547 toget, compp, next, presst, form, req->referenceId,
1548 req->preferredRecordSyntax);
1551 resp->numberOfRecordsReturned = toget;
1552 resp->nextResultSetPosition = next;
1553 resp->searchStatus = sr;
1554 resp->resultSetStatus = 0;
1555 resp->presentStatus = presst;
1559 if (*resp->resultCount)
1561 resp->numberOfRecordsReturned = nulint;
1562 resp->nextResultSetPosition = next;
1563 resp->searchStatus = sr;
1564 resp->resultSetStatus = 0;
1565 resp->presentStatus = 0;
1568 resp->additionalSearchInfo = bsrt->search_info;
1573 * Maybe we got a little over-friendly when we designed bend_fetch to
1574 * get only one record at a time. Some backends can optimise multiple-record
1575 * fetches, and at any rate, there is some overhead involved in
1576 * all that selecting and hopping around. Problem is, of course, that the
1577 * frontend can't know ahead of time how many records it'll need to
1578 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
1579 * is downright lousy as a bulk data transfer protocol.
1581 * To start with, we'll do the fetching of records from the backend
1582 * in one operation: To save some trips in and out of the event-handler,
1583 * and to simplify the interface to pack_records. At any rate, asynch
1584 * operation is more fun in operations that have an unpredictable execution
1585 * speed - which is normally more true for search than for present.
1587 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
1590 Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
1594 Z_PresentResponse *resp;
1598 yaz_log(LOG_LOG, "Got PresentRequest.");
1600 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
1603 form = prefformat->value;
1604 resp = (Z_PresentResponse *)odr_malloc (assoc->encode, sizeof(*resp));
1606 resp->presentStatus = odr_intdup(assoc->encode, 0);
1607 if (assoc->init->bend_present)
1609 bend_present_rr *bprr = (bend_present_rr *)
1610 nmem_malloc (reqb->request_mem, sizeof(*bprr));
1611 bprr->setname = req->resultSetId;
1612 bprr->start = *req->resultSetStartPoint;
1613 bprr->number = *req->numberOfRecordsRequested;
1614 bprr->format = form;
1615 bprr->comp = req->recordComposition;
1616 bprr->referenceId = req->referenceId;
1617 bprr->stream = assoc->encode;
1618 bprr->print = assoc->print;
1619 bprr->request = reqb;
1620 bprr->association = assoc;
1622 bprr->errstring = NULL;
1623 (*assoc->init->bend_present)(assoc->backend, bprr);
1629 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
1630 *resp->presentStatus = Z_PRES_FAILURE;
1633 apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1634 next = odr_intdup(assoc->encode, 0);
1635 num = odr_intdup(assoc->encode, 0);
1637 apdu->which = Z_APDU_presentResponse;
1638 apdu->u.presentResponse = resp;
1639 resp->referenceId = req->referenceId;
1640 resp->otherInfo = 0;
1644 *num = *req->numberOfRecordsRequested;
1646 pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
1647 num, req->recordComposition, next, resp->presentStatus,
1648 form, req->referenceId, req->preferredRecordSyntax);
1652 resp->numberOfRecordsReturned = num;
1653 resp->nextResultSetPosition = next;
1659 * Scan was implemented rather in a hurry, and with support for only the basic
1660 * elements of the service in the backend API. Suggestions are welcome.
1662 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
1664 Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
1665 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1666 Z_ScanResponse *res = (Z_ScanResponse *)
1667 odr_malloc (assoc->encode, sizeof(*res));
1668 int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
1669 int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
1670 Z_ListEntries *ents = (Z_ListEntries *)
1671 odr_malloc (assoc->encode, sizeof(*ents));
1672 Z_DiagRecs *diagrecs_p = NULL;
1674 bend_scan_rr *bsrr = (bend_scan_rr *)
1675 odr_malloc (assoc->encode, sizeof(*bsrr));
1677 yaz_log(LOG_LOG, "Got ScanRequest");
1679 apdu->which = Z_APDU_scanResponse;
1680 apdu->u.scanResponse = res;
1681 res->referenceId = req->referenceId;
1683 /* if step is absent, set it to 0 */
1684 res->stepSize = odr_intdup(assoc->encode, 0);
1686 *res->stepSize = *req->stepSize;
1688 res->scanStatus = scanStatus;
1689 res->numberOfEntriesReturned = numberOfEntriesReturned;
1690 res->positionOfTerm = 0;
1691 res->entries = ents;
1692 ents->num_entries = 0;
1693 ents->entries = NULL;
1694 ents->num_nonsurrogateDiagnostics = 0;
1695 ents->nonsurrogateDiagnostics = NULL;
1696 res->attributeSet = 0;
1699 if (req->databaseNames)
1702 for (i = 0; i < req->num_databaseNames; i++)
1703 yaz_log (LOG_LOG, "Database '%s'", req->databaseNames[i]);
1705 bsrr->num_bases = req->num_databaseNames;
1706 bsrr->basenames = req->databaseNames;
1707 bsrr->num_entries = *req->numberOfTermsRequested;
1708 bsrr->term = req->termListAndStartPoint;
1709 bsrr->referenceId = req->referenceId;
1710 bsrr->stream = assoc->encode;
1711 bsrr->print = assoc->print;
1712 bsrr->step_size = res->stepSize;
1713 if (req->attributeSet &&
1714 (attset = oid_getentbyoid(req->attributeSet)) &&
1715 (attset->oclass == CLASS_ATTSET || attset->oclass == CLASS_GENERAL))
1716 bsrr->attributeset = attset->value;
1718 bsrr->attributeset = VAL_NONE;
1719 log_scan_term (req->termListAndStartPoint, bsrr->attributeset);
1720 bsrr->term_position = req->preferredPositionInResponse ?
1721 *req->preferredPositionInResponse : 1;
1722 ((int (*)(void *, bend_scan_rr *))
1723 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1725 diagrecs_p = diagrecs(assoc, bsrr->errcode, bsrr->errstring);
1729 Z_Entry **tab = (Z_Entry **)
1730 odr_malloc (assoc->encode, sizeof(*tab) * bsrr->num_entries);
1732 if (bsrr->status == BEND_SCAN_PARTIAL)
1733 *scanStatus = Z_Scan_partial_5;
1735 *scanStatus = Z_Scan_success;
1736 ents->entries = tab;
1737 ents->num_entries = bsrr->num_entries;
1738 res->numberOfEntriesReturned = &ents->num_entries;
1739 res->positionOfTerm = &bsrr->term_position;
1740 for (i = 0; i < bsrr->num_entries; i++)
1746 tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
1747 if (bsrr->entries[i].occurrences >= 0)
1749 e->which = Z_Entry_termInfo;
1750 e->u.termInfo = t = (Z_TermInfo *)
1751 odr_malloc(assoc->encode, sizeof(*t));
1752 t->suggestedAttributes = 0;
1754 t->alternativeTerm = 0;
1755 t->byAttributes = 0;
1756 t->otherTermInfo = 0;
1757 t->globalOccurrences = &bsrr->entries[i].occurrences;
1758 t->term = (Z_Term *)
1759 odr_malloc(assoc->encode, sizeof(*t->term));
1760 t->term->which = Z_Term_general;
1761 t->term->u.general = o =
1762 (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
1763 o->buf = (unsigned char *)
1764 odr_malloc(assoc->encode, o->len = o->size =
1765 strlen(bsrr->entries[i].term));
1766 memcpy(o->buf, bsrr->entries[i].term, o->len);
1767 yaz_log(LOG_DEBUG, " term #%d: '%s' (%d)", i,
1768 bsrr->entries[i].term, bsrr->entries[i].occurrences);
1772 Z_DiagRecs *drecs = diagrecs (assoc,
1773 bsrr->entries[i].errcode,
1774 bsrr->entries[i].errstring);
1775 assert (drecs->num_diagRecs == 1);
1776 e->which = Z_Entry_surrogateDiagnostic;
1777 assert (drecs->diagRecs[0]);
1778 e->u.surrogateDiagnostic = drecs->diagRecs[0];
1784 ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
1785 ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
1790 static Z_APDU *process_sortRequest(association *assoc, request *reqb,
1793 Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
1794 Z_SortResponse *res = (Z_SortResponse *)
1795 odr_malloc (assoc->encode, sizeof(*res));
1796 bend_sort_rr *bsrr = (bend_sort_rr *)
1797 odr_malloc (assoc->encode, sizeof(*bsrr));
1799 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1801 yaz_log(LOG_LOG, "Got SortRequest.");
1803 bsrr->num_input_setnames = req->num_inputResultSetNames;
1804 bsrr->input_setnames = req->inputResultSetNames;
1805 bsrr->referenceId = req->referenceId;
1806 bsrr->output_setname = req->sortedResultSetName;
1807 bsrr->sort_sequence = req->sortSequence;
1808 bsrr->stream = assoc->encode;
1809 bsrr->print = assoc->print;
1811 bsrr->sort_status = Z_SortStatus_failure;
1813 bsrr->errstring = 0;
1815 (*assoc->init->bend_sort)(assoc->backend, bsrr);
1817 res->referenceId = bsrr->referenceId;
1818 res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
1819 res->resultSetStatus = 0;
1822 Z_DiagRecs *dr = diagrecs (assoc, bsrr->errcode, bsrr->errstring);
1823 res->diagnostics = dr->diagRecs;
1824 res->num_diagnostics = dr->num_diagRecs;
1828 res->num_diagnostics = 0;
1829 res->diagnostics = 0;
1833 apdu->which = Z_APDU_sortResponse;
1834 apdu->u.sortResponse = res;
1838 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
1841 Z_DeleteResultSetRequest *req =
1842 reqb->apdu_request->u.deleteResultSetRequest;
1843 Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
1844 odr_malloc (assoc->encode, sizeof(*res));
1845 bend_delete_rr *bdrr = (bend_delete_rr *)
1846 odr_malloc (assoc->encode, sizeof(*bdrr));
1847 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1849 yaz_log(LOG_LOG, "Got DeleteRequest.");
1851 bdrr->num_setnames = req->num_resultSetList;
1852 bdrr->setnames = req->resultSetList;
1853 bdrr->stream = assoc->encode;
1854 bdrr->print = assoc->print;
1855 bdrr->function = *req->deleteFunction;
1856 bdrr->referenceId = req->referenceId;
1858 if (bdrr->num_setnames > 0)
1861 bdrr->statuses = (int*)
1862 odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
1863 bdrr->num_setnames);
1864 for (i = 0; i < bdrr->num_setnames; i++)
1865 bdrr->statuses[i] = 0;
1867 (*assoc->init->bend_delete)(assoc->backend, bdrr);
1869 res->referenceId = req->referenceId;
1871 res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
1873 res->deleteListStatuses = 0;
1874 if (bdrr->num_setnames > 0)
1877 res->deleteListStatuses = (Z_ListStatuses *)
1878 odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
1879 res->deleteListStatuses->num = bdrr->num_setnames;
1880 res->deleteListStatuses->elements =
1882 odr_malloc (assoc->encode,
1883 sizeof(*res->deleteListStatuses->elements) *
1884 bdrr->num_setnames);
1885 for (i = 0; i<bdrr->num_setnames; i++)
1887 res->deleteListStatuses->elements[i] =
1889 odr_malloc (assoc->encode,
1890 sizeof(**res->deleteListStatuses->elements));
1891 res->deleteListStatuses->elements[i]->status = bdrr->statuses+i;
1892 res->deleteListStatuses->elements[i]->id =
1893 odr_strdup (assoc->encode, bdrr->setnames[i]);
1897 res->numberNotDeleted = 0;
1898 res->bulkStatuses = 0;
1899 res->deleteMessage = 0;
1902 apdu->which = Z_APDU_deleteResultSetResponse;
1903 apdu->u.deleteResultSetResponse = res;
1907 static void process_close(association *assoc, request *reqb)
1909 Z_Close *req = reqb->apdu_request->u.close;
1910 static char *reasons[] =
1917 "securityViolation",
1924 yaz_log(LOG_LOG, "Got Close, reason %s, message %s",
1925 reasons[*req->closeReason], req->diagnosticInformation ?
1926 req->diagnosticInformation : "NULL");
1927 if (assoc->version < 3) /* to make do_force respond with close */
1929 do_close_req(assoc, Z_Close_finished,
1930 "Association terminated by client", reqb);
1933 void save_referenceId (request *reqb, Z_ReferenceId *refid)
1937 reqb->len_refid = refid->len;
1938 reqb->refid = (char *)nmem_malloc (reqb->request_mem, refid->len);
1939 memcpy (reqb->refid, refid->buf, refid->len);
1943 reqb->len_refid = 0;
1948 void bend_request_send (bend_association a, bend_request req, Z_APDU *res)
1950 process_z_response (a, req, res);
1953 bend_request bend_request_mk (bend_association a)
1955 request *nreq = request_get (&a->outgoing);
1956 nreq->request_mem = nmem_create ();
1960 Z_ReferenceId *bend_request_getid (ODR odr, bend_request req)
1965 id = (Odr_oct *)odr_malloc (odr, sizeof(*odr));
1966 id->buf = (unsigned char *)odr_malloc (odr, req->len_refid);
1967 id->len = id->size = req->len_refid;
1968 memcpy (id->buf, req->refid, req->len_refid);
1972 void bend_request_destroy (bend_request *req)
1974 nmem_destroy((*req)->request_mem);
1975 request_release(*req);
1979 int bend_backend_respond (bend_association a, bend_request req)
1983 r = process_z_request (a, req, &msg);
1985 yaz_log (LOG_WARN, "%s", msg);
1989 void bend_request_setdata(bend_request r, void *p)
1994 void *bend_request_getdata(bend_request r)
1996 return r->clientData;
1999 static Z_APDU *process_segmentRequest (association *assoc, request *reqb)
2001 bend_segment_rr req;
2003 req.segment = reqb->apdu_request->u.segmentRequest;
2004 req.stream = assoc->encode;
2005 req.decode = assoc->decode;
2006 req.print = assoc->print;
2007 req.association = assoc;
2009 (*assoc->init->bend_segment)(assoc->backend, &req);
2014 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd)
2016 bend_esrequest_rr esrequest;
2018 Z_ExtendedServicesRequest *req =
2019 reqb->apdu_request->u.extendedServicesRequest;
2020 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
2022 Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
2024 yaz_log(LOG_DEBUG,"inside Process esRequest");
2026 esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
2027 esrequest.stream = assoc->encode;
2028 esrequest.decode = assoc->decode;
2029 esrequest.print = assoc->print;
2030 esrequest.errcode = 0;
2031 esrequest.errstring = NULL;
2032 esrequest.request = reqb;
2033 esrequest.association = assoc;
2034 esrequest.taskPackage = 0;
2035 esrequest.referenceId = req->referenceId;
2037 (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
2039 /* If the response is being delayed, return NULL */
2040 if (esrequest.request == NULL)
2043 resp->referenceId = req->referenceId;
2045 if (esrequest.errcode == -1)
2047 /* Backend service indicates request will be processed */
2048 yaz_log(LOG_DEBUG,"Request could be processed...Accepted !");
2049 *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
2051 else if (esrequest.errcode == 0)
2053 /* Backend service indicates request will be processed */
2054 yaz_log(LOG_DEBUG,"Request could be processed...Done !");
2055 *resp->operationStatus = Z_ExtendedServicesResponse_done;
2059 Z_DiagRecs *diagRecs = diagrecs (assoc, esrequest.errcode,
2060 esrequest.errstring);
2062 /* Backend indicates error, request will not be processed */
2063 yaz_log(LOG_DEBUG,"Request could not be processed...failure !");
2064 *resp->operationStatus = Z_ExtendedServicesResponse_failure;
2065 resp->num_diagnostics = diagRecs->num_diagRecs;
2066 resp->diagnostics = diagRecs->diagRecs;
2068 /* Do something with the members of bend_extendedservice */
2069 if (esrequest.taskPackage)
2070 resp->taskPackage = z_ext_record (assoc->encode, VAL_EXTENDED,
2071 (const char *) esrequest.taskPackage,
2073 yaz_log(LOG_DEBUG,"Send the result apdu");