2 * Copyright (C) 1995-2005, Index Data ApS
3 * See the file LICENSE for details.
5 * $Id: seshigh.c,v 1.93 2006-07-07 12:40:15 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;
106 static int log_request = 0; /* one-line logs for requests */
107 static int log_requestdetail = 0; /* more detailed stuff */
109 /** get_logbits sets global loglevel bits */
110 static void get_logbits()
111 { /* needs to be called after parsing cmd-line args that can set loglevels!*/
115 log_session = yaz_log_module_level("session");
116 log_request = yaz_log_module_level("request");
117 log_requestdetail = yaz_log_module_level("requestdetail");
123 static void wr_diag(WRBUF w, int error, const char *addinfo)
125 wrbuf_printf(w, "ERROR %d+", error);
126 wrbuf_puts_replace_char(w, diagbib1_str(error), ' ', '_');
129 wrbuf_puts_replace_char(w, addinfo, ' ', '_');
137 * Create and initialize a new association-handle.
138 * channel : iochannel for the current line.
139 * link : communications channel.
140 * Returns: 0 or a new association handle.
142 association *create_association(IOCHAN channel, COMSTACK link,
143 const char *apdufile)
149 if (!(anew = (association *)xmalloc(sizeof(*anew))))
153 anew->last_control = 0;
154 anew->client_chan = channel;
155 anew->client_link = link;
156 anew->cs_get_mask = 0;
157 anew->cs_put_mask = 0;
158 anew->cs_accept_mask = 0;
159 if (!(anew->decode = odr_createmem(ODR_DECODE)) ||
160 !(anew->encode = odr_createmem(ODR_ENCODE)))
162 if (apdufile && *apdufile)
166 if (!(anew->print = odr_createmem(ODR_PRINT)))
168 if (*apdufile == '@')
170 odr_setprint(anew->print, yaz_log_file());
172 else if (*apdufile != '-')
175 sprintf(filename, "%.200s.%ld", apdufile, (long)getpid());
176 if (!(f = fopen(filename, "w")))
178 yaz_log(YLOG_WARN|YLOG_ERRNO, "%s", filename);
181 setvbuf(f, 0, _IONBF, 0);
182 odr_setprint(anew->print, f);
187 anew->input_buffer = 0;
188 anew->input_buffer_len = 0;
190 anew->state = ASSOC_NEW;
191 request_initq(&anew->incoming);
192 request_initq(&anew->outgoing);
193 anew->proto = cs_getproto(link);
199 * Free association and release resources.
201 void destroy_association(association *h)
203 statserv_options_block *cb = statserv_getcontrol();
207 odr_destroy(h->decode);
208 odr_destroy(h->encode);
210 odr_destroy(h->print);
212 xfree(h->input_buffer);
214 (*cb->bend_close)(h->backend);
215 while ((req = request_deq(&h->incoming)))
216 request_release(req);
217 while ((req = request_deq(&h->outgoing)))
218 request_release(req);
219 request_delq(&h->incoming);
220 request_delq(&h->outgoing);
222 xmalloc_trav("session closed");
223 if (cb && cb->one_shot)
229 static void do_close_req(association *a, int reason, char *message,
233 Z_Close *cls = zget_Close(a->encode);
235 /* Purge request queue */
236 while (request_deq(&a->incoming));
237 while (request_deq(&a->outgoing));
240 yaz_log(log_requestdetail, "Sending Close PDU, reason=%d, message=%s",
241 reason, message ? message : "none");
242 apdu.which = Z_APDU_close;
244 *cls->closeReason = reason;
245 cls->diagnosticInformation = message;
246 process_z_response(a, req, &apdu);
247 iochan_settimeout(a->client_chan, 20);
251 request_release(req);
252 yaz_log(log_requestdetail, "v2 client. No Close PDU");
253 iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
256 a->state = ASSOC_DEAD;
259 static void do_close(association *a, int reason, char *message)
261 request *req = request_get(&a->outgoing);
262 do_close_req (a, reason, message, req);
266 * This is where PDUs from the client are read and the further
267 * processing is initiated. Flow of control moves down through the
268 * various process_* functions below, until the encoded result comes back up
269 * to the output handler in here.
271 * h : the I/O channel that has an outstanding event.
272 * event : the current outstanding event.
274 void ir_session(IOCHAN h, int event)
277 association *assoc = (association *)iochan_getdata(h);
278 COMSTACK conn = assoc->client_link;
281 assert(h && conn && assoc);
282 if (event == EVENT_TIMEOUT)
284 if (assoc->state != ASSOC_UP)
286 yaz_log(YLOG_DEBUG, "Final timeout - closing connection.");
287 /* do we need to lod this at all */
289 destroy_association(assoc);
294 yaz_log(log_session, "Session idle too long. Sending close.");
295 do_close(assoc, Z_Close_lackOfActivity, 0);
299 if (event & assoc->cs_accept_mask)
301 if (!cs_accept (conn))
303 yaz_log (YLOG_WARN, "accept failed");
304 destroy_association(assoc);
307 iochan_clearflag (h, EVENT_OUTPUT);
308 if (conn->io_pending)
309 { /* cs_accept didn't complete */
310 assoc->cs_accept_mask =
311 ((conn->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
312 ((conn->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
314 iochan_setflag (h, assoc->cs_accept_mask);
317 { /* cs_accept completed. Prepare for reading (cs_get) */
318 assoc->cs_accept_mask = 0;
319 assoc->cs_get_mask = EVENT_INPUT;
320 iochan_setflag (h, assoc->cs_get_mask);
324 if ((event & assoc->cs_get_mask) || (event & EVENT_WORK)) /* input */
326 if ((assoc->cs_put_mask & EVENT_INPUT) == 0 && (event & assoc->cs_get_mask))
328 yaz_log(YLOG_DEBUG, "ir_session (input)");
329 /* We aren't speaking to this fellow */
330 if (assoc->state == ASSOC_DEAD)
332 yaz_log(log_session, "Connection closed - end of session");
334 destroy_association(assoc);
338 assoc->cs_get_mask = EVENT_INPUT;
339 if ((res = cs_get(conn, &assoc->input_buffer,
340 &assoc->input_buffer_len)) <= 0)
342 yaz_log(log_session, "Connection closed by client");
344 destroy_association(assoc);
348 else if (res == 1) /* incomplete read - wait for more */
350 if (conn->io_pending & CS_WANT_WRITE)
351 assoc->cs_get_mask |= EVENT_OUTPUT;
352 iochan_setflag(h, assoc->cs_get_mask);
355 if (cs_more(conn)) /* more stuff - call us again later, please */
356 iochan_setevent(h, EVENT_INPUT);
358 /* we got a complete PDU. Let's decode it */
359 yaz_log(YLOG_DEBUG, "Got PDU, %d bytes: lead=%02X %02X %02X", res,
360 assoc->input_buffer[0] & 0xff,
361 assoc->input_buffer[1] & 0xff,
362 assoc->input_buffer[2] & 0xff);
363 req = request_get(&assoc->incoming); /* get a new request */
364 odr_reset(assoc->decode);
365 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
366 if (!z_GDU(assoc->decode, &req->gdu_request, 0, 0))
368 yaz_log(YLOG_WARN, "ODR error on incoming PDU: %s [element %s] "
370 odr_errmsg(odr_geterror(assoc->decode)),
371 odr_getelement(assoc->decode),
372 (long) odr_offset(assoc->decode));
373 if (assoc->decode->error != OHTTP)
375 yaz_log(YLOG_WARN, "PDU dump:");
376 odr_dumpBER(yaz_log_file(), assoc->input_buffer, res);
377 request_release(req);
378 do_close(assoc, Z_Close_protocolError,"Malformed package");
382 Z_GDU *p = z_get_HTTP_Response(assoc->encode, 400);
383 assoc->state = ASSOC_DEAD;
384 process_gdu_response(assoc, req, p);
388 req->request_mem = odr_extract_mem(assoc->decode);
391 if (!z_GDU(assoc->print, &req->gdu_request, 0, 0))
392 yaz_log(YLOG_WARN, "ODR print error: %s",
393 odr_errmsg(odr_geterror(assoc->print)));
394 odr_reset(assoc->print);
396 request_enq(&assoc->incoming, req);
399 /* can we do something yet? */
400 req = request_head(&assoc->incoming);
401 if (req->state == REQUEST_IDLE)
403 request_deq(&assoc->incoming);
404 process_gdu_request(assoc, req);
407 if (event & assoc->cs_put_mask)
409 request *req = request_head(&assoc->outgoing);
411 assoc->cs_put_mask = 0;
412 yaz_log(YLOG_DEBUG, "ir_session (output)");
413 req->state = REQUEST_PENDING;
414 switch (res = cs_put(conn, req->response, req->len_response))
417 yaz_log(log_session, "Connection closed by client");
419 destroy_association(assoc);
422 case 0: /* all sent - release the request structure */
423 yaz_log(YLOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
425 yaz_log(YLOG_DEBUG, "HTTP out:\n%.*s", req->len_response,
428 nmem_destroy(req->request_mem);
429 request_deq(&assoc->outgoing);
430 request_release(req);
431 if (!request_head(&assoc->outgoing))
432 { /* restore mask for cs_get operation ... */
433 iochan_clearflag(h, EVENT_OUTPUT|EVENT_INPUT);
434 iochan_setflag(h, assoc->cs_get_mask);
435 if (assoc->state == ASSOC_DEAD)
436 iochan_setevent(assoc->client_chan, EVENT_TIMEOUT);
440 assoc->cs_put_mask = EVENT_OUTPUT;
444 if (conn->io_pending & CS_WANT_WRITE)
445 assoc->cs_put_mask |= EVENT_OUTPUT;
446 if (conn->io_pending & CS_WANT_READ)
447 assoc->cs_put_mask |= EVENT_INPUT;
448 iochan_setflag(h, assoc->cs_put_mask);
451 if (event & EVENT_EXCEPT)
453 yaz_log(YLOG_WARN, "ir_session (exception)");
455 destroy_association(assoc);
460 static int process_z_request(association *assoc, request *req, char **msg);
463 static void assoc_init_reset(association *assoc)
466 assoc->init = (bend_initrequest *) xmalloc (sizeof(*assoc->init));
468 assoc->init->stream = assoc->encode;
469 assoc->init->print = assoc->print;
470 assoc->init->auth = 0;
471 assoc->init->referenceId = 0;
472 assoc->init->implementation_version = 0;
473 assoc->init->implementation_id = 0;
474 assoc->init->implementation_name = 0;
475 assoc->init->bend_sort = NULL;
476 assoc->init->bend_search = NULL;
477 assoc->init->bend_present = NULL;
478 assoc->init->bend_esrequest = NULL;
479 assoc->init->bend_delete = NULL;
480 assoc->init->bend_scan = NULL;
481 assoc->init->bend_segment = NULL;
482 assoc->init->bend_fetch = NULL;
483 assoc->init->bend_explain = NULL;
484 assoc->init->bend_srw_scan = NULL;
485 assoc->init->bend_srw_update = NULL;
487 assoc->init->charneg_request = NULL;
488 assoc->init->charneg_response = NULL;
490 assoc->init->decode = assoc->decode;
491 assoc->init->peer_name =
492 odr_strdup (assoc->encode, cs_addrstr(assoc->client_link));
494 yaz_log(log_requestdetail, "peer %s", assoc->init->peer_name);
497 static int srw_bend_init(association *assoc, Z_SRW_diagnostic **d, int *num, Z_SRW_PDU *sr)
499 statserv_options_block *cb = statserv_getcontrol();
502 const char *encoding = "UTF-8";
504 bend_initresult *binitres;
506 yaz_log(log_requestdetail, "srw_bend_init config=%s", cb->configname);
507 assoc_init_reset(assoc);
509 assoc->maximumRecordSize = 3000000;
510 assoc->preferredMessageSize = 3000000;
514 Z_IdAuthentication *auth = odr_malloc(assoc->decode, sizeof(*auth));
517 len = strlen(sr->username) + 1;
519 len += strlen(sr->password) + 2;
520 auth->which = Z_IdAuthentication_open;
521 auth->u.open = odr_malloc(assoc->decode, len);
522 strcpy(auth->u.open, sr->username);
523 if (sr->password && *sr->password)
525 strcat(auth->u.open, "/");
526 strcat(auth->u.open, sr->password);
528 assoc->init->auth = auth;
532 ce = yaz_set_proposal_charneg(assoc->decode, &encoding, 1, 0, 0, 1);
533 assoc->init->charneg_request = ce->u.charNeg3;
536 if (!(binitres = (*cb->bend_init)(assoc->init)))
538 assoc->state = ASSOC_DEAD;
539 yaz_add_srw_diagnostic(assoc->encode, d, num,
540 YAZ_SRW_AUTHENTICATION_ERROR, 0);
543 assoc->backend = binitres->handle;
544 assoc->init->auth = 0;
545 if (binitres->errcode)
547 int srw_code = yaz_diag_bib1_to_srw(binitres->errcode);
548 assoc->state = ASSOC_DEAD;
549 yaz_add_srw_diagnostic(assoc->encode, d, num, srw_code,
550 binitres->errstring);
558 static const char *get_esn(Z_RecordComposition *comp)
560 if (comp && comp->which == Z_RecordComp_complex)
562 if (comp->u.complex->generic
563 && comp->u.complex->generic->elementSpec
564 && (comp->u.complex->generic->elementSpec->which ==
565 Z_ElementSpec_elementSetName))
566 return comp->u.complex->generic->elementSpec->u.elementSetName;
568 else if (comp && comp->which == Z_RecordComp_simple &&
569 comp->u.simple->which == Z_ElementSetNames_generic)
570 return comp->u.simple->u.generic;
574 static void set_esn(Z_RecordComposition **comp_p, const char *esn, NMEM nmem)
576 Z_RecordComposition *comp = nmem_malloc(nmem, sizeof(*comp));
578 comp->which = Z_RecordComp_simple;
579 comp->u.simple = nmem_malloc(nmem, sizeof(*comp->u.simple));
580 comp->u.simple->which = Z_ElementSetNames_generic;
581 comp->u.simple->u.generic = nmem_strdup(nmem, esn);
585 static int retrieve_fetch(association *assoc, bend_fetch_rr *rr)
588 yaz_record_conv_t rc = 0;
589 const char *match_schema = 0;
590 int *match_syntax = 0;
595 const char *input_schema = get_esn(rr->comp);
596 Odr_oid *input_syntax_raw = rr->request_format_raw;
598 const char *backend_schema = 0;
599 Odr_oid *backend_syntax = 0;
601 r = yaz_retrieval_request(assoc->server->retrieval,
609 if (r == -1) /* error ? */
611 const char *details = yaz_retrieval_get_error(
612 assoc->server->retrieval);
614 rr->errcode = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
616 rr->errstring = odr_strdup(rr->stream, details);
619 else if (r == 1 || r == 3)
621 const char *details = input_schema;
622 rr->errcode = YAZ_BIB1_ELEMENT_SET_NAMES_UNSUPP;
624 rr->errstring = odr_strdup(rr->stream, details);
629 rr->errcode = YAZ_BIB1_RECORD_SYNTAX_UNSUPP;
630 if (input_syntax_raw)
632 char oidbuf[OID_STR_MAX];
633 oid_to_dotstring(input_syntax_raw, oidbuf);
634 rr->errstring = odr_strdup(rr->stream, oidbuf);
640 set_esn(&rr->comp, backend_schema, rr->stream->mem);
644 oident *oident_syntax = oid_getentbyoid(backend_syntax);
646 rr->request_format_raw = backend_syntax;
649 rr->request_format = oident_syntax->value;
651 rr->request_format = VAL_NONE;
654 (*assoc->init->bend_fetch)(assoc->backend, rr);
655 if (rc && rr->record && rr->errcode == 0 && rr->len > 0)
656 { /* post conversion must take place .. */
657 WRBUF output_record = wrbuf_alloc();
658 int r = yaz_record_conv_record(rc, rr->record, rr->len, output_record);
661 const char *details = yaz_record_conv_get_error(rc);
662 rr->errcode = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
664 rr->errstring = odr_strdup(rr->stream, details);
668 rr->len = wrbuf_len(output_record);
669 rr->record = odr_malloc(rr->stream, rr->len);
670 memcpy(rr->record, wrbuf_buf(output_record), rr->len);
672 wrbuf_free(output_record, 1);
676 struct oident *oi = oid_getentbyoid(match_syntax);
677 rr->output_format = oi ? oi->value : VAL_NONE;
678 rr->output_format_raw = match_syntax;
681 rr->schema = odr_strdup(rr->stream, match_schema);
684 (*assoc->init->bend_fetch)(assoc->backend, rr);
688 static int srw_bend_fetch(association *assoc, int pos,
689 Z_SRW_searchRetrieveRequest *srw_req,
690 Z_SRW_record *record)
693 ODR o = assoc->encode;
695 rr.setname = "default";
698 rr.request_format = VAL_TEXT_XML;
699 rr.request_format_raw = yaz_oidval_to_z3950oid(assoc->decode,
702 rr.comp = (Z_RecordComposition *)
703 odr_malloc(assoc->decode, sizeof(*rr.comp));
704 rr.comp->which = Z_RecordComp_complex;
705 rr.comp->u.complex = (Z_CompSpec *)
706 odr_malloc(assoc->decode, sizeof(Z_CompSpec));
707 rr.comp->u.complex->selectAlternativeSyntax = (bool_t *)
708 odr_malloc(assoc->encode, sizeof(bool_t));
709 *rr.comp->u.complex->selectAlternativeSyntax = 0;
710 rr.comp->u.complex->num_dbSpecific = 0;
711 rr.comp->u.complex->dbSpecific = 0;
712 rr.comp->u.complex->num_recordSyntax = 0;
713 rr.comp->u.complex->recordSyntax = 0;
715 rr.comp->u.complex->generic = (Z_Specification *)
716 odr_malloc(assoc->decode, sizeof(Z_Specification));
718 /* schema uri = recordSchema (or NULL if recordSchema is not given) */
719 rr.comp->u.complex->generic->which = Z_Schema_uri;
720 rr.comp->u.complex->generic->schema.uri = srw_req->recordSchema;
722 /* ESN = recordSchema if recordSchema is present */
723 rr.comp->u.complex->generic->elementSpec = 0;
724 if (srw_req->recordSchema)
726 rr.comp->u.complex->generic->elementSpec =
727 (Z_ElementSpec *) odr_malloc(assoc->encode, sizeof(Z_ElementSpec));
728 rr.comp->u.complex->generic->elementSpec->which =
729 Z_ElementSpec_elementSetName;
730 rr.comp->u.complex->generic->elementSpec->u.elementSetName =
731 srw_req->recordSchema;
734 rr.stream = assoc->encode;
735 rr.print = assoc->print;
743 rr.surrogate_flag = 0;
744 rr.schema = srw_req->recordSchema;
746 if (!assoc->init->bend_fetch)
749 retrieve_fetch(assoc, &rr);
751 if (rr.errcode && rr.surrogate_flag)
753 int code = yaz_diag_bib1_to_srw(rr.errcode);
754 const char *message = yaz_diag_srw_str(code);
757 len += strlen(message);
759 len += strlen(rr.errstring);
761 record->recordData_buf = odr_malloc(o, len);
763 sprintf(record->recordData_buf, "<diagnostic "
764 "xmlns=\"http://www.loc.gov/zing/srw/diagnostic/\">\n"
765 " <uri>info:srw/diagnostic/1/%d</uri>\n", code);
767 sprintf(record->recordData_buf + strlen(record->recordData_buf),
768 " <details>%s</details>\n", rr.errstring);
770 sprintf(record->recordData_buf + strlen(record->recordData_buf),
771 " <message>%s</message>\n", message);
772 sprintf(record->recordData_buf + strlen(record->recordData_buf),
774 record->recordData_len = strlen(record->recordData_buf);
775 record->recordPosition = odr_intdup(o, pos);
776 record->recordSchema = "info:srw/schema/1/diagnostics-v1.1";
779 else if (rr.len >= 0)
781 record->recordData_buf = rr.record;
782 record->recordData_len = rr.len;
783 record->recordPosition = odr_intdup(o, pos);
785 record->recordSchema = odr_strdup(o, rr.schema);
787 record->recordSchema = 0;
792 static int cql2pqf(ODR odr, const char *cql, cql_transform_t ct,
793 Z_Query *query_result)
795 /* have a CQL query and CQL to PQF transform .. */
796 CQL_parser cp = cql_parser_create();
802 r = cql_parser_string(cp, cql);
805 /* CQL syntax error */
811 r = cql_transform_buf(ct,
812 cql_parser_result(cp),
813 rpn_buf, sizeof(rpn_buf)-1);
815 srw_errcode = cql_transform_error(ct, &add);
819 /* Syntax & transform OK. */
820 /* Convert PQF string to Z39.50 to RPN query struct */
821 YAZ_PQF_Parser pp = yaz_pqf_create();
822 Z_RPNQuery *rpnquery = yaz_pqf_parse(pp, odr, rpn_buf);
827 int code = yaz_pqf_error(pp, &pqf_msg, &off);
828 yaz_log(YLOG_WARN, "PQF Parser Error %s (code %d)",
834 query_result->which = Z_Query_type_1;
835 query_result->u.type_1 = rpnquery;
839 cql_parser_destroy(cp);
843 static int cql2pqf_scan(ODR odr, const char *cql, cql_transform_t ct,
844 Z_AttributesPlusTerm *result)
848 int srw_error = cql2pqf(odr, cql, ct, &query);
851 if (query.which != Z_Query_type_1 && query.which != Z_Query_type_101)
852 return 10; /* bad query type */
853 rpn = query.u.type_1;
854 if (!rpn->RPNStructure)
855 return 10; /* must be structure */
856 if (rpn->RPNStructure->which != Z_RPNStructure_simple)
857 return 10; /* must be simple */
858 if (rpn->RPNStructure->u.simple->which != Z_Operand_APT)
859 return 10; /* must be attributes plus term node .. */
860 memcpy(result, rpn->RPNStructure->u.simple->u.attributesPlusTerm,
865 static void srw_bend_search(association *assoc, request *req,
867 Z_SRW_searchRetrieveResponse *srw_res,
872 Z_SRW_searchRetrieveRequest *srw_req = sr->u.request;
875 yaz_log(log_requestdetail, "Got SRW SearchRetrieveRequest");
876 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
877 if (srw_res->num_diagnostics == 0 && assoc->init)
880 rr.setname = "default";
883 rr.basenames = &srw_req->database;
887 rr.srw_setnameIdleTime = 0;
888 rr.query = (Z_Query *) odr_malloc (assoc->decode, sizeof(*rr.query));
889 rr.query->u.type_1 = 0;
891 if (srw_req->query_type == Z_SRW_query_type_cql)
893 if (assoc->server && assoc->server->cql_transform)
895 int srw_errcode = cql2pqf(assoc->encode, srw_req->query.cql,
896 assoc->server->cql_transform,
900 yaz_add_srw_diagnostic(assoc->encode,
901 &srw_res->diagnostics,
902 &srw_res->num_diagnostics,
908 /* CQL query to backend. Wrap it - Z39.50 style */
909 ext = (Z_External *) odr_malloc(assoc->decode, sizeof(*ext));
910 ext->direct_reference = odr_getoidbystr(assoc->decode,
911 "1.2.840.10003.16.2");
912 ext->indirect_reference = 0;
914 ext->which = Z_External_CQL;
915 ext->u.cql = srw_req->query.cql;
917 rr.query->which = Z_Query_type_104;
918 rr.query->u.type_104 = ext;
921 else if (srw_req->query_type == Z_SRW_query_type_pqf)
923 Z_RPNQuery *RPNquery;
924 YAZ_PQF_Parser pqf_parser;
926 pqf_parser = yaz_pqf_create ();
928 RPNquery = yaz_pqf_parse (pqf_parser, assoc->decode,
934 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
935 yaz_log(log_requestdetail, "Parse error %d %s near offset %ld",
936 code, pqf_msg, (long) off);
937 srw_error = YAZ_SRW_QUERY_SYNTAX_ERROR;
940 rr.query->which = Z_Query_type_1;
941 rr.query->u.type_1 = RPNquery;
943 yaz_pqf_destroy (pqf_parser);
947 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
948 &srw_res->num_diagnostics,
949 YAZ_SRW_UNSUPP_QUERY_TYPE, 0);
951 if (rr.query->u.type_1)
953 rr.stream = assoc->encode;
954 rr.decode = assoc->decode;
955 rr.print = assoc->print;
957 if ( srw_req->sort.sortKeys )
958 rr.srw_sortKeys = odr_strdup(assoc->encode,
959 srw_req->sort.sortKeys );
960 rr.association = assoc;
966 yaz_log_zquery_level(log_requestdetail,rr.query);
968 (assoc->init->bend_search)(assoc->backend, &rr);
971 if (rr.errcode == YAZ_BIB1_DATABASE_UNAVAILABLE)
977 srw_error = yaz_diag_bib1_to_srw (rr.errcode);
978 yaz_add_srw_diagnostic(assoc->encode,
979 &srw_res->diagnostics,
980 &srw_res->num_diagnostics,
981 srw_error, rr.errstring);
986 int number = srw_req->maximumRecords ? *srw_req->maximumRecords : 0;
987 int start = srw_req->startRecord ? *srw_req->startRecord : 1;
989 yaz_log(log_requestdetail, "Request to pack %d+%d out of %d",
990 start, number, rr.hits);
992 srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
995 srw_res->resultSetId =
996 odr_strdup(assoc->encode, rr.srw_setname );
997 srw_res->resultSetIdleTime =
998 odr_intdup(assoc->encode, *rr.srw_setnameIdleTime );
1004 if (start > rr.hits)
1006 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1007 &srw_res->num_diagnostics,
1008 YAZ_SRW_FIRST_RECORD_POSITION_OUT_OF_RANGE, 0);
1013 if (start + number > rr.hits)
1014 number = rr.hits - start + 1;
1016 /* Call bend_present if defined */
1017 if (assoc->init->bend_present)
1019 bend_present_rr *bprr = (bend_present_rr*)
1020 odr_malloc (assoc->decode, sizeof(*bprr));
1021 bprr->setname = "default";
1022 bprr->start = start;
1023 bprr->number = number;
1024 bprr->format = VAL_TEXT_XML;
1025 if (srw_req->recordSchema)
1027 bprr->comp = (Z_RecordComposition *) odr_malloc(assoc->decode,
1028 sizeof(*bprr->comp));
1029 bprr->comp->which = Z_RecordComp_simple;
1030 bprr->comp->u.simple = (Z_ElementSetNames *)
1031 odr_malloc(assoc->decode, sizeof(Z_ElementSetNames));
1032 bprr->comp->u.simple->which = Z_ElementSetNames_generic;
1033 bprr->comp->u.simple->u.generic = srw_req->recordSchema;
1039 bprr->stream = assoc->encode;
1040 bprr->referenceId = 0;
1041 bprr->print = assoc->print;
1042 bprr->request = req;
1043 bprr->association = assoc;
1045 bprr->errstring = NULL;
1046 (*assoc->init->bend_present)(assoc->backend, bprr);
1052 srw_error = yaz_diag_bib1_to_srw (bprr->errcode);
1053 yaz_add_srw_diagnostic(assoc->encode,
1054 &srw_res->diagnostics,
1055 &srw_res->num_diagnostics,
1056 srw_error, bprr->errstring);
1064 int packing = Z_SRW_recordPacking_string;
1065 if (srw_req->recordPacking){
1066 if (!strcmp(srw_req->recordPacking, "xml"))
1067 packing = Z_SRW_recordPacking_XML;
1068 if (!strcmp(srw_req->recordPacking, "url"))
1069 packing = Z_SRW_recordPacking_URL;
1071 srw_res->records = (Z_SRW_record *)
1072 odr_malloc(assoc->encode,
1073 number * sizeof(*srw_res->records));
1075 srw_res->extra_records = (Z_SRW_extra_record **)
1076 odr_malloc(assoc->encode,
1077 number*sizeof(*srw_res->extra_records));
1079 for (i = 0; i<number; i++)
1083 srw_res->records[j].recordPacking = packing;
1084 srw_res->records[j].recordData_buf = 0;
1085 srw_res->extra_records[j] = 0;
1086 yaz_log(YLOG_DEBUG, "srw_bend_fetch %d", i+start);
1087 errcode = srw_bend_fetch(assoc, i+start, srw_req,
1088 srw_res->records + j);
1091 yaz_add_srw_diagnostic(assoc->encode,
1092 &srw_res->diagnostics,
1093 &srw_res->num_diagnostics,
1094 yaz_diag_bib1_to_srw (errcode),
1099 if (srw_res->records[j].recordData_buf)
1102 srw_res->num_records = j;
1104 srw_res->records = 0;
1113 const char *querystr = "?";
1114 const char *querytype = "?";
1115 WRBUF wr = wrbuf_alloc();
1117 switch (srw_req->query_type)
1119 case Z_SRW_query_type_cql:
1121 querystr = srw_req->query.cql;
1123 case Z_SRW_query_type_pqf:
1125 querystr = srw_req->query.pqf;
1128 wrbuf_printf(wr, "SRWSearch ");
1129 wrbuf_printf(wr, srw_req->database);
1130 wrbuf_printf(wr, " ");
1131 if (srw_res->num_diagnostics)
1132 wrbuf_printf(wr, "ERROR %s", srw_res->diagnostics[0].uri);
1133 else if (*http_code != 200)
1134 wrbuf_printf(wr, "ERROR info:http/%d", *http_code);
1135 else if (srw_res->numberOfRecords)
1137 wrbuf_printf(wr, "OK %d",
1138 (srw_res->numberOfRecords ?
1139 *srw_res->numberOfRecords : 0));
1141 wrbuf_printf(wr, " %s %d+%d",
1142 (srw_res->resultSetId ?
1143 srw_res->resultSetId : "-"),
1144 (srw_req->startRecord ? *srw_req->startRecord : 1),
1145 srw_res->num_records);
1146 yaz_log(log_request, "%s %s: %s", wrbuf_buf(wr), querytype, querystr);
1151 static char *srw_bend_explain_default(void *handle, bend_explain_rr *rr)
1154 xmlNodePtr ptr = rr->server_node_ptr;
1157 for (ptr = ptr->children; ptr; ptr = ptr->next)
1159 if (ptr->type != XML_ELEMENT_NODE)
1161 if (!strcmp((const char *) ptr->name, "explain"))
1164 xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
1168 ptr = xmlCopyNode(ptr, 1);
1170 xmlDocSetRootElement(doc, ptr);
1172 xmlDocDumpMemory(doc, &buf_out, &len);
1173 content = (char*) odr_malloc(rr->stream, 1+len);
1174 memcpy(content, buf_out, len);
1175 content[len] = '\0';
1179 rr->explain_buf = content;
1187 static void srw_bend_explain(association *assoc, request *req,
1189 Z_SRW_explainResponse *srw_res,
1192 Z_SRW_explainRequest *srw_req = sr->u.explain_request;
1193 yaz_log(log_requestdetail, "Got SRW ExplainRequest");
1195 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1200 rr.stream = assoc->encode;
1201 rr.decode = assoc->decode;
1202 rr.print = assoc->print;
1204 rr.database = srw_req->database;
1206 rr.server_node_ptr = assoc->server->server_node_ptr;
1208 rr.server_node_ptr = 0;
1209 rr.schema = "http://explain.z3950.org/dtd/2.0/";
1210 if (assoc->init->bend_explain)
1211 (*assoc->init->bend_explain)(assoc->backend, &rr);
1213 srw_bend_explain_default(assoc->backend, &rr);
1217 int packing = Z_SRW_recordPacking_string;
1218 if (srw_req->recordPacking)
1220 if (!strcmp(srw_req->recordPacking, "xml"))
1221 packing = Z_SRW_recordPacking_XML;
1222 else if (!strcmp(srw_req->recordPacking, "url"))
1223 packing = Z_SRW_recordPacking_URL;
1225 srw_res->record.recordSchema = rr.schema;
1226 srw_res->record.recordPacking = packing;
1227 srw_res->record.recordData_buf = rr.explain_buf;
1228 srw_res->record.recordData_len = strlen(rr.explain_buf);
1229 srw_res->record.recordPosition = 0;
1235 static void srw_bend_scan(association *assoc, request *req,
1237 Z_SRW_scanResponse *srw_res,
1240 Z_SRW_scanRequest *srw_req = sr->u.scan_request;
1241 yaz_log(log_requestdetail, "Got SRW ScanRequest");
1244 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1245 if (srw_res->num_diagnostics == 0 && assoc->init)
1247 struct scan_entry *save_entries;
1249 bend_scan_rr *bsrr = (bend_scan_rr *)
1250 odr_malloc (assoc->encode, sizeof(*bsrr));
1251 bsrr->num_bases = 1;
1252 bsrr->basenames = &srw_req->database;
1254 bsrr->num_entries = srw_req->maximumTerms ?
1255 *srw_req->maximumTerms : 10;
1256 bsrr->term_position = srw_req->responsePosition ?
1257 *srw_req->responsePosition : 1;
1260 bsrr->errstring = 0;
1261 bsrr->referenceId = 0;
1262 bsrr->stream = assoc->encode;
1263 bsrr->print = assoc->print;
1264 bsrr->step_size = odr_intdup(assoc->decode, 0);
1267 if (bsrr->num_entries > 0)
1270 bsrr->entries = odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
1272 for (i = 0; i<bsrr->num_entries; i++)
1274 bsrr->entries[i].term = 0;
1275 bsrr->entries[i].occurrences = 0;
1276 bsrr->entries[i].errcode = 0;
1277 bsrr->entries[i].errstring = 0;
1278 bsrr->entries[i].display_term = 0;
1281 save_entries = bsrr->entries; /* save it so we can compare later */
1283 if (srw_req->query_type == Z_SRW_query_type_pqf &&
1284 assoc->init->bend_scan)
1286 Odr_oid *scan_attributeSet = 0;
1288 YAZ_PQF_Parser pqf_parser = yaz_pqf_create();
1290 bsrr->term = yaz_pqf_scan(pqf_parser, assoc->decode,
1292 srw_req->scanClause.pqf);
1293 if (scan_attributeSet &&
1294 (attset = oid_getentbyoid(scan_attributeSet)) &&
1295 (attset->oclass == CLASS_ATTSET ||
1296 attset->oclass == CLASS_GENERAL))
1297 bsrr->attributeset = attset->value;
1299 bsrr->attributeset = VAL_NONE;
1300 yaz_pqf_destroy(pqf_parser);
1301 bsrr->scanClause = 0;
1302 ((int (*)(void *, bend_scan_rr *))
1303 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1305 else if (srw_req->query_type == Z_SRW_query_type_cql
1306 && assoc->init->bend_scan && assoc->server
1307 && assoc->server->cql_transform)
1310 bsrr->scanClause = 0;
1311 bsrr->attributeset = VAL_NONE;
1312 bsrr->term = odr_malloc(assoc->decode, sizeof(*bsrr->term));
1313 srw_error = cql2pqf_scan(assoc->encode,
1314 srw_req->scanClause.cql,
1315 assoc->server->cql_transform,
1318 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1319 &srw_res->num_diagnostics,
1323 ((int (*)(void *, bend_scan_rr *))
1324 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1327 else if (srw_req->query_type == Z_SRW_query_type_cql
1328 && assoc->init->bend_srw_scan)
1331 bsrr->attributeset = VAL_NONE;
1332 bsrr->scanClause = srw_req->scanClause.cql;
1333 ((int (*)(void *, bend_scan_rr *))
1334 (*assoc->init->bend_srw_scan))(assoc->backend, bsrr);
1338 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1339 &srw_res->num_diagnostics,
1340 YAZ_SRW_UNSUPP_OPERATION, "scan");
1345 if (bsrr->errcode == YAZ_BIB1_DATABASE_UNAVAILABLE)
1350 srw_error = yaz_diag_bib1_to_srw (bsrr->errcode);
1352 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1353 &srw_res->num_diagnostics,
1354 srw_error, bsrr->errstring);
1356 else if (srw_res->num_diagnostics == 0 && bsrr->num_entries)
1359 srw_res->terms = (Z_SRW_scanTerm*)
1360 odr_malloc(assoc->encode, sizeof(*srw_res->terms) *
1363 srw_res->num_terms = bsrr->num_entries;
1364 for (i = 0; i<bsrr->num_entries; i++)
1366 Z_SRW_scanTerm *t = srw_res->terms + i;
1367 t->value = odr_strdup(assoc->encode, bsrr->entries[i].term);
1368 t->numberOfRecords =
1369 odr_intdup(assoc->encode, bsrr->entries[i].occurrences);
1371 if (save_entries == bsrr->entries &&
1372 bsrr->entries[i].display_term)
1374 /* the entries was _not_ set by the handler. So it's
1375 safe to test for new member display_term. It is
1378 t->displayTerm = odr_strdup(assoc->encode,
1379 bsrr->entries[i].display_term);
1387 WRBUF wr = wrbuf_alloc();
1388 const char *querytype = 0;
1389 const char *querystr = 0;
1391 switch(srw_req->query_type)
1393 case Z_SRW_query_type_pqf:
1395 querystr = srw_req->scanClause.pqf;
1397 case Z_SRW_query_type_cql:
1399 querystr = srw_req->scanClause.cql;
1402 querytype = "UNKNOWN";
1406 wrbuf_printf(wr, "SRWScan ");
1407 wrbuf_printf(wr, srw_req->database);
1408 wrbuf_printf(wr, " ");
1410 if (srw_res->num_diagnostics)
1411 wrbuf_printf(wr, "ERROR %s - ", srw_res->diagnostics[0].uri);
1412 else if (srw_res->num_terms)
1413 wrbuf_printf(wr, "OK %d - ", srw_res->num_terms);
1415 wrbuf_printf(wr, "OK - - ");
1417 wrbuf_printf(wr, "%d+%d+0 ",
1418 (srw_req->responsePosition ?
1419 *srw_req->responsePosition : 1),
1420 (srw_req->maximumTerms ?
1421 *srw_req->maximumTerms : 1));
1422 /* there is no step size in SRU/W ??? */
1423 wrbuf_printf(wr, "%s: %s ", querytype, querystr);
1424 yaz_log(log_request, "%s ", wrbuf_buf(wr) );
1430 static void srw_bend_update(association *assoc, request *req,
1432 Z_SRW_updateResponse *srw_res,
1435 Z_SRW_updateRequest *srw_req = sr->u.update_request;
1436 yaz_log(YLOG_DEBUG, "Got SRW UpdateRequest");
1437 yaz_log(YLOG_DEBUG, "num_diag = %d", srw_res->num_diagnostics );
1439 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1444 rr.stream = assoc->encode;
1445 rr.print = assoc->print;
1447 rr.basenames = &srw_req->database;
1448 rr.operation = srw_req->operation;
1449 rr.operation_status = "failed";
1451 rr.record_version = 0;
1452 rr.record_checksum = 0;
1453 rr.record_old_version = 0;
1454 rr.record_packing = "xml";
1455 rr.record_schema = 0;
1457 rr.request_extra_record = 0;
1458 rr.response_extra_record = 0;
1459 rr.extra_request_data = 0;
1460 rr.extra_response_data = 0;
1465 yaz_log(YLOG_DEBUG, "basename = %s", rr.basenames[0] );
1466 yaz_log(YLOG_DEBUG, "Operation = %s", rr.operation );
1467 if ( !strcmp( rr.operation, "delete" ) ){
1468 if ( !srw_req->recordId ){
1469 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1470 &srw_res->num_diagnostics,
1474 rr.record_id = srw_req->recordId;
1476 if ( !srw_req->recordVersion ){
1477 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1478 &srw_res->num_diagnostics,
1479 7, "recordVersion" );
1482 rr.record_version = odr_strdup( assoc->encode,
1483 srw_req->recordVersion );
1486 if ( srw_req->recordOldVersion ){
1487 rr.record_old_version = odr_strdup(assoc->encode,
1488 srw_req->recordOldVersion );
1490 if ( srw_req->extraRequestData ){
1491 rr.extra_request_data = odr_strdup(assoc->encode,
1492 srw_req->extraRequestData );
1495 else if ( !strcmp( rr.operation, "replace" ) ){
1496 if ( !srw_req->recordId ){
1497 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1498 &srw_res->num_diagnostics,
1502 rr.record_id = srw_req->recordId;
1504 if ( srw_req->record.recordSchema == 0 ){
1505 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1506 &srw_res->num_diagnostics,
1507 7, "recordSchema" );
1510 rr.record_schema = odr_strdup(assoc->encode,
1511 srw_req->record.recordSchema );
1513 switch (srw_req->record.recordPacking)
1515 case Z_SRW_recordPacking_string:
1516 rr.record_packing = "string";
1518 case Z_SRW_recordPacking_XML:
1519 rr.record_packing = "xml";
1521 case Z_SRW_recordPacking_URL:
1522 rr.record_packing = "url";
1525 if ( srw_req->record.recordData_len ){
1526 rr.record_data = odr_strdupn(assoc->encode,
1527 srw_req->record.recordData_buf,
1528 srw_req->record.recordData_len );
1529 rr.request_extra_record = srw_req->extra_record;
1532 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1533 &srw_res->num_diagnostics,
1536 if (srw_req->extraRequestData)
1537 rr.extra_request_data = odr_strdup(assoc->encode,
1538 srw_req->extraRequestData );
1540 else if ( !strcmp( rr.operation, "insert" ) )
1542 rr.record_id = srw_req->recordId;
1543 if ( srw_req->record.recordSchema == 0 ){
1544 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1545 &srw_res->num_diagnostics,
1546 7, "recordSchema" );
1549 rr.record_schema = odr_strdup(assoc->encode,
1550 srw_req->record.recordSchema);
1552 switch (srw_req->record.recordPacking)
1554 case Z_SRW_recordPacking_string:
1555 rr.record_packing = "string";
1557 case Z_SRW_recordPacking_XML:
1558 rr.record_packing = "xml";
1560 case Z_SRW_recordPacking_URL:
1561 rr.record_packing = "url";
1565 if (srw_req->record.recordData_len)
1567 rr.record_data = odr_strdupn(assoc->encode,
1568 srw_req->record.recordData_buf,
1569 srw_req->record.recordData_len );
1570 rr.request_extra_record = srw_req->extra_record;
1573 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1574 &srw_res->num_diagnostics,
1576 if ( srw_req->extraRequestData )
1577 rr.extra_request_data = odr_strdup(assoc->encode,
1578 srw_req->extraRequestData );
1580 if (srw_res->num_diagnostics == 0)
1582 if ( assoc->init->bend_srw_update)
1583 (*assoc->init->bend_srw_update)(assoc->backend, &rr);
1585 yaz_log( YLOG_WARN, "Got No Update function!");
1591 yaz_add_srw_diagnostic_uri(assoc->encode,
1592 &srw_res->diagnostics,
1593 &srw_res->num_diagnostics,
1597 srw_res->recordId = rr.record_id;
1598 srw_res->operationStatus = rr.operation_status;
1599 srw_res->recordVersion = rr.record_version;
1600 srw_res->recordChecksum = rr.record_checksum;
1601 srw_res->extraResponseData = rr.extra_response_data;
1602 srw_res->record.recordPosition = 0;
1603 if (srw_res->num_diagnostics == 0 && rr.record_data)
1605 srw_res->record.recordSchema = rr.record_schema;
1606 srw_res->record.recordPacking = srw_req->record.recordPacking;
1607 srw_res->record.recordData_buf = rr.record_data;
1608 srw_res->record.recordData_len = strlen(rr.record_data);
1609 srw_res->extra_record = rr.response_extra_record;
1613 srw_res->record.recordData_len = 0;
1618 /* check if path is OK (1); BAD (0) */
1619 static int check_path(const char *path)
1623 if (strstr(path, ".."))
1628 static char *read_file(const char *fname, ODR o, int *sz)
1631 FILE *inf = fopen(fname, "rb");
1635 fseek(inf, 0L, SEEK_END);
1638 buf = odr_malloc(o, *sz);
1639 fread(buf, 1, *sz, inf);
1644 static void process_http_request(association *assoc, request *req)
1646 Z_HTTP_Request *hreq = req->gdu_request->u.HTTP_Request;
1647 ODR o = assoc->encode;
1648 int r = 2; /* 2=NOT TAKEN, 1=TAKEN, 0=SOAP TAKEN */
1650 Z_SOAP *soap_package = 0;
1653 Z_HTTP_Response *hres = 0;
1655 const char *stylesheet = 0; /* for now .. set later */
1656 Z_SRW_diagnostic *diagnostic = 0;
1657 int num_diagnostic = 0;
1658 const char *host = z_HTTP_header_lookup(hreq->headers, "Host");
1660 if (!control_association(assoc, host, 0))
1662 p = z_get_HTTP_Response(o, 404);
1665 if (r == 2 && assoc->server && assoc->server->docpath
1666 && hreq->path[0] == '/'
1668 /* check if path is a proper prefix of documentroot */
1669 strncmp(hreq->path+1, assoc->server->docpath,
1670 strlen(assoc->server->docpath))
1673 if (!check_path(hreq->path))
1675 yaz_log(YLOG_LOG, "File %s access forbidden", hreq->path+1);
1676 p = z_get_HTTP_Response(o, 404);
1680 int content_size = 0;
1681 char *content_buf = read_file(hreq->path+1, o, &content_size);
1684 yaz_log(YLOG_LOG, "File %s not found", hreq->path+1);
1685 p = z_get_HTTP_Response(o, 404);
1689 const char *ctype = 0;
1690 yaz_mime_types types = yaz_mime_types_create();
1692 yaz_mime_types_add(types, "xsl", "application/xml");
1693 yaz_mime_types_add(types, "xml", "application/xml");
1694 yaz_mime_types_add(types, "css", "text/css");
1695 yaz_mime_types_add(types, "html", "text/html");
1696 yaz_mime_types_add(types, "htm", "text/html");
1697 yaz_mime_types_add(types, "txt", "text/plain");
1698 yaz_mime_types_add(types, "js", "application/x-javascript");
1700 yaz_mime_types_add(types, "gif", "image/gif");
1701 yaz_mime_types_add(types, "png", "image/png");
1702 yaz_mime_types_add(types, "jpg", "image/jpeg");
1703 yaz_mime_types_add(types, "jpeg", "image/jpeg");
1705 ctype = yaz_mime_lookup_fname(types, hreq->path);
1708 yaz_log(YLOG_LOG, "No mime type for %s", hreq->path+1);
1709 p = z_get_HTTP_Response(o, 404);
1713 p = z_get_HTTP_Response(o, 200);
1714 hres = p->u.HTTP_Response;
1715 hres->content_buf = content_buf;
1716 hres->content_len = content_size;
1717 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1719 yaz_mime_types_destroy(types);
1727 r = yaz_srw_decode(hreq, &sr, &soap_package, assoc->decode, &charset);
1728 yaz_log(YLOG_DEBUG, "yaz_srw_decode returned %d", r);
1730 if (r == 2) /* not taken */
1732 r = yaz_sru_decode(hreq, &sr, &soap_package, assoc->decode, &charset,
1733 &diagnostic, &num_diagnostic);
1734 yaz_log(YLOG_DEBUG, "yaz_sru_decode returned %d", r);
1736 if (r == 0) /* decode SRW/SRU OK .. */
1738 int http_code = 200;
1739 if (sr->which == Z_SRW_searchRetrieve_request)
1742 yaz_srw_get(assoc->encode, Z_SRW_searchRetrieve_response);
1744 stylesheet = sr->u.request->stylesheet;
1747 res->u.response->diagnostics = diagnostic;
1748 res->u.response->num_diagnostics = num_diagnostic;
1752 srw_bend_search(assoc, req, sr, res->u.response,
1755 if (http_code == 200)
1756 soap_package->u.generic->p = res;
1758 else if (sr->which == Z_SRW_explain_request)
1760 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_explain_response);
1761 stylesheet = sr->u.explain_request->stylesheet;
1764 res->u.explain_response->diagnostics = diagnostic;
1765 res->u.explain_response->num_diagnostics = num_diagnostic;
1767 srw_bend_explain(assoc, req, sr,
1768 res->u.explain_response, &http_code);
1769 if (http_code == 200)
1770 soap_package->u.generic->p = res;
1772 else if (sr->which == Z_SRW_scan_request)
1774 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_scan_response);
1775 stylesheet = sr->u.scan_request->stylesheet;
1778 res->u.scan_response->diagnostics = diagnostic;
1779 res->u.scan_response->num_diagnostics = num_diagnostic;
1781 srw_bend_scan(assoc, req, sr,
1782 res->u.scan_response, &http_code);
1783 if (http_code == 200)
1784 soap_package->u.generic->p = res;
1786 else if (sr->which == Z_SRW_update_request)
1788 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_update_response);
1789 yaz_log(YLOG_DEBUG, "handling SRW UpdateRequest");
1792 res->u.update_response->diagnostics = diagnostic;
1793 res->u.update_response->num_diagnostics = num_diagnostic;
1795 yaz_log(YLOG_DEBUG, "num_diag = %d", res->u.update_response->num_diagnostics );
1796 srw_bend_update(assoc, req, sr,
1797 res->u.update_response, &http_code);
1798 if (http_code == 200)
1799 soap_package->u.generic->p = res;
1803 yaz_log(log_request, "SOAP ERROR");
1804 /* FIXME - what error, what query */
1806 z_soap_error(assoc->encode, soap_package,
1807 "SOAP-ENV:Client", "Bad method", 0);
1809 if (http_code == 200 || http_code == 500)
1811 static Z_SOAP_Handler soap_handlers[4] = {
1813 {"http://www.loc.gov/zing/srw/", 0,
1814 (Z_SOAP_fun) yaz_srw_codec},
1815 {"http://www.loc.gov/zing/srw/v1.0/", 0,
1816 (Z_SOAP_fun) yaz_srw_codec},
1817 {"http://www.loc.gov/zing/srw/update/", 0,
1818 (Z_SOAP_fun) yaz_ucp_codec},
1824 p = z_get_HTTP_Response(o, 200);
1825 hres = p->u.HTTP_Response;
1827 if (!stylesheet && assoc->server)
1828 stylesheet = assoc->server->stylesheet;
1830 /* empty stylesheet means NO stylesheet */
1831 if (stylesheet && *stylesheet == '\0')
1834 ret = z_soap_codec_enc_xsl(assoc->encode, &soap_package,
1835 &hres->content_buf, &hres->content_len,
1836 soap_handlers, charset, stylesheet);
1837 hres->code = http_code;
1839 strcpy(ctype, "text/xml");
1842 strcat(ctype, "; charset=");
1843 strcat(ctype, charset);
1845 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1848 p = z_get_HTTP_Response(o, http_code);
1852 p = z_get_HTTP_Response(o, 500);
1853 hres = p->u.HTTP_Response;
1854 if (!strcmp(hreq->version, "1.0"))
1856 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1857 if (v && !strcmp(v, "Keep-Alive"))
1861 hres->version = "1.0";
1865 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1866 if (v && !strcmp(v, "close"))
1870 hres->version = "1.1";
1874 z_HTTP_header_add(o, &hres->headers, "Connection", "close");
1875 assoc->state = ASSOC_DEAD;
1876 assoc->cs_get_mask = 0;
1881 const char *alive = z_HTTP_header_lookup(hreq->headers, "Keep-Alive");
1883 if (alive && isdigit(*(const unsigned char *) alive))
1887 if (t < 0 || t > 3600)
1889 iochan_settimeout(assoc->client_chan,t);
1890 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1892 process_gdu_response(assoc, req, p);
1895 static void process_gdu_request(association *assoc, request *req)
1897 if (req->gdu_request->which == Z_GDU_Z3950)
1900 req->apdu_request = req->gdu_request->u.z3950;
1901 if (process_z_request(assoc, req, &msg) < 0)
1902 do_close_req(assoc, Z_Close_systemProblem, msg, req);
1904 else if (req->gdu_request->which == Z_GDU_HTTP_Request)
1905 process_http_request(assoc, req);
1908 do_close_req(assoc, Z_Close_systemProblem, "bad protocol packet", req);
1913 * Initiate request processing.
1915 static int process_z_request(association *assoc, request *req, char **msg)
1921 *msg = "Unknown Error";
1922 assert(req && req->state == REQUEST_IDLE);
1923 if (req->apdu_request->which != Z_APDU_initRequest && !assoc->init)
1925 *msg = "Missing InitRequest";
1928 switch (req->apdu_request->which)
1930 case Z_APDU_initRequest:
1931 res = process_initRequest(assoc, req); break;
1932 case Z_APDU_searchRequest:
1933 res = process_searchRequest(assoc, req, &fd); break;
1934 case Z_APDU_presentRequest:
1935 res = process_presentRequest(assoc, req, &fd); break;
1936 case Z_APDU_scanRequest:
1937 if (assoc->init->bend_scan)
1938 res = process_scanRequest(assoc, req, &fd);
1941 *msg = "Cannot handle Scan APDU";
1945 case Z_APDU_extendedServicesRequest:
1946 if (assoc->init->bend_esrequest)
1947 res = process_ESRequest(assoc, req, &fd);
1950 *msg = "Cannot handle Extended Services APDU";
1954 case Z_APDU_sortRequest:
1955 if (assoc->init->bend_sort)
1956 res = process_sortRequest(assoc, req, &fd);
1959 *msg = "Cannot handle Sort APDU";
1964 process_close(assoc, req);
1966 case Z_APDU_deleteResultSetRequest:
1967 if (assoc->init->bend_delete)
1968 res = process_deleteRequest(assoc, req, &fd);
1971 *msg = "Cannot handle Delete APDU";
1975 case Z_APDU_segmentRequest:
1976 if (assoc->init->bend_segment)
1978 res = process_segmentRequest (assoc, req);
1982 *msg = "Cannot handle Segment APDU";
1986 case Z_APDU_triggerResourceControlRequest:
1989 *msg = "Bad APDU received";
1994 yaz_log(YLOG_DEBUG, " result immediately available");
1995 retval = process_z_response(assoc, req, res);
1999 yaz_log(YLOG_DEBUG, " result unavailble");
2002 else /* no result yet - one will be provided later */
2006 /* Set up an I/O handler for the fd supplied by the backend */
2008 yaz_log(YLOG_DEBUG, " establishing handler for result");
2009 req->state = REQUEST_PENDING;
2010 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT, 0)))
2012 iochan_setdata(chan, assoc);
2019 * Handle message from the backend.
2021 void backend_response(IOCHAN i, int event)
2023 association *assoc = (association *)iochan_getdata(i);
2024 request *req = request_head(&assoc->incoming);
2028 yaz_log(YLOG_DEBUG, "backend_response");
2029 assert(assoc && req && req->state != REQUEST_IDLE);
2030 /* determine what it is we're waiting for */
2031 switch (req->apdu_request->which)
2033 case Z_APDU_searchRequest:
2034 res = response_searchRequest(assoc, req, 0, &fd); break;
2036 case Z_APDU_presentRequest:
2037 res = response_presentRequest(assoc, req, 0, &fd); break;
2038 case Z_APDU_scanRequest:
2039 res = response_scanRequest(assoc, req, 0, &fd); break;
2042 yaz_log(YLOG_FATAL, "Serious programmer's lapse or bug");
2045 if ((res && process_z_response(assoc, req, res) < 0) || fd < 0)
2047 yaz_log(YLOG_WARN, "Fatal error when talking to backend");
2048 do_close(assoc, Z_Close_systemProblem, 0);
2052 else if (!res) /* no result yet - try again later */
2054 yaz_log(YLOG_DEBUG, " no result yet");
2055 iochan_setfd(i, fd); /* in case fd has changed */
2060 * Encode response, and transfer the request structure to the outgoing queue.
2062 static int process_gdu_response(association *assoc, request *req, Z_GDU *res)
2064 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
2068 if (!z_GDU(assoc->print, &res, 0, 0))
2069 yaz_log(YLOG_WARN, "ODR print error: %s",
2070 odr_errmsg(odr_geterror(assoc->print)));
2071 odr_reset(assoc->print);
2073 if (!z_GDU(assoc->encode, &res, 0, 0))
2075 yaz_log(YLOG_WARN, "ODR error when encoding PDU: %s [element %s]",
2076 odr_errmsg(odr_geterror(assoc->decode)),
2077 odr_getelement(assoc->decode));
2080 req->response = odr_getbuf(assoc->encode, &req->len_response,
2081 &req->size_response);
2082 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
2083 odr_reset(assoc->encode);
2084 req->state = REQUEST_IDLE;
2085 request_enq(&assoc->outgoing, req);
2086 /* turn the work over to the ir_session handler */
2087 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
2088 assoc->cs_put_mask = EVENT_OUTPUT;
2089 /* Is there more work to be done? give that to the input handler too */
2091 if (request_head(&assoc->incoming))
2093 yaz_log (YLOG_DEBUG, "more work to be done");
2094 iochan_setevent(assoc->client_chan, EVENT_WORK);
2101 * Encode response, and transfer the request structure to the outgoing queue.
2103 static int process_z_response(association *assoc, request *req, Z_APDU *res)
2105 Z_GDU *gres = (Z_GDU *) odr_malloc(assoc->encode, sizeof(*res));
2106 gres->which = Z_GDU_Z3950;
2107 gres->u.z3950 = res;
2109 return process_gdu_response(assoc, req, gres);
2112 static char *get_vhost(Z_OtherInformation *otherInfo)
2114 return yaz_oi_get_string_oidval(&otherInfo, VAL_PROXY, 1, 0);
2118 * Handle init request.
2119 * At the moment, we don't check the options
2120 * anywhere else in the code - we just try not to do anything that would
2121 * break a naive client. We'll toss 'em into the association block when
2122 * we need them there.
2124 static Z_APDU *process_initRequest(association *assoc, request *reqb)
2126 Z_InitRequest *req = reqb->apdu_request->u.initRequest;
2127 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
2128 Z_InitResponse *resp = apdu->u.initResponse;
2129 bend_initresult *binitres;
2132 statserv_options_block *cb = 0; /* by default no control for backend */
2134 if (control_association(assoc, get_vhost(req->otherInfo), 1))
2135 cb = statserv_getcontrol(); /* got control block for backend */
2137 if (cb && assoc->backend)
2138 (*cb->bend_close)(assoc->backend);
2140 yaz_log(log_requestdetail, "Got initRequest");
2141 if (req->implementationId)
2142 yaz_log(log_requestdetail, "Id: %s",
2143 req->implementationId);
2144 if (req->implementationName)
2145 yaz_log(log_requestdetail, "Name: %s",
2146 req->implementationName);
2147 if (req->implementationVersion)
2148 yaz_log(log_requestdetail, "Version: %s",
2149 req->implementationVersion);
2151 assoc_init_reset(assoc);
2153 assoc->init->auth = req->idAuthentication;
2154 assoc->init->referenceId = req->referenceId;
2156 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
2158 Z_CharSetandLanguageNegotiation *negotiation =
2159 yaz_get_charneg_record (req->otherInfo);
2161 negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
2162 assoc->init->charneg_request = negotiation;
2168 if (req->implementationVersion)
2169 yaz_log(log_requestdetail, "Config: %s",
2172 iochan_settimeout(assoc->client_chan, cb->idle_timeout * 60);
2174 /* we have a backend control block, so call that init function */
2175 if (!(binitres = (*cb->bend_init)(assoc->init)))
2177 yaz_log(YLOG_WARN, "Bad response from backend.");
2180 assoc->backend = binitres->handle;
2184 /* no backend. return error */
2185 binitres = odr_malloc(assoc->encode, sizeof(*binitres));
2186 binitres->errstring = 0;
2187 binitres->errcode = YAZ_BIB1_PERMANENT_SYSTEM_ERROR;
2188 iochan_settimeout(assoc->client_chan, 10);
2190 if ((assoc->init->bend_sort))
2191 yaz_log (YLOG_DEBUG, "Sort handler installed");
2192 if ((assoc->init->bend_search))
2193 yaz_log (YLOG_DEBUG, "Search handler installed");
2194 if ((assoc->init->bend_present))
2195 yaz_log (YLOG_DEBUG, "Present handler installed");
2196 if ((assoc->init->bend_esrequest))
2197 yaz_log (YLOG_DEBUG, "ESRequest handler installed");
2198 if ((assoc->init->bend_delete))
2199 yaz_log (YLOG_DEBUG, "Delete handler installed");
2200 if ((assoc->init->bend_scan))
2201 yaz_log (YLOG_DEBUG, "Scan handler installed");
2202 if ((assoc->init->bend_segment))
2203 yaz_log (YLOG_DEBUG, "Segment handler installed");
2205 resp->referenceId = req->referenceId;
2207 /* let's tell the client what we can do */
2208 if (ODR_MASK_GET(req->options, Z_Options_search))
2210 ODR_MASK_SET(resp->options, Z_Options_search);
2211 strcat(options, "srch");
2213 if (ODR_MASK_GET(req->options, Z_Options_present))
2215 ODR_MASK_SET(resp->options, Z_Options_present);
2216 strcat(options, " prst");
2218 if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
2219 assoc->init->bend_delete)
2221 ODR_MASK_SET(resp->options, Z_Options_delSet);
2222 strcat(options, " del");
2224 if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
2225 assoc->init->bend_esrequest)
2227 ODR_MASK_SET(resp->options, Z_Options_extendedServices);
2228 strcat (options, " extendedServices");
2230 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
2232 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
2233 strcat(options, " namedresults");
2235 if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
2237 ODR_MASK_SET(resp->options, Z_Options_scan);
2238 strcat(options, " scan");
2240 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
2242 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
2243 strcat(options, " concurrop");
2245 if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
2247 ODR_MASK_SET(resp->options, Z_Options_sort);
2248 strcat(options, " sort");
2251 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel)
2252 && assoc->init->charneg_response)
2254 Z_OtherInformation **p;
2255 Z_OtherInformationUnit *p0;
2257 yaz_oi_APDU(apdu, &p);
2259 if ((p0=yaz_oi_update(p, assoc->encode, NULL, 0, 0))) {
2260 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
2262 p0->which = Z_OtherInfo_externallyDefinedInfo;
2263 p0->information.externallyDefinedInfo =
2264 assoc->init->charneg_response;
2266 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
2267 strcat(options, " negotiation");
2270 if (ODR_MASK_GET(req->options, Z_Options_triggerResourceCtrl))
2271 ODR_MASK_SET(resp->options, Z_Options_triggerResourceCtrl);
2273 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
2275 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
2276 assoc->version = 1; /* 1 & 2 are equivalent */
2278 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
2280 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
2283 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
2285 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
2289 yaz_log(log_requestdetail, "Negotiated to v%d: %s", assoc->version, options);
2290 assoc->maximumRecordSize = *req->maximumRecordSize;
2292 if (cb && assoc->maximumRecordSize > cb->maxrecordsize)
2293 assoc->maximumRecordSize = cb->maxrecordsize;
2294 assoc->preferredMessageSize = *req->preferredMessageSize;
2295 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
2296 assoc->preferredMessageSize = assoc->maximumRecordSize;
2298 resp->preferredMessageSize = &assoc->preferredMessageSize;
2299 resp->maximumRecordSize = &assoc->maximumRecordSize;
2301 resp->implementationId = odr_prepend(assoc->encode,
2302 assoc->init->implementation_id,
2303 resp->implementationId);
2305 resp->implementationName = odr_prepend(assoc->encode,
2306 assoc->init->implementation_name,
2307 odr_prepend(assoc->encode, "GFS", resp->implementationName));
2309 version = odr_strdup(assoc->encode, "$Revision: 1.93 $");
2310 if (strlen(version) > 10) /* check for unexpanded CVS strings */
2311 version[strlen(version)-2] = '\0';
2312 resp->implementationVersion = odr_prepend(assoc->encode,
2313 assoc->init->implementation_version,
2314 odr_prepend(assoc->encode, &version[11],
2315 resp->implementationVersion));
2317 if (binitres->errcode)
2319 assoc->state = ASSOC_DEAD;
2320 resp->userInformationField =
2321 init_diagnostics(assoc->encode, binitres->errcode,
2322 binitres->errstring);
2327 if (!req->idAuthentication)
2328 yaz_log(log_request, "Auth none");
2329 else if (req->idAuthentication->which == Z_IdAuthentication_open)
2331 const char *open = req->idAuthentication->u.open;
2332 const char *slash = strchr(open, '/');
2338 yaz_log(log_request, "Auth open %.*s", len, open);
2340 else if (req->idAuthentication->which == Z_IdAuthentication_idPass)
2342 const char *user = req->idAuthentication->u.idPass->userId;
2343 const char *group = req->idAuthentication->u.idPass->groupId;
2344 yaz_log(log_request, "Auth idPass %s %s",
2345 user ? user : "-", group ? group : "-");
2347 else if (req->idAuthentication->which
2348 == Z_IdAuthentication_anonymous)
2350 yaz_log(log_request, "Auth anonymous");
2354 yaz_log(log_request, "Auth other");
2359 WRBUF wr = wrbuf_alloc();
2360 wrbuf_printf(wr, "Init ");
2361 if (binitres->errcode)
2362 wrbuf_printf(wr, "ERROR %d", binitres->errcode);
2364 wrbuf_printf(wr, "OK -");
2365 wrbuf_printf(wr, " ID:%s Name:%s Version:%s",
2366 (req->implementationId ? req->implementationId :"-"),
2367 (req->implementationName ?
2368 req->implementationName : "-"),
2369 (req->implementationVersion ?
2370 req->implementationVersion : "-")
2372 yaz_log(log_request, "%s", wrbuf_buf(wr));
2379 * Set the specified `errcode' and `errstring' into a UserInfo-1
2380 * external to be returned to the client in accordance with Z35.90
2381 * Implementor Agreement 5 (Returning diagnostics in an InitResponse):
2382 * http://lcweb.loc.gov/z3950/agency/agree/initdiag.html
2384 static Z_External *init_diagnostics(ODR odr, int error, const char *addinfo)
2386 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2387 addinfo ? " -- " : "", addinfo ? addinfo : "");
2388 return zget_init_diagnostics(odr, error, addinfo);
2392 * nonsurrogate diagnostic record.
2394 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
2396 Z_Records *rec = (Z_Records *) odr_malloc (assoc->encode, sizeof(*rec));
2398 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2399 addinfo ? " -- " : "", addinfo ? addinfo : "");
2401 rec->which = Z_Records_NSD;
2402 rec->u.nonSurrogateDiagnostic = zget_DefaultDiagFormat(assoc->encode,
2408 * surrogate diagnostic.
2410 static Z_NamePlusRecord *surrogatediagrec(association *assoc,
2412 int error, const char *addinfo)
2414 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2415 addinfo ? " -- " : "", addinfo ? addinfo : "");
2416 return zget_surrogateDiagRec(assoc->encode, dbname, error, addinfo);
2419 static Z_Records *pack_records(association *a, char *setname, int start,
2420 int *num, Z_RecordComposition *comp,
2421 int *next, int *pres, oid_value format,
2422 Z_ReferenceId *referenceId,
2423 int *oid, int *errcode)
2425 int recno, total_length = 0, toget = *num, dumped_records = 0;
2426 Z_Records *records =
2427 (Z_Records *) odr_malloc (a->encode, sizeof(*records));
2428 Z_NamePlusRecordList *reclist =
2429 (Z_NamePlusRecordList *) odr_malloc (a->encode, sizeof(*reclist));
2430 Z_NamePlusRecord **list =
2431 (Z_NamePlusRecord **) odr_malloc (a->encode, sizeof(*list) * toget);
2433 records->which = Z_Records_DBOSD;
2434 records->u.databaseOrSurDiagnostics = reclist;
2435 reclist->num_records = 0;
2436 reclist->records = list;
2437 *pres = Z_PresentStatus_success;
2441 yaz_log(log_requestdetail, "Request to pack %d+%d %s", start, toget, setname);
2442 yaz_log(log_requestdetail, "pms=%d, mrs=%d", a->preferredMessageSize,
2443 a->maximumRecordSize);
2444 for (recno = start; reclist->num_records < toget; recno++)
2447 Z_NamePlusRecord *thisrec;
2448 int this_length = 0;
2450 * we get the number of bytes allocated on the stream before any
2451 * allocation done by the backend - this should give us a reasonable
2452 * idea of the total size of the data so far.
2454 total_length = odr_total(a->encode) - dumped_records;
2460 freq.last_in_set = 0;
2461 freq.setname = setname;
2462 freq.surrogate_flag = 0;
2463 freq.number = recno;
2465 freq.request_format = format;
2466 freq.request_format_raw = oid;
2467 freq.output_format = format;
2468 freq.output_format_raw = 0;
2469 freq.stream = a->encode;
2470 freq.print = a->print;
2471 freq.referenceId = referenceId;
2474 retrieve_fetch(a, &freq);
2476 *next = freq.last_in_set ? 0 : recno + 1;
2478 /* backend should be able to signal whether error is system-wide
2479 or only pertaining to current record */
2482 if (!freq.surrogate_flag)
2485 *pres = Z_PresentStatus_failure;
2486 /* for 'present request out of range',
2487 set addinfo to record position if not set */
2488 if (freq.errcode == YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE &&
2489 freq.errstring == 0)
2491 sprintf (s, "%d", recno);
2495 *errcode = freq.errcode;
2496 return diagrec(a, freq.errcode, freq.errstring);
2498 reclist->records[reclist->num_records] =
2499 surrogatediagrec(a, freq.basename, freq.errcode,
2501 reclist->num_records++;
2504 if (freq.record == 0) /* no error and no record ? */
2506 *next = 0; /* signal end-of-set and stop */
2510 this_length = freq.len;
2512 this_length = odr_total(a->encode) - total_length - dumped_records;
2513 yaz_log(YLOG_DEBUG, " fetched record, len=%d, total=%d dumped=%d",
2514 this_length, total_length, dumped_records);
2515 if (a->preferredMessageSize > 0 &&
2516 this_length + total_length > a->preferredMessageSize)
2518 /* record is small enough, really */
2519 if (this_length <= a->preferredMessageSize && recno > start)
2521 yaz_log(log_requestdetail, " Dropped last normal-sized record");
2522 *pres = Z_PresentStatus_partial_2;
2525 /* record can only be fetched by itself */
2526 if (this_length < a->maximumRecordSize)
2528 yaz_log(log_requestdetail, " Record > prefmsgsz");
2531 yaz_log(YLOG_DEBUG, " Dropped it");
2532 reclist->records[reclist->num_records] =
2533 surrogatediagrec(a, freq.basename, 16, 0);
2534 reclist->num_records++;
2535 dumped_records += this_length;
2539 else /* too big entirely */
2541 yaz_log(log_requestdetail, "Record > maxrcdsz this=%d max=%d",
2542 this_length, a->maximumRecordSize);
2543 reclist->records[reclist->num_records] =
2544 surrogatediagrec(a, freq.basename, 17, 0);
2545 reclist->num_records++;
2546 dumped_records += this_length;
2551 if (!(thisrec = (Z_NamePlusRecord *)
2552 odr_malloc(a->encode, sizeof(*thisrec))))
2555 thisrec->databaseName = odr_strdup(a->encode, freq.basename);
2557 thisrec->databaseName = 0;
2558 thisrec->which = Z_NamePlusRecord_databaseRecord;
2560 if (freq.output_format_raw)
2562 struct oident *ident = oid_getentbyoid(freq.output_format_raw);
2563 freq.output_format = ident->value;
2565 thisrec->u.databaseRecord = z_ext_record(a->encode, freq.output_format,
2566 freq.record, freq.len);
2567 if (!thisrec->u.databaseRecord)
2569 reclist->records[reclist->num_records] = thisrec;
2570 reclist->num_records++;
2572 *num = reclist->num_records;
2576 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
2579 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2580 bend_search_rr *bsrr =
2581 (bend_search_rr *)nmem_malloc (reqb->request_mem, sizeof(*bsrr));
2583 yaz_log(log_requestdetail, "Got SearchRequest.");
2585 bsrr->request = reqb;
2586 bsrr->association = assoc;
2587 bsrr->referenceId = req->referenceId;
2588 save_referenceId (reqb, bsrr->referenceId);
2589 bsrr->srw_sortKeys = 0;
2590 bsrr->srw_setname = 0;
2591 bsrr->srw_setnameIdleTime = 0;
2593 yaz_log (log_requestdetail, "ResultSet '%s'", req->resultSetName);
2594 if (req->databaseNames)
2597 for (i = 0; i < req->num_databaseNames; i++)
2598 yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
2601 yaz_log_zquery_level(log_requestdetail,req->query);
2603 if (assoc->init->bend_search)
2605 bsrr->setname = req->resultSetName;
2606 bsrr->replace_set = *req->replaceIndicator;
2607 bsrr->num_bases = req->num_databaseNames;
2608 bsrr->basenames = req->databaseNames;
2609 bsrr->query = req->query;
2610 bsrr->stream = assoc->encode;
2611 nmem_transfer(bsrr->stream->mem, reqb->request_mem);
2612 bsrr->decode = assoc->decode;
2613 bsrr->print = assoc->print;
2616 bsrr->errstring = NULL;
2617 bsrr->search_info = NULL;
2619 if (assoc->server && assoc->server->cql_transform
2620 && req->query->which == Z_Query_type_104
2621 && req->query->u.type_104->which == Z_External_CQL)
2623 /* have a CQL query and a CQL to PQF transform .. */
2625 cql2pqf(bsrr->stream, req->query->u.type_104->u.cql,
2626 assoc->server->cql_transform, bsrr->query);
2628 bsrr->errcode = yaz_diag_srw_to_bib1(srw_errcode);
2631 (assoc->init->bend_search)(assoc->backend, bsrr);
2632 if (!bsrr->request) /* backend not ready with the search response */
2633 return 0; /* should not be used any more */
2637 /* FIXME - make a diagnostic for it */
2638 yaz_log(YLOG_WARN,"Search not supported ?!?!");
2640 return response_searchRequest(assoc, reqb, bsrr, fd);
2643 int bend_searchresponse(void *handle, bend_search_rr *bsrr) {return 0;}
2646 * Prepare a searchresponse based on the backend results. We probably want
2647 * to look at making the fetching of records nonblocking as well, but
2648 * so far, we'll keep things simple.
2649 * If bsrt is null, that means we're called in response to a communications
2650 * event, and we'll have to get the response for ourselves.
2652 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
2653 bend_search_rr *bsrt, int *fd)
2655 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2656 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2657 Z_SearchResponse *resp = (Z_SearchResponse *)
2658 odr_malloc (assoc->encode, sizeof(*resp));
2659 int *nulint = odr_intdup (assoc->encode, 0);
2660 bool_t *sr = odr_intdup(assoc->encode, 1);
2661 int *next = odr_intdup(assoc->encode, 0);
2662 int *none = odr_intdup(assoc->encode, Z_SearchResponse_none);
2665 apdu->which = Z_APDU_searchResponse;
2666 apdu->u.searchResponse = resp;
2667 resp->referenceId = req->referenceId;
2668 resp->additionalSearchInfo = 0;
2669 resp->otherInfo = 0;
2671 if (!bsrt && !bend_searchresponse(assoc->backend, bsrt))
2673 yaz_log(YLOG_FATAL, "Bad result from backend");
2676 else if (bsrt->errcode)
2678 resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
2679 resp->resultCount = nulint;
2680 resp->numberOfRecordsReturned = nulint;
2681 resp->nextResultSetPosition = nulint;
2682 resp->searchStatus = nulint;
2683 resp->resultSetStatus = none;
2684 resp->presentStatus = 0;
2688 int *toget = odr_intdup(assoc->encode, 0);
2689 int *presst = odr_intdup(assoc->encode, 0);
2690 Z_RecordComposition comp, *compp = 0;
2692 yaz_log (log_requestdetail, "resultCount: %d", bsrt->hits);
2695 resp->resultCount = &bsrt->hits;
2697 comp.which = Z_RecordComp_simple;
2698 /* how many records does the user agent want, then? */
2699 if (bsrt->hits <= *req->smallSetUpperBound)
2701 *toget = bsrt->hits;
2702 if ((comp.u.simple = req->smallSetElementSetNames))
2705 else if (bsrt->hits < *req->largeSetLowerBound)
2707 *toget = *req->mediumSetPresentNumber;
2708 if (*toget > bsrt->hits)
2709 *toget = bsrt->hits;
2710 if ((comp.u.simple = req->mediumSetElementSetNames))
2716 if (*toget && !resp->records)
2721 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
2724 form = prefformat->value;
2726 /* Call bend_present if defined */
2727 if (assoc->init->bend_present)
2729 bend_present_rr *bprr = (bend_present_rr *)
2730 nmem_malloc (reqb->request_mem, sizeof(*bprr));
2731 bprr->setname = req->resultSetName;
2733 bprr->number = *toget;
2734 bprr->format = form;
2736 bprr->referenceId = req->referenceId;
2737 bprr->stream = assoc->encode;
2738 bprr->print = assoc->print;
2739 bprr->request = reqb;
2740 bprr->association = assoc;
2742 bprr->errstring = NULL;
2743 (*assoc->init->bend_present)(assoc->backend, bprr);
2749 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2750 *resp->presentStatus = Z_PresentStatus_failure;
2755 resp->records = pack_records(assoc, req->resultSetName, 1,
2756 toget, compp, next, presst, form, req->referenceId,
2757 req->preferredRecordSyntax, NULL);
2760 resp->numberOfRecordsReturned = toget;
2761 returnedrecs = *toget;
2762 resp->nextResultSetPosition = next;
2763 resp->searchStatus = sr;
2764 resp->resultSetStatus = 0;
2765 resp->presentStatus = presst;
2769 if (*resp->resultCount)
2771 resp->numberOfRecordsReturned = nulint;
2772 resp->nextResultSetPosition = next;
2773 resp->searchStatus = sr;
2774 resp->resultSetStatus = 0;
2775 resp->presentStatus = 0;
2778 resp->additionalSearchInfo = bsrt->search_info;
2783 WRBUF wr = wrbuf_alloc();
2785 for (i = 0 ; i < req->num_databaseNames; i++){
2787 wrbuf_printf(wr, "+");
2788 wrbuf_printf(wr, req->databaseNames[i]);
2790 wrbuf_printf(wr, " ");
2793 wrbuf_printf(wr, "ERROR %d", bsrt->errcode);
2795 wrbuf_printf(wr, "OK %d", bsrt->hits);
2796 wrbuf_printf(wr, " %s 1+%d ",
2797 req->resultSetName, returnedrecs);
2798 yaz_query_to_wrbuf(wr, req->query);
2800 yaz_log(log_request, "Search %s", wrbuf_buf(wr));
2807 * Maybe we got a little over-friendly when we designed bend_fetch to
2808 * get only one record at a time. Some backends can optimise multiple-record
2809 * fetches, and at any rate, there is some overhead involved in
2810 * all that selecting and hopping around. Problem is, of course, that the
2811 * frontend can't know ahead of time how many records it'll need to
2812 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
2813 * is downright lousy as a bulk data transfer protocol.
2815 * To start with, we'll do the fetching of records from the backend
2816 * in one operation: To save some trips in and out of the event-handler,
2817 * and to simplify the interface to pack_records. At any rate, asynch
2818 * operation is more fun in operations that have an unpredictable execution
2819 * speed - which is normally more true for search than for present.
2821 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
2824 Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
2828 Z_PresentResponse *resp;
2832 const char *errstring = 0;
2834 yaz_log(log_requestdetail, "Got PresentRequest.");
2836 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
2839 form = prefformat->value;
2840 resp = (Z_PresentResponse *)odr_malloc (assoc->encode, sizeof(*resp));
2842 resp->presentStatus = odr_intdup(assoc->encode, 0);
2843 if (assoc->init->bend_present)
2845 bend_present_rr *bprr = (bend_present_rr *)
2846 nmem_malloc (reqb->request_mem, sizeof(*bprr));
2847 bprr->setname = req->resultSetId;
2848 bprr->start = *req->resultSetStartPoint;
2849 bprr->number = *req->numberOfRecordsRequested;
2850 bprr->format = form;
2851 bprr->comp = req->recordComposition;
2852 bprr->referenceId = req->referenceId;
2853 bprr->stream = assoc->encode;
2854 bprr->print = assoc->print;
2855 bprr->request = reqb;
2856 bprr->association = assoc;
2858 bprr->errstring = NULL;
2859 (*assoc->init->bend_present)(assoc->backend, bprr);
2862 return 0; /* should not happen */
2865 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2866 *resp->presentStatus = Z_PresentStatus_failure;
2867 errcode = bprr->errcode;
2868 errstring = bprr->errstring;
2871 apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2872 next = odr_intdup(assoc->encode, 0);
2873 num = odr_intdup(assoc->encode, 0);
2875 apdu->which = Z_APDU_presentResponse;
2876 apdu->u.presentResponse = resp;
2877 resp->referenceId = req->referenceId;
2878 resp->otherInfo = 0;
2882 *num = *req->numberOfRecordsRequested;
2884 pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
2885 num, req->recordComposition, next,
2886 resp->presentStatus,
2887 form, req->referenceId, req->preferredRecordSyntax,
2892 WRBUF wr = wrbuf_alloc();
2893 wrbuf_printf(wr, "Present ");
2895 if (*resp->presentStatus == Z_PresentStatus_failure)
2896 wrbuf_printf(wr, "ERROR %d ", errcode);
2897 else if (*resp->presentStatus == Z_PresentStatus_success)
2898 wrbuf_printf(wr, "OK - ");
2900 wrbuf_printf(wr, "Partial %d - ", *resp->presentStatus);
2902 wrbuf_printf(wr, " %s %d+%d ",
2903 req->resultSetId, *req->resultSetStartPoint,
2904 *req->numberOfRecordsRequested);
2905 yaz_log(log_request, "%s", wrbuf_buf(wr) );
2910 resp->numberOfRecordsReturned = num;
2911 resp->nextResultSetPosition = next;
2917 * Scan was implemented rather in a hurry, and with support for only the basic
2918 * elements of the service in the backend API. Suggestions are welcome.
2920 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
2922 Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
2923 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2924 Z_ScanResponse *res = (Z_ScanResponse *)
2925 odr_malloc (assoc->encode, sizeof(*res));
2926 int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
2927 int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
2928 Z_ListEntries *ents = (Z_ListEntries *)
2929 odr_malloc (assoc->encode, sizeof(*ents));
2930 Z_DiagRecs *diagrecs_p = NULL;
2932 bend_scan_rr *bsrr = (bend_scan_rr *)
2933 odr_malloc (assoc->encode, sizeof(*bsrr));
2934 struct scan_entry *save_entries;
2936 yaz_log(log_requestdetail, "Got ScanRequest");
2938 apdu->which = Z_APDU_scanResponse;
2939 apdu->u.scanResponse = res;
2940 res->referenceId = req->referenceId;
2942 /* if step is absent, set it to 0 */
2943 res->stepSize = odr_intdup(assoc->encode, 0);
2945 *res->stepSize = *req->stepSize;
2947 res->scanStatus = scanStatus;
2948 res->numberOfEntriesReturned = numberOfEntriesReturned;
2949 res->positionOfTerm = 0;
2950 res->entries = ents;
2951 ents->num_entries = 0;
2952 ents->entries = NULL;
2953 ents->num_nonsurrogateDiagnostics = 0;
2954 ents->nonsurrogateDiagnostics = NULL;
2955 res->attributeSet = 0;
2958 if (req->databaseNames)
2961 for (i = 0; i < req->num_databaseNames; i++)
2962 yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
2964 bsrr->scanClause = 0;
2966 bsrr->errstring = 0;
2967 bsrr->num_bases = req->num_databaseNames;
2968 bsrr->basenames = req->databaseNames;
2969 bsrr->num_entries = *req->numberOfTermsRequested;
2970 bsrr->term = req->termListAndStartPoint;
2971 bsrr->referenceId = req->referenceId;
2972 bsrr->stream = assoc->encode;
2973 bsrr->print = assoc->print;
2974 bsrr->step_size = res->stepSize;
2976 /* For YAZ 2.0 and earlier it was the backend handler that
2977 initialized entries (member display_term did not exist)
2978 YAZ 2.0 and later sets 'entries' and initialize all members
2979 including 'display_term'. If YAZ 2.0 or later sees that
2980 entries was modified - we assume that it is an old handler and
2981 that 'display_term' is _not_ set.
2983 if (bsrr->num_entries > 0)
2986 bsrr->entries = odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
2988 for (i = 0; i<bsrr->num_entries; i++)
2990 bsrr->entries[i].term = 0;
2991 bsrr->entries[i].occurrences = 0;
2992 bsrr->entries[i].errcode = 0;
2993 bsrr->entries[i].errstring = 0;
2994 bsrr->entries[i].display_term = 0;
2997 save_entries = bsrr->entries; /* save it so we can compare later */
2999 if (req->attributeSet &&
3000 (attset = oid_getentbyoid(req->attributeSet)) &&
3001 (attset->oclass == CLASS_ATTSET || attset->oclass == CLASS_GENERAL))
3002 bsrr->attributeset = attset->value;
3004 bsrr->attributeset = VAL_NONE;
3005 log_scan_term_level (log_requestdetail, req->termListAndStartPoint,
3006 bsrr->attributeset);
3007 bsrr->term_position = req->preferredPositionInResponse ?
3008 *req->preferredPositionInResponse : 1;
3010 ((int (*)(void *, bend_scan_rr *))
3011 (*assoc->init->bend_scan))(assoc->backend, bsrr);
3014 diagrecs_p = zget_DiagRecs(assoc->encode,
3015 bsrr->errcode, bsrr->errstring);
3019 Z_Entry **tab = (Z_Entry **)
3020 odr_malloc (assoc->encode, sizeof(*tab) * bsrr->num_entries);
3022 if (bsrr->status == BEND_SCAN_PARTIAL)
3023 *scanStatus = Z_Scan_partial_5;
3025 *scanStatus = Z_Scan_success;
3026 ents->entries = tab;
3027 ents->num_entries = bsrr->num_entries;
3028 res->numberOfEntriesReturned = &ents->num_entries;
3029 res->positionOfTerm = &bsrr->term_position;
3030 for (i = 0; i < bsrr->num_entries; i++)
3036 tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
3037 if (bsrr->entries[i].occurrences >= 0)
3039 e->which = Z_Entry_termInfo;
3040 e->u.termInfo = t = (Z_TermInfo *)
3041 odr_malloc(assoc->encode, sizeof(*t));
3042 t->suggestedAttributes = 0;
3044 if (save_entries == bsrr->entries &&
3045 bsrr->entries[i].display_term)
3047 /* the entries was _not_ set by the handler. So it's
3048 safe to test for new member display_term. It is
3051 t->displayTerm = odr_strdup(assoc->encode,
3052 bsrr->entries[i].display_term);
3054 t->alternativeTerm = 0;
3055 t->byAttributes = 0;
3056 t->otherTermInfo = 0;
3057 t->globalOccurrences = &bsrr->entries[i].occurrences;
3058 t->term = (Z_Term *)
3059 odr_malloc(assoc->encode, sizeof(*t->term));
3060 t->term->which = Z_Term_general;
3061 t->term->u.general = o =
3062 (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
3063 o->buf = (unsigned char *)
3064 odr_malloc(assoc->encode, o->len = o->size =
3065 strlen(bsrr->entries[i].term));
3066 memcpy(o->buf, bsrr->entries[i].term, o->len);
3067 yaz_log(YLOG_DEBUG, " term #%d: '%s' (%d)", i,
3068 bsrr->entries[i].term, bsrr->entries[i].occurrences);
3072 Z_DiagRecs *drecs = zget_DiagRecs(assoc->encode,
3073 bsrr->entries[i].errcode,
3074 bsrr->entries[i].errstring);
3075 assert (drecs->num_diagRecs == 1);
3076 e->which = Z_Entry_surrogateDiagnostic;
3077 assert (drecs->diagRecs[0]);
3078 e->u.surrogateDiagnostic = drecs->diagRecs[0];
3084 ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
3085 ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
3090 WRBUF wr = wrbuf_alloc();
3091 wrbuf_printf(wr, "Scan ");
3092 for (i = 0 ; i < req->num_databaseNames; i++){
3094 wrbuf_printf(wr, "+");
3095 wrbuf_printf(wr, req->databaseNames[i]);
3097 wrbuf_printf(wr, " ");
3100 wr_diag(wr, bsrr->errcode, bsrr->errstring);
3101 wrbuf_printf(wr, " ");
3104 wrbuf_printf(wr, "OK ");
3105 /* else if (*res->scanStatus == Z_Scan_success) */
3106 /* wrbuf_printf(wr, "OK "); */
3108 /* wrbuf_printf(wr, "Partial "); */
3110 if (*res->numberOfEntriesReturned)
3111 wrbuf_printf(wr, "%d - ", *res->numberOfEntriesReturned);
3113 wrbuf_printf(wr, "0 - ");
3115 wrbuf_printf(wr, "%d+%d+%d ",
3116 (req->preferredPositionInResponse ?
3117 *req->preferredPositionInResponse : 1),
3118 *req->numberOfTermsRequested,
3119 (res->stepSize ? *res->stepSize : 1));
3121 yaz_scan_to_wrbuf(wr, req->termListAndStartPoint,
3122 bsrr->attributeset);
3123 yaz_log(log_request, "%s", wrbuf_buf(wr) );
3129 static Z_APDU *process_sortRequest(association *assoc, request *reqb,
3133 Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
3134 Z_SortResponse *res = (Z_SortResponse *)
3135 odr_malloc (assoc->encode, sizeof(*res));
3136 bend_sort_rr *bsrr = (bend_sort_rr *)
3137 odr_malloc (assoc->encode, sizeof(*bsrr));
3139 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
3141 yaz_log(log_requestdetail, "Got SortRequest.");
3143 bsrr->num_input_setnames = req->num_inputResultSetNames;
3144 for (i=0;i<req->num_inputResultSetNames;i++)
3145 yaz_log(log_requestdetail, "Input resultset: '%s'",
3146 req->inputResultSetNames[i]);
3147 bsrr->input_setnames = req->inputResultSetNames;
3148 bsrr->referenceId = req->referenceId;
3149 bsrr->output_setname = req->sortedResultSetName;
3150 yaz_log(log_requestdetail, "Output resultset: '%s'",
3151 req->sortedResultSetName);
3152 bsrr->sort_sequence = req->sortSequence;
3153 /*FIXME - dump those sequences too */
3154 bsrr->stream = assoc->encode;
3155 bsrr->print = assoc->print;
3157 bsrr->sort_status = Z_SortResponse_failure;
3159 bsrr->errstring = 0;
3161 (*assoc->init->bend_sort)(assoc->backend, bsrr);
3163 res->referenceId = bsrr->referenceId;
3164 res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
3165 res->resultSetStatus = 0;
3168 Z_DiagRecs *dr = zget_DiagRecs(assoc->encode,
3169 bsrr->errcode, bsrr->errstring);
3170 res->diagnostics = dr->diagRecs;
3171 res->num_diagnostics = dr->num_diagRecs;
3175 res->num_diagnostics = 0;
3176 res->diagnostics = 0;
3178 res->resultCount = 0;
3181 apdu->which = Z_APDU_sortResponse;
3182 apdu->u.sortResponse = res;
3185 WRBUF wr = wrbuf_alloc();
3186 wrbuf_printf(wr, "Sort ");
3188 wrbuf_printf(wr, " ERROR %d", bsrr->errcode);
3190 wrbuf_printf(wr, "OK -");
3191 wrbuf_printf(wr, " (");
3192 for (i = 0; i<req->num_inputResultSetNames; i++)
3195 wrbuf_printf(wr, "+");
3196 wrbuf_printf(wr, req->inputResultSetNames[i]);
3198 wrbuf_printf(wr, ")->%s ",req->sortedResultSetName);
3200 yaz_log(log_request, "%s", wrbuf_buf(wr) );
3206 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
3210 Z_DeleteResultSetRequest *req =
3211 reqb->apdu_request->u.deleteResultSetRequest;
3212 Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
3213 odr_malloc (assoc->encode, sizeof(*res));
3214 bend_delete_rr *bdrr = (bend_delete_rr *)
3215 odr_malloc (assoc->encode, sizeof(*bdrr));
3216 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
3218 yaz_log(log_requestdetail, "Got DeleteRequest.");
3220 bdrr->num_setnames = req->num_resultSetList;
3221 bdrr->setnames = req->resultSetList;
3222 for (i = 0; i<req->num_resultSetList; i++)
3223 yaz_log(log_requestdetail, "resultset: '%s'",
3224 req->resultSetList[i]);
3225 bdrr->stream = assoc->encode;
3226 bdrr->print = assoc->print;
3227 bdrr->function = *req->deleteFunction;
3228 bdrr->referenceId = req->referenceId;
3230 if (bdrr->num_setnames > 0)
3232 bdrr->statuses = (int*)
3233 odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
3234 bdrr->num_setnames);
3235 for (i = 0; i < bdrr->num_setnames; i++)
3236 bdrr->statuses[i] = 0;
3238 (*assoc->init->bend_delete)(assoc->backend, bdrr);
3240 res->referenceId = req->referenceId;
3242 res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
3244 res->deleteListStatuses = 0;
3245 if (bdrr->num_setnames > 0)
3248 res->deleteListStatuses = (Z_ListStatuses *)
3249 odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
3250 res->deleteListStatuses->num = bdrr->num_setnames;
3251 res->deleteListStatuses->elements =
3253 odr_malloc (assoc->encode,
3254 sizeof(*res->deleteListStatuses->elements) *
3255 bdrr->num_setnames);
3256 for (i = 0; i<bdrr->num_setnames; i++)
3258 res->deleteListStatuses->elements[i] =
3260 odr_malloc (assoc->encode,
3261 sizeof(**res->deleteListStatuses->elements));
3262 res->deleteListStatuses->elements[i]->status = bdrr->statuses+i;
3263 res->deleteListStatuses->elements[i]->id =
3264 odr_strdup (assoc->encode, bdrr->setnames[i]);
3267 res->numberNotDeleted = 0;
3268 res->bulkStatuses = 0;
3269 res->deleteMessage = 0;
3272 apdu->which = Z_APDU_deleteResultSetResponse;
3273 apdu->u.deleteResultSetResponse = res;
3276 WRBUF wr = wrbuf_alloc();
3277 wrbuf_printf(wr, "Delete ");
3278 if (bdrr->delete_status)
3279 wrbuf_printf(wr, "ERROR %d", bdrr->delete_status);
3281 wrbuf_printf(wr, "OK -");
3282 for (i = 0; i<req->num_resultSetList; i++)
3283 wrbuf_printf(wr, " %s ", req->resultSetList[i]);
3284 yaz_log(log_request, "%s", wrbuf_buf(wr) );
3290 static void process_close(association *assoc, request *reqb)
3292 Z_Close *req = reqb->apdu_request->u.close;
3293 static char *reasons[] =
3300 "securityViolation",
3307 yaz_log(log_requestdetail, "Got Close, reason %s, message %s",
3308 reasons[*req->closeReason], req->diagnosticInformation ?
3309 req->diagnosticInformation : "NULL");
3310 if (assoc->version < 3) /* to make do_force respond with close */
3312 do_close_req(assoc, Z_Close_finished,
3313 "Association terminated by client", reqb);
3314 yaz_log(log_request,"Close OK");
3317 void save_referenceId (request *reqb, Z_ReferenceId *refid)
3321 reqb->len_refid = refid->len;
3322 reqb->refid = (char *)nmem_malloc (reqb->request_mem, refid->len);
3323 memcpy (reqb->refid, refid->buf, refid->len);
3327 reqb->len_refid = 0;
3332 void bend_request_send (bend_association a, bend_request req, Z_APDU *res)
3334 process_z_response (a, req, res);
3337 bend_request bend_request_mk (bend_association a)
3339 request *nreq = request_get (&a->outgoing);
3340 nreq->request_mem = nmem_create ();
3344 Z_ReferenceId *bend_request_getid (ODR odr, bend_request req)
3349 id = (Odr_oct *)odr_malloc (odr, sizeof(*odr));
3350 id->buf = (unsigned char *)odr_malloc (odr, req->len_refid);
3351 id->len = id->size = req->len_refid;
3352 memcpy (id->buf, req->refid, req->len_refid);
3356 void bend_request_destroy (bend_request *req)
3358 nmem_destroy((*req)->request_mem);
3359 request_release(*req);
3363 int bend_backend_respond (bend_association a, bend_request req)
3367 r = process_z_request (a, req, &msg);
3369 yaz_log (YLOG_WARN, "%s", msg);
3373 void bend_request_setdata(bend_request r, void *p)
3378 void *bend_request_getdata(bend_request r)
3380 return r->clientData;
3383 static Z_APDU *process_segmentRequest (association *assoc, request *reqb)
3385 bend_segment_rr req;
3387 req.segment = reqb->apdu_request->u.segmentRequest;
3388 req.stream = assoc->encode;
3389 req.decode = assoc->decode;
3390 req.print = assoc->print;
3391 req.association = assoc;
3393 (*assoc->init->bend_segment)(assoc->backend, &req);
3398 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd)
3400 bend_esrequest_rr esrequest;
3401 const char *ext_name = "unknown";
3403 Z_ExtendedServicesRequest *req =
3404 reqb->apdu_request->u.extendedServicesRequest;
3405 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
3407 Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
3409 esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
3410 esrequest.stream = assoc->encode;
3411 esrequest.decode = assoc->decode;
3412 esrequest.print = assoc->print;
3413 esrequest.errcode = 0;
3414 esrequest.errstring = NULL;
3415 esrequest.request = reqb;
3416 esrequest.association = assoc;
3417 esrequest.taskPackage = 0;
3418 esrequest.referenceId = req->referenceId;
3421 if (esrequest.esr && esrequest.esr->taskSpecificParameters)
3423 switch(esrequest.esr->taskSpecificParameters->which)
3425 case Z_External_itemOrder:
3426 ext_name = "ItemOrder"; break;
3427 case Z_External_update:
3428 ext_name = "Update"; break;
3429 case Z_External_update0:
3430 ext_name = "Update0"; break;
3431 case Z_External_ESAdmin:
3432 ext_name = "Admin"; break;
3437 (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
3439 /* If the response is being delayed, return NULL */
3440 if (esrequest.request == NULL)
3443 resp->referenceId = req->referenceId;
3445 if (esrequest.errcode == -1)
3447 /* Backend service indicates request will be processed */
3448 yaz_log(log_request, "Extended Service: %s (accepted)", ext_name);
3449 *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
3451 else if (esrequest.errcode == 0)
3453 /* Backend service indicates request will be processed */
3454 yaz_log(log_request, "Extended Service: %s (done)", ext_name);
3455 *resp->operationStatus = Z_ExtendedServicesResponse_done;
3459 Z_DiagRecs *diagRecs =
3460 zget_DiagRecs(assoc->encode, esrequest.errcode,
3461 esrequest.errstring);
3462 /* Backend indicates error, request will not be processed */
3463 yaz_log(log_request, "Extended Service: %s (failed)", ext_name);
3464 *resp->operationStatus = Z_ExtendedServicesResponse_failure;
3465 resp->num_diagnostics = diagRecs->num_diagRecs;
3466 resp->diagnostics = diagRecs->diagRecs;
3469 WRBUF wr = wrbuf_alloc();
3470 wrbuf_diags(wr, resp->num_diagnostics, resp->diagnostics);
3471 yaz_log(log_request, "EsRequest %s", wrbuf_buf(wr) );
3476 /* Do something with the members of bend_extendedservice */
3477 if (esrequest.taskPackage)
3478 resp->taskPackage = z_ext_record (assoc->encode, VAL_EXTENDED,
3479 (const char *) esrequest.taskPackage,
3481 yaz_log(YLOG_DEBUG,"Send the result apdu");
3488 * indent-tabs-mode: nil
3490 * vim: shiftwidth=4 tabstop=8 expandtab