2 * Copyright (C) 1995-2005, Index Data ApS
3 * See the file LICENSE for details.
5 * $Id: seshigh.c,v 1.50 2005-03-05 09:17:27 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 */
247 a->state = ASSOC_DEAD;
250 static void do_close(association *a, int reason, char *message)
252 request *req = request_get(&a->outgoing);
253 do_close_req (a, reason, message, req);
257 * This is where PDUs from the client are read and the further
258 * processing is initiated. Flow of control moves down through the
259 * various process_* functions below, until the encoded result comes back up
260 * to the output handler in here.
262 * h : the I/O channel that has an outstanding event.
263 * event : the current outstanding event.
265 void ir_session(IOCHAN h, int event)
268 association *assoc = (association *)iochan_getdata(h);
269 COMSTACK conn = assoc->client_link;
272 assert(h && conn && assoc);
273 if (event == EVENT_TIMEOUT)
275 if (assoc->state != ASSOC_UP)
277 yaz_log(YLOG_DEBUG, "Final timeout - closing connection.");
278 /* do we need to lod this at all */
280 destroy_association(assoc);
285 yaz_log(log_session, "Session idle too long. Sending close.");
286 do_close(assoc, Z_Close_lackOfActivity, 0);
290 if (event & assoc->cs_accept_mask)
292 if (!cs_accept (conn))
294 yaz_log (YLOG_WARN, "accept failed");
295 destroy_association(assoc);
298 iochan_clearflag (h, EVENT_OUTPUT);
299 if (conn->io_pending)
300 { /* cs_accept didn't complete */
301 assoc->cs_accept_mask =
302 ((conn->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
303 ((conn->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
305 iochan_setflag (h, assoc->cs_accept_mask);
308 { /* cs_accept completed. Prepare for reading (cs_get) */
309 assoc->cs_accept_mask = 0;
310 assoc->cs_get_mask = EVENT_INPUT;
311 iochan_setflag (h, assoc->cs_get_mask);
315 if ((event & assoc->cs_get_mask) || (event & EVENT_WORK)) /* input */
317 if ((assoc->cs_put_mask & EVENT_INPUT) == 0 && (event & assoc->cs_get_mask))
319 yaz_log(YLOG_DEBUG, "ir_session (input)");
320 /* We aren't speaking to this fellow */
321 if (assoc->state == ASSOC_DEAD)
323 yaz_log(log_session, "Connection closed - end of session");
325 destroy_association(assoc);
329 assoc->cs_get_mask = EVENT_INPUT;
330 if ((res = cs_get(conn, &assoc->input_buffer,
331 &assoc->input_buffer_len)) <= 0)
333 yaz_log(log_session, "Connection closed by client");
335 destroy_association(assoc);
339 else if (res == 1) /* incomplete read - wait for more */
341 if (conn->io_pending & CS_WANT_WRITE)
342 assoc->cs_get_mask |= EVENT_OUTPUT;
343 iochan_setflag(h, assoc->cs_get_mask);
346 if (cs_more(conn)) /* more stuff - call us again later, please */
347 iochan_setevent(h, EVENT_INPUT);
349 /* we got a complete PDU. Let's decode it */
350 yaz_log(YLOG_DEBUG, "Got PDU, %d bytes: lead=%02X %02X %02X", res,
351 assoc->input_buffer[0] & 0xff,
352 assoc->input_buffer[1] & 0xff,
353 assoc->input_buffer[2] & 0xff);
354 req = request_get(&assoc->incoming); /* get a new request */
355 odr_reset(assoc->decode);
356 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
357 if (!z_GDU(assoc->decode, &req->gdu_request, 0, 0))
359 yaz_log(YLOG_WARN, "ODR error on incoming PDU: %s [element %s] "
361 odr_errmsg(odr_geterror(assoc->decode)),
362 odr_getelement(assoc->decode),
363 odr_offset(assoc->decode));
364 if (assoc->decode->error != OHTTP)
366 yaz_log(YLOG_WARN, "PDU dump:");
367 odr_dumpBER(yaz_log_file(), assoc->input_buffer, res);
368 request_release(req);
369 do_close(assoc, Z_Close_protocolError,"Malformed package");
373 Z_GDU *p = z_get_HTTP_Response(assoc->encode, 400);
374 assoc->state = ASSOC_DEAD;
375 process_gdu_response(assoc, req, p);
379 req->request_mem = odr_extract_mem(assoc->decode);
382 if (!z_GDU(assoc->print, &req->gdu_request, 0, 0))
383 yaz_log(YLOG_WARN, "ODR print error: %s",
384 odr_errmsg(odr_geterror(assoc->print)));
385 odr_reset(assoc->print);
387 request_enq(&assoc->incoming, req);
390 /* can we do something yet? */
391 req = request_head(&assoc->incoming);
392 if (req->state == REQUEST_IDLE)
394 request_deq(&assoc->incoming);
395 process_gdu_request(assoc, req);
398 if (event & assoc->cs_put_mask)
400 request *req = request_head(&assoc->outgoing);
402 assoc->cs_put_mask = 0;
403 yaz_log(YLOG_DEBUG, "ir_session (output)");
404 req->state = REQUEST_PENDING;
405 switch (res = cs_put(conn, req->response, req->len_response))
408 yaz_log(log_session, "Connection closed by client");
410 destroy_association(assoc);
413 case 0: /* all sent - release the request structure */
414 yaz_log(YLOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
416 yaz_log(YLOG_DEBUG, "HTTP out:\n%.*s", req->len_response,
419 nmem_destroy(req->request_mem);
420 request_deq(&assoc->outgoing);
421 request_release(req);
422 if (!request_head(&assoc->outgoing))
423 { /* restore mask for cs_get operation ... */
424 iochan_clearflag(h, EVENT_OUTPUT|EVENT_INPUT);
425 iochan_setflag(h, assoc->cs_get_mask);
426 if (assoc->state == ASSOC_DEAD)
427 iochan_setevent(assoc->client_chan, EVENT_TIMEOUT);
431 assoc->cs_put_mask = EVENT_OUTPUT;
435 if (conn->io_pending & CS_WANT_WRITE)
436 assoc->cs_put_mask |= EVENT_OUTPUT;
437 if (conn->io_pending & CS_WANT_READ)
438 assoc->cs_put_mask |= EVENT_INPUT;
439 iochan_setflag(h, assoc->cs_put_mask);
442 if (event & EVENT_EXCEPT)
444 yaz_log(YLOG_WARN, "ir_session (exception)");
446 destroy_association(assoc);
451 static int process_z_request(association *assoc, request *req, char **msg);
454 static void assoc_init_reset(association *assoc)
457 assoc->init = (bend_initrequest *) xmalloc (sizeof(*assoc->init));
459 assoc->init->stream = assoc->encode;
460 assoc->init->print = assoc->print;
461 assoc->init->auth = 0;
462 assoc->init->referenceId = 0;
463 assoc->init->implementation_version = 0;
464 assoc->init->implementation_id = 0;
465 assoc->init->implementation_name = 0;
466 assoc->init->bend_sort = NULL;
467 assoc->init->bend_search = NULL;
468 assoc->init->bend_present = NULL;
469 assoc->init->bend_esrequest = NULL;
470 assoc->init->bend_delete = NULL;
471 assoc->init->bend_scan = NULL;
472 assoc->init->bend_segment = NULL;
473 assoc->init->bend_fetch = NULL;
474 assoc->init->bend_explain = NULL;
475 assoc->init->bend_srw_scan = NULL;
477 assoc->init->charneg_request = NULL;
478 assoc->init->charneg_response = NULL;
480 assoc->init->decode = assoc->decode;
481 assoc->init->peer_name =
482 odr_strdup (assoc->encode, cs_addrstr(assoc->client_link));
484 yaz_log(log_requestdetail, "peer %s", assoc->init->peer_name);
487 static int srw_bend_init(association *assoc, Z_SRW_diagnostic **d, int *num)
489 statserv_options_block *cb = statserv_getcontrol();
492 const char *encoding = "UTF-8";
494 bend_initresult *binitres;
496 yaz_log(YLOG_LOG, "srw_bend_init config=%s", cb->configname);
497 assoc_init_reset(assoc);
499 assoc->maximumRecordSize = 3000000;
500 assoc->preferredMessageSize = 3000000;
502 ce = yaz_set_proposal_charneg(assoc->decode, &encoding, 1, 0, 0, 1);
503 assoc->init->charneg_request = ce->u.charNeg3;
506 if (!(binitres = (*cb->bend_init)(assoc->init)))
508 assoc->state = ASSOC_DEAD;
509 yaz_add_srw_diagnostic(assoc->encode, d, num, 3, 0);
512 assoc->backend = binitres->handle;
513 if (binitres->errcode)
515 assoc->state = ASSOC_DEAD;
516 yaz_add_srw_diagnostic(assoc->encode, d, num, binitres->errcode,
517 binitres->errstring);
525 static int srw_bend_fetch(association *assoc, int pos,
526 Z_SRW_searchRetrieveRequest *srw_req,
527 Z_SRW_record *record)
530 ODR o = assoc->encode;
532 rr.setname = "default";
535 rr.request_format = VAL_TEXT_XML;
536 rr.request_format_raw = yaz_oidval_to_z3950oid(assoc->decode,
539 rr.comp = (Z_RecordComposition *)
540 odr_malloc(assoc->decode, sizeof(*rr.comp));
541 rr.comp->which = Z_RecordComp_complex;
542 rr.comp->u.complex = (Z_CompSpec *)
543 odr_malloc(assoc->decode, sizeof(Z_CompSpec));
544 rr.comp->u.complex->selectAlternativeSyntax = (bool_t *)
545 odr_malloc(assoc->encode, sizeof(bool_t));
546 *rr.comp->u.complex->selectAlternativeSyntax = 0;
547 rr.comp->u.complex->num_dbSpecific = 0;
548 rr.comp->u.complex->dbSpecific = 0;
549 rr.comp->u.complex->num_recordSyntax = 0;
550 rr.comp->u.complex->recordSyntax = 0;
552 rr.comp->u.complex->generic = (Z_Specification *)
553 odr_malloc(assoc->decode, sizeof(Z_Specification));
555 /* schema uri = recordSchema (or NULL if recordSchema is not given) */
556 rr.comp->u.complex->generic->which = Z_Schema_uri;
557 rr.comp->u.complex->generic->schema.uri = srw_req->recordSchema;
559 /* ESN = recordSchema if recordSchema is present */
560 rr.comp->u.complex->generic->elementSpec = 0;
561 if (srw_req->recordSchema)
563 rr.comp->u.complex->generic->elementSpec =
564 (Z_ElementSpec *) odr_malloc(assoc->encode, sizeof(Z_ElementSpec));
565 rr.comp->u.complex->generic->elementSpec->which =
566 Z_ElementSpec_elementSetName;
567 rr.comp->u.complex->generic->elementSpec->u.elementSetName =
568 srw_req->recordSchema;
571 rr.stream = assoc->encode;
572 rr.print = assoc->print;
578 rr.output_format = VAL_TEXT_XML;
579 rr.output_format_raw = 0;
582 rr.surrogate_flag = 0;
583 rr.schema = srw_req->recordSchema;
585 if (!assoc->init->bend_fetch)
588 (*assoc->init->bend_fetch)(assoc->backend, &rr);
590 if (rr.errcode && rr.surrogate_flag)
592 int code = yaz_diag_bib1_to_srw(rr.errcode);
593 const char *message = yaz_diag_srw_str(code);
596 len += strlen(message);
598 len += strlen(rr.errstring);
600 record->recordData_buf = odr_malloc(o, len);
602 sprintf(record->recordData_buf, "<diagnostic "
603 "xmlns=\"http://www.loc.gov/zing/srw/diagnostic/\">\n"
604 " <uri>info:srw/diagnostic/1/%d</uri>\n", code);
606 sprintf(record->recordData_buf + strlen(record->recordData_buf),
607 " <details>%s</details>\n", rr.errstring);
609 sprintf(record->recordData_buf + strlen(record->recordData_buf),
610 " <message>%s</message>\n", message);
611 sprintf(record->recordData_buf + strlen(record->recordData_buf),
613 record->recordData_len = strlen(record->recordData_buf);
614 record->recordPosition = odr_intdup(o, pos);
615 record->recordSchema = "info:srw/schema/1/diagnostics-v1.1";
618 else if (rr.len >= 0)
620 record->recordData_buf = rr.record;
621 record->recordData_len = rr.len;
622 record->recordPosition = odr_intdup(o, pos);
624 record->recordSchema = odr_strdup(o, rr.schema);
626 record->recordSchema = 0;
631 static int cql2pqf(ODR odr, const char *cql, cql_transform_t ct,
632 Z_Query *query_result)
634 /* have a CQL query and CQL to PQF transform .. */
635 CQL_parser cp = cql_parser_create();
641 r = cql_parser_string(cp, cql);
644 /* CQL syntax error */
650 r = cql_transform_buf(ct,
651 cql_parser_result(cp),
652 rpn_buf, sizeof(rpn_buf)-1);
654 srw_errcode = cql_transform_error(ct, &add);
658 /* Syntax & transform OK. */
659 /* Convert PQF string to Z39.50 to RPN query struct */
660 YAZ_PQF_Parser pp = yaz_pqf_create();
661 Z_RPNQuery *rpnquery = yaz_pqf_parse(pp, odr, rpn_buf);
666 int code = yaz_pqf_error(pp, &pqf_msg, &off);
667 yaz_log(YLOG_WARN, "PQF Parser Error %s (code %d)",
673 query_result->which = Z_Query_type_1;
674 query_result->u.type_1 = rpnquery;
678 cql_parser_destroy(cp);
682 static int cql2pqf_scan(ODR odr, const char *cql, cql_transform_t ct,
683 Z_AttributesPlusTerm *result)
687 int srw_error = cql2pqf(odr, cql, ct, &query);
690 if (query.which != Z_Query_type_1 && query.which != Z_Query_type_101)
691 return 10; /* bad query type */
692 rpn = query.u.type_1;
693 if (!rpn->RPNStructure)
694 return 10; /* must be structure */
695 if (rpn->RPNStructure->which != Z_RPNStructure_simple)
696 return 10; /* must be simple */
697 if (rpn->RPNStructure->u.simple->which != Z_Operand_APT)
698 return 10; /* must be attributes plus term node .. */
699 memcpy(result, rpn->RPNStructure->u.simple->u.attributesPlusTerm,
704 static void srw_bend_search(association *assoc, request *req,
705 Z_SRW_searchRetrieveRequest *srw_req,
706 Z_SRW_searchRetrieveResponse *srw_res,
713 yaz_log(log_requestdetail, "Got SRW SearchRetrieveRequest");
714 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics);
715 if (srw_req->sort_type != Z_SRW_sort_type_none)
716 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
717 &srw_res->num_diagnostics, 80, 0);
718 else if (srw_res->num_diagnostics == 0 && assoc->init)
721 rr.setname = "default";
724 rr.basenames = &srw_req->database;
727 rr.query = (Z_Query *) odr_malloc (assoc->decode, sizeof(*rr.query));
728 rr.query->u.type_1 = 0;
730 if (srw_req->query_type == Z_SRW_query_type_cql)
732 if (assoc->cql_transform)
734 int srw_errcode = cql2pqf(assoc->encode, srw_req->query.cql,
735 assoc->cql_transform, rr.query);
738 yaz_add_srw_diagnostic(assoc->encode,
739 &srw_res->diagnostics,
740 &srw_res->num_diagnostics,
746 /* CQL query to backend. Wrap it - Z39.50 style */
747 ext = (Z_External *) odr_malloc(assoc->decode, sizeof(*ext));
748 ext->direct_reference = odr_getoidbystr(assoc->decode,
749 "1.2.840.10003.16.2");
750 ext->indirect_reference = 0;
752 ext->which = Z_External_CQL;
753 ext->u.cql = srw_req->query.cql;
755 rr.query->which = Z_Query_type_104;
756 rr.query->u.type_104 = ext;
759 else if (srw_req->query_type == Z_SRW_query_type_pqf)
761 Z_RPNQuery *RPNquery;
762 YAZ_PQF_Parser pqf_parser;
764 pqf_parser = yaz_pqf_create ();
766 RPNquery = yaz_pqf_parse (pqf_parser, assoc->decode,
772 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
773 yaz_log(log_requestdetail, "Parse error %d %s near offset %d",
778 rr.query->which = Z_Query_type_1;
779 rr.query->u.type_1 = RPNquery;
781 yaz_pqf_destroy (pqf_parser);
785 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
786 &srw_res->num_diagnostics, 11, 0);
788 if (rr.query->u.type_1)
790 rr.stream = assoc->encode;
791 rr.decode = assoc->decode;
792 rr.print = assoc->print;
794 rr.association = assoc;
800 yaz_log_zquery_level(log_requestdetail,rr.query);
802 (assoc->init->bend_search)(assoc->backend, &rr);
805 if (rr.errcode == 109) /* database unavailable */
811 srw_error = yaz_diag_bib1_to_srw (rr.errcode);
812 yaz_add_srw_diagnostic(assoc->encode,
813 &srw_res->diagnostics,
814 &srw_res->num_diagnostics,
815 srw_error, rr.errstring);
820 int number = srw_req->maximumRecords ? *srw_req->maximumRecords : 0;
821 int start = srw_req->startRecord ? *srw_req->startRecord : 1;
823 yaz_log(log_requestdetail, "Request to pack %d+%d out of %d",
824 start, number, rr.hits);
826 srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
833 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
834 &srw_res->num_diagnostics,
840 int packing = Z_SRW_recordPacking_string;
841 if (start + number > rr.hits)
842 number = rr.hits - start + 1;
843 if (srw_req->recordPacking &&
844 !strcmp(srw_req->recordPacking, "xml"))
845 packing = Z_SRW_recordPacking_XML;
846 srw_res->records = (Z_SRW_record *)
847 odr_malloc(assoc->encode,
848 number * sizeof(*srw_res->records));
849 for (i = 0; i<number; i++)
853 srw_res->records[j].recordPacking = packing;
854 srw_res->records[j].recordData_buf = 0;
855 yaz_log(YLOG_DEBUG, "srw_bend_fetch %d", i+start);
856 errcode = srw_bend_fetch(assoc, i+start, srw_req,
857 srw_res->records + j);
860 yaz_add_srw_diagnostic(assoc->encode,
861 &srw_res->diagnostics,
862 &srw_res->num_diagnostics,
863 yaz_diag_bib1_to_srw (errcode),
868 if (srw_res->records[j].recordData_buf)
871 srw_res->num_records = j;
873 srw_res->records = 0;
881 const char *querystr = "?";
882 const char *querytype = "?";
883 WRBUF wr = wrbuf_alloc();
885 switch (srw_req->query_type)
887 case Z_SRW_query_type_cql:
889 querystr = srw_req->query.cql;
891 case Z_SRW_query_type_pqf:
893 querystr = srw_req->query.pqf;
896 wrbuf_printf(wr, "SRWSearch ");
897 if (srw_res->num_diagnostics)
898 wrbuf_printf(wr, "ERROR %s", srw_res->diagnostics[0].uri);
899 else if (*http_code != 200)
900 wrbuf_printf(wr, "ERROR info:http/%d", *http_code);
901 else if (srw_res->numberOfRecords)
903 wrbuf_printf(wr, "OK %d",
904 (srw_res->numberOfRecords ?
905 *srw_res->numberOfRecords : 0));
907 wrbuf_printf(wr, " %s %d+%d",
908 (srw_res->resultSetId ?
909 srw_res->resultSetId : "-"),
910 (srw_req->startRecord ? *srw_req->startRecord : 1),
911 srw_res->num_records);
912 yaz_log(log_request, "%s %s: %s", wrbuf_buf(wr), querytype, querystr);
917 static char *srw_bend_explain_default(void *handle, bend_explain_rr *rr)
920 xmlNodePtr ptr = rr->server_node_ptr;
923 for (ptr = ptr->children; ptr; ptr = ptr->next)
925 if (ptr->type != XML_ELEMENT_NODE)
927 if (!strcmp((const char *) ptr->name, "explain"))
930 ptr = xmlCopyNode(ptr, 1);
932 xmlDocPtr doc = xmlNewDoc((const xmlChar *) "1.0");
934 xmlDocSetRootElement(doc, ptr);
937 xmlDocDumpMemory(doc, &buf_out, &len);
938 char *content = (char*) odr_malloc(rr->stream, 1+len);
939 memcpy(content, buf_out, len);
944 rr->explain_buf = content;
952 static void srw_bend_explain(association *assoc, request *req,
953 Z_SRW_explainRequest *srw_req,
954 Z_SRW_explainResponse *srw_res,
957 yaz_log(log_requestdetail, "Got SRW ExplainRequest");
959 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics);
964 rr.stream = assoc->encode;
965 rr.decode = assoc->decode;
966 rr.print = assoc->print;
968 rr.database = srw_req->database;
969 rr.server_node_ptr = assoc->server_node_ptr;
970 rr.schema = "http://explain.z3950.org/dtd/2.0/";
971 if (assoc->init->bend_explain)
972 (*assoc->init->bend_explain)(assoc->backend, &rr);
974 srw_bend_explain_default(assoc->backend, &rr);
978 int packing = Z_SRW_recordPacking_string;
979 if (srw_req->recordPacking &&
980 !strcmp(srw_req->recordPacking, "xml"))
981 packing = Z_SRW_recordPacking_XML;
982 srw_res->record.recordSchema = rr.schema;
983 srw_res->record.recordPacking = packing;
984 srw_res->record.recordData_buf = rr.explain_buf;
985 srw_res->record.recordData_len = strlen(rr.explain_buf);
986 srw_res->record.recordPosition = 0;
992 static void srw_bend_scan(association *assoc, request *req,
993 Z_SRW_scanRequest *srw_req,
994 Z_SRW_scanResponse *srw_res,
997 yaz_log(log_requestdetail, "Got SRW ScanRequest");
1000 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics);
1001 if (srw_res->num_diagnostics == 0 && assoc->init)
1003 struct scan_entry *save_entries;
1005 bend_scan_rr *bsrr = (bend_scan_rr *)
1006 odr_malloc (assoc->encode, sizeof(*bsrr));
1007 bsrr->num_bases = 1;
1008 bsrr->basenames = &srw_req->database;
1010 bsrr->num_entries = srw_req->maximumTerms ?
1011 *srw_req->maximumTerms : 10;
1012 bsrr->term_position = srw_req->responsePosition ?
1013 *srw_req->responsePosition : 1;
1016 bsrr->errstring = 0;
1017 bsrr->referenceId = 0;
1018 bsrr->stream = assoc->encode;
1019 bsrr->print = assoc->print;
1020 bsrr->step_size = odr_intdup(assoc->decode, 0);
1023 if (bsrr->num_entries > 0)
1026 bsrr->entries = odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
1028 for (i = 0; i<bsrr->num_entries; i++)
1030 bsrr->entries[i].term = 0;
1031 bsrr->entries[i].occurrences = 0;
1032 bsrr->entries[i].errcode = 0;
1033 bsrr->entries[i].errstring = 0;
1034 bsrr->entries[i].display_term = 0;
1037 save_entries = bsrr->entries; /* save it so we can compare later */
1039 if (srw_req->query_type == Z_SRW_query_type_pqf &&
1040 assoc->init->bend_scan)
1042 Odr_oid *scan_attributeSet = 0;
1044 YAZ_PQF_Parser pqf_parser = yaz_pqf_create();
1046 bsrr->term = yaz_pqf_scan(pqf_parser, assoc->decode,
1048 srw_req->scanClause.pqf);
1049 if (scan_attributeSet &&
1050 (attset = oid_getentbyoid(scan_attributeSet)) &&
1051 (attset->oclass == CLASS_ATTSET ||
1052 attset->oclass == CLASS_GENERAL))
1053 bsrr->attributeset = attset->value;
1055 bsrr->attributeset = VAL_NONE;
1056 yaz_pqf_destroy(pqf_parser);
1057 bsrr->scanClause = 0;
1058 ((int (*)(void *, bend_scan_rr *))
1059 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1061 else if (srw_req->query_type == Z_SRW_query_type_cql
1062 && assoc->init->bend_srw_scan)
1064 if (assoc->cql_transform)
1066 bsrr->scanClause = 0;
1067 bsrr->attributeset = VAL_NONE;
1068 bsrr->term = odr_malloc(assoc->decode, sizeof(*bsrr->term));
1069 int srw_error = cql2pqf_scan(assoc->encode,
1070 srw_req->scanClause.cql,
1071 assoc->cql_transform,
1074 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1075 &srw_res->num_diagnostics,
1079 ((int (*)(void *, bend_scan_rr *))
1080 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1086 bsrr->attributeset = VAL_NONE;
1087 bsrr->scanClause = srw_req->scanClause.cql;
1088 ((int (*)(void *, bend_scan_rr *))
1089 (*assoc->init->bend_srw_scan))(assoc->backend, bsrr);
1094 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1095 &srw_res->num_diagnostics, 4, "scan");
1100 if (bsrr->errcode == 109) /* database unavailable */
1105 srw_error = yaz_diag_bib1_to_srw (bsrr->errcode);
1107 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1108 &srw_res->num_diagnostics,
1109 srw_error, bsrr->errstring);
1111 else if (srw_res->num_diagnostics == 0 && bsrr->num_entries)
1114 srw_res->terms = (Z_SRW_scanTerm*)
1115 odr_malloc(assoc->encode, sizeof(*srw_res->terms) *
1118 srw_res->num_terms = bsrr->num_entries;
1119 for (i = 0; i<bsrr->num_entries; i++)
1121 Z_SRW_scanTerm *t = srw_res->terms + i;
1122 t->value = odr_strdup(assoc->encode, bsrr->entries[i].term);
1123 t->numberOfRecords =
1124 odr_intdup(assoc->encode, bsrr->entries[i].occurrences);
1126 if (save_entries == bsrr->entries &&
1127 bsrr->entries[i].display_term)
1129 /* the entries was _not_ set by the handler. So it's
1130 safe to test for new member display_term. It is
1133 t->displayTerm = odr_strdup(assoc->encode,
1134 bsrr->entries[i].display_term);
1142 WRBUF wr = wrbuf_alloc();
1143 const char *querytype = 0;
1144 const char *querystr = 0;
1146 switch(srw_req->query_type)
1148 case Z_SRW_query_type_pqf:
1150 querystr = srw_req->scanClause.pqf;
1152 case Z_SRW_query_type_cql:
1154 querystr = srw_req->scanClause.cql;
1157 querytype = "Unknown";
1160 wrbuf_printf(wr, "SRWScan %d+%d",
1161 (srw_req->responsePosition ?
1162 *srw_req->responsePosition : 1),
1163 (srw_req->maximumTerms ?
1164 *srw_req->maximumTerms : 1));
1165 if (srw_res->num_diagnostics)
1166 wrbuf_printf(wr, " ERROR %s", srw_res->diagnostics[0].uri);
1168 wrbuf_printf(wr, " OK -");
1169 wrbuf_printf(wr, " %s: %s", querytype, querystr);
1170 yaz_log(log_request, "%s", wrbuf_buf(wr) );
1177 static void process_http_request(association *assoc, request *req)
1179 Z_HTTP_Request *hreq = req->gdu_request->u.HTTP_Request;
1180 ODR o = assoc->encode;
1181 int r = 2; /* 2=NOT TAKEN, 1=TAKEN, 0=SOAP TAKEN */
1183 Z_SOAP *soap_package = 0;
1186 Z_HTTP_Response *hres = 0;
1188 char *stylesheet = 0;
1189 Z_SRW_diagnostic *diagnostic = 0;
1190 int num_diagnostic = 0;
1191 const char *host = z_HTTP_header_lookup(hreq->headers, "Host");
1193 if (!control_association(assoc, host, 0))
1195 p = z_get_HTTP_Response(o, 404);
1198 if (r == 2 && !strcmp(hreq->path, "/test"))
1200 p = z_get_HTTP_Response(o, 200);
1201 hres = p->u.HTTP_Response;
1202 hres->content_buf = "1234567890\n";
1203 hres->content_len = strlen(hres->content_buf);
1208 r = yaz_srw_decode(hreq, &sr, &soap_package, assoc->decode, &charset);
1209 yaz_log(YLOG_DEBUG, "yaz_srw_decode returned %d", r);
1211 if (r == 2) /* not taken */
1213 r = yaz_sru_decode(hreq, &sr, &soap_package, assoc->decode, &charset,
1214 &diagnostic, &num_diagnostic);
1215 yaz_log(YLOG_DEBUG, "yaz_sru_decode returned %d", r);
1217 if (r == 0) /* decode SRW/SRU OK .. */
1219 int http_code = 200;
1220 if (sr->which == Z_SRW_searchRetrieve_request)
1223 yaz_srw_get(assoc->encode, Z_SRW_searchRetrieve_response);
1225 stylesheet = sr->u.request->stylesheet;
1228 res->u.response->diagnostics = diagnostic;
1229 res->u.response->num_diagnostics = num_diagnostic;
1233 srw_bend_search(assoc, req, sr->u.request, res->u.response,
1236 if (http_code == 200)
1237 soap_package->u.generic->p = res;
1239 else if (sr->which == Z_SRW_explain_request)
1241 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_explain_response);
1242 stylesheet = sr->u.explain_request->stylesheet;
1245 res->u.explain_response->diagnostics = diagnostic;
1246 res->u.explain_response->num_diagnostics = num_diagnostic;
1248 srw_bend_explain(assoc, req, sr->u.explain_request,
1249 res->u.explain_response, &http_code);
1250 if (http_code == 200)
1251 soap_package->u.generic->p = res;
1253 else if (sr->which == Z_SRW_scan_request)
1255 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_scan_response);
1256 stylesheet = sr->u.scan_request->stylesheet;
1259 res->u.scan_response->diagnostics = diagnostic;
1260 res->u.scan_response->num_diagnostics = num_diagnostic;
1262 srw_bend_scan(assoc, req, sr->u.scan_request,
1263 res->u.scan_response, &http_code);
1264 if (http_code == 200)
1265 soap_package->u.generic->p = res;
1269 yaz_log(log_request, "SOAP ERROR");
1270 /* FIXME - what error, what query */
1272 z_soap_error(assoc->encode, soap_package,
1273 "SOAP-ENV:Client", "Bad method", 0);
1275 if (http_code == 200 || http_code == 500)
1277 static Z_SOAP_Handler soap_handlers[3] = {
1279 {"http://www.loc.gov/zing/srw/", 0,
1280 (Z_SOAP_fun) yaz_srw_codec},
1281 {"http://www.loc.gov/zing/srw/v1.0/", 0,
1282 (Z_SOAP_fun) yaz_srw_codec},
1288 p = z_get_HTTP_Response(o, 200);
1289 hres = p->u.HTTP_Response;
1290 ret = z_soap_codec_enc_xsl(assoc->encode, &soap_package,
1291 &hres->content_buf, &hres->content_len,
1292 soap_handlers, charset, stylesheet);
1293 hres->code = http_code;
1295 strcpy(ctype, "text/xml");
1298 strcat(ctype, "; charset=");
1299 strcat(ctype, charset);
1301 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1304 p = z_get_HTTP_Response(o, http_code);
1308 p = z_get_HTTP_Response(o, 500);
1309 hres = p->u.HTTP_Response;
1310 if (!strcmp(hreq->version, "1.0"))
1312 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1313 if (v && !strcmp(v, "Keep-Alive"))
1317 hres->version = "1.0";
1321 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1322 if (v && !strcmp(v, "close"))
1326 hres->version = "1.1";
1330 z_HTTP_header_add(o, &hres->headers, "Connection", "close");
1331 assoc->state = ASSOC_DEAD;
1332 assoc->cs_get_mask = 0;
1337 const char *alive = z_HTTP_header_lookup(hreq->headers, "Keep-Alive");
1339 if (alive && isdigit(*(const unsigned char *) alive))
1343 if (t < 0 || t > 3600)
1345 iochan_settimeout(assoc->client_chan,t);
1346 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1348 process_gdu_response(assoc, req, p);
1351 static void process_gdu_request(association *assoc, request *req)
1353 if (req->gdu_request->which == Z_GDU_Z3950)
1356 req->apdu_request = req->gdu_request->u.z3950;
1357 if (process_z_request(assoc, req, &msg) < 0)
1358 do_close_req(assoc, Z_Close_systemProblem, msg, req);
1360 else if (req->gdu_request->which == Z_GDU_HTTP_Request)
1361 process_http_request(assoc, req);
1364 do_close_req(assoc, Z_Close_systemProblem, "bad protocol packet", req);
1369 * Initiate request processing.
1371 static int process_z_request(association *assoc, request *req, char **msg)
1377 *msg = "Unknown Error";
1378 assert(req && req->state == REQUEST_IDLE);
1379 if (req->apdu_request->which != Z_APDU_initRequest && !assoc->init)
1381 *msg = "Missing InitRequest";
1384 switch (req->apdu_request->which)
1386 case Z_APDU_initRequest:
1387 res = process_initRequest(assoc, req); break;
1388 case Z_APDU_searchRequest:
1389 res = process_searchRequest(assoc, req, &fd); break;
1390 case Z_APDU_presentRequest:
1391 res = process_presentRequest(assoc, req, &fd); break;
1392 case Z_APDU_scanRequest:
1393 if (assoc->init->bend_scan)
1394 res = process_scanRequest(assoc, req, &fd);
1397 *msg = "Cannot handle Scan APDU";
1401 case Z_APDU_extendedServicesRequest:
1402 if (assoc->init->bend_esrequest)
1403 res = process_ESRequest(assoc, req, &fd);
1406 *msg = "Cannot handle Extended Services APDU";
1410 case Z_APDU_sortRequest:
1411 if (assoc->init->bend_sort)
1412 res = process_sortRequest(assoc, req, &fd);
1415 *msg = "Cannot handle Sort APDU";
1420 process_close(assoc, req);
1422 case Z_APDU_deleteResultSetRequest:
1423 if (assoc->init->bend_delete)
1424 res = process_deleteRequest(assoc, req, &fd);
1427 *msg = "Cannot handle Delete APDU";
1431 case Z_APDU_segmentRequest:
1432 if (assoc->init->bend_segment)
1434 res = process_segmentRequest (assoc, req);
1438 *msg = "Cannot handle Segment APDU";
1442 case Z_APDU_triggerResourceControlRequest:
1445 *msg = "Bad APDU received";
1450 yaz_log(YLOG_DEBUG, " result immediately available");
1451 retval = process_z_response(assoc, req, res);
1455 yaz_log(YLOG_DEBUG, " result unavailble");
1458 else /* no result yet - one will be provided later */
1462 /* Set up an I/O handler for the fd supplied by the backend */
1464 yaz_log(YLOG_DEBUG, " establishing handler for result");
1465 req->state = REQUEST_PENDING;
1466 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT, 0)))
1468 iochan_setdata(chan, assoc);
1475 * Handle message from the backend.
1477 void backend_response(IOCHAN i, int event)
1479 association *assoc = (association *)iochan_getdata(i);
1480 request *req = request_head(&assoc->incoming);
1484 yaz_log(YLOG_DEBUG, "backend_response");
1485 assert(assoc && req && req->state != REQUEST_IDLE);
1486 /* determine what it is we're waiting for */
1487 switch (req->apdu_request->which)
1489 case Z_APDU_searchRequest:
1490 res = response_searchRequest(assoc, req, 0, &fd); break;
1492 case Z_APDU_presentRequest:
1493 res = response_presentRequest(assoc, req, 0, &fd); break;
1494 case Z_APDU_scanRequest:
1495 res = response_scanRequest(assoc, req, 0, &fd); break;
1498 yaz_log(YLOG_FATAL, "Serious programmer's lapse or bug");
1501 if ((res && process_z_response(assoc, req, res) < 0) || fd < 0)
1503 yaz_log(YLOG_WARN, "Fatal error when talking to backend");
1504 do_close(assoc, Z_Close_systemProblem, 0);
1508 else if (!res) /* no result yet - try again later */
1510 yaz_log(YLOG_DEBUG, " no result yet");
1511 iochan_setfd(i, fd); /* in case fd has changed */
1516 * Encode response, and transfer the request structure to the outgoing queue.
1518 static int process_gdu_response(association *assoc, request *req, Z_GDU *res)
1520 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
1524 if (!z_GDU(assoc->print, &res, 0, 0))
1525 yaz_log(YLOG_WARN, "ODR print error: %s",
1526 odr_errmsg(odr_geterror(assoc->print)));
1527 odr_reset(assoc->print);
1529 if (!z_GDU(assoc->encode, &res, 0, 0))
1531 yaz_log(YLOG_WARN, "ODR error when encoding PDU: %s [element %s]",
1532 odr_errmsg(odr_geterror(assoc->decode)),
1533 odr_getelement(assoc->decode));
1536 req->response = odr_getbuf(assoc->encode, &req->len_response,
1537 &req->size_response);
1538 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
1539 odr_reset(assoc->encode);
1540 req->state = REQUEST_IDLE;
1541 request_enq(&assoc->outgoing, req);
1542 /* turn the work over to the ir_session handler */
1543 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
1544 assoc->cs_put_mask = EVENT_OUTPUT;
1545 /* Is there more work to be done? give that to the input handler too */
1547 if (request_head(&assoc->incoming))
1549 yaz_log (YLOG_DEBUG, "more work to be done");
1550 iochan_setevent(assoc->client_chan, EVENT_WORK);
1557 * Encode response, and transfer the request structure to the outgoing queue.
1559 static int process_z_response(association *assoc, request *req, Z_APDU *res)
1561 Z_GDU *gres = (Z_GDU *) odr_malloc(assoc->encode, sizeof(*res));
1562 gres->which = Z_GDU_Z3950;
1563 gres->u.z3950 = res;
1565 return process_gdu_response(assoc, req, gres);
1568 static char *get_vhost(Z_OtherInformation *otherInfo)
1570 return yaz_oi_get_string_oidval(&otherInfo, VAL_PROXY, 1, 0);
1574 * Handle init request.
1575 * At the moment, we don't check the options
1576 * anywhere else in the code - we just try not to do anything that would
1577 * break a naive client. We'll toss 'em into the association block when
1578 * we need them there.
1580 static Z_APDU *process_initRequest(association *assoc, request *reqb)
1582 Z_InitRequest *req = reqb->apdu_request->u.initRequest;
1583 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
1584 Z_InitResponse *resp = apdu->u.initResponse;
1585 bend_initresult *binitres;
1588 statserv_options_block *cb = 0; /* by default no control for backend */
1590 if (control_association(assoc, get_vhost(req->otherInfo), 1))
1591 cb = statserv_getcontrol(); /* got control block for backend */
1593 yaz_log(log_requestdetail, "Got initRequest");
1594 if (req->implementationId)
1595 yaz_log(log_requestdetail, "Id: %s",
1596 req->implementationId);
1597 if (req->implementationName)
1598 yaz_log(log_requestdetail, "Name: %s",
1599 req->implementationName);
1600 if (req->implementationVersion)
1601 yaz_log(log_requestdetail, "Version: %s",
1602 req->implementationVersion);
1604 assoc_init_reset(assoc);
1606 assoc->init->auth = req->idAuthentication;
1607 assoc->init->referenceId = req->referenceId;
1609 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
1611 Z_CharSetandLanguageNegotiation *negotiation =
1612 yaz_get_charneg_record (req->otherInfo);
1614 negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
1615 assoc->init->charneg_request = negotiation;
1621 if (req->implementationVersion)
1622 yaz_log(log_requestdetail, "Config: %s",
1625 iochan_settimeout(assoc->client_chan, cb->idle_timeout * 60);
1627 /* we have a backend control block, so call that init function */
1628 if (!(binitres = (*cb->bend_init)(assoc->init)))
1630 yaz_log(YLOG_WARN, "Bad response from backend.");
1633 assoc->backend = binitres->handle;
1637 /* no backend. return error */
1638 binitres = odr_malloc(assoc->encode, sizeof(*binitres));
1639 binitres->errstring = 0;
1640 binitres->errcode = 1;
1641 iochan_settimeout(assoc->client_chan, 10);
1643 if ((assoc->init->bend_sort))
1644 yaz_log (YLOG_DEBUG, "Sort handler installed");
1645 if ((assoc->init->bend_search))
1646 yaz_log (YLOG_DEBUG, "Search handler installed");
1647 if ((assoc->init->bend_present))
1648 yaz_log (YLOG_DEBUG, "Present handler installed");
1649 if ((assoc->init->bend_esrequest))
1650 yaz_log (YLOG_DEBUG, "ESRequest handler installed");
1651 if ((assoc->init->bend_delete))
1652 yaz_log (YLOG_DEBUG, "Delete handler installed");
1653 if ((assoc->init->bend_scan))
1654 yaz_log (YLOG_DEBUG, "Scan handler installed");
1655 if ((assoc->init->bend_segment))
1656 yaz_log (YLOG_DEBUG, "Segment handler installed");
1658 resp->referenceId = req->referenceId;
1660 /* let's tell the client what we can do */
1661 if (ODR_MASK_GET(req->options, Z_Options_search))
1663 ODR_MASK_SET(resp->options, Z_Options_search);
1664 strcat(options, "srch");
1666 if (ODR_MASK_GET(req->options, Z_Options_present))
1668 ODR_MASK_SET(resp->options, Z_Options_present);
1669 strcat(options, " prst");
1671 if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
1672 assoc->init->bend_delete)
1674 ODR_MASK_SET(resp->options, Z_Options_delSet);
1675 strcat(options, " del");
1677 if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
1678 assoc->init->bend_esrequest)
1680 ODR_MASK_SET(resp->options, Z_Options_extendedServices);
1681 strcat (options, " extendedServices");
1683 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
1685 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
1686 strcat(options, " namedresults");
1688 if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
1690 ODR_MASK_SET(resp->options, Z_Options_scan);
1691 strcat(options, " scan");
1693 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
1695 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
1696 strcat(options, " concurrop");
1698 if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
1700 ODR_MASK_SET(resp->options, Z_Options_sort);
1701 strcat(options, " sort");
1704 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel)
1705 && assoc->init->charneg_response)
1707 Z_OtherInformation **p;
1708 Z_OtherInformationUnit *p0;
1710 yaz_oi_APDU(apdu, &p);
1712 if ((p0=yaz_oi_update(p, assoc->encode, NULL, 0, 0))) {
1713 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
1715 p0->which = Z_OtherInfo_externallyDefinedInfo;
1716 p0->information.externallyDefinedInfo =
1717 assoc->init->charneg_response;
1719 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
1720 strcat(options, " negotiation");
1723 ODR_MASK_SET(resp->options, Z_Options_triggerResourceCtrl);
1725 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
1727 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
1728 assoc->version = 1; /* 1 & 2 are equivalent */
1730 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
1732 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
1735 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
1737 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
1741 yaz_log(log_requestdetail, "Negotiated to v%d: %s", assoc->version, options);
1742 assoc->maximumRecordSize = *req->maximumRecordSize;
1744 if (cb && assoc->maximumRecordSize > cb->maxrecordsize)
1745 assoc->maximumRecordSize = cb->maxrecordsize;
1746 assoc->preferredMessageSize = *req->preferredMessageSize;
1747 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
1748 assoc->preferredMessageSize = assoc->maximumRecordSize;
1750 resp->preferredMessageSize = &assoc->preferredMessageSize;
1751 resp->maximumRecordSize = &assoc->maximumRecordSize;
1753 resp->implementationId = odr_prepend(assoc->encode,
1754 assoc->init->implementation_id,
1755 resp->implementationId);
1757 resp->implementationName = odr_prepend(assoc->encode,
1758 assoc->init->implementation_name,
1759 odr_prepend(assoc->encode, "GFS", resp->implementationName));
1761 version = odr_strdup(assoc->encode, "$Revision: 1.50 $");
1762 if (strlen(version) > 10) /* check for unexpanded CVS strings */
1763 version[strlen(version)-2] = '\0';
1764 resp->implementationVersion = odr_prepend(assoc->encode,
1765 assoc->init->implementation_version,
1766 odr_prepend(assoc->encode, &version[11],
1767 resp->implementationVersion));
1769 if (binitres->errcode)
1771 assoc->state = ASSOC_DEAD;
1772 resp->userInformationField =
1773 init_diagnostics(assoc->encode, binitres->errcode,
1774 binitres->errstring);
1779 WRBUF wr = wrbuf_alloc();
1780 wrbuf_printf(wr, "Init ");
1781 if (binitres->errcode)
1782 wrbuf_printf(wr, "ERROR %d", binitres->errcode);
1784 wrbuf_printf(wr, "OK -");
1785 wrbuf_printf(wr, " ID:%s Name:%s Version:%s",
1786 (req->implementationId ? req->implementationId :"-"),
1787 (req->implementationName ?
1788 req->implementationName : "-"),
1789 (req->implementationVersion ?
1790 req->implementationVersion : "-")
1792 yaz_log(log_request, "%s", wrbuf_buf(wr));
1799 * Set the specified `errcode' and `errstring' into a UserInfo-1
1800 * external to be returned to the client in accordance with Z35.90
1801 * Implementor Agreement 5 (Returning diagnostics in an InitResponse):
1802 * http://lcweb.loc.gov/z3950/agency/agree/initdiag.html
1804 static Z_External *init_diagnostics(ODR odr, int error, const char *addinfo)
1806 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
1807 addinfo ? " -- " : "", addinfo ? addinfo : "");
1808 return zget_init_diagnostics(odr, error, addinfo);
1812 * nonsurrogate diagnostic record.
1814 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
1816 Z_Records *rec = (Z_Records *) odr_malloc (assoc->encode, sizeof(*rec));
1818 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
1819 addinfo ? " -- " : "", addinfo ? addinfo : "");
1821 rec->which = Z_Records_NSD;
1822 rec->u.nonSurrogateDiagnostic = zget_DefaultDiagFormat(assoc->encode,
1828 * surrogate diagnostic.
1830 static Z_NamePlusRecord *surrogatediagrec(association *assoc,
1832 int error, const char *addinfo)
1834 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
1835 addinfo ? " -- " : "", addinfo ? addinfo : "");
1836 return zget_surrogateDiagRec(assoc->encode, dbname, error, addinfo);
1839 static Z_Records *pack_records(association *a, char *setname, int start,
1840 int *num, Z_RecordComposition *comp,
1841 int *next, int *pres, oid_value format,
1842 Z_ReferenceId *referenceId,
1843 int *oid, int *errcode)
1845 int recno, total_length = 0, toget = *num, dumped_records = 0;
1846 Z_Records *records =
1847 (Z_Records *) odr_malloc (a->encode, sizeof(*records));
1848 Z_NamePlusRecordList *reclist =
1849 (Z_NamePlusRecordList *) odr_malloc (a->encode, sizeof(*reclist));
1850 Z_NamePlusRecord **list =
1851 (Z_NamePlusRecord **) odr_malloc (a->encode, sizeof(*list) * toget);
1853 records->which = Z_Records_DBOSD;
1854 records->u.databaseOrSurDiagnostics = reclist;
1855 reclist->num_records = 0;
1856 reclist->records = list;
1857 *pres = Z_PresentStatus_success;
1861 yaz_log(log_requestdetail, "Request to pack %d+%d %s", start, toget, setname);
1862 yaz_log(log_requestdetail, "pms=%d, mrs=%d", a->preferredMessageSize,
1863 a->maximumRecordSize);
1864 for (recno = start; reclist->num_records < toget; recno++)
1867 Z_NamePlusRecord *thisrec;
1868 int this_length = 0;
1870 * we get the number of bytes allocated on the stream before any
1871 * allocation done by the backend - this should give us a reasonable
1872 * idea of the total size of the data so far.
1874 total_length = odr_total(a->encode) - dumped_records;
1880 freq.last_in_set = 0;
1881 freq.setname = setname;
1882 freq.surrogate_flag = 0;
1883 freq.number = recno;
1885 freq.request_format = format;
1886 freq.request_format_raw = oid;
1887 freq.output_format = format;
1888 freq.output_format_raw = 0;
1889 freq.stream = a->encode;
1890 freq.print = a->print;
1891 freq.referenceId = referenceId;
1893 (*a->init->bend_fetch)(a->backend, &freq);
1894 /* backend should be able to signal whether error is system-wide
1895 or only pertaining to current record */
1898 if (!freq.surrogate_flag)
1901 *pres = Z_PresentStatus_failure;
1902 /* for 'present request out of range',
1903 set addinfo to record position if not set */
1904 if (freq.errcode == 13 && freq.errstring == 0)
1906 sprintf (s, "%d", recno);
1910 *errcode = freq.errcode;
1911 return diagrec(a, freq.errcode, freq.errstring);
1913 reclist->records[reclist->num_records] =
1914 surrogatediagrec(a, freq.basename, freq.errcode,
1916 reclist->num_records++;
1917 *next = freq.last_in_set ? 0 : recno + 1;
1921 this_length = freq.len;
1923 this_length = odr_total(a->encode) - total_length - dumped_records;
1924 yaz_log(YLOG_DEBUG, " fetched record, len=%d, total=%d dumped=%d",
1925 this_length, total_length, dumped_records);
1926 if (a->preferredMessageSize > 0 &&
1927 this_length + total_length > a->preferredMessageSize)
1929 /* record is small enough, really */
1930 if (this_length <= a->preferredMessageSize && recno > start)
1932 yaz_log(log_requestdetail, " Dropped last normal-sized record");
1933 *pres = Z_PresentStatus_partial_2;
1936 /* record can only be fetched by itself */
1937 if (this_length < a->maximumRecordSize)
1939 yaz_log(log_requestdetail, " Record > prefmsgsz");
1942 yaz_log(YLOG_DEBUG, " Dropped it");
1943 reclist->records[reclist->num_records] =
1944 surrogatediagrec(a, freq.basename, 16, 0);
1945 reclist->num_records++;
1946 *next = freq.last_in_set ? 0 : recno + 1;
1947 dumped_records += this_length;
1951 else /* too big entirely */
1953 yaz_log(log_requestdetail, "Record > maxrcdsz this=%d max=%d",
1954 this_length, a->maximumRecordSize);
1955 reclist->records[reclist->num_records] =
1956 surrogatediagrec(a, freq.basename, 17, 0);
1957 reclist->num_records++;
1958 *next = freq.last_in_set ? 0 : recno + 1;
1959 dumped_records += this_length;
1964 if (!(thisrec = (Z_NamePlusRecord *)
1965 odr_malloc(a->encode, sizeof(*thisrec))))
1967 if (!(thisrec->databaseName = (char *)odr_malloc(a->encode,
1968 strlen(freq.basename) + 1)))
1970 strcpy(thisrec->databaseName, freq.basename);
1971 thisrec->which = Z_NamePlusRecord_databaseRecord;
1973 if (freq.output_format_raw)
1975 struct oident *ident = oid_getentbyoid(freq.output_format_raw);
1976 freq.output_format = ident->value;
1978 thisrec->u.databaseRecord = z_ext_record(a->encode, freq.output_format,
1979 freq.record, freq.len);
1980 if (!thisrec->u.databaseRecord)
1982 reclist->records[reclist->num_records] = thisrec;
1983 reclist->num_records++;
1984 *next = freq.last_in_set ? 0 : recno + 1;
1986 *num = reclist->num_records;
1990 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
1993 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
1994 bend_search_rr *bsrr =
1995 (bend_search_rr *)nmem_malloc (reqb->request_mem, sizeof(*bsrr));
1997 yaz_log(log_requestdetail, "Got SearchRequest.");
1999 bsrr->request = reqb;
2000 bsrr->association = assoc;
2001 bsrr->referenceId = req->referenceId;
2002 save_referenceId (reqb, bsrr->referenceId);
2004 yaz_log (log_requestdetail, "ResultSet '%s'", req->resultSetName);
2005 if (req->databaseNames)
2008 for (i = 0; i < req->num_databaseNames; i++)
2009 yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
2012 yaz_log_zquery_level(log_requestdetail,req->query);
2014 if (assoc->init->bend_search)
2016 bsrr->setname = req->resultSetName;
2017 bsrr->replace_set = *req->replaceIndicator;
2018 bsrr->num_bases = req->num_databaseNames;
2019 bsrr->basenames = req->databaseNames;
2020 bsrr->query = req->query;
2021 bsrr->stream = assoc->encode;
2022 nmem_transfer(bsrr->stream->mem, reqb->request_mem);
2023 bsrr->decode = assoc->decode;
2024 bsrr->print = assoc->print;
2027 bsrr->errstring = NULL;
2028 bsrr->search_info = NULL;
2030 if (assoc->cql_transform &&
2031 req->query->which == Z_Query_type_104 &&
2032 req->query->u.type_104->which == Z_External_CQL)
2034 /* have a CQL query and a CQL to PQF transform .. */
2036 cql2pqf(bsrr->stream, req->query->u.type_104->u.cql,
2037 assoc->cql_transform, bsrr->query);
2039 bsrr->errcode = yaz_diag_srw_to_bib1(srw_errcode);
2042 (assoc->init->bend_search)(assoc->backend, bsrr);
2043 if (!bsrr->request) /* backend not ready with the search response */
2044 return 0; /* should not be used any more */
2048 /* FIXME - make a diagnostic for it */
2049 yaz_log(YLOG_WARN,"Search not supported ?!?!");
2051 return response_searchRequest(assoc, reqb, bsrr, fd);
2054 int bend_searchresponse(void *handle, bend_search_rr *bsrr) {return 0;}
2057 * Prepare a searchresponse based on the backend results. We probably want
2058 * to look at making the fetching of records nonblocking as well, but
2059 * so far, we'll keep things simple.
2060 * If bsrt is null, that means we're called in response to a communications
2061 * event, and we'll have to get the response for ourselves.
2063 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
2064 bend_search_rr *bsrt, int *fd)
2066 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2067 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2068 Z_SearchResponse *resp = (Z_SearchResponse *)
2069 odr_malloc (assoc->encode, sizeof(*resp));
2070 int *nulint = odr_intdup (assoc->encode, 0);
2071 bool_t *sr = odr_intdup(assoc->encode, 1);
2072 int *next = odr_intdup(assoc->encode, 0);
2073 int *none = odr_intdup(assoc->encode, Z_SearchResponse_none);
2076 apdu->which = Z_APDU_searchResponse;
2077 apdu->u.searchResponse = resp;
2078 resp->referenceId = req->referenceId;
2079 resp->additionalSearchInfo = 0;
2080 resp->otherInfo = 0;
2082 if (!bsrt && !bend_searchresponse(assoc->backend, bsrt))
2084 yaz_log(YLOG_FATAL, "Bad result from backend");
2087 else if (bsrt->errcode)
2089 resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
2090 resp->resultCount = nulint;
2091 resp->numberOfRecordsReturned = nulint;
2092 resp->nextResultSetPosition = nulint;
2093 resp->searchStatus = nulint;
2094 resp->resultSetStatus = none;
2095 resp->presentStatus = 0;
2099 int *toget = odr_intdup(assoc->encode, 0);
2100 int *presst = odr_intdup(assoc->encode, 0);
2101 Z_RecordComposition comp, *compp = 0;
2103 yaz_log (log_requestdetail, "resultCount: %d", bsrt->hits);
2106 resp->resultCount = &bsrt->hits;
2108 comp.which = Z_RecordComp_simple;
2109 /* how many records does the user agent want, then? */
2110 if (bsrt->hits <= *req->smallSetUpperBound)
2112 *toget = bsrt->hits;
2113 if ((comp.u.simple = req->smallSetElementSetNames))
2116 else if (bsrt->hits < *req->largeSetLowerBound)
2118 *toget = *req->mediumSetPresentNumber;
2119 if (*toget > bsrt->hits)
2120 *toget = bsrt->hits;
2121 if ((comp.u.simple = req->mediumSetElementSetNames))
2127 if (*toget && !resp->records)
2132 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
2135 form = prefformat->value;
2136 resp->records = pack_records(assoc, req->resultSetName, 1,
2137 toget, compp, next, presst, form, req->referenceId,
2138 req->preferredRecordSyntax, NULL);
2141 resp->numberOfRecordsReturned = toget;
2142 returnedrecs = *toget;
2143 resp->nextResultSetPosition = next;
2144 resp->searchStatus = sr;
2145 resp->resultSetStatus = 0;
2146 resp->presentStatus = presst;
2150 if (*resp->resultCount)
2152 resp->numberOfRecordsReturned = nulint;
2153 resp->nextResultSetPosition = next;
2154 resp->searchStatus = sr;
2155 resp->resultSetStatus = 0;
2156 resp->presentStatus = 0;
2159 resp->additionalSearchInfo = bsrt->search_info;
2163 WRBUF wr = wrbuf_alloc();
2165 wrbuf_printf(wr, "ERROR %d", bsrt->errcode);
2167 wrbuf_printf(wr, "OK %d", bsrt->hits);
2168 wrbuf_printf(wr, " %s 1+%d ",
2169 req->resultSetName, returnedrecs);
2170 wrbuf_put_zquery(wr, req->query);
2172 yaz_log(log_request, "Search %s", wrbuf_buf(wr));
2179 * Maybe we got a little over-friendly when we designed bend_fetch to
2180 * get only one record at a time. Some backends can optimise multiple-record
2181 * fetches, and at any rate, there is some overhead involved in
2182 * all that selecting and hopping around. Problem is, of course, that the
2183 * frontend can't know ahead of time how many records it'll need to
2184 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
2185 * is downright lousy as a bulk data transfer protocol.
2187 * To start with, we'll do the fetching of records from the backend
2188 * in one operation: To save some trips in and out of the event-handler,
2189 * and to simplify the interface to pack_records. At any rate, asynch
2190 * operation is more fun in operations that have an unpredictable execution
2191 * speed - which is normally more true for search than for present.
2193 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
2196 Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
2200 Z_PresentResponse *resp;
2204 const char *errstring = 0;
2206 yaz_log(log_requestdetail, "Got PresentRequest.");
2208 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
2211 form = prefformat->value;
2212 resp = (Z_PresentResponse *)odr_malloc (assoc->encode, sizeof(*resp));
2214 resp->presentStatus = odr_intdup(assoc->encode, 0);
2215 if (assoc->init->bend_present)
2217 bend_present_rr *bprr = (bend_present_rr *)
2218 nmem_malloc (reqb->request_mem, sizeof(*bprr));
2219 bprr->setname = req->resultSetId;
2220 bprr->start = *req->resultSetStartPoint;
2221 bprr->number = *req->numberOfRecordsRequested;
2222 bprr->format = form;
2223 bprr->comp = req->recordComposition;
2224 bprr->referenceId = req->referenceId;
2225 bprr->stream = assoc->encode;
2226 bprr->print = assoc->print;
2227 bprr->request = reqb;
2228 bprr->association = assoc;
2230 bprr->errstring = NULL;
2231 (*assoc->init->bend_present)(assoc->backend, bprr);
2234 return 0; /* should not happen */
2237 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2238 *resp->presentStatus = Z_PresentStatus_failure;
2239 errcode = bprr->errcode;
2240 errstring = bprr->errstring;
2243 apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2244 next = odr_intdup(assoc->encode, 0);
2245 num = odr_intdup(assoc->encode, 0);
2247 apdu->which = Z_APDU_presentResponse;
2248 apdu->u.presentResponse = resp;
2249 resp->referenceId = req->referenceId;
2250 resp->otherInfo = 0;
2254 *num = *req->numberOfRecordsRequested;
2256 pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
2257 num, req->recordComposition, next,
2258 resp->presentStatus,
2259 form, req->referenceId, req->preferredRecordSyntax,
2264 WRBUF wr = wrbuf_alloc();
2265 wrbuf_printf(wr, "Present ");
2267 if (*resp->presentStatus == Z_PresentStatus_failure)
2268 wrbuf_printf(wr, "ERROR %d", errcode);
2269 else if (*resp->presentStatus == Z_PresentStatus_success)
2270 wrbuf_printf(wr, "OK -");
2272 wrbuf_printf(wr, "Partial %d", *resp->presentStatus);
2274 wrbuf_printf(wr, " %s %d+%d ",
2275 req->resultSetId, *req->resultSetStartPoint,
2276 *req->numberOfRecordsRequested);
2277 yaz_log(log_request, "%s", wrbuf_buf(wr) );
2282 resp->numberOfRecordsReturned = num;
2283 resp->nextResultSetPosition = next;
2289 * Scan was implemented rather in a hurry, and with support for only the basic
2290 * elements of the service in the backend API. Suggestions are welcome.
2292 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
2294 Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
2295 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2296 Z_ScanResponse *res = (Z_ScanResponse *)
2297 odr_malloc (assoc->encode, sizeof(*res));
2298 int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
2299 int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
2300 Z_ListEntries *ents = (Z_ListEntries *)
2301 odr_malloc (assoc->encode, sizeof(*ents));
2302 Z_DiagRecs *diagrecs_p = NULL;
2304 bend_scan_rr *bsrr = (bend_scan_rr *)
2305 odr_malloc (assoc->encode, sizeof(*bsrr));
2306 struct scan_entry *save_entries;
2308 yaz_log(log_requestdetail, "Got ScanRequest");
2310 apdu->which = Z_APDU_scanResponse;
2311 apdu->u.scanResponse = res;
2312 res->referenceId = req->referenceId;
2314 /* if step is absent, set it to 0 */
2315 res->stepSize = odr_intdup(assoc->encode, 0);
2317 *res->stepSize = *req->stepSize;
2319 res->scanStatus = scanStatus;
2320 res->numberOfEntriesReturned = numberOfEntriesReturned;
2321 res->positionOfTerm = 0;
2322 res->entries = ents;
2323 ents->num_entries = 0;
2324 ents->entries = NULL;
2325 ents->num_nonsurrogateDiagnostics = 0;
2326 ents->nonsurrogateDiagnostics = NULL;
2327 res->attributeSet = 0;
2330 if (req->databaseNames)
2333 for (i = 0; i < req->num_databaseNames; i++)
2334 yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
2336 yaz_log(log_requestdetail, "pos %d step %d entries %d",
2337 *req->preferredPositionInResponse, *res->stepSize,
2338 *req->numberOfTermsRequested);
2339 bsrr->num_bases = req->num_databaseNames;
2340 bsrr->basenames = req->databaseNames;
2341 bsrr->num_entries = *req->numberOfTermsRequested;
2342 bsrr->term = req->termListAndStartPoint;
2343 bsrr->referenceId = req->referenceId;
2344 bsrr->stream = assoc->encode;
2345 bsrr->print = assoc->print;
2346 bsrr->step_size = res->stepSize;
2348 /* For YAZ 2.0 and earlier it was the backend handler that
2349 initialized entries (member display_term did not exist)
2350 YAZ 2.0 and later sets 'entries' and initialize all members
2351 including 'display_term'. If YAZ 2.0 or later sees that
2352 entries was modified - we assume that it is an old handler and
2353 that 'display_term' is _not_ set.
2355 if (bsrr->num_entries > 0)
2358 bsrr->entries = odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
2360 for (i = 0; i<bsrr->num_entries; i++)
2362 bsrr->entries[i].term = 0;
2363 bsrr->entries[i].occurrences = 0;
2364 bsrr->entries[i].errcode = 0;
2365 bsrr->entries[i].errstring = 0;
2366 bsrr->entries[i].display_term = 0;
2369 save_entries = bsrr->entries; /* save it so we can compare later */
2371 if (req->attributeSet &&
2372 (attset = oid_getentbyoid(req->attributeSet)) &&
2373 (attset->oclass == CLASS_ATTSET || attset->oclass == CLASS_GENERAL))
2374 bsrr->attributeset = attset->value;
2376 bsrr->attributeset = VAL_NONE;
2377 log_scan_term_level (log_requestdetail, req->termListAndStartPoint,
2378 bsrr->attributeset);
2379 bsrr->term_position = req->preferredPositionInResponse ?
2380 *req->preferredPositionInResponse : 1;
2382 ((int (*)(void *, bend_scan_rr *))
2383 (*assoc->init->bend_scan))(assoc->backend, bsrr);
2386 diagrecs_p = zget_DiagRecs(assoc->encode,
2387 bsrr->errcode, bsrr->errstring);
2391 Z_Entry **tab = (Z_Entry **)
2392 odr_malloc (assoc->encode, sizeof(*tab) * bsrr->num_entries);
2394 if (bsrr->status == BEND_SCAN_PARTIAL)
2395 *scanStatus = Z_Scan_partial_5;
2397 *scanStatus = Z_Scan_success;
2398 ents->entries = tab;
2399 ents->num_entries = bsrr->num_entries;
2400 res->numberOfEntriesReturned = &ents->num_entries;
2401 res->positionOfTerm = &bsrr->term_position;
2402 for (i = 0; i < bsrr->num_entries; i++)
2408 tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
2409 if (bsrr->entries[i].occurrences >= 0)
2411 e->which = Z_Entry_termInfo;
2412 e->u.termInfo = t = (Z_TermInfo *)
2413 odr_malloc(assoc->encode, sizeof(*t));
2414 t->suggestedAttributes = 0;
2416 if (save_entries == bsrr->entries &&
2417 bsrr->entries[i].display_term)
2419 /* the entries was _not_ set by the handler. So it's
2420 safe to test for new member display_term. It is
2423 t->displayTerm = odr_strdup(assoc->encode,
2424 bsrr->entries[i].display_term);
2426 t->alternativeTerm = 0;
2427 t->byAttributes = 0;
2428 t->otherTermInfo = 0;
2429 t->globalOccurrences = &bsrr->entries[i].occurrences;
2430 t->term = (Z_Term *)
2431 odr_malloc(assoc->encode, sizeof(*t->term));
2432 t->term->which = Z_Term_general;
2433 t->term->u.general = o =
2434 (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
2435 o->buf = (unsigned char *)
2436 odr_malloc(assoc->encode, o->len = o->size =
2437 strlen(bsrr->entries[i].term));
2438 memcpy(o->buf, bsrr->entries[i].term, o->len);
2439 yaz_log(YLOG_DEBUG, " term #%d: '%s' (%d)", i,
2440 bsrr->entries[i].term, bsrr->entries[i].occurrences);
2444 Z_DiagRecs *drecs = zget_DiagRecs(assoc->encode,
2445 bsrr->entries[i].errcode,
2446 bsrr->entries[i].errstring);
2447 assert (drecs->num_diagRecs == 1);
2448 e->which = Z_Entry_surrogateDiagnostic;
2449 assert (drecs->diagRecs[0]);
2450 e->u.surrogateDiagnostic = drecs->diagRecs[0];
2456 ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
2457 ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
2461 WRBUF wr = wrbuf_alloc();
2463 wr_diag(wr, bsrr->errcode, bsrr->errstring);
2464 else if (*res->scanStatus == Z_Scan_success)
2465 wrbuf_printf(wr, "OK");
2467 wrbuf_printf(wr, "Partial");
2469 wrbuf_printf(wr, " %d+%d %d ",
2470 *req->preferredPositionInResponse,
2471 *req->numberOfTermsRequested,
2472 (res->stepSize ? *res->stepSize : 0));
2473 wrbuf_scan_term(wr, req->termListAndStartPoint,
2474 bsrr->attributeset);
2476 yaz_log(log_request, "Scan %s", wrbuf_buf(wr) );
2482 static Z_APDU *process_sortRequest(association *assoc, request *reqb,
2486 Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
2487 Z_SortResponse *res = (Z_SortResponse *)
2488 odr_malloc (assoc->encode, sizeof(*res));
2489 bend_sort_rr *bsrr = (bend_sort_rr *)
2490 odr_malloc (assoc->encode, sizeof(*bsrr));
2492 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2494 yaz_log(log_requestdetail, "Got SortRequest.");
2496 bsrr->num_input_setnames = req->num_inputResultSetNames;
2497 for (i=0;i<req->num_inputResultSetNames;i++)
2498 yaz_log(log_requestdetail, "Input resultset: '%s'",
2499 req->inputResultSetNames[i]);
2500 bsrr->input_setnames = req->inputResultSetNames;
2501 bsrr->referenceId = req->referenceId;
2502 bsrr->output_setname = req->sortedResultSetName;
2503 yaz_log(log_requestdetail, "Output resultset: '%s'",
2504 req->sortedResultSetName);
2505 bsrr->sort_sequence = req->sortSequence;
2506 /*FIXME - dump those sequences too */
2507 bsrr->stream = assoc->encode;
2508 bsrr->print = assoc->print;
2510 bsrr->sort_status = Z_SortResponse_failure;
2512 bsrr->errstring = 0;
2514 (*assoc->init->bend_sort)(assoc->backend, bsrr);
2516 res->referenceId = bsrr->referenceId;
2517 res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
2518 res->resultSetStatus = 0;
2521 Z_DiagRecs *dr = zget_DiagRecs(assoc->encode,
2522 bsrr->errcode, bsrr->errstring);
2523 res->diagnostics = dr->diagRecs;
2524 res->num_diagnostics = dr->num_diagRecs;
2528 res->num_diagnostics = 0;
2529 res->diagnostics = 0;
2531 res->resultCount = 0;
2534 apdu->which = Z_APDU_sortResponse;
2535 apdu->u.sortResponse = res;
2538 WRBUF wr = wrbuf_alloc();
2539 wrbuf_printf(wr, "Sort ");
2541 wrbuf_printf(wr, " ERROR %d", bsrr->errcode);
2543 wrbuf_printf(wr, "OK -");
2544 wrbuf_printf(wr, " (");
2545 for (i = 0; i<req->num_inputResultSetNames; i++)
2548 wrbuf_printf(wr, ",");
2549 wrbuf_printf(wr, req->inputResultSetNames[i]);
2551 wrbuf_printf(wr, ")->%s ",req->sortedResultSetName);
2553 yaz_log(log_request, "%s", wrbuf_buf(wr) );
2559 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
2563 Z_DeleteResultSetRequest *req =
2564 reqb->apdu_request->u.deleteResultSetRequest;
2565 Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
2566 odr_malloc (assoc->encode, sizeof(*res));
2567 bend_delete_rr *bdrr = (bend_delete_rr *)
2568 odr_malloc (assoc->encode, sizeof(*bdrr));
2569 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2571 yaz_log(log_requestdetail, "Got DeleteRequest.");
2573 bdrr->num_setnames = req->num_resultSetList;
2574 bdrr->setnames = req->resultSetList;
2575 for (i = 0; i<req->num_resultSetList; i++)
2576 yaz_log(log_requestdetail, "resultset: '%s'",
2577 req->resultSetList[i]);
2578 bdrr->stream = assoc->encode;
2579 bdrr->print = assoc->print;
2580 bdrr->function = *req->deleteFunction;
2581 bdrr->referenceId = req->referenceId;
2583 if (bdrr->num_setnames > 0)
2585 bdrr->statuses = (int*)
2586 odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
2587 bdrr->num_setnames);
2588 for (i = 0; i < bdrr->num_setnames; i++)
2589 bdrr->statuses[i] = 0;
2591 (*assoc->init->bend_delete)(assoc->backend, bdrr);
2593 res->referenceId = req->referenceId;
2595 res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
2597 res->deleteListStatuses = 0;
2598 if (bdrr->num_setnames > 0)
2601 res->deleteListStatuses = (Z_ListStatuses *)
2602 odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
2603 res->deleteListStatuses->num = bdrr->num_setnames;
2604 res->deleteListStatuses->elements =
2606 odr_malloc (assoc->encode,
2607 sizeof(*res->deleteListStatuses->elements) *
2608 bdrr->num_setnames);
2609 for (i = 0; i<bdrr->num_setnames; i++)
2611 res->deleteListStatuses->elements[i] =
2613 odr_malloc (assoc->encode,
2614 sizeof(**res->deleteListStatuses->elements));
2615 res->deleteListStatuses->elements[i]->status = bdrr->statuses+i;
2616 res->deleteListStatuses->elements[i]->id =
2617 odr_strdup (assoc->encode, bdrr->setnames[i]);
2620 res->numberNotDeleted = 0;
2621 res->bulkStatuses = 0;
2622 res->deleteMessage = 0;
2625 apdu->which = Z_APDU_deleteResultSetResponse;
2626 apdu->u.deleteResultSetResponse = res;
2629 WRBUF wr = wrbuf_alloc();
2630 wrbuf_printf(wr, "Delete ");
2631 if (bdrr->delete_status)
2632 wrbuf_printf(wr, "ERROR %d", bdrr->delete_status);
2634 wrbuf_printf(wr, "OK -");
2635 for (i = 0; i<req->num_resultSetList; i++)
2636 wrbuf_printf(wr, " %s ", req->resultSetList[i]);
2637 yaz_log(log_request, "%s", wrbuf_buf(wr) );
2643 static void process_close(association *assoc, request *reqb)
2645 Z_Close *req = reqb->apdu_request->u.close;
2646 static char *reasons[] =
2653 "securityViolation",
2660 yaz_log(log_requestdetail, "Got Close, reason %s, message %s",
2661 reasons[*req->closeReason], req->diagnosticInformation ?
2662 req->diagnosticInformation : "NULL");
2663 if (assoc->version < 3) /* to make do_force respond with close */
2665 do_close_req(assoc, Z_Close_finished,
2666 "Association terminated by client", reqb);
2667 yaz_log(log_request,"Close OK");
2670 void save_referenceId (request *reqb, Z_ReferenceId *refid)
2674 reqb->len_refid = refid->len;
2675 reqb->refid = (char *)nmem_malloc (reqb->request_mem, refid->len);
2676 memcpy (reqb->refid, refid->buf, refid->len);
2680 reqb->len_refid = 0;
2685 void bend_request_send (bend_association a, bend_request req, Z_APDU *res)
2687 process_z_response (a, req, res);
2690 bend_request bend_request_mk (bend_association a)
2692 request *nreq = request_get (&a->outgoing);
2693 nreq->request_mem = nmem_create ();
2697 Z_ReferenceId *bend_request_getid (ODR odr, bend_request req)
2702 id = (Odr_oct *)odr_malloc (odr, sizeof(*odr));
2703 id->buf = (unsigned char *)odr_malloc (odr, req->len_refid);
2704 id->len = id->size = req->len_refid;
2705 memcpy (id->buf, req->refid, req->len_refid);
2709 void bend_request_destroy (bend_request *req)
2711 nmem_destroy((*req)->request_mem);
2712 request_release(*req);
2716 int bend_backend_respond (bend_association a, bend_request req)
2720 r = process_z_request (a, req, &msg);
2722 yaz_log (YLOG_WARN, "%s", msg);
2726 void bend_request_setdata(bend_request r, void *p)
2731 void *bend_request_getdata(bend_request r)
2733 return r->clientData;
2736 static Z_APDU *process_segmentRequest (association *assoc, request *reqb)
2738 bend_segment_rr req;
2740 req.segment = reqb->apdu_request->u.segmentRequest;
2741 req.stream = assoc->encode;
2742 req.decode = assoc->decode;
2743 req.print = assoc->print;
2744 req.association = assoc;
2746 (*assoc->init->bend_segment)(assoc->backend, &req);
2751 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd)
2753 bend_esrequest_rr esrequest;
2755 Z_ExtendedServicesRequest *req =
2756 reqb->apdu_request->u.extendedServicesRequest;
2757 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
2759 Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
2761 yaz_log(log_requestdetail,"Got EsRequest");
2763 esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
2764 esrequest.stream = assoc->encode;
2765 esrequest.decode = assoc->decode;
2766 esrequest.print = assoc->print;
2767 esrequest.errcode = 0;
2768 esrequest.errstring = NULL;
2769 esrequest.request = reqb;
2770 esrequest.association = assoc;
2771 esrequest.taskPackage = 0;
2772 esrequest.referenceId = req->referenceId;
2774 (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
2776 /* If the response is being delayed, return NULL */
2777 if (esrequest.request == NULL)
2780 resp->referenceId = req->referenceId;
2782 if (esrequest.errcode == -1)
2784 /* Backend service indicates request will be processed */
2785 yaz_log(log_request,"EsRequest OK: Accepted !");
2786 *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
2788 else if (esrequest.errcode == 0)
2790 /* Backend service indicates request will be processed */
2791 yaz_log(log_request,"EsRequest OK: Done !");
2792 *resp->operationStatus = Z_ExtendedServicesResponse_done;
2796 Z_DiagRecs *diagRecs =
2797 zget_DiagRecs(assoc->encode, esrequest.errcode,
2798 esrequest.errstring);
2799 /* Backend indicates error, request will not be processed */
2800 yaz_log(YLOG_DEBUG,"Request could not be processed...failure !");
2801 *resp->operationStatus = Z_ExtendedServicesResponse_failure;
2802 resp->num_diagnostics = diagRecs->num_diagRecs;
2803 resp->diagnostics = diagRecs->diagRecs;
2806 WRBUF wr = wrbuf_alloc();
2807 wrbuf_diags(wr, resp->num_diagnostics, resp->diagnostics);
2808 yaz_log(log_request, "EsRequest %s", wrbuf_buf(wr) );
2813 /* Do something with the members of bend_extendedservice */
2814 if (esrequest.taskPackage)
2815 resp->taskPackage = z_ext_record (assoc->encode, VAL_EXTENDED,
2816 (const char *) esrequest.taskPackage,
2818 yaz_log(YLOG_DEBUG,"Send the result apdu");