2 * Copyright (C) 1995-2005, Index Data ApS
3 * See the file LICENSE for details.
5 * $Id: seshigh.c,v 1.77 2006-05-07 14:48:25 adam Exp $
9 * \brief Implements GFS session logic.
11 * Frontend server logic.
13 * This code receives incoming APDUs, and handles client requests by means
16 * Some of the code is getting quite involved, compared to simpler servers -
17 * primarily because it is asynchronous both in the communication with
18 * the user and the backend. We think the complexity will pay off in
19 * the form of greater flexibility when more asynchronous facilities
22 * Memory management has become somewhat involved. In the simple case, where
23 * only one PDU is pending at a time, it will simply reuse the same memory,
24 * once it has found its working size. When we enable multiple concurrent
25 * operations, perhaps even with multiple parallel calls to the backend, it
26 * will maintain a pool of buffers for encoding and decoding, trying to
27 * minimize memory allocation/deallocation during normal operation.
37 #include <sys/types.h>
45 #define S_ISREG(x) (x & _S_IFREG)
54 #include <libxml/parser.h>
55 #include <libxml/tree.h>
58 #include <yaz/yconfig.h>
59 #include <yaz/xmalloc.h>
60 #include <yaz/comstack.h>
64 #include <yaz/proto.h>
67 #include <yaz/logrpn.h>
68 #include <yaz/querytowrbuf.h>
69 #include <yaz/statserv.h>
70 #include <yaz/diagbib1.h>
71 #include <yaz/charneg.h>
72 #include <yaz/otherinfo.h>
73 #include <yaz/yaz-util.h>
74 #include <yaz/pquery.h>
77 #include <yaz/backend.h>
79 static void process_gdu_request(association *assoc, request *req);
80 static int process_z_request(association *assoc, request *req, char **msg);
81 void backend_response(IOCHAN i, int event);
82 static int process_gdu_response(association *assoc, request *req, Z_GDU *res);
83 static int process_z_response(association *assoc, request *req, Z_APDU *res);
84 static Z_APDU *process_initRequest(association *assoc, request *reqb);
85 static Z_External *init_diagnostics(ODR odr, int errcode,
86 const char *errstring);
87 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
89 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
90 bend_search_rr *bsrr, int *fd);
91 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
93 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
94 static Z_APDU *process_sortRequest(association *assoc, request *reqb, int *fd);
95 static void process_close(association *assoc, request *reqb);
96 void save_referenceId (request *reqb, Z_ReferenceId *refid);
97 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
99 static Z_APDU *process_segmentRequest (association *assoc, request *reqb);
101 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd);
103 /* dynamic logging levels */
104 static int logbits_set = 0;
105 static int log_session = 0;
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);
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;
627 const char *details = input_schema;
628 rr->errcode = YAZ_BIB1_ELEMENT_SET_NAMES_UNSUPP;
630 rr->errstring = odr_strdup(rr->stream, details);
635 rr->errcode = YAZ_BIB1_RECORD_NOT_AVAILABLE_IN_REQUESTED_SYNTAX;
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;
741 rr.output_format = VAL_TEXT_XML;
742 rr.output_format_raw = 0;
745 rr.surrogate_flag = 0;
746 rr.schema = srw_req->recordSchema;
748 if (!assoc->init->bend_fetch)
751 retrieve_fetch(assoc, &rr);
753 if (rr.errcode && rr.surrogate_flag)
755 int code = yaz_diag_bib1_to_srw(rr.errcode);
756 const char *message = yaz_diag_srw_str(code);
759 len += strlen(message);
761 len += strlen(rr.errstring);
763 record->recordData_buf = odr_malloc(o, len);
765 sprintf(record->recordData_buf, "<diagnostic "
766 "xmlns=\"http://www.loc.gov/zing/srw/diagnostic/\">\n"
767 " <uri>info:srw/diagnostic/1/%d</uri>\n", code);
769 sprintf(record->recordData_buf + strlen(record->recordData_buf),
770 " <details>%s</details>\n", rr.errstring);
772 sprintf(record->recordData_buf + strlen(record->recordData_buf),
773 " <message>%s</message>\n", message);
774 sprintf(record->recordData_buf + strlen(record->recordData_buf),
776 record->recordData_len = strlen(record->recordData_buf);
777 record->recordPosition = odr_intdup(o, pos);
778 record->recordSchema = "info:srw/schema/1/diagnostics-v1.1";
781 else if (rr.len >= 0)
783 record->recordData_buf = rr.record;
784 record->recordData_len = rr.len;
785 record->recordPosition = odr_intdup(o, pos);
787 record->recordSchema = odr_strdup(o, rr.schema);
789 record->recordSchema = 0;
794 static int cql2pqf(ODR odr, const char *cql, cql_transform_t ct,
795 Z_Query *query_result)
797 /* have a CQL query and CQL to PQF transform .. */
798 CQL_parser cp = cql_parser_create();
804 r = cql_parser_string(cp, cql);
807 /* CQL syntax error */
813 r = cql_transform_buf(ct,
814 cql_parser_result(cp),
815 rpn_buf, sizeof(rpn_buf)-1);
817 srw_errcode = cql_transform_error(ct, &add);
821 /* Syntax & transform OK. */
822 /* Convert PQF string to Z39.50 to RPN query struct */
823 YAZ_PQF_Parser pp = yaz_pqf_create();
824 Z_RPNQuery *rpnquery = yaz_pqf_parse(pp, odr, rpn_buf);
829 int code = yaz_pqf_error(pp, &pqf_msg, &off);
830 yaz_log(YLOG_WARN, "PQF Parser Error %s (code %d)",
836 query_result->which = Z_Query_type_1;
837 query_result->u.type_1 = rpnquery;
841 cql_parser_destroy(cp);
845 static int cql2pqf_scan(ODR odr, const char *cql, cql_transform_t ct,
846 Z_AttributesPlusTerm *result)
850 int srw_error = cql2pqf(odr, cql, ct, &query);
853 if (query.which != Z_Query_type_1 && query.which != Z_Query_type_101)
854 return 10; /* bad query type */
855 rpn = query.u.type_1;
856 if (!rpn->RPNStructure)
857 return 10; /* must be structure */
858 if (rpn->RPNStructure->which != Z_RPNStructure_simple)
859 return 10; /* must be simple */
860 if (rpn->RPNStructure->u.simple->which != Z_Operand_APT)
861 return 10; /* must be attributes plus term node .. */
862 memcpy(result, rpn->RPNStructure->u.simple->u.attributesPlusTerm,
867 static void srw_bend_search(association *assoc, request *req,
869 Z_SRW_searchRetrieveResponse *srw_res,
874 Z_SRW_searchRetrieveRequest *srw_req = sr->u.request;
877 yaz_log(log_requestdetail, "Got SRW SearchRetrieveRequest");
878 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
879 if (srw_res->num_diagnostics == 0 && assoc->init)
882 rr.setname = "default";
885 rr.basenames = &srw_req->database;
889 rr.srw_setnameIdleTime = 0;
890 rr.query = (Z_Query *) odr_malloc (assoc->decode, sizeof(*rr.query));
891 rr.query->u.type_1 = 0;
893 if (srw_req->query_type == Z_SRW_query_type_cql)
895 if (assoc->server && assoc->server->cql_transform)
897 int srw_errcode = cql2pqf(assoc->encode, srw_req->query.cql,
898 assoc->server->cql_transform,
902 yaz_add_srw_diagnostic(assoc->encode,
903 &srw_res->diagnostics,
904 &srw_res->num_diagnostics,
910 /* CQL query to backend. Wrap it - Z39.50 style */
911 ext = (Z_External *) odr_malloc(assoc->decode, sizeof(*ext));
912 ext->direct_reference = odr_getoidbystr(assoc->decode,
913 "1.2.840.10003.16.2");
914 ext->indirect_reference = 0;
916 ext->which = Z_External_CQL;
917 ext->u.cql = srw_req->query.cql;
919 rr.query->which = Z_Query_type_104;
920 rr.query->u.type_104 = ext;
923 else if (srw_req->query_type == Z_SRW_query_type_pqf)
925 Z_RPNQuery *RPNquery;
926 YAZ_PQF_Parser pqf_parser;
928 pqf_parser = yaz_pqf_create ();
930 RPNquery = yaz_pqf_parse (pqf_parser, assoc->decode,
936 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
937 yaz_log(log_requestdetail, "Parse error %d %s near offset %ld",
938 code, pqf_msg, (long) off);
939 srw_error = YAZ_SRW_QUERY_SYNTAX_ERROR;
942 rr.query->which = Z_Query_type_1;
943 rr.query->u.type_1 = RPNquery;
945 yaz_pqf_destroy (pqf_parser);
949 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
950 &srw_res->num_diagnostics,
951 YAZ_SRW_UNSUPP_QUERY_TYPE, 0);
953 if (rr.query->u.type_1)
955 rr.stream = assoc->encode;
956 rr.decode = assoc->decode;
957 rr.print = assoc->print;
959 if ( srw_req->sort.sortKeys )
960 rr.srw_sortKeys = odr_strdup(assoc->encode,
961 srw_req->sort.sortKeys );
962 rr.association = assoc;
968 yaz_log_zquery_level(log_requestdetail,rr.query);
970 (assoc->init->bend_search)(assoc->backend, &rr);
973 if (rr.errcode == YAZ_BIB1_DATABASE_UNAVAILABLE)
979 srw_error = yaz_diag_bib1_to_srw (rr.errcode);
980 yaz_add_srw_diagnostic(assoc->encode,
981 &srw_res->diagnostics,
982 &srw_res->num_diagnostics,
983 srw_error, rr.errstring);
988 int number = srw_req->maximumRecords ? *srw_req->maximumRecords : 0;
989 int start = srw_req->startRecord ? *srw_req->startRecord : 1;
991 yaz_log(log_requestdetail, "Request to pack %d+%d out of %d",
992 start, number, rr.hits);
994 srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
997 srw_res->resultSetId =
998 odr_strdup(assoc->encode, rr.srw_setname );
999 srw_res->resultSetIdleTime =
1000 odr_intdup(assoc->encode, *rr.srw_setnameIdleTime );
1006 if (start > rr.hits)
1008 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1009 &srw_res->num_diagnostics,
1010 YAZ_SRW_FIRST_RECORD_POSITION_OUT_OF_RANGE, 0);
1015 int packing = Z_SRW_recordPacking_string;
1016 if (start + number > rr.hits)
1017 number = rr.hits - start + 1;
1018 if (srw_req->recordPacking){
1019 if (!strcmp(srw_req->recordPacking, "xml"))
1020 packing = Z_SRW_recordPacking_XML;
1021 if (!strcmp(srw_req->recordPacking, "url"))
1022 packing = Z_SRW_recordPacking_URL;
1024 srw_res->records = (Z_SRW_record *)
1025 odr_malloc(assoc->encode,
1026 number * sizeof(*srw_res->records));
1028 srw_res->extra_records = (Z_SRW_extra_record **)
1029 odr_malloc(assoc->encode,
1030 number*sizeof(*srw_res->extra_records));
1032 for (i = 0; i<number; i++)
1036 srw_res->records[j].recordPacking = packing;
1037 srw_res->records[j].recordData_buf = 0;
1038 srw_res->extra_records[j] = 0;
1039 yaz_log(YLOG_DEBUG, "srw_bend_fetch %d", i+start);
1040 errcode = srw_bend_fetch(assoc, i+start, srw_req,
1041 srw_res->records + j);
1044 yaz_add_srw_diagnostic(assoc->encode,
1045 &srw_res->diagnostics,
1046 &srw_res->num_diagnostics,
1047 yaz_diag_bib1_to_srw (errcode),
1052 if (srw_res->records[j].recordData_buf)
1055 srw_res->num_records = j;
1057 srw_res->records = 0;
1065 const char *querystr = "?";
1066 const char *querytype = "?";
1067 WRBUF wr = wrbuf_alloc();
1069 switch (srw_req->query_type)
1071 case Z_SRW_query_type_cql:
1073 querystr = srw_req->query.cql;
1075 case Z_SRW_query_type_pqf:
1077 querystr = srw_req->query.pqf;
1080 wrbuf_printf(wr, "SRWSearch ");
1081 if (srw_res->num_diagnostics)
1082 wrbuf_printf(wr, "ERROR %s", srw_res->diagnostics[0].uri);
1083 else if (*http_code != 200)
1084 wrbuf_printf(wr, "ERROR info:http/%d", *http_code);
1085 else if (srw_res->numberOfRecords)
1087 wrbuf_printf(wr, "OK %d",
1088 (srw_res->numberOfRecords ?
1089 *srw_res->numberOfRecords : 0));
1091 wrbuf_printf(wr, " %s %d+%d",
1092 (srw_res->resultSetId ?
1093 srw_res->resultSetId : "-"),
1094 (srw_req->startRecord ? *srw_req->startRecord : 1),
1095 srw_res->num_records);
1096 yaz_log(log_request, "%s %s: %s", wrbuf_buf(wr), querytype, querystr);
1101 static char *srw_bend_explain_default(void *handle, bend_explain_rr *rr)
1104 xmlNodePtr ptr = rr->server_node_ptr;
1107 for (ptr = ptr->children; ptr; ptr = ptr->next)
1109 if (ptr->type != XML_ELEMENT_NODE)
1111 if (!strcmp((const char *) ptr->name, "explain"))
1114 xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
1118 ptr = xmlCopyNode(ptr, 1);
1120 xmlDocSetRootElement(doc, ptr);
1122 xmlDocDumpMemory(doc, &buf_out, &len);
1123 content = (char*) odr_malloc(rr->stream, 1+len);
1124 memcpy(content, buf_out, len);
1125 content[len] = '\0';
1129 rr->explain_buf = content;
1137 static void srw_bend_explain(association *assoc, request *req,
1139 Z_SRW_explainResponse *srw_res,
1142 Z_SRW_explainRequest *srw_req = sr->u.explain_request;
1143 yaz_log(log_requestdetail, "Got SRW ExplainRequest");
1145 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1150 rr.stream = assoc->encode;
1151 rr.decode = assoc->decode;
1152 rr.print = assoc->print;
1154 rr.database = srw_req->database;
1156 rr.server_node_ptr = assoc->server->server_node_ptr;
1158 rr.server_node_ptr = 0;
1159 rr.schema = "http://explain.z3950.org/dtd/2.0/";
1160 if (assoc->init->bend_explain)
1161 (*assoc->init->bend_explain)(assoc->backend, &rr);
1163 srw_bend_explain_default(assoc->backend, &rr);
1167 int packing = Z_SRW_recordPacking_string;
1168 if (srw_req->recordPacking)
1170 if (!strcmp(srw_req->recordPacking, "xml"))
1171 packing = Z_SRW_recordPacking_XML;
1172 else if (!strcmp(srw_req->recordPacking, "url"))
1173 packing = Z_SRW_recordPacking_URL;
1175 srw_res->record.recordSchema = rr.schema;
1176 srw_res->record.recordPacking = packing;
1177 srw_res->record.recordData_buf = rr.explain_buf;
1178 srw_res->record.recordData_len = strlen(rr.explain_buf);
1179 srw_res->record.recordPosition = 0;
1185 static void srw_bend_scan(association *assoc, request *req,
1187 Z_SRW_scanResponse *srw_res,
1190 Z_SRW_scanRequest *srw_req = sr->u.scan_request;
1191 yaz_log(log_requestdetail, "Got SRW ScanRequest");
1194 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1195 if (srw_res->num_diagnostics == 0 && assoc->init)
1197 struct scan_entry *save_entries;
1199 bend_scan_rr *bsrr = (bend_scan_rr *)
1200 odr_malloc (assoc->encode, sizeof(*bsrr));
1201 bsrr->num_bases = 1;
1202 bsrr->basenames = &srw_req->database;
1204 bsrr->num_entries = srw_req->maximumTerms ?
1205 *srw_req->maximumTerms : 10;
1206 bsrr->term_position = srw_req->responsePosition ?
1207 *srw_req->responsePosition : 1;
1210 bsrr->errstring = 0;
1211 bsrr->referenceId = 0;
1212 bsrr->stream = assoc->encode;
1213 bsrr->print = assoc->print;
1214 bsrr->step_size = odr_intdup(assoc->decode, 0);
1217 if (bsrr->num_entries > 0)
1220 bsrr->entries = odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
1222 for (i = 0; i<bsrr->num_entries; i++)
1224 bsrr->entries[i].term = 0;
1225 bsrr->entries[i].occurrences = 0;
1226 bsrr->entries[i].errcode = 0;
1227 bsrr->entries[i].errstring = 0;
1228 bsrr->entries[i].display_term = 0;
1231 save_entries = bsrr->entries; /* save it so we can compare later */
1233 if (srw_req->query_type == Z_SRW_query_type_pqf &&
1234 assoc->init->bend_scan)
1236 Odr_oid *scan_attributeSet = 0;
1238 YAZ_PQF_Parser pqf_parser = yaz_pqf_create();
1240 bsrr->term = yaz_pqf_scan(pqf_parser, assoc->decode,
1242 srw_req->scanClause.pqf);
1243 if (scan_attributeSet &&
1244 (attset = oid_getentbyoid(scan_attributeSet)) &&
1245 (attset->oclass == CLASS_ATTSET ||
1246 attset->oclass == CLASS_GENERAL))
1247 bsrr->attributeset = attset->value;
1249 bsrr->attributeset = VAL_NONE;
1250 yaz_pqf_destroy(pqf_parser);
1251 bsrr->scanClause = 0;
1252 ((int (*)(void *, bend_scan_rr *))
1253 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1255 else if (srw_req->query_type == Z_SRW_query_type_cql
1256 && assoc->init->bend_scan && assoc->server
1257 && assoc->server->cql_transform)
1260 bsrr->scanClause = 0;
1261 bsrr->attributeset = VAL_NONE;
1262 bsrr->term = odr_malloc(assoc->decode, sizeof(*bsrr->term));
1263 srw_error = cql2pqf_scan(assoc->encode,
1264 srw_req->scanClause.cql,
1265 assoc->server->cql_transform,
1268 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1269 &srw_res->num_diagnostics,
1273 ((int (*)(void *, bend_scan_rr *))
1274 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1277 else if (srw_req->query_type == Z_SRW_query_type_cql
1278 && assoc->init->bend_srw_scan)
1281 bsrr->attributeset = VAL_NONE;
1282 bsrr->scanClause = srw_req->scanClause.cql;
1283 ((int (*)(void *, bend_scan_rr *))
1284 (*assoc->init->bend_srw_scan))(assoc->backend, bsrr);
1288 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1289 &srw_res->num_diagnostics,
1290 YAZ_SRW_UNSUPP_OPERATION, "scan");
1295 if (bsrr->errcode == YAZ_BIB1_DATABASE_UNAVAILABLE)
1300 srw_error = yaz_diag_bib1_to_srw (bsrr->errcode);
1302 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1303 &srw_res->num_diagnostics,
1304 srw_error, bsrr->errstring);
1306 else if (srw_res->num_diagnostics == 0 && bsrr->num_entries)
1309 srw_res->terms = (Z_SRW_scanTerm*)
1310 odr_malloc(assoc->encode, sizeof(*srw_res->terms) *
1313 srw_res->num_terms = bsrr->num_entries;
1314 for (i = 0; i<bsrr->num_entries; i++)
1316 Z_SRW_scanTerm *t = srw_res->terms + i;
1317 t->value = odr_strdup(assoc->encode, bsrr->entries[i].term);
1318 t->numberOfRecords =
1319 odr_intdup(assoc->encode, bsrr->entries[i].occurrences);
1321 if (save_entries == bsrr->entries &&
1322 bsrr->entries[i].display_term)
1324 /* the entries was _not_ set by the handler. So it's
1325 safe to test for new member display_term. It is
1328 t->displayTerm = odr_strdup(assoc->encode,
1329 bsrr->entries[i].display_term);
1337 WRBUF wr = wrbuf_alloc();
1338 const char *querytype = 0;
1339 const char *querystr = 0;
1341 switch(srw_req->query_type)
1343 case Z_SRW_query_type_pqf:
1345 querystr = srw_req->scanClause.pqf;
1347 case Z_SRW_query_type_cql:
1349 querystr = srw_req->scanClause.cql;
1352 querytype = "Unknown";
1355 wrbuf_printf(wr, "SRWScan %d+%d",
1356 (srw_req->responsePosition ?
1357 *srw_req->responsePosition : 1),
1358 (srw_req->maximumTerms ?
1359 *srw_req->maximumTerms : 1));
1360 if (srw_res->num_diagnostics)
1361 wrbuf_printf(wr, " ERROR %s", srw_res->diagnostics[0].uri);
1363 wrbuf_printf(wr, " OK -");
1364 wrbuf_printf(wr, " %s: %s", querytype, querystr);
1365 yaz_log(log_request, "%s", wrbuf_buf(wr) );
1371 static void srw_bend_update(association *assoc, request *req,
1373 Z_SRW_updateResponse *srw_res,
1376 Z_SRW_updateRequest *srw_req = sr->u.update_request;
1377 yaz_log(YLOG_DEBUG, "Got SRW UpdateRequest");
1378 yaz_log(YLOG_DEBUG, "num_diag = %d", srw_res->num_diagnostics );
1380 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1385 rr.stream = assoc->encode;
1386 rr.print = assoc->print;
1388 rr.basenames = &srw_req->database;
1389 rr.operation = srw_req->operation;
1390 rr.operation_status = "failed";
1392 rr.record_version = 0;
1393 rr.record_checksum = 0;
1394 rr.record_old_version = 0;
1395 rr.record_packing = "xml";
1396 rr.record_schema = 0;
1398 rr.request_extra_record = 0;
1399 rr.response_extra_record = 0;
1400 rr.extra_request_data = 0;
1401 rr.extra_response_data = 0;
1405 yaz_log(YLOG_DEBUG, "basename = %s", rr.basenames[0] );
1406 yaz_log(YLOG_DEBUG, "Operation = %s", rr.operation );
1407 if ( !strcmp( rr.operation, "delete" ) ){
1408 if ( !srw_req->recordId ){
1409 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1410 &srw_res->num_diagnostics,
1414 rr.record_id = srw_req->recordId;
1416 if ( !srw_req->recordVersion ){
1417 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1418 &srw_res->num_diagnostics,
1419 7, "recordVersion" );
1422 rr.record_version = odr_strdup( assoc->encode,
1423 srw_req->recordVersion );
1426 if ( srw_req->recordOldVersion ){
1427 rr.record_old_version = odr_strdup(assoc->encode,
1428 srw_req->recordOldVersion );
1430 if ( srw_req->extraRequestData ){
1431 rr.extra_request_data = odr_strdup(assoc->encode,
1432 srw_req->extraRequestData );
1435 else if ( !strcmp( rr.operation, "replace" ) ){
1436 if ( !srw_req->recordId ){
1437 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1438 &srw_res->num_diagnostics,
1442 rr.record_id = srw_req->recordId;
1444 if ( srw_req->record.recordSchema == 0 ){
1445 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1446 &srw_res->num_diagnostics,
1447 7, "recordSchema" );
1450 rr.record_schema = odr_strdup(assoc->encode,
1451 srw_req->record.recordSchema );
1453 switch (srw_req->record.recordPacking)
1455 case Z_SRW_recordPacking_string:
1456 rr.record_packing = "string";
1458 case Z_SRW_recordPacking_XML:
1459 rr.record_packing = "xml";
1461 case Z_SRW_recordPacking_URL:
1462 rr.record_packing = "url";
1465 if ( srw_req->record.recordData_len ){
1466 rr.record_data = odr_strdupn(assoc->encode,
1467 srw_req->record.recordData_buf,
1468 srw_req->record.recordData_len );
1469 rr.request_extra_record = srw_req->extra_record;
1472 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1473 &srw_res->num_diagnostics,
1476 if (srw_req->extraRequestData)
1477 rr.extra_request_data = odr_strdup(assoc->encode,
1478 srw_req->extraRequestData );
1480 else if ( !strcmp( rr.operation, "insert" ) )
1482 if ( srw_req->record.recordSchema == 0 ){
1483 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1484 &srw_res->num_diagnostics,
1485 7, "recordSchema" );
1488 rr.record_schema = odr_strdup(assoc->encode,
1489 srw_req->record.recordSchema);
1491 switch (srw_req->record.recordPacking)
1493 case Z_SRW_recordPacking_string:
1494 rr.record_packing = "string";
1496 case Z_SRW_recordPacking_XML:
1497 rr.record_packing = "xml";
1499 case Z_SRW_recordPacking_URL:
1500 rr.record_packing = "url";
1504 if (srw_req->record.recordData_len)
1506 rr.record_data = odr_strdupn(assoc->encode,
1507 srw_req->record.recordData_buf,
1508 srw_req->record.recordData_len );
1509 rr.request_extra_record = srw_req->extra_record;
1512 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1513 &srw_res->num_diagnostics,
1515 if ( srw_req->extraRequestData )
1516 rr.extra_request_data = odr_strdup(assoc->encode,
1517 srw_req->extraRequestData );
1519 if (srw_res->num_diagnostics == 0)
1521 if ( assoc->init->bend_srw_update)
1522 (*assoc->init->bend_srw_update)(assoc->backend, &rr);
1524 yaz_log( YLOG_WARN, "Got No Update function!");
1529 yaz_add_srw_diagnostic(assoc->encode,
1530 &srw_res->diagnostics,
1531 &srw_res->num_diagnostics,
1532 rr.errcode, rr.errstring);
1533 srw_res->recordId = rr.record_id;
1534 srw_res->operationStatus = rr.operation_status;
1535 srw_res->recordVersion = rr.record_version;
1536 srw_res->recordChecksum = rr.record_checksum;
1537 srw_res->extraResponseData = rr.extra_response_data;
1538 srw_res->record.recordPosition = 0;
1539 if (srw_res->num_diagnostics == 0 && rr.record_data)
1541 srw_res->record.recordSchema = rr.record_schema;
1542 srw_res->record.recordPacking = srw_req->record.recordPacking;
1543 srw_res->record.recordData_buf = rr.record_data;
1544 srw_res->record.recordData_len = strlen(rr.record_data);
1545 srw_res->extra_record = rr.response_extra_record;
1549 srw_res->record.recordData_len = 0;
1554 /* check if path is OK (1); BAD (0) */
1555 static int check_path(const char *path)
1559 if (strstr(path, ".."))
1564 static char *read_file(const char *fname, ODR o, int *sz)
1567 FILE *inf = fopen(fname, "rb");
1571 fseek(inf, 0L, SEEK_END);
1574 buf = odr_malloc(o, *sz);
1575 fread(buf, 1, *sz, inf);
1580 static void process_http_request(association *assoc, request *req)
1582 Z_HTTP_Request *hreq = req->gdu_request->u.HTTP_Request;
1583 ODR o = assoc->encode;
1584 int r = 2; /* 2=NOT TAKEN, 1=TAKEN, 0=SOAP TAKEN */
1586 Z_SOAP *soap_package = 0;
1589 Z_HTTP_Response *hres = 0;
1591 const char *stylesheet = 0; /* for now .. set later */
1592 Z_SRW_diagnostic *diagnostic = 0;
1593 int num_diagnostic = 0;
1594 const char *host = z_HTTP_header_lookup(hreq->headers, "Host");
1596 if (!control_association(assoc, host, 0))
1598 p = z_get_HTTP_Response(o, 404);
1601 if (r == 2 && assoc->server && assoc->server->docpath
1602 && hreq->path[0] == '/'
1604 /* check if path is a proper prefix of documentroot */
1605 strncmp(hreq->path+1, assoc->server->docpath,
1606 strlen(assoc->server->docpath))
1609 if (!check_path(hreq->path))
1611 yaz_log(YLOG_LOG, "File %s access forbidden", hreq->path+1);
1612 p = z_get_HTTP_Response(o, 404);
1616 int content_size = 0;
1617 char *content_buf = read_file(hreq->path+1, o, &content_size);
1620 yaz_log(YLOG_LOG, "File %s not found", hreq->path+1);
1621 p = z_get_HTTP_Response(o, 404);
1625 const char *ctype = 0;
1626 yaz_mime_types types = yaz_mime_types_create();
1628 yaz_mime_types_add(types, "xsl", "application/xml");
1629 yaz_mime_types_add(types, "xml", "application/xml");
1630 yaz_mime_types_add(types, "css", "text/css");
1631 yaz_mime_types_add(types, "html", "text/html");
1632 yaz_mime_types_add(types, "htm", "text/html");
1633 yaz_mime_types_add(types, "txt", "text/plain");
1634 yaz_mime_types_add(types, "js", "application/x-javascript");
1636 yaz_mime_types_add(types, "gif", "image/gif");
1637 yaz_mime_types_add(types, "png", "image/png");
1638 yaz_mime_types_add(types, "jpg", "image/jpeg");
1639 yaz_mime_types_add(types, "jpeg", "image/jpeg");
1641 ctype = yaz_mime_lookup_fname(types, hreq->path);
1644 yaz_log(YLOG_LOG, "No mime type for %s", hreq->path+1);
1645 p = z_get_HTTP_Response(o, 404);
1649 p = z_get_HTTP_Response(o, 200);
1650 hres = p->u.HTTP_Response;
1651 hres->content_buf = content_buf;
1652 hres->content_len = content_size;
1653 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1655 yaz_mime_types_destroy(types);
1663 r = yaz_srw_decode(hreq, &sr, &soap_package, assoc->decode, &charset);
1664 yaz_log(YLOG_DEBUG, "yaz_srw_decode returned %d", r);
1666 if (r == 2) /* not taken */
1668 r = yaz_sru_decode(hreq, &sr, &soap_package, assoc->decode, &charset,
1669 &diagnostic, &num_diagnostic);
1670 yaz_log(YLOG_DEBUG, "yaz_sru_decode returned %d", r);
1672 if (r == 0) /* decode SRW/SRU OK .. */
1674 int http_code = 200;
1675 if (sr->which == Z_SRW_searchRetrieve_request)
1678 yaz_srw_get(assoc->encode, Z_SRW_searchRetrieve_response);
1680 stylesheet = sr->u.request->stylesheet;
1683 res->u.response->diagnostics = diagnostic;
1684 res->u.response->num_diagnostics = num_diagnostic;
1688 srw_bend_search(assoc, req, sr, res->u.response,
1691 if (http_code == 200)
1692 soap_package->u.generic->p = res;
1694 else if (sr->which == Z_SRW_explain_request)
1696 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_explain_response);
1697 stylesheet = sr->u.explain_request->stylesheet;
1700 res->u.explain_response->diagnostics = diagnostic;
1701 res->u.explain_response->num_diagnostics = num_diagnostic;
1703 srw_bend_explain(assoc, req, sr,
1704 res->u.explain_response, &http_code);
1705 if (http_code == 200)
1706 soap_package->u.generic->p = res;
1708 else if (sr->which == Z_SRW_scan_request)
1710 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_scan_response);
1711 stylesheet = sr->u.scan_request->stylesheet;
1714 res->u.scan_response->diagnostics = diagnostic;
1715 res->u.scan_response->num_diagnostics = num_diagnostic;
1717 srw_bend_scan(assoc, req, sr,
1718 res->u.scan_response, &http_code);
1719 if (http_code == 200)
1720 soap_package->u.generic->p = res;
1722 else if (sr->which == Z_SRW_update_request)
1724 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_update_response);
1725 yaz_log(YLOG_DEBUG, "handling SRW UpdateRequest");
1728 res->u.update_response->diagnostics = diagnostic;
1729 res->u.update_response->num_diagnostics = num_diagnostic;
1731 yaz_log(YLOG_DEBUG, "num_diag = %d", res->u.update_response->num_diagnostics );
1732 srw_bend_update(assoc, req, sr,
1733 res->u.update_response, &http_code);
1734 if (http_code == 200)
1735 soap_package->u.generic->p = res;
1739 yaz_log(log_request, "SOAP ERROR");
1740 /* FIXME - what error, what query */
1742 z_soap_error(assoc->encode, soap_package,
1743 "SOAP-ENV:Client", "Bad method", 0);
1745 if (http_code == 200 || http_code == 500)
1747 static Z_SOAP_Handler soap_handlers[4] = {
1749 {"http://www.loc.gov/zing/srw/", 0,
1750 (Z_SOAP_fun) yaz_srw_codec},
1751 {"http://www.loc.gov/zing/srw/v1.0/", 0,
1752 (Z_SOAP_fun) yaz_srw_codec},
1753 {"http://www.loc.gov/zing/srw/update/", 0,
1754 (Z_SOAP_fun) yaz_ucp_codec},
1760 p = z_get_HTTP_Response(o, 200);
1761 hres = p->u.HTTP_Response;
1763 if (!stylesheet && assoc->server)
1764 stylesheet = assoc->server->stylesheet;
1766 /* empty stylesheet means NO stylesheet */
1767 if (stylesheet && *stylesheet == '\0')
1770 ret = z_soap_codec_enc_xsl(assoc->encode, &soap_package,
1771 &hres->content_buf, &hres->content_len,
1772 soap_handlers, charset, stylesheet);
1773 hres->code = http_code;
1775 strcpy(ctype, "text/xml");
1778 strcat(ctype, "; charset=");
1779 strcat(ctype, charset);
1781 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1784 p = z_get_HTTP_Response(o, http_code);
1788 p = z_get_HTTP_Response(o, 500);
1789 hres = p->u.HTTP_Response;
1790 if (!strcmp(hreq->version, "1.0"))
1792 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1793 if (v && !strcmp(v, "Keep-Alive"))
1797 hres->version = "1.0";
1801 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1802 if (v && !strcmp(v, "close"))
1806 hres->version = "1.1";
1810 z_HTTP_header_add(o, &hres->headers, "Connection", "close");
1811 assoc->state = ASSOC_DEAD;
1812 assoc->cs_get_mask = 0;
1817 const char *alive = z_HTTP_header_lookup(hreq->headers, "Keep-Alive");
1819 if (alive && isdigit(*(const unsigned char *) alive))
1823 if (t < 0 || t > 3600)
1825 iochan_settimeout(assoc->client_chan,t);
1826 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1828 process_gdu_response(assoc, req, p);
1831 static void process_gdu_request(association *assoc, request *req)
1833 if (req->gdu_request->which == Z_GDU_Z3950)
1836 req->apdu_request = req->gdu_request->u.z3950;
1837 if (process_z_request(assoc, req, &msg) < 0)
1838 do_close_req(assoc, Z_Close_systemProblem, msg, req);
1840 else if (req->gdu_request->which == Z_GDU_HTTP_Request)
1841 process_http_request(assoc, req);
1844 do_close_req(assoc, Z_Close_systemProblem, "bad protocol packet", req);
1849 * Initiate request processing.
1851 static int process_z_request(association *assoc, request *req, char **msg)
1857 *msg = "Unknown Error";
1858 assert(req && req->state == REQUEST_IDLE);
1859 if (req->apdu_request->which != Z_APDU_initRequest && !assoc->init)
1861 *msg = "Missing InitRequest";
1864 switch (req->apdu_request->which)
1866 case Z_APDU_initRequest:
1867 res = process_initRequest(assoc, req); break;
1868 case Z_APDU_searchRequest:
1869 res = process_searchRequest(assoc, req, &fd); break;
1870 case Z_APDU_presentRequest:
1871 res = process_presentRequest(assoc, req, &fd); break;
1872 case Z_APDU_scanRequest:
1873 if (assoc->init->bend_scan)
1874 res = process_scanRequest(assoc, req, &fd);
1877 *msg = "Cannot handle Scan APDU";
1881 case Z_APDU_extendedServicesRequest:
1882 if (assoc->init->bend_esrequest)
1883 res = process_ESRequest(assoc, req, &fd);
1886 *msg = "Cannot handle Extended Services APDU";
1890 case Z_APDU_sortRequest:
1891 if (assoc->init->bend_sort)
1892 res = process_sortRequest(assoc, req, &fd);
1895 *msg = "Cannot handle Sort APDU";
1900 process_close(assoc, req);
1902 case Z_APDU_deleteResultSetRequest:
1903 if (assoc->init->bend_delete)
1904 res = process_deleteRequest(assoc, req, &fd);
1907 *msg = "Cannot handle Delete APDU";
1911 case Z_APDU_segmentRequest:
1912 if (assoc->init->bend_segment)
1914 res = process_segmentRequest (assoc, req);
1918 *msg = "Cannot handle Segment APDU";
1922 case Z_APDU_triggerResourceControlRequest:
1925 *msg = "Bad APDU received";
1930 yaz_log(YLOG_DEBUG, " result immediately available");
1931 retval = process_z_response(assoc, req, res);
1935 yaz_log(YLOG_DEBUG, " result unavailble");
1938 else /* no result yet - one will be provided later */
1942 /* Set up an I/O handler for the fd supplied by the backend */
1944 yaz_log(YLOG_DEBUG, " establishing handler for result");
1945 req->state = REQUEST_PENDING;
1946 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT, 0)))
1948 iochan_setdata(chan, assoc);
1955 * Handle message from the backend.
1957 void backend_response(IOCHAN i, int event)
1959 association *assoc = (association *)iochan_getdata(i);
1960 request *req = request_head(&assoc->incoming);
1964 yaz_log(YLOG_DEBUG, "backend_response");
1965 assert(assoc && req && req->state != REQUEST_IDLE);
1966 /* determine what it is we're waiting for */
1967 switch (req->apdu_request->which)
1969 case Z_APDU_searchRequest:
1970 res = response_searchRequest(assoc, req, 0, &fd); break;
1972 case Z_APDU_presentRequest:
1973 res = response_presentRequest(assoc, req, 0, &fd); break;
1974 case Z_APDU_scanRequest:
1975 res = response_scanRequest(assoc, req, 0, &fd); break;
1978 yaz_log(YLOG_FATAL, "Serious programmer's lapse or bug");
1981 if ((res && process_z_response(assoc, req, res) < 0) || fd < 0)
1983 yaz_log(YLOG_WARN, "Fatal error when talking to backend");
1984 do_close(assoc, Z_Close_systemProblem, 0);
1988 else if (!res) /* no result yet - try again later */
1990 yaz_log(YLOG_DEBUG, " no result yet");
1991 iochan_setfd(i, fd); /* in case fd has changed */
1996 * Encode response, and transfer the request structure to the outgoing queue.
1998 static int process_gdu_response(association *assoc, request *req, Z_GDU *res)
2000 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
2004 if (!z_GDU(assoc->print, &res, 0, 0))
2005 yaz_log(YLOG_WARN, "ODR print error: %s",
2006 odr_errmsg(odr_geterror(assoc->print)));
2007 odr_reset(assoc->print);
2009 if (!z_GDU(assoc->encode, &res, 0, 0))
2011 yaz_log(YLOG_WARN, "ODR error when encoding PDU: %s [element %s]",
2012 odr_errmsg(odr_geterror(assoc->decode)),
2013 odr_getelement(assoc->decode));
2016 req->response = odr_getbuf(assoc->encode, &req->len_response,
2017 &req->size_response);
2018 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
2019 odr_reset(assoc->encode);
2020 req->state = REQUEST_IDLE;
2021 request_enq(&assoc->outgoing, req);
2022 /* turn the work over to the ir_session handler */
2023 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
2024 assoc->cs_put_mask = EVENT_OUTPUT;
2025 /* Is there more work to be done? give that to the input handler too */
2027 if (request_head(&assoc->incoming))
2029 yaz_log (YLOG_DEBUG, "more work to be done");
2030 iochan_setevent(assoc->client_chan, EVENT_WORK);
2037 * Encode response, and transfer the request structure to the outgoing queue.
2039 static int process_z_response(association *assoc, request *req, Z_APDU *res)
2041 Z_GDU *gres = (Z_GDU *) odr_malloc(assoc->encode, sizeof(*res));
2042 gres->which = Z_GDU_Z3950;
2043 gres->u.z3950 = res;
2045 return process_gdu_response(assoc, req, gres);
2048 static char *get_vhost(Z_OtherInformation *otherInfo)
2050 return yaz_oi_get_string_oidval(&otherInfo, VAL_PROXY, 1, 0);
2054 * Handle init request.
2055 * At the moment, we don't check the options
2056 * anywhere else in the code - we just try not to do anything that would
2057 * break a naive client. We'll toss 'em into the association block when
2058 * we need them there.
2060 static Z_APDU *process_initRequest(association *assoc, request *reqb)
2062 Z_InitRequest *req = reqb->apdu_request->u.initRequest;
2063 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
2064 Z_InitResponse *resp = apdu->u.initResponse;
2065 bend_initresult *binitres;
2068 statserv_options_block *cb = 0; /* by default no control for backend */
2070 if (control_association(assoc, get_vhost(req->otherInfo), 1))
2071 cb = statserv_getcontrol(); /* got control block for backend */
2073 if (cb && assoc->backend)
2074 (*cb->bend_close)(assoc->backend);
2076 yaz_log(log_requestdetail, "Got initRequest");
2077 if (req->implementationId)
2078 yaz_log(log_requestdetail, "Id: %s",
2079 req->implementationId);
2080 if (req->implementationName)
2081 yaz_log(log_requestdetail, "Name: %s",
2082 req->implementationName);
2083 if (req->implementationVersion)
2084 yaz_log(log_requestdetail, "Version: %s",
2085 req->implementationVersion);
2087 assoc_init_reset(assoc);
2089 assoc->init->auth = req->idAuthentication;
2090 assoc->init->referenceId = req->referenceId;
2092 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
2094 Z_CharSetandLanguageNegotiation *negotiation =
2095 yaz_get_charneg_record (req->otherInfo);
2097 negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
2098 assoc->init->charneg_request = negotiation;
2104 if (req->implementationVersion)
2105 yaz_log(log_requestdetail, "Config: %s",
2108 iochan_settimeout(assoc->client_chan, cb->idle_timeout * 60);
2110 /* we have a backend control block, so call that init function */
2111 if (!(binitres = (*cb->bend_init)(assoc->init)))
2113 yaz_log(YLOG_WARN, "Bad response from backend.");
2116 assoc->backend = binitres->handle;
2120 /* no backend. return error */
2121 binitres = odr_malloc(assoc->encode, sizeof(*binitres));
2122 binitres->errstring = 0;
2123 binitres->errcode = YAZ_BIB1_PERMANENT_SYSTEM_ERROR;
2124 iochan_settimeout(assoc->client_chan, 10);
2126 if ((assoc->init->bend_sort))
2127 yaz_log (YLOG_DEBUG, "Sort handler installed");
2128 if ((assoc->init->bend_search))
2129 yaz_log (YLOG_DEBUG, "Search handler installed");
2130 if ((assoc->init->bend_present))
2131 yaz_log (YLOG_DEBUG, "Present handler installed");
2132 if ((assoc->init->bend_esrequest))
2133 yaz_log (YLOG_DEBUG, "ESRequest handler installed");
2134 if ((assoc->init->bend_delete))
2135 yaz_log (YLOG_DEBUG, "Delete handler installed");
2136 if ((assoc->init->bend_scan))
2137 yaz_log (YLOG_DEBUG, "Scan handler installed");
2138 if ((assoc->init->bend_segment))
2139 yaz_log (YLOG_DEBUG, "Segment handler installed");
2141 resp->referenceId = req->referenceId;
2143 /* let's tell the client what we can do */
2144 if (ODR_MASK_GET(req->options, Z_Options_search))
2146 ODR_MASK_SET(resp->options, Z_Options_search);
2147 strcat(options, "srch");
2149 if (ODR_MASK_GET(req->options, Z_Options_present))
2151 ODR_MASK_SET(resp->options, Z_Options_present);
2152 strcat(options, " prst");
2154 if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
2155 assoc->init->bend_delete)
2157 ODR_MASK_SET(resp->options, Z_Options_delSet);
2158 strcat(options, " del");
2160 if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
2161 assoc->init->bend_esrequest)
2163 ODR_MASK_SET(resp->options, Z_Options_extendedServices);
2164 strcat (options, " extendedServices");
2166 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
2168 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
2169 strcat(options, " namedresults");
2171 if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
2173 ODR_MASK_SET(resp->options, Z_Options_scan);
2174 strcat(options, " scan");
2176 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
2178 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
2179 strcat(options, " concurrop");
2181 if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
2183 ODR_MASK_SET(resp->options, Z_Options_sort);
2184 strcat(options, " sort");
2187 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel)
2188 && assoc->init->charneg_response)
2190 Z_OtherInformation **p;
2191 Z_OtherInformationUnit *p0;
2193 yaz_oi_APDU(apdu, &p);
2195 if ((p0=yaz_oi_update(p, assoc->encode, NULL, 0, 0))) {
2196 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
2198 p0->which = Z_OtherInfo_externallyDefinedInfo;
2199 p0->information.externallyDefinedInfo =
2200 assoc->init->charneg_response;
2202 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
2203 strcat(options, " negotiation");
2206 ODR_MASK_SET(resp->options, Z_Options_triggerResourceCtrl);
2208 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
2210 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
2211 assoc->version = 1; /* 1 & 2 are equivalent */
2213 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
2215 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
2218 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
2220 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
2224 yaz_log(log_requestdetail, "Negotiated to v%d: %s", assoc->version, options);
2225 assoc->maximumRecordSize = *req->maximumRecordSize;
2227 if (cb && assoc->maximumRecordSize > cb->maxrecordsize)
2228 assoc->maximumRecordSize = cb->maxrecordsize;
2229 assoc->preferredMessageSize = *req->preferredMessageSize;
2230 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
2231 assoc->preferredMessageSize = assoc->maximumRecordSize;
2233 resp->preferredMessageSize = &assoc->preferredMessageSize;
2234 resp->maximumRecordSize = &assoc->maximumRecordSize;
2236 resp->implementationId = odr_prepend(assoc->encode,
2237 assoc->init->implementation_id,
2238 resp->implementationId);
2240 resp->implementationName = odr_prepend(assoc->encode,
2241 assoc->init->implementation_name,
2242 odr_prepend(assoc->encode, "GFS", resp->implementationName));
2244 version = odr_strdup(assoc->encode, "$Revision: 1.77 $");
2245 if (strlen(version) > 10) /* check for unexpanded CVS strings */
2246 version[strlen(version)-2] = '\0';
2247 resp->implementationVersion = odr_prepend(assoc->encode,
2248 assoc->init->implementation_version,
2249 odr_prepend(assoc->encode, &version[11],
2250 resp->implementationVersion));
2252 if (binitres->errcode)
2254 assoc->state = ASSOC_DEAD;
2255 resp->userInformationField =
2256 init_diagnostics(assoc->encode, binitres->errcode,
2257 binitres->errstring);
2262 if (!req->idAuthentication)
2263 yaz_log(log_request, "Auth none");
2264 else if (req->idAuthentication->which == Z_IdAuthentication_open)
2266 const char *open = req->idAuthentication->u.open;
2267 const char *slash = strchr(open, '/');
2273 yaz_log(log_request, "Auth open %.*s", len, open);
2275 else if (req->idAuthentication->which == Z_IdAuthentication_idPass)
2277 const char *user = req->idAuthentication->u.idPass->userId;
2278 const char *group = req->idAuthentication->u.idPass->groupId;
2279 yaz_log(log_request, "Auth idPass %s %s",
2280 user ? user : "-", group ? group : "-");
2282 else if (req->idAuthentication->which
2283 == Z_IdAuthentication_anonymous)
2285 yaz_log(log_request, "Auth anonymous");
2289 yaz_log(log_request, "Auth other");
2294 WRBUF wr = wrbuf_alloc();
2295 wrbuf_printf(wr, "Init ");
2296 if (binitres->errcode)
2297 wrbuf_printf(wr, "ERROR %d", binitres->errcode);
2299 wrbuf_printf(wr, "OK -");
2300 wrbuf_printf(wr, " ID:%s Name:%s Version:%s",
2301 (req->implementationId ? req->implementationId :"-"),
2302 (req->implementationName ?
2303 req->implementationName : "-"),
2304 (req->implementationVersion ?
2305 req->implementationVersion : "-")
2307 yaz_log(log_request, "%s", wrbuf_buf(wr));
2314 * Set the specified `errcode' and `errstring' into a UserInfo-1
2315 * external to be returned to the client in accordance with Z35.90
2316 * Implementor Agreement 5 (Returning diagnostics in an InitResponse):
2317 * http://lcweb.loc.gov/z3950/agency/agree/initdiag.html
2319 static Z_External *init_diagnostics(ODR odr, int error, const char *addinfo)
2321 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2322 addinfo ? " -- " : "", addinfo ? addinfo : "");
2323 return zget_init_diagnostics(odr, error, addinfo);
2327 * nonsurrogate diagnostic record.
2329 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
2331 Z_Records *rec = (Z_Records *) odr_malloc (assoc->encode, sizeof(*rec));
2333 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2334 addinfo ? " -- " : "", addinfo ? addinfo : "");
2336 rec->which = Z_Records_NSD;
2337 rec->u.nonSurrogateDiagnostic = zget_DefaultDiagFormat(assoc->encode,
2343 * surrogate diagnostic.
2345 static Z_NamePlusRecord *surrogatediagrec(association *assoc,
2347 int error, const char *addinfo)
2349 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2350 addinfo ? " -- " : "", addinfo ? addinfo : "");
2351 return zget_surrogateDiagRec(assoc->encode, dbname, error, addinfo);
2354 static Z_Records *pack_records(association *a, char *setname, int start,
2355 int *num, Z_RecordComposition *comp,
2356 int *next, int *pres, oid_value format,
2357 Z_ReferenceId *referenceId,
2358 int *oid, int *errcode)
2360 int recno, total_length = 0, toget = *num, dumped_records = 0;
2361 Z_Records *records =
2362 (Z_Records *) odr_malloc (a->encode, sizeof(*records));
2363 Z_NamePlusRecordList *reclist =
2364 (Z_NamePlusRecordList *) odr_malloc (a->encode, sizeof(*reclist));
2365 Z_NamePlusRecord **list =
2366 (Z_NamePlusRecord **) odr_malloc (a->encode, sizeof(*list) * toget);
2368 records->which = Z_Records_DBOSD;
2369 records->u.databaseOrSurDiagnostics = reclist;
2370 reclist->num_records = 0;
2371 reclist->records = list;
2372 *pres = Z_PresentStatus_success;
2376 yaz_log(log_requestdetail, "Request to pack %d+%d %s", start, toget, setname);
2377 yaz_log(log_requestdetail, "pms=%d, mrs=%d", a->preferredMessageSize,
2378 a->maximumRecordSize);
2379 for (recno = start; reclist->num_records < toget; recno++)
2382 Z_NamePlusRecord *thisrec;
2383 int this_length = 0;
2385 * we get the number of bytes allocated on the stream before any
2386 * allocation done by the backend - this should give us a reasonable
2387 * idea of the total size of the data so far.
2389 total_length = odr_total(a->encode) - dumped_records;
2395 freq.last_in_set = 0;
2396 freq.setname = setname;
2397 freq.surrogate_flag = 0;
2398 freq.number = recno;
2400 freq.request_format = format;
2401 freq.request_format_raw = oid;
2402 freq.output_format = format;
2403 freq.output_format_raw = 0;
2404 freq.stream = a->encode;
2405 freq.print = a->print;
2406 freq.referenceId = referenceId;
2409 retrieve_fetch(a, &freq);
2411 *next = freq.last_in_set ? 0 : recno + 1;
2413 /* backend should be able to signal whether error is system-wide
2414 or only pertaining to current record */
2417 if (!freq.surrogate_flag)
2420 *pres = Z_PresentStatus_failure;
2421 /* for 'present request out of range',
2422 set addinfo to record position if not set */
2423 if (freq.errcode == YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE &&
2424 freq.errstring == 0)
2426 sprintf (s, "%d", recno);
2430 *errcode = freq.errcode;
2431 return diagrec(a, freq.errcode, freq.errstring);
2433 reclist->records[reclist->num_records] =
2434 surrogatediagrec(a, freq.basename, freq.errcode,
2436 reclist->num_records++;
2439 if (freq.record == 0) /* no error and no record ? */
2441 *next = 0; /* signal end-of-set and stop */
2445 this_length = freq.len;
2447 this_length = odr_total(a->encode) - total_length - dumped_records;
2448 yaz_log(YLOG_DEBUG, " fetched record, len=%d, total=%d dumped=%d",
2449 this_length, total_length, dumped_records);
2450 if (a->preferredMessageSize > 0 &&
2451 this_length + total_length > a->preferredMessageSize)
2453 /* record is small enough, really */
2454 if (this_length <= a->preferredMessageSize && recno > start)
2456 yaz_log(log_requestdetail, " Dropped last normal-sized record");
2457 *pres = Z_PresentStatus_partial_2;
2460 /* record can only be fetched by itself */
2461 if (this_length < a->maximumRecordSize)
2463 yaz_log(log_requestdetail, " Record > prefmsgsz");
2466 yaz_log(YLOG_DEBUG, " Dropped it");
2467 reclist->records[reclist->num_records] =
2468 surrogatediagrec(a, freq.basename, 16, 0);
2469 reclist->num_records++;
2470 dumped_records += this_length;
2474 else /* too big entirely */
2476 yaz_log(log_requestdetail, "Record > maxrcdsz this=%d max=%d",
2477 this_length, a->maximumRecordSize);
2478 reclist->records[reclist->num_records] =
2479 surrogatediagrec(a, freq.basename, 17, 0);
2480 reclist->num_records++;
2481 dumped_records += this_length;
2486 if (!(thisrec = (Z_NamePlusRecord *)
2487 odr_malloc(a->encode, sizeof(*thisrec))))
2490 thisrec->databaseName = odr_strdup(a->encode, freq.basename);
2492 thisrec->databaseName = 0;
2493 thisrec->which = Z_NamePlusRecord_databaseRecord;
2495 if (freq.output_format_raw)
2497 struct oident *ident = oid_getentbyoid(freq.output_format_raw);
2498 freq.output_format = ident->value;
2500 thisrec->u.databaseRecord = z_ext_record(a->encode, freq.output_format,
2501 freq.record, freq.len);
2502 if (!thisrec->u.databaseRecord)
2504 reclist->records[reclist->num_records] = thisrec;
2505 reclist->num_records++;
2507 *num = reclist->num_records;
2511 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
2514 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2515 bend_search_rr *bsrr =
2516 (bend_search_rr *)nmem_malloc (reqb->request_mem, sizeof(*bsrr));
2518 yaz_log(log_requestdetail, "Got SearchRequest.");
2520 bsrr->request = reqb;
2521 bsrr->association = assoc;
2522 bsrr->referenceId = req->referenceId;
2523 save_referenceId (reqb, bsrr->referenceId);
2524 bsrr->srw_sortKeys = 0;
2525 bsrr->srw_setname = 0;
2526 bsrr->srw_setnameIdleTime = 0;
2528 yaz_log (log_requestdetail, "ResultSet '%s'", req->resultSetName);
2529 if (req->databaseNames)
2532 for (i = 0; i < req->num_databaseNames; i++)
2533 yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
2536 yaz_log_zquery_level(log_requestdetail,req->query);
2538 if (assoc->init->bend_search)
2540 bsrr->setname = req->resultSetName;
2541 bsrr->replace_set = *req->replaceIndicator;
2542 bsrr->num_bases = req->num_databaseNames;
2543 bsrr->basenames = req->databaseNames;
2544 bsrr->query = req->query;
2545 bsrr->stream = assoc->encode;
2546 nmem_transfer(bsrr->stream->mem, reqb->request_mem);
2547 bsrr->decode = assoc->decode;
2548 bsrr->print = assoc->print;
2551 bsrr->errstring = NULL;
2552 bsrr->search_info = NULL;
2554 if (assoc->server && assoc->server->cql_transform
2555 && req->query->which == Z_Query_type_104
2556 && req->query->u.type_104->which == Z_External_CQL)
2558 /* have a CQL query and a CQL to PQF transform .. */
2560 cql2pqf(bsrr->stream, req->query->u.type_104->u.cql,
2561 assoc->server->cql_transform, bsrr->query);
2563 bsrr->errcode = yaz_diag_srw_to_bib1(srw_errcode);
2566 (assoc->init->bend_search)(assoc->backend, bsrr);
2567 if (!bsrr->request) /* backend not ready with the search response */
2568 return 0; /* should not be used any more */
2572 /* FIXME - make a diagnostic for it */
2573 yaz_log(YLOG_WARN,"Search not supported ?!?!");
2575 return response_searchRequest(assoc, reqb, bsrr, fd);
2578 int bend_searchresponse(void *handle, bend_search_rr *bsrr) {return 0;}
2581 * Prepare a searchresponse based on the backend results. We probably want
2582 * to look at making the fetching of records nonblocking as well, but
2583 * so far, we'll keep things simple.
2584 * If bsrt is null, that means we're called in response to a communications
2585 * event, and we'll have to get the response for ourselves.
2587 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
2588 bend_search_rr *bsrt, int *fd)
2590 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2591 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2592 Z_SearchResponse *resp = (Z_SearchResponse *)
2593 odr_malloc (assoc->encode, sizeof(*resp));
2594 int *nulint = odr_intdup (assoc->encode, 0);
2595 bool_t *sr = odr_intdup(assoc->encode, 1);
2596 int *next = odr_intdup(assoc->encode, 0);
2597 int *none = odr_intdup(assoc->encode, Z_SearchResponse_none);
2600 apdu->which = Z_APDU_searchResponse;
2601 apdu->u.searchResponse = resp;
2602 resp->referenceId = req->referenceId;
2603 resp->additionalSearchInfo = 0;
2604 resp->otherInfo = 0;
2606 if (!bsrt && !bend_searchresponse(assoc->backend, bsrt))
2608 yaz_log(YLOG_FATAL, "Bad result from backend");
2611 else if (bsrt->errcode)
2613 resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
2614 resp->resultCount = nulint;
2615 resp->numberOfRecordsReturned = nulint;
2616 resp->nextResultSetPosition = nulint;
2617 resp->searchStatus = nulint;
2618 resp->resultSetStatus = none;
2619 resp->presentStatus = 0;
2623 int *toget = odr_intdup(assoc->encode, 0);
2624 int *presst = odr_intdup(assoc->encode, 0);
2625 Z_RecordComposition comp, *compp = 0;
2627 yaz_log (log_requestdetail, "resultCount: %d", bsrt->hits);
2630 resp->resultCount = &bsrt->hits;
2632 comp.which = Z_RecordComp_simple;
2633 /* how many records does the user agent want, then? */
2634 if (bsrt->hits <= *req->smallSetUpperBound)
2636 *toget = bsrt->hits;
2637 if ((comp.u.simple = req->smallSetElementSetNames))
2640 else if (bsrt->hits < *req->largeSetLowerBound)
2642 *toget = *req->mediumSetPresentNumber;
2643 if (*toget > bsrt->hits)
2644 *toget = bsrt->hits;
2645 if ((comp.u.simple = req->mediumSetElementSetNames))
2651 if (*toget && !resp->records)
2656 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
2659 form = prefformat->value;
2660 resp->records = pack_records(assoc, req->resultSetName, 1,
2661 toget, compp, next, presst, form, req->referenceId,
2662 req->preferredRecordSyntax, NULL);
2665 resp->numberOfRecordsReturned = toget;
2666 returnedrecs = *toget;
2667 resp->nextResultSetPosition = next;
2668 resp->searchStatus = sr;
2669 resp->resultSetStatus = 0;
2670 resp->presentStatus = presst;
2674 if (*resp->resultCount)
2676 resp->numberOfRecordsReturned = nulint;
2677 resp->nextResultSetPosition = next;
2678 resp->searchStatus = sr;
2679 resp->resultSetStatus = 0;
2680 resp->presentStatus = 0;
2683 resp->additionalSearchInfo = bsrt->search_info;
2687 WRBUF wr = wrbuf_alloc();
2689 wrbuf_printf(wr, "ERROR %d", bsrt->errcode);
2691 wrbuf_printf(wr, "OK %d", bsrt->hits);
2692 wrbuf_printf(wr, " %s 1+%d ",
2693 req->resultSetName, returnedrecs);
2694 yaz_query_to_wrbuf(wr, req->query);
2696 yaz_log(log_request, "Search %s", wrbuf_buf(wr));
2703 * Maybe we got a little over-friendly when we designed bend_fetch to
2704 * get only one record at a time. Some backends can optimise multiple-record
2705 * fetches, and at any rate, there is some overhead involved in
2706 * all that selecting and hopping around. Problem is, of course, that the
2707 * frontend can't know ahead of time how many records it'll need to
2708 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
2709 * is downright lousy as a bulk data transfer protocol.
2711 * To start with, we'll do the fetching of records from the backend
2712 * in one operation: To save some trips in and out of the event-handler,
2713 * and to simplify the interface to pack_records. At any rate, asynch
2714 * operation is more fun in operations that have an unpredictable execution
2715 * speed - which is normally more true for search than for present.
2717 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
2720 Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
2724 Z_PresentResponse *resp;
2728 const char *errstring = 0;
2730 yaz_log(log_requestdetail, "Got PresentRequest.");
2732 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
2735 form = prefformat->value;
2736 resp = (Z_PresentResponse *)odr_malloc (assoc->encode, sizeof(*resp));
2738 resp->presentStatus = odr_intdup(assoc->encode, 0);
2739 if (assoc->init->bend_present)
2741 bend_present_rr *bprr = (bend_present_rr *)
2742 nmem_malloc (reqb->request_mem, sizeof(*bprr));
2743 bprr->setname = req->resultSetId;
2744 bprr->start = *req->resultSetStartPoint;
2745 bprr->number = *req->numberOfRecordsRequested;
2746 bprr->format = form;
2747 bprr->comp = req->recordComposition;
2748 bprr->referenceId = req->referenceId;
2749 bprr->stream = assoc->encode;
2750 bprr->print = assoc->print;
2751 bprr->request = reqb;
2752 bprr->association = assoc;
2754 bprr->errstring = NULL;
2755 (*assoc->init->bend_present)(assoc->backend, bprr);
2758 return 0; /* should not happen */
2761 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2762 *resp->presentStatus = Z_PresentStatus_failure;
2763 errcode = bprr->errcode;
2764 errstring = bprr->errstring;
2767 apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2768 next = odr_intdup(assoc->encode, 0);
2769 num = odr_intdup(assoc->encode, 0);
2771 apdu->which = Z_APDU_presentResponse;
2772 apdu->u.presentResponse = resp;
2773 resp->referenceId = req->referenceId;
2774 resp->otherInfo = 0;
2778 *num = *req->numberOfRecordsRequested;
2780 pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
2781 num, req->recordComposition, next,
2782 resp->presentStatus,
2783 form, req->referenceId, req->preferredRecordSyntax,
2788 WRBUF wr = wrbuf_alloc();
2789 wrbuf_printf(wr, "Present ");
2791 if (*resp->presentStatus == Z_PresentStatus_failure)
2792 wrbuf_printf(wr, "ERROR %d", errcode);
2793 else if (*resp->presentStatus == Z_PresentStatus_success)
2794 wrbuf_printf(wr, "OK -");
2796 wrbuf_printf(wr, "Partial %d", *resp->presentStatus);
2798 wrbuf_printf(wr, " %s %d+%d ",
2799 req->resultSetId, *req->resultSetStartPoint,
2800 *req->numberOfRecordsRequested);
2801 yaz_log(log_request, "%s", wrbuf_buf(wr) );
2806 resp->numberOfRecordsReturned = num;
2807 resp->nextResultSetPosition = next;
2813 * Scan was implemented rather in a hurry, and with support for only the basic
2814 * elements of the service in the backend API. Suggestions are welcome.
2816 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
2818 Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
2819 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2820 Z_ScanResponse *res = (Z_ScanResponse *)
2821 odr_malloc (assoc->encode, sizeof(*res));
2822 int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
2823 int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
2824 Z_ListEntries *ents = (Z_ListEntries *)
2825 odr_malloc (assoc->encode, sizeof(*ents));
2826 Z_DiagRecs *diagrecs_p = NULL;
2828 bend_scan_rr *bsrr = (bend_scan_rr *)
2829 odr_malloc (assoc->encode, sizeof(*bsrr));
2830 struct scan_entry *save_entries;
2832 yaz_log(log_requestdetail, "Got ScanRequest");
2834 apdu->which = Z_APDU_scanResponse;
2835 apdu->u.scanResponse = res;
2836 res->referenceId = req->referenceId;
2838 /* if step is absent, set it to 0 */
2839 res->stepSize = odr_intdup(assoc->encode, 0);
2841 *res->stepSize = *req->stepSize;
2843 res->scanStatus = scanStatus;
2844 res->numberOfEntriesReturned = numberOfEntriesReturned;
2845 res->positionOfTerm = 0;
2846 res->entries = ents;
2847 ents->num_entries = 0;
2848 ents->entries = NULL;
2849 ents->num_nonsurrogateDiagnostics = 0;
2850 ents->nonsurrogateDiagnostics = NULL;
2851 res->attributeSet = 0;
2854 if (req->databaseNames)
2857 for (i = 0; i < req->num_databaseNames; i++)
2858 yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
2860 bsrr->scanClause = 0;
2862 bsrr->errstring = 0;
2863 bsrr->num_bases = req->num_databaseNames;
2864 bsrr->basenames = req->databaseNames;
2865 bsrr->num_entries = *req->numberOfTermsRequested;
2866 bsrr->term = req->termListAndStartPoint;
2867 bsrr->referenceId = req->referenceId;
2868 bsrr->stream = assoc->encode;
2869 bsrr->print = assoc->print;
2870 bsrr->step_size = res->stepSize;
2872 /* For YAZ 2.0 and earlier it was the backend handler that
2873 initialized entries (member display_term did not exist)
2874 YAZ 2.0 and later sets 'entries' and initialize all members
2875 including 'display_term'. If YAZ 2.0 or later sees that
2876 entries was modified - we assume that it is an old handler and
2877 that 'display_term' is _not_ set.
2879 if (bsrr->num_entries > 0)
2882 bsrr->entries = odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
2884 for (i = 0; i<bsrr->num_entries; i++)
2886 bsrr->entries[i].term = 0;
2887 bsrr->entries[i].occurrences = 0;
2888 bsrr->entries[i].errcode = 0;
2889 bsrr->entries[i].errstring = 0;
2890 bsrr->entries[i].display_term = 0;
2893 save_entries = bsrr->entries; /* save it so we can compare later */
2895 if (req->attributeSet &&
2896 (attset = oid_getentbyoid(req->attributeSet)) &&
2897 (attset->oclass == CLASS_ATTSET || attset->oclass == CLASS_GENERAL))
2898 bsrr->attributeset = attset->value;
2900 bsrr->attributeset = VAL_NONE;
2901 log_scan_term_level (log_requestdetail, req->termListAndStartPoint,
2902 bsrr->attributeset);
2903 bsrr->term_position = req->preferredPositionInResponse ?
2904 *req->preferredPositionInResponse : 1;
2906 ((int (*)(void *, bend_scan_rr *))
2907 (*assoc->init->bend_scan))(assoc->backend, bsrr);
2910 diagrecs_p = zget_DiagRecs(assoc->encode,
2911 bsrr->errcode, bsrr->errstring);
2915 Z_Entry **tab = (Z_Entry **)
2916 odr_malloc (assoc->encode, sizeof(*tab) * bsrr->num_entries);
2918 if (bsrr->status == BEND_SCAN_PARTIAL)
2919 *scanStatus = Z_Scan_partial_5;
2921 *scanStatus = Z_Scan_success;
2922 ents->entries = tab;
2923 ents->num_entries = bsrr->num_entries;
2924 res->numberOfEntriesReturned = &ents->num_entries;
2925 res->positionOfTerm = &bsrr->term_position;
2926 for (i = 0; i < bsrr->num_entries; i++)
2932 tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
2933 if (bsrr->entries[i].occurrences >= 0)
2935 e->which = Z_Entry_termInfo;
2936 e->u.termInfo = t = (Z_TermInfo *)
2937 odr_malloc(assoc->encode, sizeof(*t));
2938 t->suggestedAttributes = 0;
2940 if (save_entries == bsrr->entries &&
2941 bsrr->entries[i].display_term)
2943 /* the entries was _not_ set by the handler. So it's
2944 safe to test for new member display_term. It is
2947 t->displayTerm = odr_strdup(assoc->encode,
2948 bsrr->entries[i].display_term);
2950 t->alternativeTerm = 0;
2951 t->byAttributes = 0;
2952 t->otherTermInfo = 0;
2953 t->globalOccurrences = &bsrr->entries[i].occurrences;
2954 t->term = (Z_Term *)
2955 odr_malloc(assoc->encode, sizeof(*t->term));
2956 t->term->which = Z_Term_general;
2957 t->term->u.general = o =
2958 (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
2959 o->buf = (unsigned char *)
2960 odr_malloc(assoc->encode, o->len = o->size =
2961 strlen(bsrr->entries[i].term));
2962 memcpy(o->buf, bsrr->entries[i].term, o->len);
2963 yaz_log(YLOG_DEBUG, " term #%d: '%s' (%d)", i,
2964 bsrr->entries[i].term, bsrr->entries[i].occurrences);
2968 Z_DiagRecs *drecs = zget_DiagRecs(assoc->encode,
2969 bsrr->entries[i].errcode,
2970 bsrr->entries[i].errstring);
2971 assert (drecs->num_diagRecs == 1);
2972 e->which = Z_Entry_surrogateDiagnostic;
2973 assert (drecs->diagRecs[0]);
2974 e->u.surrogateDiagnostic = drecs->diagRecs[0];
2980 ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
2981 ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
2985 WRBUF wr = wrbuf_alloc();
2987 wr_diag(wr, bsrr->errcode, bsrr->errstring);
2988 else if (*res->scanStatus == Z_Scan_success)
2989 wrbuf_printf(wr, "OK");
2991 wrbuf_printf(wr, "Partial");
2993 wrbuf_printf(wr, " %d+%d %d ",
2994 (req->preferredPositionInResponse ?
2995 *req->preferredPositionInResponse : 1),
2996 *req->numberOfTermsRequested,
2997 (res->stepSize ? *res->stepSize : 0));
2998 yaz_scan_to_wrbuf(wr, req->termListAndStartPoint,
2999 bsrr->attributeset);
3000 yaz_log(log_request, "Scan %s", wrbuf_buf(wr) );
3006 static Z_APDU *process_sortRequest(association *assoc, request *reqb,
3010 Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
3011 Z_SortResponse *res = (Z_SortResponse *)
3012 odr_malloc (assoc->encode, sizeof(*res));
3013 bend_sort_rr *bsrr = (bend_sort_rr *)
3014 odr_malloc (assoc->encode, sizeof(*bsrr));
3016 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
3018 yaz_log(log_requestdetail, "Got SortRequest.");
3020 bsrr->num_input_setnames = req->num_inputResultSetNames;
3021 for (i=0;i<req->num_inputResultSetNames;i++)
3022 yaz_log(log_requestdetail, "Input resultset: '%s'",
3023 req->inputResultSetNames[i]);
3024 bsrr->input_setnames = req->inputResultSetNames;
3025 bsrr->referenceId = req->referenceId;
3026 bsrr->output_setname = req->sortedResultSetName;
3027 yaz_log(log_requestdetail, "Output resultset: '%s'",
3028 req->sortedResultSetName);
3029 bsrr->sort_sequence = req->sortSequence;
3030 /*FIXME - dump those sequences too */
3031 bsrr->stream = assoc->encode;
3032 bsrr->print = assoc->print;
3034 bsrr->sort_status = Z_SortResponse_failure;
3036 bsrr->errstring = 0;
3038 (*assoc->init->bend_sort)(assoc->backend, bsrr);
3040 res->referenceId = bsrr->referenceId;
3041 res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
3042 res->resultSetStatus = 0;
3045 Z_DiagRecs *dr = zget_DiagRecs(assoc->encode,
3046 bsrr->errcode, bsrr->errstring);
3047 res->diagnostics = dr->diagRecs;
3048 res->num_diagnostics = dr->num_diagRecs;
3052 res->num_diagnostics = 0;
3053 res->diagnostics = 0;
3055 res->resultCount = 0;
3058 apdu->which = Z_APDU_sortResponse;
3059 apdu->u.sortResponse = res;
3062 WRBUF wr = wrbuf_alloc();
3063 wrbuf_printf(wr, "Sort ");
3065 wrbuf_printf(wr, " ERROR %d", bsrr->errcode);
3067 wrbuf_printf(wr, "OK -");
3068 wrbuf_printf(wr, " (");
3069 for (i = 0; i<req->num_inputResultSetNames; i++)
3072 wrbuf_printf(wr, ",");
3073 wrbuf_printf(wr, req->inputResultSetNames[i]);
3075 wrbuf_printf(wr, ")->%s ",req->sortedResultSetName);
3077 yaz_log(log_request, "%s", wrbuf_buf(wr) );
3083 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
3087 Z_DeleteResultSetRequest *req =
3088 reqb->apdu_request->u.deleteResultSetRequest;
3089 Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
3090 odr_malloc (assoc->encode, sizeof(*res));
3091 bend_delete_rr *bdrr = (bend_delete_rr *)
3092 odr_malloc (assoc->encode, sizeof(*bdrr));
3093 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
3095 yaz_log(log_requestdetail, "Got DeleteRequest.");
3097 bdrr->num_setnames = req->num_resultSetList;
3098 bdrr->setnames = req->resultSetList;
3099 for (i = 0; i<req->num_resultSetList; i++)
3100 yaz_log(log_requestdetail, "resultset: '%s'",
3101 req->resultSetList[i]);
3102 bdrr->stream = assoc->encode;
3103 bdrr->print = assoc->print;
3104 bdrr->function = *req->deleteFunction;
3105 bdrr->referenceId = req->referenceId;
3107 if (bdrr->num_setnames > 0)
3109 bdrr->statuses = (int*)
3110 odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
3111 bdrr->num_setnames);
3112 for (i = 0; i < bdrr->num_setnames; i++)
3113 bdrr->statuses[i] = 0;
3115 (*assoc->init->bend_delete)(assoc->backend, bdrr);
3117 res->referenceId = req->referenceId;
3119 res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
3121 res->deleteListStatuses = 0;
3122 if (bdrr->num_setnames > 0)
3125 res->deleteListStatuses = (Z_ListStatuses *)
3126 odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
3127 res->deleteListStatuses->num = bdrr->num_setnames;
3128 res->deleteListStatuses->elements =
3130 odr_malloc (assoc->encode,
3131 sizeof(*res->deleteListStatuses->elements) *
3132 bdrr->num_setnames);
3133 for (i = 0; i<bdrr->num_setnames; i++)
3135 res->deleteListStatuses->elements[i] =
3137 odr_malloc (assoc->encode,
3138 sizeof(**res->deleteListStatuses->elements));
3139 res->deleteListStatuses->elements[i]->status = bdrr->statuses+i;
3140 res->deleteListStatuses->elements[i]->id =
3141 odr_strdup (assoc->encode, bdrr->setnames[i]);
3144 res->numberNotDeleted = 0;
3145 res->bulkStatuses = 0;
3146 res->deleteMessage = 0;
3149 apdu->which = Z_APDU_deleteResultSetResponse;
3150 apdu->u.deleteResultSetResponse = res;
3153 WRBUF wr = wrbuf_alloc();
3154 wrbuf_printf(wr, "Delete ");
3155 if (bdrr->delete_status)
3156 wrbuf_printf(wr, "ERROR %d", bdrr->delete_status);
3158 wrbuf_printf(wr, "OK -");
3159 for (i = 0; i<req->num_resultSetList; i++)
3160 wrbuf_printf(wr, " %s ", req->resultSetList[i]);
3161 yaz_log(log_request, "%s", wrbuf_buf(wr) );
3167 static void process_close(association *assoc, request *reqb)
3169 Z_Close *req = reqb->apdu_request->u.close;
3170 static char *reasons[] =
3177 "securityViolation",
3184 yaz_log(log_requestdetail, "Got Close, reason %s, message %s",
3185 reasons[*req->closeReason], req->diagnosticInformation ?
3186 req->diagnosticInformation : "NULL");
3187 if (assoc->version < 3) /* to make do_force respond with close */
3189 do_close_req(assoc, Z_Close_finished,
3190 "Association terminated by client", reqb);
3191 yaz_log(log_request,"Close OK");
3194 void save_referenceId (request *reqb, Z_ReferenceId *refid)
3198 reqb->len_refid = refid->len;
3199 reqb->refid = (char *)nmem_malloc (reqb->request_mem, refid->len);
3200 memcpy (reqb->refid, refid->buf, refid->len);
3204 reqb->len_refid = 0;
3209 void bend_request_send (bend_association a, bend_request req, Z_APDU *res)
3211 process_z_response (a, req, res);
3214 bend_request bend_request_mk (bend_association a)
3216 request *nreq = request_get (&a->outgoing);
3217 nreq->request_mem = nmem_create ();
3221 Z_ReferenceId *bend_request_getid (ODR odr, bend_request req)
3226 id = (Odr_oct *)odr_malloc (odr, sizeof(*odr));
3227 id->buf = (unsigned char *)odr_malloc (odr, req->len_refid);
3228 id->len = id->size = req->len_refid;
3229 memcpy (id->buf, req->refid, req->len_refid);
3233 void bend_request_destroy (bend_request *req)
3235 nmem_destroy((*req)->request_mem);
3236 request_release(*req);
3240 int bend_backend_respond (bend_association a, bend_request req)
3244 r = process_z_request (a, req, &msg);
3246 yaz_log (YLOG_WARN, "%s", msg);
3250 void bend_request_setdata(bend_request r, void *p)
3255 void *bend_request_getdata(bend_request r)
3257 return r->clientData;
3260 static Z_APDU *process_segmentRequest (association *assoc, request *reqb)
3262 bend_segment_rr req;
3264 req.segment = reqb->apdu_request->u.segmentRequest;
3265 req.stream = assoc->encode;
3266 req.decode = assoc->decode;
3267 req.print = assoc->print;
3268 req.association = assoc;
3270 (*assoc->init->bend_segment)(assoc->backend, &req);
3275 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd)
3277 bend_esrequest_rr esrequest;
3278 const char *ext_name = "unknown";
3280 Z_ExtendedServicesRequest *req =
3281 reqb->apdu_request->u.extendedServicesRequest;
3282 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
3284 Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
3286 esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
3287 esrequest.stream = assoc->encode;
3288 esrequest.decode = assoc->decode;
3289 esrequest.print = assoc->print;
3290 esrequest.errcode = 0;
3291 esrequest.errstring = NULL;
3292 esrequest.request = reqb;
3293 esrequest.association = assoc;
3294 esrequest.taskPackage = 0;
3295 esrequest.referenceId = req->referenceId;
3298 if (esrequest.esr && esrequest.esr->taskSpecificParameters)
3300 switch(esrequest.esr->taskSpecificParameters->which)
3302 case Z_External_itemOrder:
3303 ext_name = "ItemOrder"; break;
3304 case Z_External_update:
3305 ext_name = "Update"; break;
3306 case Z_External_update0:
3307 ext_name = "Update0"; break;
3308 case Z_External_ESAdmin:
3309 ext_name = "Admin"; break;
3314 (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
3316 /* If the response is being delayed, return NULL */
3317 if (esrequest.request == NULL)
3320 resp->referenceId = req->referenceId;
3322 if (esrequest.errcode == -1)
3324 /* Backend service indicates request will be processed */
3325 yaz_log(log_request, "Extended Service: %s (accepted)", ext_name);
3326 *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
3328 else if (esrequest.errcode == 0)
3330 /* Backend service indicates request will be processed */
3331 yaz_log(log_request, "Extended Service: %s (done)", ext_name);
3332 *resp->operationStatus = Z_ExtendedServicesResponse_done;
3336 Z_DiagRecs *diagRecs =
3337 zget_DiagRecs(assoc->encode, esrequest.errcode,
3338 esrequest.errstring);
3339 /* Backend indicates error, request will not be processed */
3340 yaz_log(log_request, "Extended Service: %s (failed)", ext_name);
3341 *resp->operationStatus = Z_ExtendedServicesResponse_failure;
3342 resp->num_diagnostics = diagRecs->num_diagRecs;
3343 resp->diagnostics = diagRecs->diagRecs;
3346 WRBUF wr = wrbuf_alloc();
3347 wrbuf_diags(wr, resp->num_diagnostics, resp->diagnostics);
3348 yaz_log(log_request, "EsRequest %s", wrbuf_buf(wr) );
3353 /* Do something with the members of bend_extendedservice */
3354 if (esrequest.taskPackage)
3355 resp->taskPackage = z_ext_record (assoc->encode, VAL_EXTENDED,
3356 (const char *) esrequest.taskPackage,
3358 yaz_log(YLOG_DEBUG,"Send the result apdu");
3365 * indent-tabs-mode: nil
3367 * vim: shiftwidth=4 tabstop=8 expandtab