2 * Copyright (C) 1995-2007, Index Data ApS
3 * See the file LICENSE for details.
5 * $Id: seshigh.c,v 1.128 2007-09-11 08:37:53 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>
65 #include <yaz/oid_db.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>
75 #include <yaz/oid_db.h>
78 #include <yaz/backend.h>
79 #include <yaz/yaz-ccl.h>
81 static void process_gdu_request(association *assoc, request *req);
82 static int process_z_request(association *assoc, request *req, char **msg);
83 void backend_response(IOCHAN i, int event);
84 static int process_gdu_response(association *assoc, request *req, Z_GDU *res);
85 static int process_z_response(association *assoc, request *req, Z_APDU *res);
86 static Z_APDU *process_initRequest(association *assoc, request *reqb);
87 static Z_External *init_diagnostics(ODR odr, int errcode,
88 const char *errstring);
89 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
91 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
92 bend_search_rr *bsrr, int *fd);
93 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
95 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
96 static Z_APDU *process_sortRequest(association *assoc, request *reqb, int *fd);
97 static void process_close(association *assoc, request *reqb);
98 void save_referenceId (request *reqb, Z_ReferenceId *refid);
99 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
101 static Z_APDU *process_segmentRequest (association *assoc, request *reqb);
103 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd);
105 /* dynamic logging levels */
106 static int logbits_set = 0;
107 static int log_session = 0; /* one-line logs for session */
108 static int log_sessiondetail = 0; /* more detailed stuff */
109 static int log_request = 0; /* one-line logs for requests */
110 static int log_requestdetail = 0; /* more detailed stuff */
112 /** get_logbits sets global loglevel bits */
113 static void get_logbits(void)
114 { /* needs to be called after parsing cmd-line args that can set loglevels!*/
118 log_session = yaz_log_module_level("session");
119 log_sessiondetail = yaz_log_module_level("sessiondetail");
120 log_request = yaz_log_module_level("request");
121 log_requestdetail = yaz_log_module_level("requestdetail");
127 static void wr_diag(WRBUF w, int error, const char *addinfo)
129 wrbuf_printf(w, "ERROR %d+", error);
130 wrbuf_puts_replace_char(w, diagbib1_str(error), ' ', '_');
133 wrbuf_puts_replace_char(w, addinfo, ' ', '_');
141 * Create and initialize a new association-handle.
142 * channel : iochannel for the current line.
143 * link : communications channel.
144 * Returns: 0 or a new association handle.
146 association *create_association(IOCHAN channel, COMSTACK link,
147 const char *apdufile)
153 if (!(anew = (association *)xmalloc(sizeof(*anew))))
157 anew->last_control = 0;
158 anew->client_chan = channel;
159 anew->client_link = link;
160 anew->cs_get_mask = 0;
161 anew->cs_put_mask = 0;
162 anew->cs_accept_mask = 0;
163 if (!(anew->decode = odr_createmem(ODR_DECODE)) ||
164 !(anew->encode = odr_createmem(ODR_ENCODE)))
166 if (apdufile && *apdufile)
170 if (!(anew->print = odr_createmem(ODR_PRINT)))
172 if (*apdufile == '@')
174 odr_setprint(anew->print, yaz_log_file());
176 else if (*apdufile != '-')
179 sprintf(filename, "%.200s.%ld", apdufile, (long)getpid());
180 if (!(f = fopen(filename, "w")))
182 yaz_log(YLOG_WARN|YLOG_ERRNO, "%s", filename);
185 setvbuf(f, 0, _IONBF, 0);
186 odr_setprint(anew->print, f);
191 anew->input_buffer = 0;
192 anew->input_buffer_len = 0;
194 anew->state = ASSOC_NEW;
195 request_initq(&anew->incoming);
196 request_initq(&anew->outgoing);
197 anew->proto = cs_getproto(link);
203 * Free association and release resources.
205 void destroy_association(association *h)
207 statserv_options_block *cb = statserv_getcontrol();
211 odr_destroy(h->decode);
212 odr_destroy(h->encode);
214 odr_destroy(h->print);
216 xfree(h->input_buffer);
218 (*cb->bend_close)(h->backend);
219 while ((req = request_deq(&h->incoming)))
220 request_release(req);
221 while ((req = request_deq(&h->outgoing)))
222 request_release(req);
223 request_delq(&h->incoming);
224 request_delq(&h->outgoing);
226 xmalloc_trav("session closed");
227 if (cb && cb->one_shot)
233 static void do_close_req(association *a, int reason, char *message,
237 Z_Close *cls = zget_Close(a->encode);
239 /* Purge request queue */
240 while (request_deq(&a->incoming));
241 while (request_deq(&a->outgoing));
244 yaz_log(log_requestdetail, "Sending Close PDU, reason=%d, message=%s",
245 reason, message ? message : "none");
246 apdu.which = Z_APDU_close;
248 *cls->closeReason = reason;
249 cls->diagnosticInformation = message;
250 process_z_response(a, req, &apdu);
251 iochan_settimeout(a->client_chan, 20);
255 request_release(req);
256 yaz_log(log_requestdetail, "v2 client. No Close PDU");
257 iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
260 a->state = ASSOC_DEAD;
263 static void do_close(association *a, int reason, char *message)
265 request *req = request_get(&a->outgoing);
266 do_close_req (a, reason, message, req);
270 int ir_read(IOCHAN h, int event)
272 association *assoc = (association *)iochan_getdata(h);
273 COMSTACK conn = assoc->client_link;
276 if ((assoc->cs_put_mask & EVENT_INPUT) == 0 && (event & assoc->cs_get_mask))
278 yaz_log(YLOG_DEBUG, "ir_session (input)");
279 /* We aren't speaking to this fellow */
280 if (assoc->state == ASSOC_DEAD)
282 yaz_log(log_sessiondetail, "Connection closed - end of session");
284 destroy_association(assoc);
288 assoc->cs_get_mask = EVENT_INPUT;
292 int res = cs_get(conn, &assoc->input_buffer,
293 &assoc->input_buffer_len);
294 if (res < 0 && cs_errno(conn) == CSBUFSIZE)
296 yaz_log(log_session, "Connection error: %s res=%d",
297 cs_errmsg(cs_errno(conn)), res);
298 req = request_get(&assoc->incoming); /* get a new request */
299 do_close_req(assoc, Z_Close_protocolError,
300 "Incoming package too large", req);
305 yaz_log(log_session, "Connection closed by client");
306 assoc->state = ASSOC_DEAD;
309 else if (res == 1) /* incomplete read - wait for more */
311 if (conn->io_pending & CS_WANT_WRITE)
312 assoc->cs_get_mask |= EVENT_OUTPUT;
313 iochan_setflag(h, assoc->cs_get_mask);
316 /* we got a complete PDU. Let's decode it */
317 yaz_log(YLOG_DEBUG, "Got PDU, %d bytes: lead=%02X %02X %02X", res,
318 assoc->input_buffer[0] & 0xff,
319 assoc->input_buffer[1] & 0xff,
320 assoc->input_buffer[2] & 0xff);
321 req = request_get(&assoc->incoming); /* get a new request */
322 odr_reset(assoc->decode);
323 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
324 if (!z_GDU(assoc->decode, &req->gdu_request, 0, 0))
326 yaz_log(YLOG_WARN, "ODR error on incoming PDU: %s [element %s] "
328 odr_errmsg(odr_geterror(assoc->decode)),
329 odr_getelement(assoc->decode),
330 (long) odr_offset(assoc->decode));
331 if (assoc->decode->error != OHTTP)
333 yaz_log(YLOG_WARN, "PDU dump:");
334 odr_dumpBER(yaz_log_file(), assoc->input_buffer, res);
335 request_release(req);
336 do_close(assoc, Z_Close_protocolError, "Malformed package");
340 Z_GDU *p = z_get_HTTP_Response(assoc->encode, 400);
341 assoc->state = ASSOC_DEAD;
342 process_gdu_response(assoc, req, p);
346 req->request_mem = odr_extract_mem(assoc->decode);
349 if (!z_GDU(assoc->print, &req->gdu_request, 0, 0))
350 yaz_log(YLOG_WARN, "ODR print error: %s",
351 odr_errmsg(odr_geterror(assoc->print)));
352 odr_reset(assoc->print);
354 request_enq(&assoc->incoming, req);
356 while (cs_more(conn));
362 * This is where PDUs from the client are read and the further
363 * processing is initiated. Flow of control moves down through the
364 * various process_* functions below, until the encoded result comes back up
365 * to the output handler in here.
367 * h : the I/O channel that has an outstanding event.
368 * event : the current outstanding event.
370 void ir_session(IOCHAN h, int event)
373 association *assoc = (association *)iochan_getdata(h);
374 COMSTACK conn = assoc->client_link;
377 assert(h && conn && assoc);
378 if (event == EVENT_TIMEOUT)
380 if (assoc->state != ASSOC_UP)
382 yaz_log(YLOG_DEBUG, "Final timeout - closing connection.");
383 /* do we need to lod this at all */
385 destroy_association(assoc);
390 yaz_log(log_sessiondetail,
391 "Session idle too long. Sending close.");
392 do_close(assoc, Z_Close_lackOfActivity, 0);
396 if (event & assoc->cs_accept_mask)
398 if (!cs_accept (conn))
400 yaz_log (YLOG_WARN, "accept failed");
401 destroy_association(assoc);
404 iochan_clearflag (h, EVENT_OUTPUT);
405 if (conn->io_pending)
406 { /* cs_accept didn't complete */
407 assoc->cs_accept_mask =
408 ((conn->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
409 ((conn->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
411 iochan_setflag (h, assoc->cs_accept_mask);
414 { /* cs_accept completed. Prepare for reading (cs_get) */
415 assoc->cs_accept_mask = 0;
416 assoc->cs_get_mask = EVENT_INPUT;
417 iochan_setflag (h, assoc->cs_get_mask);
421 if (event & assoc->cs_get_mask) /* input */
423 if (!ir_read(h, event))
425 req = request_head(&assoc->incoming);
426 if (req->state == REQUEST_IDLE)
428 request_deq(&assoc->incoming);
429 process_gdu_request(assoc, req);
432 if (event & assoc->cs_put_mask)
434 request *req = request_head(&assoc->outgoing);
436 assoc->cs_put_mask = 0;
437 yaz_log(YLOG_DEBUG, "ir_session (output)");
438 req->state = REQUEST_PENDING;
439 switch (res = cs_put(conn, req->response, req->len_response))
442 yaz_log(log_sessiondetail, "Connection closed by client");
444 destroy_association(assoc);
447 case 0: /* all sent - release the request structure */
448 yaz_log(YLOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
450 yaz_log(YLOG_DEBUG, "HTTP out:\n%.*s", req->len_response,
453 nmem_destroy(req->request_mem);
454 request_deq(&assoc->outgoing);
455 request_release(req);
456 if (!request_head(&assoc->outgoing))
457 { /* restore mask for cs_get operation ... */
458 iochan_clearflag(h, EVENT_OUTPUT|EVENT_INPUT);
459 iochan_setflag(h, assoc->cs_get_mask);
460 if (assoc->state == ASSOC_DEAD)
461 iochan_setevent(assoc->client_chan, EVENT_TIMEOUT);
465 assoc->cs_put_mask = EVENT_OUTPUT;
469 if (conn->io_pending & CS_WANT_WRITE)
470 assoc->cs_put_mask |= EVENT_OUTPUT;
471 if (conn->io_pending & CS_WANT_READ)
472 assoc->cs_put_mask |= EVENT_INPUT;
473 iochan_setflag(h, assoc->cs_put_mask);
476 if (event & EVENT_EXCEPT)
478 yaz_log(YLOG_WARN, "ir_session (exception)");
480 destroy_association(assoc);
485 static int process_z_request(association *assoc, request *req, char **msg);
488 static void assoc_init_reset(association *assoc)
491 assoc->init = (bend_initrequest *) xmalloc (sizeof(*assoc->init));
493 assoc->init->stream = assoc->encode;
494 assoc->init->print = assoc->print;
495 assoc->init->auth = 0;
496 assoc->init->referenceId = 0;
497 assoc->init->implementation_version = 0;
498 assoc->init->implementation_id = 0;
499 assoc->init->implementation_name = 0;
500 assoc->init->query_charset = 0;
501 assoc->init->records_in_same_charset = 0;
502 assoc->init->bend_sort = NULL;
503 assoc->init->bend_search = NULL;
504 assoc->init->bend_present = NULL;
505 assoc->init->bend_esrequest = NULL;
506 assoc->init->bend_delete = NULL;
507 assoc->init->bend_scan = NULL;
508 assoc->init->bend_segment = NULL;
509 assoc->init->bend_fetch = NULL;
510 assoc->init->bend_explain = NULL;
511 assoc->init->bend_srw_scan = NULL;
512 assoc->init->bend_srw_update = NULL;
514 assoc->init->charneg_request = NULL;
515 assoc->init->charneg_response = NULL;
517 assoc->init->decode = assoc->decode;
518 assoc->init->peer_name =
519 odr_strdup (assoc->encode, cs_addrstr(assoc->client_link));
521 yaz_log(log_requestdetail, "peer %s", assoc->init->peer_name);
524 static int srw_bend_init(association *assoc, Z_SRW_diagnostic **d, int *num, Z_SRW_PDU *sr)
526 statserv_options_block *cb = statserv_getcontrol();
529 const char *encoding = "UTF-8";
531 bend_initresult *binitres;
533 yaz_log(log_requestdetail, "srw_bend_init config=%s", cb->configname);
534 assoc_init_reset(assoc);
538 Z_IdAuthentication *auth = (Z_IdAuthentication *)
539 odr_malloc(assoc->decode, sizeof(*auth));
542 len = strlen(sr->username) + 1;
544 len += strlen(sr->password) + 2;
545 auth->which = Z_IdAuthentication_open;
546 auth->u.open = (char *) odr_malloc(assoc->decode, len);
547 strcpy(auth->u.open, sr->username);
548 if (sr->password && *sr->password)
550 strcat(auth->u.open, "/");
551 strcat(auth->u.open, sr->password);
553 assoc->init->auth = auth;
557 ce = yaz_set_proposal_charneg(assoc->decode, &encoding, 1, 0, 0, 1);
558 assoc->init->charneg_request = ce->u.charNeg3;
561 if (!(binitres = (*cb->bend_init)(assoc->init)))
563 assoc->state = ASSOC_DEAD;
564 yaz_add_srw_diagnostic(assoc->encode, d, num,
565 YAZ_SRW_AUTHENTICATION_ERROR, 0);
568 assoc->backend = binitres->handle;
569 assoc->init->auth = 0;
570 if (binitres->errcode)
572 int srw_code = yaz_diag_bib1_to_srw(binitres->errcode);
573 assoc->state = ASSOC_DEAD;
574 yaz_add_srw_diagnostic(assoc->encode, d, num, srw_code,
575 binitres->errstring);
583 static int retrieve_fetch(association *assoc, bend_fetch_rr *rr)
586 yaz_record_conv_t rc = 0;
587 const char *match_schema = 0;
588 Odr_oid *match_syntax = 0;
593 const char *input_schema = yaz_get_esn(rr->comp);
594 Odr_oid *input_syntax_raw = rr->request_format;
596 const char *backend_schema = 0;
597 Odr_oid *backend_syntax = 0;
599 r = yaz_retrieval_request(assoc->server->retrieval,
607 if (r == -1) /* error ? */
609 const char *details = yaz_retrieval_get_error(
610 assoc->server->retrieval);
612 rr->errcode = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
614 rr->errstring = odr_strdup(rr->stream, details);
617 else if (r == 1 || r == 3)
619 const char *details = input_schema;
621 YAZ_BIB1_SPECIFIED_ELEMENT_SET_NAME_NOT_VALID_FOR_SPECIFIED_;
623 rr->errstring = odr_strdup(rr->stream, details);
628 rr->errcode = YAZ_BIB1_RECORD_SYNTAX_UNSUPP;
629 if (input_syntax_raw)
631 char oidbuf[OID_STR_MAX];
632 oid_oid_to_dotstring(input_syntax_raw, oidbuf);
633 rr->errstring = odr_strdup(rr->stream, oidbuf);
639 yaz_set_esn(&rr->comp, backend_schema, odr_getmem(rr->stream));
642 rr->request_format = backend_syntax;
644 (*assoc->init->bend_fetch)(assoc->backend, rr);
645 if (rc && rr->record && rr->errcode == 0 && rr->len > 0)
646 { /* post conversion must take place .. */
647 WRBUF output_record = wrbuf_alloc();
648 int r = yaz_record_conv_record(rc, rr->record, rr->len, output_record);
651 const char *details = yaz_record_conv_get_error(rc);
652 rr->errcode = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
654 rr->errstring = odr_strdup(rr->stream, details);
658 rr->len = wrbuf_len(output_record);
659 rr->record = (char *) odr_malloc(rr->stream, rr->len);
660 memcpy(rr->record, wrbuf_buf(output_record), rr->len);
662 wrbuf_destroy(output_record);
665 rr->output_format = match_syntax;
667 rr->schema = odr_strdup(rr->stream, match_schema);
670 (*assoc->init->bend_fetch)(assoc->backend, rr);
675 static int srw_bend_fetch(association *assoc, int pos,
676 Z_SRW_searchRetrieveRequest *srw_req,
677 Z_SRW_record *record,
678 const char **addinfo)
681 ODR o = assoc->encode;
683 rr.setname = "default";
686 rr.request_format = odr_oiddup(assoc->decode, yaz_oid_recsyn_xml);
688 rr.comp = (Z_RecordComposition *)
689 odr_malloc(assoc->decode, sizeof(*rr.comp));
690 rr.comp->which = Z_RecordComp_complex;
691 rr.comp->u.complex = (Z_CompSpec *)
692 odr_malloc(assoc->decode, sizeof(Z_CompSpec));
693 rr.comp->u.complex->selectAlternativeSyntax = (bool_t *)
694 odr_malloc(assoc->encode, sizeof(bool_t));
695 *rr.comp->u.complex->selectAlternativeSyntax = 0;
696 rr.comp->u.complex->num_dbSpecific = 0;
697 rr.comp->u.complex->dbSpecific = 0;
698 rr.comp->u.complex->num_recordSyntax = 0;
699 rr.comp->u.complex->recordSyntax = 0;
701 rr.comp->u.complex->generic = (Z_Specification *)
702 odr_malloc(assoc->decode, sizeof(Z_Specification));
704 /* schema uri = recordSchema (or NULL if recordSchema is not given) */
705 rr.comp->u.complex->generic->which = Z_Schema_uri;
706 rr.comp->u.complex->generic->schema.uri = srw_req->recordSchema;
708 /* ESN = recordSchema if recordSchema is present */
709 rr.comp->u.complex->generic->elementSpec = 0;
710 if (srw_req->recordSchema)
712 rr.comp->u.complex->generic->elementSpec =
713 (Z_ElementSpec *) odr_malloc(assoc->encode, sizeof(Z_ElementSpec));
714 rr.comp->u.complex->generic->elementSpec->which =
715 Z_ElementSpec_elementSetName;
716 rr.comp->u.complex->generic->elementSpec->u.elementSetName =
717 srw_req->recordSchema;
720 rr.stream = assoc->encode;
721 rr.print = assoc->print;
729 rr.surrogate_flag = 0;
730 rr.schema = srw_req->recordSchema;
732 if (!assoc->init->bend_fetch)
735 retrieve_fetch(assoc, &rr);
737 if (rr.errcode && rr.surrogate_flag)
739 int code = yaz_diag_bib1_to_srw(rr.errcode);
740 const char *message = yaz_diag_srw_str(code);
743 len += strlen(message);
745 len += strlen(rr.errstring);
747 record->recordData_buf = (char *) odr_malloc(o, len);
749 sprintf(record->recordData_buf, "<diagnostic "
750 "xmlns=\"http://www.loc.gov/zing/srw/diagnostic/\">\n"
751 " <uri>info:srw/diagnostic/1/%d</uri>\n", code);
753 sprintf(record->recordData_buf + strlen(record->recordData_buf),
754 " <details>%s</details>\n", rr.errstring);
756 sprintf(record->recordData_buf + strlen(record->recordData_buf),
757 " <message>%s</message>\n", message);
758 sprintf(record->recordData_buf + strlen(record->recordData_buf),
760 record->recordData_len = strlen(record->recordData_buf);
761 record->recordPosition = odr_intdup(o, pos);
762 record->recordSchema = "info:srw/schema/1/diagnostics-v1.1";
765 else if (rr.len >= 0)
767 record->recordData_buf = rr.record;
768 record->recordData_len = rr.len;
769 record->recordPosition = odr_intdup(o, pos);
770 record->recordSchema = odr_strdup_null(o, rr.schema);
774 *addinfo = rr.errstring;
780 static int cql2pqf(ODR odr, const char *cql, cql_transform_t ct,
781 Z_Query *query_result)
783 /* have a CQL query and CQL to PQF transform .. */
784 CQL_parser cp = cql_parser_create();
790 r = cql_parser_string(cp, cql);
793 /* CQL syntax error */
799 r = cql_transform_buf(ct,
800 cql_parser_result(cp),
801 rpn_buf, sizeof(rpn_buf)-1);
803 srw_errcode = cql_transform_error(ct, &add);
807 /* Syntax & transform OK. */
808 /* Convert PQF string to Z39.50 to RPN query struct */
809 YAZ_PQF_Parser pp = yaz_pqf_create();
810 Z_RPNQuery *rpnquery = yaz_pqf_parse(pp, odr, rpn_buf);
815 int code = yaz_pqf_error(pp, &pqf_msg, &off);
816 yaz_log(YLOG_WARN, "PQF Parser Error %s (code %d)",
822 query_result->which = Z_Query_type_1;
823 query_result->u.type_1 = rpnquery;
827 cql_parser_destroy(cp);
831 static int cql2pqf_scan(ODR odr, const char *cql, cql_transform_t ct,
832 Z_AttributesPlusTerm *result)
836 int srw_error = cql2pqf(odr, cql, ct, &query);
839 if (query.which != Z_Query_type_1 && query.which != Z_Query_type_101)
840 return 10; /* bad query type */
841 rpn = query.u.type_1;
842 if (!rpn->RPNStructure)
843 return 10; /* must be structure */
844 if (rpn->RPNStructure->which != Z_RPNStructure_simple)
845 return 10; /* must be simple */
846 if (rpn->RPNStructure->u.simple->which != Z_Operand_APT)
847 return 10; /* must be attributes plus term node .. */
848 memcpy(result, rpn->RPNStructure->u.simple->u.attributesPlusTerm,
854 static int ccl2pqf(ODR odr, const Odr_oct *ccl, CCL_bibset bibset,
855 bend_search_rr *bsrr) {
857 struct ccl_rpn_node *node;
860 ccl0 = odr_strdupn(odr, (char*) ccl->buf, ccl->len);
861 if ((node = ccl_find_str(bibset, ccl0, &errcode, &pos)) == 0) {
862 bsrr->errstring = (char*) ccl_err_msg(errcode);
863 return 10; /* Query syntax error */
866 bsrr->query->which = Z_Query_type_1;
867 bsrr->query->u.type_1 = ccl_rpn_query(odr, node);
872 static void srw_bend_search(association *assoc, request *req,
874 Z_SRW_searchRetrieveResponse *srw_res,
879 Z_SRW_searchRetrieveRequest *srw_req = sr->u.request;
882 yaz_log(log_requestdetail, "Got SRW SearchRetrieveRequest");
883 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
884 if (srw_res->num_diagnostics == 0 && assoc->init)
887 rr.setname = "default";
890 rr.basenames = &srw_req->database;
894 rr.srw_setnameIdleTime = 0;
895 rr.estimated_hit_count = 0;
896 rr.partial_resultset = 0;
897 rr.query = (Z_Query *) odr_malloc (assoc->decode, sizeof(*rr.query));
898 rr.query->u.type_1 = 0;
900 if (srw_req->query_type == Z_SRW_query_type_cql)
902 if (assoc->server && assoc->server->cql_transform)
904 int srw_errcode = cql2pqf(assoc->encode, srw_req->query.cql,
905 assoc->server->cql_transform,
909 yaz_add_srw_diagnostic(assoc->encode,
910 &srw_res->diagnostics,
911 &srw_res->num_diagnostics,
917 /* CQL query to backend. Wrap it - Z39.50 style */
918 ext = (Z_External *) odr_malloc(assoc->decode, sizeof(*ext));
919 ext->direct_reference = odr_getoidbystr(assoc->decode,
920 "1.2.840.10003.16.2");
921 ext->indirect_reference = 0;
923 ext->which = Z_External_CQL;
924 ext->u.cql = srw_req->query.cql;
926 rr.query->which = Z_Query_type_104;
927 rr.query->u.type_104 = ext;
930 else if (srw_req->query_type == Z_SRW_query_type_pqf)
932 Z_RPNQuery *RPNquery;
933 YAZ_PQF_Parser pqf_parser;
935 pqf_parser = yaz_pqf_create ();
937 RPNquery = yaz_pqf_parse (pqf_parser, assoc->decode,
943 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
944 yaz_log(log_requestdetail, "Parse error %d %s near offset %ld",
945 code, pqf_msg, (long) off);
946 srw_error = YAZ_SRW_QUERY_SYNTAX_ERROR;
949 rr.query->which = Z_Query_type_1;
950 rr.query->u.type_1 = RPNquery;
952 yaz_pqf_destroy (pqf_parser);
956 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
957 &srw_res->num_diagnostics,
958 YAZ_SRW_UNSUPP_QUERY_TYPE, 0);
960 if (rr.query->u.type_1)
962 rr.stream = assoc->encode;
963 rr.decode = assoc->decode;
964 rr.print = assoc->print;
966 if ( srw_req->sort.sortKeys )
967 rr.srw_sortKeys = odr_strdup(assoc->encode,
968 srw_req->sort.sortKeys );
969 rr.association = assoc;
975 yaz_log_zquery_level(log_requestdetail,rr.query);
977 (assoc->init->bend_search)(assoc->backend, &rr);
980 if (rr.errcode == YAZ_BIB1_DATABASE_UNAVAILABLE)
986 srw_error = yaz_diag_bib1_to_srw (rr.errcode);
987 yaz_add_srw_diagnostic(assoc->encode,
988 &srw_res->diagnostics,
989 &srw_res->num_diagnostics,
990 srw_error, rr.errstring);
995 int number = srw_req->maximumRecords ? *srw_req->maximumRecords : 0;
996 int start = srw_req->startRecord ? *srw_req->startRecord : 1;
998 yaz_log(log_requestdetail, "Request to pack %d+%d out of %d",
999 start, number, rr.hits);
1001 srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
1004 srw_res->resultSetId =
1005 odr_strdup(assoc->encode, rr.srw_setname );
1006 srw_res->resultSetIdleTime =
1007 odr_intdup(assoc->encode, *rr.srw_setnameIdleTime );
1010 if (start > rr.hits || start < 1)
1012 /* if hits<=0 and start=1 we don't return a diagnostic */
1014 yaz_add_srw_diagnostic(
1016 &srw_res->diagnostics, &srw_res->num_diagnostics,
1017 YAZ_SRW_FIRST_RECORD_POSITION_OUT_OF_RANGE, 0);
1019 else if (number > 0)
1023 if (start + number > rr.hits)
1024 number = rr.hits - start + 1;
1026 /* Call bend_present if defined */
1027 if (assoc->init->bend_present)
1029 bend_present_rr *bprr = (bend_present_rr*)
1030 odr_malloc (assoc->decode, sizeof(*bprr));
1031 bprr->setname = "default";
1032 bprr->start = start;
1033 bprr->number = number;
1034 if (srw_req->recordSchema)
1036 bprr->comp = (Z_RecordComposition *) odr_malloc(assoc->decode,
1037 sizeof(*bprr->comp));
1038 bprr->comp->which = Z_RecordComp_simple;
1039 bprr->comp->u.simple = (Z_ElementSetNames *)
1040 odr_malloc(assoc->decode, sizeof(Z_ElementSetNames));
1041 bprr->comp->u.simple->which = Z_ElementSetNames_generic;
1042 bprr->comp->u.simple->u.generic = srw_req->recordSchema;
1048 bprr->stream = assoc->encode;
1049 bprr->referenceId = 0;
1050 bprr->print = assoc->print;
1051 bprr->request = req;
1052 bprr->association = assoc;
1054 bprr->errstring = NULL;
1055 (*assoc->init->bend_present)(assoc->backend, bprr);
1061 srw_error = yaz_diag_bib1_to_srw (bprr->errcode);
1062 yaz_add_srw_diagnostic(assoc->encode,
1063 &srw_res->diagnostics,
1064 &srw_res->num_diagnostics,
1065 srw_error, bprr->errstring);
1073 int packing = Z_SRW_recordPacking_string;
1074 if (srw_req->recordPacking)
1077 yaz_srw_str_to_pack(srw_req->recordPacking);
1079 packing = Z_SRW_recordPacking_string;
1081 srw_res->records = (Z_SRW_record *)
1082 odr_malloc(assoc->encode,
1083 number * sizeof(*srw_res->records));
1085 srw_res->extra_records = (Z_SRW_extra_record **)
1086 odr_malloc(assoc->encode,
1087 number*sizeof(*srw_res->extra_records));
1089 for (i = 0; i<number; i++)
1092 const char *addinfo = 0;
1094 srw_res->records[j].recordPacking = packing;
1095 srw_res->records[j].recordData_buf = 0;
1096 srw_res->extra_records[j] = 0;
1097 yaz_log(YLOG_DEBUG, "srw_bend_fetch %d", i+start);
1098 errcode = srw_bend_fetch(assoc, i+start, srw_req,
1099 srw_res->records + j,
1103 yaz_add_srw_diagnostic(assoc->encode,
1104 &srw_res->diagnostics,
1105 &srw_res->num_diagnostics,
1106 yaz_diag_bib1_to_srw (errcode),
1111 if (srw_res->records[j].recordData_buf)
1114 srw_res->num_records = j;
1116 srw_res->records = 0;
1119 if (rr.estimated_hit_count || rr.partial_resultset)
1121 yaz_add_srw_diagnostic(
1123 &srw_res->diagnostics,
1124 &srw_res->num_diagnostics,
1125 YAZ_SRW_RESULT_SET_CREATED_WITH_VALID_PARTIAL_RESULTS_AVAILABLE,
1133 const char *querystr = "?";
1134 const char *querytype = "?";
1135 WRBUF wr = wrbuf_alloc();
1137 switch (srw_req->query_type)
1139 case Z_SRW_query_type_cql:
1141 querystr = srw_req->query.cql;
1143 case Z_SRW_query_type_pqf:
1145 querystr = srw_req->query.pqf;
1148 wrbuf_printf(wr, "SRWSearch ");
1149 wrbuf_printf(wr, srw_req->database);
1150 wrbuf_printf(wr, " ");
1151 if (srw_res->num_diagnostics)
1152 wrbuf_printf(wr, "ERROR %s", srw_res->diagnostics[0].uri);
1153 else if (*http_code != 200)
1154 wrbuf_printf(wr, "ERROR info:http/%d", *http_code);
1155 else if (srw_res->numberOfRecords)
1157 wrbuf_printf(wr, "OK %d",
1158 (srw_res->numberOfRecords ?
1159 *srw_res->numberOfRecords : 0));
1161 wrbuf_printf(wr, " %s %d+%d",
1162 (srw_res->resultSetId ?
1163 srw_res->resultSetId : "-"),
1164 (srw_req->startRecord ? *srw_req->startRecord : 1),
1165 srw_res->num_records);
1166 yaz_log(log_request, "%s %s: %s", wrbuf_cstr(wr), querytype, querystr);
1171 static char *srw_bend_explain_default(void *handle, bend_explain_rr *rr)
1174 xmlNodePtr ptr = (xmlNode *) rr->server_node_ptr;
1177 for (ptr = ptr->children; ptr; ptr = ptr->next)
1179 if (ptr->type != XML_ELEMENT_NODE)
1181 if (!strcmp((const char *) ptr->name, "explain"))
1184 xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
1188 ptr = xmlCopyNode(ptr, 1);
1190 xmlDocSetRootElement(doc, ptr);
1192 xmlDocDumpMemory(doc, &buf_out, &len);
1193 content = (char*) odr_malloc(rr->stream, 1+len);
1194 memcpy(content, buf_out, len);
1195 content[len] = '\0';
1199 rr->explain_buf = content;
1207 static void srw_bend_explain(association *assoc, request *req,
1209 Z_SRW_explainResponse *srw_res,
1212 Z_SRW_explainRequest *srw_req = sr->u.explain_request;
1213 yaz_log(log_requestdetail, "Got SRW ExplainRequest");
1215 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1220 rr.stream = assoc->encode;
1221 rr.decode = assoc->decode;
1222 rr.print = assoc->print;
1224 rr.database = srw_req->database;
1226 rr.server_node_ptr = assoc->server->server_node_ptr;
1228 rr.server_node_ptr = 0;
1229 rr.schema = "http://explain.z3950.org/dtd/2.0/";
1230 if (assoc->init->bend_explain)
1231 (*assoc->init->bend_explain)(assoc->backend, &rr);
1233 srw_bend_explain_default(assoc->backend, &rr);
1237 int packing = Z_SRW_recordPacking_string;
1238 if (srw_req->recordPacking)
1241 yaz_srw_str_to_pack(srw_req->recordPacking);
1243 packing = Z_SRW_recordPacking_string;
1245 srw_res->record.recordSchema = rr.schema;
1246 srw_res->record.recordPacking = packing;
1247 srw_res->record.recordData_buf = rr.explain_buf;
1248 srw_res->record.recordData_len = strlen(rr.explain_buf);
1249 srw_res->record.recordPosition = 0;
1255 static void srw_bend_scan(association *assoc, request *req,
1257 Z_SRW_scanResponse *srw_res,
1260 Z_SRW_scanRequest *srw_req = sr->u.scan_request;
1261 yaz_log(log_requestdetail, "Got SRW ScanRequest");
1264 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1265 if (srw_res->num_diagnostics == 0 && assoc->init)
1267 struct scan_entry *save_entries;
1269 bend_scan_rr *bsrr = (bend_scan_rr *)
1270 odr_malloc (assoc->encode, sizeof(*bsrr));
1271 bsrr->num_bases = 1;
1272 bsrr->basenames = &srw_req->database;
1274 bsrr->num_entries = srw_req->maximumTerms ?
1275 *srw_req->maximumTerms : 10;
1276 bsrr->term_position = srw_req->responsePosition ?
1277 *srw_req->responsePosition : 1;
1280 bsrr->errstring = 0;
1281 bsrr->referenceId = 0;
1282 bsrr->stream = assoc->encode;
1283 bsrr->print = assoc->print;
1284 bsrr->step_size = odr_intdup(assoc->decode, 0);
1288 if (bsrr->num_entries > 0)
1291 bsrr->entries = (struct scan_entry *)
1292 odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
1294 for (i = 0; i<bsrr->num_entries; i++)
1296 bsrr->entries[i].term = 0;
1297 bsrr->entries[i].occurrences = 0;
1298 bsrr->entries[i].errcode = 0;
1299 bsrr->entries[i].errstring = 0;
1300 bsrr->entries[i].display_term = 0;
1303 save_entries = bsrr->entries; /* save it so we can compare later */
1305 if (srw_req->query_type == Z_SRW_query_type_pqf &&
1306 assoc->init->bend_scan)
1308 YAZ_PQF_Parser pqf_parser = yaz_pqf_create();
1310 bsrr->term = yaz_pqf_scan(pqf_parser, assoc->decode,
1311 &bsrr->attributeset,
1312 srw_req->scanClause.pqf);
1313 yaz_pqf_destroy(pqf_parser);
1314 bsrr->scanClause = 0;
1315 ((int (*)(void *, bend_scan_rr *))
1316 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1318 else if (srw_req->query_type == Z_SRW_query_type_cql
1319 && assoc->init->bend_scan && assoc->server
1320 && assoc->server->cql_transform)
1323 bsrr->scanClause = 0;
1324 bsrr->attributeset = 0;
1325 bsrr->term = (Z_AttributesPlusTerm *)
1326 odr_malloc(assoc->decode, sizeof(*bsrr->term));
1327 srw_error = cql2pqf_scan(assoc->encode,
1328 srw_req->scanClause.cql,
1329 assoc->server->cql_transform,
1332 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1333 &srw_res->num_diagnostics,
1337 ((int (*)(void *, bend_scan_rr *))
1338 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1341 else if (srw_req->query_type == Z_SRW_query_type_cql
1342 && assoc->init->bend_srw_scan)
1345 bsrr->attributeset = 0;
1346 bsrr->scanClause = srw_req->scanClause.cql;
1347 ((int (*)(void *, bend_scan_rr *))
1348 (*assoc->init->bend_srw_scan))(assoc->backend, bsrr);
1352 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1353 &srw_res->num_diagnostics,
1354 YAZ_SRW_UNSUPP_OPERATION, "scan");
1359 if (bsrr->errcode == YAZ_BIB1_DATABASE_UNAVAILABLE)
1364 srw_error = yaz_diag_bib1_to_srw (bsrr->errcode);
1366 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1367 &srw_res->num_diagnostics,
1368 srw_error, bsrr->errstring);
1370 else if (srw_res->num_diagnostics == 0 && bsrr->num_entries)
1373 srw_res->terms = (Z_SRW_scanTerm*)
1374 odr_malloc(assoc->encode, sizeof(*srw_res->terms) *
1377 srw_res->num_terms = bsrr->num_entries;
1378 for (i = 0; i<bsrr->num_entries; i++)
1380 Z_SRW_scanTerm *t = srw_res->terms + i;
1381 t->value = odr_strdup(assoc->encode, bsrr->entries[i].term);
1382 t->numberOfRecords =
1383 odr_intdup(assoc->encode, bsrr->entries[i].occurrences);
1385 if (save_entries == bsrr->entries &&
1386 bsrr->entries[i].display_term)
1388 /* the entries was _not_ set by the handler. So it's
1389 safe to test for new member display_term. It is
1392 t->displayTerm = odr_strdup(assoc->encode,
1393 bsrr->entries[i].display_term);
1401 WRBUF wr = wrbuf_alloc();
1402 const char *querytype = 0;
1403 const char *querystr = 0;
1405 switch(srw_req->query_type)
1407 case Z_SRW_query_type_pqf:
1409 querystr = srw_req->scanClause.pqf;
1411 case Z_SRW_query_type_cql:
1413 querystr = srw_req->scanClause.cql;
1416 querytype = "UNKNOWN";
1420 wrbuf_printf(wr, "SRWScan ");
1421 wrbuf_printf(wr, srw_req->database);
1422 wrbuf_printf(wr, " ");
1424 if (srw_res->num_diagnostics)
1425 wrbuf_printf(wr, "ERROR %s - ", srw_res->diagnostics[0].uri);
1426 else if (srw_res->num_terms)
1427 wrbuf_printf(wr, "OK %d - ", srw_res->num_terms);
1429 wrbuf_printf(wr, "OK - - ");
1431 wrbuf_printf(wr, "%d+%d+0 ",
1432 (srw_req->responsePosition ?
1433 *srw_req->responsePosition : 1),
1434 (srw_req->maximumTerms ?
1435 *srw_req->maximumTerms : 1));
1436 /* there is no step size in SRU/W ??? */
1437 wrbuf_printf(wr, "%s: %s ", querytype, querystr);
1438 yaz_log(log_request, "%s ", wrbuf_cstr(wr) );
1444 static void srw_bend_update(association *assoc, request *req,
1446 Z_SRW_updateResponse *srw_res,
1449 Z_SRW_updateRequest *srw_req = sr->u.update_request;
1450 yaz_log(log_session, "SRWUpdate action=%s", srw_req->operation);
1451 yaz_log(YLOG_DEBUG, "num_diag = %d", srw_res->num_diagnostics );
1453 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1457 Z_SRW_extra_record *extra = srw_req->extra_record;
1459 rr.stream = assoc->encode;
1460 rr.print = assoc->print;
1462 rr.basenames = &srw_req->database;
1463 rr.operation = srw_req->operation;
1464 rr.operation_status = "failed";
1466 rr.record_versions = 0;
1467 rr.num_versions = 0;
1468 rr.record_packing = "string";
1469 rr.record_schema = 0;
1471 rr.extra_record_data = 0;
1472 rr.extra_request_data = 0;
1473 rr.extra_response_data = 0;
1479 if (rr.operation == 0)
1481 yaz_add_sru_update_diagnostic(
1482 assoc->encode, &srw_res->diagnostics,
1483 &srw_res->num_diagnostics,
1484 YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,
1488 yaz_log(YLOG_DEBUG, "basename = %s", rr.basenames[0] );
1489 yaz_log(YLOG_DEBUG, "Operation = %s", rr.operation );
1490 if (!strcmp( rr.operation, "delete"))
1492 if (srw_req->record && !srw_req->record->recordSchema)
1494 rr.record_schema = odr_strdup(
1496 srw_req->record->recordSchema);
1498 if (srw_req->record)
1500 rr.record_data = odr_strdupn(
1502 srw_req->record->recordData_buf,
1503 srw_req->record->recordData_len );
1505 if (extra && extra->extraRecordData_len)
1507 rr.extra_record_data = odr_strdupn(
1509 extra->extraRecordData_buf,
1510 extra->extraRecordData_len );
1512 if (srw_req->recordId)
1513 rr.record_id = srw_req->recordId;
1514 else if (extra && extra->recordIdentifier)
1515 rr.record_id = extra->recordIdentifier;
1517 else if (!strcmp(rr.operation, "replace"))
1519 if (srw_req->recordId)
1520 rr.record_id = srw_req->recordId;
1521 else if (extra && extra->recordIdentifier)
1522 rr.record_id = extra->recordIdentifier;
1525 yaz_add_sru_update_diagnostic(
1526 assoc->encode, &srw_res->diagnostics,
1527 &srw_res->num_diagnostics,
1528 YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,
1529 "recordIdentifier");
1531 if (!srw_req->record)
1533 yaz_add_sru_update_diagnostic(
1534 assoc->encode, &srw_res->diagnostics,
1535 &srw_res->num_diagnostics,
1536 YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,
1541 if (srw_req->record->recordSchema)
1542 rr.record_schema = odr_strdup(
1543 assoc->encode, srw_req->record->recordSchema);
1544 if (srw_req->record->recordData_len )
1546 rr.record_data = odr_strdupn(assoc->encode,
1547 srw_req->record->recordData_buf,
1548 srw_req->record->recordData_len );
1552 yaz_add_sru_update_diagnostic(
1553 assoc->encode, &srw_res->diagnostics,
1554 &srw_res->num_diagnostics,
1555 YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,
1559 if (extra && extra->extraRecordData_len)
1561 rr.extra_record_data = odr_strdupn(
1563 extra->extraRecordData_buf,
1564 extra->extraRecordData_len );
1567 else if (!strcmp(rr.operation, "insert"))
1569 if (srw_req->recordId)
1570 rr.record_id = srw_req->recordId;
1572 rr.record_id = extra->recordIdentifier;
1574 if (srw_req->record)
1576 if (srw_req->record->recordSchema)
1577 rr.record_schema = odr_strdup(
1578 assoc->encode, srw_req->record->recordSchema);
1580 if (srw_req->record->recordData_len)
1581 rr.record_data = odr_strdupn(
1583 srw_req->record->recordData_buf,
1584 srw_req->record->recordData_len );
1586 if (extra && extra->extraRecordData_len)
1588 rr.extra_record_data = odr_strdupn(
1590 extra->extraRecordData_buf,
1591 extra->extraRecordData_len );
1595 yaz_add_sru_update_diagnostic(assoc->encode, &srw_res->diagnostics,
1596 &srw_res->num_diagnostics,
1597 YAZ_SRU_UPDATE_INVALID_ACTION,
1600 if (srw_req->record)
1602 const char *pack_str =
1603 yaz_srw_pack_to_str(srw_req->record->recordPacking);
1605 rr.record_packing = odr_strdup(assoc->encode, pack_str);
1608 if (srw_req->num_recordVersions)
1610 rr.record_versions = srw_req->recordVersions;
1611 rr.num_versions = srw_req->num_recordVersions;
1613 if (srw_req->extraRequestData_len)
1615 rr.extra_request_data = odr_strdupn(assoc->encode,
1616 srw_req->extraRequestData_buf,
1617 srw_req->extraRequestData_len );
1619 if (srw_res->num_diagnostics == 0)
1621 if ( assoc->init->bend_srw_update)
1622 (*assoc->init->bend_srw_update)(assoc->backend, &rr);
1624 yaz_add_sru_update_diagnostic(
1625 assoc->encode, &srw_res->diagnostics,
1626 &srw_res->num_diagnostics,
1627 YAZ_SRU_UPDATE_UNSPECIFIED_DATABASE_ERROR,
1628 "No Update backend handler");
1632 yaz_add_srw_diagnostic_uri(assoc->encode,
1633 &srw_res->diagnostics,
1634 &srw_res->num_diagnostics,
1638 srw_res->recordId = rr.record_id;
1639 srw_res->operationStatus = rr.operation_status;
1640 srw_res->recordVersions = rr.record_versions;
1641 srw_res->num_recordVersions = rr.num_versions;
1642 if (srw_res->extraResponseData_len)
1644 srw_res->extraResponseData_buf = rr.extra_response_data;
1645 srw_res->extraResponseData_len = strlen(rr.extra_response_data);
1647 if (srw_res->num_diagnostics == 0 && rr.record_data)
1649 srw_res->record = yaz_srw_get_record(assoc->encode);
1650 srw_res->record->recordSchema = rr.record_schema;
1651 if (rr.record_packing)
1653 int pack = yaz_srw_str_to_pack(rr.record_packing);
1657 pack = Z_SRW_recordPacking_string;
1658 yaz_log(YLOG_WARN, "Back packing %s from backend",
1661 srw_res->record->recordPacking = pack;
1663 srw_res->record->recordData_buf = rr.record_data;
1664 srw_res->record->recordData_len = strlen(rr.record_data);
1665 if (rr.extra_record_data)
1667 Z_SRW_extra_record *ex =
1668 yaz_srw_get_extra_record(assoc->encode);
1669 srw_res->extra_record = ex;
1670 ex->extraRecordData_buf = rr.extra_record_data;
1671 ex->extraRecordData_len = strlen(rr.extra_record_data);
1677 /* check if path is OK (1); BAD (0) */
1678 static int check_path(const char *path)
1682 if (strstr(path, ".."))
1687 static char *read_file(const char *fname, ODR o, int *sz)
1690 FILE *inf = fopen(fname, "rb");
1694 fseek(inf, 0L, SEEK_END);
1697 buf = (char *) odr_malloc(o, *sz);
1698 fread(buf, 1, *sz, inf);
1703 static void process_http_request(association *assoc, request *req)
1705 Z_HTTP_Request *hreq = req->gdu_request->u.HTTP_Request;
1706 ODR o = assoc->encode;
1707 int r = 2; /* 2=NOT TAKEN, 1=TAKEN, 0=SOAP TAKEN */
1709 Z_SOAP *soap_package = 0;
1712 Z_HTTP_Response *hres = 0;
1714 const char *stylesheet = 0; /* for now .. set later */
1715 Z_SRW_diagnostic *diagnostic = 0;
1716 int num_diagnostic = 0;
1717 const char *host = z_HTTP_header_lookup(hreq->headers, "Host");
1719 if (!control_association(assoc, host, 0))
1721 p = z_get_HTTP_Response(o, 404);
1724 if (r == 2 && assoc->server && assoc->server->docpath
1725 && hreq->path[0] == '/'
1727 /* check if path is a proper prefix of documentroot */
1728 strncmp(hreq->path+1, assoc->server->docpath,
1729 strlen(assoc->server->docpath))
1732 if (!check_path(hreq->path))
1734 yaz_log(YLOG_LOG, "File %s access forbidden", hreq->path+1);
1735 p = z_get_HTTP_Response(o, 404);
1739 int content_size = 0;
1740 char *content_buf = read_file(hreq->path+1, o, &content_size);
1743 yaz_log(YLOG_LOG, "File %s not found", hreq->path+1);
1744 p = z_get_HTTP_Response(o, 404);
1748 const char *ctype = 0;
1749 yaz_mime_types types = yaz_mime_types_create();
1751 yaz_mime_types_add(types, "xsl", "application/xml");
1752 yaz_mime_types_add(types, "xml", "application/xml");
1753 yaz_mime_types_add(types, "css", "text/css");
1754 yaz_mime_types_add(types, "html", "text/html");
1755 yaz_mime_types_add(types, "htm", "text/html");
1756 yaz_mime_types_add(types, "txt", "text/plain");
1757 yaz_mime_types_add(types, "js", "application/x-javascript");
1759 yaz_mime_types_add(types, "gif", "image/gif");
1760 yaz_mime_types_add(types, "png", "image/png");
1761 yaz_mime_types_add(types, "jpg", "image/jpeg");
1762 yaz_mime_types_add(types, "jpeg", "image/jpeg");
1764 ctype = yaz_mime_lookup_fname(types, hreq->path);
1767 yaz_log(YLOG_LOG, "No mime type for %s", hreq->path+1);
1768 p = z_get_HTTP_Response(o, 404);
1772 p = z_get_HTTP_Response(o, 200);
1773 hres = p->u.HTTP_Response;
1774 hres->content_buf = content_buf;
1775 hres->content_len = content_size;
1776 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1778 yaz_mime_types_destroy(types);
1786 r = yaz_srw_decode(hreq, &sr, &soap_package, assoc->decode, &charset);
1787 yaz_log(YLOG_DEBUG, "yaz_srw_decode returned %d", r);
1789 if (r == 2) /* not taken */
1791 r = yaz_sru_decode(hreq, &sr, &soap_package, assoc->decode, &charset,
1792 &diagnostic, &num_diagnostic);
1793 yaz_log(YLOG_DEBUG, "yaz_sru_decode returned %d", r);
1795 if (r == 0) /* decode SRW/SRU OK .. */
1797 int http_code = 200;
1798 if (sr->which == Z_SRW_searchRetrieve_request)
1801 yaz_srw_get_pdu(assoc->encode, Z_SRW_searchRetrieve_response,
1803 stylesheet = sr->u.request->stylesheet;
1806 res->u.response->diagnostics = diagnostic;
1807 res->u.response->num_diagnostics = num_diagnostic;
1811 srw_bend_search(assoc, req, sr, res->u.response,
1814 if (http_code == 200)
1815 soap_package->u.generic->p = res;
1817 else if (sr->which == Z_SRW_explain_request)
1819 Z_SRW_PDU *res = yaz_srw_get_pdu(o, Z_SRW_explain_response,
1821 stylesheet = sr->u.explain_request->stylesheet;
1824 res->u.explain_response->diagnostics = diagnostic;
1825 res->u.explain_response->num_diagnostics = num_diagnostic;
1827 srw_bend_explain(assoc, req, sr,
1828 res->u.explain_response, &http_code);
1829 if (http_code == 200)
1830 soap_package->u.generic->p = res;
1832 else if (sr->which == Z_SRW_scan_request)
1834 Z_SRW_PDU *res = yaz_srw_get_pdu(o, Z_SRW_scan_response,
1836 stylesheet = sr->u.scan_request->stylesheet;
1839 res->u.scan_response->diagnostics = diagnostic;
1840 res->u.scan_response->num_diagnostics = num_diagnostic;
1842 srw_bend_scan(assoc, req, sr,
1843 res->u.scan_response, &http_code);
1844 if (http_code == 200)
1845 soap_package->u.generic->p = res;
1847 else if (sr->which == Z_SRW_update_request)
1849 Z_SRW_PDU *res = yaz_srw_get_pdu(o, Z_SRW_update_response,
1851 yaz_log(YLOG_DEBUG, "handling SRW UpdateRequest");
1854 res->u.update_response->diagnostics = diagnostic;
1855 res->u.update_response->num_diagnostics = num_diagnostic;
1857 yaz_log(YLOG_DEBUG, "num_diag = %d", res->u.update_response->num_diagnostics );
1858 srw_bend_update(assoc, req, sr,
1859 res->u.update_response, &http_code);
1860 if (http_code == 200)
1861 soap_package->u.generic->p = res;
1865 yaz_log(log_request, "SOAP ERROR");
1866 /* FIXME - what error, what query */
1868 z_soap_error(assoc->encode, soap_package,
1869 "SOAP-ENV:Client", "Bad method", 0);
1871 if (http_code == 200 || http_code == 500)
1873 static Z_SOAP_Handler soap_handlers[4] = {
1875 {YAZ_XMLNS_SRU_v1_1, 0, (Z_SOAP_fun) yaz_srw_codec},
1876 {YAZ_XMLNS_SRU_v1_0, 0, (Z_SOAP_fun) yaz_srw_codec},
1877 {YAZ_XMLNS_UPDATE_v0_9, 0, (Z_SOAP_fun) yaz_ucp_codec},
1883 p = z_get_HTTP_Response(o, 200);
1884 hres = p->u.HTTP_Response;
1886 if (!stylesheet && assoc->server)
1887 stylesheet = assoc->server->stylesheet;
1889 /* empty stylesheet means NO stylesheet */
1890 if (stylesheet && *stylesheet == '\0')
1893 ret = z_soap_codec_enc_xsl(assoc->encode, &soap_package,
1894 &hres->content_buf, &hres->content_len,
1895 soap_handlers, charset, stylesheet);
1896 hres->code = http_code;
1898 strcpy(ctype, "text/xml");
1899 if (charset && strlen(charset) < sizeof(ctype)-30)
1901 strcat(ctype, "; charset=");
1902 strcat(ctype, charset);
1904 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1907 p = z_get_HTTP_Response(o, http_code);
1911 p = z_get_HTTP_Response(o, 500);
1912 hres = p->u.HTTP_Response;
1913 if (!strcmp(hreq->version, "1.0"))
1915 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1916 if (v && !strcmp(v, "Keep-Alive"))
1920 hres->version = "1.0";
1924 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1925 if (v && !strcmp(v, "close"))
1929 hres->version = "1.1";
1933 z_HTTP_header_add(o, &hres->headers, "Connection", "close");
1934 assoc->state = ASSOC_DEAD;
1935 assoc->cs_get_mask = 0;
1940 const char *alive = z_HTTP_header_lookup(hreq->headers, "Keep-Alive");
1942 if (alive && isdigit(*(const unsigned char *) alive))
1946 if (t < 0 || t > 3600)
1948 iochan_settimeout(assoc->client_chan,t);
1949 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1951 process_gdu_response(assoc, req, p);
1954 static void process_gdu_request(association *assoc, request *req)
1956 if (req->gdu_request->which == Z_GDU_Z3950)
1959 req->apdu_request = req->gdu_request->u.z3950;
1960 if (process_z_request(assoc, req, &msg) < 0)
1961 do_close_req(assoc, Z_Close_systemProblem, msg, req);
1963 else if (req->gdu_request->which == Z_GDU_HTTP_Request)
1964 process_http_request(assoc, req);
1967 do_close_req(assoc, Z_Close_systemProblem, "bad protocol packet", req);
1972 * Initiate request processing.
1974 static int process_z_request(association *assoc, request *req, char **msg)
1980 *msg = "Unknown Error";
1981 assert(req && req->state == REQUEST_IDLE);
1982 if (req->apdu_request->which != Z_APDU_initRequest && !assoc->init)
1984 *msg = "Missing InitRequest";
1987 switch (req->apdu_request->which)
1989 case Z_APDU_initRequest:
1990 res = process_initRequest(assoc, req); break;
1991 case Z_APDU_searchRequest:
1992 res = process_searchRequest(assoc, req, &fd); break;
1993 case Z_APDU_presentRequest:
1994 res = process_presentRequest(assoc, req, &fd); break;
1995 case Z_APDU_scanRequest:
1996 if (assoc->init->bend_scan)
1997 res = process_scanRequest(assoc, req, &fd);
2000 *msg = "Cannot handle Scan APDU";
2004 case Z_APDU_extendedServicesRequest:
2005 if (assoc->init->bend_esrequest)
2006 res = process_ESRequest(assoc, req, &fd);
2009 *msg = "Cannot handle Extended Services APDU";
2013 case Z_APDU_sortRequest:
2014 if (assoc->init->bend_sort)
2015 res = process_sortRequest(assoc, req, &fd);
2018 *msg = "Cannot handle Sort APDU";
2023 process_close(assoc, req);
2025 case Z_APDU_deleteResultSetRequest:
2026 if (assoc->init->bend_delete)
2027 res = process_deleteRequest(assoc, req, &fd);
2030 *msg = "Cannot handle Delete APDU";
2034 case Z_APDU_segmentRequest:
2035 if (assoc->init->bend_segment)
2037 res = process_segmentRequest (assoc, req);
2041 *msg = "Cannot handle Segment APDU";
2045 case Z_APDU_triggerResourceControlRequest:
2048 *msg = "Bad APDU received";
2053 yaz_log(YLOG_DEBUG, " result immediately available");
2054 retval = process_z_response(assoc, req, res);
2058 yaz_log(YLOG_DEBUG, " result unavailble");
2061 else /* no result yet - one will be provided later */
2065 /* Set up an I/O handler for the fd supplied by the backend */
2067 yaz_log(YLOG_DEBUG, " establishing handler for result");
2068 req->state = REQUEST_PENDING;
2069 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT, 0)))
2071 iochan_setdata(chan, assoc);
2078 * Handle message from the backend.
2080 void backend_response(IOCHAN i, int event)
2082 association *assoc = (association *)iochan_getdata(i);
2083 request *req = request_head(&assoc->incoming);
2087 yaz_log(YLOG_DEBUG, "backend_response");
2088 assert(assoc && req && req->state != REQUEST_IDLE);
2089 /* determine what it is we're waiting for */
2090 switch (req->apdu_request->which)
2092 case Z_APDU_searchRequest:
2093 res = response_searchRequest(assoc, req, 0, &fd); break;
2095 case Z_APDU_presentRequest:
2096 res = response_presentRequest(assoc, req, 0, &fd); break;
2097 case Z_APDU_scanRequest:
2098 res = response_scanRequest(assoc, req, 0, &fd); break;
2101 yaz_log(YLOG_FATAL, "Serious programmer's lapse or bug");
2104 if ((res && process_z_response(assoc, req, res) < 0) || fd < 0)
2106 yaz_log(YLOG_WARN, "Fatal error when talking to backend");
2107 do_close(assoc, Z_Close_systemProblem, 0);
2111 else if (!res) /* no result yet - try again later */
2113 yaz_log(YLOG_DEBUG, " no result yet");
2114 iochan_setfd(i, fd); /* in case fd has changed */
2119 * Encode response, and transfer the request structure to the outgoing queue.
2121 static int process_gdu_response(association *assoc, request *req, Z_GDU *res)
2123 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
2127 if (!z_GDU(assoc->print, &res, 0, 0))
2128 yaz_log(YLOG_WARN, "ODR print error: %s",
2129 odr_errmsg(odr_geterror(assoc->print)));
2130 odr_reset(assoc->print);
2132 if (!z_GDU(assoc->encode, &res, 0, 0))
2134 yaz_log(YLOG_WARN, "ODR error when encoding PDU: %s [element %s]",
2135 odr_errmsg(odr_geterror(assoc->decode)),
2136 odr_getelement(assoc->decode));
2139 req->response = odr_getbuf(assoc->encode, &req->len_response,
2140 &req->size_response);
2141 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
2142 odr_reset(assoc->encode);
2143 req->state = REQUEST_IDLE;
2144 request_enq(&assoc->outgoing, req);
2145 /* turn the work over to the ir_session handler */
2146 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
2147 assoc->cs_put_mask = EVENT_OUTPUT;
2148 /* Is there more work to be done? give that to the input handler too */
2151 req = request_head(&assoc->incoming);
2152 if (req && req->state == REQUEST_IDLE)
2154 request_deq(&assoc->incoming);
2155 process_gdu_request(assoc, req);
2164 * Encode response, and transfer the request structure to the outgoing queue.
2166 static int process_z_response(association *assoc, request *req, Z_APDU *res)
2168 Z_GDU *gres = (Z_GDU *) odr_malloc(assoc->encode, sizeof(*res));
2169 gres->which = Z_GDU_Z3950;
2170 gres->u.z3950 = res;
2172 return process_gdu_response(assoc, req, gres);
2175 static char *get_vhost(Z_OtherInformation *otherInfo)
2177 return yaz_oi_get_string_oid(&otherInfo, yaz_oid_userinfo_proxy, 1, 0);
2181 * Handle init request.
2182 * At the moment, we don't check the options
2183 * anywhere else in the code - we just try not to do anything that would
2184 * break a naive client. We'll toss 'em into the association block when
2185 * we need them there.
2187 static Z_APDU *process_initRequest(association *assoc, request *reqb)
2189 Z_InitRequest *req = reqb->apdu_request->u.initRequest;
2190 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
2191 Z_InitResponse *resp = apdu->u.initResponse;
2192 bend_initresult *binitres;
2195 statserv_options_block *cb = 0; /* by default no control for backend */
2197 if (control_association(assoc, get_vhost(req->otherInfo), 1))
2198 cb = statserv_getcontrol(); /* got control block for backend */
2200 if (cb && assoc->backend)
2201 (*cb->bend_close)(assoc->backend);
2203 yaz_log(log_requestdetail, "Got initRequest");
2204 if (req->implementationId)
2205 yaz_log(log_requestdetail, "Id: %s",
2206 req->implementationId);
2207 if (req->implementationName)
2208 yaz_log(log_requestdetail, "Name: %s",
2209 req->implementationName);
2210 if (req->implementationVersion)
2211 yaz_log(log_requestdetail, "Version: %s",
2212 req->implementationVersion);
2214 assoc_init_reset(assoc);
2216 assoc->init->auth = req->idAuthentication;
2217 assoc->init->referenceId = req->referenceId;
2219 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
2221 Z_CharSetandLanguageNegotiation *negotiation =
2222 yaz_get_charneg_record (req->otherInfo);
2224 negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
2225 assoc->init->charneg_request = negotiation;
2231 if (req->implementationVersion)
2232 yaz_log(log_requestdetail, "Config: %s",
2235 iochan_settimeout(assoc->client_chan, cb->idle_timeout * 60);
2237 /* we have a backend control block, so call that init function */
2238 if (!(binitres = (*cb->bend_init)(assoc->init)))
2240 yaz_log(YLOG_WARN, "Bad response from backend.");
2243 assoc->backend = binitres->handle;
2247 /* no backend. return error */
2248 binitres = (bend_initresult *)
2249 odr_malloc(assoc->encode, sizeof(*binitres));
2250 binitres->errstring = 0;
2251 binitres->errcode = YAZ_BIB1_PERMANENT_SYSTEM_ERROR;
2252 iochan_settimeout(assoc->client_chan, 10);
2254 if ((assoc->init->bend_sort))
2255 yaz_log (YLOG_DEBUG, "Sort handler installed");
2256 if ((assoc->init->bend_search))
2257 yaz_log (YLOG_DEBUG, "Search handler installed");
2258 if ((assoc->init->bend_present))
2259 yaz_log (YLOG_DEBUG, "Present handler installed");
2260 if ((assoc->init->bend_esrequest))
2261 yaz_log (YLOG_DEBUG, "ESRequest handler installed");
2262 if ((assoc->init->bend_delete))
2263 yaz_log (YLOG_DEBUG, "Delete handler installed");
2264 if ((assoc->init->bend_scan))
2265 yaz_log (YLOG_DEBUG, "Scan handler installed");
2266 if ((assoc->init->bend_segment))
2267 yaz_log (YLOG_DEBUG, "Segment handler installed");
2269 resp->referenceId = req->referenceId;
2271 /* let's tell the client what we can do */
2272 if (ODR_MASK_GET(req->options, Z_Options_search))
2274 ODR_MASK_SET(resp->options, Z_Options_search);
2275 strcat(options, "srch");
2277 if (ODR_MASK_GET(req->options, Z_Options_present))
2279 ODR_MASK_SET(resp->options, Z_Options_present);
2280 strcat(options, " prst");
2282 if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
2283 assoc->init->bend_delete)
2285 ODR_MASK_SET(resp->options, Z_Options_delSet);
2286 strcat(options, " del");
2288 if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
2289 assoc->init->bend_esrequest)
2291 ODR_MASK_SET(resp->options, Z_Options_extendedServices);
2292 strcat (options, " extendedServices");
2294 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
2296 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
2297 strcat(options, " namedresults");
2299 if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
2301 ODR_MASK_SET(resp->options, Z_Options_scan);
2302 strcat(options, " scan");
2304 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
2306 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
2307 strcat(options, " concurrop");
2309 if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
2311 ODR_MASK_SET(resp->options, Z_Options_sort);
2312 strcat(options, " sort");
2315 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
2317 Z_OtherInformationUnit *p0;
2319 if (!assoc->init->charneg_response)
2321 if (assoc->init->query_charset)
2323 assoc->init->charneg_response = yaz_set_response_charneg(
2324 assoc->encode, assoc->init->query_charset, 0,
2325 assoc->init->records_in_same_charset);
2329 yaz_log(YLOG_WARN, "default query_charset not defined by backend");
2332 if (assoc->init->charneg_response
2333 && (p0=yaz_oi_update(&resp->otherInfo, assoc->encode, NULL, 0, 0)))
2335 p0->which = Z_OtherInfo_externallyDefinedInfo;
2336 p0->information.externallyDefinedInfo =
2337 assoc->init->charneg_response;
2338 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
2339 strcat(options, " negotiation");
2342 if (ODR_MASK_GET(req->options, Z_Options_triggerResourceCtrl))
2343 ODR_MASK_SET(resp->options, Z_Options_triggerResourceCtrl);
2345 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
2347 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
2348 assoc->version = 1; /* 1 & 2 are equivalent */
2350 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
2352 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
2355 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
2357 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
2361 yaz_log(log_requestdetail, "Negotiated to v%d: %s", assoc->version, options);
2363 if (*req->maximumRecordSize < assoc->maximumRecordSize)
2364 assoc->maximumRecordSize = *req->maximumRecordSize;
2366 if (*req->preferredMessageSize < assoc->preferredMessageSize)
2367 assoc->preferredMessageSize = *req->preferredMessageSize;
2369 resp->preferredMessageSize = &assoc->preferredMessageSize;
2370 resp->maximumRecordSize = &assoc->maximumRecordSize;
2372 resp->implementationId = odr_prepend(assoc->encode,
2373 assoc->init->implementation_id,
2374 resp->implementationId);
2376 resp->implementationName = odr_prepend(assoc->encode,
2377 assoc->init->implementation_name,
2378 odr_prepend(assoc->encode, "GFS", resp->implementationName));
2380 version = odr_strdup(assoc->encode, "$Revision: 1.128 $");
2381 if (strlen(version) > 10) /* check for unexpanded CVS strings */
2382 version[strlen(version)-2] = '\0';
2383 resp->implementationVersion = odr_prepend(assoc->encode,
2384 assoc->init->implementation_version,
2385 odr_prepend(assoc->encode, &version[11],
2386 resp->implementationVersion));
2388 if (binitres->errcode)
2390 assoc->state = ASSOC_DEAD;
2391 resp->userInformationField =
2392 init_diagnostics(assoc->encode, binitres->errcode,
2393 binitres->errstring);
2398 if (!req->idAuthentication)
2399 yaz_log(log_request, "Auth none");
2400 else if (req->idAuthentication->which == Z_IdAuthentication_open)
2402 const char *open = req->idAuthentication->u.open;
2403 const char *slash = strchr(open, '/');
2409 yaz_log(log_request, "Auth open %.*s", len, open);
2411 else if (req->idAuthentication->which == Z_IdAuthentication_idPass)
2413 const char *user = req->idAuthentication->u.idPass->userId;
2414 const char *group = req->idAuthentication->u.idPass->groupId;
2415 yaz_log(log_request, "Auth idPass %s %s",
2416 user ? user : "-", group ? group : "-");
2418 else if (req->idAuthentication->which
2419 == Z_IdAuthentication_anonymous)
2421 yaz_log(log_request, "Auth anonymous");
2425 yaz_log(log_request, "Auth other");
2430 WRBUF wr = wrbuf_alloc();
2431 wrbuf_printf(wr, "Init ");
2432 if (binitres->errcode)
2433 wrbuf_printf(wr, "ERROR %d", binitres->errcode);
2435 wrbuf_printf(wr, "OK -");
2436 wrbuf_printf(wr, " ID:%s Name:%s Version:%s",
2437 (req->implementationId ? req->implementationId :"-"),
2438 (req->implementationName ?
2439 req->implementationName : "-"),
2440 (req->implementationVersion ?
2441 req->implementationVersion : "-")
2443 yaz_log(log_request, "%s", wrbuf_cstr(wr));
2450 * Set the specified `errcode' and `errstring' into a UserInfo-1
2451 * external to be returned to the client in accordance with Z35.90
2452 * Implementor Agreement 5 (Returning diagnostics in an InitResponse):
2453 * http://lcweb.loc.gov/z3950/agency/agree/initdiag.html
2455 static Z_External *init_diagnostics(ODR odr, int error, const char *addinfo)
2457 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2458 addinfo ? " -- " : "", addinfo ? addinfo : "");
2459 return zget_init_diagnostics(odr, error, addinfo);
2463 * nonsurrogate diagnostic record.
2465 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
2467 Z_Records *rec = (Z_Records *) odr_malloc (assoc->encode, sizeof(*rec));
2469 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2470 addinfo ? " -- " : "", addinfo ? addinfo : "");
2472 rec->which = Z_Records_NSD;
2473 rec->u.nonSurrogateDiagnostic = zget_DefaultDiagFormat(assoc->encode,
2479 * surrogate diagnostic.
2481 static Z_NamePlusRecord *surrogatediagrec(association *assoc,
2483 int error, const char *addinfo)
2485 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2486 addinfo ? " -- " : "", addinfo ? addinfo : "");
2487 return zget_surrogateDiagRec(assoc->encode, dbname, error, addinfo);
2490 static Z_Records *pack_records(association *a, char *setname, int start,
2491 int *num, Z_RecordComposition *comp,
2492 int *next, int *pres,
2493 Z_ReferenceId *referenceId,
2494 Odr_oid *oid, int *errcode)
2496 int recno, total_length = 0, toget = *num, dumped_records = 0;
2497 Z_Records *records =
2498 (Z_Records *) odr_malloc (a->encode, sizeof(*records));
2499 Z_NamePlusRecordList *reclist =
2500 (Z_NamePlusRecordList *) odr_malloc (a->encode, sizeof(*reclist));
2501 Z_NamePlusRecord **list =
2502 (Z_NamePlusRecord **) odr_malloc (a->encode, sizeof(*list) * toget);
2504 records->which = Z_Records_DBOSD;
2505 records->u.databaseOrSurDiagnostics = reclist;
2506 reclist->num_records = 0;
2507 reclist->records = list;
2508 *pres = Z_PresentStatus_success;
2512 yaz_log(log_requestdetail, "Request to pack %d+%d %s", start, toget, setname);
2513 yaz_log(log_requestdetail, "pms=%d, mrs=%d", a->preferredMessageSize,
2514 a->maximumRecordSize);
2515 for (recno = start; reclist->num_records < toget; recno++)
2518 Z_NamePlusRecord *thisrec;
2519 int this_length = 0;
2521 * we get the number of bytes allocated on the stream before any
2522 * allocation done by the backend - this should give us a reasonable
2523 * idea of the total size of the data so far.
2525 total_length = odr_total(a->encode) - dumped_records;
2531 freq.last_in_set = 0;
2532 freq.setname = setname;
2533 freq.surrogate_flag = 0;
2534 freq.number = recno;
2536 freq.request_format = oid;
2537 freq.output_format = 0;
2538 freq.stream = a->encode;
2539 freq.print = a->print;
2540 freq.referenceId = referenceId;
2543 retrieve_fetch(a, &freq);
2545 *next = freq.last_in_set ? 0 : recno + 1;
2547 /* backend should be able to signal whether error is system-wide
2548 or only pertaining to current record */
2551 if (!freq.surrogate_flag)
2554 *pres = Z_PresentStatus_failure;
2555 /* for 'present request out of range',
2556 set addinfo to record position if not set */
2557 if (freq.errcode == YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE &&
2558 freq.errstring == 0)
2560 sprintf (s, "%d", recno);
2564 *errcode = freq.errcode;
2565 return diagrec(a, freq.errcode, freq.errstring);
2567 reclist->records[reclist->num_records] =
2568 surrogatediagrec(a, freq.basename, freq.errcode,
2570 reclist->num_records++;
2573 if (freq.record == 0) /* no error and no record ? */
2575 *next = 0; /* signal end-of-set and stop */
2579 this_length = freq.len;
2581 this_length = odr_total(a->encode) - total_length - dumped_records;
2582 yaz_log(YLOG_DEBUG, " fetched record, len=%d, total=%d dumped=%d",
2583 this_length, total_length, dumped_records);
2584 if (a->preferredMessageSize > 0 &&
2585 this_length + total_length > a->preferredMessageSize)
2587 /* record is small enough, really */
2588 if (this_length <= a->preferredMessageSize && recno > start)
2590 yaz_log(log_requestdetail, " Dropped last normal-sized record");
2591 *pres = Z_PresentStatus_partial_2;
2594 /* record can only be fetched by itself */
2595 if (this_length < a->maximumRecordSize)
2597 yaz_log(log_requestdetail, " Record > prefmsgsz");
2600 yaz_log(YLOG_DEBUG, " Dropped it");
2601 reclist->records[reclist->num_records] =
2602 surrogatediagrec(a, freq.basename, 16, 0);
2603 reclist->num_records++;
2604 dumped_records += this_length;
2608 else /* too big entirely */
2610 yaz_log(log_requestdetail, "Record > maxrcdsz this=%d max=%d",
2611 this_length, a->maximumRecordSize);
2612 reclist->records[reclist->num_records] =
2613 surrogatediagrec(a, freq.basename, 17, 0);
2614 reclist->num_records++;
2615 dumped_records += this_length;
2620 if (!(thisrec = (Z_NamePlusRecord *)
2621 odr_malloc(a->encode, sizeof(*thisrec))))
2623 thisrec->databaseName = odr_strdup_null(a->encode, freq.basename);
2624 thisrec->which = Z_NamePlusRecord_databaseRecord;
2626 if (!freq.output_format)
2627 freq.output_format = freq.request_format;
2628 thisrec->u.databaseRecord = z_ext_record_oid(
2629 a->encode, freq.output_format, freq.record, freq.len);
2630 if (!thisrec->u.databaseRecord)
2632 reclist->records[reclist->num_records] = thisrec;
2633 reclist->num_records++;
2635 *num = reclist->num_records;
2639 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
2642 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2643 bend_search_rr *bsrr =
2644 (bend_search_rr *)nmem_malloc (reqb->request_mem, sizeof(*bsrr));
2646 yaz_log(log_requestdetail, "Got SearchRequest.");
2648 bsrr->request = reqb;
2649 bsrr->association = assoc;
2650 bsrr->referenceId = req->referenceId;
2651 save_referenceId (reqb, bsrr->referenceId);
2652 bsrr->srw_sortKeys = 0;
2653 bsrr->srw_setname = 0;
2654 bsrr->srw_setnameIdleTime = 0;
2655 bsrr->estimated_hit_count = 0;
2656 bsrr->partial_resultset = 0;
2658 yaz_log (log_requestdetail, "ResultSet '%s'", req->resultSetName);
2659 if (req->databaseNames)
2662 for (i = 0; i < req->num_databaseNames; i++)
2663 yaz_log(log_requestdetail, "Database '%s'", req->databaseNames[i]);
2666 yaz_log_zquery_level(log_requestdetail,req->query);
2668 if (assoc->init->bend_search)
2670 bsrr->setname = req->resultSetName;
2671 bsrr->replace_set = *req->replaceIndicator;
2672 bsrr->num_bases = req->num_databaseNames;
2673 bsrr->basenames = req->databaseNames;
2674 bsrr->query = req->query;
2675 bsrr->stream = assoc->encode;
2676 nmem_transfer(odr_getmem(bsrr->stream), reqb->request_mem);
2677 bsrr->decode = assoc->decode;
2678 bsrr->print = assoc->print;
2681 bsrr->errstring = NULL;
2682 bsrr->search_info = NULL;
2684 if (assoc->server && assoc->server->cql_transform
2685 && req->query->which == Z_Query_type_104
2686 && req->query->u.type_104->which == Z_External_CQL)
2688 /* have a CQL query and a CQL to PQF transform .. */
2690 cql2pqf(bsrr->stream, req->query->u.type_104->u.cql,
2691 assoc->server->cql_transform, bsrr->query);
2693 bsrr->errcode = yaz_diag_srw_to_bib1(srw_errcode);
2696 if (assoc->server && assoc->server->ccl_transform
2697 && req->query->which == Z_Query_type_2) /*CCL*/
2699 /* have a CCL query and a CCL to PQF transform .. */
2701 ccl2pqf(bsrr->stream, req->query->u.type_2,
2702 assoc->server->ccl_transform, bsrr);
2704 bsrr->errcode = yaz_diag_srw_to_bib1(srw_errcode);
2708 (assoc->init->bend_search)(assoc->backend, bsrr);
2709 if (!bsrr->request) /* backend not ready with the search response */
2710 return 0; /* should not be used any more */
2714 /* FIXME - make a diagnostic for it */
2715 yaz_log(YLOG_WARN,"Search not supported ?!?!");
2717 return response_searchRequest(assoc, reqb, bsrr, fd);
2720 int bend_searchresponse(void *handle, bend_search_rr *bsrr) {return 0;}
2723 * Prepare a searchresponse based on the backend results. We probably want
2724 * to look at making the fetching of records nonblocking as well, but
2725 * so far, we'll keep things simple.
2726 * If bsrt is null, that means we're called in response to a communications
2727 * event, and we'll have to get the response for ourselves.
2729 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
2730 bend_search_rr *bsrt, int *fd)
2732 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2733 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2734 Z_SearchResponse *resp = (Z_SearchResponse *)
2735 odr_malloc (assoc->encode, sizeof(*resp));
2736 int *nulint = odr_intdup (assoc->encode, 0);
2737 int *next = odr_intdup(assoc->encode, 0);
2738 int *none = odr_intdup(assoc->encode, Z_SearchResponse_none);
2739 int returnedrecs = 0;
2741 apdu->which = Z_APDU_searchResponse;
2742 apdu->u.searchResponse = resp;
2743 resp->referenceId = req->referenceId;
2744 resp->additionalSearchInfo = 0;
2745 resp->otherInfo = 0;
2747 if (!bsrt && !bend_searchresponse(assoc->backend, bsrt))
2749 yaz_log(YLOG_FATAL, "Bad result from backend");
2752 else if (bsrt->errcode)
2754 resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
2755 resp->resultCount = nulint;
2756 resp->numberOfRecordsReturned = nulint;
2757 resp->nextResultSetPosition = nulint;
2758 resp->searchStatus = nulint;
2759 resp->resultSetStatus = none;
2760 resp->presentStatus = 0;
2764 bool_t *sr = odr_intdup(assoc->encode, 1);
2765 int *toget = odr_intdup(assoc->encode, 0);
2766 Z_RecordComposition comp, *compp = 0;
2768 yaz_log (log_requestdetail, "resultCount: %d", bsrt->hits);
2771 resp->resultCount = &bsrt->hits;
2773 comp.which = Z_RecordComp_simple;
2774 /* how many records does the user agent want, then? */
2775 if (bsrt->hits <= *req->smallSetUpperBound)
2777 *toget = bsrt->hits;
2778 if ((comp.u.simple = req->smallSetElementSetNames))
2781 else if (bsrt->hits < *req->largeSetLowerBound)
2783 *toget = *req->mediumSetPresentNumber;
2784 if (*toget > bsrt->hits)
2785 *toget = bsrt->hits;
2786 if ((comp.u.simple = req->mediumSetElementSetNames))
2792 if (*toget && !resp->records)
2794 int *presst = odr_intdup(assoc->encode, 0);
2795 /* Call bend_present if defined */
2796 if (assoc->init->bend_present)
2798 bend_present_rr *bprr = (bend_present_rr *)
2799 nmem_malloc (reqb->request_mem, sizeof(*bprr));
2800 bprr->setname = req->resultSetName;
2802 bprr->number = *toget;
2803 bprr->format = req->preferredRecordSyntax;
2805 bprr->referenceId = req->referenceId;
2806 bprr->stream = assoc->encode;
2807 bprr->print = assoc->print;
2808 bprr->request = reqb;
2809 bprr->association = assoc;
2811 bprr->errstring = NULL;
2812 (*assoc->init->bend_present)(assoc->backend, bprr);
2818 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2819 *resp->presentStatus = Z_PresentStatus_failure;
2824 resp->records = pack_records(
2825 assoc, req->resultSetName, 1,
2826 toget, compp, next, presst, req->referenceId,
2827 req->preferredRecordSyntax, NULL);
2830 resp->numberOfRecordsReturned = toget;
2831 returnedrecs = *toget;
2832 resp->presentStatus = presst;
2836 if (*resp->resultCount)
2838 resp->numberOfRecordsReturned = nulint;
2839 resp->presentStatus = 0;
2841 resp->nextResultSetPosition = next;
2842 resp->searchStatus = sr;
2843 resp->resultSetStatus = 0;
2844 if (bsrt->estimated_hit_count)
2846 resp->resultSetStatus = odr_intdup(assoc->encode,
2847 Z_SearchResponse_estimate);
2849 else if (bsrt->partial_resultset)
2851 resp->resultSetStatus = odr_intdup(assoc->encode,
2852 Z_SearchResponse_subset);
2855 resp->additionalSearchInfo = bsrt->search_info;
2860 WRBUF wr = wrbuf_alloc();
2862 for (i = 0 ; i < req->num_databaseNames; i++){
2864 wrbuf_printf(wr, "+");
2865 wrbuf_printf(wr, req->databaseNames[i]);
2867 wrbuf_printf(wr, " ");
2870 wrbuf_printf(wr, "ERROR %d", bsrt->errcode);
2872 wrbuf_printf(wr, "OK %d", bsrt->hits);
2873 wrbuf_printf(wr, " %s 1+%d ",
2874 req->resultSetName, returnedrecs);
2875 yaz_query_to_wrbuf(wr, req->query);
2877 yaz_log(log_request, "Search %s", wrbuf_cstr(wr));
2884 * Maybe we got a little over-friendly when we designed bend_fetch to
2885 * get only one record at a time. Some backends can optimise multiple-record
2886 * fetches, and at any rate, there is some overhead involved in
2887 * all that selecting and hopping around. Problem is, of course, that the
2888 * frontend can't know ahead of time how many records it'll need to
2889 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
2890 * is downright lousy as a bulk data transfer protocol.
2892 * To start with, we'll do the fetching of records from the backend
2893 * in one operation: To save some trips in and out of the event-handler,
2894 * and to simplify the interface to pack_records. At any rate, asynch
2895 * operation is more fun in operations that have an unpredictable execution
2896 * speed - which is normally more true for search than for present.
2898 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
2901 Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
2903 Z_PresentResponse *resp;
2907 const char *errstring = 0;
2909 yaz_log(log_requestdetail, "Got PresentRequest.");
2911 resp = (Z_PresentResponse *)odr_malloc (assoc->encode, sizeof(*resp));
2913 resp->presentStatus = odr_intdup(assoc->encode, 0);
2914 if (assoc->init->bend_present)
2916 bend_present_rr *bprr = (bend_present_rr *)
2917 nmem_malloc (reqb->request_mem, sizeof(*bprr));
2918 bprr->setname = req->resultSetId;
2919 bprr->start = *req->resultSetStartPoint;
2920 bprr->number = *req->numberOfRecordsRequested;
2921 bprr->format = req->preferredRecordSyntax;
2922 bprr->comp = req->recordComposition;
2923 bprr->referenceId = req->referenceId;
2924 bprr->stream = assoc->encode;
2925 bprr->print = assoc->print;
2926 bprr->request = reqb;
2927 bprr->association = assoc;
2929 bprr->errstring = NULL;
2930 (*assoc->init->bend_present)(assoc->backend, bprr);
2933 return 0; /* should not happen */
2936 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2937 *resp->presentStatus = Z_PresentStatus_failure;
2938 errcode = bprr->errcode;
2939 errstring = bprr->errstring;
2942 apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2943 next = odr_intdup(assoc->encode, 0);
2944 num = odr_intdup(assoc->encode, 0);
2946 apdu->which = Z_APDU_presentResponse;
2947 apdu->u.presentResponse = resp;
2948 resp->referenceId = req->referenceId;
2949 resp->otherInfo = 0;
2953 *num = *req->numberOfRecordsRequested;
2955 pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
2956 num, req->recordComposition, next,
2957 resp->presentStatus,
2958 req->referenceId, req->preferredRecordSyntax,
2963 WRBUF wr = wrbuf_alloc();
2964 wrbuf_printf(wr, "Present ");
2966 if (*resp->presentStatus == Z_PresentStatus_failure)
2967 wrbuf_printf(wr, "ERROR %d ", errcode);
2968 else if (*resp->presentStatus == Z_PresentStatus_success)
2969 wrbuf_printf(wr, "OK - ");
2971 wrbuf_printf(wr, "Partial %d - ", *resp->presentStatus);
2973 wrbuf_printf(wr, " %s %d+%d ",
2974 req->resultSetId, *req->resultSetStartPoint,
2975 *req->numberOfRecordsRequested);
2976 yaz_log(log_request, "%s", wrbuf_cstr(wr) );
2981 resp->numberOfRecordsReturned = num;
2982 resp->nextResultSetPosition = next;
2988 * Scan was implemented rather in a hurry, and with support for only the basic
2989 * elements of the service in the backend API. Suggestions are welcome.
2991 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
2993 Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
2994 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2995 Z_ScanResponse *res = (Z_ScanResponse *)
2996 odr_malloc (assoc->encode, sizeof(*res));
2997 int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
2998 int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
2999 Z_ListEntries *ents = (Z_ListEntries *)
3000 odr_malloc (assoc->encode, sizeof(*ents));
3001 Z_DiagRecs *diagrecs_p = NULL;
3002 bend_scan_rr *bsrr = (bend_scan_rr *)
3003 odr_malloc (assoc->encode, sizeof(*bsrr));
3004 struct scan_entry *save_entries;
3006 yaz_log(log_requestdetail, "Got ScanRequest");
3008 apdu->which = Z_APDU_scanResponse;
3009 apdu->u.scanResponse = res;
3010 res->referenceId = req->referenceId;
3012 /* if step is absent, set it to 0 */
3013 res->stepSize = odr_intdup(assoc->encode, 0);
3015 *res->stepSize = *req->stepSize;
3017 res->scanStatus = scanStatus;
3018 res->numberOfEntriesReturned = numberOfEntriesReturned;
3019 res->positionOfTerm = 0;
3020 res->entries = ents;
3021 ents->num_entries = 0;
3022 ents->entries = NULL;
3023 ents->num_nonsurrogateDiagnostics = 0;
3024 ents->nonsurrogateDiagnostics = NULL;
3025 res->attributeSet = 0;
3028 if (req->databaseNames)
3031 for (i = 0; i < req->num_databaseNames; i++)
3032 yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
3034 bsrr->scanClause = 0;
3036 bsrr->errstring = 0;
3037 bsrr->num_bases = req->num_databaseNames;
3038 bsrr->basenames = req->databaseNames;
3039 bsrr->num_entries = *req->numberOfTermsRequested;
3040 bsrr->term = req->termListAndStartPoint;
3041 bsrr->referenceId = req->referenceId;
3042 bsrr->stream = assoc->encode;
3043 bsrr->print = assoc->print;
3044 bsrr->step_size = res->stepSize;
3045 bsrr->setname = yaz_oi_get_string_oid(&req->otherInfo,
3046 yaz_oid_userinfo_scan_set, 1, 0);
3048 /* For YAZ 2.0 and earlier it was the backend handler that
3049 initialized entries (member display_term did not exist)
3050 YAZ 2.0 and later sets 'entries' and initialize all members
3051 including 'display_term'. If YAZ 2.0 or later sees that
3052 entries was modified - we assume that it is an old handler and
3053 that 'display_term' is _not_ set.
3055 if (bsrr->num_entries > 0)
3058 bsrr->entries = (struct scan_entry *)
3059 odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
3061 for (i = 0; i<bsrr->num_entries; i++)
3063 bsrr->entries[i].term = 0;
3064 bsrr->entries[i].occurrences = 0;
3065 bsrr->entries[i].errcode = 0;
3066 bsrr->entries[i].errstring = 0;
3067 bsrr->entries[i].display_term = 0;
3070 save_entries = bsrr->entries; /* save it so we can compare later */
3072 bsrr->attributeset = req->attributeSet;
3073 log_scan_term_level (log_requestdetail, req->termListAndStartPoint,
3074 bsrr->attributeset);
3075 bsrr->term_position = req->preferredPositionInResponse ?
3076 *req->preferredPositionInResponse : 1;
3078 ((int (*)(void *, bend_scan_rr *))
3079 (*assoc->init->bend_scan))(assoc->backend, bsrr);
3082 diagrecs_p = zget_DiagRecs(assoc->encode,
3083 bsrr->errcode, bsrr->errstring);
3087 Z_Entry **tab = (Z_Entry **)
3088 odr_malloc (assoc->encode, sizeof(*tab) * bsrr->num_entries);
3090 if (bsrr->status == BEND_SCAN_PARTIAL)
3091 *scanStatus = Z_Scan_partial_5;
3093 *scanStatus = Z_Scan_success;
3094 ents->entries = tab;
3095 ents->num_entries = bsrr->num_entries;
3096 res->numberOfEntriesReturned = &ents->num_entries;
3097 res->positionOfTerm = &bsrr->term_position;
3098 for (i = 0; i < bsrr->num_entries; i++)
3104 tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
3105 if (bsrr->entries[i].occurrences >= 0)
3107 e->which = Z_Entry_termInfo;
3108 e->u.termInfo = t = (Z_TermInfo *)
3109 odr_malloc(assoc->encode, sizeof(*t));
3110 t->suggestedAttributes = 0;
3112 if (save_entries == bsrr->entries &&
3113 bsrr->entries[i].display_term)
3115 /* the entries was _not_ set by the handler. So it's
3116 safe to test for new member display_term. It is
3119 t->displayTerm = odr_strdup(assoc->encode,
3120 bsrr->entries[i].display_term);
3122 t->alternativeTerm = 0;
3123 t->byAttributes = 0;
3124 t->otherTermInfo = 0;
3125 t->globalOccurrences = &bsrr->entries[i].occurrences;
3126 t->term = (Z_Term *)
3127 odr_malloc(assoc->encode, sizeof(*t->term));
3128 t->term->which = Z_Term_general;
3129 t->term->u.general = o =
3130 (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
3131 o->buf = (unsigned char *)
3132 odr_malloc(assoc->encode, o->len = o->size =
3133 strlen(bsrr->entries[i].term));
3134 memcpy(o->buf, bsrr->entries[i].term, o->len);
3135 yaz_log(YLOG_DEBUG, " term #%d: '%s' (%d)", i,
3136 bsrr->entries[i].term, bsrr->entries[i].occurrences);
3140 Z_DiagRecs *drecs = zget_DiagRecs(assoc->encode,
3141 bsrr->entries[i].errcode,
3142 bsrr->entries[i].errstring);
3143 assert (drecs->num_diagRecs == 1);
3144 e->which = Z_Entry_surrogateDiagnostic;
3145 assert (drecs->diagRecs[0]);
3146 e->u.surrogateDiagnostic = drecs->diagRecs[0];
3152 ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
3153 ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
3158 WRBUF wr = wrbuf_alloc();
3159 wrbuf_printf(wr, "Scan ");
3160 for (i = 0 ; i < req->num_databaseNames; i++)
3163 wrbuf_printf(wr, "+");
3164 wrbuf_printf(wr, req->databaseNames[i]);
3167 wrbuf_printf(wr, " ");
3170 wr_diag(wr, bsrr->errcode, bsrr->errstring);
3172 wrbuf_printf(wr, "OK");
3174 wrbuf_printf(wr, " %d - %d+%d+%d",
3175 res->numberOfEntriesReturned ?
3176 *res->numberOfEntriesReturned : 0,
3177 (req->preferredPositionInResponse ?
3178 *req->preferredPositionInResponse : 1),
3179 *req->numberOfTermsRequested,
3180 (res->stepSize ? *res->stepSize : 1));
3183 wrbuf_printf(wr, "+%s", bsrr->setname);
3185 wrbuf_printf(wr, " ");
3186 yaz_scan_to_wrbuf(wr, req->termListAndStartPoint,
3187 bsrr->attributeset);
3188 yaz_log(log_request, "%s", wrbuf_cstr(wr) );
3194 static Z_APDU *process_sortRequest(association *assoc, request *reqb,
3198 Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
3199 Z_SortResponse *res = (Z_SortResponse *)
3200 odr_malloc (assoc->encode, sizeof(*res));
3201 bend_sort_rr *bsrr = (bend_sort_rr *)
3202 odr_malloc (assoc->encode, sizeof(*bsrr));
3204 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
3206 yaz_log(log_requestdetail, "Got SortRequest.");
3208 bsrr->num_input_setnames = req->num_inputResultSetNames;
3209 for (i=0;i<req->num_inputResultSetNames;i++)
3210 yaz_log(log_requestdetail, "Input resultset: '%s'",
3211 req->inputResultSetNames[i]);
3212 bsrr->input_setnames = req->inputResultSetNames;
3213 bsrr->referenceId = req->referenceId;
3214 bsrr->output_setname = req->sortedResultSetName;
3215 yaz_log(log_requestdetail, "Output resultset: '%s'",
3216 req->sortedResultSetName);
3217 bsrr->sort_sequence = req->sortSequence;
3218 /*FIXME - dump those sequences too */
3219 bsrr->stream = assoc->encode;
3220 bsrr->print = assoc->print;
3222 bsrr->sort_status = Z_SortResponse_failure;
3224 bsrr->errstring = 0;
3226 (*assoc->init->bend_sort)(assoc->backend, bsrr);
3228 res->referenceId = bsrr->referenceId;
3229 res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
3230 res->resultSetStatus = 0;
3233 Z_DiagRecs *dr = zget_DiagRecs(assoc->encode,
3234 bsrr->errcode, bsrr->errstring);
3235 res->diagnostics = dr->diagRecs;
3236 res->num_diagnostics = dr->num_diagRecs;
3240 res->num_diagnostics = 0;
3241 res->diagnostics = 0;
3243 res->resultCount = 0;
3246 apdu->which = Z_APDU_sortResponse;
3247 apdu->u.sortResponse = res;
3250 WRBUF wr = wrbuf_alloc();
3251 wrbuf_printf(wr, "Sort ");
3253 wrbuf_printf(wr, " ERROR %d", bsrr->errcode);
3255 wrbuf_printf(wr, "OK -");
3256 wrbuf_printf(wr, " (");
3257 for (i = 0; i<req->num_inputResultSetNames; i++)
3260 wrbuf_printf(wr, "+");
3261 wrbuf_printf(wr, req->inputResultSetNames[i]);
3263 wrbuf_printf(wr, ")->%s ",req->sortedResultSetName);
3265 yaz_log(log_request, "%s", wrbuf_cstr(wr) );
3271 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
3275 Z_DeleteResultSetRequest *req =
3276 reqb->apdu_request->u.deleteResultSetRequest;
3277 Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
3278 odr_malloc (assoc->encode, sizeof(*res));
3279 bend_delete_rr *bdrr = (bend_delete_rr *)
3280 odr_malloc (assoc->encode, sizeof(*bdrr));
3281 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
3283 yaz_log(log_requestdetail, "Got DeleteRequest.");
3285 bdrr->num_setnames = req->num_resultSetList;
3286 bdrr->setnames = req->resultSetList;
3287 for (i = 0; i<req->num_resultSetList; i++)
3288 yaz_log(log_requestdetail, "resultset: '%s'",
3289 req->resultSetList[i]);
3290 bdrr->stream = assoc->encode;
3291 bdrr->print = assoc->print;
3292 bdrr->function = *req->deleteFunction;
3293 bdrr->referenceId = req->referenceId;
3295 if (bdrr->num_setnames > 0)
3297 bdrr->statuses = (int*)
3298 odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
3299 bdrr->num_setnames);
3300 for (i = 0; i < bdrr->num_setnames; i++)
3301 bdrr->statuses[i] = 0;
3303 (*assoc->init->bend_delete)(assoc->backend, bdrr);
3305 res->referenceId = req->referenceId;
3307 res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
3309 res->deleteListStatuses = 0;
3310 if (bdrr->num_setnames > 0)
3313 res->deleteListStatuses = (Z_ListStatuses *)
3314 odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
3315 res->deleteListStatuses->num = bdrr->num_setnames;
3316 res->deleteListStatuses->elements =
3318 odr_malloc (assoc->encode,
3319 sizeof(*res->deleteListStatuses->elements) *
3320 bdrr->num_setnames);
3321 for (i = 0; i<bdrr->num_setnames; i++)
3323 res->deleteListStatuses->elements[i] =
3325 odr_malloc (assoc->encode,
3326 sizeof(**res->deleteListStatuses->elements));
3327 res->deleteListStatuses->elements[i]->status = bdrr->statuses+i;
3328 res->deleteListStatuses->elements[i]->id =
3329 odr_strdup (assoc->encode, bdrr->setnames[i]);
3332 res->numberNotDeleted = 0;
3333 res->bulkStatuses = 0;
3334 res->deleteMessage = 0;
3337 apdu->which = Z_APDU_deleteResultSetResponse;
3338 apdu->u.deleteResultSetResponse = res;
3341 WRBUF wr = wrbuf_alloc();
3342 wrbuf_printf(wr, "Delete ");
3343 if (bdrr->delete_status)
3344 wrbuf_printf(wr, "ERROR %d", bdrr->delete_status);
3346 wrbuf_printf(wr, "OK -");
3347 for (i = 0; i<req->num_resultSetList; i++)
3348 wrbuf_printf(wr, " %s ", req->resultSetList[i]);
3349 yaz_log(log_request, "%s", wrbuf_cstr(wr) );
3355 static void process_close(association *assoc, request *reqb)
3357 Z_Close *req = reqb->apdu_request->u.close;
3358 static char *reasons[] =
3365 "securityViolation",
3372 yaz_log(log_requestdetail, "Got Close, reason %s, message %s",
3373 reasons[*req->closeReason], req->diagnosticInformation ?
3374 req->diagnosticInformation : "NULL");
3375 if (assoc->version < 3) /* to make do_force respond with close */
3377 do_close_req(assoc, Z_Close_finished,
3378 "Association terminated by client", reqb);
3379 yaz_log(log_request,"Close OK");
3382 void save_referenceId (request *reqb, Z_ReferenceId *refid)
3386 reqb->len_refid = refid->len;
3387 reqb->refid = (char *)nmem_malloc (reqb->request_mem, refid->len);
3388 memcpy (reqb->refid, refid->buf, refid->len);
3392 reqb->len_refid = 0;
3397 void bend_request_send (bend_association a, bend_request req, Z_APDU *res)
3399 process_z_response (a, req, res);
3402 bend_request bend_request_mk (bend_association a)
3404 request *nreq = request_get (&a->outgoing);
3405 nreq->request_mem = nmem_create ();
3409 Z_ReferenceId *bend_request_getid (ODR odr, bend_request req)
3414 id = (Odr_oct *)odr_malloc (odr, sizeof(*odr));
3415 id->buf = (unsigned char *)odr_malloc (odr, req->len_refid);
3416 id->len = id->size = req->len_refid;
3417 memcpy (id->buf, req->refid, req->len_refid);
3421 void bend_request_destroy (bend_request *req)
3423 nmem_destroy((*req)->request_mem);
3424 request_release(*req);
3428 int bend_backend_respond (bend_association a, bend_request req)
3432 r = process_z_request (a, req, &msg);
3434 yaz_log (YLOG_WARN, "%s", msg);
3438 void bend_request_setdata(bend_request r, void *p)
3443 void *bend_request_getdata(bend_request r)
3445 return r->clientData;
3448 static Z_APDU *process_segmentRequest (association *assoc, request *reqb)
3450 bend_segment_rr req;
3452 req.segment = reqb->apdu_request->u.segmentRequest;
3453 req.stream = assoc->encode;
3454 req.decode = assoc->decode;
3455 req.print = assoc->print;
3456 req.association = assoc;
3458 (*assoc->init->bend_segment)(assoc->backend, &req);
3463 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd)
3465 bend_esrequest_rr esrequest;
3466 const char *ext_name = "unknown";
3468 Z_ExtendedServicesRequest *req =
3469 reqb->apdu_request->u.extendedServicesRequest;
3470 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
3472 Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
3474 esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
3475 esrequest.stream = assoc->encode;
3476 esrequest.decode = assoc->decode;
3477 esrequest.print = assoc->print;
3478 esrequest.errcode = 0;
3479 esrequest.errstring = NULL;
3480 esrequest.request = reqb;
3481 esrequest.association = assoc;
3482 esrequest.taskPackage = 0;
3483 esrequest.referenceId = req->referenceId;
3486 if (esrequest.esr && esrequest.esr->taskSpecificParameters)
3488 switch(esrequest.esr->taskSpecificParameters->which)
3490 case Z_External_itemOrder:
3491 ext_name = "ItemOrder"; break;
3492 case Z_External_update:
3493 ext_name = "Update"; break;
3494 case Z_External_update0:
3495 ext_name = "Update0"; break;
3496 case Z_External_ESAdmin:
3497 ext_name = "Admin"; break;
3502 (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
3504 /* If the response is being delayed, return NULL */
3505 if (esrequest.request == NULL)
3508 resp->referenceId = req->referenceId;
3510 if (esrequest.errcode == -1)
3512 /* Backend service indicates request will be processed */
3513 yaz_log(log_request, "Extended Service: %s (accepted)", ext_name);
3514 *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
3516 else if (esrequest.errcode == 0)
3518 /* Backend service indicates request will be processed */
3519 yaz_log(log_request, "Extended Service: %s (done)", ext_name);
3520 *resp->operationStatus = Z_ExtendedServicesResponse_done;
3524 Z_DiagRecs *diagRecs =
3525 zget_DiagRecs(assoc->encode, esrequest.errcode,
3526 esrequest.errstring);
3527 /* Backend indicates error, request will not be processed */
3528 yaz_log(log_request, "Extended Service: %s (failed)", ext_name);
3529 *resp->operationStatus = Z_ExtendedServicesResponse_failure;
3530 resp->num_diagnostics = diagRecs->num_diagRecs;
3531 resp->diagnostics = diagRecs->diagRecs;
3534 WRBUF wr = wrbuf_alloc();
3535 wrbuf_diags(wr, resp->num_diagnostics, resp->diagnostics);
3536 yaz_log(log_request, "EsRequest %s", wrbuf_cstr(wr) );
3541 /* Do something with the members of bend_extendedservice */
3542 if (esrequest.taskPackage)
3544 resp->taskPackage = z_ext_record_oid(
3545 assoc->encode, yaz_oid_recsyn_extended,
3546 (const char *) esrequest.taskPackage, -1
3549 yaz_log(YLOG_DEBUG,"Send the result apdu");
3553 int bend_assoc_is_alive(bend_association assoc)
3555 if (assoc->state == ASSOC_DEAD)
3556 return 0; /* already marked as dead. Don't check I/O chan anymore */
3558 return iochan_is_alive(assoc->client_chan);
3565 * indent-tabs-mode: nil
3567 * vim: shiftwidth=4 tabstop=8 expandtab