2 * Copyright (C) 1995-2005, Index Data ApS
3 * See the file LICENSE for details.
5 * $Id: seshigh.c,v 1.45 2005-01-16 21:51:50 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 FILE *apduf = 0; /* for use in static mode */
95 static statserv_options_block *control_block = 0;
97 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd);
99 /* dynamic logging levels */
100 static int logbits_set = 0;
101 static int log_session = 0;
102 static int log_request = 0; /* one-line logs for requests */
103 static int log_requestdetail = 0; /* more detailed stuff */
105 /** get_logbits sets global loglevel bits */
106 static void get_logbits()
107 { /* needs to be called after parsing cmd-line args that can set loglevels!*/
111 log_session=yaz_log_module_level("session");
112 log_request=yaz_log_module_level("request");
113 log_requestdetail=yaz_log_module_level("requestdetail");
117 static void wr_diag(WRBUF w, int error, const char *addinfo)
119 wrbuf_printf(w, "ERROR [%d] %s%s%s",
120 error, diagbib1_str(error),
121 addinfo ? "--" : "", addinfo ? addinfo : "");
126 * Create and initialize a new association-handle.
127 * channel : iochannel for the current line.
128 * link : communications channel.
129 * Returns: 0 or a new association handle.
131 association *create_association(IOCHAN channel, COMSTACK link)
138 control_block = statserv_getcontrol();
139 if (!(anew = (association *)xmalloc(sizeof(*anew))))
143 anew->client_chan = channel;
144 anew->client_link = link;
145 anew->cs_get_mask = 0;
146 anew->cs_put_mask = 0;
147 anew->cs_accept_mask = 0;
148 if (!(anew->decode = odr_createmem(ODR_DECODE)) ||
149 !(anew->encode = odr_createmem(ODR_ENCODE)))
151 if (*control_block->apdufile)
156 strcpy(filename, control_block->apdufile);
157 if (!(anew->print = odr_createmem(ODR_PRINT)))
159 if (*control_block->apdufile == '@')
161 odr_setprint(anew->print, yaz_log_file());
163 else if (*control_block->apdufile != '-')
165 strcpy(filename, control_block->apdufile);
166 if (!control_block->dynamic)
170 if (!(apduf = fopen(filename, "w")))
172 yaz_log(YLOG_WARN|YLOG_ERRNO, "can't open apdu dump %s", filename);
175 setvbuf(apduf, 0, _IONBF, 0);
181 sprintf(filename + strlen(filename), ".%ld", (long)getpid());
182 if (!(f = fopen(filename, "w")))
184 yaz_log(YLOG_WARN|YLOG_ERRNO, "%s", filename);
187 setvbuf(f, 0, _IONBF, 0);
189 odr_setprint(anew->print, f);
194 anew->input_buffer = 0;
195 anew->input_buffer_len = 0;
197 anew->state = ASSOC_NEW;
198 request_initq(&anew->incoming);
199 request_initq(&anew->outgoing);
200 anew->proto = cs_getproto(link);
205 * Free association and release resources.
207 void destroy_association(association *h)
209 statserv_options_block *cb = statserv_getcontrol();
213 odr_destroy(h->decode);
214 odr_destroy(h->encode);
216 odr_destroy(h->print);
218 xfree(h->input_buffer);
220 (*cb->bend_close)(h->backend);
221 while ((req = request_deq(&h->incoming)))
222 request_release(req);
223 while ((req = request_deq(&h->outgoing)))
224 request_release(req);
225 request_delq(&h->incoming);
226 request_delq(&h->outgoing);
228 xmalloc_trav("session closed");
229 if (control_block && control_block->one_shot)
235 static void do_close_req(association *a, int reason, char *message,
239 Z_Close *cls = zget_Close(a->encode);
241 /* Purge request queue */
242 while (request_deq(&a->incoming));
243 while (request_deq(&a->outgoing));
246 yaz_log(log_requestdetail, "Sending Close PDU, reason=%d, message=%s",
247 reason, message ? message : "none");
248 apdu.which = Z_APDU_close;
250 *cls->closeReason = reason;
251 cls->diagnosticInformation = message;
252 process_z_response(a, req, &apdu);
253 iochan_settimeout(a->client_chan, 20);
257 request_release(req);
258 yaz_log(log_requestdetail, "v2 client. No Close PDU");
259 iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
261 a->state = ASSOC_DEAD;
264 static void do_close(association *a, int reason, char *message)
266 request *req = request_get(&a->outgoing);
267 do_close_req (a, reason, message, req);
271 * This is where PDUs from the client are read and the further
272 * processing is initiated. Flow of control moves down through the
273 * various process_* functions below, until the encoded result comes back up
274 * to the output handler in here.
276 * h : the I/O channel that has an outstanding event.
277 * event : the current outstanding event.
279 void ir_session(IOCHAN h, int event)
282 association *assoc = (association *)iochan_getdata(h);
283 COMSTACK conn = assoc->client_link;
286 assert(h && conn && assoc);
287 if (event == EVENT_TIMEOUT)
289 if (assoc->state != ASSOC_UP)
291 yaz_log(YLOG_DEBUG, "Final timeout - closing connection.");
292 /* do we need to lod this at all */
294 destroy_association(assoc);
299 yaz_log(log_session, "Session idle too long. Sending close.");
300 do_close(assoc, Z_Close_lackOfActivity, 0);
304 if (event & assoc->cs_accept_mask)
306 if (!cs_accept (conn))
308 yaz_log (YLOG_WARN, "accept failed");
309 destroy_association(assoc);
312 iochan_clearflag (h, EVENT_OUTPUT);
313 if (conn->io_pending)
314 { /* cs_accept didn't complete */
315 assoc->cs_accept_mask =
316 ((conn->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
317 ((conn->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
319 iochan_setflag (h, assoc->cs_accept_mask);
322 { /* cs_accept completed. Prepare for reading (cs_get) */
323 assoc->cs_accept_mask = 0;
324 assoc->cs_get_mask = EVENT_INPUT;
325 iochan_setflag (h, assoc->cs_get_mask);
329 if ((event & assoc->cs_get_mask) || (event & EVENT_WORK)) /* input */
331 if ((assoc->cs_put_mask & EVENT_INPUT) == 0 && (event & assoc->cs_get_mask))
333 yaz_log(YLOG_DEBUG, "ir_session (input)");
334 /* We aren't speaking to this fellow */
335 if (assoc->state == ASSOC_DEAD)
337 yaz_log(log_session, "Connection closed - end of session");
339 destroy_association(assoc);
343 assoc->cs_get_mask = EVENT_INPUT;
344 if ((res = cs_get(conn, &assoc->input_buffer,
345 &assoc->input_buffer_len)) <= 0)
347 yaz_log(log_session, "Connection closed by client");
349 destroy_association(assoc);
353 else if (res == 1) /* incomplete read - wait for more */
355 if (conn->io_pending & CS_WANT_WRITE)
356 assoc->cs_get_mask |= EVENT_OUTPUT;
357 iochan_setflag(h, assoc->cs_get_mask);
360 if (cs_more(conn)) /* more stuff - call us again later, please */
361 iochan_setevent(h, EVENT_INPUT);
363 /* we got a complete PDU. Let's decode it */
364 yaz_log(YLOG_DEBUG, "Got PDU, %d bytes: lead=%02X %02X %02X", res,
365 assoc->input_buffer[0] & 0xff,
366 assoc->input_buffer[1] & 0xff,
367 assoc->input_buffer[2] & 0xff);
368 req = request_get(&assoc->incoming); /* get a new request */
369 odr_reset(assoc->decode);
370 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
371 if (!z_GDU(assoc->decode, &req->gdu_request, 0, 0))
373 yaz_log(YLOG_WARN, "ODR error on incoming PDU: %s [element %s] "
375 odr_errmsg(odr_geterror(assoc->decode)),
376 odr_getelement(assoc->decode),
377 odr_offset(assoc->decode));
378 if (assoc->decode->error != OHTTP)
380 yaz_log(YLOG_WARN, "PDU dump:");
381 odr_dumpBER(yaz_log_file(), assoc->input_buffer, res);
382 request_release(req);
383 do_close(assoc, Z_Close_protocolError,"Malformed package");
387 Z_GDU *p = z_get_HTTP_Response(assoc->encode, 400);
388 assoc->state = ASSOC_DEAD;
389 process_gdu_response(assoc, req, p);
393 req->request_mem = odr_extract_mem(assoc->decode);
396 if (!z_GDU(assoc->print, &req->gdu_request, 0, 0))
397 yaz_log(YLOG_WARN, "ODR print error: %s",
398 odr_errmsg(odr_geterror(assoc->print)));
399 odr_reset(assoc->print);
401 request_enq(&assoc->incoming, req);
404 /* can we do something yet? */
405 req = request_head(&assoc->incoming);
406 if (req->state == REQUEST_IDLE)
408 request_deq(&assoc->incoming);
409 process_gdu_request(assoc, req);
412 if (event & assoc->cs_put_mask)
414 request *req = request_head(&assoc->outgoing);
416 assoc->cs_put_mask = 0;
417 yaz_log(YLOG_DEBUG, "ir_session (output)");
418 req->state = REQUEST_PENDING;
419 switch (res = cs_put(conn, req->response, req->len_response))
422 yaz_log(log_session, "Connection closed by client");
424 destroy_association(assoc);
427 case 0: /* all sent - release the request structure */
428 yaz_log(YLOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
430 yaz_log(YLOG_DEBUG, "HTTP out:\n%.*s", req->len_response,
433 nmem_destroy(req->request_mem);
434 request_deq(&assoc->outgoing);
435 request_release(req);
436 if (!request_head(&assoc->outgoing))
437 { /* restore mask for cs_get operation ... */
438 iochan_clearflag(h, EVENT_OUTPUT|EVENT_INPUT);
439 iochan_setflag(h, assoc->cs_get_mask);
440 if (assoc->state == ASSOC_DEAD)
441 iochan_setevent(assoc->client_chan, EVENT_TIMEOUT);
445 assoc->cs_put_mask = EVENT_OUTPUT;
449 if (conn->io_pending & CS_WANT_WRITE)
450 assoc->cs_put_mask |= EVENT_OUTPUT;
451 if (conn->io_pending & CS_WANT_READ)
452 assoc->cs_put_mask |= EVENT_INPUT;
453 iochan_setflag(h, assoc->cs_put_mask);
456 if (event & EVENT_EXCEPT)
458 yaz_log(YLOG_WARN, "ir_session (exception)");
460 destroy_association(assoc);
465 static int process_z_request(association *assoc, request *req, char **msg);
467 static void assoc_init_reset(association *assoc)
470 assoc->init = (bend_initrequest *) xmalloc (sizeof(*assoc->init));
472 assoc->init->stream = assoc->encode;
473 assoc->init->print = assoc->print;
474 assoc->init->auth = 0;
475 assoc->init->referenceId = 0;
476 assoc->init->implementation_version = 0;
477 assoc->init->implementation_id = 0;
478 assoc->init->implementation_name = 0;
479 assoc->init->bend_sort = NULL;
480 assoc->init->bend_search = NULL;
481 assoc->init->bend_present = NULL;
482 assoc->init->bend_esrequest = NULL;
483 assoc->init->bend_delete = NULL;
484 assoc->init->bend_scan = NULL;
485 assoc->init->bend_segment = NULL;
486 assoc->init->bend_fetch = NULL;
487 assoc->init->bend_explain = NULL;
488 assoc->init->bend_srw_scan = NULL;
490 assoc->init->charneg_request = NULL;
491 assoc->init->charneg_response = NULL;
493 assoc->init->decode = assoc->decode;
494 assoc->init->peer_name =
495 odr_strdup (assoc->encode, cs_addrstr(assoc->client_link));
498 static int srw_bend_init(association *assoc, Z_SRW_diagnostic **d, int *num)
500 const char *encoding = "UTF-8";
502 bend_initresult *binitres;
503 statserv_options_block *cb = statserv_getcontrol();
505 assoc_init_reset(assoc);
507 assoc->maximumRecordSize = 3000000;
508 assoc->preferredMessageSize = 3000000;
510 ce = yaz_set_proposal_charneg(assoc->decode, &encoding, 1, 0, 0, 1);
511 assoc->init->charneg_request = ce->u.charNeg3;
514 if (!(binitres = (*cb->bend_init)(assoc->init)))
516 assoc->state = ASSOC_DEAD;
517 yaz_add_srw_diagnostic(assoc->encode, d, num, 3, 0);
520 assoc->backend = binitres->handle;
521 if (binitres->errcode)
523 assoc->state = ASSOC_DEAD;
524 yaz_add_srw_diagnostic(assoc->encode, d, num, binitres->errcode,
525 binitres->errstring);
531 static int srw_bend_fetch(association *assoc, int pos,
532 Z_SRW_searchRetrieveRequest *srw_req,
533 Z_SRW_record *record)
536 ODR o = assoc->encode;
538 rr.setname = "default";
541 rr.request_format = VAL_TEXT_XML;
542 rr.request_format_raw = yaz_oidval_to_z3950oid(assoc->decode,
545 rr.comp = (Z_RecordComposition *)
546 odr_malloc(assoc->decode, sizeof(*rr.comp));
547 rr.comp->which = Z_RecordComp_complex;
548 rr.comp->u.complex = (Z_CompSpec *)
549 odr_malloc(assoc->decode, sizeof(Z_CompSpec));
550 rr.comp->u.complex->selectAlternativeSyntax = (bool_t *)
551 odr_malloc(assoc->encode, sizeof(bool_t));
552 *rr.comp->u.complex->selectAlternativeSyntax = 0;
553 rr.comp->u.complex->num_dbSpecific = 0;
554 rr.comp->u.complex->dbSpecific = 0;
555 rr.comp->u.complex->num_recordSyntax = 0;
556 rr.comp->u.complex->recordSyntax = 0;
558 rr.comp->u.complex->generic = (Z_Specification *)
559 odr_malloc(assoc->decode, sizeof(Z_Specification));
561 /* schema uri = recordSchema (or NULL if recordSchema is not given) */
562 rr.comp->u.complex->generic->which = Z_Schema_uri;
563 rr.comp->u.complex->generic->schema.uri = srw_req->recordSchema;
565 /* ESN = recordSchema if recordSchema is present */
566 rr.comp->u.complex->generic->elementSpec = 0;
567 if (srw_req->recordSchema)
569 rr.comp->u.complex->generic->elementSpec =
570 (Z_ElementSpec *) odr_malloc(assoc->encode, sizeof(Z_ElementSpec));
571 rr.comp->u.complex->generic->elementSpec->which =
572 Z_ElementSpec_elementSetName;
573 rr.comp->u.complex->generic->elementSpec->u.elementSetName =
574 srw_req->recordSchema;
577 rr.stream = assoc->encode;
578 rr.print = assoc->print;
584 rr.output_format = VAL_TEXT_XML;
585 rr.output_format_raw = 0;
588 rr.surrogate_flag = 0;
589 rr.schema = srw_req->recordSchema;
591 if (!assoc->init->bend_fetch)
594 (*assoc->init->bend_fetch)(assoc->backend, &rr);
596 if (rr.errcode && rr.surrogate_flag)
598 int code = yaz_diag_bib1_to_srw(rr.errcode);
599 const char *message = yaz_diag_srw_str(code);
602 len += strlen(message);
604 len += strlen(rr.errstring);
606 record->recordData_buf = odr_malloc(o, len);
608 sprintf(record->recordData_buf, "<diagnostic "
609 "xmlns=\"http://www.loc.gov/zing/srw/diagnostic/\">\n"
610 " <uri>info:srw/diagnostic/1/%d</uri>\n", code);
612 sprintf(record->recordData_buf + strlen(record->recordData_buf),
613 " <details>%s</details>\n", rr.errstring);
615 sprintf(record->recordData_buf + strlen(record->recordData_buf),
616 " <message>%s</message>\n", message);
617 sprintf(record->recordData_buf + strlen(record->recordData_buf),
619 record->recordData_len = strlen(record->recordData_buf);
620 record->recordPosition = odr_intdup(o, pos);
621 record->recordSchema = "info:srw/schema/1/diagnostics-v1.1";
624 else if (rr.len >= 0)
626 record->recordData_buf = rr.record;
627 record->recordData_len = rr.len;
628 record->recordPosition = odr_intdup(o, pos);
630 record->recordSchema = odr_strdup(o, rr.schema);
632 record->recordSchema = 0;
637 static void srw_bend_search(association *assoc, request *req,
638 Z_SRW_searchRetrieveRequest *srw_req,
639 Z_SRW_searchRetrieveResponse *srw_res,
646 yaz_log(log_requestdetail, "Got SRW SearchRetrieveRequest");
648 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics);
649 if (srw_req->sort_type != Z_SRW_sort_type_none)
650 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
651 &srw_res->num_diagnostics, 80, 0);
652 else if (srw_res->num_diagnostics == 0 && assoc->init)
655 rr.setname = "default";
658 rr.basenames = &srw_req->database;
661 rr.query = (Z_Query *) odr_malloc (assoc->decode, sizeof(*rr.query));
663 if (srw_req->query_type == Z_SRW_query_type_cql)
665 ext = (Z_External *) odr_malloc(assoc->decode, sizeof(*ext));
666 ext->direct_reference = odr_getoidbystr(assoc->decode,
667 "1.2.840.10003.16.2");
668 ext->indirect_reference = 0;
670 ext->which = Z_External_CQL;
671 ext->u.cql = srw_req->query.cql;
673 rr.query->which = Z_Query_type_104;
674 rr.query->u.type_104 = ext;
676 else if (srw_req->query_type == Z_SRW_query_type_pqf)
678 Z_RPNQuery *RPNquery;
679 YAZ_PQF_Parser pqf_parser;
681 pqf_parser = yaz_pqf_create ();
683 RPNquery = yaz_pqf_parse (pqf_parser, assoc->decode,
689 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
690 yaz_log(log_requestdetail, "Parse error %d %s near offset %d",
695 rr.query->which = Z_Query_type_1;
696 rr.query->u.type_1 = RPNquery;
698 yaz_pqf_destroy (pqf_parser);
702 rr.query->u.type_1 = 0;
703 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
704 &srw_res->num_diagnostics, 11, 0);
706 if (rr.query->u.type_1)
708 rr.stream = assoc->encode;
709 rr.decode = assoc->decode;
710 rr.print = assoc->print;
712 rr.association = assoc;
718 yaz_log_zquery_level(log_requestdetail,rr.query);
720 (assoc->init->bend_search)(assoc->backend, &rr);
723 if (rr.errcode == 109) /* database unavailable */
729 srw_error = yaz_diag_bib1_to_srw (rr.errcode);
730 yaz_add_srw_diagnostic(assoc->encode,
731 &srw_res->diagnostics,
732 &srw_res->num_diagnostics,
733 srw_error, rr.errstring);
738 int number = srw_req->maximumRecords ? *srw_req->maximumRecords : 0;
739 int start = srw_req->startRecord ? *srw_req->startRecord : 1;
741 yaz_log(log_requestdetail, "Request to pack %d+%d out of %d",
742 start, number, rr.hits);
744 srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
751 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
752 &srw_res->num_diagnostics,
758 int packing = Z_SRW_recordPacking_string;
759 if (start + number > rr.hits)
760 number = rr.hits - start + 1;
761 if (srw_req->recordPacking &&
762 !strcmp(srw_req->recordPacking, "xml"))
763 packing = Z_SRW_recordPacking_XML;
764 srw_res->records = (Z_SRW_record *)
765 odr_malloc(assoc->encode,
766 number * sizeof(*srw_res->records));
767 for (i = 0; i<number; i++)
771 srw_res->records[j].recordPacking = packing;
772 srw_res->records[j].recordData_buf = 0;
773 yaz_log(YLOG_DEBUG, "srw_bend_fetch %d", i+start);
774 errcode = srw_bend_fetch(assoc, i+start, srw_req,
775 srw_res->records + j);
778 yaz_add_srw_diagnostic(assoc->encode,
779 &srw_res->diagnostics,
780 &srw_res->num_diagnostics,
781 yaz_diag_bib1_to_srw (errcode),
786 if (srw_res->records[j].recordData_buf)
789 srw_res->num_records = j;
791 srw_res->records = 0;
799 const char *querystr = "?";
800 const char *querytype = "?";
801 WRBUF wr = wrbuf_alloc();
803 switch (srw_req->query_type)
805 case Z_SRW_query_type_cql:
807 querystr = srw_req->query.cql;
809 case Z_SRW_query_type_pqf:
811 querystr = srw_req->query.pqf;
814 wrbuf_printf(wr, "SRWSearch ");
815 if (srw_res->num_diagnostics)
816 wrbuf_printf(wr, "ERROR %s", srw_res->diagnostics[0].uri);
817 else if (*http_code != 200)
818 wrbuf_printf(wr, "ERROR info:http/%d", *http_code);
819 else if (srw_res->numberOfRecords)
821 wrbuf_printf(wr, "OK %d",
822 (srw_res->numberOfRecords ?
823 *srw_res->numberOfRecords : 0));
825 wrbuf_printf(wr, " %s %d+%d",
826 (srw_res->resultSetId ?
827 srw_res->resultSetId : "-"),
828 (srw_req->startRecord ? *srw_req->startRecord : 1),
829 srw_res->num_records);
830 yaz_log(log_request, "%s %s: %s", wrbuf_buf(wr), querytype, querystr);
835 static void srw_bend_explain(association *assoc, request *req,
836 Z_SRW_explainRequest *srw_req,
837 Z_SRW_explainResponse *srw_res,
840 yaz_log(log_requestdetail, "Got SRW ExplainRequest");
843 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics);
844 if (assoc->init && assoc->init->bend_explain)
848 rr.stream = assoc->encode;
849 rr.decode = assoc->decode;
850 rr.print = assoc->print;
852 rr.database = srw_req->database;
853 rr.schema = "http://explain.z3950.org/dtd/2.0/";
854 (*assoc->init->bend_explain)(assoc->backend, &rr);
857 int packing = Z_SRW_recordPacking_string;
858 if (srw_req->recordPacking &&
859 !strcmp(srw_req->recordPacking, "xml"))
860 packing = Z_SRW_recordPacking_XML;
861 srw_res->record.recordSchema = rr.schema;
862 srw_res->record.recordPacking = packing;
863 srw_res->record.recordData_buf = rr.explain_buf;
864 srw_res->record.recordData_len = strlen(rr.explain_buf);
865 srw_res->record.recordPosition = 0;
871 static void srw_bend_scan(association *assoc, request *req,
872 Z_SRW_scanRequest *srw_req,
873 Z_SRW_scanResponse *srw_res,
876 yaz_log(log_requestdetail, "Got SRW ScanRequest");
880 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics);
881 if (srw_res->num_diagnostics == 0 && assoc->init)
883 struct scan_entry *save_entries;
885 bend_scan_rr *bsrr = (bend_scan_rr *)
886 odr_malloc (assoc->encode, sizeof(*bsrr));
888 bsrr->basenames = &srw_req->database;
890 bsrr->num_entries = srw_req->maximumTerms ?
891 *srw_req->maximumTerms : 10;
892 bsrr->term_position = srw_req->responsePosition ?
893 *srw_req->responsePosition : 1;
897 bsrr->referenceId = 0;
898 bsrr->stream = assoc->encode;
899 bsrr->print = assoc->print;
900 bsrr->step_size = odr_intdup(assoc->decode, 0);
903 if (bsrr->num_entries > 0)
906 bsrr->entries = odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
908 for (i = 0; i<bsrr->num_entries; i++)
910 bsrr->entries[i].term = 0;
911 bsrr->entries[i].occurrences = 0;
912 bsrr->entries[i].errcode = 0;
913 bsrr->entries[i].errstring = 0;
914 bsrr->entries[i].display_term = 0;
917 save_entries = bsrr->entries; /* save it so we can compare later */
919 if (srw_req->query_type == Z_SRW_query_type_pqf &&
920 assoc->init->bend_scan)
922 Odr_oid *scan_attributeSet = 0;
924 YAZ_PQF_Parser pqf_parser = yaz_pqf_create();
926 bsrr->term = yaz_pqf_scan(pqf_parser, assoc->decode,
928 srw_req->scanClause.pqf);
929 if (scan_attributeSet &&
930 (attset = oid_getentbyoid(scan_attributeSet)) &&
931 (attset->oclass == CLASS_ATTSET ||
932 attset->oclass == CLASS_GENERAL))
933 bsrr->attributeset = attset->value;
935 bsrr->attributeset = VAL_NONE;
936 yaz_pqf_destroy(pqf_parser);
937 bsrr->scanClause = 0;
938 ((int (*)(void *, bend_scan_rr *))
939 (*assoc->init->bend_scan))(assoc->backend, bsrr);
941 else if (srw_req->query_type == Z_SRW_query_type_cql
942 && assoc->init->bend_srw_scan)
945 bsrr->attributeset = VAL_NONE;
946 bsrr->scanClause = srw_req->scanClause.cql;
947 ((int (*)(void *, bend_scan_rr *))
948 (*assoc->init->bend_srw_scan))(assoc->backend, bsrr);
952 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
953 &srw_res->num_diagnostics, 4, "scan");
958 if (bsrr->errcode == 109) /* database unavailable */
963 srw_error = yaz_diag_bib1_to_srw (bsrr->errcode);
965 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
966 &srw_res->num_diagnostics,
967 srw_error, bsrr->errstring);
969 else if (srw_res->num_diagnostics == 0 && bsrr->num_entries)
972 srw_res->terms = (Z_SRW_scanTerm*)
973 odr_malloc(assoc->encode, sizeof(*srw_res->terms) *
976 srw_res->num_terms = bsrr->num_entries;
977 for (i = 0; i<bsrr->num_entries; i++)
979 Z_SRW_scanTerm *t = srw_res->terms + i;
980 t->value = odr_strdup(assoc->encode, bsrr->entries[i].term);
982 odr_intdup(assoc->encode, bsrr->entries[i].occurrences);
984 if (save_entries == bsrr->entries &&
985 bsrr->entries[i].display_term)
987 /* the entries was _not_ set by the handler. So it's
988 safe to test for new member display_term. It is
991 t->displayTerm = odr_strdup(assoc->encode,
992 bsrr->entries[i].display_term);
1000 WRBUF wr = wrbuf_alloc();
1001 const char *querytype = 0;
1002 const char *querystr = 0;
1004 switch(srw_req->query_type)
1006 case Z_SRW_query_type_pqf:
1008 querystr = srw_req->scanClause.pqf;
1010 case Z_SRW_query_type_cql:
1012 querystr = srw_req->scanClause.cql;
1015 querytype = "Unknown";
1018 wrbuf_printf(wr, "SRWScan %d+%d",
1019 (srw_req->responsePosition ?
1020 *srw_req->responsePosition : 1),
1021 (srw_req->maximumTerms ?
1022 *srw_req->maximumTerms : 1));
1023 if (srw_res->num_diagnostics)
1024 wrbuf_printf(wr, " ERROR %s", srw_res->diagnostics[0].uri);
1026 wrbuf_printf(wr, " OK -");
1027 wrbuf_printf(wr, " %s: %s", querytype, querystr);
1028 yaz_log(log_request, "%s", wrbuf_buf(wr) );
1035 static void process_http_request(association *assoc, request *req)
1037 Z_HTTP_Request *hreq = req->gdu_request->u.HTTP_Request;
1038 ODR o = assoc->encode;
1039 int r = 2; /* 2=NOT TAKEN, 1=TAKEN, 0=SOAP TAKEN */
1041 Z_SOAP *soap_package = 0;
1044 Z_HTTP_Response *hres = 0;
1046 char *stylesheet = 0;
1047 Z_SRW_diagnostic *diagnostic = 0;
1048 int num_diagnostic = 0;
1050 if (!strcmp(hreq->path, "/test"))
1052 p = z_get_HTTP_Response(o, 200);
1053 hres = p->u.HTTP_Response;
1054 hres->content_buf = "1234567890\n";
1055 hres->content_len = strlen(hres->content_buf);
1060 r = yaz_srw_decode(hreq, &sr, &soap_package, assoc->decode, &charset);
1061 yaz_log(YLOG_DEBUG, "yaz_srw_decode returned %d", r);
1063 if (r == 2) /* not taken */
1065 r = yaz_sru_decode(hreq, &sr, &soap_package, assoc->decode, &charset,
1066 &diagnostic, &num_diagnostic);
1067 yaz_log(YLOG_DEBUG, "yaz_sru_decode returned %d", r);
1069 if (r == 0) /* decode SRW/SRU OK .. */
1071 int http_code = 200;
1072 if (sr->which == Z_SRW_searchRetrieve_request)
1075 yaz_srw_get(assoc->encode, Z_SRW_searchRetrieve_response);
1077 stylesheet = sr->u.request->stylesheet;
1080 res->u.response->diagnostics = diagnostic;
1081 res->u.response->num_diagnostics = num_diagnostic;
1085 srw_bend_search(assoc, req, sr->u.request, res->u.response,
1088 if (http_code == 200)
1089 soap_package->u.generic->p = res;
1091 else if (sr->which == Z_SRW_explain_request)
1093 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_explain_response);
1094 stylesheet = sr->u.explain_request->stylesheet;
1097 res->u.explain_response->diagnostics = diagnostic;
1098 res->u.explain_response->num_diagnostics = num_diagnostic;
1100 srw_bend_explain(assoc, req, sr->u.explain_request,
1101 res->u.explain_response, &http_code);
1102 if (http_code == 200)
1103 soap_package->u.generic->p = res;
1105 else if (sr->which == Z_SRW_scan_request)
1107 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_scan_response);
1108 stylesheet = sr->u.scan_request->stylesheet;
1111 res->u.scan_response->diagnostics = diagnostic;
1112 res->u.scan_response->num_diagnostics = num_diagnostic;
1114 srw_bend_scan(assoc, req, sr->u.scan_request,
1115 res->u.scan_response, &http_code);
1116 if (http_code == 200)
1117 soap_package->u.generic->p = res;
1121 yaz_log(log_request, "SOAP ERROR");
1122 /* FIXME - what error, what query */
1124 z_soap_error(assoc->encode, soap_package,
1125 "SOAP-ENV:Client", "Bad method", 0);
1127 if (http_code == 200 || http_code == 500)
1129 static Z_SOAP_Handler soap_handlers[3] = {
1131 {"http://www.loc.gov/zing/srw/", 0,
1132 (Z_SOAP_fun) yaz_srw_codec},
1133 {"http://www.loc.gov/zing/srw/v1.0/", 0,
1134 (Z_SOAP_fun) yaz_srw_codec},
1140 p = z_get_HTTP_Response(o, 200);
1141 hres = p->u.HTTP_Response;
1142 ret = z_soap_codec_enc_xsl(assoc->encode, &soap_package,
1143 &hres->content_buf, &hres->content_len,
1144 soap_handlers, charset, stylesheet);
1145 hres->code = http_code;
1147 strcpy(ctype, "text/xml");
1150 strcat(ctype, "; charset=");
1151 strcat(ctype, charset);
1153 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1156 p = z_get_HTTP_Response(o, http_code);
1160 p = z_get_HTTP_Response(o, 500);
1161 hres = p->u.HTTP_Response;
1162 if (!strcmp(hreq->version, "1.0"))
1164 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1165 if (v && !strcmp(v, "Keep-Alive"))
1169 hres->version = "1.0";
1173 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1174 if (v && !strcmp(v, "close"))
1178 hres->version = "1.1";
1182 z_HTTP_header_add(o, &hres->headers, "Connection", "close");
1183 assoc->state = ASSOC_DEAD;
1184 assoc->cs_get_mask = 0;
1189 const char *alive = z_HTTP_header_lookup(hreq->headers, "Keep-Alive");
1191 if (alive && isdigit(*(const unsigned char *) alive))
1195 if (t < 0 || t > 3600)
1197 iochan_settimeout(assoc->client_chan,t);
1198 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1200 process_gdu_response(assoc, req, p);
1203 static void process_gdu_request(association *assoc, request *req)
1205 if (req->gdu_request->which == Z_GDU_Z3950)
1208 req->apdu_request = req->gdu_request->u.z3950;
1209 if (process_z_request(assoc, req, &msg) < 0)
1210 do_close_req(assoc, Z_Close_systemProblem, msg, req);
1212 else if (req->gdu_request->which == Z_GDU_HTTP_Request)
1213 process_http_request(assoc, req);
1216 do_close_req(assoc, Z_Close_systemProblem, "bad protocol packet", req);
1221 * Initiate request processing.
1223 static int process_z_request(association *assoc, request *req, char **msg)
1229 *msg = "Unknown Error";
1230 assert(req && req->state == REQUEST_IDLE);
1231 if (req->apdu_request->which != Z_APDU_initRequest && !assoc->init)
1233 *msg = "Missing InitRequest";
1236 switch (req->apdu_request->which)
1238 case Z_APDU_initRequest:
1239 iochan_settimeout(assoc->client_chan,
1240 statserv_getcontrol()->idle_timeout * 60);
1241 res = process_initRequest(assoc, req); break;
1242 case Z_APDU_searchRequest:
1243 res = process_searchRequest(assoc, req, &fd); break;
1244 case Z_APDU_presentRequest:
1245 res = process_presentRequest(assoc, req, &fd); break;
1246 case Z_APDU_scanRequest:
1247 if (assoc->init->bend_scan)
1248 res = process_scanRequest(assoc, req, &fd);
1251 *msg = "Cannot handle Scan APDU";
1255 case Z_APDU_extendedServicesRequest:
1256 if (assoc->init->bend_esrequest)
1257 res = process_ESRequest(assoc, req, &fd);
1260 *msg = "Cannot handle Extended Services APDU";
1264 case Z_APDU_sortRequest:
1265 if (assoc->init->bend_sort)
1266 res = process_sortRequest(assoc, req, &fd);
1269 *msg = "Cannot handle Sort APDU";
1274 process_close(assoc, req);
1276 case Z_APDU_deleteResultSetRequest:
1277 if (assoc->init->bend_delete)
1278 res = process_deleteRequest(assoc, req, &fd);
1281 *msg = "Cannot handle Delete APDU";
1285 case Z_APDU_segmentRequest:
1286 if (assoc->init->bend_segment)
1288 res = process_segmentRequest (assoc, req);
1292 *msg = "Cannot handle Segment APDU";
1296 case Z_APDU_triggerResourceControlRequest:
1299 *msg = "Bad APDU received";
1304 yaz_log(YLOG_DEBUG, " result immediately available");
1305 retval = process_z_response(assoc, req, res);
1309 yaz_log(YLOG_DEBUG, " result unavailble");
1312 else /* no result yet - one will be provided later */
1316 /* Set up an I/O handler for the fd supplied by the backend */
1318 yaz_log(YLOG_DEBUG, " establishing handler for result");
1319 req->state = REQUEST_PENDING;
1320 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT)))
1322 iochan_setdata(chan, assoc);
1329 * Handle message from the backend.
1331 void backend_response(IOCHAN i, int event)
1333 association *assoc = (association *)iochan_getdata(i);
1334 request *req = request_head(&assoc->incoming);
1338 yaz_log(YLOG_DEBUG, "backend_response");
1339 assert(assoc && req && req->state != REQUEST_IDLE);
1340 /* determine what it is we're waiting for */
1341 switch (req->apdu_request->which)
1343 case Z_APDU_searchRequest:
1344 res = response_searchRequest(assoc, req, 0, &fd); break;
1346 case Z_APDU_presentRequest:
1347 res = response_presentRequest(assoc, req, 0, &fd); break;
1348 case Z_APDU_scanRequest:
1349 res = response_scanRequest(assoc, req, 0, &fd); break;
1352 yaz_log(YLOG_FATAL, "Serious programmer's lapse or bug");
1355 if ((res && process_z_response(assoc, req, res) < 0) || fd < 0)
1357 yaz_log(YLOG_WARN, "Fatal error when talking to backend");
1358 do_close(assoc, Z_Close_systemProblem, 0);
1362 else if (!res) /* no result yet - try again later */
1364 yaz_log(YLOG_DEBUG, " no result yet");
1365 iochan_setfd(i, fd); /* in case fd has changed */
1370 * Encode response, and transfer the request structure to the outgoing queue.
1372 static int process_gdu_response(association *assoc, request *req, Z_GDU *res)
1374 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
1378 if (!z_GDU(assoc->print, &res, 0, 0))
1379 yaz_log(YLOG_WARN, "ODR print error: %s",
1380 odr_errmsg(odr_geterror(assoc->print)));
1381 odr_reset(assoc->print);
1383 if (!z_GDU(assoc->encode, &res, 0, 0))
1385 yaz_log(YLOG_WARN, "ODR error when encoding PDU: %s [element %s]",
1386 odr_errmsg(odr_geterror(assoc->decode)),
1387 odr_getelement(assoc->decode));
1390 req->response = odr_getbuf(assoc->encode, &req->len_response,
1391 &req->size_response);
1392 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
1393 odr_reset(assoc->encode);
1394 req->state = REQUEST_IDLE;
1395 request_enq(&assoc->outgoing, req);
1396 /* turn the work over to the ir_session handler */
1397 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
1398 assoc->cs_put_mask = EVENT_OUTPUT;
1399 /* Is there more work to be done? give that to the input handler too */
1401 if (request_head(&assoc->incoming))
1403 yaz_log (YLOG_DEBUG, "more work to be done");
1404 iochan_setevent(assoc->client_chan, EVENT_WORK);
1411 * Encode response, and transfer the request structure to the outgoing queue.
1413 static int process_z_response(association *assoc, request *req, Z_APDU *res)
1415 Z_GDU *gres = (Z_GDU *) odr_malloc(assoc->encode, sizeof(*res));
1416 gres->which = Z_GDU_Z3950;
1417 gres->u.z3950 = res;
1419 return process_gdu_response(assoc, req, gres);
1424 * Handle init request.
1425 * At the moment, we don't check the options
1426 * anywhere else in the code - we just try not to do anything that would
1427 * break a naive client. We'll toss 'em into the association block when
1428 * we need them there.
1430 static Z_APDU *process_initRequest(association *assoc, request *reqb)
1432 statserv_options_block *cb = statserv_getcontrol();
1433 Z_InitRequest *req = reqb->apdu_request->u.initRequest;
1434 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
1435 Z_InitResponse *resp = apdu->u.initResponse;
1436 bend_initresult *binitres;
1440 yaz_log(log_requestdetail, "Got initRequest");
1441 if (req->implementationId)
1442 yaz_log(log_requestdetail, "Id: %s", req->implementationId);
1443 if (req->implementationName)
1444 yaz_log(log_requestdetail, "Name: %s", req->implementationName);
1445 if (req->implementationVersion)
1446 yaz_log(log_requestdetail, "Version: %s", 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;
1463 if (!(binitres = (*cb->bend_init)(assoc->init)))
1465 yaz_log(YLOG_WARN, "Bad response from backend.");
1469 assoc->backend = binitres->handle;
1470 if ((assoc->init->bend_sort))
1471 yaz_log (YLOG_DEBUG, "Sort handler installed");
1472 if ((assoc->init->bend_search))
1473 yaz_log (YLOG_DEBUG, "Search handler installed");
1474 if ((assoc->init->bend_present))
1475 yaz_log (YLOG_DEBUG, "Present handler installed");
1476 if ((assoc->init->bend_esrequest))
1477 yaz_log (YLOG_DEBUG, "ESRequest handler installed");
1478 if ((assoc->init->bend_delete))
1479 yaz_log (YLOG_DEBUG, "Delete handler installed");
1480 if ((assoc->init->bend_scan))
1481 yaz_log (YLOG_DEBUG, "Scan handler installed");
1482 if ((assoc->init->bend_segment))
1483 yaz_log (YLOG_DEBUG, "Segment handler installed");
1485 resp->referenceId = req->referenceId;
1487 /* let's tell the client what we can do */
1488 if (ODR_MASK_GET(req->options, Z_Options_search))
1490 ODR_MASK_SET(resp->options, Z_Options_search);
1491 strcat(options, "srch");
1493 if (ODR_MASK_GET(req->options, Z_Options_present))
1495 ODR_MASK_SET(resp->options, Z_Options_present);
1496 strcat(options, " prst");
1498 if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
1499 assoc->init->bend_delete)
1501 ODR_MASK_SET(resp->options, Z_Options_delSet);
1502 strcat(options, " del");
1504 if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
1505 assoc->init->bend_esrequest)
1507 ODR_MASK_SET(resp->options, Z_Options_extendedServices);
1508 strcat (options, " extendedServices");
1510 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
1512 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
1513 strcat(options, " namedresults");
1515 if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
1517 ODR_MASK_SET(resp->options, Z_Options_scan);
1518 strcat(options, " scan");
1520 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
1522 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
1523 strcat(options, " concurrop");
1525 if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
1527 ODR_MASK_SET(resp->options, Z_Options_sort);
1528 strcat(options, " sort");
1531 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel)
1532 && assoc->init->charneg_response)
1534 Z_OtherInformation **p;
1535 Z_OtherInformationUnit *p0;
1537 yaz_oi_APDU(apdu, &p);
1539 if ((p0=yaz_oi_update(p, assoc->encode, NULL, 0, 0))) {
1540 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
1542 p0->which = Z_OtherInfo_externallyDefinedInfo;
1543 p0->information.externallyDefinedInfo =
1544 assoc->init->charneg_response;
1546 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
1547 strcat(options, " negotiation");
1550 ODR_MASK_SET(resp->options, Z_Options_triggerResourceCtrl);
1552 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
1554 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
1555 assoc->version = 1; /* 1 & 2 are equivalent */
1557 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
1559 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
1562 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
1564 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
1568 yaz_log(log_requestdetail, "Negotiated to v%d: %s", assoc->version, options);
1569 assoc->maximumRecordSize = *req->maximumRecordSize;
1570 if (assoc->maximumRecordSize > control_block->maxrecordsize)
1571 assoc->maximumRecordSize = control_block->maxrecordsize;
1572 assoc->preferredMessageSize = *req->preferredMessageSize;
1573 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
1574 assoc->preferredMessageSize = assoc->maximumRecordSize;
1576 resp->preferredMessageSize = &assoc->preferredMessageSize;
1577 resp->maximumRecordSize = &assoc->maximumRecordSize;
1579 resp->implementationId = odr_prepend(assoc->encode,
1580 assoc->init->implementation_id,
1581 resp->implementationId);
1583 resp->implementationName = odr_prepend(assoc->encode,
1584 assoc->init->implementation_name,
1585 odr_prepend(assoc->encode, "GFS", resp->implementationName));
1587 version = odr_strdup(assoc->encode, "$Revision: 1.45 $");
1588 if (strlen(version) > 10) /* check for unexpanded CVS strings */
1589 version[strlen(version)-2] = '\0';
1590 resp->implementationVersion = odr_prepend(assoc->encode,
1591 assoc->init->implementation_version,
1592 odr_prepend(assoc->encode, &version[11],
1593 resp->implementationVersion));
1595 if (binitres->errcode)
1597 assoc->state = ASSOC_DEAD;
1598 resp->userInformationField =
1599 init_diagnostics(assoc->encode, binitres->errcode,
1600 binitres->errstring);
1605 WRBUF wr = wrbuf_alloc();
1606 wrbuf_printf(wr, "Init ");
1607 if (binitres->errcode)
1608 wrbuf_printf(wr, "ERROR %d", binitres->errcode);
1610 wrbuf_printf(wr, "OK -");
1611 wrbuf_printf(wr, " ID:%s Name:%s Version:%s",
1612 (req->implementationId ? req->implementationId :"-"),
1613 (req->implementationName ?
1614 req->implementationName : "-"),
1615 (req->implementationVersion ?
1616 req->implementationVersion : "-")
1618 yaz_log(log_request, "%s", wrbuf_buf(wr));
1625 * Set the specified `errcode' and `errstring' into a UserInfo-1
1626 * external to be returned to the client in accordance with Z35.90
1627 * Implementor Agreement 5 (Returning diagnostics in an InitResponse):
1628 * http://lcweb.loc.gov/z3950/agency/agree/initdiag.html
1630 static Z_External *init_diagnostics(ODR odr, int error, const char *addinfo)
1632 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
1633 addinfo ? " -- " : "", addinfo ? addinfo : "");
1634 return zget_init_diagnostics(odr, error, addinfo);
1638 * nonsurrogate diagnostic record.
1640 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
1642 Z_Records *rec = (Z_Records *) odr_malloc (assoc->encode, sizeof(*rec));
1644 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
1645 addinfo ? " -- " : "", addinfo ? addinfo : "");
1647 rec->which = Z_Records_NSD;
1648 rec->u.nonSurrogateDiagnostic = zget_DefaultDiagFormat(assoc->encode,
1654 * surrogate diagnostic.
1656 static Z_NamePlusRecord *surrogatediagrec(association *assoc,
1658 int error, const char *addinfo)
1660 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
1661 addinfo ? " -- " : "", addinfo ? addinfo : "");
1662 return zget_surrogateDiagRec(assoc->encode, dbname, error, addinfo);
1665 static Z_Records *pack_records(association *a, char *setname, int start,
1666 int *num, Z_RecordComposition *comp,
1667 int *next, int *pres, oid_value format,
1668 Z_ReferenceId *referenceId,
1669 int *oid, int *errcode)
1671 int recno, total_length = 0, toget = *num, dumped_records = 0;
1672 Z_Records *records =
1673 (Z_Records *) odr_malloc (a->encode, sizeof(*records));
1674 Z_NamePlusRecordList *reclist =
1675 (Z_NamePlusRecordList *) odr_malloc (a->encode, sizeof(*reclist));
1676 Z_NamePlusRecord **list =
1677 (Z_NamePlusRecord **) odr_malloc (a->encode, sizeof(*list) * toget);
1679 records->which = Z_Records_DBOSD;
1680 records->u.databaseOrSurDiagnostics = reclist;
1681 reclist->num_records = 0;
1682 reclist->records = list;
1683 *pres = Z_PresentStatus_success;
1687 yaz_log(log_requestdetail, "Request to pack %d+%d %s", start, toget, setname);
1688 yaz_log(log_requestdetail, "pms=%d, mrs=%d", a->preferredMessageSize,
1689 a->maximumRecordSize);
1690 for (recno = start; reclist->num_records < toget; recno++)
1693 Z_NamePlusRecord *thisrec;
1694 int this_length = 0;
1696 * we get the number of bytes allocated on the stream before any
1697 * allocation done by the backend - this should give us a reasonable
1698 * idea of the total size of the data so far.
1700 total_length = odr_total(a->encode) - dumped_records;
1706 freq.last_in_set = 0;
1707 freq.setname = setname;
1708 freq.surrogate_flag = 0;
1709 freq.number = recno;
1711 freq.request_format = format;
1712 freq.request_format_raw = oid;
1713 freq.output_format = format;
1714 freq.output_format_raw = 0;
1715 freq.stream = a->encode;
1716 freq.print = a->print;
1717 freq.referenceId = referenceId;
1719 (*a->init->bend_fetch)(a->backend, &freq);
1720 /* backend should be able to signal whether error is system-wide
1721 or only pertaining to current record */
1724 if (!freq.surrogate_flag)
1727 *pres = Z_PresentStatus_failure;
1728 /* for 'present request out of range',
1729 set addinfo to record position if not set */
1730 if (freq.errcode == 13 && freq.errstring == 0)
1732 sprintf (s, "%d", recno);
1736 *errcode = freq.errcode;
1737 return diagrec(a, freq.errcode, freq.errstring);
1739 reclist->records[reclist->num_records] =
1740 surrogatediagrec(a, freq.basename, freq.errcode,
1742 reclist->num_records++;
1743 *next = freq.last_in_set ? 0 : recno + 1;
1747 this_length = freq.len;
1749 this_length = odr_total(a->encode) - total_length - dumped_records;
1750 yaz_log(YLOG_DEBUG, " fetched record, len=%d, total=%d dumped=%d",
1751 this_length, total_length, dumped_records);
1752 if (a->preferredMessageSize > 0 &&
1753 this_length + total_length > a->preferredMessageSize)
1755 /* record is small enough, really */
1756 if (this_length <= a->preferredMessageSize && recno > start)
1758 yaz_log(log_requestdetail, " Dropped last normal-sized record");
1759 *pres = Z_PresentStatus_partial_2;
1762 /* record can only be fetched by itself */
1763 if (this_length < a->maximumRecordSize)
1765 yaz_log(log_requestdetail, " Record > prefmsgsz");
1768 yaz_log(YLOG_DEBUG, " Dropped it");
1769 reclist->records[reclist->num_records] =
1770 surrogatediagrec(a, freq.basename, 16, 0);
1771 reclist->num_records++;
1772 *next = freq.last_in_set ? 0 : recno + 1;
1773 dumped_records += this_length;
1777 else /* too big entirely */
1779 yaz_log(log_requestdetail, "Record > maxrcdsz this=%d max=%d",
1780 this_length, a->maximumRecordSize);
1781 reclist->records[reclist->num_records] =
1782 surrogatediagrec(a, freq.basename, 17, 0);
1783 reclist->num_records++;
1784 *next = freq.last_in_set ? 0 : recno + 1;
1785 dumped_records += this_length;
1790 if (!(thisrec = (Z_NamePlusRecord *)
1791 odr_malloc(a->encode, sizeof(*thisrec))))
1793 if (!(thisrec->databaseName = (char *)odr_malloc(a->encode,
1794 strlen(freq.basename) + 1)))
1796 strcpy(thisrec->databaseName, freq.basename);
1797 thisrec->which = Z_NamePlusRecord_databaseRecord;
1799 if (freq.output_format_raw)
1801 struct oident *ident = oid_getentbyoid(freq.output_format_raw);
1802 freq.output_format = ident->value;
1804 thisrec->u.databaseRecord = z_ext_record(a->encode, freq.output_format,
1805 freq.record, freq.len);
1806 if (!thisrec->u.databaseRecord)
1808 reclist->records[reclist->num_records] = thisrec;
1809 reclist->num_records++;
1810 *next = freq.last_in_set ? 0 : recno + 1;
1812 *num = reclist->num_records;
1816 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
1819 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
1820 bend_search_rr *bsrr =
1821 (bend_search_rr *)nmem_malloc (reqb->request_mem, sizeof(*bsrr));
1823 yaz_log(log_requestdetail, "Got SearchRequest.");
1825 bsrr->request = reqb;
1826 bsrr->association = assoc;
1827 bsrr->referenceId = req->referenceId;
1828 save_referenceId (reqb, bsrr->referenceId);
1830 yaz_log (log_requestdetail, "ResultSet '%s'", req->resultSetName);
1831 if (req->databaseNames)
1834 for (i = 0; i < req->num_databaseNames; i++)
1835 yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
1838 yaz_log_zquery_level(log_requestdetail,req->query);
1840 if (assoc->init->bend_search)
1842 bsrr->setname = req->resultSetName;
1843 bsrr->replace_set = *req->replaceIndicator;
1844 bsrr->num_bases = req->num_databaseNames;
1845 bsrr->basenames = req->databaseNames;
1846 bsrr->query = req->query;
1847 bsrr->stream = assoc->encode;
1848 nmem_transfer(bsrr->stream->mem, reqb->request_mem);
1849 bsrr->decode = assoc->decode;
1850 bsrr->print = assoc->print;
1853 bsrr->errstring = NULL;
1854 bsrr->search_info = NULL;
1855 (assoc->init->bend_search)(assoc->backend, bsrr);
1856 if (!bsrr->request) /* backend not ready with the search response */
1857 return 0; /* should not be used any more */
1861 /* FIXME - make a diagnostic for it */
1862 yaz_log(YLOG_WARN,"Search not supported ?!?!");
1864 return response_searchRequest(assoc, reqb, bsrr, fd);
1867 int bend_searchresponse(void *handle, bend_search_rr *bsrr) {return 0;}
1870 * Prepare a searchresponse based on the backend results. We probably want
1871 * to look at making the fetching of records nonblocking as well, but
1872 * so far, we'll keep things simple.
1873 * If bsrt is null, that means we're called in response to a communications
1874 * event, and we'll have to get the response for ourselves.
1876 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
1877 bend_search_rr *bsrt, int *fd)
1879 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
1880 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1881 Z_SearchResponse *resp = (Z_SearchResponse *)
1882 odr_malloc (assoc->encode, sizeof(*resp));
1883 int *nulint = odr_intdup (assoc->encode, 0);
1884 bool_t *sr = odr_intdup(assoc->encode, 1);
1885 int *next = odr_intdup(assoc->encode, 0);
1886 int *none = odr_intdup(assoc->encode, Z_SearchResponse_none);
1889 apdu->which = Z_APDU_searchResponse;
1890 apdu->u.searchResponse = resp;
1891 resp->referenceId = req->referenceId;
1892 resp->additionalSearchInfo = 0;
1893 resp->otherInfo = 0;
1895 if (!bsrt && !bend_searchresponse(assoc->backend, bsrt))
1897 yaz_log(YLOG_FATAL, "Bad result from backend");
1900 else if (bsrt->errcode)
1902 resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
1903 resp->resultCount = nulint;
1904 resp->numberOfRecordsReturned = nulint;
1905 resp->nextResultSetPosition = nulint;
1906 resp->searchStatus = nulint;
1907 resp->resultSetStatus = none;
1908 resp->presentStatus = 0;
1912 int *toget = odr_intdup(assoc->encode, 0);
1913 int *presst = odr_intdup(assoc->encode, 0);
1914 Z_RecordComposition comp, *compp = 0;
1916 yaz_log (log_requestdetail, "resultCount: %d", bsrt->hits);
1919 resp->resultCount = &bsrt->hits;
1921 comp.which = Z_RecordComp_simple;
1922 /* how many records does the user agent want, then? */
1923 if (bsrt->hits <= *req->smallSetUpperBound)
1925 *toget = bsrt->hits;
1926 if ((comp.u.simple = req->smallSetElementSetNames))
1929 else if (bsrt->hits < *req->largeSetLowerBound)
1931 *toget = *req->mediumSetPresentNumber;
1932 if (*toget > bsrt->hits)
1933 *toget = bsrt->hits;
1934 if ((comp.u.simple = req->mediumSetElementSetNames))
1940 if (*toget && !resp->records)
1945 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
1948 form = prefformat->value;
1949 resp->records = pack_records(assoc, req->resultSetName, 1,
1950 toget, compp, next, presst, form, req->referenceId,
1951 req->preferredRecordSyntax, NULL);
1954 resp->numberOfRecordsReturned = toget;
1955 returnedrecs = *toget;
1956 resp->nextResultSetPosition = next;
1957 resp->searchStatus = sr;
1958 resp->resultSetStatus = 0;
1959 resp->presentStatus = presst;
1963 if (*resp->resultCount)
1965 resp->numberOfRecordsReturned = nulint;
1966 resp->nextResultSetPosition = next;
1967 resp->searchStatus = sr;
1968 resp->resultSetStatus = 0;
1969 resp->presentStatus = 0;
1972 resp->additionalSearchInfo = bsrt->search_info;
1976 WRBUF wr = wrbuf_alloc();
1978 wrbuf_printf(wr, "ERROR %d", bsrt->errcode);
1980 wrbuf_printf(wr, "OK %d", bsrt->hits);
1981 wrbuf_printf(wr, " %s 1+%d ",
1982 req->resultSetName, returnedrecs);
1983 wrbuf_put_zquery(wr, req->query);
1985 yaz_log(log_request, "Search %s", wrbuf_buf(wr));
1992 * Maybe we got a little over-friendly when we designed bend_fetch to
1993 * get only one record at a time. Some backends can optimise multiple-record
1994 * fetches, and at any rate, there is some overhead involved in
1995 * all that selecting and hopping around. Problem is, of course, that the
1996 * frontend can't know ahead of time how many records it'll need to
1997 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
1998 * is downright lousy as a bulk data transfer protocol.
2000 * To start with, we'll do the fetching of records from the backend
2001 * in one operation: To save some trips in and out of the event-handler,
2002 * and to simplify the interface to pack_records. At any rate, asynch
2003 * operation is more fun in operations that have an unpredictable execution
2004 * speed - which is normally more true for search than for present.
2006 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
2009 Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
2013 Z_PresentResponse *resp;
2017 const char *errstring = 0;
2019 yaz_log(log_requestdetail, "Got PresentRequest.");
2021 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
2024 form = prefformat->value;
2025 resp = (Z_PresentResponse *)odr_malloc (assoc->encode, sizeof(*resp));
2027 resp->presentStatus = odr_intdup(assoc->encode, 0);
2028 if (assoc->init->bend_present)
2030 bend_present_rr *bprr = (bend_present_rr *)
2031 nmem_malloc (reqb->request_mem, sizeof(*bprr));
2032 bprr->setname = req->resultSetId;
2033 bprr->start = *req->resultSetStartPoint;
2034 bprr->number = *req->numberOfRecordsRequested;
2035 bprr->format = form;
2036 bprr->comp = req->recordComposition;
2037 bprr->referenceId = req->referenceId;
2038 bprr->stream = assoc->encode;
2039 bprr->print = assoc->print;
2040 bprr->request = reqb;
2041 bprr->association = assoc;
2043 bprr->errstring = NULL;
2044 (*assoc->init->bend_present)(assoc->backend, bprr);
2047 return 0; /* should not happen */
2050 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2051 *resp->presentStatus = Z_PresentStatus_failure;
2052 errcode = bprr->errcode;
2053 errstring = bprr->errstring;
2056 apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2057 next = odr_intdup(assoc->encode, 0);
2058 num = odr_intdup(assoc->encode, 0);
2060 apdu->which = Z_APDU_presentResponse;
2061 apdu->u.presentResponse = resp;
2062 resp->referenceId = req->referenceId;
2063 resp->otherInfo = 0;
2067 *num = *req->numberOfRecordsRequested;
2069 pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
2070 num, req->recordComposition, next,
2071 resp->presentStatus,
2072 form, req->referenceId, req->preferredRecordSyntax,
2077 WRBUF wr = wrbuf_alloc();
2078 wrbuf_printf(wr, "Present ");
2080 if (*resp->presentStatus == Z_PresentStatus_failure)
2081 wrbuf_printf(wr, "ERROR %d", errcode);
2082 else if (*resp->presentStatus == Z_PresentStatus_success)
2083 wrbuf_printf(wr, "OK -");
2085 wrbuf_printf(wr, "Partial %d", *resp->presentStatus);
2087 wrbuf_printf(wr, " %s %d+%d ",
2088 req->resultSetId, *req->resultSetStartPoint,
2089 *req->numberOfRecordsRequested);
2090 yaz_log(log_request, "%s", wrbuf_buf(wr) );
2095 resp->numberOfRecordsReturned = num;
2096 resp->nextResultSetPosition = next;
2102 * Scan was implemented rather in a hurry, and with support for only the basic
2103 * elements of the service in the backend API. Suggestions are welcome.
2105 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
2107 Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
2108 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2109 Z_ScanResponse *res = (Z_ScanResponse *)
2110 odr_malloc (assoc->encode, sizeof(*res));
2111 int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
2112 int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
2113 Z_ListEntries *ents = (Z_ListEntries *)
2114 odr_malloc (assoc->encode, sizeof(*ents));
2115 Z_DiagRecs *diagrecs_p = NULL;
2117 bend_scan_rr *bsrr = (bend_scan_rr *)
2118 odr_malloc (assoc->encode, sizeof(*bsrr));
2119 struct scan_entry *save_entries;
2121 yaz_log(log_requestdetail, "Got ScanRequest");
2123 apdu->which = Z_APDU_scanResponse;
2124 apdu->u.scanResponse = res;
2125 res->referenceId = req->referenceId;
2127 /* if step is absent, set it to 0 */
2128 res->stepSize = odr_intdup(assoc->encode, 0);
2130 *res->stepSize = *req->stepSize;
2132 res->scanStatus = scanStatus;
2133 res->numberOfEntriesReturned = numberOfEntriesReturned;
2134 res->positionOfTerm = 0;
2135 res->entries = ents;
2136 ents->num_entries = 0;
2137 ents->entries = NULL;
2138 ents->num_nonsurrogateDiagnostics = 0;
2139 ents->nonsurrogateDiagnostics = NULL;
2140 res->attributeSet = 0;
2143 if (req->databaseNames)
2146 for (i = 0; i < req->num_databaseNames; i++)
2147 yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
2149 yaz_log(log_requestdetail, "pos %d step %d entries %d",
2150 *req->preferredPositionInResponse, *res->stepSize,
2151 *req->numberOfTermsRequested);
2152 bsrr->num_bases = req->num_databaseNames;
2153 bsrr->basenames = req->databaseNames;
2154 bsrr->num_entries = *req->numberOfTermsRequested;
2155 bsrr->term = req->termListAndStartPoint;
2156 bsrr->referenceId = req->referenceId;
2157 bsrr->stream = assoc->encode;
2158 bsrr->print = assoc->print;
2159 bsrr->step_size = res->stepSize;
2161 /* For YAZ 2.0 and earlier it was the backend handler that
2162 initialized entries (member display_term did not exist)
2163 YAZ 2.0 and later sets 'entries' and initialize all members
2164 including 'display_term'. If YAZ 2.0 or later sees that
2165 entries was modified - we assume that it is an old handler and
2166 that 'display_term' is _not_ set.
2168 if (bsrr->num_entries > 0)
2171 bsrr->entries = odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
2173 for (i = 0; i<bsrr->num_entries; i++)
2175 bsrr->entries[i].term = 0;
2176 bsrr->entries[i].occurrences = 0;
2177 bsrr->entries[i].errcode = 0;
2178 bsrr->entries[i].errstring = 0;
2179 bsrr->entries[i].display_term = 0;
2182 save_entries = bsrr->entries; /* save it so we can compare later */
2184 if (req->attributeSet &&
2185 (attset = oid_getentbyoid(req->attributeSet)) &&
2186 (attset->oclass == CLASS_ATTSET || attset->oclass == CLASS_GENERAL))
2187 bsrr->attributeset = attset->value;
2189 bsrr->attributeset = VAL_NONE;
2190 log_scan_term_level (log_requestdetail, req->termListAndStartPoint,
2191 bsrr->attributeset);
2192 bsrr->term_position = req->preferredPositionInResponse ?
2193 *req->preferredPositionInResponse : 1;
2195 ((int (*)(void *, bend_scan_rr *))
2196 (*assoc->init->bend_scan))(assoc->backend, bsrr);
2199 diagrecs_p = zget_DiagRecs(assoc->encode,
2200 bsrr->errcode, bsrr->errstring);
2204 Z_Entry **tab = (Z_Entry **)
2205 odr_malloc (assoc->encode, sizeof(*tab) * bsrr->num_entries);
2207 if (bsrr->status == BEND_SCAN_PARTIAL)
2208 *scanStatus = Z_Scan_partial_5;
2210 *scanStatus = Z_Scan_success;
2211 ents->entries = tab;
2212 ents->num_entries = bsrr->num_entries;
2213 res->numberOfEntriesReturned = &ents->num_entries;
2214 res->positionOfTerm = &bsrr->term_position;
2215 for (i = 0; i < bsrr->num_entries; i++)
2221 tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
2222 if (bsrr->entries[i].occurrences >= 0)
2224 e->which = Z_Entry_termInfo;
2225 e->u.termInfo = t = (Z_TermInfo *)
2226 odr_malloc(assoc->encode, sizeof(*t));
2227 t->suggestedAttributes = 0;
2229 if (save_entries == bsrr->entries &&
2230 bsrr->entries[i].display_term)
2232 /* the entries was _not_ set by the handler. So it's
2233 safe to test for new member display_term. It is
2236 t->displayTerm = odr_strdup(assoc->encode,
2237 bsrr->entries[i].display_term);
2239 t->alternativeTerm = 0;
2240 t->byAttributes = 0;
2241 t->otherTermInfo = 0;
2242 t->globalOccurrences = &bsrr->entries[i].occurrences;
2243 t->term = (Z_Term *)
2244 odr_malloc(assoc->encode, sizeof(*t->term));
2245 t->term->which = Z_Term_general;
2246 t->term->u.general = o =
2247 (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
2248 o->buf = (unsigned char *)
2249 odr_malloc(assoc->encode, o->len = o->size =
2250 strlen(bsrr->entries[i].term));
2251 memcpy(o->buf, bsrr->entries[i].term, o->len);
2252 yaz_log(YLOG_DEBUG, " term #%d: '%s' (%d)", i,
2253 bsrr->entries[i].term, bsrr->entries[i].occurrences);
2257 Z_DiagRecs *drecs = zget_DiagRecs(assoc->encode,
2258 bsrr->entries[i].errcode,
2259 bsrr->entries[i].errstring);
2260 assert (drecs->num_diagRecs == 1);
2261 e->which = Z_Entry_surrogateDiagnostic;
2262 assert (drecs->diagRecs[0]);
2263 e->u.surrogateDiagnostic = drecs->diagRecs[0];
2269 ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
2270 ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
2274 WRBUF wr = wrbuf_alloc();
2275 if (*res->scanStatus == Z_Scan_success)
2276 wrbuf_printf(wr, "OK ");
2278 wr_diag(wr, bsrr->errcode, bsrr->errstring);
2280 wrbuf_printf(wr, "%d+%d %d ",
2281 *req->preferredPositionInResponse,
2282 *req->numberOfTermsRequested,
2283 (res->stepSize ? *res->stepSize : 0));
2284 wrbuf_scan_term(wr, req->termListAndStartPoint,
2285 bsrr->attributeset);
2287 yaz_log(log_request, "Scan %s", wrbuf_buf(wr) );
2293 static Z_APDU *process_sortRequest(association *assoc, request *reqb,
2297 Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
2298 Z_SortResponse *res = (Z_SortResponse *)
2299 odr_malloc (assoc->encode, sizeof(*res));
2300 bend_sort_rr *bsrr = (bend_sort_rr *)
2301 odr_malloc (assoc->encode, sizeof(*bsrr));
2303 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2305 yaz_log(log_requestdetail, "Got SortRequest.");
2307 bsrr->num_input_setnames = req->num_inputResultSetNames;
2308 for (i=0;i<req->num_inputResultSetNames;i++)
2309 yaz_log(log_requestdetail, "Input resultset: '%s'",
2310 req->inputResultSetNames[i]);
2311 bsrr->input_setnames = req->inputResultSetNames;
2312 bsrr->referenceId = req->referenceId;
2313 bsrr->output_setname = req->sortedResultSetName;
2314 yaz_log(log_requestdetail, "Output resultset: '%s'",
2315 req->sortedResultSetName);
2316 bsrr->sort_sequence = req->sortSequence;
2317 /*FIXME - dump those sequences too */
2318 bsrr->stream = assoc->encode;
2319 bsrr->print = assoc->print;
2321 bsrr->sort_status = Z_SortResponse_failure;
2323 bsrr->errstring = 0;
2325 (*assoc->init->bend_sort)(assoc->backend, bsrr);
2327 res->referenceId = bsrr->referenceId;
2328 res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
2329 res->resultSetStatus = 0;
2332 Z_DiagRecs *dr = zget_DiagRecs(assoc->encode,
2333 bsrr->errcode, bsrr->errstring);
2334 res->diagnostics = dr->diagRecs;
2335 res->num_diagnostics = dr->num_diagRecs;
2339 res->num_diagnostics = 0;
2340 res->diagnostics = 0;
2342 res->resultCount = 0;
2345 apdu->which = Z_APDU_sortResponse;
2346 apdu->u.sortResponse = res;
2349 WRBUF wr = wrbuf_alloc();
2350 wrbuf_printf(wr, "Sort ");
2352 wrbuf_printf(wr, " ERROR %d", bsrr->errcode);
2354 wrbuf_printf(wr, "OK -");
2355 wrbuf_printf(wr, " (");
2356 for (i = 0; i<req->num_inputResultSetNames; i++)
2359 wrbuf_printf(wr, ",");
2360 wrbuf_printf(wr, req->inputResultSetNames[i]);
2362 wrbuf_printf(wr, ")->%s ",req->sortedResultSetName);
2364 yaz_log(log_request, "%s", wrbuf_buf(wr) );
2370 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
2374 Z_DeleteResultSetRequest *req =
2375 reqb->apdu_request->u.deleteResultSetRequest;
2376 Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
2377 odr_malloc (assoc->encode, sizeof(*res));
2378 bend_delete_rr *bdrr = (bend_delete_rr *)
2379 odr_malloc (assoc->encode, sizeof(*bdrr));
2380 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2382 yaz_log(log_requestdetail, "Got DeleteRequest.");
2384 bdrr->num_setnames = req->num_resultSetList;
2385 bdrr->setnames = req->resultSetList;
2386 for (i = 0; i<req->num_resultSetList; i++)
2387 yaz_log(log_requestdetail, "resultset: '%s'",
2388 req->resultSetList[i]);
2389 bdrr->stream = assoc->encode;
2390 bdrr->print = assoc->print;
2391 bdrr->function = *req->deleteFunction;
2392 bdrr->referenceId = req->referenceId;
2394 if (bdrr->num_setnames > 0)
2396 bdrr->statuses = (int*)
2397 odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
2398 bdrr->num_setnames);
2399 for (i = 0; i < bdrr->num_setnames; i++)
2400 bdrr->statuses[i] = 0;
2402 (*assoc->init->bend_delete)(assoc->backend, bdrr);
2404 res->referenceId = req->referenceId;
2406 res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
2408 res->deleteListStatuses = 0;
2409 if (bdrr->num_setnames > 0)
2412 res->deleteListStatuses = (Z_ListStatuses *)
2413 odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
2414 res->deleteListStatuses->num = bdrr->num_setnames;
2415 res->deleteListStatuses->elements =
2417 odr_malloc (assoc->encode,
2418 sizeof(*res->deleteListStatuses->elements) *
2419 bdrr->num_setnames);
2420 for (i = 0; i<bdrr->num_setnames; i++)
2422 res->deleteListStatuses->elements[i] =
2424 odr_malloc (assoc->encode,
2425 sizeof(**res->deleteListStatuses->elements));
2426 res->deleteListStatuses->elements[i]->status = bdrr->statuses+i;
2427 res->deleteListStatuses->elements[i]->id =
2428 odr_strdup (assoc->encode, bdrr->setnames[i]);
2431 res->numberNotDeleted = 0;
2432 res->bulkStatuses = 0;
2433 res->deleteMessage = 0;
2436 apdu->which = Z_APDU_deleteResultSetResponse;
2437 apdu->u.deleteResultSetResponse = res;
2440 WRBUF wr = wrbuf_alloc();
2441 wrbuf_printf(wr, "Delete ");
2442 if (bdrr->delete_status)
2443 wrbuf_printf(wr, "ERROR %d", bdrr->delete_status);
2445 wrbuf_printf(wr, "OK -");
2446 for (i = 0; i<req->num_resultSetList; i++)
2447 wrbuf_printf(wr, " %s ", req->resultSetList[i]);
2448 yaz_log(log_request, "%s", wrbuf_buf(wr) );
2454 static void process_close(association *assoc, request *reqb)
2456 Z_Close *req = reqb->apdu_request->u.close;
2457 static char *reasons[] =
2464 "securityViolation",
2471 yaz_log(log_requestdetail, "Got Close, reason %s, message %s",
2472 reasons[*req->closeReason], req->diagnosticInformation ?
2473 req->diagnosticInformation : "NULL");
2474 if (assoc->version < 3) /* to make do_force respond with close */
2476 do_close_req(assoc, Z_Close_finished,
2477 "Association terminated by client", reqb);
2478 yaz_log(log_request,"Close OK");
2481 void save_referenceId (request *reqb, Z_ReferenceId *refid)
2485 reqb->len_refid = refid->len;
2486 reqb->refid = (char *)nmem_malloc (reqb->request_mem, refid->len);
2487 memcpy (reqb->refid, refid->buf, refid->len);
2491 reqb->len_refid = 0;
2496 void bend_request_send (bend_association a, bend_request req, Z_APDU *res)
2498 process_z_response (a, req, res);
2501 bend_request bend_request_mk (bend_association a)
2503 request *nreq = request_get (&a->outgoing);
2504 nreq->request_mem = nmem_create ();
2508 Z_ReferenceId *bend_request_getid (ODR odr, bend_request req)
2513 id = (Odr_oct *)odr_malloc (odr, sizeof(*odr));
2514 id->buf = (unsigned char *)odr_malloc (odr, req->len_refid);
2515 id->len = id->size = req->len_refid;
2516 memcpy (id->buf, req->refid, req->len_refid);
2520 void bend_request_destroy (bend_request *req)
2522 nmem_destroy((*req)->request_mem);
2523 request_release(*req);
2527 int bend_backend_respond (bend_association a, bend_request req)
2531 r = process_z_request (a, req, &msg);
2533 yaz_log (YLOG_WARN, "%s", msg);
2537 void bend_request_setdata(bend_request r, void *p)
2542 void *bend_request_getdata(bend_request r)
2544 return r->clientData;
2547 static Z_APDU *process_segmentRequest (association *assoc, request *reqb)
2549 bend_segment_rr req;
2551 req.segment = reqb->apdu_request->u.segmentRequest;
2552 req.stream = assoc->encode;
2553 req.decode = assoc->decode;
2554 req.print = assoc->print;
2555 req.association = assoc;
2557 (*assoc->init->bend_segment)(assoc->backend, &req);
2562 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd)
2564 bend_esrequest_rr esrequest;
2566 Z_ExtendedServicesRequest *req =
2567 reqb->apdu_request->u.extendedServicesRequest;
2568 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
2570 Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
2572 yaz_log(log_requestdetail,"Got EsRequest");
2574 esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
2575 esrequest.stream = assoc->encode;
2576 esrequest.decode = assoc->decode;
2577 esrequest.print = assoc->print;
2578 esrequest.errcode = 0;
2579 esrequest.errstring = NULL;
2580 esrequest.request = reqb;
2581 esrequest.association = assoc;
2582 esrequest.taskPackage = 0;
2583 esrequest.referenceId = req->referenceId;
2585 (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
2587 /* If the response is being delayed, return NULL */
2588 if (esrequest.request == NULL)
2591 resp->referenceId = req->referenceId;
2593 if (esrequest.errcode == -1)
2595 /* Backend service indicates request will be processed */
2596 yaz_log(log_request,"EsRequest OK: Accepted !");
2597 *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
2599 else if (esrequest.errcode == 0)
2601 /* Backend service indicates request will be processed */
2602 yaz_log(log_request,"EsRequest OK: Done !");
2603 *resp->operationStatus = Z_ExtendedServicesResponse_done;
2607 Z_DiagRecs *diagRecs =
2608 zget_DiagRecs(assoc->encode, esrequest.errcode,
2609 esrequest.errstring);
2610 /* Backend indicates error, request will not be processed */
2611 yaz_log(YLOG_DEBUG,"Request could not be processed...failure !");
2612 *resp->operationStatus = Z_ExtendedServicesResponse_failure;
2613 resp->num_diagnostics = diagRecs->num_diagRecs;
2614 resp->diagnostics = diagRecs->diagRecs;
2617 WRBUF wr=wrbuf_alloc();
2618 wrbuf_diags(wr, resp->num_diagnostics, resp->diagnostics);
2619 yaz_log(log_request, "EsRequest %s", wrbuf_buf(wr) );
2624 /* Do something with the members of bend_extendedservice */
2625 if (esrequest.taskPackage)
2626 resp->taskPackage = z_ext_record (assoc->encode, VAL_EXTENDED,
2627 (const char *) esrequest.taskPackage,
2629 yaz_log(YLOG_DEBUG,"Send the result apdu");