2 * Copyright (C) 1995-2005, Index Data ApS
3 * See the file LICENSE for details.
5 * $Id: seshigh.c,v 1.48 2005-03-01 20:37:01 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)
53 #include <yaz/yconfig.h>
54 #include <yaz/xmalloc.h>
55 #include <yaz/comstack.h>
58 #include <yaz/proto.h>
61 #include <yaz/logrpn.h>
62 #include <yaz/statserv.h>
63 #include <yaz/diagbib1.h>
64 #include <yaz/charneg.h>
65 #include <yaz/otherinfo.h>
66 #include <yaz/yaz-util.h>
67 #include <yaz/pquery.h>
70 #include <yaz/backend.h>
72 static void process_gdu_request(association *assoc, request *req);
73 static int process_z_request(association *assoc, request *req, char **msg);
74 void backend_response(IOCHAN i, int event);
75 static int process_gdu_response(association *assoc, request *req, Z_GDU *res);
76 static int process_z_response(association *assoc, request *req, Z_APDU *res);
77 static Z_APDU *process_initRequest(association *assoc, request *reqb);
78 static Z_External *init_diagnostics(ODR odr, int errcode,
79 const char *errstring);
80 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
82 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
83 bend_search_rr *bsrr, int *fd);
84 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
86 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
87 static Z_APDU *process_sortRequest(association *assoc, request *reqb, int *fd);
88 static void process_close(association *assoc, request *reqb);
89 void save_referenceId (request *reqb, Z_ReferenceId *refid);
90 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
92 static Z_APDU *process_segmentRequest (association *assoc, request *reqb);
94 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd);
96 /* dynamic logging levels */
97 static int logbits_set = 0;
98 static int log_session = 0;
99 static int log_request = 0; /* one-line logs for requests */
100 static int log_requestdetail = 0; /* more detailed stuff */
102 /** get_logbits sets global loglevel bits */
103 static void get_logbits()
104 { /* needs to be called after parsing cmd-line args that can set loglevels!*/
108 log_session = yaz_log_module_level("session");
109 log_request = yaz_log_module_level("request");
110 log_requestdetail = yaz_log_module_level("requestdetail");
114 static void wr_diag(WRBUF w, int error, const char *addinfo)
116 wrbuf_printf(w, "ERROR [%d] %s%s%s",
117 error, diagbib1_str(error),
118 addinfo ? "--" : "", addinfo ? addinfo : "");
123 * Create and initialize a new association-handle.
124 * channel : iochannel for the current line.
125 * link : communications channel.
126 * Returns: 0 or a new association handle.
128 association *create_association(IOCHAN channel, COMSTACK link,
129 const char *apdufile)
135 if (!(anew = (association *)xmalloc(sizeof(*anew))))
139 anew->last_control = 0;
140 anew->client_chan = channel;
141 anew->client_link = link;
142 anew->cs_get_mask = 0;
143 anew->cs_put_mask = 0;
144 anew->cs_accept_mask = 0;
145 if (!(anew->decode = odr_createmem(ODR_DECODE)) ||
146 !(anew->encode = odr_createmem(ODR_ENCODE)))
148 if (apdufile && *apdufile)
152 if (!(anew->print = odr_createmem(ODR_PRINT)))
154 if (*apdufile == '@')
156 odr_setprint(anew->print, yaz_log_file());
158 else if (*apdufile != '-')
161 sprintf(filename, "%.200s.%ld", apdufile, (long)getpid());
162 if (!(f = fopen(filename, "w")))
164 yaz_log(YLOG_WARN|YLOG_ERRNO, "%s", filename);
167 setvbuf(f, 0, _IONBF, 0);
168 odr_setprint(anew->print, f);
173 anew->input_buffer = 0;
174 anew->input_buffer_len = 0;
176 anew->state = ASSOC_NEW;
177 request_initq(&anew->incoming);
178 request_initq(&anew->outgoing);
179 anew->proto = cs_getproto(link);
180 anew->cql_transform = 0;
185 * Free association and release resources.
187 void destroy_association(association *h)
189 statserv_options_block *cb = statserv_getcontrol();
193 odr_destroy(h->decode);
194 odr_destroy(h->encode);
196 odr_destroy(h->print);
198 xfree(h->input_buffer);
200 (*cb->bend_close)(h->backend);
201 while ((req = request_deq(&h->incoming)))
202 request_release(req);
203 while ((req = request_deq(&h->outgoing)))
204 request_release(req);
205 request_delq(&h->incoming);
206 request_delq(&h->outgoing);
208 xmalloc_trav("session closed");
209 if (cb && cb->one_shot)
215 static void do_close_req(association *a, int reason, char *message,
219 Z_Close *cls = zget_Close(a->encode);
221 /* Purge request queue */
222 while (request_deq(&a->incoming));
223 while (request_deq(&a->outgoing));
226 yaz_log(log_requestdetail, "Sending Close PDU, reason=%d, message=%s",
227 reason, message ? message : "none");
228 apdu.which = Z_APDU_close;
230 *cls->closeReason = reason;
231 cls->diagnosticInformation = message;
232 process_z_response(a, req, &apdu);
233 iochan_settimeout(a->client_chan, 20);
237 request_release(req);
238 yaz_log(log_requestdetail, "v2 client. No Close PDU");
239 iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
241 a->state = ASSOC_DEAD;
244 static void do_close(association *a, int reason, char *message)
246 request *req = request_get(&a->outgoing);
247 do_close_req (a, reason, message, req);
251 * This is where PDUs from the client are read and the further
252 * processing is initiated. Flow of control moves down through the
253 * various process_* functions below, until the encoded result comes back up
254 * to the output handler in here.
256 * h : the I/O channel that has an outstanding event.
257 * event : the current outstanding event.
259 void ir_session(IOCHAN h, int event)
262 association *assoc = (association *)iochan_getdata(h);
263 COMSTACK conn = assoc->client_link;
266 assert(h && conn && assoc);
267 if (event == EVENT_TIMEOUT)
269 if (assoc->state != ASSOC_UP)
271 yaz_log(YLOG_DEBUG, "Final timeout - closing connection.");
272 /* do we need to lod this at all */
274 destroy_association(assoc);
279 yaz_log(log_session, "Session idle too long. Sending close.");
280 do_close(assoc, Z_Close_lackOfActivity, 0);
284 if (event & assoc->cs_accept_mask)
286 if (!cs_accept (conn))
288 yaz_log (YLOG_WARN, "accept failed");
289 destroy_association(assoc);
292 iochan_clearflag (h, EVENT_OUTPUT);
293 if (conn->io_pending)
294 { /* cs_accept didn't complete */
295 assoc->cs_accept_mask =
296 ((conn->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
297 ((conn->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
299 iochan_setflag (h, assoc->cs_accept_mask);
302 { /* cs_accept completed. Prepare for reading (cs_get) */
303 assoc->cs_accept_mask = 0;
304 assoc->cs_get_mask = EVENT_INPUT;
305 iochan_setflag (h, assoc->cs_get_mask);
309 if ((event & assoc->cs_get_mask) || (event & EVENT_WORK)) /* input */
311 if ((assoc->cs_put_mask & EVENT_INPUT) == 0 && (event & assoc->cs_get_mask))
313 yaz_log(YLOG_DEBUG, "ir_session (input)");
314 /* We aren't speaking to this fellow */
315 if (assoc->state == ASSOC_DEAD)
317 yaz_log(log_session, "Connection closed - end of session");
319 destroy_association(assoc);
323 assoc->cs_get_mask = EVENT_INPUT;
324 if ((res = cs_get(conn, &assoc->input_buffer,
325 &assoc->input_buffer_len)) <= 0)
327 yaz_log(log_session, "Connection closed by client");
329 destroy_association(assoc);
333 else if (res == 1) /* incomplete read - wait for more */
335 if (conn->io_pending & CS_WANT_WRITE)
336 assoc->cs_get_mask |= EVENT_OUTPUT;
337 iochan_setflag(h, assoc->cs_get_mask);
340 if (cs_more(conn)) /* more stuff - call us again later, please */
341 iochan_setevent(h, EVENT_INPUT);
343 /* we got a complete PDU. Let's decode it */
344 yaz_log(YLOG_DEBUG, "Got PDU, %d bytes: lead=%02X %02X %02X", res,
345 assoc->input_buffer[0] & 0xff,
346 assoc->input_buffer[1] & 0xff,
347 assoc->input_buffer[2] & 0xff);
348 req = request_get(&assoc->incoming); /* get a new request */
349 odr_reset(assoc->decode);
350 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
351 if (!z_GDU(assoc->decode, &req->gdu_request, 0, 0))
353 yaz_log(YLOG_WARN, "ODR error on incoming PDU: %s [element %s] "
355 odr_errmsg(odr_geterror(assoc->decode)),
356 odr_getelement(assoc->decode),
357 odr_offset(assoc->decode));
358 if (assoc->decode->error != OHTTP)
360 yaz_log(YLOG_WARN, "PDU dump:");
361 odr_dumpBER(yaz_log_file(), assoc->input_buffer, res);
362 request_release(req);
363 do_close(assoc, Z_Close_protocolError,"Malformed package");
367 Z_GDU *p = z_get_HTTP_Response(assoc->encode, 400);
368 assoc->state = ASSOC_DEAD;
369 process_gdu_response(assoc, req, p);
373 req->request_mem = odr_extract_mem(assoc->decode);
376 if (!z_GDU(assoc->print, &req->gdu_request, 0, 0))
377 yaz_log(YLOG_WARN, "ODR print error: %s",
378 odr_errmsg(odr_geterror(assoc->print)));
379 odr_reset(assoc->print);
381 request_enq(&assoc->incoming, req);
384 /* can we do something yet? */
385 req = request_head(&assoc->incoming);
386 if (req->state == REQUEST_IDLE)
388 request_deq(&assoc->incoming);
389 process_gdu_request(assoc, req);
392 if (event & assoc->cs_put_mask)
394 request *req = request_head(&assoc->outgoing);
396 assoc->cs_put_mask = 0;
397 yaz_log(YLOG_DEBUG, "ir_session (output)");
398 req->state = REQUEST_PENDING;
399 switch (res = cs_put(conn, req->response, req->len_response))
402 yaz_log(log_session, "Connection closed by client");
404 destroy_association(assoc);
407 case 0: /* all sent - release the request structure */
408 yaz_log(YLOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
410 yaz_log(YLOG_DEBUG, "HTTP out:\n%.*s", req->len_response,
413 nmem_destroy(req->request_mem);
414 request_deq(&assoc->outgoing);
415 request_release(req);
416 if (!request_head(&assoc->outgoing))
417 { /* restore mask for cs_get operation ... */
418 iochan_clearflag(h, EVENT_OUTPUT|EVENT_INPUT);
419 iochan_setflag(h, assoc->cs_get_mask);
420 if (assoc->state == ASSOC_DEAD)
421 iochan_setevent(assoc->client_chan, EVENT_TIMEOUT);
425 assoc->cs_put_mask = EVENT_OUTPUT;
429 if (conn->io_pending & CS_WANT_WRITE)
430 assoc->cs_put_mask |= EVENT_OUTPUT;
431 if (conn->io_pending & CS_WANT_READ)
432 assoc->cs_put_mask |= EVENT_INPUT;
433 iochan_setflag(h, assoc->cs_put_mask);
436 if (event & EVENT_EXCEPT)
438 yaz_log(YLOG_WARN, "ir_session (exception)");
440 destroy_association(assoc);
445 static int process_z_request(association *assoc, request *req, char **msg);
448 static void assoc_init_reset(association *assoc)
451 assoc->init = (bend_initrequest *) xmalloc (sizeof(*assoc->init));
453 assoc->init->stream = assoc->encode;
454 assoc->init->print = assoc->print;
455 assoc->init->auth = 0;
456 assoc->init->referenceId = 0;
457 assoc->init->implementation_version = 0;
458 assoc->init->implementation_id = 0;
459 assoc->init->implementation_name = 0;
460 assoc->init->bend_sort = NULL;
461 assoc->init->bend_search = NULL;
462 assoc->init->bend_present = NULL;
463 assoc->init->bend_esrequest = NULL;
464 assoc->init->bend_delete = NULL;
465 assoc->init->bend_scan = NULL;
466 assoc->init->bend_segment = NULL;
467 assoc->init->bend_fetch = NULL;
468 assoc->init->bend_explain = NULL;
469 assoc->init->bend_srw_scan = NULL;
471 assoc->init->charneg_request = NULL;
472 assoc->init->charneg_response = NULL;
474 assoc->init->decode = assoc->decode;
475 assoc->init->peer_name =
476 odr_strdup (assoc->encode, cs_addrstr(assoc->client_link));
478 yaz_log(log_requestdetail, "peer %s", assoc->init->peer_name);
481 static int srw_bend_init(association *assoc, Z_SRW_diagnostic **d, int *num)
483 statserv_options_block *cb = statserv_getcontrol();
486 const char *encoding = "UTF-8";
488 bend_initresult *binitres;
490 yaz_log(YLOG_LOG, "srw_bend_init config=%s", cb->configname);
491 assoc_init_reset(assoc);
493 assoc->maximumRecordSize = 3000000;
494 assoc->preferredMessageSize = 3000000;
496 ce = yaz_set_proposal_charneg(assoc->decode, &encoding, 1, 0, 0, 1);
497 assoc->init->charneg_request = ce->u.charNeg3;
500 if (!(binitres = (*cb->bend_init)(assoc->init)))
502 assoc->state = ASSOC_DEAD;
503 yaz_add_srw_diagnostic(assoc->encode, d, num, 3, 0);
506 assoc->backend = binitres->handle;
507 if (binitres->errcode)
509 assoc->state = ASSOC_DEAD;
510 yaz_add_srw_diagnostic(assoc->encode, d, num, binitres->errcode,
511 binitres->errstring);
519 static int srw_bend_fetch(association *assoc, int pos,
520 Z_SRW_searchRetrieveRequest *srw_req,
521 Z_SRW_record *record)
524 ODR o = assoc->encode;
526 rr.setname = "default";
529 rr.request_format = VAL_TEXT_XML;
530 rr.request_format_raw = yaz_oidval_to_z3950oid(assoc->decode,
533 rr.comp = (Z_RecordComposition *)
534 odr_malloc(assoc->decode, sizeof(*rr.comp));
535 rr.comp->which = Z_RecordComp_complex;
536 rr.comp->u.complex = (Z_CompSpec *)
537 odr_malloc(assoc->decode, sizeof(Z_CompSpec));
538 rr.comp->u.complex->selectAlternativeSyntax = (bool_t *)
539 odr_malloc(assoc->encode, sizeof(bool_t));
540 *rr.comp->u.complex->selectAlternativeSyntax = 0;
541 rr.comp->u.complex->num_dbSpecific = 0;
542 rr.comp->u.complex->dbSpecific = 0;
543 rr.comp->u.complex->num_recordSyntax = 0;
544 rr.comp->u.complex->recordSyntax = 0;
546 rr.comp->u.complex->generic = (Z_Specification *)
547 odr_malloc(assoc->decode, sizeof(Z_Specification));
549 /* schema uri = recordSchema (or NULL if recordSchema is not given) */
550 rr.comp->u.complex->generic->which = Z_Schema_uri;
551 rr.comp->u.complex->generic->schema.uri = srw_req->recordSchema;
553 /* ESN = recordSchema if recordSchema is present */
554 rr.comp->u.complex->generic->elementSpec = 0;
555 if (srw_req->recordSchema)
557 rr.comp->u.complex->generic->elementSpec =
558 (Z_ElementSpec *) odr_malloc(assoc->encode, sizeof(Z_ElementSpec));
559 rr.comp->u.complex->generic->elementSpec->which =
560 Z_ElementSpec_elementSetName;
561 rr.comp->u.complex->generic->elementSpec->u.elementSetName =
562 srw_req->recordSchema;
565 rr.stream = assoc->encode;
566 rr.print = assoc->print;
572 rr.output_format = VAL_TEXT_XML;
573 rr.output_format_raw = 0;
576 rr.surrogate_flag = 0;
577 rr.schema = srw_req->recordSchema;
579 if (!assoc->init->bend_fetch)
582 (*assoc->init->bend_fetch)(assoc->backend, &rr);
584 if (rr.errcode && rr.surrogate_flag)
586 int code = yaz_diag_bib1_to_srw(rr.errcode);
587 const char *message = yaz_diag_srw_str(code);
590 len += strlen(message);
592 len += strlen(rr.errstring);
594 record->recordData_buf = odr_malloc(o, len);
596 sprintf(record->recordData_buf, "<diagnostic "
597 "xmlns=\"http://www.loc.gov/zing/srw/diagnostic/\">\n"
598 " <uri>info:srw/diagnostic/1/%d</uri>\n", code);
600 sprintf(record->recordData_buf + strlen(record->recordData_buf),
601 " <details>%s</details>\n", rr.errstring);
603 sprintf(record->recordData_buf + strlen(record->recordData_buf),
604 " <message>%s</message>\n", message);
605 sprintf(record->recordData_buf + strlen(record->recordData_buf),
607 record->recordData_len = strlen(record->recordData_buf);
608 record->recordPosition = odr_intdup(o, pos);
609 record->recordSchema = "info:srw/schema/1/diagnostics-v1.1";
612 else if (rr.len >= 0)
614 record->recordData_buf = rr.record;
615 record->recordData_len = rr.len;
616 record->recordPosition = odr_intdup(o, pos);
618 record->recordSchema = odr_strdup(o, rr.schema);
620 record->recordSchema = 0;
625 static int cql2pqf(ODR odr, const char *cql, cql_transform_t ct,
626 Z_Query *query_result)
628 /* have a CQL query and CQL to PQF transform .. */
629 CQL_parser cp = cql_parser_create();
635 r = cql_parser_string(cp, cql);
638 /* CQL syntax error */
644 r = cql_transform_buf(ct,
645 cql_parser_result(cp),
646 rpn_buf, sizeof(rpn_buf)-1);
648 srw_errcode = cql_transform_error(ct, &add);
652 /* Syntax & transform OK. */
653 /* Convert PQF string to Z39.50 to RPN query struct */
654 YAZ_PQF_Parser pp = yaz_pqf_create();
655 Z_RPNQuery *rpnquery = yaz_pqf_parse(pp, odr, rpn_buf);
660 int code = yaz_pqf_error(pp, &pqf_msg, &off);
661 yaz_log(YLOG_WARN, "PQF Parser Error %s (code %d)",
667 query_result->which = Z_Query_type_1;
668 query_result->u.type_1 = rpnquery;
672 cql_parser_destroy(cp);
676 static int cql2pqf_scan(ODR odr, const char *cql, cql_transform_t ct,
677 Z_AttributesPlusTerm *result)
681 int srw_error = cql2pqf(odr, cql, ct, &query);
684 if (query.which != Z_Query_type_1 && query.which != Z_Query_type_101)
685 return 10; /* bad query type */
686 rpn = query.u.type_1;
687 if (!rpn->RPNStructure)
688 return 10; /* must be structure */
689 if (rpn->RPNStructure->which != Z_RPNStructure_simple)
690 return 10; /* must be simple */
691 if (rpn->RPNStructure->u.simple->which != Z_Operand_APT)
692 return 10; /* must be attributes plus term node .. */
693 memcpy(result, rpn->RPNStructure->u.simple->u.attributesPlusTerm,
698 static void srw_bend_search(association *assoc, request *req,
699 Z_SRW_searchRetrieveRequest *srw_req,
700 Z_SRW_searchRetrieveResponse *srw_res,
707 yaz_log(log_requestdetail, "Got SRW SearchRetrieveRequest");
708 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics);
709 if (srw_req->sort_type != Z_SRW_sort_type_none)
710 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
711 &srw_res->num_diagnostics, 80, 0);
712 else if (srw_res->num_diagnostics == 0 && assoc->init)
715 rr.setname = "default";
718 rr.basenames = &srw_req->database;
721 rr.query = (Z_Query *) odr_malloc (assoc->decode, sizeof(*rr.query));
722 rr.query->u.type_1 = 0;
724 if (srw_req->query_type == Z_SRW_query_type_cql)
726 if (assoc->cql_transform)
728 int srw_errcode = cql2pqf(assoc->encode, srw_req->query.cql,
729 assoc->cql_transform, rr.query);
732 yaz_add_srw_diagnostic(assoc->encode,
733 &srw_res->diagnostics,
734 &srw_res->num_diagnostics,
740 /* CQL query to backend. Wrap it - Z39.50 style */
741 ext = (Z_External *) odr_malloc(assoc->decode, sizeof(*ext));
742 ext->direct_reference = odr_getoidbystr(assoc->decode,
743 "1.2.840.10003.16.2");
744 ext->indirect_reference = 0;
746 ext->which = Z_External_CQL;
747 ext->u.cql = srw_req->query.cql;
749 rr.query->which = Z_Query_type_104;
750 rr.query->u.type_104 = ext;
753 else if (srw_req->query_type == Z_SRW_query_type_pqf)
755 Z_RPNQuery *RPNquery;
756 YAZ_PQF_Parser pqf_parser;
758 pqf_parser = yaz_pqf_create ();
760 RPNquery = yaz_pqf_parse (pqf_parser, assoc->decode,
766 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
767 yaz_log(log_requestdetail, "Parse error %d %s near offset %d",
772 rr.query->which = Z_Query_type_1;
773 rr.query->u.type_1 = RPNquery;
775 yaz_pqf_destroy (pqf_parser);
779 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
780 &srw_res->num_diagnostics, 11, 0);
782 if (rr.query->u.type_1)
784 rr.stream = assoc->encode;
785 rr.decode = assoc->decode;
786 rr.print = assoc->print;
788 rr.association = assoc;
794 yaz_log_zquery_level(log_requestdetail,rr.query);
796 (assoc->init->bend_search)(assoc->backend, &rr);
799 if (rr.errcode == 109) /* database unavailable */
805 srw_error = yaz_diag_bib1_to_srw (rr.errcode);
806 yaz_add_srw_diagnostic(assoc->encode,
807 &srw_res->diagnostics,
808 &srw_res->num_diagnostics,
809 srw_error, rr.errstring);
814 int number = srw_req->maximumRecords ? *srw_req->maximumRecords : 0;
815 int start = srw_req->startRecord ? *srw_req->startRecord : 1;
817 yaz_log(log_requestdetail, "Request to pack %d+%d out of %d",
818 start, number, rr.hits);
820 srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
827 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
828 &srw_res->num_diagnostics,
834 int packing = Z_SRW_recordPacking_string;
835 if (start + number > rr.hits)
836 number = rr.hits - start + 1;
837 if (srw_req->recordPacking &&
838 !strcmp(srw_req->recordPacking, "xml"))
839 packing = Z_SRW_recordPacking_XML;
840 srw_res->records = (Z_SRW_record *)
841 odr_malloc(assoc->encode,
842 number * sizeof(*srw_res->records));
843 for (i = 0; i<number; i++)
847 srw_res->records[j].recordPacking = packing;
848 srw_res->records[j].recordData_buf = 0;
849 yaz_log(YLOG_DEBUG, "srw_bend_fetch %d", i+start);
850 errcode = srw_bend_fetch(assoc, i+start, srw_req,
851 srw_res->records + j);
854 yaz_add_srw_diagnostic(assoc->encode,
855 &srw_res->diagnostics,
856 &srw_res->num_diagnostics,
857 yaz_diag_bib1_to_srw (errcode),
862 if (srw_res->records[j].recordData_buf)
865 srw_res->num_records = j;
867 srw_res->records = 0;
875 const char *querystr = "?";
876 const char *querytype = "?";
877 WRBUF wr = wrbuf_alloc();
879 switch (srw_req->query_type)
881 case Z_SRW_query_type_cql:
883 querystr = srw_req->query.cql;
885 case Z_SRW_query_type_pqf:
887 querystr = srw_req->query.pqf;
890 wrbuf_printf(wr, "SRWSearch ");
891 if (srw_res->num_diagnostics)
892 wrbuf_printf(wr, "ERROR %s", srw_res->diagnostics[0].uri);
893 else if (*http_code != 200)
894 wrbuf_printf(wr, "ERROR info:http/%d", *http_code);
895 else if (srw_res->numberOfRecords)
897 wrbuf_printf(wr, "OK %d",
898 (srw_res->numberOfRecords ?
899 *srw_res->numberOfRecords : 0));
901 wrbuf_printf(wr, " %s %d+%d",
902 (srw_res->resultSetId ?
903 srw_res->resultSetId : "-"),
904 (srw_req->startRecord ? *srw_req->startRecord : 1),
905 srw_res->num_records);
906 yaz_log(log_request, "%s %s: %s", wrbuf_buf(wr), querytype, querystr);
911 static void srw_bend_explain(association *assoc, request *req,
912 Z_SRW_explainRequest *srw_req,
913 Z_SRW_explainResponse *srw_res,
916 yaz_log(log_requestdetail, "Got SRW ExplainRequest");
918 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics);
919 if (assoc->init && assoc->init->bend_explain)
923 rr.stream = assoc->encode;
924 rr.decode = assoc->decode;
925 rr.print = assoc->print;
927 rr.database = srw_req->database;
928 rr.schema = "http://explain.z3950.org/dtd/2.0/";
929 (*assoc->init->bend_explain)(assoc->backend, &rr);
932 int packing = Z_SRW_recordPacking_string;
933 if (srw_req->recordPacking &&
934 !strcmp(srw_req->recordPacking, "xml"))
935 packing = Z_SRW_recordPacking_XML;
936 srw_res->record.recordSchema = rr.schema;
937 srw_res->record.recordPacking = packing;
938 srw_res->record.recordData_buf = rr.explain_buf;
939 srw_res->record.recordData_len = strlen(rr.explain_buf);
940 srw_res->record.recordPosition = 0;
946 static void srw_bend_scan(association *assoc, request *req,
947 Z_SRW_scanRequest *srw_req,
948 Z_SRW_scanResponse *srw_res,
951 yaz_log(log_requestdetail, "Got SRW ScanRequest");
954 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics);
955 if (srw_res->num_diagnostics == 0 && assoc->init)
957 struct scan_entry *save_entries;
959 bend_scan_rr *bsrr = (bend_scan_rr *)
960 odr_malloc (assoc->encode, sizeof(*bsrr));
962 bsrr->basenames = &srw_req->database;
964 bsrr->num_entries = srw_req->maximumTerms ?
965 *srw_req->maximumTerms : 10;
966 bsrr->term_position = srw_req->responsePosition ?
967 *srw_req->responsePosition : 1;
971 bsrr->referenceId = 0;
972 bsrr->stream = assoc->encode;
973 bsrr->print = assoc->print;
974 bsrr->step_size = odr_intdup(assoc->decode, 0);
977 if (bsrr->num_entries > 0)
980 bsrr->entries = odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
982 for (i = 0; i<bsrr->num_entries; i++)
984 bsrr->entries[i].term = 0;
985 bsrr->entries[i].occurrences = 0;
986 bsrr->entries[i].errcode = 0;
987 bsrr->entries[i].errstring = 0;
988 bsrr->entries[i].display_term = 0;
991 save_entries = bsrr->entries; /* save it so we can compare later */
993 if (srw_req->query_type == Z_SRW_query_type_pqf &&
994 assoc->init->bend_scan)
996 Odr_oid *scan_attributeSet = 0;
998 YAZ_PQF_Parser pqf_parser = yaz_pqf_create();
1000 bsrr->term = yaz_pqf_scan(pqf_parser, assoc->decode,
1002 srw_req->scanClause.pqf);
1003 if (scan_attributeSet &&
1004 (attset = oid_getentbyoid(scan_attributeSet)) &&
1005 (attset->oclass == CLASS_ATTSET ||
1006 attset->oclass == CLASS_GENERAL))
1007 bsrr->attributeset = attset->value;
1009 bsrr->attributeset = VAL_NONE;
1010 yaz_pqf_destroy(pqf_parser);
1011 bsrr->scanClause = 0;
1012 ((int (*)(void *, bend_scan_rr *))
1013 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1015 else if (srw_req->query_type == Z_SRW_query_type_cql
1016 && assoc->init->bend_srw_scan)
1018 if (assoc->cql_transform)
1020 bsrr->scanClause = 0;
1021 bsrr->attributeset = VAL_NONE;
1022 bsrr->term = odr_malloc(assoc->decode, sizeof(*bsrr->term));
1023 int srw_error = cql2pqf_scan(assoc->encode,
1024 srw_req->scanClause.cql,
1025 assoc->cql_transform,
1028 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1029 &srw_res->num_diagnostics,
1033 ((int (*)(void *, bend_scan_rr *))
1034 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1040 bsrr->attributeset = VAL_NONE;
1041 bsrr->scanClause = srw_req->scanClause.cql;
1042 ((int (*)(void *, bend_scan_rr *))
1043 (*assoc->init->bend_srw_scan))(assoc->backend, bsrr);
1048 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1049 &srw_res->num_diagnostics, 4, "scan");
1054 if (bsrr->errcode == 109) /* database unavailable */
1059 srw_error = yaz_diag_bib1_to_srw (bsrr->errcode);
1061 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1062 &srw_res->num_diagnostics,
1063 srw_error, bsrr->errstring);
1065 else if (srw_res->num_diagnostics == 0 && bsrr->num_entries)
1068 srw_res->terms = (Z_SRW_scanTerm*)
1069 odr_malloc(assoc->encode, sizeof(*srw_res->terms) *
1072 srw_res->num_terms = bsrr->num_entries;
1073 for (i = 0; i<bsrr->num_entries; i++)
1075 Z_SRW_scanTerm *t = srw_res->terms + i;
1076 t->value = odr_strdup(assoc->encode, bsrr->entries[i].term);
1077 t->numberOfRecords =
1078 odr_intdup(assoc->encode, bsrr->entries[i].occurrences);
1080 if (save_entries == bsrr->entries &&
1081 bsrr->entries[i].display_term)
1083 /* the entries was _not_ set by the handler. So it's
1084 safe to test for new member display_term. It is
1087 t->displayTerm = odr_strdup(assoc->encode,
1088 bsrr->entries[i].display_term);
1096 WRBUF wr = wrbuf_alloc();
1097 const char *querytype = 0;
1098 const char *querystr = 0;
1100 switch(srw_req->query_type)
1102 case Z_SRW_query_type_pqf:
1104 querystr = srw_req->scanClause.pqf;
1106 case Z_SRW_query_type_cql:
1108 querystr = srw_req->scanClause.cql;
1111 querytype = "Unknown";
1114 wrbuf_printf(wr, "SRWScan %d+%d",
1115 (srw_req->responsePosition ?
1116 *srw_req->responsePosition : 1),
1117 (srw_req->maximumTerms ?
1118 *srw_req->maximumTerms : 1));
1119 if (srw_res->num_diagnostics)
1120 wrbuf_printf(wr, " ERROR %s", srw_res->diagnostics[0].uri);
1122 wrbuf_printf(wr, " OK -");
1123 wrbuf_printf(wr, " %s: %s", querytype, querystr);
1124 yaz_log(log_request, "%s", wrbuf_buf(wr) );
1131 static void process_http_request(association *assoc, request *req)
1133 Z_HTTP_Request *hreq = req->gdu_request->u.HTTP_Request;
1134 ODR o = assoc->encode;
1135 int r = 2; /* 2=NOT TAKEN, 1=TAKEN, 0=SOAP TAKEN */
1137 Z_SOAP *soap_package = 0;
1140 Z_HTTP_Response *hres = 0;
1142 char *stylesheet = 0;
1143 Z_SRW_diagnostic *diagnostic = 0;
1144 int num_diagnostic = 0;
1145 const char *host = z_HTTP_header_lookup(hreq->headers, "Host");
1147 if (!control_association(assoc, host, 0))
1149 p = z_get_HTTP_Response(o, 404);
1152 if (r == 2 && !strcmp(hreq->path, "/test"))
1154 p = z_get_HTTP_Response(o, 200);
1155 hres = p->u.HTTP_Response;
1156 hres->content_buf = "1234567890\n";
1157 hres->content_len = strlen(hres->content_buf);
1162 r = yaz_srw_decode(hreq, &sr, &soap_package, assoc->decode, &charset);
1163 yaz_log(YLOG_DEBUG, "yaz_srw_decode returned %d", r);
1165 if (r == 2) /* not taken */
1167 r = yaz_sru_decode(hreq, &sr, &soap_package, assoc->decode, &charset,
1168 &diagnostic, &num_diagnostic);
1169 yaz_log(YLOG_DEBUG, "yaz_sru_decode returned %d", r);
1171 if (r == 0) /* decode SRW/SRU OK .. */
1173 int http_code = 200;
1174 if (sr->which == Z_SRW_searchRetrieve_request)
1177 yaz_srw_get(assoc->encode, Z_SRW_searchRetrieve_response);
1179 stylesheet = sr->u.request->stylesheet;
1182 res->u.response->diagnostics = diagnostic;
1183 res->u.response->num_diagnostics = num_diagnostic;
1187 srw_bend_search(assoc, req, sr->u.request, res->u.response,
1190 if (http_code == 200)
1191 soap_package->u.generic->p = res;
1193 else if (sr->which == Z_SRW_explain_request)
1195 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_explain_response);
1196 stylesheet = sr->u.explain_request->stylesheet;
1199 res->u.explain_response->diagnostics = diagnostic;
1200 res->u.explain_response->num_diagnostics = num_diagnostic;
1202 srw_bend_explain(assoc, req, sr->u.explain_request,
1203 res->u.explain_response, &http_code);
1204 if (http_code == 200)
1205 soap_package->u.generic->p = res;
1207 else if (sr->which == Z_SRW_scan_request)
1209 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_scan_response);
1210 stylesheet = sr->u.scan_request->stylesheet;
1213 res->u.scan_response->diagnostics = diagnostic;
1214 res->u.scan_response->num_diagnostics = num_diagnostic;
1216 srw_bend_scan(assoc, req, sr->u.scan_request,
1217 res->u.scan_response, &http_code);
1218 if (http_code == 200)
1219 soap_package->u.generic->p = res;
1223 yaz_log(log_request, "SOAP ERROR");
1224 /* FIXME - what error, what query */
1226 z_soap_error(assoc->encode, soap_package,
1227 "SOAP-ENV:Client", "Bad method", 0);
1229 if (http_code == 200 || http_code == 500)
1231 static Z_SOAP_Handler soap_handlers[3] = {
1233 {"http://www.loc.gov/zing/srw/", 0,
1234 (Z_SOAP_fun) yaz_srw_codec},
1235 {"http://www.loc.gov/zing/srw/v1.0/", 0,
1236 (Z_SOAP_fun) yaz_srw_codec},
1242 p = z_get_HTTP_Response(o, 200);
1243 hres = p->u.HTTP_Response;
1244 ret = z_soap_codec_enc_xsl(assoc->encode, &soap_package,
1245 &hres->content_buf, &hres->content_len,
1246 soap_handlers, charset, stylesheet);
1247 hres->code = http_code;
1249 strcpy(ctype, "text/xml");
1252 strcat(ctype, "; charset=");
1253 strcat(ctype, charset);
1255 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1258 p = z_get_HTTP_Response(o, http_code);
1262 p = z_get_HTTP_Response(o, 500);
1263 hres = p->u.HTTP_Response;
1264 if (!strcmp(hreq->version, "1.0"))
1266 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1267 if (v && !strcmp(v, "Keep-Alive"))
1271 hres->version = "1.0";
1275 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1276 if (v && !strcmp(v, "close"))
1280 hres->version = "1.1";
1284 z_HTTP_header_add(o, &hres->headers, "Connection", "close");
1285 assoc->state = ASSOC_DEAD;
1286 assoc->cs_get_mask = 0;
1291 const char *alive = z_HTTP_header_lookup(hreq->headers, "Keep-Alive");
1293 if (alive && isdigit(*(const unsigned char *) alive))
1297 if (t < 0 || t > 3600)
1299 iochan_settimeout(assoc->client_chan,t);
1300 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1302 process_gdu_response(assoc, req, p);
1305 static void process_gdu_request(association *assoc, request *req)
1307 if (req->gdu_request->which == Z_GDU_Z3950)
1310 req->apdu_request = req->gdu_request->u.z3950;
1311 if (process_z_request(assoc, req, &msg) < 0)
1312 do_close_req(assoc, Z_Close_systemProblem, msg, req);
1314 else if (req->gdu_request->which == Z_GDU_HTTP_Request)
1315 process_http_request(assoc, req);
1318 do_close_req(assoc, Z_Close_systemProblem, "bad protocol packet", req);
1323 * Initiate request processing.
1325 static int process_z_request(association *assoc, request *req, char **msg)
1331 *msg = "Unknown Error";
1332 assert(req && req->state == REQUEST_IDLE);
1333 if (req->apdu_request->which != Z_APDU_initRequest && !assoc->init)
1335 *msg = "Missing InitRequest";
1338 switch (req->apdu_request->which)
1340 case Z_APDU_initRequest:
1341 res = process_initRequest(assoc, req); break;
1342 case Z_APDU_searchRequest:
1343 res = process_searchRequest(assoc, req, &fd); break;
1344 case Z_APDU_presentRequest:
1345 res = process_presentRequest(assoc, req, &fd); break;
1346 case Z_APDU_scanRequest:
1347 if (assoc->init->bend_scan)
1348 res = process_scanRequest(assoc, req, &fd);
1351 *msg = "Cannot handle Scan APDU";
1355 case Z_APDU_extendedServicesRequest:
1356 if (assoc->init->bend_esrequest)
1357 res = process_ESRequest(assoc, req, &fd);
1360 *msg = "Cannot handle Extended Services APDU";
1364 case Z_APDU_sortRequest:
1365 if (assoc->init->bend_sort)
1366 res = process_sortRequest(assoc, req, &fd);
1369 *msg = "Cannot handle Sort APDU";
1374 process_close(assoc, req);
1376 case Z_APDU_deleteResultSetRequest:
1377 if (assoc->init->bend_delete)
1378 res = process_deleteRequest(assoc, req, &fd);
1381 *msg = "Cannot handle Delete APDU";
1385 case Z_APDU_segmentRequest:
1386 if (assoc->init->bend_segment)
1388 res = process_segmentRequest (assoc, req);
1392 *msg = "Cannot handle Segment APDU";
1396 case Z_APDU_triggerResourceControlRequest:
1399 *msg = "Bad APDU received";
1404 yaz_log(YLOG_DEBUG, " result immediately available");
1405 retval = process_z_response(assoc, req, res);
1409 yaz_log(YLOG_DEBUG, " result unavailble");
1412 else /* no result yet - one will be provided later */
1416 /* Set up an I/O handler for the fd supplied by the backend */
1418 yaz_log(YLOG_DEBUG, " establishing handler for result");
1419 req->state = REQUEST_PENDING;
1420 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT, 0)))
1422 iochan_setdata(chan, assoc);
1429 * Handle message from the backend.
1431 void backend_response(IOCHAN i, int event)
1433 association *assoc = (association *)iochan_getdata(i);
1434 request *req = request_head(&assoc->incoming);
1438 yaz_log(YLOG_DEBUG, "backend_response");
1439 assert(assoc && req && req->state != REQUEST_IDLE);
1440 /* determine what it is we're waiting for */
1441 switch (req->apdu_request->which)
1443 case Z_APDU_searchRequest:
1444 res = response_searchRequest(assoc, req, 0, &fd); break;
1446 case Z_APDU_presentRequest:
1447 res = response_presentRequest(assoc, req, 0, &fd); break;
1448 case Z_APDU_scanRequest:
1449 res = response_scanRequest(assoc, req, 0, &fd); break;
1452 yaz_log(YLOG_FATAL, "Serious programmer's lapse or bug");
1455 if ((res && process_z_response(assoc, req, res) < 0) || fd < 0)
1457 yaz_log(YLOG_WARN, "Fatal error when talking to backend");
1458 do_close(assoc, Z_Close_systemProblem, 0);
1462 else if (!res) /* no result yet - try again later */
1464 yaz_log(YLOG_DEBUG, " no result yet");
1465 iochan_setfd(i, fd); /* in case fd has changed */
1470 * Encode response, and transfer the request structure to the outgoing queue.
1472 static int process_gdu_response(association *assoc, request *req, Z_GDU *res)
1474 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
1478 if (!z_GDU(assoc->print, &res, 0, 0))
1479 yaz_log(YLOG_WARN, "ODR print error: %s",
1480 odr_errmsg(odr_geterror(assoc->print)));
1481 odr_reset(assoc->print);
1483 if (!z_GDU(assoc->encode, &res, 0, 0))
1485 yaz_log(YLOG_WARN, "ODR error when encoding PDU: %s [element %s]",
1486 odr_errmsg(odr_geterror(assoc->decode)),
1487 odr_getelement(assoc->decode));
1490 req->response = odr_getbuf(assoc->encode, &req->len_response,
1491 &req->size_response);
1492 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
1493 odr_reset(assoc->encode);
1494 req->state = REQUEST_IDLE;
1495 request_enq(&assoc->outgoing, req);
1496 /* turn the work over to the ir_session handler */
1497 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
1498 assoc->cs_put_mask = EVENT_OUTPUT;
1499 /* Is there more work to be done? give that to the input handler too */
1501 if (request_head(&assoc->incoming))
1503 yaz_log (YLOG_DEBUG, "more work to be done");
1504 iochan_setevent(assoc->client_chan, EVENT_WORK);
1511 * Encode response, and transfer the request structure to the outgoing queue.
1513 static int process_z_response(association *assoc, request *req, Z_APDU *res)
1515 Z_GDU *gres = (Z_GDU *) odr_malloc(assoc->encode, sizeof(*res));
1516 gres->which = Z_GDU_Z3950;
1517 gres->u.z3950 = res;
1519 return process_gdu_response(assoc, req, gres);
1522 static char *get_vhost(Z_OtherInformation *otherInfo)
1524 return yaz_oi_get_string_oidval(&otherInfo, VAL_PROXY, 1, 0);
1528 * Handle init request.
1529 * At the moment, we don't check the options
1530 * anywhere else in the code - we just try not to do anything that would
1531 * break a naive client. We'll toss 'em into the association block when
1532 * we need them there.
1534 static Z_APDU *process_initRequest(association *assoc, request *reqb)
1536 Z_InitRequest *req = reqb->apdu_request->u.initRequest;
1537 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
1538 Z_InitResponse *resp = apdu->u.initResponse;
1539 bend_initresult *binitres;
1542 statserv_options_block *cb = 0; /* by default no control for backend */
1544 if (control_association(assoc, get_vhost(req->otherInfo), 1))
1545 cb = statserv_getcontrol(); /* got control block for backend */
1547 yaz_log(log_requestdetail, "Got initRequest");
1548 if (req->implementationId)
1549 yaz_log(log_requestdetail, "Id: %s",
1550 req->implementationId);
1551 if (req->implementationName)
1552 yaz_log(log_requestdetail, "Name: %s",
1553 req->implementationName);
1554 if (req->implementationVersion)
1555 yaz_log(log_requestdetail, "Version: %s",
1556 req->implementationVersion);
1558 assoc_init_reset(assoc);
1560 assoc->init->auth = req->idAuthentication;
1561 assoc->init->referenceId = req->referenceId;
1563 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
1565 Z_CharSetandLanguageNegotiation *negotiation =
1566 yaz_get_charneg_record (req->otherInfo);
1568 negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
1569 assoc->init->charneg_request = negotiation;
1575 if (req->implementationVersion)
1576 yaz_log(log_requestdetail, "Config: %s",
1579 iochan_settimeout(assoc->client_chan, cb->idle_timeout * 60);
1581 /* we have a backend control block, so call that init function */
1582 if (!(binitres = (*cb->bend_init)(assoc->init)))
1584 yaz_log(YLOG_WARN, "Bad response from backend.");
1587 assoc->backend = binitres->handle;
1591 /* no backend. return error */
1592 binitres = odr_malloc(assoc->encode, sizeof(*binitres));
1593 binitres->errstring = 0;
1594 binitres->errcode = 1;
1595 iochan_settimeout(assoc->client_chan, 10);
1597 if ((assoc->init->bend_sort))
1598 yaz_log (YLOG_DEBUG, "Sort handler installed");
1599 if ((assoc->init->bend_search))
1600 yaz_log (YLOG_DEBUG, "Search handler installed");
1601 if ((assoc->init->bend_present))
1602 yaz_log (YLOG_DEBUG, "Present handler installed");
1603 if ((assoc->init->bend_esrequest))
1604 yaz_log (YLOG_DEBUG, "ESRequest handler installed");
1605 if ((assoc->init->bend_delete))
1606 yaz_log (YLOG_DEBUG, "Delete handler installed");
1607 if ((assoc->init->bend_scan))
1608 yaz_log (YLOG_DEBUG, "Scan handler installed");
1609 if ((assoc->init->bend_segment))
1610 yaz_log (YLOG_DEBUG, "Segment handler installed");
1612 resp->referenceId = req->referenceId;
1614 /* let's tell the client what we can do */
1615 if (ODR_MASK_GET(req->options, Z_Options_search))
1617 ODR_MASK_SET(resp->options, Z_Options_search);
1618 strcat(options, "srch");
1620 if (ODR_MASK_GET(req->options, Z_Options_present))
1622 ODR_MASK_SET(resp->options, Z_Options_present);
1623 strcat(options, " prst");
1625 if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
1626 assoc->init->bend_delete)
1628 ODR_MASK_SET(resp->options, Z_Options_delSet);
1629 strcat(options, " del");
1631 if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
1632 assoc->init->bend_esrequest)
1634 ODR_MASK_SET(resp->options, Z_Options_extendedServices);
1635 strcat (options, " extendedServices");
1637 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
1639 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
1640 strcat(options, " namedresults");
1642 if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
1644 ODR_MASK_SET(resp->options, Z_Options_scan);
1645 strcat(options, " scan");
1647 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
1649 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
1650 strcat(options, " concurrop");
1652 if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
1654 ODR_MASK_SET(resp->options, Z_Options_sort);
1655 strcat(options, " sort");
1658 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel)
1659 && assoc->init->charneg_response)
1661 Z_OtherInformation **p;
1662 Z_OtherInformationUnit *p0;
1664 yaz_oi_APDU(apdu, &p);
1666 if ((p0=yaz_oi_update(p, assoc->encode, NULL, 0, 0))) {
1667 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
1669 p0->which = Z_OtherInfo_externallyDefinedInfo;
1670 p0->information.externallyDefinedInfo =
1671 assoc->init->charneg_response;
1673 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
1674 strcat(options, " negotiation");
1677 ODR_MASK_SET(resp->options, Z_Options_triggerResourceCtrl);
1679 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
1681 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
1682 assoc->version = 1; /* 1 & 2 are equivalent */
1684 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
1686 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
1689 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
1691 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
1695 yaz_log(log_requestdetail, "Negotiated to v%d: %s", assoc->version, options);
1696 assoc->maximumRecordSize = *req->maximumRecordSize;
1698 if (cb && assoc->maximumRecordSize > cb->maxrecordsize)
1699 assoc->maximumRecordSize = cb->maxrecordsize;
1700 assoc->preferredMessageSize = *req->preferredMessageSize;
1701 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
1702 assoc->preferredMessageSize = assoc->maximumRecordSize;
1704 resp->preferredMessageSize = &assoc->preferredMessageSize;
1705 resp->maximumRecordSize = &assoc->maximumRecordSize;
1707 resp->implementationId = odr_prepend(assoc->encode,
1708 assoc->init->implementation_id,
1709 resp->implementationId);
1711 resp->implementationName = odr_prepend(assoc->encode,
1712 assoc->init->implementation_name,
1713 odr_prepend(assoc->encode, "GFS", resp->implementationName));
1715 version = odr_strdup(assoc->encode, "$Revision: 1.48 $");
1716 if (strlen(version) > 10) /* check for unexpanded CVS strings */
1717 version[strlen(version)-2] = '\0';
1718 resp->implementationVersion = odr_prepend(assoc->encode,
1719 assoc->init->implementation_version,
1720 odr_prepend(assoc->encode, &version[11],
1721 resp->implementationVersion));
1723 if (binitres->errcode)
1725 assoc->state = ASSOC_DEAD;
1726 resp->userInformationField =
1727 init_diagnostics(assoc->encode, binitres->errcode,
1728 binitres->errstring);
1733 WRBUF wr = wrbuf_alloc();
1734 wrbuf_printf(wr, "Init ");
1735 if (binitres->errcode)
1736 wrbuf_printf(wr, "ERROR %d", binitres->errcode);
1738 wrbuf_printf(wr, "OK -");
1739 wrbuf_printf(wr, " ID:%s Name:%s Version:%s",
1740 (req->implementationId ? req->implementationId :"-"),
1741 (req->implementationName ?
1742 req->implementationName : "-"),
1743 (req->implementationVersion ?
1744 req->implementationVersion : "-")
1746 yaz_log(log_request, "%s", wrbuf_buf(wr));
1753 * Set the specified `errcode' and `errstring' into a UserInfo-1
1754 * external to be returned to the client in accordance with Z35.90
1755 * Implementor Agreement 5 (Returning diagnostics in an InitResponse):
1756 * http://lcweb.loc.gov/z3950/agency/agree/initdiag.html
1758 static Z_External *init_diagnostics(ODR odr, int error, const char *addinfo)
1760 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
1761 addinfo ? " -- " : "", addinfo ? addinfo : "");
1762 return zget_init_diagnostics(odr, error, addinfo);
1766 * nonsurrogate diagnostic record.
1768 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
1770 Z_Records *rec = (Z_Records *) odr_malloc (assoc->encode, sizeof(*rec));
1772 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
1773 addinfo ? " -- " : "", addinfo ? addinfo : "");
1775 rec->which = Z_Records_NSD;
1776 rec->u.nonSurrogateDiagnostic = zget_DefaultDiagFormat(assoc->encode,
1782 * surrogate diagnostic.
1784 static Z_NamePlusRecord *surrogatediagrec(association *assoc,
1786 int error, const char *addinfo)
1788 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
1789 addinfo ? " -- " : "", addinfo ? addinfo : "");
1790 return zget_surrogateDiagRec(assoc->encode, dbname, error, addinfo);
1793 static Z_Records *pack_records(association *a, char *setname, int start,
1794 int *num, Z_RecordComposition *comp,
1795 int *next, int *pres, oid_value format,
1796 Z_ReferenceId *referenceId,
1797 int *oid, int *errcode)
1799 int recno, total_length = 0, toget = *num, dumped_records = 0;
1800 Z_Records *records =
1801 (Z_Records *) odr_malloc (a->encode, sizeof(*records));
1802 Z_NamePlusRecordList *reclist =
1803 (Z_NamePlusRecordList *) odr_malloc (a->encode, sizeof(*reclist));
1804 Z_NamePlusRecord **list =
1805 (Z_NamePlusRecord **) odr_malloc (a->encode, sizeof(*list) * toget);
1807 records->which = Z_Records_DBOSD;
1808 records->u.databaseOrSurDiagnostics = reclist;
1809 reclist->num_records = 0;
1810 reclist->records = list;
1811 *pres = Z_PresentStatus_success;
1815 yaz_log(log_requestdetail, "Request to pack %d+%d %s", start, toget, setname);
1816 yaz_log(log_requestdetail, "pms=%d, mrs=%d", a->preferredMessageSize,
1817 a->maximumRecordSize);
1818 for (recno = start; reclist->num_records < toget; recno++)
1821 Z_NamePlusRecord *thisrec;
1822 int this_length = 0;
1824 * we get the number of bytes allocated on the stream before any
1825 * allocation done by the backend - this should give us a reasonable
1826 * idea of the total size of the data so far.
1828 total_length = odr_total(a->encode) - dumped_records;
1834 freq.last_in_set = 0;
1835 freq.setname = setname;
1836 freq.surrogate_flag = 0;
1837 freq.number = recno;
1839 freq.request_format = format;
1840 freq.request_format_raw = oid;
1841 freq.output_format = format;
1842 freq.output_format_raw = 0;
1843 freq.stream = a->encode;
1844 freq.print = a->print;
1845 freq.referenceId = referenceId;
1847 (*a->init->bend_fetch)(a->backend, &freq);
1848 /* backend should be able to signal whether error is system-wide
1849 or only pertaining to current record */
1852 if (!freq.surrogate_flag)
1855 *pres = Z_PresentStatus_failure;
1856 /* for 'present request out of range',
1857 set addinfo to record position if not set */
1858 if (freq.errcode == 13 && freq.errstring == 0)
1860 sprintf (s, "%d", recno);
1864 *errcode = freq.errcode;
1865 return diagrec(a, freq.errcode, freq.errstring);
1867 reclist->records[reclist->num_records] =
1868 surrogatediagrec(a, freq.basename, freq.errcode,
1870 reclist->num_records++;
1871 *next = freq.last_in_set ? 0 : recno + 1;
1875 this_length = freq.len;
1877 this_length = odr_total(a->encode) - total_length - dumped_records;
1878 yaz_log(YLOG_DEBUG, " fetched record, len=%d, total=%d dumped=%d",
1879 this_length, total_length, dumped_records);
1880 if (a->preferredMessageSize > 0 &&
1881 this_length + total_length > a->preferredMessageSize)
1883 /* record is small enough, really */
1884 if (this_length <= a->preferredMessageSize && recno > start)
1886 yaz_log(log_requestdetail, " Dropped last normal-sized record");
1887 *pres = Z_PresentStatus_partial_2;
1890 /* record can only be fetched by itself */
1891 if (this_length < a->maximumRecordSize)
1893 yaz_log(log_requestdetail, " Record > prefmsgsz");
1896 yaz_log(YLOG_DEBUG, " Dropped it");
1897 reclist->records[reclist->num_records] =
1898 surrogatediagrec(a, freq.basename, 16, 0);
1899 reclist->num_records++;
1900 *next = freq.last_in_set ? 0 : recno + 1;
1901 dumped_records += this_length;
1905 else /* too big entirely */
1907 yaz_log(log_requestdetail, "Record > maxrcdsz this=%d max=%d",
1908 this_length, a->maximumRecordSize);
1909 reclist->records[reclist->num_records] =
1910 surrogatediagrec(a, freq.basename, 17, 0);
1911 reclist->num_records++;
1912 *next = freq.last_in_set ? 0 : recno + 1;
1913 dumped_records += this_length;
1918 if (!(thisrec = (Z_NamePlusRecord *)
1919 odr_malloc(a->encode, sizeof(*thisrec))))
1921 if (!(thisrec->databaseName = (char *)odr_malloc(a->encode,
1922 strlen(freq.basename) + 1)))
1924 strcpy(thisrec->databaseName, freq.basename);
1925 thisrec->which = Z_NamePlusRecord_databaseRecord;
1927 if (freq.output_format_raw)
1929 struct oident *ident = oid_getentbyoid(freq.output_format_raw);
1930 freq.output_format = ident->value;
1932 thisrec->u.databaseRecord = z_ext_record(a->encode, freq.output_format,
1933 freq.record, freq.len);
1934 if (!thisrec->u.databaseRecord)
1936 reclist->records[reclist->num_records] = thisrec;
1937 reclist->num_records++;
1938 *next = freq.last_in_set ? 0 : recno + 1;
1940 *num = reclist->num_records;
1944 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
1947 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
1948 bend_search_rr *bsrr =
1949 (bend_search_rr *)nmem_malloc (reqb->request_mem, sizeof(*bsrr));
1951 yaz_log(log_requestdetail, "Got SearchRequest.");
1953 bsrr->request = reqb;
1954 bsrr->association = assoc;
1955 bsrr->referenceId = req->referenceId;
1956 save_referenceId (reqb, bsrr->referenceId);
1958 yaz_log (log_requestdetail, "ResultSet '%s'", req->resultSetName);
1959 if (req->databaseNames)
1962 for (i = 0; i < req->num_databaseNames; i++)
1963 yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
1966 yaz_log_zquery_level(log_requestdetail,req->query);
1968 if (assoc->init->bend_search)
1970 bsrr->setname = req->resultSetName;
1971 bsrr->replace_set = *req->replaceIndicator;
1972 bsrr->num_bases = req->num_databaseNames;
1973 bsrr->basenames = req->databaseNames;
1974 bsrr->query = req->query;
1975 bsrr->stream = assoc->encode;
1976 nmem_transfer(bsrr->stream->mem, reqb->request_mem);
1977 bsrr->decode = assoc->decode;
1978 bsrr->print = assoc->print;
1981 bsrr->errstring = NULL;
1982 bsrr->search_info = NULL;
1984 if (assoc->cql_transform &&
1985 req->query->which == Z_Query_type_104 &&
1986 req->query->u.type_104->which == Z_External_CQL)
1988 /* have a CQL query and a CQL to PQF transform .. */
1990 cql2pqf(bsrr->stream, req->query->u.type_104->u.cql,
1991 assoc->cql_transform, bsrr->query);
1993 bsrr->errcode = yaz_diag_srw_to_bib1(srw_errcode);
1996 (assoc->init->bend_search)(assoc->backend, bsrr);
1997 if (!bsrr->request) /* backend not ready with the search response */
1998 return 0; /* should not be used any more */
2002 /* FIXME - make a diagnostic for it */
2003 yaz_log(YLOG_WARN,"Search not supported ?!?!");
2005 return response_searchRequest(assoc, reqb, bsrr, fd);
2008 int bend_searchresponse(void *handle, bend_search_rr *bsrr) {return 0;}
2011 * Prepare a searchresponse based on the backend results. We probably want
2012 * to look at making the fetching of records nonblocking as well, but
2013 * so far, we'll keep things simple.
2014 * If bsrt is null, that means we're called in response to a communications
2015 * event, and we'll have to get the response for ourselves.
2017 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
2018 bend_search_rr *bsrt, int *fd)
2020 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2021 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2022 Z_SearchResponse *resp = (Z_SearchResponse *)
2023 odr_malloc (assoc->encode, sizeof(*resp));
2024 int *nulint = odr_intdup (assoc->encode, 0);
2025 bool_t *sr = odr_intdup(assoc->encode, 1);
2026 int *next = odr_intdup(assoc->encode, 0);
2027 int *none = odr_intdup(assoc->encode, Z_SearchResponse_none);
2030 apdu->which = Z_APDU_searchResponse;
2031 apdu->u.searchResponse = resp;
2032 resp->referenceId = req->referenceId;
2033 resp->additionalSearchInfo = 0;
2034 resp->otherInfo = 0;
2036 if (!bsrt && !bend_searchresponse(assoc->backend, bsrt))
2038 yaz_log(YLOG_FATAL, "Bad result from backend");
2041 else if (bsrt->errcode)
2043 resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
2044 resp->resultCount = nulint;
2045 resp->numberOfRecordsReturned = nulint;
2046 resp->nextResultSetPosition = nulint;
2047 resp->searchStatus = nulint;
2048 resp->resultSetStatus = none;
2049 resp->presentStatus = 0;
2053 int *toget = odr_intdup(assoc->encode, 0);
2054 int *presst = odr_intdup(assoc->encode, 0);
2055 Z_RecordComposition comp, *compp = 0;
2057 yaz_log (log_requestdetail, "resultCount: %d", bsrt->hits);
2060 resp->resultCount = &bsrt->hits;
2062 comp.which = Z_RecordComp_simple;
2063 /* how many records does the user agent want, then? */
2064 if (bsrt->hits <= *req->smallSetUpperBound)
2066 *toget = bsrt->hits;
2067 if ((comp.u.simple = req->smallSetElementSetNames))
2070 else if (bsrt->hits < *req->largeSetLowerBound)
2072 *toget = *req->mediumSetPresentNumber;
2073 if (*toget > bsrt->hits)
2074 *toget = bsrt->hits;
2075 if ((comp.u.simple = req->mediumSetElementSetNames))
2081 if (*toget && !resp->records)
2086 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
2089 form = prefformat->value;
2090 resp->records = pack_records(assoc, req->resultSetName, 1,
2091 toget, compp, next, presst, form, req->referenceId,
2092 req->preferredRecordSyntax, NULL);
2095 resp->numberOfRecordsReturned = toget;
2096 returnedrecs = *toget;
2097 resp->nextResultSetPosition = next;
2098 resp->searchStatus = sr;
2099 resp->resultSetStatus = 0;
2100 resp->presentStatus = presst;
2104 if (*resp->resultCount)
2106 resp->numberOfRecordsReturned = nulint;
2107 resp->nextResultSetPosition = next;
2108 resp->searchStatus = sr;
2109 resp->resultSetStatus = 0;
2110 resp->presentStatus = 0;
2113 resp->additionalSearchInfo = bsrt->search_info;
2117 WRBUF wr = wrbuf_alloc();
2119 wrbuf_printf(wr, "ERROR %d", bsrt->errcode);
2121 wrbuf_printf(wr, "OK %d", bsrt->hits);
2122 wrbuf_printf(wr, " %s 1+%d ",
2123 req->resultSetName, returnedrecs);
2124 wrbuf_put_zquery(wr, req->query);
2126 yaz_log(log_request, "Search %s", wrbuf_buf(wr));
2133 * Maybe we got a little over-friendly when we designed bend_fetch to
2134 * get only one record at a time. Some backends can optimise multiple-record
2135 * fetches, and at any rate, there is some overhead involved in
2136 * all that selecting and hopping around. Problem is, of course, that the
2137 * frontend can't know ahead of time how many records it'll need to
2138 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
2139 * is downright lousy as a bulk data transfer protocol.
2141 * To start with, we'll do the fetching of records from the backend
2142 * in one operation: To save some trips in and out of the event-handler,
2143 * and to simplify the interface to pack_records. At any rate, asynch
2144 * operation is more fun in operations that have an unpredictable execution
2145 * speed - which is normally more true for search than for present.
2147 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
2150 Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
2154 Z_PresentResponse *resp;
2158 const char *errstring = 0;
2160 yaz_log(log_requestdetail, "Got PresentRequest.");
2162 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
2165 form = prefformat->value;
2166 resp = (Z_PresentResponse *)odr_malloc (assoc->encode, sizeof(*resp));
2168 resp->presentStatus = odr_intdup(assoc->encode, 0);
2169 if (assoc->init->bend_present)
2171 bend_present_rr *bprr = (bend_present_rr *)
2172 nmem_malloc (reqb->request_mem, sizeof(*bprr));
2173 bprr->setname = req->resultSetId;
2174 bprr->start = *req->resultSetStartPoint;
2175 bprr->number = *req->numberOfRecordsRequested;
2176 bprr->format = form;
2177 bprr->comp = req->recordComposition;
2178 bprr->referenceId = req->referenceId;
2179 bprr->stream = assoc->encode;
2180 bprr->print = assoc->print;
2181 bprr->request = reqb;
2182 bprr->association = assoc;
2184 bprr->errstring = NULL;
2185 (*assoc->init->bend_present)(assoc->backend, bprr);
2188 return 0; /* should not happen */
2191 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2192 *resp->presentStatus = Z_PresentStatus_failure;
2193 errcode = bprr->errcode;
2194 errstring = bprr->errstring;
2197 apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2198 next = odr_intdup(assoc->encode, 0);
2199 num = odr_intdup(assoc->encode, 0);
2201 apdu->which = Z_APDU_presentResponse;
2202 apdu->u.presentResponse = resp;
2203 resp->referenceId = req->referenceId;
2204 resp->otherInfo = 0;
2208 *num = *req->numberOfRecordsRequested;
2210 pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
2211 num, req->recordComposition, next,
2212 resp->presentStatus,
2213 form, req->referenceId, req->preferredRecordSyntax,
2218 WRBUF wr = wrbuf_alloc();
2219 wrbuf_printf(wr, "Present ");
2221 if (*resp->presentStatus == Z_PresentStatus_failure)
2222 wrbuf_printf(wr, "ERROR %d", errcode);
2223 else if (*resp->presentStatus == Z_PresentStatus_success)
2224 wrbuf_printf(wr, "OK -");
2226 wrbuf_printf(wr, "Partial %d", *resp->presentStatus);
2228 wrbuf_printf(wr, " %s %d+%d ",
2229 req->resultSetId, *req->resultSetStartPoint,
2230 *req->numberOfRecordsRequested);
2231 yaz_log(log_request, "%s", wrbuf_buf(wr) );
2236 resp->numberOfRecordsReturned = num;
2237 resp->nextResultSetPosition = next;
2243 * Scan was implemented rather in a hurry, and with support for only the basic
2244 * elements of the service in the backend API. Suggestions are welcome.
2246 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
2248 Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
2249 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2250 Z_ScanResponse *res = (Z_ScanResponse *)
2251 odr_malloc (assoc->encode, sizeof(*res));
2252 int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
2253 int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
2254 Z_ListEntries *ents = (Z_ListEntries *)
2255 odr_malloc (assoc->encode, sizeof(*ents));
2256 Z_DiagRecs *diagrecs_p = NULL;
2258 bend_scan_rr *bsrr = (bend_scan_rr *)
2259 odr_malloc (assoc->encode, sizeof(*bsrr));
2260 struct scan_entry *save_entries;
2262 yaz_log(log_requestdetail, "Got ScanRequest");
2264 apdu->which = Z_APDU_scanResponse;
2265 apdu->u.scanResponse = res;
2266 res->referenceId = req->referenceId;
2268 /* if step is absent, set it to 0 */
2269 res->stepSize = odr_intdup(assoc->encode, 0);
2271 *res->stepSize = *req->stepSize;
2273 res->scanStatus = scanStatus;
2274 res->numberOfEntriesReturned = numberOfEntriesReturned;
2275 res->positionOfTerm = 0;
2276 res->entries = ents;
2277 ents->num_entries = 0;
2278 ents->entries = NULL;
2279 ents->num_nonsurrogateDiagnostics = 0;
2280 ents->nonsurrogateDiagnostics = NULL;
2281 res->attributeSet = 0;
2284 if (req->databaseNames)
2287 for (i = 0; i < req->num_databaseNames; i++)
2288 yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
2290 yaz_log(log_requestdetail, "pos %d step %d entries %d",
2291 *req->preferredPositionInResponse, *res->stepSize,
2292 *req->numberOfTermsRequested);
2293 bsrr->num_bases = req->num_databaseNames;
2294 bsrr->basenames = req->databaseNames;
2295 bsrr->num_entries = *req->numberOfTermsRequested;
2296 bsrr->term = req->termListAndStartPoint;
2297 bsrr->referenceId = req->referenceId;
2298 bsrr->stream = assoc->encode;
2299 bsrr->print = assoc->print;
2300 bsrr->step_size = res->stepSize;
2302 /* For YAZ 2.0 and earlier it was the backend handler that
2303 initialized entries (member display_term did not exist)
2304 YAZ 2.0 and later sets 'entries' and initialize all members
2305 including 'display_term'. If YAZ 2.0 or later sees that
2306 entries was modified - we assume that it is an old handler and
2307 that 'display_term' is _not_ set.
2309 if (bsrr->num_entries > 0)
2312 bsrr->entries = odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
2314 for (i = 0; i<bsrr->num_entries; i++)
2316 bsrr->entries[i].term = 0;
2317 bsrr->entries[i].occurrences = 0;
2318 bsrr->entries[i].errcode = 0;
2319 bsrr->entries[i].errstring = 0;
2320 bsrr->entries[i].display_term = 0;
2323 save_entries = bsrr->entries; /* save it so we can compare later */
2325 if (req->attributeSet &&
2326 (attset = oid_getentbyoid(req->attributeSet)) &&
2327 (attset->oclass == CLASS_ATTSET || attset->oclass == CLASS_GENERAL))
2328 bsrr->attributeset = attset->value;
2330 bsrr->attributeset = VAL_NONE;
2331 log_scan_term_level (log_requestdetail, req->termListAndStartPoint,
2332 bsrr->attributeset);
2333 bsrr->term_position = req->preferredPositionInResponse ?
2334 *req->preferredPositionInResponse : 1;
2336 ((int (*)(void *, bend_scan_rr *))
2337 (*assoc->init->bend_scan))(assoc->backend, bsrr);
2340 diagrecs_p = zget_DiagRecs(assoc->encode,
2341 bsrr->errcode, bsrr->errstring);
2345 Z_Entry **tab = (Z_Entry **)
2346 odr_malloc (assoc->encode, sizeof(*tab) * bsrr->num_entries);
2348 if (bsrr->status == BEND_SCAN_PARTIAL)
2349 *scanStatus = Z_Scan_partial_5;
2351 *scanStatus = Z_Scan_success;
2352 ents->entries = tab;
2353 ents->num_entries = bsrr->num_entries;
2354 res->numberOfEntriesReturned = &ents->num_entries;
2355 res->positionOfTerm = &bsrr->term_position;
2356 for (i = 0; i < bsrr->num_entries; i++)
2362 tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
2363 if (bsrr->entries[i].occurrences >= 0)
2365 e->which = Z_Entry_termInfo;
2366 e->u.termInfo = t = (Z_TermInfo *)
2367 odr_malloc(assoc->encode, sizeof(*t));
2368 t->suggestedAttributes = 0;
2370 if (save_entries == bsrr->entries &&
2371 bsrr->entries[i].display_term)
2373 /* the entries was _not_ set by the handler. So it's
2374 safe to test for new member display_term. It is
2377 t->displayTerm = odr_strdup(assoc->encode,
2378 bsrr->entries[i].display_term);
2380 t->alternativeTerm = 0;
2381 t->byAttributes = 0;
2382 t->otherTermInfo = 0;
2383 t->globalOccurrences = &bsrr->entries[i].occurrences;
2384 t->term = (Z_Term *)
2385 odr_malloc(assoc->encode, sizeof(*t->term));
2386 t->term->which = Z_Term_general;
2387 t->term->u.general = o =
2388 (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
2389 o->buf = (unsigned char *)
2390 odr_malloc(assoc->encode, o->len = o->size =
2391 strlen(bsrr->entries[i].term));
2392 memcpy(o->buf, bsrr->entries[i].term, o->len);
2393 yaz_log(YLOG_DEBUG, " term #%d: '%s' (%d)", i,
2394 bsrr->entries[i].term, bsrr->entries[i].occurrences);
2398 Z_DiagRecs *drecs = zget_DiagRecs(assoc->encode,
2399 bsrr->entries[i].errcode,
2400 bsrr->entries[i].errstring);
2401 assert (drecs->num_diagRecs == 1);
2402 e->which = Z_Entry_surrogateDiagnostic;
2403 assert (drecs->diagRecs[0]);
2404 e->u.surrogateDiagnostic = drecs->diagRecs[0];
2410 ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
2411 ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
2415 WRBUF wr = wrbuf_alloc();
2417 wr_diag(wr, bsrr->errcode, bsrr->errstring);
2418 else if (*res->scanStatus == Z_Scan_success)
2419 wrbuf_printf(wr, "OK");
2421 wrbuf_printf(wr, "Partial");
2423 wrbuf_printf(wr, " %d+%d %d ",
2424 *req->preferredPositionInResponse,
2425 *req->numberOfTermsRequested,
2426 (res->stepSize ? *res->stepSize : 0));
2427 wrbuf_scan_term(wr, req->termListAndStartPoint,
2428 bsrr->attributeset);
2430 yaz_log(log_request, "Scan %s", wrbuf_buf(wr) );
2436 static Z_APDU *process_sortRequest(association *assoc, request *reqb,
2440 Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
2441 Z_SortResponse *res = (Z_SortResponse *)
2442 odr_malloc (assoc->encode, sizeof(*res));
2443 bend_sort_rr *bsrr = (bend_sort_rr *)
2444 odr_malloc (assoc->encode, sizeof(*bsrr));
2446 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2448 yaz_log(log_requestdetail, "Got SortRequest.");
2450 bsrr->num_input_setnames = req->num_inputResultSetNames;
2451 for (i=0;i<req->num_inputResultSetNames;i++)
2452 yaz_log(log_requestdetail, "Input resultset: '%s'",
2453 req->inputResultSetNames[i]);
2454 bsrr->input_setnames = req->inputResultSetNames;
2455 bsrr->referenceId = req->referenceId;
2456 bsrr->output_setname = req->sortedResultSetName;
2457 yaz_log(log_requestdetail, "Output resultset: '%s'",
2458 req->sortedResultSetName);
2459 bsrr->sort_sequence = req->sortSequence;
2460 /*FIXME - dump those sequences too */
2461 bsrr->stream = assoc->encode;
2462 bsrr->print = assoc->print;
2464 bsrr->sort_status = Z_SortResponse_failure;
2466 bsrr->errstring = 0;
2468 (*assoc->init->bend_sort)(assoc->backend, bsrr);
2470 res->referenceId = bsrr->referenceId;
2471 res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
2472 res->resultSetStatus = 0;
2475 Z_DiagRecs *dr = zget_DiagRecs(assoc->encode,
2476 bsrr->errcode, bsrr->errstring);
2477 res->diagnostics = dr->diagRecs;
2478 res->num_diagnostics = dr->num_diagRecs;
2482 res->num_diagnostics = 0;
2483 res->diagnostics = 0;
2485 res->resultCount = 0;
2488 apdu->which = Z_APDU_sortResponse;
2489 apdu->u.sortResponse = res;
2492 WRBUF wr = wrbuf_alloc();
2493 wrbuf_printf(wr, "Sort ");
2495 wrbuf_printf(wr, " ERROR %d", bsrr->errcode);
2497 wrbuf_printf(wr, "OK -");
2498 wrbuf_printf(wr, " (");
2499 for (i = 0; i<req->num_inputResultSetNames; i++)
2502 wrbuf_printf(wr, ",");
2503 wrbuf_printf(wr, req->inputResultSetNames[i]);
2505 wrbuf_printf(wr, ")->%s ",req->sortedResultSetName);
2507 yaz_log(log_request, "%s", wrbuf_buf(wr) );
2513 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
2517 Z_DeleteResultSetRequest *req =
2518 reqb->apdu_request->u.deleteResultSetRequest;
2519 Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
2520 odr_malloc (assoc->encode, sizeof(*res));
2521 bend_delete_rr *bdrr = (bend_delete_rr *)
2522 odr_malloc (assoc->encode, sizeof(*bdrr));
2523 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2525 yaz_log(log_requestdetail, "Got DeleteRequest.");
2527 bdrr->num_setnames = req->num_resultSetList;
2528 bdrr->setnames = req->resultSetList;
2529 for (i = 0; i<req->num_resultSetList; i++)
2530 yaz_log(log_requestdetail, "resultset: '%s'",
2531 req->resultSetList[i]);
2532 bdrr->stream = assoc->encode;
2533 bdrr->print = assoc->print;
2534 bdrr->function = *req->deleteFunction;
2535 bdrr->referenceId = req->referenceId;
2537 if (bdrr->num_setnames > 0)
2539 bdrr->statuses = (int*)
2540 odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
2541 bdrr->num_setnames);
2542 for (i = 0; i < bdrr->num_setnames; i++)
2543 bdrr->statuses[i] = 0;
2545 (*assoc->init->bend_delete)(assoc->backend, bdrr);
2547 res->referenceId = req->referenceId;
2549 res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
2551 res->deleteListStatuses = 0;
2552 if (bdrr->num_setnames > 0)
2555 res->deleteListStatuses = (Z_ListStatuses *)
2556 odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
2557 res->deleteListStatuses->num = bdrr->num_setnames;
2558 res->deleteListStatuses->elements =
2560 odr_malloc (assoc->encode,
2561 sizeof(*res->deleteListStatuses->elements) *
2562 bdrr->num_setnames);
2563 for (i = 0; i<bdrr->num_setnames; i++)
2565 res->deleteListStatuses->elements[i] =
2567 odr_malloc (assoc->encode,
2568 sizeof(**res->deleteListStatuses->elements));
2569 res->deleteListStatuses->elements[i]->status = bdrr->statuses+i;
2570 res->deleteListStatuses->elements[i]->id =
2571 odr_strdup (assoc->encode, bdrr->setnames[i]);
2574 res->numberNotDeleted = 0;
2575 res->bulkStatuses = 0;
2576 res->deleteMessage = 0;
2579 apdu->which = Z_APDU_deleteResultSetResponse;
2580 apdu->u.deleteResultSetResponse = res;
2583 WRBUF wr = wrbuf_alloc();
2584 wrbuf_printf(wr, "Delete ");
2585 if (bdrr->delete_status)
2586 wrbuf_printf(wr, "ERROR %d", bdrr->delete_status);
2588 wrbuf_printf(wr, "OK -");
2589 for (i = 0; i<req->num_resultSetList; i++)
2590 wrbuf_printf(wr, " %s ", req->resultSetList[i]);
2591 yaz_log(log_request, "%s", wrbuf_buf(wr) );
2597 static void process_close(association *assoc, request *reqb)
2599 Z_Close *req = reqb->apdu_request->u.close;
2600 static char *reasons[] =
2607 "securityViolation",
2614 yaz_log(log_requestdetail, "Got Close, reason %s, message %s",
2615 reasons[*req->closeReason], req->diagnosticInformation ?
2616 req->diagnosticInformation : "NULL");
2617 if (assoc->version < 3) /* to make do_force respond with close */
2619 do_close_req(assoc, Z_Close_finished,
2620 "Association terminated by client", reqb);
2621 yaz_log(log_request,"Close OK");
2624 void save_referenceId (request *reqb, Z_ReferenceId *refid)
2628 reqb->len_refid = refid->len;
2629 reqb->refid = (char *)nmem_malloc (reqb->request_mem, refid->len);
2630 memcpy (reqb->refid, refid->buf, refid->len);
2634 reqb->len_refid = 0;
2639 void bend_request_send (bend_association a, bend_request req, Z_APDU *res)
2641 process_z_response (a, req, res);
2644 bend_request bend_request_mk (bend_association a)
2646 request *nreq = request_get (&a->outgoing);
2647 nreq->request_mem = nmem_create ();
2651 Z_ReferenceId *bend_request_getid (ODR odr, bend_request req)
2656 id = (Odr_oct *)odr_malloc (odr, sizeof(*odr));
2657 id->buf = (unsigned char *)odr_malloc (odr, req->len_refid);
2658 id->len = id->size = req->len_refid;
2659 memcpy (id->buf, req->refid, req->len_refid);
2663 void bend_request_destroy (bend_request *req)
2665 nmem_destroy((*req)->request_mem);
2666 request_release(*req);
2670 int bend_backend_respond (bend_association a, bend_request req)
2674 r = process_z_request (a, req, &msg);
2676 yaz_log (YLOG_WARN, "%s", msg);
2680 void bend_request_setdata(bend_request r, void *p)
2685 void *bend_request_getdata(bend_request r)
2687 return r->clientData;
2690 static Z_APDU *process_segmentRequest (association *assoc, request *reqb)
2692 bend_segment_rr req;
2694 req.segment = reqb->apdu_request->u.segmentRequest;
2695 req.stream = assoc->encode;
2696 req.decode = assoc->decode;
2697 req.print = assoc->print;
2698 req.association = assoc;
2700 (*assoc->init->bend_segment)(assoc->backend, &req);
2705 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd)
2707 bend_esrequest_rr esrequest;
2709 Z_ExtendedServicesRequest *req =
2710 reqb->apdu_request->u.extendedServicesRequest;
2711 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
2713 Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
2715 yaz_log(log_requestdetail,"Got EsRequest");
2717 esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
2718 esrequest.stream = assoc->encode;
2719 esrequest.decode = assoc->decode;
2720 esrequest.print = assoc->print;
2721 esrequest.errcode = 0;
2722 esrequest.errstring = NULL;
2723 esrequest.request = reqb;
2724 esrequest.association = assoc;
2725 esrequest.taskPackage = 0;
2726 esrequest.referenceId = req->referenceId;
2728 (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
2730 /* If the response is being delayed, return NULL */
2731 if (esrequest.request == NULL)
2734 resp->referenceId = req->referenceId;
2736 if (esrequest.errcode == -1)
2738 /* Backend service indicates request will be processed */
2739 yaz_log(log_request,"EsRequest OK: Accepted !");
2740 *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
2742 else if (esrequest.errcode == 0)
2744 /* Backend service indicates request will be processed */
2745 yaz_log(log_request,"EsRequest OK: Done !");
2746 *resp->operationStatus = Z_ExtendedServicesResponse_done;
2750 Z_DiagRecs *diagRecs =
2751 zget_DiagRecs(assoc->encode, esrequest.errcode,
2752 esrequest.errstring);
2753 /* Backend indicates error, request will not be processed */
2754 yaz_log(YLOG_DEBUG,"Request could not be processed...failure !");
2755 *resp->operationStatus = Z_ExtendedServicesResponse_failure;
2756 resp->num_diagnostics = diagRecs->num_diagRecs;
2757 resp->diagnostics = diagRecs->diagRecs;
2760 WRBUF wr = wrbuf_alloc();
2761 wrbuf_diags(wr, resp->num_diagnostics, resp->diagnostics);
2762 yaz_log(log_request, "EsRequest %s", wrbuf_buf(wr) );
2767 /* Do something with the members of bend_extendedservice */
2768 if (esrequest.taskPackage)
2769 resp->taskPackage = z_ext_record (assoc->encode, VAL_EXTENDED,
2770 (const char *) esrequest.taskPackage,
2772 yaz_log(YLOG_DEBUG,"Send the result apdu");