2 * Copyright (C) 1995-2005, Index Data ApS
3 * See the file LICENSE for details.
5 * $Id: seshigh.c,v 1.89 2006-07-06 14:16:00 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");
121 static void wr_diag(WRBUF w, int error, const char *addinfo)
123 wrbuf_printf(w, "ERROR [%d] %s%s%s",
124 error, diagbib1_str(error),
125 addinfo ? "--" : "", addinfo ? addinfo : "");
130 * Create and initialize a new association-handle.
131 * channel : iochannel for the current line.
132 * link : communications channel.
133 * Returns: 0 or a new association handle.
135 association *create_association(IOCHAN channel, COMSTACK link,
136 const char *apdufile)
142 if (!(anew = (association *)xmalloc(sizeof(*anew))))
146 anew->last_control = 0;
147 anew->client_chan = channel;
148 anew->client_link = link;
149 anew->cs_get_mask = 0;
150 anew->cs_put_mask = 0;
151 anew->cs_accept_mask = 0;
152 if (!(anew->decode = odr_createmem(ODR_DECODE)) ||
153 !(anew->encode = odr_createmem(ODR_ENCODE)))
155 if (apdufile && *apdufile)
159 if (!(anew->print = odr_createmem(ODR_PRINT)))
161 if (*apdufile == '@')
163 odr_setprint(anew->print, yaz_log_file());
165 else if (*apdufile != '-')
168 sprintf(filename, "%.200s.%ld", apdufile, (long)getpid());
169 if (!(f = fopen(filename, "w")))
171 yaz_log(YLOG_WARN|YLOG_ERRNO, "%s", filename);
174 setvbuf(f, 0, _IONBF, 0);
175 odr_setprint(anew->print, f);
180 anew->input_buffer = 0;
181 anew->input_buffer_len = 0;
183 anew->state = ASSOC_NEW;
184 request_initq(&anew->incoming);
185 request_initq(&anew->outgoing);
186 anew->proto = cs_getproto(link);
192 * Free association and release resources.
194 void destroy_association(association *h)
196 statserv_options_block *cb = statserv_getcontrol();
200 odr_destroy(h->decode);
201 odr_destroy(h->encode);
203 odr_destroy(h->print);
205 xfree(h->input_buffer);
207 (*cb->bend_close)(h->backend);
208 while ((req = request_deq(&h->incoming)))
209 request_release(req);
210 while ((req = request_deq(&h->outgoing)))
211 request_release(req);
212 request_delq(&h->incoming);
213 request_delq(&h->outgoing);
215 xmalloc_trav("session closed");
216 if (cb && cb->one_shot)
222 static void do_close_req(association *a, int reason, char *message,
226 Z_Close *cls = zget_Close(a->encode);
228 /* Purge request queue */
229 while (request_deq(&a->incoming));
230 while (request_deq(&a->outgoing));
233 yaz_log(log_requestdetail, "Sending Close PDU, reason=%d, message=%s",
234 reason, message ? message : "none");
235 apdu.which = Z_APDU_close;
237 *cls->closeReason = reason;
238 cls->diagnosticInformation = message;
239 process_z_response(a, req, &apdu);
240 iochan_settimeout(a->client_chan, 20);
244 request_release(req);
245 yaz_log(log_requestdetail, "v2 client. No Close PDU");
246 iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
249 a->state = ASSOC_DEAD;
252 static void do_close(association *a, int reason, char *message)
254 request *req = request_get(&a->outgoing);
255 do_close_req (a, reason, message, req);
259 * This is where PDUs from the client are read and the further
260 * processing is initiated. Flow of control moves down through the
261 * various process_* functions below, until the encoded result comes back up
262 * to the output handler in here.
264 * h : the I/O channel that has an outstanding event.
265 * event : the current outstanding event.
267 void ir_session(IOCHAN h, int event)
270 association *assoc = (association *)iochan_getdata(h);
271 COMSTACK conn = assoc->client_link;
274 assert(h && conn && assoc);
275 if (event == EVENT_TIMEOUT)
277 if (assoc->state != ASSOC_UP)
279 yaz_log(YLOG_DEBUG, "Final timeout - closing connection.");
280 /* do we need to lod this at all */
282 destroy_association(assoc);
287 yaz_log(log_session, "Session idle too long. Sending close.");
288 do_close(assoc, Z_Close_lackOfActivity, 0);
292 if (event & assoc->cs_accept_mask)
294 if (!cs_accept (conn))
296 yaz_log (YLOG_WARN, "accept failed");
297 destroy_association(assoc);
300 iochan_clearflag (h, EVENT_OUTPUT);
301 if (conn->io_pending)
302 { /* cs_accept didn't complete */
303 assoc->cs_accept_mask =
304 ((conn->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
305 ((conn->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
307 iochan_setflag (h, assoc->cs_accept_mask);
310 { /* cs_accept completed. Prepare for reading (cs_get) */
311 assoc->cs_accept_mask = 0;
312 assoc->cs_get_mask = EVENT_INPUT;
313 iochan_setflag (h, assoc->cs_get_mask);
317 if ((event & assoc->cs_get_mask) || (event & EVENT_WORK)) /* input */
319 if ((assoc->cs_put_mask & EVENT_INPUT) == 0 && (event & assoc->cs_get_mask))
321 yaz_log(YLOG_DEBUG, "ir_session (input)");
322 /* We aren't speaking to this fellow */
323 if (assoc->state == ASSOC_DEAD)
325 yaz_log(log_session, "Connection closed - end of session");
327 destroy_association(assoc);
331 assoc->cs_get_mask = EVENT_INPUT;
332 if ((res = cs_get(conn, &assoc->input_buffer,
333 &assoc->input_buffer_len)) <= 0)
335 yaz_log(log_session, "Connection closed by client");
337 destroy_association(assoc);
341 else if (res == 1) /* incomplete read - wait for more */
343 if (conn->io_pending & CS_WANT_WRITE)
344 assoc->cs_get_mask |= EVENT_OUTPUT;
345 iochan_setflag(h, assoc->cs_get_mask);
348 if (cs_more(conn)) /* more stuff - call us again later, please */
349 iochan_setevent(h, EVENT_INPUT);
351 /* we got a complete PDU. Let's decode it */
352 yaz_log(YLOG_DEBUG, "Got PDU, %d bytes: lead=%02X %02X %02X", res,
353 assoc->input_buffer[0] & 0xff,
354 assoc->input_buffer[1] & 0xff,
355 assoc->input_buffer[2] & 0xff);
356 req = request_get(&assoc->incoming); /* get a new request */
357 odr_reset(assoc->decode);
358 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
359 if (!z_GDU(assoc->decode, &req->gdu_request, 0, 0))
361 yaz_log(YLOG_WARN, "ODR error on incoming PDU: %s [element %s] "
363 odr_errmsg(odr_geterror(assoc->decode)),
364 odr_getelement(assoc->decode),
365 (long) odr_offset(assoc->decode));
366 if (assoc->decode->error != OHTTP)
368 yaz_log(YLOG_WARN, "PDU dump:");
369 odr_dumpBER(yaz_log_file(), assoc->input_buffer, res);
370 request_release(req);
371 do_close(assoc, Z_Close_protocolError,"Malformed package");
375 Z_GDU *p = z_get_HTTP_Response(assoc->encode, 400);
376 assoc->state = ASSOC_DEAD;
377 process_gdu_response(assoc, req, p);
381 req->request_mem = odr_extract_mem(assoc->decode);
384 if (!z_GDU(assoc->print, &req->gdu_request, 0, 0))
385 yaz_log(YLOG_WARN, "ODR print error: %s",
386 odr_errmsg(odr_geterror(assoc->print)));
387 odr_reset(assoc->print);
389 request_enq(&assoc->incoming, req);
392 /* can we do something yet? */
393 req = request_head(&assoc->incoming);
394 if (req->state == REQUEST_IDLE)
396 request_deq(&assoc->incoming);
397 process_gdu_request(assoc, req);
400 if (event & assoc->cs_put_mask)
402 request *req = request_head(&assoc->outgoing);
404 assoc->cs_put_mask = 0;
405 yaz_log(YLOG_DEBUG, "ir_session (output)");
406 req->state = REQUEST_PENDING;
407 switch (res = cs_put(conn, req->response, req->len_response))
410 yaz_log(log_session, "Connection closed by client");
412 destroy_association(assoc);
415 case 0: /* all sent - release the request structure */
416 yaz_log(YLOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
418 yaz_log(YLOG_DEBUG, "HTTP out:\n%.*s", req->len_response,
421 nmem_destroy(req->request_mem);
422 request_deq(&assoc->outgoing);
423 request_release(req);
424 if (!request_head(&assoc->outgoing))
425 { /* restore mask for cs_get operation ... */
426 iochan_clearflag(h, EVENT_OUTPUT|EVENT_INPUT);
427 iochan_setflag(h, assoc->cs_get_mask);
428 if (assoc->state == ASSOC_DEAD)
429 iochan_setevent(assoc->client_chan, EVENT_TIMEOUT);
433 assoc->cs_put_mask = EVENT_OUTPUT;
437 if (conn->io_pending & CS_WANT_WRITE)
438 assoc->cs_put_mask |= EVENT_OUTPUT;
439 if (conn->io_pending & CS_WANT_READ)
440 assoc->cs_put_mask |= EVENT_INPUT;
441 iochan_setflag(h, assoc->cs_put_mask);
444 if (event & EVENT_EXCEPT)
446 yaz_log(YLOG_WARN, "ir_session (exception)");
448 destroy_association(assoc);
453 static int process_z_request(association *assoc, request *req, char **msg);
456 static void assoc_init_reset(association *assoc)
459 assoc->init = (bend_initrequest *) xmalloc (sizeof(*assoc->init));
461 assoc->init->stream = assoc->encode;
462 assoc->init->print = assoc->print;
463 assoc->init->auth = 0;
464 assoc->init->referenceId = 0;
465 assoc->init->implementation_version = 0;
466 assoc->init->implementation_id = 0;
467 assoc->init->implementation_name = 0;
468 assoc->init->bend_sort = NULL;
469 assoc->init->bend_search = NULL;
470 assoc->init->bend_present = NULL;
471 assoc->init->bend_esrequest = NULL;
472 assoc->init->bend_delete = NULL;
473 assoc->init->bend_scan = NULL;
474 assoc->init->bend_segment = NULL;
475 assoc->init->bend_fetch = NULL;
476 assoc->init->bend_explain = NULL;
477 assoc->init->bend_srw_scan = NULL;
478 assoc->init->bend_srw_update = NULL;
480 assoc->init->charneg_request = NULL;
481 assoc->init->charneg_response = NULL;
483 assoc->init->decode = assoc->decode;
484 assoc->init->peer_name =
485 odr_strdup (assoc->encode, cs_addrstr(assoc->client_link));
487 yaz_log(log_requestdetail, "peer %s", assoc->init->peer_name);
490 static int srw_bend_init(association *assoc, Z_SRW_diagnostic **d, int *num, Z_SRW_PDU *sr)
492 statserv_options_block *cb = statserv_getcontrol();
495 const char *encoding = "UTF-8";
497 bend_initresult *binitres;
499 yaz_log(YLOG_LOG, "srw_bend_init config=%s", cb->configname);
500 assoc_init_reset(assoc);
502 assoc->maximumRecordSize = 3000000;
503 assoc->preferredMessageSize = 3000000;
507 Z_IdAuthentication *auth = odr_malloc(assoc->decode, sizeof(*auth));
510 len = strlen(sr->username) + 1;
512 len += strlen(sr->password) + 2;
513 auth->which = Z_IdAuthentication_open;
514 auth->u.open = odr_malloc(assoc->decode, len);
515 strcpy(auth->u.open, sr->username);
516 if (sr->password && *sr->password)
518 strcat(auth->u.open, "/");
519 strcat(auth->u.open, sr->password);
521 assoc->init->auth = auth;
525 ce = yaz_set_proposal_charneg(assoc->decode, &encoding, 1, 0, 0, 1);
526 assoc->init->charneg_request = ce->u.charNeg3;
529 if (!(binitres = (*cb->bend_init)(assoc->init)))
531 assoc->state = ASSOC_DEAD;
532 yaz_add_srw_diagnostic(assoc->encode, d, num,
533 YAZ_SRW_AUTHENTICATION_ERROR, 0);
536 assoc->backend = binitres->handle;
537 assoc->init->auth = 0;
538 if (binitres->errcode)
540 int srw_code = yaz_diag_bib1_to_srw(binitres->errcode);
541 assoc->state = ASSOC_DEAD;
542 yaz_add_srw_diagnostic(assoc->encode, d, num, srw_code,
543 binitres->errstring);
551 static const char *get_esn(Z_RecordComposition *comp)
553 if (comp && comp->which == Z_RecordComp_complex)
555 if (comp->u.complex->generic
556 && comp->u.complex->generic->elementSpec
557 && (comp->u.complex->generic->elementSpec->which ==
558 Z_ElementSpec_elementSetName))
559 return comp->u.complex->generic->elementSpec->u.elementSetName;
561 else if (comp && comp->which == Z_RecordComp_simple &&
562 comp->u.simple->which == Z_ElementSetNames_generic)
563 return comp->u.simple->u.generic;
567 static void set_esn(Z_RecordComposition **comp_p, const char *esn, NMEM nmem)
569 Z_RecordComposition *comp = nmem_malloc(nmem, sizeof(*comp));
571 comp->which = Z_RecordComp_simple;
572 comp->u.simple = nmem_malloc(nmem, sizeof(*comp->u.simple));
573 comp->u.simple->which = Z_ElementSetNames_generic;
574 comp->u.simple->u.generic = nmem_strdup(nmem, esn);
578 static int retrieve_fetch(association *assoc, bend_fetch_rr *rr)
581 yaz_record_conv_t rc = 0;
582 const char *match_schema = 0;
583 int *match_syntax = 0;
588 const char *input_schema = get_esn(rr->comp);
589 Odr_oid *input_syntax_raw = rr->request_format_raw;
591 const char *backend_schema = 0;
592 Odr_oid *backend_syntax = 0;
594 r = yaz_retrieval_request(assoc->server->retrieval,
602 if (r == -1) /* error ? */
604 const char *details = yaz_retrieval_get_error(
605 assoc->server->retrieval);
607 rr->errcode = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
609 rr->errstring = odr_strdup(rr->stream, details);
612 else if (r == 1 || r == 3)
614 const char *details = input_schema;
615 rr->errcode = YAZ_BIB1_ELEMENT_SET_NAMES_UNSUPP;
617 rr->errstring = odr_strdup(rr->stream, details);
622 rr->errcode = YAZ_BIB1_RECORD_SYNTAX_UNSUPP;
623 if (input_syntax_raw)
625 char oidbuf[OID_STR_MAX];
626 oid_to_dotstring(input_syntax_raw, oidbuf);
627 rr->errstring = odr_strdup(rr->stream, oidbuf);
633 set_esn(&rr->comp, backend_schema, rr->stream->mem);
637 oident *oident_syntax = oid_getentbyoid(backend_syntax);
639 rr->request_format_raw = backend_syntax;
642 rr->request_format = oident_syntax->value;
644 rr->request_format = VAL_NONE;
647 (*assoc->init->bend_fetch)(assoc->backend, rr);
648 if (rc && rr->record && rr->errcode == 0 && rr->len > 0)
649 { /* post conversion must take place .. */
650 WRBUF output_record = wrbuf_alloc();
651 int r = yaz_record_conv_record(rc, rr->record, rr->len, output_record);
654 const char *details = yaz_record_conv_get_error(rc);
655 rr->errcode = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
657 rr->errstring = odr_strdup(rr->stream, details);
661 rr->len = wrbuf_len(output_record);
662 rr->record = odr_malloc(rr->stream, rr->len);
663 memcpy(rr->record, wrbuf_buf(output_record), rr->len);
665 wrbuf_free(output_record, 1);
669 struct oident *oi = oid_getentbyoid(match_syntax);
670 rr->output_format = oi ? oi->value : VAL_NONE;
671 rr->output_format_raw = match_syntax;
674 rr->schema = odr_strdup(rr->stream, match_schema);
677 (*assoc->init->bend_fetch)(assoc->backend, rr);
681 static int srw_bend_fetch(association *assoc, int pos,
682 Z_SRW_searchRetrieveRequest *srw_req,
683 Z_SRW_record *record)
686 ODR o = assoc->encode;
688 rr.setname = "default";
691 rr.request_format = VAL_TEXT_XML;
692 rr.request_format_raw = yaz_oidval_to_z3950oid(assoc->decode,
695 rr.comp = (Z_RecordComposition *)
696 odr_malloc(assoc->decode, sizeof(*rr.comp));
697 rr.comp->which = Z_RecordComp_complex;
698 rr.comp->u.complex = (Z_CompSpec *)
699 odr_malloc(assoc->decode, sizeof(Z_CompSpec));
700 rr.comp->u.complex->selectAlternativeSyntax = (bool_t *)
701 odr_malloc(assoc->encode, sizeof(bool_t));
702 *rr.comp->u.complex->selectAlternativeSyntax = 0;
703 rr.comp->u.complex->num_dbSpecific = 0;
704 rr.comp->u.complex->dbSpecific = 0;
705 rr.comp->u.complex->num_recordSyntax = 0;
706 rr.comp->u.complex->recordSyntax = 0;
708 rr.comp->u.complex->generic = (Z_Specification *)
709 odr_malloc(assoc->decode, sizeof(Z_Specification));
711 /* schema uri = recordSchema (or NULL if recordSchema is not given) */
712 rr.comp->u.complex->generic->which = Z_Schema_uri;
713 rr.comp->u.complex->generic->schema.uri = srw_req->recordSchema;
715 /* ESN = recordSchema if recordSchema is present */
716 rr.comp->u.complex->generic->elementSpec = 0;
717 if (srw_req->recordSchema)
719 rr.comp->u.complex->generic->elementSpec =
720 (Z_ElementSpec *) odr_malloc(assoc->encode, sizeof(Z_ElementSpec));
721 rr.comp->u.complex->generic->elementSpec->which =
722 Z_ElementSpec_elementSetName;
723 rr.comp->u.complex->generic->elementSpec->u.elementSetName =
724 srw_req->recordSchema;
727 rr.stream = assoc->encode;
728 rr.print = assoc->print;
736 rr.surrogate_flag = 0;
737 rr.schema = srw_req->recordSchema;
739 if (!assoc->init->bend_fetch)
742 retrieve_fetch(assoc, &rr);
744 if (rr.errcode && rr.surrogate_flag)
746 int code = yaz_diag_bib1_to_srw(rr.errcode);
747 const char *message = yaz_diag_srw_str(code);
750 len += strlen(message);
752 len += strlen(rr.errstring);
754 record->recordData_buf = odr_malloc(o, len);
756 sprintf(record->recordData_buf, "<diagnostic "
757 "xmlns=\"http://www.loc.gov/zing/srw/diagnostic/\">\n"
758 " <uri>info:srw/diagnostic/1/%d</uri>\n", code);
760 sprintf(record->recordData_buf + strlen(record->recordData_buf),
761 " <details>%s</details>\n", rr.errstring);
763 sprintf(record->recordData_buf + strlen(record->recordData_buf),
764 " <message>%s</message>\n", message);
765 sprintf(record->recordData_buf + strlen(record->recordData_buf),
767 record->recordData_len = strlen(record->recordData_buf);
768 record->recordPosition = odr_intdup(o, pos);
769 record->recordSchema = "info:srw/schema/1/diagnostics-v1.1";
772 else if (rr.len >= 0)
774 record->recordData_buf = rr.record;
775 record->recordData_len = rr.len;
776 record->recordPosition = odr_intdup(o, pos);
778 record->recordSchema = odr_strdup(o, rr.schema);
780 record->recordSchema = 0;
785 static int cql2pqf(ODR odr, const char *cql, cql_transform_t ct,
786 Z_Query *query_result)
788 /* have a CQL query and CQL to PQF transform .. */
789 CQL_parser cp = cql_parser_create();
795 r = cql_parser_string(cp, cql);
798 /* CQL syntax error */
804 r = cql_transform_buf(ct,
805 cql_parser_result(cp),
806 rpn_buf, sizeof(rpn_buf)-1);
808 srw_errcode = cql_transform_error(ct, &add);
812 /* Syntax & transform OK. */
813 /* Convert PQF string to Z39.50 to RPN query struct */
814 YAZ_PQF_Parser pp = yaz_pqf_create();
815 Z_RPNQuery *rpnquery = yaz_pqf_parse(pp, odr, rpn_buf);
820 int code = yaz_pqf_error(pp, &pqf_msg, &off);
821 yaz_log(YLOG_WARN, "PQF Parser Error %s (code %d)",
827 query_result->which = Z_Query_type_1;
828 query_result->u.type_1 = rpnquery;
832 cql_parser_destroy(cp);
836 static int cql2pqf_scan(ODR odr, const char *cql, cql_transform_t ct,
837 Z_AttributesPlusTerm *result)
841 int srw_error = cql2pqf(odr, cql, ct, &query);
844 if (query.which != Z_Query_type_1 && query.which != Z_Query_type_101)
845 return 10; /* bad query type */
846 rpn = query.u.type_1;
847 if (!rpn->RPNStructure)
848 return 10; /* must be structure */
849 if (rpn->RPNStructure->which != Z_RPNStructure_simple)
850 return 10; /* must be simple */
851 if (rpn->RPNStructure->u.simple->which != Z_Operand_APT)
852 return 10; /* must be attributes plus term node .. */
853 memcpy(result, rpn->RPNStructure->u.simple->u.attributesPlusTerm,
858 static void srw_bend_search(association *assoc, request *req,
860 Z_SRW_searchRetrieveResponse *srw_res,
865 Z_SRW_searchRetrieveRequest *srw_req = sr->u.request;
868 yaz_log(log_requestdetail, "Got SRW SearchRetrieveRequest");
869 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
870 if (srw_res->num_diagnostics == 0 && assoc->init)
873 rr.setname = "default";
876 rr.basenames = &srw_req->database;
880 rr.srw_setnameIdleTime = 0;
881 rr.query = (Z_Query *) odr_malloc (assoc->decode, sizeof(*rr.query));
882 rr.query->u.type_1 = 0;
884 if (srw_req->query_type == Z_SRW_query_type_cql)
886 if (assoc->server && assoc->server->cql_transform)
888 int srw_errcode = cql2pqf(assoc->encode, srw_req->query.cql,
889 assoc->server->cql_transform,
893 yaz_add_srw_diagnostic(assoc->encode,
894 &srw_res->diagnostics,
895 &srw_res->num_diagnostics,
901 /* CQL query to backend. Wrap it - Z39.50 style */
902 ext = (Z_External *) odr_malloc(assoc->decode, sizeof(*ext));
903 ext->direct_reference = odr_getoidbystr(assoc->decode,
904 "1.2.840.10003.16.2");
905 ext->indirect_reference = 0;
907 ext->which = Z_External_CQL;
908 ext->u.cql = srw_req->query.cql;
910 rr.query->which = Z_Query_type_104;
911 rr.query->u.type_104 = ext;
914 else if (srw_req->query_type == Z_SRW_query_type_pqf)
916 Z_RPNQuery *RPNquery;
917 YAZ_PQF_Parser pqf_parser;
919 pqf_parser = yaz_pqf_create ();
921 RPNquery = yaz_pqf_parse (pqf_parser, assoc->decode,
927 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
928 yaz_log(log_requestdetail, "Parse error %d %s near offset %ld",
929 code, pqf_msg, (long) off);
930 srw_error = YAZ_SRW_QUERY_SYNTAX_ERROR;
933 rr.query->which = Z_Query_type_1;
934 rr.query->u.type_1 = RPNquery;
936 yaz_pqf_destroy (pqf_parser);
940 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
941 &srw_res->num_diagnostics,
942 YAZ_SRW_UNSUPP_QUERY_TYPE, 0);
944 if (rr.query->u.type_1)
946 rr.stream = assoc->encode;
947 rr.decode = assoc->decode;
948 rr.print = assoc->print;
950 if ( srw_req->sort.sortKeys )
951 rr.srw_sortKeys = odr_strdup(assoc->encode,
952 srw_req->sort.sortKeys );
953 rr.association = assoc;
959 yaz_log_zquery_level(log_requestdetail,rr.query);
961 (assoc->init->bend_search)(assoc->backend, &rr);
964 if (rr.errcode == YAZ_BIB1_DATABASE_UNAVAILABLE)
970 srw_error = yaz_diag_bib1_to_srw (rr.errcode);
971 yaz_add_srw_diagnostic(assoc->encode,
972 &srw_res->diagnostics,
973 &srw_res->num_diagnostics,
974 srw_error, rr.errstring);
979 int number = srw_req->maximumRecords ? *srw_req->maximumRecords : 0;
980 int start = srw_req->startRecord ? *srw_req->startRecord : 1;
982 yaz_log(log_requestdetail, "Request to pack %d+%d out of %d",
983 start, number, rr.hits);
985 srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
988 srw_res->resultSetId =
989 odr_strdup(assoc->encode, rr.srw_setname );
990 srw_res->resultSetIdleTime =
991 odr_intdup(assoc->encode, *rr.srw_setnameIdleTime );
999 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1000 &srw_res->num_diagnostics,
1001 YAZ_SRW_FIRST_RECORD_POSITION_OUT_OF_RANGE, 0);
1006 if (start + number > rr.hits)
1007 number = rr.hits - start + 1;
1009 /* Call bend_present if defined */
1010 if (assoc->init->bend_present)
1012 bend_present_rr *bprr = (bend_present_rr*)
1013 odr_malloc (assoc->decode, sizeof(*bprr));
1014 bprr->setname = "default";
1015 bprr->start = start;
1016 bprr->number = number;
1017 bprr->format = VAL_TEXT_XML;
1018 if (srw_req->recordSchema)
1020 bprr->comp = (Z_RecordComposition *) odr_malloc(assoc->decode,
1021 sizeof(*bprr->comp));
1022 bprr->comp->which = Z_RecordComp_simple;
1023 bprr->comp->u.simple = (Z_ElementSetNames *)
1024 odr_malloc(assoc->decode, sizeof(Z_ElementSetNames));
1025 bprr->comp->u.simple->which = Z_ElementSetNames_generic;
1026 bprr->comp->u.simple->u.generic = srw_req->recordSchema;
1032 bprr->stream = assoc->encode;
1033 bprr->referenceId = 0;
1034 bprr->print = assoc->print;
1035 bprr->request = req;
1036 bprr->association = assoc;
1038 bprr->errstring = NULL;
1039 (*assoc->init->bend_present)(assoc->backend, bprr);
1045 srw_error = yaz_diag_bib1_to_srw (bprr->errcode);
1046 yaz_add_srw_diagnostic(assoc->encode,
1047 &srw_res->diagnostics,
1048 &srw_res->num_diagnostics,
1049 srw_error, bprr->errstring);
1057 int packing = Z_SRW_recordPacking_string;
1058 if (srw_req->recordPacking){
1059 if (!strcmp(srw_req->recordPacking, "xml"))
1060 packing = Z_SRW_recordPacking_XML;
1061 if (!strcmp(srw_req->recordPacking, "url"))
1062 packing = Z_SRW_recordPacking_URL;
1064 srw_res->records = (Z_SRW_record *)
1065 odr_malloc(assoc->encode,
1066 number * sizeof(*srw_res->records));
1068 srw_res->extra_records = (Z_SRW_extra_record **)
1069 odr_malloc(assoc->encode,
1070 number*sizeof(*srw_res->extra_records));
1072 for (i = 0; i<number; i++)
1076 srw_res->records[j].recordPacking = packing;
1077 srw_res->records[j].recordData_buf = 0;
1078 srw_res->extra_records[j] = 0;
1079 yaz_log(YLOG_DEBUG, "srw_bend_fetch %d", i+start);
1080 errcode = srw_bend_fetch(assoc, i+start, srw_req,
1081 srw_res->records + j);
1084 yaz_add_srw_diagnostic(assoc->encode,
1085 &srw_res->diagnostics,
1086 &srw_res->num_diagnostics,
1087 yaz_diag_bib1_to_srw (errcode),
1092 if (srw_res->records[j].recordData_buf)
1095 srw_res->num_records = j;
1097 srw_res->records = 0;
1106 const char *querystr = "?";
1107 const char *querytype = "?";
1108 WRBUF wr = wrbuf_alloc();
1110 switch (srw_req->query_type)
1112 case Z_SRW_query_type_cql:
1114 querystr = srw_req->query.cql;
1116 case Z_SRW_query_type_pqf:
1118 querystr = srw_req->query.pqf;
1121 wrbuf_printf(wr, "SRWSearch ");
1122 wrbuf_printf(wr, srw_req->database);
1123 wrbuf_printf(wr, " ");
1124 if (srw_res->num_diagnostics)
1125 wrbuf_printf(wr, "ERROR %s", srw_res->diagnostics[0].uri);
1126 else if (*http_code != 200)
1127 wrbuf_printf(wr, "ERROR info:http/%d", *http_code);
1128 else if (srw_res->numberOfRecords)
1130 wrbuf_printf(wr, "OK %d",
1131 (srw_res->numberOfRecords ?
1132 *srw_res->numberOfRecords : 0));
1134 wrbuf_printf(wr, " %s %d+%d",
1135 (srw_res->resultSetId ?
1136 srw_res->resultSetId : "-"),
1137 (srw_req->startRecord ? *srw_req->startRecord : 1),
1138 srw_res->num_records);
1139 yaz_log(log_request, "%s %s: %s", wrbuf_buf(wr), querytype, querystr);
1144 static char *srw_bend_explain_default(void *handle, bend_explain_rr *rr)
1147 xmlNodePtr ptr = rr->server_node_ptr;
1150 for (ptr = ptr->children; ptr; ptr = ptr->next)
1152 if (ptr->type != XML_ELEMENT_NODE)
1154 if (!strcmp((const char *) ptr->name, "explain"))
1157 xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
1161 ptr = xmlCopyNode(ptr, 1);
1163 xmlDocSetRootElement(doc, ptr);
1165 xmlDocDumpMemory(doc, &buf_out, &len);
1166 content = (char*) odr_malloc(rr->stream, 1+len);
1167 memcpy(content, buf_out, len);
1168 content[len] = '\0';
1172 rr->explain_buf = content;
1180 static void srw_bend_explain(association *assoc, request *req,
1182 Z_SRW_explainResponse *srw_res,
1185 Z_SRW_explainRequest *srw_req = sr->u.explain_request;
1186 yaz_log(log_requestdetail, "Got SRW ExplainRequest");
1188 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1193 rr.stream = assoc->encode;
1194 rr.decode = assoc->decode;
1195 rr.print = assoc->print;
1197 rr.database = srw_req->database;
1199 rr.server_node_ptr = assoc->server->server_node_ptr;
1201 rr.server_node_ptr = 0;
1202 rr.schema = "http://explain.z3950.org/dtd/2.0/";
1203 if (assoc->init->bend_explain)
1204 (*assoc->init->bend_explain)(assoc->backend, &rr);
1206 srw_bend_explain_default(assoc->backend, &rr);
1210 int packing = Z_SRW_recordPacking_string;
1211 if (srw_req->recordPacking)
1213 if (!strcmp(srw_req->recordPacking, "xml"))
1214 packing = Z_SRW_recordPacking_XML;
1215 else if (!strcmp(srw_req->recordPacking, "url"))
1216 packing = Z_SRW_recordPacking_URL;
1218 srw_res->record.recordSchema = rr.schema;
1219 srw_res->record.recordPacking = packing;
1220 srw_res->record.recordData_buf = rr.explain_buf;
1221 srw_res->record.recordData_len = strlen(rr.explain_buf);
1222 srw_res->record.recordPosition = 0;
1228 static void srw_bend_scan(association *assoc, request *req,
1230 Z_SRW_scanResponse *srw_res,
1233 Z_SRW_scanRequest *srw_req = sr->u.scan_request;
1234 yaz_log(log_requestdetail, "Got SRW ScanRequest");
1237 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1238 if (srw_res->num_diagnostics == 0 && assoc->init)
1240 struct scan_entry *save_entries;
1242 bend_scan_rr *bsrr = (bend_scan_rr *)
1243 odr_malloc (assoc->encode, sizeof(*bsrr));
1244 bsrr->num_bases = 1;
1245 bsrr->basenames = &srw_req->database;
1247 bsrr->num_entries = srw_req->maximumTerms ?
1248 *srw_req->maximumTerms : 10;
1249 bsrr->term_position = srw_req->responsePosition ?
1250 *srw_req->responsePosition : 1;
1253 bsrr->errstring = 0;
1254 bsrr->referenceId = 0;
1255 bsrr->stream = assoc->encode;
1256 bsrr->print = assoc->print;
1257 bsrr->step_size = odr_intdup(assoc->decode, 0);
1260 if (bsrr->num_entries > 0)
1263 bsrr->entries = odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
1265 for (i = 0; i<bsrr->num_entries; i++)
1267 bsrr->entries[i].term = 0;
1268 bsrr->entries[i].occurrences = 0;
1269 bsrr->entries[i].errcode = 0;
1270 bsrr->entries[i].errstring = 0;
1271 bsrr->entries[i].display_term = 0;
1274 save_entries = bsrr->entries; /* save it so we can compare later */
1276 if (srw_req->query_type == Z_SRW_query_type_pqf &&
1277 assoc->init->bend_scan)
1279 Odr_oid *scan_attributeSet = 0;
1281 YAZ_PQF_Parser pqf_parser = yaz_pqf_create();
1283 bsrr->term = yaz_pqf_scan(pqf_parser, assoc->decode,
1285 srw_req->scanClause.pqf);
1286 if (scan_attributeSet &&
1287 (attset = oid_getentbyoid(scan_attributeSet)) &&
1288 (attset->oclass == CLASS_ATTSET ||
1289 attset->oclass == CLASS_GENERAL))
1290 bsrr->attributeset = attset->value;
1292 bsrr->attributeset = VAL_NONE;
1293 yaz_pqf_destroy(pqf_parser);
1294 bsrr->scanClause = 0;
1295 ((int (*)(void *, bend_scan_rr *))
1296 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1298 else if (srw_req->query_type == Z_SRW_query_type_cql
1299 && assoc->init->bend_scan && assoc->server
1300 && assoc->server->cql_transform)
1303 bsrr->scanClause = 0;
1304 bsrr->attributeset = VAL_NONE;
1305 bsrr->term = odr_malloc(assoc->decode, sizeof(*bsrr->term));
1306 srw_error = cql2pqf_scan(assoc->encode,
1307 srw_req->scanClause.cql,
1308 assoc->server->cql_transform,
1311 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1312 &srw_res->num_diagnostics,
1316 ((int (*)(void *, bend_scan_rr *))
1317 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1320 else if (srw_req->query_type == Z_SRW_query_type_cql
1321 && assoc->init->bend_srw_scan)
1324 bsrr->attributeset = VAL_NONE;
1325 bsrr->scanClause = srw_req->scanClause.cql;
1326 ((int (*)(void *, bend_scan_rr *))
1327 (*assoc->init->bend_srw_scan))(assoc->backend, bsrr);
1331 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1332 &srw_res->num_diagnostics,
1333 YAZ_SRW_UNSUPP_OPERATION, "scan");
1338 if (bsrr->errcode == YAZ_BIB1_DATABASE_UNAVAILABLE)
1343 srw_error = yaz_diag_bib1_to_srw (bsrr->errcode);
1345 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1346 &srw_res->num_diagnostics,
1347 srw_error, bsrr->errstring);
1349 else if (srw_res->num_diagnostics == 0 && bsrr->num_entries)
1352 srw_res->terms = (Z_SRW_scanTerm*)
1353 odr_malloc(assoc->encode, sizeof(*srw_res->terms) *
1356 srw_res->num_terms = bsrr->num_entries;
1357 for (i = 0; i<bsrr->num_entries; i++)
1359 Z_SRW_scanTerm *t = srw_res->terms + i;
1360 t->value = odr_strdup(assoc->encode, bsrr->entries[i].term);
1361 t->numberOfRecords =
1362 odr_intdup(assoc->encode, bsrr->entries[i].occurrences);
1364 if (save_entries == bsrr->entries &&
1365 bsrr->entries[i].display_term)
1367 /* the entries was _not_ set by the handler. So it's
1368 safe to test for new member display_term. It is
1371 t->displayTerm = odr_strdup(assoc->encode,
1372 bsrr->entries[i].display_term);
1380 WRBUF wr = wrbuf_alloc();
1381 const char *querytype = 0;
1382 const char *querystr = 0;
1384 switch(srw_req->query_type)
1386 case Z_SRW_query_type_pqf:
1388 querystr = srw_req->scanClause.pqf;
1390 case Z_SRW_query_type_cql:
1392 querystr = srw_req->scanClause.cql;
1395 querytype = "Unknown";
1398 wrbuf_printf(wr, "SRWScan %d+%d",
1399 (srw_req->responsePosition ?
1400 *srw_req->responsePosition : 1),
1401 (srw_req->maximumTerms ?
1402 *srw_req->maximumTerms : 1));
1403 if (srw_res->num_diagnostics)
1404 wrbuf_printf(wr, " ERROR %s", srw_res->diagnostics[0].uri);
1406 wrbuf_printf(wr, " OK -");
1407 wrbuf_printf(wr, " %s: %s", querytype, querystr);
1408 yaz_log(log_request, "%s", wrbuf_buf(wr) );
1414 static void srw_bend_update(association *assoc, request *req,
1416 Z_SRW_updateResponse *srw_res,
1419 Z_SRW_updateRequest *srw_req = sr->u.update_request;
1420 yaz_log(YLOG_DEBUG, "Got SRW UpdateRequest");
1421 yaz_log(YLOG_DEBUG, "num_diag = %d", srw_res->num_diagnostics );
1423 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1428 rr.stream = assoc->encode;
1429 rr.print = assoc->print;
1431 rr.basenames = &srw_req->database;
1432 rr.operation = srw_req->operation;
1433 rr.operation_status = "failed";
1435 rr.record_version = 0;
1436 rr.record_checksum = 0;
1437 rr.record_old_version = 0;
1438 rr.record_packing = "xml";
1439 rr.record_schema = 0;
1441 rr.request_extra_record = 0;
1442 rr.response_extra_record = 0;
1443 rr.extra_request_data = 0;
1444 rr.extra_response_data = 0;
1449 yaz_log(YLOG_DEBUG, "basename = %s", rr.basenames[0] );
1450 yaz_log(YLOG_DEBUG, "Operation = %s", rr.operation );
1451 if ( !strcmp( rr.operation, "delete" ) ){
1452 if ( !srw_req->recordId ){
1453 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1454 &srw_res->num_diagnostics,
1458 rr.record_id = srw_req->recordId;
1460 if ( !srw_req->recordVersion ){
1461 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1462 &srw_res->num_diagnostics,
1463 7, "recordVersion" );
1466 rr.record_version = odr_strdup( assoc->encode,
1467 srw_req->recordVersion );
1470 if ( srw_req->recordOldVersion ){
1471 rr.record_old_version = odr_strdup(assoc->encode,
1472 srw_req->recordOldVersion );
1474 if ( srw_req->extraRequestData ){
1475 rr.extra_request_data = odr_strdup(assoc->encode,
1476 srw_req->extraRequestData );
1479 else if ( !strcmp( rr.operation, "replace" ) ){
1480 if ( !srw_req->recordId ){
1481 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1482 &srw_res->num_diagnostics,
1486 rr.record_id = srw_req->recordId;
1488 if ( srw_req->record.recordSchema == 0 ){
1489 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1490 &srw_res->num_diagnostics,
1491 7, "recordSchema" );
1494 rr.record_schema = odr_strdup(assoc->encode,
1495 srw_req->record.recordSchema );
1497 switch (srw_req->record.recordPacking)
1499 case Z_SRW_recordPacking_string:
1500 rr.record_packing = "string";
1502 case Z_SRW_recordPacking_XML:
1503 rr.record_packing = "xml";
1505 case Z_SRW_recordPacking_URL:
1506 rr.record_packing = "url";
1509 if ( srw_req->record.recordData_len ){
1510 rr.record_data = odr_strdupn(assoc->encode,
1511 srw_req->record.recordData_buf,
1512 srw_req->record.recordData_len );
1513 rr.request_extra_record = srw_req->extra_record;
1516 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1517 &srw_res->num_diagnostics,
1520 if (srw_req->extraRequestData)
1521 rr.extra_request_data = odr_strdup(assoc->encode,
1522 srw_req->extraRequestData );
1524 else if ( !strcmp( rr.operation, "insert" ) )
1526 rr.record_id = srw_req->recordId;
1527 if ( srw_req->record.recordSchema == 0 ){
1528 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1529 &srw_res->num_diagnostics,
1530 7, "recordSchema" );
1533 rr.record_schema = odr_strdup(assoc->encode,
1534 srw_req->record.recordSchema);
1536 switch (srw_req->record.recordPacking)
1538 case Z_SRW_recordPacking_string:
1539 rr.record_packing = "string";
1541 case Z_SRW_recordPacking_XML:
1542 rr.record_packing = "xml";
1544 case Z_SRW_recordPacking_URL:
1545 rr.record_packing = "url";
1549 if (srw_req->record.recordData_len)
1551 rr.record_data = odr_strdupn(assoc->encode,
1552 srw_req->record.recordData_buf,
1553 srw_req->record.recordData_len );
1554 rr.request_extra_record = srw_req->extra_record;
1557 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1558 &srw_res->num_diagnostics,
1560 if ( srw_req->extraRequestData )
1561 rr.extra_request_data = odr_strdup(assoc->encode,
1562 srw_req->extraRequestData );
1564 if (srw_res->num_diagnostics == 0)
1566 if ( assoc->init->bend_srw_update)
1567 (*assoc->init->bend_srw_update)(assoc->backend, &rr);
1569 yaz_log( YLOG_WARN, "Got No Update function!");
1575 yaz_add_srw_diagnostic_uri(assoc->encode,
1576 &srw_res->diagnostics,
1577 &srw_res->num_diagnostics,
1581 srw_res->recordId = rr.record_id;
1582 srw_res->operationStatus = rr.operation_status;
1583 srw_res->recordVersion = rr.record_version;
1584 srw_res->recordChecksum = rr.record_checksum;
1585 srw_res->extraResponseData = rr.extra_response_data;
1586 srw_res->record.recordPosition = 0;
1587 if (srw_res->num_diagnostics == 0 && rr.record_data)
1589 srw_res->record.recordSchema = rr.record_schema;
1590 srw_res->record.recordPacking = srw_req->record.recordPacking;
1591 srw_res->record.recordData_buf = rr.record_data;
1592 srw_res->record.recordData_len = strlen(rr.record_data);
1593 srw_res->extra_record = rr.response_extra_record;
1597 srw_res->record.recordData_len = 0;
1602 /* check if path is OK (1); BAD (0) */
1603 static int check_path(const char *path)
1607 if (strstr(path, ".."))
1612 static char *read_file(const char *fname, ODR o, int *sz)
1615 FILE *inf = fopen(fname, "rb");
1619 fseek(inf, 0L, SEEK_END);
1622 buf = odr_malloc(o, *sz);
1623 fread(buf, 1, *sz, inf);
1628 static void process_http_request(association *assoc, request *req)
1630 Z_HTTP_Request *hreq = req->gdu_request->u.HTTP_Request;
1631 ODR o = assoc->encode;
1632 int r = 2; /* 2=NOT TAKEN, 1=TAKEN, 0=SOAP TAKEN */
1634 Z_SOAP *soap_package = 0;
1637 Z_HTTP_Response *hres = 0;
1639 const char *stylesheet = 0; /* for now .. set later */
1640 Z_SRW_diagnostic *diagnostic = 0;
1641 int num_diagnostic = 0;
1642 const char *host = z_HTTP_header_lookup(hreq->headers, "Host");
1644 if (!control_association(assoc, host, 0))
1646 p = z_get_HTTP_Response(o, 404);
1649 if (r == 2 && assoc->server && assoc->server->docpath
1650 && hreq->path[0] == '/'
1652 /* check if path is a proper prefix of documentroot */
1653 strncmp(hreq->path+1, assoc->server->docpath,
1654 strlen(assoc->server->docpath))
1657 if (!check_path(hreq->path))
1659 yaz_log(YLOG_LOG, "File %s access forbidden", hreq->path+1);
1660 p = z_get_HTTP_Response(o, 404);
1664 int content_size = 0;
1665 char *content_buf = read_file(hreq->path+1, o, &content_size);
1668 yaz_log(YLOG_LOG, "File %s not found", hreq->path+1);
1669 p = z_get_HTTP_Response(o, 404);
1673 const char *ctype = 0;
1674 yaz_mime_types types = yaz_mime_types_create();
1676 yaz_mime_types_add(types, "xsl", "application/xml");
1677 yaz_mime_types_add(types, "xml", "application/xml");
1678 yaz_mime_types_add(types, "css", "text/css");
1679 yaz_mime_types_add(types, "html", "text/html");
1680 yaz_mime_types_add(types, "htm", "text/html");
1681 yaz_mime_types_add(types, "txt", "text/plain");
1682 yaz_mime_types_add(types, "js", "application/x-javascript");
1684 yaz_mime_types_add(types, "gif", "image/gif");
1685 yaz_mime_types_add(types, "png", "image/png");
1686 yaz_mime_types_add(types, "jpg", "image/jpeg");
1687 yaz_mime_types_add(types, "jpeg", "image/jpeg");
1689 ctype = yaz_mime_lookup_fname(types, hreq->path);
1692 yaz_log(YLOG_LOG, "No mime type for %s", hreq->path+1);
1693 p = z_get_HTTP_Response(o, 404);
1697 p = z_get_HTTP_Response(o, 200);
1698 hres = p->u.HTTP_Response;
1699 hres->content_buf = content_buf;
1700 hres->content_len = content_size;
1701 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1703 yaz_mime_types_destroy(types);
1711 r = yaz_srw_decode(hreq, &sr, &soap_package, assoc->decode, &charset);
1712 yaz_log(YLOG_DEBUG, "yaz_srw_decode returned %d", r);
1714 if (r == 2) /* not taken */
1716 r = yaz_sru_decode(hreq, &sr, &soap_package, assoc->decode, &charset,
1717 &diagnostic, &num_diagnostic);
1718 yaz_log(YLOG_DEBUG, "yaz_sru_decode returned %d", r);
1720 if (r == 0) /* decode SRW/SRU OK .. */
1722 int http_code = 200;
1723 if (sr->which == Z_SRW_searchRetrieve_request)
1726 yaz_srw_get(assoc->encode, Z_SRW_searchRetrieve_response);
1728 stylesheet = sr->u.request->stylesheet;
1731 res->u.response->diagnostics = diagnostic;
1732 res->u.response->num_diagnostics = num_diagnostic;
1736 srw_bend_search(assoc, req, sr, res->u.response,
1739 if (http_code == 200)
1740 soap_package->u.generic->p = res;
1742 else if (sr->which == Z_SRW_explain_request)
1744 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_explain_response);
1745 stylesheet = sr->u.explain_request->stylesheet;
1748 res->u.explain_response->diagnostics = diagnostic;
1749 res->u.explain_response->num_diagnostics = num_diagnostic;
1751 srw_bend_explain(assoc, req, sr,
1752 res->u.explain_response, &http_code);
1753 if (http_code == 200)
1754 soap_package->u.generic->p = res;
1756 else if (sr->which == Z_SRW_scan_request)
1758 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_scan_response);
1759 stylesheet = sr->u.scan_request->stylesheet;
1762 res->u.scan_response->diagnostics = diagnostic;
1763 res->u.scan_response->num_diagnostics = num_diagnostic;
1765 srw_bend_scan(assoc, req, sr,
1766 res->u.scan_response, &http_code);
1767 if (http_code == 200)
1768 soap_package->u.generic->p = res;
1770 else if (sr->which == Z_SRW_update_request)
1772 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_update_response);
1773 yaz_log(YLOG_DEBUG, "handling SRW UpdateRequest");
1776 res->u.update_response->diagnostics = diagnostic;
1777 res->u.update_response->num_diagnostics = num_diagnostic;
1779 yaz_log(YLOG_DEBUG, "num_diag = %d", res->u.update_response->num_diagnostics );
1780 srw_bend_update(assoc, req, sr,
1781 res->u.update_response, &http_code);
1782 if (http_code == 200)
1783 soap_package->u.generic->p = res;
1787 yaz_log(log_request, "SOAP ERROR");
1788 /* FIXME - what error, what query */
1790 z_soap_error(assoc->encode, soap_package,
1791 "SOAP-ENV:Client", "Bad method", 0);
1793 if (http_code == 200 || http_code == 500)
1795 static Z_SOAP_Handler soap_handlers[4] = {
1797 {"http://www.loc.gov/zing/srw/", 0,
1798 (Z_SOAP_fun) yaz_srw_codec},
1799 {"http://www.loc.gov/zing/srw/v1.0/", 0,
1800 (Z_SOAP_fun) yaz_srw_codec},
1801 {"http://www.loc.gov/zing/srw/update/", 0,
1802 (Z_SOAP_fun) yaz_ucp_codec},
1808 p = z_get_HTTP_Response(o, 200);
1809 hres = p->u.HTTP_Response;
1811 if (!stylesheet && assoc->server)
1812 stylesheet = assoc->server->stylesheet;
1814 /* empty stylesheet means NO stylesheet */
1815 if (stylesheet && *stylesheet == '\0')
1818 ret = z_soap_codec_enc_xsl(assoc->encode, &soap_package,
1819 &hres->content_buf, &hres->content_len,
1820 soap_handlers, charset, stylesheet);
1821 hres->code = http_code;
1823 strcpy(ctype, "text/xml");
1826 strcat(ctype, "; charset=");
1827 strcat(ctype, charset);
1829 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1832 p = z_get_HTTP_Response(o, http_code);
1836 p = z_get_HTTP_Response(o, 500);
1837 hres = p->u.HTTP_Response;
1838 if (!strcmp(hreq->version, "1.0"))
1840 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1841 if (v && !strcmp(v, "Keep-Alive"))
1845 hres->version = "1.0";
1849 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1850 if (v && !strcmp(v, "close"))
1854 hres->version = "1.1";
1858 z_HTTP_header_add(o, &hres->headers, "Connection", "close");
1859 assoc->state = ASSOC_DEAD;
1860 assoc->cs_get_mask = 0;
1865 const char *alive = z_HTTP_header_lookup(hreq->headers, "Keep-Alive");
1867 if (alive && isdigit(*(const unsigned char *) alive))
1871 if (t < 0 || t > 3600)
1873 iochan_settimeout(assoc->client_chan,t);
1874 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1876 process_gdu_response(assoc, req, p);
1879 static void process_gdu_request(association *assoc, request *req)
1881 if (req->gdu_request->which == Z_GDU_Z3950)
1884 req->apdu_request = req->gdu_request->u.z3950;
1885 if (process_z_request(assoc, req, &msg) < 0)
1886 do_close_req(assoc, Z_Close_systemProblem, msg, req);
1888 else if (req->gdu_request->which == Z_GDU_HTTP_Request)
1889 process_http_request(assoc, req);
1892 do_close_req(assoc, Z_Close_systemProblem, "bad protocol packet", req);
1897 * Initiate request processing.
1899 static int process_z_request(association *assoc, request *req, char **msg)
1905 *msg = "Unknown Error";
1906 assert(req && req->state == REQUEST_IDLE);
1907 if (req->apdu_request->which != Z_APDU_initRequest && !assoc->init)
1909 *msg = "Missing InitRequest";
1912 switch (req->apdu_request->which)
1914 case Z_APDU_initRequest:
1915 res = process_initRequest(assoc, req); break;
1916 case Z_APDU_searchRequest:
1917 res = process_searchRequest(assoc, req, &fd); break;
1918 case Z_APDU_presentRequest:
1919 res = process_presentRequest(assoc, req, &fd); break;
1920 case Z_APDU_scanRequest:
1921 if (assoc->init->bend_scan)
1922 res = process_scanRequest(assoc, req, &fd);
1925 *msg = "Cannot handle Scan APDU";
1929 case Z_APDU_extendedServicesRequest:
1930 if (assoc->init->bend_esrequest)
1931 res = process_ESRequest(assoc, req, &fd);
1934 *msg = "Cannot handle Extended Services APDU";
1938 case Z_APDU_sortRequest:
1939 if (assoc->init->bend_sort)
1940 res = process_sortRequest(assoc, req, &fd);
1943 *msg = "Cannot handle Sort APDU";
1948 process_close(assoc, req);
1950 case Z_APDU_deleteResultSetRequest:
1951 if (assoc->init->bend_delete)
1952 res = process_deleteRequest(assoc, req, &fd);
1955 *msg = "Cannot handle Delete APDU";
1959 case Z_APDU_segmentRequest:
1960 if (assoc->init->bend_segment)
1962 res = process_segmentRequest (assoc, req);
1966 *msg = "Cannot handle Segment APDU";
1970 case Z_APDU_triggerResourceControlRequest:
1973 *msg = "Bad APDU received";
1978 yaz_log(YLOG_DEBUG, " result immediately available");
1979 retval = process_z_response(assoc, req, res);
1983 yaz_log(YLOG_DEBUG, " result unavailble");
1986 else /* no result yet - one will be provided later */
1990 /* Set up an I/O handler for the fd supplied by the backend */
1992 yaz_log(YLOG_DEBUG, " establishing handler for result");
1993 req->state = REQUEST_PENDING;
1994 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT, 0)))
1996 iochan_setdata(chan, assoc);
2003 * Handle message from the backend.
2005 void backend_response(IOCHAN i, int event)
2007 association *assoc = (association *)iochan_getdata(i);
2008 request *req = request_head(&assoc->incoming);
2012 yaz_log(YLOG_DEBUG, "backend_response");
2013 assert(assoc && req && req->state != REQUEST_IDLE);
2014 /* determine what it is we're waiting for */
2015 switch (req->apdu_request->which)
2017 case Z_APDU_searchRequest:
2018 res = response_searchRequest(assoc, req, 0, &fd); break;
2020 case Z_APDU_presentRequest:
2021 res = response_presentRequest(assoc, req, 0, &fd); break;
2022 case Z_APDU_scanRequest:
2023 res = response_scanRequest(assoc, req, 0, &fd); break;
2026 yaz_log(YLOG_FATAL, "Serious programmer's lapse or bug");
2029 if ((res && process_z_response(assoc, req, res) < 0) || fd < 0)
2031 yaz_log(YLOG_WARN, "Fatal error when talking to backend");
2032 do_close(assoc, Z_Close_systemProblem, 0);
2036 else if (!res) /* no result yet - try again later */
2038 yaz_log(YLOG_DEBUG, " no result yet");
2039 iochan_setfd(i, fd); /* in case fd has changed */
2044 * Encode response, and transfer the request structure to the outgoing queue.
2046 static int process_gdu_response(association *assoc, request *req, Z_GDU *res)
2048 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
2052 if (!z_GDU(assoc->print, &res, 0, 0))
2053 yaz_log(YLOG_WARN, "ODR print error: %s",
2054 odr_errmsg(odr_geterror(assoc->print)));
2055 odr_reset(assoc->print);
2057 if (!z_GDU(assoc->encode, &res, 0, 0))
2059 yaz_log(YLOG_WARN, "ODR error when encoding PDU: %s [element %s]",
2060 odr_errmsg(odr_geterror(assoc->decode)),
2061 odr_getelement(assoc->decode));
2064 req->response = odr_getbuf(assoc->encode, &req->len_response,
2065 &req->size_response);
2066 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
2067 odr_reset(assoc->encode);
2068 req->state = REQUEST_IDLE;
2069 request_enq(&assoc->outgoing, req);
2070 /* turn the work over to the ir_session handler */
2071 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
2072 assoc->cs_put_mask = EVENT_OUTPUT;
2073 /* Is there more work to be done? give that to the input handler too */
2075 if (request_head(&assoc->incoming))
2077 yaz_log (YLOG_DEBUG, "more work to be done");
2078 iochan_setevent(assoc->client_chan, EVENT_WORK);
2085 * Encode response, and transfer the request structure to the outgoing queue.
2087 static int process_z_response(association *assoc, request *req, Z_APDU *res)
2089 Z_GDU *gres = (Z_GDU *) odr_malloc(assoc->encode, sizeof(*res));
2090 gres->which = Z_GDU_Z3950;
2091 gres->u.z3950 = res;
2093 return process_gdu_response(assoc, req, gres);
2096 static char *get_vhost(Z_OtherInformation *otherInfo)
2098 return yaz_oi_get_string_oidval(&otherInfo, VAL_PROXY, 1, 0);
2102 * Handle init request.
2103 * At the moment, we don't check the options
2104 * anywhere else in the code - we just try not to do anything that would
2105 * break a naive client. We'll toss 'em into the association block when
2106 * we need them there.
2108 static Z_APDU *process_initRequest(association *assoc, request *reqb)
2110 Z_InitRequest *req = reqb->apdu_request->u.initRequest;
2111 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
2112 Z_InitResponse *resp = apdu->u.initResponse;
2113 bend_initresult *binitres;
2116 statserv_options_block *cb = 0; /* by default no control for backend */
2118 if (control_association(assoc, get_vhost(req->otherInfo), 1))
2119 cb = statserv_getcontrol(); /* got control block for backend */
2121 if (cb && assoc->backend)
2122 (*cb->bend_close)(assoc->backend);
2124 yaz_log(log_requestdetail, "Got initRequest");
2125 if (req->implementationId)
2126 yaz_log(log_requestdetail, "Id: %s",
2127 req->implementationId);
2128 if (req->implementationName)
2129 yaz_log(log_requestdetail, "Name: %s",
2130 req->implementationName);
2131 if (req->implementationVersion)
2132 yaz_log(log_requestdetail, "Version: %s",
2133 req->implementationVersion);
2135 assoc_init_reset(assoc);
2137 assoc->init->auth = req->idAuthentication;
2138 assoc->init->referenceId = req->referenceId;
2140 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
2142 Z_CharSetandLanguageNegotiation *negotiation =
2143 yaz_get_charneg_record (req->otherInfo);
2145 negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
2146 assoc->init->charneg_request = negotiation;
2152 if (req->implementationVersion)
2153 yaz_log(log_requestdetail, "Config: %s",
2156 iochan_settimeout(assoc->client_chan, cb->idle_timeout * 60);
2158 /* we have a backend control block, so call that init function */
2159 if (!(binitres = (*cb->bend_init)(assoc->init)))
2161 yaz_log(YLOG_WARN, "Bad response from backend.");
2164 assoc->backend = binitres->handle;
2168 /* no backend. return error */
2169 binitres = odr_malloc(assoc->encode, sizeof(*binitres));
2170 binitres->errstring = 0;
2171 binitres->errcode = YAZ_BIB1_PERMANENT_SYSTEM_ERROR;
2172 iochan_settimeout(assoc->client_chan, 10);
2174 if ((assoc->init->bend_sort))
2175 yaz_log (YLOG_DEBUG, "Sort handler installed");
2176 if ((assoc->init->bend_search))
2177 yaz_log (YLOG_DEBUG, "Search handler installed");
2178 if ((assoc->init->bend_present))
2179 yaz_log (YLOG_DEBUG, "Present handler installed");
2180 if ((assoc->init->bend_esrequest))
2181 yaz_log (YLOG_DEBUG, "ESRequest handler installed");
2182 if ((assoc->init->bend_delete))
2183 yaz_log (YLOG_DEBUG, "Delete handler installed");
2184 if ((assoc->init->bend_scan))
2185 yaz_log (YLOG_DEBUG, "Scan handler installed");
2186 if ((assoc->init->bend_segment))
2187 yaz_log (YLOG_DEBUG, "Segment handler installed");
2189 resp->referenceId = req->referenceId;
2191 /* let's tell the client what we can do */
2192 if (ODR_MASK_GET(req->options, Z_Options_search))
2194 ODR_MASK_SET(resp->options, Z_Options_search);
2195 strcat(options, "srch");
2197 if (ODR_MASK_GET(req->options, Z_Options_present))
2199 ODR_MASK_SET(resp->options, Z_Options_present);
2200 strcat(options, " prst");
2202 if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
2203 assoc->init->bend_delete)
2205 ODR_MASK_SET(resp->options, Z_Options_delSet);
2206 strcat(options, " del");
2208 if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
2209 assoc->init->bend_esrequest)
2211 ODR_MASK_SET(resp->options, Z_Options_extendedServices);
2212 strcat (options, " extendedServices");
2214 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
2216 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
2217 strcat(options, " namedresults");
2219 if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
2221 ODR_MASK_SET(resp->options, Z_Options_scan);
2222 strcat(options, " scan");
2224 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
2226 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
2227 strcat(options, " concurrop");
2229 if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
2231 ODR_MASK_SET(resp->options, Z_Options_sort);
2232 strcat(options, " sort");
2235 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel)
2236 && assoc->init->charneg_response)
2238 Z_OtherInformation **p;
2239 Z_OtherInformationUnit *p0;
2241 yaz_oi_APDU(apdu, &p);
2243 if ((p0=yaz_oi_update(p, assoc->encode, NULL, 0, 0))) {
2244 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
2246 p0->which = Z_OtherInfo_externallyDefinedInfo;
2247 p0->information.externallyDefinedInfo =
2248 assoc->init->charneg_response;
2250 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
2251 strcat(options, " negotiation");
2254 if (ODR_MASK_GET(req->options, Z_Options_triggerResourceCtrl))
2255 ODR_MASK_SET(resp->options, Z_Options_triggerResourceCtrl);
2257 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
2259 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
2260 assoc->version = 1; /* 1 & 2 are equivalent */
2262 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
2264 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
2267 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
2269 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
2273 yaz_log(log_requestdetail, "Negotiated to v%d: %s", assoc->version, options);
2274 assoc->maximumRecordSize = *req->maximumRecordSize;
2276 if (cb && assoc->maximumRecordSize > cb->maxrecordsize)
2277 assoc->maximumRecordSize = cb->maxrecordsize;
2278 assoc->preferredMessageSize = *req->preferredMessageSize;
2279 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
2280 assoc->preferredMessageSize = assoc->maximumRecordSize;
2282 resp->preferredMessageSize = &assoc->preferredMessageSize;
2283 resp->maximumRecordSize = &assoc->maximumRecordSize;
2285 resp->implementationId = odr_prepend(assoc->encode,
2286 assoc->init->implementation_id,
2287 resp->implementationId);
2289 resp->implementationName = odr_prepend(assoc->encode,
2290 assoc->init->implementation_name,
2291 odr_prepend(assoc->encode, "GFS", resp->implementationName));
2293 version = odr_strdup(assoc->encode, "$Revision: 1.89 $");
2294 if (strlen(version) > 10) /* check for unexpanded CVS strings */
2295 version[strlen(version)-2] = '\0';
2296 resp->implementationVersion = odr_prepend(assoc->encode,
2297 assoc->init->implementation_version,
2298 odr_prepend(assoc->encode, &version[11],
2299 resp->implementationVersion));
2301 if (binitres->errcode)
2303 assoc->state = ASSOC_DEAD;
2304 resp->userInformationField =
2305 init_diagnostics(assoc->encode, binitres->errcode,
2306 binitres->errstring);
2311 if (!req->idAuthentication)
2312 yaz_log(log_request, "Auth none");
2313 else if (req->idAuthentication->which == Z_IdAuthentication_open)
2315 const char *open = req->idAuthentication->u.open;
2316 const char *slash = strchr(open, '/');
2322 yaz_log(log_request, "Auth open %.*s", len, open);
2324 else if (req->idAuthentication->which == Z_IdAuthentication_idPass)
2326 const char *user = req->idAuthentication->u.idPass->userId;
2327 const char *group = req->idAuthentication->u.idPass->groupId;
2328 yaz_log(log_request, "Auth idPass %s %s",
2329 user ? user : "-", group ? group : "-");
2331 else if (req->idAuthentication->which
2332 == Z_IdAuthentication_anonymous)
2334 yaz_log(log_request, "Auth anonymous");
2338 yaz_log(log_request, "Auth other");
2343 WRBUF wr = wrbuf_alloc();
2344 wrbuf_printf(wr, "Init ");
2345 if (binitres->errcode)
2346 wrbuf_printf(wr, "ERROR %d", binitres->errcode);
2348 wrbuf_printf(wr, "OK -");
2349 wrbuf_printf(wr, " ID:%s Name:%s Version:%s",
2350 (req->implementationId ? req->implementationId :"-"),
2351 (req->implementationName ?
2352 req->implementationName : "-"),
2353 (req->implementationVersion ?
2354 req->implementationVersion : "-")
2356 yaz_log(log_request, "%s", wrbuf_buf(wr));
2363 * Set the specified `errcode' and `errstring' into a UserInfo-1
2364 * external to be returned to the client in accordance with Z35.90
2365 * Implementor Agreement 5 (Returning diagnostics in an InitResponse):
2366 * http://lcweb.loc.gov/z3950/agency/agree/initdiag.html
2368 static Z_External *init_diagnostics(ODR odr, int error, const char *addinfo)
2370 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2371 addinfo ? " -- " : "", addinfo ? addinfo : "");
2372 return zget_init_diagnostics(odr, error, addinfo);
2376 * nonsurrogate diagnostic record.
2378 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
2380 Z_Records *rec = (Z_Records *) odr_malloc (assoc->encode, sizeof(*rec));
2382 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2383 addinfo ? " -- " : "", addinfo ? addinfo : "");
2385 rec->which = Z_Records_NSD;
2386 rec->u.nonSurrogateDiagnostic = zget_DefaultDiagFormat(assoc->encode,
2392 * surrogate diagnostic.
2394 static Z_NamePlusRecord *surrogatediagrec(association *assoc,
2396 int error, const char *addinfo)
2398 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2399 addinfo ? " -- " : "", addinfo ? addinfo : "");
2400 return zget_surrogateDiagRec(assoc->encode, dbname, error, addinfo);
2403 static Z_Records *pack_records(association *a, char *setname, int start,
2404 int *num, Z_RecordComposition *comp,
2405 int *next, int *pres, oid_value format,
2406 Z_ReferenceId *referenceId,
2407 int *oid, int *errcode)
2409 int recno, total_length = 0, toget = *num, dumped_records = 0;
2410 Z_Records *records =
2411 (Z_Records *) odr_malloc (a->encode, sizeof(*records));
2412 Z_NamePlusRecordList *reclist =
2413 (Z_NamePlusRecordList *) odr_malloc (a->encode, sizeof(*reclist));
2414 Z_NamePlusRecord **list =
2415 (Z_NamePlusRecord **) odr_malloc (a->encode, sizeof(*list) * toget);
2417 records->which = Z_Records_DBOSD;
2418 records->u.databaseOrSurDiagnostics = reclist;
2419 reclist->num_records = 0;
2420 reclist->records = list;
2421 *pres = Z_PresentStatus_success;
2425 yaz_log(log_requestdetail, "Request to pack %d+%d %s", start, toget, setname);
2426 yaz_log(log_requestdetail, "pms=%d, mrs=%d", a->preferredMessageSize,
2427 a->maximumRecordSize);
2428 for (recno = start; reclist->num_records < toget; recno++)
2431 Z_NamePlusRecord *thisrec;
2432 int this_length = 0;
2434 * we get the number of bytes allocated on the stream before any
2435 * allocation done by the backend - this should give us a reasonable
2436 * idea of the total size of the data so far.
2438 total_length = odr_total(a->encode) - dumped_records;
2444 freq.last_in_set = 0;
2445 freq.setname = setname;
2446 freq.surrogate_flag = 0;
2447 freq.number = recno;
2449 freq.request_format = format;
2450 freq.request_format_raw = oid;
2451 freq.output_format = format;
2452 freq.output_format_raw = 0;
2453 freq.stream = a->encode;
2454 freq.print = a->print;
2455 freq.referenceId = referenceId;
2458 retrieve_fetch(a, &freq);
2460 *next = freq.last_in_set ? 0 : recno + 1;
2462 /* backend should be able to signal whether error is system-wide
2463 or only pertaining to current record */
2466 if (!freq.surrogate_flag)
2469 *pres = Z_PresentStatus_failure;
2470 /* for 'present request out of range',
2471 set addinfo to record position if not set */
2472 if (freq.errcode == YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE &&
2473 freq.errstring == 0)
2475 sprintf (s, "%d", recno);
2479 *errcode = freq.errcode;
2480 return diagrec(a, freq.errcode, freq.errstring);
2482 reclist->records[reclist->num_records] =
2483 surrogatediagrec(a, freq.basename, freq.errcode,
2485 reclist->num_records++;
2488 if (freq.record == 0) /* no error and no record ? */
2490 *next = 0; /* signal end-of-set and stop */
2494 this_length = freq.len;
2496 this_length = odr_total(a->encode) - total_length - dumped_records;
2497 yaz_log(YLOG_DEBUG, " fetched record, len=%d, total=%d dumped=%d",
2498 this_length, total_length, dumped_records);
2499 if (a->preferredMessageSize > 0 &&
2500 this_length + total_length > a->preferredMessageSize)
2502 /* record is small enough, really */
2503 if (this_length <= a->preferredMessageSize && recno > start)
2505 yaz_log(log_requestdetail, " Dropped last normal-sized record");
2506 *pres = Z_PresentStatus_partial_2;
2509 /* record can only be fetched by itself */
2510 if (this_length < a->maximumRecordSize)
2512 yaz_log(log_requestdetail, " Record > prefmsgsz");
2515 yaz_log(YLOG_DEBUG, " Dropped it");
2516 reclist->records[reclist->num_records] =
2517 surrogatediagrec(a, freq.basename, 16, 0);
2518 reclist->num_records++;
2519 dumped_records += this_length;
2523 else /* too big entirely */
2525 yaz_log(log_requestdetail, "Record > maxrcdsz this=%d max=%d",
2526 this_length, a->maximumRecordSize);
2527 reclist->records[reclist->num_records] =
2528 surrogatediagrec(a, freq.basename, 17, 0);
2529 reclist->num_records++;
2530 dumped_records += this_length;
2535 if (!(thisrec = (Z_NamePlusRecord *)
2536 odr_malloc(a->encode, sizeof(*thisrec))))
2539 thisrec->databaseName = odr_strdup(a->encode, freq.basename);
2541 thisrec->databaseName = 0;
2542 thisrec->which = Z_NamePlusRecord_databaseRecord;
2544 if (freq.output_format_raw)
2546 struct oident *ident = oid_getentbyoid(freq.output_format_raw);
2547 freq.output_format = ident->value;
2549 thisrec->u.databaseRecord = z_ext_record(a->encode, freq.output_format,
2550 freq.record, freq.len);
2551 if (!thisrec->u.databaseRecord)
2553 reclist->records[reclist->num_records] = thisrec;
2554 reclist->num_records++;
2556 *num = reclist->num_records;
2560 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
2563 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2564 bend_search_rr *bsrr =
2565 (bend_search_rr *)nmem_malloc (reqb->request_mem, sizeof(*bsrr));
2567 yaz_log(log_requestdetail, "Got SearchRequest.");
2569 bsrr->request = reqb;
2570 bsrr->association = assoc;
2571 bsrr->referenceId = req->referenceId;
2572 save_referenceId (reqb, bsrr->referenceId);
2573 bsrr->srw_sortKeys = 0;
2574 bsrr->srw_setname = 0;
2575 bsrr->srw_setnameIdleTime = 0;
2577 yaz_log (log_requestdetail, "ResultSet '%s'", req->resultSetName);
2578 if (req->databaseNames)
2581 for (i = 0; i < req->num_databaseNames; i++)
2582 yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
2585 yaz_log_zquery_level(log_requestdetail,req->query);
2587 if (assoc->init->bend_search)
2589 bsrr->setname = req->resultSetName;
2590 bsrr->replace_set = *req->replaceIndicator;
2591 bsrr->num_bases = req->num_databaseNames;
2592 bsrr->basenames = req->databaseNames;
2593 bsrr->query = req->query;
2594 bsrr->stream = assoc->encode;
2595 nmem_transfer(bsrr->stream->mem, reqb->request_mem);
2596 bsrr->decode = assoc->decode;
2597 bsrr->print = assoc->print;
2600 bsrr->errstring = NULL;
2601 bsrr->search_info = NULL;
2603 if (assoc->server && assoc->server->cql_transform
2604 && req->query->which == Z_Query_type_104
2605 && req->query->u.type_104->which == Z_External_CQL)
2607 /* have a CQL query and a CQL to PQF transform .. */
2609 cql2pqf(bsrr->stream, req->query->u.type_104->u.cql,
2610 assoc->server->cql_transform, bsrr->query);
2612 bsrr->errcode = yaz_diag_srw_to_bib1(srw_errcode);
2615 (assoc->init->bend_search)(assoc->backend, bsrr);
2616 if (!bsrr->request) /* backend not ready with the search response */
2617 return 0; /* should not be used any more */
2621 /* FIXME - make a diagnostic for it */
2622 yaz_log(YLOG_WARN,"Search not supported ?!?!");
2624 return response_searchRequest(assoc, reqb, bsrr, fd);
2627 int bend_searchresponse(void *handle, bend_search_rr *bsrr) {return 0;}
2630 * Prepare a searchresponse based on the backend results. We probably want
2631 * to look at making the fetching of records nonblocking as well, but
2632 * so far, we'll keep things simple.
2633 * If bsrt is null, that means we're called in response to a communications
2634 * event, and we'll have to get the response for ourselves.
2636 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
2637 bend_search_rr *bsrt, int *fd)
2639 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2640 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2641 Z_SearchResponse *resp = (Z_SearchResponse *)
2642 odr_malloc (assoc->encode, sizeof(*resp));
2643 int *nulint = odr_intdup (assoc->encode, 0);
2644 bool_t *sr = odr_intdup(assoc->encode, 1);
2645 int *next = odr_intdup(assoc->encode, 0);
2646 int *none = odr_intdup(assoc->encode, Z_SearchResponse_none);
2649 apdu->which = Z_APDU_searchResponse;
2650 apdu->u.searchResponse = resp;
2651 resp->referenceId = req->referenceId;
2652 resp->additionalSearchInfo = 0;
2653 resp->otherInfo = 0;
2655 if (!bsrt && !bend_searchresponse(assoc->backend, bsrt))
2657 yaz_log(YLOG_FATAL, "Bad result from backend");
2660 else if (bsrt->errcode)
2662 resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
2663 resp->resultCount = nulint;
2664 resp->numberOfRecordsReturned = nulint;
2665 resp->nextResultSetPosition = nulint;
2666 resp->searchStatus = nulint;
2667 resp->resultSetStatus = none;
2668 resp->presentStatus = 0;
2672 int *toget = odr_intdup(assoc->encode, 0);
2673 int *presst = odr_intdup(assoc->encode, 0);
2674 Z_RecordComposition comp, *compp = 0;
2676 yaz_log (log_requestdetail, "resultCount: %d", bsrt->hits);
2679 resp->resultCount = &bsrt->hits;
2681 comp.which = Z_RecordComp_simple;
2682 /* how many records does the user agent want, then? */
2683 if (bsrt->hits <= *req->smallSetUpperBound)
2685 *toget = bsrt->hits;
2686 if ((comp.u.simple = req->smallSetElementSetNames))
2689 else if (bsrt->hits < *req->largeSetLowerBound)
2691 *toget = *req->mediumSetPresentNumber;
2692 if (*toget > bsrt->hits)
2693 *toget = bsrt->hits;
2694 if ((comp.u.simple = req->mediumSetElementSetNames))
2700 if (*toget && !resp->records)
2705 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
2708 form = prefformat->value;
2710 /* Call bend_present if defined */
2711 if (assoc->init->bend_present)
2713 bend_present_rr *bprr = (bend_present_rr *)
2714 nmem_malloc (reqb->request_mem, sizeof(*bprr));
2715 bprr->setname = req->resultSetName;
2717 bprr->number = *toget;
2718 bprr->format = form;
2720 bprr->referenceId = req->referenceId;
2721 bprr->stream = assoc->encode;
2722 bprr->print = assoc->print;
2723 bprr->request = reqb;
2724 bprr->association = assoc;
2726 bprr->errstring = NULL;
2727 (*assoc->init->bend_present)(assoc->backend, bprr);
2733 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2734 *resp->presentStatus = Z_PresentStatus_failure;
2739 resp->records = pack_records(assoc, req->resultSetName, 1,
2740 toget, compp, next, presst, form, req->referenceId,
2741 req->preferredRecordSyntax, NULL);
2744 resp->numberOfRecordsReturned = toget;
2745 returnedrecs = *toget;
2746 resp->nextResultSetPosition = next;
2747 resp->searchStatus = sr;
2748 resp->resultSetStatus = 0;
2749 resp->presentStatus = presst;
2753 if (*resp->resultCount)
2755 resp->numberOfRecordsReturned = nulint;
2756 resp->nextResultSetPosition = next;
2757 resp->searchStatus = sr;
2758 resp->resultSetStatus = 0;
2759 resp->presentStatus = 0;
2762 resp->additionalSearchInfo = bsrt->search_info;
2767 WRBUF wr = wrbuf_alloc();
2768 /* int num_databaseNames;
2769 Z_DatabaseName **databaseNames; */
2770 for (i = 0 ; i < req->num_databaseNames; i++){
2772 wrbuf_printf(wr, ",");
2773 wrbuf_printf(wr, req->databaseNames[i]);
2775 wrbuf_printf(wr, " ");
2778 wrbuf_printf(wr, "ERROR %d", bsrt->errcode);
2780 wrbuf_printf(wr, "OK %d", bsrt->hits);
2781 wrbuf_printf(wr, " %s 1+%d ",
2782 req->resultSetName, returnedrecs);
2783 yaz_query_to_wrbuf(wr, req->query);
2785 yaz_log(log_request, "Search %s", wrbuf_buf(wr));
2792 * Maybe we got a little over-friendly when we designed bend_fetch to
2793 * get only one record at a time. Some backends can optimise multiple-record
2794 * fetches, and at any rate, there is some overhead involved in
2795 * all that selecting and hopping around. Problem is, of course, that the
2796 * frontend can't know ahead of time how many records it'll need to
2797 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
2798 * is downright lousy as a bulk data transfer protocol.
2800 * To start with, we'll do the fetching of records from the backend
2801 * in one operation: To save some trips in and out of the event-handler,
2802 * and to simplify the interface to pack_records. At any rate, asynch
2803 * operation is more fun in operations that have an unpredictable execution
2804 * speed - which is normally more true for search than for present.
2806 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
2809 Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
2813 Z_PresentResponse *resp;
2817 const char *errstring = 0;
2819 yaz_log(log_requestdetail, "Got PresentRequest.");
2821 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
2824 form = prefformat->value;
2825 resp = (Z_PresentResponse *)odr_malloc (assoc->encode, sizeof(*resp));
2827 resp->presentStatus = odr_intdup(assoc->encode, 0);
2828 if (assoc->init->bend_present)
2830 bend_present_rr *bprr = (bend_present_rr *)
2831 nmem_malloc (reqb->request_mem, sizeof(*bprr));
2832 bprr->setname = req->resultSetId;
2833 bprr->start = *req->resultSetStartPoint;
2834 bprr->number = *req->numberOfRecordsRequested;
2835 bprr->format = form;
2836 bprr->comp = req->recordComposition;
2837 bprr->referenceId = req->referenceId;
2838 bprr->stream = assoc->encode;
2839 bprr->print = assoc->print;
2840 bprr->request = reqb;
2841 bprr->association = assoc;
2843 bprr->errstring = NULL;
2844 (*assoc->init->bend_present)(assoc->backend, bprr);
2847 return 0; /* should not happen */
2850 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2851 *resp->presentStatus = Z_PresentStatus_failure;
2852 errcode = bprr->errcode;
2853 errstring = bprr->errstring;
2856 apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2857 next = odr_intdup(assoc->encode, 0);
2858 num = odr_intdup(assoc->encode, 0);
2860 apdu->which = Z_APDU_presentResponse;
2861 apdu->u.presentResponse = resp;
2862 resp->referenceId = req->referenceId;
2863 resp->otherInfo = 0;
2867 *num = *req->numberOfRecordsRequested;
2869 pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
2870 num, req->recordComposition, next,
2871 resp->presentStatus,
2872 form, req->referenceId, req->preferredRecordSyntax,
2877 WRBUF wr = wrbuf_alloc();
2878 wrbuf_printf(wr, "Present ");
2880 if (*resp->presentStatus == Z_PresentStatus_failure)
2881 wrbuf_printf(wr, "ERROR %d", errcode);
2882 else if (*resp->presentStatus == Z_PresentStatus_success)
2883 wrbuf_printf(wr, "OK -");
2885 wrbuf_printf(wr, "Partial %d", *resp->presentStatus);
2887 wrbuf_printf(wr, " %s %d+%d ",
2888 req->resultSetId, *req->resultSetStartPoint,
2889 *req->numberOfRecordsRequested);
2890 yaz_log(log_request, "%s", wrbuf_buf(wr) );
2895 resp->numberOfRecordsReturned = num;
2896 resp->nextResultSetPosition = next;
2902 * Scan was implemented rather in a hurry, and with support for only the basic
2903 * elements of the service in the backend API. Suggestions are welcome.
2905 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
2907 Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
2908 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2909 Z_ScanResponse *res = (Z_ScanResponse *)
2910 odr_malloc (assoc->encode, sizeof(*res));
2911 int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
2912 int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
2913 Z_ListEntries *ents = (Z_ListEntries *)
2914 odr_malloc (assoc->encode, sizeof(*ents));
2915 Z_DiagRecs *diagrecs_p = NULL;
2917 bend_scan_rr *bsrr = (bend_scan_rr *)
2918 odr_malloc (assoc->encode, sizeof(*bsrr));
2919 struct scan_entry *save_entries;
2921 yaz_log(log_requestdetail, "Got ScanRequest");
2923 apdu->which = Z_APDU_scanResponse;
2924 apdu->u.scanResponse = res;
2925 res->referenceId = req->referenceId;
2927 /* if step is absent, set it to 0 */
2928 res->stepSize = odr_intdup(assoc->encode, 0);
2930 *res->stepSize = *req->stepSize;
2932 res->scanStatus = scanStatus;
2933 res->numberOfEntriesReturned = numberOfEntriesReturned;
2934 res->positionOfTerm = 0;
2935 res->entries = ents;
2936 ents->num_entries = 0;
2937 ents->entries = NULL;
2938 ents->num_nonsurrogateDiagnostics = 0;
2939 ents->nonsurrogateDiagnostics = NULL;
2940 res->attributeSet = 0;
2943 if (req->databaseNames)
2946 for (i = 0; i < req->num_databaseNames; i++)
2947 yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
2949 bsrr->scanClause = 0;
2951 bsrr->errstring = 0;
2952 bsrr->num_bases = req->num_databaseNames;
2953 bsrr->basenames = req->databaseNames;
2954 bsrr->num_entries = *req->numberOfTermsRequested;
2955 bsrr->term = req->termListAndStartPoint;
2956 bsrr->referenceId = req->referenceId;
2957 bsrr->stream = assoc->encode;
2958 bsrr->print = assoc->print;
2959 bsrr->step_size = res->stepSize;
2961 /* For YAZ 2.0 and earlier it was the backend handler that
2962 initialized entries (member display_term did not exist)
2963 YAZ 2.0 and later sets 'entries' and initialize all members
2964 including 'display_term'. If YAZ 2.0 or later sees that
2965 entries was modified - we assume that it is an old handler and
2966 that 'display_term' is _not_ set.
2968 if (bsrr->num_entries > 0)
2971 bsrr->entries = odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
2973 for (i = 0; i<bsrr->num_entries; i++)
2975 bsrr->entries[i].term = 0;
2976 bsrr->entries[i].occurrences = 0;
2977 bsrr->entries[i].errcode = 0;
2978 bsrr->entries[i].errstring = 0;
2979 bsrr->entries[i].display_term = 0;
2982 save_entries = bsrr->entries; /* save it so we can compare later */
2984 if (req->attributeSet &&
2985 (attset = oid_getentbyoid(req->attributeSet)) &&
2986 (attset->oclass == CLASS_ATTSET || attset->oclass == CLASS_GENERAL))
2987 bsrr->attributeset = attset->value;
2989 bsrr->attributeset = VAL_NONE;
2990 log_scan_term_level (log_requestdetail, req->termListAndStartPoint,
2991 bsrr->attributeset);
2992 bsrr->term_position = req->preferredPositionInResponse ?
2993 *req->preferredPositionInResponse : 1;
2995 ((int (*)(void *, bend_scan_rr *))
2996 (*assoc->init->bend_scan))(assoc->backend, bsrr);
2999 diagrecs_p = zget_DiagRecs(assoc->encode,
3000 bsrr->errcode, bsrr->errstring);
3004 Z_Entry **tab = (Z_Entry **)
3005 odr_malloc (assoc->encode, sizeof(*tab) * bsrr->num_entries);
3007 if (bsrr->status == BEND_SCAN_PARTIAL)
3008 *scanStatus = Z_Scan_partial_5;
3010 *scanStatus = Z_Scan_success;
3011 ents->entries = tab;
3012 ents->num_entries = bsrr->num_entries;
3013 res->numberOfEntriesReturned = &ents->num_entries;
3014 res->positionOfTerm = &bsrr->term_position;
3015 for (i = 0; i < bsrr->num_entries; i++)
3021 tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
3022 if (bsrr->entries[i].occurrences >= 0)
3024 e->which = Z_Entry_termInfo;
3025 e->u.termInfo = t = (Z_TermInfo *)
3026 odr_malloc(assoc->encode, sizeof(*t));
3027 t->suggestedAttributes = 0;
3029 if (save_entries == bsrr->entries &&
3030 bsrr->entries[i].display_term)
3032 /* the entries was _not_ set by the handler. So it's
3033 safe to test for new member display_term. It is
3036 t->displayTerm = odr_strdup(assoc->encode,
3037 bsrr->entries[i].display_term);
3039 t->alternativeTerm = 0;
3040 t->byAttributes = 0;
3041 t->otherTermInfo = 0;
3042 t->globalOccurrences = &bsrr->entries[i].occurrences;
3043 t->term = (Z_Term *)
3044 odr_malloc(assoc->encode, sizeof(*t->term));
3045 t->term->which = Z_Term_general;
3046 t->term->u.general = o =
3047 (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
3048 o->buf = (unsigned char *)
3049 odr_malloc(assoc->encode, o->len = o->size =
3050 strlen(bsrr->entries[i].term));
3051 memcpy(o->buf, bsrr->entries[i].term, o->len);
3052 yaz_log(YLOG_DEBUG, " term #%d: '%s' (%d)", i,
3053 bsrr->entries[i].term, bsrr->entries[i].occurrences);
3057 Z_DiagRecs *drecs = zget_DiagRecs(assoc->encode,
3058 bsrr->entries[i].errcode,
3059 bsrr->entries[i].errstring);
3060 assert (drecs->num_diagRecs == 1);
3061 e->which = Z_Entry_surrogateDiagnostic;
3062 assert (drecs->diagRecs[0]);
3063 e->u.surrogateDiagnostic = drecs->diagRecs[0];
3069 ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
3070 ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
3074 WRBUF wr = wrbuf_alloc();
3076 wr_diag(wr, bsrr->errcode, bsrr->errstring);
3077 else if (*res->scanStatus == Z_Scan_success)
3078 wrbuf_printf(wr, "OK");
3080 wrbuf_printf(wr, "Partial");
3082 wrbuf_printf(wr, " %d+%d %d ",
3083 (req->preferredPositionInResponse ?
3084 *req->preferredPositionInResponse : 1),
3085 *req->numberOfTermsRequested,
3086 (res->stepSize ? *res->stepSize : 0));
3087 yaz_scan_to_wrbuf(wr, req->termListAndStartPoint,
3088 bsrr->attributeset);
3089 yaz_log(log_request, "Scan %s", wrbuf_buf(wr) );
3095 static Z_APDU *process_sortRequest(association *assoc, request *reqb,
3099 Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
3100 Z_SortResponse *res = (Z_SortResponse *)
3101 odr_malloc (assoc->encode, sizeof(*res));
3102 bend_sort_rr *bsrr = (bend_sort_rr *)
3103 odr_malloc (assoc->encode, sizeof(*bsrr));
3105 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
3107 yaz_log(log_requestdetail, "Got SortRequest.");
3109 bsrr->num_input_setnames = req->num_inputResultSetNames;
3110 for (i=0;i<req->num_inputResultSetNames;i++)
3111 yaz_log(log_requestdetail, "Input resultset: '%s'",
3112 req->inputResultSetNames[i]);
3113 bsrr->input_setnames = req->inputResultSetNames;
3114 bsrr->referenceId = req->referenceId;
3115 bsrr->output_setname = req->sortedResultSetName;
3116 yaz_log(log_requestdetail, "Output resultset: '%s'",
3117 req->sortedResultSetName);
3118 bsrr->sort_sequence = req->sortSequence;
3119 /*FIXME - dump those sequences too */
3120 bsrr->stream = assoc->encode;
3121 bsrr->print = assoc->print;
3123 bsrr->sort_status = Z_SortResponse_failure;
3125 bsrr->errstring = 0;
3127 (*assoc->init->bend_sort)(assoc->backend, bsrr);
3129 res->referenceId = bsrr->referenceId;
3130 res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
3131 res->resultSetStatus = 0;
3134 Z_DiagRecs *dr = zget_DiagRecs(assoc->encode,
3135 bsrr->errcode, bsrr->errstring);
3136 res->diagnostics = dr->diagRecs;
3137 res->num_diagnostics = dr->num_diagRecs;
3141 res->num_diagnostics = 0;
3142 res->diagnostics = 0;
3144 res->resultCount = 0;
3147 apdu->which = Z_APDU_sortResponse;
3148 apdu->u.sortResponse = res;
3151 WRBUF wr = wrbuf_alloc();
3152 wrbuf_printf(wr, "Sort ");
3154 wrbuf_printf(wr, " ERROR %d", bsrr->errcode);
3156 wrbuf_printf(wr, "OK -");
3157 wrbuf_printf(wr, " (");
3158 for (i = 0; i<req->num_inputResultSetNames; i++)
3161 wrbuf_printf(wr, ",");
3162 wrbuf_printf(wr, req->inputResultSetNames[i]);
3164 wrbuf_printf(wr, ")->%s ",req->sortedResultSetName);
3166 yaz_log(log_request, "%s", wrbuf_buf(wr) );
3172 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
3176 Z_DeleteResultSetRequest *req =
3177 reqb->apdu_request->u.deleteResultSetRequest;
3178 Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
3179 odr_malloc (assoc->encode, sizeof(*res));
3180 bend_delete_rr *bdrr = (bend_delete_rr *)
3181 odr_malloc (assoc->encode, sizeof(*bdrr));
3182 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
3184 yaz_log(log_requestdetail, "Got DeleteRequest.");
3186 bdrr->num_setnames = req->num_resultSetList;
3187 bdrr->setnames = req->resultSetList;
3188 for (i = 0; i<req->num_resultSetList; i++)
3189 yaz_log(log_requestdetail, "resultset: '%s'",
3190 req->resultSetList[i]);
3191 bdrr->stream = assoc->encode;
3192 bdrr->print = assoc->print;
3193 bdrr->function = *req->deleteFunction;
3194 bdrr->referenceId = req->referenceId;
3196 if (bdrr->num_setnames > 0)
3198 bdrr->statuses = (int*)
3199 odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
3200 bdrr->num_setnames);
3201 for (i = 0; i < bdrr->num_setnames; i++)
3202 bdrr->statuses[i] = 0;
3204 (*assoc->init->bend_delete)(assoc->backend, bdrr);
3206 res->referenceId = req->referenceId;
3208 res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
3210 res->deleteListStatuses = 0;
3211 if (bdrr->num_setnames > 0)
3214 res->deleteListStatuses = (Z_ListStatuses *)
3215 odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
3216 res->deleteListStatuses->num = bdrr->num_setnames;
3217 res->deleteListStatuses->elements =
3219 odr_malloc (assoc->encode,
3220 sizeof(*res->deleteListStatuses->elements) *
3221 bdrr->num_setnames);
3222 for (i = 0; i<bdrr->num_setnames; i++)
3224 res->deleteListStatuses->elements[i] =
3226 odr_malloc (assoc->encode,
3227 sizeof(**res->deleteListStatuses->elements));
3228 res->deleteListStatuses->elements[i]->status = bdrr->statuses+i;
3229 res->deleteListStatuses->elements[i]->id =
3230 odr_strdup (assoc->encode, bdrr->setnames[i]);
3233 res->numberNotDeleted = 0;
3234 res->bulkStatuses = 0;
3235 res->deleteMessage = 0;
3238 apdu->which = Z_APDU_deleteResultSetResponse;
3239 apdu->u.deleteResultSetResponse = res;
3242 WRBUF wr = wrbuf_alloc();
3243 wrbuf_printf(wr, "Delete ");
3244 if (bdrr->delete_status)
3245 wrbuf_printf(wr, "ERROR %d", bdrr->delete_status);
3247 wrbuf_printf(wr, "OK -");
3248 for (i = 0; i<req->num_resultSetList; i++)
3249 wrbuf_printf(wr, " %s ", req->resultSetList[i]);
3250 yaz_log(log_request, "%s", wrbuf_buf(wr) );
3256 static void process_close(association *assoc, request *reqb)
3258 Z_Close *req = reqb->apdu_request->u.close;
3259 static char *reasons[] =
3266 "securityViolation",
3273 yaz_log(log_requestdetail, "Got Close, reason %s, message %s",
3274 reasons[*req->closeReason], req->diagnosticInformation ?
3275 req->diagnosticInformation : "NULL");
3276 if (assoc->version < 3) /* to make do_force respond with close */
3278 do_close_req(assoc, Z_Close_finished,
3279 "Association terminated by client", reqb);
3280 yaz_log(log_request,"Close OK");
3283 void save_referenceId (request *reqb, Z_ReferenceId *refid)
3287 reqb->len_refid = refid->len;
3288 reqb->refid = (char *)nmem_malloc (reqb->request_mem, refid->len);
3289 memcpy (reqb->refid, refid->buf, refid->len);
3293 reqb->len_refid = 0;
3298 void bend_request_send (bend_association a, bend_request req, Z_APDU *res)
3300 process_z_response (a, req, res);
3303 bend_request bend_request_mk (bend_association a)
3305 request *nreq = request_get (&a->outgoing);
3306 nreq->request_mem = nmem_create ();
3310 Z_ReferenceId *bend_request_getid (ODR odr, bend_request req)
3315 id = (Odr_oct *)odr_malloc (odr, sizeof(*odr));
3316 id->buf = (unsigned char *)odr_malloc (odr, req->len_refid);
3317 id->len = id->size = req->len_refid;
3318 memcpy (id->buf, req->refid, req->len_refid);
3322 void bend_request_destroy (bend_request *req)
3324 nmem_destroy((*req)->request_mem);
3325 request_release(*req);
3329 int bend_backend_respond (bend_association a, bend_request req)
3333 r = process_z_request (a, req, &msg);
3335 yaz_log (YLOG_WARN, "%s", msg);
3339 void bend_request_setdata(bend_request r, void *p)
3344 void *bend_request_getdata(bend_request r)
3346 return r->clientData;
3349 static Z_APDU *process_segmentRequest (association *assoc, request *reqb)
3351 bend_segment_rr req;
3353 req.segment = reqb->apdu_request->u.segmentRequest;
3354 req.stream = assoc->encode;
3355 req.decode = assoc->decode;
3356 req.print = assoc->print;
3357 req.association = assoc;
3359 (*assoc->init->bend_segment)(assoc->backend, &req);
3364 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd)
3366 bend_esrequest_rr esrequest;
3367 const char *ext_name = "unknown";
3369 Z_ExtendedServicesRequest *req =
3370 reqb->apdu_request->u.extendedServicesRequest;
3371 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
3373 Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
3375 esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
3376 esrequest.stream = assoc->encode;
3377 esrequest.decode = assoc->decode;
3378 esrequest.print = assoc->print;
3379 esrequest.errcode = 0;
3380 esrequest.errstring = NULL;
3381 esrequest.request = reqb;
3382 esrequest.association = assoc;
3383 esrequest.taskPackage = 0;
3384 esrequest.referenceId = req->referenceId;
3387 if (esrequest.esr && esrequest.esr->taskSpecificParameters)
3389 switch(esrequest.esr->taskSpecificParameters->which)
3391 case Z_External_itemOrder:
3392 ext_name = "ItemOrder"; break;
3393 case Z_External_update:
3394 ext_name = "Update"; break;
3395 case Z_External_update0:
3396 ext_name = "Update0"; break;
3397 case Z_External_ESAdmin:
3398 ext_name = "Admin"; break;
3403 (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
3405 /* If the response is being delayed, return NULL */
3406 if (esrequest.request == NULL)
3409 resp->referenceId = req->referenceId;
3411 if (esrequest.errcode == -1)
3413 /* Backend service indicates request will be processed */
3414 yaz_log(log_request, "Extended Service: %s (accepted)", ext_name);
3415 *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
3417 else if (esrequest.errcode == 0)
3419 /* Backend service indicates request will be processed */
3420 yaz_log(log_request, "Extended Service: %s (done)", ext_name);
3421 *resp->operationStatus = Z_ExtendedServicesResponse_done;
3425 Z_DiagRecs *diagRecs =
3426 zget_DiagRecs(assoc->encode, esrequest.errcode,
3427 esrequest.errstring);
3428 /* Backend indicates error, request will not be processed */
3429 yaz_log(log_request, "Extended Service: %s (failed)", ext_name);
3430 *resp->operationStatus = Z_ExtendedServicesResponse_failure;
3431 resp->num_diagnostics = diagRecs->num_diagRecs;
3432 resp->diagnostics = diagRecs->diagRecs;
3435 WRBUF wr = wrbuf_alloc();
3436 wrbuf_diags(wr, resp->num_diagnostics, resp->diagnostics);
3437 yaz_log(log_request, "EsRequest %s", wrbuf_buf(wr) );
3442 /* Do something with the members of bend_extendedservice */
3443 if (esrequest.taskPackage)
3444 resp->taskPackage = z_ext_record (assoc->encode, VAL_EXTENDED,
3445 (const char *) esrequest.taskPackage,
3447 yaz_log(YLOG_DEBUG,"Send the result apdu");
3454 * indent-tabs-mode: nil
3456 * vim: shiftwidth=4 tabstop=8 expandtab