2 * Copyright (C) 1995-2005, Index Data ApS
3 * See the file LICENSE for details.
5 * $Id: seshigh.c,v 1.95 2006-07-31 12:15:02 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);
351 else if (res == 1) /* incomplete read - wait for more */
353 if (conn->io_pending & CS_WANT_WRITE)
354 assoc->cs_get_mask |= EVENT_OUTPUT;
355 iochan_setflag(h, assoc->cs_get_mask);
358 if (cs_more(conn)) /* more stuff - call us again later, please */
359 iochan_setevent(h, EVENT_INPUT);
361 /* we got a complete PDU. Let's decode it */
362 yaz_log(YLOG_DEBUG, "Got PDU, %d bytes: lead=%02X %02X %02X", res,
363 assoc->input_buffer[0] & 0xff,
364 assoc->input_buffer[1] & 0xff,
365 assoc->input_buffer[2] & 0xff);
366 req = request_get(&assoc->incoming); /* get a new request */
367 odr_reset(assoc->decode);
368 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
369 if (!z_GDU(assoc->decode, &req->gdu_request, 0, 0))
371 yaz_log(YLOG_WARN, "ODR error on incoming PDU: %s [element %s] "
373 odr_errmsg(odr_geterror(assoc->decode)),
374 odr_getelement(assoc->decode),
375 (long) odr_offset(assoc->decode));
376 if (assoc->decode->error != OHTTP)
378 yaz_log(YLOG_WARN, "PDU dump:");
379 odr_dumpBER(yaz_log_file(), assoc->input_buffer, res);
380 request_release(req);
381 do_close(assoc, Z_Close_protocolError,"Malformed package");
385 Z_GDU *p = z_get_HTTP_Response(assoc->encode, 400);
386 assoc->state = ASSOC_DEAD;
387 process_gdu_response(assoc, req, p);
391 req->request_mem = odr_extract_mem(assoc->decode);
394 if (!z_GDU(assoc->print, &req->gdu_request, 0, 0))
395 yaz_log(YLOG_WARN, "ODR print error: %s",
396 odr_errmsg(odr_geterror(assoc->print)));
397 odr_reset(assoc->print);
399 request_enq(&assoc->incoming, req);
402 /* can we do something yet? */
403 req = request_head(&assoc->incoming);
404 if (req->state == REQUEST_IDLE)
406 request_deq(&assoc->incoming);
407 process_gdu_request(assoc, req);
410 if (event & assoc->cs_put_mask)
412 request *req = request_head(&assoc->outgoing);
414 assoc->cs_put_mask = 0;
415 yaz_log(YLOG_DEBUG, "ir_session (output)");
416 req->state = REQUEST_PENDING;
417 switch (res = cs_put(conn, req->response, req->len_response))
420 yaz_log(log_sessiondetail, "Connection closed by client");
422 destroy_association(assoc);
425 case 0: /* all sent - release the request structure */
426 yaz_log(YLOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
428 yaz_log(YLOG_DEBUG, "HTTP out:\n%.*s", req->len_response,
431 nmem_destroy(req->request_mem);
432 request_deq(&assoc->outgoing);
433 request_release(req);
434 if (!request_head(&assoc->outgoing))
435 { /* restore mask for cs_get operation ... */
436 iochan_clearflag(h, EVENT_OUTPUT|EVENT_INPUT);
437 iochan_setflag(h, assoc->cs_get_mask);
438 if (assoc->state == ASSOC_DEAD)
439 iochan_setevent(assoc->client_chan, EVENT_TIMEOUT);
443 assoc->cs_put_mask = EVENT_OUTPUT;
447 if (conn->io_pending & CS_WANT_WRITE)
448 assoc->cs_put_mask |= EVENT_OUTPUT;
449 if (conn->io_pending & CS_WANT_READ)
450 assoc->cs_put_mask |= EVENT_INPUT;
451 iochan_setflag(h, assoc->cs_put_mask);
454 if (event & EVENT_EXCEPT)
456 yaz_log(YLOG_WARN, "ir_session (exception)");
458 destroy_association(assoc);
463 static int process_z_request(association *assoc, request *req, char **msg);
466 static void assoc_init_reset(association *assoc)
469 assoc->init = (bend_initrequest *) xmalloc (sizeof(*assoc->init));
471 assoc->init->stream = assoc->encode;
472 assoc->init->print = assoc->print;
473 assoc->init->auth = 0;
474 assoc->init->referenceId = 0;
475 assoc->init->implementation_version = 0;
476 assoc->init->implementation_id = 0;
477 assoc->init->implementation_name = 0;
478 assoc->init->bend_sort = NULL;
479 assoc->init->bend_search = NULL;
480 assoc->init->bend_present = NULL;
481 assoc->init->bend_esrequest = NULL;
482 assoc->init->bend_delete = NULL;
483 assoc->init->bend_scan = NULL;
484 assoc->init->bend_segment = NULL;
485 assoc->init->bend_fetch = NULL;
486 assoc->init->bend_explain = NULL;
487 assoc->init->bend_srw_scan = NULL;
488 assoc->init->bend_srw_update = NULL;
490 assoc->init->charneg_request = NULL;
491 assoc->init->charneg_response = NULL;
493 assoc->init->decode = assoc->decode;
494 assoc->init->peer_name =
495 odr_strdup (assoc->encode, cs_addrstr(assoc->client_link));
497 yaz_log(log_requestdetail, "peer %s", assoc->init->peer_name);
500 static int srw_bend_init(association *assoc, Z_SRW_diagnostic **d, int *num, Z_SRW_PDU *sr)
502 statserv_options_block *cb = statserv_getcontrol();
505 const char *encoding = "UTF-8";
507 bend_initresult *binitres;
509 yaz_log(log_requestdetail, "srw_bend_init config=%s", cb->configname);
510 assoc_init_reset(assoc);
512 assoc->maximumRecordSize = 3000000;
513 assoc->preferredMessageSize = 3000000;
517 Z_IdAuthentication *auth = odr_malloc(assoc->decode, sizeof(*auth));
520 len = strlen(sr->username) + 1;
522 len += strlen(sr->password) + 2;
523 auth->which = Z_IdAuthentication_open;
524 auth->u.open = odr_malloc(assoc->decode, len);
525 strcpy(auth->u.open, sr->username);
526 if (sr->password && *sr->password)
528 strcat(auth->u.open, "/");
529 strcat(auth->u.open, sr->password);
531 assoc->init->auth = auth;
535 ce = yaz_set_proposal_charneg(assoc->decode, &encoding, 1, 0, 0, 1);
536 assoc->init->charneg_request = ce->u.charNeg3;
539 if (!(binitres = (*cb->bend_init)(assoc->init)))
541 assoc->state = ASSOC_DEAD;
542 yaz_add_srw_diagnostic(assoc->encode, d, num,
543 YAZ_SRW_AUTHENTICATION_ERROR, 0);
546 assoc->backend = binitres->handle;
547 assoc->init->auth = 0;
548 if (binitres->errcode)
550 int srw_code = yaz_diag_bib1_to_srw(binitres->errcode);
551 assoc->state = ASSOC_DEAD;
552 yaz_add_srw_diagnostic(assoc->encode, d, num, srw_code,
553 binitres->errstring);
561 static const char *get_esn(Z_RecordComposition *comp)
563 if (comp && comp->which == Z_RecordComp_complex)
565 if (comp->u.complex->generic
566 && comp->u.complex->generic->elementSpec
567 && (comp->u.complex->generic->elementSpec->which ==
568 Z_ElementSpec_elementSetName))
569 return comp->u.complex->generic->elementSpec->u.elementSetName;
571 else if (comp && comp->which == Z_RecordComp_simple &&
572 comp->u.simple->which == Z_ElementSetNames_generic)
573 return comp->u.simple->u.generic;
577 static void set_esn(Z_RecordComposition **comp_p, const char *esn, NMEM nmem)
579 Z_RecordComposition *comp = nmem_malloc(nmem, sizeof(*comp));
581 comp->which = Z_RecordComp_simple;
582 comp->u.simple = nmem_malloc(nmem, sizeof(*comp->u.simple));
583 comp->u.simple->which = Z_ElementSetNames_generic;
584 comp->u.simple->u.generic = nmem_strdup(nmem, esn);
588 static int retrieve_fetch(association *assoc, bend_fetch_rr *rr)
591 yaz_record_conv_t rc = 0;
592 const char *match_schema = 0;
593 int *match_syntax = 0;
598 const char *input_schema = get_esn(rr->comp);
599 Odr_oid *input_syntax_raw = rr->request_format_raw;
601 const char *backend_schema = 0;
602 Odr_oid *backend_syntax = 0;
604 r = yaz_retrieval_request(assoc->server->retrieval,
612 if (r == -1) /* error ? */
614 const char *details = yaz_retrieval_get_error(
615 assoc->server->retrieval);
617 rr->errcode = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
619 rr->errstring = odr_strdup(rr->stream, details);
622 else if (r == 1 || r == 3)
624 const char *details = input_schema;
625 rr->errcode = YAZ_BIB1_ELEMENT_SET_NAMES_UNSUPP;
627 rr->errstring = odr_strdup(rr->stream, details);
632 rr->errcode = YAZ_BIB1_RECORD_SYNTAX_UNSUPP;
633 if (input_syntax_raw)
635 char oidbuf[OID_STR_MAX];
636 oid_to_dotstring(input_syntax_raw, oidbuf);
637 rr->errstring = odr_strdup(rr->stream, oidbuf);
643 set_esn(&rr->comp, backend_schema, rr->stream->mem);
647 oident *oident_syntax = oid_getentbyoid(backend_syntax);
649 rr->request_format_raw = backend_syntax;
652 rr->request_format = oident_syntax->value;
654 rr->request_format = VAL_NONE;
657 (*assoc->init->bend_fetch)(assoc->backend, rr);
658 if (rc && rr->record && rr->errcode == 0 && rr->len > 0)
659 { /* post conversion must take place .. */
660 WRBUF output_record = wrbuf_alloc();
661 int r = yaz_record_conv_record(rc, rr->record, rr->len, output_record);
664 const char *details = yaz_record_conv_get_error(rc);
665 rr->errcode = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
667 rr->errstring = odr_strdup(rr->stream, details);
671 rr->len = wrbuf_len(output_record);
672 rr->record = odr_malloc(rr->stream, rr->len);
673 memcpy(rr->record, wrbuf_buf(output_record), rr->len);
675 wrbuf_free(output_record, 1);
679 struct oident *oi = oid_getentbyoid(match_syntax);
680 rr->output_format = oi ? oi->value : VAL_NONE;
681 rr->output_format_raw = match_syntax;
684 rr->schema = odr_strdup(rr->stream, match_schema);
687 (*assoc->init->bend_fetch)(assoc->backend, rr);
691 static int srw_bend_fetch(association *assoc, int pos,
692 Z_SRW_searchRetrieveRequest *srw_req,
693 Z_SRW_record *record,
694 const char **addinfo)
697 ODR o = assoc->encode;
699 rr.setname = "default";
702 rr.request_format = VAL_TEXT_XML;
703 rr.request_format_raw = yaz_oidval_to_z3950oid(assoc->decode,
706 rr.comp = (Z_RecordComposition *)
707 odr_malloc(assoc->decode, sizeof(*rr.comp));
708 rr.comp->which = Z_RecordComp_complex;
709 rr.comp->u.complex = (Z_CompSpec *)
710 odr_malloc(assoc->decode, sizeof(Z_CompSpec));
711 rr.comp->u.complex->selectAlternativeSyntax = (bool_t *)
712 odr_malloc(assoc->encode, sizeof(bool_t));
713 *rr.comp->u.complex->selectAlternativeSyntax = 0;
714 rr.comp->u.complex->num_dbSpecific = 0;
715 rr.comp->u.complex->dbSpecific = 0;
716 rr.comp->u.complex->num_recordSyntax = 0;
717 rr.comp->u.complex->recordSyntax = 0;
719 rr.comp->u.complex->generic = (Z_Specification *)
720 odr_malloc(assoc->decode, sizeof(Z_Specification));
722 /* schema uri = recordSchema (or NULL if recordSchema is not given) */
723 rr.comp->u.complex->generic->which = Z_Schema_uri;
724 rr.comp->u.complex->generic->schema.uri = srw_req->recordSchema;
726 /* ESN = recordSchema if recordSchema is present */
727 rr.comp->u.complex->generic->elementSpec = 0;
728 if (srw_req->recordSchema)
730 rr.comp->u.complex->generic->elementSpec =
731 (Z_ElementSpec *) odr_malloc(assoc->encode, sizeof(Z_ElementSpec));
732 rr.comp->u.complex->generic->elementSpec->which =
733 Z_ElementSpec_elementSetName;
734 rr.comp->u.complex->generic->elementSpec->u.elementSetName =
735 srw_req->recordSchema;
738 rr.stream = assoc->encode;
739 rr.print = assoc->print;
747 rr.surrogate_flag = 0;
748 rr.schema = srw_req->recordSchema;
750 if (!assoc->init->bend_fetch)
753 retrieve_fetch(assoc, &rr);
755 if (rr.errcode && rr.surrogate_flag)
757 int code = yaz_diag_bib1_to_srw(rr.errcode);
758 const char *message = yaz_diag_srw_str(code);
761 len += strlen(message);
763 len += strlen(rr.errstring);
765 record->recordData_buf = odr_malloc(o, len);
767 sprintf(record->recordData_buf, "<diagnostic "
768 "xmlns=\"http://www.loc.gov/zing/srw/diagnostic/\">\n"
769 " <uri>info:srw/diagnostic/1/%d</uri>\n", code);
771 sprintf(record->recordData_buf + strlen(record->recordData_buf),
772 " <details>%s</details>\n", rr.errstring);
774 sprintf(record->recordData_buf + strlen(record->recordData_buf),
775 " <message>%s</message>\n", message);
776 sprintf(record->recordData_buf + strlen(record->recordData_buf),
778 record->recordData_len = strlen(record->recordData_buf);
779 record->recordPosition = odr_intdup(o, pos);
780 record->recordSchema = "info:srw/schema/1/diagnostics-v1.1";
783 else if (rr.len >= 0)
785 record->recordData_buf = rr.record;
786 record->recordData_len = rr.len;
787 record->recordPosition = odr_intdup(o, pos);
789 record->recordSchema = odr_strdup(o, rr.schema);
791 record->recordSchema = 0;
795 *addinfo = rr.errstring;
801 static int cql2pqf(ODR odr, const char *cql, cql_transform_t ct,
802 Z_Query *query_result)
804 /* have a CQL query and CQL to PQF transform .. */
805 CQL_parser cp = cql_parser_create();
811 r = cql_parser_string(cp, cql);
814 /* CQL syntax error */
820 r = cql_transform_buf(ct,
821 cql_parser_result(cp),
822 rpn_buf, sizeof(rpn_buf)-1);
824 srw_errcode = cql_transform_error(ct, &add);
828 /* Syntax & transform OK. */
829 /* Convert PQF string to Z39.50 to RPN query struct */
830 YAZ_PQF_Parser pp = yaz_pqf_create();
831 Z_RPNQuery *rpnquery = yaz_pqf_parse(pp, odr, rpn_buf);
836 int code = yaz_pqf_error(pp, &pqf_msg, &off);
837 yaz_log(YLOG_WARN, "PQF Parser Error %s (code %d)",
843 query_result->which = Z_Query_type_1;
844 query_result->u.type_1 = rpnquery;
848 cql_parser_destroy(cp);
852 static int cql2pqf_scan(ODR odr, const char *cql, cql_transform_t ct,
853 Z_AttributesPlusTerm *result)
857 int srw_error = cql2pqf(odr, cql, ct, &query);
860 if (query.which != Z_Query_type_1 && query.which != Z_Query_type_101)
861 return 10; /* bad query type */
862 rpn = query.u.type_1;
863 if (!rpn->RPNStructure)
864 return 10; /* must be structure */
865 if (rpn->RPNStructure->which != Z_RPNStructure_simple)
866 return 10; /* must be simple */
867 if (rpn->RPNStructure->u.simple->which != Z_Operand_APT)
868 return 10; /* must be attributes plus term node .. */
869 memcpy(result, rpn->RPNStructure->u.simple->u.attributesPlusTerm,
874 static void srw_bend_search(association *assoc, request *req,
876 Z_SRW_searchRetrieveResponse *srw_res,
881 Z_SRW_searchRetrieveRequest *srw_req = sr->u.request;
884 yaz_log(log_requestdetail, "Got SRW SearchRetrieveRequest");
885 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
886 if (srw_res->num_diagnostics == 0 && assoc->init)
889 rr.setname = "default";
892 rr.basenames = &srw_req->database;
896 rr.srw_setnameIdleTime = 0;
897 rr.query = (Z_Query *) odr_malloc (assoc->decode, sizeof(*rr.query));
898 rr.query->u.type_1 = 0;
900 if (srw_req->query_type == Z_SRW_query_type_cql)
902 if (assoc->server && assoc->server->cql_transform)
904 int srw_errcode = cql2pqf(assoc->encode, srw_req->query.cql,
905 assoc->server->cql_transform,
909 yaz_add_srw_diagnostic(assoc->encode,
910 &srw_res->diagnostics,
911 &srw_res->num_diagnostics,
917 /* CQL query to backend. Wrap it - Z39.50 style */
918 ext = (Z_External *) odr_malloc(assoc->decode, sizeof(*ext));
919 ext->direct_reference = odr_getoidbystr(assoc->decode,
920 "1.2.840.10003.16.2");
921 ext->indirect_reference = 0;
923 ext->which = Z_External_CQL;
924 ext->u.cql = srw_req->query.cql;
926 rr.query->which = Z_Query_type_104;
927 rr.query->u.type_104 = ext;
930 else if (srw_req->query_type == Z_SRW_query_type_pqf)
932 Z_RPNQuery *RPNquery;
933 YAZ_PQF_Parser pqf_parser;
935 pqf_parser = yaz_pqf_create ();
937 RPNquery = yaz_pqf_parse (pqf_parser, assoc->decode,
943 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
944 yaz_log(log_requestdetail, "Parse error %d %s near offset %ld",
945 code, pqf_msg, (long) off);
946 srw_error = YAZ_SRW_QUERY_SYNTAX_ERROR;
949 rr.query->which = Z_Query_type_1;
950 rr.query->u.type_1 = RPNquery;
952 yaz_pqf_destroy (pqf_parser);
956 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
957 &srw_res->num_diagnostics,
958 YAZ_SRW_UNSUPP_QUERY_TYPE, 0);
960 if (rr.query->u.type_1)
962 rr.stream = assoc->encode;
963 rr.decode = assoc->decode;
964 rr.print = assoc->print;
966 if ( srw_req->sort.sortKeys )
967 rr.srw_sortKeys = odr_strdup(assoc->encode,
968 srw_req->sort.sortKeys );
969 rr.association = assoc;
975 yaz_log_zquery_level(log_requestdetail,rr.query);
977 (assoc->init->bend_search)(assoc->backend, &rr);
980 if (rr.errcode == YAZ_BIB1_DATABASE_UNAVAILABLE)
986 srw_error = yaz_diag_bib1_to_srw (rr.errcode);
987 yaz_add_srw_diagnostic(assoc->encode,
988 &srw_res->diagnostics,
989 &srw_res->num_diagnostics,
990 srw_error, rr.errstring);
995 int number = srw_req->maximumRecords ? *srw_req->maximumRecords : 0;
996 int start = srw_req->startRecord ? *srw_req->startRecord : 1;
998 yaz_log(log_requestdetail, "Request to pack %d+%d out of %d",
999 start, number, rr.hits);
1001 srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
1004 srw_res->resultSetId =
1005 odr_strdup(assoc->encode, rr.srw_setname );
1006 srw_res->resultSetIdleTime =
1007 odr_intdup(assoc->encode, *rr.srw_setnameIdleTime );
1013 if (start > rr.hits)
1015 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1016 &srw_res->num_diagnostics,
1017 YAZ_SRW_FIRST_RECORD_POSITION_OUT_OF_RANGE, 0);
1022 if (start + number > rr.hits)
1023 number = rr.hits - start + 1;
1025 /* Call bend_present if defined */
1026 if (assoc->init->bend_present)
1028 bend_present_rr *bprr = (bend_present_rr*)
1029 odr_malloc (assoc->decode, sizeof(*bprr));
1030 bprr->setname = "default";
1031 bprr->start = start;
1032 bprr->number = number;
1033 bprr->format = VAL_TEXT_XML;
1034 if (srw_req->recordSchema)
1036 bprr->comp = (Z_RecordComposition *) odr_malloc(assoc->decode,
1037 sizeof(*bprr->comp));
1038 bprr->comp->which = Z_RecordComp_simple;
1039 bprr->comp->u.simple = (Z_ElementSetNames *)
1040 odr_malloc(assoc->decode, sizeof(Z_ElementSetNames));
1041 bprr->comp->u.simple->which = Z_ElementSetNames_generic;
1042 bprr->comp->u.simple->u.generic = srw_req->recordSchema;
1048 bprr->stream = assoc->encode;
1049 bprr->referenceId = 0;
1050 bprr->print = assoc->print;
1051 bprr->request = req;
1052 bprr->association = assoc;
1054 bprr->errstring = NULL;
1055 (*assoc->init->bend_present)(assoc->backend, bprr);
1061 srw_error = yaz_diag_bib1_to_srw (bprr->errcode);
1062 yaz_add_srw_diagnostic(assoc->encode,
1063 &srw_res->diagnostics,
1064 &srw_res->num_diagnostics,
1065 srw_error, bprr->errstring);
1073 int packing = Z_SRW_recordPacking_string;
1074 if (srw_req->recordPacking){
1075 if (!strcmp(srw_req->recordPacking, "xml"))
1076 packing = Z_SRW_recordPacking_XML;
1077 if (!strcmp(srw_req->recordPacking, "url"))
1078 packing = Z_SRW_recordPacking_URL;
1080 srw_res->records = (Z_SRW_record *)
1081 odr_malloc(assoc->encode,
1082 number * sizeof(*srw_res->records));
1084 srw_res->extra_records = (Z_SRW_extra_record **)
1085 odr_malloc(assoc->encode,
1086 number*sizeof(*srw_res->extra_records));
1088 for (i = 0; i<number; i++)
1091 const char *addinfo = 0;
1093 srw_res->records[j].recordPacking = packing;
1094 srw_res->records[j].recordData_buf = 0;
1095 srw_res->extra_records[j] = 0;
1096 yaz_log(YLOG_DEBUG, "srw_bend_fetch %d", i+start);
1097 errcode = srw_bend_fetch(assoc, i+start, srw_req,
1098 srw_res->records + j,
1102 yaz_add_srw_diagnostic(assoc->encode,
1103 &srw_res->diagnostics,
1104 &srw_res->num_diagnostics,
1105 yaz_diag_bib1_to_srw (errcode),
1110 if (srw_res->records[j].recordData_buf)
1113 srw_res->num_records = j;
1115 srw_res->records = 0;
1124 const char *querystr = "?";
1125 const char *querytype = "?";
1126 WRBUF wr = wrbuf_alloc();
1128 switch (srw_req->query_type)
1130 case Z_SRW_query_type_cql:
1132 querystr = srw_req->query.cql;
1134 case Z_SRW_query_type_pqf:
1136 querystr = srw_req->query.pqf;
1139 wrbuf_printf(wr, "SRWSearch ");
1140 wrbuf_printf(wr, srw_req->database);
1141 wrbuf_printf(wr, " ");
1142 if (srw_res->num_diagnostics)
1143 wrbuf_printf(wr, "ERROR %s", srw_res->diagnostics[0].uri);
1144 else if (*http_code != 200)
1145 wrbuf_printf(wr, "ERROR info:http/%d", *http_code);
1146 else if (srw_res->numberOfRecords)
1148 wrbuf_printf(wr, "OK %d",
1149 (srw_res->numberOfRecords ?
1150 *srw_res->numberOfRecords : 0));
1152 wrbuf_printf(wr, " %s %d+%d",
1153 (srw_res->resultSetId ?
1154 srw_res->resultSetId : "-"),
1155 (srw_req->startRecord ? *srw_req->startRecord : 1),
1156 srw_res->num_records);
1157 yaz_log(log_request, "%s %s: %s", wrbuf_buf(wr), querytype, querystr);
1162 static char *srw_bend_explain_default(void *handle, bend_explain_rr *rr)
1165 xmlNodePtr ptr = rr->server_node_ptr;
1168 for (ptr = ptr->children; ptr; ptr = ptr->next)
1170 if (ptr->type != XML_ELEMENT_NODE)
1172 if (!strcmp((const char *) ptr->name, "explain"))
1175 xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
1179 ptr = xmlCopyNode(ptr, 1);
1181 xmlDocSetRootElement(doc, ptr);
1183 xmlDocDumpMemory(doc, &buf_out, &len);
1184 content = (char*) odr_malloc(rr->stream, 1+len);
1185 memcpy(content, buf_out, len);
1186 content[len] = '\0';
1190 rr->explain_buf = content;
1198 static void srw_bend_explain(association *assoc, request *req,
1200 Z_SRW_explainResponse *srw_res,
1203 Z_SRW_explainRequest *srw_req = sr->u.explain_request;
1204 yaz_log(log_requestdetail, "Got SRW ExplainRequest");
1206 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1211 rr.stream = assoc->encode;
1212 rr.decode = assoc->decode;
1213 rr.print = assoc->print;
1215 rr.database = srw_req->database;
1217 rr.server_node_ptr = assoc->server->server_node_ptr;
1219 rr.server_node_ptr = 0;
1220 rr.schema = "http://explain.z3950.org/dtd/2.0/";
1221 if (assoc->init->bend_explain)
1222 (*assoc->init->bend_explain)(assoc->backend, &rr);
1224 srw_bend_explain_default(assoc->backend, &rr);
1228 int packing = Z_SRW_recordPacking_string;
1229 if (srw_req->recordPacking)
1231 if (!strcmp(srw_req->recordPacking, "xml"))
1232 packing = Z_SRW_recordPacking_XML;
1233 else if (!strcmp(srw_req->recordPacking, "url"))
1234 packing = Z_SRW_recordPacking_URL;
1236 srw_res->record.recordSchema = rr.schema;
1237 srw_res->record.recordPacking = packing;
1238 srw_res->record.recordData_buf = rr.explain_buf;
1239 srw_res->record.recordData_len = strlen(rr.explain_buf);
1240 srw_res->record.recordPosition = 0;
1246 static void srw_bend_scan(association *assoc, request *req,
1248 Z_SRW_scanResponse *srw_res,
1251 Z_SRW_scanRequest *srw_req = sr->u.scan_request;
1252 yaz_log(log_requestdetail, "Got SRW ScanRequest");
1255 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1256 if (srw_res->num_diagnostics == 0 && assoc->init)
1258 struct scan_entry *save_entries;
1260 bend_scan_rr *bsrr = (bend_scan_rr *)
1261 odr_malloc (assoc->encode, sizeof(*bsrr));
1262 bsrr->num_bases = 1;
1263 bsrr->basenames = &srw_req->database;
1265 bsrr->num_entries = srw_req->maximumTerms ?
1266 *srw_req->maximumTerms : 10;
1267 bsrr->term_position = srw_req->responsePosition ?
1268 *srw_req->responsePosition : 1;
1271 bsrr->errstring = 0;
1272 bsrr->referenceId = 0;
1273 bsrr->stream = assoc->encode;
1274 bsrr->print = assoc->print;
1275 bsrr->step_size = odr_intdup(assoc->decode, 0);
1278 if (bsrr->num_entries > 0)
1281 bsrr->entries = odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
1283 for (i = 0; i<bsrr->num_entries; i++)
1285 bsrr->entries[i].term = 0;
1286 bsrr->entries[i].occurrences = 0;
1287 bsrr->entries[i].errcode = 0;
1288 bsrr->entries[i].errstring = 0;
1289 bsrr->entries[i].display_term = 0;
1292 save_entries = bsrr->entries; /* save it so we can compare later */
1294 if (srw_req->query_type == Z_SRW_query_type_pqf &&
1295 assoc->init->bend_scan)
1297 Odr_oid *scan_attributeSet = 0;
1299 YAZ_PQF_Parser pqf_parser = yaz_pqf_create();
1301 bsrr->term = yaz_pqf_scan(pqf_parser, assoc->decode,
1303 srw_req->scanClause.pqf);
1304 if (scan_attributeSet &&
1305 (attset = oid_getentbyoid(scan_attributeSet)) &&
1306 (attset->oclass == CLASS_ATTSET ||
1307 attset->oclass == CLASS_GENERAL))
1308 bsrr->attributeset = attset->value;
1310 bsrr->attributeset = VAL_NONE;
1311 yaz_pqf_destroy(pqf_parser);
1312 bsrr->scanClause = 0;
1313 ((int (*)(void *, bend_scan_rr *))
1314 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1316 else if (srw_req->query_type == Z_SRW_query_type_cql
1317 && assoc->init->bend_scan && assoc->server
1318 && assoc->server->cql_transform)
1321 bsrr->scanClause = 0;
1322 bsrr->attributeset = VAL_NONE;
1323 bsrr->term = odr_malloc(assoc->decode, sizeof(*bsrr->term));
1324 srw_error = cql2pqf_scan(assoc->encode,
1325 srw_req->scanClause.cql,
1326 assoc->server->cql_transform,
1329 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1330 &srw_res->num_diagnostics,
1334 ((int (*)(void *, bend_scan_rr *))
1335 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1338 else if (srw_req->query_type == Z_SRW_query_type_cql
1339 && assoc->init->bend_srw_scan)
1342 bsrr->attributeset = VAL_NONE;
1343 bsrr->scanClause = srw_req->scanClause.cql;
1344 ((int (*)(void *, bend_scan_rr *))
1345 (*assoc->init->bend_srw_scan))(assoc->backend, bsrr);
1349 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1350 &srw_res->num_diagnostics,
1351 YAZ_SRW_UNSUPP_OPERATION, "scan");
1356 if (bsrr->errcode == YAZ_BIB1_DATABASE_UNAVAILABLE)
1361 srw_error = yaz_diag_bib1_to_srw (bsrr->errcode);
1363 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1364 &srw_res->num_diagnostics,
1365 srw_error, bsrr->errstring);
1367 else if (srw_res->num_diagnostics == 0 && bsrr->num_entries)
1370 srw_res->terms = (Z_SRW_scanTerm*)
1371 odr_malloc(assoc->encode, sizeof(*srw_res->terms) *
1374 srw_res->num_terms = bsrr->num_entries;
1375 for (i = 0; i<bsrr->num_entries; i++)
1377 Z_SRW_scanTerm *t = srw_res->terms + i;
1378 t->value = odr_strdup(assoc->encode, bsrr->entries[i].term);
1379 t->numberOfRecords =
1380 odr_intdup(assoc->encode, bsrr->entries[i].occurrences);
1382 if (save_entries == bsrr->entries &&
1383 bsrr->entries[i].display_term)
1385 /* the entries was _not_ set by the handler. So it's
1386 safe to test for new member display_term. It is
1389 t->displayTerm = odr_strdup(assoc->encode,
1390 bsrr->entries[i].display_term);
1398 WRBUF wr = wrbuf_alloc();
1399 const char *querytype = 0;
1400 const char *querystr = 0;
1402 switch(srw_req->query_type)
1404 case Z_SRW_query_type_pqf:
1406 querystr = srw_req->scanClause.pqf;
1408 case Z_SRW_query_type_cql:
1410 querystr = srw_req->scanClause.cql;
1413 querytype = "UNKNOWN";
1417 wrbuf_printf(wr, "SRWScan ");
1418 wrbuf_printf(wr, srw_req->database);
1419 wrbuf_printf(wr, " ");
1421 if (srw_res->num_diagnostics)
1422 wrbuf_printf(wr, "ERROR %s - ", srw_res->diagnostics[0].uri);
1423 else if (srw_res->num_terms)
1424 wrbuf_printf(wr, "OK %d - ", srw_res->num_terms);
1426 wrbuf_printf(wr, "OK - - ");
1428 wrbuf_printf(wr, "%d+%d+0 ",
1429 (srw_req->responsePosition ?
1430 *srw_req->responsePosition : 1),
1431 (srw_req->maximumTerms ?
1432 *srw_req->maximumTerms : 1));
1433 /* there is no step size in SRU/W ??? */
1434 wrbuf_printf(wr, "%s: %s ", querytype, querystr);
1435 yaz_log(log_request, "%s ", wrbuf_buf(wr) );
1441 static void srw_bend_update(association *assoc, request *req,
1443 Z_SRW_updateResponse *srw_res,
1446 Z_SRW_updateRequest *srw_req = sr->u.update_request;
1447 yaz_log(YLOG_DEBUG, "Got SRW UpdateRequest");
1448 yaz_log(YLOG_DEBUG, "num_diag = %d", srw_res->num_diagnostics );
1450 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1455 rr.stream = assoc->encode;
1456 rr.print = assoc->print;
1458 rr.basenames = &srw_req->database;
1459 rr.operation = srw_req->operation;
1460 rr.operation_status = "failed";
1462 rr.record_version = 0;
1463 rr.record_checksum = 0;
1464 rr.record_old_version = 0;
1465 rr.record_packing = "xml";
1466 rr.record_schema = 0;
1468 rr.request_extra_record = 0;
1469 rr.response_extra_record = 0;
1470 rr.extra_request_data = 0;
1471 rr.extra_response_data = 0;
1476 yaz_log(YLOG_DEBUG, "basename = %s", rr.basenames[0] );
1477 yaz_log(YLOG_DEBUG, "Operation = %s", rr.operation );
1478 if ( !strcmp( rr.operation, "delete" ) ){
1479 if ( !srw_req->recordId ){
1480 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1481 &srw_res->num_diagnostics,
1485 rr.record_id = srw_req->recordId;
1487 if ( !srw_req->recordVersion ){
1488 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1489 &srw_res->num_diagnostics,
1490 7, "recordVersion" );
1493 rr.record_version = odr_strdup( assoc->encode,
1494 srw_req->recordVersion );
1497 if ( srw_req->recordOldVersion ){
1498 rr.record_old_version = odr_strdup(assoc->encode,
1499 srw_req->recordOldVersion );
1501 if ( srw_req->extraRequestData ){
1502 rr.extra_request_data = odr_strdup(assoc->encode,
1503 srw_req->extraRequestData );
1506 else if ( !strcmp( rr.operation, "replace" ) ){
1507 if ( !srw_req->recordId ){
1508 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1509 &srw_res->num_diagnostics,
1513 rr.record_id = srw_req->recordId;
1515 if ( srw_req->record.recordSchema == 0 ){
1516 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1517 &srw_res->num_diagnostics,
1518 7, "recordSchema" );
1521 rr.record_schema = odr_strdup(assoc->encode,
1522 srw_req->record.recordSchema );
1524 switch (srw_req->record.recordPacking)
1526 case Z_SRW_recordPacking_string:
1527 rr.record_packing = "string";
1529 case Z_SRW_recordPacking_XML:
1530 rr.record_packing = "xml";
1532 case Z_SRW_recordPacking_URL:
1533 rr.record_packing = "url";
1536 if ( srw_req->record.recordData_len ){
1537 rr.record_data = odr_strdupn(assoc->encode,
1538 srw_req->record.recordData_buf,
1539 srw_req->record.recordData_len );
1540 rr.request_extra_record = srw_req->extra_record;
1543 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1544 &srw_res->num_diagnostics,
1547 if (srw_req->extraRequestData)
1548 rr.extra_request_data = odr_strdup(assoc->encode,
1549 srw_req->extraRequestData );
1551 else if ( !strcmp( rr.operation, "insert" ) )
1553 rr.record_id = srw_req->recordId;
1554 if ( srw_req->record.recordSchema == 0 ){
1555 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1556 &srw_res->num_diagnostics,
1557 7, "recordSchema" );
1560 rr.record_schema = odr_strdup(assoc->encode,
1561 srw_req->record.recordSchema);
1563 switch (srw_req->record.recordPacking)
1565 case Z_SRW_recordPacking_string:
1566 rr.record_packing = "string";
1568 case Z_SRW_recordPacking_XML:
1569 rr.record_packing = "xml";
1571 case Z_SRW_recordPacking_URL:
1572 rr.record_packing = "url";
1576 if (srw_req->record.recordData_len)
1578 rr.record_data = odr_strdupn(assoc->encode,
1579 srw_req->record.recordData_buf,
1580 srw_req->record.recordData_len );
1581 rr.request_extra_record = srw_req->extra_record;
1584 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1585 &srw_res->num_diagnostics,
1587 if ( srw_req->extraRequestData )
1588 rr.extra_request_data = odr_strdup(assoc->encode,
1589 srw_req->extraRequestData );
1591 if (srw_res->num_diagnostics == 0)
1593 if ( assoc->init->bend_srw_update)
1594 (*assoc->init->bend_srw_update)(assoc->backend, &rr);
1596 yaz_log( YLOG_WARN, "Got No Update function!");
1602 yaz_add_srw_diagnostic_uri(assoc->encode,
1603 &srw_res->diagnostics,
1604 &srw_res->num_diagnostics,
1608 srw_res->recordId = rr.record_id;
1609 srw_res->operationStatus = rr.operation_status;
1610 srw_res->recordVersion = rr.record_version;
1611 srw_res->recordChecksum = rr.record_checksum;
1612 srw_res->extraResponseData = rr.extra_response_data;
1613 srw_res->record.recordPosition = 0;
1614 if (srw_res->num_diagnostics == 0 && rr.record_data)
1616 srw_res->record.recordSchema = rr.record_schema;
1617 srw_res->record.recordPacking = srw_req->record.recordPacking;
1618 srw_res->record.recordData_buf = rr.record_data;
1619 srw_res->record.recordData_len = strlen(rr.record_data);
1620 srw_res->extra_record = rr.response_extra_record;
1624 srw_res->record.recordData_len = 0;
1629 /* check if path is OK (1); BAD (0) */
1630 static int check_path(const char *path)
1634 if (strstr(path, ".."))
1639 static char *read_file(const char *fname, ODR o, int *sz)
1642 FILE *inf = fopen(fname, "rb");
1646 fseek(inf, 0L, SEEK_END);
1649 buf = odr_malloc(o, *sz);
1650 fread(buf, 1, *sz, inf);
1655 static void process_http_request(association *assoc, request *req)
1657 Z_HTTP_Request *hreq = req->gdu_request->u.HTTP_Request;
1658 ODR o = assoc->encode;
1659 int r = 2; /* 2=NOT TAKEN, 1=TAKEN, 0=SOAP TAKEN */
1661 Z_SOAP *soap_package = 0;
1664 Z_HTTP_Response *hres = 0;
1666 const char *stylesheet = 0; /* for now .. set later */
1667 Z_SRW_diagnostic *diagnostic = 0;
1668 int num_diagnostic = 0;
1669 const char *host = z_HTTP_header_lookup(hreq->headers, "Host");
1671 if (!control_association(assoc, host, 0))
1673 p = z_get_HTTP_Response(o, 404);
1676 if (r == 2 && assoc->server && assoc->server->docpath
1677 && hreq->path[0] == '/'
1679 /* check if path is a proper prefix of documentroot */
1680 strncmp(hreq->path+1, assoc->server->docpath,
1681 strlen(assoc->server->docpath))
1684 if (!check_path(hreq->path))
1686 yaz_log(YLOG_LOG, "File %s access forbidden", hreq->path+1);
1687 p = z_get_HTTP_Response(o, 404);
1691 int content_size = 0;
1692 char *content_buf = read_file(hreq->path+1, o, &content_size);
1695 yaz_log(YLOG_LOG, "File %s not found", hreq->path+1);
1696 p = z_get_HTTP_Response(o, 404);
1700 const char *ctype = 0;
1701 yaz_mime_types types = yaz_mime_types_create();
1703 yaz_mime_types_add(types, "xsl", "application/xml");
1704 yaz_mime_types_add(types, "xml", "application/xml");
1705 yaz_mime_types_add(types, "css", "text/css");
1706 yaz_mime_types_add(types, "html", "text/html");
1707 yaz_mime_types_add(types, "htm", "text/html");
1708 yaz_mime_types_add(types, "txt", "text/plain");
1709 yaz_mime_types_add(types, "js", "application/x-javascript");
1711 yaz_mime_types_add(types, "gif", "image/gif");
1712 yaz_mime_types_add(types, "png", "image/png");
1713 yaz_mime_types_add(types, "jpg", "image/jpeg");
1714 yaz_mime_types_add(types, "jpeg", "image/jpeg");
1716 ctype = yaz_mime_lookup_fname(types, hreq->path);
1719 yaz_log(YLOG_LOG, "No mime type for %s", hreq->path+1);
1720 p = z_get_HTTP_Response(o, 404);
1724 p = z_get_HTTP_Response(o, 200);
1725 hres = p->u.HTTP_Response;
1726 hres->content_buf = content_buf;
1727 hres->content_len = content_size;
1728 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1730 yaz_mime_types_destroy(types);
1738 r = yaz_srw_decode(hreq, &sr, &soap_package, assoc->decode, &charset);
1739 yaz_log(YLOG_DEBUG, "yaz_srw_decode returned %d", r);
1741 if (r == 2) /* not taken */
1743 r = yaz_sru_decode(hreq, &sr, &soap_package, assoc->decode, &charset,
1744 &diagnostic, &num_diagnostic);
1745 yaz_log(YLOG_DEBUG, "yaz_sru_decode returned %d", r);
1747 if (r == 0) /* decode SRW/SRU OK .. */
1749 int http_code = 200;
1750 if (sr->which == Z_SRW_searchRetrieve_request)
1753 yaz_srw_get(assoc->encode, Z_SRW_searchRetrieve_response);
1755 stylesheet = sr->u.request->stylesheet;
1758 res->u.response->diagnostics = diagnostic;
1759 res->u.response->num_diagnostics = num_diagnostic;
1763 srw_bend_search(assoc, req, sr, res->u.response,
1766 if (http_code == 200)
1767 soap_package->u.generic->p = res;
1769 else if (sr->which == Z_SRW_explain_request)
1771 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_explain_response);
1772 stylesheet = sr->u.explain_request->stylesheet;
1775 res->u.explain_response->diagnostics = diagnostic;
1776 res->u.explain_response->num_diagnostics = num_diagnostic;
1778 srw_bend_explain(assoc, req, sr,
1779 res->u.explain_response, &http_code);
1780 if (http_code == 200)
1781 soap_package->u.generic->p = res;
1783 else if (sr->which == Z_SRW_scan_request)
1785 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_scan_response);
1786 stylesheet = sr->u.scan_request->stylesheet;
1789 res->u.scan_response->diagnostics = diagnostic;
1790 res->u.scan_response->num_diagnostics = num_diagnostic;
1792 srw_bend_scan(assoc, req, sr,
1793 res->u.scan_response, &http_code);
1794 if (http_code == 200)
1795 soap_package->u.generic->p = res;
1797 else if (sr->which == Z_SRW_update_request)
1799 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_update_response);
1800 yaz_log(YLOG_DEBUG, "handling SRW UpdateRequest");
1803 res->u.update_response->diagnostics = diagnostic;
1804 res->u.update_response->num_diagnostics = num_diagnostic;
1806 yaz_log(YLOG_DEBUG, "num_diag = %d", res->u.update_response->num_diagnostics );
1807 srw_bend_update(assoc, req, sr,
1808 res->u.update_response, &http_code);
1809 if (http_code == 200)
1810 soap_package->u.generic->p = res;
1814 yaz_log(log_request, "SOAP ERROR");
1815 /* FIXME - what error, what query */
1817 z_soap_error(assoc->encode, soap_package,
1818 "SOAP-ENV:Client", "Bad method", 0);
1820 if (http_code == 200 || http_code == 500)
1822 static Z_SOAP_Handler soap_handlers[4] = {
1824 {"http://www.loc.gov/zing/srw/", 0,
1825 (Z_SOAP_fun) yaz_srw_codec},
1826 {"http://www.loc.gov/zing/srw/v1.0/", 0,
1827 (Z_SOAP_fun) yaz_srw_codec},
1828 {"http://www.loc.gov/zing/srw/update/", 0,
1829 (Z_SOAP_fun) yaz_ucp_codec},
1835 p = z_get_HTTP_Response(o, 200);
1836 hres = p->u.HTTP_Response;
1838 if (!stylesheet && assoc->server)
1839 stylesheet = assoc->server->stylesheet;
1841 /* empty stylesheet means NO stylesheet */
1842 if (stylesheet && *stylesheet == '\0')
1845 ret = z_soap_codec_enc_xsl(assoc->encode, &soap_package,
1846 &hres->content_buf, &hres->content_len,
1847 soap_handlers, charset, stylesheet);
1848 hres->code = http_code;
1850 strcpy(ctype, "text/xml");
1853 strcat(ctype, "; charset=");
1854 strcat(ctype, charset);
1856 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1859 p = z_get_HTTP_Response(o, http_code);
1863 p = z_get_HTTP_Response(o, 500);
1864 hres = p->u.HTTP_Response;
1865 if (!strcmp(hreq->version, "1.0"))
1867 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1868 if (v && !strcmp(v, "Keep-Alive"))
1872 hres->version = "1.0";
1876 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1877 if (v && !strcmp(v, "close"))
1881 hres->version = "1.1";
1885 z_HTTP_header_add(o, &hres->headers, "Connection", "close");
1886 assoc->state = ASSOC_DEAD;
1887 assoc->cs_get_mask = 0;
1892 const char *alive = z_HTTP_header_lookup(hreq->headers, "Keep-Alive");
1894 if (alive && isdigit(*(const unsigned char *) alive))
1898 if (t < 0 || t > 3600)
1900 iochan_settimeout(assoc->client_chan,t);
1901 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1903 process_gdu_response(assoc, req, p);
1906 static void process_gdu_request(association *assoc, request *req)
1908 if (req->gdu_request->which == Z_GDU_Z3950)
1911 req->apdu_request = req->gdu_request->u.z3950;
1912 if (process_z_request(assoc, req, &msg) < 0)
1913 do_close_req(assoc, Z_Close_systemProblem, msg, req);
1915 else if (req->gdu_request->which == Z_GDU_HTTP_Request)
1916 process_http_request(assoc, req);
1919 do_close_req(assoc, Z_Close_systemProblem, "bad protocol packet", req);
1924 * Initiate request processing.
1926 static int process_z_request(association *assoc, request *req, char **msg)
1932 *msg = "Unknown Error";
1933 assert(req && req->state == REQUEST_IDLE);
1934 if (req->apdu_request->which != Z_APDU_initRequest && !assoc->init)
1936 *msg = "Missing InitRequest";
1939 switch (req->apdu_request->which)
1941 case Z_APDU_initRequest:
1942 res = process_initRequest(assoc, req); break;
1943 case Z_APDU_searchRequest:
1944 res = process_searchRequest(assoc, req, &fd); break;
1945 case Z_APDU_presentRequest:
1946 res = process_presentRequest(assoc, req, &fd); break;
1947 case Z_APDU_scanRequest:
1948 if (assoc->init->bend_scan)
1949 res = process_scanRequest(assoc, req, &fd);
1952 *msg = "Cannot handle Scan APDU";
1956 case Z_APDU_extendedServicesRequest:
1957 if (assoc->init->bend_esrequest)
1958 res = process_ESRequest(assoc, req, &fd);
1961 *msg = "Cannot handle Extended Services APDU";
1965 case Z_APDU_sortRequest:
1966 if (assoc->init->bend_sort)
1967 res = process_sortRequest(assoc, req, &fd);
1970 *msg = "Cannot handle Sort APDU";
1975 process_close(assoc, req);
1977 case Z_APDU_deleteResultSetRequest:
1978 if (assoc->init->bend_delete)
1979 res = process_deleteRequest(assoc, req, &fd);
1982 *msg = "Cannot handle Delete APDU";
1986 case Z_APDU_segmentRequest:
1987 if (assoc->init->bend_segment)
1989 res = process_segmentRequest (assoc, req);
1993 *msg = "Cannot handle Segment APDU";
1997 case Z_APDU_triggerResourceControlRequest:
2000 *msg = "Bad APDU received";
2005 yaz_log(YLOG_DEBUG, " result immediately available");
2006 retval = process_z_response(assoc, req, res);
2010 yaz_log(YLOG_DEBUG, " result unavailble");
2013 else /* no result yet - one will be provided later */
2017 /* Set up an I/O handler for the fd supplied by the backend */
2019 yaz_log(YLOG_DEBUG, " establishing handler for result");
2020 req->state = REQUEST_PENDING;
2021 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT, 0)))
2023 iochan_setdata(chan, assoc);
2030 * Handle message from the backend.
2032 void backend_response(IOCHAN i, int event)
2034 association *assoc = (association *)iochan_getdata(i);
2035 request *req = request_head(&assoc->incoming);
2039 yaz_log(YLOG_DEBUG, "backend_response");
2040 assert(assoc && req && req->state != REQUEST_IDLE);
2041 /* determine what it is we're waiting for */
2042 switch (req->apdu_request->which)
2044 case Z_APDU_searchRequest:
2045 res = response_searchRequest(assoc, req, 0, &fd); break;
2047 case Z_APDU_presentRequest:
2048 res = response_presentRequest(assoc, req, 0, &fd); break;
2049 case Z_APDU_scanRequest:
2050 res = response_scanRequest(assoc, req, 0, &fd); break;
2053 yaz_log(YLOG_FATAL, "Serious programmer's lapse or bug");
2056 if ((res && process_z_response(assoc, req, res) < 0) || fd < 0)
2058 yaz_log(YLOG_WARN, "Fatal error when talking to backend");
2059 do_close(assoc, Z_Close_systemProblem, 0);
2063 else if (!res) /* no result yet - try again later */
2065 yaz_log(YLOG_DEBUG, " no result yet");
2066 iochan_setfd(i, fd); /* in case fd has changed */
2071 * Encode response, and transfer the request structure to the outgoing queue.
2073 static int process_gdu_response(association *assoc, request *req, Z_GDU *res)
2075 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
2079 if (!z_GDU(assoc->print, &res, 0, 0))
2080 yaz_log(YLOG_WARN, "ODR print error: %s",
2081 odr_errmsg(odr_geterror(assoc->print)));
2082 odr_reset(assoc->print);
2084 if (!z_GDU(assoc->encode, &res, 0, 0))
2086 yaz_log(YLOG_WARN, "ODR error when encoding PDU: %s [element %s]",
2087 odr_errmsg(odr_geterror(assoc->decode)),
2088 odr_getelement(assoc->decode));
2091 req->response = odr_getbuf(assoc->encode, &req->len_response,
2092 &req->size_response);
2093 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
2094 odr_reset(assoc->encode);
2095 req->state = REQUEST_IDLE;
2096 request_enq(&assoc->outgoing, req);
2097 /* turn the work over to the ir_session handler */
2098 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
2099 assoc->cs_put_mask = EVENT_OUTPUT;
2100 /* Is there more work to be done? give that to the input handler too */
2102 if (request_head(&assoc->incoming))
2104 yaz_log (YLOG_DEBUG, "more work to be done");
2105 iochan_setevent(assoc->client_chan, EVENT_WORK);
2112 * Encode response, and transfer the request structure to the outgoing queue.
2114 static int process_z_response(association *assoc, request *req, Z_APDU *res)
2116 Z_GDU *gres = (Z_GDU *) odr_malloc(assoc->encode, sizeof(*res));
2117 gres->which = Z_GDU_Z3950;
2118 gres->u.z3950 = res;
2120 return process_gdu_response(assoc, req, gres);
2123 static char *get_vhost(Z_OtherInformation *otherInfo)
2125 return yaz_oi_get_string_oidval(&otherInfo, VAL_PROXY, 1, 0);
2129 * Handle init request.
2130 * At the moment, we don't check the options
2131 * anywhere else in the code - we just try not to do anything that would
2132 * break a naive client. We'll toss 'em into the association block when
2133 * we need them there.
2135 static Z_APDU *process_initRequest(association *assoc, request *reqb)
2137 Z_InitRequest *req = reqb->apdu_request->u.initRequest;
2138 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
2139 Z_InitResponse *resp = apdu->u.initResponse;
2140 bend_initresult *binitres;
2143 statserv_options_block *cb = 0; /* by default no control for backend */
2145 if (control_association(assoc, get_vhost(req->otherInfo), 1))
2146 cb = statserv_getcontrol(); /* got control block for backend */
2148 if (cb && assoc->backend)
2149 (*cb->bend_close)(assoc->backend);
2151 yaz_log(log_requestdetail, "Got initRequest");
2152 if (req->implementationId)
2153 yaz_log(log_requestdetail, "Id: %s",
2154 req->implementationId);
2155 if (req->implementationName)
2156 yaz_log(log_requestdetail, "Name: %s",
2157 req->implementationName);
2158 if (req->implementationVersion)
2159 yaz_log(log_requestdetail, "Version: %s",
2160 req->implementationVersion);
2162 assoc_init_reset(assoc);
2164 assoc->init->auth = req->idAuthentication;
2165 assoc->init->referenceId = req->referenceId;
2167 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
2169 Z_CharSetandLanguageNegotiation *negotiation =
2170 yaz_get_charneg_record (req->otherInfo);
2172 negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
2173 assoc->init->charneg_request = negotiation;
2179 if (req->implementationVersion)
2180 yaz_log(log_requestdetail, "Config: %s",
2183 iochan_settimeout(assoc->client_chan, cb->idle_timeout * 60);
2185 /* we have a backend control block, so call that init function */
2186 if (!(binitres = (*cb->bend_init)(assoc->init)))
2188 yaz_log(YLOG_WARN, "Bad response from backend.");
2191 assoc->backend = binitres->handle;
2195 /* no backend. return error */
2196 binitres = odr_malloc(assoc->encode, sizeof(*binitres));
2197 binitres->errstring = 0;
2198 binitres->errcode = YAZ_BIB1_PERMANENT_SYSTEM_ERROR;
2199 iochan_settimeout(assoc->client_chan, 10);
2201 if ((assoc->init->bend_sort))
2202 yaz_log (YLOG_DEBUG, "Sort handler installed");
2203 if ((assoc->init->bend_search))
2204 yaz_log (YLOG_DEBUG, "Search handler installed");
2205 if ((assoc->init->bend_present))
2206 yaz_log (YLOG_DEBUG, "Present handler installed");
2207 if ((assoc->init->bend_esrequest))
2208 yaz_log (YLOG_DEBUG, "ESRequest handler installed");
2209 if ((assoc->init->bend_delete))
2210 yaz_log (YLOG_DEBUG, "Delete handler installed");
2211 if ((assoc->init->bend_scan))
2212 yaz_log (YLOG_DEBUG, "Scan handler installed");
2213 if ((assoc->init->bend_segment))
2214 yaz_log (YLOG_DEBUG, "Segment handler installed");
2216 resp->referenceId = req->referenceId;
2218 /* let's tell the client what we can do */
2219 if (ODR_MASK_GET(req->options, Z_Options_search))
2221 ODR_MASK_SET(resp->options, Z_Options_search);
2222 strcat(options, "srch");
2224 if (ODR_MASK_GET(req->options, Z_Options_present))
2226 ODR_MASK_SET(resp->options, Z_Options_present);
2227 strcat(options, " prst");
2229 if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
2230 assoc->init->bend_delete)
2232 ODR_MASK_SET(resp->options, Z_Options_delSet);
2233 strcat(options, " del");
2235 if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
2236 assoc->init->bend_esrequest)
2238 ODR_MASK_SET(resp->options, Z_Options_extendedServices);
2239 strcat (options, " extendedServices");
2241 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
2243 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
2244 strcat(options, " namedresults");
2246 if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
2248 ODR_MASK_SET(resp->options, Z_Options_scan);
2249 strcat(options, " scan");
2251 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
2253 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
2254 strcat(options, " concurrop");
2256 if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
2258 ODR_MASK_SET(resp->options, Z_Options_sort);
2259 strcat(options, " sort");
2262 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel)
2263 && assoc->init->charneg_response)
2265 Z_OtherInformation **p;
2266 Z_OtherInformationUnit *p0;
2268 yaz_oi_APDU(apdu, &p);
2270 if ((p0=yaz_oi_update(p, assoc->encode, NULL, 0, 0))) {
2271 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
2273 p0->which = Z_OtherInfo_externallyDefinedInfo;
2274 p0->information.externallyDefinedInfo =
2275 assoc->init->charneg_response;
2277 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
2278 strcat(options, " negotiation");
2281 if (ODR_MASK_GET(req->options, Z_Options_triggerResourceCtrl))
2282 ODR_MASK_SET(resp->options, Z_Options_triggerResourceCtrl);
2284 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
2286 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
2287 assoc->version = 1; /* 1 & 2 are equivalent */
2289 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
2291 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
2294 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
2296 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
2300 yaz_log(log_requestdetail, "Negotiated to v%d: %s", assoc->version, options);
2301 assoc->maximumRecordSize = *req->maximumRecordSize;
2303 if (cb && assoc->maximumRecordSize > cb->maxrecordsize)
2304 assoc->maximumRecordSize = cb->maxrecordsize;
2305 assoc->preferredMessageSize = *req->preferredMessageSize;
2306 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
2307 assoc->preferredMessageSize = assoc->maximumRecordSize;
2309 resp->preferredMessageSize = &assoc->preferredMessageSize;
2310 resp->maximumRecordSize = &assoc->maximumRecordSize;
2312 resp->implementationId = odr_prepend(assoc->encode,
2313 assoc->init->implementation_id,
2314 resp->implementationId);
2316 resp->implementationName = odr_prepend(assoc->encode,
2317 assoc->init->implementation_name,
2318 odr_prepend(assoc->encode, "GFS", resp->implementationName));
2320 version = odr_strdup(assoc->encode, "$Revision: 1.95 $");
2321 if (strlen(version) > 10) /* check for unexpanded CVS strings */
2322 version[strlen(version)-2] = '\0';
2323 resp->implementationVersion = odr_prepend(assoc->encode,
2324 assoc->init->implementation_version,
2325 odr_prepend(assoc->encode, &version[11],
2326 resp->implementationVersion));
2328 if (binitres->errcode)
2330 assoc->state = ASSOC_DEAD;
2331 resp->userInformationField =
2332 init_diagnostics(assoc->encode, binitres->errcode,
2333 binitres->errstring);
2338 if (!req->idAuthentication)
2339 yaz_log(log_request, "Auth none");
2340 else if (req->idAuthentication->which == Z_IdAuthentication_open)
2342 const char *open = req->idAuthentication->u.open;
2343 const char *slash = strchr(open, '/');
2349 yaz_log(log_request, "Auth open %.*s", len, open);
2351 else if (req->idAuthentication->which == Z_IdAuthentication_idPass)
2353 const char *user = req->idAuthentication->u.idPass->userId;
2354 const char *group = req->idAuthentication->u.idPass->groupId;
2355 yaz_log(log_request, "Auth idPass %s %s",
2356 user ? user : "-", group ? group : "-");
2358 else if (req->idAuthentication->which
2359 == Z_IdAuthentication_anonymous)
2361 yaz_log(log_request, "Auth anonymous");
2365 yaz_log(log_request, "Auth other");
2370 WRBUF wr = wrbuf_alloc();
2371 wrbuf_printf(wr, "Init ");
2372 if (binitres->errcode)
2373 wrbuf_printf(wr, "ERROR %d", binitres->errcode);
2375 wrbuf_printf(wr, "OK -");
2376 wrbuf_printf(wr, " ID:%s Name:%s Version:%s",
2377 (req->implementationId ? req->implementationId :"-"),
2378 (req->implementationName ?
2379 req->implementationName : "-"),
2380 (req->implementationVersion ?
2381 req->implementationVersion : "-")
2383 yaz_log(log_request, "%s", wrbuf_buf(wr));
2390 * Set the specified `errcode' and `errstring' into a UserInfo-1
2391 * external to be returned to the client in accordance with Z35.90
2392 * Implementor Agreement 5 (Returning diagnostics in an InitResponse):
2393 * http://lcweb.loc.gov/z3950/agency/agree/initdiag.html
2395 static Z_External *init_diagnostics(ODR odr, int error, const char *addinfo)
2397 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2398 addinfo ? " -- " : "", addinfo ? addinfo : "");
2399 return zget_init_diagnostics(odr, error, addinfo);
2403 * nonsurrogate diagnostic record.
2405 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
2407 Z_Records *rec = (Z_Records *) odr_malloc (assoc->encode, sizeof(*rec));
2409 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2410 addinfo ? " -- " : "", addinfo ? addinfo : "");
2412 rec->which = Z_Records_NSD;
2413 rec->u.nonSurrogateDiagnostic = zget_DefaultDiagFormat(assoc->encode,
2419 * surrogate diagnostic.
2421 static Z_NamePlusRecord *surrogatediagrec(association *assoc,
2423 int error, const char *addinfo)
2425 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2426 addinfo ? " -- " : "", addinfo ? addinfo : "");
2427 return zget_surrogateDiagRec(assoc->encode, dbname, error, addinfo);
2430 static Z_Records *pack_records(association *a, char *setname, int start,
2431 int *num, Z_RecordComposition *comp,
2432 int *next, int *pres, oid_value format,
2433 Z_ReferenceId *referenceId,
2434 int *oid, int *errcode)
2436 int recno, total_length = 0, toget = *num, dumped_records = 0;
2437 Z_Records *records =
2438 (Z_Records *) odr_malloc (a->encode, sizeof(*records));
2439 Z_NamePlusRecordList *reclist =
2440 (Z_NamePlusRecordList *) odr_malloc (a->encode, sizeof(*reclist));
2441 Z_NamePlusRecord **list =
2442 (Z_NamePlusRecord **) odr_malloc (a->encode, sizeof(*list) * toget);
2444 records->which = Z_Records_DBOSD;
2445 records->u.databaseOrSurDiagnostics = reclist;
2446 reclist->num_records = 0;
2447 reclist->records = list;
2448 *pres = Z_PresentStatus_success;
2452 yaz_log(log_requestdetail, "Request to pack %d+%d %s", start, toget, setname);
2453 yaz_log(log_requestdetail, "pms=%d, mrs=%d", a->preferredMessageSize,
2454 a->maximumRecordSize);
2455 for (recno = start; reclist->num_records < toget; recno++)
2458 Z_NamePlusRecord *thisrec;
2459 int this_length = 0;
2461 * we get the number of bytes allocated on the stream before any
2462 * allocation done by the backend - this should give us a reasonable
2463 * idea of the total size of the data so far.
2465 total_length = odr_total(a->encode) - dumped_records;
2471 freq.last_in_set = 0;
2472 freq.setname = setname;
2473 freq.surrogate_flag = 0;
2474 freq.number = recno;
2476 freq.request_format = format;
2477 freq.request_format_raw = oid;
2478 freq.output_format = format;
2479 freq.output_format_raw = 0;
2480 freq.stream = a->encode;
2481 freq.print = a->print;
2482 freq.referenceId = referenceId;
2485 retrieve_fetch(a, &freq);
2487 *next = freq.last_in_set ? 0 : recno + 1;
2489 /* backend should be able to signal whether error is system-wide
2490 or only pertaining to current record */
2493 if (!freq.surrogate_flag)
2496 *pres = Z_PresentStatus_failure;
2497 /* for 'present request out of range',
2498 set addinfo to record position if not set */
2499 if (freq.errcode == YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE &&
2500 freq.errstring == 0)
2502 sprintf (s, "%d", recno);
2506 *errcode = freq.errcode;
2507 return diagrec(a, freq.errcode, freq.errstring);
2509 reclist->records[reclist->num_records] =
2510 surrogatediagrec(a, freq.basename, freq.errcode,
2512 reclist->num_records++;
2515 if (freq.record == 0) /* no error and no record ? */
2517 *next = 0; /* signal end-of-set and stop */
2521 this_length = freq.len;
2523 this_length = odr_total(a->encode) - total_length - dumped_records;
2524 yaz_log(YLOG_DEBUG, " fetched record, len=%d, total=%d dumped=%d",
2525 this_length, total_length, dumped_records);
2526 if (a->preferredMessageSize > 0 &&
2527 this_length + total_length > a->preferredMessageSize)
2529 /* record is small enough, really */
2530 if (this_length <= a->preferredMessageSize && recno > start)
2532 yaz_log(log_requestdetail, " Dropped last normal-sized record");
2533 *pres = Z_PresentStatus_partial_2;
2536 /* record can only be fetched by itself */
2537 if (this_length < a->maximumRecordSize)
2539 yaz_log(log_requestdetail, " Record > prefmsgsz");
2542 yaz_log(YLOG_DEBUG, " Dropped it");
2543 reclist->records[reclist->num_records] =
2544 surrogatediagrec(a, freq.basename, 16, 0);
2545 reclist->num_records++;
2546 dumped_records += this_length;
2550 else /* too big entirely */
2552 yaz_log(log_requestdetail, "Record > maxrcdsz this=%d max=%d",
2553 this_length, a->maximumRecordSize);
2554 reclist->records[reclist->num_records] =
2555 surrogatediagrec(a, freq.basename, 17, 0);
2556 reclist->num_records++;
2557 dumped_records += this_length;
2562 if (!(thisrec = (Z_NamePlusRecord *)
2563 odr_malloc(a->encode, sizeof(*thisrec))))
2566 thisrec->databaseName = odr_strdup(a->encode, freq.basename);
2568 thisrec->databaseName = 0;
2569 thisrec->which = Z_NamePlusRecord_databaseRecord;
2571 if (freq.output_format_raw)
2573 struct oident *ident = oid_getentbyoid(freq.output_format_raw);
2574 freq.output_format = ident->value;
2576 thisrec->u.databaseRecord = z_ext_record(a->encode, freq.output_format,
2577 freq.record, freq.len);
2578 if (!thisrec->u.databaseRecord)
2580 reclist->records[reclist->num_records] = thisrec;
2581 reclist->num_records++;
2583 *num = reclist->num_records;
2587 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
2590 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2591 bend_search_rr *bsrr =
2592 (bend_search_rr *)nmem_malloc (reqb->request_mem, sizeof(*bsrr));
2594 yaz_log(log_requestdetail, "Got SearchRequest.");
2596 bsrr->request = reqb;
2597 bsrr->association = assoc;
2598 bsrr->referenceId = req->referenceId;
2599 save_referenceId (reqb, bsrr->referenceId);
2600 bsrr->srw_sortKeys = 0;
2601 bsrr->srw_setname = 0;
2602 bsrr->srw_setnameIdleTime = 0;
2604 yaz_log (log_requestdetail, "ResultSet '%s'", req->resultSetName);
2605 if (req->databaseNames)
2608 for (i = 0; i < req->num_databaseNames; i++)
2609 yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
2612 yaz_log_zquery_level(log_requestdetail,req->query);
2614 if (assoc->init->bend_search)
2616 bsrr->setname = req->resultSetName;
2617 bsrr->replace_set = *req->replaceIndicator;
2618 bsrr->num_bases = req->num_databaseNames;
2619 bsrr->basenames = req->databaseNames;
2620 bsrr->query = req->query;
2621 bsrr->stream = assoc->encode;
2622 nmem_transfer(bsrr->stream->mem, reqb->request_mem);
2623 bsrr->decode = assoc->decode;
2624 bsrr->print = assoc->print;
2627 bsrr->errstring = NULL;
2628 bsrr->search_info = NULL;
2630 if (assoc->server && assoc->server->cql_transform
2631 && req->query->which == Z_Query_type_104
2632 && req->query->u.type_104->which == Z_External_CQL)
2634 /* have a CQL query and a CQL to PQF transform .. */
2636 cql2pqf(bsrr->stream, req->query->u.type_104->u.cql,
2637 assoc->server->cql_transform, bsrr->query);
2639 bsrr->errcode = yaz_diag_srw_to_bib1(srw_errcode);
2642 (assoc->init->bend_search)(assoc->backend, bsrr);
2643 if (!bsrr->request) /* backend not ready with the search response */
2644 return 0; /* should not be used any more */
2648 /* FIXME - make a diagnostic for it */
2649 yaz_log(YLOG_WARN,"Search not supported ?!?!");
2651 return response_searchRequest(assoc, reqb, bsrr, fd);
2654 int bend_searchresponse(void *handle, bend_search_rr *bsrr) {return 0;}
2657 * Prepare a searchresponse based on the backend results. We probably want
2658 * to look at making the fetching of records nonblocking as well, but
2659 * so far, we'll keep things simple.
2660 * If bsrt is null, that means we're called in response to a communications
2661 * event, and we'll have to get the response for ourselves.
2663 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
2664 bend_search_rr *bsrt, int *fd)
2666 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2667 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2668 Z_SearchResponse *resp = (Z_SearchResponse *)
2669 odr_malloc (assoc->encode, sizeof(*resp));
2670 int *nulint = odr_intdup (assoc->encode, 0);
2671 bool_t *sr = odr_intdup(assoc->encode, 1);
2672 int *next = odr_intdup(assoc->encode, 0);
2673 int *none = odr_intdup(assoc->encode, Z_SearchResponse_none);
2676 apdu->which = Z_APDU_searchResponse;
2677 apdu->u.searchResponse = resp;
2678 resp->referenceId = req->referenceId;
2679 resp->additionalSearchInfo = 0;
2680 resp->otherInfo = 0;
2682 if (!bsrt && !bend_searchresponse(assoc->backend, bsrt))
2684 yaz_log(YLOG_FATAL, "Bad result from backend");
2687 else if (bsrt->errcode)
2689 resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
2690 resp->resultCount = nulint;
2691 resp->numberOfRecordsReturned = nulint;
2692 resp->nextResultSetPosition = nulint;
2693 resp->searchStatus = nulint;
2694 resp->resultSetStatus = none;
2695 resp->presentStatus = 0;
2699 int *toget = odr_intdup(assoc->encode, 0);
2700 int *presst = odr_intdup(assoc->encode, 0);
2701 Z_RecordComposition comp, *compp = 0;
2703 yaz_log (log_requestdetail, "resultCount: %d", bsrt->hits);
2706 resp->resultCount = &bsrt->hits;
2708 comp.which = Z_RecordComp_simple;
2709 /* how many records does the user agent want, then? */
2710 if (bsrt->hits <= *req->smallSetUpperBound)
2712 *toget = bsrt->hits;
2713 if ((comp.u.simple = req->smallSetElementSetNames))
2716 else if (bsrt->hits < *req->largeSetLowerBound)
2718 *toget = *req->mediumSetPresentNumber;
2719 if (*toget > bsrt->hits)
2720 *toget = bsrt->hits;
2721 if ((comp.u.simple = req->mediumSetElementSetNames))
2727 if (*toget && !resp->records)
2732 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
2735 form = prefformat->value;
2737 /* Call bend_present if defined */
2738 if (assoc->init->bend_present)
2740 bend_present_rr *bprr = (bend_present_rr *)
2741 nmem_malloc (reqb->request_mem, sizeof(*bprr));
2742 bprr->setname = req->resultSetName;
2744 bprr->number = *toget;
2745 bprr->format = form;
2747 bprr->referenceId = req->referenceId;
2748 bprr->stream = assoc->encode;
2749 bprr->print = assoc->print;
2750 bprr->request = reqb;
2751 bprr->association = assoc;
2753 bprr->errstring = NULL;
2754 (*assoc->init->bend_present)(assoc->backend, bprr);
2760 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2761 *resp->presentStatus = Z_PresentStatus_failure;
2766 resp->records = pack_records(assoc, req->resultSetName, 1,
2767 toget, compp, next, presst, form, req->referenceId,
2768 req->preferredRecordSyntax, NULL);
2771 resp->numberOfRecordsReturned = toget;
2772 returnedrecs = *toget;
2773 resp->nextResultSetPosition = next;
2774 resp->searchStatus = sr;
2775 resp->resultSetStatus = 0;
2776 resp->presentStatus = presst;
2780 if (*resp->resultCount)
2782 resp->numberOfRecordsReturned = nulint;
2783 resp->nextResultSetPosition = next;
2784 resp->searchStatus = sr;
2785 resp->resultSetStatus = 0;
2786 resp->presentStatus = 0;
2789 resp->additionalSearchInfo = bsrt->search_info;
2794 WRBUF wr = wrbuf_alloc();
2796 for (i = 0 ; i < req->num_databaseNames; i++){
2798 wrbuf_printf(wr, "+");
2799 wrbuf_printf(wr, req->databaseNames[i]);
2801 wrbuf_printf(wr, " ");
2804 wrbuf_printf(wr, "ERROR %d", bsrt->errcode);
2806 wrbuf_printf(wr, "OK %d", bsrt->hits);
2807 wrbuf_printf(wr, " %s 1+%d ",
2808 req->resultSetName, returnedrecs);
2809 yaz_query_to_wrbuf(wr, req->query);
2811 yaz_log(log_request, "Search %s", wrbuf_buf(wr));
2818 * Maybe we got a little over-friendly when we designed bend_fetch to
2819 * get only one record at a time. Some backends can optimise multiple-record
2820 * fetches, and at any rate, there is some overhead involved in
2821 * all that selecting and hopping around. Problem is, of course, that the
2822 * frontend can't know ahead of time how many records it'll need to
2823 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
2824 * is downright lousy as a bulk data transfer protocol.
2826 * To start with, we'll do the fetching of records from the backend
2827 * in one operation: To save some trips in and out of the event-handler,
2828 * and to simplify the interface to pack_records. At any rate, asynch
2829 * operation is more fun in operations that have an unpredictable execution
2830 * speed - which is normally more true for search than for present.
2832 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
2835 Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
2839 Z_PresentResponse *resp;
2843 const char *errstring = 0;
2845 yaz_log(log_requestdetail, "Got PresentRequest.");
2847 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
2850 form = prefformat->value;
2851 resp = (Z_PresentResponse *)odr_malloc (assoc->encode, sizeof(*resp));
2853 resp->presentStatus = odr_intdup(assoc->encode, 0);
2854 if (assoc->init->bend_present)
2856 bend_present_rr *bprr = (bend_present_rr *)
2857 nmem_malloc (reqb->request_mem, sizeof(*bprr));
2858 bprr->setname = req->resultSetId;
2859 bprr->start = *req->resultSetStartPoint;
2860 bprr->number = *req->numberOfRecordsRequested;
2861 bprr->format = form;
2862 bprr->comp = req->recordComposition;
2863 bprr->referenceId = req->referenceId;
2864 bprr->stream = assoc->encode;
2865 bprr->print = assoc->print;
2866 bprr->request = reqb;
2867 bprr->association = assoc;
2869 bprr->errstring = NULL;
2870 (*assoc->init->bend_present)(assoc->backend, bprr);
2873 return 0; /* should not happen */
2876 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2877 *resp->presentStatus = Z_PresentStatus_failure;
2878 errcode = bprr->errcode;
2879 errstring = bprr->errstring;
2882 apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2883 next = odr_intdup(assoc->encode, 0);
2884 num = odr_intdup(assoc->encode, 0);
2886 apdu->which = Z_APDU_presentResponse;
2887 apdu->u.presentResponse = resp;
2888 resp->referenceId = req->referenceId;
2889 resp->otherInfo = 0;
2893 *num = *req->numberOfRecordsRequested;
2895 pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
2896 num, req->recordComposition, next,
2897 resp->presentStatus,
2898 form, req->referenceId, req->preferredRecordSyntax,
2903 WRBUF wr = wrbuf_alloc();
2904 wrbuf_printf(wr, "Present ");
2906 if (*resp->presentStatus == Z_PresentStatus_failure)
2907 wrbuf_printf(wr, "ERROR %d ", errcode);
2908 else if (*resp->presentStatus == Z_PresentStatus_success)
2909 wrbuf_printf(wr, "OK - ");
2911 wrbuf_printf(wr, "Partial %d - ", *resp->presentStatus);
2913 wrbuf_printf(wr, " %s %d+%d ",
2914 req->resultSetId, *req->resultSetStartPoint,
2915 *req->numberOfRecordsRequested);
2916 yaz_log(log_request, "%s", wrbuf_buf(wr) );
2921 resp->numberOfRecordsReturned = num;
2922 resp->nextResultSetPosition = next;
2928 * Scan was implemented rather in a hurry, and with support for only the basic
2929 * elements of the service in the backend API. Suggestions are welcome.
2931 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
2933 Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
2934 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2935 Z_ScanResponse *res = (Z_ScanResponse *)
2936 odr_malloc (assoc->encode, sizeof(*res));
2937 int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
2938 int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
2939 Z_ListEntries *ents = (Z_ListEntries *)
2940 odr_malloc (assoc->encode, sizeof(*ents));
2941 Z_DiagRecs *diagrecs_p = NULL;
2943 bend_scan_rr *bsrr = (bend_scan_rr *)
2944 odr_malloc (assoc->encode, sizeof(*bsrr));
2945 struct scan_entry *save_entries;
2947 yaz_log(log_requestdetail, "Got ScanRequest");
2949 apdu->which = Z_APDU_scanResponse;
2950 apdu->u.scanResponse = res;
2951 res->referenceId = req->referenceId;
2953 /* if step is absent, set it to 0 */
2954 res->stepSize = odr_intdup(assoc->encode, 0);
2956 *res->stepSize = *req->stepSize;
2958 res->scanStatus = scanStatus;
2959 res->numberOfEntriesReturned = numberOfEntriesReturned;
2960 res->positionOfTerm = 0;
2961 res->entries = ents;
2962 ents->num_entries = 0;
2963 ents->entries = NULL;
2964 ents->num_nonsurrogateDiagnostics = 0;
2965 ents->nonsurrogateDiagnostics = NULL;
2966 res->attributeSet = 0;
2969 if (req->databaseNames)
2972 for (i = 0; i < req->num_databaseNames; i++)
2973 yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
2975 bsrr->scanClause = 0;
2977 bsrr->errstring = 0;
2978 bsrr->num_bases = req->num_databaseNames;
2979 bsrr->basenames = req->databaseNames;
2980 bsrr->num_entries = *req->numberOfTermsRequested;
2981 bsrr->term = req->termListAndStartPoint;
2982 bsrr->referenceId = req->referenceId;
2983 bsrr->stream = assoc->encode;
2984 bsrr->print = assoc->print;
2985 bsrr->step_size = res->stepSize;
2987 /* For YAZ 2.0 and earlier it was the backend handler that
2988 initialized entries (member display_term did not exist)
2989 YAZ 2.0 and later sets 'entries' and initialize all members
2990 including 'display_term'. If YAZ 2.0 or later sees that
2991 entries was modified - we assume that it is an old handler and
2992 that 'display_term' is _not_ set.
2994 if (bsrr->num_entries > 0)
2997 bsrr->entries = odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
2999 for (i = 0; i<bsrr->num_entries; i++)
3001 bsrr->entries[i].term = 0;
3002 bsrr->entries[i].occurrences = 0;
3003 bsrr->entries[i].errcode = 0;
3004 bsrr->entries[i].errstring = 0;
3005 bsrr->entries[i].display_term = 0;
3008 save_entries = bsrr->entries; /* save it so we can compare later */
3010 if (req->attributeSet &&
3011 (attset = oid_getentbyoid(req->attributeSet)) &&
3012 (attset->oclass == CLASS_ATTSET || attset->oclass == CLASS_GENERAL))
3013 bsrr->attributeset = attset->value;
3015 bsrr->attributeset = VAL_NONE;
3016 log_scan_term_level (log_requestdetail, req->termListAndStartPoint,
3017 bsrr->attributeset);
3018 bsrr->term_position = req->preferredPositionInResponse ?
3019 *req->preferredPositionInResponse : 1;
3021 ((int (*)(void *, bend_scan_rr *))
3022 (*assoc->init->bend_scan))(assoc->backend, bsrr);
3025 diagrecs_p = zget_DiagRecs(assoc->encode,
3026 bsrr->errcode, bsrr->errstring);
3030 Z_Entry **tab = (Z_Entry **)
3031 odr_malloc (assoc->encode, sizeof(*tab) * bsrr->num_entries);
3033 if (bsrr->status == BEND_SCAN_PARTIAL)
3034 *scanStatus = Z_Scan_partial_5;
3036 *scanStatus = Z_Scan_success;
3037 ents->entries = tab;
3038 ents->num_entries = bsrr->num_entries;
3039 res->numberOfEntriesReturned = &ents->num_entries;
3040 res->positionOfTerm = &bsrr->term_position;
3041 for (i = 0; i < bsrr->num_entries; i++)
3047 tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
3048 if (bsrr->entries[i].occurrences >= 0)
3050 e->which = Z_Entry_termInfo;
3051 e->u.termInfo = t = (Z_TermInfo *)
3052 odr_malloc(assoc->encode, sizeof(*t));
3053 t->suggestedAttributes = 0;
3055 if (save_entries == bsrr->entries &&
3056 bsrr->entries[i].display_term)
3058 /* the entries was _not_ set by the handler. So it's
3059 safe to test for new member display_term. It is
3062 t->displayTerm = odr_strdup(assoc->encode,
3063 bsrr->entries[i].display_term);
3065 t->alternativeTerm = 0;
3066 t->byAttributes = 0;
3067 t->otherTermInfo = 0;
3068 t->globalOccurrences = &bsrr->entries[i].occurrences;
3069 t->term = (Z_Term *)
3070 odr_malloc(assoc->encode, sizeof(*t->term));
3071 t->term->which = Z_Term_general;
3072 t->term->u.general = o =
3073 (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
3074 o->buf = (unsigned char *)
3075 odr_malloc(assoc->encode, o->len = o->size =
3076 strlen(bsrr->entries[i].term));
3077 memcpy(o->buf, bsrr->entries[i].term, o->len);
3078 yaz_log(YLOG_DEBUG, " term #%d: '%s' (%d)", i,
3079 bsrr->entries[i].term, bsrr->entries[i].occurrences);
3083 Z_DiagRecs *drecs = zget_DiagRecs(assoc->encode,
3084 bsrr->entries[i].errcode,
3085 bsrr->entries[i].errstring);
3086 assert (drecs->num_diagRecs == 1);
3087 e->which = Z_Entry_surrogateDiagnostic;
3088 assert (drecs->diagRecs[0]);
3089 e->u.surrogateDiagnostic = drecs->diagRecs[0];
3095 ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
3096 ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
3101 WRBUF wr = wrbuf_alloc();
3102 wrbuf_printf(wr, "Scan ");
3103 for (i = 0 ; i < req->num_databaseNames; i++){
3105 wrbuf_printf(wr, "+");
3106 wrbuf_printf(wr, req->databaseNames[i]);
3108 wrbuf_printf(wr, " ");
3111 wr_diag(wr, bsrr->errcode, bsrr->errstring);
3112 wrbuf_printf(wr, " ");
3115 wrbuf_printf(wr, "OK ");
3116 /* else if (*res->scanStatus == Z_Scan_success) */
3117 /* wrbuf_printf(wr, "OK "); */
3119 /* wrbuf_printf(wr, "Partial "); */
3121 if (*res->numberOfEntriesReturned)
3122 wrbuf_printf(wr, "%d - ", *res->numberOfEntriesReturned);
3124 wrbuf_printf(wr, "0 - ");
3126 wrbuf_printf(wr, "%d+%d+%d ",
3127 (req->preferredPositionInResponse ?
3128 *req->preferredPositionInResponse : 1),
3129 *req->numberOfTermsRequested,
3130 (res->stepSize ? *res->stepSize : 1));
3132 yaz_scan_to_wrbuf(wr, req->termListAndStartPoint,
3133 bsrr->attributeset);
3134 yaz_log(log_request, "%s", wrbuf_buf(wr) );
3140 static Z_APDU *process_sortRequest(association *assoc, request *reqb,
3144 Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
3145 Z_SortResponse *res = (Z_SortResponse *)
3146 odr_malloc (assoc->encode, sizeof(*res));
3147 bend_sort_rr *bsrr = (bend_sort_rr *)
3148 odr_malloc (assoc->encode, sizeof(*bsrr));
3150 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
3152 yaz_log(log_requestdetail, "Got SortRequest.");
3154 bsrr->num_input_setnames = req->num_inputResultSetNames;
3155 for (i=0;i<req->num_inputResultSetNames;i++)
3156 yaz_log(log_requestdetail, "Input resultset: '%s'",
3157 req->inputResultSetNames[i]);
3158 bsrr->input_setnames = req->inputResultSetNames;
3159 bsrr->referenceId = req->referenceId;
3160 bsrr->output_setname = req->sortedResultSetName;
3161 yaz_log(log_requestdetail, "Output resultset: '%s'",
3162 req->sortedResultSetName);
3163 bsrr->sort_sequence = req->sortSequence;
3164 /*FIXME - dump those sequences too */
3165 bsrr->stream = assoc->encode;
3166 bsrr->print = assoc->print;
3168 bsrr->sort_status = Z_SortResponse_failure;
3170 bsrr->errstring = 0;
3172 (*assoc->init->bend_sort)(assoc->backend, bsrr);
3174 res->referenceId = bsrr->referenceId;
3175 res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
3176 res->resultSetStatus = 0;
3179 Z_DiagRecs *dr = zget_DiagRecs(assoc->encode,
3180 bsrr->errcode, bsrr->errstring);
3181 res->diagnostics = dr->diagRecs;
3182 res->num_diagnostics = dr->num_diagRecs;
3186 res->num_diagnostics = 0;
3187 res->diagnostics = 0;
3189 res->resultCount = 0;
3192 apdu->which = Z_APDU_sortResponse;
3193 apdu->u.sortResponse = res;
3196 WRBUF wr = wrbuf_alloc();
3197 wrbuf_printf(wr, "Sort ");
3199 wrbuf_printf(wr, " ERROR %d", bsrr->errcode);
3201 wrbuf_printf(wr, "OK -");
3202 wrbuf_printf(wr, " (");
3203 for (i = 0; i<req->num_inputResultSetNames; i++)
3206 wrbuf_printf(wr, "+");
3207 wrbuf_printf(wr, req->inputResultSetNames[i]);
3209 wrbuf_printf(wr, ")->%s ",req->sortedResultSetName);
3211 yaz_log(log_request, "%s", wrbuf_buf(wr) );
3217 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
3221 Z_DeleteResultSetRequest *req =
3222 reqb->apdu_request->u.deleteResultSetRequest;
3223 Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
3224 odr_malloc (assoc->encode, sizeof(*res));
3225 bend_delete_rr *bdrr = (bend_delete_rr *)
3226 odr_malloc (assoc->encode, sizeof(*bdrr));
3227 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
3229 yaz_log(log_requestdetail, "Got DeleteRequest.");
3231 bdrr->num_setnames = req->num_resultSetList;
3232 bdrr->setnames = req->resultSetList;
3233 for (i = 0; i<req->num_resultSetList; i++)
3234 yaz_log(log_requestdetail, "resultset: '%s'",
3235 req->resultSetList[i]);
3236 bdrr->stream = assoc->encode;
3237 bdrr->print = assoc->print;
3238 bdrr->function = *req->deleteFunction;
3239 bdrr->referenceId = req->referenceId;
3241 if (bdrr->num_setnames > 0)
3243 bdrr->statuses = (int*)
3244 odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
3245 bdrr->num_setnames);
3246 for (i = 0; i < bdrr->num_setnames; i++)
3247 bdrr->statuses[i] = 0;
3249 (*assoc->init->bend_delete)(assoc->backend, bdrr);
3251 res->referenceId = req->referenceId;
3253 res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
3255 res->deleteListStatuses = 0;
3256 if (bdrr->num_setnames > 0)
3259 res->deleteListStatuses = (Z_ListStatuses *)
3260 odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
3261 res->deleteListStatuses->num = bdrr->num_setnames;
3262 res->deleteListStatuses->elements =
3264 odr_malloc (assoc->encode,
3265 sizeof(*res->deleteListStatuses->elements) *
3266 bdrr->num_setnames);
3267 for (i = 0; i<bdrr->num_setnames; i++)
3269 res->deleteListStatuses->elements[i] =
3271 odr_malloc (assoc->encode,
3272 sizeof(**res->deleteListStatuses->elements));
3273 res->deleteListStatuses->elements[i]->status = bdrr->statuses+i;
3274 res->deleteListStatuses->elements[i]->id =
3275 odr_strdup (assoc->encode, bdrr->setnames[i]);
3278 res->numberNotDeleted = 0;
3279 res->bulkStatuses = 0;
3280 res->deleteMessage = 0;
3283 apdu->which = Z_APDU_deleteResultSetResponse;
3284 apdu->u.deleteResultSetResponse = res;
3287 WRBUF wr = wrbuf_alloc();
3288 wrbuf_printf(wr, "Delete ");
3289 if (bdrr->delete_status)
3290 wrbuf_printf(wr, "ERROR %d", bdrr->delete_status);
3292 wrbuf_printf(wr, "OK -");
3293 for (i = 0; i<req->num_resultSetList; i++)
3294 wrbuf_printf(wr, " %s ", req->resultSetList[i]);
3295 yaz_log(log_request, "%s", wrbuf_buf(wr) );
3301 static void process_close(association *assoc, request *reqb)
3303 Z_Close *req = reqb->apdu_request->u.close;
3304 static char *reasons[] =
3311 "securityViolation",
3318 yaz_log(log_requestdetail, "Got Close, reason %s, message %s",
3319 reasons[*req->closeReason], req->diagnosticInformation ?
3320 req->diagnosticInformation : "NULL");
3321 if (assoc->version < 3) /* to make do_force respond with close */
3323 do_close_req(assoc, Z_Close_finished,
3324 "Association terminated by client", reqb);
3325 yaz_log(log_request,"Close OK");
3328 void save_referenceId (request *reqb, Z_ReferenceId *refid)
3332 reqb->len_refid = refid->len;
3333 reqb->refid = (char *)nmem_malloc (reqb->request_mem, refid->len);
3334 memcpy (reqb->refid, refid->buf, refid->len);
3338 reqb->len_refid = 0;
3343 void bend_request_send (bend_association a, bend_request req, Z_APDU *res)
3345 process_z_response (a, req, res);
3348 bend_request bend_request_mk (bend_association a)
3350 request *nreq = request_get (&a->outgoing);
3351 nreq->request_mem = nmem_create ();
3355 Z_ReferenceId *bend_request_getid (ODR odr, bend_request req)
3360 id = (Odr_oct *)odr_malloc (odr, sizeof(*odr));
3361 id->buf = (unsigned char *)odr_malloc (odr, req->len_refid);
3362 id->len = id->size = req->len_refid;
3363 memcpy (id->buf, req->refid, req->len_refid);
3367 void bend_request_destroy (bend_request *req)
3369 nmem_destroy((*req)->request_mem);
3370 request_release(*req);
3374 int bend_backend_respond (bend_association a, bend_request req)
3378 r = process_z_request (a, req, &msg);
3380 yaz_log (YLOG_WARN, "%s", msg);
3384 void bend_request_setdata(bend_request r, void *p)
3389 void *bend_request_getdata(bend_request r)
3391 return r->clientData;
3394 static Z_APDU *process_segmentRequest (association *assoc, request *reqb)
3396 bend_segment_rr req;
3398 req.segment = reqb->apdu_request->u.segmentRequest;
3399 req.stream = assoc->encode;
3400 req.decode = assoc->decode;
3401 req.print = assoc->print;
3402 req.association = assoc;
3404 (*assoc->init->bend_segment)(assoc->backend, &req);
3409 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd)
3411 bend_esrequest_rr esrequest;
3412 const char *ext_name = "unknown";
3414 Z_ExtendedServicesRequest *req =
3415 reqb->apdu_request->u.extendedServicesRequest;
3416 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
3418 Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
3420 esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
3421 esrequest.stream = assoc->encode;
3422 esrequest.decode = assoc->decode;
3423 esrequest.print = assoc->print;
3424 esrequest.errcode = 0;
3425 esrequest.errstring = NULL;
3426 esrequest.request = reqb;
3427 esrequest.association = assoc;
3428 esrequest.taskPackage = 0;
3429 esrequest.referenceId = req->referenceId;
3432 if (esrequest.esr && esrequest.esr->taskSpecificParameters)
3434 switch(esrequest.esr->taskSpecificParameters->which)
3436 case Z_External_itemOrder:
3437 ext_name = "ItemOrder"; break;
3438 case Z_External_update:
3439 ext_name = "Update"; break;
3440 case Z_External_update0:
3441 ext_name = "Update0"; break;
3442 case Z_External_ESAdmin:
3443 ext_name = "Admin"; break;
3448 (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
3450 /* If the response is being delayed, return NULL */
3451 if (esrequest.request == NULL)
3454 resp->referenceId = req->referenceId;
3456 if (esrequest.errcode == -1)
3458 /* Backend service indicates request will be processed */
3459 yaz_log(log_request, "Extended Service: %s (accepted)", ext_name);
3460 *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
3462 else if (esrequest.errcode == 0)
3464 /* Backend service indicates request will be processed */
3465 yaz_log(log_request, "Extended Service: %s (done)", ext_name);
3466 *resp->operationStatus = Z_ExtendedServicesResponse_done;
3470 Z_DiagRecs *diagRecs =
3471 zget_DiagRecs(assoc->encode, esrequest.errcode,
3472 esrequest.errstring);
3473 /* Backend indicates error, request will not be processed */
3474 yaz_log(log_request, "Extended Service: %s (failed)", ext_name);
3475 *resp->operationStatus = Z_ExtendedServicesResponse_failure;
3476 resp->num_diagnostics = diagRecs->num_diagRecs;
3477 resp->diagnostics = diagRecs->diagRecs;
3480 WRBUF wr = wrbuf_alloc();
3481 wrbuf_diags(wr, resp->num_diagnostics, resp->diagnostics);
3482 yaz_log(log_request, "EsRequest %s", wrbuf_buf(wr) );
3487 /* Do something with the members of bend_extendedservice */
3488 if (esrequest.taskPackage)
3489 resp->taskPackage = z_ext_record (assoc->encode, VAL_EXTENDED,
3490 (const char *) esrequest.taskPackage,
3492 yaz_log(YLOG_DEBUG,"Send the result apdu");
3499 * indent-tabs-mode: nil
3501 * vim: shiftwidth=4 tabstop=8 expandtab