2 * Copyright (C) 1995-2007, Index Data ApS
3 * See the file LICENSE for details.
5 * $Id: seshigh.c,v 1.125 2007-08-21 13:20:51 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);
771 record->recordSchema = odr_strdup(o, rr.schema);
773 record->recordSchema = 0;
777 *addinfo = rr.errstring;
783 static int cql2pqf(ODR odr, const char *cql, cql_transform_t ct,
784 Z_Query *query_result)
786 /* have a CQL query and CQL to PQF transform .. */
787 CQL_parser cp = cql_parser_create();
793 r = cql_parser_string(cp, cql);
796 /* CQL syntax error */
802 r = cql_transform_buf(ct,
803 cql_parser_result(cp),
804 rpn_buf, sizeof(rpn_buf)-1);
806 srw_errcode = cql_transform_error(ct, &add);
810 /* Syntax & transform OK. */
811 /* Convert PQF string to Z39.50 to RPN query struct */
812 YAZ_PQF_Parser pp = yaz_pqf_create();
813 Z_RPNQuery *rpnquery = yaz_pqf_parse(pp, odr, rpn_buf);
818 int code = yaz_pqf_error(pp, &pqf_msg, &off);
819 yaz_log(YLOG_WARN, "PQF Parser Error %s (code %d)",
825 query_result->which = Z_Query_type_1;
826 query_result->u.type_1 = rpnquery;
830 cql_parser_destroy(cp);
834 static int cql2pqf_scan(ODR odr, const char *cql, cql_transform_t ct,
835 Z_AttributesPlusTerm *result)
839 int srw_error = cql2pqf(odr, cql, ct, &query);
842 if (query.which != Z_Query_type_1 && query.which != Z_Query_type_101)
843 return 10; /* bad query type */
844 rpn = query.u.type_1;
845 if (!rpn->RPNStructure)
846 return 10; /* must be structure */
847 if (rpn->RPNStructure->which != Z_RPNStructure_simple)
848 return 10; /* must be simple */
849 if (rpn->RPNStructure->u.simple->which != Z_Operand_APT)
850 return 10; /* must be attributes plus term node .. */
851 memcpy(result, rpn->RPNStructure->u.simple->u.attributesPlusTerm,
857 static int ccl2pqf(ODR odr, const Odr_oct *ccl, CCL_bibset bibset,
858 bend_search_rr *bsrr) {
860 struct ccl_rpn_node *node;
863 ccl0 = odr_strdupn(odr, (char*) ccl->buf, ccl->len);
864 if ((node = ccl_find_str(bibset, ccl0, &errcode, &pos)) == 0) {
865 bsrr->errstring = (char*) ccl_err_msg(errcode);
866 return 10; /* Query syntax error */
869 bsrr->query->which = Z_Query_type_1;
870 bsrr->query->u.type_1 = ccl_rpn_query(odr, node);
875 static void srw_bend_search(association *assoc, request *req,
877 Z_SRW_searchRetrieveResponse *srw_res,
882 Z_SRW_searchRetrieveRequest *srw_req = sr->u.request;
885 yaz_log(log_requestdetail, "Got SRW SearchRetrieveRequest");
886 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
887 if (srw_res->num_diagnostics == 0 && assoc->init)
890 rr.setname = "default";
893 rr.basenames = &srw_req->database;
897 rr.srw_setnameIdleTime = 0;
898 rr.estimated_hit_count = 0;
899 rr.partial_resultset = 0;
900 rr.query = (Z_Query *) odr_malloc (assoc->decode, sizeof(*rr.query));
901 rr.query->u.type_1 = 0;
903 if (srw_req->query_type == Z_SRW_query_type_cql)
905 if (assoc->server && assoc->server->cql_transform)
907 int srw_errcode = cql2pqf(assoc->encode, srw_req->query.cql,
908 assoc->server->cql_transform,
912 yaz_add_srw_diagnostic(assoc->encode,
913 &srw_res->diagnostics,
914 &srw_res->num_diagnostics,
920 /* CQL query to backend. Wrap it - Z39.50 style */
921 ext = (Z_External *) odr_malloc(assoc->decode, sizeof(*ext));
922 ext->direct_reference = odr_getoidbystr(assoc->decode,
923 "1.2.840.10003.16.2");
924 ext->indirect_reference = 0;
926 ext->which = Z_External_CQL;
927 ext->u.cql = srw_req->query.cql;
929 rr.query->which = Z_Query_type_104;
930 rr.query->u.type_104 = ext;
933 else if (srw_req->query_type == Z_SRW_query_type_pqf)
935 Z_RPNQuery *RPNquery;
936 YAZ_PQF_Parser pqf_parser;
938 pqf_parser = yaz_pqf_create ();
940 RPNquery = yaz_pqf_parse (pqf_parser, assoc->decode,
946 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
947 yaz_log(log_requestdetail, "Parse error %d %s near offset %ld",
948 code, pqf_msg, (long) off);
949 srw_error = YAZ_SRW_QUERY_SYNTAX_ERROR;
952 rr.query->which = Z_Query_type_1;
953 rr.query->u.type_1 = RPNquery;
955 yaz_pqf_destroy (pqf_parser);
959 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
960 &srw_res->num_diagnostics,
961 YAZ_SRW_UNSUPP_QUERY_TYPE, 0);
963 if (rr.query->u.type_1)
965 rr.stream = assoc->encode;
966 rr.decode = assoc->decode;
967 rr.print = assoc->print;
969 if ( srw_req->sort.sortKeys )
970 rr.srw_sortKeys = odr_strdup(assoc->encode,
971 srw_req->sort.sortKeys );
972 rr.association = assoc;
978 yaz_log_zquery_level(log_requestdetail,rr.query);
980 (assoc->init->bend_search)(assoc->backend, &rr);
983 if (rr.errcode == YAZ_BIB1_DATABASE_UNAVAILABLE)
989 srw_error = yaz_diag_bib1_to_srw (rr.errcode);
990 yaz_add_srw_diagnostic(assoc->encode,
991 &srw_res->diagnostics,
992 &srw_res->num_diagnostics,
993 srw_error, rr.errstring);
998 int number = srw_req->maximumRecords ? *srw_req->maximumRecords : 0;
999 int start = srw_req->startRecord ? *srw_req->startRecord : 1;
1001 yaz_log(log_requestdetail, "Request to pack %d+%d out of %d",
1002 start, number, rr.hits);
1004 srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
1007 srw_res->resultSetId =
1008 odr_strdup(assoc->encode, rr.srw_setname );
1009 srw_res->resultSetIdleTime =
1010 odr_intdup(assoc->encode, *rr.srw_setnameIdleTime );
1013 if (start > rr.hits || start < 1)
1015 /* if hits<=0 and start=1 we don't return a diagnostic */
1017 yaz_add_srw_diagnostic(
1019 &srw_res->diagnostics, &srw_res->num_diagnostics,
1020 YAZ_SRW_FIRST_RECORD_POSITION_OUT_OF_RANGE, 0);
1022 else if (number > 0)
1026 if (start + number > rr.hits)
1027 number = rr.hits - start + 1;
1029 /* Call bend_present if defined */
1030 if (assoc->init->bend_present)
1032 bend_present_rr *bprr = (bend_present_rr*)
1033 odr_malloc (assoc->decode, sizeof(*bprr));
1034 bprr->setname = "default";
1035 bprr->start = start;
1036 bprr->number = number;
1037 if (srw_req->recordSchema)
1039 bprr->comp = (Z_RecordComposition *) odr_malloc(assoc->decode,
1040 sizeof(*bprr->comp));
1041 bprr->comp->which = Z_RecordComp_simple;
1042 bprr->comp->u.simple = (Z_ElementSetNames *)
1043 odr_malloc(assoc->decode, sizeof(Z_ElementSetNames));
1044 bprr->comp->u.simple->which = Z_ElementSetNames_generic;
1045 bprr->comp->u.simple->u.generic = srw_req->recordSchema;
1051 bprr->stream = assoc->encode;
1052 bprr->referenceId = 0;
1053 bprr->print = assoc->print;
1054 bprr->request = req;
1055 bprr->association = assoc;
1057 bprr->errstring = NULL;
1058 (*assoc->init->bend_present)(assoc->backend, bprr);
1064 srw_error = yaz_diag_bib1_to_srw (bprr->errcode);
1065 yaz_add_srw_diagnostic(assoc->encode,
1066 &srw_res->diagnostics,
1067 &srw_res->num_diagnostics,
1068 srw_error, bprr->errstring);
1076 int packing = Z_SRW_recordPacking_string;
1077 if (srw_req->recordPacking)
1080 yaz_srw_str_to_pack(srw_req->recordPacking);
1082 packing = Z_SRW_recordPacking_string;
1084 srw_res->records = (Z_SRW_record *)
1085 odr_malloc(assoc->encode,
1086 number * sizeof(*srw_res->records));
1088 srw_res->extra_records = (Z_SRW_extra_record **)
1089 odr_malloc(assoc->encode,
1090 number*sizeof(*srw_res->extra_records));
1092 for (i = 0; i<number; i++)
1095 const char *addinfo = 0;
1097 srw_res->records[j].recordPacking = packing;
1098 srw_res->records[j].recordData_buf = 0;
1099 srw_res->extra_records[j] = 0;
1100 yaz_log(YLOG_DEBUG, "srw_bend_fetch %d", i+start);
1101 errcode = srw_bend_fetch(assoc, i+start, srw_req,
1102 srw_res->records + j,
1106 yaz_add_srw_diagnostic(assoc->encode,
1107 &srw_res->diagnostics,
1108 &srw_res->num_diagnostics,
1109 yaz_diag_bib1_to_srw (errcode),
1114 if (srw_res->records[j].recordData_buf)
1117 srw_res->num_records = j;
1119 srw_res->records = 0;
1122 if (rr.estimated_hit_count || rr.partial_resultset)
1124 yaz_add_srw_diagnostic(
1126 &srw_res->diagnostics,
1127 &srw_res->num_diagnostics,
1128 YAZ_SRW_RESULT_SET_CREATED_WITH_VALID_PARTIAL_RESULTS_AVAILABLE,
1136 const char *querystr = "?";
1137 const char *querytype = "?";
1138 WRBUF wr = wrbuf_alloc();
1140 switch (srw_req->query_type)
1142 case Z_SRW_query_type_cql:
1144 querystr = srw_req->query.cql;
1146 case Z_SRW_query_type_pqf:
1148 querystr = srw_req->query.pqf;
1151 wrbuf_printf(wr, "SRWSearch ");
1152 wrbuf_printf(wr, srw_req->database);
1153 wrbuf_printf(wr, " ");
1154 if (srw_res->num_diagnostics)
1155 wrbuf_printf(wr, "ERROR %s", srw_res->diagnostics[0].uri);
1156 else if (*http_code != 200)
1157 wrbuf_printf(wr, "ERROR info:http/%d", *http_code);
1158 else if (srw_res->numberOfRecords)
1160 wrbuf_printf(wr, "OK %d",
1161 (srw_res->numberOfRecords ?
1162 *srw_res->numberOfRecords : 0));
1164 wrbuf_printf(wr, " %s %d+%d",
1165 (srw_res->resultSetId ?
1166 srw_res->resultSetId : "-"),
1167 (srw_req->startRecord ? *srw_req->startRecord : 1),
1168 srw_res->num_records);
1169 yaz_log(log_request, "%s %s: %s", wrbuf_cstr(wr), querytype, querystr);
1174 static char *srw_bend_explain_default(void *handle, bend_explain_rr *rr)
1177 xmlNodePtr ptr = (xmlNode *) rr->server_node_ptr;
1180 for (ptr = ptr->children; ptr; ptr = ptr->next)
1182 if (ptr->type != XML_ELEMENT_NODE)
1184 if (!strcmp((const char *) ptr->name, "explain"))
1187 xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
1191 ptr = xmlCopyNode(ptr, 1);
1193 xmlDocSetRootElement(doc, ptr);
1195 xmlDocDumpMemory(doc, &buf_out, &len);
1196 content = (char*) odr_malloc(rr->stream, 1+len);
1197 memcpy(content, buf_out, len);
1198 content[len] = '\0';
1202 rr->explain_buf = content;
1210 static void srw_bend_explain(association *assoc, request *req,
1212 Z_SRW_explainResponse *srw_res,
1215 Z_SRW_explainRequest *srw_req = sr->u.explain_request;
1216 yaz_log(log_requestdetail, "Got SRW ExplainRequest");
1218 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1223 rr.stream = assoc->encode;
1224 rr.decode = assoc->decode;
1225 rr.print = assoc->print;
1227 rr.database = srw_req->database;
1229 rr.server_node_ptr = assoc->server->server_node_ptr;
1231 rr.server_node_ptr = 0;
1232 rr.schema = "http://explain.z3950.org/dtd/2.0/";
1233 if (assoc->init->bend_explain)
1234 (*assoc->init->bend_explain)(assoc->backend, &rr);
1236 srw_bend_explain_default(assoc->backend, &rr);
1240 int packing = Z_SRW_recordPacking_string;
1241 if (srw_req->recordPacking)
1244 yaz_srw_str_to_pack(srw_req->recordPacking);
1246 packing = Z_SRW_recordPacking_string;
1248 srw_res->record.recordSchema = rr.schema;
1249 srw_res->record.recordPacking = packing;
1250 srw_res->record.recordData_buf = rr.explain_buf;
1251 srw_res->record.recordData_len = strlen(rr.explain_buf);
1252 srw_res->record.recordPosition = 0;
1258 static void srw_bend_scan(association *assoc, request *req,
1260 Z_SRW_scanResponse *srw_res,
1263 Z_SRW_scanRequest *srw_req = sr->u.scan_request;
1264 yaz_log(log_requestdetail, "Got SRW ScanRequest");
1267 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1268 if (srw_res->num_diagnostics == 0 && assoc->init)
1270 struct scan_entry *save_entries;
1272 bend_scan_rr *bsrr = (bend_scan_rr *)
1273 odr_malloc (assoc->encode, sizeof(*bsrr));
1274 bsrr->num_bases = 1;
1275 bsrr->basenames = &srw_req->database;
1277 bsrr->num_entries = srw_req->maximumTerms ?
1278 *srw_req->maximumTerms : 10;
1279 bsrr->term_position = srw_req->responsePosition ?
1280 *srw_req->responsePosition : 1;
1283 bsrr->errstring = 0;
1284 bsrr->referenceId = 0;
1285 bsrr->stream = assoc->encode;
1286 bsrr->print = assoc->print;
1287 bsrr->step_size = odr_intdup(assoc->decode, 0);
1291 if (bsrr->num_entries > 0)
1294 bsrr->entries = (struct scan_entry *)
1295 odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
1297 for (i = 0; i<bsrr->num_entries; i++)
1299 bsrr->entries[i].term = 0;
1300 bsrr->entries[i].occurrences = 0;
1301 bsrr->entries[i].errcode = 0;
1302 bsrr->entries[i].errstring = 0;
1303 bsrr->entries[i].display_term = 0;
1306 save_entries = bsrr->entries; /* save it so we can compare later */
1308 if (srw_req->query_type == Z_SRW_query_type_pqf &&
1309 assoc->init->bend_scan)
1311 YAZ_PQF_Parser pqf_parser = yaz_pqf_create();
1313 bsrr->term = yaz_pqf_scan(pqf_parser, assoc->decode,
1314 &bsrr->attributeset,
1315 srw_req->scanClause.pqf);
1316 yaz_pqf_destroy(pqf_parser);
1317 bsrr->scanClause = 0;
1318 ((int (*)(void *, bend_scan_rr *))
1319 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1321 else if (srw_req->query_type == Z_SRW_query_type_cql
1322 && assoc->init->bend_scan && assoc->server
1323 && assoc->server->cql_transform)
1326 bsrr->scanClause = 0;
1327 bsrr->attributeset = 0;
1328 bsrr->term = (Z_AttributesPlusTerm *)
1329 odr_malloc(assoc->decode, sizeof(*bsrr->term));
1330 srw_error = cql2pqf_scan(assoc->encode,
1331 srw_req->scanClause.cql,
1332 assoc->server->cql_transform,
1335 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1336 &srw_res->num_diagnostics,
1340 ((int (*)(void *, bend_scan_rr *))
1341 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1344 else if (srw_req->query_type == Z_SRW_query_type_cql
1345 && assoc->init->bend_srw_scan)
1348 bsrr->attributeset = 0;
1349 bsrr->scanClause = srw_req->scanClause.cql;
1350 ((int (*)(void *, bend_scan_rr *))
1351 (*assoc->init->bend_srw_scan))(assoc->backend, bsrr);
1355 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1356 &srw_res->num_diagnostics,
1357 YAZ_SRW_UNSUPP_OPERATION, "scan");
1362 if (bsrr->errcode == YAZ_BIB1_DATABASE_UNAVAILABLE)
1367 srw_error = yaz_diag_bib1_to_srw (bsrr->errcode);
1369 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1370 &srw_res->num_diagnostics,
1371 srw_error, bsrr->errstring);
1373 else if (srw_res->num_diagnostics == 0 && bsrr->num_entries)
1376 srw_res->terms = (Z_SRW_scanTerm*)
1377 odr_malloc(assoc->encode, sizeof(*srw_res->terms) *
1380 srw_res->num_terms = bsrr->num_entries;
1381 for (i = 0; i<bsrr->num_entries; i++)
1383 Z_SRW_scanTerm *t = srw_res->terms + i;
1384 t->value = odr_strdup(assoc->encode, bsrr->entries[i].term);
1385 t->numberOfRecords =
1386 odr_intdup(assoc->encode, bsrr->entries[i].occurrences);
1388 if (save_entries == bsrr->entries &&
1389 bsrr->entries[i].display_term)
1391 /* the entries was _not_ set by the handler. So it's
1392 safe to test for new member display_term. It is
1395 t->displayTerm = odr_strdup(assoc->encode,
1396 bsrr->entries[i].display_term);
1404 WRBUF wr = wrbuf_alloc();
1405 const char *querytype = 0;
1406 const char *querystr = 0;
1408 switch(srw_req->query_type)
1410 case Z_SRW_query_type_pqf:
1412 querystr = srw_req->scanClause.pqf;
1414 case Z_SRW_query_type_cql:
1416 querystr = srw_req->scanClause.cql;
1419 querytype = "UNKNOWN";
1423 wrbuf_printf(wr, "SRWScan ");
1424 wrbuf_printf(wr, srw_req->database);
1425 wrbuf_printf(wr, " ");
1427 if (srw_res->num_diagnostics)
1428 wrbuf_printf(wr, "ERROR %s - ", srw_res->diagnostics[0].uri);
1429 else if (srw_res->num_terms)
1430 wrbuf_printf(wr, "OK %d - ", srw_res->num_terms);
1432 wrbuf_printf(wr, "OK - - ");
1434 wrbuf_printf(wr, "%d+%d+0 ",
1435 (srw_req->responsePosition ?
1436 *srw_req->responsePosition : 1),
1437 (srw_req->maximumTerms ?
1438 *srw_req->maximumTerms : 1));
1439 /* there is no step size in SRU/W ??? */
1440 wrbuf_printf(wr, "%s: %s ", querytype, querystr);
1441 yaz_log(log_request, "%s ", wrbuf_cstr(wr) );
1447 static void srw_bend_update(association *assoc, request *req,
1449 Z_SRW_updateResponse *srw_res,
1452 Z_SRW_updateRequest *srw_req = sr->u.update_request;
1453 yaz_log(log_session, "SRWUpdate action=%s", srw_req->operation);
1454 yaz_log(YLOG_DEBUG, "num_diag = %d", srw_res->num_diagnostics );
1456 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1460 Z_SRW_extra_record *extra = srw_req->extra_record;
1462 rr.stream = assoc->encode;
1463 rr.print = assoc->print;
1465 rr.basenames = &srw_req->database;
1466 rr.operation = srw_req->operation;
1467 rr.operation_status = "failed";
1469 rr.record_versions = 0;
1470 rr.num_versions = 0;
1471 rr.record_packing = "string";
1472 rr.record_schema = 0;
1474 rr.extra_record_data = 0;
1475 rr.extra_request_data = 0;
1476 rr.extra_response_data = 0;
1482 if (rr.operation == 0)
1484 yaz_add_sru_update_diagnostic(
1485 assoc->encode, &srw_res->diagnostics,
1486 &srw_res->num_diagnostics,
1487 YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,
1491 yaz_log(YLOG_DEBUG, "basename = %s", rr.basenames[0] );
1492 yaz_log(YLOG_DEBUG, "Operation = %s", rr.operation );
1493 if (!strcmp( rr.operation, "delete"))
1495 if (srw_req->record && !srw_req->record->recordSchema)
1497 rr.record_schema = odr_strdup(
1499 srw_req->record->recordSchema);
1501 if (srw_req->record)
1503 rr.record_data = odr_strdupn(
1505 srw_req->record->recordData_buf,
1506 srw_req->record->recordData_len );
1508 if (extra && extra->extraRecordData_len)
1510 rr.extra_record_data = odr_strdupn(
1512 extra->extraRecordData_buf,
1513 extra->extraRecordData_len );
1515 if (srw_req->recordId)
1516 rr.record_id = srw_req->recordId;
1517 else if (extra && extra->recordIdentifier)
1518 rr.record_id = extra->recordIdentifier;
1520 else if (!strcmp(rr.operation, "replace"))
1522 if (srw_req->recordId)
1523 rr.record_id = srw_req->recordId;
1524 else if (extra && extra->recordIdentifier)
1525 rr.record_id = extra->recordIdentifier;
1528 yaz_add_sru_update_diagnostic(
1529 assoc->encode, &srw_res->diagnostics,
1530 &srw_res->num_diagnostics,
1531 YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,
1532 "recordIdentifier");
1534 if (!srw_req->record)
1536 yaz_add_sru_update_diagnostic(
1537 assoc->encode, &srw_res->diagnostics,
1538 &srw_res->num_diagnostics,
1539 YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,
1544 if (srw_req->record->recordSchema)
1545 rr.record_schema = odr_strdup(
1546 assoc->encode, srw_req->record->recordSchema);
1547 if (srw_req->record->recordData_len )
1549 rr.record_data = odr_strdupn(assoc->encode,
1550 srw_req->record->recordData_buf,
1551 srw_req->record->recordData_len );
1555 yaz_add_sru_update_diagnostic(
1556 assoc->encode, &srw_res->diagnostics,
1557 &srw_res->num_diagnostics,
1558 YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,
1562 if (extra && extra->extraRecordData_len)
1564 rr.extra_record_data = odr_strdupn(
1566 extra->extraRecordData_buf,
1567 extra->extraRecordData_len );
1570 else if (!strcmp(rr.operation, "insert"))
1572 if (srw_req->recordId)
1573 rr.record_id = srw_req->recordId;
1575 rr.record_id = extra->recordIdentifier;
1577 if (srw_req->record)
1579 if (srw_req->record->recordSchema)
1580 rr.record_schema = odr_strdup(
1581 assoc->encode, srw_req->record->recordSchema);
1583 if (srw_req->record->recordData_len)
1584 rr.record_data = odr_strdupn(
1586 srw_req->record->recordData_buf,
1587 srw_req->record->recordData_len );
1589 if (extra && extra->extraRecordData_len)
1591 rr.extra_record_data = odr_strdupn(
1593 extra->extraRecordData_buf,
1594 extra->extraRecordData_len );
1598 yaz_add_sru_update_diagnostic(assoc->encode, &srw_res->diagnostics,
1599 &srw_res->num_diagnostics,
1600 YAZ_SRU_UPDATE_INVALID_ACTION,
1603 if (srw_req->record)
1605 const char *pack_str =
1606 yaz_srw_pack_to_str(srw_req->record->recordPacking);
1608 rr.record_packing = odr_strdup(assoc->encode, pack_str);
1611 if (srw_req->num_recordVersions)
1613 rr.record_versions = srw_req->recordVersions;
1614 rr.num_versions = srw_req->num_recordVersions;
1616 if (srw_req->extraRequestData_len)
1618 rr.extra_request_data = odr_strdupn(assoc->encode,
1619 srw_req->extraRequestData_buf,
1620 srw_req->extraRequestData_len );
1622 if (srw_res->num_diagnostics == 0)
1624 if ( assoc->init->bend_srw_update)
1625 (*assoc->init->bend_srw_update)(assoc->backend, &rr);
1627 yaz_add_sru_update_diagnostic(
1628 assoc->encode, &srw_res->diagnostics,
1629 &srw_res->num_diagnostics,
1630 YAZ_SRU_UPDATE_UNSPECIFIED_DATABASE_ERROR,
1631 "No Update backend handler");
1635 yaz_add_srw_diagnostic_uri(assoc->encode,
1636 &srw_res->diagnostics,
1637 &srw_res->num_diagnostics,
1641 srw_res->recordId = rr.record_id;
1642 srw_res->operationStatus = rr.operation_status;
1643 srw_res->recordVersions = rr.record_versions;
1644 srw_res->num_recordVersions = rr.num_versions;
1645 if (srw_res->extraResponseData_len)
1647 srw_res->extraResponseData_buf = rr.extra_response_data;
1648 srw_res->extraResponseData_len = strlen(rr.extra_response_data);
1650 if (srw_res->num_diagnostics == 0 && rr.record_data)
1652 srw_res->record = yaz_srw_get_record(assoc->encode);
1653 srw_res->record->recordSchema = rr.record_schema;
1654 if (rr.record_packing)
1656 int pack = yaz_srw_str_to_pack(rr.record_packing);
1660 pack = Z_SRW_recordPacking_string;
1661 yaz_log(YLOG_WARN, "Back packing %s from backend",
1664 srw_res->record->recordPacking = pack;
1666 srw_res->record->recordData_buf = rr.record_data;
1667 srw_res->record->recordData_len = strlen(rr.record_data);
1668 if (rr.extra_record_data)
1670 Z_SRW_extra_record *ex =
1671 yaz_srw_get_extra_record(assoc->encode);
1672 srw_res->extra_record = ex;
1673 ex->extraRecordData_buf = rr.extra_record_data;
1674 ex->extraRecordData_len = strlen(rr.extra_record_data);
1680 /* check if path is OK (1); BAD (0) */
1681 static int check_path(const char *path)
1685 if (strstr(path, ".."))
1690 static char *read_file(const char *fname, ODR o, int *sz)
1693 FILE *inf = fopen(fname, "rb");
1697 fseek(inf, 0L, SEEK_END);
1700 buf = (char *) odr_malloc(o, *sz);
1701 fread(buf, 1, *sz, inf);
1706 static void process_http_request(association *assoc, request *req)
1708 Z_HTTP_Request *hreq = req->gdu_request->u.HTTP_Request;
1709 ODR o = assoc->encode;
1710 int r = 2; /* 2=NOT TAKEN, 1=TAKEN, 0=SOAP TAKEN */
1712 Z_SOAP *soap_package = 0;
1715 Z_HTTP_Response *hres = 0;
1717 const char *stylesheet = 0; /* for now .. set later */
1718 Z_SRW_diagnostic *diagnostic = 0;
1719 int num_diagnostic = 0;
1720 const char *host = z_HTTP_header_lookup(hreq->headers, "Host");
1722 if (!control_association(assoc, host, 0))
1724 p = z_get_HTTP_Response(o, 404);
1727 if (r == 2 && assoc->server && assoc->server->docpath
1728 && hreq->path[0] == '/'
1730 /* check if path is a proper prefix of documentroot */
1731 strncmp(hreq->path+1, assoc->server->docpath,
1732 strlen(assoc->server->docpath))
1735 if (!check_path(hreq->path))
1737 yaz_log(YLOG_LOG, "File %s access forbidden", hreq->path+1);
1738 p = z_get_HTTP_Response(o, 404);
1742 int content_size = 0;
1743 char *content_buf = read_file(hreq->path+1, o, &content_size);
1746 yaz_log(YLOG_LOG, "File %s not found", hreq->path+1);
1747 p = z_get_HTTP_Response(o, 404);
1751 const char *ctype = 0;
1752 yaz_mime_types types = yaz_mime_types_create();
1754 yaz_mime_types_add(types, "xsl", "application/xml");
1755 yaz_mime_types_add(types, "xml", "application/xml");
1756 yaz_mime_types_add(types, "css", "text/css");
1757 yaz_mime_types_add(types, "html", "text/html");
1758 yaz_mime_types_add(types, "htm", "text/html");
1759 yaz_mime_types_add(types, "txt", "text/plain");
1760 yaz_mime_types_add(types, "js", "application/x-javascript");
1762 yaz_mime_types_add(types, "gif", "image/gif");
1763 yaz_mime_types_add(types, "png", "image/png");
1764 yaz_mime_types_add(types, "jpg", "image/jpeg");
1765 yaz_mime_types_add(types, "jpeg", "image/jpeg");
1767 ctype = yaz_mime_lookup_fname(types, hreq->path);
1770 yaz_log(YLOG_LOG, "No mime type for %s", hreq->path+1);
1771 p = z_get_HTTP_Response(o, 404);
1775 p = z_get_HTTP_Response(o, 200);
1776 hres = p->u.HTTP_Response;
1777 hres->content_buf = content_buf;
1778 hres->content_len = content_size;
1779 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1781 yaz_mime_types_destroy(types);
1789 r = yaz_srw_decode(hreq, &sr, &soap_package, assoc->decode, &charset);
1790 yaz_log(YLOG_DEBUG, "yaz_srw_decode returned %d", r);
1792 if (r == 2) /* not taken */
1794 r = yaz_sru_decode(hreq, &sr, &soap_package, assoc->decode, &charset,
1795 &diagnostic, &num_diagnostic);
1796 yaz_log(YLOG_DEBUG, "yaz_sru_decode returned %d", r);
1798 if (r == 0) /* decode SRW/SRU OK .. */
1800 int http_code = 200;
1801 if (sr->which == Z_SRW_searchRetrieve_request)
1804 yaz_srw_get(assoc->encode, Z_SRW_searchRetrieve_response);
1806 stylesheet = sr->u.request->stylesheet;
1809 res->u.response->diagnostics = diagnostic;
1810 res->u.response->num_diagnostics = num_diagnostic;
1814 srw_bend_search(assoc, req, sr, res->u.response,
1817 if (http_code == 200)
1818 soap_package->u.generic->p = res;
1820 else if (sr->which == Z_SRW_explain_request)
1822 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_explain_response);
1823 stylesheet = sr->u.explain_request->stylesheet;
1826 res->u.explain_response->diagnostics = diagnostic;
1827 res->u.explain_response->num_diagnostics = num_diagnostic;
1829 srw_bend_explain(assoc, req, sr,
1830 res->u.explain_response, &http_code);
1831 if (http_code == 200)
1832 soap_package->u.generic->p = res;
1834 else if (sr->which == Z_SRW_scan_request)
1836 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_scan_response);
1837 stylesheet = sr->u.scan_request->stylesheet;
1840 res->u.scan_response->diagnostics = diagnostic;
1841 res->u.scan_response->num_diagnostics = num_diagnostic;
1843 srw_bend_scan(assoc, req, sr,
1844 res->u.scan_response, &http_code);
1845 if (http_code == 200)
1846 soap_package->u.generic->p = res;
1848 else if (sr->which == Z_SRW_update_request)
1850 Z_SRW_PDU *res = yaz_srw_get(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.125 $");
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))))
2624 thisrec->databaseName = odr_strdup(a->encode, freq.basename);
2626 thisrec->databaseName = 0;
2627 thisrec->which = Z_NamePlusRecord_databaseRecord;
2629 if (!freq.output_format)
2630 freq.output_format = freq.request_format;
2631 thisrec->u.databaseRecord = z_ext_record_oid(
2632 a->encode, freq.output_format, freq.record, freq.len);
2633 if (!thisrec->u.databaseRecord)
2635 reclist->records[reclist->num_records] = thisrec;
2636 reclist->num_records++;
2638 *num = reclist->num_records;
2642 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
2645 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2646 bend_search_rr *bsrr =
2647 (bend_search_rr *)nmem_malloc (reqb->request_mem, sizeof(*bsrr));
2649 yaz_log(log_requestdetail, "Got SearchRequest.");
2651 bsrr->request = reqb;
2652 bsrr->association = assoc;
2653 bsrr->referenceId = req->referenceId;
2654 save_referenceId (reqb, bsrr->referenceId);
2655 bsrr->srw_sortKeys = 0;
2656 bsrr->srw_setname = 0;
2657 bsrr->srw_setnameIdleTime = 0;
2658 bsrr->estimated_hit_count = 0;
2659 bsrr->partial_resultset = 0;
2661 yaz_log (log_requestdetail, "ResultSet '%s'", req->resultSetName);
2662 if (req->databaseNames)
2665 for (i = 0; i < req->num_databaseNames; i++)
2666 yaz_log(log_requestdetail, "Database '%s'", req->databaseNames[i]);
2669 yaz_log_zquery_level(log_requestdetail,req->query);
2671 if (assoc->init->bend_search)
2673 bsrr->setname = req->resultSetName;
2674 bsrr->replace_set = *req->replaceIndicator;
2675 bsrr->num_bases = req->num_databaseNames;
2676 bsrr->basenames = req->databaseNames;
2677 bsrr->query = req->query;
2678 bsrr->stream = assoc->encode;
2679 nmem_transfer(odr_getmem(bsrr->stream), reqb->request_mem);
2680 bsrr->decode = assoc->decode;
2681 bsrr->print = assoc->print;
2684 bsrr->errstring = NULL;
2685 bsrr->search_info = NULL;
2687 if (assoc->server && assoc->server->cql_transform
2688 && req->query->which == Z_Query_type_104
2689 && req->query->u.type_104->which == Z_External_CQL)
2691 /* have a CQL query and a CQL to PQF transform .. */
2693 cql2pqf(bsrr->stream, req->query->u.type_104->u.cql,
2694 assoc->server->cql_transform, bsrr->query);
2696 bsrr->errcode = yaz_diag_srw_to_bib1(srw_errcode);
2699 if (assoc->server && assoc->server->ccl_transform
2700 && req->query->which == Z_Query_type_2) /*CCL*/
2702 /* have a CCL query and a CCL to PQF transform .. */
2704 ccl2pqf(bsrr->stream, req->query->u.type_2,
2705 assoc->server->ccl_transform, bsrr);
2707 bsrr->errcode = yaz_diag_srw_to_bib1(srw_errcode);
2711 (assoc->init->bend_search)(assoc->backend, bsrr);
2712 if (!bsrr->request) /* backend not ready with the search response */
2713 return 0; /* should not be used any more */
2717 /* FIXME - make a diagnostic for it */
2718 yaz_log(YLOG_WARN,"Search not supported ?!?!");
2720 return response_searchRequest(assoc, reqb, bsrr, fd);
2723 int bend_searchresponse(void *handle, bend_search_rr *bsrr) {return 0;}
2726 * Prepare a searchresponse based on the backend results. We probably want
2727 * to look at making the fetching of records nonblocking as well, but
2728 * so far, we'll keep things simple.
2729 * If bsrt is null, that means we're called in response to a communications
2730 * event, and we'll have to get the response for ourselves.
2732 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
2733 bend_search_rr *bsrt, int *fd)
2735 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2736 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2737 Z_SearchResponse *resp = (Z_SearchResponse *)
2738 odr_malloc (assoc->encode, sizeof(*resp));
2739 int *nulint = odr_intdup (assoc->encode, 0);
2740 int *next = odr_intdup(assoc->encode, 0);
2741 int *none = odr_intdup(assoc->encode, Z_SearchResponse_none);
2742 int returnedrecs = 0;
2744 apdu->which = Z_APDU_searchResponse;
2745 apdu->u.searchResponse = resp;
2746 resp->referenceId = req->referenceId;
2747 resp->additionalSearchInfo = 0;
2748 resp->otherInfo = 0;
2750 if (!bsrt && !bend_searchresponse(assoc->backend, bsrt))
2752 yaz_log(YLOG_FATAL, "Bad result from backend");
2755 else if (bsrt->errcode)
2757 resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
2758 resp->resultCount = nulint;
2759 resp->numberOfRecordsReturned = nulint;
2760 resp->nextResultSetPosition = nulint;
2761 resp->searchStatus = nulint;
2762 resp->resultSetStatus = none;
2763 resp->presentStatus = 0;
2767 bool_t *sr = odr_intdup(assoc->encode, 1);
2768 int *toget = odr_intdup(assoc->encode, 0);
2769 Z_RecordComposition comp, *compp = 0;
2771 yaz_log (log_requestdetail, "resultCount: %d", bsrt->hits);
2774 resp->resultCount = &bsrt->hits;
2776 comp.which = Z_RecordComp_simple;
2777 /* how many records does the user agent want, then? */
2778 if (bsrt->hits <= *req->smallSetUpperBound)
2780 *toget = bsrt->hits;
2781 if ((comp.u.simple = req->smallSetElementSetNames))
2784 else if (bsrt->hits < *req->largeSetLowerBound)
2786 *toget = *req->mediumSetPresentNumber;
2787 if (*toget > bsrt->hits)
2788 *toget = bsrt->hits;
2789 if ((comp.u.simple = req->mediumSetElementSetNames))
2795 if (*toget && !resp->records)
2797 int *presst = odr_intdup(assoc->encode, 0);
2798 /* Call bend_present if defined */
2799 if (assoc->init->bend_present)
2801 bend_present_rr *bprr = (bend_present_rr *)
2802 nmem_malloc (reqb->request_mem, sizeof(*bprr));
2803 bprr->setname = req->resultSetName;
2805 bprr->number = *toget;
2806 bprr->format = req->preferredRecordSyntax;
2808 bprr->referenceId = req->referenceId;
2809 bprr->stream = assoc->encode;
2810 bprr->print = assoc->print;
2811 bprr->request = reqb;
2812 bprr->association = assoc;
2814 bprr->errstring = NULL;
2815 (*assoc->init->bend_present)(assoc->backend, bprr);
2821 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2822 *resp->presentStatus = Z_PresentStatus_failure;
2827 resp->records = pack_records(
2828 assoc, req->resultSetName, 1,
2829 toget, compp, next, presst, req->referenceId,
2830 req->preferredRecordSyntax, NULL);
2833 resp->numberOfRecordsReturned = toget;
2834 returnedrecs = *toget;
2835 resp->presentStatus = presst;
2839 if (*resp->resultCount)
2841 resp->numberOfRecordsReturned = nulint;
2842 resp->presentStatus = 0;
2844 resp->nextResultSetPosition = next;
2845 resp->searchStatus = sr;
2846 resp->resultSetStatus = 0;
2847 if (bsrt->estimated_hit_count)
2849 resp->resultSetStatus = odr_intdup(assoc->encode,
2850 Z_SearchResponse_estimate);
2852 else if (bsrt->partial_resultset)
2854 resp->resultSetStatus = odr_intdup(assoc->encode,
2855 Z_SearchResponse_subset);
2858 resp->additionalSearchInfo = bsrt->search_info;
2863 WRBUF wr = wrbuf_alloc();
2865 for (i = 0 ; i < req->num_databaseNames; i++){
2867 wrbuf_printf(wr, "+");
2868 wrbuf_printf(wr, req->databaseNames[i]);
2870 wrbuf_printf(wr, " ");
2873 wrbuf_printf(wr, "ERROR %d", bsrt->errcode);
2875 wrbuf_printf(wr, "OK %d", bsrt->hits);
2876 wrbuf_printf(wr, " %s 1+%d ",
2877 req->resultSetName, returnedrecs);
2878 yaz_query_to_wrbuf(wr, req->query);
2880 yaz_log(log_request, "Search %s", wrbuf_cstr(wr));
2887 * Maybe we got a little over-friendly when we designed bend_fetch to
2888 * get only one record at a time. Some backends can optimise multiple-record
2889 * fetches, and at any rate, there is some overhead involved in
2890 * all that selecting and hopping around. Problem is, of course, that the
2891 * frontend can't know ahead of time how many records it'll need to
2892 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
2893 * is downright lousy as a bulk data transfer protocol.
2895 * To start with, we'll do the fetching of records from the backend
2896 * in one operation: To save some trips in and out of the event-handler,
2897 * and to simplify the interface to pack_records. At any rate, asynch
2898 * operation is more fun in operations that have an unpredictable execution
2899 * speed - which is normally more true for search than for present.
2901 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
2904 Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
2906 Z_PresentResponse *resp;
2910 const char *errstring = 0;
2912 yaz_log(log_requestdetail, "Got PresentRequest.");
2914 resp = (Z_PresentResponse *)odr_malloc (assoc->encode, sizeof(*resp));
2916 resp->presentStatus = odr_intdup(assoc->encode, 0);
2917 if (assoc->init->bend_present)
2919 bend_present_rr *bprr = (bend_present_rr *)
2920 nmem_malloc (reqb->request_mem, sizeof(*bprr));
2921 bprr->setname = req->resultSetId;
2922 bprr->start = *req->resultSetStartPoint;
2923 bprr->number = *req->numberOfRecordsRequested;
2924 bprr->format = req->preferredRecordSyntax;
2925 bprr->comp = req->recordComposition;
2926 bprr->referenceId = req->referenceId;
2927 bprr->stream = assoc->encode;
2928 bprr->print = assoc->print;
2929 bprr->request = reqb;
2930 bprr->association = assoc;
2932 bprr->errstring = NULL;
2933 (*assoc->init->bend_present)(assoc->backend, bprr);
2936 return 0; /* should not happen */
2939 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2940 *resp->presentStatus = Z_PresentStatus_failure;
2941 errcode = bprr->errcode;
2942 errstring = bprr->errstring;
2945 apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2946 next = odr_intdup(assoc->encode, 0);
2947 num = odr_intdup(assoc->encode, 0);
2949 apdu->which = Z_APDU_presentResponse;
2950 apdu->u.presentResponse = resp;
2951 resp->referenceId = req->referenceId;
2952 resp->otherInfo = 0;
2956 *num = *req->numberOfRecordsRequested;
2958 pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
2959 num, req->recordComposition, next,
2960 resp->presentStatus,
2961 req->referenceId, req->preferredRecordSyntax,
2966 WRBUF wr = wrbuf_alloc();
2967 wrbuf_printf(wr, "Present ");
2969 if (*resp->presentStatus == Z_PresentStatus_failure)
2970 wrbuf_printf(wr, "ERROR %d ", errcode);
2971 else if (*resp->presentStatus == Z_PresentStatus_success)
2972 wrbuf_printf(wr, "OK - ");
2974 wrbuf_printf(wr, "Partial %d - ", *resp->presentStatus);
2976 wrbuf_printf(wr, " %s %d+%d ",
2977 req->resultSetId, *req->resultSetStartPoint,
2978 *req->numberOfRecordsRequested);
2979 yaz_log(log_request, "%s", wrbuf_cstr(wr) );
2984 resp->numberOfRecordsReturned = num;
2985 resp->nextResultSetPosition = next;
2991 * Scan was implemented rather in a hurry, and with support for only the basic
2992 * elements of the service in the backend API. Suggestions are welcome.
2994 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
2996 Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
2997 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2998 Z_ScanResponse *res = (Z_ScanResponse *)
2999 odr_malloc (assoc->encode, sizeof(*res));
3000 int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
3001 int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
3002 Z_ListEntries *ents = (Z_ListEntries *)
3003 odr_malloc (assoc->encode, sizeof(*ents));
3004 Z_DiagRecs *diagrecs_p = NULL;
3005 bend_scan_rr *bsrr = (bend_scan_rr *)
3006 odr_malloc (assoc->encode, sizeof(*bsrr));
3007 struct scan_entry *save_entries;
3009 yaz_log(log_requestdetail, "Got ScanRequest");
3011 apdu->which = Z_APDU_scanResponse;
3012 apdu->u.scanResponse = res;
3013 res->referenceId = req->referenceId;
3015 /* if step is absent, set it to 0 */
3016 res->stepSize = odr_intdup(assoc->encode, 0);
3018 *res->stepSize = *req->stepSize;
3020 res->scanStatus = scanStatus;
3021 res->numberOfEntriesReturned = numberOfEntriesReturned;
3022 res->positionOfTerm = 0;
3023 res->entries = ents;
3024 ents->num_entries = 0;
3025 ents->entries = NULL;
3026 ents->num_nonsurrogateDiagnostics = 0;
3027 ents->nonsurrogateDiagnostics = NULL;
3028 res->attributeSet = 0;
3031 if (req->databaseNames)
3034 for (i = 0; i < req->num_databaseNames; i++)
3035 yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
3037 bsrr->scanClause = 0;
3039 bsrr->errstring = 0;
3040 bsrr->num_bases = req->num_databaseNames;
3041 bsrr->basenames = req->databaseNames;
3042 bsrr->num_entries = *req->numberOfTermsRequested;
3043 bsrr->term = req->termListAndStartPoint;
3044 bsrr->referenceId = req->referenceId;
3045 bsrr->stream = assoc->encode;
3046 bsrr->print = assoc->print;
3047 bsrr->step_size = res->stepSize;
3048 bsrr->setname = yaz_oi_get_string_oid(&req->otherInfo,
3049 yaz_oid_userinfo_scan_set, 1, 0);
3051 /* For YAZ 2.0 and earlier it was the backend handler that
3052 initialized entries (member display_term did not exist)
3053 YAZ 2.0 and later sets 'entries' and initialize all members
3054 including 'display_term'.
3056 if (bsrr->num_entries > 0)
3059 bsrr->entries = (struct scan_entry *)
3060 odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
3062 for (i = 0; i<bsrr->num_entries; i++)
3064 bsrr->entries[i].term = 0;
3065 bsrr->entries[i].occurrences = 0;
3066 bsrr->entries[i].errcode = 0;
3067 bsrr->entries[i].errstring = 0;
3068 bsrr->entries[i].display_term = 0;
3071 save_entries = bsrr->entries; /* save it so we can compare later */
3073 bsrr->attributeset = req->attributeSet;
3074 log_scan_term_level (log_requestdetail, req->termListAndStartPoint,
3075 bsrr->attributeset);
3076 bsrr->term_position = req->preferredPositionInResponse ?
3077 *req->preferredPositionInResponse : 1;
3079 ((int (*)(void *, bend_scan_rr *))
3080 (*assoc->init->bend_scan))(assoc->backend, bsrr);
3083 diagrecs_p = zget_DiagRecs(assoc->encode,
3084 bsrr->errcode, bsrr->errstring);
3088 Z_Entry **tab = (Z_Entry **)
3089 odr_malloc (assoc->encode, sizeof(*tab) * bsrr->num_entries);
3091 if (bsrr->status == BEND_SCAN_PARTIAL)
3092 *scanStatus = Z_Scan_partial_5;
3094 *scanStatus = Z_Scan_success;
3095 ents->entries = tab;
3096 ents->num_entries = bsrr->num_entries;
3097 res->numberOfEntriesReturned = &ents->num_entries;
3098 res->positionOfTerm = &bsrr->term_position;
3099 for (i = 0; i < bsrr->num_entries; i++)
3105 tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
3106 if (bsrr->entries[i].occurrences >= 0)
3108 e->which = Z_Entry_termInfo;
3109 e->u.termInfo = t = (Z_TermInfo *)
3110 odr_malloc(assoc->encode, sizeof(*t));
3111 t->suggestedAttributes = 0;
3113 if (bsrr->entries[i].display_term)
3115 t->displayTerm = odr_strdup(assoc->encode,
3116 bsrr->entries[i].display_term);
3118 t->alternativeTerm = 0;
3119 t->byAttributes = 0;
3120 t->otherTermInfo = 0;
3121 t->globalOccurrences = &bsrr->entries[i].occurrences;
3122 t->term = (Z_Term *)
3123 odr_malloc(assoc->encode, sizeof(*t->term));
3124 t->term->which = Z_Term_general;
3125 t->term->u.general = o =
3126 (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
3127 o->buf = (unsigned char *)
3128 odr_malloc(assoc->encode, o->len = o->size =
3129 strlen(bsrr->entries[i].term));
3130 memcpy(o->buf, bsrr->entries[i].term, o->len);
3131 yaz_log(YLOG_DEBUG, " term #%d: '%s' (%d)", i,
3132 bsrr->entries[i].term, bsrr->entries[i].occurrences);
3136 Z_DiagRecs *drecs = zget_DiagRecs(assoc->encode,
3137 bsrr->entries[i].errcode,
3138 bsrr->entries[i].errstring);
3139 assert (drecs->num_diagRecs == 1);
3140 e->which = Z_Entry_surrogateDiagnostic;
3141 assert (drecs->diagRecs[0]);
3142 e->u.surrogateDiagnostic = drecs->diagRecs[0];
3148 ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
3149 ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
3154 WRBUF wr = wrbuf_alloc();
3155 wrbuf_printf(wr, "Scan ");
3156 for (i = 0 ; i < req->num_databaseNames; i++)
3159 wrbuf_printf(wr, "+");
3160 wrbuf_printf(wr, req->databaseNames[i]);
3163 wrbuf_printf(wr, " ");
3166 wr_diag(wr, bsrr->errcode, bsrr->errstring);
3168 wrbuf_printf(wr, "OK");
3170 wrbuf_printf(wr, " %d - %d+%d+%d",
3171 res->numberOfEntriesReturned ?
3172 *res->numberOfEntriesReturned : 0,
3173 (req->preferredPositionInResponse ?
3174 *req->preferredPositionInResponse : 1),
3175 *req->numberOfTermsRequested,
3176 (res->stepSize ? *res->stepSize : 1));
3179 wrbuf_printf(wr, "+%s", bsrr->setname);
3181 wrbuf_printf(wr, " ");
3182 yaz_scan_to_wrbuf(wr, req->termListAndStartPoint,
3183 bsrr->attributeset);
3184 yaz_log(log_request, "%s", wrbuf_cstr(wr) );
3190 static Z_APDU *process_sortRequest(association *assoc, request *reqb,
3194 Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
3195 Z_SortResponse *res = (Z_SortResponse *)
3196 odr_malloc (assoc->encode, sizeof(*res));
3197 bend_sort_rr *bsrr = (bend_sort_rr *)
3198 odr_malloc (assoc->encode, sizeof(*bsrr));
3200 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
3202 yaz_log(log_requestdetail, "Got SortRequest.");
3204 bsrr->num_input_setnames = req->num_inputResultSetNames;
3205 for (i=0;i<req->num_inputResultSetNames;i++)
3206 yaz_log(log_requestdetail, "Input resultset: '%s'",
3207 req->inputResultSetNames[i]);
3208 bsrr->input_setnames = req->inputResultSetNames;
3209 bsrr->referenceId = req->referenceId;
3210 bsrr->output_setname = req->sortedResultSetName;
3211 yaz_log(log_requestdetail, "Output resultset: '%s'",
3212 req->sortedResultSetName);
3213 bsrr->sort_sequence = req->sortSequence;
3214 /*FIXME - dump those sequences too */
3215 bsrr->stream = assoc->encode;
3216 bsrr->print = assoc->print;
3218 bsrr->sort_status = Z_SortResponse_failure;
3220 bsrr->errstring = 0;
3222 (*assoc->init->bend_sort)(assoc->backend, bsrr);
3224 res->referenceId = bsrr->referenceId;
3225 res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
3226 res->resultSetStatus = 0;
3229 Z_DiagRecs *dr = zget_DiagRecs(assoc->encode,
3230 bsrr->errcode, bsrr->errstring);
3231 res->diagnostics = dr->diagRecs;
3232 res->num_diagnostics = dr->num_diagRecs;
3236 res->num_diagnostics = 0;
3237 res->diagnostics = 0;
3239 res->resultCount = 0;
3242 apdu->which = Z_APDU_sortResponse;
3243 apdu->u.sortResponse = res;
3246 WRBUF wr = wrbuf_alloc();
3247 wrbuf_printf(wr, "Sort ");
3249 wrbuf_printf(wr, " ERROR %d", bsrr->errcode);
3251 wrbuf_printf(wr, "OK -");
3252 wrbuf_printf(wr, " (");
3253 for (i = 0; i<req->num_inputResultSetNames; i++)
3256 wrbuf_printf(wr, "+");
3257 wrbuf_printf(wr, req->inputResultSetNames[i]);
3259 wrbuf_printf(wr, ")->%s ",req->sortedResultSetName);
3261 yaz_log(log_request, "%s", wrbuf_cstr(wr) );
3267 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
3271 Z_DeleteResultSetRequest *req =
3272 reqb->apdu_request->u.deleteResultSetRequest;
3273 Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
3274 odr_malloc (assoc->encode, sizeof(*res));
3275 bend_delete_rr *bdrr = (bend_delete_rr *)
3276 odr_malloc (assoc->encode, sizeof(*bdrr));
3277 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
3279 yaz_log(log_requestdetail, "Got DeleteRequest.");
3281 bdrr->num_setnames = req->num_resultSetList;
3282 bdrr->setnames = req->resultSetList;
3283 for (i = 0; i<req->num_resultSetList; i++)
3284 yaz_log(log_requestdetail, "resultset: '%s'",
3285 req->resultSetList[i]);
3286 bdrr->stream = assoc->encode;
3287 bdrr->print = assoc->print;
3288 bdrr->function = *req->deleteFunction;
3289 bdrr->referenceId = req->referenceId;
3291 if (bdrr->num_setnames > 0)
3293 bdrr->statuses = (int*)
3294 odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
3295 bdrr->num_setnames);
3296 for (i = 0; i < bdrr->num_setnames; i++)
3297 bdrr->statuses[i] = 0;
3299 (*assoc->init->bend_delete)(assoc->backend, bdrr);
3301 res->referenceId = req->referenceId;
3303 res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
3305 res->deleteListStatuses = 0;
3306 if (bdrr->num_setnames > 0)
3309 res->deleteListStatuses = (Z_ListStatuses *)
3310 odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
3311 res->deleteListStatuses->num = bdrr->num_setnames;
3312 res->deleteListStatuses->elements =
3314 odr_malloc (assoc->encode,
3315 sizeof(*res->deleteListStatuses->elements) *
3316 bdrr->num_setnames);
3317 for (i = 0; i<bdrr->num_setnames; i++)
3319 res->deleteListStatuses->elements[i] =
3321 odr_malloc (assoc->encode,
3322 sizeof(**res->deleteListStatuses->elements));
3323 res->deleteListStatuses->elements[i]->status = bdrr->statuses+i;
3324 res->deleteListStatuses->elements[i]->id =
3325 odr_strdup (assoc->encode, bdrr->setnames[i]);
3328 res->numberNotDeleted = 0;
3329 res->bulkStatuses = 0;
3330 res->deleteMessage = 0;
3333 apdu->which = Z_APDU_deleteResultSetResponse;
3334 apdu->u.deleteResultSetResponse = res;
3337 WRBUF wr = wrbuf_alloc();
3338 wrbuf_printf(wr, "Delete ");
3339 if (bdrr->delete_status)
3340 wrbuf_printf(wr, "ERROR %d", bdrr->delete_status);
3342 wrbuf_printf(wr, "OK -");
3343 for (i = 0; i<req->num_resultSetList; i++)
3344 wrbuf_printf(wr, " %s ", req->resultSetList[i]);
3345 yaz_log(log_request, "%s", wrbuf_cstr(wr) );
3351 static void process_close(association *assoc, request *reqb)
3353 Z_Close *req = reqb->apdu_request->u.close;
3354 static char *reasons[] =
3361 "securityViolation",
3368 yaz_log(log_requestdetail, "Got Close, reason %s, message %s",
3369 reasons[*req->closeReason], req->diagnosticInformation ?
3370 req->diagnosticInformation : "NULL");
3371 if (assoc->version < 3) /* to make do_force respond with close */
3373 do_close_req(assoc, Z_Close_finished,
3374 "Association terminated by client", reqb);
3375 yaz_log(log_request,"Close OK");
3378 void save_referenceId (request *reqb, Z_ReferenceId *refid)
3382 reqb->len_refid = refid->len;
3383 reqb->refid = (char *)nmem_malloc (reqb->request_mem, refid->len);
3384 memcpy (reqb->refid, refid->buf, refid->len);
3388 reqb->len_refid = 0;
3393 void bend_request_send (bend_association a, bend_request req, Z_APDU *res)
3395 process_z_response (a, req, res);
3398 bend_request bend_request_mk (bend_association a)
3400 request *nreq = request_get (&a->outgoing);
3401 nreq->request_mem = nmem_create ();
3405 Z_ReferenceId *bend_request_getid (ODR odr, bend_request req)
3410 id = (Odr_oct *)odr_malloc (odr, sizeof(*odr));
3411 id->buf = (unsigned char *)odr_malloc (odr, req->len_refid);
3412 id->len = id->size = req->len_refid;
3413 memcpy (id->buf, req->refid, req->len_refid);
3417 void bend_request_destroy (bend_request *req)
3419 nmem_destroy((*req)->request_mem);
3420 request_release(*req);
3424 int bend_backend_respond (bend_association a, bend_request req)
3428 r = process_z_request (a, req, &msg);
3430 yaz_log (YLOG_WARN, "%s", msg);
3434 void bend_request_setdata(bend_request r, void *p)
3439 void *bend_request_getdata(bend_request r)
3441 return r->clientData;
3444 static Z_APDU *process_segmentRequest (association *assoc, request *reqb)
3446 bend_segment_rr req;
3448 req.segment = reqb->apdu_request->u.segmentRequest;
3449 req.stream = assoc->encode;
3450 req.decode = assoc->decode;
3451 req.print = assoc->print;
3452 req.association = assoc;
3454 (*assoc->init->bend_segment)(assoc->backend, &req);
3459 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd)
3461 bend_esrequest_rr esrequest;
3462 const char *ext_name = "unknown";
3464 Z_ExtendedServicesRequest *req =
3465 reqb->apdu_request->u.extendedServicesRequest;
3466 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
3468 Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
3470 esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
3471 esrequest.stream = assoc->encode;
3472 esrequest.decode = assoc->decode;
3473 esrequest.print = assoc->print;
3474 esrequest.errcode = 0;
3475 esrequest.errstring = NULL;
3476 esrequest.request = reqb;
3477 esrequest.association = assoc;
3478 esrequest.taskPackage = 0;
3479 esrequest.referenceId = req->referenceId;
3482 if (esrequest.esr && esrequest.esr->taskSpecificParameters)
3484 switch(esrequest.esr->taskSpecificParameters->which)
3486 case Z_External_itemOrder:
3487 ext_name = "ItemOrder"; break;
3488 case Z_External_update:
3489 ext_name = "Update"; break;
3490 case Z_External_update0:
3491 ext_name = "Update0"; break;
3492 case Z_External_ESAdmin:
3493 ext_name = "Admin"; break;
3498 (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
3500 /* If the response is being delayed, return NULL */
3501 if (esrequest.request == NULL)
3504 resp->referenceId = req->referenceId;
3506 if (esrequest.errcode == -1)
3508 /* Backend service indicates request will be processed */
3509 yaz_log(log_request, "Extended Service: %s (accepted)", ext_name);
3510 *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
3512 else if (esrequest.errcode == 0)
3514 /* Backend service indicates request will be processed */
3515 yaz_log(log_request, "Extended Service: %s (done)", ext_name);
3516 *resp->operationStatus = Z_ExtendedServicesResponse_done;
3520 Z_DiagRecs *diagRecs =
3521 zget_DiagRecs(assoc->encode, esrequest.errcode,
3522 esrequest.errstring);
3523 /* Backend indicates error, request will not be processed */
3524 yaz_log(log_request, "Extended Service: %s (failed)", ext_name);
3525 *resp->operationStatus = Z_ExtendedServicesResponse_failure;
3526 resp->num_diagnostics = diagRecs->num_diagRecs;
3527 resp->diagnostics = diagRecs->diagRecs;
3530 WRBUF wr = wrbuf_alloc();
3531 wrbuf_diags(wr, resp->num_diagnostics, resp->diagnostics);
3532 yaz_log(log_request, "EsRequest %s", wrbuf_cstr(wr) );
3537 /* Do something with the members of bend_extendedservice */
3538 if (esrequest.taskPackage)
3540 resp->taskPackage = z_ext_record_oid(
3541 assoc->encode, yaz_oid_recsyn_extended,
3542 (const char *) esrequest.taskPackage, -1
3545 yaz_log(YLOG_DEBUG,"Send the result apdu");
3549 int bend_assoc_is_alive(bend_association assoc)
3551 if (assoc->state == ASSOC_DEAD)
3552 return 0; /* already marked as dead. Don't check I/O chan anymore */
3554 return iochan_is_alive(assoc->client_chan);
3561 * indent-tabs-mode: nil
3563 * vim: shiftwidth=4 tabstop=8 expandtab