1 /* This file is part of the YAZ toolkit.
2 * Copyright (C) 1995-2010 Index Data
3 * See the file LICENSE for details.
7 * \brief Implements GFS session logic.
9 * Frontend server logic.
11 * This code receives incoming APDUs, and handles client requests by means
14 * Some of the code is getting quite involved, compared to simpler servers -
15 * primarily because it is asynchronous both in the communication with
16 * the user and the backend. We think the complexity will pay off in
17 * the form of greater flexibility when more asynchronous facilities
20 * Memory management has become somewhat involved. In the simple case, where
21 * only one PDU is pending at a time, it will simply reuse the same memory,
22 * once it has found its working size. When we enable multiple concurrent
23 * operations, perhaps even with multiple parallel calls to the backend, it
24 * will maintain a pool of buffers for encoding and decoding, trying to
25 * minimize memory allocation/deallocation during normal operation.
35 #include <sys/types.h>
43 #define S_ISREG(x) (x & _S_IFREG)
52 #include <libxml/parser.h>
53 #include <libxml/tree.h>
56 #include <yaz/yconfig.h>
57 #include <yaz/xmalloc.h>
58 #include <yaz/comstack.h>
62 #include <yaz/proto.h>
63 #include <yaz/oid_db.h>
65 #include <yaz/logrpn.h>
66 #include <yaz/querytowrbuf.h>
67 #include <yaz/statserv.h>
68 #include <yaz/diagbib1.h>
69 #include <yaz/charneg.h>
70 #include <yaz/otherinfo.h>
71 #include <yaz/yaz-util.h>
72 #include <yaz/pquery.h>
73 #include <yaz/oid_db.h>
76 #include <yaz/backend.h>
77 #include <yaz/yaz-ccl.h>
79 static void process_gdu_request(association *assoc, request *req);
80 static int process_z_request(association *assoc, request *req, char **msg);
81 static int process_gdu_response(association *assoc, request *req, Z_GDU *res);
82 static int process_z_response(association *assoc, request *req, Z_APDU *res);
83 static Z_APDU *process_initRequest(association *assoc, request *reqb);
84 static Z_External *init_diagnostics(ODR odr, int errcode,
85 const char *errstring);
86 static Z_APDU *process_searchRequest(association *assoc, request *reqb);
87 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
88 bend_search_rr *bsrr);
89 static Z_APDU *process_presentRequest(association *assoc, request *reqb);
90 static Z_APDU *process_scanRequest(association *assoc, request *reqb);
91 static Z_APDU *process_sortRequest(association *assoc, request *reqb);
92 static void process_close(association *assoc, request *reqb);
93 static Z_APDU *process_deleteRequest(association *assoc, request *reqb);
94 static Z_APDU *process_segmentRequest(association *assoc, request *reqb);
95 static Z_APDU *process_ESRequest(association *assoc, request *reqb);
97 /* dynamic logging levels */
98 static int logbits_set = 0;
99 static int log_session = 0; /* one-line logs for session */
100 static int log_sessiondetail = 0; /* more detailed stuff */
101 static int log_request = 0; /* one-line logs for requests */
102 static int log_requestdetail = 0; /* more detailed stuff */
104 /** get_logbits sets global loglevel bits */
105 static void get_logbits(void)
106 { /* needs to be called after parsing cmd-line args that can set loglevels!*/
110 log_session = yaz_log_module_level("session");
111 log_sessiondetail = yaz_log_module_level("sessiondetail");
112 log_request = yaz_log_module_level("request");
113 log_requestdetail = yaz_log_module_level("requestdetail");
117 static void wr_diag(WRBUF w, int error, const char *addinfo)
119 wrbuf_printf(w, "ERROR %d+", error);
120 wrbuf_puts_replace_char(w, diagbib1_str(error), ' ', '_');
124 wrbuf_puts_replace_char(w, addinfo, ' ', '_');
130 * Create and initialize a new association-handle.
131 * channel : iochannel for the current line.
132 * link : communications channel.
133 * Returns: 0 or a new association handle.
135 association *create_association(IOCHAN channel, COMSTACK link,
136 const char *apdufile)
142 if (!(anew = (association *)xmalloc(sizeof(*anew))))
146 anew->last_control = 0;
147 anew->client_chan = channel;
148 anew->client_link = link;
149 anew->cs_get_mask = 0;
150 anew->cs_put_mask = 0;
151 anew->cs_accept_mask = 0;
152 if (!(anew->decode = odr_createmem(ODR_DECODE)) ||
153 !(anew->encode = odr_createmem(ODR_ENCODE)))
155 if (apdufile && *apdufile)
159 if (!(anew->print = odr_createmem(ODR_PRINT)))
161 if (*apdufile == '@')
163 odr_setprint(anew->print, yaz_log_file());
165 else if (*apdufile != '-')
168 sprintf(filename, "%.200s.%ld", apdufile, (long)getpid());
169 if (!(f = fopen(filename, "w")))
171 yaz_log(YLOG_WARN|YLOG_ERRNO, "%s", filename);
174 setvbuf(f, 0, _IONBF, 0);
175 odr_setprint(anew->print, f);
180 anew->input_buffer = 0;
181 anew->input_buffer_len = 0;
183 anew->state = ASSOC_NEW;
184 request_initq(&anew->incoming);
185 request_initq(&anew->outgoing);
186 anew->proto = cs_getproto(link);
192 * Free association and release resources.
194 void destroy_association(association *h)
196 statserv_options_block *cb = statserv_getcontrol();
200 odr_destroy(h->decode);
201 odr_destroy(h->encode);
203 odr_destroy(h->print);
205 xfree(h->input_buffer);
207 (*cb->bend_close)(h->backend);
208 while ((req = request_deq(&h->incoming)))
209 request_release(req);
210 while ((req = request_deq(&h->outgoing)))
211 request_release(req);
212 request_delq(&h->incoming);
213 request_delq(&h->outgoing);
215 xmalloc_trav("session closed");
216 if (cb && cb->one_shot)
222 static void do_close_req(association *a, int reason, char *message,
225 Z_APDU *apdu = zget_APDU(a->encode, Z_APDU_close);
226 Z_Close *cls = apdu->u.close;
228 /* Purge request queue */
229 while (request_deq(&a->incoming));
230 while (request_deq(&a->outgoing));
233 yaz_log(log_requestdetail, "Sending Close PDU, reason=%d, message=%s",
234 reason, message ? message : "none");
235 *cls->closeReason = reason;
236 cls->diagnosticInformation = message;
237 process_z_response(a, req, apdu);
238 iochan_settimeout(a->client_chan, 20);
242 request_release(req);
243 yaz_log(log_requestdetail, "v2 client. No Close PDU");
244 iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
247 a->state = ASSOC_DEAD;
250 static void do_close(association *a, int reason, char *message)
252 request *req = request_get(&a->outgoing);
253 do_close_req(a, reason, message, req);
257 int ir_read(IOCHAN h, int event)
259 association *assoc = (association *)iochan_getdata(h);
260 COMSTACK conn = assoc->client_link;
263 if ((assoc->cs_put_mask & EVENT_INPUT) == 0 && (event & assoc->cs_get_mask))
265 yaz_log(YLOG_DEBUG, "ir_session (input)");
266 /* We aren't speaking to this fellow */
267 if (assoc->state == ASSOC_DEAD)
269 yaz_log(log_sessiondetail, "Connection closed - end of session");
271 destroy_association(assoc);
275 assoc->cs_get_mask = EVENT_INPUT;
279 int res = cs_get(conn, &assoc->input_buffer,
280 &assoc->input_buffer_len);
281 if (res < 0 && cs_errno(conn) == CSBUFSIZE)
283 yaz_log(log_session, "Connection error: %s res=%d",
284 cs_errmsg(cs_errno(conn)), res);
285 req = request_get(&assoc->incoming); /* get a new request */
286 do_close_req(assoc, Z_Close_protocolError,
287 "Incoming package too large", req);
292 yaz_log(log_session, "Connection closed by client");
293 assoc->state = ASSOC_DEAD;
296 else if (res == 1) /* incomplete read - wait for more */
298 if (conn->io_pending & CS_WANT_WRITE)
299 assoc->cs_get_mask |= EVENT_OUTPUT;
300 iochan_setflag(h, assoc->cs_get_mask);
303 /* we got a complete PDU. Let's decode it */
304 yaz_log(YLOG_DEBUG, "Got PDU, %d bytes: lead=%02X %02X %02X", res,
305 assoc->input_buffer[0] & 0xff,
306 assoc->input_buffer[1] & 0xff,
307 assoc->input_buffer[2] & 0xff);
308 req = request_get(&assoc->incoming); /* get a new request */
309 odr_reset(assoc->decode);
310 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
311 if (!z_GDU(assoc->decode, &req->gdu_request, 0, 0))
313 yaz_log(YLOG_WARN, "ODR error on incoming PDU: %s [element %s] "
315 odr_errmsg(odr_geterror(assoc->decode)),
316 odr_getelement(assoc->decode),
317 (long) odr_offset(assoc->decode));
318 if (assoc->decode->error != OHTTP)
320 yaz_log(YLOG_WARN, "PDU dump:");
321 odr_dumpBER(yaz_log_file(), assoc->input_buffer, res);
322 request_release(req);
323 do_close(assoc, Z_Close_protocolError, "Malformed package");
327 Z_GDU *p = z_get_HTTP_Response(assoc->encode, 400);
328 assoc->state = ASSOC_DEAD;
329 process_gdu_response(assoc, req, p);
333 req->request_mem = odr_extract_mem(assoc->decode);
336 if (!z_GDU(assoc->print, &req->gdu_request, 0, 0))
337 yaz_log(YLOG_WARN, "ODR print error: %s",
338 odr_errmsg(odr_geterror(assoc->print)));
339 odr_reset(assoc->print);
341 request_enq(&assoc->incoming, req);
343 while (cs_more(conn));
349 * This is where PDUs from the client are read and the further
350 * processing is initiated. Flow of control moves down through the
351 * various process_* functions below, until the encoded result comes back up
352 * to the output handler in here.
354 * h : the I/O channel that has an outstanding event.
355 * event : the current outstanding event.
357 void ir_session(IOCHAN h, int event)
360 association *assoc = (association *)iochan_getdata(h);
361 COMSTACK conn = assoc->client_link;
364 assert(h && conn && assoc);
365 if (event == EVENT_TIMEOUT)
367 if (assoc->state != ASSOC_UP)
369 yaz_log(log_session, "Timeout. Closing connection");
370 /* do we need to lod this at all */
372 destroy_association(assoc);
377 yaz_log(log_sessiondetail, "Timeout. Sending Z39.50 Close");
378 do_close(assoc, Z_Close_lackOfActivity, 0);
382 if (event & assoc->cs_accept_mask)
384 if (!cs_accept(conn))
386 yaz_log(YLOG_WARN, "accept failed");
387 destroy_association(assoc);
391 iochan_clearflag(h, EVENT_OUTPUT);
392 if (conn->io_pending)
393 { /* cs_accept didn't complete */
394 assoc->cs_accept_mask =
395 ((conn->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
396 ((conn->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
398 iochan_setflag(h, assoc->cs_accept_mask);
401 { /* cs_accept completed. Prepare for reading (cs_get) */
402 assoc->cs_accept_mask = 0;
403 assoc->cs_get_mask = EVENT_INPUT;
404 iochan_setflag(h, assoc->cs_get_mask);
408 if (event & assoc->cs_get_mask) /* input */
410 if (!ir_read(h, event))
412 req = request_head(&assoc->incoming);
413 if (req->state == REQUEST_IDLE)
415 request_deq(&assoc->incoming);
416 process_gdu_request(assoc, req);
419 if (event & assoc->cs_put_mask)
421 request *req = request_head(&assoc->outgoing);
423 assoc->cs_put_mask = 0;
424 yaz_log(YLOG_DEBUG, "ir_session (output)");
425 req->state = REQUEST_PENDING;
426 switch (res = cs_put(conn, req->response, req->len_response))
429 yaz_log(log_sessiondetail, "Connection closed by client");
431 destroy_association(assoc);
434 case 0: /* all sent - release the request structure */
435 yaz_log(YLOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
437 yaz_log(YLOG_DEBUG, "HTTP out:\n%.*s", req->len_response,
440 nmem_destroy(req->request_mem);
441 request_deq(&assoc->outgoing);
442 request_release(req);
443 if (!request_head(&assoc->outgoing))
444 { /* restore mask for cs_get operation ... */
445 iochan_clearflag(h, EVENT_OUTPUT|EVENT_INPUT);
446 iochan_setflag(h, assoc->cs_get_mask);
447 if (assoc->state == ASSOC_DEAD)
448 iochan_setevent(assoc->client_chan, EVENT_TIMEOUT);
452 assoc->cs_put_mask = EVENT_OUTPUT;
456 if (conn->io_pending & CS_WANT_WRITE)
457 assoc->cs_put_mask |= EVENT_OUTPUT;
458 if (conn->io_pending & CS_WANT_READ)
459 assoc->cs_put_mask |= EVENT_INPUT;
460 iochan_setflag(h, assoc->cs_put_mask);
463 if (event & EVENT_EXCEPT)
465 yaz_log(YLOG_WARN, "ir_session (exception)");
467 destroy_association(assoc);
472 static int process_z_request(association *assoc, request *req, char **msg);
475 static void assoc_init_reset(association *assoc)
478 assoc->init = (bend_initrequest *) xmalloc(sizeof(*assoc->init));
480 assoc->init->stream = assoc->encode;
481 assoc->init->print = assoc->print;
482 assoc->init->auth = 0;
483 assoc->init->referenceId = 0;
484 assoc->init->implementation_version = 0;
485 assoc->init->implementation_id = 0;
486 assoc->init->implementation_name = 0;
487 assoc->init->query_charset = 0;
488 assoc->init->records_in_same_charset = 0;
489 assoc->init->bend_sort = NULL;
490 assoc->init->bend_search = NULL;
491 assoc->init->bend_present = NULL;
492 assoc->init->bend_esrequest = NULL;
493 assoc->init->bend_delete = NULL;
494 assoc->init->bend_scan = NULL;
495 assoc->init->bend_segment = NULL;
496 assoc->init->bend_fetch = NULL;
497 assoc->init->bend_explain = NULL;
498 assoc->init->bend_srw_scan = NULL;
499 assoc->init->bend_srw_update = NULL;
500 assoc->init->named_result_sets = 0;
502 assoc->init->charneg_request = NULL;
503 assoc->init->charneg_response = NULL;
505 assoc->init->decode = assoc->decode;
506 assoc->init->peer_name =
507 odr_strdup(assoc->encode, cs_addrstr(assoc->client_link));
509 yaz_log(log_requestdetail, "peer %s", assoc->init->peer_name);
512 static int srw_bend_init(association *assoc, Z_SRW_diagnostic **d, int *num, Z_SRW_PDU *sr)
514 statserv_options_block *cb = statserv_getcontrol();
517 const char *encoding = "UTF-8";
519 bend_initresult *binitres;
521 yaz_log(log_requestdetail, "srw_bend_init config=%s", cb->configname);
522 assoc_init_reset(assoc);
526 Z_IdAuthentication *auth = (Z_IdAuthentication *)
527 odr_malloc(assoc->decode, sizeof(*auth));
530 len = strlen(sr->username) + 1;
532 len += strlen(sr->password) + 2;
533 auth->which = Z_IdAuthentication_open;
534 auth->u.open = (char *) odr_malloc(assoc->decode, len);
535 strcpy(auth->u.open, sr->username);
536 if (sr->password && *sr->password)
538 strcat(auth->u.open, "/");
539 strcat(auth->u.open, sr->password);
541 assoc->init->auth = auth;
545 ce = yaz_set_proposal_charneg(assoc->decode, &encoding, 1, 0, 0, 1);
546 assoc->init->charneg_request = ce->u.charNeg3;
549 if (!(binitres = (*cb->bend_init)(assoc->init)))
551 assoc->state = ASSOC_DEAD;
552 yaz_add_srw_diagnostic(assoc->encode, d, num,
553 YAZ_SRW_AUTHENTICATION_ERROR, 0);
556 assoc->backend = binitres->handle;
557 assoc->init->auth = 0;
558 if (binitres->errcode)
560 int srw_code = yaz_diag_bib1_to_srw(binitres->errcode);
561 assoc->state = ASSOC_DEAD;
562 yaz_add_srw_diagnostic(assoc->encode, d, num, srw_code,
563 binitres->errstring);
571 static int retrieve_fetch(association *assoc, bend_fetch_rr *rr)
574 yaz_record_conv_t rc = 0;
575 const char *match_schema = 0;
576 Odr_oid *match_syntax = 0;
581 const char *input_schema = yaz_get_esn(rr->comp);
582 Odr_oid *input_syntax_raw = rr->request_format;
584 const char *backend_schema = 0;
585 Odr_oid *backend_syntax = 0;
587 r = yaz_retrieval_request(assoc->server->retrieval,
595 if (r == -1) /* error ? */
597 const char *details = yaz_retrieval_get_error(
598 assoc->server->retrieval);
600 rr->errcode = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
602 rr->errstring = odr_strdup(rr->stream, details);
605 else if (r == 1 || r == 3)
607 const char *details = input_schema;
609 YAZ_BIB1_SPECIFIED_ELEMENT_SET_NAME_NOT_VALID_FOR_SPECIFIED_;
611 rr->errstring = odr_strdup(rr->stream, details);
616 rr->errcode = YAZ_BIB1_RECORD_SYNTAX_UNSUPP;
617 if (input_syntax_raw)
619 char oidbuf[OID_STR_MAX];
620 oid_oid_to_dotstring(input_syntax_raw, oidbuf);
621 rr->errstring = odr_strdup(rr->stream, oidbuf);
627 yaz_set_esn(&rr->comp, backend_schema, odr_getmem(rr->stream));
630 rr->request_format = backend_syntax;
632 (*assoc->init->bend_fetch)(assoc->backend, rr);
633 if (rc && rr->record && rr->errcode == 0 && rr->len > 0)
634 { /* post conversion must take place .. */
635 WRBUF output_record = wrbuf_alloc();
636 int r = yaz_record_conv_record(rc, rr->record, rr->len, output_record);
639 const char *details = yaz_record_conv_get_error(rc);
640 rr->errcode = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
642 rr->errstring = odr_strdup(rr->stream, details);
646 rr->len = wrbuf_len(output_record);
647 rr->record = (char *) odr_malloc(rr->stream, rr->len);
648 memcpy(rr->record, wrbuf_buf(output_record), rr->len);
650 wrbuf_destroy(output_record);
653 rr->output_format = match_syntax;
655 rr->schema = odr_strdup(rr->stream, match_schema);
657 (*assoc->init->bend_fetch)(assoc->backend, rr);
662 static int srw_bend_fetch(association *assoc, int pos,
663 Z_SRW_searchRetrieveRequest *srw_req,
664 Z_SRW_record *record,
665 const char **addinfo)
668 ODR o = assoc->encode;
670 rr.setname = "default";
673 rr.request_format = odr_oiddup(assoc->decode, yaz_oid_recsyn_xml);
675 rr.comp = (Z_RecordComposition *)
676 odr_malloc(assoc->decode, sizeof(*rr.comp));
677 rr.comp->which = Z_RecordComp_complex;
678 rr.comp->u.complex = (Z_CompSpec *)
679 odr_malloc(assoc->decode, sizeof(Z_CompSpec));
680 rr.comp->u.complex->selectAlternativeSyntax = (bool_t *)
681 odr_malloc(assoc->encode, sizeof(bool_t));
682 *rr.comp->u.complex->selectAlternativeSyntax = 0;
683 rr.comp->u.complex->num_dbSpecific = 0;
684 rr.comp->u.complex->dbSpecific = 0;
685 rr.comp->u.complex->num_recordSyntax = 0;
686 rr.comp->u.complex->recordSyntax = 0;
688 rr.comp->u.complex->generic = (Z_Specification *)
689 odr_malloc(assoc->decode, sizeof(Z_Specification));
691 /* schema uri = recordSchema (or NULL if recordSchema is not given) */
692 rr.comp->u.complex->generic->which = Z_Schema_uri;
693 rr.comp->u.complex->generic->schema.uri = srw_req->recordSchema;
695 /* ESN = recordSchema if recordSchema is present */
696 rr.comp->u.complex->generic->elementSpec = 0;
697 if (srw_req->recordSchema)
699 rr.comp->u.complex->generic->elementSpec =
700 (Z_ElementSpec *) odr_malloc(assoc->encode, sizeof(Z_ElementSpec));
701 rr.comp->u.complex->generic->elementSpec->which =
702 Z_ElementSpec_elementSetName;
703 rr.comp->u.complex->generic->elementSpec->u.elementSetName =
704 srw_req->recordSchema;
707 rr.stream = assoc->encode;
708 rr.print = assoc->print;
716 rr.surrogate_flag = 0;
717 rr.schema = srw_req->recordSchema;
719 if (!assoc->init->bend_fetch)
722 retrieve_fetch(assoc, &rr);
724 if (rr.errcode && rr.surrogate_flag)
726 int code = yaz_diag_bib1_to_srw(rr.errcode);
727 yaz_mk_sru_surrogate(o, record, pos, code, rr.errstring);
730 else if (rr.len >= 0)
732 record->recordData_buf = rr.record;
733 record->recordData_len = rr.len;
734 record->recordPosition = odr_intdup(o, pos);
735 record->recordSchema = odr_strdup_null(
736 o, rr.schema ? rr.schema : srw_req->recordSchema);
740 *addinfo = rr.errstring;
746 static int cql2pqf(ODR odr, const char *cql, cql_transform_t ct,
747 Z_Query *query_result)
749 /* have a CQL query and CQL to PQF transform .. */
750 CQL_parser cp = cql_parser_create();
756 r = cql_parser_string(cp, cql);
759 srw_errcode = YAZ_SRW_QUERY_SYNTAX_ERROR;
764 r = cql_transform_buf(ct,
765 cql_parser_result(cp),
766 rpn_buf, sizeof(rpn_buf)-1);
768 srw_errcode = cql_transform_error(ct, &add);
772 /* Syntax & transform OK. */
773 /* Convert PQF string to Z39.50 to RPN query struct */
774 YAZ_PQF_Parser pp = yaz_pqf_create();
775 Z_RPNQuery *rpnquery = yaz_pqf_parse(pp, odr, rpn_buf);
780 int code = yaz_pqf_error(pp, &pqf_msg, &off);
781 yaz_log(YLOG_WARN, "PQF Parser Error %s (code %d)",
783 srw_errcode = YAZ_SRW_QUERY_SYNTAX_ERROR;
787 query_result->which = Z_Query_type_1;
788 query_result->u.type_1 = rpnquery;
792 cql_parser_destroy(cp);
796 static int cql2pqf_scan(ODR odr, const char *cql, cql_transform_t ct,
797 Z_AttributesPlusTerm *result)
801 int srw_error = cql2pqf(odr, cql, ct, &query);
804 if (query.which != Z_Query_type_1 && query.which != Z_Query_type_101)
805 return YAZ_SRW_QUERY_SYNTAX_ERROR; /* bad query type */
806 rpn = query.u.type_1;
807 if (!rpn->RPNStructure)
808 return YAZ_SRW_QUERY_SYNTAX_ERROR; /* must be structure */
809 if (rpn->RPNStructure->which != Z_RPNStructure_simple)
810 return YAZ_SRW_QUERY_SYNTAX_ERROR; /* must be simple */
811 if (rpn->RPNStructure->u.simple->which != Z_Operand_APT)
812 return YAZ_SRW_QUERY_SYNTAX_ERROR; /* must be be attributes + term */
813 memcpy(result, rpn->RPNStructure->u.simple->u.attributesPlusTerm,
819 static int ccl2pqf(ODR odr, const Odr_oct *ccl, CCL_bibset bibset,
820 bend_search_rr *bsrr)
823 struct ccl_rpn_node *node;
826 ccl0 = odr_strdupn(odr, (char*) ccl->buf, ccl->len);
827 if ((node = ccl_find_str(bibset, ccl0, &errcode, &pos)) == 0)
829 bsrr->errstring = (char*) ccl_err_msg(errcode);
830 return YAZ_SRW_QUERY_SYNTAX_ERROR; /* Query syntax error */
833 bsrr->query->which = Z_Query_type_1;
834 bsrr->query->u.type_1 = ccl_rpn_query(odr, node);
839 static void srw_bend_search(association *assoc, request *req,
844 Z_SRW_searchRetrieveResponse *srw_res = res->u.response;
847 Z_SRW_searchRetrieveRequest *srw_req = sr->u.request;
850 yaz_log(log_requestdetail, "Got SRW SearchRetrieveRequest");
851 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
852 if (srw_res->num_diagnostics == 0 && assoc->init)
855 rr.setname = "default";
858 rr.basenames = &srw_req->database;
862 rr.srw_setnameIdleTime = 0;
863 rr.estimated_hit_count = 0;
864 rr.partial_resultset = 0;
865 rr.query = (Z_Query *) odr_malloc(assoc->decode, sizeof(*rr.query));
866 rr.query->u.type_1 = 0;
867 rr.extra_args = sr->extra_args;
868 rr.extra_response_data = 0;
870 if (srw_req->query_type == Z_SRW_query_type_cql)
872 if (assoc->server && assoc->server->cql_transform)
874 int srw_errcode = cql2pqf(assoc->encode, srw_req->query.cql,
875 assoc->server->cql_transform,
879 yaz_add_srw_diagnostic(assoc->encode,
880 &srw_res->diagnostics,
881 &srw_res->num_diagnostics,
887 /* CQL query to backend. Wrap it - Z39.50 style */
888 ext = (Z_External *) odr_malloc(assoc->decode, sizeof(*ext));
889 ext->direct_reference = odr_getoidbystr(assoc->decode,
890 "1.2.840.10003.16.2");
891 ext->indirect_reference = 0;
893 ext->which = Z_External_CQL;
894 ext->u.cql = srw_req->query.cql;
896 rr.query->which = Z_Query_type_104;
897 rr.query->u.type_104 = ext;
900 else if (srw_req->query_type == Z_SRW_query_type_pqf)
902 Z_RPNQuery *RPNquery;
903 YAZ_PQF_Parser pqf_parser;
905 pqf_parser = yaz_pqf_create();
907 RPNquery = yaz_pqf_parse(pqf_parser, assoc->decode,
913 int code = yaz_pqf_error(pqf_parser, &pqf_msg, &off);
914 yaz_log(log_requestdetail, "Parse error %d %s near offset %ld",
915 code, pqf_msg, (long) off);
916 srw_error = YAZ_SRW_QUERY_SYNTAX_ERROR;
919 rr.query->which = Z_Query_type_1;
920 rr.query->u.type_1 = RPNquery;
922 yaz_pqf_destroy(pqf_parser);
926 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
927 &srw_res->num_diagnostics,
928 YAZ_SRW_UNSUPP_QUERY_TYPE, 0);
930 if (rr.query->u.type_1)
932 rr.stream = assoc->encode;
933 rr.decode = assoc->decode;
934 rr.print = assoc->print;
935 if ( srw_req->sort.sortKeys )
936 rr.srw_sortKeys = odr_strdup(assoc->encode,
937 srw_req->sort.sortKeys );
938 rr.association = assoc;
943 yaz_log_zquery_level(log_requestdetail,rr.query);
945 (assoc->init->bend_search)(assoc->backend, &rr);
948 if (rr.errcode == YAZ_BIB1_DATABASE_UNAVAILABLE)
954 srw_error = yaz_diag_bib1_to_srw(rr.errcode);
955 yaz_add_srw_diagnostic(assoc->encode,
956 &srw_res->diagnostics,
957 &srw_res->num_diagnostics,
958 srw_error, rr.errstring);
963 int number = srw_req->maximumRecords ? *srw_req->maximumRecords : 0;
964 int start = srw_req->startRecord ? *srw_req->startRecord : 1;
966 yaz_log(log_requestdetail, "Request to pack %d+%d out of "
968 start, number, rr.hits);
970 srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
973 srw_res->resultSetId =
974 odr_strdup(assoc->encode, rr.srw_setname );
975 srw_res->resultSetIdleTime =
976 odr_intdup(assoc->encode, *rr.srw_setnameIdleTime );
979 if (start > rr.hits || start < 1)
981 /* if hits<=0 and start=1 we don't return a diagnostic */
983 yaz_add_srw_diagnostic(
985 &srw_res->diagnostics, &srw_res->num_diagnostics,
986 YAZ_SRW_FIRST_RECORD_POSITION_OUT_OF_RANGE, 0);
992 if (start + number > rr.hits)
993 number = rr.hits - start + 1;
995 /* Call bend_present if defined */
996 if (assoc->init->bend_present)
998 bend_present_rr *bprr = (bend_present_rr*)
999 odr_malloc(assoc->decode, sizeof(*bprr));
1000 bprr->setname = "default";
1001 bprr->start = start;
1002 bprr->number = number;
1003 if (srw_req->recordSchema)
1005 bprr->comp = (Z_RecordComposition *) odr_malloc(assoc->decode,
1006 sizeof(*bprr->comp));
1007 bprr->comp->which = Z_RecordComp_simple;
1008 bprr->comp->u.simple = (Z_ElementSetNames *)
1009 odr_malloc(assoc->decode, sizeof(Z_ElementSetNames));
1010 bprr->comp->u.simple->which = Z_ElementSetNames_generic;
1011 bprr->comp->u.simple->u.generic = srw_req->recordSchema;
1017 bprr->stream = assoc->encode;
1018 bprr->referenceId = 0;
1019 bprr->print = assoc->print;
1020 bprr->association = assoc;
1022 bprr->errstring = NULL;
1023 (*assoc->init->bend_present)(assoc->backend, bprr);
1027 srw_error = yaz_diag_bib1_to_srw(bprr->errcode);
1028 yaz_add_srw_diagnostic(assoc->encode,
1029 &srw_res->diagnostics,
1030 &srw_res->num_diagnostics,
1031 srw_error, bprr->errstring);
1039 int packing = Z_SRW_recordPacking_string;
1040 if (srw_req->recordPacking)
1043 yaz_srw_str_to_pack(srw_req->recordPacking);
1045 packing = Z_SRW_recordPacking_string;
1047 srw_res->records = (Z_SRW_record *)
1048 odr_malloc(assoc->encode,
1049 number * sizeof(*srw_res->records));
1051 srw_res->extra_records = (Z_SRW_extra_record **)
1052 odr_malloc(assoc->encode,
1053 number*sizeof(*srw_res->extra_records));
1055 for (i = 0; i<number; i++)
1058 const char *addinfo = 0;
1060 srw_res->records[j].recordPacking = packing;
1061 srw_res->records[j].recordData_buf = 0;
1062 srw_res->extra_records[j] = 0;
1063 yaz_log(YLOG_DEBUG, "srw_bend_fetch %d", i+start);
1064 errcode = srw_bend_fetch(assoc, i+start, srw_req,
1065 srw_res->records + j,
1069 yaz_add_srw_diagnostic(assoc->encode,
1070 &srw_res->diagnostics,
1071 &srw_res->num_diagnostics,
1072 yaz_diag_bib1_to_srw(errcode),
1077 if (srw_res->records[j].recordData_buf)
1080 srw_res->num_records = j;
1082 srw_res->records = 0;
1085 if (rr.extra_response_data)
1087 res->extraResponseData_buf = rr.extra_response_data;
1088 res->extraResponseData_len = strlen(rr.extra_response_data);
1090 if (rr.estimated_hit_count || rr.partial_resultset)
1092 yaz_add_srw_diagnostic(
1094 &srw_res->diagnostics,
1095 &srw_res->num_diagnostics,
1096 YAZ_SRW_RESULT_SET_CREATED_WITH_VALID_PARTIAL_RESULTS_AVAILABLE,
1104 const char *querystr = "?";
1105 const char *querytype = "?";
1106 WRBUF wr = wrbuf_alloc();
1108 switch (srw_req->query_type)
1110 case Z_SRW_query_type_cql:
1112 querystr = srw_req->query.cql;
1114 case Z_SRW_query_type_pqf:
1116 querystr = srw_req->query.pqf;
1119 wrbuf_printf(wr, "SRWSearch %s ", srw_req->database);
1120 if (srw_res->num_diagnostics)
1121 wrbuf_printf(wr, "ERROR %s", srw_res->diagnostics[0].uri);
1122 else if (*http_code != 200)
1123 wrbuf_printf(wr, "ERROR info:http/%d", *http_code);
1124 else if (srw_res->numberOfRecords)
1126 wrbuf_printf(wr, "OK " ODR_INT_PRINTF,
1127 (srw_res->numberOfRecords ?
1128 *srw_res->numberOfRecords : 0));
1130 wrbuf_printf(wr, " %s " ODR_INT_PRINTF " +%d",
1131 (srw_res->resultSetId ?
1132 srw_res->resultSetId : "-"),
1133 (srw_req->startRecord ? *srw_req->startRecord : 1),
1134 srw_res->num_records);
1135 yaz_log(log_request, "%s %s: %s", wrbuf_cstr(wr), querytype, querystr);
1140 static char *srw_bend_explain_default(void *handle, bend_explain_rr *rr)
1143 xmlNodePtr ptr = (xmlNode *) rr->server_node_ptr;
1146 for (ptr = ptr->children; ptr; ptr = ptr->next)
1148 if (ptr->type != XML_ELEMENT_NODE)
1150 if (!strcmp((const char *) ptr->name, "explain"))
1153 xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
1157 ptr = xmlCopyNode(ptr, 1);
1159 xmlDocSetRootElement(doc, ptr);
1161 xmlDocDumpMemory(doc, &buf_out, &len);
1162 content = (char*) odr_malloc(rr->stream, 1+len);
1163 memcpy(content, buf_out, len);
1164 content[len] = '\0';
1168 rr->explain_buf = content;
1176 static void srw_bend_explain(association *assoc, request *req,
1178 Z_SRW_explainResponse *srw_res,
1181 Z_SRW_explainRequest *srw_req = sr->u.explain_request;
1182 yaz_log(log_requestdetail, "Got SRW ExplainRequest");
1184 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1189 rr.stream = assoc->encode;
1190 rr.decode = assoc->decode;
1191 rr.print = assoc->print;
1193 rr.database = srw_req->database;
1195 rr.server_node_ptr = assoc->server->server_node_ptr;
1197 rr.server_node_ptr = 0;
1198 rr.schema = "http://explain.z3950.org/dtd/2.0/";
1199 if (assoc->init->bend_explain)
1200 (*assoc->init->bend_explain)(assoc->backend, &rr);
1202 srw_bend_explain_default(assoc->backend, &rr);
1206 int packing = Z_SRW_recordPacking_string;
1207 if (srw_req->recordPacking)
1210 yaz_srw_str_to_pack(srw_req->recordPacking);
1212 packing = Z_SRW_recordPacking_string;
1214 srw_res->record.recordSchema = rr.schema;
1215 srw_res->record.recordPacking = packing;
1216 srw_res->record.recordData_buf = rr.explain_buf;
1217 srw_res->record.recordData_len = strlen(rr.explain_buf);
1218 srw_res->record.recordPosition = 0;
1224 static void srw_bend_scan(association *assoc, request *req,
1226 Z_SRW_scanResponse *srw_res,
1229 Z_SRW_scanRequest *srw_req = sr->u.scan_request;
1230 yaz_log(log_requestdetail, "Got SRW ScanRequest");
1233 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1234 if (srw_res->num_diagnostics == 0 && assoc->init)
1236 struct scan_entry *save_entries;
1238 bend_scan_rr *bsrr = (bend_scan_rr *)
1239 odr_malloc(assoc->encode, sizeof(*bsrr));
1240 bsrr->num_bases = 1;
1241 bsrr->basenames = &srw_req->database;
1243 bsrr->num_entries = srw_req->maximumTerms ?
1244 *srw_req->maximumTerms : 10;
1245 bsrr->term_position = srw_req->responsePosition ?
1246 *srw_req->responsePosition : 1;
1249 bsrr->errstring = 0;
1250 bsrr->referenceId = 0;
1251 bsrr->stream = assoc->encode;
1252 bsrr->print = assoc->print;
1253 bsrr->step_size = odr_intdup(assoc->decode, 0);
1257 if (bsrr->num_entries > 0)
1260 bsrr->entries = (struct scan_entry *)
1261 odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
1263 for (i = 0; i<bsrr->num_entries; i++)
1265 bsrr->entries[i].term = 0;
1266 bsrr->entries[i].occurrences = 0;
1267 bsrr->entries[i].errcode = 0;
1268 bsrr->entries[i].errstring = 0;
1269 bsrr->entries[i].display_term = 0;
1272 save_entries = bsrr->entries; /* save it so we can compare later */
1274 if (srw_req->query_type == Z_SRW_query_type_pqf &&
1275 assoc->init->bend_scan)
1277 YAZ_PQF_Parser pqf_parser = yaz_pqf_create();
1279 bsrr->term = yaz_pqf_scan(pqf_parser, assoc->decode,
1280 &bsrr->attributeset,
1281 srw_req->scanClause.pqf);
1282 yaz_pqf_destroy(pqf_parser);
1283 bsrr->scanClause = 0;
1284 ((int (*)(void *, bend_scan_rr *))
1285 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1287 else if (srw_req->query_type == Z_SRW_query_type_cql
1288 && assoc->init->bend_scan && assoc->server
1289 && assoc->server->cql_transform)
1292 bsrr->scanClause = 0;
1293 bsrr->attributeset = 0;
1294 bsrr->term = (Z_AttributesPlusTerm *)
1295 odr_malloc(assoc->decode, sizeof(*bsrr->term));
1296 srw_error = cql2pqf_scan(assoc->encode,
1297 srw_req->scanClause.cql,
1298 assoc->server->cql_transform,
1301 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1302 &srw_res->num_diagnostics,
1306 ((int (*)(void *, bend_scan_rr *))
1307 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1310 else if (srw_req->query_type == Z_SRW_query_type_cql
1311 && assoc->init->bend_srw_scan)
1314 bsrr->attributeset = 0;
1315 bsrr->scanClause = srw_req->scanClause.cql;
1316 ((int (*)(void *, bend_scan_rr *))
1317 (*assoc->init->bend_srw_scan))(assoc->backend, bsrr);
1321 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1322 &srw_res->num_diagnostics,
1323 YAZ_SRW_UNSUPP_OPERATION, "scan");
1328 if (bsrr->errcode == YAZ_BIB1_DATABASE_UNAVAILABLE)
1333 srw_error = yaz_diag_bib1_to_srw(bsrr->errcode);
1335 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1336 &srw_res->num_diagnostics,
1337 srw_error, bsrr->errstring);
1339 else if (srw_res->num_diagnostics == 0 && bsrr->num_entries)
1342 srw_res->terms = (Z_SRW_scanTerm*)
1343 odr_malloc(assoc->encode, sizeof(*srw_res->terms) *
1346 srw_res->num_terms = bsrr->num_entries;
1347 for (i = 0; i<bsrr->num_entries; i++)
1349 Z_SRW_scanTerm *t = srw_res->terms + i;
1350 t->value = odr_strdup(assoc->encode, bsrr->entries[i].term);
1351 t->numberOfRecords =
1352 odr_intdup(assoc->encode, bsrr->entries[i].occurrences);
1354 if (save_entries == bsrr->entries &&
1355 bsrr->entries[i].display_term)
1357 /* the entries was _not_ set by the handler. So it's
1358 safe to test for new member display_term. It is
1361 t->displayTerm = odr_strdup(assoc->encode,
1362 bsrr->entries[i].display_term);
1370 WRBUF wr = wrbuf_alloc();
1371 const char *querytype = 0;
1372 const char *querystr = 0;
1374 switch(srw_req->query_type)
1376 case Z_SRW_query_type_pqf:
1378 querystr = srw_req->scanClause.pqf;
1380 case Z_SRW_query_type_cql:
1382 querystr = srw_req->scanClause.cql;
1385 querytype = "UNKNOWN";
1389 wrbuf_printf(wr, "SRWScan %s ", srw_req->database);
1391 if (srw_res->num_diagnostics)
1392 wrbuf_printf(wr, "ERROR %s - ", srw_res->diagnostics[0].uri);
1393 else if (srw_res->num_terms)
1394 wrbuf_printf(wr, "OK %d - ", srw_res->num_terms);
1396 wrbuf_printf(wr, "OK - - ");
1398 wrbuf_printf(wr, ODR_INT_PRINTF "+" ODR_INT_PRINTF " ",
1399 (srw_req->responsePosition ?
1400 *srw_req->responsePosition : 1),
1401 (srw_req->maximumTerms ?
1402 *srw_req->maximumTerms : 1));
1403 /* there is no step size in SRU/W ??? */
1404 wrbuf_printf(wr, "%s: %s ", querytype, querystr);
1405 yaz_log(log_request, "%s ", wrbuf_cstr(wr) );
1411 static void srw_bend_update(association *assoc, request *req,
1413 Z_SRW_updateResponse *srw_res,
1416 Z_SRW_updateRequest *srw_req = sr->u.update_request;
1417 yaz_log(log_session, "SRWUpdate action=%s", srw_req->operation);
1418 yaz_log(YLOG_DEBUG, "num_diag = %d", srw_res->num_diagnostics );
1420 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1424 Z_SRW_extra_record *extra = srw_req->extra_record;
1426 rr.stream = assoc->encode;
1427 rr.print = assoc->print;
1429 rr.basenames = &srw_req->database;
1430 rr.operation = srw_req->operation;
1431 rr.operation_status = "failed";
1433 rr.record_versions = 0;
1434 rr.num_versions = 0;
1435 rr.record_packing = "string";
1436 rr.record_schema = 0;
1438 rr.extra_record_data = 0;
1439 rr.extra_request_data = 0;
1440 rr.extra_response_data = 0;
1446 if (rr.operation == 0)
1448 yaz_add_sru_update_diagnostic(
1449 assoc->encode, &srw_res->diagnostics,
1450 &srw_res->num_diagnostics,
1451 YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,
1455 yaz_log(YLOG_DEBUG, "basename = %s", rr.basenames[0] );
1456 yaz_log(YLOG_DEBUG, "Operation = %s", rr.operation );
1457 if (!strcmp( rr.operation, "delete"))
1459 if (srw_req->record && !srw_req->record->recordSchema)
1461 rr.record_schema = odr_strdup(
1463 srw_req->record->recordSchema);
1465 if (srw_req->record)
1467 rr.record_data = odr_strdupn(
1469 srw_req->record->recordData_buf,
1470 srw_req->record->recordData_len );
1472 if (extra && extra->extraRecordData_len)
1474 rr.extra_record_data = odr_strdupn(
1476 extra->extraRecordData_buf,
1477 extra->extraRecordData_len );
1479 if (srw_req->recordId)
1480 rr.record_id = srw_req->recordId;
1481 else if (extra && extra->recordIdentifier)
1482 rr.record_id = extra->recordIdentifier;
1484 else if (!strcmp(rr.operation, "replace"))
1486 if (srw_req->recordId)
1487 rr.record_id = srw_req->recordId;
1488 else if (extra && extra->recordIdentifier)
1489 rr.record_id = extra->recordIdentifier;
1492 yaz_add_sru_update_diagnostic(
1493 assoc->encode, &srw_res->diagnostics,
1494 &srw_res->num_diagnostics,
1495 YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,
1496 "recordIdentifier");
1498 if (!srw_req->record)
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,
1508 if (srw_req->record->recordSchema)
1509 rr.record_schema = odr_strdup(
1510 assoc->encode, srw_req->record->recordSchema);
1511 if (srw_req->record->recordData_len )
1513 rr.record_data = odr_strdupn(assoc->encode,
1514 srw_req->record->recordData_buf,
1515 srw_req->record->recordData_len );
1519 yaz_add_sru_update_diagnostic(
1520 assoc->encode, &srw_res->diagnostics,
1521 &srw_res->num_diagnostics,
1522 YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,
1526 if (extra && extra->extraRecordData_len)
1528 rr.extra_record_data = odr_strdupn(
1530 extra->extraRecordData_buf,
1531 extra->extraRecordData_len );
1534 else if (!strcmp(rr.operation, "insert"))
1536 if (srw_req->recordId)
1537 rr.record_id = srw_req->recordId;
1539 rr.record_id = extra->recordIdentifier;
1541 if (srw_req->record)
1543 if (srw_req->record->recordSchema)
1544 rr.record_schema = odr_strdup(
1545 assoc->encode, srw_req->record->recordSchema);
1547 if (srw_req->record->recordData_len)
1548 rr.record_data = odr_strdupn(
1550 srw_req->record->recordData_buf,
1551 srw_req->record->recordData_len );
1553 if (extra && extra->extraRecordData_len)
1555 rr.extra_record_data = odr_strdupn(
1557 extra->extraRecordData_buf,
1558 extra->extraRecordData_len );
1562 yaz_add_sru_update_diagnostic(assoc->encode, &srw_res->diagnostics,
1563 &srw_res->num_diagnostics,
1564 YAZ_SRU_UPDATE_INVALID_ACTION,
1567 if (srw_req->record)
1569 const char *pack_str =
1570 yaz_srw_pack_to_str(srw_req->record->recordPacking);
1572 rr.record_packing = odr_strdup(assoc->encode, pack_str);
1575 if (srw_req->num_recordVersions)
1577 rr.record_versions = srw_req->recordVersions;
1578 rr.num_versions = srw_req->num_recordVersions;
1580 if (srw_req->extraRequestData_len)
1582 rr.extra_request_data = odr_strdupn(assoc->encode,
1583 srw_req->extraRequestData_buf,
1584 srw_req->extraRequestData_len );
1586 if (srw_res->num_diagnostics == 0)
1588 if ( assoc->init->bend_srw_update)
1589 (*assoc->init->bend_srw_update)(assoc->backend, &rr);
1591 yaz_add_sru_update_diagnostic(
1592 assoc->encode, &srw_res->diagnostics,
1593 &srw_res->num_diagnostics,
1594 YAZ_SRU_UPDATE_UNSPECIFIED_DATABASE_ERROR,
1595 "No Update backend handler");
1599 yaz_add_srw_diagnostic_uri(assoc->encode,
1600 &srw_res->diagnostics,
1601 &srw_res->num_diagnostics,
1605 srw_res->recordId = rr.record_id;
1606 srw_res->operationStatus = rr.operation_status;
1607 srw_res->recordVersions = rr.record_versions;
1608 srw_res->num_recordVersions = rr.num_versions;
1609 if (srw_res->extraResponseData_len)
1611 srw_res->extraResponseData_buf = rr.extra_response_data;
1612 srw_res->extraResponseData_len = strlen(rr.extra_response_data);
1614 if (srw_res->num_diagnostics == 0 && rr.record_data)
1616 srw_res->record = yaz_srw_get_record(assoc->encode);
1617 srw_res->record->recordSchema = rr.record_schema;
1618 if (rr.record_packing)
1620 int pack = yaz_srw_str_to_pack(rr.record_packing);
1624 pack = Z_SRW_recordPacking_string;
1625 yaz_log(YLOG_WARN, "Back packing %s from backend",
1628 srw_res->record->recordPacking = pack;
1630 srw_res->record->recordData_buf = rr.record_data;
1631 srw_res->record->recordData_len = strlen(rr.record_data);
1632 if (rr.extra_record_data)
1634 Z_SRW_extra_record *ex =
1635 yaz_srw_get_extra_record(assoc->encode);
1636 srw_res->extra_record = ex;
1637 ex->extraRecordData_buf = rr.extra_record_data;
1638 ex->extraRecordData_len = strlen(rr.extra_record_data);
1644 /* check if path is OK (1); BAD (0) */
1645 static int check_path(const char *path)
1649 if (strstr(path, ".."))
1654 static char *read_file(const char *fname, ODR o, size_t *sz)
1657 FILE *inf = fopen(fname, "rb");
1661 fseek(inf, 0L, SEEK_END);
1664 buf = (char *) odr_malloc(o, *sz);
1665 if (fread(buf, 1, *sz, inf) != *sz)
1666 yaz_log(YLOG_WARN|YLOG_ERRNO, "short read %s", fname);
1671 static void process_http_request(association *assoc, request *req)
1673 Z_HTTP_Request *hreq = req->gdu_request->u.HTTP_Request;
1674 ODR o = assoc->encode;
1675 int r = 2; /* 2=NOT TAKEN, 1=TAKEN, 0=SOAP TAKEN */
1677 Z_SOAP *soap_package = 0;
1680 Z_HTTP_Response *hres = 0;
1682 const char *stylesheet = 0; /* for now .. set later */
1683 Z_SRW_diagnostic *diagnostic = 0;
1684 int num_diagnostic = 0;
1685 const char *host = z_HTTP_header_lookup(hreq->headers, "Host");
1687 yaz_log(log_request, "%s %s HTTP/%s", hreq->method, hreq->path, hreq->version);
1688 if (!control_association(assoc, host, 0))
1690 p = z_get_HTTP_Response(o, 404);
1693 if (r == 2 && assoc->server && assoc->server->docpath
1694 && hreq->path[0] == '/'
1696 /* check if path is a proper prefix of documentroot */
1697 strncmp(hreq->path+1, assoc->server->docpath,
1698 strlen(assoc->server->docpath))
1701 if (!check_path(hreq->path))
1703 yaz_log(YLOG_LOG, "File %s access forbidden", hreq->path+1);
1704 p = z_get_HTTP_Response(o, 404);
1708 size_t content_size = 0;
1709 char *content_buf = read_file(hreq->path+1, o, &content_size);
1712 yaz_log(YLOG_LOG, "File %s not found", hreq->path+1);
1713 p = z_get_HTTP_Response(o, 404);
1717 const char *ctype = 0;
1718 yaz_mime_types types = yaz_mime_types_create();
1720 yaz_mime_types_add(types, "xsl", "application/xml");
1721 yaz_mime_types_add(types, "xml", "application/xml");
1722 yaz_mime_types_add(types, "css", "text/css");
1723 yaz_mime_types_add(types, "html", "text/html");
1724 yaz_mime_types_add(types, "htm", "text/html");
1725 yaz_mime_types_add(types, "txt", "text/plain");
1726 yaz_mime_types_add(types, "js", "application/x-javascript");
1728 yaz_mime_types_add(types, "gif", "image/gif");
1729 yaz_mime_types_add(types, "png", "image/png");
1730 yaz_mime_types_add(types, "jpg", "image/jpeg");
1731 yaz_mime_types_add(types, "jpeg", "image/jpeg");
1733 ctype = yaz_mime_lookup_fname(types, hreq->path);
1736 yaz_log(YLOG_LOG, "No mime type for %s", hreq->path+1);
1737 p = z_get_HTTP_Response(o, 404);
1741 p = z_get_HTTP_Response(o, 200);
1742 hres = p->u.HTTP_Response;
1743 hres->content_buf = content_buf;
1744 hres->content_len = content_size;
1745 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1747 yaz_mime_types_destroy(types);
1755 r = yaz_srw_decode(hreq, &sr, &soap_package, assoc->decode, &charset);
1756 yaz_log(YLOG_DEBUG, "yaz_srw_decode returned %d", r);
1758 if (r == 2) /* not taken */
1760 r = yaz_sru_decode(hreq, &sr, &soap_package, assoc->decode, &charset,
1761 &diagnostic, &num_diagnostic);
1762 yaz_log(YLOG_DEBUG, "yaz_sru_decode returned %d", r);
1764 if (r == 0) /* decode SRW/SRU OK .. */
1766 int http_code = 200;
1767 if (sr->which == Z_SRW_searchRetrieve_request)
1770 yaz_srw_get_pdu(assoc->encode, Z_SRW_searchRetrieve_response,
1772 stylesheet = sr->u.request->stylesheet;
1775 res->u.response->diagnostics = diagnostic;
1776 res->u.response->num_diagnostics = num_diagnostic;
1780 srw_bend_search(assoc, req, sr, res, &http_code);
1782 if (http_code == 200)
1783 soap_package->u.generic->p = res;
1785 else if (sr->which == Z_SRW_explain_request)
1787 Z_SRW_PDU *res = yaz_srw_get_pdu(o, Z_SRW_explain_response,
1789 stylesheet = sr->u.explain_request->stylesheet;
1792 res->u.explain_response->diagnostics = diagnostic;
1793 res->u.explain_response->num_diagnostics = num_diagnostic;
1795 srw_bend_explain(assoc, req, sr,
1796 res->u.explain_response, &http_code);
1797 if (http_code == 200)
1798 soap_package->u.generic->p = res;
1800 else if (sr->which == Z_SRW_scan_request)
1802 Z_SRW_PDU *res = yaz_srw_get_pdu(o, Z_SRW_scan_response,
1804 stylesheet = sr->u.scan_request->stylesheet;
1807 res->u.scan_response->diagnostics = diagnostic;
1808 res->u.scan_response->num_diagnostics = num_diagnostic;
1810 srw_bend_scan(assoc, req, sr,
1811 res->u.scan_response, &http_code);
1812 if (http_code == 200)
1813 soap_package->u.generic->p = res;
1815 else if (sr->which == Z_SRW_update_request)
1817 Z_SRW_PDU *res = yaz_srw_get_pdu(o, Z_SRW_update_response,
1819 yaz_log(YLOG_DEBUG, "handling SRW UpdateRequest");
1822 res->u.update_response->diagnostics = diagnostic;
1823 res->u.update_response->num_diagnostics = num_diagnostic;
1825 yaz_log(YLOG_DEBUG, "num_diag = %d", res->u.update_response->num_diagnostics );
1826 srw_bend_update(assoc, req, sr,
1827 res->u.update_response, &http_code);
1828 if (http_code == 200)
1829 soap_package->u.generic->p = res;
1833 yaz_log(log_request, "SOAP ERROR");
1834 /* FIXME - what error, what query */
1836 z_soap_error(assoc->encode, soap_package,
1837 "SOAP-ENV:Client", "Bad method", 0);
1839 if (http_code == 200 || http_code == 500)
1841 static Z_SOAP_Handler soap_handlers[4] = {
1843 {YAZ_XMLNS_SRU_v1_1, 0, (Z_SOAP_fun) yaz_srw_codec},
1844 {YAZ_XMLNS_SRU_v1_0, 0, (Z_SOAP_fun) yaz_srw_codec},
1845 {YAZ_XMLNS_UPDATE_v0_9, 0, (Z_SOAP_fun) yaz_ucp_codec},
1851 p = z_get_HTTP_Response(o, 200);
1852 hres = p->u.HTTP_Response;
1854 if (!stylesheet && assoc->server)
1855 stylesheet = assoc->server->stylesheet;
1857 /* empty stylesheet means NO stylesheet */
1858 if (stylesheet && *stylesheet == '\0')
1861 ret = z_soap_codec_enc_xsl(assoc->encode, &soap_package,
1862 &hres->content_buf, &hres->content_len,
1863 soap_handlers, charset, stylesheet);
1864 hres->code = http_code;
1866 strcpy(ctype, "text/xml");
1867 if (charset && strlen(charset) < sizeof(ctype)-30)
1869 strcat(ctype, "; charset=");
1870 strcat(ctype, charset);
1872 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1875 p = z_get_HTTP_Response(o, http_code);
1879 p = z_get_HTTP_Response(o, 500);
1880 hres = p->u.HTTP_Response;
1881 if (!strcmp(hreq->version, "1.0"))
1883 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1884 if (v && !strcmp(v, "Keep-Alive"))
1888 hres->version = "1.0";
1892 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1893 if (v && !strcmp(v, "close"))
1897 hres->version = "1.1";
1901 z_HTTP_header_add(o, &hres->headers, "Connection", "close");
1902 assoc->state = ASSOC_DEAD;
1903 assoc->cs_get_mask = 0;
1908 const char *alive = z_HTTP_header_lookup(hreq->headers, "Keep-Alive");
1910 if (alive && isdigit(*(const unsigned char *) alive))
1914 if (t < 0 || t > 3600)
1916 iochan_settimeout(assoc->client_chan,t);
1917 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1919 process_gdu_response(assoc, req, p);
1922 static void process_gdu_request(association *assoc, request *req)
1924 if (req->gdu_request->which == Z_GDU_Z3950)
1927 req->apdu_request = req->gdu_request->u.z3950;
1928 if (process_z_request(assoc, req, &msg) < 0)
1929 do_close_req(assoc, Z_Close_systemProblem, msg, req);
1931 else if (req->gdu_request->which == Z_GDU_HTTP_Request)
1932 process_http_request(assoc, req);
1935 do_close_req(assoc, Z_Close_systemProblem, "bad protocol packet", req);
1940 * Initiate request processing.
1942 static int process_z_request(association *assoc, request *req, char **msg)
1947 *msg = "Unknown Error";
1948 assert(req && req->state == REQUEST_IDLE);
1949 if (req->apdu_request->which != Z_APDU_initRequest && !assoc->init)
1951 *msg = "Missing InitRequest";
1954 switch (req->apdu_request->which)
1956 case Z_APDU_initRequest:
1957 res = process_initRequest(assoc, req); break;
1958 case Z_APDU_searchRequest:
1959 res = process_searchRequest(assoc, req); break;
1960 case Z_APDU_presentRequest:
1961 res = process_presentRequest(assoc, req); break;
1962 case Z_APDU_scanRequest:
1963 if (assoc->init->bend_scan)
1964 res = process_scanRequest(assoc, req);
1967 *msg = "Cannot handle Scan APDU";
1971 case Z_APDU_extendedServicesRequest:
1972 if (assoc->init->bend_esrequest)
1973 res = process_ESRequest(assoc, req);
1976 *msg = "Cannot handle Extended Services APDU";
1980 case Z_APDU_sortRequest:
1981 if (assoc->init->bend_sort)
1982 res = process_sortRequest(assoc, req);
1985 *msg = "Cannot handle Sort APDU";
1990 process_close(assoc, req);
1992 case Z_APDU_deleteResultSetRequest:
1993 if (assoc->init->bend_delete)
1994 res = process_deleteRequest(assoc, req);
1997 *msg = "Cannot handle Delete APDU";
2001 case Z_APDU_segmentRequest:
2002 if (assoc->init->bend_segment)
2004 res = process_segmentRequest(assoc, req);
2008 *msg = "Cannot handle Segment APDU";
2012 case Z_APDU_triggerResourceControlRequest:
2015 *msg = "Bad APDU received";
2020 yaz_log(YLOG_DEBUG, " result immediately available");
2021 retval = process_z_response(assoc, req, res);
2025 yaz_log(YLOG_DEBUG, " result unavailble");
2032 * Encode response, and transfer the request structure to the outgoing queue.
2034 static int process_gdu_response(association *assoc, request *req, Z_GDU *res)
2036 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
2040 if (!z_GDU(assoc->print, &res, 0, 0))
2041 yaz_log(YLOG_WARN, "ODR print error: %s",
2042 odr_errmsg(odr_geterror(assoc->print)));
2043 odr_reset(assoc->print);
2045 if (!z_GDU(assoc->encode, &res, 0, 0))
2047 yaz_log(YLOG_WARN, "ODR error when encoding PDU: %s [element %s]",
2048 odr_errmsg(odr_geterror(assoc->decode)),
2049 odr_getelement(assoc->decode));
2052 req->response = odr_getbuf(assoc->encode, &req->len_response,
2053 &req->size_response);
2054 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
2055 odr_reset(assoc->encode);
2056 req->state = REQUEST_IDLE;
2057 request_enq(&assoc->outgoing, req);
2058 /* turn the work over to the ir_session handler */
2059 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
2060 assoc->cs_put_mask = EVENT_OUTPUT;
2061 /* Is there more work to be done? give that to the input handler too */
2064 req = request_head(&assoc->incoming);
2065 if (req && req->state == REQUEST_IDLE)
2067 request_deq(&assoc->incoming);
2068 process_gdu_request(assoc, req);
2077 * Encode response, and transfer the request structure to the outgoing queue.
2079 static int process_z_response(association *assoc, request *req, Z_APDU *res)
2081 Z_GDU *gres = (Z_GDU *) odr_malloc(assoc->encode, sizeof(*res));
2082 gres->which = Z_GDU_Z3950;
2083 gres->u.z3950 = res;
2085 return process_gdu_response(assoc, req, gres);
2088 static char *get_vhost(Z_OtherInformation *otherInfo)
2090 return yaz_oi_get_string_oid(&otherInfo, yaz_oid_userinfo_proxy, 1, 0);
2094 * Handle init request.
2095 * At the moment, we don't check the options
2096 * anywhere else in the code - we just try not to do anything that would
2097 * break a naive client. We'll toss 'em into the association block when
2098 * we need them there.
2100 static Z_APDU *process_initRequest(association *assoc, request *reqb)
2102 Z_InitRequest *req = reqb->apdu_request->u.initRequest;
2103 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
2104 Z_InitResponse *resp = apdu->u.initResponse;
2105 bend_initresult *binitres;
2107 statserv_options_block *cb = 0; /* by default no control for backend */
2109 if (control_association(assoc, get_vhost(req->otherInfo), 1))
2110 cb = statserv_getcontrol(); /* got control block for backend */
2112 if (cb && assoc->backend)
2113 (*cb->bend_close)(assoc->backend);
2115 yaz_log(log_requestdetail, "Got initRequest");
2116 if (req->implementationId)
2117 yaz_log(log_requestdetail, "Id: %s",
2118 req->implementationId);
2119 if (req->implementationName)
2120 yaz_log(log_requestdetail, "Name: %s",
2121 req->implementationName);
2122 if (req->implementationVersion)
2123 yaz_log(log_requestdetail, "Version: %s",
2124 req->implementationVersion);
2126 assoc_init_reset(assoc);
2128 assoc->init->auth = req->idAuthentication;
2129 assoc->init->referenceId = req->referenceId;
2131 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
2133 Z_CharSetandLanguageNegotiation *negotiation =
2134 yaz_get_charneg_record (req->otherInfo);
2136 negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
2137 assoc->init->charneg_request = negotiation;
2140 /* by default named_result_sets is 0 .. Enable it if client asks for it. */
2141 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
2142 assoc->init->named_result_sets = 1;
2147 if (req->implementationVersion)
2148 yaz_log(log_requestdetail, "Config: %s",
2151 iochan_settimeout(assoc->client_chan, cb->idle_timeout * 60);
2153 /* we have a backend control block, so call that init function */
2154 if (!(binitres = (*cb->bend_init)(assoc->init)))
2156 yaz_log(YLOG_WARN, "Bad response from backend.");
2159 assoc->backend = binitres->handle;
2163 /* no backend. return error */
2164 binitres = (bend_initresult *)
2165 odr_malloc(assoc->encode, sizeof(*binitres));
2166 binitres->errstring = 0;
2167 binitres->errcode = YAZ_BIB1_PERMANENT_SYSTEM_ERROR;
2168 iochan_settimeout(assoc->client_chan, 10);
2170 if ((assoc->init->bend_sort))
2171 yaz_log(YLOG_DEBUG, "Sort handler installed");
2172 if ((assoc->init->bend_search))
2173 yaz_log(YLOG_DEBUG, "Search handler installed");
2174 if ((assoc->init->bend_present))
2175 yaz_log(YLOG_DEBUG, "Present handler installed");
2176 if ((assoc->init->bend_esrequest))
2177 yaz_log(YLOG_DEBUG, "ESRequest handler installed");
2178 if ((assoc->init->bend_delete))
2179 yaz_log(YLOG_DEBUG, "Delete handler installed");
2180 if ((assoc->init->bend_scan))
2181 yaz_log(YLOG_DEBUG, "Scan handler installed");
2182 if ((assoc->init->bend_segment))
2183 yaz_log(YLOG_DEBUG, "Segment handler installed");
2185 resp->referenceId = req->referenceId;
2187 /* let's tell the client what we can do */
2188 if (ODR_MASK_GET(req->options, Z_Options_search))
2190 ODR_MASK_SET(resp->options, Z_Options_search);
2191 strcat(options, "srch");
2193 if (ODR_MASK_GET(req->options, Z_Options_present))
2195 ODR_MASK_SET(resp->options, Z_Options_present);
2196 strcat(options, " prst");
2198 if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
2199 assoc->init->bend_delete)
2201 ODR_MASK_SET(resp->options, Z_Options_delSet);
2202 strcat(options, " del");
2204 if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
2205 assoc->init->bend_esrequest)
2207 ODR_MASK_SET(resp->options, Z_Options_extendedServices);
2208 strcat(options, " extendedServices");
2210 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets)
2211 && assoc->init->named_result_sets)
2213 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
2214 strcat(options, " namedresults");
2216 if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
2218 ODR_MASK_SET(resp->options, Z_Options_scan);
2219 strcat(options, " scan");
2221 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
2223 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
2224 strcat(options, " concurrop");
2226 if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
2228 ODR_MASK_SET(resp->options, Z_Options_sort);
2229 strcat(options, " sort");
2232 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
2234 Z_OtherInformationUnit *p0;
2236 if (!assoc->init->charneg_response)
2238 if (assoc->init->query_charset)
2240 assoc->init->charneg_response = yaz_set_response_charneg(
2241 assoc->encode, assoc->init->query_charset, 0,
2242 assoc->init->records_in_same_charset);
2246 yaz_log(YLOG_WARN, "default query_charset not defined by backend");
2249 if (assoc->init->charneg_response
2250 && (p0=yaz_oi_update(&resp->otherInfo, assoc->encode, NULL, 0, 0)))
2252 p0->which = Z_OtherInfo_externallyDefinedInfo;
2253 p0->information.externallyDefinedInfo =
2254 assoc->init->charneg_response;
2255 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
2256 strcat(options, " negotiation");
2259 if (ODR_MASK_GET(req->options, Z_Options_triggerResourceCtrl))
2260 ODR_MASK_SET(resp->options, Z_Options_triggerResourceCtrl);
2262 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
2264 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
2265 assoc->version = 1; /* 1 & 2 are equivalent */
2267 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
2269 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
2272 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
2274 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
2278 yaz_log(log_requestdetail, "Negotiated to v%d: %s", assoc->version, options);
2280 if (*req->maximumRecordSize < assoc->maximumRecordSize)
2281 assoc->maximumRecordSize = *req->maximumRecordSize;
2283 if (*req->preferredMessageSize < assoc->preferredMessageSize)
2284 assoc->preferredMessageSize = *req->preferredMessageSize;
2286 resp->preferredMessageSize = &assoc->preferredMessageSize;
2287 resp->maximumRecordSize = &assoc->maximumRecordSize;
2289 resp->implementationId = odr_prepend(assoc->encode,
2290 assoc->init->implementation_id,
2291 resp->implementationId);
2293 resp->implementationName = odr_prepend(assoc->encode,
2294 assoc->init->implementation_name,
2295 odr_prepend(assoc->encode, "GFS", resp->implementationName));
2297 if (binitres->errcode)
2299 assoc->state = ASSOC_DEAD;
2300 resp->userInformationField =
2301 init_diagnostics(assoc->encode, binitres->errcode,
2302 binitres->errstring);
2306 assoc->state = ASSOC_UP;
2310 if (!req->idAuthentication)
2311 yaz_log(log_request, "Auth none");
2312 else if (req->idAuthentication->which == Z_IdAuthentication_open)
2314 const char *open = req->idAuthentication->u.open;
2315 const char *slash = strchr(open, '/');
2321 yaz_log(log_request, "Auth open %.*s", len, open);
2323 else if (req->idAuthentication->which == Z_IdAuthentication_idPass)
2325 const char *user = req->idAuthentication->u.idPass->userId;
2326 const char *group = req->idAuthentication->u.idPass->groupId;
2327 yaz_log(log_request, "Auth idPass %s %s",
2328 user ? user : "-", group ? group : "-");
2330 else if (req->idAuthentication->which
2331 == Z_IdAuthentication_anonymous)
2333 yaz_log(log_request, "Auth anonymous");
2337 yaz_log(log_request, "Auth other");
2342 WRBUF wr = wrbuf_alloc();
2343 wrbuf_printf(wr, "Init ");
2344 if (binitres->errcode)
2345 wrbuf_printf(wr, "ERROR %d", binitres->errcode);
2347 wrbuf_printf(wr, "OK -");
2348 wrbuf_printf(wr, " ID:%s Name:%s Version:%s",
2349 (req->implementationId ? req->implementationId :"-"),
2350 (req->implementationName ?
2351 req->implementationName : "-"),
2352 (req->implementationVersion ?
2353 req->implementationVersion : "-")
2355 yaz_log(log_request, "%s", wrbuf_cstr(wr));
2362 * Set the specified `errcode' and `errstring' into a UserInfo-1
2363 * external to be returned to the client in accordance with Z35.90
2364 * Implementor Agreement 5 (Returning diagnostics in an InitResponse):
2365 * http://lcweb.loc.gov/z3950/agency/agree/initdiag.html
2367 static Z_External *init_diagnostics(ODR odr, int error, const char *addinfo)
2369 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2370 addinfo ? " -- " : "", addinfo ? addinfo : "");
2371 return zget_init_diagnostics(odr, error, addinfo);
2375 * nonsurrogate diagnostic record.
2377 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
2379 Z_Records *rec = (Z_Records *) odr_malloc(assoc->encode, sizeof(*rec));
2381 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2382 addinfo ? " -- " : "", addinfo ? addinfo : "");
2384 rec->which = Z_Records_NSD;
2385 rec->u.nonSurrogateDiagnostic = zget_DefaultDiagFormat(assoc->encode,
2391 * surrogate diagnostic.
2393 static Z_NamePlusRecord *surrogatediagrec(association *assoc,
2395 int error, const char *addinfo)
2397 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2398 addinfo ? " -- " : "", addinfo ? addinfo : "");
2399 return zget_surrogateDiagRec(assoc->encode, dbname, error, addinfo);
2402 static Z_Records *pack_records(association *a, char *setname, Odr_int start,
2403 Odr_int *num, Z_RecordComposition *comp,
2404 Odr_int *next, Odr_int *pres,
2405 Z_ReferenceId *referenceId,
2406 Odr_oid *oid, int *errcode)
2408 int recno, total_length = 0, toget = *num, dumped_records = 0;
2409 Z_Records *records =
2410 (Z_Records *) odr_malloc(a->encode, sizeof(*records));
2411 Z_NamePlusRecordList *reclist =
2412 (Z_NamePlusRecordList *) odr_malloc(a->encode, sizeof(*reclist));
2413 Z_NamePlusRecord **list =
2414 (Z_NamePlusRecord **) odr_malloc(a->encode, sizeof(*list) * toget);
2416 records->which = Z_Records_DBOSD;
2417 records->u.databaseOrSurDiagnostics = reclist;
2418 reclist->num_records = 0;
2419 reclist->records = list;
2420 *pres = Z_PresentStatus_success;
2424 yaz_log(log_requestdetail, "Request to pack " ODR_INT_PRINTF "+%d %s", start, toget, setname);
2425 yaz_log(log_requestdetail, "pms=" ODR_INT_PRINTF
2426 ", mrs=" ODR_INT_PRINTF, a->preferredMessageSize,
2427 a->maximumRecordSize);
2428 for (recno = start; reclist->num_records < toget; recno++)
2431 Z_NamePlusRecord *thisrec;
2432 int this_length = 0;
2434 * we get the number of bytes allocated on the stream before any
2435 * allocation done by the backend - this should give us a reasonable
2436 * idea of the total size of the data so far.
2438 total_length = odr_total(a->encode) - dumped_records;
2444 freq.last_in_set = 0;
2445 freq.setname = setname;
2446 freq.surrogate_flag = 0;
2447 freq.number = recno;
2449 freq.request_format = oid;
2450 freq.output_format = 0;
2451 freq.stream = a->encode;
2452 freq.print = a->print;
2453 freq.referenceId = referenceId;
2456 retrieve_fetch(a, &freq);
2458 *next = freq.last_in_set ? 0 : recno + 1;
2462 if (!freq.surrogate_flag) /* non-surrogate diagnostic i.e. global */
2465 *pres = Z_PresentStatus_failure;
2466 /* for 'present request out of range',
2467 set addinfo to record position if not set */
2468 if (freq.errcode == YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE &&
2469 freq.errstring == 0)
2471 sprintf(s, "%d", recno);
2475 *errcode = freq.errcode;
2476 return diagrec(a, freq.errcode, freq.errstring);
2478 reclist->records[reclist->num_records] =
2479 surrogatediagrec(a, freq.basename, freq.errcode,
2481 reclist->num_records++;
2484 if (freq.record == 0) /* no error and no record ? */
2486 *next = 0; /* signal end-of-set and stop */
2490 this_length = freq.len;
2492 this_length = odr_total(a->encode) - total_length - dumped_records;
2493 yaz_log(YLOG_DEBUG, " fetched record, len=%d, total=%d dumped=%d",
2494 this_length, total_length, dumped_records);
2495 if (a->preferredMessageSize > 0 &&
2496 this_length + total_length > a->preferredMessageSize)
2498 /* record is small enough, really */
2499 if (this_length <= a->preferredMessageSize && recno > start)
2501 yaz_log(log_requestdetail, " Dropped last normal-sized record");
2502 *pres = Z_PresentStatus_partial_2;
2505 /* record can only be fetched by itself */
2506 if (this_length < a->maximumRecordSize)
2508 yaz_log(log_requestdetail, " Record > prefmsgsz");
2511 yaz_log(YLOG_DEBUG, " Dropped it");
2512 reclist->records[reclist->num_records] =
2513 surrogatediagrec(a, freq.basename, 16, 0);
2514 reclist->num_records++;
2515 dumped_records += this_length;
2519 else /* too big entirely */
2521 yaz_log(log_requestdetail, "Record > maxrcdsz "
2522 "this=%d max=" ODR_INT_PRINTF,
2523 this_length, a->maximumRecordSize);
2524 reclist->records[reclist->num_records] =
2525 surrogatediagrec(a, freq.basename, 17, 0);
2526 reclist->num_records++;
2527 dumped_records += this_length;
2532 if (!(thisrec = (Z_NamePlusRecord *)
2533 odr_malloc(a->encode, sizeof(*thisrec))))
2535 thisrec->databaseName = odr_strdup_null(a->encode, freq.basename);
2536 thisrec->which = Z_NamePlusRecord_databaseRecord;
2538 if (!freq.output_format)
2539 freq.output_format = freq.request_format;
2540 thisrec->u.databaseRecord = z_ext_record_oid(
2541 a->encode, freq.output_format, freq.record, freq.len);
2542 if (!thisrec->u.databaseRecord)
2544 reclist->records[reclist->num_records] = thisrec;
2545 reclist->num_records++;
2547 *num = reclist->num_records;
2551 static Z_APDU *process_searchRequest(association *assoc, request *reqb)
2553 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2554 bend_search_rr *bsrr =
2555 (bend_search_rr *)nmem_malloc(reqb->request_mem, sizeof(*bsrr));
2557 yaz_log(log_requestdetail, "Got SearchRequest.");
2558 bsrr->association = assoc;
2559 bsrr->referenceId = req->referenceId;
2560 bsrr->srw_sortKeys = 0;
2561 bsrr->srw_setname = 0;
2562 bsrr->srw_setnameIdleTime = 0;
2563 bsrr->estimated_hit_count = 0;
2564 bsrr->partial_resultset = 0;
2565 bsrr->extra_args = 0;
2566 bsrr->extra_response_data = 0;
2568 yaz_log (log_requestdetail, "ResultSet '%s'", req->resultSetName);
2569 if (req->databaseNames)
2572 for (i = 0; i < req->num_databaseNames; i++)
2573 yaz_log(log_requestdetail, "Database '%s'", req->databaseNames[i]);
2576 yaz_log_zquery_level(log_requestdetail,req->query);
2578 if (assoc->init->bend_search)
2580 bsrr->setname = req->resultSetName;
2581 bsrr->replace_set = *req->replaceIndicator;
2582 bsrr->num_bases = req->num_databaseNames;
2583 bsrr->basenames = req->databaseNames;
2584 bsrr->query = req->query;
2585 bsrr->stream = assoc->encode;
2586 nmem_transfer(odr_getmem(bsrr->stream), reqb->request_mem);
2587 bsrr->decode = assoc->decode;
2588 bsrr->print = assoc->print;
2591 bsrr->errstring = NULL;
2592 bsrr->search_info = NULL;
2594 if (assoc->server && assoc->server->cql_transform
2595 && req->query->which == Z_Query_type_104
2596 && req->query->u.type_104->which == Z_External_CQL)
2598 /* have a CQL query and a CQL to PQF transform .. */
2600 cql2pqf(bsrr->stream, req->query->u.type_104->u.cql,
2601 assoc->server->cql_transform, bsrr->query);
2603 bsrr->errcode = yaz_diag_srw_to_bib1(srw_errcode);
2606 if (assoc->server && assoc->server->ccl_transform
2607 && req->query->which == Z_Query_type_2) /*CCL*/
2609 /* have a CCL query and a CCL to PQF transform .. */
2611 ccl2pqf(bsrr->stream, req->query->u.type_2,
2612 assoc->server->ccl_transform, bsrr);
2614 bsrr->errcode = yaz_diag_srw_to_bib1(srw_errcode);
2618 (assoc->init->bend_search)(assoc->backend, bsrr);
2622 /* FIXME - make a diagnostic for it */
2623 yaz_log(YLOG_WARN,"Search not supported ?!?!");
2625 return response_searchRequest(assoc, reqb, bsrr);
2629 * Prepare a searchresponse based on the backend results. We probably want
2630 * to look at making the fetching of records nonblocking as well, but
2631 * so far, we'll keep things simple.
2632 * If bsrt is null, that means we're called in response to a communications
2633 * event, and we'll have to get the response for ourselves.
2635 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
2636 bend_search_rr *bsrt)
2638 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2639 Z_APDU *apdu = (Z_APDU *)odr_malloc(assoc->encode, sizeof(*apdu));
2640 Z_SearchResponse *resp = (Z_SearchResponse *)
2641 odr_malloc(assoc->encode, sizeof(*resp));
2642 Odr_int *nulint = odr_intdup(assoc->encode, 0);
2643 Odr_int *next = odr_intdup(assoc->encode, 0);
2644 Odr_int *none = odr_intdup(assoc->encode, Z_SearchResponse_none);
2645 int returnedrecs = 0;
2647 apdu->which = Z_APDU_searchResponse;
2648 apdu->u.searchResponse = resp;
2649 resp->referenceId = req->referenceId;
2650 resp->additionalSearchInfo = 0;
2651 resp->otherInfo = 0;
2654 yaz_log(YLOG_FATAL, "Bad result from backend");
2657 else if (bsrt->errcode)
2659 resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
2660 resp->resultCount = nulint;
2661 resp->numberOfRecordsReturned = nulint;
2662 resp->nextResultSetPosition = nulint;
2663 resp->searchStatus = odr_booldup(assoc->encode, 0);
2664 resp->resultSetStatus = none;
2665 resp->presentStatus = 0;
2669 bool_t *sr = odr_booldup(assoc->encode, 1);
2670 Odr_int *toget = odr_intdup(assoc->encode, 0);
2671 Z_RecordComposition comp, *compp = 0;
2673 yaz_log(log_requestdetail, "resultCount: " ODR_INT_PRINTF, bsrt->hits);
2676 resp->resultCount = &bsrt->hits;
2678 comp.which = Z_RecordComp_simple;
2679 /* how many records does the user agent want, then? */
2682 else if (bsrt->hits <= *req->smallSetUpperBound)
2684 *toget = bsrt->hits;
2685 if ((comp.u.simple = req->smallSetElementSetNames))
2688 else if (bsrt->hits < *req->largeSetLowerBound)
2690 *toget = *req->mediumSetPresentNumber;
2691 if (*toget > bsrt->hits)
2692 *toget = bsrt->hits;
2693 if ((comp.u.simple = req->mediumSetElementSetNames))
2699 if (*toget && !resp->records)
2701 Odr_int *presst = odr_intdup(assoc->encode, 0);
2702 /* Call bend_present if defined */
2703 if (assoc->init->bend_present)
2705 bend_present_rr *bprr = (bend_present_rr *)
2706 nmem_malloc(reqb->request_mem, sizeof(*bprr));
2707 bprr->setname = req->resultSetName;
2709 bprr->number = *toget;
2710 bprr->format = req->preferredRecordSyntax;
2712 bprr->referenceId = req->referenceId;
2713 bprr->stream = assoc->encode;
2714 bprr->print = assoc->print;
2715 bprr->association = assoc;
2717 bprr->errstring = NULL;
2718 (*assoc->init->bend_present)(assoc->backend, bprr);
2722 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2723 *resp->presentStatus = Z_PresentStatus_failure;
2728 resp->records = pack_records(
2729 assoc, req->resultSetName, 1,
2730 toget, compp, next, presst, req->referenceId,
2731 req->preferredRecordSyntax, NULL);
2734 resp->numberOfRecordsReturned = toget;
2735 returnedrecs = *toget;
2736 resp->presentStatus = presst;
2740 if (*resp->resultCount)
2742 resp->numberOfRecordsReturned = nulint;
2743 resp->presentStatus = 0;
2745 resp->nextResultSetPosition = next;
2746 resp->searchStatus = sr;
2747 resp->resultSetStatus = 0;
2748 if (bsrt->estimated_hit_count)
2750 resp->resultSetStatus = odr_intdup(assoc->encode,
2751 Z_SearchResponse_estimate);
2753 else if (bsrt->partial_resultset)
2755 resp->resultSetStatus = odr_intdup(assoc->encode,
2756 Z_SearchResponse_subset);
2759 resp->additionalSearchInfo = bsrt->search_info;
2764 WRBUF wr = wrbuf_alloc();
2766 for (i = 0 ; i < req->num_databaseNames; i++)
2769 wrbuf_printf(wr, "+");
2770 wrbuf_puts(wr, req->databaseNames[i]);
2772 wrbuf_printf(wr, " ");
2775 wrbuf_printf(wr, "ERROR %d", bsrt->errcode);
2777 wrbuf_printf(wr, "OK " ODR_INT_PRINTF, bsrt->hits);
2778 wrbuf_printf(wr, " %s 1+%d ",
2779 req->resultSetName, returnedrecs);
2780 yaz_query_to_wrbuf(wr, req->query);
2782 yaz_log(log_request, "Search %s", wrbuf_cstr(wr));
2789 * Maybe we got a little over-friendly when we designed bend_fetch to
2790 * get only one record at a time. Some backends can optimise multiple-record
2791 * fetches, and at any rate, there is some overhead involved in
2792 * all that selecting and hopping around. Problem is, of course, that the
2793 * frontend can't know ahead of time how many records it'll need to
2794 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
2795 * is downright lousy as a bulk data transfer protocol.
2797 * To start with, we'll do the fetching of records from the backend
2798 * in one operation: To save some trips in and out of the event-handler,
2799 * and to simplify the interface to pack_records. At any rate, asynch
2800 * operation is more fun in operations that have an unpredictable execution
2801 * speed - which is normally more true for search than for present.
2803 static Z_APDU *process_presentRequest(association *assoc, request *reqb)
2805 Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
2807 Z_PresentResponse *resp;
2811 const char *errstring = 0;
2813 yaz_log(log_requestdetail, "Got PresentRequest.");
2815 resp = (Z_PresentResponse *)odr_malloc(assoc->encode, sizeof(*resp));
2817 resp->presentStatus = odr_intdup(assoc->encode, 0);
2818 if (assoc->init->bend_present)
2820 bend_present_rr *bprr = (bend_present_rr *)
2821 nmem_malloc(reqb->request_mem, sizeof(*bprr));
2822 bprr->setname = req->resultSetId;
2823 bprr->start = *req->resultSetStartPoint;
2824 bprr->number = *req->numberOfRecordsRequested;
2825 bprr->format = req->preferredRecordSyntax;
2826 bprr->comp = req->recordComposition;
2827 bprr->referenceId = req->referenceId;
2828 bprr->stream = assoc->encode;
2829 bprr->print = assoc->print;
2830 bprr->association = assoc;
2832 bprr->errstring = NULL;
2833 (*assoc->init->bend_present)(assoc->backend, bprr);
2837 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2838 *resp->presentStatus = Z_PresentStatus_failure;
2839 errcode = bprr->errcode;
2840 errstring = bprr->errstring;
2843 apdu = (Z_APDU *)odr_malloc(assoc->encode, sizeof(*apdu));
2844 next = odr_intdup(assoc->encode, 0);
2845 num = odr_intdup(assoc->encode, 0);
2847 apdu->which = Z_APDU_presentResponse;
2848 apdu->u.presentResponse = resp;
2849 resp->referenceId = req->referenceId;
2850 resp->otherInfo = 0;
2854 *num = *req->numberOfRecordsRequested;
2856 pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
2857 num, req->recordComposition, next,
2858 resp->presentStatus,
2859 req->referenceId, req->preferredRecordSyntax,
2864 WRBUF wr = wrbuf_alloc();
2865 wrbuf_printf(wr, "Present ");
2867 if (*resp->presentStatus == Z_PresentStatus_failure)
2868 wrbuf_printf(wr, "ERROR %d ", errcode);
2869 else if (*resp->presentStatus == Z_PresentStatus_success)
2870 wrbuf_printf(wr, "OK - ");
2872 wrbuf_printf(wr, "Partial " ODR_INT_PRINTF " - ",
2873 *resp->presentStatus);
2875 wrbuf_printf(wr, " %s " ODR_INT_PRINTF "+" ODR_INT_PRINTF " ",
2876 req->resultSetId, *req->resultSetStartPoint,
2877 *req->numberOfRecordsRequested);
2878 yaz_log(log_request, "%s", wrbuf_cstr(wr) );
2883 resp->numberOfRecordsReturned = num;
2884 resp->nextResultSetPosition = next;
2890 * Scan was implemented rather in a hurry, and with support for only the basic
2891 * elements of the service in the backend API. Suggestions are welcome.
2893 static Z_APDU *process_scanRequest(association *assoc, request *reqb)
2895 Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
2896 Z_APDU *apdu = (Z_APDU *)odr_malloc(assoc->encode, sizeof(*apdu));
2897 Z_ScanResponse *res = (Z_ScanResponse *)
2898 odr_malloc(assoc->encode, sizeof(*res));
2899 Odr_int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
2900 Odr_int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
2901 Z_ListEntries *ents = (Z_ListEntries *)
2902 odr_malloc(assoc->encode, sizeof(*ents));
2903 Z_DiagRecs *diagrecs_p = NULL;
2904 bend_scan_rr *bsrr = (bend_scan_rr *)
2905 odr_malloc(assoc->encode, sizeof(*bsrr));
2906 struct scan_entry *save_entries;
2908 yaz_log(log_requestdetail, "Got ScanRequest");
2910 apdu->which = Z_APDU_scanResponse;
2911 apdu->u.scanResponse = res;
2912 res->referenceId = req->referenceId;
2914 /* if step is absent, set it to 0 */
2915 res->stepSize = odr_intdup(assoc->encode, 0);
2917 *res->stepSize = *req->stepSize;
2919 res->scanStatus = scanStatus;
2920 res->numberOfEntriesReturned = numberOfEntriesReturned;
2921 res->positionOfTerm = 0;
2922 res->entries = ents;
2923 ents->num_entries = 0;
2924 ents->entries = NULL;
2925 ents->num_nonsurrogateDiagnostics = 0;
2926 ents->nonsurrogateDiagnostics = NULL;
2927 res->attributeSet = 0;
2930 if (req->databaseNames)
2933 for (i = 0; i < req->num_databaseNames; i++)
2934 yaz_log(log_requestdetail, "Database '%s'", req->databaseNames[i]);
2936 bsrr->scanClause = 0;
2938 bsrr->errstring = 0;
2939 bsrr->num_bases = req->num_databaseNames;
2940 bsrr->basenames = req->databaseNames;
2941 bsrr->num_entries = *req->numberOfTermsRequested;
2942 bsrr->term = req->termListAndStartPoint;
2943 bsrr->referenceId = req->referenceId;
2944 bsrr->stream = assoc->encode;
2945 bsrr->print = assoc->print;
2946 bsrr->step_size = res->stepSize;
2947 bsrr->setname = yaz_oi_get_string_oid(&req->otherInfo,
2948 yaz_oid_userinfo_scan_set, 1, 0);
2950 /* For YAZ 2.0 and earlier it was the backend handler that
2951 initialized entries (member display_term did not exist)
2952 YAZ 2.0 and later sets 'entries' and initialize all members
2953 including 'display_term'. If YAZ 2.0 or later sees that
2954 entries was modified - we assume that it is an old handler and
2955 that 'display_term' is _not_ set.
2957 if (bsrr->num_entries > 0)
2960 bsrr->entries = (struct scan_entry *)
2961 odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
2963 for (i = 0; i<bsrr->num_entries; i++)
2965 bsrr->entries[i].term = 0;
2966 bsrr->entries[i].occurrences = 0;
2967 bsrr->entries[i].errcode = 0;
2968 bsrr->entries[i].errstring = 0;
2969 bsrr->entries[i].display_term = 0;
2972 save_entries = bsrr->entries; /* save it so we can compare later */
2974 bsrr->attributeset = req->attributeSet;
2975 log_scan_term_level(log_requestdetail, req->termListAndStartPoint,
2976 bsrr->attributeset);
2977 bsrr->term_position = req->preferredPositionInResponse ?
2978 *req->preferredPositionInResponse : 1;
2980 ((int (*)(void *, bend_scan_rr *))
2981 (*assoc->init->bend_scan))(assoc->backend, bsrr);
2984 diagrecs_p = zget_DiagRecs(assoc->encode,
2985 bsrr->errcode, bsrr->errstring);
2989 Z_Entry **tab = (Z_Entry **)
2990 odr_malloc(assoc->encode, sizeof(*tab) * bsrr->num_entries);
2992 if (bsrr->status == BEND_SCAN_PARTIAL)
2993 *scanStatus = Z_Scan_partial_5;
2995 *scanStatus = Z_Scan_success;
2996 ents->entries = tab;
2997 ents->num_entries = bsrr->num_entries;
2998 res->numberOfEntriesReturned = odr_intdup(assoc->encode,
3000 res->positionOfTerm = &bsrr->term_position;
3001 for (i = 0; i < bsrr->num_entries; i++)
3007 tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
3008 if (bsrr->entries[i].occurrences >= 0)
3010 e->which = Z_Entry_termInfo;
3011 e->u.termInfo = t = (Z_TermInfo *)
3012 odr_malloc(assoc->encode, sizeof(*t));
3013 t->suggestedAttributes = 0;
3015 if (save_entries == bsrr->entries &&
3016 bsrr->entries[i].display_term)
3018 /* the entries was _not_ set by the handler. So it's
3019 safe to test for new member display_term. It is
3022 t->displayTerm = odr_strdup(assoc->encode,
3023 bsrr->entries[i].display_term);
3025 t->alternativeTerm = 0;
3026 t->byAttributes = 0;
3027 t->otherTermInfo = 0;
3028 t->globalOccurrences = &bsrr->entries[i].occurrences;
3029 t->term = (Z_Term *)
3030 odr_malloc(assoc->encode, sizeof(*t->term));
3031 t->term->which = Z_Term_general;
3032 t->term->u.general = o =
3033 (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
3034 o->buf = (unsigned char *)
3035 odr_malloc(assoc->encode, o->len = o->size =
3036 strlen(bsrr->entries[i].term));
3037 memcpy(o->buf, bsrr->entries[i].term, o->len);
3038 yaz_log(YLOG_DEBUG, " term #%d: '%s' (" ODR_INT_PRINTF ")", i,
3039 bsrr->entries[i].term, bsrr->entries[i].occurrences);
3043 Z_DiagRecs *drecs = zget_DiagRecs(assoc->encode,
3044 bsrr->entries[i].errcode,
3045 bsrr->entries[i].errstring);
3046 assert(drecs->num_diagRecs == 1);
3047 e->which = Z_Entry_surrogateDiagnostic;
3048 assert(drecs->diagRecs[0]);
3049 e->u.surrogateDiagnostic = drecs->diagRecs[0];
3055 ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
3056 ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
3061 WRBUF wr = wrbuf_alloc();
3062 wrbuf_printf(wr, "Scan ");
3063 for (i = 0 ; i < req->num_databaseNames; i++)
3066 wrbuf_printf(wr, "+");
3067 wrbuf_puts(wr, req->databaseNames[i]);
3070 wrbuf_printf(wr, " ");
3073 wr_diag(wr, bsrr->errcode, bsrr->errstring);
3075 wrbuf_printf(wr, "OK");
3077 wrbuf_printf(wr, " " ODR_INT_PRINTF " - " ODR_INT_PRINTF "+"
3078 ODR_INT_PRINTF "+" ODR_INT_PRINTF,
3079 res->numberOfEntriesReturned ?
3080 *res->numberOfEntriesReturned : 0,
3081 (req->preferredPositionInResponse ?
3082 *req->preferredPositionInResponse : 1),
3083 *req->numberOfTermsRequested,
3084 (res->stepSize ? *res->stepSize : 1));
3087 wrbuf_printf(wr, "+%s", bsrr->setname);
3089 wrbuf_printf(wr, " ");
3090 yaz_scan_to_wrbuf(wr, req->termListAndStartPoint,
3091 bsrr->attributeset);
3092 yaz_log(log_request, "%s", wrbuf_cstr(wr) );
3098 static Z_APDU *process_sortRequest(association *assoc, request *reqb)
3101 Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
3102 Z_SortResponse *res = (Z_SortResponse *)
3103 odr_malloc(assoc->encode, sizeof(*res));
3104 bend_sort_rr *bsrr = (bend_sort_rr *)
3105 odr_malloc(assoc->encode, sizeof(*bsrr));
3107 Z_APDU *apdu = (Z_APDU *)odr_malloc(assoc->encode, sizeof(*apdu));
3109 yaz_log(log_requestdetail, "Got SortRequest.");
3111 bsrr->num_input_setnames = req->num_inputResultSetNames;
3112 for (i=0;i<req->num_inputResultSetNames;i++)
3113 yaz_log(log_requestdetail, "Input resultset: '%s'",
3114 req->inputResultSetNames[i]);
3115 bsrr->input_setnames = req->inputResultSetNames;
3116 bsrr->referenceId = req->referenceId;
3117 bsrr->output_setname = req->sortedResultSetName;
3118 yaz_log(log_requestdetail, "Output resultset: '%s'",
3119 req->sortedResultSetName);
3120 bsrr->sort_sequence = req->sortSequence;
3121 /*FIXME - dump those sequences too */
3122 bsrr->stream = assoc->encode;
3123 bsrr->print = assoc->print;
3125 bsrr->sort_status = Z_SortResponse_failure;
3127 bsrr->errstring = 0;
3129 (*assoc->init->bend_sort)(assoc->backend, bsrr);
3131 res->referenceId = bsrr->referenceId;
3132 res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
3133 res->resultSetStatus = 0;
3136 Z_DiagRecs *dr = zget_DiagRecs(assoc->encode,
3137 bsrr->errcode, bsrr->errstring);
3138 res->diagnostics = dr->diagRecs;
3139 res->num_diagnostics = dr->num_diagRecs;
3143 res->num_diagnostics = 0;
3144 res->diagnostics = 0;
3146 res->resultCount = 0;
3149 apdu->which = Z_APDU_sortResponse;
3150 apdu->u.sortResponse = res;
3153 WRBUF wr = wrbuf_alloc();
3154 wrbuf_printf(wr, "Sort ");
3156 wrbuf_printf(wr, " ERROR %d", bsrr->errcode);
3158 wrbuf_printf(wr, "OK -");
3159 wrbuf_printf(wr, " (");
3160 for (i = 0; i<req->num_inputResultSetNames; i++)
3163 wrbuf_printf(wr, "+");
3164 wrbuf_puts(wr, req->inputResultSetNames[i]);
3166 wrbuf_printf(wr, ")->%s ",req->sortedResultSetName);
3168 yaz_log(log_request, "%s", wrbuf_cstr(wr) );
3174 static Z_APDU *process_deleteRequest(association *assoc, request *reqb)
3177 Z_DeleteResultSetRequest *req =
3178 reqb->apdu_request->u.deleteResultSetRequest;
3179 Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
3180 odr_malloc(assoc->encode, sizeof(*res));
3181 bend_delete_rr *bdrr = (bend_delete_rr *)
3182 odr_malloc(assoc->encode, sizeof(*bdrr));
3183 Z_APDU *apdu = (Z_APDU *)odr_malloc(assoc->encode, sizeof(*apdu));
3185 yaz_log(log_requestdetail, "Got DeleteRequest.");
3187 bdrr->num_setnames = req->num_resultSetList;
3188 bdrr->setnames = req->resultSetList;
3189 for (i = 0; i<req->num_resultSetList; i++)
3190 yaz_log(log_requestdetail, "resultset: '%s'",
3191 req->resultSetList[i]);
3192 bdrr->stream = assoc->encode;
3193 bdrr->print = assoc->print;
3194 bdrr->function = *req->deleteFunction;
3195 bdrr->referenceId = req->referenceId;
3197 if (bdrr->num_setnames > 0)
3199 bdrr->statuses = (Odr_int*)
3200 odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
3201 bdrr->num_setnames);
3202 for (i = 0; i < bdrr->num_setnames; i++)
3203 bdrr->statuses[i] = 0;
3205 (*assoc->init->bend_delete)(assoc->backend, bdrr);
3207 res->referenceId = req->referenceId;
3209 res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
3211 res->deleteListStatuses = 0;
3212 if (bdrr->num_setnames > 0)
3215 res->deleteListStatuses = (Z_ListStatuses *)
3216 odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
3217 res->deleteListStatuses->num = bdrr->num_setnames;
3218 res->deleteListStatuses->elements =
3220 odr_malloc(assoc->encode,
3221 sizeof(*res->deleteListStatuses->elements) *
3222 bdrr->num_setnames);
3223 for (i = 0; i<bdrr->num_setnames; i++)
3225 res->deleteListStatuses->elements[i] =
3227 odr_malloc(assoc->encode,
3228 sizeof(**res->deleteListStatuses->elements));
3229 res->deleteListStatuses->elements[i]->status = bdrr->statuses+i;
3230 res->deleteListStatuses->elements[i]->id =
3231 odr_strdup(assoc->encode, bdrr->setnames[i]);
3234 res->numberNotDeleted = 0;
3235 res->bulkStatuses = 0;
3236 res->deleteMessage = 0;
3239 apdu->which = Z_APDU_deleteResultSetResponse;
3240 apdu->u.deleteResultSetResponse = res;
3243 WRBUF wr = wrbuf_alloc();
3244 wrbuf_printf(wr, "Delete ");
3245 if (bdrr->delete_status)
3246 wrbuf_printf(wr, "ERROR %d", bdrr->delete_status);
3248 wrbuf_printf(wr, "OK -");
3249 for (i = 0; i<req->num_resultSetList; i++)
3250 wrbuf_printf(wr, " %s ", req->resultSetList[i]);
3251 yaz_log(log_request, "%s", wrbuf_cstr(wr) );
3257 static void process_close(association *assoc, request *reqb)
3259 Z_Close *req = reqb->apdu_request->u.close;
3260 static char *reasons[] =
3267 "securityViolation",
3274 yaz_log(log_requestdetail, "Got Close, reason %s, message %s",
3275 reasons[*req->closeReason], req->diagnosticInformation ?
3276 req->diagnosticInformation : "NULL");
3277 if (assoc->version < 3) /* to make do_force respond with close */
3279 do_close_req(assoc, Z_Close_finished,
3280 "Association terminated by client", reqb);
3281 yaz_log(log_request,"Close OK");
3284 static Z_APDU *process_segmentRequest(association *assoc, request *reqb)
3286 bend_segment_rr req;
3288 req.segment = reqb->apdu_request->u.segmentRequest;
3289 req.stream = assoc->encode;
3290 req.decode = assoc->decode;
3291 req.print = assoc->print;
3292 req.association = assoc;
3294 (*assoc->init->bend_segment)(assoc->backend, &req);
3299 static Z_APDU *process_ESRequest(association *assoc, request *reqb)
3301 bend_esrequest_rr esrequest;
3302 const char *ext_name = "unknown";
3304 Z_ExtendedServicesRequest *req =
3305 reqb->apdu_request->u.extendedServicesRequest;
3306 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
3308 Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
3310 esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
3311 esrequest.stream = assoc->encode;
3312 esrequest.decode = assoc->decode;
3313 esrequest.print = assoc->print;
3314 esrequest.errcode = 0;
3315 esrequest.errstring = NULL;
3316 esrequest.association = assoc;
3317 esrequest.taskPackage = 0;
3318 esrequest.referenceId = req->referenceId;
3320 if (esrequest.esr && esrequest.esr->taskSpecificParameters)
3322 switch(esrequest.esr->taskSpecificParameters->which)
3324 case Z_External_itemOrder:
3325 ext_name = "ItemOrder"; break;
3326 case Z_External_update:
3327 ext_name = "Update"; break;
3328 case Z_External_update0:
3329 ext_name = "Update0"; break;
3330 case Z_External_ESAdmin:
3331 ext_name = "Admin"; break;
3336 (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
3338 resp->referenceId = req->referenceId;
3340 if (esrequest.errcode == -1)
3342 /* Backend service indicates request will be processed */
3343 yaz_log(log_request, "Extended Service: %s (accepted)", ext_name);
3344 *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
3346 else if (esrequest.errcode == 0)
3348 /* Backend service indicates request will be processed */
3349 yaz_log(log_request, "Extended Service: %s (done)", ext_name);
3350 *resp->operationStatus = Z_ExtendedServicesResponse_done;
3354 Z_DiagRecs *diagRecs =
3355 zget_DiagRecs(assoc->encode, esrequest.errcode,
3356 esrequest.errstring);
3357 /* Backend indicates error, request will not be processed */
3358 yaz_log(log_request, "Extended Service: %s (failed)", ext_name);
3359 *resp->operationStatus = Z_ExtendedServicesResponse_failure;
3360 resp->num_diagnostics = diagRecs->num_diagRecs;
3361 resp->diagnostics = diagRecs->diagRecs;
3364 WRBUF wr = wrbuf_alloc();
3365 wrbuf_diags(wr, resp->num_diagnostics, resp->diagnostics);
3366 yaz_log(log_request, "EsRequest %s", wrbuf_cstr(wr) );
3371 /* Do something with the members of bend_extendedservice */
3372 if (esrequest.taskPackage)
3374 resp->taskPackage = z_ext_record_oid(
3375 assoc->encode, yaz_oid_recsyn_extended,
3376 (const char *) esrequest.taskPackage, -1);
3378 yaz_log(YLOG_DEBUG,"Send the result apdu");
3382 int bend_assoc_is_alive(bend_association assoc)
3384 if (assoc->state == ASSOC_DEAD)
3385 return 0; /* already marked as dead. Don't check I/O chan anymore */
3387 return iochan_is_alive(assoc->client_chan);
3394 * c-file-style: "Stroustrup"
3395 * indent-tabs-mode: nil
3397 * vim: shiftwidth=4 tabstop=8 expandtab