2 * Copyright (C) 1995-2005, Index Data ApS
3 * See the file LICENSE for details.
5 * $Id: seshigh.c,v 1.94 2006-07-07 13:02:21 marc 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)
696 ODR o = assoc->encode;
698 rr.setname = "default";
701 rr.request_format = VAL_TEXT_XML;
702 rr.request_format_raw = yaz_oidval_to_z3950oid(assoc->decode,
705 rr.comp = (Z_RecordComposition *)
706 odr_malloc(assoc->decode, sizeof(*rr.comp));
707 rr.comp->which = Z_RecordComp_complex;
708 rr.comp->u.complex = (Z_CompSpec *)
709 odr_malloc(assoc->decode, sizeof(Z_CompSpec));
710 rr.comp->u.complex->selectAlternativeSyntax = (bool_t *)
711 odr_malloc(assoc->encode, sizeof(bool_t));
712 *rr.comp->u.complex->selectAlternativeSyntax = 0;
713 rr.comp->u.complex->num_dbSpecific = 0;
714 rr.comp->u.complex->dbSpecific = 0;
715 rr.comp->u.complex->num_recordSyntax = 0;
716 rr.comp->u.complex->recordSyntax = 0;
718 rr.comp->u.complex->generic = (Z_Specification *)
719 odr_malloc(assoc->decode, sizeof(Z_Specification));
721 /* schema uri = recordSchema (or NULL if recordSchema is not given) */
722 rr.comp->u.complex->generic->which = Z_Schema_uri;
723 rr.comp->u.complex->generic->schema.uri = srw_req->recordSchema;
725 /* ESN = recordSchema if recordSchema is present */
726 rr.comp->u.complex->generic->elementSpec = 0;
727 if (srw_req->recordSchema)
729 rr.comp->u.complex->generic->elementSpec =
730 (Z_ElementSpec *) odr_malloc(assoc->encode, sizeof(Z_ElementSpec));
731 rr.comp->u.complex->generic->elementSpec->which =
732 Z_ElementSpec_elementSetName;
733 rr.comp->u.complex->generic->elementSpec->u.elementSetName =
734 srw_req->recordSchema;
737 rr.stream = assoc->encode;
738 rr.print = assoc->print;
746 rr.surrogate_flag = 0;
747 rr.schema = srw_req->recordSchema;
749 if (!assoc->init->bend_fetch)
752 retrieve_fetch(assoc, &rr);
754 if (rr.errcode && rr.surrogate_flag)
756 int code = yaz_diag_bib1_to_srw(rr.errcode);
757 const char *message = yaz_diag_srw_str(code);
760 len += strlen(message);
762 len += strlen(rr.errstring);
764 record->recordData_buf = odr_malloc(o, len);
766 sprintf(record->recordData_buf, "<diagnostic "
767 "xmlns=\"http://www.loc.gov/zing/srw/diagnostic/\">\n"
768 " <uri>info:srw/diagnostic/1/%d</uri>\n", code);
770 sprintf(record->recordData_buf + strlen(record->recordData_buf),
771 " <details>%s</details>\n", rr.errstring);
773 sprintf(record->recordData_buf + strlen(record->recordData_buf),
774 " <message>%s</message>\n", message);
775 sprintf(record->recordData_buf + strlen(record->recordData_buf),
777 record->recordData_len = strlen(record->recordData_buf);
778 record->recordPosition = odr_intdup(o, pos);
779 record->recordSchema = "info:srw/schema/1/diagnostics-v1.1";
782 else if (rr.len >= 0)
784 record->recordData_buf = rr.record;
785 record->recordData_len = rr.len;
786 record->recordPosition = odr_intdup(o, pos);
788 record->recordSchema = odr_strdup(o, rr.schema);
790 record->recordSchema = 0;
795 static int cql2pqf(ODR odr, const char *cql, cql_transform_t ct,
796 Z_Query *query_result)
798 /* have a CQL query and CQL to PQF transform .. */
799 CQL_parser cp = cql_parser_create();
805 r = cql_parser_string(cp, cql);
808 /* CQL syntax error */
814 r = cql_transform_buf(ct,
815 cql_parser_result(cp),
816 rpn_buf, sizeof(rpn_buf)-1);
818 srw_errcode = cql_transform_error(ct, &add);
822 /* Syntax & transform OK. */
823 /* Convert PQF string to Z39.50 to RPN query struct */
824 YAZ_PQF_Parser pp = yaz_pqf_create();
825 Z_RPNQuery *rpnquery = yaz_pqf_parse(pp, odr, rpn_buf);
830 int code = yaz_pqf_error(pp, &pqf_msg, &off);
831 yaz_log(YLOG_WARN, "PQF Parser Error %s (code %d)",
837 query_result->which = Z_Query_type_1;
838 query_result->u.type_1 = rpnquery;
842 cql_parser_destroy(cp);
846 static int cql2pqf_scan(ODR odr, const char *cql, cql_transform_t ct,
847 Z_AttributesPlusTerm *result)
851 int srw_error = cql2pqf(odr, cql, ct, &query);
854 if (query.which != Z_Query_type_1 && query.which != Z_Query_type_101)
855 return 10; /* bad query type */
856 rpn = query.u.type_1;
857 if (!rpn->RPNStructure)
858 return 10; /* must be structure */
859 if (rpn->RPNStructure->which != Z_RPNStructure_simple)
860 return 10; /* must be simple */
861 if (rpn->RPNStructure->u.simple->which != Z_Operand_APT)
862 return 10; /* must be attributes plus term node .. */
863 memcpy(result, rpn->RPNStructure->u.simple->u.attributesPlusTerm,
868 static void srw_bend_search(association *assoc, request *req,
870 Z_SRW_searchRetrieveResponse *srw_res,
875 Z_SRW_searchRetrieveRequest *srw_req = sr->u.request;
878 yaz_log(log_requestdetail, "Got SRW SearchRetrieveRequest");
879 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
880 if (srw_res->num_diagnostics == 0 && assoc->init)
883 rr.setname = "default";
886 rr.basenames = &srw_req->database;
890 rr.srw_setnameIdleTime = 0;
891 rr.query = (Z_Query *) odr_malloc (assoc->decode, sizeof(*rr.query));
892 rr.query->u.type_1 = 0;
894 if (srw_req->query_type == Z_SRW_query_type_cql)
896 if (assoc->server && assoc->server->cql_transform)
898 int srw_errcode = cql2pqf(assoc->encode, srw_req->query.cql,
899 assoc->server->cql_transform,
903 yaz_add_srw_diagnostic(assoc->encode,
904 &srw_res->diagnostics,
905 &srw_res->num_diagnostics,
911 /* CQL query to backend. Wrap it - Z39.50 style */
912 ext = (Z_External *) odr_malloc(assoc->decode, sizeof(*ext));
913 ext->direct_reference = odr_getoidbystr(assoc->decode,
914 "1.2.840.10003.16.2");
915 ext->indirect_reference = 0;
917 ext->which = Z_External_CQL;
918 ext->u.cql = srw_req->query.cql;
920 rr.query->which = Z_Query_type_104;
921 rr.query->u.type_104 = ext;
924 else if (srw_req->query_type == Z_SRW_query_type_pqf)
926 Z_RPNQuery *RPNquery;
927 YAZ_PQF_Parser pqf_parser;
929 pqf_parser = yaz_pqf_create ();
931 RPNquery = yaz_pqf_parse (pqf_parser, assoc->decode,
937 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
938 yaz_log(log_requestdetail, "Parse error %d %s near offset %ld",
939 code, pqf_msg, (long) off);
940 srw_error = YAZ_SRW_QUERY_SYNTAX_ERROR;
943 rr.query->which = Z_Query_type_1;
944 rr.query->u.type_1 = RPNquery;
946 yaz_pqf_destroy (pqf_parser);
950 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
951 &srw_res->num_diagnostics,
952 YAZ_SRW_UNSUPP_QUERY_TYPE, 0);
954 if (rr.query->u.type_1)
956 rr.stream = assoc->encode;
957 rr.decode = assoc->decode;
958 rr.print = assoc->print;
960 if ( srw_req->sort.sortKeys )
961 rr.srw_sortKeys = odr_strdup(assoc->encode,
962 srw_req->sort.sortKeys );
963 rr.association = assoc;
969 yaz_log_zquery_level(log_requestdetail,rr.query);
971 (assoc->init->bend_search)(assoc->backend, &rr);
974 if (rr.errcode == YAZ_BIB1_DATABASE_UNAVAILABLE)
980 srw_error = yaz_diag_bib1_to_srw (rr.errcode);
981 yaz_add_srw_diagnostic(assoc->encode,
982 &srw_res->diagnostics,
983 &srw_res->num_diagnostics,
984 srw_error, rr.errstring);
989 int number = srw_req->maximumRecords ? *srw_req->maximumRecords : 0;
990 int start = srw_req->startRecord ? *srw_req->startRecord : 1;
992 yaz_log(log_requestdetail, "Request to pack %d+%d out of %d",
993 start, number, rr.hits);
995 srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
998 srw_res->resultSetId =
999 odr_strdup(assoc->encode, rr.srw_setname );
1000 srw_res->resultSetIdleTime =
1001 odr_intdup(assoc->encode, *rr.srw_setnameIdleTime );
1007 if (start > rr.hits)
1009 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1010 &srw_res->num_diagnostics,
1011 YAZ_SRW_FIRST_RECORD_POSITION_OUT_OF_RANGE, 0);
1016 if (start + number > rr.hits)
1017 number = rr.hits - start + 1;
1019 /* Call bend_present if defined */
1020 if (assoc->init->bend_present)
1022 bend_present_rr *bprr = (bend_present_rr*)
1023 odr_malloc (assoc->decode, sizeof(*bprr));
1024 bprr->setname = "default";
1025 bprr->start = start;
1026 bprr->number = number;
1027 bprr->format = VAL_TEXT_XML;
1028 if (srw_req->recordSchema)
1030 bprr->comp = (Z_RecordComposition *) odr_malloc(assoc->decode,
1031 sizeof(*bprr->comp));
1032 bprr->comp->which = Z_RecordComp_simple;
1033 bprr->comp->u.simple = (Z_ElementSetNames *)
1034 odr_malloc(assoc->decode, sizeof(Z_ElementSetNames));
1035 bprr->comp->u.simple->which = Z_ElementSetNames_generic;
1036 bprr->comp->u.simple->u.generic = srw_req->recordSchema;
1042 bprr->stream = assoc->encode;
1043 bprr->referenceId = 0;
1044 bprr->print = assoc->print;
1045 bprr->request = req;
1046 bprr->association = assoc;
1048 bprr->errstring = NULL;
1049 (*assoc->init->bend_present)(assoc->backend, bprr);
1055 srw_error = yaz_diag_bib1_to_srw (bprr->errcode);
1056 yaz_add_srw_diagnostic(assoc->encode,
1057 &srw_res->diagnostics,
1058 &srw_res->num_diagnostics,
1059 srw_error, bprr->errstring);
1067 int packing = Z_SRW_recordPacking_string;
1068 if (srw_req->recordPacking){
1069 if (!strcmp(srw_req->recordPacking, "xml"))
1070 packing = Z_SRW_recordPacking_XML;
1071 if (!strcmp(srw_req->recordPacking, "url"))
1072 packing = Z_SRW_recordPacking_URL;
1074 srw_res->records = (Z_SRW_record *)
1075 odr_malloc(assoc->encode,
1076 number * sizeof(*srw_res->records));
1078 srw_res->extra_records = (Z_SRW_extra_record **)
1079 odr_malloc(assoc->encode,
1080 number*sizeof(*srw_res->extra_records));
1082 for (i = 0; i<number; i++)
1086 srw_res->records[j].recordPacking = packing;
1087 srw_res->records[j].recordData_buf = 0;
1088 srw_res->extra_records[j] = 0;
1089 yaz_log(YLOG_DEBUG, "srw_bend_fetch %d", i+start);
1090 errcode = srw_bend_fetch(assoc, i+start, srw_req,
1091 srw_res->records + j);
1094 yaz_add_srw_diagnostic(assoc->encode,
1095 &srw_res->diagnostics,
1096 &srw_res->num_diagnostics,
1097 yaz_diag_bib1_to_srw (errcode),
1102 if (srw_res->records[j].recordData_buf)
1105 srw_res->num_records = j;
1107 srw_res->records = 0;
1116 const char *querystr = "?";
1117 const char *querytype = "?";
1118 WRBUF wr = wrbuf_alloc();
1120 switch (srw_req->query_type)
1122 case Z_SRW_query_type_cql:
1124 querystr = srw_req->query.cql;
1126 case Z_SRW_query_type_pqf:
1128 querystr = srw_req->query.pqf;
1131 wrbuf_printf(wr, "SRWSearch ");
1132 wrbuf_printf(wr, srw_req->database);
1133 wrbuf_printf(wr, " ");
1134 if (srw_res->num_diagnostics)
1135 wrbuf_printf(wr, "ERROR %s", srw_res->diagnostics[0].uri);
1136 else if (*http_code != 200)
1137 wrbuf_printf(wr, "ERROR info:http/%d", *http_code);
1138 else if (srw_res->numberOfRecords)
1140 wrbuf_printf(wr, "OK %d",
1141 (srw_res->numberOfRecords ?
1142 *srw_res->numberOfRecords : 0));
1144 wrbuf_printf(wr, " %s %d+%d",
1145 (srw_res->resultSetId ?
1146 srw_res->resultSetId : "-"),
1147 (srw_req->startRecord ? *srw_req->startRecord : 1),
1148 srw_res->num_records);
1149 yaz_log(log_request, "%s %s: %s", wrbuf_buf(wr), querytype, querystr);
1154 static char *srw_bend_explain_default(void *handle, bend_explain_rr *rr)
1157 xmlNodePtr ptr = rr->server_node_ptr;
1160 for (ptr = ptr->children; ptr; ptr = ptr->next)
1162 if (ptr->type != XML_ELEMENT_NODE)
1164 if (!strcmp((const char *) ptr->name, "explain"))
1167 xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
1171 ptr = xmlCopyNode(ptr, 1);
1173 xmlDocSetRootElement(doc, ptr);
1175 xmlDocDumpMemory(doc, &buf_out, &len);
1176 content = (char*) odr_malloc(rr->stream, 1+len);
1177 memcpy(content, buf_out, len);
1178 content[len] = '\0';
1182 rr->explain_buf = content;
1190 static void srw_bend_explain(association *assoc, request *req,
1192 Z_SRW_explainResponse *srw_res,
1195 Z_SRW_explainRequest *srw_req = sr->u.explain_request;
1196 yaz_log(log_requestdetail, "Got SRW ExplainRequest");
1198 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1203 rr.stream = assoc->encode;
1204 rr.decode = assoc->decode;
1205 rr.print = assoc->print;
1207 rr.database = srw_req->database;
1209 rr.server_node_ptr = assoc->server->server_node_ptr;
1211 rr.server_node_ptr = 0;
1212 rr.schema = "http://explain.z3950.org/dtd/2.0/";
1213 if (assoc->init->bend_explain)
1214 (*assoc->init->bend_explain)(assoc->backend, &rr);
1216 srw_bend_explain_default(assoc->backend, &rr);
1220 int packing = Z_SRW_recordPacking_string;
1221 if (srw_req->recordPacking)
1223 if (!strcmp(srw_req->recordPacking, "xml"))
1224 packing = Z_SRW_recordPacking_XML;
1225 else if (!strcmp(srw_req->recordPacking, "url"))
1226 packing = Z_SRW_recordPacking_URL;
1228 srw_res->record.recordSchema = rr.schema;
1229 srw_res->record.recordPacking = packing;
1230 srw_res->record.recordData_buf = rr.explain_buf;
1231 srw_res->record.recordData_len = strlen(rr.explain_buf);
1232 srw_res->record.recordPosition = 0;
1238 static void srw_bend_scan(association *assoc, request *req,
1240 Z_SRW_scanResponse *srw_res,
1243 Z_SRW_scanRequest *srw_req = sr->u.scan_request;
1244 yaz_log(log_requestdetail, "Got SRW ScanRequest");
1247 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1248 if (srw_res->num_diagnostics == 0 && assoc->init)
1250 struct scan_entry *save_entries;
1252 bend_scan_rr *bsrr = (bend_scan_rr *)
1253 odr_malloc (assoc->encode, sizeof(*bsrr));
1254 bsrr->num_bases = 1;
1255 bsrr->basenames = &srw_req->database;
1257 bsrr->num_entries = srw_req->maximumTerms ?
1258 *srw_req->maximumTerms : 10;
1259 bsrr->term_position = srw_req->responsePosition ?
1260 *srw_req->responsePosition : 1;
1263 bsrr->errstring = 0;
1264 bsrr->referenceId = 0;
1265 bsrr->stream = assoc->encode;
1266 bsrr->print = assoc->print;
1267 bsrr->step_size = odr_intdup(assoc->decode, 0);
1270 if (bsrr->num_entries > 0)
1273 bsrr->entries = odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
1275 for (i = 0; i<bsrr->num_entries; i++)
1277 bsrr->entries[i].term = 0;
1278 bsrr->entries[i].occurrences = 0;
1279 bsrr->entries[i].errcode = 0;
1280 bsrr->entries[i].errstring = 0;
1281 bsrr->entries[i].display_term = 0;
1284 save_entries = bsrr->entries; /* save it so we can compare later */
1286 if (srw_req->query_type == Z_SRW_query_type_pqf &&
1287 assoc->init->bend_scan)
1289 Odr_oid *scan_attributeSet = 0;
1291 YAZ_PQF_Parser pqf_parser = yaz_pqf_create();
1293 bsrr->term = yaz_pqf_scan(pqf_parser, assoc->decode,
1295 srw_req->scanClause.pqf);
1296 if (scan_attributeSet &&
1297 (attset = oid_getentbyoid(scan_attributeSet)) &&
1298 (attset->oclass == CLASS_ATTSET ||
1299 attset->oclass == CLASS_GENERAL))
1300 bsrr->attributeset = attset->value;
1302 bsrr->attributeset = VAL_NONE;
1303 yaz_pqf_destroy(pqf_parser);
1304 bsrr->scanClause = 0;
1305 ((int (*)(void *, bend_scan_rr *))
1306 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1308 else if (srw_req->query_type == Z_SRW_query_type_cql
1309 && assoc->init->bend_scan && assoc->server
1310 && assoc->server->cql_transform)
1313 bsrr->scanClause = 0;
1314 bsrr->attributeset = VAL_NONE;
1315 bsrr->term = odr_malloc(assoc->decode, sizeof(*bsrr->term));
1316 srw_error = cql2pqf_scan(assoc->encode,
1317 srw_req->scanClause.cql,
1318 assoc->server->cql_transform,
1321 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1322 &srw_res->num_diagnostics,
1326 ((int (*)(void *, bend_scan_rr *))
1327 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1330 else if (srw_req->query_type == Z_SRW_query_type_cql
1331 && assoc->init->bend_srw_scan)
1334 bsrr->attributeset = VAL_NONE;
1335 bsrr->scanClause = srw_req->scanClause.cql;
1336 ((int (*)(void *, bend_scan_rr *))
1337 (*assoc->init->bend_srw_scan))(assoc->backend, bsrr);
1341 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1342 &srw_res->num_diagnostics,
1343 YAZ_SRW_UNSUPP_OPERATION, "scan");
1348 if (bsrr->errcode == YAZ_BIB1_DATABASE_UNAVAILABLE)
1353 srw_error = yaz_diag_bib1_to_srw (bsrr->errcode);
1355 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1356 &srw_res->num_diagnostics,
1357 srw_error, bsrr->errstring);
1359 else if (srw_res->num_diagnostics == 0 && bsrr->num_entries)
1362 srw_res->terms = (Z_SRW_scanTerm*)
1363 odr_malloc(assoc->encode, sizeof(*srw_res->terms) *
1366 srw_res->num_terms = bsrr->num_entries;
1367 for (i = 0; i<bsrr->num_entries; i++)
1369 Z_SRW_scanTerm *t = srw_res->terms + i;
1370 t->value = odr_strdup(assoc->encode, bsrr->entries[i].term);
1371 t->numberOfRecords =
1372 odr_intdup(assoc->encode, bsrr->entries[i].occurrences);
1374 if (save_entries == bsrr->entries &&
1375 bsrr->entries[i].display_term)
1377 /* the entries was _not_ set by the handler. So it's
1378 safe to test for new member display_term. It is
1381 t->displayTerm = odr_strdup(assoc->encode,
1382 bsrr->entries[i].display_term);
1390 WRBUF wr = wrbuf_alloc();
1391 const char *querytype = 0;
1392 const char *querystr = 0;
1394 switch(srw_req->query_type)
1396 case Z_SRW_query_type_pqf:
1398 querystr = srw_req->scanClause.pqf;
1400 case Z_SRW_query_type_cql:
1402 querystr = srw_req->scanClause.cql;
1405 querytype = "UNKNOWN";
1409 wrbuf_printf(wr, "SRWScan ");
1410 wrbuf_printf(wr, srw_req->database);
1411 wrbuf_printf(wr, " ");
1413 if (srw_res->num_diagnostics)
1414 wrbuf_printf(wr, "ERROR %s - ", srw_res->diagnostics[0].uri);
1415 else if (srw_res->num_terms)
1416 wrbuf_printf(wr, "OK %d - ", srw_res->num_terms);
1418 wrbuf_printf(wr, "OK - - ");
1420 wrbuf_printf(wr, "%d+%d+0 ",
1421 (srw_req->responsePosition ?
1422 *srw_req->responsePosition : 1),
1423 (srw_req->maximumTerms ?
1424 *srw_req->maximumTerms : 1));
1425 /* there is no step size in SRU/W ??? */
1426 wrbuf_printf(wr, "%s: %s ", querytype, querystr);
1427 yaz_log(log_request, "%s ", wrbuf_buf(wr) );
1433 static void srw_bend_update(association *assoc, request *req,
1435 Z_SRW_updateResponse *srw_res,
1438 Z_SRW_updateRequest *srw_req = sr->u.update_request;
1439 yaz_log(YLOG_DEBUG, "Got SRW UpdateRequest");
1440 yaz_log(YLOG_DEBUG, "num_diag = %d", srw_res->num_diagnostics );
1442 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1447 rr.stream = assoc->encode;
1448 rr.print = assoc->print;
1450 rr.basenames = &srw_req->database;
1451 rr.operation = srw_req->operation;
1452 rr.operation_status = "failed";
1454 rr.record_version = 0;
1455 rr.record_checksum = 0;
1456 rr.record_old_version = 0;
1457 rr.record_packing = "xml";
1458 rr.record_schema = 0;
1460 rr.request_extra_record = 0;
1461 rr.response_extra_record = 0;
1462 rr.extra_request_data = 0;
1463 rr.extra_response_data = 0;
1468 yaz_log(YLOG_DEBUG, "basename = %s", rr.basenames[0] );
1469 yaz_log(YLOG_DEBUG, "Operation = %s", rr.operation );
1470 if ( !strcmp( rr.operation, "delete" ) ){
1471 if ( !srw_req->recordId ){
1472 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1473 &srw_res->num_diagnostics,
1477 rr.record_id = srw_req->recordId;
1479 if ( !srw_req->recordVersion ){
1480 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1481 &srw_res->num_diagnostics,
1482 7, "recordVersion" );
1485 rr.record_version = odr_strdup( assoc->encode,
1486 srw_req->recordVersion );
1489 if ( srw_req->recordOldVersion ){
1490 rr.record_old_version = odr_strdup(assoc->encode,
1491 srw_req->recordOldVersion );
1493 if ( srw_req->extraRequestData ){
1494 rr.extra_request_data = odr_strdup(assoc->encode,
1495 srw_req->extraRequestData );
1498 else if ( !strcmp( rr.operation, "replace" ) ){
1499 if ( !srw_req->recordId ){
1500 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1501 &srw_res->num_diagnostics,
1505 rr.record_id = srw_req->recordId;
1507 if ( srw_req->record.recordSchema == 0 ){
1508 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1509 &srw_res->num_diagnostics,
1510 7, "recordSchema" );
1513 rr.record_schema = odr_strdup(assoc->encode,
1514 srw_req->record.recordSchema );
1516 switch (srw_req->record.recordPacking)
1518 case Z_SRW_recordPacking_string:
1519 rr.record_packing = "string";
1521 case Z_SRW_recordPacking_XML:
1522 rr.record_packing = "xml";
1524 case Z_SRW_recordPacking_URL:
1525 rr.record_packing = "url";
1528 if ( srw_req->record.recordData_len ){
1529 rr.record_data = odr_strdupn(assoc->encode,
1530 srw_req->record.recordData_buf,
1531 srw_req->record.recordData_len );
1532 rr.request_extra_record = srw_req->extra_record;
1535 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1536 &srw_res->num_diagnostics,
1539 if (srw_req->extraRequestData)
1540 rr.extra_request_data = odr_strdup(assoc->encode,
1541 srw_req->extraRequestData );
1543 else if ( !strcmp( rr.operation, "insert" ) )
1545 rr.record_id = srw_req->recordId;
1546 if ( srw_req->record.recordSchema == 0 ){
1547 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1548 &srw_res->num_diagnostics,
1549 7, "recordSchema" );
1552 rr.record_schema = odr_strdup(assoc->encode,
1553 srw_req->record.recordSchema);
1555 switch (srw_req->record.recordPacking)
1557 case Z_SRW_recordPacking_string:
1558 rr.record_packing = "string";
1560 case Z_SRW_recordPacking_XML:
1561 rr.record_packing = "xml";
1563 case Z_SRW_recordPacking_URL:
1564 rr.record_packing = "url";
1568 if (srw_req->record.recordData_len)
1570 rr.record_data = odr_strdupn(assoc->encode,
1571 srw_req->record.recordData_buf,
1572 srw_req->record.recordData_len );
1573 rr.request_extra_record = srw_req->extra_record;
1576 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1577 &srw_res->num_diagnostics,
1579 if ( srw_req->extraRequestData )
1580 rr.extra_request_data = odr_strdup(assoc->encode,
1581 srw_req->extraRequestData );
1583 if (srw_res->num_diagnostics == 0)
1585 if ( assoc->init->bend_srw_update)
1586 (*assoc->init->bend_srw_update)(assoc->backend, &rr);
1588 yaz_log( YLOG_WARN, "Got No Update function!");
1594 yaz_add_srw_diagnostic_uri(assoc->encode,
1595 &srw_res->diagnostics,
1596 &srw_res->num_diagnostics,
1600 srw_res->recordId = rr.record_id;
1601 srw_res->operationStatus = rr.operation_status;
1602 srw_res->recordVersion = rr.record_version;
1603 srw_res->recordChecksum = rr.record_checksum;
1604 srw_res->extraResponseData = rr.extra_response_data;
1605 srw_res->record.recordPosition = 0;
1606 if (srw_res->num_diagnostics == 0 && rr.record_data)
1608 srw_res->record.recordSchema = rr.record_schema;
1609 srw_res->record.recordPacking = srw_req->record.recordPacking;
1610 srw_res->record.recordData_buf = rr.record_data;
1611 srw_res->record.recordData_len = strlen(rr.record_data);
1612 srw_res->extra_record = rr.response_extra_record;
1616 srw_res->record.recordData_len = 0;
1621 /* check if path is OK (1); BAD (0) */
1622 static int check_path(const char *path)
1626 if (strstr(path, ".."))
1631 static char *read_file(const char *fname, ODR o, int *sz)
1634 FILE *inf = fopen(fname, "rb");
1638 fseek(inf, 0L, SEEK_END);
1641 buf = odr_malloc(o, *sz);
1642 fread(buf, 1, *sz, inf);
1647 static void process_http_request(association *assoc, request *req)
1649 Z_HTTP_Request *hreq = req->gdu_request->u.HTTP_Request;
1650 ODR o = assoc->encode;
1651 int r = 2; /* 2=NOT TAKEN, 1=TAKEN, 0=SOAP TAKEN */
1653 Z_SOAP *soap_package = 0;
1656 Z_HTTP_Response *hres = 0;
1658 const char *stylesheet = 0; /* for now .. set later */
1659 Z_SRW_diagnostic *diagnostic = 0;
1660 int num_diagnostic = 0;
1661 const char *host = z_HTTP_header_lookup(hreq->headers, "Host");
1663 if (!control_association(assoc, host, 0))
1665 p = z_get_HTTP_Response(o, 404);
1668 if (r == 2 && assoc->server && assoc->server->docpath
1669 && hreq->path[0] == '/'
1671 /* check if path is a proper prefix of documentroot */
1672 strncmp(hreq->path+1, assoc->server->docpath,
1673 strlen(assoc->server->docpath))
1676 if (!check_path(hreq->path))
1678 yaz_log(YLOG_LOG, "File %s access forbidden", hreq->path+1);
1679 p = z_get_HTTP_Response(o, 404);
1683 int content_size = 0;
1684 char *content_buf = read_file(hreq->path+1, o, &content_size);
1687 yaz_log(YLOG_LOG, "File %s not found", hreq->path+1);
1688 p = z_get_HTTP_Response(o, 404);
1692 const char *ctype = 0;
1693 yaz_mime_types types = yaz_mime_types_create();
1695 yaz_mime_types_add(types, "xsl", "application/xml");
1696 yaz_mime_types_add(types, "xml", "application/xml");
1697 yaz_mime_types_add(types, "css", "text/css");
1698 yaz_mime_types_add(types, "html", "text/html");
1699 yaz_mime_types_add(types, "htm", "text/html");
1700 yaz_mime_types_add(types, "txt", "text/plain");
1701 yaz_mime_types_add(types, "js", "application/x-javascript");
1703 yaz_mime_types_add(types, "gif", "image/gif");
1704 yaz_mime_types_add(types, "png", "image/png");
1705 yaz_mime_types_add(types, "jpg", "image/jpeg");
1706 yaz_mime_types_add(types, "jpeg", "image/jpeg");
1708 ctype = yaz_mime_lookup_fname(types, hreq->path);
1711 yaz_log(YLOG_LOG, "No mime type for %s", hreq->path+1);
1712 p = z_get_HTTP_Response(o, 404);
1716 p = z_get_HTTP_Response(o, 200);
1717 hres = p->u.HTTP_Response;
1718 hres->content_buf = content_buf;
1719 hres->content_len = content_size;
1720 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1722 yaz_mime_types_destroy(types);
1730 r = yaz_srw_decode(hreq, &sr, &soap_package, assoc->decode, &charset);
1731 yaz_log(YLOG_DEBUG, "yaz_srw_decode returned %d", r);
1733 if (r == 2) /* not taken */
1735 r = yaz_sru_decode(hreq, &sr, &soap_package, assoc->decode, &charset,
1736 &diagnostic, &num_diagnostic);
1737 yaz_log(YLOG_DEBUG, "yaz_sru_decode returned %d", r);
1739 if (r == 0) /* decode SRW/SRU OK .. */
1741 int http_code = 200;
1742 if (sr->which == Z_SRW_searchRetrieve_request)
1745 yaz_srw_get(assoc->encode, Z_SRW_searchRetrieve_response);
1747 stylesheet = sr->u.request->stylesheet;
1750 res->u.response->diagnostics = diagnostic;
1751 res->u.response->num_diagnostics = num_diagnostic;
1755 srw_bend_search(assoc, req, sr, res->u.response,
1758 if (http_code == 200)
1759 soap_package->u.generic->p = res;
1761 else if (sr->which == Z_SRW_explain_request)
1763 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_explain_response);
1764 stylesheet = sr->u.explain_request->stylesheet;
1767 res->u.explain_response->diagnostics = diagnostic;
1768 res->u.explain_response->num_diagnostics = num_diagnostic;
1770 srw_bend_explain(assoc, req, sr,
1771 res->u.explain_response, &http_code);
1772 if (http_code == 200)
1773 soap_package->u.generic->p = res;
1775 else if (sr->which == Z_SRW_scan_request)
1777 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_scan_response);
1778 stylesheet = sr->u.scan_request->stylesheet;
1781 res->u.scan_response->diagnostics = diagnostic;
1782 res->u.scan_response->num_diagnostics = num_diagnostic;
1784 srw_bend_scan(assoc, req, sr,
1785 res->u.scan_response, &http_code);
1786 if (http_code == 200)
1787 soap_package->u.generic->p = res;
1789 else if (sr->which == Z_SRW_update_request)
1791 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_update_response);
1792 yaz_log(YLOG_DEBUG, "handling SRW UpdateRequest");
1795 res->u.update_response->diagnostics = diagnostic;
1796 res->u.update_response->num_diagnostics = num_diagnostic;
1798 yaz_log(YLOG_DEBUG, "num_diag = %d", res->u.update_response->num_diagnostics );
1799 srw_bend_update(assoc, req, sr,
1800 res->u.update_response, &http_code);
1801 if (http_code == 200)
1802 soap_package->u.generic->p = res;
1806 yaz_log(log_request, "SOAP ERROR");
1807 /* FIXME - what error, what query */
1809 z_soap_error(assoc->encode, soap_package,
1810 "SOAP-ENV:Client", "Bad method", 0);
1812 if (http_code == 200 || http_code == 500)
1814 static Z_SOAP_Handler soap_handlers[4] = {
1816 {"http://www.loc.gov/zing/srw/", 0,
1817 (Z_SOAP_fun) yaz_srw_codec},
1818 {"http://www.loc.gov/zing/srw/v1.0/", 0,
1819 (Z_SOAP_fun) yaz_srw_codec},
1820 {"http://www.loc.gov/zing/srw/update/", 0,
1821 (Z_SOAP_fun) yaz_ucp_codec},
1827 p = z_get_HTTP_Response(o, 200);
1828 hres = p->u.HTTP_Response;
1830 if (!stylesheet && assoc->server)
1831 stylesheet = assoc->server->stylesheet;
1833 /* empty stylesheet means NO stylesheet */
1834 if (stylesheet && *stylesheet == '\0')
1837 ret = z_soap_codec_enc_xsl(assoc->encode, &soap_package,
1838 &hres->content_buf, &hres->content_len,
1839 soap_handlers, charset, stylesheet);
1840 hres->code = http_code;
1842 strcpy(ctype, "text/xml");
1845 strcat(ctype, "; charset=");
1846 strcat(ctype, charset);
1848 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1851 p = z_get_HTTP_Response(o, http_code);
1855 p = z_get_HTTP_Response(o, 500);
1856 hres = p->u.HTTP_Response;
1857 if (!strcmp(hreq->version, "1.0"))
1859 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1860 if (v && !strcmp(v, "Keep-Alive"))
1864 hres->version = "1.0";
1868 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1869 if (v && !strcmp(v, "close"))
1873 hres->version = "1.1";
1877 z_HTTP_header_add(o, &hres->headers, "Connection", "close");
1878 assoc->state = ASSOC_DEAD;
1879 assoc->cs_get_mask = 0;
1884 const char *alive = z_HTTP_header_lookup(hreq->headers, "Keep-Alive");
1886 if (alive && isdigit(*(const unsigned char *) alive))
1890 if (t < 0 || t > 3600)
1892 iochan_settimeout(assoc->client_chan,t);
1893 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1895 process_gdu_response(assoc, req, p);
1898 static void process_gdu_request(association *assoc, request *req)
1900 if (req->gdu_request->which == Z_GDU_Z3950)
1903 req->apdu_request = req->gdu_request->u.z3950;
1904 if (process_z_request(assoc, req, &msg) < 0)
1905 do_close_req(assoc, Z_Close_systemProblem, msg, req);
1907 else if (req->gdu_request->which == Z_GDU_HTTP_Request)
1908 process_http_request(assoc, req);
1911 do_close_req(assoc, Z_Close_systemProblem, "bad protocol packet", req);
1916 * Initiate request processing.
1918 static int process_z_request(association *assoc, request *req, char **msg)
1924 *msg = "Unknown Error";
1925 assert(req && req->state == REQUEST_IDLE);
1926 if (req->apdu_request->which != Z_APDU_initRequest && !assoc->init)
1928 *msg = "Missing InitRequest";
1931 switch (req->apdu_request->which)
1933 case Z_APDU_initRequest:
1934 res = process_initRequest(assoc, req); break;
1935 case Z_APDU_searchRequest:
1936 res = process_searchRequest(assoc, req, &fd); break;
1937 case Z_APDU_presentRequest:
1938 res = process_presentRequest(assoc, req, &fd); break;
1939 case Z_APDU_scanRequest:
1940 if (assoc->init->bend_scan)
1941 res = process_scanRequest(assoc, req, &fd);
1944 *msg = "Cannot handle Scan APDU";
1948 case Z_APDU_extendedServicesRequest:
1949 if (assoc->init->bend_esrequest)
1950 res = process_ESRequest(assoc, req, &fd);
1953 *msg = "Cannot handle Extended Services APDU";
1957 case Z_APDU_sortRequest:
1958 if (assoc->init->bend_sort)
1959 res = process_sortRequest(assoc, req, &fd);
1962 *msg = "Cannot handle Sort APDU";
1967 process_close(assoc, req);
1969 case Z_APDU_deleteResultSetRequest:
1970 if (assoc->init->bend_delete)
1971 res = process_deleteRequest(assoc, req, &fd);
1974 *msg = "Cannot handle Delete APDU";
1978 case Z_APDU_segmentRequest:
1979 if (assoc->init->bend_segment)
1981 res = process_segmentRequest (assoc, req);
1985 *msg = "Cannot handle Segment APDU";
1989 case Z_APDU_triggerResourceControlRequest:
1992 *msg = "Bad APDU received";
1997 yaz_log(YLOG_DEBUG, " result immediately available");
1998 retval = process_z_response(assoc, req, res);
2002 yaz_log(YLOG_DEBUG, " result unavailble");
2005 else /* no result yet - one will be provided later */
2009 /* Set up an I/O handler for the fd supplied by the backend */
2011 yaz_log(YLOG_DEBUG, " establishing handler for result");
2012 req->state = REQUEST_PENDING;
2013 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT, 0)))
2015 iochan_setdata(chan, assoc);
2022 * Handle message from the backend.
2024 void backend_response(IOCHAN i, int event)
2026 association *assoc = (association *)iochan_getdata(i);
2027 request *req = request_head(&assoc->incoming);
2031 yaz_log(YLOG_DEBUG, "backend_response");
2032 assert(assoc && req && req->state != REQUEST_IDLE);
2033 /* determine what it is we're waiting for */
2034 switch (req->apdu_request->which)
2036 case Z_APDU_searchRequest:
2037 res = response_searchRequest(assoc, req, 0, &fd); break;
2039 case Z_APDU_presentRequest:
2040 res = response_presentRequest(assoc, req, 0, &fd); break;
2041 case Z_APDU_scanRequest:
2042 res = response_scanRequest(assoc, req, 0, &fd); break;
2045 yaz_log(YLOG_FATAL, "Serious programmer's lapse or bug");
2048 if ((res && process_z_response(assoc, req, res) < 0) || fd < 0)
2050 yaz_log(YLOG_WARN, "Fatal error when talking to backend");
2051 do_close(assoc, Z_Close_systemProblem, 0);
2055 else if (!res) /* no result yet - try again later */
2057 yaz_log(YLOG_DEBUG, " no result yet");
2058 iochan_setfd(i, fd); /* in case fd has changed */
2063 * Encode response, and transfer the request structure to the outgoing queue.
2065 static int process_gdu_response(association *assoc, request *req, Z_GDU *res)
2067 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
2071 if (!z_GDU(assoc->print, &res, 0, 0))
2072 yaz_log(YLOG_WARN, "ODR print error: %s",
2073 odr_errmsg(odr_geterror(assoc->print)));
2074 odr_reset(assoc->print);
2076 if (!z_GDU(assoc->encode, &res, 0, 0))
2078 yaz_log(YLOG_WARN, "ODR error when encoding PDU: %s [element %s]",
2079 odr_errmsg(odr_geterror(assoc->decode)),
2080 odr_getelement(assoc->decode));
2083 req->response = odr_getbuf(assoc->encode, &req->len_response,
2084 &req->size_response);
2085 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
2086 odr_reset(assoc->encode);
2087 req->state = REQUEST_IDLE;
2088 request_enq(&assoc->outgoing, req);
2089 /* turn the work over to the ir_session handler */
2090 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
2091 assoc->cs_put_mask = EVENT_OUTPUT;
2092 /* Is there more work to be done? give that to the input handler too */
2094 if (request_head(&assoc->incoming))
2096 yaz_log (YLOG_DEBUG, "more work to be done");
2097 iochan_setevent(assoc->client_chan, EVENT_WORK);
2104 * Encode response, and transfer the request structure to the outgoing queue.
2106 static int process_z_response(association *assoc, request *req, Z_APDU *res)
2108 Z_GDU *gres = (Z_GDU *) odr_malloc(assoc->encode, sizeof(*res));
2109 gres->which = Z_GDU_Z3950;
2110 gres->u.z3950 = res;
2112 return process_gdu_response(assoc, req, gres);
2115 static char *get_vhost(Z_OtherInformation *otherInfo)
2117 return yaz_oi_get_string_oidval(&otherInfo, VAL_PROXY, 1, 0);
2121 * Handle init request.
2122 * At the moment, we don't check the options
2123 * anywhere else in the code - we just try not to do anything that would
2124 * break a naive client. We'll toss 'em into the association block when
2125 * we need them there.
2127 static Z_APDU *process_initRequest(association *assoc, request *reqb)
2129 Z_InitRequest *req = reqb->apdu_request->u.initRequest;
2130 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
2131 Z_InitResponse *resp = apdu->u.initResponse;
2132 bend_initresult *binitres;
2135 statserv_options_block *cb = 0; /* by default no control for backend */
2137 if (control_association(assoc, get_vhost(req->otherInfo), 1))
2138 cb = statserv_getcontrol(); /* got control block for backend */
2140 if (cb && assoc->backend)
2141 (*cb->bend_close)(assoc->backend);
2143 yaz_log(log_requestdetail, "Got initRequest");
2144 if (req->implementationId)
2145 yaz_log(log_requestdetail, "Id: %s",
2146 req->implementationId);
2147 if (req->implementationName)
2148 yaz_log(log_requestdetail, "Name: %s",
2149 req->implementationName);
2150 if (req->implementationVersion)
2151 yaz_log(log_requestdetail, "Version: %s",
2152 req->implementationVersion);
2154 assoc_init_reset(assoc);
2156 assoc->init->auth = req->idAuthentication;
2157 assoc->init->referenceId = req->referenceId;
2159 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
2161 Z_CharSetandLanguageNegotiation *negotiation =
2162 yaz_get_charneg_record (req->otherInfo);
2164 negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
2165 assoc->init->charneg_request = negotiation;
2171 if (req->implementationVersion)
2172 yaz_log(log_requestdetail, "Config: %s",
2175 iochan_settimeout(assoc->client_chan, cb->idle_timeout * 60);
2177 /* we have a backend control block, so call that init function */
2178 if (!(binitres = (*cb->bend_init)(assoc->init)))
2180 yaz_log(YLOG_WARN, "Bad response from backend.");
2183 assoc->backend = binitres->handle;
2187 /* no backend. return error */
2188 binitres = odr_malloc(assoc->encode, sizeof(*binitres));
2189 binitres->errstring = 0;
2190 binitres->errcode = YAZ_BIB1_PERMANENT_SYSTEM_ERROR;
2191 iochan_settimeout(assoc->client_chan, 10);
2193 if ((assoc->init->bend_sort))
2194 yaz_log (YLOG_DEBUG, "Sort handler installed");
2195 if ((assoc->init->bend_search))
2196 yaz_log (YLOG_DEBUG, "Search handler installed");
2197 if ((assoc->init->bend_present))
2198 yaz_log (YLOG_DEBUG, "Present handler installed");
2199 if ((assoc->init->bend_esrequest))
2200 yaz_log (YLOG_DEBUG, "ESRequest handler installed");
2201 if ((assoc->init->bend_delete))
2202 yaz_log (YLOG_DEBUG, "Delete handler installed");
2203 if ((assoc->init->bend_scan))
2204 yaz_log (YLOG_DEBUG, "Scan handler installed");
2205 if ((assoc->init->bend_segment))
2206 yaz_log (YLOG_DEBUG, "Segment handler installed");
2208 resp->referenceId = req->referenceId;
2210 /* let's tell the client what we can do */
2211 if (ODR_MASK_GET(req->options, Z_Options_search))
2213 ODR_MASK_SET(resp->options, Z_Options_search);
2214 strcat(options, "srch");
2216 if (ODR_MASK_GET(req->options, Z_Options_present))
2218 ODR_MASK_SET(resp->options, Z_Options_present);
2219 strcat(options, " prst");
2221 if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
2222 assoc->init->bend_delete)
2224 ODR_MASK_SET(resp->options, Z_Options_delSet);
2225 strcat(options, " del");
2227 if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
2228 assoc->init->bend_esrequest)
2230 ODR_MASK_SET(resp->options, Z_Options_extendedServices);
2231 strcat (options, " extendedServices");
2233 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
2235 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
2236 strcat(options, " namedresults");
2238 if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
2240 ODR_MASK_SET(resp->options, Z_Options_scan);
2241 strcat(options, " scan");
2243 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
2245 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
2246 strcat(options, " concurrop");
2248 if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
2250 ODR_MASK_SET(resp->options, Z_Options_sort);
2251 strcat(options, " sort");
2254 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel)
2255 && assoc->init->charneg_response)
2257 Z_OtherInformation **p;
2258 Z_OtherInformationUnit *p0;
2260 yaz_oi_APDU(apdu, &p);
2262 if ((p0=yaz_oi_update(p, assoc->encode, NULL, 0, 0))) {
2263 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
2265 p0->which = Z_OtherInfo_externallyDefinedInfo;
2266 p0->information.externallyDefinedInfo =
2267 assoc->init->charneg_response;
2269 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
2270 strcat(options, " negotiation");
2273 if (ODR_MASK_GET(req->options, Z_Options_triggerResourceCtrl))
2274 ODR_MASK_SET(resp->options, Z_Options_triggerResourceCtrl);
2276 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
2278 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
2279 assoc->version = 1; /* 1 & 2 are equivalent */
2281 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
2283 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
2286 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
2288 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
2292 yaz_log(log_requestdetail, "Negotiated to v%d: %s", assoc->version, options);
2293 assoc->maximumRecordSize = *req->maximumRecordSize;
2295 if (cb && assoc->maximumRecordSize > cb->maxrecordsize)
2296 assoc->maximumRecordSize = cb->maxrecordsize;
2297 assoc->preferredMessageSize = *req->preferredMessageSize;
2298 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
2299 assoc->preferredMessageSize = assoc->maximumRecordSize;
2301 resp->preferredMessageSize = &assoc->preferredMessageSize;
2302 resp->maximumRecordSize = &assoc->maximumRecordSize;
2304 resp->implementationId = odr_prepend(assoc->encode,
2305 assoc->init->implementation_id,
2306 resp->implementationId);
2308 resp->implementationName = odr_prepend(assoc->encode,
2309 assoc->init->implementation_name,
2310 odr_prepend(assoc->encode, "GFS", resp->implementationName));
2312 version = odr_strdup(assoc->encode, "$Revision: 1.94 $");
2313 if (strlen(version) > 10) /* check for unexpanded CVS strings */
2314 version[strlen(version)-2] = '\0';
2315 resp->implementationVersion = odr_prepend(assoc->encode,
2316 assoc->init->implementation_version,
2317 odr_prepend(assoc->encode, &version[11],
2318 resp->implementationVersion));
2320 if (binitres->errcode)
2322 assoc->state = ASSOC_DEAD;
2323 resp->userInformationField =
2324 init_diagnostics(assoc->encode, binitres->errcode,
2325 binitres->errstring);
2330 if (!req->idAuthentication)
2331 yaz_log(log_request, "Auth none");
2332 else if (req->idAuthentication->which == Z_IdAuthentication_open)
2334 const char *open = req->idAuthentication->u.open;
2335 const char *slash = strchr(open, '/');
2341 yaz_log(log_request, "Auth open %.*s", len, open);
2343 else if (req->idAuthentication->which == Z_IdAuthentication_idPass)
2345 const char *user = req->idAuthentication->u.idPass->userId;
2346 const char *group = req->idAuthentication->u.idPass->groupId;
2347 yaz_log(log_request, "Auth idPass %s %s",
2348 user ? user : "-", group ? group : "-");
2350 else if (req->idAuthentication->which
2351 == Z_IdAuthentication_anonymous)
2353 yaz_log(log_request, "Auth anonymous");
2357 yaz_log(log_request, "Auth other");
2362 WRBUF wr = wrbuf_alloc();
2363 wrbuf_printf(wr, "Init ");
2364 if (binitres->errcode)
2365 wrbuf_printf(wr, "ERROR %d", binitres->errcode);
2367 wrbuf_printf(wr, "OK -");
2368 wrbuf_printf(wr, " ID:%s Name:%s Version:%s",
2369 (req->implementationId ? req->implementationId :"-"),
2370 (req->implementationName ?
2371 req->implementationName : "-"),
2372 (req->implementationVersion ?
2373 req->implementationVersion : "-")
2375 yaz_log(log_request, "%s", wrbuf_buf(wr));
2382 * Set the specified `errcode' and `errstring' into a UserInfo-1
2383 * external to be returned to the client in accordance with Z35.90
2384 * Implementor Agreement 5 (Returning diagnostics in an InitResponse):
2385 * http://lcweb.loc.gov/z3950/agency/agree/initdiag.html
2387 static Z_External *init_diagnostics(ODR odr, int error, const char *addinfo)
2389 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2390 addinfo ? " -- " : "", addinfo ? addinfo : "");
2391 return zget_init_diagnostics(odr, error, addinfo);
2395 * nonsurrogate diagnostic record.
2397 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
2399 Z_Records *rec = (Z_Records *) odr_malloc (assoc->encode, sizeof(*rec));
2401 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2402 addinfo ? " -- " : "", addinfo ? addinfo : "");
2404 rec->which = Z_Records_NSD;
2405 rec->u.nonSurrogateDiagnostic = zget_DefaultDiagFormat(assoc->encode,
2411 * surrogate diagnostic.
2413 static Z_NamePlusRecord *surrogatediagrec(association *assoc,
2415 int error, const char *addinfo)
2417 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2418 addinfo ? " -- " : "", addinfo ? addinfo : "");
2419 return zget_surrogateDiagRec(assoc->encode, dbname, error, addinfo);
2422 static Z_Records *pack_records(association *a, char *setname, int start,
2423 int *num, Z_RecordComposition *comp,
2424 int *next, int *pres, oid_value format,
2425 Z_ReferenceId *referenceId,
2426 int *oid, int *errcode)
2428 int recno, total_length = 0, toget = *num, dumped_records = 0;
2429 Z_Records *records =
2430 (Z_Records *) odr_malloc (a->encode, sizeof(*records));
2431 Z_NamePlusRecordList *reclist =
2432 (Z_NamePlusRecordList *) odr_malloc (a->encode, sizeof(*reclist));
2433 Z_NamePlusRecord **list =
2434 (Z_NamePlusRecord **) odr_malloc (a->encode, sizeof(*list) * toget);
2436 records->which = Z_Records_DBOSD;
2437 records->u.databaseOrSurDiagnostics = reclist;
2438 reclist->num_records = 0;
2439 reclist->records = list;
2440 *pres = Z_PresentStatus_success;
2444 yaz_log(log_requestdetail, "Request to pack %d+%d %s", start, toget, setname);
2445 yaz_log(log_requestdetail, "pms=%d, mrs=%d", a->preferredMessageSize,
2446 a->maximumRecordSize);
2447 for (recno = start; reclist->num_records < toget; recno++)
2450 Z_NamePlusRecord *thisrec;
2451 int this_length = 0;
2453 * we get the number of bytes allocated on the stream before any
2454 * allocation done by the backend - this should give us a reasonable
2455 * idea of the total size of the data so far.
2457 total_length = odr_total(a->encode) - dumped_records;
2463 freq.last_in_set = 0;
2464 freq.setname = setname;
2465 freq.surrogate_flag = 0;
2466 freq.number = recno;
2468 freq.request_format = format;
2469 freq.request_format_raw = oid;
2470 freq.output_format = format;
2471 freq.output_format_raw = 0;
2472 freq.stream = a->encode;
2473 freq.print = a->print;
2474 freq.referenceId = referenceId;
2477 retrieve_fetch(a, &freq);
2479 *next = freq.last_in_set ? 0 : recno + 1;
2481 /* backend should be able to signal whether error is system-wide
2482 or only pertaining to current record */
2485 if (!freq.surrogate_flag)
2488 *pres = Z_PresentStatus_failure;
2489 /* for 'present request out of range',
2490 set addinfo to record position if not set */
2491 if (freq.errcode == YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE &&
2492 freq.errstring == 0)
2494 sprintf (s, "%d", recno);
2498 *errcode = freq.errcode;
2499 return diagrec(a, freq.errcode, freq.errstring);
2501 reclist->records[reclist->num_records] =
2502 surrogatediagrec(a, freq.basename, freq.errcode,
2504 reclist->num_records++;
2507 if (freq.record == 0) /* no error and no record ? */
2509 *next = 0; /* signal end-of-set and stop */
2513 this_length = freq.len;
2515 this_length = odr_total(a->encode) - total_length - dumped_records;
2516 yaz_log(YLOG_DEBUG, " fetched record, len=%d, total=%d dumped=%d",
2517 this_length, total_length, dumped_records);
2518 if (a->preferredMessageSize > 0 &&
2519 this_length + total_length > a->preferredMessageSize)
2521 /* record is small enough, really */
2522 if (this_length <= a->preferredMessageSize && recno > start)
2524 yaz_log(log_requestdetail, " Dropped last normal-sized record");
2525 *pres = Z_PresentStatus_partial_2;
2528 /* record can only be fetched by itself */
2529 if (this_length < a->maximumRecordSize)
2531 yaz_log(log_requestdetail, " Record > prefmsgsz");
2534 yaz_log(YLOG_DEBUG, " Dropped it");
2535 reclist->records[reclist->num_records] =
2536 surrogatediagrec(a, freq.basename, 16, 0);
2537 reclist->num_records++;
2538 dumped_records += this_length;
2542 else /* too big entirely */
2544 yaz_log(log_requestdetail, "Record > maxrcdsz this=%d max=%d",
2545 this_length, a->maximumRecordSize);
2546 reclist->records[reclist->num_records] =
2547 surrogatediagrec(a, freq.basename, 17, 0);
2548 reclist->num_records++;
2549 dumped_records += this_length;
2554 if (!(thisrec = (Z_NamePlusRecord *)
2555 odr_malloc(a->encode, sizeof(*thisrec))))
2558 thisrec->databaseName = odr_strdup(a->encode, freq.basename);
2560 thisrec->databaseName = 0;
2561 thisrec->which = Z_NamePlusRecord_databaseRecord;
2563 if (freq.output_format_raw)
2565 struct oident *ident = oid_getentbyoid(freq.output_format_raw);
2566 freq.output_format = ident->value;
2568 thisrec->u.databaseRecord = z_ext_record(a->encode, freq.output_format,
2569 freq.record, freq.len);
2570 if (!thisrec->u.databaseRecord)
2572 reclist->records[reclist->num_records] = thisrec;
2573 reclist->num_records++;
2575 *num = reclist->num_records;
2579 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
2582 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2583 bend_search_rr *bsrr =
2584 (bend_search_rr *)nmem_malloc (reqb->request_mem, sizeof(*bsrr));
2586 yaz_log(log_requestdetail, "Got SearchRequest.");
2588 bsrr->request = reqb;
2589 bsrr->association = assoc;
2590 bsrr->referenceId = req->referenceId;
2591 save_referenceId (reqb, bsrr->referenceId);
2592 bsrr->srw_sortKeys = 0;
2593 bsrr->srw_setname = 0;
2594 bsrr->srw_setnameIdleTime = 0;
2596 yaz_log (log_requestdetail, "ResultSet '%s'", req->resultSetName);
2597 if (req->databaseNames)
2600 for (i = 0; i < req->num_databaseNames; i++)
2601 yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
2604 yaz_log_zquery_level(log_requestdetail,req->query);
2606 if (assoc->init->bend_search)
2608 bsrr->setname = req->resultSetName;
2609 bsrr->replace_set = *req->replaceIndicator;
2610 bsrr->num_bases = req->num_databaseNames;
2611 bsrr->basenames = req->databaseNames;
2612 bsrr->query = req->query;
2613 bsrr->stream = assoc->encode;
2614 nmem_transfer(bsrr->stream->mem, reqb->request_mem);
2615 bsrr->decode = assoc->decode;
2616 bsrr->print = assoc->print;
2619 bsrr->errstring = NULL;
2620 bsrr->search_info = NULL;
2622 if (assoc->server && assoc->server->cql_transform
2623 && req->query->which == Z_Query_type_104
2624 && req->query->u.type_104->which == Z_External_CQL)
2626 /* have a CQL query and a CQL to PQF transform .. */
2628 cql2pqf(bsrr->stream, req->query->u.type_104->u.cql,
2629 assoc->server->cql_transform, bsrr->query);
2631 bsrr->errcode = yaz_diag_srw_to_bib1(srw_errcode);
2634 (assoc->init->bend_search)(assoc->backend, bsrr);
2635 if (!bsrr->request) /* backend not ready with the search response */
2636 return 0; /* should not be used any more */
2640 /* FIXME - make a diagnostic for it */
2641 yaz_log(YLOG_WARN,"Search not supported ?!?!");
2643 return response_searchRequest(assoc, reqb, bsrr, fd);
2646 int bend_searchresponse(void *handle, bend_search_rr *bsrr) {return 0;}
2649 * Prepare a searchresponse based on the backend results. We probably want
2650 * to look at making the fetching of records nonblocking as well, but
2651 * so far, we'll keep things simple.
2652 * If bsrt is null, that means we're called in response to a communications
2653 * event, and we'll have to get the response for ourselves.
2655 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
2656 bend_search_rr *bsrt, int *fd)
2658 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2659 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2660 Z_SearchResponse *resp = (Z_SearchResponse *)
2661 odr_malloc (assoc->encode, sizeof(*resp));
2662 int *nulint = odr_intdup (assoc->encode, 0);
2663 bool_t *sr = odr_intdup(assoc->encode, 1);
2664 int *next = odr_intdup(assoc->encode, 0);
2665 int *none = odr_intdup(assoc->encode, Z_SearchResponse_none);
2668 apdu->which = Z_APDU_searchResponse;
2669 apdu->u.searchResponse = resp;
2670 resp->referenceId = req->referenceId;
2671 resp->additionalSearchInfo = 0;
2672 resp->otherInfo = 0;
2674 if (!bsrt && !bend_searchresponse(assoc->backend, bsrt))
2676 yaz_log(YLOG_FATAL, "Bad result from backend");
2679 else if (bsrt->errcode)
2681 resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
2682 resp->resultCount = nulint;
2683 resp->numberOfRecordsReturned = nulint;
2684 resp->nextResultSetPosition = nulint;
2685 resp->searchStatus = nulint;
2686 resp->resultSetStatus = none;
2687 resp->presentStatus = 0;
2691 int *toget = odr_intdup(assoc->encode, 0);
2692 int *presst = odr_intdup(assoc->encode, 0);
2693 Z_RecordComposition comp, *compp = 0;
2695 yaz_log (log_requestdetail, "resultCount: %d", bsrt->hits);
2698 resp->resultCount = &bsrt->hits;
2700 comp.which = Z_RecordComp_simple;
2701 /* how many records does the user agent want, then? */
2702 if (bsrt->hits <= *req->smallSetUpperBound)
2704 *toget = bsrt->hits;
2705 if ((comp.u.simple = req->smallSetElementSetNames))
2708 else if (bsrt->hits < *req->largeSetLowerBound)
2710 *toget = *req->mediumSetPresentNumber;
2711 if (*toget > bsrt->hits)
2712 *toget = bsrt->hits;
2713 if ((comp.u.simple = req->mediumSetElementSetNames))
2719 if (*toget && !resp->records)
2724 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
2727 form = prefformat->value;
2729 /* Call bend_present if defined */
2730 if (assoc->init->bend_present)
2732 bend_present_rr *bprr = (bend_present_rr *)
2733 nmem_malloc (reqb->request_mem, sizeof(*bprr));
2734 bprr->setname = req->resultSetName;
2736 bprr->number = *toget;
2737 bprr->format = form;
2739 bprr->referenceId = req->referenceId;
2740 bprr->stream = assoc->encode;
2741 bprr->print = assoc->print;
2742 bprr->request = reqb;
2743 bprr->association = assoc;
2745 bprr->errstring = NULL;
2746 (*assoc->init->bend_present)(assoc->backend, bprr);
2752 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2753 *resp->presentStatus = Z_PresentStatus_failure;
2758 resp->records = pack_records(assoc, req->resultSetName, 1,
2759 toget, compp, next, presst, form, req->referenceId,
2760 req->preferredRecordSyntax, NULL);
2763 resp->numberOfRecordsReturned = toget;
2764 returnedrecs = *toget;
2765 resp->nextResultSetPosition = next;
2766 resp->searchStatus = sr;
2767 resp->resultSetStatus = 0;
2768 resp->presentStatus = presst;
2772 if (*resp->resultCount)
2774 resp->numberOfRecordsReturned = nulint;
2775 resp->nextResultSetPosition = next;
2776 resp->searchStatus = sr;
2777 resp->resultSetStatus = 0;
2778 resp->presentStatus = 0;
2781 resp->additionalSearchInfo = bsrt->search_info;
2786 WRBUF wr = wrbuf_alloc();
2788 for (i = 0 ; i < req->num_databaseNames; i++){
2790 wrbuf_printf(wr, "+");
2791 wrbuf_printf(wr, req->databaseNames[i]);
2793 wrbuf_printf(wr, " ");
2796 wrbuf_printf(wr, "ERROR %d", bsrt->errcode);
2798 wrbuf_printf(wr, "OK %d", bsrt->hits);
2799 wrbuf_printf(wr, " %s 1+%d ",
2800 req->resultSetName, returnedrecs);
2801 yaz_query_to_wrbuf(wr, req->query);
2803 yaz_log(log_request, "Search %s", wrbuf_buf(wr));
2810 * Maybe we got a little over-friendly when we designed bend_fetch to
2811 * get only one record at a time. Some backends can optimise multiple-record
2812 * fetches, and at any rate, there is some overhead involved in
2813 * all that selecting and hopping around. Problem is, of course, that the
2814 * frontend can't know ahead of time how many records it'll need to
2815 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
2816 * is downright lousy as a bulk data transfer protocol.
2818 * To start with, we'll do the fetching of records from the backend
2819 * in one operation: To save some trips in and out of the event-handler,
2820 * and to simplify the interface to pack_records. At any rate, asynch
2821 * operation is more fun in operations that have an unpredictable execution
2822 * speed - which is normally more true for search than for present.
2824 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
2827 Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
2831 Z_PresentResponse *resp;
2835 const char *errstring = 0;
2837 yaz_log(log_requestdetail, "Got PresentRequest.");
2839 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
2842 form = prefformat->value;
2843 resp = (Z_PresentResponse *)odr_malloc (assoc->encode, sizeof(*resp));
2845 resp->presentStatus = odr_intdup(assoc->encode, 0);
2846 if (assoc->init->bend_present)
2848 bend_present_rr *bprr = (bend_present_rr *)
2849 nmem_malloc (reqb->request_mem, sizeof(*bprr));
2850 bprr->setname = req->resultSetId;
2851 bprr->start = *req->resultSetStartPoint;
2852 bprr->number = *req->numberOfRecordsRequested;
2853 bprr->format = form;
2854 bprr->comp = req->recordComposition;
2855 bprr->referenceId = req->referenceId;
2856 bprr->stream = assoc->encode;
2857 bprr->print = assoc->print;
2858 bprr->request = reqb;
2859 bprr->association = assoc;
2861 bprr->errstring = NULL;
2862 (*assoc->init->bend_present)(assoc->backend, bprr);
2865 return 0; /* should not happen */
2868 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2869 *resp->presentStatus = Z_PresentStatus_failure;
2870 errcode = bprr->errcode;
2871 errstring = bprr->errstring;
2874 apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2875 next = odr_intdup(assoc->encode, 0);
2876 num = odr_intdup(assoc->encode, 0);
2878 apdu->which = Z_APDU_presentResponse;
2879 apdu->u.presentResponse = resp;
2880 resp->referenceId = req->referenceId;
2881 resp->otherInfo = 0;
2885 *num = *req->numberOfRecordsRequested;
2887 pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
2888 num, req->recordComposition, next,
2889 resp->presentStatus,
2890 form, req->referenceId, req->preferredRecordSyntax,
2895 WRBUF wr = wrbuf_alloc();
2896 wrbuf_printf(wr, "Present ");
2898 if (*resp->presentStatus == Z_PresentStatus_failure)
2899 wrbuf_printf(wr, "ERROR %d ", errcode);
2900 else if (*resp->presentStatus == Z_PresentStatus_success)
2901 wrbuf_printf(wr, "OK - ");
2903 wrbuf_printf(wr, "Partial %d - ", *resp->presentStatus);
2905 wrbuf_printf(wr, " %s %d+%d ",
2906 req->resultSetId, *req->resultSetStartPoint,
2907 *req->numberOfRecordsRequested);
2908 yaz_log(log_request, "%s", wrbuf_buf(wr) );
2913 resp->numberOfRecordsReturned = num;
2914 resp->nextResultSetPosition = next;
2920 * Scan was implemented rather in a hurry, and with support for only the basic
2921 * elements of the service in the backend API. Suggestions are welcome.
2923 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
2925 Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
2926 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2927 Z_ScanResponse *res = (Z_ScanResponse *)
2928 odr_malloc (assoc->encode, sizeof(*res));
2929 int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
2930 int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
2931 Z_ListEntries *ents = (Z_ListEntries *)
2932 odr_malloc (assoc->encode, sizeof(*ents));
2933 Z_DiagRecs *diagrecs_p = NULL;
2935 bend_scan_rr *bsrr = (bend_scan_rr *)
2936 odr_malloc (assoc->encode, sizeof(*bsrr));
2937 struct scan_entry *save_entries;
2939 yaz_log(log_requestdetail, "Got ScanRequest");
2941 apdu->which = Z_APDU_scanResponse;
2942 apdu->u.scanResponse = res;
2943 res->referenceId = req->referenceId;
2945 /* if step is absent, set it to 0 */
2946 res->stepSize = odr_intdup(assoc->encode, 0);
2948 *res->stepSize = *req->stepSize;
2950 res->scanStatus = scanStatus;
2951 res->numberOfEntriesReturned = numberOfEntriesReturned;
2952 res->positionOfTerm = 0;
2953 res->entries = ents;
2954 ents->num_entries = 0;
2955 ents->entries = NULL;
2956 ents->num_nonsurrogateDiagnostics = 0;
2957 ents->nonsurrogateDiagnostics = NULL;
2958 res->attributeSet = 0;
2961 if (req->databaseNames)
2964 for (i = 0; i < req->num_databaseNames; i++)
2965 yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
2967 bsrr->scanClause = 0;
2969 bsrr->errstring = 0;
2970 bsrr->num_bases = req->num_databaseNames;
2971 bsrr->basenames = req->databaseNames;
2972 bsrr->num_entries = *req->numberOfTermsRequested;
2973 bsrr->term = req->termListAndStartPoint;
2974 bsrr->referenceId = req->referenceId;
2975 bsrr->stream = assoc->encode;
2976 bsrr->print = assoc->print;
2977 bsrr->step_size = res->stepSize;
2979 /* For YAZ 2.0 and earlier it was the backend handler that
2980 initialized entries (member display_term did not exist)
2981 YAZ 2.0 and later sets 'entries' and initialize all members
2982 including 'display_term'. If YAZ 2.0 or later sees that
2983 entries was modified - we assume that it is an old handler and
2984 that 'display_term' is _not_ set.
2986 if (bsrr->num_entries > 0)
2989 bsrr->entries = odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
2991 for (i = 0; i<bsrr->num_entries; i++)
2993 bsrr->entries[i].term = 0;
2994 bsrr->entries[i].occurrences = 0;
2995 bsrr->entries[i].errcode = 0;
2996 bsrr->entries[i].errstring = 0;
2997 bsrr->entries[i].display_term = 0;
3000 save_entries = bsrr->entries; /* save it so we can compare later */
3002 if (req->attributeSet &&
3003 (attset = oid_getentbyoid(req->attributeSet)) &&
3004 (attset->oclass == CLASS_ATTSET || attset->oclass == CLASS_GENERAL))
3005 bsrr->attributeset = attset->value;
3007 bsrr->attributeset = VAL_NONE;
3008 log_scan_term_level (log_requestdetail, req->termListAndStartPoint,
3009 bsrr->attributeset);
3010 bsrr->term_position = req->preferredPositionInResponse ?
3011 *req->preferredPositionInResponse : 1;
3013 ((int (*)(void *, bend_scan_rr *))
3014 (*assoc->init->bend_scan))(assoc->backend, bsrr);
3017 diagrecs_p = zget_DiagRecs(assoc->encode,
3018 bsrr->errcode, bsrr->errstring);
3022 Z_Entry **tab = (Z_Entry **)
3023 odr_malloc (assoc->encode, sizeof(*tab) * bsrr->num_entries);
3025 if (bsrr->status == BEND_SCAN_PARTIAL)
3026 *scanStatus = Z_Scan_partial_5;
3028 *scanStatus = Z_Scan_success;
3029 ents->entries = tab;
3030 ents->num_entries = bsrr->num_entries;
3031 res->numberOfEntriesReturned = &ents->num_entries;
3032 res->positionOfTerm = &bsrr->term_position;
3033 for (i = 0; i < bsrr->num_entries; i++)
3039 tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
3040 if (bsrr->entries[i].occurrences >= 0)
3042 e->which = Z_Entry_termInfo;
3043 e->u.termInfo = t = (Z_TermInfo *)
3044 odr_malloc(assoc->encode, sizeof(*t));
3045 t->suggestedAttributes = 0;
3047 if (save_entries == bsrr->entries &&
3048 bsrr->entries[i].display_term)
3050 /* the entries was _not_ set by the handler. So it's
3051 safe to test for new member display_term. It is
3054 t->displayTerm = odr_strdup(assoc->encode,
3055 bsrr->entries[i].display_term);
3057 t->alternativeTerm = 0;
3058 t->byAttributes = 0;
3059 t->otherTermInfo = 0;
3060 t->globalOccurrences = &bsrr->entries[i].occurrences;
3061 t->term = (Z_Term *)
3062 odr_malloc(assoc->encode, sizeof(*t->term));
3063 t->term->which = Z_Term_general;
3064 t->term->u.general = o =
3065 (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
3066 o->buf = (unsigned char *)
3067 odr_malloc(assoc->encode, o->len = o->size =
3068 strlen(bsrr->entries[i].term));
3069 memcpy(o->buf, bsrr->entries[i].term, o->len);
3070 yaz_log(YLOG_DEBUG, " term #%d: '%s' (%d)", i,
3071 bsrr->entries[i].term, bsrr->entries[i].occurrences);
3075 Z_DiagRecs *drecs = zget_DiagRecs(assoc->encode,
3076 bsrr->entries[i].errcode,
3077 bsrr->entries[i].errstring);
3078 assert (drecs->num_diagRecs == 1);
3079 e->which = Z_Entry_surrogateDiagnostic;
3080 assert (drecs->diagRecs[0]);
3081 e->u.surrogateDiagnostic = drecs->diagRecs[0];
3087 ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
3088 ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
3093 WRBUF wr = wrbuf_alloc();
3094 wrbuf_printf(wr, "Scan ");
3095 for (i = 0 ; i < req->num_databaseNames; i++){
3097 wrbuf_printf(wr, "+");
3098 wrbuf_printf(wr, req->databaseNames[i]);
3100 wrbuf_printf(wr, " ");
3103 wr_diag(wr, bsrr->errcode, bsrr->errstring);
3104 wrbuf_printf(wr, " ");
3107 wrbuf_printf(wr, "OK ");
3108 /* else if (*res->scanStatus == Z_Scan_success) */
3109 /* wrbuf_printf(wr, "OK "); */
3111 /* wrbuf_printf(wr, "Partial "); */
3113 if (*res->numberOfEntriesReturned)
3114 wrbuf_printf(wr, "%d - ", *res->numberOfEntriesReturned);
3116 wrbuf_printf(wr, "0 - ");
3118 wrbuf_printf(wr, "%d+%d+%d ",
3119 (req->preferredPositionInResponse ?
3120 *req->preferredPositionInResponse : 1),
3121 *req->numberOfTermsRequested,
3122 (res->stepSize ? *res->stepSize : 1));
3124 yaz_scan_to_wrbuf(wr, req->termListAndStartPoint,
3125 bsrr->attributeset);
3126 yaz_log(log_request, "%s", wrbuf_buf(wr) );
3132 static Z_APDU *process_sortRequest(association *assoc, request *reqb,
3136 Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
3137 Z_SortResponse *res = (Z_SortResponse *)
3138 odr_malloc (assoc->encode, sizeof(*res));
3139 bend_sort_rr *bsrr = (bend_sort_rr *)
3140 odr_malloc (assoc->encode, sizeof(*bsrr));
3142 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
3144 yaz_log(log_requestdetail, "Got SortRequest.");
3146 bsrr->num_input_setnames = req->num_inputResultSetNames;
3147 for (i=0;i<req->num_inputResultSetNames;i++)
3148 yaz_log(log_requestdetail, "Input resultset: '%s'",
3149 req->inputResultSetNames[i]);
3150 bsrr->input_setnames = req->inputResultSetNames;
3151 bsrr->referenceId = req->referenceId;
3152 bsrr->output_setname = req->sortedResultSetName;
3153 yaz_log(log_requestdetail, "Output resultset: '%s'",
3154 req->sortedResultSetName);
3155 bsrr->sort_sequence = req->sortSequence;
3156 /*FIXME - dump those sequences too */
3157 bsrr->stream = assoc->encode;
3158 bsrr->print = assoc->print;
3160 bsrr->sort_status = Z_SortResponse_failure;
3162 bsrr->errstring = 0;
3164 (*assoc->init->bend_sort)(assoc->backend, bsrr);
3166 res->referenceId = bsrr->referenceId;
3167 res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
3168 res->resultSetStatus = 0;
3171 Z_DiagRecs *dr = zget_DiagRecs(assoc->encode,
3172 bsrr->errcode, bsrr->errstring);
3173 res->diagnostics = dr->diagRecs;
3174 res->num_diagnostics = dr->num_diagRecs;
3178 res->num_diagnostics = 0;
3179 res->diagnostics = 0;
3181 res->resultCount = 0;
3184 apdu->which = Z_APDU_sortResponse;
3185 apdu->u.sortResponse = res;
3188 WRBUF wr = wrbuf_alloc();
3189 wrbuf_printf(wr, "Sort ");
3191 wrbuf_printf(wr, " ERROR %d", bsrr->errcode);
3193 wrbuf_printf(wr, "OK -");
3194 wrbuf_printf(wr, " (");
3195 for (i = 0; i<req->num_inputResultSetNames; i++)
3198 wrbuf_printf(wr, "+");
3199 wrbuf_printf(wr, req->inputResultSetNames[i]);
3201 wrbuf_printf(wr, ")->%s ",req->sortedResultSetName);
3203 yaz_log(log_request, "%s", wrbuf_buf(wr) );
3209 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
3213 Z_DeleteResultSetRequest *req =
3214 reqb->apdu_request->u.deleteResultSetRequest;
3215 Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
3216 odr_malloc (assoc->encode, sizeof(*res));
3217 bend_delete_rr *bdrr = (bend_delete_rr *)
3218 odr_malloc (assoc->encode, sizeof(*bdrr));
3219 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
3221 yaz_log(log_requestdetail, "Got DeleteRequest.");
3223 bdrr->num_setnames = req->num_resultSetList;
3224 bdrr->setnames = req->resultSetList;
3225 for (i = 0; i<req->num_resultSetList; i++)
3226 yaz_log(log_requestdetail, "resultset: '%s'",
3227 req->resultSetList[i]);
3228 bdrr->stream = assoc->encode;
3229 bdrr->print = assoc->print;
3230 bdrr->function = *req->deleteFunction;
3231 bdrr->referenceId = req->referenceId;
3233 if (bdrr->num_setnames > 0)
3235 bdrr->statuses = (int*)
3236 odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
3237 bdrr->num_setnames);
3238 for (i = 0; i < bdrr->num_setnames; i++)
3239 bdrr->statuses[i] = 0;
3241 (*assoc->init->bend_delete)(assoc->backend, bdrr);
3243 res->referenceId = req->referenceId;
3245 res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
3247 res->deleteListStatuses = 0;
3248 if (bdrr->num_setnames > 0)
3251 res->deleteListStatuses = (Z_ListStatuses *)
3252 odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
3253 res->deleteListStatuses->num = bdrr->num_setnames;
3254 res->deleteListStatuses->elements =
3256 odr_malloc (assoc->encode,
3257 sizeof(*res->deleteListStatuses->elements) *
3258 bdrr->num_setnames);
3259 for (i = 0; i<bdrr->num_setnames; i++)
3261 res->deleteListStatuses->elements[i] =
3263 odr_malloc (assoc->encode,
3264 sizeof(**res->deleteListStatuses->elements));
3265 res->deleteListStatuses->elements[i]->status = bdrr->statuses+i;
3266 res->deleteListStatuses->elements[i]->id =
3267 odr_strdup (assoc->encode, bdrr->setnames[i]);
3270 res->numberNotDeleted = 0;
3271 res->bulkStatuses = 0;
3272 res->deleteMessage = 0;
3275 apdu->which = Z_APDU_deleteResultSetResponse;
3276 apdu->u.deleteResultSetResponse = res;
3279 WRBUF wr = wrbuf_alloc();
3280 wrbuf_printf(wr, "Delete ");
3281 if (bdrr->delete_status)
3282 wrbuf_printf(wr, "ERROR %d", bdrr->delete_status);
3284 wrbuf_printf(wr, "OK -");
3285 for (i = 0; i<req->num_resultSetList; i++)
3286 wrbuf_printf(wr, " %s ", req->resultSetList[i]);
3287 yaz_log(log_request, "%s", wrbuf_buf(wr) );
3293 static void process_close(association *assoc, request *reqb)
3295 Z_Close *req = reqb->apdu_request->u.close;
3296 static char *reasons[] =
3303 "securityViolation",
3310 yaz_log(log_requestdetail, "Got Close, reason %s, message %s",
3311 reasons[*req->closeReason], req->diagnosticInformation ?
3312 req->diagnosticInformation : "NULL");
3313 if (assoc->version < 3) /* to make do_force respond with close */
3315 do_close_req(assoc, Z_Close_finished,
3316 "Association terminated by client", reqb);
3317 yaz_log(log_request,"Close OK");
3320 void save_referenceId (request *reqb, Z_ReferenceId *refid)
3324 reqb->len_refid = refid->len;
3325 reqb->refid = (char *)nmem_malloc (reqb->request_mem, refid->len);
3326 memcpy (reqb->refid, refid->buf, refid->len);
3330 reqb->len_refid = 0;
3335 void bend_request_send (bend_association a, bend_request req, Z_APDU *res)
3337 process_z_response (a, req, res);
3340 bend_request bend_request_mk (bend_association a)
3342 request *nreq = request_get (&a->outgoing);
3343 nreq->request_mem = nmem_create ();
3347 Z_ReferenceId *bend_request_getid (ODR odr, bend_request req)
3352 id = (Odr_oct *)odr_malloc (odr, sizeof(*odr));
3353 id->buf = (unsigned char *)odr_malloc (odr, req->len_refid);
3354 id->len = id->size = req->len_refid;
3355 memcpy (id->buf, req->refid, req->len_refid);
3359 void bend_request_destroy (bend_request *req)
3361 nmem_destroy((*req)->request_mem);
3362 request_release(*req);
3366 int bend_backend_respond (bend_association a, bend_request req)
3370 r = process_z_request (a, req, &msg);
3372 yaz_log (YLOG_WARN, "%s", msg);
3376 void bend_request_setdata(bend_request r, void *p)
3381 void *bend_request_getdata(bend_request r)
3383 return r->clientData;
3386 static Z_APDU *process_segmentRequest (association *assoc, request *reqb)
3388 bend_segment_rr req;
3390 req.segment = reqb->apdu_request->u.segmentRequest;
3391 req.stream = assoc->encode;
3392 req.decode = assoc->decode;
3393 req.print = assoc->print;
3394 req.association = assoc;
3396 (*assoc->init->bend_segment)(assoc->backend, &req);
3401 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd)
3403 bend_esrequest_rr esrequest;
3404 const char *ext_name = "unknown";
3406 Z_ExtendedServicesRequest *req =
3407 reqb->apdu_request->u.extendedServicesRequest;
3408 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
3410 Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
3412 esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
3413 esrequest.stream = assoc->encode;
3414 esrequest.decode = assoc->decode;
3415 esrequest.print = assoc->print;
3416 esrequest.errcode = 0;
3417 esrequest.errstring = NULL;
3418 esrequest.request = reqb;
3419 esrequest.association = assoc;
3420 esrequest.taskPackage = 0;
3421 esrequest.referenceId = req->referenceId;
3424 if (esrequest.esr && esrequest.esr->taskSpecificParameters)
3426 switch(esrequest.esr->taskSpecificParameters->which)
3428 case Z_External_itemOrder:
3429 ext_name = "ItemOrder"; break;
3430 case Z_External_update:
3431 ext_name = "Update"; break;
3432 case Z_External_update0:
3433 ext_name = "Update0"; break;
3434 case Z_External_ESAdmin:
3435 ext_name = "Admin"; break;
3440 (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
3442 /* If the response is being delayed, return NULL */
3443 if (esrequest.request == NULL)
3446 resp->referenceId = req->referenceId;
3448 if (esrequest.errcode == -1)
3450 /* Backend service indicates request will be processed */
3451 yaz_log(log_request, "Extended Service: %s (accepted)", ext_name);
3452 *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
3454 else if (esrequest.errcode == 0)
3456 /* Backend service indicates request will be processed */
3457 yaz_log(log_request, "Extended Service: %s (done)", ext_name);
3458 *resp->operationStatus = Z_ExtendedServicesResponse_done;
3462 Z_DiagRecs *diagRecs =
3463 zget_DiagRecs(assoc->encode, esrequest.errcode,
3464 esrequest.errstring);
3465 /* Backend indicates error, request will not be processed */
3466 yaz_log(log_request, "Extended Service: %s (failed)", ext_name);
3467 *resp->operationStatus = Z_ExtendedServicesResponse_failure;
3468 resp->num_diagnostics = diagRecs->num_diagRecs;
3469 resp->diagnostics = diagRecs->diagRecs;
3472 WRBUF wr = wrbuf_alloc();
3473 wrbuf_diags(wr, resp->num_diagnostics, resp->diagnostics);
3474 yaz_log(log_request, "EsRequest %s", wrbuf_buf(wr) );
3479 /* Do something with the members of bend_extendedservice */
3480 if (esrequest.taskPackage)
3481 resp->taskPackage = z_ext_record (assoc->encode, VAL_EXTENDED,
3482 (const char *) esrequest.taskPackage,
3484 yaz_log(YLOG_DEBUG,"Send the result apdu");
3491 * indent-tabs-mode: nil
3493 * vim: shiftwidth=4 tabstop=8 expandtab