2 * Copyright (C) 1995-2005, Index Data ApS
3 * See the file LICENSE for details.
5 * $Id: seshigh.c,v 1.96 2006-08-24 13:25:45 adam Exp $
9 * \brief Implements GFS session logic.
11 * Frontend server logic.
13 * This code receives incoming APDUs, and handles client requests by means
16 * Some of the code is getting quite involved, compared to simpler servers -
17 * primarily because it is asynchronous both in the communication with
18 * the user and the backend. We think the complexity will pay off in
19 * the form of greater flexibility when more asynchronous facilities
22 * Memory management has become somewhat involved. In the simple case, where
23 * only one PDU is pending at a time, it will simply reuse the same memory,
24 * once it has found its working size. When we enable multiple concurrent
25 * operations, perhaps even with multiple parallel calls to the backend, it
26 * will maintain a pool of buffers for encoding and decoding, trying to
27 * minimize memory allocation/deallocation during normal operation.
37 #include <sys/types.h>
45 #define S_ISREG(x) (x & _S_IFREG)
54 #include <libxml/parser.h>
55 #include <libxml/tree.h>
58 #include <yaz/yconfig.h>
59 #include <yaz/xmalloc.h>
60 #include <yaz/comstack.h>
64 #include <yaz/proto.h>
67 #include <yaz/logrpn.h>
68 #include <yaz/querytowrbuf.h>
69 #include <yaz/statserv.h>
70 #include <yaz/diagbib1.h>
71 #include <yaz/charneg.h>
72 #include <yaz/otherinfo.h>
73 #include <yaz/yaz-util.h>
74 #include <yaz/pquery.h>
77 #include <yaz/backend.h>
79 static void process_gdu_request(association *assoc, request *req);
80 static int process_z_request(association *assoc, request *req, char **msg);
81 void backend_response(IOCHAN i, int event);
82 static int process_gdu_response(association *assoc, request *req, Z_GDU *res);
83 static int process_z_response(association *assoc, request *req, Z_APDU *res);
84 static Z_APDU *process_initRequest(association *assoc, request *reqb);
85 static Z_External *init_diagnostics(ODR odr, int errcode,
86 const char *errstring);
87 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
89 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
90 bend_search_rr *bsrr, int *fd);
91 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
93 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
94 static Z_APDU *process_sortRequest(association *assoc, request *reqb, int *fd);
95 static void process_close(association *assoc, request *reqb);
96 void save_referenceId (request *reqb, Z_ReferenceId *refid);
97 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
99 static Z_APDU *process_segmentRequest (association *assoc, request *reqb);
101 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd);
103 /* dynamic logging levels */
104 static int logbits_set = 0;
105 static int log_session = 0; /* one-line logs for session */
106 static int log_sessiondetail = 0; /* more detailed stuff */
107 static int log_request = 0; /* one-line logs for requests */
108 static int log_requestdetail = 0; /* more detailed stuff */
110 /** get_logbits sets global loglevel bits */
111 static void get_logbits()
112 { /* needs to be called after parsing cmd-line args that can set loglevels!*/
116 log_session = yaz_log_module_level("session");
117 log_sessiondetail = yaz_log_module_level("sessiondetail");
118 log_request = yaz_log_module_level("request");
119 log_requestdetail = yaz_log_module_level("requestdetail");
125 static void wr_diag(WRBUF w, int error, const char *addinfo)
127 wrbuf_printf(w, "ERROR %d+", error);
128 wrbuf_puts_replace_char(w, diagbib1_str(error), ' ', '_');
131 wrbuf_puts_replace_char(w, addinfo, ' ', '_');
139 * Create and initialize a new association-handle.
140 * channel : iochannel for the current line.
141 * link : communications channel.
142 * Returns: 0 or a new association handle.
144 association *create_association(IOCHAN channel, COMSTACK link,
145 const char *apdufile)
151 if (!(anew = (association *)xmalloc(sizeof(*anew))))
155 anew->last_control = 0;
156 anew->client_chan = channel;
157 anew->client_link = link;
158 anew->cs_get_mask = 0;
159 anew->cs_put_mask = 0;
160 anew->cs_accept_mask = 0;
161 if (!(anew->decode = odr_createmem(ODR_DECODE)) ||
162 !(anew->encode = odr_createmem(ODR_ENCODE)))
164 if (apdufile && *apdufile)
168 if (!(anew->print = odr_createmem(ODR_PRINT)))
170 if (*apdufile == '@')
172 odr_setprint(anew->print, yaz_log_file());
174 else if (*apdufile != '-')
177 sprintf(filename, "%.200s.%ld", apdufile, (long)getpid());
178 if (!(f = fopen(filename, "w")))
180 yaz_log(YLOG_WARN|YLOG_ERRNO, "%s", filename);
183 setvbuf(f, 0, _IONBF, 0);
184 odr_setprint(anew->print, f);
189 anew->input_buffer = 0;
190 anew->input_buffer_len = 0;
192 anew->state = ASSOC_NEW;
193 request_initq(&anew->incoming);
194 request_initq(&anew->outgoing);
195 anew->proto = cs_getproto(link);
201 * Free association and release resources.
203 void destroy_association(association *h)
205 statserv_options_block *cb = statserv_getcontrol();
209 odr_destroy(h->decode);
210 odr_destroy(h->encode);
212 odr_destroy(h->print);
214 xfree(h->input_buffer);
216 (*cb->bend_close)(h->backend);
217 while ((req = request_deq(&h->incoming)))
218 request_release(req);
219 while ((req = request_deq(&h->outgoing)))
220 request_release(req);
221 request_delq(&h->incoming);
222 request_delq(&h->outgoing);
224 xmalloc_trav("session closed");
225 if (cb && cb->one_shot)
231 static void do_close_req(association *a, int reason, char *message,
235 Z_Close *cls = zget_Close(a->encode);
237 /* Purge request queue */
238 while (request_deq(&a->incoming));
239 while (request_deq(&a->outgoing));
242 yaz_log(log_requestdetail, "Sending Close PDU, reason=%d, message=%s",
243 reason, message ? message : "none");
244 apdu.which = Z_APDU_close;
246 *cls->closeReason = reason;
247 cls->diagnosticInformation = message;
248 process_z_response(a, req, &apdu);
249 iochan_settimeout(a->client_chan, 20);
253 request_release(req);
254 yaz_log(log_requestdetail, "v2 client. No Close PDU");
255 iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
258 a->state = ASSOC_DEAD;
261 static void do_close(association *a, int reason, char *message)
263 request *req = request_get(&a->outgoing);
264 do_close_req (a, reason, message, req);
268 * This is where PDUs from the client are read and the further
269 * processing is initiated. Flow of control moves down through the
270 * various process_* functions below, until the encoded result comes back up
271 * to the output handler in here.
273 * h : the I/O channel that has an outstanding event.
274 * event : the current outstanding event.
276 void ir_session(IOCHAN h, int event)
279 association *assoc = (association *)iochan_getdata(h);
280 COMSTACK conn = assoc->client_link;
283 assert(h && conn && assoc);
284 if (event == EVENT_TIMEOUT)
286 if (assoc->state != ASSOC_UP)
288 yaz_log(YLOG_DEBUG, "Final timeout - closing connection.");
289 /* do we need to lod this at all */
291 destroy_association(assoc);
296 yaz_log(log_sessiondetail,
297 "Session idle too long. Sending close.");
298 do_close(assoc, Z_Close_lackOfActivity, 0);
302 if (event & assoc->cs_accept_mask)
304 if (!cs_accept (conn))
306 yaz_log (YLOG_WARN, "accept failed");
307 destroy_association(assoc);
310 iochan_clearflag (h, EVENT_OUTPUT);
311 if (conn->io_pending)
312 { /* cs_accept didn't complete */
313 assoc->cs_accept_mask =
314 ((conn->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
315 ((conn->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
317 iochan_setflag (h, assoc->cs_accept_mask);
320 { /* cs_accept completed. Prepare for reading (cs_get) */
321 assoc->cs_accept_mask = 0;
322 assoc->cs_get_mask = EVENT_INPUT;
323 iochan_setflag (h, assoc->cs_get_mask);
327 if ((event & assoc->cs_get_mask) || (event & EVENT_WORK)) /* input */
329 if ((assoc->cs_put_mask & EVENT_INPUT) == 0 && (event & assoc->cs_get_mask))
331 yaz_log(YLOG_DEBUG, "ir_session (input)");
332 /* We aren't speaking to this fellow */
333 if (assoc->state == ASSOC_DEAD)
335 yaz_log(log_sessiondetail, "Connection closed - end of session");
337 destroy_association(assoc);
341 assoc->cs_get_mask = EVENT_INPUT;
342 if ((res = cs_get(conn, &assoc->input_buffer,
343 &assoc->input_buffer_len)) == 0)
345 yaz_log(log_sessiondetail, "Connection closed by client");
347 destroy_association(assoc);
353 yaz_log(log_session, "Connection error: %s",
354 cs_errmsg(cs_errno(conn)));
355 req = request_get(&assoc->incoming); /* get a new request */
356 do_close_req(assoc, Z_Close_protocolError,
357 "Incoming package too large", req);
360 else if (res == 1) /* incomplete read - wait for more */
362 if (conn->io_pending & CS_WANT_WRITE)
363 assoc->cs_get_mask |= EVENT_OUTPUT;
364 iochan_setflag(h, assoc->cs_get_mask);
367 if (cs_more(conn)) /* more stuff - call us again later, please */
368 iochan_setevent(h, EVENT_INPUT);
370 /* we got a complete PDU. Let's decode it */
371 yaz_log(YLOG_DEBUG, "Got PDU, %d bytes: lead=%02X %02X %02X", res,
372 assoc->input_buffer[0] & 0xff,
373 assoc->input_buffer[1] & 0xff,
374 assoc->input_buffer[2] & 0xff);
375 req = request_get(&assoc->incoming); /* get a new request */
376 odr_reset(assoc->decode);
377 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
378 if (!z_GDU(assoc->decode, &req->gdu_request, 0, 0))
380 yaz_log(YLOG_WARN, "ODR error on incoming PDU: %s [element %s] "
382 odr_errmsg(odr_geterror(assoc->decode)),
383 odr_getelement(assoc->decode),
384 (long) odr_offset(assoc->decode));
385 if (assoc->decode->error != OHTTP)
387 yaz_log(YLOG_WARN, "PDU dump:");
388 odr_dumpBER(yaz_log_file(), assoc->input_buffer, res);
389 request_release(req);
390 do_close(assoc, Z_Close_protocolError, "Malformed package");
394 Z_GDU *p = z_get_HTTP_Response(assoc->encode, 400);
395 assoc->state = ASSOC_DEAD;
396 process_gdu_response(assoc, req, p);
400 req->request_mem = odr_extract_mem(assoc->decode);
403 if (!z_GDU(assoc->print, &req->gdu_request, 0, 0))
404 yaz_log(YLOG_WARN, "ODR print error: %s",
405 odr_errmsg(odr_geterror(assoc->print)));
406 odr_reset(assoc->print);
408 request_enq(&assoc->incoming, req);
411 /* can we do something yet? */
412 req = request_head(&assoc->incoming);
413 if (req->state == REQUEST_IDLE)
415 request_deq(&assoc->incoming);
416 process_gdu_request(assoc, req);
419 if (event & assoc->cs_put_mask)
421 request *req = request_head(&assoc->outgoing);
423 assoc->cs_put_mask = 0;
424 yaz_log(YLOG_DEBUG, "ir_session (output)");
425 req->state = REQUEST_PENDING;
426 switch (res = cs_put(conn, req->response, req->len_response))
429 yaz_log(log_sessiondetail, "Connection closed by client");
431 destroy_association(assoc);
434 case 0: /* all sent - release the request structure */
435 yaz_log(YLOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
437 yaz_log(YLOG_DEBUG, "HTTP out:\n%.*s", req->len_response,
440 nmem_destroy(req->request_mem);
441 request_deq(&assoc->outgoing);
442 request_release(req);
443 if (!request_head(&assoc->outgoing))
444 { /* restore mask for cs_get operation ... */
445 iochan_clearflag(h, EVENT_OUTPUT|EVENT_INPUT);
446 iochan_setflag(h, assoc->cs_get_mask);
447 if (assoc->state == ASSOC_DEAD)
448 iochan_setevent(assoc->client_chan, EVENT_TIMEOUT);
452 assoc->cs_put_mask = EVENT_OUTPUT;
456 if (conn->io_pending & CS_WANT_WRITE)
457 assoc->cs_put_mask |= EVENT_OUTPUT;
458 if (conn->io_pending & CS_WANT_READ)
459 assoc->cs_put_mask |= EVENT_INPUT;
460 iochan_setflag(h, assoc->cs_put_mask);
463 if (event & EVENT_EXCEPT)
465 yaz_log(YLOG_WARN, "ir_session (exception)");
467 destroy_association(assoc);
472 static int process_z_request(association *assoc, request *req, char **msg);
475 static void assoc_init_reset(association *assoc)
478 assoc->init = (bend_initrequest *) xmalloc (sizeof(*assoc->init));
480 assoc->init->stream = assoc->encode;
481 assoc->init->print = assoc->print;
482 assoc->init->auth = 0;
483 assoc->init->referenceId = 0;
484 assoc->init->implementation_version = 0;
485 assoc->init->implementation_id = 0;
486 assoc->init->implementation_name = 0;
487 assoc->init->bend_sort = NULL;
488 assoc->init->bend_search = NULL;
489 assoc->init->bend_present = NULL;
490 assoc->init->bend_esrequest = NULL;
491 assoc->init->bend_delete = NULL;
492 assoc->init->bend_scan = NULL;
493 assoc->init->bend_segment = NULL;
494 assoc->init->bend_fetch = NULL;
495 assoc->init->bend_explain = NULL;
496 assoc->init->bend_srw_scan = NULL;
497 assoc->init->bend_srw_update = NULL;
499 assoc->init->charneg_request = NULL;
500 assoc->init->charneg_response = NULL;
502 assoc->init->decode = assoc->decode;
503 assoc->init->peer_name =
504 odr_strdup (assoc->encode, cs_addrstr(assoc->client_link));
506 yaz_log(log_requestdetail, "peer %s", assoc->init->peer_name);
509 static int srw_bend_init(association *assoc, Z_SRW_diagnostic **d, int *num, Z_SRW_PDU *sr)
511 statserv_options_block *cb = statserv_getcontrol();
514 const char *encoding = "UTF-8";
516 bend_initresult *binitres;
518 yaz_log(log_requestdetail, "srw_bend_init config=%s", cb->configname);
519 assoc_init_reset(assoc);
521 assoc->maximumRecordSize = 3000000;
522 assoc->preferredMessageSize = 3000000;
526 Z_IdAuthentication *auth = odr_malloc(assoc->decode, sizeof(*auth));
529 len = strlen(sr->username) + 1;
531 len += strlen(sr->password) + 2;
532 auth->which = Z_IdAuthentication_open;
533 auth->u.open = odr_malloc(assoc->decode, len);
534 strcpy(auth->u.open, sr->username);
535 if (sr->password && *sr->password)
537 strcat(auth->u.open, "/");
538 strcat(auth->u.open, sr->password);
540 assoc->init->auth = auth;
544 ce = yaz_set_proposal_charneg(assoc->decode, &encoding, 1, 0, 0, 1);
545 assoc->init->charneg_request = ce->u.charNeg3;
548 if (!(binitres = (*cb->bend_init)(assoc->init)))
550 assoc->state = ASSOC_DEAD;
551 yaz_add_srw_diagnostic(assoc->encode, d, num,
552 YAZ_SRW_AUTHENTICATION_ERROR, 0);
555 assoc->backend = binitres->handle;
556 assoc->init->auth = 0;
557 if (binitres->errcode)
559 int srw_code = yaz_diag_bib1_to_srw(binitres->errcode);
560 assoc->state = ASSOC_DEAD;
561 yaz_add_srw_diagnostic(assoc->encode, d, num, srw_code,
562 binitres->errstring);
570 static const char *get_esn(Z_RecordComposition *comp)
572 if (comp && comp->which == Z_RecordComp_complex)
574 if (comp->u.complex->generic
575 && comp->u.complex->generic->elementSpec
576 && (comp->u.complex->generic->elementSpec->which ==
577 Z_ElementSpec_elementSetName))
578 return comp->u.complex->generic->elementSpec->u.elementSetName;
580 else if (comp && comp->which == Z_RecordComp_simple &&
581 comp->u.simple->which == Z_ElementSetNames_generic)
582 return comp->u.simple->u.generic;
586 static void set_esn(Z_RecordComposition **comp_p, const char *esn, NMEM nmem)
588 Z_RecordComposition *comp = nmem_malloc(nmem, sizeof(*comp));
590 comp->which = Z_RecordComp_simple;
591 comp->u.simple = nmem_malloc(nmem, sizeof(*comp->u.simple));
592 comp->u.simple->which = Z_ElementSetNames_generic;
593 comp->u.simple->u.generic = nmem_strdup(nmem, esn);
597 static int retrieve_fetch(association *assoc, bend_fetch_rr *rr)
600 yaz_record_conv_t rc = 0;
601 const char *match_schema = 0;
602 int *match_syntax = 0;
607 const char *input_schema = get_esn(rr->comp);
608 Odr_oid *input_syntax_raw = rr->request_format_raw;
610 const char *backend_schema = 0;
611 Odr_oid *backend_syntax = 0;
613 r = yaz_retrieval_request(assoc->server->retrieval,
621 if (r == -1) /* error ? */
623 const char *details = yaz_retrieval_get_error(
624 assoc->server->retrieval);
626 rr->errcode = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
628 rr->errstring = odr_strdup(rr->stream, details);
631 else if (r == 1 || r == 3)
633 const char *details = input_schema;
634 rr->errcode = YAZ_BIB1_ELEMENT_SET_NAMES_UNSUPP;
636 rr->errstring = odr_strdup(rr->stream, details);
641 rr->errcode = YAZ_BIB1_RECORD_SYNTAX_UNSUPP;
642 if (input_syntax_raw)
644 char oidbuf[OID_STR_MAX];
645 oid_to_dotstring(input_syntax_raw, oidbuf);
646 rr->errstring = odr_strdup(rr->stream, oidbuf);
652 set_esn(&rr->comp, backend_schema, rr->stream->mem);
656 oident *oident_syntax = oid_getentbyoid(backend_syntax);
658 rr->request_format_raw = backend_syntax;
661 rr->request_format = oident_syntax->value;
663 rr->request_format = VAL_NONE;
666 (*assoc->init->bend_fetch)(assoc->backend, rr);
667 if (rc && rr->record && rr->errcode == 0 && rr->len > 0)
668 { /* post conversion must take place .. */
669 WRBUF output_record = wrbuf_alloc();
670 int r = yaz_record_conv_record(rc, rr->record, rr->len, output_record);
673 const char *details = yaz_record_conv_get_error(rc);
674 rr->errcode = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
676 rr->errstring = odr_strdup(rr->stream, details);
680 rr->len = wrbuf_len(output_record);
681 rr->record = odr_malloc(rr->stream, rr->len);
682 memcpy(rr->record, wrbuf_buf(output_record), rr->len);
684 wrbuf_free(output_record, 1);
688 struct oident *oi = oid_getentbyoid(match_syntax);
689 rr->output_format = oi ? oi->value : VAL_NONE;
690 rr->output_format_raw = match_syntax;
693 rr->schema = odr_strdup(rr->stream, match_schema);
696 (*assoc->init->bend_fetch)(assoc->backend, rr);
700 static int srw_bend_fetch(association *assoc, int pos,
701 Z_SRW_searchRetrieveRequest *srw_req,
702 Z_SRW_record *record,
703 const char **addinfo)
706 ODR o = assoc->encode;
708 rr.setname = "default";
711 rr.request_format = VAL_TEXT_XML;
712 rr.request_format_raw = yaz_oidval_to_z3950oid(assoc->decode,
715 rr.comp = (Z_RecordComposition *)
716 odr_malloc(assoc->decode, sizeof(*rr.comp));
717 rr.comp->which = Z_RecordComp_complex;
718 rr.comp->u.complex = (Z_CompSpec *)
719 odr_malloc(assoc->decode, sizeof(Z_CompSpec));
720 rr.comp->u.complex->selectAlternativeSyntax = (bool_t *)
721 odr_malloc(assoc->encode, sizeof(bool_t));
722 *rr.comp->u.complex->selectAlternativeSyntax = 0;
723 rr.comp->u.complex->num_dbSpecific = 0;
724 rr.comp->u.complex->dbSpecific = 0;
725 rr.comp->u.complex->num_recordSyntax = 0;
726 rr.comp->u.complex->recordSyntax = 0;
728 rr.comp->u.complex->generic = (Z_Specification *)
729 odr_malloc(assoc->decode, sizeof(Z_Specification));
731 /* schema uri = recordSchema (or NULL if recordSchema is not given) */
732 rr.comp->u.complex->generic->which = Z_Schema_uri;
733 rr.comp->u.complex->generic->schema.uri = srw_req->recordSchema;
735 /* ESN = recordSchema if recordSchema is present */
736 rr.comp->u.complex->generic->elementSpec = 0;
737 if (srw_req->recordSchema)
739 rr.comp->u.complex->generic->elementSpec =
740 (Z_ElementSpec *) odr_malloc(assoc->encode, sizeof(Z_ElementSpec));
741 rr.comp->u.complex->generic->elementSpec->which =
742 Z_ElementSpec_elementSetName;
743 rr.comp->u.complex->generic->elementSpec->u.elementSetName =
744 srw_req->recordSchema;
747 rr.stream = assoc->encode;
748 rr.print = assoc->print;
756 rr.surrogate_flag = 0;
757 rr.schema = srw_req->recordSchema;
759 if (!assoc->init->bend_fetch)
762 retrieve_fetch(assoc, &rr);
764 if (rr.errcode && rr.surrogate_flag)
766 int code = yaz_diag_bib1_to_srw(rr.errcode);
767 const char *message = yaz_diag_srw_str(code);
770 len += strlen(message);
772 len += strlen(rr.errstring);
774 record->recordData_buf = odr_malloc(o, len);
776 sprintf(record->recordData_buf, "<diagnostic "
777 "xmlns=\"http://www.loc.gov/zing/srw/diagnostic/\">\n"
778 " <uri>info:srw/diagnostic/1/%d</uri>\n", code);
780 sprintf(record->recordData_buf + strlen(record->recordData_buf),
781 " <details>%s</details>\n", rr.errstring);
783 sprintf(record->recordData_buf + strlen(record->recordData_buf),
784 " <message>%s</message>\n", message);
785 sprintf(record->recordData_buf + strlen(record->recordData_buf),
787 record->recordData_len = strlen(record->recordData_buf);
788 record->recordPosition = odr_intdup(o, pos);
789 record->recordSchema = "info:srw/schema/1/diagnostics-v1.1";
792 else if (rr.len >= 0)
794 record->recordData_buf = rr.record;
795 record->recordData_len = rr.len;
796 record->recordPosition = odr_intdup(o, pos);
798 record->recordSchema = odr_strdup(o, rr.schema);
800 record->recordSchema = 0;
804 *addinfo = rr.errstring;
810 static int cql2pqf(ODR odr, const char *cql, cql_transform_t ct,
811 Z_Query *query_result)
813 /* have a CQL query and CQL to PQF transform .. */
814 CQL_parser cp = cql_parser_create();
820 r = cql_parser_string(cp, cql);
823 /* CQL syntax error */
829 r = cql_transform_buf(ct,
830 cql_parser_result(cp),
831 rpn_buf, sizeof(rpn_buf)-1);
833 srw_errcode = cql_transform_error(ct, &add);
837 /* Syntax & transform OK. */
838 /* Convert PQF string to Z39.50 to RPN query struct */
839 YAZ_PQF_Parser pp = yaz_pqf_create();
840 Z_RPNQuery *rpnquery = yaz_pqf_parse(pp, odr, rpn_buf);
845 int code = yaz_pqf_error(pp, &pqf_msg, &off);
846 yaz_log(YLOG_WARN, "PQF Parser Error %s (code %d)",
852 query_result->which = Z_Query_type_1;
853 query_result->u.type_1 = rpnquery;
857 cql_parser_destroy(cp);
861 static int cql2pqf_scan(ODR odr, const char *cql, cql_transform_t ct,
862 Z_AttributesPlusTerm *result)
866 int srw_error = cql2pqf(odr, cql, ct, &query);
869 if (query.which != Z_Query_type_1 && query.which != Z_Query_type_101)
870 return 10; /* bad query type */
871 rpn = query.u.type_1;
872 if (!rpn->RPNStructure)
873 return 10; /* must be structure */
874 if (rpn->RPNStructure->which != Z_RPNStructure_simple)
875 return 10; /* must be simple */
876 if (rpn->RPNStructure->u.simple->which != Z_Operand_APT)
877 return 10; /* must be attributes plus term node .. */
878 memcpy(result, rpn->RPNStructure->u.simple->u.attributesPlusTerm,
883 static void srw_bend_search(association *assoc, request *req,
885 Z_SRW_searchRetrieveResponse *srw_res,
890 Z_SRW_searchRetrieveRequest *srw_req = sr->u.request;
893 yaz_log(log_requestdetail, "Got SRW SearchRetrieveRequest");
894 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
895 if (srw_res->num_diagnostics == 0 && assoc->init)
898 rr.setname = "default";
901 rr.basenames = &srw_req->database;
905 rr.srw_setnameIdleTime = 0;
906 rr.query = (Z_Query *) odr_malloc (assoc->decode, sizeof(*rr.query));
907 rr.query->u.type_1 = 0;
909 if (srw_req->query_type == Z_SRW_query_type_cql)
911 if (assoc->server && assoc->server->cql_transform)
913 int srw_errcode = cql2pqf(assoc->encode, srw_req->query.cql,
914 assoc->server->cql_transform,
918 yaz_add_srw_diagnostic(assoc->encode,
919 &srw_res->diagnostics,
920 &srw_res->num_diagnostics,
926 /* CQL query to backend. Wrap it - Z39.50 style */
927 ext = (Z_External *) odr_malloc(assoc->decode, sizeof(*ext));
928 ext->direct_reference = odr_getoidbystr(assoc->decode,
929 "1.2.840.10003.16.2");
930 ext->indirect_reference = 0;
932 ext->which = Z_External_CQL;
933 ext->u.cql = srw_req->query.cql;
935 rr.query->which = Z_Query_type_104;
936 rr.query->u.type_104 = ext;
939 else if (srw_req->query_type == Z_SRW_query_type_pqf)
941 Z_RPNQuery *RPNquery;
942 YAZ_PQF_Parser pqf_parser;
944 pqf_parser = yaz_pqf_create ();
946 RPNquery = yaz_pqf_parse (pqf_parser, assoc->decode,
952 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
953 yaz_log(log_requestdetail, "Parse error %d %s near offset %ld",
954 code, pqf_msg, (long) off);
955 srw_error = YAZ_SRW_QUERY_SYNTAX_ERROR;
958 rr.query->which = Z_Query_type_1;
959 rr.query->u.type_1 = RPNquery;
961 yaz_pqf_destroy (pqf_parser);
965 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
966 &srw_res->num_diagnostics,
967 YAZ_SRW_UNSUPP_QUERY_TYPE, 0);
969 if (rr.query->u.type_1)
971 rr.stream = assoc->encode;
972 rr.decode = assoc->decode;
973 rr.print = assoc->print;
975 if ( srw_req->sort.sortKeys )
976 rr.srw_sortKeys = odr_strdup(assoc->encode,
977 srw_req->sort.sortKeys );
978 rr.association = assoc;
984 yaz_log_zquery_level(log_requestdetail,rr.query);
986 (assoc->init->bend_search)(assoc->backend, &rr);
989 if (rr.errcode == YAZ_BIB1_DATABASE_UNAVAILABLE)
995 srw_error = yaz_diag_bib1_to_srw (rr.errcode);
996 yaz_add_srw_diagnostic(assoc->encode,
997 &srw_res->diagnostics,
998 &srw_res->num_diagnostics,
999 srw_error, rr.errstring);
1004 int number = srw_req->maximumRecords ? *srw_req->maximumRecords : 0;
1005 int start = srw_req->startRecord ? *srw_req->startRecord : 1;
1007 yaz_log(log_requestdetail, "Request to pack %d+%d out of %d",
1008 start, number, rr.hits);
1010 srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
1013 srw_res->resultSetId =
1014 odr_strdup(assoc->encode, rr.srw_setname );
1015 srw_res->resultSetIdleTime =
1016 odr_intdup(assoc->encode, *rr.srw_setnameIdleTime );
1022 if (start > rr.hits)
1024 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1025 &srw_res->num_diagnostics,
1026 YAZ_SRW_FIRST_RECORD_POSITION_OUT_OF_RANGE, 0);
1031 if (start + number > rr.hits)
1032 number = rr.hits - start + 1;
1034 /* Call bend_present if defined */
1035 if (assoc->init->bend_present)
1037 bend_present_rr *bprr = (bend_present_rr*)
1038 odr_malloc (assoc->decode, sizeof(*bprr));
1039 bprr->setname = "default";
1040 bprr->start = start;
1041 bprr->number = number;
1042 bprr->format = VAL_TEXT_XML;
1043 if (srw_req->recordSchema)
1045 bprr->comp = (Z_RecordComposition *) odr_malloc(assoc->decode,
1046 sizeof(*bprr->comp));
1047 bprr->comp->which = Z_RecordComp_simple;
1048 bprr->comp->u.simple = (Z_ElementSetNames *)
1049 odr_malloc(assoc->decode, sizeof(Z_ElementSetNames));
1050 bprr->comp->u.simple->which = Z_ElementSetNames_generic;
1051 bprr->comp->u.simple->u.generic = srw_req->recordSchema;
1057 bprr->stream = assoc->encode;
1058 bprr->referenceId = 0;
1059 bprr->print = assoc->print;
1060 bprr->request = req;
1061 bprr->association = assoc;
1063 bprr->errstring = NULL;
1064 (*assoc->init->bend_present)(assoc->backend, bprr);
1070 srw_error = yaz_diag_bib1_to_srw (bprr->errcode);
1071 yaz_add_srw_diagnostic(assoc->encode,
1072 &srw_res->diagnostics,
1073 &srw_res->num_diagnostics,
1074 srw_error, bprr->errstring);
1082 int packing = Z_SRW_recordPacking_string;
1083 if (srw_req->recordPacking){
1084 if (!strcmp(srw_req->recordPacking, "xml"))
1085 packing = Z_SRW_recordPacking_XML;
1086 if (!strcmp(srw_req->recordPacking, "url"))
1087 packing = Z_SRW_recordPacking_URL;
1089 srw_res->records = (Z_SRW_record *)
1090 odr_malloc(assoc->encode,
1091 number * sizeof(*srw_res->records));
1093 srw_res->extra_records = (Z_SRW_extra_record **)
1094 odr_malloc(assoc->encode,
1095 number*sizeof(*srw_res->extra_records));
1097 for (i = 0; i<number; i++)
1100 const char *addinfo = 0;
1102 srw_res->records[j].recordPacking = packing;
1103 srw_res->records[j].recordData_buf = 0;
1104 srw_res->extra_records[j] = 0;
1105 yaz_log(YLOG_DEBUG, "srw_bend_fetch %d", i+start);
1106 errcode = srw_bend_fetch(assoc, i+start, srw_req,
1107 srw_res->records + j,
1111 yaz_add_srw_diagnostic(assoc->encode,
1112 &srw_res->diagnostics,
1113 &srw_res->num_diagnostics,
1114 yaz_diag_bib1_to_srw (errcode),
1119 if (srw_res->records[j].recordData_buf)
1122 srw_res->num_records = j;
1124 srw_res->records = 0;
1133 const char *querystr = "?";
1134 const char *querytype = "?";
1135 WRBUF wr = wrbuf_alloc();
1137 switch (srw_req->query_type)
1139 case Z_SRW_query_type_cql:
1141 querystr = srw_req->query.cql;
1143 case Z_SRW_query_type_pqf:
1145 querystr = srw_req->query.pqf;
1148 wrbuf_printf(wr, "SRWSearch ");
1149 wrbuf_printf(wr, srw_req->database);
1150 wrbuf_printf(wr, " ");
1151 if (srw_res->num_diagnostics)
1152 wrbuf_printf(wr, "ERROR %s", srw_res->diagnostics[0].uri);
1153 else if (*http_code != 200)
1154 wrbuf_printf(wr, "ERROR info:http/%d", *http_code);
1155 else if (srw_res->numberOfRecords)
1157 wrbuf_printf(wr, "OK %d",
1158 (srw_res->numberOfRecords ?
1159 *srw_res->numberOfRecords : 0));
1161 wrbuf_printf(wr, " %s %d+%d",
1162 (srw_res->resultSetId ?
1163 srw_res->resultSetId : "-"),
1164 (srw_req->startRecord ? *srw_req->startRecord : 1),
1165 srw_res->num_records);
1166 yaz_log(log_request, "%s %s: %s", wrbuf_buf(wr), querytype, querystr);
1171 static char *srw_bend_explain_default(void *handle, bend_explain_rr *rr)
1174 xmlNodePtr ptr = rr->server_node_ptr;
1177 for (ptr = ptr->children; ptr; ptr = ptr->next)
1179 if (ptr->type != XML_ELEMENT_NODE)
1181 if (!strcmp((const char *) ptr->name, "explain"))
1184 xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
1188 ptr = xmlCopyNode(ptr, 1);
1190 xmlDocSetRootElement(doc, ptr);
1192 xmlDocDumpMemory(doc, &buf_out, &len);
1193 content = (char*) odr_malloc(rr->stream, 1+len);
1194 memcpy(content, buf_out, len);
1195 content[len] = '\0';
1199 rr->explain_buf = content;
1207 static void srw_bend_explain(association *assoc, request *req,
1209 Z_SRW_explainResponse *srw_res,
1212 Z_SRW_explainRequest *srw_req = sr->u.explain_request;
1213 yaz_log(log_requestdetail, "Got SRW ExplainRequest");
1215 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1220 rr.stream = assoc->encode;
1221 rr.decode = assoc->decode;
1222 rr.print = assoc->print;
1224 rr.database = srw_req->database;
1226 rr.server_node_ptr = assoc->server->server_node_ptr;
1228 rr.server_node_ptr = 0;
1229 rr.schema = "http://explain.z3950.org/dtd/2.0/";
1230 if (assoc->init->bend_explain)
1231 (*assoc->init->bend_explain)(assoc->backend, &rr);
1233 srw_bend_explain_default(assoc->backend, &rr);
1237 int packing = Z_SRW_recordPacking_string;
1238 if (srw_req->recordPacking)
1240 if (!strcmp(srw_req->recordPacking, "xml"))
1241 packing = Z_SRW_recordPacking_XML;
1242 else if (!strcmp(srw_req->recordPacking, "url"))
1243 packing = Z_SRW_recordPacking_URL;
1245 srw_res->record.recordSchema = rr.schema;
1246 srw_res->record.recordPacking = packing;
1247 srw_res->record.recordData_buf = rr.explain_buf;
1248 srw_res->record.recordData_len = strlen(rr.explain_buf);
1249 srw_res->record.recordPosition = 0;
1255 static void srw_bend_scan(association *assoc, request *req,
1257 Z_SRW_scanResponse *srw_res,
1260 Z_SRW_scanRequest *srw_req = sr->u.scan_request;
1261 yaz_log(log_requestdetail, "Got SRW ScanRequest");
1264 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1265 if (srw_res->num_diagnostics == 0 && assoc->init)
1267 struct scan_entry *save_entries;
1269 bend_scan_rr *bsrr = (bend_scan_rr *)
1270 odr_malloc (assoc->encode, sizeof(*bsrr));
1271 bsrr->num_bases = 1;
1272 bsrr->basenames = &srw_req->database;
1274 bsrr->num_entries = srw_req->maximumTerms ?
1275 *srw_req->maximumTerms : 10;
1276 bsrr->term_position = srw_req->responsePosition ?
1277 *srw_req->responsePosition : 1;
1280 bsrr->errstring = 0;
1281 bsrr->referenceId = 0;
1282 bsrr->stream = assoc->encode;
1283 bsrr->print = assoc->print;
1284 bsrr->step_size = odr_intdup(assoc->decode, 0);
1287 if (bsrr->num_entries > 0)
1290 bsrr->entries = odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
1292 for (i = 0; i<bsrr->num_entries; i++)
1294 bsrr->entries[i].term = 0;
1295 bsrr->entries[i].occurrences = 0;
1296 bsrr->entries[i].errcode = 0;
1297 bsrr->entries[i].errstring = 0;
1298 bsrr->entries[i].display_term = 0;
1301 save_entries = bsrr->entries; /* save it so we can compare later */
1303 if (srw_req->query_type == Z_SRW_query_type_pqf &&
1304 assoc->init->bend_scan)
1306 Odr_oid *scan_attributeSet = 0;
1308 YAZ_PQF_Parser pqf_parser = yaz_pqf_create();
1310 bsrr->term = yaz_pqf_scan(pqf_parser, assoc->decode,
1312 srw_req->scanClause.pqf);
1313 if (scan_attributeSet &&
1314 (attset = oid_getentbyoid(scan_attributeSet)) &&
1315 (attset->oclass == CLASS_ATTSET ||
1316 attset->oclass == CLASS_GENERAL))
1317 bsrr->attributeset = attset->value;
1319 bsrr->attributeset = VAL_NONE;
1320 yaz_pqf_destroy(pqf_parser);
1321 bsrr->scanClause = 0;
1322 ((int (*)(void *, bend_scan_rr *))
1323 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1325 else if (srw_req->query_type == Z_SRW_query_type_cql
1326 && assoc->init->bend_scan && assoc->server
1327 && assoc->server->cql_transform)
1330 bsrr->scanClause = 0;
1331 bsrr->attributeset = VAL_NONE;
1332 bsrr->term = odr_malloc(assoc->decode, sizeof(*bsrr->term));
1333 srw_error = cql2pqf_scan(assoc->encode,
1334 srw_req->scanClause.cql,
1335 assoc->server->cql_transform,
1338 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1339 &srw_res->num_diagnostics,
1343 ((int (*)(void *, bend_scan_rr *))
1344 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1347 else if (srw_req->query_type == Z_SRW_query_type_cql
1348 && assoc->init->bend_srw_scan)
1351 bsrr->attributeset = VAL_NONE;
1352 bsrr->scanClause = srw_req->scanClause.cql;
1353 ((int (*)(void *, bend_scan_rr *))
1354 (*assoc->init->bend_srw_scan))(assoc->backend, bsrr);
1358 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1359 &srw_res->num_diagnostics,
1360 YAZ_SRW_UNSUPP_OPERATION, "scan");
1365 if (bsrr->errcode == YAZ_BIB1_DATABASE_UNAVAILABLE)
1370 srw_error = yaz_diag_bib1_to_srw (bsrr->errcode);
1372 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1373 &srw_res->num_diagnostics,
1374 srw_error, bsrr->errstring);
1376 else if (srw_res->num_diagnostics == 0 && bsrr->num_entries)
1379 srw_res->terms = (Z_SRW_scanTerm*)
1380 odr_malloc(assoc->encode, sizeof(*srw_res->terms) *
1383 srw_res->num_terms = bsrr->num_entries;
1384 for (i = 0; i<bsrr->num_entries; i++)
1386 Z_SRW_scanTerm *t = srw_res->terms + i;
1387 t->value = odr_strdup(assoc->encode, bsrr->entries[i].term);
1388 t->numberOfRecords =
1389 odr_intdup(assoc->encode, bsrr->entries[i].occurrences);
1391 if (save_entries == bsrr->entries &&
1392 bsrr->entries[i].display_term)
1394 /* the entries was _not_ set by the handler. So it's
1395 safe to test for new member display_term. It is
1398 t->displayTerm = odr_strdup(assoc->encode,
1399 bsrr->entries[i].display_term);
1407 WRBUF wr = wrbuf_alloc();
1408 const char *querytype = 0;
1409 const char *querystr = 0;
1411 switch(srw_req->query_type)
1413 case Z_SRW_query_type_pqf:
1415 querystr = srw_req->scanClause.pqf;
1417 case Z_SRW_query_type_cql:
1419 querystr = srw_req->scanClause.cql;
1422 querytype = "UNKNOWN";
1426 wrbuf_printf(wr, "SRWScan ");
1427 wrbuf_printf(wr, srw_req->database);
1428 wrbuf_printf(wr, " ");
1430 if (srw_res->num_diagnostics)
1431 wrbuf_printf(wr, "ERROR %s - ", srw_res->diagnostics[0].uri);
1432 else if (srw_res->num_terms)
1433 wrbuf_printf(wr, "OK %d - ", srw_res->num_terms);
1435 wrbuf_printf(wr, "OK - - ");
1437 wrbuf_printf(wr, "%d+%d+0 ",
1438 (srw_req->responsePosition ?
1439 *srw_req->responsePosition : 1),
1440 (srw_req->maximumTerms ?
1441 *srw_req->maximumTerms : 1));
1442 /* there is no step size in SRU/W ??? */
1443 wrbuf_printf(wr, "%s: %s ", querytype, querystr);
1444 yaz_log(log_request, "%s ", wrbuf_buf(wr) );
1450 static void srw_bend_update(association *assoc, request *req,
1452 Z_SRW_updateResponse *srw_res,
1455 Z_SRW_updateRequest *srw_req = sr->u.update_request;
1456 yaz_log(YLOG_DEBUG, "Got SRW UpdateRequest");
1457 yaz_log(YLOG_DEBUG, "num_diag = %d", srw_res->num_diagnostics );
1459 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1464 rr.stream = assoc->encode;
1465 rr.print = assoc->print;
1467 rr.basenames = &srw_req->database;
1468 rr.operation = srw_req->operation;
1469 rr.operation_status = "failed";
1471 rr.record_version = 0;
1472 rr.record_checksum = 0;
1473 rr.record_old_version = 0;
1474 rr.record_packing = "xml";
1475 rr.record_schema = 0;
1477 rr.request_extra_record = 0;
1478 rr.response_extra_record = 0;
1479 rr.extra_request_data = 0;
1480 rr.extra_response_data = 0;
1485 yaz_log(YLOG_DEBUG, "basename = %s", rr.basenames[0] );
1486 yaz_log(YLOG_DEBUG, "Operation = %s", rr.operation );
1487 if ( !strcmp( rr.operation, "delete" ) ){
1488 if ( !srw_req->recordId ){
1489 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1490 &srw_res->num_diagnostics,
1494 rr.record_id = srw_req->recordId;
1496 if ( !srw_req->recordVersion ){
1497 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1498 &srw_res->num_diagnostics,
1499 7, "recordVersion" );
1502 rr.record_version = odr_strdup( assoc->encode,
1503 srw_req->recordVersion );
1506 if ( srw_req->recordOldVersion ){
1507 rr.record_old_version = odr_strdup(assoc->encode,
1508 srw_req->recordOldVersion );
1510 if ( srw_req->extraRequestData ){
1511 rr.extra_request_data = odr_strdup(assoc->encode,
1512 srw_req->extraRequestData );
1515 else if ( !strcmp( rr.operation, "replace" ) ){
1516 if ( !srw_req->recordId ){
1517 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1518 &srw_res->num_diagnostics,
1522 rr.record_id = srw_req->recordId;
1524 if ( srw_req->record.recordSchema == 0 ){
1525 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1526 &srw_res->num_diagnostics,
1527 7, "recordSchema" );
1530 rr.record_schema = odr_strdup(assoc->encode,
1531 srw_req->record.recordSchema );
1533 switch (srw_req->record.recordPacking)
1535 case Z_SRW_recordPacking_string:
1536 rr.record_packing = "string";
1538 case Z_SRW_recordPacking_XML:
1539 rr.record_packing = "xml";
1541 case Z_SRW_recordPacking_URL:
1542 rr.record_packing = "url";
1545 if ( srw_req->record.recordData_len ){
1546 rr.record_data = odr_strdupn(assoc->encode,
1547 srw_req->record.recordData_buf,
1548 srw_req->record.recordData_len );
1549 rr.request_extra_record = srw_req->extra_record;
1552 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1553 &srw_res->num_diagnostics,
1556 if (srw_req->extraRequestData)
1557 rr.extra_request_data = odr_strdup(assoc->encode,
1558 srw_req->extraRequestData );
1560 else if ( !strcmp( rr.operation, "insert" ) )
1562 rr.record_id = srw_req->recordId;
1563 if ( srw_req->record.recordSchema == 0 ){
1564 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1565 &srw_res->num_diagnostics,
1566 7, "recordSchema" );
1569 rr.record_schema = odr_strdup(assoc->encode,
1570 srw_req->record.recordSchema);
1572 switch (srw_req->record.recordPacking)
1574 case Z_SRW_recordPacking_string:
1575 rr.record_packing = "string";
1577 case Z_SRW_recordPacking_XML:
1578 rr.record_packing = "xml";
1580 case Z_SRW_recordPacking_URL:
1581 rr.record_packing = "url";
1585 if (srw_req->record.recordData_len)
1587 rr.record_data = odr_strdupn(assoc->encode,
1588 srw_req->record.recordData_buf,
1589 srw_req->record.recordData_len );
1590 rr.request_extra_record = srw_req->extra_record;
1593 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1594 &srw_res->num_diagnostics,
1596 if ( srw_req->extraRequestData )
1597 rr.extra_request_data = odr_strdup(assoc->encode,
1598 srw_req->extraRequestData );
1600 if (srw_res->num_diagnostics == 0)
1602 if ( assoc->init->bend_srw_update)
1603 (*assoc->init->bend_srw_update)(assoc->backend, &rr);
1605 yaz_log( YLOG_WARN, "Got No Update function!");
1611 yaz_add_srw_diagnostic_uri(assoc->encode,
1612 &srw_res->diagnostics,
1613 &srw_res->num_diagnostics,
1617 srw_res->recordId = rr.record_id;
1618 srw_res->operationStatus = rr.operation_status;
1619 srw_res->recordVersion = rr.record_version;
1620 srw_res->recordChecksum = rr.record_checksum;
1621 srw_res->extraResponseData = rr.extra_response_data;
1622 srw_res->record.recordPosition = 0;
1623 if (srw_res->num_diagnostics == 0 && rr.record_data)
1625 srw_res->record.recordSchema = rr.record_schema;
1626 srw_res->record.recordPacking = srw_req->record.recordPacking;
1627 srw_res->record.recordData_buf = rr.record_data;
1628 srw_res->record.recordData_len = strlen(rr.record_data);
1629 srw_res->extra_record = rr.response_extra_record;
1633 srw_res->record.recordData_len = 0;
1638 /* check if path is OK (1); BAD (0) */
1639 static int check_path(const char *path)
1643 if (strstr(path, ".."))
1648 static char *read_file(const char *fname, ODR o, int *sz)
1651 FILE *inf = fopen(fname, "rb");
1655 fseek(inf, 0L, SEEK_END);
1658 buf = odr_malloc(o, *sz);
1659 fread(buf, 1, *sz, inf);
1664 static void process_http_request(association *assoc, request *req)
1666 Z_HTTP_Request *hreq = req->gdu_request->u.HTTP_Request;
1667 ODR o = assoc->encode;
1668 int r = 2; /* 2=NOT TAKEN, 1=TAKEN, 0=SOAP TAKEN */
1670 Z_SOAP *soap_package = 0;
1673 Z_HTTP_Response *hres = 0;
1675 const char *stylesheet = 0; /* for now .. set later */
1676 Z_SRW_diagnostic *diagnostic = 0;
1677 int num_diagnostic = 0;
1678 const char *host = z_HTTP_header_lookup(hreq->headers, "Host");
1680 if (!control_association(assoc, host, 0))
1682 p = z_get_HTTP_Response(o, 404);
1685 if (r == 2 && assoc->server && assoc->server->docpath
1686 && hreq->path[0] == '/'
1688 /* check if path is a proper prefix of documentroot */
1689 strncmp(hreq->path+1, assoc->server->docpath,
1690 strlen(assoc->server->docpath))
1693 if (!check_path(hreq->path))
1695 yaz_log(YLOG_LOG, "File %s access forbidden", hreq->path+1);
1696 p = z_get_HTTP_Response(o, 404);
1700 int content_size = 0;
1701 char *content_buf = read_file(hreq->path+1, o, &content_size);
1704 yaz_log(YLOG_LOG, "File %s not found", hreq->path+1);
1705 p = z_get_HTTP_Response(o, 404);
1709 const char *ctype = 0;
1710 yaz_mime_types types = yaz_mime_types_create();
1712 yaz_mime_types_add(types, "xsl", "application/xml");
1713 yaz_mime_types_add(types, "xml", "application/xml");
1714 yaz_mime_types_add(types, "css", "text/css");
1715 yaz_mime_types_add(types, "html", "text/html");
1716 yaz_mime_types_add(types, "htm", "text/html");
1717 yaz_mime_types_add(types, "txt", "text/plain");
1718 yaz_mime_types_add(types, "js", "application/x-javascript");
1720 yaz_mime_types_add(types, "gif", "image/gif");
1721 yaz_mime_types_add(types, "png", "image/png");
1722 yaz_mime_types_add(types, "jpg", "image/jpeg");
1723 yaz_mime_types_add(types, "jpeg", "image/jpeg");
1725 ctype = yaz_mime_lookup_fname(types, hreq->path);
1728 yaz_log(YLOG_LOG, "No mime type for %s", hreq->path+1);
1729 p = z_get_HTTP_Response(o, 404);
1733 p = z_get_HTTP_Response(o, 200);
1734 hres = p->u.HTTP_Response;
1735 hres->content_buf = content_buf;
1736 hres->content_len = content_size;
1737 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1739 yaz_mime_types_destroy(types);
1747 r = yaz_srw_decode(hreq, &sr, &soap_package, assoc->decode, &charset);
1748 yaz_log(YLOG_DEBUG, "yaz_srw_decode returned %d", r);
1750 if (r == 2) /* not taken */
1752 r = yaz_sru_decode(hreq, &sr, &soap_package, assoc->decode, &charset,
1753 &diagnostic, &num_diagnostic);
1754 yaz_log(YLOG_DEBUG, "yaz_sru_decode returned %d", r);
1756 if (r == 0) /* decode SRW/SRU OK .. */
1758 int http_code = 200;
1759 if (sr->which == Z_SRW_searchRetrieve_request)
1762 yaz_srw_get(assoc->encode, Z_SRW_searchRetrieve_response);
1764 stylesheet = sr->u.request->stylesheet;
1767 res->u.response->diagnostics = diagnostic;
1768 res->u.response->num_diagnostics = num_diagnostic;
1772 srw_bend_search(assoc, req, sr, res->u.response,
1775 if (http_code == 200)
1776 soap_package->u.generic->p = res;
1778 else if (sr->which == Z_SRW_explain_request)
1780 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_explain_response);
1781 stylesheet = sr->u.explain_request->stylesheet;
1784 res->u.explain_response->diagnostics = diagnostic;
1785 res->u.explain_response->num_diagnostics = num_diagnostic;
1787 srw_bend_explain(assoc, req, sr,
1788 res->u.explain_response, &http_code);
1789 if (http_code == 200)
1790 soap_package->u.generic->p = res;
1792 else if (sr->which == Z_SRW_scan_request)
1794 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_scan_response);
1795 stylesheet = sr->u.scan_request->stylesheet;
1798 res->u.scan_response->diagnostics = diagnostic;
1799 res->u.scan_response->num_diagnostics = num_diagnostic;
1801 srw_bend_scan(assoc, req, sr,
1802 res->u.scan_response, &http_code);
1803 if (http_code == 200)
1804 soap_package->u.generic->p = res;
1806 else if (sr->which == Z_SRW_update_request)
1808 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_update_response);
1809 yaz_log(YLOG_DEBUG, "handling SRW UpdateRequest");
1812 res->u.update_response->diagnostics = diagnostic;
1813 res->u.update_response->num_diagnostics = num_diagnostic;
1815 yaz_log(YLOG_DEBUG, "num_diag = %d", res->u.update_response->num_diagnostics );
1816 srw_bend_update(assoc, req, sr,
1817 res->u.update_response, &http_code);
1818 if (http_code == 200)
1819 soap_package->u.generic->p = res;
1823 yaz_log(log_request, "SOAP ERROR");
1824 /* FIXME - what error, what query */
1826 z_soap_error(assoc->encode, soap_package,
1827 "SOAP-ENV:Client", "Bad method", 0);
1829 if (http_code == 200 || http_code == 500)
1831 static Z_SOAP_Handler soap_handlers[4] = {
1833 {"http://www.loc.gov/zing/srw/", 0,
1834 (Z_SOAP_fun) yaz_srw_codec},
1835 {"http://www.loc.gov/zing/srw/v1.0/", 0,
1836 (Z_SOAP_fun) yaz_srw_codec},
1837 {"http://www.loc.gov/zing/srw/update/", 0,
1838 (Z_SOAP_fun) yaz_ucp_codec},
1844 p = z_get_HTTP_Response(o, 200);
1845 hres = p->u.HTTP_Response;
1847 if (!stylesheet && assoc->server)
1848 stylesheet = assoc->server->stylesheet;
1850 /* empty stylesheet means NO stylesheet */
1851 if (stylesheet && *stylesheet == '\0')
1854 ret = z_soap_codec_enc_xsl(assoc->encode, &soap_package,
1855 &hres->content_buf, &hres->content_len,
1856 soap_handlers, charset, stylesheet);
1857 hres->code = http_code;
1859 strcpy(ctype, "text/xml");
1862 strcat(ctype, "; charset=");
1863 strcat(ctype, charset);
1865 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1868 p = z_get_HTTP_Response(o, http_code);
1872 p = z_get_HTTP_Response(o, 500);
1873 hres = p->u.HTTP_Response;
1874 if (!strcmp(hreq->version, "1.0"))
1876 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1877 if (v && !strcmp(v, "Keep-Alive"))
1881 hres->version = "1.0";
1885 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1886 if (v && !strcmp(v, "close"))
1890 hres->version = "1.1";
1894 z_HTTP_header_add(o, &hres->headers, "Connection", "close");
1895 assoc->state = ASSOC_DEAD;
1896 assoc->cs_get_mask = 0;
1901 const char *alive = z_HTTP_header_lookup(hreq->headers, "Keep-Alive");
1903 if (alive && isdigit(*(const unsigned char *) alive))
1907 if (t < 0 || t > 3600)
1909 iochan_settimeout(assoc->client_chan,t);
1910 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1912 process_gdu_response(assoc, req, p);
1915 static void process_gdu_request(association *assoc, request *req)
1917 if (req->gdu_request->which == Z_GDU_Z3950)
1920 req->apdu_request = req->gdu_request->u.z3950;
1921 if (process_z_request(assoc, req, &msg) < 0)
1922 do_close_req(assoc, Z_Close_systemProblem, msg, req);
1924 else if (req->gdu_request->which == Z_GDU_HTTP_Request)
1925 process_http_request(assoc, req);
1928 do_close_req(assoc, Z_Close_systemProblem, "bad protocol packet", req);
1933 * Initiate request processing.
1935 static int process_z_request(association *assoc, request *req, char **msg)
1941 *msg = "Unknown Error";
1942 assert(req && req->state == REQUEST_IDLE);
1943 if (req->apdu_request->which != Z_APDU_initRequest && !assoc->init)
1945 *msg = "Missing InitRequest";
1948 switch (req->apdu_request->which)
1950 case Z_APDU_initRequest:
1951 res = process_initRequest(assoc, req); break;
1952 case Z_APDU_searchRequest:
1953 res = process_searchRequest(assoc, req, &fd); break;
1954 case Z_APDU_presentRequest:
1955 res = process_presentRequest(assoc, req, &fd); break;
1956 case Z_APDU_scanRequest:
1957 if (assoc->init->bend_scan)
1958 res = process_scanRequest(assoc, req, &fd);
1961 *msg = "Cannot handle Scan APDU";
1965 case Z_APDU_extendedServicesRequest:
1966 if (assoc->init->bend_esrequest)
1967 res = process_ESRequest(assoc, req, &fd);
1970 *msg = "Cannot handle Extended Services APDU";
1974 case Z_APDU_sortRequest:
1975 if (assoc->init->bend_sort)
1976 res = process_sortRequest(assoc, req, &fd);
1979 *msg = "Cannot handle Sort APDU";
1984 process_close(assoc, req);
1986 case Z_APDU_deleteResultSetRequest:
1987 if (assoc->init->bend_delete)
1988 res = process_deleteRequest(assoc, req, &fd);
1991 *msg = "Cannot handle Delete APDU";
1995 case Z_APDU_segmentRequest:
1996 if (assoc->init->bend_segment)
1998 res = process_segmentRequest (assoc, req);
2002 *msg = "Cannot handle Segment APDU";
2006 case Z_APDU_triggerResourceControlRequest:
2009 *msg = "Bad APDU received";
2014 yaz_log(YLOG_DEBUG, " result immediately available");
2015 retval = process_z_response(assoc, req, res);
2019 yaz_log(YLOG_DEBUG, " result unavailble");
2022 else /* no result yet - one will be provided later */
2026 /* Set up an I/O handler for the fd supplied by the backend */
2028 yaz_log(YLOG_DEBUG, " establishing handler for result");
2029 req->state = REQUEST_PENDING;
2030 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT, 0)))
2032 iochan_setdata(chan, assoc);
2039 * Handle message from the backend.
2041 void backend_response(IOCHAN i, int event)
2043 association *assoc = (association *)iochan_getdata(i);
2044 request *req = request_head(&assoc->incoming);
2048 yaz_log(YLOG_DEBUG, "backend_response");
2049 assert(assoc && req && req->state != REQUEST_IDLE);
2050 /* determine what it is we're waiting for */
2051 switch (req->apdu_request->which)
2053 case Z_APDU_searchRequest:
2054 res = response_searchRequest(assoc, req, 0, &fd); break;
2056 case Z_APDU_presentRequest:
2057 res = response_presentRequest(assoc, req, 0, &fd); break;
2058 case Z_APDU_scanRequest:
2059 res = response_scanRequest(assoc, req, 0, &fd); break;
2062 yaz_log(YLOG_FATAL, "Serious programmer's lapse or bug");
2065 if ((res && process_z_response(assoc, req, res) < 0) || fd < 0)
2067 yaz_log(YLOG_WARN, "Fatal error when talking to backend");
2068 do_close(assoc, Z_Close_systemProblem, 0);
2072 else if (!res) /* no result yet - try again later */
2074 yaz_log(YLOG_DEBUG, " no result yet");
2075 iochan_setfd(i, fd); /* in case fd has changed */
2080 * Encode response, and transfer the request structure to the outgoing queue.
2082 static int process_gdu_response(association *assoc, request *req, Z_GDU *res)
2084 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
2088 if (!z_GDU(assoc->print, &res, 0, 0))
2089 yaz_log(YLOG_WARN, "ODR print error: %s",
2090 odr_errmsg(odr_geterror(assoc->print)));
2091 odr_reset(assoc->print);
2093 if (!z_GDU(assoc->encode, &res, 0, 0))
2095 yaz_log(YLOG_WARN, "ODR error when encoding PDU: %s [element %s]",
2096 odr_errmsg(odr_geterror(assoc->decode)),
2097 odr_getelement(assoc->decode));
2100 req->response = odr_getbuf(assoc->encode, &req->len_response,
2101 &req->size_response);
2102 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
2103 odr_reset(assoc->encode);
2104 req->state = REQUEST_IDLE;
2105 request_enq(&assoc->outgoing, req);
2106 /* turn the work over to the ir_session handler */
2107 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
2108 assoc->cs_put_mask = EVENT_OUTPUT;
2109 /* Is there more work to be done? give that to the input handler too */
2111 if (request_head(&assoc->incoming))
2113 yaz_log (YLOG_DEBUG, "more work to be done");
2114 iochan_setevent(assoc->client_chan, EVENT_WORK);
2121 * Encode response, and transfer the request structure to the outgoing queue.
2123 static int process_z_response(association *assoc, request *req, Z_APDU *res)
2125 Z_GDU *gres = (Z_GDU *) odr_malloc(assoc->encode, sizeof(*res));
2126 gres->which = Z_GDU_Z3950;
2127 gres->u.z3950 = res;
2129 return process_gdu_response(assoc, req, gres);
2132 static char *get_vhost(Z_OtherInformation *otherInfo)
2134 return yaz_oi_get_string_oidval(&otherInfo, VAL_PROXY, 1, 0);
2138 * Handle init request.
2139 * At the moment, we don't check the options
2140 * anywhere else in the code - we just try not to do anything that would
2141 * break a naive client. We'll toss 'em into the association block when
2142 * we need them there.
2144 static Z_APDU *process_initRequest(association *assoc, request *reqb)
2146 Z_InitRequest *req = reqb->apdu_request->u.initRequest;
2147 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
2148 Z_InitResponse *resp = apdu->u.initResponse;
2149 bend_initresult *binitres;
2152 statserv_options_block *cb = 0; /* by default no control for backend */
2154 if (control_association(assoc, get_vhost(req->otherInfo), 1))
2155 cb = statserv_getcontrol(); /* got control block for backend */
2157 if (cb && assoc->backend)
2158 (*cb->bend_close)(assoc->backend);
2160 yaz_log(log_requestdetail, "Got initRequest");
2161 if (req->implementationId)
2162 yaz_log(log_requestdetail, "Id: %s",
2163 req->implementationId);
2164 if (req->implementationName)
2165 yaz_log(log_requestdetail, "Name: %s",
2166 req->implementationName);
2167 if (req->implementationVersion)
2168 yaz_log(log_requestdetail, "Version: %s",
2169 req->implementationVersion);
2171 assoc_init_reset(assoc);
2173 assoc->init->auth = req->idAuthentication;
2174 assoc->init->referenceId = req->referenceId;
2176 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
2178 Z_CharSetandLanguageNegotiation *negotiation =
2179 yaz_get_charneg_record (req->otherInfo);
2181 negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
2182 assoc->init->charneg_request = negotiation;
2188 if (req->implementationVersion)
2189 yaz_log(log_requestdetail, "Config: %s",
2192 iochan_settimeout(assoc->client_chan, cb->idle_timeout * 60);
2194 /* we have a backend control block, so call that init function */
2195 if (!(binitres = (*cb->bend_init)(assoc->init)))
2197 yaz_log(YLOG_WARN, "Bad response from backend.");
2200 assoc->backend = binitres->handle;
2204 /* no backend. return error */
2205 binitres = odr_malloc(assoc->encode, sizeof(*binitres));
2206 binitres->errstring = 0;
2207 binitres->errcode = YAZ_BIB1_PERMANENT_SYSTEM_ERROR;
2208 iochan_settimeout(assoc->client_chan, 10);
2210 if ((assoc->init->bend_sort))
2211 yaz_log (YLOG_DEBUG, "Sort handler installed");
2212 if ((assoc->init->bend_search))
2213 yaz_log (YLOG_DEBUG, "Search handler installed");
2214 if ((assoc->init->bend_present))
2215 yaz_log (YLOG_DEBUG, "Present handler installed");
2216 if ((assoc->init->bend_esrequest))
2217 yaz_log (YLOG_DEBUG, "ESRequest handler installed");
2218 if ((assoc->init->bend_delete))
2219 yaz_log (YLOG_DEBUG, "Delete handler installed");
2220 if ((assoc->init->bend_scan))
2221 yaz_log (YLOG_DEBUG, "Scan handler installed");
2222 if ((assoc->init->bend_segment))
2223 yaz_log (YLOG_DEBUG, "Segment handler installed");
2225 resp->referenceId = req->referenceId;
2227 /* let's tell the client what we can do */
2228 if (ODR_MASK_GET(req->options, Z_Options_search))
2230 ODR_MASK_SET(resp->options, Z_Options_search);
2231 strcat(options, "srch");
2233 if (ODR_MASK_GET(req->options, Z_Options_present))
2235 ODR_MASK_SET(resp->options, Z_Options_present);
2236 strcat(options, " prst");
2238 if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
2239 assoc->init->bend_delete)
2241 ODR_MASK_SET(resp->options, Z_Options_delSet);
2242 strcat(options, " del");
2244 if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
2245 assoc->init->bend_esrequest)
2247 ODR_MASK_SET(resp->options, Z_Options_extendedServices);
2248 strcat (options, " extendedServices");
2250 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
2252 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
2253 strcat(options, " namedresults");
2255 if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
2257 ODR_MASK_SET(resp->options, Z_Options_scan);
2258 strcat(options, " scan");
2260 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
2262 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
2263 strcat(options, " concurrop");
2265 if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
2267 ODR_MASK_SET(resp->options, Z_Options_sort);
2268 strcat(options, " sort");
2271 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel)
2272 && assoc->init->charneg_response)
2274 Z_OtherInformation **p;
2275 Z_OtherInformationUnit *p0;
2277 yaz_oi_APDU(apdu, &p);
2279 if ((p0=yaz_oi_update(p, assoc->encode, NULL, 0, 0))) {
2280 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
2282 p0->which = Z_OtherInfo_externallyDefinedInfo;
2283 p0->information.externallyDefinedInfo =
2284 assoc->init->charneg_response;
2286 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
2287 strcat(options, " negotiation");
2290 if (ODR_MASK_GET(req->options, Z_Options_triggerResourceCtrl))
2291 ODR_MASK_SET(resp->options, Z_Options_triggerResourceCtrl);
2293 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
2295 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
2296 assoc->version = 1; /* 1 & 2 are equivalent */
2298 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
2300 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
2303 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
2305 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
2309 yaz_log(log_requestdetail, "Negotiated to v%d: %s", assoc->version, options);
2310 assoc->maximumRecordSize = *req->maximumRecordSize;
2312 if (cb && assoc->maximumRecordSize > cb->maxrecordsize)
2313 assoc->maximumRecordSize = cb->maxrecordsize;
2314 assoc->preferredMessageSize = *req->preferredMessageSize;
2315 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
2316 assoc->preferredMessageSize = assoc->maximumRecordSize;
2318 resp->preferredMessageSize = &assoc->preferredMessageSize;
2319 resp->maximumRecordSize = &assoc->maximumRecordSize;
2321 resp->implementationId = odr_prepend(assoc->encode,
2322 assoc->init->implementation_id,
2323 resp->implementationId);
2325 resp->implementationName = odr_prepend(assoc->encode,
2326 assoc->init->implementation_name,
2327 odr_prepend(assoc->encode, "GFS", resp->implementationName));
2329 version = odr_strdup(assoc->encode, "$Revision: 1.96 $");
2330 if (strlen(version) > 10) /* check for unexpanded CVS strings */
2331 version[strlen(version)-2] = '\0';
2332 resp->implementationVersion = odr_prepend(assoc->encode,
2333 assoc->init->implementation_version,
2334 odr_prepend(assoc->encode, &version[11],
2335 resp->implementationVersion));
2337 if (binitres->errcode)
2339 assoc->state = ASSOC_DEAD;
2340 resp->userInformationField =
2341 init_diagnostics(assoc->encode, binitres->errcode,
2342 binitres->errstring);
2347 if (!req->idAuthentication)
2348 yaz_log(log_request, "Auth none");
2349 else if (req->idAuthentication->which == Z_IdAuthentication_open)
2351 const char *open = req->idAuthentication->u.open;
2352 const char *slash = strchr(open, '/');
2358 yaz_log(log_request, "Auth open %.*s", len, open);
2360 else if (req->idAuthentication->which == Z_IdAuthentication_idPass)
2362 const char *user = req->idAuthentication->u.idPass->userId;
2363 const char *group = req->idAuthentication->u.idPass->groupId;
2364 yaz_log(log_request, "Auth idPass %s %s",
2365 user ? user : "-", group ? group : "-");
2367 else if (req->idAuthentication->which
2368 == Z_IdAuthentication_anonymous)
2370 yaz_log(log_request, "Auth anonymous");
2374 yaz_log(log_request, "Auth other");
2379 WRBUF wr = wrbuf_alloc();
2380 wrbuf_printf(wr, "Init ");
2381 if (binitres->errcode)
2382 wrbuf_printf(wr, "ERROR %d", binitres->errcode);
2384 wrbuf_printf(wr, "OK -");
2385 wrbuf_printf(wr, " ID:%s Name:%s Version:%s",
2386 (req->implementationId ? req->implementationId :"-"),
2387 (req->implementationName ?
2388 req->implementationName : "-"),
2389 (req->implementationVersion ?
2390 req->implementationVersion : "-")
2392 yaz_log(log_request, "%s", wrbuf_buf(wr));
2399 * Set the specified `errcode' and `errstring' into a UserInfo-1
2400 * external to be returned to the client in accordance with Z35.90
2401 * Implementor Agreement 5 (Returning diagnostics in an InitResponse):
2402 * http://lcweb.loc.gov/z3950/agency/agree/initdiag.html
2404 static Z_External *init_diagnostics(ODR odr, int error, const char *addinfo)
2406 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2407 addinfo ? " -- " : "", addinfo ? addinfo : "");
2408 return zget_init_diagnostics(odr, error, addinfo);
2412 * nonsurrogate diagnostic record.
2414 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
2416 Z_Records *rec = (Z_Records *) odr_malloc (assoc->encode, sizeof(*rec));
2418 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2419 addinfo ? " -- " : "", addinfo ? addinfo : "");
2421 rec->which = Z_Records_NSD;
2422 rec->u.nonSurrogateDiagnostic = zget_DefaultDiagFormat(assoc->encode,
2428 * surrogate diagnostic.
2430 static Z_NamePlusRecord *surrogatediagrec(association *assoc,
2432 int error, const char *addinfo)
2434 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2435 addinfo ? " -- " : "", addinfo ? addinfo : "");
2436 return zget_surrogateDiagRec(assoc->encode, dbname, error, addinfo);
2439 static Z_Records *pack_records(association *a, char *setname, int start,
2440 int *num, Z_RecordComposition *comp,
2441 int *next, int *pres, oid_value format,
2442 Z_ReferenceId *referenceId,
2443 int *oid, int *errcode)
2445 int recno, total_length = 0, toget = *num, dumped_records = 0;
2446 Z_Records *records =
2447 (Z_Records *) odr_malloc (a->encode, sizeof(*records));
2448 Z_NamePlusRecordList *reclist =
2449 (Z_NamePlusRecordList *) odr_malloc (a->encode, sizeof(*reclist));
2450 Z_NamePlusRecord **list =
2451 (Z_NamePlusRecord **) odr_malloc (a->encode, sizeof(*list) * toget);
2453 records->which = Z_Records_DBOSD;
2454 records->u.databaseOrSurDiagnostics = reclist;
2455 reclist->num_records = 0;
2456 reclist->records = list;
2457 *pres = Z_PresentStatus_success;
2461 yaz_log(log_requestdetail, "Request to pack %d+%d %s", start, toget, setname);
2462 yaz_log(log_requestdetail, "pms=%d, mrs=%d", a->preferredMessageSize,
2463 a->maximumRecordSize);
2464 for (recno = start; reclist->num_records < toget; recno++)
2467 Z_NamePlusRecord *thisrec;
2468 int this_length = 0;
2470 * we get the number of bytes allocated on the stream before any
2471 * allocation done by the backend - this should give us a reasonable
2472 * idea of the total size of the data so far.
2474 total_length = odr_total(a->encode) - dumped_records;
2480 freq.last_in_set = 0;
2481 freq.setname = setname;
2482 freq.surrogate_flag = 0;
2483 freq.number = recno;
2485 freq.request_format = format;
2486 freq.request_format_raw = oid;
2487 freq.output_format = format;
2488 freq.output_format_raw = 0;
2489 freq.stream = a->encode;
2490 freq.print = a->print;
2491 freq.referenceId = referenceId;
2494 retrieve_fetch(a, &freq);
2496 *next = freq.last_in_set ? 0 : recno + 1;
2498 /* backend should be able to signal whether error is system-wide
2499 or only pertaining to current record */
2502 if (!freq.surrogate_flag)
2505 *pres = Z_PresentStatus_failure;
2506 /* for 'present request out of range',
2507 set addinfo to record position if not set */
2508 if (freq.errcode == YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE &&
2509 freq.errstring == 0)
2511 sprintf (s, "%d", recno);
2515 *errcode = freq.errcode;
2516 return diagrec(a, freq.errcode, freq.errstring);
2518 reclist->records[reclist->num_records] =
2519 surrogatediagrec(a, freq.basename, freq.errcode,
2521 reclist->num_records++;
2524 if (freq.record == 0) /* no error and no record ? */
2526 *next = 0; /* signal end-of-set and stop */
2530 this_length = freq.len;
2532 this_length = odr_total(a->encode) - total_length - dumped_records;
2533 yaz_log(YLOG_DEBUG, " fetched record, len=%d, total=%d dumped=%d",
2534 this_length, total_length, dumped_records);
2535 if (a->preferredMessageSize > 0 &&
2536 this_length + total_length > a->preferredMessageSize)
2538 /* record is small enough, really */
2539 if (this_length <= a->preferredMessageSize && recno > start)
2541 yaz_log(log_requestdetail, " Dropped last normal-sized record");
2542 *pres = Z_PresentStatus_partial_2;
2545 /* record can only be fetched by itself */
2546 if (this_length < a->maximumRecordSize)
2548 yaz_log(log_requestdetail, " Record > prefmsgsz");
2551 yaz_log(YLOG_DEBUG, " Dropped it");
2552 reclist->records[reclist->num_records] =
2553 surrogatediagrec(a, freq.basename, 16, 0);
2554 reclist->num_records++;
2555 dumped_records += this_length;
2559 else /* too big entirely */
2561 yaz_log(log_requestdetail, "Record > maxrcdsz this=%d max=%d",
2562 this_length, a->maximumRecordSize);
2563 reclist->records[reclist->num_records] =
2564 surrogatediagrec(a, freq.basename, 17, 0);
2565 reclist->num_records++;
2566 dumped_records += this_length;
2571 if (!(thisrec = (Z_NamePlusRecord *)
2572 odr_malloc(a->encode, sizeof(*thisrec))))
2575 thisrec->databaseName = odr_strdup(a->encode, freq.basename);
2577 thisrec->databaseName = 0;
2578 thisrec->which = Z_NamePlusRecord_databaseRecord;
2580 if (freq.output_format_raw)
2582 struct oident *ident = oid_getentbyoid(freq.output_format_raw);
2583 freq.output_format = ident->value;
2585 thisrec->u.databaseRecord = z_ext_record(a->encode, freq.output_format,
2586 freq.record, freq.len);
2587 if (!thisrec->u.databaseRecord)
2589 reclist->records[reclist->num_records] = thisrec;
2590 reclist->num_records++;
2592 *num = reclist->num_records;
2596 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
2599 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2600 bend_search_rr *bsrr =
2601 (bend_search_rr *)nmem_malloc (reqb->request_mem, sizeof(*bsrr));
2603 yaz_log(log_requestdetail, "Got SearchRequest.");
2605 bsrr->request = reqb;
2606 bsrr->association = assoc;
2607 bsrr->referenceId = req->referenceId;
2608 save_referenceId (reqb, bsrr->referenceId);
2609 bsrr->srw_sortKeys = 0;
2610 bsrr->srw_setname = 0;
2611 bsrr->srw_setnameIdleTime = 0;
2613 yaz_log (log_requestdetail, "ResultSet '%s'", req->resultSetName);
2614 if (req->databaseNames)
2617 for (i = 0; i < req->num_databaseNames; i++)
2618 yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
2621 yaz_log_zquery_level(log_requestdetail,req->query);
2623 if (assoc->init->bend_search)
2625 bsrr->setname = req->resultSetName;
2626 bsrr->replace_set = *req->replaceIndicator;
2627 bsrr->num_bases = req->num_databaseNames;
2628 bsrr->basenames = req->databaseNames;
2629 bsrr->query = req->query;
2630 bsrr->stream = assoc->encode;
2631 nmem_transfer(bsrr->stream->mem, reqb->request_mem);
2632 bsrr->decode = assoc->decode;
2633 bsrr->print = assoc->print;
2636 bsrr->errstring = NULL;
2637 bsrr->search_info = NULL;
2639 if (assoc->server && assoc->server->cql_transform
2640 && req->query->which == Z_Query_type_104
2641 && req->query->u.type_104->which == Z_External_CQL)
2643 /* have a CQL query and a CQL to PQF transform .. */
2645 cql2pqf(bsrr->stream, req->query->u.type_104->u.cql,
2646 assoc->server->cql_transform, bsrr->query);
2648 bsrr->errcode = yaz_diag_srw_to_bib1(srw_errcode);
2651 (assoc->init->bend_search)(assoc->backend, bsrr);
2652 if (!bsrr->request) /* backend not ready with the search response */
2653 return 0; /* should not be used any more */
2657 /* FIXME - make a diagnostic for it */
2658 yaz_log(YLOG_WARN,"Search not supported ?!?!");
2660 return response_searchRequest(assoc, reqb, bsrr, fd);
2663 int bend_searchresponse(void *handle, bend_search_rr *bsrr) {return 0;}
2666 * Prepare a searchresponse based on the backend results. We probably want
2667 * to look at making the fetching of records nonblocking as well, but
2668 * so far, we'll keep things simple.
2669 * If bsrt is null, that means we're called in response to a communications
2670 * event, and we'll have to get the response for ourselves.
2672 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
2673 bend_search_rr *bsrt, int *fd)
2675 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2676 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2677 Z_SearchResponse *resp = (Z_SearchResponse *)
2678 odr_malloc (assoc->encode, sizeof(*resp));
2679 int *nulint = odr_intdup (assoc->encode, 0);
2680 bool_t *sr = odr_intdup(assoc->encode, 1);
2681 int *next = odr_intdup(assoc->encode, 0);
2682 int *none = odr_intdup(assoc->encode, Z_SearchResponse_none);
2685 apdu->which = Z_APDU_searchResponse;
2686 apdu->u.searchResponse = resp;
2687 resp->referenceId = req->referenceId;
2688 resp->additionalSearchInfo = 0;
2689 resp->otherInfo = 0;
2691 if (!bsrt && !bend_searchresponse(assoc->backend, bsrt))
2693 yaz_log(YLOG_FATAL, "Bad result from backend");
2696 else if (bsrt->errcode)
2698 resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
2699 resp->resultCount = nulint;
2700 resp->numberOfRecordsReturned = nulint;
2701 resp->nextResultSetPosition = nulint;
2702 resp->searchStatus = nulint;
2703 resp->resultSetStatus = none;
2704 resp->presentStatus = 0;
2708 int *toget = odr_intdup(assoc->encode, 0);
2709 int *presst = odr_intdup(assoc->encode, 0);
2710 Z_RecordComposition comp, *compp = 0;
2712 yaz_log (log_requestdetail, "resultCount: %d", bsrt->hits);
2715 resp->resultCount = &bsrt->hits;
2717 comp.which = Z_RecordComp_simple;
2718 /* how many records does the user agent want, then? */
2719 if (bsrt->hits <= *req->smallSetUpperBound)
2721 *toget = bsrt->hits;
2722 if ((comp.u.simple = req->smallSetElementSetNames))
2725 else if (bsrt->hits < *req->largeSetLowerBound)
2727 *toget = *req->mediumSetPresentNumber;
2728 if (*toget > bsrt->hits)
2729 *toget = bsrt->hits;
2730 if ((comp.u.simple = req->mediumSetElementSetNames))
2736 if (*toget && !resp->records)
2741 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
2744 form = prefformat->value;
2746 /* Call bend_present if defined */
2747 if (assoc->init->bend_present)
2749 bend_present_rr *bprr = (bend_present_rr *)
2750 nmem_malloc (reqb->request_mem, sizeof(*bprr));
2751 bprr->setname = req->resultSetName;
2753 bprr->number = *toget;
2754 bprr->format = form;
2756 bprr->referenceId = req->referenceId;
2757 bprr->stream = assoc->encode;
2758 bprr->print = assoc->print;
2759 bprr->request = reqb;
2760 bprr->association = assoc;
2762 bprr->errstring = NULL;
2763 (*assoc->init->bend_present)(assoc->backend, bprr);
2769 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2770 *resp->presentStatus = Z_PresentStatus_failure;
2775 resp->records = pack_records(assoc, req->resultSetName, 1,
2776 toget, compp, next, presst, form, req->referenceId,
2777 req->preferredRecordSyntax, NULL);
2780 resp->numberOfRecordsReturned = toget;
2781 returnedrecs = *toget;
2782 resp->nextResultSetPosition = next;
2783 resp->searchStatus = sr;
2784 resp->resultSetStatus = 0;
2785 resp->presentStatus = presst;
2789 if (*resp->resultCount)
2791 resp->numberOfRecordsReturned = nulint;
2792 resp->nextResultSetPosition = next;
2793 resp->searchStatus = sr;
2794 resp->resultSetStatus = 0;
2795 resp->presentStatus = 0;
2798 resp->additionalSearchInfo = bsrt->search_info;
2803 WRBUF wr = wrbuf_alloc();
2805 for (i = 0 ; i < req->num_databaseNames; i++){
2807 wrbuf_printf(wr, "+");
2808 wrbuf_printf(wr, req->databaseNames[i]);
2810 wrbuf_printf(wr, " ");
2813 wrbuf_printf(wr, "ERROR %d", bsrt->errcode);
2815 wrbuf_printf(wr, "OK %d", bsrt->hits);
2816 wrbuf_printf(wr, " %s 1+%d ",
2817 req->resultSetName, returnedrecs);
2818 yaz_query_to_wrbuf(wr, req->query);
2820 yaz_log(log_request, "Search %s", wrbuf_buf(wr));
2827 * Maybe we got a little over-friendly when we designed bend_fetch to
2828 * get only one record at a time. Some backends can optimise multiple-record
2829 * fetches, and at any rate, there is some overhead involved in
2830 * all that selecting and hopping around. Problem is, of course, that the
2831 * frontend can't know ahead of time how many records it'll need to
2832 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
2833 * is downright lousy as a bulk data transfer protocol.
2835 * To start with, we'll do the fetching of records from the backend
2836 * in one operation: To save some trips in and out of the event-handler,
2837 * and to simplify the interface to pack_records. At any rate, asynch
2838 * operation is more fun in operations that have an unpredictable execution
2839 * speed - which is normally more true for search than for present.
2841 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
2844 Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
2848 Z_PresentResponse *resp;
2852 const char *errstring = 0;
2854 yaz_log(log_requestdetail, "Got PresentRequest.");
2856 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
2859 form = prefformat->value;
2860 resp = (Z_PresentResponse *)odr_malloc (assoc->encode, sizeof(*resp));
2862 resp->presentStatus = odr_intdup(assoc->encode, 0);
2863 if (assoc->init->bend_present)
2865 bend_present_rr *bprr = (bend_present_rr *)
2866 nmem_malloc (reqb->request_mem, sizeof(*bprr));
2867 bprr->setname = req->resultSetId;
2868 bprr->start = *req->resultSetStartPoint;
2869 bprr->number = *req->numberOfRecordsRequested;
2870 bprr->format = form;
2871 bprr->comp = req->recordComposition;
2872 bprr->referenceId = req->referenceId;
2873 bprr->stream = assoc->encode;
2874 bprr->print = assoc->print;
2875 bprr->request = reqb;
2876 bprr->association = assoc;
2878 bprr->errstring = NULL;
2879 (*assoc->init->bend_present)(assoc->backend, bprr);
2882 return 0; /* should not happen */
2885 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2886 *resp->presentStatus = Z_PresentStatus_failure;
2887 errcode = bprr->errcode;
2888 errstring = bprr->errstring;
2891 apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2892 next = odr_intdup(assoc->encode, 0);
2893 num = odr_intdup(assoc->encode, 0);
2895 apdu->which = Z_APDU_presentResponse;
2896 apdu->u.presentResponse = resp;
2897 resp->referenceId = req->referenceId;
2898 resp->otherInfo = 0;
2902 *num = *req->numberOfRecordsRequested;
2904 pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
2905 num, req->recordComposition, next,
2906 resp->presentStatus,
2907 form, req->referenceId, req->preferredRecordSyntax,
2912 WRBUF wr = wrbuf_alloc();
2913 wrbuf_printf(wr, "Present ");
2915 if (*resp->presentStatus == Z_PresentStatus_failure)
2916 wrbuf_printf(wr, "ERROR %d ", errcode);
2917 else if (*resp->presentStatus == Z_PresentStatus_success)
2918 wrbuf_printf(wr, "OK - ");
2920 wrbuf_printf(wr, "Partial %d - ", *resp->presentStatus);
2922 wrbuf_printf(wr, " %s %d+%d ",
2923 req->resultSetId, *req->resultSetStartPoint,
2924 *req->numberOfRecordsRequested);
2925 yaz_log(log_request, "%s", wrbuf_buf(wr) );
2930 resp->numberOfRecordsReturned = num;
2931 resp->nextResultSetPosition = next;
2937 * Scan was implemented rather in a hurry, and with support for only the basic
2938 * elements of the service in the backend API. Suggestions are welcome.
2940 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
2942 Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
2943 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2944 Z_ScanResponse *res = (Z_ScanResponse *)
2945 odr_malloc (assoc->encode, sizeof(*res));
2946 int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
2947 int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
2948 Z_ListEntries *ents = (Z_ListEntries *)
2949 odr_malloc (assoc->encode, sizeof(*ents));
2950 Z_DiagRecs *diagrecs_p = NULL;
2952 bend_scan_rr *bsrr = (bend_scan_rr *)
2953 odr_malloc (assoc->encode, sizeof(*bsrr));
2954 struct scan_entry *save_entries;
2956 yaz_log(log_requestdetail, "Got ScanRequest");
2958 apdu->which = Z_APDU_scanResponse;
2959 apdu->u.scanResponse = res;
2960 res->referenceId = req->referenceId;
2962 /* if step is absent, set it to 0 */
2963 res->stepSize = odr_intdup(assoc->encode, 0);
2965 *res->stepSize = *req->stepSize;
2967 res->scanStatus = scanStatus;
2968 res->numberOfEntriesReturned = numberOfEntriesReturned;
2969 res->positionOfTerm = 0;
2970 res->entries = ents;
2971 ents->num_entries = 0;
2972 ents->entries = NULL;
2973 ents->num_nonsurrogateDiagnostics = 0;
2974 ents->nonsurrogateDiagnostics = NULL;
2975 res->attributeSet = 0;
2978 if (req->databaseNames)
2981 for (i = 0; i < req->num_databaseNames; i++)
2982 yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
2984 bsrr->scanClause = 0;
2986 bsrr->errstring = 0;
2987 bsrr->num_bases = req->num_databaseNames;
2988 bsrr->basenames = req->databaseNames;
2989 bsrr->num_entries = *req->numberOfTermsRequested;
2990 bsrr->term = req->termListAndStartPoint;
2991 bsrr->referenceId = req->referenceId;
2992 bsrr->stream = assoc->encode;
2993 bsrr->print = assoc->print;
2994 bsrr->step_size = res->stepSize;
2996 /* For YAZ 2.0 and earlier it was the backend handler that
2997 initialized entries (member display_term did not exist)
2998 YAZ 2.0 and later sets 'entries' and initialize all members
2999 including 'display_term'. If YAZ 2.0 or later sees that
3000 entries was modified - we assume that it is an old handler and
3001 that 'display_term' is _not_ set.
3003 if (bsrr->num_entries > 0)
3006 bsrr->entries = odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
3008 for (i = 0; i<bsrr->num_entries; i++)
3010 bsrr->entries[i].term = 0;
3011 bsrr->entries[i].occurrences = 0;
3012 bsrr->entries[i].errcode = 0;
3013 bsrr->entries[i].errstring = 0;
3014 bsrr->entries[i].display_term = 0;
3017 save_entries = bsrr->entries; /* save it so we can compare later */
3019 if (req->attributeSet &&
3020 (attset = oid_getentbyoid(req->attributeSet)) &&
3021 (attset->oclass == CLASS_ATTSET || attset->oclass == CLASS_GENERAL))
3022 bsrr->attributeset = attset->value;
3024 bsrr->attributeset = VAL_NONE;
3025 log_scan_term_level (log_requestdetail, req->termListAndStartPoint,
3026 bsrr->attributeset);
3027 bsrr->term_position = req->preferredPositionInResponse ?
3028 *req->preferredPositionInResponse : 1;
3030 ((int (*)(void *, bend_scan_rr *))
3031 (*assoc->init->bend_scan))(assoc->backend, bsrr);
3034 diagrecs_p = zget_DiagRecs(assoc->encode,
3035 bsrr->errcode, bsrr->errstring);
3039 Z_Entry **tab = (Z_Entry **)
3040 odr_malloc (assoc->encode, sizeof(*tab) * bsrr->num_entries);
3042 if (bsrr->status == BEND_SCAN_PARTIAL)
3043 *scanStatus = Z_Scan_partial_5;
3045 *scanStatus = Z_Scan_success;
3046 ents->entries = tab;
3047 ents->num_entries = bsrr->num_entries;
3048 res->numberOfEntriesReturned = &ents->num_entries;
3049 res->positionOfTerm = &bsrr->term_position;
3050 for (i = 0; i < bsrr->num_entries; i++)
3056 tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
3057 if (bsrr->entries[i].occurrences >= 0)
3059 e->which = Z_Entry_termInfo;
3060 e->u.termInfo = t = (Z_TermInfo *)
3061 odr_malloc(assoc->encode, sizeof(*t));
3062 t->suggestedAttributes = 0;
3064 if (save_entries == bsrr->entries &&
3065 bsrr->entries[i].display_term)
3067 /* the entries was _not_ set by the handler. So it's
3068 safe to test for new member display_term. It is
3071 t->displayTerm = odr_strdup(assoc->encode,
3072 bsrr->entries[i].display_term);
3074 t->alternativeTerm = 0;
3075 t->byAttributes = 0;
3076 t->otherTermInfo = 0;
3077 t->globalOccurrences = &bsrr->entries[i].occurrences;
3078 t->term = (Z_Term *)
3079 odr_malloc(assoc->encode, sizeof(*t->term));
3080 t->term->which = Z_Term_general;
3081 t->term->u.general = o =
3082 (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
3083 o->buf = (unsigned char *)
3084 odr_malloc(assoc->encode, o->len = o->size =
3085 strlen(bsrr->entries[i].term));
3086 memcpy(o->buf, bsrr->entries[i].term, o->len);
3087 yaz_log(YLOG_DEBUG, " term #%d: '%s' (%d)", i,
3088 bsrr->entries[i].term, bsrr->entries[i].occurrences);
3092 Z_DiagRecs *drecs = zget_DiagRecs(assoc->encode,
3093 bsrr->entries[i].errcode,
3094 bsrr->entries[i].errstring);
3095 assert (drecs->num_diagRecs == 1);
3096 e->which = Z_Entry_surrogateDiagnostic;
3097 assert (drecs->diagRecs[0]);
3098 e->u.surrogateDiagnostic = drecs->diagRecs[0];
3104 ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
3105 ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
3110 WRBUF wr = wrbuf_alloc();
3111 wrbuf_printf(wr, "Scan ");
3112 for (i = 0 ; i < req->num_databaseNames; i++){
3114 wrbuf_printf(wr, "+");
3115 wrbuf_printf(wr, req->databaseNames[i]);
3117 wrbuf_printf(wr, " ");
3120 wr_diag(wr, bsrr->errcode, bsrr->errstring);
3121 wrbuf_printf(wr, " ");
3124 wrbuf_printf(wr, "OK ");
3125 /* else if (*res->scanStatus == Z_Scan_success) */
3126 /* wrbuf_printf(wr, "OK "); */
3128 /* wrbuf_printf(wr, "Partial "); */
3130 if (*res->numberOfEntriesReturned)
3131 wrbuf_printf(wr, "%d - ", *res->numberOfEntriesReturned);
3133 wrbuf_printf(wr, "0 - ");
3135 wrbuf_printf(wr, "%d+%d+%d ",
3136 (req->preferredPositionInResponse ?
3137 *req->preferredPositionInResponse : 1),
3138 *req->numberOfTermsRequested,
3139 (res->stepSize ? *res->stepSize : 1));
3141 yaz_scan_to_wrbuf(wr, req->termListAndStartPoint,
3142 bsrr->attributeset);
3143 yaz_log(log_request, "%s", wrbuf_buf(wr) );
3149 static Z_APDU *process_sortRequest(association *assoc, request *reqb,
3153 Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
3154 Z_SortResponse *res = (Z_SortResponse *)
3155 odr_malloc (assoc->encode, sizeof(*res));
3156 bend_sort_rr *bsrr = (bend_sort_rr *)
3157 odr_malloc (assoc->encode, sizeof(*bsrr));
3159 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
3161 yaz_log(log_requestdetail, "Got SortRequest.");
3163 bsrr->num_input_setnames = req->num_inputResultSetNames;
3164 for (i=0;i<req->num_inputResultSetNames;i++)
3165 yaz_log(log_requestdetail, "Input resultset: '%s'",
3166 req->inputResultSetNames[i]);
3167 bsrr->input_setnames = req->inputResultSetNames;
3168 bsrr->referenceId = req->referenceId;
3169 bsrr->output_setname = req->sortedResultSetName;
3170 yaz_log(log_requestdetail, "Output resultset: '%s'",
3171 req->sortedResultSetName);
3172 bsrr->sort_sequence = req->sortSequence;
3173 /*FIXME - dump those sequences too */
3174 bsrr->stream = assoc->encode;
3175 bsrr->print = assoc->print;
3177 bsrr->sort_status = Z_SortResponse_failure;
3179 bsrr->errstring = 0;
3181 (*assoc->init->bend_sort)(assoc->backend, bsrr);
3183 res->referenceId = bsrr->referenceId;
3184 res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
3185 res->resultSetStatus = 0;
3188 Z_DiagRecs *dr = zget_DiagRecs(assoc->encode,
3189 bsrr->errcode, bsrr->errstring);
3190 res->diagnostics = dr->diagRecs;
3191 res->num_diagnostics = dr->num_diagRecs;
3195 res->num_diagnostics = 0;
3196 res->diagnostics = 0;
3198 res->resultCount = 0;
3201 apdu->which = Z_APDU_sortResponse;
3202 apdu->u.sortResponse = res;
3205 WRBUF wr = wrbuf_alloc();
3206 wrbuf_printf(wr, "Sort ");
3208 wrbuf_printf(wr, " ERROR %d", bsrr->errcode);
3210 wrbuf_printf(wr, "OK -");
3211 wrbuf_printf(wr, " (");
3212 for (i = 0; i<req->num_inputResultSetNames; i++)
3215 wrbuf_printf(wr, "+");
3216 wrbuf_printf(wr, req->inputResultSetNames[i]);
3218 wrbuf_printf(wr, ")->%s ",req->sortedResultSetName);
3220 yaz_log(log_request, "%s", wrbuf_buf(wr) );
3226 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
3230 Z_DeleteResultSetRequest *req =
3231 reqb->apdu_request->u.deleteResultSetRequest;
3232 Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
3233 odr_malloc (assoc->encode, sizeof(*res));
3234 bend_delete_rr *bdrr = (bend_delete_rr *)
3235 odr_malloc (assoc->encode, sizeof(*bdrr));
3236 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
3238 yaz_log(log_requestdetail, "Got DeleteRequest.");
3240 bdrr->num_setnames = req->num_resultSetList;
3241 bdrr->setnames = req->resultSetList;
3242 for (i = 0; i<req->num_resultSetList; i++)
3243 yaz_log(log_requestdetail, "resultset: '%s'",
3244 req->resultSetList[i]);
3245 bdrr->stream = assoc->encode;
3246 bdrr->print = assoc->print;
3247 bdrr->function = *req->deleteFunction;
3248 bdrr->referenceId = req->referenceId;
3250 if (bdrr->num_setnames > 0)
3252 bdrr->statuses = (int*)
3253 odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
3254 bdrr->num_setnames);
3255 for (i = 0; i < bdrr->num_setnames; i++)
3256 bdrr->statuses[i] = 0;
3258 (*assoc->init->bend_delete)(assoc->backend, bdrr);
3260 res->referenceId = req->referenceId;
3262 res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
3264 res->deleteListStatuses = 0;
3265 if (bdrr->num_setnames > 0)
3268 res->deleteListStatuses = (Z_ListStatuses *)
3269 odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
3270 res->deleteListStatuses->num = bdrr->num_setnames;
3271 res->deleteListStatuses->elements =
3273 odr_malloc (assoc->encode,
3274 sizeof(*res->deleteListStatuses->elements) *
3275 bdrr->num_setnames);
3276 for (i = 0; i<bdrr->num_setnames; i++)
3278 res->deleteListStatuses->elements[i] =
3280 odr_malloc (assoc->encode,
3281 sizeof(**res->deleteListStatuses->elements));
3282 res->deleteListStatuses->elements[i]->status = bdrr->statuses+i;
3283 res->deleteListStatuses->elements[i]->id =
3284 odr_strdup (assoc->encode, bdrr->setnames[i]);
3287 res->numberNotDeleted = 0;
3288 res->bulkStatuses = 0;
3289 res->deleteMessage = 0;
3292 apdu->which = Z_APDU_deleteResultSetResponse;
3293 apdu->u.deleteResultSetResponse = res;
3296 WRBUF wr = wrbuf_alloc();
3297 wrbuf_printf(wr, "Delete ");
3298 if (bdrr->delete_status)
3299 wrbuf_printf(wr, "ERROR %d", bdrr->delete_status);
3301 wrbuf_printf(wr, "OK -");
3302 for (i = 0; i<req->num_resultSetList; i++)
3303 wrbuf_printf(wr, " %s ", req->resultSetList[i]);
3304 yaz_log(log_request, "%s", wrbuf_buf(wr) );
3310 static void process_close(association *assoc, request *reqb)
3312 Z_Close *req = reqb->apdu_request->u.close;
3313 static char *reasons[] =
3320 "securityViolation",
3327 yaz_log(log_requestdetail, "Got Close, reason %s, message %s",
3328 reasons[*req->closeReason], req->diagnosticInformation ?
3329 req->diagnosticInformation : "NULL");
3330 if (assoc->version < 3) /* to make do_force respond with close */
3332 do_close_req(assoc, Z_Close_finished,
3333 "Association terminated by client", reqb);
3334 yaz_log(log_request,"Close OK");
3337 void save_referenceId (request *reqb, Z_ReferenceId *refid)
3341 reqb->len_refid = refid->len;
3342 reqb->refid = (char *)nmem_malloc (reqb->request_mem, refid->len);
3343 memcpy (reqb->refid, refid->buf, refid->len);
3347 reqb->len_refid = 0;
3352 void bend_request_send (bend_association a, bend_request req, Z_APDU *res)
3354 process_z_response (a, req, res);
3357 bend_request bend_request_mk (bend_association a)
3359 request *nreq = request_get (&a->outgoing);
3360 nreq->request_mem = nmem_create ();
3364 Z_ReferenceId *bend_request_getid (ODR odr, bend_request req)
3369 id = (Odr_oct *)odr_malloc (odr, sizeof(*odr));
3370 id->buf = (unsigned char *)odr_malloc (odr, req->len_refid);
3371 id->len = id->size = req->len_refid;
3372 memcpy (id->buf, req->refid, req->len_refid);
3376 void bend_request_destroy (bend_request *req)
3378 nmem_destroy((*req)->request_mem);
3379 request_release(*req);
3383 int bend_backend_respond (bend_association a, bend_request req)
3387 r = process_z_request (a, req, &msg);
3389 yaz_log (YLOG_WARN, "%s", msg);
3393 void bend_request_setdata(bend_request r, void *p)
3398 void *bend_request_getdata(bend_request r)
3400 return r->clientData;
3403 static Z_APDU *process_segmentRequest (association *assoc, request *reqb)
3405 bend_segment_rr req;
3407 req.segment = reqb->apdu_request->u.segmentRequest;
3408 req.stream = assoc->encode;
3409 req.decode = assoc->decode;
3410 req.print = assoc->print;
3411 req.association = assoc;
3413 (*assoc->init->bend_segment)(assoc->backend, &req);
3418 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd)
3420 bend_esrequest_rr esrequest;
3421 const char *ext_name = "unknown";
3423 Z_ExtendedServicesRequest *req =
3424 reqb->apdu_request->u.extendedServicesRequest;
3425 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
3427 Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
3429 esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
3430 esrequest.stream = assoc->encode;
3431 esrequest.decode = assoc->decode;
3432 esrequest.print = assoc->print;
3433 esrequest.errcode = 0;
3434 esrequest.errstring = NULL;
3435 esrequest.request = reqb;
3436 esrequest.association = assoc;
3437 esrequest.taskPackage = 0;
3438 esrequest.referenceId = req->referenceId;
3441 if (esrequest.esr && esrequest.esr->taskSpecificParameters)
3443 switch(esrequest.esr->taskSpecificParameters->which)
3445 case Z_External_itemOrder:
3446 ext_name = "ItemOrder"; break;
3447 case Z_External_update:
3448 ext_name = "Update"; break;
3449 case Z_External_update0:
3450 ext_name = "Update0"; break;
3451 case Z_External_ESAdmin:
3452 ext_name = "Admin"; break;
3457 (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
3459 /* If the response is being delayed, return NULL */
3460 if (esrequest.request == NULL)
3463 resp->referenceId = req->referenceId;
3465 if (esrequest.errcode == -1)
3467 /* Backend service indicates request will be processed */
3468 yaz_log(log_request, "Extended Service: %s (accepted)", ext_name);
3469 *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
3471 else if (esrequest.errcode == 0)
3473 /* Backend service indicates request will be processed */
3474 yaz_log(log_request, "Extended Service: %s (done)", ext_name);
3475 *resp->operationStatus = Z_ExtendedServicesResponse_done;
3479 Z_DiagRecs *diagRecs =
3480 zget_DiagRecs(assoc->encode, esrequest.errcode,
3481 esrequest.errstring);
3482 /* Backend indicates error, request will not be processed */
3483 yaz_log(log_request, "Extended Service: %s (failed)", ext_name);
3484 *resp->operationStatus = Z_ExtendedServicesResponse_failure;
3485 resp->num_diagnostics = diagRecs->num_diagRecs;
3486 resp->diagnostics = diagRecs->diagRecs;
3489 WRBUF wr = wrbuf_alloc();
3490 wrbuf_diags(wr, resp->num_diagnostics, resp->diagnostics);
3491 yaz_log(log_request, "EsRequest %s", wrbuf_buf(wr) );
3496 /* Do something with the members of bend_extendedservice */
3497 if (esrequest.taskPackage)
3498 resp->taskPackage = z_ext_record (assoc->encode, VAL_EXTENDED,
3499 (const char *) esrequest.taskPackage,
3501 yaz_log(YLOG_DEBUG,"Send the result apdu");
3508 * indent-tabs-mode: nil
3510 * vim: shiftwidth=4 tabstop=8 expandtab