2 * Copyright (C) 1995-2007, Index Data ApS
3 * See the file LICENSE for details.
5 * $Id: seshigh.c,v 1.115 2007-04-16 21:53:09 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>
80 static void process_gdu_request(association *assoc, request *req);
81 static int process_z_request(association *assoc, request *req, char **msg);
82 void backend_response(IOCHAN i, int event);
83 static int process_gdu_response(association *assoc, request *req, Z_GDU *res);
84 static int process_z_response(association *assoc, request *req, Z_APDU *res);
85 static Z_APDU *process_initRequest(association *assoc, request *reqb);
86 static Z_External *init_diagnostics(ODR odr, int errcode,
87 const char *errstring);
88 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
90 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
91 bend_search_rr *bsrr, int *fd);
92 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
94 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
95 static Z_APDU *process_sortRequest(association *assoc, request *reqb, int *fd);
96 static void process_close(association *assoc, request *reqb);
97 void save_referenceId (request *reqb, Z_ReferenceId *refid);
98 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
100 static Z_APDU *process_segmentRequest (association *assoc, request *reqb);
102 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd);
104 /* dynamic logging levels */
105 static int logbits_set = 0;
106 static int log_session = 0; /* one-line logs for session */
107 static int log_sessiondetail = 0; /* more detailed stuff */
108 static int log_request = 0; /* one-line logs for requests */
109 static int log_requestdetail = 0; /* more detailed stuff */
111 /** get_logbits sets global loglevel bits */
112 static void get_logbits(void)
113 { /* needs to be called after parsing cmd-line args that can set loglevels!*/
117 log_session = yaz_log_module_level("session");
118 log_sessiondetail = yaz_log_module_level("sessiondetail");
119 log_request = yaz_log_module_level("request");
120 log_requestdetail = yaz_log_module_level("requestdetail");
126 static void wr_diag(WRBUF w, int error, const char *addinfo)
128 wrbuf_printf(w, "ERROR %d+", error);
129 wrbuf_puts_replace_char(w, diagbib1_str(error), ' ', '_');
132 wrbuf_puts_replace_char(w, addinfo, ' ', '_');
140 * Create and initialize a new association-handle.
141 * channel : iochannel for the current line.
142 * link : communications channel.
143 * Returns: 0 or a new association handle.
145 association *create_association(IOCHAN channel, COMSTACK link,
146 const char *apdufile)
152 if (!(anew = (association *)xmalloc(sizeof(*anew))))
156 anew->last_control = 0;
157 anew->client_chan = channel;
158 anew->client_link = link;
159 anew->cs_get_mask = 0;
160 anew->cs_put_mask = 0;
161 anew->cs_accept_mask = 0;
162 if (!(anew->decode = odr_createmem(ODR_DECODE)) ||
163 !(anew->encode = odr_createmem(ODR_ENCODE)))
165 if (apdufile && *apdufile)
169 if (!(anew->print = odr_createmem(ODR_PRINT)))
171 if (*apdufile == '@')
173 odr_setprint(anew->print, yaz_log_file());
175 else if (*apdufile != '-')
178 sprintf(filename, "%.200s.%ld", apdufile, (long)getpid());
179 if (!(f = fopen(filename, "w")))
181 yaz_log(YLOG_WARN|YLOG_ERRNO, "%s", filename);
184 setvbuf(f, 0, _IONBF, 0);
185 odr_setprint(anew->print, f);
190 anew->input_buffer = 0;
191 anew->input_buffer_len = 0;
193 anew->state = ASSOC_NEW;
194 request_initq(&anew->incoming);
195 request_initq(&anew->outgoing);
196 anew->proto = cs_getproto(link);
202 * Free association and release resources.
204 void destroy_association(association *h)
206 statserv_options_block *cb = statserv_getcontrol();
210 odr_destroy(h->decode);
211 odr_destroy(h->encode);
213 odr_destroy(h->print);
215 xfree(h->input_buffer);
217 (*cb->bend_close)(h->backend);
218 while ((req = request_deq(&h->incoming)))
219 request_release(req);
220 while ((req = request_deq(&h->outgoing)))
221 request_release(req);
222 request_delq(&h->incoming);
223 request_delq(&h->outgoing);
225 xmalloc_trav("session closed");
226 if (cb && cb->one_shot)
232 static void do_close_req(association *a, int reason, char *message,
236 Z_Close *cls = zget_Close(a->encode);
238 /* Purge request queue */
239 while (request_deq(&a->incoming));
240 while (request_deq(&a->outgoing));
243 yaz_log(log_requestdetail, "Sending Close PDU, reason=%d, message=%s",
244 reason, message ? message : "none");
245 apdu.which = Z_APDU_close;
247 *cls->closeReason = reason;
248 cls->diagnosticInformation = message;
249 process_z_response(a, req, &apdu);
250 iochan_settimeout(a->client_chan, 20);
254 request_release(req);
255 yaz_log(log_requestdetail, "v2 client. No Close PDU");
256 iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
259 a->state = ASSOC_DEAD;
262 static void do_close(association *a, int reason, char *message)
264 request *req = request_get(&a->outgoing);
265 do_close_req (a, reason, message, req);
269 int ir_read(IOCHAN h, int event)
271 association *assoc = (association *)iochan_getdata(h);
272 COMSTACK conn = assoc->client_link;
275 if ((assoc->cs_put_mask & EVENT_INPUT) == 0 && (event & assoc->cs_get_mask))
277 yaz_log(YLOG_DEBUG, "ir_session (input)");
278 /* We aren't speaking to this fellow */
279 if (assoc->state == ASSOC_DEAD)
281 yaz_log(log_sessiondetail, "Connection closed - end of session");
283 destroy_association(assoc);
287 assoc->cs_get_mask = EVENT_INPUT;
291 int res = cs_get(conn, &assoc->input_buffer,
292 &assoc->input_buffer_len);
293 if (res < 0 && cs_errno(conn) == CSBUFSIZE)
295 yaz_log(log_session, "Connection error: %s res=%d",
296 cs_errmsg(cs_errno(conn)), res);
297 req = request_get(&assoc->incoming); /* get a new request */
298 do_close_req(assoc, Z_Close_protocolError,
299 "Incoming package too large", req);
304 yaz_log(log_session, "Connection closed by client");
305 assoc->state = ASSOC_DEAD;
308 else if (res == 1) /* incomplete read - wait for more */
310 if (conn->io_pending & CS_WANT_WRITE)
311 assoc->cs_get_mask |= EVENT_OUTPUT;
312 iochan_setflag(h, assoc->cs_get_mask);
315 /* we got a complete PDU. Let's decode it */
316 yaz_log(YLOG_DEBUG, "Got PDU, %d bytes: lead=%02X %02X %02X", res,
317 assoc->input_buffer[0] & 0xff,
318 assoc->input_buffer[1] & 0xff,
319 assoc->input_buffer[2] & 0xff);
320 req = request_get(&assoc->incoming); /* get a new request */
321 odr_reset(assoc->decode);
322 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
323 if (!z_GDU(assoc->decode, &req->gdu_request, 0, 0))
325 yaz_log(YLOG_WARN, "ODR error on incoming PDU: %s [element %s] "
327 odr_errmsg(odr_geterror(assoc->decode)),
328 odr_getelement(assoc->decode),
329 (long) odr_offset(assoc->decode));
330 if (assoc->decode->error != OHTTP)
332 yaz_log(YLOG_WARN, "PDU dump:");
333 odr_dumpBER(yaz_log_file(), assoc->input_buffer, res);
334 request_release(req);
335 do_close(assoc, Z_Close_protocolError, "Malformed package");
339 Z_GDU *p = z_get_HTTP_Response(assoc->encode, 400);
340 assoc->state = ASSOC_DEAD;
341 process_gdu_response(assoc, req, p);
345 req->request_mem = odr_extract_mem(assoc->decode);
348 if (!z_GDU(assoc->print, &req->gdu_request, 0, 0))
349 yaz_log(YLOG_WARN, "ODR print error: %s",
350 odr_errmsg(odr_geterror(assoc->print)));
351 odr_reset(assoc->print);
353 request_enq(&assoc->incoming, req);
355 while (cs_more(conn));
361 * This is where PDUs from the client are read and the further
362 * processing is initiated. Flow of control moves down through the
363 * various process_* functions below, until the encoded result comes back up
364 * to the output handler in here.
366 * h : the I/O channel that has an outstanding event.
367 * event : the current outstanding event.
369 void ir_session(IOCHAN h, int event)
372 association *assoc = (association *)iochan_getdata(h);
373 COMSTACK conn = assoc->client_link;
376 assert(h && conn && assoc);
377 if (event == EVENT_TIMEOUT)
379 if (assoc->state != ASSOC_UP)
381 yaz_log(YLOG_DEBUG, "Final timeout - closing connection.");
382 /* do we need to lod this at all */
384 destroy_association(assoc);
389 yaz_log(log_sessiondetail,
390 "Session idle too long. Sending close.");
391 do_close(assoc, Z_Close_lackOfActivity, 0);
395 if (event & assoc->cs_accept_mask)
397 if (!cs_accept (conn))
399 yaz_log (YLOG_WARN, "accept failed");
400 destroy_association(assoc);
403 iochan_clearflag (h, EVENT_OUTPUT);
404 if (conn->io_pending)
405 { /* cs_accept didn't complete */
406 assoc->cs_accept_mask =
407 ((conn->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
408 ((conn->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
410 iochan_setflag (h, assoc->cs_accept_mask);
413 { /* cs_accept completed. Prepare for reading (cs_get) */
414 assoc->cs_accept_mask = 0;
415 assoc->cs_get_mask = EVENT_INPUT;
416 iochan_setflag (h, assoc->cs_get_mask);
420 if (event & assoc->cs_get_mask) /* input */
422 if (!ir_read(h, event))
424 req = request_head(&assoc->incoming);
425 if (req->state == REQUEST_IDLE)
427 request_deq(&assoc->incoming);
428 process_gdu_request(assoc, req);
431 if (event & assoc->cs_put_mask)
433 request *req = request_head(&assoc->outgoing);
435 assoc->cs_put_mask = 0;
436 yaz_log(YLOG_DEBUG, "ir_session (output)");
437 req->state = REQUEST_PENDING;
438 switch (res = cs_put(conn, req->response, req->len_response))
441 yaz_log(log_sessiondetail, "Connection closed by client");
443 destroy_association(assoc);
446 case 0: /* all sent - release the request structure */
447 yaz_log(YLOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
449 yaz_log(YLOG_DEBUG, "HTTP out:\n%.*s", req->len_response,
452 nmem_destroy(req->request_mem);
453 request_deq(&assoc->outgoing);
454 request_release(req);
455 if (!request_head(&assoc->outgoing))
456 { /* restore mask for cs_get operation ... */
457 iochan_clearflag(h, EVENT_OUTPUT|EVENT_INPUT);
458 iochan_setflag(h, assoc->cs_get_mask);
459 if (assoc->state == ASSOC_DEAD)
460 iochan_setevent(assoc->client_chan, EVENT_TIMEOUT);
464 assoc->cs_put_mask = EVENT_OUTPUT;
468 if (conn->io_pending & CS_WANT_WRITE)
469 assoc->cs_put_mask |= EVENT_OUTPUT;
470 if (conn->io_pending & CS_WANT_READ)
471 assoc->cs_put_mask |= EVENT_INPUT;
472 iochan_setflag(h, assoc->cs_put_mask);
475 if (event & EVENT_EXCEPT)
477 yaz_log(YLOG_WARN, "ir_session (exception)");
479 destroy_association(assoc);
484 static int process_z_request(association *assoc, request *req, char **msg);
487 static void assoc_init_reset(association *assoc)
490 assoc->init = (bend_initrequest *) xmalloc (sizeof(*assoc->init));
492 assoc->init->stream = assoc->encode;
493 assoc->init->print = assoc->print;
494 assoc->init->auth = 0;
495 assoc->init->referenceId = 0;
496 assoc->init->implementation_version = 0;
497 assoc->init->implementation_id = 0;
498 assoc->init->implementation_name = 0;
499 assoc->init->bend_sort = NULL;
500 assoc->init->bend_search = NULL;
501 assoc->init->bend_present = NULL;
502 assoc->init->bend_esrequest = NULL;
503 assoc->init->bend_delete = NULL;
504 assoc->init->bend_scan = NULL;
505 assoc->init->bend_segment = NULL;
506 assoc->init->bend_fetch = NULL;
507 assoc->init->bend_explain = NULL;
508 assoc->init->bend_srw_scan = NULL;
509 assoc->init->bend_srw_update = NULL;
511 assoc->init->charneg_request = NULL;
512 assoc->init->charneg_response = NULL;
514 assoc->init->decode = assoc->decode;
515 assoc->init->peer_name =
516 odr_strdup (assoc->encode, cs_addrstr(assoc->client_link));
518 yaz_log(log_requestdetail, "peer %s", assoc->init->peer_name);
521 static int srw_bend_init(association *assoc, Z_SRW_diagnostic **d, int *num, Z_SRW_PDU *sr)
523 statserv_options_block *cb = statserv_getcontrol();
526 const char *encoding = "UTF-8";
528 bend_initresult *binitres;
530 yaz_log(log_requestdetail, "srw_bend_init config=%s", cb->configname);
531 assoc_init_reset(assoc);
535 Z_IdAuthentication *auth = odr_malloc(assoc->decode, sizeof(*auth));
538 len = strlen(sr->username) + 1;
540 len += strlen(sr->password) + 2;
541 auth->which = Z_IdAuthentication_open;
542 auth->u.open = odr_malloc(assoc->decode, len);
543 strcpy(auth->u.open, sr->username);
544 if (sr->password && *sr->password)
546 strcat(auth->u.open, "/");
547 strcat(auth->u.open, sr->password);
549 assoc->init->auth = auth;
553 ce = yaz_set_proposal_charneg(assoc->decode, &encoding, 1, 0, 0, 1);
554 assoc->init->charneg_request = ce->u.charNeg3;
557 if (!(binitres = (*cb->bend_init)(assoc->init)))
559 assoc->state = ASSOC_DEAD;
560 yaz_add_srw_diagnostic(assoc->encode, d, num,
561 YAZ_SRW_AUTHENTICATION_ERROR, 0);
564 assoc->backend = binitres->handle;
565 assoc->init->auth = 0;
566 if (binitres->errcode)
568 int srw_code = yaz_diag_bib1_to_srw(binitres->errcode);
569 assoc->state = ASSOC_DEAD;
570 yaz_add_srw_diagnostic(assoc->encode, d, num, srw_code,
571 binitres->errstring);
579 static int retrieve_fetch(association *assoc, bend_fetch_rr *rr)
582 yaz_record_conv_t rc = 0;
583 const char *match_schema = 0;
584 int *match_syntax = 0;
589 const char *input_schema = yaz_get_esn(rr->comp);
590 Odr_oid *input_syntax_raw = rr->request_format;
592 const char *backend_schema = 0;
593 Odr_oid *backend_syntax = 0;
595 r = yaz_retrieval_request(assoc->server->retrieval,
603 if (r == -1) /* error ? */
605 const char *details = yaz_retrieval_get_error(
606 assoc->server->retrieval);
608 rr->errcode = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
610 rr->errstring = odr_strdup(rr->stream, details);
613 else if (r == 1 || r == 3)
615 const char *details = input_schema;
617 YAZ_BIB1_SPECIFIED_ELEMENT_SET_NAME_NOT_VALID_FOR_SPECIFIED_;
619 rr->errstring = odr_strdup(rr->stream, details);
624 rr->errcode = YAZ_BIB1_RECORD_SYNTAX_UNSUPP;
625 if (input_syntax_raw)
627 char oidbuf[OID_STR_MAX];
628 oid_oid_to_dotstring(input_syntax_raw, oidbuf);
629 rr->errstring = odr_strdup(rr->stream, oidbuf);
635 yaz_set_esn(&rr->comp, backend_schema, odr_getmem(rr->stream));
638 rr->request_format = backend_syntax;
640 (*assoc->init->bend_fetch)(assoc->backend, rr);
641 if (rc && rr->record && rr->errcode == 0 && rr->len > 0)
642 { /* post conversion must take place .. */
643 WRBUF output_record = wrbuf_alloc();
644 int r = yaz_record_conv_record(rc, rr->record, rr->len, output_record);
647 const char *details = yaz_record_conv_get_error(rc);
648 rr->errcode = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
650 rr->errstring = odr_strdup(rr->stream, details);
654 rr->len = wrbuf_len(output_record);
655 rr->record = odr_malloc(rr->stream, rr->len);
656 memcpy(rr->record, wrbuf_buf(output_record), rr->len);
658 wrbuf_destroy(output_record);
661 rr->output_format = match_syntax;
663 rr->schema = odr_strdup(rr->stream, match_schema);
666 (*assoc->init->bend_fetch)(assoc->backend, rr);
671 static int srw_bend_fetch(association *assoc, int pos,
672 Z_SRW_searchRetrieveRequest *srw_req,
673 Z_SRW_record *record,
674 const char **addinfo)
677 ODR o = assoc->encode;
679 rr.setname = "default";
682 rr.request_format = odr_oiddup(assoc->decode, yaz_oid_recsyn_xml);
684 rr.comp = (Z_RecordComposition *)
685 odr_malloc(assoc->decode, sizeof(*rr.comp));
686 rr.comp->which = Z_RecordComp_complex;
687 rr.comp->u.complex = (Z_CompSpec *)
688 odr_malloc(assoc->decode, sizeof(Z_CompSpec));
689 rr.comp->u.complex->selectAlternativeSyntax = (bool_t *)
690 odr_malloc(assoc->encode, sizeof(bool_t));
691 *rr.comp->u.complex->selectAlternativeSyntax = 0;
692 rr.comp->u.complex->num_dbSpecific = 0;
693 rr.comp->u.complex->dbSpecific = 0;
694 rr.comp->u.complex->num_recordSyntax = 0;
695 rr.comp->u.complex->recordSyntax = 0;
697 rr.comp->u.complex->generic = (Z_Specification *)
698 odr_malloc(assoc->decode, sizeof(Z_Specification));
700 /* schema uri = recordSchema (or NULL if recordSchema is not given) */
701 rr.comp->u.complex->generic->which = Z_Schema_uri;
702 rr.comp->u.complex->generic->schema.uri = srw_req->recordSchema;
704 /* ESN = recordSchema if recordSchema is present */
705 rr.comp->u.complex->generic->elementSpec = 0;
706 if (srw_req->recordSchema)
708 rr.comp->u.complex->generic->elementSpec =
709 (Z_ElementSpec *) odr_malloc(assoc->encode, sizeof(Z_ElementSpec));
710 rr.comp->u.complex->generic->elementSpec->which =
711 Z_ElementSpec_elementSetName;
712 rr.comp->u.complex->generic->elementSpec->u.elementSetName =
713 srw_req->recordSchema;
716 rr.stream = assoc->encode;
717 rr.print = assoc->print;
725 rr.surrogate_flag = 0;
726 rr.schema = srw_req->recordSchema;
728 if (!assoc->init->bend_fetch)
731 retrieve_fetch(assoc, &rr);
733 if (rr.errcode && rr.surrogate_flag)
735 int code = yaz_diag_bib1_to_srw(rr.errcode);
736 const char *message = yaz_diag_srw_str(code);
739 len += strlen(message);
741 len += strlen(rr.errstring);
743 record->recordData_buf = odr_malloc(o, len);
745 sprintf(record->recordData_buf, "<diagnostic "
746 "xmlns=\"http://www.loc.gov/zing/srw/diagnostic/\">\n"
747 " <uri>info:srw/diagnostic/1/%d</uri>\n", code);
749 sprintf(record->recordData_buf + strlen(record->recordData_buf),
750 " <details>%s</details>\n", rr.errstring);
752 sprintf(record->recordData_buf + strlen(record->recordData_buf),
753 " <message>%s</message>\n", message);
754 sprintf(record->recordData_buf + strlen(record->recordData_buf),
756 record->recordData_len = strlen(record->recordData_buf);
757 record->recordPosition = odr_intdup(o, pos);
758 record->recordSchema = "info:srw/schema/1/diagnostics-v1.1";
761 else if (rr.len >= 0)
763 record->recordData_buf = rr.record;
764 record->recordData_len = rr.len;
765 record->recordPosition = odr_intdup(o, pos);
767 record->recordSchema = odr_strdup(o, rr.schema);
769 record->recordSchema = 0;
773 *addinfo = rr.errstring;
779 static int cql2pqf(ODR odr, const char *cql, cql_transform_t ct,
780 Z_Query *query_result)
782 /* have a CQL query and CQL to PQF transform .. */
783 CQL_parser cp = cql_parser_create();
789 r = cql_parser_string(cp, cql);
792 /* CQL syntax error */
798 r = cql_transform_buf(ct,
799 cql_parser_result(cp),
800 rpn_buf, sizeof(rpn_buf)-1);
802 srw_errcode = cql_transform_error(ct, &add);
806 /* Syntax & transform OK. */
807 /* Convert PQF string to Z39.50 to RPN query struct */
808 YAZ_PQF_Parser pp = yaz_pqf_create();
809 Z_RPNQuery *rpnquery = yaz_pqf_parse(pp, odr, rpn_buf);
814 int code = yaz_pqf_error(pp, &pqf_msg, &off);
815 yaz_log(YLOG_WARN, "PQF Parser Error %s (code %d)",
821 query_result->which = Z_Query_type_1;
822 query_result->u.type_1 = rpnquery;
826 cql_parser_destroy(cp);
830 static int cql2pqf_scan(ODR odr, const char *cql, cql_transform_t ct,
831 Z_AttributesPlusTerm *result)
835 int srw_error = cql2pqf(odr, cql, ct, &query);
838 if (query.which != Z_Query_type_1 && query.which != Z_Query_type_101)
839 return 10; /* bad query type */
840 rpn = query.u.type_1;
841 if (!rpn->RPNStructure)
842 return 10; /* must be structure */
843 if (rpn->RPNStructure->which != Z_RPNStructure_simple)
844 return 10; /* must be simple */
845 if (rpn->RPNStructure->u.simple->which != Z_Operand_APT)
846 return 10; /* must be attributes plus term node .. */
847 memcpy(result, rpn->RPNStructure->u.simple->u.attributesPlusTerm,
852 static void srw_bend_search(association *assoc, request *req,
854 Z_SRW_searchRetrieveResponse *srw_res,
859 Z_SRW_searchRetrieveRequest *srw_req = sr->u.request;
862 yaz_log(log_requestdetail, "Got SRW SearchRetrieveRequest");
863 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
864 if (srw_res->num_diagnostics == 0 && assoc->init)
867 rr.setname = "default";
870 rr.basenames = &srw_req->database;
874 rr.srw_setnameIdleTime = 0;
875 rr.estimated_hit_count = 0;
876 rr.partial_resultset = 0;
877 rr.query = (Z_Query *) odr_malloc (assoc->decode, sizeof(*rr.query));
878 rr.query->u.type_1 = 0;
880 if (srw_req->query_type == Z_SRW_query_type_cql)
882 if (assoc->server && assoc->server->cql_transform)
884 int srw_errcode = cql2pqf(assoc->encode, srw_req->query.cql,
885 assoc->server->cql_transform,
889 yaz_add_srw_diagnostic(assoc->encode,
890 &srw_res->diagnostics,
891 &srw_res->num_diagnostics,
897 /* CQL query to backend. Wrap it - Z39.50 style */
898 ext = (Z_External *) odr_malloc(assoc->decode, sizeof(*ext));
899 ext->direct_reference = odr_getoidbystr(assoc->decode,
900 "1.2.840.10003.16.2");
901 ext->indirect_reference = 0;
903 ext->which = Z_External_CQL;
904 ext->u.cql = srw_req->query.cql;
906 rr.query->which = Z_Query_type_104;
907 rr.query->u.type_104 = ext;
910 else if (srw_req->query_type == Z_SRW_query_type_pqf)
912 Z_RPNQuery *RPNquery;
913 YAZ_PQF_Parser pqf_parser;
915 pqf_parser = yaz_pqf_create ();
917 RPNquery = yaz_pqf_parse (pqf_parser, assoc->decode,
923 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
924 yaz_log(log_requestdetail, "Parse error %d %s near offset %ld",
925 code, pqf_msg, (long) off);
926 srw_error = YAZ_SRW_QUERY_SYNTAX_ERROR;
929 rr.query->which = Z_Query_type_1;
930 rr.query->u.type_1 = RPNquery;
932 yaz_pqf_destroy (pqf_parser);
936 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
937 &srw_res->num_diagnostics,
938 YAZ_SRW_UNSUPP_QUERY_TYPE, 0);
940 if (rr.query->u.type_1)
942 rr.stream = assoc->encode;
943 rr.decode = assoc->decode;
944 rr.print = assoc->print;
946 if ( srw_req->sort.sortKeys )
947 rr.srw_sortKeys = odr_strdup(assoc->encode,
948 srw_req->sort.sortKeys );
949 rr.association = assoc;
955 yaz_log_zquery_level(log_requestdetail,rr.query);
957 (assoc->init->bend_search)(assoc->backend, &rr);
960 if (rr.errcode == YAZ_BIB1_DATABASE_UNAVAILABLE)
966 srw_error = yaz_diag_bib1_to_srw (rr.errcode);
967 yaz_add_srw_diagnostic(assoc->encode,
968 &srw_res->diagnostics,
969 &srw_res->num_diagnostics,
970 srw_error, rr.errstring);
975 int number = srw_req->maximumRecords ? *srw_req->maximumRecords : 0;
976 int start = srw_req->startRecord ? *srw_req->startRecord : 1;
978 yaz_log(log_requestdetail, "Request to pack %d+%d out of %d",
979 start, number, rr.hits);
981 srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
984 srw_res->resultSetId =
985 odr_strdup(assoc->encode, rr.srw_setname );
986 srw_res->resultSetIdleTime =
987 odr_intdup(assoc->encode, *rr.srw_setnameIdleTime );
990 if ((rr.hits > 0 && start > rr.hits) || start < 1)
992 yaz_add_srw_diagnostic(
994 &srw_res->diagnostics, &srw_res->num_diagnostics,
995 YAZ_SRW_FIRST_RECORD_POSITION_OUT_OF_RANGE, 0);
1001 if (start + number > rr.hits)
1002 number = rr.hits - start + 1;
1004 /* Call bend_present if defined */
1005 if (assoc->init->bend_present)
1007 bend_present_rr *bprr = (bend_present_rr*)
1008 odr_malloc (assoc->decode, sizeof(*bprr));
1009 bprr->setname = "default";
1010 bprr->start = start;
1011 bprr->number = number;
1012 if (srw_req->recordSchema)
1014 bprr->comp = (Z_RecordComposition *) odr_malloc(assoc->decode,
1015 sizeof(*bprr->comp));
1016 bprr->comp->which = Z_RecordComp_simple;
1017 bprr->comp->u.simple = (Z_ElementSetNames *)
1018 odr_malloc(assoc->decode, sizeof(Z_ElementSetNames));
1019 bprr->comp->u.simple->which = Z_ElementSetNames_generic;
1020 bprr->comp->u.simple->u.generic = srw_req->recordSchema;
1026 bprr->stream = assoc->encode;
1027 bprr->referenceId = 0;
1028 bprr->print = assoc->print;
1029 bprr->request = req;
1030 bprr->association = assoc;
1032 bprr->errstring = NULL;
1033 (*assoc->init->bend_present)(assoc->backend, bprr);
1039 srw_error = yaz_diag_bib1_to_srw (bprr->errcode);
1040 yaz_add_srw_diagnostic(assoc->encode,
1041 &srw_res->diagnostics,
1042 &srw_res->num_diagnostics,
1043 srw_error, bprr->errstring);
1051 int packing = Z_SRW_recordPacking_string;
1052 if (srw_req->recordPacking)
1055 yaz_srw_str_to_pack(srw_req->recordPacking);
1057 packing = Z_SRW_recordPacking_string;
1059 srw_res->records = (Z_SRW_record *)
1060 odr_malloc(assoc->encode,
1061 number * sizeof(*srw_res->records));
1063 srw_res->extra_records = (Z_SRW_extra_record **)
1064 odr_malloc(assoc->encode,
1065 number*sizeof(*srw_res->extra_records));
1067 for (i = 0; i<number; i++)
1070 const char *addinfo = 0;
1072 srw_res->records[j].recordPacking = packing;
1073 srw_res->records[j].recordData_buf = 0;
1074 srw_res->extra_records[j] = 0;
1075 yaz_log(YLOG_DEBUG, "srw_bend_fetch %d", i+start);
1076 errcode = srw_bend_fetch(assoc, i+start, srw_req,
1077 srw_res->records + j,
1081 yaz_add_srw_diagnostic(assoc->encode,
1082 &srw_res->diagnostics,
1083 &srw_res->num_diagnostics,
1084 yaz_diag_bib1_to_srw (errcode),
1089 if (srw_res->records[j].recordData_buf)
1092 srw_res->num_records = j;
1094 srw_res->records = 0;
1097 if (rr.estimated_hit_count || rr.partial_resultset)
1099 yaz_add_srw_diagnostic(
1101 &srw_res->diagnostics,
1102 &srw_res->num_diagnostics,
1103 YAZ_SRW_RESULT_SET_CREATED_WITH_VALID_PARTIAL_RESULTS_AVAILABLE,
1111 const char *querystr = "?";
1112 const char *querytype = "?";
1113 WRBUF wr = wrbuf_alloc();
1115 switch (srw_req->query_type)
1117 case Z_SRW_query_type_cql:
1119 querystr = srw_req->query.cql;
1121 case Z_SRW_query_type_pqf:
1123 querystr = srw_req->query.pqf;
1126 wrbuf_printf(wr, "SRWSearch ");
1127 wrbuf_printf(wr, srw_req->database);
1128 wrbuf_printf(wr, " ");
1129 if (srw_res->num_diagnostics)
1130 wrbuf_printf(wr, "ERROR %s", srw_res->diagnostics[0].uri);
1131 else if (*http_code != 200)
1132 wrbuf_printf(wr, "ERROR info:http/%d", *http_code);
1133 else if (srw_res->numberOfRecords)
1135 wrbuf_printf(wr, "OK %d",
1136 (srw_res->numberOfRecords ?
1137 *srw_res->numberOfRecords : 0));
1139 wrbuf_printf(wr, " %s %d+%d",
1140 (srw_res->resultSetId ?
1141 srw_res->resultSetId : "-"),
1142 (srw_req->startRecord ? *srw_req->startRecord : 1),
1143 srw_res->num_records);
1144 yaz_log(log_request, "%s %s: %s", wrbuf_cstr(wr), querytype, querystr);
1149 static char *srw_bend_explain_default(void *handle, bend_explain_rr *rr)
1152 xmlNodePtr ptr = rr->server_node_ptr;
1155 for (ptr = ptr->children; ptr; ptr = ptr->next)
1157 if (ptr->type != XML_ELEMENT_NODE)
1159 if (!strcmp((const char *) ptr->name, "explain"))
1162 xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
1166 ptr = xmlCopyNode(ptr, 1);
1168 xmlDocSetRootElement(doc, ptr);
1170 xmlDocDumpMemory(doc, &buf_out, &len);
1171 content = (char*) odr_malloc(rr->stream, 1+len);
1172 memcpy(content, buf_out, len);
1173 content[len] = '\0';
1177 rr->explain_buf = content;
1185 static void srw_bend_explain(association *assoc, request *req,
1187 Z_SRW_explainResponse *srw_res,
1190 Z_SRW_explainRequest *srw_req = sr->u.explain_request;
1191 yaz_log(log_requestdetail, "Got SRW ExplainRequest");
1193 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1198 rr.stream = assoc->encode;
1199 rr.decode = assoc->decode;
1200 rr.print = assoc->print;
1202 rr.database = srw_req->database;
1204 rr.server_node_ptr = assoc->server->server_node_ptr;
1206 rr.server_node_ptr = 0;
1207 rr.schema = "http://explain.z3950.org/dtd/2.0/";
1208 if (assoc->init->bend_explain)
1209 (*assoc->init->bend_explain)(assoc->backend, &rr);
1211 srw_bend_explain_default(assoc->backend, &rr);
1215 int packing = Z_SRW_recordPacking_string;
1216 if (srw_req->recordPacking)
1219 yaz_srw_str_to_pack(srw_req->recordPacking);
1221 packing = Z_SRW_recordPacking_string;
1223 srw_res->record.recordSchema = rr.schema;
1224 srw_res->record.recordPacking = packing;
1225 srw_res->record.recordData_buf = rr.explain_buf;
1226 srw_res->record.recordData_len = strlen(rr.explain_buf);
1227 srw_res->record.recordPosition = 0;
1233 static void srw_bend_scan(association *assoc, request *req,
1235 Z_SRW_scanResponse *srw_res,
1238 Z_SRW_scanRequest *srw_req = sr->u.scan_request;
1239 yaz_log(log_requestdetail, "Got SRW ScanRequest");
1242 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1243 if (srw_res->num_diagnostics == 0 && assoc->init)
1245 struct scan_entry *save_entries;
1247 bend_scan_rr *bsrr = (bend_scan_rr *)
1248 odr_malloc (assoc->encode, sizeof(*bsrr));
1249 bsrr->num_bases = 1;
1250 bsrr->basenames = &srw_req->database;
1252 bsrr->num_entries = srw_req->maximumTerms ?
1253 *srw_req->maximumTerms : 10;
1254 bsrr->term_position = srw_req->responsePosition ?
1255 *srw_req->responsePosition : 1;
1258 bsrr->errstring = 0;
1259 bsrr->referenceId = 0;
1260 bsrr->stream = assoc->encode;
1261 bsrr->print = assoc->print;
1262 bsrr->step_size = odr_intdup(assoc->decode, 0);
1265 if (bsrr->num_entries > 0)
1268 bsrr->entries = odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
1270 for (i = 0; i<bsrr->num_entries; i++)
1272 bsrr->entries[i].term = 0;
1273 bsrr->entries[i].occurrences = 0;
1274 bsrr->entries[i].errcode = 0;
1275 bsrr->entries[i].errstring = 0;
1276 bsrr->entries[i].display_term = 0;
1279 save_entries = bsrr->entries; /* save it so we can compare later */
1281 if (srw_req->query_type == Z_SRW_query_type_pqf &&
1282 assoc->init->bend_scan)
1284 YAZ_PQF_Parser pqf_parser = yaz_pqf_create();
1286 bsrr->term = yaz_pqf_scan(pqf_parser, assoc->decode,
1287 &bsrr->attributeset,
1288 srw_req->scanClause.pqf);
1289 yaz_pqf_destroy(pqf_parser);
1290 bsrr->scanClause = 0;
1291 ((int (*)(void *, bend_scan_rr *))
1292 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1294 else if (srw_req->query_type == Z_SRW_query_type_cql
1295 && assoc->init->bend_scan && assoc->server
1296 && assoc->server->cql_transform)
1299 bsrr->scanClause = 0;
1300 bsrr->attributeset = 0;
1301 bsrr->term = odr_malloc(assoc->decode, sizeof(*bsrr->term));
1302 srw_error = cql2pqf_scan(assoc->encode,
1303 srw_req->scanClause.cql,
1304 assoc->server->cql_transform,
1307 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1308 &srw_res->num_diagnostics,
1312 ((int (*)(void *, bend_scan_rr *))
1313 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1316 else if (srw_req->query_type == Z_SRW_query_type_cql
1317 && assoc->init->bend_srw_scan)
1320 bsrr->attributeset = 0;
1321 bsrr->scanClause = srw_req->scanClause.cql;
1322 ((int (*)(void *, bend_scan_rr *))
1323 (*assoc->init->bend_srw_scan))(assoc->backend, bsrr);
1327 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1328 &srw_res->num_diagnostics,
1329 YAZ_SRW_UNSUPP_OPERATION, "scan");
1334 if (bsrr->errcode == YAZ_BIB1_DATABASE_UNAVAILABLE)
1339 srw_error = yaz_diag_bib1_to_srw (bsrr->errcode);
1341 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1342 &srw_res->num_diagnostics,
1343 srw_error, bsrr->errstring);
1345 else if (srw_res->num_diagnostics == 0 && bsrr->num_entries)
1348 srw_res->terms = (Z_SRW_scanTerm*)
1349 odr_malloc(assoc->encode, sizeof(*srw_res->terms) *
1352 srw_res->num_terms = bsrr->num_entries;
1353 for (i = 0; i<bsrr->num_entries; i++)
1355 Z_SRW_scanTerm *t = srw_res->terms + i;
1356 t->value = odr_strdup(assoc->encode, bsrr->entries[i].term);
1357 t->numberOfRecords =
1358 odr_intdup(assoc->encode, bsrr->entries[i].occurrences);
1360 if (save_entries == bsrr->entries &&
1361 bsrr->entries[i].display_term)
1363 /* the entries was _not_ set by the handler. So it's
1364 safe to test for new member display_term. It is
1367 t->displayTerm = odr_strdup(assoc->encode,
1368 bsrr->entries[i].display_term);
1376 WRBUF wr = wrbuf_alloc();
1377 const char *querytype = 0;
1378 const char *querystr = 0;
1380 switch(srw_req->query_type)
1382 case Z_SRW_query_type_pqf:
1384 querystr = srw_req->scanClause.pqf;
1386 case Z_SRW_query_type_cql:
1388 querystr = srw_req->scanClause.cql;
1391 querytype = "UNKNOWN";
1395 wrbuf_printf(wr, "SRWScan ");
1396 wrbuf_printf(wr, srw_req->database);
1397 wrbuf_printf(wr, " ");
1399 if (srw_res->num_diagnostics)
1400 wrbuf_printf(wr, "ERROR %s - ", srw_res->diagnostics[0].uri);
1401 else if (srw_res->num_terms)
1402 wrbuf_printf(wr, "OK %d - ", srw_res->num_terms);
1404 wrbuf_printf(wr, "OK - - ");
1406 wrbuf_printf(wr, "%d+%d+0 ",
1407 (srw_req->responsePosition ?
1408 *srw_req->responsePosition : 1),
1409 (srw_req->maximumTerms ?
1410 *srw_req->maximumTerms : 1));
1411 /* there is no step size in SRU/W ??? */
1412 wrbuf_printf(wr, "%s: %s ", querytype, querystr);
1413 yaz_log(log_request, "%s ", wrbuf_cstr(wr) );
1419 static void srw_bend_update(association *assoc, request *req,
1421 Z_SRW_updateResponse *srw_res,
1424 Z_SRW_updateRequest *srw_req = sr->u.update_request;
1425 yaz_log(log_session, "SRWUpdate action=%s", srw_req->operation);
1426 yaz_log(YLOG_DEBUG, "num_diag = %d", srw_res->num_diagnostics );
1428 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1432 Z_SRW_extra_record *extra = srw_req->extra_record;
1434 rr.stream = assoc->encode;
1435 rr.print = assoc->print;
1437 rr.basenames = &srw_req->database;
1438 rr.operation = srw_req->operation;
1439 rr.operation_status = "failed";
1441 rr.record_versions = 0;
1442 rr.num_versions = 0;
1443 rr.record_packing = "string";
1444 rr.record_schema = 0;
1446 rr.extra_record_data = 0;
1447 rr.extra_request_data = 0;
1448 rr.extra_response_data = 0;
1454 if (rr.operation == 0)
1456 yaz_add_sru_update_diagnostic(
1457 assoc->encode, &srw_res->diagnostics,
1458 &srw_res->num_diagnostics,
1459 YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,
1463 yaz_log(YLOG_DEBUG, "basename = %s", rr.basenames[0] );
1464 yaz_log(YLOG_DEBUG, "Operation = %s", rr.operation );
1465 if (!strcmp( rr.operation, "delete"))
1467 if (srw_req->record && !srw_req->record->recordSchema)
1469 rr.record_schema = odr_strdup(
1471 srw_req->record->recordSchema);
1473 if (srw_req->record)
1475 rr.record_data = odr_strdupn(
1477 srw_req->record->recordData_buf,
1478 srw_req->record->recordData_len );
1480 if (extra && extra->extraRecordData_len)
1482 rr.extra_record_data = odr_strdupn(
1484 extra->extraRecordData_buf,
1485 extra->extraRecordData_len );
1487 if (srw_req->recordId)
1488 rr.record_id = srw_req->recordId;
1489 else if (extra && extra->recordIdentifier)
1490 rr.record_id = extra->recordIdentifier;
1492 else if (!strcmp(rr.operation, "replace"))
1494 if (srw_req->recordId)
1495 rr.record_id = srw_req->recordId;
1496 else if (extra && extra->recordIdentifier)
1497 rr.record_id = extra->recordIdentifier;
1500 yaz_add_sru_update_diagnostic(
1501 assoc->encode, &srw_res->diagnostics,
1502 &srw_res->num_diagnostics,
1503 YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,
1504 "recordIdentifier");
1506 if (!srw_req->record)
1508 yaz_add_sru_update_diagnostic(
1509 assoc->encode, &srw_res->diagnostics,
1510 &srw_res->num_diagnostics,
1511 YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,
1516 if (srw_req->record->recordSchema)
1517 rr.record_schema = odr_strdup(
1518 assoc->encode, srw_req->record->recordSchema);
1519 if (srw_req->record->recordData_len )
1521 rr.record_data = odr_strdupn(assoc->encode,
1522 srw_req->record->recordData_buf,
1523 srw_req->record->recordData_len );
1527 yaz_add_sru_update_diagnostic(
1528 assoc->encode, &srw_res->diagnostics,
1529 &srw_res->num_diagnostics,
1530 YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,
1534 if (extra && extra->extraRecordData_len)
1536 rr.extra_record_data = odr_strdupn(
1538 extra->extraRecordData_buf,
1539 extra->extraRecordData_len );
1542 else if (!strcmp(rr.operation, "insert"))
1544 if (srw_req->recordId)
1545 rr.record_id = srw_req->recordId;
1547 rr.record_id = extra->recordIdentifier;
1549 if (srw_req->record)
1551 if (srw_req->record->recordSchema)
1552 rr.record_schema = odr_strdup(
1553 assoc->encode, srw_req->record->recordSchema);
1555 if (srw_req->record->recordData_len)
1556 rr.record_data = odr_strdupn(
1558 srw_req->record->recordData_buf,
1559 srw_req->record->recordData_len );
1561 if (extra && extra->extraRecordData_len)
1563 rr.extra_record_data = odr_strdupn(
1565 extra->extraRecordData_buf,
1566 extra->extraRecordData_len );
1570 yaz_add_sru_update_diagnostic(assoc->encode, &srw_res->diagnostics,
1571 &srw_res->num_diagnostics,
1572 YAZ_SRU_UPDATE_INVALID_ACTION,
1575 if (srw_req->record)
1577 const char *pack_str =
1578 yaz_srw_pack_to_str(srw_req->record->recordPacking);
1580 rr.record_packing = odr_strdup(assoc->encode, pack_str);
1583 if (srw_req->num_recordVersions)
1585 rr.record_versions = srw_req->recordVersions;
1586 rr.num_versions = srw_req->num_recordVersions;
1588 if (srw_req->extraRequestData_len)
1590 rr.extra_request_data = odr_strdupn(assoc->encode,
1591 srw_req->extraRequestData_buf,
1592 srw_req->extraRequestData_len );
1594 if (srw_res->num_diagnostics == 0)
1596 if ( assoc->init->bend_srw_update)
1597 (*assoc->init->bend_srw_update)(assoc->backend, &rr);
1599 yaz_add_sru_update_diagnostic(
1600 assoc->encode, &srw_res->diagnostics,
1601 &srw_res->num_diagnostics,
1602 YAZ_SRU_UPDATE_UNSPECIFIED_DATABASE_ERROR,
1603 "No Update backend handler");
1607 yaz_add_srw_diagnostic_uri(assoc->encode,
1608 &srw_res->diagnostics,
1609 &srw_res->num_diagnostics,
1613 srw_res->recordId = rr.record_id;
1614 srw_res->operationStatus = rr.operation_status;
1615 srw_res->recordVersions = rr.record_versions;
1616 srw_res->num_recordVersions = rr.num_versions;
1617 if (srw_res->extraResponseData_len)
1619 srw_res->extraResponseData_buf = rr.extra_response_data;
1620 srw_res->extraResponseData_len = strlen(rr.extra_response_data);
1622 if (srw_res->num_diagnostics == 0 && rr.record_data)
1624 srw_res->record = yaz_srw_get_record(assoc->encode);
1625 srw_res->record->recordSchema = rr.record_schema;
1626 if (rr.record_packing)
1628 int pack = yaz_srw_str_to_pack(rr.record_packing);
1632 pack = Z_SRW_recordPacking_string;
1633 yaz_log(YLOG_WARN, "Back packing %s from backend",
1636 srw_res->record->recordPacking = pack;
1638 srw_res->record->recordData_buf = rr.record_data;
1639 srw_res->record->recordData_len = strlen(rr.record_data);
1640 if (rr.extra_record_data)
1642 Z_SRW_extra_record *ex =
1643 yaz_srw_get_extra_record(assoc->encode);
1644 srw_res->extra_record = ex;
1645 ex->extraRecordData_buf = rr.extra_record_data;
1646 ex->extraRecordData_len = strlen(rr.extra_record_data);
1652 /* check if path is OK (1); BAD (0) */
1653 static int check_path(const char *path)
1657 if (strstr(path, ".."))
1662 static char *read_file(const char *fname, ODR o, int *sz)
1665 FILE *inf = fopen(fname, "rb");
1669 fseek(inf, 0L, SEEK_END);
1672 buf = odr_malloc(o, *sz);
1673 fread(buf, 1, *sz, inf);
1678 static void process_http_request(association *assoc, request *req)
1680 Z_HTTP_Request *hreq = req->gdu_request->u.HTTP_Request;
1681 ODR o = assoc->encode;
1682 int r = 2; /* 2=NOT TAKEN, 1=TAKEN, 0=SOAP TAKEN */
1684 Z_SOAP *soap_package = 0;
1687 Z_HTTP_Response *hres = 0;
1689 const char *stylesheet = 0; /* for now .. set later */
1690 Z_SRW_diagnostic *diagnostic = 0;
1691 int num_diagnostic = 0;
1692 const char *host = z_HTTP_header_lookup(hreq->headers, "Host");
1694 if (!control_association(assoc, host, 0))
1696 p = z_get_HTTP_Response(o, 404);
1699 if (r == 2 && assoc->server && assoc->server->docpath
1700 && hreq->path[0] == '/'
1702 /* check if path is a proper prefix of documentroot */
1703 strncmp(hreq->path+1, assoc->server->docpath,
1704 strlen(assoc->server->docpath))
1707 if (!check_path(hreq->path))
1709 yaz_log(YLOG_LOG, "File %s access forbidden", hreq->path+1);
1710 p = z_get_HTTP_Response(o, 404);
1714 int content_size = 0;
1715 char *content_buf = read_file(hreq->path+1, o, &content_size);
1718 yaz_log(YLOG_LOG, "File %s not found", hreq->path+1);
1719 p = z_get_HTTP_Response(o, 404);
1723 const char *ctype = 0;
1724 yaz_mime_types types = yaz_mime_types_create();
1726 yaz_mime_types_add(types, "xsl", "application/xml");
1727 yaz_mime_types_add(types, "xml", "application/xml");
1728 yaz_mime_types_add(types, "css", "text/css");
1729 yaz_mime_types_add(types, "html", "text/html");
1730 yaz_mime_types_add(types, "htm", "text/html");
1731 yaz_mime_types_add(types, "txt", "text/plain");
1732 yaz_mime_types_add(types, "js", "application/x-javascript");
1734 yaz_mime_types_add(types, "gif", "image/gif");
1735 yaz_mime_types_add(types, "png", "image/png");
1736 yaz_mime_types_add(types, "jpg", "image/jpeg");
1737 yaz_mime_types_add(types, "jpeg", "image/jpeg");
1739 ctype = yaz_mime_lookup_fname(types, hreq->path);
1742 yaz_log(YLOG_LOG, "No mime type for %s", hreq->path+1);
1743 p = z_get_HTTP_Response(o, 404);
1747 p = z_get_HTTP_Response(o, 200);
1748 hres = p->u.HTTP_Response;
1749 hres->content_buf = content_buf;
1750 hres->content_len = content_size;
1751 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1753 yaz_mime_types_destroy(types);
1761 r = yaz_srw_decode(hreq, &sr, &soap_package, assoc->decode, &charset);
1762 yaz_log(YLOG_DEBUG, "yaz_srw_decode returned %d", r);
1764 if (r == 2) /* not taken */
1766 r = yaz_sru_decode(hreq, &sr, &soap_package, assoc->decode, &charset,
1767 &diagnostic, &num_diagnostic);
1768 yaz_log(YLOG_DEBUG, "yaz_sru_decode returned %d", r);
1770 if (r == 0) /* decode SRW/SRU OK .. */
1772 int http_code = 200;
1773 if (sr->which == Z_SRW_searchRetrieve_request)
1776 yaz_srw_get(assoc->encode, Z_SRW_searchRetrieve_response);
1778 stylesheet = sr->u.request->stylesheet;
1781 res->u.response->diagnostics = diagnostic;
1782 res->u.response->num_diagnostics = num_diagnostic;
1786 srw_bend_search(assoc, req, sr, res->u.response,
1789 if (http_code == 200)
1790 soap_package->u.generic->p = res;
1792 else if (sr->which == Z_SRW_explain_request)
1794 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_explain_response);
1795 stylesheet = sr->u.explain_request->stylesheet;
1798 res->u.explain_response->diagnostics = diagnostic;
1799 res->u.explain_response->num_diagnostics = num_diagnostic;
1801 srw_bend_explain(assoc, req, sr,
1802 res->u.explain_response, &http_code);
1803 if (http_code == 200)
1804 soap_package->u.generic->p = res;
1806 else if (sr->which == Z_SRW_scan_request)
1808 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_scan_response);
1809 stylesheet = sr->u.scan_request->stylesheet;
1812 res->u.scan_response->diagnostics = diagnostic;
1813 res->u.scan_response->num_diagnostics = num_diagnostic;
1815 srw_bend_scan(assoc, req, sr,
1816 res->u.scan_response, &http_code);
1817 if (http_code == 200)
1818 soap_package->u.generic->p = res;
1820 else if (sr->which == Z_SRW_update_request)
1822 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_update_response);
1823 yaz_log(YLOG_DEBUG, "handling SRW UpdateRequest");
1826 res->u.update_response->diagnostics = diagnostic;
1827 res->u.update_response->num_diagnostics = num_diagnostic;
1829 yaz_log(YLOG_DEBUG, "num_diag = %d", res->u.update_response->num_diagnostics );
1830 srw_bend_update(assoc, req, sr,
1831 res->u.update_response, &http_code);
1832 if (http_code == 200)
1833 soap_package->u.generic->p = res;
1837 yaz_log(log_request, "SOAP ERROR");
1838 /* FIXME - what error, what query */
1840 z_soap_error(assoc->encode, soap_package,
1841 "SOAP-ENV:Client", "Bad method", 0);
1843 if (http_code == 200 || http_code == 500)
1845 static Z_SOAP_Handler soap_handlers[4] = {
1847 {YAZ_XMLNS_SRU_v1_1, 0, (Z_SOAP_fun) yaz_srw_codec},
1848 {YAZ_XMLNS_SRU_v1_0, 0, (Z_SOAP_fun) yaz_srw_codec},
1849 {YAZ_XMLNS_UPDATE_v0_9, 0, (Z_SOAP_fun) yaz_ucp_codec},
1855 p = z_get_HTTP_Response(o, 200);
1856 hres = p->u.HTTP_Response;
1858 if (!stylesheet && assoc->server)
1859 stylesheet = assoc->server->stylesheet;
1861 /* empty stylesheet means NO stylesheet */
1862 if (stylesheet && *stylesheet == '\0')
1865 ret = z_soap_codec_enc_xsl(assoc->encode, &soap_package,
1866 &hres->content_buf, &hres->content_len,
1867 soap_handlers, charset, stylesheet);
1868 hres->code = http_code;
1870 strcpy(ctype, "text/xml");
1873 strcat(ctype, "; charset=");
1874 strcat(ctype, charset);
1876 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1879 p = z_get_HTTP_Response(o, http_code);
1883 p = z_get_HTTP_Response(o, 500);
1884 hres = p->u.HTTP_Response;
1885 if (!strcmp(hreq->version, "1.0"))
1887 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1888 if (v && !strcmp(v, "Keep-Alive"))
1892 hres->version = "1.0";
1896 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1897 if (v && !strcmp(v, "close"))
1901 hres->version = "1.1";
1905 z_HTTP_header_add(o, &hres->headers, "Connection", "close");
1906 assoc->state = ASSOC_DEAD;
1907 assoc->cs_get_mask = 0;
1912 const char *alive = z_HTTP_header_lookup(hreq->headers, "Keep-Alive");
1914 if (alive && isdigit(*(const unsigned char *) alive))
1918 if (t < 0 || t > 3600)
1920 iochan_settimeout(assoc->client_chan,t);
1921 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1923 process_gdu_response(assoc, req, p);
1926 static void process_gdu_request(association *assoc, request *req)
1928 if (req->gdu_request->which == Z_GDU_Z3950)
1931 req->apdu_request = req->gdu_request->u.z3950;
1932 if (process_z_request(assoc, req, &msg) < 0)
1933 do_close_req(assoc, Z_Close_systemProblem, msg, req);
1935 else if (req->gdu_request->which == Z_GDU_HTTP_Request)
1936 process_http_request(assoc, req);
1939 do_close_req(assoc, Z_Close_systemProblem, "bad protocol packet", req);
1944 * Initiate request processing.
1946 static int process_z_request(association *assoc, request *req, char **msg)
1952 *msg = "Unknown Error";
1953 assert(req && req->state == REQUEST_IDLE);
1954 if (req->apdu_request->which != Z_APDU_initRequest && !assoc->init)
1956 *msg = "Missing InitRequest";
1959 switch (req->apdu_request->which)
1961 case Z_APDU_initRequest:
1962 res = process_initRequest(assoc, req); break;
1963 case Z_APDU_searchRequest:
1964 res = process_searchRequest(assoc, req, &fd); break;
1965 case Z_APDU_presentRequest:
1966 res = process_presentRequest(assoc, req, &fd); break;
1967 case Z_APDU_scanRequest:
1968 if (assoc->init->bend_scan)
1969 res = process_scanRequest(assoc, req, &fd);
1972 *msg = "Cannot handle Scan APDU";
1976 case Z_APDU_extendedServicesRequest:
1977 if (assoc->init->bend_esrequest)
1978 res = process_ESRequest(assoc, req, &fd);
1981 *msg = "Cannot handle Extended Services APDU";
1985 case Z_APDU_sortRequest:
1986 if (assoc->init->bend_sort)
1987 res = process_sortRequest(assoc, req, &fd);
1990 *msg = "Cannot handle Sort APDU";
1995 process_close(assoc, req);
1997 case Z_APDU_deleteResultSetRequest:
1998 if (assoc->init->bend_delete)
1999 res = process_deleteRequest(assoc, req, &fd);
2002 *msg = "Cannot handle Delete APDU";
2006 case Z_APDU_segmentRequest:
2007 if (assoc->init->bend_segment)
2009 res = process_segmentRequest (assoc, req);
2013 *msg = "Cannot handle Segment APDU";
2017 case Z_APDU_triggerResourceControlRequest:
2020 *msg = "Bad APDU received";
2025 yaz_log(YLOG_DEBUG, " result immediately available");
2026 retval = process_z_response(assoc, req, res);
2030 yaz_log(YLOG_DEBUG, " result unavailble");
2033 else /* no result yet - one will be provided later */
2037 /* Set up an I/O handler for the fd supplied by the backend */
2039 yaz_log(YLOG_DEBUG, " establishing handler for result");
2040 req->state = REQUEST_PENDING;
2041 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT, 0)))
2043 iochan_setdata(chan, assoc);
2050 * Handle message from the backend.
2052 void backend_response(IOCHAN i, int event)
2054 association *assoc = (association *)iochan_getdata(i);
2055 request *req = request_head(&assoc->incoming);
2059 yaz_log(YLOG_DEBUG, "backend_response");
2060 assert(assoc && req && req->state != REQUEST_IDLE);
2061 /* determine what it is we're waiting for */
2062 switch (req->apdu_request->which)
2064 case Z_APDU_searchRequest:
2065 res = response_searchRequest(assoc, req, 0, &fd); break;
2067 case Z_APDU_presentRequest:
2068 res = response_presentRequest(assoc, req, 0, &fd); break;
2069 case Z_APDU_scanRequest:
2070 res = response_scanRequest(assoc, req, 0, &fd); break;
2073 yaz_log(YLOG_FATAL, "Serious programmer's lapse or bug");
2076 if ((res && process_z_response(assoc, req, res) < 0) || fd < 0)
2078 yaz_log(YLOG_WARN, "Fatal error when talking to backend");
2079 do_close(assoc, Z_Close_systemProblem, 0);
2083 else if (!res) /* no result yet - try again later */
2085 yaz_log(YLOG_DEBUG, " no result yet");
2086 iochan_setfd(i, fd); /* in case fd has changed */
2091 * Encode response, and transfer the request structure to the outgoing queue.
2093 static int process_gdu_response(association *assoc, request *req, Z_GDU *res)
2095 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
2099 if (!z_GDU(assoc->print, &res, 0, 0))
2100 yaz_log(YLOG_WARN, "ODR print error: %s",
2101 odr_errmsg(odr_geterror(assoc->print)));
2102 odr_reset(assoc->print);
2104 if (!z_GDU(assoc->encode, &res, 0, 0))
2106 yaz_log(YLOG_WARN, "ODR error when encoding PDU: %s [element %s]",
2107 odr_errmsg(odr_geterror(assoc->decode)),
2108 odr_getelement(assoc->decode));
2111 req->response = odr_getbuf(assoc->encode, &req->len_response,
2112 &req->size_response);
2113 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
2114 odr_reset(assoc->encode);
2115 req->state = REQUEST_IDLE;
2116 request_enq(&assoc->outgoing, req);
2117 /* turn the work over to the ir_session handler */
2118 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
2119 assoc->cs_put_mask = EVENT_OUTPUT;
2120 /* Is there more work to be done? give that to the input handler too */
2123 req = request_head(&assoc->incoming);
2124 if (req && req->state == REQUEST_IDLE)
2126 request_deq(&assoc->incoming);
2127 process_gdu_request(assoc, req);
2136 * Encode response, and transfer the request structure to the outgoing queue.
2138 static int process_z_response(association *assoc, request *req, Z_APDU *res)
2140 Z_GDU *gres = (Z_GDU *) odr_malloc(assoc->encode, sizeof(*res));
2141 gres->which = Z_GDU_Z3950;
2142 gres->u.z3950 = res;
2144 return process_gdu_response(assoc, req, gres);
2147 static char *get_vhost(Z_OtherInformation *otherInfo)
2149 return yaz_oi_get_string_oid(&otherInfo, yaz_oid_userinfo_proxy, 1, 0);
2153 * Handle init request.
2154 * At the moment, we don't check the options
2155 * anywhere else in the code - we just try not to do anything that would
2156 * break a naive client. We'll toss 'em into the association block when
2157 * we need them there.
2159 static Z_APDU *process_initRequest(association *assoc, request *reqb)
2161 Z_InitRequest *req = reqb->apdu_request->u.initRequest;
2162 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
2163 Z_InitResponse *resp = apdu->u.initResponse;
2164 bend_initresult *binitres;
2167 statserv_options_block *cb = 0; /* by default no control for backend */
2169 if (control_association(assoc, get_vhost(req->otherInfo), 1))
2170 cb = statserv_getcontrol(); /* got control block for backend */
2172 if (cb && assoc->backend)
2173 (*cb->bend_close)(assoc->backend);
2175 yaz_log(log_requestdetail, "Got initRequest");
2176 if (req->implementationId)
2177 yaz_log(log_requestdetail, "Id: %s",
2178 req->implementationId);
2179 if (req->implementationName)
2180 yaz_log(log_requestdetail, "Name: %s",
2181 req->implementationName);
2182 if (req->implementationVersion)
2183 yaz_log(log_requestdetail, "Version: %s",
2184 req->implementationVersion);
2186 assoc_init_reset(assoc);
2188 assoc->init->auth = req->idAuthentication;
2189 assoc->init->referenceId = req->referenceId;
2191 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
2193 Z_CharSetandLanguageNegotiation *negotiation =
2194 yaz_get_charneg_record (req->otherInfo);
2196 negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
2197 assoc->init->charneg_request = negotiation;
2203 if (req->implementationVersion)
2204 yaz_log(log_requestdetail, "Config: %s",
2207 iochan_settimeout(assoc->client_chan, cb->idle_timeout * 60);
2209 /* we have a backend control block, so call that init function */
2210 if (!(binitres = (*cb->bend_init)(assoc->init)))
2212 yaz_log(YLOG_WARN, "Bad response from backend.");
2215 assoc->backend = binitres->handle;
2219 /* no backend. return error */
2220 binitres = odr_malloc(assoc->encode, sizeof(*binitres));
2221 binitres->errstring = 0;
2222 binitres->errcode = YAZ_BIB1_PERMANENT_SYSTEM_ERROR;
2223 iochan_settimeout(assoc->client_chan, 10);
2225 if ((assoc->init->bend_sort))
2226 yaz_log (YLOG_DEBUG, "Sort handler installed");
2227 if ((assoc->init->bend_search))
2228 yaz_log (YLOG_DEBUG, "Search handler installed");
2229 if ((assoc->init->bend_present))
2230 yaz_log (YLOG_DEBUG, "Present handler installed");
2231 if ((assoc->init->bend_esrequest))
2232 yaz_log (YLOG_DEBUG, "ESRequest handler installed");
2233 if ((assoc->init->bend_delete))
2234 yaz_log (YLOG_DEBUG, "Delete handler installed");
2235 if ((assoc->init->bend_scan))
2236 yaz_log (YLOG_DEBUG, "Scan handler installed");
2237 if ((assoc->init->bend_segment))
2238 yaz_log (YLOG_DEBUG, "Segment handler installed");
2240 resp->referenceId = req->referenceId;
2242 /* let's tell the client what we can do */
2243 if (ODR_MASK_GET(req->options, Z_Options_search))
2245 ODR_MASK_SET(resp->options, Z_Options_search);
2246 strcat(options, "srch");
2248 if (ODR_MASK_GET(req->options, Z_Options_present))
2250 ODR_MASK_SET(resp->options, Z_Options_present);
2251 strcat(options, " prst");
2253 if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
2254 assoc->init->bend_delete)
2256 ODR_MASK_SET(resp->options, Z_Options_delSet);
2257 strcat(options, " del");
2259 if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
2260 assoc->init->bend_esrequest)
2262 ODR_MASK_SET(resp->options, Z_Options_extendedServices);
2263 strcat (options, " extendedServices");
2265 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
2267 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
2268 strcat(options, " namedresults");
2270 if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
2272 ODR_MASK_SET(resp->options, Z_Options_scan);
2273 strcat(options, " scan");
2275 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
2277 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
2278 strcat(options, " concurrop");
2280 if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
2282 ODR_MASK_SET(resp->options, Z_Options_sort);
2283 strcat(options, " sort");
2286 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel)
2287 && assoc->init->charneg_response)
2289 Z_OtherInformation **p;
2290 Z_OtherInformationUnit *p0;
2292 yaz_oi_APDU(apdu, &p);
2294 if ((p0=yaz_oi_update(p, assoc->encode, NULL, 0, 0))) {
2295 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
2297 p0->which = Z_OtherInfo_externallyDefinedInfo;
2298 p0->information.externallyDefinedInfo =
2299 assoc->init->charneg_response;
2301 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
2302 strcat(options, " negotiation");
2305 if (ODR_MASK_GET(req->options, Z_Options_triggerResourceCtrl))
2306 ODR_MASK_SET(resp->options, Z_Options_triggerResourceCtrl);
2308 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
2310 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
2311 assoc->version = 1; /* 1 & 2 are equivalent */
2313 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
2315 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
2318 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
2320 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
2324 yaz_log(log_requestdetail, "Negotiated to v%d: %s", assoc->version, options);
2326 if (*req->maximumRecordSize < assoc->maximumRecordSize)
2327 assoc->maximumRecordSize = *req->maximumRecordSize;
2329 if (*req->preferredMessageSize < assoc->preferredMessageSize)
2330 assoc->preferredMessageSize = *req->preferredMessageSize;
2332 resp->preferredMessageSize = &assoc->preferredMessageSize;
2333 resp->maximumRecordSize = &assoc->maximumRecordSize;
2335 resp->implementationId = odr_prepend(assoc->encode,
2336 assoc->init->implementation_id,
2337 resp->implementationId);
2339 resp->implementationName = odr_prepend(assoc->encode,
2340 assoc->init->implementation_name,
2341 odr_prepend(assoc->encode, "GFS", resp->implementationName));
2343 version = odr_strdup(assoc->encode, "$Revision: 1.115 $");
2344 if (strlen(version) > 10) /* check for unexpanded CVS strings */
2345 version[strlen(version)-2] = '\0';
2346 resp->implementationVersion = odr_prepend(assoc->encode,
2347 assoc->init->implementation_version,
2348 odr_prepend(assoc->encode, &version[11],
2349 resp->implementationVersion));
2351 if (binitres->errcode)
2353 assoc->state = ASSOC_DEAD;
2354 resp->userInformationField =
2355 init_diagnostics(assoc->encode, binitres->errcode,
2356 binitres->errstring);
2361 if (!req->idAuthentication)
2362 yaz_log(log_request, "Auth none");
2363 else if (req->idAuthentication->which == Z_IdAuthentication_open)
2365 const char *open = req->idAuthentication->u.open;
2366 const char *slash = strchr(open, '/');
2372 yaz_log(log_request, "Auth open %.*s", len, open);
2374 else if (req->idAuthentication->which == Z_IdAuthentication_idPass)
2376 const char *user = req->idAuthentication->u.idPass->userId;
2377 const char *group = req->idAuthentication->u.idPass->groupId;
2378 yaz_log(log_request, "Auth idPass %s %s",
2379 user ? user : "-", group ? group : "-");
2381 else if (req->idAuthentication->which
2382 == Z_IdAuthentication_anonymous)
2384 yaz_log(log_request, "Auth anonymous");
2388 yaz_log(log_request, "Auth other");
2393 WRBUF wr = wrbuf_alloc();
2394 wrbuf_printf(wr, "Init ");
2395 if (binitres->errcode)
2396 wrbuf_printf(wr, "ERROR %d", binitres->errcode);
2398 wrbuf_printf(wr, "OK -");
2399 wrbuf_printf(wr, " ID:%s Name:%s Version:%s",
2400 (req->implementationId ? req->implementationId :"-"),
2401 (req->implementationName ?
2402 req->implementationName : "-"),
2403 (req->implementationVersion ?
2404 req->implementationVersion : "-")
2406 yaz_log(log_request, "%s", wrbuf_cstr(wr));
2413 * Set the specified `errcode' and `errstring' into a UserInfo-1
2414 * external to be returned to the client in accordance with Z35.90
2415 * Implementor Agreement 5 (Returning diagnostics in an InitResponse):
2416 * http://lcweb.loc.gov/z3950/agency/agree/initdiag.html
2418 static Z_External *init_diagnostics(ODR odr, int error, const char *addinfo)
2420 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2421 addinfo ? " -- " : "", addinfo ? addinfo : "");
2422 return zget_init_diagnostics(odr, error, addinfo);
2426 * nonsurrogate diagnostic record.
2428 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
2430 Z_Records *rec = (Z_Records *) odr_malloc (assoc->encode, sizeof(*rec));
2432 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2433 addinfo ? " -- " : "", addinfo ? addinfo : "");
2435 rec->which = Z_Records_NSD;
2436 rec->u.nonSurrogateDiagnostic = zget_DefaultDiagFormat(assoc->encode,
2442 * surrogate diagnostic.
2444 static Z_NamePlusRecord *surrogatediagrec(association *assoc,
2446 int error, const char *addinfo)
2448 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2449 addinfo ? " -- " : "", addinfo ? addinfo : "");
2450 return zget_surrogateDiagRec(assoc->encode, dbname, error, addinfo);
2453 static Z_Records *pack_records(association *a, char *setname, int start,
2454 int *num, Z_RecordComposition *comp,
2455 int *next, int *pres,
2456 Z_ReferenceId *referenceId,
2457 int *oid, int *errcode)
2459 int recno, total_length = 0, toget = *num, dumped_records = 0;
2460 Z_Records *records =
2461 (Z_Records *) odr_malloc (a->encode, sizeof(*records));
2462 Z_NamePlusRecordList *reclist =
2463 (Z_NamePlusRecordList *) odr_malloc (a->encode, sizeof(*reclist));
2464 Z_NamePlusRecord **list =
2465 (Z_NamePlusRecord **) odr_malloc (a->encode, sizeof(*list) * toget);
2467 records->which = Z_Records_DBOSD;
2468 records->u.databaseOrSurDiagnostics = reclist;
2469 reclist->num_records = 0;
2470 reclist->records = list;
2471 *pres = Z_PresentStatus_success;
2475 yaz_log(log_requestdetail, "Request to pack %d+%d %s", start, toget, setname);
2476 yaz_log(log_requestdetail, "pms=%d, mrs=%d", a->preferredMessageSize,
2477 a->maximumRecordSize);
2478 for (recno = start; reclist->num_records < toget; recno++)
2481 Z_NamePlusRecord *thisrec;
2482 int this_length = 0;
2484 * we get the number of bytes allocated on the stream before any
2485 * allocation done by the backend - this should give us a reasonable
2486 * idea of the total size of the data so far.
2488 total_length = odr_total(a->encode) - dumped_records;
2494 freq.last_in_set = 0;
2495 freq.setname = setname;
2496 freq.surrogate_flag = 0;
2497 freq.number = recno;
2499 freq.request_format = oid;
2500 freq.output_format = 0;
2501 freq.stream = a->encode;
2502 freq.print = a->print;
2503 freq.referenceId = referenceId;
2506 retrieve_fetch(a, &freq);
2508 *next = freq.last_in_set ? 0 : recno + 1;
2510 /* backend should be able to signal whether error is system-wide
2511 or only pertaining to current record */
2514 if (!freq.surrogate_flag)
2517 *pres = Z_PresentStatus_failure;
2518 /* for 'present request out of range',
2519 set addinfo to record position if not set */
2520 if (freq.errcode == YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE &&
2521 freq.errstring == 0)
2523 sprintf (s, "%d", recno);
2527 *errcode = freq.errcode;
2528 return diagrec(a, freq.errcode, freq.errstring);
2530 reclist->records[reclist->num_records] =
2531 surrogatediagrec(a, freq.basename, freq.errcode,
2533 reclist->num_records++;
2536 if (freq.record == 0) /* no error and no record ? */
2538 *next = 0; /* signal end-of-set and stop */
2542 this_length = freq.len;
2544 this_length = odr_total(a->encode) - total_length - dumped_records;
2545 yaz_log(YLOG_DEBUG, " fetched record, len=%d, total=%d dumped=%d",
2546 this_length, total_length, dumped_records);
2547 if (a->preferredMessageSize > 0 &&
2548 this_length + total_length > a->preferredMessageSize)
2550 /* record is small enough, really */
2551 if (this_length <= a->preferredMessageSize && recno > start)
2553 yaz_log(log_requestdetail, " Dropped last normal-sized record");
2554 *pres = Z_PresentStatus_partial_2;
2557 /* record can only be fetched by itself */
2558 if (this_length < a->maximumRecordSize)
2560 yaz_log(log_requestdetail, " Record > prefmsgsz");
2563 yaz_log(YLOG_DEBUG, " Dropped it");
2564 reclist->records[reclist->num_records] =
2565 surrogatediagrec(a, freq.basename, 16, 0);
2566 reclist->num_records++;
2567 dumped_records += this_length;
2571 else /* too big entirely */
2573 yaz_log(log_requestdetail, "Record > maxrcdsz this=%d max=%d",
2574 this_length, a->maximumRecordSize);
2575 reclist->records[reclist->num_records] =
2576 surrogatediagrec(a, freq.basename, 17, 0);
2577 reclist->num_records++;
2578 dumped_records += this_length;
2583 if (!(thisrec = (Z_NamePlusRecord *)
2584 odr_malloc(a->encode, sizeof(*thisrec))))
2587 thisrec->databaseName = odr_strdup(a->encode, freq.basename);
2589 thisrec->databaseName = 0;
2590 thisrec->which = Z_NamePlusRecord_databaseRecord;
2592 if (!freq.output_format)
2593 freq.output_format = freq.request_format;
2594 thisrec->u.databaseRecord = z_ext_record_oid(
2595 a->encode, freq.output_format, freq.record, freq.len);
2596 if (!thisrec->u.databaseRecord)
2598 reclist->records[reclist->num_records] = thisrec;
2599 reclist->num_records++;
2601 *num = reclist->num_records;
2605 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
2608 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2609 bend_search_rr *bsrr =
2610 (bend_search_rr *)nmem_malloc (reqb->request_mem, sizeof(*bsrr));
2612 yaz_log(log_requestdetail, "Got SearchRequest.");
2614 bsrr->request = reqb;
2615 bsrr->association = assoc;
2616 bsrr->referenceId = req->referenceId;
2617 save_referenceId (reqb, bsrr->referenceId);
2618 bsrr->srw_sortKeys = 0;
2619 bsrr->srw_setname = 0;
2620 bsrr->srw_setnameIdleTime = 0;
2621 bsrr->estimated_hit_count = 0;
2622 bsrr->partial_resultset = 0;
2624 yaz_log (log_requestdetail, "ResultSet '%s'", req->resultSetName);
2625 if (req->databaseNames)
2628 for (i = 0; i < req->num_databaseNames; i++)
2629 yaz_log(log_requestdetail, "Database '%s'", req->databaseNames[i]);
2632 yaz_log_zquery_level(log_requestdetail,req->query);
2634 if (assoc->init->bend_search)
2636 bsrr->setname = req->resultSetName;
2637 bsrr->replace_set = *req->replaceIndicator;
2638 bsrr->num_bases = req->num_databaseNames;
2639 bsrr->basenames = req->databaseNames;
2640 bsrr->query = req->query;
2641 bsrr->stream = assoc->encode;
2642 nmem_transfer(odr_getmem(bsrr->stream), reqb->request_mem);
2643 bsrr->decode = assoc->decode;
2644 bsrr->print = assoc->print;
2647 bsrr->errstring = NULL;
2648 bsrr->search_info = NULL;
2650 if (assoc->server && assoc->server->cql_transform
2651 && req->query->which == Z_Query_type_104
2652 && req->query->u.type_104->which == Z_External_CQL)
2654 /* have a CQL query and a CQL to PQF transform .. */
2656 cql2pqf(bsrr->stream, req->query->u.type_104->u.cql,
2657 assoc->server->cql_transform, bsrr->query);
2659 bsrr->errcode = yaz_diag_srw_to_bib1(srw_errcode);
2662 (assoc->init->bend_search)(assoc->backend, bsrr);
2663 if (!bsrr->request) /* backend not ready with the search response */
2664 return 0; /* should not be used any more */
2668 /* FIXME - make a diagnostic for it */
2669 yaz_log(YLOG_WARN,"Search not supported ?!?!");
2671 return response_searchRequest(assoc, reqb, bsrr, fd);
2674 int bend_searchresponse(void *handle, bend_search_rr *bsrr) {return 0;}
2677 * Prepare a searchresponse based on the backend results. We probably want
2678 * to look at making the fetching of records nonblocking as well, but
2679 * so far, we'll keep things simple.
2680 * If bsrt is null, that means we're called in response to a communications
2681 * event, and we'll have to get the response for ourselves.
2683 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
2684 bend_search_rr *bsrt, int *fd)
2686 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2687 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2688 Z_SearchResponse *resp = (Z_SearchResponse *)
2689 odr_malloc (assoc->encode, sizeof(*resp));
2690 int *nulint = odr_intdup (assoc->encode, 0);
2691 int *next = odr_intdup(assoc->encode, 0);
2692 int *none = odr_intdup(assoc->encode, Z_SearchResponse_none);
2693 int returnedrecs = 0;
2695 apdu->which = Z_APDU_searchResponse;
2696 apdu->u.searchResponse = resp;
2697 resp->referenceId = req->referenceId;
2698 resp->additionalSearchInfo = 0;
2699 resp->otherInfo = 0;
2701 if (!bsrt && !bend_searchresponse(assoc->backend, bsrt))
2703 yaz_log(YLOG_FATAL, "Bad result from backend");
2706 else if (bsrt->errcode)
2708 resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
2709 resp->resultCount = nulint;
2710 resp->numberOfRecordsReturned = nulint;
2711 resp->nextResultSetPosition = nulint;
2712 resp->searchStatus = nulint;
2713 resp->resultSetStatus = none;
2714 resp->presentStatus = 0;
2718 bool_t *sr = odr_intdup(assoc->encode, 1);
2719 int *toget = odr_intdup(assoc->encode, 0);
2720 Z_RecordComposition comp, *compp = 0;
2722 yaz_log (log_requestdetail, "resultCount: %d", bsrt->hits);
2725 resp->resultCount = &bsrt->hits;
2727 comp.which = Z_RecordComp_simple;
2728 /* how many records does the user agent want, then? */
2729 if (bsrt->hits <= *req->smallSetUpperBound)
2731 *toget = bsrt->hits;
2732 if ((comp.u.simple = req->smallSetElementSetNames))
2735 else if (bsrt->hits < *req->largeSetLowerBound)
2737 *toget = *req->mediumSetPresentNumber;
2738 if (*toget > bsrt->hits)
2739 *toget = bsrt->hits;
2740 if ((comp.u.simple = req->mediumSetElementSetNames))
2746 if (*toget && !resp->records)
2748 int *presst = odr_intdup(assoc->encode, 0);
2749 /* Call bend_present if defined */
2750 if (assoc->init->bend_present)
2752 bend_present_rr *bprr = (bend_present_rr *)
2753 nmem_malloc (reqb->request_mem, sizeof(*bprr));
2754 bprr->setname = req->resultSetName;
2756 bprr->number = *toget;
2757 bprr->format = req->preferredRecordSyntax;
2759 bprr->referenceId = req->referenceId;
2760 bprr->stream = assoc->encode;
2761 bprr->print = assoc->print;
2762 bprr->request = reqb;
2763 bprr->association = assoc;
2765 bprr->errstring = NULL;
2766 (*assoc->init->bend_present)(assoc->backend, bprr);
2772 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2773 *resp->presentStatus = Z_PresentStatus_failure;
2778 resp->records = pack_records(
2779 assoc, req->resultSetName, 1,
2780 toget, compp, next, presst, req->referenceId,
2781 req->preferredRecordSyntax, NULL);
2784 resp->numberOfRecordsReturned = toget;
2785 returnedrecs = *toget;
2786 resp->presentStatus = presst;
2790 if (*resp->resultCount)
2792 resp->numberOfRecordsReturned = nulint;
2793 resp->presentStatus = 0;
2795 resp->nextResultSetPosition = next;
2796 resp->searchStatus = sr;
2797 resp->resultSetStatus = 0;
2798 if (bsrt->estimated_hit_count)
2800 resp->resultSetStatus = odr_intdup(assoc->encode,
2801 Z_SearchResponse_estimate);
2803 else if (bsrt->partial_resultset)
2805 resp->resultSetStatus = odr_intdup(assoc->encode,
2806 Z_SearchResponse_subset);
2809 resp->additionalSearchInfo = bsrt->search_info;
2814 WRBUF wr = wrbuf_alloc();
2816 for (i = 0 ; i < req->num_databaseNames; i++){
2818 wrbuf_printf(wr, "+");
2819 wrbuf_printf(wr, req->databaseNames[i]);
2821 wrbuf_printf(wr, " ");
2824 wrbuf_printf(wr, "ERROR %d", bsrt->errcode);
2826 wrbuf_printf(wr, "OK %d", bsrt->hits);
2827 wrbuf_printf(wr, " %s 1+%d ",
2828 req->resultSetName, returnedrecs);
2829 yaz_query_to_wrbuf(wr, req->query);
2831 yaz_log(log_request, "Search %s", wrbuf_cstr(wr));
2838 * Maybe we got a little over-friendly when we designed bend_fetch to
2839 * get only one record at a time. Some backends can optimise multiple-record
2840 * fetches, and at any rate, there is some overhead involved in
2841 * all that selecting and hopping around. Problem is, of course, that the
2842 * frontend can't know ahead of time how many records it'll need to
2843 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
2844 * is downright lousy as a bulk data transfer protocol.
2846 * To start with, we'll do the fetching of records from the backend
2847 * in one operation: To save some trips in and out of the event-handler,
2848 * and to simplify the interface to pack_records. At any rate, asynch
2849 * operation is more fun in operations that have an unpredictable execution
2850 * speed - which is normally more true for search than for present.
2852 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
2855 Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
2857 Z_PresentResponse *resp;
2861 const char *errstring = 0;
2863 yaz_log(log_requestdetail, "Got PresentRequest.");
2865 resp = (Z_PresentResponse *)odr_malloc (assoc->encode, sizeof(*resp));
2867 resp->presentStatus = odr_intdup(assoc->encode, 0);
2868 if (assoc->init->bend_present)
2870 bend_present_rr *bprr = (bend_present_rr *)
2871 nmem_malloc (reqb->request_mem, sizeof(*bprr));
2872 bprr->setname = req->resultSetId;
2873 bprr->start = *req->resultSetStartPoint;
2874 bprr->number = *req->numberOfRecordsRequested;
2875 bprr->format = req->preferredRecordSyntax;
2876 bprr->comp = req->recordComposition;
2877 bprr->referenceId = req->referenceId;
2878 bprr->stream = assoc->encode;
2879 bprr->print = assoc->print;
2880 bprr->request = reqb;
2881 bprr->association = assoc;
2883 bprr->errstring = NULL;
2884 (*assoc->init->bend_present)(assoc->backend, bprr);
2887 return 0; /* should not happen */
2890 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2891 *resp->presentStatus = Z_PresentStatus_failure;
2892 errcode = bprr->errcode;
2893 errstring = bprr->errstring;
2896 apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2897 next = odr_intdup(assoc->encode, 0);
2898 num = odr_intdup(assoc->encode, 0);
2900 apdu->which = Z_APDU_presentResponse;
2901 apdu->u.presentResponse = resp;
2902 resp->referenceId = req->referenceId;
2903 resp->otherInfo = 0;
2907 *num = *req->numberOfRecordsRequested;
2909 pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
2910 num, req->recordComposition, next,
2911 resp->presentStatus,
2912 req->referenceId, req->preferredRecordSyntax,
2917 WRBUF wr = wrbuf_alloc();
2918 wrbuf_printf(wr, "Present ");
2920 if (*resp->presentStatus == Z_PresentStatus_failure)
2921 wrbuf_printf(wr, "ERROR %d ", errcode);
2922 else if (*resp->presentStatus == Z_PresentStatus_success)
2923 wrbuf_printf(wr, "OK - ");
2925 wrbuf_printf(wr, "Partial %d - ", *resp->presentStatus);
2927 wrbuf_printf(wr, " %s %d+%d ",
2928 req->resultSetId, *req->resultSetStartPoint,
2929 *req->numberOfRecordsRequested);
2930 yaz_log(log_request, "%s", wrbuf_cstr(wr) );
2935 resp->numberOfRecordsReturned = num;
2936 resp->nextResultSetPosition = next;
2942 * Scan was implemented rather in a hurry, and with support for only the basic
2943 * elements of the service in the backend API. Suggestions are welcome.
2945 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
2947 Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
2948 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2949 Z_ScanResponse *res = (Z_ScanResponse *)
2950 odr_malloc (assoc->encode, sizeof(*res));
2951 int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
2952 int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
2953 Z_ListEntries *ents = (Z_ListEntries *)
2954 odr_malloc (assoc->encode, sizeof(*ents));
2955 Z_DiagRecs *diagrecs_p = NULL;
2956 bend_scan_rr *bsrr = (bend_scan_rr *)
2957 odr_malloc (assoc->encode, sizeof(*bsrr));
2958 struct scan_entry *save_entries;
2960 yaz_log(log_requestdetail, "Got ScanRequest");
2962 apdu->which = Z_APDU_scanResponse;
2963 apdu->u.scanResponse = res;
2964 res->referenceId = req->referenceId;
2966 /* if step is absent, set it to 0 */
2967 res->stepSize = odr_intdup(assoc->encode, 0);
2969 *res->stepSize = *req->stepSize;
2971 res->scanStatus = scanStatus;
2972 res->numberOfEntriesReturned = numberOfEntriesReturned;
2973 res->positionOfTerm = 0;
2974 res->entries = ents;
2975 ents->num_entries = 0;
2976 ents->entries = NULL;
2977 ents->num_nonsurrogateDiagnostics = 0;
2978 ents->nonsurrogateDiagnostics = NULL;
2979 res->attributeSet = 0;
2982 if (req->databaseNames)
2985 for (i = 0; i < req->num_databaseNames; i++)
2986 yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
2988 bsrr->scanClause = 0;
2990 bsrr->errstring = 0;
2991 bsrr->num_bases = req->num_databaseNames;
2992 bsrr->basenames = req->databaseNames;
2993 bsrr->num_entries = *req->numberOfTermsRequested;
2994 bsrr->term = req->termListAndStartPoint;
2995 bsrr->referenceId = req->referenceId;
2996 bsrr->stream = assoc->encode;
2997 bsrr->print = assoc->print;
2998 bsrr->step_size = res->stepSize;
3000 /* For YAZ 2.0 and earlier it was the backend handler that
3001 initialized entries (member display_term did not exist)
3002 YAZ 2.0 and later sets 'entries' and initialize all members
3003 including 'display_term'. If YAZ 2.0 or later sees that
3004 entries was modified - we assume that it is an old handler and
3005 that 'display_term' is _not_ set.
3007 if (bsrr->num_entries > 0)
3010 bsrr->entries = odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
3012 for (i = 0; i<bsrr->num_entries; i++)
3014 bsrr->entries[i].term = 0;
3015 bsrr->entries[i].occurrences = 0;
3016 bsrr->entries[i].errcode = 0;
3017 bsrr->entries[i].errstring = 0;
3018 bsrr->entries[i].display_term = 0;
3021 save_entries = bsrr->entries; /* save it so we can compare later */
3023 bsrr->attributeset = req->attributeSet;
3024 log_scan_term_level (log_requestdetail, req->termListAndStartPoint,
3025 bsrr->attributeset);
3026 bsrr->term_position = req->preferredPositionInResponse ?
3027 *req->preferredPositionInResponse : 1;
3029 ((int (*)(void *, bend_scan_rr *))
3030 (*assoc->init->bend_scan))(assoc->backend, bsrr);
3033 diagrecs_p = zget_DiagRecs(assoc->encode,
3034 bsrr->errcode, bsrr->errstring);
3038 Z_Entry **tab = (Z_Entry **)
3039 odr_malloc (assoc->encode, sizeof(*tab) * bsrr->num_entries);
3041 if (bsrr->status == BEND_SCAN_PARTIAL)
3042 *scanStatus = Z_Scan_partial_5;
3044 *scanStatus = Z_Scan_success;
3045 ents->entries = tab;
3046 ents->num_entries = bsrr->num_entries;
3047 res->numberOfEntriesReturned = &ents->num_entries;
3048 res->positionOfTerm = &bsrr->term_position;
3049 for (i = 0; i < bsrr->num_entries; i++)
3055 tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
3056 if (bsrr->entries[i].occurrences >= 0)
3058 e->which = Z_Entry_termInfo;
3059 e->u.termInfo = t = (Z_TermInfo *)
3060 odr_malloc(assoc->encode, sizeof(*t));
3061 t->suggestedAttributes = 0;
3063 if (save_entries == bsrr->entries &&
3064 bsrr->entries[i].display_term)
3066 /* the entries was _not_ set by the handler. So it's
3067 safe to test for new member display_term. It is
3070 t->displayTerm = odr_strdup(assoc->encode,
3071 bsrr->entries[i].display_term);
3073 t->alternativeTerm = 0;
3074 t->byAttributes = 0;
3075 t->otherTermInfo = 0;
3076 t->globalOccurrences = &bsrr->entries[i].occurrences;
3077 t->term = (Z_Term *)
3078 odr_malloc(assoc->encode, sizeof(*t->term));
3079 t->term->which = Z_Term_general;
3080 t->term->u.general = o =
3081 (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
3082 o->buf = (unsigned char *)
3083 odr_malloc(assoc->encode, o->len = o->size =
3084 strlen(bsrr->entries[i].term));
3085 memcpy(o->buf, bsrr->entries[i].term, o->len);
3086 yaz_log(YLOG_DEBUG, " term #%d: '%s' (%d)", i,
3087 bsrr->entries[i].term, bsrr->entries[i].occurrences);
3091 Z_DiagRecs *drecs = zget_DiagRecs(assoc->encode,
3092 bsrr->entries[i].errcode,
3093 bsrr->entries[i].errstring);
3094 assert (drecs->num_diagRecs == 1);
3095 e->which = Z_Entry_surrogateDiagnostic;
3096 assert (drecs->diagRecs[0]);
3097 e->u.surrogateDiagnostic = drecs->diagRecs[0];
3103 ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
3104 ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
3109 WRBUF wr = wrbuf_alloc();
3110 wrbuf_printf(wr, "Scan ");
3111 for (i = 0 ; i < req->num_databaseNames; i++){
3113 wrbuf_printf(wr, "+");
3114 wrbuf_printf(wr, req->databaseNames[i]);
3116 wrbuf_printf(wr, " ");
3119 wr_diag(wr, bsrr->errcode, bsrr->errstring);
3120 wrbuf_printf(wr, " ");
3123 wrbuf_printf(wr, "OK ");
3124 /* else if (*res->scanStatus == Z_Scan_success) */
3125 /* wrbuf_printf(wr, "OK "); */
3127 /* wrbuf_printf(wr, "Partial "); */
3129 if (*res->numberOfEntriesReturned)
3130 wrbuf_printf(wr, "%d - ", *res->numberOfEntriesReturned);
3132 wrbuf_printf(wr, "0 - ");
3134 wrbuf_printf(wr, "%d+%d+%d ",
3135 (req->preferredPositionInResponse ?
3136 *req->preferredPositionInResponse : 1),
3137 *req->numberOfTermsRequested,
3138 (res->stepSize ? *res->stepSize : 1));
3140 yaz_scan_to_wrbuf(wr, req->termListAndStartPoint,
3141 bsrr->attributeset);
3142 yaz_log(log_request, "%s", wrbuf_cstr(wr) );
3148 static Z_APDU *process_sortRequest(association *assoc, request *reqb,
3152 Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
3153 Z_SortResponse *res = (Z_SortResponse *)
3154 odr_malloc (assoc->encode, sizeof(*res));
3155 bend_sort_rr *bsrr = (bend_sort_rr *)
3156 odr_malloc (assoc->encode, sizeof(*bsrr));
3158 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
3160 yaz_log(log_requestdetail, "Got SortRequest.");
3162 bsrr->num_input_setnames = req->num_inputResultSetNames;
3163 for (i=0;i<req->num_inputResultSetNames;i++)
3164 yaz_log(log_requestdetail, "Input resultset: '%s'",
3165 req->inputResultSetNames[i]);
3166 bsrr->input_setnames = req->inputResultSetNames;
3167 bsrr->referenceId = req->referenceId;
3168 bsrr->output_setname = req->sortedResultSetName;
3169 yaz_log(log_requestdetail, "Output resultset: '%s'",
3170 req->sortedResultSetName);
3171 bsrr->sort_sequence = req->sortSequence;
3172 /*FIXME - dump those sequences too */
3173 bsrr->stream = assoc->encode;
3174 bsrr->print = assoc->print;
3176 bsrr->sort_status = Z_SortResponse_failure;
3178 bsrr->errstring = 0;
3180 (*assoc->init->bend_sort)(assoc->backend, bsrr);
3182 res->referenceId = bsrr->referenceId;
3183 res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
3184 res->resultSetStatus = 0;
3187 Z_DiagRecs *dr = zget_DiagRecs(assoc->encode,
3188 bsrr->errcode, bsrr->errstring);
3189 res->diagnostics = dr->diagRecs;
3190 res->num_diagnostics = dr->num_diagRecs;
3194 res->num_diagnostics = 0;
3195 res->diagnostics = 0;
3197 res->resultCount = 0;
3200 apdu->which = Z_APDU_sortResponse;
3201 apdu->u.sortResponse = res;
3204 WRBUF wr = wrbuf_alloc();
3205 wrbuf_printf(wr, "Sort ");
3207 wrbuf_printf(wr, " ERROR %d", bsrr->errcode);
3209 wrbuf_printf(wr, "OK -");
3210 wrbuf_printf(wr, " (");
3211 for (i = 0; i<req->num_inputResultSetNames; i++)
3214 wrbuf_printf(wr, "+");
3215 wrbuf_printf(wr, req->inputResultSetNames[i]);
3217 wrbuf_printf(wr, ")->%s ",req->sortedResultSetName);
3219 yaz_log(log_request, "%s", wrbuf_cstr(wr) );
3225 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
3229 Z_DeleteResultSetRequest *req =
3230 reqb->apdu_request->u.deleteResultSetRequest;
3231 Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
3232 odr_malloc (assoc->encode, sizeof(*res));
3233 bend_delete_rr *bdrr = (bend_delete_rr *)
3234 odr_malloc (assoc->encode, sizeof(*bdrr));
3235 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
3237 yaz_log(log_requestdetail, "Got DeleteRequest.");
3239 bdrr->num_setnames = req->num_resultSetList;
3240 bdrr->setnames = req->resultSetList;
3241 for (i = 0; i<req->num_resultSetList; i++)
3242 yaz_log(log_requestdetail, "resultset: '%s'",
3243 req->resultSetList[i]);
3244 bdrr->stream = assoc->encode;
3245 bdrr->print = assoc->print;
3246 bdrr->function = *req->deleteFunction;
3247 bdrr->referenceId = req->referenceId;
3249 if (bdrr->num_setnames > 0)
3251 bdrr->statuses = (int*)
3252 odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
3253 bdrr->num_setnames);
3254 for (i = 0; i < bdrr->num_setnames; i++)
3255 bdrr->statuses[i] = 0;
3257 (*assoc->init->bend_delete)(assoc->backend, bdrr);
3259 res->referenceId = req->referenceId;
3261 res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
3263 res->deleteListStatuses = 0;
3264 if (bdrr->num_setnames > 0)
3267 res->deleteListStatuses = (Z_ListStatuses *)
3268 odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
3269 res->deleteListStatuses->num = bdrr->num_setnames;
3270 res->deleteListStatuses->elements =
3272 odr_malloc (assoc->encode,
3273 sizeof(*res->deleteListStatuses->elements) *
3274 bdrr->num_setnames);
3275 for (i = 0; i<bdrr->num_setnames; i++)
3277 res->deleteListStatuses->elements[i] =
3279 odr_malloc (assoc->encode,
3280 sizeof(**res->deleteListStatuses->elements));
3281 res->deleteListStatuses->elements[i]->status = bdrr->statuses+i;
3282 res->deleteListStatuses->elements[i]->id =
3283 odr_strdup (assoc->encode, bdrr->setnames[i]);
3286 res->numberNotDeleted = 0;
3287 res->bulkStatuses = 0;
3288 res->deleteMessage = 0;
3291 apdu->which = Z_APDU_deleteResultSetResponse;
3292 apdu->u.deleteResultSetResponse = res;
3295 WRBUF wr = wrbuf_alloc();
3296 wrbuf_printf(wr, "Delete ");
3297 if (bdrr->delete_status)
3298 wrbuf_printf(wr, "ERROR %d", bdrr->delete_status);
3300 wrbuf_printf(wr, "OK -");
3301 for (i = 0; i<req->num_resultSetList; i++)
3302 wrbuf_printf(wr, " %s ", req->resultSetList[i]);
3303 yaz_log(log_request, "%s", wrbuf_cstr(wr) );
3309 static void process_close(association *assoc, request *reqb)
3311 Z_Close *req = reqb->apdu_request->u.close;
3312 static char *reasons[] =
3319 "securityViolation",
3326 yaz_log(log_requestdetail, "Got Close, reason %s, message %s",
3327 reasons[*req->closeReason], req->diagnosticInformation ?
3328 req->diagnosticInformation : "NULL");
3329 if (assoc->version < 3) /* to make do_force respond with close */
3331 do_close_req(assoc, Z_Close_finished,
3332 "Association terminated by client", reqb);
3333 yaz_log(log_request,"Close OK");
3336 void save_referenceId (request *reqb, Z_ReferenceId *refid)
3340 reqb->len_refid = refid->len;
3341 reqb->refid = (char *)nmem_malloc (reqb->request_mem, refid->len);
3342 memcpy (reqb->refid, refid->buf, refid->len);
3346 reqb->len_refid = 0;
3351 void bend_request_send (bend_association a, bend_request req, Z_APDU *res)
3353 process_z_response (a, req, res);
3356 bend_request bend_request_mk (bend_association a)
3358 request *nreq = request_get (&a->outgoing);
3359 nreq->request_mem = nmem_create ();
3363 Z_ReferenceId *bend_request_getid (ODR odr, bend_request req)
3368 id = (Odr_oct *)odr_malloc (odr, sizeof(*odr));
3369 id->buf = (unsigned char *)odr_malloc (odr, req->len_refid);
3370 id->len = id->size = req->len_refid;
3371 memcpy (id->buf, req->refid, req->len_refid);
3375 void bend_request_destroy (bend_request *req)
3377 nmem_destroy((*req)->request_mem);
3378 request_release(*req);
3382 int bend_backend_respond (bend_association a, bend_request req)
3386 r = process_z_request (a, req, &msg);
3388 yaz_log (YLOG_WARN, "%s", msg);
3392 void bend_request_setdata(bend_request r, void *p)
3397 void *bend_request_getdata(bend_request r)
3399 return r->clientData;
3402 static Z_APDU *process_segmentRequest (association *assoc, request *reqb)
3404 bend_segment_rr req;
3406 req.segment = reqb->apdu_request->u.segmentRequest;
3407 req.stream = assoc->encode;
3408 req.decode = assoc->decode;
3409 req.print = assoc->print;
3410 req.association = assoc;
3412 (*assoc->init->bend_segment)(assoc->backend, &req);
3417 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd)
3419 bend_esrequest_rr esrequest;
3420 const char *ext_name = "unknown";
3422 Z_ExtendedServicesRequest *req =
3423 reqb->apdu_request->u.extendedServicesRequest;
3424 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
3426 Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
3428 esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
3429 esrequest.stream = assoc->encode;
3430 esrequest.decode = assoc->decode;
3431 esrequest.print = assoc->print;
3432 esrequest.errcode = 0;
3433 esrequest.errstring = NULL;
3434 esrequest.request = reqb;
3435 esrequest.association = assoc;
3436 esrequest.taskPackage = 0;
3437 esrequest.referenceId = req->referenceId;
3440 if (esrequest.esr && esrequest.esr->taskSpecificParameters)
3442 switch(esrequest.esr->taskSpecificParameters->which)
3444 case Z_External_itemOrder:
3445 ext_name = "ItemOrder"; break;
3446 case Z_External_update:
3447 ext_name = "Update"; break;
3448 case Z_External_update0:
3449 ext_name = "Update0"; break;
3450 case Z_External_ESAdmin:
3451 ext_name = "Admin"; break;
3456 (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
3458 /* If the response is being delayed, return NULL */
3459 if (esrequest.request == NULL)
3462 resp->referenceId = req->referenceId;
3464 if (esrequest.errcode == -1)
3466 /* Backend service indicates request will be processed */
3467 yaz_log(log_request, "Extended Service: %s (accepted)", ext_name);
3468 *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
3470 else if (esrequest.errcode == 0)
3472 /* Backend service indicates request will be processed */
3473 yaz_log(log_request, "Extended Service: %s (done)", ext_name);
3474 *resp->operationStatus = Z_ExtendedServicesResponse_done;
3478 Z_DiagRecs *diagRecs =
3479 zget_DiagRecs(assoc->encode, esrequest.errcode,
3480 esrequest.errstring);
3481 /* Backend indicates error, request will not be processed */
3482 yaz_log(log_request, "Extended Service: %s (failed)", ext_name);
3483 *resp->operationStatus = Z_ExtendedServicesResponse_failure;
3484 resp->num_diagnostics = diagRecs->num_diagRecs;
3485 resp->diagnostics = diagRecs->diagRecs;
3488 WRBUF wr = wrbuf_alloc();
3489 wrbuf_diags(wr, resp->num_diagnostics, resp->diagnostics);
3490 yaz_log(log_request, "EsRequest %s", wrbuf_cstr(wr) );
3495 /* Do something with the members of bend_extendedservice */
3496 if (esrequest.taskPackage)
3498 resp->taskPackage = z_ext_record_oid(
3499 assoc->encode, yaz_oid_recsyn_extended,
3500 (const char *) esrequest.taskPackage, -1
3503 yaz_log(YLOG_DEBUG,"Send the result apdu");
3507 int bend_assoc_is_alive(bend_association assoc)
3509 if (assoc->state == ASSOC_DEAD)
3510 return 0; /* already marked as dead. Don't check I/O chan anymore */
3512 return iochan_is_alive(assoc->client_chan);
3519 * indent-tabs-mode: nil
3521 * vim: shiftwidth=4 tabstop=8 expandtab