2 * Copyright (C) 1995-2005, Index Data ApS
3 * See the file LICENSE for details.
5 * $Id: seshigh.c,v 1.47 2005-02-01 14:46:47 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);
184 * Free association and release resources.
186 void destroy_association(association *h)
188 statserv_options_block *cb = statserv_getcontrol();
192 odr_destroy(h->decode);
193 odr_destroy(h->encode);
195 odr_destroy(h->print);
197 xfree(h->input_buffer);
199 (*cb->bend_close)(h->backend);
200 while ((req = request_deq(&h->incoming)))
201 request_release(req);
202 while ((req = request_deq(&h->outgoing)))
203 request_release(req);
204 request_delq(&h->incoming);
205 request_delq(&h->outgoing);
207 xmalloc_trav("session closed");
208 if (cb && cb->one_shot)
214 static void do_close_req(association *a, int reason, char *message,
218 Z_Close *cls = zget_Close(a->encode);
220 /* Purge request queue */
221 while (request_deq(&a->incoming));
222 while (request_deq(&a->outgoing));
225 yaz_log(log_requestdetail, "Sending Close PDU, reason=%d, message=%s",
226 reason, message ? message : "none");
227 apdu.which = Z_APDU_close;
229 *cls->closeReason = reason;
230 cls->diagnosticInformation = message;
231 process_z_response(a, req, &apdu);
232 iochan_settimeout(a->client_chan, 20);
236 request_release(req);
237 yaz_log(log_requestdetail, "v2 client. No Close PDU");
238 iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
240 a->state = ASSOC_DEAD;
243 static void do_close(association *a, int reason, char *message)
245 request *req = request_get(&a->outgoing);
246 do_close_req (a, reason, message, req);
250 * This is where PDUs from the client are read and the further
251 * processing is initiated. Flow of control moves down through the
252 * various process_* functions below, until the encoded result comes back up
253 * to the output handler in here.
255 * h : the I/O channel that has an outstanding event.
256 * event : the current outstanding event.
258 void ir_session(IOCHAN h, int event)
261 association *assoc = (association *)iochan_getdata(h);
262 COMSTACK conn = assoc->client_link;
265 assert(h && conn && assoc);
266 if (event == EVENT_TIMEOUT)
268 if (assoc->state != ASSOC_UP)
270 yaz_log(YLOG_DEBUG, "Final timeout - closing connection.");
271 /* do we need to lod this at all */
273 destroy_association(assoc);
278 yaz_log(log_session, "Session idle too long. Sending close.");
279 do_close(assoc, Z_Close_lackOfActivity, 0);
283 if (event & assoc->cs_accept_mask)
285 if (!cs_accept (conn))
287 yaz_log (YLOG_WARN, "accept failed");
288 destroy_association(assoc);
291 iochan_clearflag (h, EVENT_OUTPUT);
292 if (conn->io_pending)
293 { /* cs_accept didn't complete */
294 assoc->cs_accept_mask =
295 ((conn->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
296 ((conn->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
298 iochan_setflag (h, assoc->cs_accept_mask);
301 { /* cs_accept completed. Prepare for reading (cs_get) */
302 assoc->cs_accept_mask = 0;
303 assoc->cs_get_mask = EVENT_INPUT;
304 iochan_setflag (h, assoc->cs_get_mask);
308 if ((event & assoc->cs_get_mask) || (event & EVENT_WORK)) /* input */
310 if ((assoc->cs_put_mask & EVENT_INPUT) == 0 && (event & assoc->cs_get_mask))
312 yaz_log(YLOG_DEBUG, "ir_session (input)");
313 /* We aren't speaking to this fellow */
314 if (assoc->state == ASSOC_DEAD)
316 yaz_log(log_session, "Connection closed - end of session");
318 destroy_association(assoc);
322 assoc->cs_get_mask = EVENT_INPUT;
323 if ((res = cs_get(conn, &assoc->input_buffer,
324 &assoc->input_buffer_len)) <= 0)
326 yaz_log(log_session, "Connection closed by client");
328 destroy_association(assoc);
332 else if (res == 1) /* incomplete read - wait for more */
334 if (conn->io_pending & CS_WANT_WRITE)
335 assoc->cs_get_mask |= EVENT_OUTPUT;
336 iochan_setflag(h, assoc->cs_get_mask);
339 if (cs_more(conn)) /* more stuff - call us again later, please */
340 iochan_setevent(h, EVENT_INPUT);
342 /* we got a complete PDU. Let's decode it */
343 yaz_log(YLOG_DEBUG, "Got PDU, %d bytes: lead=%02X %02X %02X", res,
344 assoc->input_buffer[0] & 0xff,
345 assoc->input_buffer[1] & 0xff,
346 assoc->input_buffer[2] & 0xff);
347 req = request_get(&assoc->incoming); /* get a new request */
348 odr_reset(assoc->decode);
349 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
350 if (!z_GDU(assoc->decode, &req->gdu_request, 0, 0))
352 yaz_log(YLOG_WARN, "ODR error on incoming PDU: %s [element %s] "
354 odr_errmsg(odr_geterror(assoc->decode)),
355 odr_getelement(assoc->decode),
356 odr_offset(assoc->decode));
357 if (assoc->decode->error != OHTTP)
359 yaz_log(YLOG_WARN, "PDU dump:");
360 odr_dumpBER(yaz_log_file(), assoc->input_buffer, res);
361 request_release(req);
362 do_close(assoc, Z_Close_protocolError,"Malformed package");
366 Z_GDU *p = z_get_HTTP_Response(assoc->encode, 400);
367 assoc->state = ASSOC_DEAD;
368 process_gdu_response(assoc, req, p);
372 req->request_mem = odr_extract_mem(assoc->decode);
375 if (!z_GDU(assoc->print, &req->gdu_request, 0, 0))
376 yaz_log(YLOG_WARN, "ODR print error: %s",
377 odr_errmsg(odr_geterror(assoc->print)));
378 odr_reset(assoc->print);
380 request_enq(&assoc->incoming, req);
383 /* can we do something yet? */
384 req = request_head(&assoc->incoming);
385 if (req->state == REQUEST_IDLE)
387 request_deq(&assoc->incoming);
388 process_gdu_request(assoc, req);
391 if (event & assoc->cs_put_mask)
393 request *req = request_head(&assoc->outgoing);
395 assoc->cs_put_mask = 0;
396 yaz_log(YLOG_DEBUG, "ir_session (output)");
397 req->state = REQUEST_PENDING;
398 switch (res = cs_put(conn, req->response, req->len_response))
401 yaz_log(log_session, "Connection closed by client");
403 destroy_association(assoc);
406 case 0: /* all sent - release the request structure */
407 yaz_log(YLOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
409 yaz_log(YLOG_DEBUG, "HTTP out:\n%.*s", req->len_response,
412 nmem_destroy(req->request_mem);
413 request_deq(&assoc->outgoing);
414 request_release(req);
415 if (!request_head(&assoc->outgoing))
416 { /* restore mask for cs_get operation ... */
417 iochan_clearflag(h, EVENT_OUTPUT|EVENT_INPUT);
418 iochan_setflag(h, assoc->cs_get_mask);
419 if (assoc->state == ASSOC_DEAD)
420 iochan_setevent(assoc->client_chan, EVENT_TIMEOUT);
424 assoc->cs_put_mask = EVENT_OUTPUT;
428 if (conn->io_pending & CS_WANT_WRITE)
429 assoc->cs_put_mask |= EVENT_OUTPUT;
430 if (conn->io_pending & CS_WANT_READ)
431 assoc->cs_put_mask |= EVENT_INPUT;
432 iochan_setflag(h, assoc->cs_put_mask);
435 if (event & EVENT_EXCEPT)
437 yaz_log(YLOG_WARN, "ir_session (exception)");
439 destroy_association(assoc);
444 static int process_z_request(association *assoc, request *req, char **msg);
447 static void assoc_init_reset(association *assoc)
450 assoc->init = (bend_initrequest *) xmalloc (sizeof(*assoc->init));
452 assoc->init->stream = assoc->encode;
453 assoc->init->print = assoc->print;
454 assoc->init->auth = 0;
455 assoc->init->referenceId = 0;
456 assoc->init->implementation_version = 0;
457 assoc->init->implementation_id = 0;
458 assoc->init->implementation_name = 0;
459 assoc->init->bend_sort = NULL;
460 assoc->init->bend_search = NULL;
461 assoc->init->bend_present = NULL;
462 assoc->init->bend_esrequest = NULL;
463 assoc->init->bend_delete = NULL;
464 assoc->init->bend_scan = NULL;
465 assoc->init->bend_segment = NULL;
466 assoc->init->bend_fetch = NULL;
467 assoc->init->bend_explain = NULL;
468 assoc->init->bend_srw_scan = NULL;
470 assoc->init->charneg_request = NULL;
471 assoc->init->charneg_response = NULL;
473 assoc->init->decode = assoc->decode;
474 assoc->init->peer_name =
475 odr_strdup (assoc->encode, cs_addrstr(assoc->client_link));
477 yaz_log(log_requestdetail, "peer %s", assoc->init->peer_name);
482 static int srw_bend_init(association *assoc, Z_SRW_diagnostic **d, int *num)
484 statserv_options_block *cb = statserv_getcontrol();
487 const char *encoding = "UTF-8";
489 bend_initresult *binitres;
491 yaz_log(YLOG_LOG, "srw_bend_init config=%s", cb->configname);
492 assoc_init_reset(assoc);
494 assoc->maximumRecordSize = 3000000;
495 assoc->preferredMessageSize = 3000000;
497 ce = yaz_set_proposal_charneg(assoc->decode, &encoding, 1, 0, 0, 1);
498 assoc->init->charneg_request = ce->u.charNeg3;
501 if (!(binitres = (*cb->bend_init)(assoc->init)))
503 assoc->state = ASSOC_DEAD;
504 yaz_add_srw_diagnostic(assoc->encode, d, num, 3, 0);
507 assoc->backend = binitres->handle;
508 if (binitres->errcode)
510 assoc->state = ASSOC_DEAD;
511 yaz_add_srw_diagnostic(assoc->encode, d, num, binitres->errcode,
512 binitres->errstring);
520 static int srw_bend_fetch(association *assoc, int pos,
521 Z_SRW_searchRetrieveRequest *srw_req,
522 Z_SRW_record *record)
525 ODR o = assoc->encode;
527 rr.setname = "default";
530 rr.request_format = VAL_TEXT_XML;
531 rr.request_format_raw = yaz_oidval_to_z3950oid(assoc->decode,
534 rr.comp = (Z_RecordComposition *)
535 odr_malloc(assoc->decode, sizeof(*rr.comp));
536 rr.comp->which = Z_RecordComp_complex;
537 rr.comp->u.complex = (Z_CompSpec *)
538 odr_malloc(assoc->decode, sizeof(Z_CompSpec));
539 rr.comp->u.complex->selectAlternativeSyntax = (bool_t *)
540 odr_malloc(assoc->encode, sizeof(bool_t));
541 *rr.comp->u.complex->selectAlternativeSyntax = 0;
542 rr.comp->u.complex->num_dbSpecific = 0;
543 rr.comp->u.complex->dbSpecific = 0;
544 rr.comp->u.complex->num_recordSyntax = 0;
545 rr.comp->u.complex->recordSyntax = 0;
547 rr.comp->u.complex->generic = (Z_Specification *)
548 odr_malloc(assoc->decode, sizeof(Z_Specification));
550 /* schema uri = recordSchema (or NULL if recordSchema is not given) */
551 rr.comp->u.complex->generic->which = Z_Schema_uri;
552 rr.comp->u.complex->generic->schema.uri = srw_req->recordSchema;
554 /* ESN = recordSchema if recordSchema is present */
555 rr.comp->u.complex->generic->elementSpec = 0;
556 if (srw_req->recordSchema)
558 rr.comp->u.complex->generic->elementSpec =
559 (Z_ElementSpec *) odr_malloc(assoc->encode, sizeof(Z_ElementSpec));
560 rr.comp->u.complex->generic->elementSpec->which =
561 Z_ElementSpec_elementSetName;
562 rr.comp->u.complex->generic->elementSpec->u.elementSetName =
563 srw_req->recordSchema;
566 rr.stream = assoc->encode;
567 rr.print = assoc->print;
573 rr.output_format = VAL_TEXT_XML;
574 rr.output_format_raw = 0;
577 rr.surrogate_flag = 0;
578 rr.schema = srw_req->recordSchema;
580 if (!assoc->init->bend_fetch)
583 (*assoc->init->bend_fetch)(assoc->backend, &rr);
585 if (rr.errcode && rr.surrogate_flag)
587 int code = yaz_diag_bib1_to_srw(rr.errcode);
588 const char *message = yaz_diag_srw_str(code);
591 len += strlen(message);
593 len += strlen(rr.errstring);
595 record->recordData_buf = odr_malloc(o, len);
597 sprintf(record->recordData_buf, "<diagnostic "
598 "xmlns=\"http://www.loc.gov/zing/srw/diagnostic/\">\n"
599 " <uri>info:srw/diagnostic/1/%d</uri>\n", code);
601 sprintf(record->recordData_buf + strlen(record->recordData_buf),
602 " <details>%s</details>\n", rr.errstring);
604 sprintf(record->recordData_buf + strlen(record->recordData_buf),
605 " <message>%s</message>\n", message);
606 sprintf(record->recordData_buf + strlen(record->recordData_buf),
608 record->recordData_len = strlen(record->recordData_buf);
609 record->recordPosition = odr_intdup(o, pos);
610 record->recordSchema = "info:srw/schema/1/diagnostics-v1.1";
613 else if (rr.len >= 0)
615 record->recordData_buf = rr.record;
616 record->recordData_len = rr.len;
617 record->recordPosition = odr_intdup(o, pos);
619 record->recordSchema = odr_strdup(o, rr.schema);
621 record->recordSchema = 0;
626 static void srw_bend_search(association *assoc, request *req,
627 Z_SRW_searchRetrieveRequest *srw_req,
628 Z_SRW_searchRetrieveResponse *srw_res,
635 yaz_log(log_requestdetail, "Got SRW SearchRetrieveRequest");
636 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics);
637 if (srw_req->sort_type != Z_SRW_sort_type_none)
638 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
639 &srw_res->num_diagnostics, 80, 0);
640 else if (srw_res->num_diagnostics == 0 && assoc->init)
643 rr.setname = "default";
646 rr.basenames = &srw_req->database;
649 rr.query = (Z_Query *) odr_malloc (assoc->decode, sizeof(*rr.query));
651 if (srw_req->query_type == Z_SRW_query_type_cql)
653 ext = (Z_External *) odr_malloc(assoc->decode, sizeof(*ext));
654 ext->direct_reference = odr_getoidbystr(assoc->decode,
655 "1.2.840.10003.16.2");
656 ext->indirect_reference = 0;
658 ext->which = Z_External_CQL;
659 ext->u.cql = srw_req->query.cql;
661 rr.query->which = Z_Query_type_104;
662 rr.query->u.type_104 = ext;
664 else if (srw_req->query_type == Z_SRW_query_type_pqf)
666 Z_RPNQuery *RPNquery;
667 YAZ_PQF_Parser pqf_parser;
669 pqf_parser = yaz_pqf_create ();
671 RPNquery = yaz_pqf_parse (pqf_parser, assoc->decode,
677 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
678 yaz_log(log_requestdetail, "Parse error %d %s near offset %d",
683 rr.query->which = Z_Query_type_1;
684 rr.query->u.type_1 = RPNquery;
686 yaz_pqf_destroy (pqf_parser);
690 rr.query->u.type_1 = 0;
691 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
692 &srw_res->num_diagnostics, 11, 0);
694 if (rr.query->u.type_1)
696 rr.stream = assoc->encode;
697 rr.decode = assoc->decode;
698 rr.print = assoc->print;
700 rr.association = assoc;
706 yaz_log_zquery_level(log_requestdetail,rr.query);
708 (assoc->init->bend_search)(assoc->backend, &rr);
711 if (rr.errcode == 109) /* database unavailable */
717 srw_error = yaz_diag_bib1_to_srw (rr.errcode);
718 yaz_add_srw_diagnostic(assoc->encode,
719 &srw_res->diagnostics,
720 &srw_res->num_diagnostics,
721 srw_error, rr.errstring);
726 int number = srw_req->maximumRecords ? *srw_req->maximumRecords : 0;
727 int start = srw_req->startRecord ? *srw_req->startRecord : 1;
729 yaz_log(log_requestdetail, "Request to pack %d+%d out of %d",
730 start, number, rr.hits);
732 srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
739 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
740 &srw_res->num_diagnostics,
746 int packing = Z_SRW_recordPacking_string;
747 if (start + number > rr.hits)
748 number = rr.hits - start + 1;
749 if (srw_req->recordPacking &&
750 !strcmp(srw_req->recordPacking, "xml"))
751 packing = Z_SRW_recordPacking_XML;
752 srw_res->records = (Z_SRW_record *)
753 odr_malloc(assoc->encode,
754 number * sizeof(*srw_res->records));
755 for (i = 0; i<number; i++)
759 srw_res->records[j].recordPacking = packing;
760 srw_res->records[j].recordData_buf = 0;
761 yaz_log(YLOG_DEBUG, "srw_bend_fetch %d", i+start);
762 errcode = srw_bend_fetch(assoc, i+start, srw_req,
763 srw_res->records + j);
766 yaz_add_srw_diagnostic(assoc->encode,
767 &srw_res->diagnostics,
768 &srw_res->num_diagnostics,
769 yaz_diag_bib1_to_srw (errcode),
774 if (srw_res->records[j].recordData_buf)
777 srw_res->num_records = j;
779 srw_res->records = 0;
787 const char *querystr = "?";
788 const char *querytype = "?";
789 WRBUF wr = wrbuf_alloc();
791 switch (srw_req->query_type)
793 case Z_SRW_query_type_cql:
795 querystr = srw_req->query.cql;
797 case Z_SRW_query_type_pqf:
799 querystr = srw_req->query.pqf;
802 wrbuf_printf(wr, "SRWSearch ");
803 if (srw_res->num_diagnostics)
804 wrbuf_printf(wr, "ERROR %s", srw_res->diagnostics[0].uri);
805 else if (*http_code != 200)
806 wrbuf_printf(wr, "ERROR info:http/%d", *http_code);
807 else if (srw_res->numberOfRecords)
809 wrbuf_printf(wr, "OK %d",
810 (srw_res->numberOfRecords ?
811 *srw_res->numberOfRecords : 0));
813 wrbuf_printf(wr, " %s %d+%d",
814 (srw_res->resultSetId ?
815 srw_res->resultSetId : "-"),
816 (srw_req->startRecord ? *srw_req->startRecord : 1),
817 srw_res->num_records);
818 yaz_log(log_request, "%s %s: %s", wrbuf_buf(wr), querytype, querystr);
823 static void srw_bend_explain(association *assoc, request *req,
824 Z_SRW_explainRequest *srw_req,
825 Z_SRW_explainResponse *srw_res,
828 yaz_log(log_requestdetail, "Got SRW ExplainRequest");
830 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics);
831 if (assoc->init && assoc->init->bend_explain)
835 rr.stream = assoc->encode;
836 rr.decode = assoc->decode;
837 rr.print = assoc->print;
839 rr.database = srw_req->database;
840 rr.schema = "http://explain.z3950.org/dtd/2.0/";
841 (*assoc->init->bend_explain)(assoc->backend, &rr);
844 int packing = Z_SRW_recordPacking_string;
845 if (srw_req->recordPacking &&
846 !strcmp(srw_req->recordPacking, "xml"))
847 packing = Z_SRW_recordPacking_XML;
848 srw_res->record.recordSchema = rr.schema;
849 srw_res->record.recordPacking = packing;
850 srw_res->record.recordData_buf = rr.explain_buf;
851 srw_res->record.recordData_len = strlen(rr.explain_buf);
852 srw_res->record.recordPosition = 0;
858 static void srw_bend_scan(association *assoc, request *req,
859 Z_SRW_scanRequest *srw_req,
860 Z_SRW_scanResponse *srw_res,
863 yaz_log(log_requestdetail, "Got SRW ScanRequest");
866 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics);
867 if (srw_res->num_diagnostics == 0 && assoc->init)
869 struct scan_entry *save_entries;
871 bend_scan_rr *bsrr = (bend_scan_rr *)
872 odr_malloc (assoc->encode, sizeof(*bsrr));
874 bsrr->basenames = &srw_req->database;
876 bsrr->num_entries = srw_req->maximumTerms ?
877 *srw_req->maximumTerms : 10;
878 bsrr->term_position = srw_req->responsePosition ?
879 *srw_req->responsePosition : 1;
883 bsrr->referenceId = 0;
884 bsrr->stream = assoc->encode;
885 bsrr->print = assoc->print;
886 bsrr->step_size = odr_intdup(assoc->decode, 0);
889 if (bsrr->num_entries > 0)
892 bsrr->entries = odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
894 for (i = 0; i<bsrr->num_entries; i++)
896 bsrr->entries[i].term = 0;
897 bsrr->entries[i].occurrences = 0;
898 bsrr->entries[i].errcode = 0;
899 bsrr->entries[i].errstring = 0;
900 bsrr->entries[i].display_term = 0;
903 save_entries = bsrr->entries; /* save it so we can compare later */
905 if (srw_req->query_type == Z_SRW_query_type_pqf &&
906 assoc->init->bend_scan)
908 Odr_oid *scan_attributeSet = 0;
910 YAZ_PQF_Parser pqf_parser = yaz_pqf_create();
912 bsrr->term = yaz_pqf_scan(pqf_parser, assoc->decode,
914 srw_req->scanClause.pqf);
915 if (scan_attributeSet &&
916 (attset = oid_getentbyoid(scan_attributeSet)) &&
917 (attset->oclass == CLASS_ATTSET ||
918 attset->oclass == CLASS_GENERAL))
919 bsrr->attributeset = attset->value;
921 bsrr->attributeset = VAL_NONE;
922 yaz_pqf_destroy(pqf_parser);
923 bsrr->scanClause = 0;
924 ((int (*)(void *, bend_scan_rr *))
925 (*assoc->init->bend_scan))(assoc->backend, bsrr);
927 else if (srw_req->query_type == Z_SRW_query_type_cql
928 && assoc->init->bend_srw_scan)
931 bsrr->attributeset = VAL_NONE;
932 bsrr->scanClause = srw_req->scanClause.cql;
933 ((int (*)(void *, bend_scan_rr *))
934 (*assoc->init->bend_srw_scan))(assoc->backend, bsrr);
938 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
939 &srw_res->num_diagnostics, 4, "scan");
944 if (bsrr->errcode == 109) /* database unavailable */
949 srw_error = yaz_diag_bib1_to_srw (bsrr->errcode);
951 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
952 &srw_res->num_diagnostics,
953 srw_error, bsrr->errstring);
955 else if (srw_res->num_diagnostics == 0 && bsrr->num_entries)
958 srw_res->terms = (Z_SRW_scanTerm*)
959 odr_malloc(assoc->encode, sizeof(*srw_res->terms) *
962 srw_res->num_terms = bsrr->num_entries;
963 for (i = 0; i<bsrr->num_entries; i++)
965 Z_SRW_scanTerm *t = srw_res->terms + i;
966 t->value = odr_strdup(assoc->encode, bsrr->entries[i].term);
968 odr_intdup(assoc->encode, bsrr->entries[i].occurrences);
970 if (save_entries == bsrr->entries &&
971 bsrr->entries[i].display_term)
973 /* the entries was _not_ set by the handler. So it's
974 safe to test for new member display_term. It is
977 t->displayTerm = odr_strdup(assoc->encode,
978 bsrr->entries[i].display_term);
986 WRBUF wr = wrbuf_alloc();
987 const char *querytype = 0;
988 const char *querystr = 0;
990 switch(srw_req->query_type)
992 case Z_SRW_query_type_pqf:
994 querystr = srw_req->scanClause.pqf;
996 case Z_SRW_query_type_cql:
998 querystr = srw_req->scanClause.cql;
1001 querytype = "Unknown";
1004 wrbuf_printf(wr, "SRWScan %d+%d",
1005 (srw_req->responsePosition ?
1006 *srw_req->responsePosition : 1),
1007 (srw_req->maximumTerms ?
1008 *srw_req->maximumTerms : 1));
1009 if (srw_res->num_diagnostics)
1010 wrbuf_printf(wr, " ERROR %s", srw_res->diagnostics[0].uri);
1012 wrbuf_printf(wr, " OK -");
1013 wrbuf_printf(wr, " %s: %s", querytype, querystr);
1014 yaz_log(log_request, "%s", wrbuf_buf(wr) );
1021 static void process_http_request(association *assoc, request *req)
1023 Z_HTTP_Request *hreq = req->gdu_request->u.HTTP_Request;
1024 ODR o = assoc->encode;
1025 int r = 2; /* 2=NOT TAKEN, 1=TAKEN, 0=SOAP TAKEN */
1027 Z_SOAP *soap_package = 0;
1030 Z_HTTP_Response *hres = 0;
1032 char *stylesheet = 0;
1033 Z_SRW_diagnostic *diagnostic = 0;
1034 int num_diagnostic = 0;
1035 const char *host = z_HTTP_header_lookup(hreq->headers, "Host");
1037 if (!control_association(assoc, host, 0))
1039 p = z_get_HTTP_Response(o, 404);
1042 if (r == 2 && !strcmp(hreq->path, "/test"))
1044 p = z_get_HTTP_Response(o, 200);
1045 hres = p->u.HTTP_Response;
1046 hres->content_buf = "1234567890\n";
1047 hres->content_len = strlen(hres->content_buf);
1052 r = yaz_srw_decode(hreq, &sr, &soap_package, assoc->decode, &charset);
1053 yaz_log(YLOG_DEBUG, "yaz_srw_decode returned %d", r);
1055 if (r == 2) /* not taken */
1057 r = yaz_sru_decode(hreq, &sr, &soap_package, assoc->decode, &charset,
1058 &diagnostic, &num_diagnostic);
1059 yaz_log(YLOG_DEBUG, "yaz_sru_decode returned %d", r);
1061 if (r == 0) /* decode SRW/SRU OK .. */
1063 int http_code = 200;
1064 if (sr->which == Z_SRW_searchRetrieve_request)
1067 yaz_srw_get(assoc->encode, Z_SRW_searchRetrieve_response);
1069 stylesheet = sr->u.request->stylesheet;
1072 res->u.response->diagnostics = diagnostic;
1073 res->u.response->num_diagnostics = num_diagnostic;
1077 srw_bend_search(assoc, req, sr->u.request, res->u.response,
1080 if (http_code == 200)
1081 soap_package->u.generic->p = res;
1083 else if (sr->which == Z_SRW_explain_request)
1085 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_explain_response);
1086 stylesheet = sr->u.explain_request->stylesheet;
1089 res->u.explain_response->diagnostics = diagnostic;
1090 res->u.explain_response->num_diagnostics = num_diagnostic;
1092 srw_bend_explain(assoc, req, sr->u.explain_request,
1093 res->u.explain_response, &http_code);
1094 if (http_code == 200)
1095 soap_package->u.generic->p = res;
1097 else if (sr->which == Z_SRW_scan_request)
1099 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_scan_response);
1100 stylesheet = sr->u.scan_request->stylesheet;
1103 res->u.scan_response->diagnostics = diagnostic;
1104 res->u.scan_response->num_diagnostics = num_diagnostic;
1106 srw_bend_scan(assoc, req, sr->u.scan_request,
1107 res->u.scan_response, &http_code);
1108 if (http_code == 200)
1109 soap_package->u.generic->p = res;
1113 yaz_log(log_request, "SOAP ERROR");
1114 /* FIXME - what error, what query */
1116 z_soap_error(assoc->encode, soap_package,
1117 "SOAP-ENV:Client", "Bad method", 0);
1119 if (http_code == 200 || http_code == 500)
1121 static Z_SOAP_Handler soap_handlers[3] = {
1123 {"http://www.loc.gov/zing/srw/", 0,
1124 (Z_SOAP_fun) yaz_srw_codec},
1125 {"http://www.loc.gov/zing/srw/v1.0/", 0,
1126 (Z_SOAP_fun) yaz_srw_codec},
1132 p = z_get_HTTP_Response(o, 200);
1133 hres = p->u.HTTP_Response;
1134 ret = z_soap_codec_enc_xsl(assoc->encode, &soap_package,
1135 &hres->content_buf, &hres->content_len,
1136 soap_handlers, charset, stylesheet);
1137 hres->code = http_code;
1139 strcpy(ctype, "text/xml");
1142 strcat(ctype, "; charset=");
1143 strcat(ctype, charset);
1145 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1148 p = z_get_HTTP_Response(o, http_code);
1152 p = z_get_HTTP_Response(o, 500);
1153 hres = p->u.HTTP_Response;
1154 if (!strcmp(hreq->version, "1.0"))
1156 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1157 if (v && !strcmp(v, "Keep-Alive"))
1161 hres->version = "1.0";
1165 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1166 if (v && !strcmp(v, "close"))
1170 hres->version = "1.1";
1174 z_HTTP_header_add(o, &hres->headers, "Connection", "close");
1175 assoc->state = ASSOC_DEAD;
1176 assoc->cs_get_mask = 0;
1181 const char *alive = z_HTTP_header_lookup(hreq->headers, "Keep-Alive");
1183 if (alive && isdigit(*(const unsigned char *) alive))
1187 if (t < 0 || t > 3600)
1189 iochan_settimeout(assoc->client_chan,t);
1190 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1192 process_gdu_response(assoc, req, p);
1195 static void process_gdu_request(association *assoc, request *req)
1197 if (req->gdu_request->which == Z_GDU_Z3950)
1200 req->apdu_request = req->gdu_request->u.z3950;
1201 if (process_z_request(assoc, req, &msg) < 0)
1202 do_close_req(assoc, Z_Close_systemProblem, msg, req);
1204 else if (req->gdu_request->which == Z_GDU_HTTP_Request)
1205 process_http_request(assoc, req);
1208 do_close_req(assoc, Z_Close_systemProblem, "bad protocol packet", req);
1213 * Initiate request processing.
1215 static int process_z_request(association *assoc, request *req, char **msg)
1221 *msg = "Unknown Error";
1222 assert(req && req->state == REQUEST_IDLE);
1223 if (req->apdu_request->which != Z_APDU_initRequest && !assoc->init)
1225 *msg = "Missing InitRequest";
1228 switch (req->apdu_request->which)
1230 case Z_APDU_initRequest:
1231 res = process_initRequest(assoc, req); break;
1232 case Z_APDU_searchRequest:
1233 res = process_searchRequest(assoc, req, &fd); break;
1234 case Z_APDU_presentRequest:
1235 res = process_presentRequest(assoc, req, &fd); break;
1236 case Z_APDU_scanRequest:
1237 if (assoc->init->bend_scan)
1238 res = process_scanRequest(assoc, req, &fd);
1241 *msg = "Cannot handle Scan APDU";
1245 case Z_APDU_extendedServicesRequest:
1246 if (assoc->init->bend_esrequest)
1247 res = process_ESRequest(assoc, req, &fd);
1250 *msg = "Cannot handle Extended Services APDU";
1254 case Z_APDU_sortRequest:
1255 if (assoc->init->bend_sort)
1256 res = process_sortRequest(assoc, req, &fd);
1259 *msg = "Cannot handle Sort APDU";
1264 process_close(assoc, req);
1266 case Z_APDU_deleteResultSetRequest:
1267 if (assoc->init->bend_delete)
1268 res = process_deleteRequest(assoc, req, &fd);
1271 *msg = "Cannot handle Delete APDU";
1275 case Z_APDU_segmentRequest:
1276 if (assoc->init->bend_segment)
1278 res = process_segmentRequest (assoc, req);
1282 *msg = "Cannot handle Segment APDU";
1286 case Z_APDU_triggerResourceControlRequest:
1289 *msg = "Bad APDU received";
1294 yaz_log(YLOG_DEBUG, " result immediately available");
1295 retval = process_z_response(assoc, req, res);
1299 yaz_log(YLOG_DEBUG, " result unavailble");
1302 else /* no result yet - one will be provided later */
1306 /* Set up an I/O handler for the fd supplied by the backend */
1308 yaz_log(YLOG_DEBUG, " establishing handler for result");
1309 req->state = REQUEST_PENDING;
1310 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT, 0)))
1312 iochan_setdata(chan, assoc);
1319 * Handle message from the backend.
1321 void backend_response(IOCHAN i, int event)
1323 association *assoc = (association *)iochan_getdata(i);
1324 request *req = request_head(&assoc->incoming);
1328 yaz_log(YLOG_DEBUG, "backend_response");
1329 assert(assoc && req && req->state != REQUEST_IDLE);
1330 /* determine what it is we're waiting for */
1331 switch (req->apdu_request->which)
1333 case Z_APDU_searchRequest:
1334 res = response_searchRequest(assoc, req, 0, &fd); break;
1336 case Z_APDU_presentRequest:
1337 res = response_presentRequest(assoc, req, 0, &fd); break;
1338 case Z_APDU_scanRequest:
1339 res = response_scanRequest(assoc, req, 0, &fd); break;
1342 yaz_log(YLOG_FATAL, "Serious programmer's lapse or bug");
1345 if ((res && process_z_response(assoc, req, res) < 0) || fd < 0)
1347 yaz_log(YLOG_WARN, "Fatal error when talking to backend");
1348 do_close(assoc, Z_Close_systemProblem, 0);
1352 else if (!res) /* no result yet - try again later */
1354 yaz_log(YLOG_DEBUG, " no result yet");
1355 iochan_setfd(i, fd); /* in case fd has changed */
1360 * Encode response, and transfer the request structure to the outgoing queue.
1362 static int process_gdu_response(association *assoc, request *req, Z_GDU *res)
1364 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
1368 if (!z_GDU(assoc->print, &res, 0, 0))
1369 yaz_log(YLOG_WARN, "ODR print error: %s",
1370 odr_errmsg(odr_geterror(assoc->print)));
1371 odr_reset(assoc->print);
1373 if (!z_GDU(assoc->encode, &res, 0, 0))
1375 yaz_log(YLOG_WARN, "ODR error when encoding PDU: %s [element %s]",
1376 odr_errmsg(odr_geterror(assoc->decode)),
1377 odr_getelement(assoc->decode));
1380 req->response = odr_getbuf(assoc->encode, &req->len_response,
1381 &req->size_response);
1382 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
1383 odr_reset(assoc->encode);
1384 req->state = REQUEST_IDLE;
1385 request_enq(&assoc->outgoing, req);
1386 /* turn the work over to the ir_session handler */
1387 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
1388 assoc->cs_put_mask = EVENT_OUTPUT;
1389 /* Is there more work to be done? give that to the input handler too */
1391 if (request_head(&assoc->incoming))
1393 yaz_log (YLOG_DEBUG, "more work to be done");
1394 iochan_setevent(assoc->client_chan, EVENT_WORK);
1401 * Encode response, and transfer the request structure to the outgoing queue.
1403 static int process_z_response(association *assoc, request *req, Z_APDU *res)
1405 Z_GDU *gres = (Z_GDU *) odr_malloc(assoc->encode, sizeof(*res));
1406 gres->which = Z_GDU_Z3950;
1407 gres->u.z3950 = res;
1409 return process_gdu_response(assoc, req, gres);
1412 static char *get_vhost(Z_OtherInformation *otherInfo)
1414 return yaz_oi_get_string_oidval(&otherInfo, VAL_PROXY, 1, 0);
1418 * Handle init request.
1419 * At the moment, we don't check the options
1420 * anywhere else in the code - we just try not to do anything that would
1421 * break a naive client. We'll toss 'em into the association block when
1422 * we need them there.
1424 static Z_APDU *process_initRequest(association *assoc, request *reqb)
1426 Z_InitRequest *req = reqb->apdu_request->u.initRequest;
1427 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
1428 Z_InitResponse *resp = apdu->u.initResponse;
1429 bend_initresult *binitres;
1432 statserv_options_block *cb = 0; /* by default no control for backend */
1434 if (control_association(assoc, get_vhost(req->otherInfo), 1))
1435 cb = statserv_getcontrol(); /* got control block for backend */
1437 yaz_log(log_requestdetail, "Got initRequest");
1438 if (req->implementationId)
1439 yaz_log(log_requestdetail, "Id: %s",
1440 req->implementationId);
1441 if (req->implementationName)
1442 yaz_log(log_requestdetail, "Name: %s",
1443 req->implementationName);
1444 if (req->implementationVersion)
1445 yaz_log(log_requestdetail, "Version: %s",
1446 req->implementationVersion);
1448 assoc_init_reset(assoc);
1450 assoc->init->auth = req->idAuthentication;
1451 assoc->init->referenceId = req->referenceId;
1453 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
1455 Z_CharSetandLanguageNegotiation *negotiation =
1456 yaz_get_charneg_record (req->otherInfo);
1458 negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
1459 assoc->init->charneg_request = negotiation;
1465 if (req->implementationVersion)
1466 yaz_log(log_requestdetail, "Config: %s",
1469 iochan_settimeout(assoc->client_chan, cb->idle_timeout * 60);
1471 /* we have a backend control block, so call that init function */
1472 if (!(binitres = (*cb->bend_init)(assoc->init)))
1474 yaz_log(YLOG_WARN, "Bad response from backend.");
1477 assoc->backend = binitres->handle;
1481 /* no backend. return error */
1482 binitres = odr_malloc(assoc->encode, sizeof(*binitres));
1483 binitres->errstring = 0;
1484 binitres->errcode = 1;
1485 iochan_settimeout(assoc->client_chan, 10);
1487 if ((assoc->init->bend_sort))
1488 yaz_log (YLOG_DEBUG, "Sort handler installed");
1489 if ((assoc->init->bend_search))
1490 yaz_log (YLOG_DEBUG, "Search handler installed");
1491 if ((assoc->init->bend_present))
1492 yaz_log (YLOG_DEBUG, "Present handler installed");
1493 if ((assoc->init->bend_esrequest))
1494 yaz_log (YLOG_DEBUG, "ESRequest handler installed");
1495 if ((assoc->init->bend_delete))
1496 yaz_log (YLOG_DEBUG, "Delete handler installed");
1497 if ((assoc->init->bend_scan))
1498 yaz_log (YLOG_DEBUG, "Scan handler installed");
1499 if ((assoc->init->bend_segment))
1500 yaz_log (YLOG_DEBUG, "Segment handler installed");
1502 resp->referenceId = req->referenceId;
1504 /* let's tell the client what we can do */
1505 if (ODR_MASK_GET(req->options, Z_Options_search))
1507 ODR_MASK_SET(resp->options, Z_Options_search);
1508 strcat(options, "srch");
1510 if (ODR_MASK_GET(req->options, Z_Options_present))
1512 ODR_MASK_SET(resp->options, Z_Options_present);
1513 strcat(options, " prst");
1515 if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
1516 assoc->init->bend_delete)
1518 ODR_MASK_SET(resp->options, Z_Options_delSet);
1519 strcat(options, " del");
1521 if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
1522 assoc->init->bend_esrequest)
1524 ODR_MASK_SET(resp->options, Z_Options_extendedServices);
1525 strcat (options, " extendedServices");
1527 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
1529 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
1530 strcat(options, " namedresults");
1532 if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
1534 ODR_MASK_SET(resp->options, Z_Options_scan);
1535 strcat(options, " scan");
1537 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
1539 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
1540 strcat(options, " concurrop");
1542 if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
1544 ODR_MASK_SET(resp->options, Z_Options_sort);
1545 strcat(options, " sort");
1548 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel)
1549 && assoc->init->charneg_response)
1551 Z_OtherInformation **p;
1552 Z_OtherInformationUnit *p0;
1554 yaz_oi_APDU(apdu, &p);
1556 if ((p0=yaz_oi_update(p, assoc->encode, NULL, 0, 0))) {
1557 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
1559 p0->which = Z_OtherInfo_externallyDefinedInfo;
1560 p0->information.externallyDefinedInfo =
1561 assoc->init->charneg_response;
1563 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
1564 strcat(options, " negotiation");
1567 ODR_MASK_SET(resp->options, Z_Options_triggerResourceCtrl);
1569 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
1571 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
1572 assoc->version = 1; /* 1 & 2 are equivalent */
1574 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
1576 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
1579 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
1581 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
1585 yaz_log(log_requestdetail, "Negotiated to v%d: %s", assoc->version, options);
1586 assoc->maximumRecordSize = *req->maximumRecordSize;
1588 if (cb && assoc->maximumRecordSize > cb->maxrecordsize)
1589 assoc->maximumRecordSize = cb->maxrecordsize;
1590 assoc->preferredMessageSize = *req->preferredMessageSize;
1591 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
1592 assoc->preferredMessageSize = assoc->maximumRecordSize;
1594 resp->preferredMessageSize = &assoc->preferredMessageSize;
1595 resp->maximumRecordSize = &assoc->maximumRecordSize;
1597 resp->implementationId = odr_prepend(assoc->encode,
1598 assoc->init->implementation_id,
1599 resp->implementationId);
1601 resp->implementationName = odr_prepend(assoc->encode,
1602 assoc->init->implementation_name,
1603 odr_prepend(assoc->encode, "GFS", resp->implementationName));
1605 version = odr_strdup(assoc->encode, "$Revision: 1.47 $");
1606 if (strlen(version) > 10) /* check for unexpanded CVS strings */
1607 version[strlen(version)-2] = '\0';
1608 resp->implementationVersion = odr_prepend(assoc->encode,
1609 assoc->init->implementation_version,
1610 odr_prepend(assoc->encode, &version[11],
1611 resp->implementationVersion));
1613 if (binitres->errcode)
1615 assoc->state = ASSOC_DEAD;
1616 resp->userInformationField =
1617 init_diagnostics(assoc->encode, binitres->errcode,
1618 binitres->errstring);
1623 WRBUF wr = wrbuf_alloc();
1624 wrbuf_printf(wr, "Init ");
1625 if (binitres->errcode)
1626 wrbuf_printf(wr, "ERROR %d", binitres->errcode);
1628 wrbuf_printf(wr, "OK -");
1629 wrbuf_printf(wr, " ID:%s Name:%s Version:%s",
1630 (req->implementationId ? req->implementationId :"-"),
1631 (req->implementationName ?
1632 req->implementationName : "-"),
1633 (req->implementationVersion ?
1634 req->implementationVersion : "-")
1636 yaz_log(log_request, "%s", wrbuf_buf(wr));
1643 * Set the specified `errcode' and `errstring' into a UserInfo-1
1644 * external to be returned to the client in accordance with Z35.90
1645 * Implementor Agreement 5 (Returning diagnostics in an InitResponse):
1646 * http://lcweb.loc.gov/z3950/agency/agree/initdiag.html
1648 static Z_External *init_diagnostics(ODR odr, int error, const char *addinfo)
1650 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
1651 addinfo ? " -- " : "", addinfo ? addinfo : "");
1652 return zget_init_diagnostics(odr, error, addinfo);
1656 * nonsurrogate diagnostic record.
1658 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
1660 Z_Records *rec = (Z_Records *) odr_malloc (assoc->encode, sizeof(*rec));
1662 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
1663 addinfo ? " -- " : "", addinfo ? addinfo : "");
1665 rec->which = Z_Records_NSD;
1666 rec->u.nonSurrogateDiagnostic = zget_DefaultDiagFormat(assoc->encode,
1672 * surrogate diagnostic.
1674 static Z_NamePlusRecord *surrogatediagrec(association *assoc,
1676 int error, const char *addinfo)
1678 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
1679 addinfo ? " -- " : "", addinfo ? addinfo : "");
1680 return zget_surrogateDiagRec(assoc->encode, dbname, error, addinfo);
1683 static Z_Records *pack_records(association *a, char *setname, int start,
1684 int *num, Z_RecordComposition *comp,
1685 int *next, int *pres, oid_value format,
1686 Z_ReferenceId *referenceId,
1687 int *oid, int *errcode)
1689 int recno, total_length = 0, toget = *num, dumped_records = 0;
1690 Z_Records *records =
1691 (Z_Records *) odr_malloc (a->encode, sizeof(*records));
1692 Z_NamePlusRecordList *reclist =
1693 (Z_NamePlusRecordList *) odr_malloc (a->encode, sizeof(*reclist));
1694 Z_NamePlusRecord **list =
1695 (Z_NamePlusRecord **) odr_malloc (a->encode, sizeof(*list) * toget);
1697 records->which = Z_Records_DBOSD;
1698 records->u.databaseOrSurDiagnostics = reclist;
1699 reclist->num_records = 0;
1700 reclist->records = list;
1701 *pres = Z_PresentStatus_success;
1705 yaz_log(log_requestdetail, "Request to pack %d+%d %s", start, toget, setname);
1706 yaz_log(log_requestdetail, "pms=%d, mrs=%d", a->preferredMessageSize,
1707 a->maximumRecordSize);
1708 for (recno = start; reclist->num_records < toget; recno++)
1711 Z_NamePlusRecord *thisrec;
1712 int this_length = 0;
1714 * we get the number of bytes allocated on the stream before any
1715 * allocation done by the backend - this should give us a reasonable
1716 * idea of the total size of the data so far.
1718 total_length = odr_total(a->encode) - dumped_records;
1724 freq.last_in_set = 0;
1725 freq.setname = setname;
1726 freq.surrogate_flag = 0;
1727 freq.number = recno;
1729 freq.request_format = format;
1730 freq.request_format_raw = oid;
1731 freq.output_format = format;
1732 freq.output_format_raw = 0;
1733 freq.stream = a->encode;
1734 freq.print = a->print;
1735 freq.referenceId = referenceId;
1737 (*a->init->bend_fetch)(a->backend, &freq);
1738 /* backend should be able to signal whether error is system-wide
1739 or only pertaining to current record */
1742 if (!freq.surrogate_flag)
1745 *pres = Z_PresentStatus_failure;
1746 /* for 'present request out of range',
1747 set addinfo to record position if not set */
1748 if (freq.errcode == 13 && freq.errstring == 0)
1750 sprintf (s, "%d", recno);
1754 *errcode = freq.errcode;
1755 return diagrec(a, freq.errcode, freq.errstring);
1757 reclist->records[reclist->num_records] =
1758 surrogatediagrec(a, freq.basename, freq.errcode,
1760 reclist->num_records++;
1761 *next = freq.last_in_set ? 0 : recno + 1;
1765 this_length = freq.len;
1767 this_length = odr_total(a->encode) - total_length - dumped_records;
1768 yaz_log(YLOG_DEBUG, " fetched record, len=%d, total=%d dumped=%d",
1769 this_length, total_length, dumped_records);
1770 if (a->preferredMessageSize > 0 &&
1771 this_length + total_length > a->preferredMessageSize)
1773 /* record is small enough, really */
1774 if (this_length <= a->preferredMessageSize && recno > start)
1776 yaz_log(log_requestdetail, " Dropped last normal-sized record");
1777 *pres = Z_PresentStatus_partial_2;
1780 /* record can only be fetched by itself */
1781 if (this_length < a->maximumRecordSize)
1783 yaz_log(log_requestdetail, " Record > prefmsgsz");
1786 yaz_log(YLOG_DEBUG, " Dropped it");
1787 reclist->records[reclist->num_records] =
1788 surrogatediagrec(a, freq.basename, 16, 0);
1789 reclist->num_records++;
1790 *next = freq.last_in_set ? 0 : recno + 1;
1791 dumped_records += this_length;
1795 else /* too big entirely */
1797 yaz_log(log_requestdetail, "Record > maxrcdsz this=%d max=%d",
1798 this_length, a->maximumRecordSize);
1799 reclist->records[reclist->num_records] =
1800 surrogatediagrec(a, freq.basename, 17, 0);
1801 reclist->num_records++;
1802 *next = freq.last_in_set ? 0 : recno + 1;
1803 dumped_records += this_length;
1808 if (!(thisrec = (Z_NamePlusRecord *)
1809 odr_malloc(a->encode, sizeof(*thisrec))))
1811 if (!(thisrec->databaseName = (char *)odr_malloc(a->encode,
1812 strlen(freq.basename) + 1)))
1814 strcpy(thisrec->databaseName, freq.basename);
1815 thisrec->which = Z_NamePlusRecord_databaseRecord;
1817 if (freq.output_format_raw)
1819 struct oident *ident = oid_getentbyoid(freq.output_format_raw);
1820 freq.output_format = ident->value;
1822 thisrec->u.databaseRecord = z_ext_record(a->encode, freq.output_format,
1823 freq.record, freq.len);
1824 if (!thisrec->u.databaseRecord)
1826 reclist->records[reclist->num_records] = thisrec;
1827 reclist->num_records++;
1828 *next = freq.last_in_set ? 0 : recno + 1;
1830 *num = reclist->num_records;
1834 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
1837 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
1838 bend_search_rr *bsrr =
1839 (bend_search_rr *)nmem_malloc (reqb->request_mem, sizeof(*bsrr));
1841 yaz_log(log_requestdetail, "Got SearchRequest.");
1843 bsrr->request = reqb;
1844 bsrr->association = assoc;
1845 bsrr->referenceId = req->referenceId;
1846 save_referenceId (reqb, bsrr->referenceId);
1848 yaz_log (log_requestdetail, "ResultSet '%s'", req->resultSetName);
1849 if (req->databaseNames)
1852 for (i = 0; i < req->num_databaseNames; i++)
1853 yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
1856 yaz_log_zquery_level(log_requestdetail,req->query);
1858 if (assoc->init->bend_search)
1860 bsrr->setname = req->resultSetName;
1861 bsrr->replace_set = *req->replaceIndicator;
1862 bsrr->num_bases = req->num_databaseNames;
1863 bsrr->basenames = req->databaseNames;
1864 bsrr->query = req->query;
1865 bsrr->stream = assoc->encode;
1866 nmem_transfer(bsrr->stream->mem, reqb->request_mem);
1867 bsrr->decode = assoc->decode;
1868 bsrr->print = assoc->print;
1871 bsrr->errstring = NULL;
1872 bsrr->search_info = NULL;
1873 (assoc->init->bend_search)(assoc->backend, bsrr);
1874 if (!bsrr->request) /* backend not ready with the search response */
1875 return 0; /* should not be used any more */
1879 /* FIXME - make a diagnostic for it */
1880 yaz_log(YLOG_WARN,"Search not supported ?!?!");
1882 return response_searchRequest(assoc, reqb, bsrr, fd);
1885 int bend_searchresponse(void *handle, bend_search_rr *bsrr) {return 0;}
1888 * Prepare a searchresponse based on the backend results. We probably want
1889 * to look at making the fetching of records nonblocking as well, but
1890 * so far, we'll keep things simple.
1891 * If bsrt is null, that means we're called in response to a communications
1892 * event, and we'll have to get the response for ourselves.
1894 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
1895 bend_search_rr *bsrt, int *fd)
1897 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
1898 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1899 Z_SearchResponse *resp = (Z_SearchResponse *)
1900 odr_malloc (assoc->encode, sizeof(*resp));
1901 int *nulint = odr_intdup (assoc->encode, 0);
1902 bool_t *sr = odr_intdup(assoc->encode, 1);
1903 int *next = odr_intdup(assoc->encode, 0);
1904 int *none = odr_intdup(assoc->encode, Z_SearchResponse_none);
1907 apdu->which = Z_APDU_searchResponse;
1908 apdu->u.searchResponse = resp;
1909 resp->referenceId = req->referenceId;
1910 resp->additionalSearchInfo = 0;
1911 resp->otherInfo = 0;
1913 if (!bsrt && !bend_searchresponse(assoc->backend, bsrt))
1915 yaz_log(YLOG_FATAL, "Bad result from backend");
1918 else if (bsrt->errcode)
1920 resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
1921 resp->resultCount = nulint;
1922 resp->numberOfRecordsReturned = nulint;
1923 resp->nextResultSetPosition = nulint;
1924 resp->searchStatus = nulint;
1925 resp->resultSetStatus = none;
1926 resp->presentStatus = 0;
1930 int *toget = odr_intdup(assoc->encode, 0);
1931 int *presst = odr_intdup(assoc->encode, 0);
1932 Z_RecordComposition comp, *compp = 0;
1934 yaz_log (log_requestdetail, "resultCount: %d", bsrt->hits);
1937 resp->resultCount = &bsrt->hits;
1939 comp.which = Z_RecordComp_simple;
1940 /* how many records does the user agent want, then? */
1941 if (bsrt->hits <= *req->smallSetUpperBound)
1943 *toget = bsrt->hits;
1944 if ((comp.u.simple = req->smallSetElementSetNames))
1947 else if (bsrt->hits < *req->largeSetLowerBound)
1949 *toget = *req->mediumSetPresentNumber;
1950 if (*toget > bsrt->hits)
1951 *toget = bsrt->hits;
1952 if ((comp.u.simple = req->mediumSetElementSetNames))
1958 if (*toget && !resp->records)
1963 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
1966 form = prefformat->value;
1967 resp->records = pack_records(assoc, req->resultSetName, 1,
1968 toget, compp, next, presst, form, req->referenceId,
1969 req->preferredRecordSyntax, NULL);
1972 resp->numberOfRecordsReturned = toget;
1973 returnedrecs = *toget;
1974 resp->nextResultSetPosition = next;
1975 resp->searchStatus = sr;
1976 resp->resultSetStatus = 0;
1977 resp->presentStatus = presst;
1981 if (*resp->resultCount)
1983 resp->numberOfRecordsReturned = nulint;
1984 resp->nextResultSetPosition = next;
1985 resp->searchStatus = sr;
1986 resp->resultSetStatus = 0;
1987 resp->presentStatus = 0;
1990 resp->additionalSearchInfo = bsrt->search_info;
1994 WRBUF wr = wrbuf_alloc();
1996 wrbuf_printf(wr, "ERROR %d", bsrt->errcode);
1998 wrbuf_printf(wr, "OK %d", bsrt->hits);
1999 wrbuf_printf(wr, " %s 1+%d ",
2000 req->resultSetName, returnedrecs);
2001 wrbuf_put_zquery(wr, req->query);
2003 yaz_log(log_request, "Search %s", wrbuf_buf(wr));
2010 * Maybe we got a little over-friendly when we designed bend_fetch to
2011 * get only one record at a time. Some backends can optimise multiple-record
2012 * fetches, and at any rate, there is some overhead involved in
2013 * all that selecting and hopping around. Problem is, of course, that the
2014 * frontend can't know ahead of time how many records it'll need to
2015 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
2016 * is downright lousy as a bulk data transfer protocol.
2018 * To start with, we'll do the fetching of records from the backend
2019 * in one operation: To save some trips in and out of the event-handler,
2020 * and to simplify the interface to pack_records. At any rate, asynch
2021 * operation is more fun in operations that have an unpredictable execution
2022 * speed - which is normally more true for search than for present.
2024 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
2027 Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
2031 Z_PresentResponse *resp;
2035 const char *errstring = 0;
2037 yaz_log(log_requestdetail, "Got PresentRequest.");
2039 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
2042 form = prefformat->value;
2043 resp = (Z_PresentResponse *)odr_malloc (assoc->encode, sizeof(*resp));
2045 resp->presentStatus = odr_intdup(assoc->encode, 0);
2046 if (assoc->init->bend_present)
2048 bend_present_rr *bprr = (bend_present_rr *)
2049 nmem_malloc (reqb->request_mem, sizeof(*bprr));
2050 bprr->setname = req->resultSetId;
2051 bprr->start = *req->resultSetStartPoint;
2052 bprr->number = *req->numberOfRecordsRequested;
2053 bprr->format = form;
2054 bprr->comp = req->recordComposition;
2055 bprr->referenceId = req->referenceId;
2056 bprr->stream = assoc->encode;
2057 bprr->print = assoc->print;
2058 bprr->request = reqb;
2059 bprr->association = assoc;
2061 bprr->errstring = NULL;
2062 (*assoc->init->bend_present)(assoc->backend, bprr);
2065 return 0; /* should not happen */
2068 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2069 *resp->presentStatus = Z_PresentStatus_failure;
2070 errcode = bprr->errcode;
2071 errstring = bprr->errstring;
2074 apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2075 next = odr_intdup(assoc->encode, 0);
2076 num = odr_intdup(assoc->encode, 0);
2078 apdu->which = Z_APDU_presentResponse;
2079 apdu->u.presentResponse = resp;
2080 resp->referenceId = req->referenceId;
2081 resp->otherInfo = 0;
2085 *num = *req->numberOfRecordsRequested;
2087 pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
2088 num, req->recordComposition, next,
2089 resp->presentStatus,
2090 form, req->referenceId, req->preferredRecordSyntax,
2095 WRBUF wr = wrbuf_alloc();
2096 wrbuf_printf(wr, "Present ");
2098 if (*resp->presentStatus == Z_PresentStatus_failure)
2099 wrbuf_printf(wr, "ERROR %d", errcode);
2100 else if (*resp->presentStatus == Z_PresentStatus_success)
2101 wrbuf_printf(wr, "OK -");
2103 wrbuf_printf(wr, "Partial %d", *resp->presentStatus);
2105 wrbuf_printf(wr, " %s %d+%d ",
2106 req->resultSetId, *req->resultSetStartPoint,
2107 *req->numberOfRecordsRequested);
2108 yaz_log(log_request, "%s", wrbuf_buf(wr) );
2113 resp->numberOfRecordsReturned = num;
2114 resp->nextResultSetPosition = next;
2120 * Scan was implemented rather in a hurry, and with support for only the basic
2121 * elements of the service in the backend API. Suggestions are welcome.
2123 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
2125 Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
2126 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2127 Z_ScanResponse *res = (Z_ScanResponse *)
2128 odr_malloc (assoc->encode, sizeof(*res));
2129 int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
2130 int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
2131 Z_ListEntries *ents = (Z_ListEntries *)
2132 odr_malloc (assoc->encode, sizeof(*ents));
2133 Z_DiagRecs *diagrecs_p = NULL;
2135 bend_scan_rr *bsrr = (bend_scan_rr *)
2136 odr_malloc (assoc->encode, sizeof(*bsrr));
2137 struct scan_entry *save_entries;
2139 yaz_log(log_requestdetail, "Got ScanRequest");
2141 apdu->which = Z_APDU_scanResponse;
2142 apdu->u.scanResponse = res;
2143 res->referenceId = req->referenceId;
2145 /* if step is absent, set it to 0 */
2146 res->stepSize = odr_intdup(assoc->encode, 0);
2148 *res->stepSize = *req->stepSize;
2150 res->scanStatus = scanStatus;
2151 res->numberOfEntriesReturned = numberOfEntriesReturned;
2152 res->positionOfTerm = 0;
2153 res->entries = ents;
2154 ents->num_entries = 0;
2155 ents->entries = NULL;
2156 ents->num_nonsurrogateDiagnostics = 0;
2157 ents->nonsurrogateDiagnostics = NULL;
2158 res->attributeSet = 0;
2161 if (req->databaseNames)
2164 for (i = 0; i < req->num_databaseNames; i++)
2165 yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
2167 yaz_log(log_requestdetail, "pos %d step %d entries %d",
2168 *req->preferredPositionInResponse, *res->stepSize,
2169 *req->numberOfTermsRequested);
2170 bsrr->num_bases = req->num_databaseNames;
2171 bsrr->basenames = req->databaseNames;
2172 bsrr->num_entries = *req->numberOfTermsRequested;
2173 bsrr->term = req->termListAndStartPoint;
2174 bsrr->referenceId = req->referenceId;
2175 bsrr->stream = assoc->encode;
2176 bsrr->print = assoc->print;
2177 bsrr->step_size = res->stepSize;
2179 /* For YAZ 2.0 and earlier it was the backend handler that
2180 initialized entries (member display_term did not exist)
2181 YAZ 2.0 and later sets 'entries' and initialize all members
2182 including 'display_term'. If YAZ 2.0 or later sees that
2183 entries was modified - we assume that it is an old handler and
2184 that 'display_term' is _not_ set.
2186 if (bsrr->num_entries > 0)
2189 bsrr->entries = odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
2191 for (i = 0; i<bsrr->num_entries; i++)
2193 bsrr->entries[i].term = 0;
2194 bsrr->entries[i].occurrences = 0;
2195 bsrr->entries[i].errcode = 0;
2196 bsrr->entries[i].errstring = 0;
2197 bsrr->entries[i].display_term = 0;
2200 save_entries = bsrr->entries; /* save it so we can compare later */
2202 if (req->attributeSet &&
2203 (attset = oid_getentbyoid(req->attributeSet)) &&
2204 (attset->oclass == CLASS_ATTSET || attset->oclass == CLASS_GENERAL))
2205 bsrr->attributeset = attset->value;
2207 bsrr->attributeset = VAL_NONE;
2208 log_scan_term_level (log_requestdetail, req->termListAndStartPoint,
2209 bsrr->attributeset);
2210 bsrr->term_position = req->preferredPositionInResponse ?
2211 *req->preferredPositionInResponse : 1;
2213 ((int (*)(void *, bend_scan_rr *))
2214 (*assoc->init->bend_scan))(assoc->backend, bsrr);
2217 diagrecs_p = zget_DiagRecs(assoc->encode,
2218 bsrr->errcode, bsrr->errstring);
2222 Z_Entry **tab = (Z_Entry **)
2223 odr_malloc (assoc->encode, sizeof(*tab) * bsrr->num_entries);
2225 if (bsrr->status == BEND_SCAN_PARTIAL)
2226 *scanStatus = Z_Scan_partial_5;
2228 *scanStatus = Z_Scan_success;
2229 ents->entries = tab;
2230 ents->num_entries = bsrr->num_entries;
2231 res->numberOfEntriesReturned = &ents->num_entries;
2232 res->positionOfTerm = &bsrr->term_position;
2233 for (i = 0; i < bsrr->num_entries; i++)
2239 tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
2240 if (bsrr->entries[i].occurrences >= 0)
2242 e->which = Z_Entry_termInfo;
2243 e->u.termInfo = t = (Z_TermInfo *)
2244 odr_malloc(assoc->encode, sizeof(*t));
2245 t->suggestedAttributes = 0;
2247 if (save_entries == bsrr->entries &&
2248 bsrr->entries[i].display_term)
2250 /* the entries was _not_ set by the handler. So it's
2251 safe to test for new member display_term. It is
2254 t->displayTerm = odr_strdup(assoc->encode,
2255 bsrr->entries[i].display_term);
2257 t->alternativeTerm = 0;
2258 t->byAttributes = 0;
2259 t->otherTermInfo = 0;
2260 t->globalOccurrences = &bsrr->entries[i].occurrences;
2261 t->term = (Z_Term *)
2262 odr_malloc(assoc->encode, sizeof(*t->term));
2263 t->term->which = Z_Term_general;
2264 t->term->u.general = o =
2265 (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
2266 o->buf = (unsigned char *)
2267 odr_malloc(assoc->encode, o->len = o->size =
2268 strlen(bsrr->entries[i].term));
2269 memcpy(o->buf, bsrr->entries[i].term, o->len);
2270 yaz_log(YLOG_DEBUG, " term #%d: '%s' (%d)", i,
2271 bsrr->entries[i].term, bsrr->entries[i].occurrences);
2275 Z_DiagRecs *drecs = zget_DiagRecs(assoc->encode,
2276 bsrr->entries[i].errcode,
2277 bsrr->entries[i].errstring);
2278 assert (drecs->num_diagRecs == 1);
2279 e->which = Z_Entry_surrogateDiagnostic;
2280 assert (drecs->diagRecs[0]);
2281 e->u.surrogateDiagnostic = drecs->diagRecs[0];
2287 ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
2288 ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
2292 WRBUF wr = wrbuf_alloc();
2294 wr_diag(wr, bsrr->errcode, bsrr->errstring);
2295 else if (*res->scanStatus == Z_Scan_success)
2296 wrbuf_printf(wr, "OK");
2298 wrbuf_printf(wr, "Partial");
2300 wrbuf_printf(wr, " %d+%d %d ",
2301 *req->preferredPositionInResponse,
2302 *req->numberOfTermsRequested,
2303 (res->stepSize ? *res->stepSize : 0));
2304 wrbuf_scan_term(wr, req->termListAndStartPoint,
2305 bsrr->attributeset);
2307 yaz_log(log_request, "Scan %s", wrbuf_buf(wr) );
2313 static Z_APDU *process_sortRequest(association *assoc, request *reqb,
2317 Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
2318 Z_SortResponse *res = (Z_SortResponse *)
2319 odr_malloc (assoc->encode, sizeof(*res));
2320 bend_sort_rr *bsrr = (bend_sort_rr *)
2321 odr_malloc (assoc->encode, sizeof(*bsrr));
2323 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2325 yaz_log(log_requestdetail, "Got SortRequest.");
2327 bsrr->num_input_setnames = req->num_inputResultSetNames;
2328 for (i=0;i<req->num_inputResultSetNames;i++)
2329 yaz_log(log_requestdetail, "Input resultset: '%s'",
2330 req->inputResultSetNames[i]);
2331 bsrr->input_setnames = req->inputResultSetNames;
2332 bsrr->referenceId = req->referenceId;
2333 bsrr->output_setname = req->sortedResultSetName;
2334 yaz_log(log_requestdetail, "Output resultset: '%s'",
2335 req->sortedResultSetName);
2336 bsrr->sort_sequence = req->sortSequence;
2337 /*FIXME - dump those sequences too */
2338 bsrr->stream = assoc->encode;
2339 bsrr->print = assoc->print;
2341 bsrr->sort_status = Z_SortResponse_failure;
2343 bsrr->errstring = 0;
2345 (*assoc->init->bend_sort)(assoc->backend, bsrr);
2347 res->referenceId = bsrr->referenceId;
2348 res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
2349 res->resultSetStatus = 0;
2352 Z_DiagRecs *dr = zget_DiagRecs(assoc->encode,
2353 bsrr->errcode, bsrr->errstring);
2354 res->diagnostics = dr->diagRecs;
2355 res->num_diagnostics = dr->num_diagRecs;
2359 res->num_diagnostics = 0;
2360 res->diagnostics = 0;
2362 res->resultCount = 0;
2365 apdu->which = Z_APDU_sortResponse;
2366 apdu->u.sortResponse = res;
2369 WRBUF wr = wrbuf_alloc();
2370 wrbuf_printf(wr, "Sort ");
2372 wrbuf_printf(wr, " ERROR %d", bsrr->errcode);
2374 wrbuf_printf(wr, "OK -");
2375 wrbuf_printf(wr, " (");
2376 for (i = 0; i<req->num_inputResultSetNames; i++)
2379 wrbuf_printf(wr, ",");
2380 wrbuf_printf(wr, req->inputResultSetNames[i]);
2382 wrbuf_printf(wr, ")->%s ",req->sortedResultSetName);
2384 yaz_log(log_request, "%s", wrbuf_buf(wr) );
2390 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
2394 Z_DeleteResultSetRequest *req =
2395 reqb->apdu_request->u.deleteResultSetRequest;
2396 Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
2397 odr_malloc (assoc->encode, sizeof(*res));
2398 bend_delete_rr *bdrr = (bend_delete_rr *)
2399 odr_malloc (assoc->encode, sizeof(*bdrr));
2400 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2402 yaz_log(log_requestdetail, "Got DeleteRequest.");
2404 bdrr->num_setnames = req->num_resultSetList;
2405 bdrr->setnames = req->resultSetList;
2406 for (i = 0; i<req->num_resultSetList; i++)
2407 yaz_log(log_requestdetail, "resultset: '%s'",
2408 req->resultSetList[i]);
2409 bdrr->stream = assoc->encode;
2410 bdrr->print = assoc->print;
2411 bdrr->function = *req->deleteFunction;
2412 bdrr->referenceId = req->referenceId;
2414 if (bdrr->num_setnames > 0)
2416 bdrr->statuses = (int*)
2417 odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
2418 bdrr->num_setnames);
2419 for (i = 0; i < bdrr->num_setnames; i++)
2420 bdrr->statuses[i] = 0;
2422 (*assoc->init->bend_delete)(assoc->backend, bdrr);
2424 res->referenceId = req->referenceId;
2426 res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
2428 res->deleteListStatuses = 0;
2429 if (bdrr->num_setnames > 0)
2432 res->deleteListStatuses = (Z_ListStatuses *)
2433 odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
2434 res->deleteListStatuses->num = bdrr->num_setnames;
2435 res->deleteListStatuses->elements =
2437 odr_malloc (assoc->encode,
2438 sizeof(*res->deleteListStatuses->elements) *
2439 bdrr->num_setnames);
2440 for (i = 0; i<bdrr->num_setnames; i++)
2442 res->deleteListStatuses->elements[i] =
2444 odr_malloc (assoc->encode,
2445 sizeof(**res->deleteListStatuses->elements));
2446 res->deleteListStatuses->elements[i]->status = bdrr->statuses+i;
2447 res->deleteListStatuses->elements[i]->id =
2448 odr_strdup (assoc->encode, bdrr->setnames[i]);
2451 res->numberNotDeleted = 0;
2452 res->bulkStatuses = 0;
2453 res->deleteMessage = 0;
2456 apdu->which = Z_APDU_deleteResultSetResponse;
2457 apdu->u.deleteResultSetResponse = res;
2460 WRBUF wr = wrbuf_alloc();
2461 wrbuf_printf(wr, "Delete ");
2462 if (bdrr->delete_status)
2463 wrbuf_printf(wr, "ERROR %d", bdrr->delete_status);
2465 wrbuf_printf(wr, "OK -");
2466 for (i = 0; i<req->num_resultSetList; i++)
2467 wrbuf_printf(wr, " %s ", req->resultSetList[i]);
2468 yaz_log(log_request, "%s", wrbuf_buf(wr) );
2474 static void process_close(association *assoc, request *reqb)
2476 Z_Close *req = reqb->apdu_request->u.close;
2477 static char *reasons[] =
2484 "securityViolation",
2491 yaz_log(log_requestdetail, "Got Close, reason %s, message %s",
2492 reasons[*req->closeReason], req->diagnosticInformation ?
2493 req->diagnosticInformation : "NULL");
2494 if (assoc->version < 3) /* to make do_force respond with close */
2496 do_close_req(assoc, Z_Close_finished,
2497 "Association terminated by client", reqb);
2498 yaz_log(log_request,"Close OK");
2501 void save_referenceId (request *reqb, Z_ReferenceId *refid)
2505 reqb->len_refid = refid->len;
2506 reqb->refid = (char *)nmem_malloc (reqb->request_mem, refid->len);
2507 memcpy (reqb->refid, refid->buf, refid->len);
2511 reqb->len_refid = 0;
2516 void bend_request_send (bend_association a, bend_request req, Z_APDU *res)
2518 process_z_response (a, req, res);
2521 bend_request bend_request_mk (bend_association a)
2523 request *nreq = request_get (&a->outgoing);
2524 nreq->request_mem = nmem_create ();
2528 Z_ReferenceId *bend_request_getid (ODR odr, bend_request req)
2533 id = (Odr_oct *)odr_malloc (odr, sizeof(*odr));
2534 id->buf = (unsigned char *)odr_malloc (odr, req->len_refid);
2535 id->len = id->size = req->len_refid;
2536 memcpy (id->buf, req->refid, req->len_refid);
2540 void bend_request_destroy (bend_request *req)
2542 nmem_destroy((*req)->request_mem);
2543 request_release(*req);
2547 int bend_backend_respond (bend_association a, bend_request req)
2551 r = process_z_request (a, req, &msg);
2553 yaz_log (YLOG_WARN, "%s", msg);
2557 void bend_request_setdata(bend_request r, void *p)
2562 void *bend_request_getdata(bend_request r)
2564 return r->clientData;
2567 static Z_APDU *process_segmentRequest (association *assoc, request *reqb)
2569 bend_segment_rr req;
2571 req.segment = reqb->apdu_request->u.segmentRequest;
2572 req.stream = assoc->encode;
2573 req.decode = assoc->decode;
2574 req.print = assoc->print;
2575 req.association = assoc;
2577 (*assoc->init->bend_segment)(assoc->backend, &req);
2582 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd)
2584 bend_esrequest_rr esrequest;
2586 Z_ExtendedServicesRequest *req =
2587 reqb->apdu_request->u.extendedServicesRequest;
2588 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
2590 Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
2592 yaz_log(log_requestdetail,"Got EsRequest");
2594 esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
2595 esrequest.stream = assoc->encode;
2596 esrequest.decode = assoc->decode;
2597 esrequest.print = assoc->print;
2598 esrequest.errcode = 0;
2599 esrequest.errstring = NULL;
2600 esrequest.request = reqb;
2601 esrequest.association = assoc;
2602 esrequest.taskPackage = 0;
2603 esrequest.referenceId = req->referenceId;
2605 (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
2607 /* If the response is being delayed, return NULL */
2608 if (esrequest.request == NULL)
2611 resp->referenceId = req->referenceId;
2613 if (esrequest.errcode == -1)
2615 /* Backend service indicates request will be processed */
2616 yaz_log(log_request,"EsRequest OK: Accepted !");
2617 *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
2619 else if (esrequest.errcode == 0)
2621 /* Backend service indicates request will be processed */
2622 yaz_log(log_request,"EsRequest OK: Done !");
2623 *resp->operationStatus = Z_ExtendedServicesResponse_done;
2627 Z_DiagRecs *diagRecs =
2628 zget_DiagRecs(assoc->encode, esrequest.errcode,
2629 esrequest.errstring);
2630 /* Backend indicates error, request will not be processed */
2631 yaz_log(YLOG_DEBUG,"Request could not be processed...failure !");
2632 *resp->operationStatus = Z_ExtendedServicesResponse_failure;
2633 resp->num_diagnostics = diagRecs->num_diagRecs;
2634 resp->diagnostics = diagRecs->diagRecs;
2637 WRBUF wr = wrbuf_alloc();
2638 wrbuf_diags(wr, resp->num_diagnostics, resp->diagnostics);
2639 yaz_log(log_request, "EsRequest %s", wrbuf_buf(wr) );
2644 /* Do something with the members of bend_extendedservice */
2645 if (esrequest.taskPackage)
2646 resp->taskPackage = z_ext_record (assoc->encode, VAL_EXTENDED,
2647 (const char *) esrequest.taskPackage,
2649 yaz_log(YLOG_DEBUG,"Send the result apdu");