2 * Copyright (C) 1995-2005, Index Data ApS
3 * See the file LICENSE for details.
5 * $Id: seshigh.c,v 1.44 2005-01-15 19:47:14 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.
33 #include <sys/types.h>
36 #define S_ISREG(x) (x & _S_IFREG)
46 #include <yaz/yconfig.h>
47 #include <yaz/xmalloc.h>
48 #include <yaz/comstack.h>
51 #include <yaz/proto.h>
54 #include <yaz/logrpn.h>
55 #include <yaz/statserv.h>
56 #include <yaz/diagbib1.h>
57 #include <yaz/charneg.h>
58 #include <yaz/otherinfo.h>
59 #include <yaz/yaz-util.h>
60 #include <yaz/pquery.h>
63 #include <yaz/backend.h>
65 static void process_gdu_request(association *assoc, request *req);
66 static int process_z_request(association *assoc, request *req, char **msg);
67 void backend_response(IOCHAN i, int event);
68 static int process_gdu_response(association *assoc, request *req, Z_GDU *res);
69 static int process_z_response(association *assoc, request *req, Z_APDU *res);
70 static Z_APDU *process_initRequest(association *assoc, request *reqb);
71 static Z_External *init_diagnostics(ODR odr, int errcode,
72 const char *errstring);
73 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
75 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
76 bend_search_rr *bsrr, int *fd);
77 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
79 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
80 static Z_APDU *process_sortRequest(association *assoc, request *reqb, int *fd);
81 static void process_close(association *assoc, request *reqb);
82 void save_referenceId (request *reqb, Z_ReferenceId *refid);
83 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
85 static Z_APDU *process_segmentRequest (association *assoc, request *reqb);
87 static FILE *apduf = 0; /* for use in static mode */
88 static statserv_options_block *control_block = 0;
90 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd);
92 /* dynamic logging levels */
93 static int logbits_set = 0;
94 static int log_session = 0;
95 static int log_request = 0; /* one-line logs for requests */
96 static int log_requestdetail = 0; /* more detailed stuff */
98 /** get_logbits sets global loglevel bits */
99 static void get_logbits()
100 { /* needs to be called after parsing cmd-line args that can set loglevels!*/
104 log_session=yaz_log_module_level("session");
105 log_request=yaz_log_module_level("request");
106 log_requestdetail=yaz_log_module_level("requestdetail");
110 static void wr_diag(WRBUF w, int error, const char *addinfo)
112 wrbuf_printf(w, "ERROR [%d] %s%s%s",
113 error, diagbib1_str(error),
114 addinfo ? "--" : "", addinfo ? addinfo : "");
119 * Create and initialize a new association-handle.
120 * channel : iochannel for the current line.
121 * link : communications channel.
122 * Returns: 0 or a new association handle.
124 association *create_association(IOCHAN channel, COMSTACK link)
131 control_block = statserv_getcontrol();
132 if (!(anew = (association *)xmalloc(sizeof(*anew))))
136 anew->client_chan = channel;
137 anew->client_link = link;
138 anew->cs_get_mask = 0;
139 anew->cs_put_mask = 0;
140 anew->cs_accept_mask = 0;
141 if (!(anew->decode = odr_createmem(ODR_DECODE)) ||
142 !(anew->encode = odr_createmem(ODR_ENCODE)))
144 if (*control_block->apdufile)
149 strcpy(filename, control_block->apdufile);
150 if (!(anew->print = odr_createmem(ODR_PRINT)))
152 if (*control_block->apdufile == '@')
154 odr_setprint(anew->print, yaz_log_file());
156 else if (*control_block->apdufile != '-')
158 strcpy(filename, control_block->apdufile);
159 if (!control_block->dynamic)
163 if (!(apduf = fopen(filename, "w")))
165 yaz_log(YLOG_WARN|YLOG_ERRNO, "can't open apdu dump %s", filename);
168 setvbuf(apduf, 0, _IONBF, 0);
174 sprintf(filename + strlen(filename), ".%ld", (long)getpid());
175 if (!(f = fopen(filename, "w")))
177 yaz_log(YLOG_WARN|YLOG_ERRNO, "%s", filename);
180 setvbuf(f, 0, _IONBF, 0);
182 odr_setprint(anew->print, f);
187 anew->input_buffer = 0;
188 anew->input_buffer_len = 0;
190 anew->state = ASSOC_NEW;
191 request_initq(&anew->incoming);
192 request_initq(&anew->outgoing);
193 anew->proto = cs_getproto(link);
198 * Free association and release resources.
200 void destroy_association(association *h)
202 statserv_options_block *cb = statserv_getcontrol();
206 odr_destroy(h->decode);
207 odr_destroy(h->encode);
209 odr_destroy(h->print);
211 xfree(h->input_buffer);
213 (*cb->bend_close)(h->backend);
214 while ((req = request_deq(&h->incoming)))
215 request_release(req);
216 while ((req = request_deq(&h->outgoing)))
217 request_release(req);
218 request_delq(&h->incoming);
219 request_delq(&h->outgoing);
221 xmalloc_trav("session closed");
222 if (control_block && control_block->one_shot)
228 static void do_close_req(association *a, int reason, char *message,
232 Z_Close *cls = zget_Close(a->encode);
234 /* Purge request queue */
235 while (request_deq(&a->incoming));
236 while (request_deq(&a->outgoing));
239 yaz_log(log_requestdetail, "Sending Close PDU, reason=%d, message=%s",
240 reason, message ? message : "none");
241 apdu.which = Z_APDU_close;
243 *cls->closeReason = reason;
244 cls->diagnosticInformation = message;
245 process_z_response(a, req, &apdu);
246 iochan_settimeout(a->client_chan, 20);
250 request_release(req);
251 yaz_log(log_requestdetail, "v2 client. No Close PDU");
252 iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
254 a->state = ASSOC_DEAD;
257 static void do_close(association *a, int reason, char *message)
259 request *req = request_get(&a->outgoing);
260 do_close_req (a, reason, message, req);
264 * This is where PDUs from the client are read and the further
265 * processing is initiated. Flow of control moves down through the
266 * various process_* functions below, until the encoded result comes back up
267 * to the output handler in here.
269 * h : the I/O channel that has an outstanding event.
270 * event : the current outstanding event.
272 void ir_session(IOCHAN h, int event)
275 association *assoc = (association *)iochan_getdata(h);
276 COMSTACK conn = assoc->client_link;
279 assert(h && conn && assoc);
280 if (event == EVENT_TIMEOUT)
282 if (assoc->state != ASSOC_UP)
284 yaz_log(YLOG_DEBUG, "Final timeout - closing connection.");
285 /* do we need to lod this at all */
287 destroy_association(assoc);
292 yaz_log(log_session, "Session idle too long. Sending close.");
293 do_close(assoc, Z_Close_lackOfActivity, 0);
297 if (event & assoc->cs_accept_mask)
299 if (!cs_accept (conn))
301 yaz_log (YLOG_WARN, "accept failed");
302 destroy_association(assoc);
305 iochan_clearflag (h, EVENT_OUTPUT);
306 if (conn->io_pending)
307 { /* cs_accept didn't complete */
308 assoc->cs_accept_mask =
309 ((conn->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
310 ((conn->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
312 iochan_setflag (h, assoc->cs_accept_mask);
315 { /* cs_accept completed. Prepare for reading (cs_get) */
316 assoc->cs_accept_mask = 0;
317 assoc->cs_get_mask = EVENT_INPUT;
318 iochan_setflag (h, assoc->cs_get_mask);
322 if ((event & assoc->cs_get_mask) || (event & EVENT_WORK)) /* input */
324 if ((assoc->cs_put_mask & EVENT_INPUT) == 0 && (event & assoc->cs_get_mask))
326 yaz_log(YLOG_DEBUG, "ir_session (input)");
327 /* We aren't speaking to this fellow */
328 if (assoc->state == ASSOC_DEAD)
330 yaz_log(log_session, "Connection closed - end of session");
332 destroy_association(assoc);
336 assoc->cs_get_mask = EVENT_INPUT;
337 if ((res = cs_get(conn, &assoc->input_buffer,
338 &assoc->input_buffer_len)) <= 0)
340 yaz_log(log_session, "Connection closed by client");
342 destroy_association(assoc);
346 else if (res == 1) /* incomplete read - wait for more */
348 if (conn->io_pending & CS_WANT_WRITE)
349 assoc->cs_get_mask |= EVENT_OUTPUT;
350 iochan_setflag(h, assoc->cs_get_mask);
353 if (cs_more(conn)) /* more stuff - call us again later, please */
354 iochan_setevent(h, EVENT_INPUT);
356 /* we got a complete PDU. Let's decode it */
357 yaz_log(YLOG_DEBUG, "Got PDU, %d bytes: lead=%02X %02X %02X", res,
358 assoc->input_buffer[0] & 0xff,
359 assoc->input_buffer[1] & 0xff,
360 assoc->input_buffer[2] & 0xff);
361 req = request_get(&assoc->incoming); /* get a new request */
362 odr_reset(assoc->decode);
363 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
364 if (!z_GDU(assoc->decode, &req->gdu_request, 0, 0))
366 yaz_log(YLOG_WARN, "ODR error on incoming PDU: %s [element %s] "
368 odr_errmsg(odr_geterror(assoc->decode)),
369 odr_getelement(assoc->decode),
370 odr_offset(assoc->decode));
371 if (assoc->decode->error != OHTTP)
373 yaz_log(YLOG_WARN, "PDU dump:");
374 odr_dumpBER(yaz_log_file(), assoc->input_buffer, res);
375 request_release(req);
376 do_close(assoc, Z_Close_protocolError,"Malformed package");
380 Z_GDU *p = z_get_HTTP_Response(assoc->encode, 400);
381 assoc->state = ASSOC_DEAD;
382 process_gdu_response(assoc, req, p);
386 req->request_mem = odr_extract_mem(assoc->decode);
389 if (!z_GDU(assoc->print, &req->gdu_request, 0, 0))
390 yaz_log(YLOG_WARN, "ODR print error: %s",
391 odr_errmsg(odr_geterror(assoc->print)));
392 odr_reset(assoc->print);
394 request_enq(&assoc->incoming, req);
397 /* can we do something yet? */
398 req = request_head(&assoc->incoming);
399 if (req->state == REQUEST_IDLE)
401 request_deq(&assoc->incoming);
402 process_gdu_request(assoc, req);
405 if (event & assoc->cs_put_mask)
407 request *req = request_head(&assoc->outgoing);
409 assoc->cs_put_mask = 0;
410 yaz_log(YLOG_DEBUG, "ir_session (output)");
411 req->state = REQUEST_PENDING;
412 switch (res = cs_put(conn, req->response, req->len_response))
415 yaz_log(log_session, "Connection closed by client");
417 destroy_association(assoc);
420 case 0: /* all sent - release the request structure */
421 yaz_log(YLOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
423 yaz_log(YLOG_DEBUG, "HTTP out:\n%.*s", req->len_response,
426 nmem_destroy(req->request_mem);
427 request_deq(&assoc->outgoing);
428 request_release(req);
429 if (!request_head(&assoc->outgoing))
430 { /* restore mask for cs_get operation ... */
431 iochan_clearflag(h, EVENT_OUTPUT|EVENT_INPUT);
432 iochan_setflag(h, assoc->cs_get_mask);
433 if (assoc->state == ASSOC_DEAD)
434 iochan_setevent(assoc->client_chan, EVENT_TIMEOUT);
438 assoc->cs_put_mask = EVENT_OUTPUT;
442 if (conn->io_pending & CS_WANT_WRITE)
443 assoc->cs_put_mask |= EVENT_OUTPUT;
444 if (conn->io_pending & CS_WANT_READ)
445 assoc->cs_put_mask |= EVENT_INPUT;
446 iochan_setflag(h, assoc->cs_put_mask);
449 if (event & EVENT_EXCEPT)
451 yaz_log(YLOG_WARN, "ir_session (exception)");
453 destroy_association(assoc);
458 static int process_z_request(association *assoc, request *req, char **msg);
460 static void assoc_init_reset(association *assoc)
463 assoc->init = (bend_initrequest *) xmalloc (sizeof(*assoc->init));
465 assoc->init->stream = assoc->encode;
466 assoc->init->print = assoc->print;
467 assoc->init->auth = 0;
468 assoc->init->referenceId = 0;
469 assoc->init->implementation_version = 0;
470 assoc->init->implementation_id = 0;
471 assoc->init->implementation_name = 0;
472 assoc->init->bend_sort = NULL;
473 assoc->init->bend_search = NULL;
474 assoc->init->bend_present = NULL;
475 assoc->init->bend_esrequest = NULL;
476 assoc->init->bend_delete = NULL;
477 assoc->init->bend_scan = NULL;
478 assoc->init->bend_segment = NULL;
479 assoc->init->bend_fetch = NULL;
480 assoc->init->bend_explain = NULL;
481 assoc->init->bend_srw_scan = NULL;
483 assoc->init->charneg_request = NULL;
484 assoc->init->charneg_response = NULL;
486 assoc->init->decode = assoc->decode;
487 assoc->init->peer_name =
488 odr_strdup (assoc->encode, cs_addrstr(assoc->client_link));
491 static int srw_bend_init(association *assoc, Z_SRW_diagnostic **d, int *num)
493 const char *encoding = "UTF-8";
495 bend_initresult *binitres;
496 statserv_options_block *cb = statserv_getcontrol();
498 assoc_init_reset(assoc);
500 assoc->maximumRecordSize = 3000000;
501 assoc->preferredMessageSize = 3000000;
503 ce = yaz_set_proposal_charneg(assoc->decode, &encoding, 1, 0, 0, 1);
504 assoc->init->charneg_request = ce->u.charNeg3;
507 if (!(binitres = (*cb->bend_init)(assoc->init)))
509 assoc->state = ASSOC_DEAD;
510 yaz_add_srw_diagnostic(assoc->encode, d, num, 3, 0);
513 assoc->backend = binitres->handle;
514 if (binitres->errcode)
516 assoc->state = ASSOC_DEAD;
517 yaz_add_srw_diagnostic(assoc->encode, d, num, binitres->errcode,
518 binitres->errstring);
524 static int srw_bend_fetch(association *assoc, int pos,
525 Z_SRW_searchRetrieveRequest *srw_req,
526 Z_SRW_record *record)
529 ODR o = assoc->encode;
531 rr.setname = "default";
534 rr.request_format = VAL_TEXT_XML;
535 rr.request_format_raw = yaz_oidval_to_z3950oid(assoc->decode,
538 rr.comp = (Z_RecordComposition *)
539 odr_malloc(assoc->decode, sizeof(*rr.comp));
540 rr.comp->which = Z_RecordComp_complex;
541 rr.comp->u.complex = (Z_CompSpec *)
542 odr_malloc(assoc->decode, sizeof(Z_CompSpec));
543 rr.comp->u.complex->selectAlternativeSyntax = (bool_t *)
544 odr_malloc(assoc->encode, sizeof(bool_t));
545 *rr.comp->u.complex->selectAlternativeSyntax = 0;
546 rr.comp->u.complex->num_dbSpecific = 0;
547 rr.comp->u.complex->dbSpecific = 0;
548 rr.comp->u.complex->num_recordSyntax = 0;
549 rr.comp->u.complex->recordSyntax = 0;
551 rr.comp->u.complex->generic = (Z_Specification *)
552 odr_malloc(assoc->decode, sizeof(Z_Specification));
554 /* schema uri = recordSchema (or NULL if recordSchema is not given) */
555 rr.comp->u.complex->generic->which = Z_Schema_uri;
556 rr.comp->u.complex->generic->schema.uri = srw_req->recordSchema;
558 /* ESN = recordSchema if recordSchema is present */
559 rr.comp->u.complex->generic->elementSpec = 0;
560 if (srw_req->recordSchema)
562 rr.comp->u.complex->generic->elementSpec =
563 (Z_ElementSpec *) odr_malloc(assoc->encode, sizeof(Z_ElementSpec));
564 rr.comp->u.complex->generic->elementSpec->which =
565 Z_ElementSpec_elementSetName;
566 rr.comp->u.complex->generic->elementSpec->u.elementSetName =
567 srw_req->recordSchema;
570 rr.stream = assoc->encode;
571 rr.print = assoc->print;
577 rr.output_format = VAL_TEXT_XML;
578 rr.output_format_raw = 0;
581 rr.surrogate_flag = 0;
582 rr.schema = srw_req->recordSchema;
584 if (!assoc->init->bend_fetch)
587 (*assoc->init->bend_fetch)(assoc->backend, &rr);
589 if (rr.errcode && rr.surrogate_flag)
591 int code = yaz_diag_bib1_to_srw(rr.errcode);
592 const char *message = yaz_diag_srw_str(code);
595 len += strlen(message);
597 len += strlen(rr.errstring);
599 record->recordData_buf = odr_malloc(o, len);
601 sprintf(record->recordData_buf, "<diagnostic "
602 "xmlns=\"http://www.loc.gov/zing/srw/diagnostic/\">\n"
603 " <uri>info:srw/diagnostic/1/%d</uri>\n", code);
605 sprintf(record->recordData_buf + strlen(record->recordData_buf),
606 " <details>%s</details>\n", rr.errstring);
608 sprintf(record->recordData_buf + strlen(record->recordData_buf),
609 " <message>%s</message>\n", message);
610 sprintf(record->recordData_buf + strlen(record->recordData_buf),
612 record->recordData_len = strlen(record->recordData_buf);
613 record->recordPosition = odr_intdup(o, pos);
614 record->recordSchema = "info:srw/schema/1/diagnostics-v1.1";
617 else if (rr.len >= 0)
619 record->recordData_buf = rr.record;
620 record->recordData_len = rr.len;
621 record->recordPosition = odr_intdup(o, pos);
623 record->recordSchema = odr_strdup(o, rr.schema);
625 record->recordSchema = 0;
630 static void srw_bend_search(association *assoc, request *req,
631 Z_SRW_searchRetrieveRequest *srw_req,
632 Z_SRW_searchRetrieveResponse *srw_res,
639 yaz_log(log_requestdetail, "Got SRW SearchRetrieveRequest");
641 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics);
642 if (srw_req->sort_type != Z_SRW_sort_type_none)
643 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
644 &srw_res->num_diagnostics, 80, 0);
645 else if (srw_res->num_diagnostics == 0 && assoc->init)
648 rr.setname = "default";
651 rr.basenames = &srw_req->database;
654 rr.query = (Z_Query *) odr_malloc (assoc->decode, sizeof(*rr.query));
656 if (srw_req->query_type == Z_SRW_query_type_cql)
658 ext = (Z_External *) odr_malloc(assoc->decode, sizeof(*ext));
659 ext->direct_reference = odr_getoidbystr(assoc->decode,
660 "1.2.840.10003.16.2");
661 ext->indirect_reference = 0;
663 ext->which = Z_External_CQL;
664 ext->u.cql = srw_req->query.cql;
666 rr.query->which = Z_Query_type_104;
667 rr.query->u.type_104 = ext;
669 else if (srw_req->query_type == Z_SRW_query_type_pqf)
671 Z_RPNQuery *RPNquery;
672 YAZ_PQF_Parser pqf_parser;
674 pqf_parser = yaz_pqf_create ();
676 RPNquery = yaz_pqf_parse (pqf_parser, assoc->decode,
682 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
683 yaz_log(log_requestdetail, "Parse error %d %s near offset %d",
688 rr.query->which = Z_Query_type_1;
689 rr.query->u.type_1 = RPNquery;
691 yaz_pqf_destroy (pqf_parser);
695 rr.query->u.type_1 = 0;
696 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
697 &srw_res->num_diagnostics, 11, 0);
699 if (rr.query->u.type_1)
701 rr.stream = assoc->encode;
702 rr.decode = assoc->decode;
703 rr.print = assoc->print;
705 rr.association = assoc;
711 yaz_log_zquery_level(log_requestdetail,rr.query);
713 (assoc->init->bend_search)(assoc->backend, &rr);
716 if (rr.errcode == 109) /* database unavailable */
722 srw_error = yaz_diag_bib1_to_srw (rr.errcode);
723 yaz_add_srw_diagnostic(assoc->encode,
724 &srw_res->diagnostics,
725 &srw_res->num_diagnostics,
726 srw_error, rr.errstring);
731 int number = srw_req->maximumRecords ? *srw_req->maximumRecords : 0;
732 int start = srw_req->startRecord ? *srw_req->startRecord : 1;
734 yaz_log(log_requestdetail, "Request to pack %d+%d out of %d",
735 start, number, rr.hits);
737 srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
744 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
745 &srw_res->num_diagnostics,
751 int packing = Z_SRW_recordPacking_string;
752 if (start + number > rr.hits)
753 number = rr.hits - start + 1;
754 if (srw_req->recordPacking &&
755 !strcmp(srw_req->recordPacking, "xml"))
756 packing = Z_SRW_recordPacking_XML;
757 srw_res->records = (Z_SRW_record *)
758 odr_malloc(assoc->encode,
759 number * sizeof(*srw_res->records));
760 for (i = 0; i<number; i++)
764 srw_res->records[j].recordPacking = packing;
765 srw_res->records[j].recordData_buf = 0;
766 yaz_log(YLOG_DEBUG, "srw_bend_fetch %d", i+start);
767 errcode = srw_bend_fetch(assoc, i+start, srw_req,
768 srw_res->records + j);
771 yaz_add_srw_diagnostic(assoc->encode,
772 &srw_res->diagnostics,
773 &srw_res->num_diagnostics,
774 yaz_diag_bib1_to_srw (errcode),
779 if (srw_res->records[j].recordData_buf)
782 srw_res->num_records = j;
784 srw_res->records = 0;
792 const char *querystr = "?";
793 const char *querytype = "?";
794 WRBUF wr = wrbuf_alloc();
796 switch (srw_req->query_type)
798 case Z_SRW_query_type_cql:
800 querystr = srw_req->query.cql;
802 case Z_SRW_query_type_pqf:
804 querystr = srw_req->query.pqf;
807 wrbuf_printf(wr, "SRWSearch ");
808 if (srw_res->num_diagnostics)
809 wrbuf_printf(wr, "ERROR %s", srw_res->diagnostics[0].uri);
810 else if (*http_code != 200)
811 wrbuf_printf(wr, "ERROR info:http/%d", *http_code);
812 else if (srw_res->numberOfRecords)
814 wrbuf_printf(wr, "OK %d",
815 (srw_res->numberOfRecords ?
816 *srw_res->numberOfRecords : 0));
818 wrbuf_printf(wr, " %s %d+%d",
819 (srw_res->resultSetId ?
820 srw_res->resultSetId : "-"),
821 (srw_req->startRecord ? *srw_req->startRecord : 1),
822 srw_res->num_records);
823 yaz_log(log_request, "%s %s: %s", wrbuf_buf(wr), querytype, querystr);
828 static void srw_bend_explain(association *assoc, request *req,
829 Z_SRW_explainRequest *srw_req,
830 Z_SRW_explainResponse *srw_res,
833 yaz_log(log_requestdetail, "Got SRW ExplainRequest");
836 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics);
837 if (assoc->init && assoc->init->bend_explain)
841 rr.stream = assoc->encode;
842 rr.decode = assoc->decode;
843 rr.print = assoc->print;
845 rr.database = srw_req->database;
846 rr.schema = "http://explain.z3950.org/dtd/2.0/";
847 (*assoc->init->bend_explain)(assoc->backend, &rr);
850 int packing = Z_SRW_recordPacking_string;
851 if (srw_req->recordPacking &&
852 !strcmp(srw_req->recordPacking, "xml"))
853 packing = Z_SRW_recordPacking_XML;
854 srw_res->record.recordSchema = rr.schema;
855 srw_res->record.recordPacking = packing;
856 srw_res->record.recordData_buf = rr.explain_buf;
857 srw_res->record.recordData_len = strlen(rr.explain_buf);
858 srw_res->record.recordPosition = 0;
864 static void srw_bend_scan(association *assoc, request *req,
865 Z_SRW_scanRequest *srw_req,
866 Z_SRW_scanResponse *srw_res,
869 yaz_log(log_requestdetail, "Got SRW ScanRequest");
873 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics);
874 if (srw_res->num_diagnostics == 0 && assoc->init)
876 struct scan_entry *save_entries;
878 bend_scan_rr *bsrr = (bend_scan_rr *)
879 odr_malloc (assoc->encode, sizeof(*bsrr));
881 bsrr->basenames = &srw_req->database;
883 bsrr->num_entries = srw_req->maximumTerms ?
884 *srw_req->maximumTerms : 10;
885 bsrr->term_position = srw_req->responsePosition ?
886 *srw_req->responsePosition : 1;
890 bsrr->referenceId = 0;
891 bsrr->stream = assoc->encode;
892 bsrr->print = assoc->print;
893 bsrr->step_size = odr_intdup(assoc->decode, 0);
896 if (bsrr->num_entries > 0)
899 bsrr->entries = odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
901 for (i = 0; i<bsrr->num_entries; i++)
903 bsrr->entries[i].term = 0;
904 bsrr->entries[i].occurrences = 0;
905 bsrr->entries[i].errcode = 0;
906 bsrr->entries[i].errstring = 0;
907 bsrr->entries[i].display_term = 0;
910 save_entries = bsrr->entries; /* save it so we can compare later */
912 if (srw_req->query_type == Z_SRW_query_type_pqf &&
913 assoc->init->bend_scan)
915 Odr_oid *scan_attributeSet = 0;
917 YAZ_PQF_Parser pqf_parser = yaz_pqf_create();
919 bsrr->term = yaz_pqf_scan(pqf_parser, assoc->decode,
921 srw_req->scanClause.pqf);
922 if (scan_attributeSet &&
923 (attset = oid_getentbyoid(scan_attributeSet)) &&
924 (attset->oclass == CLASS_ATTSET ||
925 attset->oclass == CLASS_GENERAL))
926 bsrr->attributeset = attset->value;
928 bsrr->attributeset = VAL_NONE;
929 yaz_pqf_destroy(pqf_parser);
930 bsrr->scanClause = 0;
931 ((int (*)(void *, bend_scan_rr *))
932 (*assoc->init->bend_scan))(assoc->backend, bsrr);
934 else if (srw_req->query_type == Z_SRW_query_type_cql
935 && assoc->init->bend_srw_scan)
938 bsrr->attributeset = VAL_NONE;
939 bsrr->scanClause = srw_req->scanClause.cql;
940 ((int (*)(void *, bend_scan_rr *))
941 (*assoc->init->bend_srw_scan))(assoc->backend, bsrr);
945 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
946 &srw_res->num_diagnostics, 4, "scan");
951 if (bsrr->errcode == 109) /* database unavailable */
956 srw_error = yaz_diag_bib1_to_srw (bsrr->errcode);
958 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
959 &srw_res->num_diagnostics,
960 srw_error, bsrr->errstring);
962 else if (srw_res->num_diagnostics == 0 && bsrr->num_entries)
965 srw_res->terms = (Z_SRW_scanTerm*)
966 odr_malloc(assoc->encode, sizeof(*srw_res->terms) *
969 srw_res->num_terms = bsrr->num_entries;
970 for (i = 0; i<bsrr->num_entries; i++)
972 Z_SRW_scanTerm *t = srw_res->terms + i;
973 t->value = odr_strdup(assoc->encode, bsrr->entries[i].term);
975 odr_intdup(assoc->encode, bsrr->entries[i].occurrences);
977 if (save_entries == bsrr->entries &&
978 bsrr->entries[i].display_term)
980 /* the entries was _not_ set by the handler. So it's
981 safe to test for new member display_term. It is
984 t->displayTerm = odr_strdup(assoc->encode,
985 bsrr->entries[i].display_term);
993 WRBUF wr = wrbuf_alloc();
994 const char *querytype = 0;
995 const char *querystr = 0;
997 switch(srw_req->query_type)
999 case Z_SRW_query_type_pqf:
1001 querystr = srw_req->scanClause.pqf;
1003 case Z_SRW_query_type_cql:
1005 querystr = srw_req->scanClause.cql;
1008 querytype = "Unknown";
1011 wrbuf_printf(wr, "SRWScan %d+%d",
1012 (srw_req->responsePosition ?
1013 *srw_req->responsePosition : 1),
1014 (srw_req->maximumTerms ?
1015 *srw_req->maximumTerms : 1));
1016 if (srw_res->num_diagnostics)
1017 wrbuf_printf(wr, " ERROR %s", srw_res->diagnostics[0].uri);
1019 wrbuf_printf(wr, " OK -");
1020 wrbuf_printf(wr, " %s: %s", querytype, querystr);
1021 yaz_log(log_request, "%s", wrbuf_buf(wr) );
1028 static void process_http_request(association *assoc, request *req)
1030 Z_HTTP_Request *hreq = req->gdu_request->u.HTTP_Request;
1031 ODR o = assoc->encode;
1032 int r = 2; /* 2=NOT TAKEN, 1=TAKEN, 0=SOAP TAKEN */
1034 Z_SOAP *soap_package = 0;
1037 Z_HTTP_Response *hres = 0;
1039 char *stylesheet = 0;
1040 Z_SRW_diagnostic *diagnostic = 0;
1041 int num_diagnostic = 0;
1043 if (!strcmp(hreq->path, "/test"))
1045 p = z_get_HTTP_Response(o, 200);
1046 hres = p->u.HTTP_Response;
1047 hres->content_buf = "1234567890\n";
1048 hres->content_len = strlen(hres->content_buf);
1053 r = yaz_srw_decode(hreq, &sr, &soap_package, assoc->decode, &charset);
1054 yaz_log(YLOG_DEBUG, "yaz_srw_decode returned %d", r);
1056 if (r == 2) /* not taken */
1058 r = yaz_sru_decode(hreq, &sr, &soap_package, assoc->decode, &charset,
1059 &diagnostic, &num_diagnostic);
1060 yaz_log(YLOG_DEBUG, "yaz_sru_decode returned %d", r);
1062 if (r == 0) /* decode SRW/SRU OK .. */
1064 int http_code = 200;
1065 if (sr->which == Z_SRW_searchRetrieve_request)
1068 yaz_srw_get(assoc->encode, Z_SRW_searchRetrieve_response);
1070 stylesheet = sr->u.request->stylesheet;
1073 res->u.response->diagnostics = diagnostic;
1074 res->u.response->num_diagnostics = num_diagnostic;
1078 srw_bend_search(assoc, req, sr->u.request, res->u.response,
1081 if (http_code == 200)
1082 soap_package->u.generic->p = res;
1084 else if (sr->which == Z_SRW_explain_request)
1086 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_explain_response);
1087 stylesheet = sr->u.explain_request->stylesheet;
1090 res->u.explain_response->diagnostics = diagnostic;
1091 res->u.explain_response->num_diagnostics = num_diagnostic;
1093 srw_bend_explain(assoc, req, sr->u.explain_request,
1094 res->u.explain_response, &http_code);
1095 if (http_code == 200)
1096 soap_package->u.generic->p = res;
1098 else if (sr->which == Z_SRW_scan_request)
1100 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_scan_response);
1101 stylesheet = sr->u.scan_request->stylesheet;
1104 res->u.scan_response->diagnostics = diagnostic;
1105 res->u.scan_response->num_diagnostics = num_diagnostic;
1107 srw_bend_scan(assoc, req, sr->u.scan_request,
1108 res->u.scan_response, &http_code);
1109 if (http_code == 200)
1110 soap_package->u.generic->p = res;
1114 yaz_log(log_request, "SOAP ERROR");
1115 /* FIXME - what error, what query */
1117 z_soap_error(assoc->encode, soap_package,
1118 "SOAP-ENV:Client", "Bad method", 0);
1120 if (http_code == 200 || http_code == 500)
1122 static Z_SOAP_Handler soap_handlers[3] = {
1124 {"http://www.loc.gov/zing/srw/", 0,
1125 (Z_SOAP_fun) yaz_srw_codec},
1126 {"http://www.loc.gov/zing/srw/v1.0/", 0,
1127 (Z_SOAP_fun) yaz_srw_codec},
1133 p = z_get_HTTP_Response(o, 200);
1134 hres = p->u.HTTP_Response;
1135 ret = z_soap_codec_enc_xsl(assoc->encode, &soap_package,
1136 &hres->content_buf, &hres->content_len,
1137 soap_handlers, charset, stylesheet);
1138 hres->code = http_code;
1140 strcpy(ctype, "text/xml");
1143 strcat(ctype, "; charset=");
1144 strcat(ctype, charset);
1146 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1149 p = z_get_HTTP_Response(o, http_code);
1153 p = z_get_HTTP_Response(o, 500);
1154 hres = p->u.HTTP_Response;
1155 if (!strcmp(hreq->version, "1.0"))
1157 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1158 if (v && !strcmp(v, "Keep-Alive"))
1162 hres->version = "1.0";
1166 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1167 if (v && !strcmp(v, "close"))
1171 hres->version = "1.1";
1175 z_HTTP_header_add(o, &hres->headers, "Connection", "close");
1176 assoc->state = ASSOC_DEAD;
1177 assoc->cs_get_mask = 0;
1182 const char *alive = z_HTTP_header_lookup(hreq->headers, "Keep-Alive");
1184 if (alive && isdigit(*(const unsigned char *) alive))
1188 if (t < 0 || t > 3600)
1190 iochan_settimeout(assoc->client_chan,t);
1191 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1193 process_gdu_response(assoc, req, p);
1196 static void process_gdu_request(association *assoc, request *req)
1198 if (req->gdu_request->which == Z_GDU_Z3950)
1201 req->apdu_request = req->gdu_request->u.z3950;
1202 if (process_z_request(assoc, req, &msg) < 0)
1203 do_close_req(assoc, Z_Close_systemProblem, msg, req);
1205 else if (req->gdu_request->which == Z_GDU_HTTP_Request)
1206 process_http_request(assoc, req);
1209 do_close_req(assoc, Z_Close_systemProblem, "bad protocol packet", req);
1214 * Initiate request processing.
1216 static int process_z_request(association *assoc, request *req, char **msg)
1222 *msg = "Unknown Error";
1223 assert(req && req->state == REQUEST_IDLE);
1224 if (req->apdu_request->which != Z_APDU_initRequest && !assoc->init)
1226 *msg = "Missing InitRequest";
1229 switch (req->apdu_request->which)
1231 case Z_APDU_initRequest:
1232 iochan_settimeout(assoc->client_chan,
1233 statserv_getcontrol()->idle_timeout * 60);
1234 res = process_initRequest(assoc, req); break;
1235 case Z_APDU_searchRequest:
1236 res = process_searchRequest(assoc, req, &fd); break;
1237 case Z_APDU_presentRequest:
1238 res = process_presentRequest(assoc, req, &fd); break;
1239 case Z_APDU_scanRequest:
1240 if (assoc->init->bend_scan)
1241 res = process_scanRequest(assoc, req, &fd);
1244 *msg = "Cannot handle Scan APDU";
1248 case Z_APDU_extendedServicesRequest:
1249 if (assoc->init->bend_esrequest)
1250 res = process_ESRequest(assoc, req, &fd);
1253 *msg = "Cannot handle Extended Services APDU";
1257 case Z_APDU_sortRequest:
1258 if (assoc->init->bend_sort)
1259 res = process_sortRequest(assoc, req, &fd);
1262 *msg = "Cannot handle Sort APDU";
1267 process_close(assoc, req);
1269 case Z_APDU_deleteResultSetRequest:
1270 if (assoc->init->bend_delete)
1271 res = process_deleteRequest(assoc, req, &fd);
1274 *msg = "Cannot handle Delete APDU";
1278 case Z_APDU_segmentRequest:
1279 if (assoc->init->bend_segment)
1281 res = process_segmentRequest (assoc, req);
1285 *msg = "Cannot handle Segment APDU";
1289 case Z_APDU_triggerResourceControlRequest:
1292 *msg = "Bad APDU received";
1297 yaz_log(YLOG_DEBUG, " result immediately available");
1298 retval = process_z_response(assoc, req, res);
1302 yaz_log(YLOG_DEBUG, " result unavailble");
1305 else /* no result yet - one will be provided later */
1309 /* Set up an I/O handler for the fd supplied by the backend */
1311 yaz_log(YLOG_DEBUG, " establishing handler for result");
1312 req->state = REQUEST_PENDING;
1313 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT)))
1315 iochan_setdata(chan, assoc);
1322 * Handle message from the backend.
1324 void backend_response(IOCHAN i, int event)
1326 association *assoc = (association *)iochan_getdata(i);
1327 request *req = request_head(&assoc->incoming);
1331 yaz_log(YLOG_DEBUG, "backend_response");
1332 assert(assoc && req && req->state != REQUEST_IDLE);
1333 /* determine what it is we're waiting for */
1334 switch (req->apdu_request->which)
1336 case Z_APDU_searchRequest:
1337 res = response_searchRequest(assoc, req, 0, &fd); break;
1339 case Z_APDU_presentRequest:
1340 res = response_presentRequest(assoc, req, 0, &fd); break;
1341 case Z_APDU_scanRequest:
1342 res = response_scanRequest(assoc, req, 0, &fd); break;
1345 yaz_log(YLOG_FATAL, "Serious programmer's lapse or bug");
1348 if ((res && process_z_response(assoc, req, res) < 0) || fd < 0)
1350 yaz_log(YLOG_WARN, "Fatal error when talking to backend");
1351 do_close(assoc, Z_Close_systemProblem, 0);
1355 else if (!res) /* no result yet - try again later */
1357 yaz_log(YLOG_DEBUG, " no result yet");
1358 iochan_setfd(i, fd); /* in case fd has changed */
1363 * Encode response, and transfer the request structure to the outgoing queue.
1365 static int process_gdu_response(association *assoc, request *req, Z_GDU *res)
1367 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
1371 if (!z_GDU(assoc->print, &res, 0, 0))
1372 yaz_log(YLOG_WARN, "ODR print error: %s",
1373 odr_errmsg(odr_geterror(assoc->print)));
1374 odr_reset(assoc->print);
1376 if (!z_GDU(assoc->encode, &res, 0, 0))
1378 yaz_log(YLOG_WARN, "ODR error when encoding PDU: %s [element %s]",
1379 odr_errmsg(odr_geterror(assoc->decode)),
1380 odr_getelement(assoc->decode));
1383 req->response = odr_getbuf(assoc->encode, &req->len_response,
1384 &req->size_response);
1385 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
1386 odr_reset(assoc->encode);
1387 req->state = REQUEST_IDLE;
1388 request_enq(&assoc->outgoing, req);
1389 /* turn the work over to the ir_session handler */
1390 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
1391 assoc->cs_put_mask = EVENT_OUTPUT;
1392 /* Is there more work to be done? give that to the input handler too */
1394 if (request_head(&assoc->incoming))
1396 yaz_log (YLOG_DEBUG, "more work to be done");
1397 iochan_setevent(assoc->client_chan, EVENT_WORK);
1404 * Encode response, and transfer the request structure to the outgoing queue.
1406 static int process_z_response(association *assoc, request *req, Z_APDU *res)
1408 Z_GDU *gres = (Z_GDU *) odr_malloc(assoc->encode, sizeof(*res));
1409 gres->which = Z_GDU_Z3950;
1410 gres->u.z3950 = res;
1412 return process_gdu_response(assoc, req, gres);
1417 * Handle init request.
1418 * At the moment, we don't check the options
1419 * anywhere else in the code - we just try not to do anything that would
1420 * break a naive client. We'll toss 'em into the association block when
1421 * we need them there.
1423 static Z_APDU *process_initRequest(association *assoc, request *reqb)
1425 statserv_options_block *cb = statserv_getcontrol();
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;
1433 yaz_log(log_requestdetail, "Got initRequest");
1434 if (req->implementationId)
1435 yaz_log(log_requestdetail, "Id: %s", req->implementationId);
1436 if (req->implementationName)
1437 yaz_log(log_requestdetail, "Name: %s", req->implementationName);
1438 if (req->implementationVersion)
1439 yaz_log(log_requestdetail, "Version: %s", req->implementationVersion);
1441 assoc_init_reset(assoc);
1443 assoc->init->auth = req->idAuthentication;
1444 assoc->init->referenceId = req->referenceId;
1446 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
1448 Z_CharSetandLanguageNegotiation *negotiation =
1449 yaz_get_charneg_record (req->otherInfo);
1451 negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
1452 assoc->init->charneg_request = negotiation;
1456 if (!(binitres = (*cb->bend_init)(assoc->init)))
1458 yaz_log(YLOG_WARN, "Bad response from backend.");
1462 assoc->backend = binitres->handle;
1463 if ((assoc->init->bend_sort))
1464 yaz_log (YLOG_DEBUG, "Sort handler installed");
1465 if ((assoc->init->bend_search))
1466 yaz_log (YLOG_DEBUG, "Search handler installed");
1467 if ((assoc->init->bend_present))
1468 yaz_log (YLOG_DEBUG, "Present handler installed");
1469 if ((assoc->init->bend_esrequest))
1470 yaz_log (YLOG_DEBUG, "ESRequest handler installed");
1471 if ((assoc->init->bend_delete))
1472 yaz_log (YLOG_DEBUG, "Delete handler installed");
1473 if ((assoc->init->bend_scan))
1474 yaz_log (YLOG_DEBUG, "Scan handler installed");
1475 if ((assoc->init->bend_segment))
1476 yaz_log (YLOG_DEBUG, "Segment handler installed");
1478 resp->referenceId = req->referenceId;
1480 /* let's tell the client what we can do */
1481 if (ODR_MASK_GET(req->options, Z_Options_search))
1483 ODR_MASK_SET(resp->options, Z_Options_search);
1484 strcat(options, "srch");
1486 if (ODR_MASK_GET(req->options, Z_Options_present))
1488 ODR_MASK_SET(resp->options, Z_Options_present);
1489 strcat(options, " prst");
1491 if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
1492 assoc->init->bend_delete)
1494 ODR_MASK_SET(resp->options, Z_Options_delSet);
1495 strcat(options, " del");
1497 if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
1498 assoc->init->bend_esrequest)
1500 ODR_MASK_SET(resp->options, Z_Options_extendedServices);
1501 strcat (options, " extendedServices");
1503 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
1505 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
1506 strcat(options, " namedresults");
1508 if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
1510 ODR_MASK_SET(resp->options, Z_Options_scan);
1511 strcat(options, " scan");
1513 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
1515 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
1516 strcat(options, " concurrop");
1518 if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
1520 ODR_MASK_SET(resp->options, Z_Options_sort);
1521 strcat(options, " sort");
1524 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel)
1525 && assoc->init->charneg_response)
1527 Z_OtherInformation **p;
1528 Z_OtherInformationUnit *p0;
1530 yaz_oi_APDU(apdu, &p);
1532 if ((p0=yaz_oi_update(p, assoc->encode, NULL, 0, 0))) {
1533 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
1535 p0->which = Z_OtherInfo_externallyDefinedInfo;
1536 p0->information.externallyDefinedInfo =
1537 assoc->init->charneg_response;
1539 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
1540 strcat(options, " negotiation");
1543 ODR_MASK_SET(resp->options, Z_Options_triggerResourceCtrl);
1545 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
1547 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
1548 assoc->version = 1; /* 1 & 2 are equivalent */
1550 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
1552 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
1555 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
1557 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
1561 yaz_log(log_requestdetail, "Negotiated to v%d: %s", assoc->version, options);
1562 assoc->maximumRecordSize = *req->maximumRecordSize;
1563 if (assoc->maximumRecordSize > control_block->maxrecordsize)
1564 assoc->maximumRecordSize = control_block->maxrecordsize;
1565 assoc->preferredMessageSize = *req->preferredMessageSize;
1566 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
1567 assoc->preferredMessageSize = assoc->maximumRecordSize;
1569 resp->preferredMessageSize = &assoc->preferredMessageSize;
1570 resp->maximumRecordSize = &assoc->maximumRecordSize;
1572 resp->implementationId = odr_prepend(assoc->encode,
1573 assoc->init->implementation_id,
1574 resp->implementationId);
1576 resp->implementationName = odr_prepend(assoc->encode,
1577 assoc->init->implementation_name,
1578 odr_prepend(assoc->encode, "GFS", resp->implementationName));
1580 version = odr_strdup(assoc->encode, "$Revision: 1.44 $");
1581 if (strlen(version) > 10) /* check for unexpanded CVS strings */
1582 version[strlen(version)-2] = '\0';
1583 resp->implementationVersion = odr_prepend(assoc->encode,
1584 assoc->init->implementation_version,
1585 odr_prepend(assoc->encode, &version[11],
1586 resp->implementationVersion));
1588 if (binitres->errcode)
1590 assoc->state = ASSOC_DEAD;
1591 resp->userInformationField =
1592 init_diagnostics(assoc->encode, binitres->errcode,
1593 binitres->errstring);
1598 WRBUF wr = wrbuf_alloc();
1599 wrbuf_printf(wr, "Init ");
1600 if (binitres->errcode)
1601 wrbuf_printf(wr, "ERROR %d", binitres->errcode);
1603 wrbuf_printf(wr, "OK -");
1604 wrbuf_printf(wr, " ID:%s Name:%s Version:%s",
1605 (req->implementationId ? req->implementationId :"-"),
1606 (req->implementationName ?
1607 req->implementationName : "-"),
1608 (req->implementationVersion ?
1609 req->implementationVersion : "-")
1611 yaz_log(log_request, "%s", wrbuf_buf(wr));
1618 * Set the specified `errcode' and `errstring' into a UserInfo-1
1619 * external to be returned to the client in accordance with Z35.90
1620 * Implementor Agreement 5 (Returning diagnostics in an InitResponse):
1621 * http://lcweb.loc.gov/z3950/agency/agree/initdiag.html
1623 static Z_External *init_diagnostics(ODR odr, int error, const char *addinfo)
1625 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
1626 addinfo ? " -- " : "", addinfo ? addinfo : "");
1627 return zget_init_diagnostics(odr, error, addinfo);
1631 * nonsurrogate diagnostic record.
1633 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
1635 Z_Records *rec = (Z_Records *) odr_malloc (assoc->encode, sizeof(*rec));
1637 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
1638 addinfo ? " -- " : "", addinfo ? addinfo : "");
1640 rec->which = Z_Records_NSD;
1641 rec->u.nonSurrogateDiagnostic = zget_DefaultDiagFormat(assoc->encode,
1647 * surrogate diagnostic.
1649 static Z_NamePlusRecord *surrogatediagrec(association *assoc,
1651 int error, const char *addinfo)
1653 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
1654 addinfo ? " -- " : "", addinfo ? addinfo : "");
1655 return zget_surrogateDiagRec(assoc->encode, dbname, error, addinfo);
1658 static Z_Records *pack_records(association *a, char *setname, int start,
1659 int *num, Z_RecordComposition *comp,
1660 int *next, int *pres, oid_value format,
1661 Z_ReferenceId *referenceId,
1662 int *oid, int *errcode)
1664 int recno, total_length = 0, toget = *num, dumped_records = 0;
1665 Z_Records *records =
1666 (Z_Records *) odr_malloc (a->encode, sizeof(*records));
1667 Z_NamePlusRecordList *reclist =
1668 (Z_NamePlusRecordList *) odr_malloc (a->encode, sizeof(*reclist));
1669 Z_NamePlusRecord **list =
1670 (Z_NamePlusRecord **) odr_malloc (a->encode, sizeof(*list) * toget);
1672 records->which = Z_Records_DBOSD;
1673 records->u.databaseOrSurDiagnostics = reclist;
1674 reclist->num_records = 0;
1675 reclist->records = list;
1676 *pres = Z_PresentStatus_success;
1680 yaz_log(log_requestdetail, "Request to pack %d+%d %s", start, toget, setname);
1681 yaz_log(log_requestdetail, "pms=%d, mrs=%d", a->preferredMessageSize,
1682 a->maximumRecordSize);
1683 for (recno = start; reclist->num_records < toget; recno++)
1686 Z_NamePlusRecord *thisrec;
1687 int this_length = 0;
1689 * we get the number of bytes allocated on the stream before any
1690 * allocation done by the backend - this should give us a reasonable
1691 * idea of the total size of the data so far.
1693 total_length = odr_total(a->encode) - dumped_records;
1699 freq.last_in_set = 0;
1700 freq.setname = setname;
1701 freq.surrogate_flag = 0;
1702 freq.number = recno;
1704 freq.request_format = format;
1705 freq.request_format_raw = oid;
1706 freq.output_format = format;
1707 freq.output_format_raw = 0;
1708 freq.stream = a->encode;
1709 freq.print = a->print;
1710 freq.referenceId = referenceId;
1712 (*a->init->bend_fetch)(a->backend, &freq);
1713 /* backend should be able to signal whether error is system-wide
1714 or only pertaining to current record */
1717 if (!freq.surrogate_flag)
1720 *pres = Z_PresentStatus_failure;
1721 /* for 'present request out of range',
1722 set addinfo to record position if not set */
1723 if (freq.errcode == 13 && freq.errstring == 0)
1725 sprintf (s, "%d", recno);
1729 *errcode = freq.errcode;
1730 return diagrec(a, freq.errcode, freq.errstring);
1732 reclist->records[reclist->num_records] =
1733 surrogatediagrec(a, freq.basename, freq.errcode,
1735 reclist->num_records++;
1736 *next = freq.last_in_set ? 0 : recno + 1;
1740 this_length = freq.len;
1742 this_length = odr_total(a->encode) - total_length - dumped_records;
1743 yaz_log(YLOG_DEBUG, " fetched record, len=%d, total=%d dumped=%d",
1744 this_length, total_length, dumped_records);
1745 if (a->preferredMessageSize > 0 &&
1746 this_length + total_length > a->preferredMessageSize)
1748 /* record is small enough, really */
1749 if (this_length <= a->preferredMessageSize && recno > start)
1751 yaz_log(log_requestdetail, " Dropped last normal-sized record");
1752 *pres = Z_PresentStatus_partial_2;
1755 /* record can only be fetched by itself */
1756 if (this_length < a->maximumRecordSize)
1758 yaz_log(log_requestdetail, " Record > prefmsgsz");
1761 yaz_log(YLOG_DEBUG, " Dropped it");
1762 reclist->records[reclist->num_records] =
1763 surrogatediagrec(a, freq.basename, 16, 0);
1764 reclist->num_records++;
1765 *next = freq.last_in_set ? 0 : recno + 1;
1766 dumped_records += this_length;
1770 else /* too big entirely */
1772 yaz_log(log_requestdetail, "Record > maxrcdsz this=%d max=%d",
1773 this_length, a->maximumRecordSize);
1774 reclist->records[reclist->num_records] =
1775 surrogatediagrec(a, freq.basename, 17, 0);
1776 reclist->num_records++;
1777 *next = freq.last_in_set ? 0 : recno + 1;
1778 dumped_records += this_length;
1783 if (!(thisrec = (Z_NamePlusRecord *)
1784 odr_malloc(a->encode, sizeof(*thisrec))))
1786 if (!(thisrec->databaseName = (char *)odr_malloc(a->encode,
1787 strlen(freq.basename) + 1)))
1789 strcpy(thisrec->databaseName, freq.basename);
1790 thisrec->which = Z_NamePlusRecord_databaseRecord;
1792 if (freq.output_format_raw)
1794 struct oident *ident = oid_getentbyoid(freq.output_format_raw);
1795 freq.output_format = ident->value;
1797 thisrec->u.databaseRecord = z_ext_record(a->encode, freq.output_format,
1798 freq.record, freq.len);
1799 if (!thisrec->u.databaseRecord)
1801 reclist->records[reclist->num_records] = thisrec;
1802 reclist->num_records++;
1803 *next = freq.last_in_set ? 0 : recno + 1;
1805 *num = reclist->num_records;
1809 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
1812 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
1813 bend_search_rr *bsrr =
1814 (bend_search_rr *)nmem_malloc (reqb->request_mem, sizeof(*bsrr));
1816 yaz_log(log_requestdetail, "Got SearchRequest.");
1818 bsrr->request = reqb;
1819 bsrr->association = assoc;
1820 bsrr->referenceId = req->referenceId;
1821 save_referenceId (reqb, bsrr->referenceId);
1823 yaz_log (log_requestdetail, "ResultSet '%s'", req->resultSetName);
1824 if (req->databaseNames)
1827 for (i = 0; i < req->num_databaseNames; i++)
1828 yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
1831 yaz_log_zquery_level(log_requestdetail,req->query);
1833 if (assoc->init->bend_search)
1835 bsrr->setname = req->resultSetName;
1836 bsrr->replace_set = *req->replaceIndicator;
1837 bsrr->num_bases = req->num_databaseNames;
1838 bsrr->basenames = req->databaseNames;
1839 bsrr->query = req->query;
1840 bsrr->stream = assoc->encode;
1841 nmem_transfer(bsrr->stream->mem, reqb->request_mem);
1842 bsrr->decode = assoc->decode;
1843 bsrr->print = assoc->print;
1846 bsrr->errstring = NULL;
1847 bsrr->search_info = NULL;
1848 (assoc->init->bend_search)(assoc->backend, bsrr);
1849 if (!bsrr->request) /* backend not ready with the search response */
1850 return 0; /* should not be used any more */
1854 /* FIXME - make a diagnostic for it */
1855 yaz_log(YLOG_WARN,"Search not supported ?!?!");
1857 return response_searchRequest(assoc, reqb, bsrr, fd);
1860 int bend_searchresponse(void *handle, bend_search_rr *bsrr) {return 0;}
1863 * Prepare a searchresponse based on the backend results. We probably want
1864 * to look at making the fetching of records nonblocking as well, but
1865 * so far, we'll keep things simple.
1866 * If bsrt is null, that means we're called in response to a communications
1867 * event, and we'll have to get the response for ourselves.
1869 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
1870 bend_search_rr *bsrt, int *fd)
1872 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
1873 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1874 Z_SearchResponse *resp = (Z_SearchResponse *)
1875 odr_malloc (assoc->encode, sizeof(*resp));
1876 int *nulint = odr_intdup (assoc->encode, 0);
1877 bool_t *sr = odr_intdup(assoc->encode, 1);
1878 int *next = odr_intdup(assoc->encode, 0);
1879 int *none = odr_intdup(assoc->encode, Z_SearchResponse_none);
1882 apdu->which = Z_APDU_searchResponse;
1883 apdu->u.searchResponse = resp;
1884 resp->referenceId = req->referenceId;
1885 resp->additionalSearchInfo = 0;
1886 resp->otherInfo = 0;
1888 if (!bsrt && !bend_searchresponse(assoc->backend, bsrt))
1890 yaz_log(YLOG_FATAL, "Bad result from backend");
1893 else if (bsrt->errcode)
1895 resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
1896 resp->resultCount = nulint;
1897 resp->numberOfRecordsReturned = nulint;
1898 resp->nextResultSetPosition = nulint;
1899 resp->searchStatus = nulint;
1900 resp->resultSetStatus = none;
1901 resp->presentStatus = 0;
1905 int *toget = odr_intdup(assoc->encode, 0);
1906 int *presst = odr_intdup(assoc->encode, 0);
1907 Z_RecordComposition comp, *compp = 0;
1909 yaz_log (log_requestdetail, "resultCount: %d", bsrt->hits);
1912 resp->resultCount = &bsrt->hits;
1914 comp.which = Z_RecordComp_simple;
1915 /* how many records does the user agent want, then? */
1916 if (bsrt->hits <= *req->smallSetUpperBound)
1918 *toget = bsrt->hits;
1919 if ((comp.u.simple = req->smallSetElementSetNames))
1922 else if (bsrt->hits < *req->largeSetLowerBound)
1924 *toget = *req->mediumSetPresentNumber;
1925 if (*toget > bsrt->hits)
1926 *toget = bsrt->hits;
1927 if ((comp.u.simple = req->mediumSetElementSetNames))
1933 if (*toget && !resp->records)
1938 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
1941 form = prefformat->value;
1942 resp->records = pack_records(assoc, req->resultSetName, 1,
1943 toget, compp, next, presst, form, req->referenceId,
1944 req->preferredRecordSyntax, NULL);
1947 resp->numberOfRecordsReturned = toget;
1948 returnedrecs = *toget;
1949 resp->nextResultSetPosition = next;
1950 resp->searchStatus = sr;
1951 resp->resultSetStatus = 0;
1952 resp->presentStatus = presst;
1956 if (*resp->resultCount)
1958 resp->numberOfRecordsReturned = nulint;
1959 resp->nextResultSetPosition = next;
1960 resp->searchStatus = sr;
1961 resp->resultSetStatus = 0;
1962 resp->presentStatus = 0;
1965 resp->additionalSearchInfo = bsrt->search_info;
1969 WRBUF wr = wrbuf_alloc();
1971 wrbuf_printf(wr, "ERROR %d", bsrt->errcode);
1973 wrbuf_printf(wr, "OK %d", bsrt->hits);
1974 wrbuf_printf(wr, " %s 1+%d ",
1975 req->resultSetName, returnedrecs);
1976 wrbuf_put_zquery(wr, req->query);
1978 yaz_log(log_request, "Search %s", wrbuf_buf(wr));
1985 * Maybe we got a little over-friendly when we designed bend_fetch to
1986 * get only one record at a time. Some backends can optimise multiple-record
1987 * fetches, and at any rate, there is some overhead involved in
1988 * all that selecting and hopping around. Problem is, of course, that the
1989 * frontend can't know ahead of time how many records it'll need to
1990 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
1991 * is downright lousy as a bulk data transfer protocol.
1993 * To start with, we'll do the fetching of records from the backend
1994 * in one operation: To save some trips in and out of the event-handler,
1995 * and to simplify the interface to pack_records. At any rate, asynch
1996 * operation is more fun in operations that have an unpredictable execution
1997 * speed - which is normally more true for search than for present.
1999 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
2002 Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
2006 Z_PresentResponse *resp;
2010 const char *errstring = 0;
2012 yaz_log(log_requestdetail, "Got PresentRequest.");
2014 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
2017 form = prefformat->value;
2018 resp = (Z_PresentResponse *)odr_malloc (assoc->encode, sizeof(*resp));
2020 resp->presentStatus = odr_intdup(assoc->encode, 0);
2021 if (assoc->init->bend_present)
2023 bend_present_rr *bprr = (bend_present_rr *)
2024 nmem_malloc (reqb->request_mem, sizeof(*bprr));
2025 bprr->setname = req->resultSetId;
2026 bprr->start = *req->resultSetStartPoint;
2027 bprr->number = *req->numberOfRecordsRequested;
2028 bprr->format = form;
2029 bprr->comp = req->recordComposition;
2030 bprr->referenceId = req->referenceId;
2031 bprr->stream = assoc->encode;
2032 bprr->print = assoc->print;
2033 bprr->request = reqb;
2034 bprr->association = assoc;
2036 bprr->errstring = NULL;
2037 (*assoc->init->bend_present)(assoc->backend, bprr);
2040 return 0; /* should not happen */
2043 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2044 *resp->presentStatus = Z_PresentStatus_failure;
2045 errcode = bprr->errcode;
2046 errstring = bprr->errstring;
2049 apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2050 next = odr_intdup(assoc->encode, 0);
2051 num = odr_intdup(assoc->encode, 0);
2053 apdu->which = Z_APDU_presentResponse;
2054 apdu->u.presentResponse = resp;
2055 resp->referenceId = req->referenceId;
2056 resp->otherInfo = 0;
2060 *num = *req->numberOfRecordsRequested;
2062 pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
2063 num, req->recordComposition, next,
2064 resp->presentStatus,
2065 form, req->referenceId, req->preferredRecordSyntax,
2070 WRBUF wr = wrbuf_alloc();
2071 wrbuf_printf(wr, "Present ");
2073 if (*resp->presentStatus == Z_PresentStatus_failure)
2074 wrbuf_printf(wr, "ERROR %d", errcode);
2075 else if (*resp->presentStatus == Z_PresentStatus_success)
2076 wrbuf_printf(wr, "OK -");
2078 wrbuf_printf(wr, "Partial %d", *resp->presentStatus);
2080 wrbuf_printf(wr, " %s %d+%d ",
2081 req->resultSetId, *req->resultSetStartPoint,
2082 *req->numberOfRecordsRequested);
2083 yaz_log(log_request, "%s", wrbuf_buf(wr) );
2088 resp->numberOfRecordsReturned = num;
2089 resp->nextResultSetPosition = next;
2095 * Scan was implemented rather in a hurry, and with support for only the basic
2096 * elements of the service in the backend API. Suggestions are welcome.
2098 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
2100 Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
2101 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2102 Z_ScanResponse *res = (Z_ScanResponse *)
2103 odr_malloc (assoc->encode, sizeof(*res));
2104 int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
2105 int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
2106 Z_ListEntries *ents = (Z_ListEntries *)
2107 odr_malloc (assoc->encode, sizeof(*ents));
2108 Z_DiagRecs *diagrecs_p = NULL;
2110 bend_scan_rr *bsrr = (bend_scan_rr *)
2111 odr_malloc (assoc->encode, sizeof(*bsrr));
2112 struct scan_entry *save_entries;
2114 yaz_log(log_requestdetail, "Got ScanRequest");
2116 apdu->which = Z_APDU_scanResponse;
2117 apdu->u.scanResponse = res;
2118 res->referenceId = req->referenceId;
2120 /* if step is absent, set it to 0 */
2121 res->stepSize = odr_intdup(assoc->encode, 0);
2123 *res->stepSize = *req->stepSize;
2125 res->scanStatus = scanStatus;
2126 res->numberOfEntriesReturned = numberOfEntriesReturned;
2127 res->positionOfTerm = 0;
2128 res->entries = ents;
2129 ents->num_entries = 0;
2130 ents->entries = NULL;
2131 ents->num_nonsurrogateDiagnostics = 0;
2132 ents->nonsurrogateDiagnostics = NULL;
2133 res->attributeSet = 0;
2136 if (req->databaseNames)
2139 for (i = 0; i < req->num_databaseNames; i++)
2140 yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
2142 yaz_log(log_requestdetail, "pos %d step %d entries %d",
2143 *req->preferredPositionInResponse, *res->stepSize,
2144 *req->numberOfTermsRequested);
2145 bsrr->num_bases = req->num_databaseNames;
2146 bsrr->basenames = req->databaseNames;
2147 bsrr->num_entries = *req->numberOfTermsRequested;
2148 bsrr->term = req->termListAndStartPoint;
2149 bsrr->referenceId = req->referenceId;
2150 bsrr->stream = assoc->encode;
2151 bsrr->print = assoc->print;
2152 bsrr->step_size = res->stepSize;
2154 /* For YAZ 2.0 and earlier it was the backend handler that
2155 initialized entries (member display_term did not exist)
2156 YAZ 2.0 and later sets 'entries' and initialize all members
2157 including 'display_term'. If YAZ 2.0 or later sees that
2158 entries was modified - we assume that it is an old handler and
2159 that 'display_term' is _not_ set.
2161 if (bsrr->num_entries > 0)
2164 bsrr->entries = odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
2166 for (i = 0; i<bsrr->num_entries; i++)
2168 bsrr->entries[i].term = 0;
2169 bsrr->entries[i].occurrences = 0;
2170 bsrr->entries[i].errcode = 0;
2171 bsrr->entries[i].errstring = 0;
2172 bsrr->entries[i].display_term = 0;
2175 save_entries = bsrr->entries; /* save it so we can compare later */
2177 if (req->attributeSet &&
2178 (attset = oid_getentbyoid(req->attributeSet)) &&
2179 (attset->oclass == CLASS_ATTSET || attset->oclass == CLASS_GENERAL))
2180 bsrr->attributeset = attset->value;
2182 bsrr->attributeset = VAL_NONE;
2183 log_scan_term_level (log_requestdetail, req->termListAndStartPoint,
2184 bsrr->attributeset);
2185 bsrr->term_position = req->preferredPositionInResponse ?
2186 *req->preferredPositionInResponse : 1;
2188 ((int (*)(void *, bend_scan_rr *))
2189 (*assoc->init->bend_scan))(assoc->backend, bsrr);
2192 diagrecs_p = zget_DiagRecs(assoc->encode,
2193 bsrr->errcode, bsrr->errstring);
2197 Z_Entry **tab = (Z_Entry **)
2198 odr_malloc (assoc->encode, sizeof(*tab) * bsrr->num_entries);
2200 if (bsrr->status == BEND_SCAN_PARTIAL)
2201 *scanStatus = Z_Scan_partial_5;
2203 *scanStatus = Z_Scan_success;
2204 ents->entries = tab;
2205 ents->num_entries = bsrr->num_entries;
2206 res->numberOfEntriesReturned = &ents->num_entries;
2207 res->positionOfTerm = &bsrr->term_position;
2208 for (i = 0; i < bsrr->num_entries; i++)
2214 tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
2215 if (bsrr->entries[i].occurrences >= 0)
2217 e->which = Z_Entry_termInfo;
2218 e->u.termInfo = t = (Z_TermInfo *)
2219 odr_malloc(assoc->encode, sizeof(*t));
2220 t->suggestedAttributes = 0;
2222 if (save_entries == bsrr->entries &&
2223 bsrr->entries[i].display_term)
2225 /* the entries was _not_ set by the handler. So it's
2226 safe to test for new member display_term. It is
2229 t->displayTerm = odr_strdup(assoc->encode,
2230 bsrr->entries[i].display_term);
2232 t->alternativeTerm = 0;
2233 t->byAttributes = 0;
2234 t->otherTermInfo = 0;
2235 t->globalOccurrences = &bsrr->entries[i].occurrences;
2236 t->term = (Z_Term *)
2237 odr_malloc(assoc->encode, sizeof(*t->term));
2238 t->term->which = Z_Term_general;
2239 t->term->u.general = o =
2240 (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
2241 o->buf = (unsigned char *)
2242 odr_malloc(assoc->encode, o->len = o->size =
2243 strlen(bsrr->entries[i].term));
2244 memcpy(o->buf, bsrr->entries[i].term, o->len);
2245 yaz_log(YLOG_DEBUG, " term #%d: '%s' (%d)", i,
2246 bsrr->entries[i].term, bsrr->entries[i].occurrences);
2250 Z_DiagRecs *drecs = zget_DiagRecs(assoc->encode,
2251 bsrr->entries[i].errcode,
2252 bsrr->entries[i].errstring);
2253 assert (drecs->num_diagRecs == 1);
2254 e->which = Z_Entry_surrogateDiagnostic;
2255 assert (drecs->diagRecs[0]);
2256 e->u.surrogateDiagnostic = drecs->diagRecs[0];
2262 ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
2263 ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
2267 WRBUF wr = wrbuf_alloc();
2268 if (*res->scanStatus == Z_Scan_success)
2269 wrbuf_printf(wr, "OK ");
2271 wr_diag(wr, bsrr->errcode, bsrr->errstring);
2273 wrbuf_printf(wr, "%d+%d %d ",
2274 *req->preferredPositionInResponse,
2275 *req->numberOfTermsRequested,
2276 (res->stepSize ? *res->stepSize : 0));
2277 wrbuf_scan_term(wr, req->termListAndStartPoint,
2278 bsrr->attributeset);
2280 yaz_log(log_request, "Scan %s", wrbuf_buf(wr) );
2286 static Z_APDU *process_sortRequest(association *assoc, request *reqb,
2290 Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
2291 Z_SortResponse *res = (Z_SortResponse *)
2292 odr_malloc (assoc->encode, sizeof(*res));
2293 bend_sort_rr *bsrr = (bend_sort_rr *)
2294 odr_malloc (assoc->encode, sizeof(*bsrr));
2296 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2298 yaz_log(log_requestdetail, "Got SortRequest.");
2300 bsrr->num_input_setnames = req->num_inputResultSetNames;
2301 for (i=0;i<req->num_inputResultSetNames;i++)
2302 yaz_log(log_requestdetail, "Input resultset: '%s'",
2303 req->inputResultSetNames[i]);
2304 bsrr->input_setnames = req->inputResultSetNames;
2305 bsrr->referenceId = req->referenceId;
2306 bsrr->output_setname = req->sortedResultSetName;
2307 yaz_log(log_requestdetail, "Output resultset: '%s'",
2308 req->sortedResultSetName);
2309 bsrr->sort_sequence = req->sortSequence;
2310 /*FIXME - dump those sequences too */
2311 bsrr->stream = assoc->encode;
2312 bsrr->print = assoc->print;
2314 bsrr->sort_status = Z_SortResponse_failure;
2316 bsrr->errstring = 0;
2318 (*assoc->init->bend_sort)(assoc->backend, bsrr);
2320 res->referenceId = bsrr->referenceId;
2321 res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
2322 res->resultSetStatus = 0;
2325 Z_DiagRecs *dr = zget_DiagRecs(assoc->encode,
2326 bsrr->errcode, bsrr->errstring);
2327 res->diagnostics = dr->diagRecs;
2328 res->num_diagnostics = dr->num_diagRecs;
2332 res->num_diagnostics = 0;
2333 res->diagnostics = 0;
2335 res->resultCount = 0;
2338 apdu->which = Z_APDU_sortResponse;
2339 apdu->u.sortResponse = res;
2342 WRBUF wr = wrbuf_alloc();
2343 wrbuf_printf(wr, "Sort ");
2345 wrbuf_printf(wr, " ERROR %d", bsrr->errcode);
2347 wrbuf_printf(wr, "OK -");
2348 wrbuf_printf(wr, " (");
2349 for (i = 0; i<req->num_inputResultSetNames; i++)
2352 wrbuf_printf(wr, ",");
2353 wrbuf_printf(wr, req->inputResultSetNames[i]);
2355 wrbuf_printf(wr, ")->%s ",req->sortedResultSetName);
2357 yaz_log(log_request, "%s", wrbuf_buf(wr) );
2363 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
2367 Z_DeleteResultSetRequest *req =
2368 reqb->apdu_request->u.deleteResultSetRequest;
2369 Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
2370 odr_malloc (assoc->encode, sizeof(*res));
2371 bend_delete_rr *bdrr = (bend_delete_rr *)
2372 odr_malloc (assoc->encode, sizeof(*bdrr));
2373 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2375 yaz_log(log_requestdetail, "Got DeleteRequest.");
2377 bdrr->num_setnames = req->num_resultSetList;
2378 bdrr->setnames = req->resultSetList;
2379 for (i = 0; i<req->num_resultSetList; i++)
2380 yaz_log(log_requestdetail, "resultset: '%s'",
2381 req->resultSetList[i]);
2382 bdrr->stream = assoc->encode;
2383 bdrr->print = assoc->print;
2384 bdrr->function = *req->deleteFunction;
2385 bdrr->referenceId = req->referenceId;
2387 if (bdrr->num_setnames > 0)
2389 bdrr->statuses = (int*)
2390 odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
2391 bdrr->num_setnames);
2392 for (i = 0; i < bdrr->num_setnames; i++)
2393 bdrr->statuses[i] = 0;
2395 (*assoc->init->bend_delete)(assoc->backend, bdrr);
2397 res->referenceId = req->referenceId;
2399 res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
2401 res->deleteListStatuses = 0;
2402 if (bdrr->num_setnames > 0)
2405 res->deleteListStatuses = (Z_ListStatuses *)
2406 odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
2407 res->deleteListStatuses->num = bdrr->num_setnames;
2408 res->deleteListStatuses->elements =
2410 odr_malloc (assoc->encode,
2411 sizeof(*res->deleteListStatuses->elements) *
2412 bdrr->num_setnames);
2413 for (i = 0; i<bdrr->num_setnames; i++)
2415 res->deleteListStatuses->elements[i] =
2417 odr_malloc (assoc->encode,
2418 sizeof(**res->deleteListStatuses->elements));
2419 res->deleteListStatuses->elements[i]->status = bdrr->statuses+i;
2420 res->deleteListStatuses->elements[i]->id =
2421 odr_strdup (assoc->encode, bdrr->setnames[i]);
2424 res->numberNotDeleted = 0;
2425 res->bulkStatuses = 0;
2426 res->deleteMessage = 0;
2429 apdu->which = Z_APDU_deleteResultSetResponse;
2430 apdu->u.deleteResultSetResponse = res;
2433 WRBUF wr = wrbuf_alloc();
2434 wrbuf_printf(wr, "Delete ");
2435 if (bdrr->delete_status)
2436 wrbuf_printf(wr, "ERROR %d", bdrr->delete_status);
2438 wrbuf_printf(wr, "OK -");
2439 for (i = 0; i<req->num_resultSetList; i++)
2440 wrbuf_printf(wr, " %s ", req->resultSetList[i]);
2441 yaz_log(log_request, "%s", wrbuf_buf(wr) );
2447 static void process_close(association *assoc, request *reqb)
2449 Z_Close *req = reqb->apdu_request->u.close;
2450 static char *reasons[] =
2457 "securityViolation",
2464 yaz_log(log_requestdetail, "Got Close, reason %s, message %s",
2465 reasons[*req->closeReason], req->diagnosticInformation ?
2466 req->diagnosticInformation : "NULL");
2467 if (assoc->version < 3) /* to make do_force respond with close */
2469 do_close_req(assoc, Z_Close_finished,
2470 "Association terminated by client", reqb);
2471 yaz_log(log_request,"Close OK");
2474 void save_referenceId (request *reqb, Z_ReferenceId *refid)
2478 reqb->len_refid = refid->len;
2479 reqb->refid = (char *)nmem_malloc (reqb->request_mem, refid->len);
2480 memcpy (reqb->refid, refid->buf, refid->len);
2484 reqb->len_refid = 0;
2489 void bend_request_send (bend_association a, bend_request req, Z_APDU *res)
2491 process_z_response (a, req, res);
2494 bend_request bend_request_mk (bend_association a)
2496 request *nreq = request_get (&a->outgoing);
2497 nreq->request_mem = nmem_create ();
2501 Z_ReferenceId *bend_request_getid (ODR odr, bend_request req)
2506 id = (Odr_oct *)odr_malloc (odr, sizeof(*odr));
2507 id->buf = (unsigned char *)odr_malloc (odr, req->len_refid);
2508 id->len = id->size = req->len_refid;
2509 memcpy (id->buf, req->refid, req->len_refid);
2513 void bend_request_destroy (bend_request *req)
2515 nmem_destroy((*req)->request_mem);
2516 request_release(*req);
2520 int bend_backend_respond (bend_association a, bend_request req)
2524 r = process_z_request (a, req, &msg);
2526 yaz_log (YLOG_WARN, "%s", msg);
2530 void bend_request_setdata(bend_request r, void *p)
2535 void *bend_request_getdata(bend_request r)
2537 return r->clientData;
2540 static Z_APDU *process_segmentRequest (association *assoc, request *reqb)
2542 bend_segment_rr req;
2544 req.segment = reqb->apdu_request->u.segmentRequest;
2545 req.stream = assoc->encode;
2546 req.decode = assoc->decode;
2547 req.print = assoc->print;
2548 req.association = assoc;
2550 (*assoc->init->bend_segment)(assoc->backend, &req);
2555 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd)
2557 bend_esrequest_rr esrequest;
2559 Z_ExtendedServicesRequest *req =
2560 reqb->apdu_request->u.extendedServicesRequest;
2561 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
2563 Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
2565 yaz_log(log_requestdetail,"Got EsRequest");
2567 esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
2568 esrequest.stream = assoc->encode;
2569 esrequest.decode = assoc->decode;
2570 esrequest.print = assoc->print;
2571 esrequest.errcode = 0;
2572 esrequest.errstring = NULL;
2573 esrequest.request = reqb;
2574 esrequest.association = assoc;
2575 esrequest.taskPackage = 0;
2576 esrequest.referenceId = req->referenceId;
2578 (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
2580 /* If the response is being delayed, return NULL */
2581 if (esrequest.request == NULL)
2584 resp->referenceId = req->referenceId;
2586 if (esrequest.errcode == -1)
2588 /* Backend service indicates request will be processed */
2589 yaz_log(log_request,"EsRequest OK: Accepted !");
2590 *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
2592 else if (esrequest.errcode == 0)
2594 /* Backend service indicates request will be processed */
2595 yaz_log(log_request,"EsRequest OK: Done !");
2596 *resp->operationStatus = Z_ExtendedServicesResponse_done;
2600 Z_DiagRecs *diagRecs =
2601 zget_DiagRecs(assoc->encode, esrequest.errcode,
2602 esrequest.errstring);
2603 /* Backend indicates error, request will not be processed */
2604 yaz_log(YLOG_DEBUG,"Request could not be processed...failure !");
2605 *resp->operationStatus = Z_ExtendedServicesResponse_failure;
2606 resp->num_diagnostics = diagRecs->num_diagRecs;
2607 resp->diagnostics = diagRecs->diagRecs;
2610 WRBUF wr=wrbuf_alloc();
2611 wrbuf_diags(wr, resp->num_diagnostics, resp->diagnostics);
2612 yaz_log(log_request, "EsRequest %s", wrbuf_buf(wr) );
2617 /* Do something with the members of bend_extendedservice */
2618 if (esrequest.taskPackage)
2619 resp->taskPackage = z_ext_record (assoc->encode, VAL_EXTENDED,
2620 (const char *) esrequest.taskPackage,
2622 yaz_log(YLOG_DEBUG,"Send the result apdu");