2 * Copyright (c) 1995-2003, Index Data
3 * See the file LICENSE for details.
5 * $Id: seshigh.c,v 1.139 2003-02-17 22:35:48 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, "Closed connection after reject");
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";
521 srw_bend_init(assoc);
523 rr.setname = "default";
526 rr.basenames = &srw_req->database;
529 ext = (Z_External *) odr_malloc(assoc->decode, sizeof(*ext));
530 ext->direct_reference = odr_getoidbystr(assoc->decode,
531 "1.2.840.10003.16.2");
532 ext->indirect_reference = 0;
534 ext->which = Z_External_CQL;
536 ext->u.cql = srw_req->query;
538 ext->u.cql = "noterm";
540 rr.query = (Z_Query *) odr_malloc (assoc->decode, sizeof(*rr.query));
541 rr.query->which = Z_Query_type_104;
542 rr.query->u.type_104 = ext;
544 rr.stream = assoc->encode;
545 rr.decode = assoc->decode;
546 rr.print = assoc->print;
548 rr.association = assoc;
554 yaz_log_zquery(rr.query);
555 (assoc->init->bend_search)(assoc->backend, &rr);
556 srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
559 srw_res->num_diagnostics = 1;
560 srw_res->diagnostics = (Z_SRW_diagnostic *)
561 odr_malloc(assoc->encode, sizeof(*srw_res->diagnostics));
562 srw_res->diagnostics[0].code =
563 odr_intdup(assoc->encode, rr.errcode);
564 srw_res->diagnostics[0].details = rr.errstring;
568 srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
569 if (srw_req->maximumRecords && *srw_req->maximumRecords > 0)
571 int number = *srw_req->maximumRecords;
574 if (srw_req->startRecord)
575 start = *srw_req->startRecord;
576 if (start <= rr.hits)
579 if (start + number > rr.hits)
580 number = rr.hits - start + 1;
581 srw_res->records = (Z_SRW_record *)
582 odr_malloc(assoc->encode,
583 number * sizeof(*srw_res->records));
584 for (i = 0; i<number; i++)
586 srw_res->records[j].recordData_buf = 0;
587 srw_bend_fetch(assoc, i+start, srw_req,
588 srw_res->records + j);
589 if (srw_res->records[j].recordData_buf)
592 srw_res->num_records = j;
594 srw_res->records = 0;
595 yaz_log(LOG_LOG, "got %d records", j);
601 static void process_http_request(association *assoc, request *req)
603 Z_HTTP_Request *hreq = req->gdu_request->u.HTTP_Request;
604 ODR o = assoc->encode;
606 Z_HTTP_Response *hres = 0;
609 if (!strcmp(hreq->method, "GET"))
612 if (strlen(hreq->path) >= 5 && strlen(hreq->path) < 80 &&
613 !memcmp(hreq->path, "/doc/", 5))
618 strcpy(fpath, DOCDIR);
619 strcat(fpath, hreq->path+4);
620 f = fopen(fpath, "rb");
623 if (fstat(fileno(f), &sbuf) || !S_ISREG(sbuf.st_mode))
632 fseek(f, 0L, SEEK_END);
634 if (sz >= 0 && sz < 500000)
636 const char *ctype = "application/octet-stream";
639 p = z_get_HTTP_Response(o, 200);
640 hres = p->u.HTTP_Response;
641 hres->content_buf = (char *) odr_malloc(o, sz + 1);
642 hres->content_len = sz;
643 fseek(f, 0L, SEEK_SET);
644 fread(hres->content_buf, 1, sz, f);
645 if ((cp = strrchr(fpath, '.'))) {
647 if (!strcmp(cp, "png"))
649 else if (!strcmp(cp, "gif"))
651 else if (!strcmp(cp, "xml"))
653 else if (!strcmp(cp, "html"))
656 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
657 yaz_log(LOG_LOG, "OK send page %s size=%ld", fpath, sz);
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"))
699 const char *content_type = z_HTTP_header_lookup(hreq->headers,
701 const char *soap_action = z_HTTP_header_lookup(hreq->headers,
703 if (content_type && soap_action &&
704 !yaz_strcmp_del("text/xml", content_type, "; "))
706 Z_SOAP *soap_package = 0;
710 static Z_SOAP_Handler soap_handlers[2] = {
711 {"http://www.loc.gov/zing/srw/v1.0/", 0,
712 (Z_SOAP_fun) yaz_srw_codec},
716 ret = z_soap_codec(assoc->decode, &soap_package,
717 &hreq->content_buf, &hreq->content_len,
720 if (!ret && soap_package->which == Z_SOAP_generic &&
721 soap_package->u.generic->no == 0)
724 Z_SRW_searchRetrieve *sr = soap_package->u.generic->p;
726 if (sr->which == Z_SRW_searchRetrieve_request)
728 Z_SRW_searchRetrieve *res =
729 yaz_srw_get(assoc->encode,
730 Z_SRW_searchRetrieve_response);
732 if (!sr->u.request->database)
734 const char *p0 = hreq->path, *p1;
737 p1 = strchr(p0, '?');
739 p1 = p0 + strlen(p0);
742 sr->u.request->database =
743 odr_malloc(assoc->decode, p1 - p0 + 1);
744 memcpy (sr->u.request->database, p0, p1 - p0);
745 sr->u.request->database[p1 - p0] = '\0';
748 sr->u.request->database = "Default";
750 srw_bend_search(assoc, req, sr->u.request,
753 soap_package->u.generic->p = res;
758 p = z_get_HTTP_Response(o, 200);
759 hres = p->u.HTTP_Response;
760 ret = z_soap_codec(assoc->encode, &soap_package,
761 &hres->content_buf, &hres->content_len,
763 hres->code = http_code;
764 z_HTTP_header_add(o, &hres->headers, "Content-Type", "text/xml");
767 if (!p) /* still no response ? */
768 p = z_get_HTTP_Response(o, 500);
772 p = z_get_HTTP_Response(o, 405);
773 hres = p->u.HTTP_Response;
775 z_HTTP_header_add(o, &hres->headers, "Allow", "GET, POST");
777 hres = p->u.HTTP_Response;
778 if (!strcmp(hreq->version, "1.0"))
780 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
781 if (v && !strcmp(v, "Keep-Alive"))
785 hres->version = "1.0";
789 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
790 if (v && !strcmp(v, "close"))
794 hres->version = "1.1";
798 z_HTTP_header_add(o, &hres->headers, "Connection", "close");
799 assoc->state = ASSOC_DEAD;
804 const char *alive = z_HTTP_header_lookup(hreq->headers, "Keep-Alive");
806 if (alive && isdigit(*alive))
810 if (t < 0 || t > 3600)
812 iochan_settimeout(assoc->client_chan,t);
813 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
815 process_gdu_response(assoc, req, p);
818 static void process_gdu_request(association *assoc, request *req)
820 if (req->gdu_request->which == Z_GDU_Z3950)
823 req->apdu_request = req->gdu_request->u.z3950;
824 if (process_z_request(assoc, req, &msg) < 0)
825 do_close_req(assoc, Z_Close_systemProblem, msg, req);
827 else if (req->gdu_request->which == Z_GDU_HTTP_Request)
828 process_http_request(assoc, req);
831 do_close_req(assoc, Z_Close_systemProblem, "bad protocol packet", req);
836 * Initiate request processing.
838 static int process_z_request(association *assoc, request *req, char **msg)
844 *msg = "Unknown Error";
845 assert(req && req->state == REQUEST_IDLE);
846 if (req->apdu_request->which != Z_APDU_initRequest && !assoc->init)
848 *msg = "Missing InitRequest";
851 switch (req->apdu_request->which)
853 case Z_APDU_initRequest:
854 iochan_settimeout(assoc->client_chan,
855 statserv_getcontrol()->idle_timeout * 60);
856 res = process_initRequest(assoc, req); break;
857 case Z_APDU_searchRequest:
858 res = process_searchRequest(assoc, req, &fd); break;
859 case Z_APDU_presentRequest:
860 res = process_presentRequest(assoc, req, &fd); break;
861 case Z_APDU_scanRequest:
862 if (assoc->init->bend_scan)
863 res = process_scanRequest(assoc, req, &fd);
866 *msg = "Cannot handle Scan APDU";
870 case Z_APDU_extendedServicesRequest:
871 if (assoc->init->bend_esrequest)
872 res = process_ESRequest(assoc, req, &fd);
875 *msg = "Cannot handle Extended Services APDU";
879 case Z_APDU_sortRequest:
880 if (assoc->init->bend_sort)
881 res = process_sortRequest(assoc, req, &fd);
884 *msg = "Cannot handle Sort APDU";
889 process_close(assoc, req);
891 case Z_APDU_deleteResultSetRequest:
892 if (assoc->init->bend_delete)
893 res = process_deleteRequest(assoc, req, &fd);
896 *msg = "Cannot handle Delete APDU";
900 case Z_APDU_segmentRequest:
901 if (assoc->init->bend_segment)
903 res = process_segmentRequest (assoc, req);
907 *msg = "Cannot handle Segment APDU";
912 *msg = "Bad APDU received";
917 yaz_log(LOG_DEBUG, " result immediately available");
918 retval = process_z_response(assoc, req, res);
922 yaz_log(LOG_DEBUG, " result unavailble");
925 else /* no result yet - one will be provided later */
929 /* Set up an I/O handler for the fd supplied by the backend */
931 yaz_log(LOG_DEBUG, " establishing handler for result");
932 req->state = REQUEST_PENDING;
933 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT)))
935 iochan_setdata(chan, assoc);
942 * Handle message from the backend.
944 void backend_response(IOCHAN i, int event)
946 association *assoc = (association *)iochan_getdata(i);
947 request *req = request_head(&assoc->incoming);
951 yaz_log(LOG_DEBUG, "backend_response");
952 assert(assoc && req && req->state != REQUEST_IDLE);
953 /* determine what it is we're waiting for */
954 switch (req->apdu_request->which)
956 case Z_APDU_searchRequest:
957 res = response_searchRequest(assoc, req, 0, &fd); break;
959 case Z_APDU_presentRequest:
960 res = response_presentRequest(assoc, req, 0, &fd); break;
961 case Z_APDU_scanRequest:
962 res = response_scanRequest(assoc, req, 0, &fd); break;
965 yaz_log(LOG_WARN, "Serious programmer's lapse or bug");
968 if ((res && process_z_response(assoc, req, res) < 0) || fd < 0)
970 yaz_log(LOG_LOG, "Fatal error when talking to backend");
971 do_close(assoc, Z_Close_systemProblem, 0);
975 else if (!res) /* no result yet - try again later */
977 yaz_log(LOG_DEBUG, " no result yet");
978 iochan_setfd(i, fd); /* in case fd has changed */
983 * Encode response, and transfer the request structure to the outgoing queue.
985 static int process_gdu_response(association *assoc, request *req, Z_GDU *res)
987 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
989 if (assoc->print && !z_GDU(assoc->print, &res, 0, 0))
991 yaz_log(LOG_WARN, "ODR print error: %s",
992 odr_errmsg(odr_geterror(assoc->print)));
993 odr_reset(assoc->print);
995 if (!z_GDU(assoc->encode, &res, 0, 0))
997 yaz_log(LOG_WARN, "ODR error when encoding response: %s",
998 odr_errmsg(odr_geterror(assoc->decode)));
1001 req->response = odr_getbuf(assoc->encode, &req->len_response,
1002 &req->size_response);
1003 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
1004 odr_reset(assoc->encode);
1005 req->state = REQUEST_IDLE;
1006 request_enq(&assoc->outgoing, req);
1007 /* turn the work over to the ir_session handler */
1008 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
1009 assoc->cs_put_mask = EVENT_OUTPUT;
1010 /* Is there more work to be done? give that to the input handler too */
1012 if (request_head(&assoc->incoming))
1014 yaz_log (LOG_DEBUG, "more work to be done");
1015 iochan_setevent(assoc->client_chan, EVENT_WORK);
1022 * Encode response, and transfer the request structure to the outgoing queue.
1024 static int process_z_response(association *assoc, request *req, Z_APDU *res)
1026 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
1028 if (assoc->print && !z_APDU(assoc->print, &res, 0, 0))
1030 yaz_log(LOG_WARN, "ODR print error: %s",
1031 odr_errmsg(odr_geterror(assoc->print)));
1032 odr_reset(assoc->print);
1034 if (!z_APDU(assoc->encode, &res, 0, 0))
1036 yaz_log(LOG_WARN, "ODR error when encoding response: %s",
1037 odr_errmsg(odr_geterror(assoc->decode)));
1040 req->response = odr_getbuf(assoc->encode, &req->len_response,
1041 &req->size_response);
1042 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
1043 odr_reset(assoc->encode);
1044 req->state = REQUEST_IDLE;
1045 request_enq(&assoc->outgoing, req);
1046 /* turn the work over to the ir_session handler */
1047 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
1048 assoc->cs_put_mask = EVENT_OUTPUT;
1049 /* Is there more work to be done? give that to the input handler too */
1051 if (request_head(&assoc->incoming))
1053 yaz_log (LOG_DEBUG, "more work to be done");
1054 iochan_setevent(assoc->client_chan, EVENT_WORK);
1061 * Handle init request.
1062 * At the moment, we don't check the options
1063 * anywhere else in the code - we just try not to do anything that would
1064 * break a naive client. We'll toss 'em into the association block when
1065 * we need them there.
1067 static Z_APDU *process_initRequest(association *assoc, request *reqb)
1069 statserv_options_block *cb = statserv_getcontrol();
1070 Z_InitRequest *req = reqb->apdu_request->u.initRequest;
1071 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
1072 Z_InitResponse *resp = apdu->u.initResponse;
1073 bend_initresult *binitres;
1077 xfree (assoc->init);
1078 assoc->init = (bend_initrequest *) xmalloc (sizeof(*assoc->init));
1080 yaz_log(LOG_LOG, "Got initRequest");
1081 if (req->implementationId)
1082 yaz_log(LOG_LOG, "Id: %s", req->implementationId);
1083 if (req->implementationName)
1084 yaz_log(LOG_LOG, "Name: %s", req->implementationName);
1085 if (req->implementationVersion)
1086 yaz_log(LOG_LOG, "Version: %s", req->implementationVersion);
1088 assoc->init->stream = assoc->encode;
1089 assoc->init->print = assoc->print;
1090 assoc->init->auth = req->idAuthentication;
1091 assoc->init->referenceId = req->referenceId;
1092 assoc->init->implementation_version = 0;
1093 assoc->init->implementation_id = 0;
1094 assoc->init->implementation_name = 0;
1095 assoc->init->bend_sort = NULL;
1096 assoc->init->bend_search = NULL;
1097 assoc->init->bend_present = NULL;
1098 assoc->init->bend_esrequest = NULL;
1099 assoc->init->bend_delete = NULL;
1100 assoc->init->bend_scan = NULL;
1101 assoc->init->bend_segment = NULL;
1102 assoc->init->bend_fetch = NULL;
1103 assoc->init->charneg_request = NULL;
1104 assoc->init->charneg_response = NULL;
1105 assoc->init->decode = assoc->decode;
1107 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
1109 Z_CharSetandLanguageNegotiation *negotiation =
1110 yaz_get_charneg_record (req->otherInfo);
1111 if (negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
1112 assoc->init->charneg_request = negotiation;
1115 assoc->init->peer_name =
1116 odr_strdup (assoc->encode, cs_addrstr(assoc->client_link));
1117 if (!(binitres = (*cb->bend_init)(assoc->init)))
1119 yaz_log(LOG_WARN, "Bad response from backend.");
1123 assoc->backend = binitres->handle;
1124 if ((assoc->init->bend_sort))
1125 yaz_log (LOG_DEBUG, "Sort handler installed");
1126 if ((assoc->init->bend_search))
1127 yaz_log (LOG_DEBUG, "Search handler installed");
1128 if ((assoc->init->bend_present))
1129 yaz_log (LOG_DEBUG, "Present handler installed");
1130 if ((assoc->init->bend_esrequest))
1131 yaz_log (LOG_DEBUG, "ESRequest handler installed");
1132 if ((assoc->init->bend_delete))
1133 yaz_log (LOG_DEBUG, "Delete handler installed");
1134 if ((assoc->init->bend_scan))
1135 yaz_log (LOG_DEBUG, "Scan handler installed");
1136 if ((assoc->init->bend_segment))
1137 yaz_log (LOG_DEBUG, "Segment handler installed");
1139 resp->referenceId = req->referenceId;
1141 /* let's tell the client what we can do */
1142 if (ODR_MASK_GET(req->options, Z_Options_search))
1144 ODR_MASK_SET(resp->options, Z_Options_search);
1145 strcat(options, "srch");
1147 if (ODR_MASK_GET(req->options, Z_Options_present))
1149 ODR_MASK_SET(resp->options, Z_Options_present);
1150 strcat(options, " prst");
1152 if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
1153 assoc->init->bend_delete)
1155 ODR_MASK_SET(resp->options, Z_Options_delSet);
1156 strcat(options, " del");
1158 if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
1159 assoc->init->bend_esrequest)
1161 ODR_MASK_SET(resp->options, Z_Options_extendedServices);
1162 strcat (options, " extendedServices");
1164 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
1166 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
1167 strcat(options, " namedresults");
1169 if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
1171 ODR_MASK_SET(resp->options, Z_Options_scan);
1172 strcat(options, " scan");
1174 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
1176 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
1177 strcat(options, " concurrop");
1179 if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
1181 ODR_MASK_SET(resp->options, Z_Options_sort);
1182 strcat(options, " sort");
1185 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel)
1186 && assoc->init->charneg_response)
1188 Z_OtherInformation **p;
1189 Z_OtherInformationUnit *p0;
1191 yaz_oi_APDU(apdu, &p);
1193 if ((p0=yaz_oi_update(p, assoc->encode, NULL, 0, 0))) {
1194 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
1196 p0->which = Z_OtherInfo_externallyDefinedInfo;
1197 p0->information.externallyDefinedInfo =
1198 assoc->init->charneg_response;
1200 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
1201 strcat(options, " negotiation");
1204 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
1206 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
1207 assoc->version = 2; /* 1 & 2 are equivalent */
1209 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
1211 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
1214 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
1216 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
1220 yaz_log(LOG_LOG, "Negotiated to v%d: %s", assoc->version, options);
1221 assoc->maximumRecordSize = *req->maximumRecordSize;
1222 if (assoc->maximumRecordSize > control_block->maxrecordsize)
1223 assoc->maximumRecordSize = control_block->maxrecordsize;
1224 assoc->preferredMessageSize = *req->preferredMessageSize;
1225 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
1226 assoc->preferredMessageSize = assoc->maximumRecordSize;
1229 assoc->maximumRecordSize = 3000000;
1230 assoc->preferredMessageSize = 3000000;
1233 resp->preferredMessageSize = &assoc->preferredMessageSize;
1234 resp->maximumRecordSize = &assoc->maximumRecordSize;
1236 resp->implementationName = "GFS/YAZ";
1238 if (assoc->init->implementation_id)
1241 odr_malloc (assoc->encode,
1242 strlen(assoc->init->implementation_id) + 10 +
1243 strlen(resp->implementationId));
1244 sprintf (nv, "%s / %s",
1245 resp->implementationId, assoc->init->implementation_id);
1246 resp->implementationId = nv;
1248 if (assoc->init->implementation_name)
1251 odr_malloc (assoc->encode,
1252 strlen(assoc->init->implementation_name) + 10 +
1253 strlen(resp->implementationName));
1254 sprintf (nv, "%s / %s",
1255 resp->implementationName, assoc->init->implementation_name);
1256 resp->implementationName = nv;
1258 if (assoc->init->implementation_version)
1261 odr_malloc (assoc->encode,
1262 strlen(assoc->init->implementation_version) + 10 +
1263 strlen(resp->implementationVersion));
1264 sprintf (nv, "YAZ %s / %s",
1265 resp->implementationVersion,
1266 assoc->init->implementation_version);
1267 resp->implementationVersion = nv;
1270 if (binitres->errcode)
1272 yaz_log(LOG_LOG, "Connection rejected by backend.");
1274 assoc->state = ASSOC_DEAD;
1277 assoc->state = ASSOC_UP;
1282 * These functions should be merged.
1285 static void set_addinfo (Z_DefaultDiagFormat *dr, char *addinfo, ODR odr)
1287 dr->which = Z_DefaultDiagFormat_v2Addinfo;
1288 dr->u.v2Addinfo = odr_strdup (odr, addinfo ? addinfo : "");
1292 * nonsurrogate diagnostic record.
1294 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
1296 Z_Records *rec = (Z_Records *)
1297 odr_malloc (assoc->encode, sizeof(*rec));
1298 int *err = odr_intdup(assoc->encode, error);
1299 Z_DiagRec *drec = (Z_DiagRec *)
1300 odr_malloc (assoc->encode, sizeof(*drec));
1301 Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
1302 odr_malloc (assoc->encode, sizeof(*dr));
1304 yaz_log(LOG_LOG, "[%d] %s %s%s", error, diagbib1_str(error),
1305 addinfo ? " -- " : "", addinfo ? addinfo : "");
1306 rec->which = Z_Records_NSD;
1307 rec->u.nonSurrogateDiagnostic = dr;
1308 dr->diagnosticSetId =
1309 yaz_oidval_to_z3950oid (assoc->encode, CLASS_DIAGSET, VAL_BIB1);
1310 dr->condition = err;
1311 set_addinfo (dr, addinfo, assoc->encode);
1316 * surrogate diagnostic.
1318 static Z_NamePlusRecord *surrogatediagrec(association *assoc, char *dbname,
1319 int error, char *addinfo)
1321 Z_NamePlusRecord *rec = (Z_NamePlusRecord *)
1322 odr_malloc (assoc->encode, sizeof(*rec));
1323 int *err = odr_intdup(assoc->encode, error);
1324 Z_DiagRec *drec = (Z_DiagRec *)odr_malloc (assoc->encode, sizeof(*drec));
1325 Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
1326 odr_malloc (assoc->encode, sizeof(*dr));
1328 yaz_log(LOG_DEBUG, "SurrogateDiagnotic: %d -- %s", error, addinfo);
1329 rec->databaseName = dbname;
1330 rec->which = Z_NamePlusRecord_surrogateDiagnostic;
1331 rec->u.surrogateDiagnostic = drec;
1332 drec->which = Z_DiagRec_defaultFormat;
1333 drec->u.defaultFormat = dr;
1334 dr->diagnosticSetId =
1335 yaz_oidval_to_z3950oid (assoc->encode, CLASS_DIAGSET, VAL_BIB1);
1336 dr->condition = err;
1337 set_addinfo (dr, addinfo, assoc->encode);
1343 * multiple nonsurrogate diagnostics.
1345 static Z_DiagRecs *diagrecs(association *assoc, int error, char *addinfo)
1347 Z_DiagRecs *recs = (Z_DiagRecs *)odr_malloc (assoc->encode, sizeof(*recs));
1348 int *err = odr_intdup(assoc->encode, error);
1349 Z_DiagRec **recp = (Z_DiagRec **)odr_malloc (assoc->encode, sizeof(*recp));
1350 Z_DiagRec *drec = (Z_DiagRec *)odr_malloc (assoc->encode, sizeof(*drec));
1351 Z_DefaultDiagFormat *rec = (Z_DefaultDiagFormat *)
1352 odr_malloc (assoc->encode, sizeof(*rec));
1354 yaz_log(LOG_DEBUG, "DiagRecs: %d -- %s", error, addinfo ? addinfo : "");
1356 recs->num_diagRecs = 1;
1357 recs->diagRecs = recp;
1359 drec->which = Z_DiagRec_defaultFormat;
1360 drec->u.defaultFormat = rec;
1362 rec->diagnosticSetId =
1363 yaz_oidval_to_z3950oid (assoc->encode, CLASS_DIAGSET, VAL_BIB1);
1364 rec->condition = err;
1366 rec->which = Z_DefaultDiagFormat_v2Addinfo;
1367 rec->u.v2Addinfo = odr_strdup (assoc->encode, addinfo ? addinfo : "");
1371 static Z_Records *pack_records(association *a, char *setname, int start,
1372 int *num, Z_RecordComposition *comp,
1373 int *next, int *pres, oid_value format,
1374 Z_ReferenceId *referenceId,
1377 int recno, total_length = 0, toget = *num, dumped_records = 0;
1378 Z_Records *records =
1379 (Z_Records *) odr_malloc (a->encode, sizeof(*records));
1380 Z_NamePlusRecordList *reclist =
1381 (Z_NamePlusRecordList *) odr_malloc (a->encode, sizeof(*reclist));
1382 Z_NamePlusRecord **list =
1383 (Z_NamePlusRecord **) odr_malloc (a->encode, sizeof(*list) * toget);
1385 records->which = Z_Records_DBOSD;
1386 records->u.databaseOrSurDiagnostics = reclist;
1387 reclist->num_records = 0;
1388 reclist->records = list;
1389 *pres = Z_PRES_SUCCESS;
1393 yaz_log(LOG_LOG, "Request to pack %d+%d+%s", start, toget, setname);
1394 yaz_log(LOG_DEBUG, "pms=%d, mrs=%d", a->preferredMessageSize,
1395 a->maximumRecordSize);
1396 for (recno = start; reclist->num_records < toget; recno++)
1399 Z_NamePlusRecord *thisrec;
1400 int this_length = 0;
1402 * we get the number of bytes allocated on the stream before any
1403 * allocation done by the backend - this should give us a reasonable
1404 * idea of the total size of the data so far.
1406 total_length = odr_total(a->encode) - dumped_records;
1412 freq.last_in_set = 0;
1413 freq.setname = setname;
1414 freq.surrogate_flag = 0;
1415 freq.number = recno;
1417 freq.request_format = format;
1418 freq.request_format_raw = oid;
1419 freq.output_format = format;
1420 freq.output_format_raw = 0;
1421 freq.stream = a->encode;
1422 freq.print = a->print;
1423 freq.surrogate_flag = 0;
1424 freq.referenceId = referenceId;
1425 (*a->init->bend_fetch)(a->backend, &freq);
1426 /* backend should be able to signal whether error is system-wide
1427 or only pertaining to current record */
1430 if (!freq.surrogate_flag)
1433 *pres = Z_PRES_FAILURE;
1434 /* for 'present request out of range',
1435 set addinfo to record position if not set */
1436 if (freq.errcode == 13 && freq.errstring == 0)
1438 sprintf (s, "%d", recno);
1441 return diagrec(a, freq.errcode, freq.errstring);
1443 reclist->records[reclist->num_records] =
1444 surrogatediagrec(a, freq.basename, freq.errcode,
1446 reclist->num_records++;
1447 *next = freq.last_in_set ? 0 : recno + 1;
1451 this_length = freq.len;
1453 this_length = odr_total(a->encode) - total_length;
1454 yaz_log(LOG_DEBUG, " fetched record, len=%d, total=%d",
1455 this_length, total_length);
1456 if (this_length + total_length > a->preferredMessageSize)
1458 /* record is small enough, really */
1459 if (this_length <= a->preferredMessageSize)
1461 yaz_log(LOG_DEBUG, " Dropped last normal-sized record");
1462 *pres = Z_PRES_PARTIAL_2;
1465 /* record can only be fetched by itself */
1466 if (this_length < a->maximumRecordSize)
1468 yaz_log(LOG_DEBUG, " Record > prefmsgsz");
1471 yaz_log(LOG_DEBUG, " Dropped it");
1472 reclist->records[reclist->num_records] =
1473 surrogatediagrec(a, freq.basename, 16, 0);
1474 reclist->num_records++;
1475 *next = freq.last_in_set ? 0 : recno + 1;
1476 dumped_records += this_length;
1480 else /* too big entirely */
1482 yaz_log(LOG_LOG, "Record > maxrcdsz this=%d max=%d", this_length, a->maximumRecordSize);
1483 reclist->records[reclist->num_records] =
1484 surrogatediagrec(a, freq.basename, 17, 0);
1485 reclist->num_records++;
1486 *next = freq.last_in_set ? 0 : recno + 1;
1487 dumped_records += this_length;
1492 if (!(thisrec = (Z_NamePlusRecord *)
1493 odr_malloc(a->encode, sizeof(*thisrec))))
1495 if (!(thisrec->databaseName = (char *)odr_malloc(a->encode,
1496 strlen(freq.basename) + 1)))
1498 strcpy(thisrec->databaseName, freq.basename);
1499 thisrec->which = Z_NamePlusRecord_databaseRecord;
1501 if (freq.output_format_raw)
1503 struct oident *ident = oid_getentbyoid(freq.output_format_raw);
1504 freq.output_format = ident->value;
1506 thisrec->u.databaseRecord = z_ext_record(a->encode, freq.output_format,
1507 freq.record, freq.len);
1508 if (!thisrec->u.databaseRecord)
1510 reclist->records[reclist->num_records] = thisrec;
1511 reclist->num_records++;
1512 *next = freq.last_in_set ? 0 : recno + 1;
1514 *num = reclist->num_records;
1518 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
1521 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
1522 bend_search_rr *bsrr =
1523 (bend_search_rr *)nmem_malloc (reqb->request_mem, sizeof(*bsrr));
1525 yaz_log(LOG_LOG, "Got SearchRequest.");
1527 bsrr->request = reqb;
1528 bsrr->association = assoc;
1529 bsrr->referenceId = req->referenceId;
1530 save_referenceId (reqb, bsrr->referenceId);
1532 yaz_log (LOG_LOG, "ResultSet '%s'", req->resultSetName);
1533 if (req->databaseNames)
1536 for (i = 0; i < req->num_databaseNames; i++)
1537 yaz_log (LOG_LOG, "Database '%s'", req->databaseNames[i]);
1539 yaz_log_zquery(req->query);
1541 if (assoc->init->bend_search)
1543 bsrr->setname = req->resultSetName;
1544 bsrr->replace_set = *req->replaceIndicator;
1545 bsrr->num_bases = req->num_databaseNames;
1546 bsrr->basenames = req->databaseNames;
1547 bsrr->query = req->query;
1548 bsrr->stream = assoc->encode;
1549 bsrr->decode = assoc->decode;
1550 bsrr->print = assoc->print;
1553 bsrr->errstring = NULL;
1554 bsrr->search_info = NULL;
1555 (assoc->init->bend_search)(assoc->backend, bsrr);
1559 return response_searchRequest(assoc, reqb, bsrr, fd);
1562 int bend_searchresponse(void *handle, bend_search_rr *bsrr) {return 0;}
1565 * Prepare a searchresponse based on the backend results. We probably want
1566 * to look at making the fetching of records nonblocking as well, but
1567 * so far, we'll keep things simple.
1568 * If bsrt is null, that means we're called in response to a communications
1569 * event, and we'll have to get the response for ourselves.
1571 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
1572 bend_search_rr *bsrt, int *fd)
1574 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
1575 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1576 Z_SearchResponse *resp = (Z_SearchResponse *)
1577 odr_malloc (assoc->encode, sizeof(*resp));
1578 int *nulint = odr_intdup (assoc->encode, 0);
1579 bool_t *sr = odr_intdup(assoc->encode, 1);
1580 int *next = odr_intdup(assoc->encode, 0);
1581 int *none = odr_intdup(assoc->encode, Z_RES_NONE);
1583 apdu->which = Z_APDU_searchResponse;
1584 apdu->u.searchResponse = resp;
1585 resp->referenceId = req->referenceId;
1586 resp->additionalSearchInfo = 0;
1587 resp->otherInfo = 0;
1589 if (!bsrt && !bend_searchresponse(assoc->backend, bsrt))
1591 yaz_log(LOG_FATAL, "Bad result from backend");
1594 else if (bsrt->errcode)
1596 resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
1597 resp->resultCount = nulint;
1598 resp->numberOfRecordsReturned = nulint;
1599 resp->nextResultSetPosition = nulint;
1600 resp->searchStatus = nulint;
1601 resp->resultSetStatus = none;
1602 resp->presentStatus = 0;
1606 int *toget = odr_intdup(assoc->encode, 0);
1607 int *presst = odr_intdup(assoc->encode, 0);
1608 Z_RecordComposition comp, *compp = 0;
1610 yaz_log (LOG_LOG, "resultCount: %d", bsrt->hits);
1613 resp->resultCount = &bsrt->hits;
1615 comp.which = Z_RecordComp_simple;
1616 /* how many records does the user agent want, then? */
1617 if (bsrt->hits <= *req->smallSetUpperBound)
1619 *toget = bsrt->hits;
1620 if ((comp.u.simple = req->smallSetElementSetNames))
1623 else if (bsrt->hits < *req->largeSetLowerBound)
1625 *toget = *req->mediumSetPresentNumber;
1626 if (*toget > bsrt->hits)
1627 *toget = bsrt->hits;
1628 if ((comp.u.simple = req->mediumSetElementSetNames))
1634 if (*toget && !resp->records)
1639 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
1642 form = prefformat->value;
1643 resp->records = pack_records(assoc, req->resultSetName, 1,
1644 toget, compp, next, presst, form, req->referenceId,
1645 req->preferredRecordSyntax);
1648 resp->numberOfRecordsReturned = toget;
1649 resp->nextResultSetPosition = next;
1650 resp->searchStatus = sr;
1651 resp->resultSetStatus = 0;
1652 resp->presentStatus = presst;
1656 if (*resp->resultCount)
1658 resp->numberOfRecordsReturned = nulint;
1659 resp->nextResultSetPosition = next;
1660 resp->searchStatus = sr;
1661 resp->resultSetStatus = 0;
1662 resp->presentStatus = 0;
1665 resp->additionalSearchInfo = bsrt->search_info;
1670 * Maybe we got a little over-friendly when we designed bend_fetch to
1671 * get only one record at a time. Some backends can optimise multiple-record
1672 * fetches, and at any rate, there is some overhead involved in
1673 * all that selecting and hopping around. Problem is, of course, that the
1674 * frontend can't know ahead of time how many records it'll need to
1675 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
1676 * is downright lousy as a bulk data transfer protocol.
1678 * To start with, we'll do the fetching of records from the backend
1679 * in one operation: To save some trips in and out of the event-handler,
1680 * and to simplify the interface to pack_records. At any rate, asynch
1681 * operation is more fun in operations that have an unpredictable execution
1682 * speed - which is normally more true for search than for present.
1684 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
1687 Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
1691 Z_PresentResponse *resp;
1695 yaz_log(LOG_LOG, "Got PresentRequest.");
1697 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
1700 form = prefformat->value;
1701 resp = (Z_PresentResponse *)odr_malloc (assoc->encode, sizeof(*resp));
1703 resp->presentStatus = odr_intdup(assoc->encode, 0);
1704 if (assoc->init->bend_present)
1706 bend_present_rr *bprr = (bend_present_rr *)
1707 nmem_malloc (reqb->request_mem, sizeof(*bprr));
1708 bprr->setname = req->resultSetId;
1709 bprr->start = *req->resultSetStartPoint;
1710 bprr->number = *req->numberOfRecordsRequested;
1711 bprr->format = form;
1712 bprr->comp = req->recordComposition;
1713 bprr->referenceId = req->referenceId;
1714 bprr->stream = assoc->encode;
1715 bprr->print = assoc->print;
1716 bprr->request = reqb;
1717 bprr->association = assoc;
1719 bprr->errstring = NULL;
1720 (*assoc->init->bend_present)(assoc->backend, bprr);
1726 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
1727 *resp->presentStatus = Z_PRES_FAILURE;
1730 apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1731 next = odr_intdup(assoc->encode, 0);
1732 num = odr_intdup(assoc->encode, 0);
1734 apdu->which = Z_APDU_presentResponse;
1735 apdu->u.presentResponse = resp;
1736 resp->referenceId = req->referenceId;
1737 resp->otherInfo = 0;
1741 *num = *req->numberOfRecordsRequested;
1743 pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
1744 num, req->recordComposition, next, resp->presentStatus,
1745 form, req->referenceId, req->preferredRecordSyntax);
1749 resp->numberOfRecordsReturned = num;
1750 resp->nextResultSetPosition = next;
1756 * Scan was implemented rather in a hurry, and with support for only the basic
1757 * elements of the service in the backend API. Suggestions are welcome.
1759 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
1761 Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
1762 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1763 Z_ScanResponse *res = (Z_ScanResponse *)
1764 odr_malloc (assoc->encode, sizeof(*res));
1765 int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
1766 int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
1767 Z_ListEntries *ents = (Z_ListEntries *)
1768 odr_malloc (assoc->encode, sizeof(*ents));
1769 Z_DiagRecs *diagrecs_p = NULL;
1771 bend_scan_rr *bsrr = (bend_scan_rr *)
1772 odr_malloc (assoc->encode, sizeof(*bsrr));
1774 yaz_log(LOG_LOG, "Got ScanRequest");
1776 apdu->which = Z_APDU_scanResponse;
1777 apdu->u.scanResponse = res;
1778 res->referenceId = req->referenceId;
1780 /* if step is absent, set it to 0 */
1781 res->stepSize = odr_intdup(assoc->encode, 0);
1783 *res->stepSize = *req->stepSize;
1785 res->scanStatus = scanStatus;
1786 res->numberOfEntriesReturned = numberOfEntriesReturned;
1787 res->positionOfTerm = 0;
1788 res->entries = ents;
1789 ents->num_entries = 0;
1790 ents->entries = NULL;
1791 ents->num_nonsurrogateDiagnostics = 0;
1792 ents->nonsurrogateDiagnostics = NULL;
1793 res->attributeSet = 0;
1796 if (req->databaseNames)
1799 for (i = 0; i < req->num_databaseNames; i++)
1800 yaz_log (LOG_LOG, "Database '%s'", req->databaseNames[i]);
1802 bsrr->num_bases = req->num_databaseNames;
1803 bsrr->basenames = req->databaseNames;
1804 bsrr->num_entries = *req->numberOfTermsRequested;
1805 bsrr->term = req->termListAndStartPoint;
1806 bsrr->referenceId = req->referenceId;
1807 bsrr->stream = assoc->encode;
1808 bsrr->print = assoc->print;
1809 bsrr->step_size = res->stepSize;
1810 if (req->attributeSet &&
1811 (attset = oid_getentbyoid(req->attributeSet)) &&
1812 (attset->oclass == CLASS_ATTSET || attset->oclass == CLASS_GENERAL))
1813 bsrr->attributeset = attset->value;
1815 bsrr->attributeset = VAL_NONE;
1816 log_scan_term (req->termListAndStartPoint, bsrr->attributeset);
1817 bsrr->term_position = req->preferredPositionInResponse ?
1818 *req->preferredPositionInResponse : 1;
1819 ((int (*)(void *, bend_scan_rr *))
1820 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1822 diagrecs_p = diagrecs(assoc, bsrr->errcode, bsrr->errstring);
1826 Z_Entry **tab = (Z_Entry **)
1827 odr_malloc (assoc->encode, sizeof(*tab) * bsrr->num_entries);
1829 if (bsrr->status == BEND_SCAN_PARTIAL)
1830 *scanStatus = Z_Scan_partial_5;
1832 *scanStatus = Z_Scan_success;
1833 ents->entries = tab;
1834 ents->num_entries = bsrr->num_entries;
1835 res->numberOfEntriesReturned = &ents->num_entries;
1836 res->positionOfTerm = &bsrr->term_position;
1837 for (i = 0; i < bsrr->num_entries; i++)
1843 tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
1844 if (bsrr->entries[i].occurrences >= 0)
1846 e->which = Z_Entry_termInfo;
1847 e->u.termInfo = t = (Z_TermInfo *)
1848 odr_malloc(assoc->encode, sizeof(*t));
1849 t->suggestedAttributes = 0;
1851 t->alternativeTerm = 0;
1852 t->byAttributes = 0;
1853 t->otherTermInfo = 0;
1854 t->globalOccurrences = &bsrr->entries[i].occurrences;
1855 t->term = (Z_Term *)
1856 odr_malloc(assoc->encode, sizeof(*t->term));
1857 t->term->which = Z_Term_general;
1858 t->term->u.general = o =
1859 (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
1860 o->buf = (unsigned char *)
1861 odr_malloc(assoc->encode, o->len = o->size =
1862 strlen(bsrr->entries[i].term));
1863 memcpy(o->buf, bsrr->entries[i].term, o->len);
1864 yaz_log(LOG_DEBUG, " term #%d: '%s' (%d)", i,
1865 bsrr->entries[i].term, bsrr->entries[i].occurrences);
1869 Z_DiagRecs *drecs = diagrecs (assoc,
1870 bsrr->entries[i].errcode,
1871 bsrr->entries[i].errstring);
1872 assert (drecs->num_diagRecs == 1);
1873 e->which = Z_Entry_surrogateDiagnostic;
1874 assert (drecs->diagRecs[0]);
1875 e->u.surrogateDiagnostic = drecs->diagRecs[0];
1881 ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
1882 ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
1887 static Z_APDU *process_sortRequest(association *assoc, request *reqb,
1890 Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
1891 Z_SortResponse *res = (Z_SortResponse *)
1892 odr_malloc (assoc->encode, sizeof(*res));
1893 bend_sort_rr *bsrr = (bend_sort_rr *)
1894 odr_malloc (assoc->encode, sizeof(*bsrr));
1896 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1898 yaz_log(LOG_LOG, "Got SortRequest.");
1900 bsrr->num_input_setnames = req->num_inputResultSetNames;
1901 bsrr->input_setnames = req->inputResultSetNames;
1902 bsrr->referenceId = req->referenceId;
1903 bsrr->output_setname = req->sortedResultSetName;
1904 bsrr->sort_sequence = req->sortSequence;
1905 bsrr->stream = assoc->encode;
1906 bsrr->print = assoc->print;
1908 bsrr->sort_status = Z_SortStatus_failure;
1910 bsrr->errstring = 0;
1912 (*assoc->init->bend_sort)(assoc->backend, bsrr);
1914 res->referenceId = bsrr->referenceId;
1915 res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
1916 res->resultSetStatus = 0;
1919 Z_DiagRecs *dr = diagrecs (assoc, bsrr->errcode, bsrr->errstring);
1920 res->diagnostics = dr->diagRecs;
1921 res->num_diagnostics = dr->num_diagRecs;
1925 res->num_diagnostics = 0;
1926 res->diagnostics = 0;
1930 apdu->which = Z_APDU_sortResponse;
1931 apdu->u.sortResponse = res;
1935 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
1938 Z_DeleteResultSetRequest *req =
1939 reqb->apdu_request->u.deleteResultSetRequest;
1940 Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
1941 odr_malloc (assoc->encode, sizeof(*res));
1942 bend_delete_rr *bdrr = (bend_delete_rr *)
1943 odr_malloc (assoc->encode, sizeof(*bdrr));
1944 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1946 yaz_log(LOG_LOG, "Got DeleteRequest.");
1948 bdrr->num_setnames = req->num_resultSetList;
1949 bdrr->setnames = req->resultSetList;
1950 bdrr->stream = assoc->encode;
1951 bdrr->print = assoc->print;
1952 bdrr->function = *req->deleteFunction;
1953 bdrr->referenceId = req->referenceId;
1955 if (bdrr->num_setnames > 0)
1958 bdrr->statuses = (int*)
1959 odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
1960 bdrr->num_setnames);
1961 for (i = 0; i < bdrr->num_setnames; i++)
1962 bdrr->statuses[i] = 0;
1964 (*assoc->init->bend_delete)(assoc->backend, bdrr);
1966 res->referenceId = req->referenceId;
1968 res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
1970 res->deleteListStatuses = 0;
1971 if (bdrr->num_setnames > 0)
1974 res->deleteListStatuses = (Z_ListStatuses *)
1975 odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
1976 res->deleteListStatuses->num = bdrr->num_setnames;
1977 res->deleteListStatuses->elements =
1979 odr_malloc (assoc->encode,
1980 sizeof(*res->deleteListStatuses->elements) *
1981 bdrr->num_setnames);
1982 for (i = 0; i<bdrr->num_setnames; i++)
1984 res->deleteListStatuses->elements[i] =
1986 odr_malloc (assoc->encode,
1987 sizeof(**res->deleteListStatuses->elements));
1988 res->deleteListStatuses->elements[i]->status = bdrr->statuses+i;
1989 res->deleteListStatuses->elements[i]->id =
1990 odr_strdup (assoc->encode, bdrr->setnames[i]);
1994 res->numberNotDeleted = 0;
1995 res->bulkStatuses = 0;
1996 res->deleteMessage = 0;
1999 apdu->which = Z_APDU_deleteResultSetResponse;
2000 apdu->u.deleteResultSetResponse = res;
2004 static void process_close(association *assoc, request *reqb)
2006 Z_Close *req = reqb->apdu_request->u.close;
2007 static char *reasons[] =
2014 "securityViolation",
2021 yaz_log(LOG_LOG, "Got Close, reason %s, message %s",
2022 reasons[*req->closeReason], req->diagnosticInformation ?
2023 req->diagnosticInformation : "NULL");
2024 if (assoc->version < 3) /* to make do_force respond with close */
2026 do_close_req(assoc, Z_Close_finished,
2027 "Association terminated by client", reqb);
2030 void save_referenceId (request *reqb, Z_ReferenceId *refid)
2034 reqb->len_refid = refid->len;
2035 reqb->refid = (char *)nmem_malloc (reqb->request_mem, refid->len);
2036 memcpy (reqb->refid, refid->buf, refid->len);
2040 reqb->len_refid = 0;
2045 void bend_request_send (bend_association a, bend_request req, Z_APDU *res)
2047 process_z_response (a, req, res);
2050 bend_request bend_request_mk (bend_association a)
2052 request *nreq = request_get (&a->outgoing);
2053 nreq->request_mem = nmem_create ();
2057 Z_ReferenceId *bend_request_getid (ODR odr, bend_request req)
2062 id = (Odr_oct *)odr_malloc (odr, sizeof(*odr));
2063 id->buf = (unsigned char *)odr_malloc (odr, req->len_refid);
2064 id->len = id->size = req->len_refid;
2065 memcpy (id->buf, req->refid, req->len_refid);
2069 void bend_request_destroy (bend_request *req)
2071 nmem_destroy((*req)->request_mem);
2072 request_release(*req);
2076 int bend_backend_respond (bend_association a, bend_request req)
2080 r = process_z_request (a, req, &msg);
2082 yaz_log (LOG_WARN, "%s", msg);
2086 void bend_request_setdata(bend_request r, void *p)
2091 void *bend_request_getdata(bend_request r)
2093 return r->clientData;
2096 static Z_APDU *process_segmentRequest (association *assoc, request *reqb)
2098 bend_segment_rr req;
2100 req.segment = reqb->apdu_request->u.segmentRequest;
2101 req.stream = assoc->encode;
2102 req.decode = assoc->decode;
2103 req.print = assoc->print;
2104 req.association = assoc;
2106 (*assoc->init->bend_segment)(assoc->backend, &req);
2111 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd)
2113 bend_esrequest_rr esrequest;
2115 Z_ExtendedServicesRequest *req =
2116 reqb->apdu_request->u.extendedServicesRequest;
2117 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
2119 Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
2121 yaz_log(LOG_DEBUG,"inside Process esRequest");
2123 esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
2124 esrequest.stream = assoc->encode;
2125 esrequest.decode = assoc->decode;
2126 esrequest.print = assoc->print;
2127 esrequest.errcode = 0;
2128 esrequest.errstring = NULL;
2129 esrequest.request = reqb;
2130 esrequest.association = assoc;
2131 esrequest.taskPackage = 0;
2132 esrequest.referenceId = req->referenceId;
2134 (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
2136 /* If the response is being delayed, return NULL */
2137 if (esrequest.request == NULL)
2140 resp->referenceId = req->referenceId;
2142 if (esrequest.errcode == -1)
2144 /* Backend service indicates request will be processed */
2145 yaz_log(LOG_DEBUG,"Request could be processed...Accepted !");
2146 *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
2148 else if (esrequest.errcode == 0)
2150 /* Backend service indicates request will be processed */
2151 yaz_log(LOG_DEBUG,"Request could be processed...Done !");
2152 *resp->operationStatus = Z_ExtendedServicesResponse_done;
2156 Z_DiagRecs *diagRecs = diagrecs (assoc, esrequest.errcode,
2157 esrequest.errstring);
2159 /* Backend indicates error, request will not be processed */
2160 yaz_log(LOG_DEBUG,"Request could not be processed...failure !");
2161 *resp->operationStatus = Z_ExtendedServicesResponse_failure;
2162 resp->num_diagnostics = diagRecs->num_diagRecs;
2163 resp->diagnostics = diagRecs->diagRecs;
2165 /* Do something with the members of bend_extendedservice */
2166 if (esrequest.taskPackage)
2167 resp->taskPackage = z_ext_record (assoc->encode, VAL_EXTENDED,
2168 (const char *) esrequest.taskPackage,
2170 yaz_log(LOG_DEBUG,"Send the result apdu");