2 * Copyright (c) 1995-2003, Index Data
3 * See the file LICENSE for details.
5 * $Id: seshigh.c,v 1.148 2003-03-11 11:09:17 adam Exp $
9 * Frontend server logic.
11 * This code receives incoming APDUs, and handles client requests by means
14 * Some of the code is getting quite involved, compared to simpler servers -
15 * primarily because it is asynchronous both in the communication with
16 * the user and the backend. We think the complexity will pay off in
17 * the form of greater flexibility when more asynchronous facilities
20 * Memory management has become somewhat involved. In the simple case, where
21 * only one PDU is pending at a time, it will simply reuse the same memory,
22 * once it has found its working size. When we enable multiple concurrent
23 * operations, perhaps even with multiple parallel calls to the backend, it
24 * will maintain a pool of buffers for encoding and decoding, trying to
25 * minimize memory allocation/deallocation during normal operation.
31 #include <sys/types.h>
34 #define S_ISREG(x) (x & _S_IFREG)
44 #include <yaz/yconfig.h>
45 #include <yaz/xmalloc.h>
46 #include <yaz/comstack.h>
49 #include <yaz/proto.h>
52 #include <yaz/logrpn.h>
53 #include <yaz/statserv.h>
54 #include <yaz/diagbib1.h>
55 #include <yaz/charneg.h>
56 #include <yaz/otherinfo.h>
57 #include <yaz/yaz-util.h>
58 #include <yaz/pquery.h>
61 #include <yaz/backend.h>
63 static void process_gdu_request(association *assoc, request *req);
64 static int process_z_request(association *assoc, request *req, char **msg);
65 void backend_response(IOCHAN i, int event);
66 static int process_gdu_response(association *assoc, request *req, Z_GDU *res);
67 static int process_z_response(association *assoc, request *req, Z_APDU *res);
68 static Z_APDU *process_initRequest(association *assoc, request *reqb);
69 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
71 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
72 bend_search_rr *bsrr, int *fd);
73 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
75 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
76 static Z_APDU *process_sortRequest(association *assoc, request *reqb, int *fd);
77 static void process_close(association *assoc, request *reqb);
78 void save_referenceId (request *reqb, Z_ReferenceId *refid);
79 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
81 static Z_APDU *process_segmentRequest (association *assoc, request *reqb);
83 static FILE *apduf = 0; /* for use in static mode */
84 static statserv_options_block *control_block = 0;
86 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd);
89 * Create and initialize a new association-handle.
90 * channel : iochannel for the current line.
91 * link : communications channel.
92 * Returns: 0 or a new association handle.
94 association *create_association(IOCHAN channel, COMSTACK link)
99 control_block = statserv_getcontrol();
100 if (!(anew = (association *)xmalloc(sizeof(*anew))))
104 anew->client_chan = channel;
105 anew->client_link = link;
106 anew->cs_get_mask = 0;
107 anew->cs_put_mask = 0;
108 anew->cs_accept_mask = 0;
109 if (!(anew->decode = odr_createmem(ODR_DECODE)) ||
110 !(anew->encode = odr_createmem(ODR_ENCODE)))
112 if (*control_block->apdufile)
117 strcpy(filename, control_block->apdufile);
118 if (!(anew->print = odr_createmem(ODR_PRINT)))
120 if (*control_block->apdufile == '@')
122 odr_setprint(anew->print, yaz_log_file());
124 else if (*control_block->apdufile != '-')
126 strcpy(filename, control_block->apdufile);
127 if (!control_block->dynamic)
131 if (!(apduf = fopen(filename, "w")))
133 yaz_log(LOG_WARN|LOG_ERRNO, "%s", filename);
136 setvbuf(apduf, 0, _IONBF, 0);
142 sprintf(filename + strlen(filename), ".%d", getpid());
143 if (!(f = fopen(filename, "w")))
145 yaz_log(LOG_WARN|LOG_ERRNO, "%s", filename);
148 setvbuf(f, 0, _IONBF, 0);
150 odr_setprint(anew->print, f);
155 anew->input_buffer = 0;
156 anew->input_buffer_len = 0;
158 anew->state = ASSOC_NEW;
159 request_initq(&anew->incoming);
160 request_initq(&anew->outgoing);
161 anew->proto = cs_getproto(link);
166 * Free association and release resources.
168 void destroy_association(association *h)
170 statserv_options_block *cb = statserv_getcontrol();
173 odr_destroy(h->decode);
174 odr_destroy(h->encode);
176 odr_destroy(h->print);
178 xfree(h->input_buffer);
180 (*cb->bend_close)(h->backend);
181 while (request_deq(&h->incoming));
182 while (request_deq(&h->outgoing));
183 request_delq(&h->incoming);
184 request_delq(&h->outgoing);
186 xmalloc_trav("session closed");
187 if (control_block && control_block->one_shot)
193 static void do_close_req(association *a, int reason, char *message,
197 Z_Close *cls = zget_Close(a->encode);
199 /* Purge request queue */
200 while (request_deq(&a->incoming));
201 while (request_deq(&a->outgoing));
204 yaz_log(LOG_LOG, "Sending Close PDU, reason=%d, message=%s",
205 reason, message ? message : "none");
206 apdu.which = Z_APDU_close;
208 *cls->closeReason = reason;
209 cls->diagnosticInformation = message;
210 process_z_response(a, req, &apdu);
211 iochan_settimeout(a->client_chan, 20);
215 yaz_log(LOG_DEBUG, "v2 client. No Close PDU");
216 iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
218 a->state = ASSOC_DEAD;
221 static void do_close(association *a, int reason, char *message)
223 do_close_req (a, reason, message, request_get(&a->outgoing));
227 * This is where PDUs from the client are read and the further
228 * processing is initiated. Flow of control moves down through the
229 * various process_* functions below, until the encoded result comes back up
230 * to the output handler in here.
232 * h : the I/O channel that has an outstanding event.
233 * event : the current outstanding event.
235 void ir_session(IOCHAN h, int event)
238 association *assoc = (association *)iochan_getdata(h);
239 COMSTACK conn = assoc->client_link;
242 assert(h && conn && assoc);
243 if (event == EVENT_TIMEOUT)
245 if (assoc->state != ASSOC_UP)
247 yaz_log(LOG_LOG, "Final timeout - closing connection.");
249 destroy_association(assoc);
254 yaz_log(LOG_LOG, "Session idle too long. Sending close.");
255 do_close(assoc, Z_Close_lackOfActivity, 0);
259 if (event & assoc->cs_accept_mask)
261 yaz_log (LOG_DEBUG, "ir_session (accept)");
262 if (!cs_accept (conn))
264 yaz_log (LOG_LOG, "accept failed");
265 destroy_association(assoc);
268 iochan_clearflag (h, EVENT_OUTPUT|EVENT_OUTPUT);
269 if (conn->io_pending)
270 { /* cs_accept didn't complete */
271 assoc->cs_accept_mask =
272 ((conn->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
273 ((conn->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
275 iochan_setflag (h, assoc->cs_accept_mask);
278 { /* cs_accept completed. Prepare for reading (cs_get) */
279 assoc->cs_accept_mask = 0;
280 assoc->cs_get_mask = EVENT_INPUT;
281 iochan_setflag (h, assoc->cs_get_mask);
285 if ((event & assoc->cs_get_mask) || (event & EVENT_WORK)) /* input */
287 if ((assoc->cs_put_mask & EVENT_INPUT) == 0 && (event & assoc->cs_get_mask))
289 yaz_log(LOG_DEBUG, "ir_session (input)");
290 /* We aren't speaking to this fellow */
291 if (assoc->state == ASSOC_DEAD)
293 yaz_log(LOG_LOG, "Connection closed - end of session");
295 destroy_association(assoc);
299 assoc->cs_get_mask = EVENT_INPUT;
300 if ((res = cs_get(conn, &assoc->input_buffer,
301 &assoc->input_buffer_len)) <= 0)
303 yaz_log(LOG_LOG, "Connection closed by client");
305 destroy_association(assoc);
309 else if (res == 1) /* incomplete read - wait for more */
311 if (conn->io_pending & CS_WANT_WRITE)
312 assoc->cs_get_mask |= EVENT_OUTPUT;
313 iochan_setflag(h, assoc->cs_get_mask);
316 if (cs_more(conn)) /* more stuff - call us again later, please */
317 iochan_setevent(h, EVENT_INPUT);
319 /* we got a complete PDU. Let's decode it */
320 yaz_log(LOG_DEBUG, "Got PDU, %d bytes: lead=%02X %02X %02X", res,
321 assoc->input_buffer[0] & 0xff,
322 assoc->input_buffer[1] & 0xff,
323 assoc->input_buffer[2] & 0xff);
324 req = request_get(&assoc->incoming); /* get a new request */
325 odr_reset(assoc->decode);
326 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
327 if (!z_GDU(assoc->decode, &req->gdu_request, 0, 0))
329 yaz_log(LOG_LOG, "ODR error on incoming PDU: %s [near byte %d] ",
330 odr_errmsg(odr_geterror(assoc->decode)),
331 odr_offset(assoc->decode));
332 if (assoc->decode->error != OHTTP)
334 yaz_log(LOG_LOG, "PDU dump:");
335 odr_dumpBER(yaz_log_file(), assoc->input_buffer, res);
336 do_close(assoc, Z_Close_protocolError, "Malformed package");
340 Z_GDU *p = z_get_HTTP_Response(assoc->encode, 400);
341 assoc->state = ASSOC_DEAD;
342 process_gdu_response(assoc, req, p);
346 req->request_mem = odr_extract_mem(assoc->decode);
347 if (assoc->print && !z_GDU(assoc->print, &req->gdu_request, 0, 0))
349 yaz_log(LOG_WARN, "ODR print error: %s",
350 odr_errmsg(odr_geterror(assoc->print)));
351 odr_reset(assoc->print);
353 request_enq(&assoc->incoming, req);
356 /* can we do something yet? */
357 req = request_head(&assoc->incoming);
358 if (req->state == REQUEST_IDLE)
360 request_deq(&assoc->incoming);
361 process_gdu_request(assoc, req);
364 if (event & assoc->cs_put_mask)
366 request *req = request_head(&assoc->outgoing);
368 assoc->cs_put_mask = 0;
369 yaz_log(LOG_DEBUG, "ir_session (output)");
370 req->state = REQUEST_PENDING;
371 switch (res = cs_put(conn, req->response, req->len_response))
374 yaz_log(LOG_LOG, "Connection closed by client");
376 destroy_association(assoc);
379 case 0: /* all sent - release the request structure */
380 yaz_log(LOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
382 yaz_log(LOG_DEBUG, "HTTP out:\n%.*s", req->len_response,
385 nmem_destroy(req->request_mem);
386 request_deq(&assoc->outgoing);
387 request_release(req);
388 if (!request_head(&assoc->outgoing))
389 { /* restore mask for cs_get operation ... */
390 iochan_clearflag(h, EVENT_OUTPUT|EVENT_INPUT);
391 iochan_setflag(h, assoc->cs_get_mask);
392 if (assoc->state == ASSOC_DEAD)
393 iochan_setevent(assoc->client_chan, EVENT_TIMEOUT);
397 assoc->cs_put_mask = EVENT_OUTPUT;
401 if (conn->io_pending & CS_WANT_WRITE)
402 assoc->cs_put_mask |= EVENT_OUTPUT;
403 if (conn->io_pending & CS_WANT_READ)
404 assoc->cs_put_mask |= EVENT_INPUT;
405 iochan_setflag(h, assoc->cs_put_mask);
408 if (event & EVENT_EXCEPT)
410 yaz_log(LOG_LOG, "ir_session (exception)");
412 destroy_association(assoc);
417 static int process_z_request(association *assoc, request *req, char **msg);
419 static void assoc_init_reset(association *assoc)
422 assoc->init = (bend_initrequest *) xmalloc (sizeof(*assoc->init));
424 assoc->init->stream = assoc->encode;
425 assoc->init->print = assoc->print;
426 assoc->init->auth = 0;
427 assoc->init->referenceId = 0;
428 assoc->init->implementation_version = 0;
429 assoc->init->implementation_id = 0;
430 assoc->init->implementation_name = 0;
431 assoc->init->bend_sort = NULL;
432 assoc->init->bend_search = NULL;
433 assoc->init->bend_present = NULL;
434 assoc->init->bend_esrequest = NULL;
435 assoc->init->bend_delete = NULL;
436 assoc->init->bend_scan = NULL;
437 assoc->init->bend_segment = NULL;
438 assoc->init->bend_fetch = NULL;
439 assoc->init->charneg_request = NULL;
440 assoc->init->charneg_response = NULL;
441 assoc->init->decode = assoc->decode;
442 assoc->init->peer_name =
443 odr_strdup (assoc->encode, cs_addrstr(assoc->client_link));
446 static int srw_bend_init(association *assoc)
448 const char *encoding = "UTF-8";
450 bend_initresult *binitres;
451 statserv_options_block *cb = statserv_getcontrol();
453 assoc_init_reset(assoc);
455 assoc->maximumRecordSize = 3000000;
456 assoc->preferredMessageSize = 3000000;
458 ce = yaz_set_proposal_charneg(assoc->decode, &encoding, 1, 0, 0, 1);
459 assoc->init->charneg_request = ce->u.charNeg3;
461 if (!(binitres = (*cb->bend_init)(assoc->init)))
463 yaz_log(LOG_WARN, "Bad response from backend.");
466 assoc->backend = binitres->handle;
470 static int srw_bend_fetch(association *assoc, int pos,
471 Z_SRW_searchRetrieveRequest *srw_req,
472 Z_SRW_record *record)
475 ODR o = assoc->encode;
477 rr.setname = "default";
480 rr.request_format = VAL_TEXT_XML;
481 rr.request_format_raw = yaz_oidval_to_z3950oid(assoc->decode,
484 rr.comp = (Z_RecordComposition *)
485 odr_malloc(assoc->decode, sizeof(*rr.comp));
486 rr.comp->which = Z_RecordComp_complex;
487 rr.comp->u.complex = (Z_CompSpec *)
488 odr_malloc(assoc->decode, sizeof(Z_CompSpec));
489 rr.comp->u.complex->selectAlternativeSyntax = (bool_t *)
490 odr_malloc(assoc->encode, sizeof(bool_t));
491 *rr.comp->u.complex->selectAlternativeSyntax = 0;
492 rr.comp->u.complex->num_dbSpecific = 0;
493 rr.comp->u.complex->dbSpecific = 0;
494 rr.comp->u.complex->num_recordSyntax = 0;
495 rr.comp->u.complex->recordSyntax = 0;
497 rr.comp->u.complex->generic = (Z_Specification *)
498 odr_malloc(assoc->decode, sizeof(Z_Specification));
499 rr.comp->u.complex->generic->which = Z_Schema_uri;
500 rr.comp->u.complex->generic->schema.uri = srw_req->recordSchema;
501 rr.comp->u.complex->generic->elementSpec = 0;
503 rr.stream = assoc->encode;
504 rr.print = assoc->print;
510 rr.output_format = VAL_TEXT_XML;
511 rr.output_format_raw = 0;
514 rr.surrogate_flag = 0;
516 if (!assoc->init->bend_fetch)
519 (*assoc->init->bend_fetch)(assoc->backend, &rr);
523 record->recordData_buf = rr.record;
524 record->recordData_len = rr.len;
525 record->recordPosition = odr_intdup(o, pos);
526 record->recordSchema = 0;
527 if (srw_req->recordSchema)
528 record->recordSchema = odr_strdup(o, srw_req->recordSchema);
533 static void srw_bend_search(association *assoc, request *req,
534 Z_SRW_searchRetrieveRequest *srw_req,
535 Z_SRW_searchRetrieveResponse *srw_res)
541 yaz_log(LOG_LOG, "Got SRW SearchRetrieveRequest");
544 if (!srw_bend_init(assoc))
546 srw_error = 3; /* assume Authentication error */
548 srw_res->num_diagnostics = 1;
549 srw_res->diagnostics = (Z_SRW_diagnostic *)
550 odr_malloc(assoc->encode, sizeof(*srw_res->diagnostics));
551 srw_res->diagnostics[0].code =
552 odr_intdup(assoc->encode, srw_error);
553 srw_res->diagnostics[0].details = 0;
558 rr.setname = "default";
561 rr.basenames = &srw_req->database;
564 rr.query = (Z_Query *) odr_malloc (assoc->decode, sizeof(*rr.query));
566 if (srw_req->query_type == Z_SRW_query_type_cql)
568 ext = (Z_External *) odr_malloc(assoc->decode, sizeof(*ext));
569 ext->direct_reference = odr_getoidbystr(assoc->decode,
570 "1.2.840.10003.16.2");
571 ext->indirect_reference = 0;
573 ext->which = Z_External_CQL;
574 ext->u.cql = srw_req->query.cql;
576 rr.query->which = Z_Query_type_104;
577 rr.query->u.type_104 = ext;
579 else if (srw_req->query_type == Z_SRW_query_type_pqf)
581 Z_RPNQuery *RPNquery;
582 YAZ_PQF_Parser pqf_parser;
584 pqf_parser = yaz_pqf_create ();
586 RPNquery = yaz_pqf_parse (pqf_parser, assoc->decode,
592 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
593 yaz_log(LOG_LOG, "%*s^\n", off+4, "");
594 yaz_log(LOG_LOG, "Bad PQF: %s (code %d)\n", pqf_msg, code);
599 rr.query->which = Z_Query_type_1;
600 rr.query->u.type_1 = RPNquery;
602 yaz_pqf_destroy (pqf_parser);
607 if (!srw_error && srw_req->sort_type != Z_SRW_sort_type_none)
610 if (!srw_error && !assoc->init->bend_search)
615 srw_res->num_diagnostics = 1;
616 srw_res->diagnostics = (Z_SRW_diagnostic *)
617 odr_malloc(assoc->encode, sizeof(*srw_res->diagnostics));
618 srw_res->diagnostics[0].code =
619 odr_intdup(assoc->encode, srw_error);
620 srw_res->diagnostics[0].details = 0;
624 rr.stream = assoc->encode;
625 rr.decode = assoc->decode;
626 rr.print = assoc->print;
628 rr.association = assoc;
634 yaz_log_zquery(rr.query);
635 (assoc->init->bend_search)(assoc->backend, &rr);
636 srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
639 srw_res->num_diagnostics = 1;
640 srw_res->diagnostics = (Z_SRW_diagnostic *)
641 odr_malloc(assoc->encode, sizeof(*srw_res->diagnostics));
642 srw_res->diagnostics[0].code =
643 odr_intdup(assoc->encode,
644 yaz_diag_bib1_to_srw (rr.errcode));
645 srw_res->diagnostics[0].details = rr.errstring;
649 srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
650 if (srw_req->maximumRecords && *srw_req->maximumRecords > 0)
652 int number = *srw_req->maximumRecords;
655 if (srw_req->startRecord)
656 start = *srw_req->startRecord;
657 if (start <= rr.hits)
660 if (start + number > rr.hits)
661 number = rr.hits - start + 1;
662 srw_res->records = (Z_SRW_record *)
663 odr_malloc(assoc->encode,
664 number * sizeof(*srw_res->records));
665 for (i = 0; i<number; i++)
668 srw_res->records[j].recordData_buf = 0;
669 errcode = srw_bend_fetch(assoc, i+start, srw_req,
670 srw_res->records + j);
673 srw_res->num_diagnostics = 1;
674 srw_res->diagnostics = (Z_SRW_diagnostic *)
675 odr_malloc(assoc->encode,
676 sizeof(*srw_res->diagnostics));
677 srw_res->diagnostics[0].code =
678 odr_intdup(assoc->encode,
679 yaz_diag_bib1_to_srw (errcode));
680 srw_res->diagnostics[0].details = rr.errstring;
683 if (srw_res->records[j].recordData_buf)
686 srw_res->num_records = j;
688 srw_res->records = 0;
694 static void process_http_request(association *assoc, request *req)
696 Z_HTTP_Request *hreq = req->gdu_request->u.HTTP_Request;
697 ODR o = assoc->encode;
699 Z_HTTP_Response *hres = 0;
702 if (!strcmp(hreq->method, "GET"))
705 if (strlen(hreq->path) >= 5 && strlen(hreq->path) < 80 &&
706 !memcmp(hreq->path, "/doc/", 5))
711 strcpy(fpath, DOCDIR);
712 strcat(fpath, hreq->path+4);
713 f = fopen(fpath, "rb");
716 if (fstat(fileno(f), &sbuf) || !S_ISREG(sbuf.st_mode))
725 fseek(f, 0L, SEEK_END);
727 if (sz >= 0 && sz < 500000)
729 const char *ctype = "application/octet-stream";
732 p = z_get_HTTP_Response(o, 200);
733 hres = p->u.HTTP_Response;
734 hres->content_buf = (char *) odr_malloc(o, sz + 1);
735 hres->content_len = sz;
736 fseek(f, 0L, SEEK_SET);
737 fread(hres->content_buf, 1, sz, f);
738 if ((cp = strrchr(fpath, '.'))) {
740 if (!strcmp(cp, "png"))
742 else if (!strcmp(cp, "gif"))
744 else if (!strcmp(cp, "xml"))
746 else if (!strcmp(cp, "html"))
749 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
755 if (!strcmp(hreq->path, "/"))
760 const char *doclink = "";
761 p = z_get_HTTP_Response(o, 200);
762 hres = p->u.HTTP_Response;
763 hres->content_buf = (char *) odr_malloc(o, 400);
765 if (stat(DOCDIR "/yaz.html", &sbuf) == 0 && S_ISREG(sbuf.st_mode))
766 doclink = "<P><A HREF=\"/doc/yaz.html\">Documentation</A></P>";
768 sprintf (hres->content_buf,
769 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n"
772 " <TITLE>YAZ " YAZ_VERSION "</TITLE>\n"
775 " <P><A HREF=\"http://www.indexdata.dk/yaz/\">YAZ</A> "
779 "</HTML>\n", doclink);
780 hres->content_len = strlen(hres->content_buf);
781 z_HTTP_header_add(o, &hres->headers, "Content-Type", "text/html");
785 p = z_get_HTTP_Response(o, 404);
788 else if (!strcmp(hreq->method, "POST"))
790 const char *content_type = z_HTTP_header_lookup(hreq->headers,
792 const char *soap_action = z_HTTP_header_lookup(hreq->headers,
794 if (content_type && soap_action &&
795 !yaz_strcmp_del("text/xml", content_type, "; "))
797 Z_SOAP *soap_package = 0;
800 const char *charset_p = 0;
803 static Z_SOAP_Handler soap_handlers[2] = {
805 {"http://www.loc.gov/zing/srw/v1.0/", 0,
806 (Z_SOAP_fun) yaz_srw_codec},
810 if ((charset_p = strstr(content_type, "; charset=")))
814 while (i < 20 && charset_p[i] &&
815 !strchr("; \n\r", charset_p[i]))
817 charset = odr_malloc(assoc->encode, i+1);
818 memcpy(charset, charset_p, i);
820 yaz_log(LOG_LOG, "SOAP encoding %s", charset);
822 ret = z_soap_codec(assoc->decode, &soap_package,
823 &hreq->content_buf, &hreq->content_len,
827 if (!ret && soap_package->which == Z_SOAP_generic &&
828 soap_package->u.generic->no == 0)
831 Z_SRW_PDU *sr = soap_package->u.generic->p;
833 if (sr->which == Z_SRW_searchRetrieve_request)
836 yaz_srw_get(assoc->encode,
837 Z_SRW_searchRetrieve_response);
839 if (!sr->u.request->database)
841 const char *p0 = hreq->path, *p1;
844 p1 = strchr(p0, '?');
846 p1 = p0 + strlen(p0);
849 sr->u.request->database =
850 odr_malloc(assoc->decode, p1 - p0 + 1);
851 memcpy (sr->u.request->database, p0, p1 - p0);
852 sr->u.request->database[p1 - p0] = '\0';
855 sr->u.request->database = "Default";
857 srw_bend_search(assoc, req, sr->u.request,
860 soap_package->u.generic->p = res;
865 p = z_get_HTTP_Response(o, 200);
866 hres = p->u.HTTP_Response;
867 ret = z_soap_codec_enc(assoc->encode, &soap_package,
868 &hres->content_buf, &hres->content_len,
869 soap_handlers, charset);
870 hres->code = http_code;
872 z_HTTP_header_add(o, &hres->headers, "Content-Type", "text/xml");
876 strcpy(ctype, "text/xml; charset=");
877 strcat(ctype, charset);
878 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
881 if (!p) /* still no response ? */
882 p = z_get_HTTP_Response(o, 500);
886 p = z_get_HTTP_Response(o, 405);
887 hres = p->u.HTTP_Response;
889 z_HTTP_header_add(o, &hres->headers, "Allow", "GET, POST");
891 hres = p->u.HTTP_Response;
892 if (!strcmp(hreq->version, "1.0"))
894 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
895 if (v && !strcmp(v, "Keep-Alive"))
899 hres->version = "1.0";
903 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
904 if (v && !strcmp(v, "close"))
908 hres->version = "1.1";
912 z_HTTP_header_add(o, &hres->headers, "Connection", "close");
913 assoc->state = ASSOC_DEAD;
918 const char *alive = z_HTTP_header_lookup(hreq->headers, "Keep-Alive");
920 if (alive && isdigit(*alive))
924 if (t < 0 || t > 3600)
926 iochan_settimeout(assoc->client_chan,t);
927 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
929 process_gdu_response(assoc, req, p);
932 static void process_gdu_request(association *assoc, request *req)
934 if (req->gdu_request->which == Z_GDU_Z3950)
937 req->apdu_request = req->gdu_request->u.z3950;
938 if (process_z_request(assoc, req, &msg) < 0)
939 do_close_req(assoc, Z_Close_systemProblem, msg, req);
941 else if (req->gdu_request->which == Z_GDU_HTTP_Request)
942 process_http_request(assoc, req);
945 do_close_req(assoc, Z_Close_systemProblem, "bad protocol packet", req);
950 * Initiate request processing.
952 static int process_z_request(association *assoc, request *req, char **msg)
958 *msg = "Unknown Error";
959 assert(req && req->state == REQUEST_IDLE);
960 if (req->apdu_request->which != Z_APDU_initRequest && !assoc->init)
962 *msg = "Missing InitRequest";
965 switch (req->apdu_request->which)
967 case Z_APDU_initRequest:
968 iochan_settimeout(assoc->client_chan,
969 statserv_getcontrol()->idle_timeout * 60);
970 res = process_initRequest(assoc, req); break;
971 case Z_APDU_searchRequest:
972 res = process_searchRequest(assoc, req, &fd); break;
973 case Z_APDU_presentRequest:
974 res = process_presentRequest(assoc, req, &fd); break;
975 case Z_APDU_scanRequest:
976 if (assoc->init->bend_scan)
977 res = process_scanRequest(assoc, req, &fd);
980 *msg = "Cannot handle Scan APDU";
984 case Z_APDU_extendedServicesRequest:
985 if (assoc->init->bend_esrequest)
986 res = process_ESRequest(assoc, req, &fd);
989 *msg = "Cannot handle Extended Services APDU";
993 case Z_APDU_sortRequest:
994 if (assoc->init->bend_sort)
995 res = process_sortRequest(assoc, req, &fd);
998 *msg = "Cannot handle Sort APDU";
1003 process_close(assoc, req);
1005 case Z_APDU_deleteResultSetRequest:
1006 if (assoc->init->bend_delete)
1007 res = process_deleteRequest(assoc, req, &fd);
1010 *msg = "Cannot handle Delete APDU";
1014 case Z_APDU_segmentRequest:
1015 if (assoc->init->bend_segment)
1017 res = process_segmentRequest (assoc, req);
1021 *msg = "Cannot handle Segment APDU";
1026 *msg = "Bad APDU received";
1031 yaz_log(LOG_DEBUG, " result immediately available");
1032 retval = process_z_response(assoc, req, res);
1036 yaz_log(LOG_DEBUG, " result unavailble");
1039 else /* no result yet - one will be provided later */
1043 /* Set up an I/O handler for the fd supplied by the backend */
1045 yaz_log(LOG_DEBUG, " establishing handler for result");
1046 req->state = REQUEST_PENDING;
1047 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT)))
1049 iochan_setdata(chan, assoc);
1056 * Handle message from the backend.
1058 void backend_response(IOCHAN i, int event)
1060 association *assoc = (association *)iochan_getdata(i);
1061 request *req = request_head(&assoc->incoming);
1065 yaz_log(LOG_DEBUG, "backend_response");
1066 assert(assoc && req && req->state != REQUEST_IDLE);
1067 /* determine what it is we're waiting for */
1068 switch (req->apdu_request->which)
1070 case Z_APDU_searchRequest:
1071 res = response_searchRequest(assoc, req, 0, &fd); break;
1073 case Z_APDU_presentRequest:
1074 res = response_presentRequest(assoc, req, 0, &fd); break;
1075 case Z_APDU_scanRequest:
1076 res = response_scanRequest(assoc, req, 0, &fd); break;
1079 yaz_log(LOG_WARN, "Serious programmer's lapse or bug");
1082 if ((res && process_z_response(assoc, req, res) < 0) || fd < 0)
1084 yaz_log(LOG_LOG, "Fatal error when talking to backend");
1085 do_close(assoc, Z_Close_systemProblem, 0);
1089 else if (!res) /* no result yet - try again later */
1091 yaz_log(LOG_DEBUG, " no result yet");
1092 iochan_setfd(i, fd); /* in case fd has changed */
1097 * Encode response, and transfer the request structure to the outgoing queue.
1099 static int process_gdu_response(association *assoc, request *req, Z_GDU *res)
1101 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
1103 if (assoc->print && !z_GDU(assoc->print, &res, 0, 0))
1105 yaz_log(LOG_WARN, "ODR print error: %s",
1106 odr_errmsg(odr_geterror(assoc->print)));
1107 odr_reset(assoc->print);
1109 if (!z_GDU(assoc->encode, &res, 0, 0))
1111 yaz_log(LOG_WARN, "ODR error when encoding response: %s",
1112 odr_errmsg(odr_geterror(assoc->decode)));
1115 req->response = odr_getbuf(assoc->encode, &req->len_response,
1116 &req->size_response);
1117 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
1118 odr_reset(assoc->encode);
1119 req->state = REQUEST_IDLE;
1120 request_enq(&assoc->outgoing, req);
1121 /* turn the work over to the ir_session handler */
1122 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
1123 assoc->cs_put_mask = EVENT_OUTPUT;
1124 /* Is there more work to be done? give that to the input handler too */
1126 if (request_head(&assoc->incoming))
1128 yaz_log (LOG_DEBUG, "more work to be done");
1129 iochan_setevent(assoc->client_chan, EVENT_WORK);
1136 * Encode response, and transfer the request structure to the outgoing queue.
1138 static int process_z_response(association *assoc, request *req, Z_APDU *res)
1140 Z_GDU *gres = (Z_GDU *) odr_malloc(assoc->encode, sizeof(*res));
1141 gres->which = Z_GDU_Z3950;
1142 gres->u.z3950 = res;
1144 return process_gdu_response(assoc, req, gres);
1149 * Handle init request.
1150 * At the moment, we don't check the options
1151 * anywhere else in the code - we just try not to do anything that would
1152 * break a naive client. We'll toss 'em into the association block when
1153 * we need them there.
1155 static Z_APDU *process_initRequest(association *assoc, request *reqb)
1157 statserv_options_block *cb = statserv_getcontrol();
1158 Z_InitRequest *req = reqb->apdu_request->u.initRequest;
1159 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
1160 Z_InitResponse *resp = apdu->u.initResponse;
1161 bend_initresult *binitres;
1165 yaz_log(LOG_LOG, "Got initRequest");
1166 if (req->implementationId)
1167 yaz_log(LOG_LOG, "Id: %s", req->implementationId);
1168 if (req->implementationName)
1169 yaz_log(LOG_LOG, "Name: %s", req->implementationName);
1170 if (req->implementationVersion)
1171 yaz_log(LOG_LOG, "Version: %s", req->implementationVersion);
1173 assoc_init_reset(assoc);
1175 assoc->init->auth = req->idAuthentication;
1176 assoc->init->referenceId = req->referenceId;
1178 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
1180 Z_CharSetandLanguageNegotiation *negotiation =
1181 yaz_get_charneg_record (req->otherInfo);
1182 if (negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
1183 assoc->init->charneg_request = negotiation;
1186 if (!(binitres = (*cb->bend_init)(assoc->init)))
1188 yaz_log(LOG_WARN, "Bad response from backend.");
1192 assoc->backend = binitres->handle;
1193 if ((assoc->init->bend_sort))
1194 yaz_log (LOG_DEBUG, "Sort handler installed");
1195 if ((assoc->init->bend_search))
1196 yaz_log (LOG_DEBUG, "Search handler installed");
1197 if ((assoc->init->bend_present))
1198 yaz_log (LOG_DEBUG, "Present handler installed");
1199 if ((assoc->init->bend_esrequest))
1200 yaz_log (LOG_DEBUG, "ESRequest handler installed");
1201 if ((assoc->init->bend_delete))
1202 yaz_log (LOG_DEBUG, "Delete handler installed");
1203 if ((assoc->init->bend_scan))
1204 yaz_log (LOG_DEBUG, "Scan handler installed");
1205 if ((assoc->init->bend_segment))
1206 yaz_log (LOG_DEBUG, "Segment handler installed");
1208 resp->referenceId = req->referenceId;
1210 /* let's tell the client what we can do */
1211 if (ODR_MASK_GET(req->options, Z_Options_search))
1213 ODR_MASK_SET(resp->options, Z_Options_search);
1214 strcat(options, "srch");
1216 if (ODR_MASK_GET(req->options, Z_Options_present))
1218 ODR_MASK_SET(resp->options, Z_Options_present);
1219 strcat(options, " prst");
1221 if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
1222 assoc->init->bend_delete)
1224 ODR_MASK_SET(resp->options, Z_Options_delSet);
1225 strcat(options, " del");
1227 if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
1228 assoc->init->bend_esrequest)
1230 ODR_MASK_SET(resp->options, Z_Options_extendedServices);
1231 strcat (options, " extendedServices");
1233 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
1235 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
1236 strcat(options, " namedresults");
1238 if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
1240 ODR_MASK_SET(resp->options, Z_Options_scan);
1241 strcat(options, " scan");
1243 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
1245 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
1246 strcat(options, " concurrop");
1248 if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
1250 ODR_MASK_SET(resp->options, Z_Options_sort);
1251 strcat(options, " sort");
1254 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel)
1255 && assoc->init->charneg_response)
1257 Z_OtherInformation **p;
1258 Z_OtherInformationUnit *p0;
1260 yaz_oi_APDU(apdu, &p);
1262 if ((p0=yaz_oi_update(p, assoc->encode, NULL, 0, 0))) {
1263 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
1265 p0->which = Z_OtherInfo_externallyDefinedInfo;
1266 p0->information.externallyDefinedInfo =
1267 assoc->init->charneg_response;
1269 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
1270 strcat(options, " negotiation");
1273 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
1275 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
1276 assoc->version = 2; /* 1 & 2 are equivalent */
1278 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
1280 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
1283 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
1285 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
1289 yaz_log(LOG_LOG, "Negotiated to v%d: %s", assoc->version, options);
1290 assoc->maximumRecordSize = *req->maximumRecordSize;
1291 if (assoc->maximumRecordSize > control_block->maxrecordsize)
1292 assoc->maximumRecordSize = control_block->maxrecordsize;
1293 assoc->preferredMessageSize = *req->preferredMessageSize;
1294 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
1295 assoc->preferredMessageSize = assoc->maximumRecordSize;
1297 resp->preferredMessageSize = &assoc->preferredMessageSize;
1298 resp->maximumRecordSize = &assoc->maximumRecordSize;
1300 resp->implementationName = "GFS/YAZ";
1302 if (assoc->init->implementation_id)
1305 odr_malloc (assoc->encode,
1306 strlen(assoc->init->implementation_id) + 10 +
1307 strlen(resp->implementationId));
1308 sprintf (nv, "%s / %s",
1309 resp->implementationId, assoc->init->implementation_id);
1310 resp->implementationId = nv;
1312 if (assoc->init->implementation_name)
1315 odr_malloc (assoc->encode,
1316 strlen(assoc->init->implementation_name) + 10 +
1317 strlen(resp->implementationName));
1318 sprintf (nv, "%s / %s",
1319 resp->implementationName, assoc->init->implementation_name);
1320 resp->implementationName = nv;
1322 if (assoc->init->implementation_version)
1325 odr_malloc (assoc->encode,
1326 strlen(assoc->init->implementation_version) + 10 +
1327 strlen(resp->implementationVersion));
1328 sprintf (nv, "YAZ %s / %s",
1329 resp->implementationVersion,
1330 assoc->init->implementation_version);
1331 resp->implementationVersion = nv;
1334 if (binitres->errcode)
1336 yaz_log(LOG_LOG, "Connection rejected by backend.");
1338 assoc->state = ASSOC_DEAD;
1341 assoc->state = ASSOC_UP;
1346 * These functions should be merged.
1349 static void set_addinfo (Z_DefaultDiagFormat *dr, char *addinfo, ODR odr)
1351 dr->which = Z_DefaultDiagFormat_v2Addinfo;
1352 dr->u.v2Addinfo = odr_strdup (odr, addinfo ? addinfo : "");
1356 * nonsurrogate diagnostic record.
1358 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
1360 Z_Records *rec = (Z_Records *)
1361 odr_malloc (assoc->encode, sizeof(*rec));
1362 int *err = odr_intdup(assoc->encode, error);
1363 Z_DiagRec *drec = (Z_DiagRec *)
1364 odr_malloc (assoc->encode, sizeof(*drec));
1365 Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
1366 odr_malloc (assoc->encode, sizeof(*dr));
1368 yaz_log(LOG_LOG, "[%d] %s %s%s", error, diagbib1_str(error),
1369 addinfo ? " -- " : "", addinfo ? addinfo : "");
1370 rec->which = Z_Records_NSD;
1371 rec->u.nonSurrogateDiagnostic = dr;
1372 dr->diagnosticSetId =
1373 yaz_oidval_to_z3950oid (assoc->encode, CLASS_DIAGSET, VAL_BIB1);
1374 dr->condition = err;
1375 set_addinfo (dr, addinfo, assoc->encode);
1380 * surrogate diagnostic.
1382 static Z_NamePlusRecord *surrogatediagrec(association *assoc, char *dbname,
1383 int error, char *addinfo)
1385 Z_NamePlusRecord *rec = (Z_NamePlusRecord *)
1386 odr_malloc (assoc->encode, sizeof(*rec));
1387 int *err = odr_intdup(assoc->encode, error);
1388 Z_DiagRec *drec = (Z_DiagRec *)odr_malloc (assoc->encode, sizeof(*drec));
1389 Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
1390 odr_malloc (assoc->encode, sizeof(*dr));
1392 yaz_log(LOG_DEBUG, "SurrogateDiagnotic: %d -- %s", error, addinfo);
1393 rec->databaseName = dbname;
1394 rec->which = Z_NamePlusRecord_surrogateDiagnostic;
1395 rec->u.surrogateDiagnostic = drec;
1396 drec->which = Z_DiagRec_defaultFormat;
1397 drec->u.defaultFormat = dr;
1398 dr->diagnosticSetId =
1399 yaz_oidval_to_z3950oid (assoc->encode, CLASS_DIAGSET, VAL_BIB1);
1400 dr->condition = err;
1401 set_addinfo (dr, addinfo, assoc->encode);
1407 * multiple nonsurrogate diagnostics.
1409 static Z_DiagRecs *diagrecs(association *assoc, int error, char *addinfo)
1411 Z_DiagRecs *recs = (Z_DiagRecs *)odr_malloc (assoc->encode, sizeof(*recs));
1412 int *err = odr_intdup(assoc->encode, error);
1413 Z_DiagRec **recp = (Z_DiagRec **)odr_malloc (assoc->encode, sizeof(*recp));
1414 Z_DiagRec *drec = (Z_DiagRec *)odr_malloc (assoc->encode, sizeof(*drec));
1415 Z_DefaultDiagFormat *rec = (Z_DefaultDiagFormat *)
1416 odr_malloc (assoc->encode, sizeof(*rec));
1418 yaz_log(LOG_DEBUG, "DiagRecs: %d -- %s", error, addinfo ? addinfo : "");
1420 recs->num_diagRecs = 1;
1421 recs->diagRecs = recp;
1423 drec->which = Z_DiagRec_defaultFormat;
1424 drec->u.defaultFormat = rec;
1426 rec->diagnosticSetId =
1427 yaz_oidval_to_z3950oid (assoc->encode, CLASS_DIAGSET, VAL_BIB1);
1428 rec->condition = err;
1430 rec->which = Z_DefaultDiagFormat_v2Addinfo;
1431 rec->u.v2Addinfo = odr_strdup (assoc->encode, addinfo ? addinfo : "");
1435 static Z_Records *pack_records(association *a, char *setname, int start,
1436 int *num, Z_RecordComposition *comp,
1437 int *next, int *pres, oid_value format,
1438 Z_ReferenceId *referenceId,
1441 int recno, total_length = 0, toget = *num, dumped_records = 0;
1442 Z_Records *records =
1443 (Z_Records *) odr_malloc (a->encode, sizeof(*records));
1444 Z_NamePlusRecordList *reclist =
1445 (Z_NamePlusRecordList *) odr_malloc (a->encode, sizeof(*reclist));
1446 Z_NamePlusRecord **list =
1447 (Z_NamePlusRecord **) odr_malloc (a->encode, sizeof(*list) * toget);
1449 records->which = Z_Records_DBOSD;
1450 records->u.databaseOrSurDiagnostics = reclist;
1451 reclist->num_records = 0;
1452 reclist->records = list;
1453 *pres = Z_PRES_SUCCESS;
1457 yaz_log(LOG_LOG, "Request to pack %d+%d+%s", start, toget, setname);
1458 yaz_log(LOG_DEBUG, "pms=%d, mrs=%d", a->preferredMessageSize,
1459 a->maximumRecordSize);
1460 for (recno = start; reclist->num_records < toget; recno++)
1463 Z_NamePlusRecord *thisrec;
1464 int this_length = 0;
1466 * we get the number of bytes allocated on the stream before any
1467 * allocation done by the backend - this should give us a reasonable
1468 * idea of the total size of the data so far.
1470 total_length = odr_total(a->encode) - dumped_records;
1476 freq.last_in_set = 0;
1477 freq.setname = setname;
1478 freq.surrogate_flag = 0;
1479 freq.number = recno;
1481 freq.request_format = format;
1482 freq.request_format_raw = oid;
1483 freq.output_format = format;
1484 freq.output_format_raw = 0;
1485 freq.stream = a->encode;
1486 freq.print = a->print;
1487 freq.surrogate_flag = 0;
1488 freq.referenceId = referenceId;
1489 (*a->init->bend_fetch)(a->backend, &freq);
1490 /* backend should be able to signal whether error is system-wide
1491 or only pertaining to current record */
1494 if (!freq.surrogate_flag)
1497 *pres = Z_PRES_FAILURE;
1498 /* for 'present request out of range',
1499 set addinfo to record position if not set */
1500 if (freq.errcode == 13 && freq.errstring == 0)
1502 sprintf (s, "%d", recno);
1505 return diagrec(a, freq.errcode, freq.errstring);
1507 reclist->records[reclist->num_records] =
1508 surrogatediagrec(a, freq.basename, freq.errcode,
1510 reclist->num_records++;
1511 *next = freq.last_in_set ? 0 : recno + 1;
1515 this_length = freq.len;
1517 this_length = odr_total(a->encode) - total_length;
1518 yaz_log(LOG_DEBUG, " fetched record, len=%d, total=%d",
1519 this_length, total_length);
1520 if (this_length + total_length > a->preferredMessageSize)
1522 /* record is small enough, really */
1523 if (this_length <= a->preferredMessageSize)
1525 yaz_log(LOG_DEBUG, " Dropped last normal-sized record");
1526 *pres = Z_PRES_PARTIAL_2;
1529 /* record can only be fetched by itself */
1530 if (this_length < a->maximumRecordSize)
1532 yaz_log(LOG_DEBUG, " Record > prefmsgsz");
1535 yaz_log(LOG_DEBUG, " Dropped it");
1536 reclist->records[reclist->num_records] =
1537 surrogatediagrec(a, freq.basename, 16, 0);
1538 reclist->num_records++;
1539 *next = freq.last_in_set ? 0 : recno + 1;
1540 dumped_records += this_length;
1544 else /* too big entirely */
1546 yaz_log(LOG_LOG, "Record > maxrcdsz this=%d max=%d", this_length, a->maximumRecordSize);
1547 reclist->records[reclist->num_records] =
1548 surrogatediagrec(a, freq.basename, 17, 0);
1549 reclist->num_records++;
1550 *next = freq.last_in_set ? 0 : recno + 1;
1551 dumped_records += this_length;
1556 if (!(thisrec = (Z_NamePlusRecord *)
1557 odr_malloc(a->encode, sizeof(*thisrec))))
1559 if (!(thisrec->databaseName = (char *)odr_malloc(a->encode,
1560 strlen(freq.basename) + 1)))
1562 strcpy(thisrec->databaseName, freq.basename);
1563 thisrec->which = Z_NamePlusRecord_databaseRecord;
1565 if (freq.output_format_raw)
1567 struct oident *ident = oid_getentbyoid(freq.output_format_raw);
1568 freq.output_format = ident->value;
1570 thisrec->u.databaseRecord = z_ext_record(a->encode, freq.output_format,
1571 freq.record, freq.len);
1572 if (!thisrec->u.databaseRecord)
1574 reclist->records[reclist->num_records] = thisrec;
1575 reclist->num_records++;
1576 *next = freq.last_in_set ? 0 : recno + 1;
1578 *num = reclist->num_records;
1582 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
1585 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
1586 bend_search_rr *bsrr =
1587 (bend_search_rr *)nmem_malloc (reqb->request_mem, sizeof(*bsrr));
1589 yaz_log(LOG_LOG, "Got SearchRequest.");
1591 bsrr->request = reqb;
1592 bsrr->association = assoc;
1593 bsrr->referenceId = req->referenceId;
1594 save_referenceId (reqb, bsrr->referenceId);
1596 yaz_log (LOG_LOG, "ResultSet '%s'", req->resultSetName);
1597 if (req->databaseNames)
1600 for (i = 0; i < req->num_databaseNames; i++)
1601 yaz_log (LOG_LOG, "Database '%s'", req->databaseNames[i]);
1603 yaz_log_zquery(req->query);
1605 if (assoc->init->bend_search)
1607 bsrr->setname = req->resultSetName;
1608 bsrr->replace_set = *req->replaceIndicator;
1609 bsrr->num_bases = req->num_databaseNames;
1610 bsrr->basenames = req->databaseNames;
1611 bsrr->query = req->query;
1612 bsrr->stream = assoc->encode;
1613 bsrr->decode = assoc->decode;
1614 bsrr->print = assoc->print;
1617 bsrr->errstring = NULL;
1618 bsrr->search_info = NULL;
1619 (assoc->init->bend_search)(assoc->backend, bsrr);
1623 return response_searchRequest(assoc, reqb, bsrr, fd);
1626 int bend_searchresponse(void *handle, bend_search_rr *bsrr) {return 0;}
1629 * Prepare a searchresponse based on the backend results. We probably want
1630 * to look at making the fetching of records nonblocking as well, but
1631 * so far, we'll keep things simple.
1632 * If bsrt is null, that means we're called in response to a communications
1633 * event, and we'll have to get the response for ourselves.
1635 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
1636 bend_search_rr *bsrt, int *fd)
1638 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
1639 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1640 Z_SearchResponse *resp = (Z_SearchResponse *)
1641 odr_malloc (assoc->encode, sizeof(*resp));
1642 int *nulint = odr_intdup (assoc->encode, 0);
1643 bool_t *sr = odr_intdup(assoc->encode, 1);
1644 int *next = odr_intdup(assoc->encode, 0);
1645 int *none = odr_intdup(assoc->encode, Z_RES_NONE);
1647 apdu->which = Z_APDU_searchResponse;
1648 apdu->u.searchResponse = resp;
1649 resp->referenceId = req->referenceId;
1650 resp->additionalSearchInfo = 0;
1651 resp->otherInfo = 0;
1653 if (!bsrt && !bend_searchresponse(assoc->backend, bsrt))
1655 yaz_log(LOG_FATAL, "Bad result from backend");
1658 else if (bsrt->errcode)
1660 resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
1661 resp->resultCount = nulint;
1662 resp->numberOfRecordsReturned = nulint;
1663 resp->nextResultSetPosition = nulint;
1664 resp->searchStatus = nulint;
1665 resp->resultSetStatus = none;
1666 resp->presentStatus = 0;
1670 int *toget = odr_intdup(assoc->encode, 0);
1671 int *presst = odr_intdup(assoc->encode, 0);
1672 Z_RecordComposition comp, *compp = 0;
1674 yaz_log (LOG_LOG, "resultCount: %d", bsrt->hits);
1677 resp->resultCount = &bsrt->hits;
1679 comp.which = Z_RecordComp_simple;
1680 /* how many records does the user agent want, then? */
1681 if (bsrt->hits <= *req->smallSetUpperBound)
1683 *toget = bsrt->hits;
1684 if ((comp.u.simple = req->smallSetElementSetNames))
1687 else if (bsrt->hits < *req->largeSetLowerBound)
1689 *toget = *req->mediumSetPresentNumber;
1690 if (*toget > bsrt->hits)
1691 *toget = bsrt->hits;
1692 if ((comp.u.simple = req->mediumSetElementSetNames))
1698 if (*toget && !resp->records)
1703 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
1706 form = prefformat->value;
1707 resp->records = pack_records(assoc, req->resultSetName, 1,
1708 toget, compp, next, presst, form, req->referenceId,
1709 req->preferredRecordSyntax);
1712 resp->numberOfRecordsReturned = toget;
1713 resp->nextResultSetPosition = next;
1714 resp->searchStatus = sr;
1715 resp->resultSetStatus = 0;
1716 resp->presentStatus = presst;
1720 if (*resp->resultCount)
1722 resp->numberOfRecordsReturned = nulint;
1723 resp->nextResultSetPosition = next;
1724 resp->searchStatus = sr;
1725 resp->resultSetStatus = 0;
1726 resp->presentStatus = 0;
1729 resp->additionalSearchInfo = bsrt->search_info;
1734 * Maybe we got a little over-friendly when we designed bend_fetch to
1735 * get only one record at a time. Some backends can optimise multiple-record
1736 * fetches, and at any rate, there is some overhead involved in
1737 * all that selecting and hopping around. Problem is, of course, that the
1738 * frontend can't know ahead of time how many records it'll need to
1739 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
1740 * is downright lousy as a bulk data transfer protocol.
1742 * To start with, we'll do the fetching of records from the backend
1743 * in one operation: To save some trips in and out of the event-handler,
1744 * and to simplify the interface to pack_records. At any rate, asynch
1745 * operation is more fun in operations that have an unpredictable execution
1746 * speed - which is normally more true for search than for present.
1748 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
1751 Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
1755 Z_PresentResponse *resp;
1759 yaz_log(LOG_LOG, "Got PresentRequest.");
1761 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
1764 form = prefformat->value;
1765 resp = (Z_PresentResponse *)odr_malloc (assoc->encode, sizeof(*resp));
1767 resp->presentStatus = odr_intdup(assoc->encode, 0);
1768 if (assoc->init->bend_present)
1770 bend_present_rr *bprr = (bend_present_rr *)
1771 nmem_malloc (reqb->request_mem, sizeof(*bprr));
1772 bprr->setname = req->resultSetId;
1773 bprr->start = *req->resultSetStartPoint;
1774 bprr->number = *req->numberOfRecordsRequested;
1775 bprr->format = form;
1776 bprr->comp = req->recordComposition;
1777 bprr->referenceId = req->referenceId;
1778 bprr->stream = assoc->encode;
1779 bprr->print = assoc->print;
1780 bprr->request = reqb;
1781 bprr->association = assoc;
1783 bprr->errstring = NULL;
1784 (*assoc->init->bend_present)(assoc->backend, bprr);
1790 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
1791 *resp->presentStatus = Z_PRES_FAILURE;
1794 apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1795 next = odr_intdup(assoc->encode, 0);
1796 num = odr_intdup(assoc->encode, 0);
1798 apdu->which = Z_APDU_presentResponse;
1799 apdu->u.presentResponse = resp;
1800 resp->referenceId = req->referenceId;
1801 resp->otherInfo = 0;
1805 *num = *req->numberOfRecordsRequested;
1807 pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
1808 num, req->recordComposition, next, resp->presentStatus,
1809 form, req->referenceId, req->preferredRecordSyntax);
1813 resp->numberOfRecordsReturned = num;
1814 resp->nextResultSetPosition = next;
1820 * Scan was implemented rather in a hurry, and with support for only the basic
1821 * elements of the service in the backend API. Suggestions are welcome.
1823 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
1825 Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
1826 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1827 Z_ScanResponse *res = (Z_ScanResponse *)
1828 odr_malloc (assoc->encode, sizeof(*res));
1829 int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
1830 int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
1831 Z_ListEntries *ents = (Z_ListEntries *)
1832 odr_malloc (assoc->encode, sizeof(*ents));
1833 Z_DiagRecs *diagrecs_p = NULL;
1835 bend_scan_rr *bsrr = (bend_scan_rr *)
1836 odr_malloc (assoc->encode, sizeof(*bsrr));
1838 yaz_log(LOG_LOG, "Got ScanRequest");
1840 apdu->which = Z_APDU_scanResponse;
1841 apdu->u.scanResponse = res;
1842 res->referenceId = req->referenceId;
1844 /* if step is absent, set it to 0 */
1845 res->stepSize = odr_intdup(assoc->encode, 0);
1847 *res->stepSize = *req->stepSize;
1849 res->scanStatus = scanStatus;
1850 res->numberOfEntriesReturned = numberOfEntriesReturned;
1851 res->positionOfTerm = 0;
1852 res->entries = ents;
1853 ents->num_entries = 0;
1854 ents->entries = NULL;
1855 ents->num_nonsurrogateDiagnostics = 0;
1856 ents->nonsurrogateDiagnostics = NULL;
1857 res->attributeSet = 0;
1860 if (req->databaseNames)
1863 for (i = 0; i < req->num_databaseNames; i++)
1864 yaz_log (LOG_LOG, "Database '%s'", req->databaseNames[i]);
1866 bsrr->num_bases = req->num_databaseNames;
1867 bsrr->basenames = req->databaseNames;
1868 bsrr->num_entries = *req->numberOfTermsRequested;
1869 bsrr->term = req->termListAndStartPoint;
1870 bsrr->referenceId = req->referenceId;
1871 bsrr->stream = assoc->encode;
1872 bsrr->print = assoc->print;
1873 bsrr->step_size = res->stepSize;
1874 if (req->attributeSet &&
1875 (attset = oid_getentbyoid(req->attributeSet)) &&
1876 (attset->oclass == CLASS_ATTSET || attset->oclass == CLASS_GENERAL))
1877 bsrr->attributeset = attset->value;
1879 bsrr->attributeset = VAL_NONE;
1880 log_scan_term (req->termListAndStartPoint, bsrr->attributeset);
1881 bsrr->term_position = req->preferredPositionInResponse ?
1882 *req->preferredPositionInResponse : 1;
1883 ((int (*)(void *, bend_scan_rr *))
1884 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1886 diagrecs_p = diagrecs(assoc, bsrr->errcode, bsrr->errstring);
1890 Z_Entry **tab = (Z_Entry **)
1891 odr_malloc (assoc->encode, sizeof(*tab) * bsrr->num_entries);
1893 if (bsrr->status == BEND_SCAN_PARTIAL)
1894 *scanStatus = Z_Scan_partial_5;
1896 *scanStatus = Z_Scan_success;
1897 ents->entries = tab;
1898 ents->num_entries = bsrr->num_entries;
1899 res->numberOfEntriesReturned = &ents->num_entries;
1900 res->positionOfTerm = &bsrr->term_position;
1901 for (i = 0; i < bsrr->num_entries; i++)
1907 tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
1908 if (bsrr->entries[i].occurrences >= 0)
1910 e->which = Z_Entry_termInfo;
1911 e->u.termInfo = t = (Z_TermInfo *)
1912 odr_malloc(assoc->encode, sizeof(*t));
1913 t->suggestedAttributes = 0;
1915 t->alternativeTerm = 0;
1916 t->byAttributes = 0;
1917 t->otherTermInfo = 0;
1918 t->globalOccurrences = &bsrr->entries[i].occurrences;
1919 t->term = (Z_Term *)
1920 odr_malloc(assoc->encode, sizeof(*t->term));
1921 t->term->which = Z_Term_general;
1922 t->term->u.general = o =
1923 (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
1924 o->buf = (unsigned char *)
1925 odr_malloc(assoc->encode, o->len = o->size =
1926 strlen(bsrr->entries[i].term));
1927 memcpy(o->buf, bsrr->entries[i].term, o->len);
1928 yaz_log(LOG_DEBUG, " term #%d: '%s' (%d)", i,
1929 bsrr->entries[i].term, bsrr->entries[i].occurrences);
1933 Z_DiagRecs *drecs = diagrecs (assoc,
1934 bsrr->entries[i].errcode,
1935 bsrr->entries[i].errstring);
1936 assert (drecs->num_diagRecs == 1);
1937 e->which = Z_Entry_surrogateDiagnostic;
1938 assert (drecs->diagRecs[0]);
1939 e->u.surrogateDiagnostic = drecs->diagRecs[0];
1945 ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
1946 ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
1951 static Z_APDU *process_sortRequest(association *assoc, request *reqb,
1954 Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
1955 Z_SortResponse *res = (Z_SortResponse *)
1956 odr_malloc (assoc->encode, sizeof(*res));
1957 bend_sort_rr *bsrr = (bend_sort_rr *)
1958 odr_malloc (assoc->encode, sizeof(*bsrr));
1960 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1962 yaz_log(LOG_LOG, "Got SortRequest.");
1964 bsrr->num_input_setnames = req->num_inputResultSetNames;
1965 bsrr->input_setnames = req->inputResultSetNames;
1966 bsrr->referenceId = req->referenceId;
1967 bsrr->output_setname = req->sortedResultSetName;
1968 bsrr->sort_sequence = req->sortSequence;
1969 bsrr->stream = assoc->encode;
1970 bsrr->print = assoc->print;
1972 bsrr->sort_status = Z_SortStatus_failure;
1974 bsrr->errstring = 0;
1976 (*assoc->init->bend_sort)(assoc->backend, bsrr);
1978 res->referenceId = bsrr->referenceId;
1979 res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
1980 res->resultSetStatus = 0;
1983 Z_DiagRecs *dr = diagrecs (assoc, bsrr->errcode, bsrr->errstring);
1984 res->diagnostics = dr->diagRecs;
1985 res->num_diagnostics = dr->num_diagRecs;
1989 res->num_diagnostics = 0;
1990 res->diagnostics = 0;
1994 apdu->which = Z_APDU_sortResponse;
1995 apdu->u.sortResponse = res;
1999 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
2002 Z_DeleteResultSetRequest *req =
2003 reqb->apdu_request->u.deleteResultSetRequest;
2004 Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
2005 odr_malloc (assoc->encode, sizeof(*res));
2006 bend_delete_rr *bdrr = (bend_delete_rr *)
2007 odr_malloc (assoc->encode, sizeof(*bdrr));
2008 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2010 yaz_log(LOG_LOG, "Got DeleteRequest.");
2012 bdrr->num_setnames = req->num_resultSetList;
2013 bdrr->setnames = req->resultSetList;
2014 bdrr->stream = assoc->encode;
2015 bdrr->print = assoc->print;
2016 bdrr->function = *req->deleteFunction;
2017 bdrr->referenceId = req->referenceId;
2019 if (bdrr->num_setnames > 0)
2022 bdrr->statuses = (int*)
2023 odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
2024 bdrr->num_setnames);
2025 for (i = 0; i < bdrr->num_setnames; i++)
2026 bdrr->statuses[i] = 0;
2028 (*assoc->init->bend_delete)(assoc->backend, bdrr);
2030 res->referenceId = req->referenceId;
2032 res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
2034 res->deleteListStatuses = 0;
2035 if (bdrr->num_setnames > 0)
2038 res->deleteListStatuses = (Z_ListStatuses *)
2039 odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
2040 res->deleteListStatuses->num = bdrr->num_setnames;
2041 res->deleteListStatuses->elements =
2043 odr_malloc (assoc->encode,
2044 sizeof(*res->deleteListStatuses->elements) *
2045 bdrr->num_setnames);
2046 for (i = 0; i<bdrr->num_setnames; i++)
2048 res->deleteListStatuses->elements[i] =
2050 odr_malloc (assoc->encode,
2051 sizeof(**res->deleteListStatuses->elements));
2052 res->deleteListStatuses->elements[i]->status = bdrr->statuses+i;
2053 res->deleteListStatuses->elements[i]->id =
2054 odr_strdup (assoc->encode, bdrr->setnames[i]);
2058 res->numberNotDeleted = 0;
2059 res->bulkStatuses = 0;
2060 res->deleteMessage = 0;
2063 apdu->which = Z_APDU_deleteResultSetResponse;
2064 apdu->u.deleteResultSetResponse = res;
2068 static void process_close(association *assoc, request *reqb)
2070 Z_Close *req = reqb->apdu_request->u.close;
2071 static char *reasons[] =
2078 "securityViolation",
2085 yaz_log(LOG_LOG, "Got Close, reason %s, message %s",
2086 reasons[*req->closeReason], req->diagnosticInformation ?
2087 req->diagnosticInformation : "NULL");
2088 if (assoc->version < 3) /* to make do_force respond with close */
2090 do_close_req(assoc, Z_Close_finished,
2091 "Association terminated by client", reqb);
2094 void save_referenceId (request *reqb, Z_ReferenceId *refid)
2098 reqb->len_refid = refid->len;
2099 reqb->refid = (char *)nmem_malloc (reqb->request_mem, refid->len);
2100 memcpy (reqb->refid, refid->buf, refid->len);
2104 reqb->len_refid = 0;
2109 void bend_request_send (bend_association a, bend_request req, Z_APDU *res)
2111 process_z_response (a, req, res);
2114 bend_request bend_request_mk (bend_association a)
2116 request *nreq = request_get (&a->outgoing);
2117 nreq->request_mem = nmem_create ();
2121 Z_ReferenceId *bend_request_getid (ODR odr, bend_request req)
2126 id = (Odr_oct *)odr_malloc (odr, sizeof(*odr));
2127 id->buf = (unsigned char *)odr_malloc (odr, req->len_refid);
2128 id->len = id->size = req->len_refid;
2129 memcpy (id->buf, req->refid, req->len_refid);
2133 void bend_request_destroy (bend_request *req)
2135 nmem_destroy((*req)->request_mem);
2136 request_release(*req);
2140 int bend_backend_respond (bend_association a, bend_request req)
2144 r = process_z_request (a, req, &msg);
2146 yaz_log (LOG_WARN, "%s", msg);
2150 void bend_request_setdata(bend_request r, void *p)
2155 void *bend_request_getdata(bend_request r)
2157 return r->clientData;
2160 static Z_APDU *process_segmentRequest (association *assoc, request *reqb)
2162 bend_segment_rr req;
2164 req.segment = reqb->apdu_request->u.segmentRequest;
2165 req.stream = assoc->encode;
2166 req.decode = assoc->decode;
2167 req.print = assoc->print;
2168 req.association = assoc;
2170 (*assoc->init->bend_segment)(assoc->backend, &req);
2175 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd)
2177 bend_esrequest_rr esrequest;
2179 Z_ExtendedServicesRequest *req =
2180 reqb->apdu_request->u.extendedServicesRequest;
2181 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
2183 Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
2185 yaz_log(LOG_DEBUG,"inside Process esRequest");
2187 esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
2188 esrequest.stream = assoc->encode;
2189 esrequest.decode = assoc->decode;
2190 esrequest.print = assoc->print;
2191 esrequest.errcode = 0;
2192 esrequest.errstring = NULL;
2193 esrequest.request = reqb;
2194 esrequest.association = assoc;
2195 esrequest.taskPackage = 0;
2196 esrequest.referenceId = req->referenceId;
2198 (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
2200 /* If the response is being delayed, return NULL */
2201 if (esrequest.request == NULL)
2204 resp->referenceId = req->referenceId;
2206 if (esrequest.errcode == -1)
2208 /* Backend service indicates request will be processed */
2209 yaz_log(LOG_DEBUG,"Request could be processed...Accepted !");
2210 *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
2212 else if (esrequest.errcode == 0)
2214 /* Backend service indicates request will be processed */
2215 yaz_log(LOG_DEBUG,"Request could be processed...Done !");
2216 *resp->operationStatus = Z_ExtendedServicesResponse_done;
2220 Z_DiagRecs *diagRecs = diagrecs (assoc, esrequest.errcode,
2221 esrequest.errstring);
2223 /* Backend indicates error, request will not be processed */
2224 yaz_log(LOG_DEBUG,"Request could not be processed...failure !");
2225 *resp->operationStatus = Z_ExtendedServicesResponse_failure;
2226 resp->num_diagnostics = diagRecs->num_diagRecs;
2227 resp->diagnostics = diagRecs->diagRecs;
2229 /* Do something with the members of bend_extendedservice */
2230 if (esrequest.taskPackage)
2231 resp->taskPackage = z_ext_record (assoc->encode, VAL_EXTENDED,
2232 (const char *) esrequest.taskPackage,
2234 yaz_log(LOG_DEBUG,"Send the result apdu");