2 * Copyright (C) 1995-2005, Index Data ApS
3 * See the file LICENSE for details.
5 * $Id: seshigh.c,v 1.63 2005-09-16 09:16:40 adam Exp $
9 * \brief Implements GFS session logic.
11 * Frontend server logic.
13 * This code receives incoming APDUs, and handles client requests by means
16 * Some of the code is getting quite involved, compared to simpler servers -
17 * primarily because it is asynchronous both in the communication with
18 * the user and the backend. We think the complexity will pay off in
19 * the form of greater flexibility when more asynchronous facilities
22 * Memory management has become somewhat involved. In the simple case, where
23 * only one PDU is pending at a time, it will simply reuse the same memory,
24 * once it has found its working size. When we enable multiple concurrent
25 * operations, perhaps even with multiple parallel calls to the backend, it
26 * will maintain a pool of buffers for encoding and decoding, trying to
27 * minimize memory allocation/deallocation during normal operation.
37 #include <sys/types.h>
45 #define S_ISREG(x) (x & _S_IFREG)
54 #include <libxml/parser.h>
55 #include <libxml/tree.h>
58 #include <yaz/yconfig.h>
59 #include <yaz/xmalloc.h>
60 #include <yaz/comstack.h>
63 #include <yaz/proto.h>
66 #include <yaz/logrpn.h>
67 #include <yaz/statserv.h>
68 #include <yaz/diagbib1.h>
69 #include <yaz/charneg.h>
70 #include <yaz/otherinfo.h>
71 #include <yaz/yaz-util.h>
72 #include <yaz/pquery.h>
75 #include <yaz/backend.h>
77 static void process_gdu_request(association *assoc, request *req);
78 static int process_z_request(association *assoc, request *req, char **msg);
79 void backend_response(IOCHAN i, int event);
80 static int process_gdu_response(association *assoc, request *req, Z_GDU *res);
81 static int process_z_response(association *assoc, request *req, Z_APDU *res);
82 static Z_APDU *process_initRequest(association *assoc, request *reqb);
83 static Z_External *init_diagnostics(ODR odr, int errcode,
84 const char *errstring);
85 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
87 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
88 bend_search_rr *bsrr, int *fd);
89 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
91 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
92 static Z_APDU *process_sortRequest(association *assoc, request *reqb, int *fd);
93 static void process_close(association *assoc, request *reqb);
94 void save_referenceId (request *reqb, Z_ReferenceId *refid);
95 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
97 static Z_APDU *process_segmentRequest (association *assoc, request *reqb);
99 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd);
101 /* dynamic logging levels */
102 static int logbits_set = 0;
103 static int log_session = 0;
104 static int log_request = 0; /* one-line logs for requests */
105 static int log_requestdetail = 0; /* more detailed stuff */
107 /** get_logbits sets global loglevel bits */
108 static void get_logbits()
109 { /* needs to be called after parsing cmd-line args that can set loglevels!*/
113 log_session = yaz_log_module_level("session");
114 log_request = yaz_log_module_level("request");
115 log_requestdetail = yaz_log_module_level("requestdetail");
119 static void wr_diag(WRBUF w, int error, const char *addinfo)
121 wrbuf_printf(w, "ERROR [%d] %s%s%s",
122 error, diagbib1_str(error),
123 addinfo ? "--" : "", addinfo ? addinfo : "");
128 * Create and initialize a new association-handle.
129 * channel : iochannel for the current line.
130 * link : communications channel.
131 * Returns: 0 or a new association handle.
133 association *create_association(IOCHAN channel, COMSTACK link,
134 const char *apdufile)
140 if (!(anew = (association *)xmalloc(sizeof(*anew))))
144 anew->last_control = 0;
145 anew->client_chan = channel;
146 anew->client_link = link;
147 anew->cs_get_mask = 0;
148 anew->cs_put_mask = 0;
149 anew->cs_accept_mask = 0;
150 if (!(anew->decode = odr_createmem(ODR_DECODE)) ||
151 !(anew->encode = odr_createmem(ODR_ENCODE)))
153 if (apdufile && *apdufile)
157 if (!(anew->print = odr_createmem(ODR_PRINT)))
159 if (*apdufile == '@')
161 odr_setprint(anew->print, yaz_log_file());
163 else if (*apdufile != '-')
166 sprintf(filename, "%.200s.%ld", apdufile, (long)getpid());
167 if (!(f = fopen(filename, "w")))
169 yaz_log(YLOG_WARN|YLOG_ERRNO, "%s", filename);
172 setvbuf(f, 0, _IONBF, 0);
173 odr_setprint(anew->print, f);
178 anew->input_buffer = 0;
179 anew->input_buffer_len = 0;
181 anew->state = ASSOC_NEW;
182 request_initq(&anew->incoming);
183 request_initq(&anew->outgoing);
184 anew->proto = cs_getproto(link);
185 anew->cql_transform = 0;
186 anew->server_node_ptr = 0;
191 * Free association and release resources.
193 void destroy_association(association *h)
195 statserv_options_block *cb = statserv_getcontrol();
199 odr_destroy(h->decode);
200 odr_destroy(h->encode);
202 odr_destroy(h->print);
204 xfree(h->input_buffer);
206 (*cb->bend_close)(h->backend);
207 while ((req = request_deq(&h->incoming)))
208 request_release(req);
209 while ((req = request_deq(&h->outgoing)))
210 request_release(req);
211 request_delq(&h->incoming);
212 request_delq(&h->outgoing);
214 xmalloc_trav("session closed");
215 if (cb && cb->one_shot)
221 static void do_close_req(association *a, int reason, char *message,
225 Z_Close *cls = zget_Close(a->encode);
227 /* Purge request queue */
228 while (request_deq(&a->incoming));
229 while (request_deq(&a->outgoing));
232 yaz_log(log_requestdetail, "Sending Close PDU, reason=%d, message=%s",
233 reason, message ? message : "none");
234 apdu.which = Z_APDU_close;
236 *cls->closeReason = reason;
237 cls->diagnosticInformation = message;
238 process_z_response(a, req, &apdu);
239 iochan_settimeout(a->client_chan, 20);
243 request_release(req);
244 yaz_log(log_requestdetail, "v2 client. No Close PDU");
245 iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
248 a->state = ASSOC_DEAD;
251 static void do_close(association *a, int reason, char *message)
253 request *req = request_get(&a->outgoing);
254 do_close_req (a, reason, message, req);
258 * This is where PDUs from the client are read and the further
259 * processing is initiated. Flow of control moves down through the
260 * various process_* functions below, until the encoded result comes back up
261 * to the output handler in here.
263 * h : the I/O channel that has an outstanding event.
264 * event : the current outstanding event.
266 void ir_session(IOCHAN h, int event)
269 association *assoc = (association *)iochan_getdata(h);
270 COMSTACK conn = assoc->client_link;
273 assert(h && conn && assoc);
274 if (event == EVENT_TIMEOUT)
276 if (assoc->state != ASSOC_UP)
278 yaz_log(YLOG_DEBUG, "Final timeout - closing connection.");
279 /* do we need to lod this at all */
281 destroy_association(assoc);
286 yaz_log(log_session, "Session idle too long. Sending close.");
287 do_close(assoc, Z_Close_lackOfActivity, 0);
291 if (event & assoc->cs_accept_mask)
293 if (!cs_accept (conn))
295 yaz_log (YLOG_WARN, "accept failed");
296 destroy_association(assoc);
299 iochan_clearflag (h, EVENT_OUTPUT);
300 if (conn->io_pending)
301 { /* cs_accept didn't complete */
302 assoc->cs_accept_mask =
303 ((conn->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
304 ((conn->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
306 iochan_setflag (h, assoc->cs_accept_mask);
309 { /* cs_accept completed. Prepare for reading (cs_get) */
310 assoc->cs_accept_mask = 0;
311 assoc->cs_get_mask = EVENT_INPUT;
312 iochan_setflag (h, assoc->cs_get_mask);
316 if ((event & assoc->cs_get_mask) || (event & EVENT_WORK)) /* input */
318 if ((assoc->cs_put_mask & EVENT_INPUT) == 0 && (event & assoc->cs_get_mask))
320 yaz_log(YLOG_DEBUG, "ir_session (input)");
321 /* We aren't speaking to this fellow */
322 if (assoc->state == ASSOC_DEAD)
324 yaz_log(log_session, "Connection closed - end of session");
326 destroy_association(assoc);
330 assoc->cs_get_mask = EVENT_INPUT;
331 if ((res = cs_get(conn, &assoc->input_buffer,
332 &assoc->input_buffer_len)) <= 0)
334 yaz_log(log_session, "Connection closed by client");
336 destroy_association(assoc);
340 else if (res == 1) /* incomplete read - wait for more */
342 if (conn->io_pending & CS_WANT_WRITE)
343 assoc->cs_get_mask |= EVENT_OUTPUT;
344 iochan_setflag(h, assoc->cs_get_mask);
347 if (cs_more(conn)) /* more stuff - call us again later, please */
348 iochan_setevent(h, EVENT_INPUT);
350 /* we got a complete PDU. Let's decode it */
351 yaz_log(YLOG_DEBUG, "Got PDU, %d bytes: lead=%02X %02X %02X", res,
352 assoc->input_buffer[0] & 0xff,
353 assoc->input_buffer[1] & 0xff,
354 assoc->input_buffer[2] & 0xff);
355 req = request_get(&assoc->incoming); /* get a new request */
356 odr_reset(assoc->decode);
357 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
358 if (!z_GDU(assoc->decode, &req->gdu_request, 0, 0))
360 yaz_log(YLOG_WARN, "ODR error on incoming PDU: %s [element %s] "
362 odr_errmsg(odr_geterror(assoc->decode)),
363 odr_getelement(assoc->decode),
364 odr_offset(assoc->decode));
365 if (assoc->decode->error != OHTTP)
367 yaz_log(YLOG_WARN, "PDU dump:");
368 odr_dumpBER(yaz_log_file(), assoc->input_buffer, res);
369 request_release(req);
370 do_close(assoc, Z_Close_protocolError,"Malformed package");
374 Z_GDU *p = z_get_HTTP_Response(assoc->encode, 400);
375 assoc->state = ASSOC_DEAD;
376 process_gdu_response(assoc, req, p);
380 req->request_mem = odr_extract_mem(assoc->decode);
383 if (!z_GDU(assoc->print, &req->gdu_request, 0, 0))
384 yaz_log(YLOG_WARN, "ODR print error: %s",
385 odr_errmsg(odr_geterror(assoc->print)));
386 odr_reset(assoc->print);
388 request_enq(&assoc->incoming, req);
391 /* can we do something yet? */
392 req = request_head(&assoc->incoming);
393 if (req->state == REQUEST_IDLE)
395 request_deq(&assoc->incoming);
396 process_gdu_request(assoc, req);
399 if (event & assoc->cs_put_mask)
401 request *req = request_head(&assoc->outgoing);
403 assoc->cs_put_mask = 0;
404 yaz_log(YLOG_DEBUG, "ir_session (output)");
405 req->state = REQUEST_PENDING;
406 switch (res = cs_put(conn, req->response, req->len_response))
409 yaz_log(log_session, "Connection closed by client");
411 destroy_association(assoc);
414 case 0: /* all sent - release the request structure */
415 yaz_log(YLOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
417 yaz_log(YLOG_DEBUG, "HTTP out:\n%.*s", req->len_response,
420 nmem_destroy(req->request_mem);
421 request_deq(&assoc->outgoing);
422 request_release(req);
423 if (!request_head(&assoc->outgoing))
424 { /* restore mask for cs_get operation ... */
425 iochan_clearflag(h, EVENT_OUTPUT|EVENT_INPUT);
426 iochan_setflag(h, assoc->cs_get_mask);
427 if (assoc->state == ASSOC_DEAD)
428 iochan_setevent(assoc->client_chan, EVENT_TIMEOUT);
432 assoc->cs_put_mask = EVENT_OUTPUT;
436 if (conn->io_pending & CS_WANT_WRITE)
437 assoc->cs_put_mask |= EVENT_OUTPUT;
438 if (conn->io_pending & CS_WANT_READ)
439 assoc->cs_put_mask |= EVENT_INPUT;
440 iochan_setflag(h, assoc->cs_put_mask);
443 if (event & EVENT_EXCEPT)
445 yaz_log(YLOG_WARN, "ir_session (exception)");
447 destroy_association(assoc);
452 static int process_z_request(association *assoc, request *req, char **msg);
455 static void assoc_init_reset(association *assoc)
458 assoc->init = (bend_initrequest *) xmalloc (sizeof(*assoc->init));
460 assoc->init->stream = assoc->encode;
461 assoc->init->print = assoc->print;
462 assoc->init->auth = 0;
463 assoc->init->referenceId = 0;
464 assoc->init->implementation_version = 0;
465 assoc->init->implementation_id = 0;
466 assoc->init->implementation_name = 0;
467 assoc->init->bend_sort = NULL;
468 assoc->init->bend_search = NULL;
469 assoc->init->bend_present = NULL;
470 assoc->init->bend_esrequest = NULL;
471 assoc->init->bend_delete = NULL;
472 assoc->init->bend_scan = NULL;
473 assoc->init->bend_segment = NULL;
474 assoc->init->bend_fetch = NULL;
475 assoc->init->bend_explain = NULL;
476 assoc->init->bend_srw_scan = NULL;
478 assoc->init->charneg_request = NULL;
479 assoc->init->charneg_response = NULL;
481 assoc->init->decode = assoc->decode;
482 assoc->init->peer_name =
483 odr_strdup (assoc->encode, cs_addrstr(assoc->client_link));
485 yaz_log(log_requestdetail, "peer %s", assoc->init->peer_name);
488 static int srw_bend_init(association *assoc, Z_SRW_diagnostic **d, int *num)
490 statserv_options_block *cb = statserv_getcontrol();
493 const char *encoding = "UTF-8";
495 bend_initresult *binitres;
497 yaz_log(YLOG_LOG, "srw_bend_init config=%s", cb->configname);
498 assoc_init_reset(assoc);
500 assoc->maximumRecordSize = 3000000;
501 assoc->preferredMessageSize = 3000000;
503 ce = yaz_set_proposal_charneg(assoc->decode, &encoding, 1, 0, 0, 1);
504 assoc->init->charneg_request = ce->u.charNeg3;
507 if (!(binitres = (*cb->bend_init)(assoc->init)))
509 assoc->state = ASSOC_DEAD;
510 yaz_add_srw_diagnostic(assoc->encode, d, num,
511 YAZ_SRW_AUTHENTICATION_ERROR, 0);
514 assoc->backend = binitres->handle;
515 if (binitres->errcode)
517 assoc->state = ASSOC_DEAD;
518 yaz_add_srw_diagnostic(assoc->encode, d, num, binitres->errcode,
519 binitres->errstring);
527 static int srw_bend_fetch(association *assoc, int pos,
528 Z_SRW_searchRetrieveRequest *srw_req,
529 Z_SRW_record *record)
532 ODR o = assoc->encode;
534 rr.setname = "default";
537 rr.request_format = VAL_TEXT_XML;
538 rr.request_format_raw = yaz_oidval_to_z3950oid(assoc->decode,
541 rr.comp = (Z_RecordComposition *)
542 odr_malloc(assoc->decode, sizeof(*rr.comp));
543 rr.comp->which = Z_RecordComp_complex;
544 rr.comp->u.complex = (Z_CompSpec *)
545 odr_malloc(assoc->decode, sizeof(Z_CompSpec));
546 rr.comp->u.complex->selectAlternativeSyntax = (bool_t *)
547 odr_malloc(assoc->encode, sizeof(bool_t));
548 *rr.comp->u.complex->selectAlternativeSyntax = 0;
549 rr.comp->u.complex->num_dbSpecific = 0;
550 rr.comp->u.complex->dbSpecific = 0;
551 rr.comp->u.complex->num_recordSyntax = 0;
552 rr.comp->u.complex->recordSyntax = 0;
554 rr.comp->u.complex->generic = (Z_Specification *)
555 odr_malloc(assoc->decode, sizeof(Z_Specification));
557 /* schema uri = recordSchema (or NULL if recordSchema is not given) */
558 rr.comp->u.complex->generic->which = Z_Schema_uri;
559 rr.comp->u.complex->generic->schema.uri = srw_req->recordSchema;
561 /* ESN = recordSchema if recordSchema is present */
562 rr.comp->u.complex->generic->elementSpec = 0;
563 if (srw_req->recordSchema)
565 rr.comp->u.complex->generic->elementSpec =
566 (Z_ElementSpec *) odr_malloc(assoc->encode, sizeof(Z_ElementSpec));
567 rr.comp->u.complex->generic->elementSpec->which =
568 Z_ElementSpec_elementSetName;
569 rr.comp->u.complex->generic->elementSpec->u.elementSetName =
570 srw_req->recordSchema;
573 rr.stream = assoc->encode;
574 rr.print = assoc->print;
580 rr.output_format = VAL_TEXT_XML;
581 rr.output_format_raw = 0;
584 rr.surrogate_flag = 0;
585 rr.schema = srw_req->recordSchema;
587 if (!assoc->init->bend_fetch)
590 (*assoc->init->bend_fetch)(assoc->backend, &rr);
592 if (rr.errcode && rr.surrogate_flag)
594 int code = yaz_diag_bib1_to_srw(rr.errcode);
595 const char *message = yaz_diag_srw_str(code);
598 len += strlen(message);
600 len += strlen(rr.errstring);
602 record->recordData_buf = odr_malloc(o, len);
604 sprintf(record->recordData_buf, "<diagnostic "
605 "xmlns=\"http://www.loc.gov/zing/srw/diagnostic/\">\n"
606 " <uri>info:srw/diagnostic/1/%d</uri>\n", code);
608 sprintf(record->recordData_buf + strlen(record->recordData_buf),
609 " <details>%s</details>\n", rr.errstring);
611 sprintf(record->recordData_buf + strlen(record->recordData_buf),
612 " <message>%s</message>\n", message);
613 sprintf(record->recordData_buf + strlen(record->recordData_buf),
615 record->recordData_len = strlen(record->recordData_buf);
616 record->recordPosition = odr_intdup(o, pos);
617 record->recordSchema = "info:srw/schema/1/diagnostics-v1.1";
620 else if (rr.len >= 0)
622 record->recordData_buf = rr.record;
623 record->recordData_len = rr.len;
624 record->recordPosition = odr_intdup(o, pos);
626 record->recordSchema = odr_strdup(o, rr.schema);
628 record->recordSchema = 0;
633 static int cql2pqf(ODR odr, const char *cql, cql_transform_t ct,
634 Z_Query *query_result)
636 /* have a CQL query and CQL to PQF transform .. */
637 CQL_parser cp = cql_parser_create();
643 r = cql_parser_string(cp, cql);
646 /* CQL syntax error */
652 r = cql_transform_buf(ct,
653 cql_parser_result(cp),
654 rpn_buf, sizeof(rpn_buf)-1);
656 srw_errcode = cql_transform_error(ct, &add);
660 /* Syntax & transform OK. */
661 /* Convert PQF string to Z39.50 to RPN query struct */
662 YAZ_PQF_Parser pp = yaz_pqf_create();
663 Z_RPNQuery *rpnquery = yaz_pqf_parse(pp, odr, rpn_buf);
668 int code = yaz_pqf_error(pp, &pqf_msg, &off);
669 yaz_log(YLOG_WARN, "PQF Parser Error %s (code %d)",
675 query_result->which = Z_Query_type_1;
676 query_result->u.type_1 = rpnquery;
680 cql_parser_destroy(cp);
684 static int cql2pqf_scan(ODR odr, const char *cql, cql_transform_t ct,
685 Z_AttributesPlusTerm *result)
689 int srw_error = cql2pqf(odr, cql, ct, &query);
692 if (query.which != Z_Query_type_1 && query.which != Z_Query_type_101)
693 return 10; /* bad query type */
694 rpn = query.u.type_1;
695 if (!rpn->RPNStructure)
696 return 10; /* must be structure */
697 if (rpn->RPNStructure->which != Z_RPNStructure_simple)
698 return 10; /* must be simple */
699 if (rpn->RPNStructure->u.simple->which != Z_Operand_APT)
700 return 10; /* must be attributes plus term node .. */
701 memcpy(result, rpn->RPNStructure->u.simple->u.attributesPlusTerm,
706 static void srw_bend_search(association *assoc, request *req,
707 Z_SRW_searchRetrieveRequest *srw_req,
708 Z_SRW_searchRetrieveResponse *srw_res,
715 yaz_log(log_requestdetail, "Got SRW SearchRetrieveRequest");
716 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics);
717 if (srw_res->num_diagnostics == 0 && assoc->init)
720 rr.setname = "default";
723 rr.basenames = &srw_req->database;
727 rr.srw_setnameIdleTime = 0;
728 rr.query = (Z_Query *) odr_malloc (assoc->decode, sizeof(*rr.query));
729 rr.query->u.type_1 = 0;
731 if (srw_req->query_type == Z_SRW_query_type_cql)
733 if (assoc->cql_transform)
735 int srw_errcode = cql2pqf(assoc->encode, srw_req->query.cql,
736 assoc->cql_transform, rr.query);
739 yaz_add_srw_diagnostic(assoc->encode,
740 &srw_res->diagnostics,
741 &srw_res->num_diagnostics,
747 /* CQL query to backend. Wrap it - Z39.50 style */
748 ext = (Z_External *) odr_malloc(assoc->decode, sizeof(*ext));
749 ext->direct_reference = odr_getoidbystr(assoc->decode,
750 "1.2.840.10003.16.2");
751 ext->indirect_reference = 0;
753 ext->which = Z_External_CQL;
754 ext->u.cql = srw_req->query.cql;
756 rr.query->which = Z_Query_type_104;
757 rr.query->u.type_104 = ext;
760 else if (srw_req->query_type == Z_SRW_query_type_pqf)
762 Z_RPNQuery *RPNquery;
763 YAZ_PQF_Parser pqf_parser;
765 pqf_parser = yaz_pqf_create ();
767 RPNquery = yaz_pqf_parse (pqf_parser, assoc->decode,
773 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
774 yaz_log(log_requestdetail, "Parse error %d %s near offset %d",
776 srw_error = YAZ_SRW_QUERY_SYNTAX_ERROR;
779 rr.query->which = Z_Query_type_1;
780 rr.query->u.type_1 = RPNquery;
782 yaz_pqf_destroy (pqf_parser);
786 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
787 &srw_res->num_diagnostics,
788 YAZ_SRW_UNSUPP_QUERY_TYPE, 0);
790 if (rr.query->u.type_1)
792 rr.stream = assoc->encode;
793 rr.decode = assoc->decode;
794 rr.print = assoc->print;
796 if ( srw_req->sort.sortKeys )
797 rr.srw_sortKeys = odr_strdup(assoc->encode,
798 srw_req->sort.sortKeys );
799 rr.association = assoc;
805 yaz_log_zquery_level(log_requestdetail,rr.query);
807 (assoc->init->bend_search)(assoc->backend, &rr);
810 if (rr.errcode == YAZ_BIB1_DATABASE_UNAVAILABLE)
816 srw_error = yaz_diag_bib1_to_srw (rr.errcode);
817 yaz_add_srw_diagnostic(assoc->encode,
818 &srw_res->diagnostics,
819 &srw_res->num_diagnostics,
820 srw_error, rr.errstring);
825 int number = srw_req->maximumRecords ? *srw_req->maximumRecords : 0;
826 int start = srw_req->startRecord ? *srw_req->startRecord : 1;
828 yaz_log(log_requestdetail, "Request to pack %d+%d out of %d",
829 start, number, rr.hits);
831 srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
834 srw_res->resultSetId =
835 odr_strdup(assoc->encode, rr.srw_setname );
836 srw_res->resultSetIdleTime =
837 odr_intdup(assoc->encode, *rr.srw_setnameIdleTime );
845 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
846 &srw_res->num_diagnostics,
847 YAZ_SRW_FIRST_RECORD_POSITION_OUT_OF_RANGE, 0);
852 int packing = Z_SRW_recordPacking_string;
853 if (start + number > rr.hits)
854 number = rr.hits - start + 1;
855 if (srw_req->recordPacking &&
856 !strcmp(srw_req->recordPacking, "xml"))
857 packing = Z_SRW_recordPacking_XML;
858 srw_res->records = (Z_SRW_record *)
859 odr_malloc(assoc->encode,
860 number * sizeof(*srw_res->records));
861 for (i = 0; i<number; i++)
865 srw_res->records[j].recordPacking = packing;
866 srw_res->records[j].recordData_buf = 0;
867 yaz_log(YLOG_DEBUG, "srw_bend_fetch %d", i+start);
868 errcode = srw_bend_fetch(assoc, i+start, srw_req,
869 srw_res->records + j);
872 yaz_add_srw_diagnostic(assoc->encode,
873 &srw_res->diagnostics,
874 &srw_res->num_diagnostics,
875 yaz_diag_bib1_to_srw (errcode),
880 if (srw_res->records[j].recordData_buf)
883 srw_res->num_records = j;
885 srw_res->records = 0;
893 const char *querystr = "?";
894 const char *querytype = "?";
895 WRBUF wr = wrbuf_alloc();
897 switch (srw_req->query_type)
899 case Z_SRW_query_type_cql:
901 querystr = srw_req->query.cql;
903 case Z_SRW_query_type_pqf:
905 querystr = srw_req->query.pqf;
908 wrbuf_printf(wr, "SRWSearch ");
909 if (srw_res->num_diagnostics)
910 wrbuf_printf(wr, "ERROR %s", srw_res->diagnostics[0].uri);
911 else if (*http_code != 200)
912 wrbuf_printf(wr, "ERROR info:http/%d", *http_code);
913 else if (srw_res->numberOfRecords)
915 wrbuf_printf(wr, "OK %d",
916 (srw_res->numberOfRecords ?
917 *srw_res->numberOfRecords : 0));
919 wrbuf_printf(wr, " %s %d+%d",
920 (srw_res->resultSetId ?
921 srw_res->resultSetId : "-"),
922 (srw_req->startRecord ? *srw_req->startRecord : 1),
923 srw_res->num_records);
924 yaz_log(log_request, "%s %s: %s", wrbuf_buf(wr), querytype, querystr);
929 static char *srw_bend_explain_default(void *handle, bend_explain_rr *rr)
932 xmlNodePtr ptr = rr->server_node_ptr;
935 for (ptr = ptr->children; ptr; ptr = ptr->next)
937 if (ptr->type != XML_ELEMENT_NODE)
939 if (!strcmp((const char *) ptr->name, "explain"))
942 xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
946 ptr = xmlCopyNode(ptr, 1);
948 xmlDocSetRootElement(doc, ptr);
950 xmlDocDumpMemory(doc, &buf_out, &len);
951 content = (char*) odr_malloc(rr->stream, 1+len);
952 memcpy(content, buf_out, len);
957 rr->explain_buf = content;
965 static void srw_bend_explain(association *assoc, request *req,
966 Z_SRW_explainRequest *srw_req,
967 Z_SRW_explainResponse *srw_res,
970 yaz_log(log_requestdetail, "Got SRW ExplainRequest");
972 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics);
977 rr.stream = assoc->encode;
978 rr.decode = assoc->decode;
979 rr.print = assoc->print;
981 rr.database = srw_req->database;
982 rr.server_node_ptr = assoc->server_node_ptr;
983 rr.schema = "http://explain.z3950.org/dtd/2.0/";
984 if (assoc->init->bend_explain)
985 (*assoc->init->bend_explain)(assoc->backend, &rr);
987 srw_bend_explain_default(assoc->backend, &rr);
991 int packing = Z_SRW_recordPacking_string;
992 if (srw_req->recordPacking &&
993 !strcmp(srw_req->recordPacking, "xml"))
994 packing = Z_SRW_recordPacking_XML;
995 srw_res->record.recordSchema = rr.schema;
996 srw_res->record.recordPacking = packing;
997 srw_res->record.recordData_buf = rr.explain_buf;
998 srw_res->record.recordData_len = strlen(rr.explain_buf);
999 srw_res->record.recordPosition = 0;
1005 static void srw_bend_scan(association *assoc, request *req,
1006 Z_SRW_scanRequest *srw_req,
1007 Z_SRW_scanResponse *srw_res,
1010 yaz_log(log_requestdetail, "Got SRW ScanRequest");
1013 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics);
1014 if (srw_res->num_diagnostics == 0 && assoc->init)
1016 struct scan_entry *save_entries;
1018 bend_scan_rr *bsrr = (bend_scan_rr *)
1019 odr_malloc (assoc->encode, sizeof(*bsrr));
1020 bsrr->num_bases = 1;
1021 bsrr->basenames = &srw_req->database;
1023 bsrr->num_entries = srw_req->maximumTerms ?
1024 *srw_req->maximumTerms : 10;
1025 bsrr->term_position = srw_req->responsePosition ?
1026 *srw_req->responsePosition : 1;
1029 bsrr->errstring = 0;
1030 bsrr->referenceId = 0;
1031 bsrr->stream = assoc->encode;
1032 bsrr->print = assoc->print;
1033 bsrr->step_size = odr_intdup(assoc->decode, 0);
1036 if (bsrr->num_entries > 0)
1039 bsrr->entries = odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
1041 for (i = 0; i<bsrr->num_entries; i++)
1043 bsrr->entries[i].term = 0;
1044 bsrr->entries[i].occurrences = 0;
1045 bsrr->entries[i].errcode = 0;
1046 bsrr->entries[i].errstring = 0;
1047 bsrr->entries[i].display_term = 0;
1050 save_entries = bsrr->entries; /* save it so we can compare later */
1052 if (srw_req->query_type == Z_SRW_query_type_pqf &&
1053 assoc->init->bend_scan)
1055 Odr_oid *scan_attributeSet = 0;
1057 YAZ_PQF_Parser pqf_parser = yaz_pqf_create();
1059 bsrr->term = yaz_pqf_scan(pqf_parser, assoc->decode,
1061 srw_req->scanClause.pqf);
1062 if (scan_attributeSet &&
1063 (attset = oid_getentbyoid(scan_attributeSet)) &&
1064 (attset->oclass == CLASS_ATTSET ||
1065 attset->oclass == CLASS_GENERAL))
1066 bsrr->attributeset = attset->value;
1068 bsrr->attributeset = VAL_NONE;
1069 yaz_pqf_destroy(pqf_parser);
1070 bsrr->scanClause = 0;
1071 ((int (*)(void *, bend_scan_rr *))
1072 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1074 else if (srw_req->query_type == Z_SRW_query_type_cql
1075 && assoc->init->bend_srw_scan)
1077 if (assoc->cql_transform)
1080 bsrr->scanClause = 0;
1081 bsrr->attributeset = VAL_NONE;
1082 bsrr->term = odr_malloc(assoc->decode, sizeof(*bsrr->term));
1083 srw_error = cql2pqf_scan(assoc->encode,
1084 srw_req->scanClause.cql,
1085 assoc->cql_transform,
1088 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1089 &srw_res->num_diagnostics,
1093 ((int (*)(void *, bend_scan_rr *))
1094 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1100 bsrr->attributeset = VAL_NONE;
1101 bsrr->scanClause = srw_req->scanClause.cql;
1102 ((int (*)(void *, bend_scan_rr *))
1103 (*assoc->init->bend_srw_scan))(assoc->backend, bsrr);
1108 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1109 &srw_res->num_diagnostics,
1110 YAZ_SRW_UNSUPP_OPERATION, "scan");
1115 if (bsrr->errcode == YAZ_BIB1_DATABASE_UNAVAILABLE)
1120 srw_error = yaz_diag_bib1_to_srw (bsrr->errcode);
1122 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1123 &srw_res->num_diagnostics,
1124 srw_error, bsrr->errstring);
1126 else if (srw_res->num_diagnostics == 0 && bsrr->num_entries)
1129 srw_res->terms = (Z_SRW_scanTerm*)
1130 odr_malloc(assoc->encode, sizeof(*srw_res->terms) *
1133 srw_res->num_terms = bsrr->num_entries;
1134 for (i = 0; i<bsrr->num_entries; i++)
1136 Z_SRW_scanTerm *t = srw_res->terms + i;
1137 t->value = odr_strdup(assoc->encode, bsrr->entries[i].term);
1138 t->numberOfRecords =
1139 odr_intdup(assoc->encode, bsrr->entries[i].occurrences);
1141 if (save_entries == bsrr->entries &&
1142 bsrr->entries[i].display_term)
1144 /* the entries was _not_ set by the handler. So it's
1145 safe to test for new member display_term. It is
1148 t->displayTerm = odr_strdup(assoc->encode,
1149 bsrr->entries[i].display_term);
1157 WRBUF wr = wrbuf_alloc();
1158 const char *querytype = 0;
1159 const char *querystr = 0;
1161 switch(srw_req->query_type)
1163 case Z_SRW_query_type_pqf:
1165 querystr = srw_req->scanClause.pqf;
1167 case Z_SRW_query_type_cql:
1169 querystr = srw_req->scanClause.cql;
1172 querytype = "Unknown";
1175 wrbuf_printf(wr, "SRWScan %d+%d",
1176 (srw_req->responsePosition ?
1177 *srw_req->responsePosition : 1),
1178 (srw_req->maximumTerms ?
1179 *srw_req->maximumTerms : 1));
1180 if (srw_res->num_diagnostics)
1181 wrbuf_printf(wr, " ERROR %s", srw_res->diagnostics[0].uri);
1183 wrbuf_printf(wr, " OK -");
1184 wrbuf_printf(wr, " %s: %s", querytype, querystr);
1185 yaz_log(log_request, "%s", wrbuf_buf(wr) );
1192 static void process_http_request(association *assoc, request *req)
1194 Z_HTTP_Request *hreq = req->gdu_request->u.HTTP_Request;
1195 ODR o = assoc->encode;
1196 int r = 2; /* 2=NOT TAKEN, 1=TAKEN, 0=SOAP TAKEN */
1198 Z_SOAP *soap_package = 0;
1201 Z_HTTP_Response *hres = 0;
1203 char *stylesheet = 0;
1204 Z_SRW_diagnostic *diagnostic = 0;
1205 int num_diagnostic = 0;
1206 const char *host = z_HTTP_header_lookup(hreq->headers, "Host");
1208 if (!control_association(assoc, host, 0))
1210 p = z_get_HTTP_Response(o, 404);
1213 if (r == 2 && !strcmp(hreq->path, "/test"))
1215 p = z_get_HTTP_Response(o, 200);
1216 hres = p->u.HTTP_Response;
1217 hres->content_buf = "1234567890\n";
1218 hres->content_len = strlen(hres->content_buf);
1223 r = yaz_srw_decode(hreq, &sr, &soap_package, assoc->decode, &charset);
1224 yaz_log(YLOG_DEBUG, "yaz_srw_decode returned %d", r);
1226 if (r == 2) /* not taken */
1228 r = yaz_sru_decode(hreq, &sr, &soap_package, assoc->decode, &charset,
1229 &diagnostic, &num_diagnostic);
1230 yaz_log(YLOG_DEBUG, "yaz_sru_decode returned %d", r);
1232 if (r == 0) /* decode SRW/SRU OK .. */
1234 int http_code = 200;
1235 if (sr->which == Z_SRW_searchRetrieve_request)
1238 yaz_srw_get(assoc->encode, Z_SRW_searchRetrieve_response);
1240 stylesheet = sr->u.request->stylesheet;
1243 res->u.response->diagnostics = diagnostic;
1244 res->u.response->num_diagnostics = num_diagnostic;
1248 srw_bend_search(assoc, req, sr->u.request, res->u.response,
1251 if (http_code == 200)
1252 soap_package->u.generic->p = res;
1254 else if (sr->which == Z_SRW_explain_request)
1256 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_explain_response);
1257 stylesheet = sr->u.explain_request->stylesheet;
1260 res->u.explain_response->diagnostics = diagnostic;
1261 res->u.explain_response->num_diagnostics = num_diagnostic;
1263 srw_bend_explain(assoc, req, sr->u.explain_request,
1264 res->u.explain_response, &http_code);
1265 if (http_code == 200)
1266 soap_package->u.generic->p = res;
1268 else if (sr->which == Z_SRW_scan_request)
1270 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_scan_response);
1271 stylesheet = sr->u.scan_request->stylesheet;
1274 res->u.scan_response->diagnostics = diagnostic;
1275 res->u.scan_response->num_diagnostics = num_diagnostic;
1277 srw_bend_scan(assoc, req, sr->u.scan_request,
1278 res->u.scan_response, &http_code);
1279 if (http_code == 200)
1280 soap_package->u.generic->p = res;
1284 yaz_log(log_request, "SOAP ERROR");
1285 /* FIXME - what error, what query */
1287 z_soap_error(assoc->encode, soap_package,
1288 "SOAP-ENV:Client", "Bad method", 0);
1290 if (http_code == 200 || http_code == 500)
1292 static Z_SOAP_Handler soap_handlers[3] = {
1294 {"http://www.loc.gov/zing/srw/", 0,
1295 (Z_SOAP_fun) yaz_srw_codec},
1296 {"http://www.loc.gov/zing/srw/v1.0/", 0,
1297 (Z_SOAP_fun) yaz_srw_codec},
1303 p = z_get_HTTP_Response(o, 200);
1304 hres = p->u.HTTP_Response;
1305 ret = z_soap_codec_enc_xsl(assoc->encode, &soap_package,
1306 &hres->content_buf, &hres->content_len,
1307 soap_handlers, charset, stylesheet);
1308 hres->code = http_code;
1310 strcpy(ctype, "text/xml");
1313 strcat(ctype, "; charset=");
1314 strcat(ctype, charset);
1316 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1319 p = z_get_HTTP_Response(o, http_code);
1323 p = z_get_HTTP_Response(o, 500);
1324 hres = p->u.HTTP_Response;
1325 if (!strcmp(hreq->version, "1.0"))
1327 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1328 if (v && !strcmp(v, "Keep-Alive"))
1332 hres->version = "1.0";
1336 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1337 if (v && !strcmp(v, "close"))
1341 hres->version = "1.1";
1345 z_HTTP_header_add(o, &hres->headers, "Connection", "close");
1346 assoc->state = ASSOC_DEAD;
1347 assoc->cs_get_mask = 0;
1352 const char *alive = z_HTTP_header_lookup(hreq->headers, "Keep-Alive");
1354 if (alive && isdigit(*(const unsigned char *) alive))
1358 if (t < 0 || t > 3600)
1360 iochan_settimeout(assoc->client_chan,t);
1361 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1363 process_gdu_response(assoc, req, p);
1366 static void process_gdu_request(association *assoc, request *req)
1368 if (req->gdu_request->which == Z_GDU_Z3950)
1371 req->apdu_request = req->gdu_request->u.z3950;
1372 if (process_z_request(assoc, req, &msg) < 0)
1373 do_close_req(assoc, Z_Close_systemProblem, msg, req);
1375 else if (req->gdu_request->which == Z_GDU_HTTP_Request)
1376 process_http_request(assoc, req);
1379 do_close_req(assoc, Z_Close_systemProblem, "bad protocol packet", req);
1384 * Initiate request processing.
1386 static int process_z_request(association *assoc, request *req, char **msg)
1392 *msg = "Unknown Error";
1393 assert(req && req->state == REQUEST_IDLE);
1394 if (req->apdu_request->which != Z_APDU_initRequest && !assoc->init)
1396 *msg = "Missing InitRequest";
1399 switch (req->apdu_request->which)
1401 case Z_APDU_initRequest:
1402 res = process_initRequest(assoc, req); break;
1403 case Z_APDU_searchRequest:
1404 res = process_searchRequest(assoc, req, &fd); break;
1405 case Z_APDU_presentRequest:
1406 res = process_presentRequest(assoc, req, &fd); break;
1407 case Z_APDU_scanRequest:
1408 if (assoc->init->bend_scan)
1409 res = process_scanRequest(assoc, req, &fd);
1412 *msg = "Cannot handle Scan APDU";
1416 case Z_APDU_extendedServicesRequest:
1417 if (assoc->init->bend_esrequest)
1418 res = process_ESRequest(assoc, req, &fd);
1421 *msg = "Cannot handle Extended Services APDU";
1425 case Z_APDU_sortRequest:
1426 if (assoc->init->bend_sort)
1427 res = process_sortRequest(assoc, req, &fd);
1430 *msg = "Cannot handle Sort APDU";
1435 process_close(assoc, req);
1437 case Z_APDU_deleteResultSetRequest:
1438 if (assoc->init->bend_delete)
1439 res = process_deleteRequest(assoc, req, &fd);
1442 *msg = "Cannot handle Delete APDU";
1446 case Z_APDU_segmentRequest:
1447 if (assoc->init->bend_segment)
1449 res = process_segmentRequest (assoc, req);
1453 *msg = "Cannot handle Segment APDU";
1457 case Z_APDU_triggerResourceControlRequest:
1460 *msg = "Bad APDU received";
1465 yaz_log(YLOG_DEBUG, " result immediately available");
1466 retval = process_z_response(assoc, req, res);
1470 yaz_log(YLOG_DEBUG, " result unavailble");
1473 else /* no result yet - one will be provided later */
1477 /* Set up an I/O handler for the fd supplied by the backend */
1479 yaz_log(YLOG_DEBUG, " establishing handler for result");
1480 req->state = REQUEST_PENDING;
1481 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT, 0)))
1483 iochan_setdata(chan, assoc);
1490 * Handle message from the backend.
1492 void backend_response(IOCHAN i, int event)
1494 association *assoc = (association *)iochan_getdata(i);
1495 request *req = request_head(&assoc->incoming);
1499 yaz_log(YLOG_DEBUG, "backend_response");
1500 assert(assoc && req && req->state != REQUEST_IDLE);
1501 /* determine what it is we're waiting for */
1502 switch (req->apdu_request->which)
1504 case Z_APDU_searchRequest:
1505 res = response_searchRequest(assoc, req, 0, &fd); break;
1507 case Z_APDU_presentRequest:
1508 res = response_presentRequest(assoc, req, 0, &fd); break;
1509 case Z_APDU_scanRequest:
1510 res = response_scanRequest(assoc, req, 0, &fd); break;
1513 yaz_log(YLOG_FATAL, "Serious programmer's lapse or bug");
1516 if ((res && process_z_response(assoc, req, res) < 0) || fd < 0)
1518 yaz_log(YLOG_WARN, "Fatal error when talking to backend");
1519 do_close(assoc, Z_Close_systemProblem, 0);
1523 else if (!res) /* no result yet - try again later */
1525 yaz_log(YLOG_DEBUG, " no result yet");
1526 iochan_setfd(i, fd); /* in case fd has changed */
1531 * Encode response, and transfer the request structure to the outgoing queue.
1533 static int process_gdu_response(association *assoc, request *req, Z_GDU *res)
1535 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
1539 if (!z_GDU(assoc->print, &res, 0, 0))
1540 yaz_log(YLOG_WARN, "ODR print error: %s",
1541 odr_errmsg(odr_geterror(assoc->print)));
1542 odr_reset(assoc->print);
1544 if (!z_GDU(assoc->encode, &res, 0, 0))
1546 yaz_log(YLOG_WARN, "ODR error when encoding PDU: %s [element %s]",
1547 odr_errmsg(odr_geterror(assoc->decode)),
1548 odr_getelement(assoc->decode));
1551 req->response = odr_getbuf(assoc->encode, &req->len_response,
1552 &req->size_response);
1553 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
1554 odr_reset(assoc->encode);
1555 req->state = REQUEST_IDLE;
1556 request_enq(&assoc->outgoing, req);
1557 /* turn the work over to the ir_session handler */
1558 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
1559 assoc->cs_put_mask = EVENT_OUTPUT;
1560 /* Is there more work to be done? give that to the input handler too */
1562 if (request_head(&assoc->incoming))
1564 yaz_log (YLOG_DEBUG, "more work to be done");
1565 iochan_setevent(assoc->client_chan, EVENT_WORK);
1572 * Encode response, and transfer the request structure to the outgoing queue.
1574 static int process_z_response(association *assoc, request *req, Z_APDU *res)
1576 Z_GDU *gres = (Z_GDU *) odr_malloc(assoc->encode, sizeof(*res));
1577 gres->which = Z_GDU_Z3950;
1578 gres->u.z3950 = res;
1580 return process_gdu_response(assoc, req, gres);
1583 static char *get_vhost(Z_OtherInformation *otherInfo)
1585 return yaz_oi_get_string_oidval(&otherInfo, VAL_PROXY, 1, 0);
1589 * Handle init request.
1590 * At the moment, we don't check the options
1591 * anywhere else in the code - we just try not to do anything that would
1592 * break a naive client. We'll toss 'em into the association block when
1593 * we need them there.
1595 static Z_APDU *process_initRequest(association *assoc, request *reqb)
1597 Z_InitRequest *req = reqb->apdu_request->u.initRequest;
1598 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
1599 Z_InitResponse *resp = apdu->u.initResponse;
1600 bend_initresult *binitres;
1603 statserv_options_block *cb = 0; /* by default no control for backend */
1605 if (control_association(assoc, get_vhost(req->otherInfo), 1))
1606 cb = statserv_getcontrol(); /* got control block for backend */
1608 if (cb && assoc->backend)
1609 (*cb->bend_close)(assoc->backend);
1611 yaz_log(log_requestdetail, "Got initRequest");
1612 if (req->implementationId)
1613 yaz_log(log_requestdetail, "Id: %s",
1614 req->implementationId);
1615 if (req->implementationName)
1616 yaz_log(log_requestdetail, "Name: %s",
1617 req->implementationName);
1618 if (req->implementationVersion)
1619 yaz_log(log_requestdetail, "Version: %s",
1620 req->implementationVersion);
1622 assoc_init_reset(assoc);
1624 assoc->init->auth = req->idAuthentication;
1625 assoc->init->referenceId = req->referenceId;
1627 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
1629 Z_CharSetandLanguageNegotiation *negotiation =
1630 yaz_get_charneg_record (req->otherInfo);
1632 negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
1633 assoc->init->charneg_request = negotiation;
1639 if (req->implementationVersion)
1640 yaz_log(log_requestdetail, "Config: %s",
1643 iochan_settimeout(assoc->client_chan, cb->idle_timeout * 60);
1645 /* we have a backend control block, so call that init function */
1646 if (!(binitres = (*cb->bend_init)(assoc->init)))
1648 yaz_log(YLOG_WARN, "Bad response from backend.");
1651 assoc->backend = binitres->handle;
1655 /* no backend. return error */
1656 binitres = odr_malloc(assoc->encode, sizeof(*binitres));
1657 binitres->errstring = 0;
1658 binitres->errcode = YAZ_BIB1_PERMANENT_SYSTEM_ERROR;
1659 iochan_settimeout(assoc->client_chan, 10);
1661 if ((assoc->init->bend_sort))
1662 yaz_log (YLOG_DEBUG, "Sort handler installed");
1663 if ((assoc->init->bend_search))
1664 yaz_log (YLOG_DEBUG, "Search handler installed");
1665 if ((assoc->init->bend_present))
1666 yaz_log (YLOG_DEBUG, "Present handler installed");
1667 if ((assoc->init->bend_esrequest))
1668 yaz_log (YLOG_DEBUG, "ESRequest handler installed");
1669 if ((assoc->init->bend_delete))
1670 yaz_log (YLOG_DEBUG, "Delete handler installed");
1671 if ((assoc->init->bend_scan))
1672 yaz_log (YLOG_DEBUG, "Scan handler installed");
1673 if ((assoc->init->bend_segment))
1674 yaz_log (YLOG_DEBUG, "Segment handler installed");
1676 resp->referenceId = req->referenceId;
1678 /* let's tell the client what we can do */
1679 if (ODR_MASK_GET(req->options, Z_Options_search))
1681 ODR_MASK_SET(resp->options, Z_Options_search);
1682 strcat(options, "srch");
1684 if (ODR_MASK_GET(req->options, Z_Options_present))
1686 ODR_MASK_SET(resp->options, Z_Options_present);
1687 strcat(options, " prst");
1689 if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
1690 assoc->init->bend_delete)
1692 ODR_MASK_SET(resp->options, Z_Options_delSet);
1693 strcat(options, " del");
1695 if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
1696 assoc->init->bend_esrequest)
1698 ODR_MASK_SET(resp->options, Z_Options_extendedServices);
1699 strcat (options, " extendedServices");
1701 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
1703 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
1704 strcat(options, " namedresults");
1706 if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
1708 ODR_MASK_SET(resp->options, Z_Options_scan);
1709 strcat(options, " scan");
1711 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
1713 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
1714 strcat(options, " concurrop");
1716 if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
1718 ODR_MASK_SET(resp->options, Z_Options_sort);
1719 strcat(options, " sort");
1722 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel)
1723 && assoc->init->charneg_response)
1725 Z_OtherInformation **p;
1726 Z_OtherInformationUnit *p0;
1728 yaz_oi_APDU(apdu, &p);
1730 if ((p0=yaz_oi_update(p, assoc->encode, NULL, 0, 0))) {
1731 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
1733 p0->which = Z_OtherInfo_externallyDefinedInfo;
1734 p0->information.externallyDefinedInfo =
1735 assoc->init->charneg_response;
1737 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
1738 strcat(options, " negotiation");
1741 ODR_MASK_SET(resp->options, Z_Options_triggerResourceCtrl);
1743 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
1745 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
1746 assoc->version = 1; /* 1 & 2 are equivalent */
1748 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
1750 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
1753 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
1755 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
1759 yaz_log(log_requestdetail, "Negotiated to v%d: %s", assoc->version, options);
1760 assoc->maximumRecordSize = *req->maximumRecordSize;
1762 if (cb && assoc->maximumRecordSize > cb->maxrecordsize)
1763 assoc->maximumRecordSize = cb->maxrecordsize;
1764 assoc->preferredMessageSize = *req->preferredMessageSize;
1765 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
1766 assoc->preferredMessageSize = assoc->maximumRecordSize;
1768 resp->preferredMessageSize = &assoc->preferredMessageSize;
1769 resp->maximumRecordSize = &assoc->maximumRecordSize;
1771 resp->implementationId = odr_prepend(assoc->encode,
1772 assoc->init->implementation_id,
1773 resp->implementationId);
1775 resp->implementationName = odr_prepend(assoc->encode,
1776 assoc->init->implementation_name,
1777 odr_prepend(assoc->encode, "GFS", resp->implementationName));
1779 version = odr_strdup(assoc->encode, "$Revision: 1.63 $");
1780 if (strlen(version) > 10) /* check for unexpanded CVS strings */
1781 version[strlen(version)-2] = '\0';
1782 resp->implementationVersion = odr_prepend(assoc->encode,
1783 assoc->init->implementation_version,
1784 odr_prepend(assoc->encode, &version[11],
1785 resp->implementationVersion));
1787 if (binitres->errcode)
1789 assoc->state = ASSOC_DEAD;
1790 resp->userInformationField =
1791 init_diagnostics(assoc->encode, binitres->errcode,
1792 binitres->errstring);
1797 if (!req->idAuthentication)
1798 yaz_log(log_request, "Auth none");
1799 else if (req->idAuthentication->which == Z_IdAuthentication_open)
1801 const char *open = req->idAuthentication->u.open;
1802 const char *slash = strchr(open, '/');
1808 yaz_log(log_request, "Auth open %.*s", len, open);
1810 else if (req->idAuthentication->which == Z_IdAuthentication_idPass)
1812 const char *user = req->idAuthentication->u.idPass->userId;
1813 const char *group = req->idAuthentication->u.idPass->groupId;
1814 yaz_log(log_request, "Auth idPass %s %s",
1815 user ? user : "-", group ? group : "-");
1817 else if (req->idAuthentication->which
1818 == Z_IdAuthentication_anonymous)
1820 yaz_log(log_request, "Auth anonymous");
1824 yaz_log(log_request, "Auth other");
1829 WRBUF wr = wrbuf_alloc();
1830 wrbuf_printf(wr, "Init ");
1831 if (binitres->errcode)
1832 wrbuf_printf(wr, "ERROR %d", binitres->errcode);
1834 wrbuf_printf(wr, "OK -");
1835 wrbuf_printf(wr, " ID:%s Name:%s Version:%s",
1836 (req->implementationId ? req->implementationId :"-"),
1837 (req->implementationName ?
1838 req->implementationName : "-"),
1839 (req->implementationVersion ?
1840 req->implementationVersion : "-")
1842 yaz_log(log_request, "%s", wrbuf_buf(wr));
1849 * Set the specified `errcode' and `errstring' into a UserInfo-1
1850 * external to be returned to the client in accordance with Z35.90
1851 * Implementor Agreement 5 (Returning diagnostics in an InitResponse):
1852 * http://lcweb.loc.gov/z3950/agency/agree/initdiag.html
1854 static Z_External *init_diagnostics(ODR odr, int error, const char *addinfo)
1856 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
1857 addinfo ? " -- " : "", addinfo ? addinfo : "");
1858 return zget_init_diagnostics(odr, error, addinfo);
1862 * nonsurrogate diagnostic record.
1864 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
1866 Z_Records *rec = (Z_Records *) odr_malloc (assoc->encode, sizeof(*rec));
1868 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
1869 addinfo ? " -- " : "", addinfo ? addinfo : "");
1871 rec->which = Z_Records_NSD;
1872 rec->u.nonSurrogateDiagnostic = zget_DefaultDiagFormat(assoc->encode,
1878 * surrogate diagnostic.
1880 static Z_NamePlusRecord *surrogatediagrec(association *assoc,
1882 int error, const char *addinfo)
1884 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
1885 addinfo ? " -- " : "", addinfo ? addinfo : "");
1886 return zget_surrogateDiagRec(assoc->encode, dbname, error, addinfo);
1889 static Z_Records *pack_records(association *a, char *setname, int start,
1890 int *num, Z_RecordComposition *comp,
1891 int *next, int *pres, oid_value format,
1892 Z_ReferenceId *referenceId,
1893 int *oid, int *errcode)
1895 int recno, total_length = 0, toget = *num, dumped_records = 0;
1896 Z_Records *records =
1897 (Z_Records *) odr_malloc (a->encode, sizeof(*records));
1898 Z_NamePlusRecordList *reclist =
1899 (Z_NamePlusRecordList *) odr_malloc (a->encode, sizeof(*reclist));
1900 Z_NamePlusRecord **list =
1901 (Z_NamePlusRecord **) odr_malloc (a->encode, sizeof(*list) * toget);
1903 records->which = Z_Records_DBOSD;
1904 records->u.databaseOrSurDiagnostics = reclist;
1905 reclist->num_records = 0;
1906 reclist->records = list;
1907 *pres = Z_PresentStatus_success;
1911 yaz_log(log_requestdetail, "Request to pack %d+%d %s", start, toget, setname);
1912 yaz_log(log_requestdetail, "pms=%d, mrs=%d", a->preferredMessageSize,
1913 a->maximumRecordSize);
1914 for (recno = start; reclist->num_records < toget; recno++)
1917 Z_NamePlusRecord *thisrec;
1918 int this_length = 0;
1920 * we get the number of bytes allocated on the stream before any
1921 * allocation done by the backend - this should give us a reasonable
1922 * idea of the total size of the data so far.
1924 total_length = odr_total(a->encode) - dumped_records;
1930 freq.last_in_set = 0;
1931 freq.setname = setname;
1932 freq.surrogate_flag = 0;
1933 freq.number = recno;
1935 freq.request_format = format;
1936 freq.request_format_raw = oid;
1937 freq.output_format = format;
1938 freq.output_format_raw = 0;
1939 freq.stream = a->encode;
1940 freq.print = a->print;
1941 freq.referenceId = referenceId;
1943 (*a->init->bend_fetch)(a->backend, &freq);
1945 *next = freq.last_in_set ? 0 : recno + 1;
1947 /* backend should be able to signal whether error is system-wide
1948 or only pertaining to current record */
1951 if (!freq.surrogate_flag)
1954 *pres = Z_PresentStatus_failure;
1955 /* for 'present request out of range',
1956 set addinfo to record position if not set */
1957 if (freq.errcode == YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE &&
1958 freq.errstring == 0)
1960 sprintf (s, "%d", recno);
1964 *errcode = freq.errcode;
1965 return diagrec(a, freq.errcode, freq.errstring);
1967 reclist->records[reclist->num_records] =
1968 surrogatediagrec(a, freq.basename, freq.errcode,
1970 reclist->num_records++;
1973 if (freq.record == 0) /* no error and no record ? */
1975 *next = 0; /* signal end-of-set and stop */
1979 this_length = freq.len;
1981 this_length = odr_total(a->encode) - total_length - dumped_records;
1982 yaz_log(YLOG_DEBUG, " fetched record, len=%d, total=%d dumped=%d",
1983 this_length, total_length, dumped_records);
1984 if (a->preferredMessageSize > 0 &&
1985 this_length + total_length > a->preferredMessageSize)
1987 /* record is small enough, really */
1988 if (this_length <= a->preferredMessageSize && recno > start)
1990 yaz_log(log_requestdetail, " Dropped last normal-sized record");
1991 *pres = Z_PresentStatus_partial_2;
1994 /* record can only be fetched by itself */
1995 if (this_length < a->maximumRecordSize)
1997 yaz_log(log_requestdetail, " Record > prefmsgsz");
2000 yaz_log(YLOG_DEBUG, " Dropped it");
2001 reclist->records[reclist->num_records] =
2002 surrogatediagrec(a, freq.basename, 16, 0);
2003 reclist->num_records++;
2004 dumped_records += this_length;
2008 else /* too big entirely */
2010 yaz_log(log_requestdetail, "Record > maxrcdsz this=%d max=%d",
2011 this_length, a->maximumRecordSize);
2012 reclist->records[reclist->num_records] =
2013 surrogatediagrec(a, freq.basename, 17, 0);
2014 reclist->num_records++;
2015 dumped_records += this_length;
2020 if (!(thisrec = (Z_NamePlusRecord *)
2021 odr_malloc(a->encode, sizeof(*thisrec))))
2024 thisrec->databaseName = odr_strdup(a->encode, freq.basename);
2026 thisrec->databaseName = 0;
2027 thisrec->which = Z_NamePlusRecord_databaseRecord;
2029 if (freq.output_format_raw)
2031 struct oident *ident = oid_getentbyoid(freq.output_format_raw);
2032 freq.output_format = ident->value;
2034 thisrec->u.databaseRecord = z_ext_record(a->encode, freq.output_format,
2035 freq.record, freq.len);
2036 if (!thisrec->u.databaseRecord)
2038 reclist->records[reclist->num_records] = thisrec;
2039 reclist->num_records++;
2041 *num = reclist->num_records;
2045 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
2048 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2049 bend_search_rr *bsrr =
2050 (bend_search_rr *)nmem_malloc (reqb->request_mem, sizeof(*bsrr));
2052 yaz_log(log_requestdetail, "Got SearchRequest.");
2054 bsrr->request = reqb;
2055 bsrr->association = assoc;
2056 bsrr->referenceId = req->referenceId;
2057 save_referenceId (reqb, bsrr->referenceId);
2058 bsrr->srw_sortKeys = 0;
2059 bsrr->srw_setname = 0;
2060 bsrr->srw_setnameIdleTime = 0;
2062 yaz_log (log_requestdetail, "ResultSet '%s'", req->resultSetName);
2063 if (req->databaseNames)
2066 for (i = 0; i < req->num_databaseNames; i++)
2067 yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
2070 yaz_log_zquery_level(log_requestdetail,req->query);
2072 if (assoc->init->bend_search)
2074 bsrr->setname = req->resultSetName;
2075 bsrr->replace_set = *req->replaceIndicator;
2076 bsrr->num_bases = req->num_databaseNames;
2077 bsrr->basenames = req->databaseNames;
2078 bsrr->query = req->query;
2079 bsrr->stream = assoc->encode;
2080 nmem_transfer(bsrr->stream->mem, reqb->request_mem);
2081 bsrr->decode = assoc->decode;
2082 bsrr->print = assoc->print;
2085 bsrr->errstring = NULL;
2086 bsrr->search_info = NULL;
2088 if (assoc->cql_transform &&
2089 req->query->which == Z_Query_type_104 &&
2090 req->query->u.type_104->which == Z_External_CQL)
2092 /* have a CQL query and a CQL to PQF transform .. */
2094 cql2pqf(bsrr->stream, req->query->u.type_104->u.cql,
2095 assoc->cql_transform, bsrr->query);
2097 bsrr->errcode = yaz_diag_srw_to_bib1(srw_errcode);
2100 (assoc->init->bend_search)(assoc->backend, bsrr);
2101 if (!bsrr->request) /* backend not ready with the search response */
2102 return 0; /* should not be used any more */
2106 /* FIXME - make a diagnostic for it */
2107 yaz_log(YLOG_WARN,"Search not supported ?!?!");
2109 return response_searchRequest(assoc, reqb, bsrr, fd);
2112 int bend_searchresponse(void *handle, bend_search_rr *bsrr) {return 0;}
2115 * Prepare a searchresponse based on the backend results. We probably want
2116 * to look at making the fetching of records nonblocking as well, but
2117 * so far, we'll keep things simple.
2118 * If bsrt is null, that means we're called in response to a communications
2119 * event, and we'll have to get the response for ourselves.
2121 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
2122 bend_search_rr *bsrt, int *fd)
2124 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2125 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2126 Z_SearchResponse *resp = (Z_SearchResponse *)
2127 odr_malloc (assoc->encode, sizeof(*resp));
2128 int *nulint = odr_intdup (assoc->encode, 0);
2129 bool_t *sr = odr_intdup(assoc->encode, 1);
2130 int *next = odr_intdup(assoc->encode, 0);
2131 int *none = odr_intdup(assoc->encode, Z_SearchResponse_none);
2134 apdu->which = Z_APDU_searchResponse;
2135 apdu->u.searchResponse = resp;
2136 resp->referenceId = req->referenceId;
2137 resp->additionalSearchInfo = 0;
2138 resp->otherInfo = 0;
2140 if (!bsrt && !bend_searchresponse(assoc->backend, bsrt))
2142 yaz_log(YLOG_FATAL, "Bad result from backend");
2145 else if (bsrt->errcode)
2147 resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
2148 resp->resultCount = nulint;
2149 resp->numberOfRecordsReturned = nulint;
2150 resp->nextResultSetPosition = nulint;
2151 resp->searchStatus = nulint;
2152 resp->resultSetStatus = none;
2153 resp->presentStatus = 0;
2157 int *toget = odr_intdup(assoc->encode, 0);
2158 int *presst = odr_intdup(assoc->encode, 0);
2159 Z_RecordComposition comp, *compp = 0;
2161 yaz_log (log_requestdetail, "resultCount: %d", bsrt->hits);
2164 resp->resultCount = &bsrt->hits;
2166 comp.which = Z_RecordComp_simple;
2167 /* how many records does the user agent want, then? */
2168 if (bsrt->hits <= *req->smallSetUpperBound)
2170 *toget = bsrt->hits;
2171 if ((comp.u.simple = req->smallSetElementSetNames))
2174 else if (bsrt->hits < *req->largeSetLowerBound)
2176 *toget = *req->mediumSetPresentNumber;
2177 if (*toget > bsrt->hits)
2178 *toget = bsrt->hits;
2179 if ((comp.u.simple = req->mediumSetElementSetNames))
2185 if (*toget && !resp->records)
2190 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
2193 form = prefformat->value;
2194 resp->records = pack_records(assoc, req->resultSetName, 1,
2195 toget, compp, next, presst, form, req->referenceId,
2196 req->preferredRecordSyntax, NULL);
2199 resp->numberOfRecordsReturned = toget;
2200 returnedrecs = *toget;
2201 resp->nextResultSetPosition = next;
2202 resp->searchStatus = sr;
2203 resp->resultSetStatus = 0;
2204 resp->presentStatus = presst;
2208 if (*resp->resultCount)
2210 resp->numberOfRecordsReturned = nulint;
2211 resp->nextResultSetPosition = next;
2212 resp->searchStatus = sr;
2213 resp->resultSetStatus = 0;
2214 resp->presentStatus = 0;
2217 resp->additionalSearchInfo = bsrt->search_info;
2221 WRBUF wr = wrbuf_alloc();
2223 wrbuf_printf(wr, "ERROR %d", bsrt->errcode);
2225 wrbuf_printf(wr, "OK %d", bsrt->hits);
2226 wrbuf_printf(wr, " %s 1+%d ",
2227 req->resultSetName, returnedrecs);
2228 wrbuf_put_zquery(wr, req->query);
2230 yaz_log(log_request, "Search %s", wrbuf_buf(wr));
2237 * Maybe we got a little over-friendly when we designed bend_fetch to
2238 * get only one record at a time. Some backends can optimise multiple-record
2239 * fetches, and at any rate, there is some overhead involved in
2240 * all that selecting and hopping around. Problem is, of course, that the
2241 * frontend can't know ahead of time how many records it'll need to
2242 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
2243 * is downright lousy as a bulk data transfer protocol.
2245 * To start with, we'll do the fetching of records from the backend
2246 * in one operation: To save some trips in and out of the event-handler,
2247 * and to simplify the interface to pack_records. At any rate, asynch
2248 * operation is more fun in operations that have an unpredictable execution
2249 * speed - which is normally more true for search than for present.
2251 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
2254 Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
2258 Z_PresentResponse *resp;
2262 const char *errstring = 0;
2264 yaz_log(log_requestdetail, "Got PresentRequest.");
2266 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
2269 form = prefformat->value;
2270 resp = (Z_PresentResponse *)odr_malloc (assoc->encode, sizeof(*resp));
2272 resp->presentStatus = odr_intdup(assoc->encode, 0);
2273 if (assoc->init->bend_present)
2275 bend_present_rr *bprr = (bend_present_rr *)
2276 nmem_malloc (reqb->request_mem, sizeof(*bprr));
2277 bprr->setname = req->resultSetId;
2278 bprr->start = *req->resultSetStartPoint;
2279 bprr->number = *req->numberOfRecordsRequested;
2280 bprr->format = form;
2281 bprr->comp = req->recordComposition;
2282 bprr->referenceId = req->referenceId;
2283 bprr->stream = assoc->encode;
2284 bprr->print = assoc->print;
2285 bprr->request = reqb;
2286 bprr->association = assoc;
2288 bprr->errstring = NULL;
2289 (*assoc->init->bend_present)(assoc->backend, bprr);
2292 return 0; /* should not happen */
2295 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2296 *resp->presentStatus = Z_PresentStatus_failure;
2297 errcode = bprr->errcode;
2298 errstring = bprr->errstring;
2301 apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2302 next = odr_intdup(assoc->encode, 0);
2303 num = odr_intdup(assoc->encode, 0);
2305 apdu->which = Z_APDU_presentResponse;
2306 apdu->u.presentResponse = resp;
2307 resp->referenceId = req->referenceId;
2308 resp->otherInfo = 0;
2312 *num = *req->numberOfRecordsRequested;
2314 pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
2315 num, req->recordComposition, next,
2316 resp->presentStatus,
2317 form, req->referenceId, req->preferredRecordSyntax,
2322 WRBUF wr = wrbuf_alloc();
2323 wrbuf_printf(wr, "Present ");
2325 if (*resp->presentStatus == Z_PresentStatus_failure)
2326 wrbuf_printf(wr, "ERROR %d", errcode);
2327 else if (*resp->presentStatus == Z_PresentStatus_success)
2328 wrbuf_printf(wr, "OK -");
2330 wrbuf_printf(wr, "Partial %d", *resp->presentStatus);
2332 wrbuf_printf(wr, " %s %d+%d ",
2333 req->resultSetId, *req->resultSetStartPoint,
2334 *req->numberOfRecordsRequested);
2335 yaz_log(log_request, "%s", wrbuf_buf(wr) );
2340 resp->numberOfRecordsReturned = num;
2341 resp->nextResultSetPosition = next;
2347 * Scan was implemented rather in a hurry, and with support for only the basic
2348 * elements of the service in the backend API. Suggestions are welcome.
2350 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
2352 Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
2353 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2354 Z_ScanResponse *res = (Z_ScanResponse *)
2355 odr_malloc (assoc->encode, sizeof(*res));
2356 int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
2357 int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
2358 Z_ListEntries *ents = (Z_ListEntries *)
2359 odr_malloc (assoc->encode, sizeof(*ents));
2360 Z_DiagRecs *diagrecs_p = NULL;
2362 bend_scan_rr *bsrr = (bend_scan_rr *)
2363 odr_malloc (assoc->encode, sizeof(*bsrr));
2364 struct scan_entry *save_entries;
2366 yaz_log(log_requestdetail, "Got ScanRequest");
2368 apdu->which = Z_APDU_scanResponse;
2369 apdu->u.scanResponse = res;
2370 res->referenceId = req->referenceId;
2372 /* if step is absent, set it to 0 */
2373 res->stepSize = odr_intdup(assoc->encode, 0);
2375 *res->stepSize = *req->stepSize;
2377 res->scanStatus = scanStatus;
2378 res->numberOfEntriesReturned = numberOfEntriesReturned;
2379 res->positionOfTerm = 0;
2380 res->entries = ents;
2381 ents->num_entries = 0;
2382 ents->entries = NULL;
2383 ents->num_nonsurrogateDiagnostics = 0;
2384 ents->nonsurrogateDiagnostics = NULL;
2385 res->attributeSet = 0;
2388 if (req->databaseNames)
2391 for (i = 0; i < req->num_databaseNames; i++)
2392 yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
2394 bsrr->scanClause = 0;
2396 bsrr->errstring = 0;
2397 bsrr->num_bases = req->num_databaseNames;
2398 bsrr->basenames = req->databaseNames;
2399 bsrr->num_entries = *req->numberOfTermsRequested;
2400 bsrr->term = req->termListAndStartPoint;
2401 bsrr->referenceId = req->referenceId;
2402 bsrr->stream = assoc->encode;
2403 bsrr->print = assoc->print;
2404 bsrr->step_size = res->stepSize;
2406 /* For YAZ 2.0 and earlier it was the backend handler that
2407 initialized entries (member display_term did not exist)
2408 YAZ 2.0 and later sets 'entries' and initialize all members
2409 including 'display_term'. If YAZ 2.0 or later sees that
2410 entries was modified - we assume that it is an old handler and
2411 that 'display_term' is _not_ set.
2413 if (bsrr->num_entries > 0)
2416 bsrr->entries = odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
2418 for (i = 0; i<bsrr->num_entries; i++)
2420 bsrr->entries[i].term = 0;
2421 bsrr->entries[i].occurrences = 0;
2422 bsrr->entries[i].errcode = 0;
2423 bsrr->entries[i].errstring = 0;
2424 bsrr->entries[i].display_term = 0;
2427 save_entries = bsrr->entries; /* save it so we can compare later */
2429 if (req->attributeSet &&
2430 (attset = oid_getentbyoid(req->attributeSet)) &&
2431 (attset->oclass == CLASS_ATTSET || attset->oclass == CLASS_GENERAL))
2432 bsrr->attributeset = attset->value;
2434 bsrr->attributeset = VAL_NONE;
2435 log_scan_term_level (log_requestdetail, req->termListAndStartPoint,
2436 bsrr->attributeset);
2437 bsrr->term_position = req->preferredPositionInResponse ?
2438 *req->preferredPositionInResponse : 1;
2440 ((int (*)(void *, bend_scan_rr *))
2441 (*assoc->init->bend_scan))(assoc->backend, bsrr);
2444 diagrecs_p = zget_DiagRecs(assoc->encode,
2445 bsrr->errcode, bsrr->errstring);
2449 Z_Entry **tab = (Z_Entry **)
2450 odr_malloc (assoc->encode, sizeof(*tab) * bsrr->num_entries);
2452 if (bsrr->status == BEND_SCAN_PARTIAL)
2453 *scanStatus = Z_Scan_partial_5;
2455 *scanStatus = Z_Scan_success;
2456 ents->entries = tab;
2457 ents->num_entries = bsrr->num_entries;
2458 res->numberOfEntriesReturned = &ents->num_entries;
2459 res->positionOfTerm = &bsrr->term_position;
2460 for (i = 0; i < bsrr->num_entries; i++)
2466 tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
2467 if (bsrr->entries[i].occurrences >= 0)
2469 e->which = Z_Entry_termInfo;
2470 e->u.termInfo = t = (Z_TermInfo *)
2471 odr_malloc(assoc->encode, sizeof(*t));
2472 t->suggestedAttributes = 0;
2474 if (save_entries == bsrr->entries &&
2475 bsrr->entries[i].display_term)
2477 /* the entries was _not_ set by the handler. So it's
2478 safe to test for new member display_term. It is
2481 t->displayTerm = odr_strdup(assoc->encode,
2482 bsrr->entries[i].display_term);
2484 t->alternativeTerm = 0;
2485 t->byAttributes = 0;
2486 t->otherTermInfo = 0;
2487 t->globalOccurrences = &bsrr->entries[i].occurrences;
2488 t->term = (Z_Term *)
2489 odr_malloc(assoc->encode, sizeof(*t->term));
2490 t->term->which = Z_Term_general;
2491 t->term->u.general = o =
2492 (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
2493 o->buf = (unsigned char *)
2494 odr_malloc(assoc->encode, o->len = o->size =
2495 strlen(bsrr->entries[i].term));
2496 memcpy(o->buf, bsrr->entries[i].term, o->len);
2497 yaz_log(YLOG_DEBUG, " term #%d: '%s' (%d)", i,
2498 bsrr->entries[i].term, bsrr->entries[i].occurrences);
2502 Z_DiagRecs *drecs = zget_DiagRecs(assoc->encode,
2503 bsrr->entries[i].errcode,
2504 bsrr->entries[i].errstring);
2505 assert (drecs->num_diagRecs == 1);
2506 e->which = Z_Entry_surrogateDiagnostic;
2507 assert (drecs->diagRecs[0]);
2508 e->u.surrogateDiagnostic = drecs->diagRecs[0];
2514 ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
2515 ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
2519 WRBUF wr = wrbuf_alloc();
2521 wr_diag(wr, bsrr->errcode, bsrr->errstring);
2522 else if (*res->scanStatus == Z_Scan_success)
2523 wrbuf_printf(wr, "OK");
2525 wrbuf_printf(wr, "Partial");
2527 wrbuf_printf(wr, " %d+%d %d ",
2528 (req->preferredPositionInResponse ?
2529 *req->preferredPositionInResponse : 1),
2530 *req->numberOfTermsRequested,
2531 (res->stepSize ? *res->stepSize : 0));
2532 wrbuf_scan_term(wr, req->termListAndStartPoint,
2533 bsrr->attributeset);
2535 yaz_log(log_request, "Scan %s", wrbuf_buf(wr) );
2541 static Z_APDU *process_sortRequest(association *assoc, request *reqb,
2545 Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
2546 Z_SortResponse *res = (Z_SortResponse *)
2547 odr_malloc (assoc->encode, sizeof(*res));
2548 bend_sort_rr *bsrr = (bend_sort_rr *)
2549 odr_malloc (assoc->encode, sizeof(*bsrr));
2551 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2553 yaz_log(log_requestdetail, "Got SortRequest.");
2555 bsrr->num_input_setnames = req->num_inputResultSetNames;
2556 for (i=0;i<req->num_inputResultSetNames;i++)
2557 yaz_log(log_requestdetail, "Input resultset: '%s'",
2558 req->inputResultSetNames[i]);
2559 bsrr->input_setnames = req->inputResultSetNames;
2560 bsrr->referenceId = req->referenceId;
2561 bsrr->output_setname = req->sortedResultSetName;
2562 yaz_log(log_requestdetail, "Output resultset: '%s'",
2563 req->sortedResultSetName);
2564 bsrr->sort_sequence = req->sortSequence;
2565 /*FIXME - dump those sequences too */
2566 bsrr->stream = assoc->encode;
2567 bsrr->print = assoc->print;
2569 bsrr->sort_status = Z_SortResponse_failure;
2571 bsrr->errstring = 0;
2573 (*assoc->init->bend_sort)(assoc->backend, bsrr);
2575 res->referenceId = bsrr->referenceId;
2576 res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
2577 res->resultSetStatus = 0;
2580 Z_DiagRecs *dr = zget_DiagRecs(assoc->encode,
2581 bsrr->errcode, bsrr->errstring);
2582 res->diagnostics = dr->diagRecs;
2583 res->num_diagnostics = dr->num_diagRecs;
2587 res->num_diagnostics = 0;
2588 res->diagnostics = 0;
2590 res->resultCount = 0;
2593 apdu->which = Z_APDU_sortResponse;
2594 apdu->u.sortResponse = res;
2597 WRBUF wr = wrbuf_alloc();
2598 wrbuf_printf(wr, "Sort ");
2600 wrbuf_printf(wr, " ERROR %d", bsrr->errcode);
2602 wrbuf_printf(wr, "OK -");
2603 wrbuf_printf(wr, " (");
2604 for (i = 0; i<req->num_inputResultSetNames; i++)
2607 wrbuf_printf(wr, ",");
2608 wrbuf_printf(wr, req->inputResultSetNames[i]);
2610 wrbuf_printf(wr, ")->%s ",req->sortedResultSetName);
2612 yaz_log(log_request, "%s", wrbuf_buf(wr) );
2618 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
2622 Z_DeleteResultSetRequest *req =
2623 reqb->apdu_request->u.deleteResultSetRequest;
2624 Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
2625 odr_malloc (assoc->encode, sizeof(*res));
2626 bend_delete_rr *bdrr = (bend_delete_rr *)
2627 odr_malloc (assoc->encode, sizeof(*bdrr));
2628 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2630 yaz_log(log_requestdetail, "Got DeleteRequest.");
2632 bdrr->num_setnames = req->num_resultSetList;
2633 bdrr->setnames = req->resultSetList;
2634 for (i = 0; i<req->num_resultSetList; i++)
2635 yaz_log(log_requestdetail, "resultset: '%s'",
2636 req->resultSetList[i]);
2637 bdrr->stream = assoc->encode;
2638 bdrr->print = assoc->print;
2639 bdrr->function = *req->deleteFunction;
2640 bdrr->referenceId = req->referenceId;
2642 if (bdrr->num_setnames > 0)
2644 bdrr->statuses = (int*)
2645 odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
2646 bdrr->num_setnames);
2647 for (i = 0; i < bdrr->num_setnames; i++)
2648 bdrr->statuses[i] = 0;
2650 (*assoc->init->bend_delete)(assoc->backend, bdrr);
2652 res->referenceId = req->referenceId;
2654 res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
2656 res->deleteListStatuses = 0;
2657 if (bdrr->num_setnames > 0)
2660 res->deleteListStatuses = (Z_ListStatuses *)
2661 odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
2662 res->deleteListStatuses->num = bdrr->num_setnames;
2663 res->deleteListStatuses->elements =
2665 odr_malloc (assoc->encode,
2666 sizeof(*res->deleteListStatuses->elements) *
2667 bdrr->num_setnames);
2668 for (i = 0; i<bdrr->num_setnames; i++)
2670 res->deleteListStatuses->elements[i] =
2672 odr_malloc (assoc->encode,
2673 sizeof(**res->deleteListStatuses->elements));
2674 res->deleteListStatuses->elements[i]->status = bdrr->statuses+i;
2675 res->deleteListStatuses->elements[i]->id =
2676 odr_strdup (assoc->encode, bdrr->setnames[i]);
2679 res->numberNotDeleted = 0;
2680 res->bulkStatuses = 0;
2681 res->deleteMessage = 0;
2684 apdu->which = Z_APDU_deleteResultSetResponse;
2685 apdu->u.deleteResultSetResponse = res;
2688 WRBUF wr = wrbuf_alloc();
2689 wrbuf_printf(wr, "Delete ");
2690 if (bdrr->delete_status)
2691 wrbuf_printf(wr, "ERROR %d", bdrr->delete_status);
2693 wrbuf_printf(wr, "OK -");
2694 for (i = 0; i<req->num_resultSetList; i++)
2695 wrbuf_printf(wr, " %s ", req->resultSetList[i]);
2696 yaz_log(log_request, "%s", wrbuf_buf(wr) );
2702 static void process_close(association *assoc, request *reqb)
2704 Z_Close *req = reqb->apdu_request->u.close;
2705 static char *reasons[] =
2712 "securityViolation",
2719 yaz_log(log_requestdetail, "Got Close, reason %s, message %s",
2720 reasons[*req->closeReason], req->diagnosticInformation ?
2721 req->diagnosticInformation : "NULL");
2722 if (assoc->version < 3) /* to make do_force respond with close */
2724 do_close_req(assoc, Z_Close_finished,
2725 "Association terminated by client", reqb);
2726 yaz_log(log_request,"Close OK");
2729 void save_referenceId (request *reqb, Z_ReferenceId *refid)
2733 reqb->len_refid = refid->len;
2734 reqb->refid = (char *)nmem_malloc (reqb->request_mem, refid->len);
2735 memcpy (reqb->refid, refid->buf, refid->len);
2739 reqb->len_refid = 0;
2744 void bend_request_send (bend_association a, bend_request req, Z_APDU *res)
2746 process_z_response (a, req, res);
2749 bend_request bend_request_mk (bend_association a)
2751 request *nreq = request_get (&a->outgoing);
2752 nreq->request_mem = nmem_create ();
2756 Z_ReferenceId *bend_request_getid (ODR odr, bend_request req)
2761 id = (Odr_oct *)odr_malloc (odr, sizeof(*odr));
2762 id->buf = (unsigned char *)odr_malloc (odr, req->len_refid);
2763 id->len = id->size = req->len_refid;
2764 memcpy (id->buf, req->refid, req->len_refid);
2768 void bend_request_destroy (bend_request *req)
2770 nmem_destroy((*req)->request_mem);
2771 request_release(*req);
2775 int bend_backend_respond (bend_association a, bend_request req)
2779 r = process_z_request (a, req, &msg);
2781 yaz_log (YLOG_WARN, "%s", msg);
2785 void bend_request_setdata(bend_request r, void *p)
2790 void *bend_request_getdata(bend_request r)
2792 return r->clientData;
2795 static Z_APDU *process_segmentRequest (association *assoc, request *reqb)
2797 bend_segment_rr req;
2799 req.segment = reqb->apdu_request->u.segmentRequest;
2800 req.stream = assoc->encode;
2801 req.decode = assoc->decode;
2802 req.print = assoc->print;
2803 req.association = assoc;
2805 (*assoc->init->bend_segment)(assoc->backend, &req);
2810 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd)
2812 bend_esrequest_rr esrequest;
2814 Z_ExtendedServicesRequest *req =
2815 reqb->apdu_request->u.extendedServicesRequest;
2816 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
2818 Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
2820 yaz_log(log_requestdetail,"Got EsRequest");
2822 esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
2823 esrequest.stream = assoc->encode;
2824 esrequest.decode = assoc->decode;
2825 esrequest.print = assoc->print;
2826 esrequest.errcode = 0;
2827 esrequest.errstring = NULL;
2828 esrequest.request = reqb;
2829 esrequest.association = assoc;
2830 esrequest.taskPackage = 0;
2831 esrequest.referenceId = req->referenceId;
2833 (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
2835 /* If the response is being delayed, return NULL */
2836 if (esrequest.request == NULL)
2839 resp->referenceId = req->referenceId;
2841 if (esrequest.errcode == -1)
2843 /* Backend service indicates request will be processed */
2844 yaz_log(log_request,"EsRequest OK: Accepted !");
2845 *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
2847 else if (esrequest.errcode == 0)
2849 /* Backend service indicates request will be processed */
2850 yaz_log(log_request,"EsRequest OK: Done !");
2851 *resp->operationStatus = Z_ExtendedServicesResponse_done;
2855 Z_DiagRecs *diagRecs =
2856 zget_DiagRecs(assoc->encode, esrequest.errcode,
2857 esrequest.errstring);
2858 /* Backend indicates error, request will not be processed */
2859 yaz_log(YLOG_DEBUG,"Request could not be processed...failure !");
2860 *resp->operationStatus = Z_ExtendedServicesResponse_failure;
2861 resp->num_diagnostics = diagRecs->num_diagRecs;
2862 resp->diagnostics = diagRecs->diagRecs;
2865 WRBUF wr = wrbuf_alloc();
2866 wrbuf_diags(wr, resp->num_diagnostics, resp->diagnostics);
2867 yaz_log(log_request, "EsRequest %s", wrbuf_buf(wr) );
2872 /* Do something with the members of bend_extendedservice */
2873 if (esrequest.taskPackage)
2874 resp->taskPackage = z_ext_record (assoc->encode, VAL_EXTENDED,
2875 (const char *) esrequest.taskPackage,
2877 yaz_log(YLOG_DEBUG,"Send the result apdu");
2884 * indent-tabs-mode: nil
2886 * vim: shiftwidth=4 tabstop=8 expandtab