1 /* This file is part of the YAZ toolkit.
2 * Copyright (C) 1995-2009 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 void backend_response(IOCHAN i, int event);
82 static int process_gdu_response(association *assoc, request *req, Z_GDU *res);
83 static int process_z_response(association *assoc, request *req, Z_APDU *res);
84 static Z_APDU *process_initRequest(association *assoc, request *reqb);
85 static Z_External *init_diagnostics(ODR odr, int errcode,
86 const char *errstring);
87 static Z_APDU *process_searchRequest(association *assoc, request *reqb);
88 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
89 bend_search_rr *bsrr);
90 static Z_APDU *process_presentRequest(association *assoc, request *reqb);
91 static Z_APDU *process_scanRequest(association *assoc, request *reqb);
92 static Z_APDU *process_sortRequest(association *assoc, request *reqb);
93 static void process_close(association *assoc, request *reqb);
94 static Z_APDU *process_deleteRequest(association *assoc, request *reqb);
95 static Z_APDU *process_segmentRequest(association *assoc, request *reqb);
96 static Z_APDU *process_ESRequest(association *assoc, request *reqb);
98 /* dynamic logging levels */
99 static int logbits_set = 0;
100 static int log_session = 0; /* one-line logs for session */
101 static int log_sessiondetail = 0; /* more detailed stuff */
102 static int log_request = 0; /* one-line logs for requests */
103 static int log_requestdetail = 0; /* more detailed stuff */
105 /** get_logbits sets global loglevel bits */
106 static void get_logbits(void)
107 { /* needs to be called after parsing cmd-line args that can set loglevels!*/
111 log_session = yaz_log_module_level("session");
112 log_sessiondetail = yaz_log_module_level("sessiondetail");
113 log_request = yaz_log_module_level("request");
114 log_requestdetail = yaz_log_module_level("requestdetail");
120 static void wr_diag(WRBUF w, int error, const char *addinfo)
122 wrbuf_printf(w, "ERROR %d+", error);
123 wrbuf_puts_replace_char(w, diagbib1_str(error), ' ', '_');
126 wrbuf_puts_replace_char(w, addinfo, ' ', '_');
134 * Create and initialize a new association-handle.
135 * channel : iochannel for the current line.
136 * link : communications channel.
137 * Returns: 0 or a new association handle.
139 association *create_association(IOCHAN channel, COMSTACK link,
140 const char *apdufile)
146 if (!(anew = (association *)xmalloc(sizeof(*anew))))
150 anew->last_control = 0;
151 anew->client_chan = channel;
152 anew->client_link = link;
153 anew->cs_get_mask = 0;
154 anew->cs_put_mask = 0;
155 anew->cs_accept_mask = 0;
156 if (!(anew->decode = odr_createmem(ODR_DECODE)) ||
157 !(anew->encode = odr_createmem(ODR_ENCODE)))
159 if (apdufile && *apdufile)
163 if (!(anew->print = odr_createmem(ODR_PRINT)))
165 if (*apdufile == '@')
167 odr_setprint(anew->print, yaz_log_file());
169 else if (*apdufile != '-')
172 sprintf(filename, "%.200s.%ld", apdufile, (long)getpid());
173 if (!(f = fopen(filename, "w")))
175 yaz_log(YLOG_WARN|YLOG_ERRNO, "%s", filename);
178 setvbuf(f, 0, _IONBF, 0);
179 odr_setprint(anew->print, f);
184 anew->input_buffer = 0;
185 anew->input_buffer_len = 0;
187 anew->state = ASSOC_NEW;
188 request_initq(&anew->incoming);
189 request_initq(&anew->outgoing);
190 anew->proto = cs_getproto(link);
196 * Free association and release resources.
198 void destroy_association(association *h)
200 statserv_options_block *cb = statserv_getcontrol();
204 odr_destroy(h->decode);
205 odr_destroy(h->encode);
207 odr_destroy(h->print);
209 xfree(h->input_buffer);
211 (*cb->bend_close)(h->backend);
212 while ((req = request_deq(&h->incoming)))
213 request_release(req);
214 while ((req = request_deq(&h->outgoing)))
215 request_release(req);
216 request_delq(&h->incoming);
217 request_delq(&h->outgoing);
219 xmalloc_trav("session closed");
220 if (cb && cb->one_shot)
226 static void do_close_req(association *a, int reason, char *message,
230 Z_Close *cls = zget_Close(a->encode);
232 /* Purge request queue */
233 while (request_deq(&a->incoming));
234 while (request_deq(&a->outgoing));
237 yaz_log(log_requestdetail, "Sending Close PDU, reason=%d, message=%s",
238 reason, message ? message : "none");
239 apdu.which = Z_APDU_close;
241 *cls->closeReason = reason;
242 cls->diagnosticInformation = message;
243 process_z_response(a, req, &apdu);
244 iochan_settimeout(a->client_chan, 20);
248 request_release(req);
249 yaz_log(log_requestdetail, "v2 client. No Close PDU");
250 iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
253 a->state = ASSOC_DEAD;
256 static void do_close(association *a, int reason, char *message)
258 request *req = request_get(&a->outgoing);
259 do_close_req (a, reason, message, req);
263 int ir_read(IOCHAN h, int event)
265 association *assoc = (association *)iochan_getdata(h);
266 COMSTACK conn = assoc->client_link;
269 if ((assoc->cs_put_mask & EVENT_INPUT) == 0 && (event & assoc->cs_get_mask))
271 yaz_log(YLOG_DEBUG, "ir_session (input)");
272 /* We aren't speaking to this fellow */
273 if (assoc->state == ASSOC_DEAD)
275 yaz_log(log_sessiondetail, "Connection closed - end of session");
277 destroy_association(assoc);
281 assoc->cs_get_mask = EVENT_INPUT;
285 int res = cs_get(conn, &assoc->input_buffer,
286 &assoc->input_buffer_len);
287 if (res < 0 && cs_errno(conn) == CSBUFSIZE)
289 yaz_log(log_session, "Connection error: %s res=%d",
290 cs_errmsg(cs_errno(conn)), res);
291 req = request_get(&assoc->incoming); /* get a new request */
292 do_close_req(assoc, Z_Close_protocolError,
293 "Incoming package too large", req);
298 yaz_log(log_session, "Connection closed by client");
299 assoc->state = ASSOC_DEAD;
302 else if (res == 1) /* incomplete read - wait for more */
304 if (conn->io_pending & CS_WANT_WRITE)
305 assoc->cs_get_mask |= EVENT_OUTPUT;
306 iochan_setflag(h, assoc->cs_get_mask);
309 /* we got a complete PDU. Let's decode it */
310 yaz_log(YLOG_DEBUG, "Got PDU, %d bytes: lead=%02X %02X %02X", res,
311 assoc->input_buffer[0] & 0xff,
312 assoc->input_buffer[1] & 0xff,
313 assoc->input_buffer[2] & 0xff);
314 req = request_get(&assoc->incoming); /* get a new request */
315 odr_reset(assoc->decode);
316 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
317 if (!z_GDU(assoc->decode, &req->gdu_request, 0, 0))
319 yaz_log(YLOG_WARN, "ODR error on incoming PDU: %s [element %s] "
321 odr_errmsg(odr_geterror(assoc->decode)),
322 odr_getelement(assoc->decode),
323 (long) odr_offset(assoc->decode));
324 if (assoc->decode->error != OHTTP)
326 yaz_log(YLOG_WARN, "PDU dump:");
327 odr_dumpBER(yaz_log_file(), assoc->input_buffer, res);
328 request_release(req);
329 do_close(assoc, Z_Close_protocolError, "Malformed package");
333 Z_GDU *p = z_get_HTTP_Response(assoc->encode, 400);
334 assoc->state = ASSOC_DEAD;
335 process_gdu_response(assoc, req, p);
339 req->request_mem = odr_extract_mem(assoc->decode);
342 if (!z_GDU(assoc->print, &req->gdu_request, 0, 0))
343 yaz_log(YLOG_WARN, "ODR print error: %s",
344 odr_errmsg(odr_geterror(assoc->print)));
345 odr_reset(assoc->print);
347 request_enq(&assoc->incoming, req);
349 while (cs_more(conn));
355 * This is where PDUs from the client are read and the further
356 * processing is initiated. Flow of control moves down through the
357 * various process_* functions below, until the encoded result comes back up
358 * to the output handler in here.
360 * h : the I/O channel that has an outstanding event.
361 * event : the current outstanding event.
363 void ir_session(IOCHAN h, int event)
366 association *assoc = (association *)iochan_getdata(h);
367 COMSTACK conn = assoc->client_link;
370 assert(h && conn && assoc);
371 if (event == EVENT_TIMEOUT)
373 if (assoc->state != ASSOC_UP)
375 yaz_log(log_session, "Timeout. Closing connection");
376 /* do we need to lod this at all */
378 destroy_association(assoc);
383 yaz_log(log_sessiondetail, "Timeout. Sending Z39.50 Close");
384 do_close(assoc, Z_Close_lackOfActivity, 0);
388 if (event & assoc->cs_accept_mask)
390 if (!cs_accept(conn))
392 yaz_log(YLOG_WARN, "accept failed");
393 destroy_association(assoc);
397 iochan_clearflag(h, EVENT_OUTPUT);
398 if (conn->io_pending)
399 { /* cs_accept didn't complete */
400 assoc->cs_accept_mask =
401 ((conn->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
402 ((conn->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
404 iochan_setflag(h, assoc->cs_accept_mask);
407 { /* cs_accept completed. Prepare for reading (cs_get) */
408 assoc->cs_accept_mask = 0;
409 assoc->cs_get_mask = EVENT_INPUT;
410 iochan_setflag(h, assoc->cs_get_mask);
414 if (event & assoc->cs_get_mask) /* input */
416 if (!ir_read(h, event))
418 req = request_head(&assoc->incoming);
419 if (req->state == REQUEST_IDLE)
421 request_deq(&assoc->incoming);
422 process_gdu_request(assoc, req);
425 if (event & assoc->cs_put_mask)
427 request *req = request_head(&assoc->outgoing);
429 assoc->cs_put_mask = 0;
430 yaz_log(YLOG_DEBUG, "ir_session (output)");
431 req->state = REQUEST_PENDING;
432 switch (res = cs_put(conn, req->response, req->len_response))
435 yaz_log(log_sessiondetail, "Connection closed by client");
437 destroy_association(assoc);
440 case 0: /* all sent - release the request structure */
441 yaz_log(YLOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
443 yaz_log(YLOG_DEBUG, "HTTP out:\n%.*s", req->len_response,
446 nmem_destroy(req->request_mem);
447 request_deq(&assoc->outgoing);
448 request_release(req);
449 if (!request_head(&assoc->outgoing))
450 { /* restore mask for cs_get operation ... */
451 iochan_clearflag(h, EVENT_OUTPUT|EVENT_INPUT);
452 iochan_setflag(h, assoc->cs_get_mask);
453 if (assoc->state == ASSOC_DEAD)
454 iochan_setevent(assoc->client_chan, EVENT_TIMEOUT);
458 assoc->cs_put_mask = EVENT_OUTPUT;
462 if (conn->io_pending & CS_WANT_WRITE)
463 assoc->cs_put_mask |= EVENT_OUTPUT;
464 if (conn->io_pending & CS_WANT_READ)
465 assoc->cs_put_mask |= EVENT_INPUT;
466 iochan_setflag(h, assoc->cs_put_mask);
469 if (event & EVENT_EXCEPT)
471 yaz_log(YLOG_WARN, "ir_session (exception)");
473 destroy_association(assoc);
478 static int process_z_request(association *assoc, request *req, char **msg);
481 static void assoc_init_reset(association *assoc)
484 assoc->init = (bend_initrequest *) xmalloc(sizeof(*assoc->init));
486 assoc->init->stream = assoc->encode;
487 assoc->init->print = assoc->print;
488 assoc->init->auth = 0;
489 assoc->init->referenceId = 0;
490 assoc->init->implementation_version = 0;
491 assoc->init->implementation_id = 0;
492 assoc->init->implementation_name = 0;
493 assoc->init->query_charset = 0;
494 assoc->init->records_in_same_charset = 0;
495 assoc->init->bend_sort = NULL;
496 assoc->init->bend_search = NULL;
497 assoc->init->bend_present = NULL;
498 assoc->init->bend_esrequest = NULL;
499 assoc->init->bend_delete = NULL;
500 assoc->init->bend_scan = NULL;
501 assoc->init->bend_segment = NULL;
502 assoc->init->bend_fetch = NULL;
503 assoc->init->bend_explain = NULL;
504 assoc->init->bend_srw_scan = NULL;
505 assoc->init->bend_srw_update = NULL;
506 assoc->init->named_result_sets = 0;
508 assoc->init->charneg_request = NULL;
509 assoc->init->charneg_response = NULL;
511 assoc->init->decode = assoc->decode;
512 assoc->init->peer_name =
513 odr_strdup(assoc->encode, cs_addrstr(assoc->client_link));
515 yaz_log(log_requestdetail, "peer %s", assoc->init->peer_name);
518 static int srw_bend_init(association *assoc, Z_SRW_diagnostic **d, int *num, Z_SRW_PDU *sr)
520 statserv_options_block *cb = statserv_getcontrol();
523 const char *encoding = "UTF-8";
525 bend_initresult *binitres;
527 yaz_log(log_requestdetail, "srw_bend_init config=%s", cb->configname);
528 assoc_init_reset(assoc);
532 Z_IdAuthentication *auth = (Z_IdAuthentication *)
533 odr_malloc(assoc->decode, sizeof(*auth));
536 len = strlen(sr->username) + 1;
538 len += strlen(sr->password) + 2;
539 auth->which = Z_IdAuthentication_open;
540 auth->u.open = (char *) odr_malloc(assoc->decode, len);
541 strcpy(auth->u.open, sr->username);
542 if (sr->password && *sr->password)
544 strcat(auth->u.open, "/");
545 strcat(auth->u.open, sr->password);
547 assoc->init->auth = auth;
551 ce = yaz_set_proposal_charneg(assoc->decode, &encoding, 1, 0, 0, 1);
552 assoc->init->charneg_request = ce->u.charNeg3;
555 if (!(binitres = (*cb->bend_init)(assoc->init)))
557 assoc->state = ASSOC_DEAD;
558 yaz_add_srw_diagnostic(assoc->encode, d, num,
559 YAZ_SRW_AUTHENTICATION_ERROR, 0);
562 assoc->backend = binitres->handle;
563 assoc->init->auth = 0;
564 if (binitres->errcode)
566 int srw_code = yaz_diag_bib1_to_srw(binitres->errcode);
567 assoc->state = ASSOC_DEAD;
568 yaz_add_srw_diagnostic(assoc->encode, d, num, srw_code,
569 binitres->errstring);
577 static int retrieve_fetch(association *assoc, bend_fetch_rr *rr)
580 yaz_record_conv_t rc = 0;
581 const char *match_schema = 0;
582 Odr_oid *match_syntax = 0;
587 const char *input_schema = yaz_get_esn(rr->comp);
588 Odr_oid *input_syntax_raw = rr->request_format;
590 const char *backend_schema = 0;
591 Odr_oid *backend_syntax = 0;
593 r = yaz_retrieval_request(assoc->server->retrieval,
601 if (r == -1) /* error ? */
603 const char *details = yaz_retrieval_get_error(
604 assoc->server->retrieval);
606 rr->errcode = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
608 rr->errstring = odr_strdup(rr->stream, details);
611 else if (r == 1 || r == 3)
613 const char *details = input_schema;
615 YAZ_BIB1_SPECIFIED_ELEMENT_SET_NAME_NOT_VALID_FOR_SPECIFIED_;
617 rr->errstring = odr_strdup(rr->stream, details);
622 rr->errcode = YAZ_BIB1_RECORD_SYNTAX_UNSUPP;
623 if (input_syntax_raw)
625 char oidbuf[OID_STR_MAX];
626 oid_oid_to_dotstring(input_syntax_raw, oidbuf);
627 rr->errstring = odr_strdup(rr->stream, oidbuf);
633 yaz_set_esn(&rr->comp, backend_schema, odr_getmem(rr->stream));
636 rr->request_format = backend_syntax;
638 (*assoc->init->bend_fetch)(assoc->backend, rr);
639 if (rc && rr->record && rr->errcode == 0 && rr->len > 0)
640 { /* post conversion must take place .. */
641 WRBUF output_record = wrbuf_alloc();
642 int r = yaz_record_conv_record(rc, rr->record, rr->len, output_record);
645 const char *details = yaz_record_conv_get_error(rc);
646 rr->errcode = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
648 rr->errstring = odr_strdup(rr->stream, details);
652 rr->len = wrbuf_len(output_record);
653 rr->record = (char *) odr_malloc(rr->stream, rr->len);
654 memcpy(rr->record, wrbuf_buf(output_record), rr->len);
656 wrbuf_destroy(output_record);
659 rr->output_format = match_syntax;
661 rr->schema = odr_strdup(rr->stream, match_schema);
663 (*assoc->init->bend_fetch)(assoc->backend, rr);
668 static int srw_bend_fetch(association *assoc, int pos,
669 Z_SRW_searchRetrieveRequest *srw_req,
670 Z_SRW_record *record,
671 const char **addinfo)
674 ODR o = assoc->encode;
676 rr.setname = "default";
679 rr.request_format = odr_oiddup(assoc->decode, yaz_oid_recsyn_xml);
681 rr.comp = (Z_RecordComposition *)
682 odr_malloc(assoc->decode, sizeof(*rr.comp));
683 rr.comp->which = Z_RecordComp_complex;
684 rr.comp->u.complex = (Z_CompSpec *)
685 odr_malloc(assoc->decode, sizeof(Z_CompSpec));
686 rr.comp->u.complex->selectAlternativeSyntax = (bool_t *)
687 odr_malloc(assoc->encode, sizeof(bool_t));
688 *rr.comp->u.complex->selectAlternativeSyntax = 0;
689 rr.comp->u.complex->num_dbSpecific = 0;
690 rr.comp->u.complex->dbSpecific = 0;
691 rr.comp->u.complex->num_recordSyntax = 0;
692 rr.comp->u.complex->recordSyntax = 0;
694 rr.comp->u.complex->generic = (Z_Specification *)
695 odr_malloc(assoc->decode, sizeof(Z_Specification));
697 /* schema uri = recordSchema (or NULL if recordSchema is not given) */
698 rr.comp->u.complex->generic->which = Z_Schema_uri;
699 rr.comp->u.complex->generic->schema.uri = srw_req->recordSchema;
701 /* ESN = recordSchema if recordSchema is present */
702 rr.comp->u.complex->generic->elementSpec = 0;
703 if (srw_req->recordSchema)
705 rr.comp->u.complex->generic->elementSpec =
706 (Z_ElementSpec *) odr_malloc(assoc->encode, sizeof(Z_ElementSpec));
707 rr.comp->u.complex->generic->elementSpec->which =
708 Z_ElementSpec_elementSetName;
709 rr.comp->u.complex->generic->elementSpec->u.elementSetName =
710 srw_req->recordSchema;
713 rr.stream = assoc->encode;
714 rr.print = assoc->print;
722 rr.surrogate_flag = 0;
723 rr.schema = srw_req->recordSchema;
725 if (!assoc->init->bend_fetch)
728 retrieve_fetch(assoc, &rr);
730 if (rr.errcode && rr.surrogate_flag)
732 int code = yaz_diag_bib1_to_srw(rr.errcode);
733 yaz_mk_sru_surrogate(o, record, pos, code, rr.errstring);
736 else if (rr.len >= 0)
738 record->recordData_buf = rr.record;
739 record->recordData_len = rr.len;
740 record->recordPosition = odr_intdup(o, pos);
741 record->recordSchema = odr_strdup_null(
742 o, rr.schema ? rr.schema : srw_req->recordSchema);
746 *addinfo = rr.errstring;
752 static int cql2pqf(ODR odr, const char *cql, cql_transform_t ct,
753 Z_Query *query_result)
755 /* have a CQL query and CQL to PQF transform .. */
756 CQL_parser cp = cql_parser_create();
762 r = cql_parser_string(cp, cql);
765 srw_errcode = YAZ_SRW_QUERY_SYNTAX_ERROR;
770 r = cql_transform_buf(ct,
771 cql_parser_result(cp),
772 rpn_buf, sizeof(rpn_buf)-1);
774 srw_errcode = cql_transform_error(ct, &add);
778 /* Syntax & transform OK. */
779 /* Convert PQF string to Z39.50 to RPN query struct */
780 YAZ_PQF_Parser pp = yaz_pqf_create();
781 Z_RPNQuery *rpnquery = yaz_pqf_parse(pp, odr, rpn_buf);
786 int code = yaz_pqf_error(pp, &pqf_msg, &off);
787 yaz_log(YLOG_WARN, "PQF Parser Error %s (code %d)",
789 srw_errcode = YAZ_SRW_QUERY_SYNTAX_ERROR;
793 query_result->which = Z_Query_type_1;
794 query_result->u.type_1 = rpnquery;
798 cql_parser_destroy(cp);
802 static int cql2pqf_scan(ODR odr, const char *cql, cql_transform_t ct,
803 Z_AttributesPlusTerm *result)
807 int srw_error = cql2pqf(odr, cql, ct, &query);
810 if (query.which != Z_Query_type_1 && query.which != Z_Query_type_101)
811 return YAZ_SRW_QUERY_SYNTAX_ERROR; /* bad query type */
812 rpn = query.u.type_1;
813 if (!rpn->RPNStructure)
814 return YAZ_SRW_QUERY_SYNTAX_ERROR; /* must be structure */
815 if (rpn->RPNStructure->which != Z_RPNStructure_simple)
816 return YAZ_SRW_QUERY_SYNTAX_ERROR; /* must be simple */
817 if (rpn->RPNStructure->u.simple->which != Z_Operand_APT)
818 return YAZ_SRW_QUERY_SYNTAX_ERROR; /* must be be attributes + term */
819 memcpy(result, rpn->RPNStructure->u.simple->u.attributesPlusTerm,
825 static int ccl2pqf(ODR odr, const Odr_oct *ccl, CCL_bibset bibset,
826 bend_search_rr *bsrr) {
828 struct ccl_rpn_node *node;
831 ccl0 = odr_strdupn(odr, (char*) ccl->buf, ccl->len);
832 if ((node = ccl_find_str(bibset, ccl0, &errcode, &pos)) == 0) {
833 bsrr->errstring = (char*) ccl_err_msg(errcode);
834 return YAZ_SRW_QUERY_SYNTAX_ERROR; /* Query syntax error */
837 bsrr->query->which = Z_Query_type_1;
838 bsrr->query->u.type_1 = ccl_rpn_query(odr, node);
843 static void srw_bend_search(association *assoc, request *req,
848 Z_SRW_searchRetrieveResponse *srw_res = res->u.response;
851 Z_SRW_searchRetrieveRequest *srw_req = sr->u.request;
854 yaz_log(log_requestdetail, "Got SRW SearchRetrieveRequest");
855 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
856 if (srw_res->num_diagnostics == 0 && assoc->init)
859 rr.setname = "default";
862 rr.basenames = &srw_req->database;
866 rr.srw_setnameIdleTime = 0;
867 rr.estimated_hit_count = 0;
868 rr.partial_resultset = 0;
869 rr.query = (Z_Query *) odr_malloc(assoc->decode, sizeof(*rr.query));
870 rr.query->u.type_1 = 0;
871 rr.extra_args = sr->extra_args;
872 rr.extra_response_data = 0;
874 if (srw_req->query_type == Z_SRW_query_type_cql)
876 if (assoc->server && assoc->server->cql_transform)
878 int srw_errcode = cql2pqf(assoc->encode, srw_req->query.cql,
879 assoc->server->cql_transform,
883 yaz_add_srw_diagnostic(assoc->encode,
884 &srw_res->diagnostics,
885 &srw_res->num_diagnostics,
891 /* CQL query to backend. Wrap it - Z39.50 style */
892 ext = (Z_External *) odr_malloc(assoc->decode, sizeof(*ext));
893 ext->direct_reference = odr_getoidbystr(assoc->decode,
894 "1.2.840.10003.16.2");
895 ext->indirect_reference = 0;
897 ext->which = Z_External_CQL;
898 ext->u.cql = srw_req->query.cql;
900 rr.query->which = Z_Query_type_104;
901 rr.query->u.type_104 = ext;
904 else if (srw_req->query_type == Z_SRW_query_type_pqf)
906 Z_RPNQuery *RPNquery;
907 YAZ_PQF_Parser pqf_parser;
909 pqf_parser = yaz_pqf_create();
911 RPNquery = yaz_pqf_parse(pqf_parser, assoc->decode,
917 int code = yaz_pqf_error(pqf_parser, &pqf_msg, &off);
918 yaz_log(log_requestdetail, "Parse error %d %s near offset %ld",
919 code, pqf_msg, (long) off);
920 srw_error = YAZ_SRW_QUERY_SYNTAX_ERROR;
923 rr.query->which = Z_Query_type_1;
924 rr.query->u.type_1 = RPNquery;
926 yaz_pqf_destroy(pqf_parser);
930 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
931 &srw_res->num_diagnostics,
932 YAZ_SRW_UNSUPP_QUERY_TYPE, 0);
934 if (rr.query->u.type_1)
936 rr.stream = assoc->encode;
937 rr.decode = assoc->decode;
938 rr.print = assoc->print;
939 if ( srw_req->sort.sortKeys )
940 rr.srw_sortKeys = odr_strdup(assoc->encode,
941 srw_req->sort.sortKeys );
942 rr.association = assoc;
947 yaz_log_zquery_level(log_requestdetail,rr.query);
949 (assoc->init->bend_search)(assoc->backend, &rr);
952 if (rr.errcode == YAZ_BIB1_DATABASE_UNAVAILABLE)
958 srw_error = yaz_diag_bib1_to_srw(rr.errcode);
959 yaz_add_srw_diagnostic(assoc->encode,
960 &srw_res->diagnostics,
961 &srw_res->num_diagnostics,
962 srw_error, rr.errstring);
967 int number = srw_req->maximumRecords ? *srw_req->maximumRecords : 0;
968 int start = srw_req->startRecord ? *srw_req->startRecord : 1;
970 yaz_log(log_requestdetail, "Request to pack %d+%d out of "
972 start, number, rr.hits);
974 srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
977 srw_res->resultSetId =
978 odr_strdup(assoc->encode, rr.srw_setname );
979 srw_res->resultSetIdleTime =
980 odr_intdup(assoc->encode, *rr.srw_setnameIdleTime );
983 if (start > rr.hits || start < 1)
985 /* if hits<=0 and start=1 we don't return a diagnostic */
987 yaz_add_srw_diagnostic(
989 &srw_res->diagnostics, &srw_res->num_diagnostics,
990 YAZ_SRW_FIRST_RECORD_POSITION_OUT_OF_RANGE, 0);
996 if (start + number > rr.hits)
997 number = rr.hits - start + 1;
999 /* Call bend_present if defined */
1000 if (assoc->init->bend_present)
1002 bend_present_rr *bprr = (bend_present_rr*)
1003 odr_malloc(assoc->decode, sizeof(*bprr));
1004 bprr->setname = "default";
1005 bprr->start = start;
1006 bprr->number = number;
1007 if (srw_req->recordSchema)
1009 bprr->comp = (Z_RecordComposition *) odr_malloc(assoc->decode,
1010 sizeof(*bprr->comp));
1011 bprr->comp->which = Z_RecordComp_simple;
1012 bprr->comp->u.simple = (Z_ElementSetNames *)
1013 odr_malloc(assoc->decode, sizeof(Z_ElementSetNames));
1014 bprr->comp->u.simple->which = Z_ElementSetNames_generic;
1015 bprr->comp->u.simple->u.generic = srw_req->recordSchema;
1021 bprr->stream = assoc->encode;
1022 bprr->referenceId = 0;
1023 bprr->print = assoc->print;
1024 bprr->association = assoc;
1026 bprr->errstring = NULL;
1027 (*assoc->init->bend_present)(assoc->backend, bprr);
1031 srw_error = yaz_diag_bib1_to_srw(bprr->errcode);
1032 yaz_add_srw_diagnostic(assoc->encode,
1033 &srw_res->diagnostics,
1034 &srw_res->num_diagnostics,
1035 srw_error, bprr->errstring);
1043 int packing = Z_SRW_recordPacking_string;
1044 if (srw_req->recordPacking)
1047 yaz_srw_str_to_pack(srw_req->recordPacking);
1049 packing = Z_SRW_recordPacking_string;
1051 srw_res->records = (Z_SRW_record *)
1052 odr_malloc(assoc->encode,
1053 number * sizeof(*srw_res->records));
1055 srw_res->extra_records = (Z_SRW_extra_record **)
1056 odr_malloc(assoc->encode,
1057 number*sizeof(*srw_res->extra_records));
1059 for (i = 0; i<number; i++)
1062 const char *addinfo = 0;
1064 srw_res->records[j].recordPacking = packing;
1065 srw_res->records[j].recordData_buf = 0;
1066 srw_res->extra_records[j] = 0;
1067 yaz_log(YLOG_DEBUG, "srw_bend_fetch %d", i+start);
1068 errcode = srw_bend_fetch(assoc, i+start, srw_req,
1069 srw_res->records + j,
1073 yaz_add_srw_diagnostic(assoc->encode,
1074 &srw_res->diagnostics,
1075 &srw_res->num_diagnostics,
1076 yaz_diag_bib1_to_srw(errcode),
1081 if (srw_res->records[j].recordData_buf)
1084 srw_res->num_records = j;
1086 srw_res->records = 0;
1089 if (rr.extra_response_data)
1091 res->extraResponseData_buf = rr.extra_response_data;
1092 res->extraResponseData_len = strlen(rr.extra_response_data);
1094 if (rr.estimated_hit_count || rr.partial_resultset)
1096 yaz_add_srw_diagnostic(
1098 &srw_res->diagnostics,
1099 &srw_res->num_diagnostics,
1100 YAZ_SRW_RESULT_SET_CREATED_WITH_VALID_PARTIAL_RESULTS_AVAILABLE,
1108 const char *querystr = "?";
1109 const char *querytype = "?";
1110 WRBUF wr = wrbuf_alloc();
1112 switch (srw_req->query_type)
1114 case Z_SRW_query_type_cql:
1116 querystr = srw_req->query.cql;
1118 case Z_SRW_query_type_pqf:
1120 querystr = srw_req->query.pqf;
1123 wrbuf_printf(wr, "SRWSearch %s ", srw_req->database);
1124 if (srw_res->num_diagnostics)
1125 wrbuf_printf(wr, "ERROR %s", srw_res->diagnostics[0].uri);
1126 else if (*http_code != 200)
1127 wrbuf_printf(wr, "ERROR info:http/%d", *http_code);
1128 else if (srw_res->numberOfRecords)
1130 wrbuf_printf(wr, "OK " ODR_INT_PRINTF,
1131 (srw_res->numberOfRecords ?
1132 *srw_res->numberOfRecords : 0));
1134 wrbuf_printf(wr, " %s " ODR_INT_PRINTF " +%d",
1135 (srw_res->resultSetId ?
1136 srw_res->resultSetId : "-"),
1137 (srw_req->startRecord ? *srw_req->startRecord : 1),
1138 srw_res->num_records);
1139 yaz_log(log_request, "%s %s: %s", wrbuf_cstr(wr), querytype, querystr);
1144 static char *srw_bend_explain_default(void *handle, bend_explain_rr *rr)
1147 xmlNodePtr ptr = (xmlNode *) rr->server_node_ptr;
1150 for (ptr = ptr->children; ptr; ptr = ptr->next)
1152 if (ptr->type != XML_ELEMENT_NODE)
1154 if (!strcmp((const char *) ptr->name, "explain"))
1157 xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
1161 ptr = xmlCopyNode(ptr, 1);
1163 xmlDocSetRootElement(doc, ptr);
1165 xmlDocDumpMemory(doc, &buf_out, &len);
1166 content = (char*) odr_malloc(rr->stream, 1+len);
1167 memcpy(content, buf_out, len);
1168 content[len] = '\0';
1172 rr->explain_buf = content;
1180 static void srw_bend_explain(association *assoc, request *req,
1182 Z_SRW_explainResponse *srw_res,
1185 Z_SRW_explainRequest *srw_req = sr->u.explain_request;
1186 yaz_log(log_requestdetail, "Got SRW ExplainRequest");
1188 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1193 rr.stream = assoc->encode;
1194 rr.decode = assoc->decode;
1195 rr.print = assoc->print;
1197 rr.database = srw_req->database;
1199 rr.server_node_ptr = assoc->server->server_node_ptr;
1201 rr.server_node_ptr = 0;
1202 rr.schema = "http://explain.z3950.org/dtd/2.0/";
1203 if (assoc->init->bend_explain)
1204 (*assoc->init->bend_explain)(assoc->backend, &rr);
1206 srw_bend_explain_default(assoc->backend, &rr);
1210 int packing = Z_SRW_recordPacking_string;
1211 if (srw_req->recordPacking)
1214 yaz_srw_str_to_pack(srw_req->recordPacking);
1216 packing = Z_SRW_recordPacking_string;
1218 srw_res->record.recordSchema = rr.schema;
1219 srw_res->record.recordPacking = packing;
1220 srw_res->record.recordData_buf = rr.explain_buf;
1221 srw_res->record.recordData_len = strlen(rr.explain_buf);
1222 srw_res->record.recordPosition = 0;
1228 static void srw_bend_scan(association *assoc, request *req,
1230 Z_SRW_scanResponse *srw_res,
1233 Z_SRW_scanRequest *srw_req = sr->u.scan_request;
1234 yaz_log(log_requestdetail, "Got SRW ScanRequest");
1237 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1238 if (srw_res->num_diagnostics == 0 && assoc->init)
1240 struct scan_entry *save_entries;
1242 bend_scan_rr *bsrr = (bend_scan_rr *)
1243 odr_malloc(assoc->encode, sizeof(*bsrr));
1244 bsrr->num_bases = 1;
1245 bsrr->basenames = &srw_req->database;
1247 bsrr->num_entries = srw_req->maximumTerms ?
1248 *srw_req->maximumTerms : 10;
1249 bsrr->term_position = srw_req->responsePosition ?
1250 *srw_req->responsePosition : 1;
1253 bsrr->errstring = 0;
1254 bsrr->referenceId = 0;
1255 bsrr->stream = assoc->encode;
1256 bsrr->print = assoc->print;
1257 bsrr->step_size = odr_intdup(assoc->decode, 0);
1261 if (bsrr->num_entries > 0)
1264 bsrr->entries = (struct scan_entry *)
1265 odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
1267 for (i = 0; i<bsrr->num_entries; i++)
1269 bsrr->entries[i].term = 0;
1270 bsrr->entries[i].occurrences = 0;
1271 bsrr->entries[i].errcode = 0;
1272 bsrr->entries[i].errstring = 0;
1273 bsrr->entries[i].display_term = 0;
1276 save_entries = bsrr->entries; /* save it so we can compare later */
1278 if (srw_req->query_type == Z_SRW_query_type_pqf &&
1279 assoc->init->bend_scan)
1281 YAZ_PQF_Parser pqf_parser = yaz_pqf_create();
1283 bsrr->term = yaz_pqf_scan(pqf_parser, assoc->decode,
1284 &bsrr->attributeset,
1285 srw_req->scanClause.pqf);
1286 yaz_pqf_destroy(pqf_parser);
1287 bsrr->scanClause = 0;
1288 ((int (*)(void *, bend_scan_rr *))
1289 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1291 else if (srw_req->query_type == Z_SRW_query_type_cql
1292 && assoc->init->bend_scan && assoc->server
1293 && assoc->server->cql_transform)
1296 bsrr->scanClause = 0;
1297 bsrr->attributeset = 0;
1298 bsrr->term = (Z_AttributesPlusTerm *)
1299 odr_malloc(assoc->decode, sizeof(*bsrr->term));
1300 srw_error = cql2pqf_scan(assoc->encode,
1301 srw_req->scanClause.cql,
1302 assoc->server->cql_transform,
1305 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1306 &srw_res->num_diagnostics,
1310 ((int (*)(void *, bend_scan_rr *))
1311 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1314 else if (srw_req->query_type == Z_SRW_query_type_cql
1315 && assoc->init->bend_srw_scan)
1318 bsrr->attributeset = 0;
1319 bsrr->scanClause = srw_req->scanClause.cql;
1320 ((int (*)(void *, bend_scan_rr *))
1321 (*assoc->init->bend_srw_scan))(assoc->backend, bsrr);
1325 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1326 &srw_res->num_diagnostics,
1327 YAZ_SRW_UNSUPP_OPERATION, "scan");
1332 if (bsrr->errcode == YAZ_BIB1_DATABASE_UNAVAILABLE)
1337 srw_error = yaz_diag_bib1_to_srw(bsrr->errcode);
1339 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1340 &srw_res->num_diagnostics,
1341 srw_error, bsrr->errstring);
1343 else if (srw_res->num_diagnostics == 0 && bsrr->num_entries)
1346 srw_res->terms = (Z_SRW_scanTerm*)
1347 odr_malloc(assoc->encode, sizeof(*srw_res->terms) *
1350 srw_res->num_terms = bsrr->num_entries;
1351 for (i = 0; i<bsrr->num_entries; i++)
1353 Z_SRW_scanTerm *t = srw_res->terms + i;
1354 t->value = odr_strdup(assoc->encode, bsrr->entries[i].term);
1355 t->numberOfRecords =
1356 odr_intdup(assoc->encode, bsrr->entries[i].occurrences);
1358 if (save_entries == bsrr->entries &&
1359 bsrr->entries[i].display_term)
1361 /* the entries was _not_ set by the handler. So it's
1362 safe to test for new member display_term. It is
1365 t->displayTerm = odr_strdup(assoc->encode,
1366 bsrr->entries[i].display_term);
1374 WRBUF wr = wrbuf_alloc();
1375 const char *querytype = 0;
1376 const char *querystr = 0;
1378 switch(srw_req->query_type)
1380 case Z_SRW_query_type_pqf:
1382 querystr = srw_req->scanClause.pqf;
1384 case Z_SRW_query_type_cql:
1386 querystr = srw_req->scanClause.cql;
1389 querytype = "UNKNOWN";
1393 wrbuf_printf(wr, "SRWScan %s ", srw_req->database);
1395 if (srw_res->num_diagnostics)
1396 wrbuf_printf(wr, "ERROR %s - ", srw_res->diagnostics[0].uri);
1397 else if (srw_res->num_terms)
1398 wrbuf_printf(wr, "OK %d - ", srw_res->num_terms);
1400 wrbuf_printf(wr, "OK - - ");
1402 wrbuf_printf(wr, ODR_INT_PRINTF "+" ODR_INT_PRINTF " ",
1403 (srw_req->responsePosition ?
1404 *srw_req->responsePosition : 1),
1405 (srw_req->maximumTerms ?
1406 *srw_req->maximumTerms : 1));
1407 /* there is no step size in SRU/W ??? */
1408 wrbuf_printf(wr, "%s: %s ", querytype, querystr);
1409 yaz_log(log_request, "%s ", wrbuf_cstr(wr) );
1415 static void srw_bend_update(association *assoc, request *req,
1417 Z_SRW_updateResponse *srw_res,
1420 Z_SRW_updateRequest *srw_req = sr->u.update_request;
1421 yaz_log(log_session, "SRWUpdate action=%s", srw_req->operation);
1422 yaz_log(YLOG_DEBUG, "num_diag = %d", srw_res->num_diagnostics );
1424 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1428 Z_SRW_extra_record *extra = srw_req->extra_record;
1430 rr.stream = assoc->encode;
1431 rr.print = assoc->print;
1433 rr.basenames = &srw_req->database;
1434 rr.operation = srw_req->operation;
1435 rr.operation_status = "failed";
1437 rr.record_versions = 0;
1438 rr.num_versions = 0;
1439 rr.record_packing = "string";
1440 rr.record_schema = 0;
1442 rr.extra_record_data = 0;
1443 rr.extra_request_data = 0;
1444 rr.extra_response_data = 0;
1450 if (rr.operation == 0)
1452 yaz_add_sru_update_diagnostic(
1453 assoc->encode, &srw_res->diagnostics,
1454 &srw_res->num_diagnostics,
1455 YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,
1459 yaz_log(YLOG_DEBUG, "basename = %s", rr.basenames[0] );
1460 yaz_log(YLOG_DEBUG, "Operation = %s", rr.operation );
1461 if (!strcmp( rr.operation, "delete"))
1463 if (srw_req->record && !srw_req->record->recordSchema)
1465 rr.record_schema = odr_strdup(
1467 srw_req->record->recordSchema);
1469 if (srw_req->record)
1471 rr.record_data = odr_strdupn(
1473 srw_req->record->recordData_buf,
1474 srw_req->record->recordData_len );
1476 if (extra && extra->extraRecordData_len)
1478 rr.extra_record_data = odr_strdupn(
1480 extra->extraRecordData_buf,
1481 extra->extraRecordData_len );
1483 if (srw_req->recordId)
1484 rr.record_id = srw_req->recordId;
1485 else if (extra && extra->recordIdentifier)
1486 rr.record_id = extra->recordIdentifier;
1488 else if (!strcmp(rr.operation, "replace"))
1490 if (srw_req->recordId)
1491 rr.record_id = srw_req->recordId;
1492 else if (extra && extra->recordIdentifier)
1493 rr.record_id = extra->recordIdentifier;
1496 yaz_add_sru_update_diagnostic(
1497 assoc->encode, &srw_res->diagnostics,
1498 &srw_res->num_diagnostics,
1499 YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,
1500 "recordIdentifier");
1502 if (!srw_req->record)
1504 yaz_add_sru_update_diagnostic(
1505 assoc->encode, &srw_res->diagnostics,
1506 &srw_res->num_diagnostics,
1507 YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,
1512 if (srw_req->record->recordSchema)
1513 rr.record_schema = odr_strdup(
1514 assoc->encode, srw_req->record->recordSchema);
1515 if (srw_req->record->recordData_len )
1517 rr.record_data = odr_strdupn(assoc->encode,
1518 srw_req->record->recordData_buf,
1519 srw_req->record->recordData_len );
1523 yaz_add_sru_update_diagnostic(
1524 assoc->encode, &srw_res->diagnostics,
1525 &srw_res->num_diagnostics,
1526 YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,
1530 if (extra && extra->extraRecordData_len)
1532 rr.extra_record_data = odr_strdupn(
1534 extra->extraRecordData_buf,
1535 extra->extraRecordData_len );
1538 else if (!strcmp(rr.operation, "insert"))
1540 if (srw_req->recordId)
1541 rr.record_id = srw_req->recordId;
1543 rr.record_id = extra->recordIdentifier;
1545 if (srw_req->record)
1547 if (srw_req->record->recordSchema)
1548 rr.record_schema = odr_strdup(
1549 assoc->encode, srw_req->record->recordSchema);
1551 if (srw_req->record->recordData_len)
1552 rr.record_data = odr_strdupn(
1554 srw_req->record->recordData_buf,
1555 srw_req->record->recordData_len );
1557 if (extra && extra->extraRecordData_len)
1559 rr.extra_record_data = odr_strdupn(
1561 extra->extraRecordData_buf,
1562 extra->extraRecordData_len );
1566 yaz_add_sru_update_diagnostic(assoc->encode, &srw_res->diagnostics,
1567 &srw_res->num_diagnostics,
1568 YAZ_SRU_UPDATE_INVALID_ACTION,
1571 if (srw_req->record)
1573 const char *pack_str =
1574 yaz_srw_pack_to_str(srw_req->record->recordPacking);
1576 rr.record_packing = odr_strdup(assoc->encode, pack_str);
1579 if (srw_req->num_recordVersions)
1581 rr.record_versions = srw_req->recordVersions;
1582 rr.num_versions = srw_req->num_recordVersions;
1584 if (srw_req->extraRequestData_len)
1586 rr.extra_request_data = odr_strdupn(assoc->encode,
1587 srw_req->extraRequestData_buf,
1588 srw_req->extraRequestData_len );
1590 if (srw_res->num_diagnostics == 0)
1592 if ( assoc->init->bend_srw_update)
1593 (*assoc->init->bend_srw_update)(assoc->backend, &rr);
1595 yaz_add_sru_update_diagnostic(
1596 assoc->encode, &srw_res->diagnostics,
1597 &srw_res->num_diagnostics,
1598 YAZ_SRU_UPDATE_UNSPECIFIED_DATABASE_ERROR,
1599 "No Update backend handler");
1603 yaz_add_srw_diagnostic_uri(assoc->encode,
1604 &srw_res->diagnostics,
1605 &srw_res->num_diagnostics,
1609 srw_res->recordId = rr.record_id;
1610 srw_res->operationStatus = rr.operation_status;
1611 srw_res->recordVersions = rr.record_versions;
1612 srw_res->num_recordVersions = rr.num_versions;
1613 if (srw_res->extraResponseData_len)
1615 srw_res->extraResponseData_buf = rr.extra_response_data;
1616 srw_res->extraResponseData_len = strlen(rr.extra_response_data);
1618 if (srw_res->num_diagnostics == 0 && rr.record_data)
1620 srw_res->record = yaz_srw_get_record(assoc->encode);
1621 srw_res->record->recordSchema = rr.record_schema;
1622 if (rr.record_packing)
1624 int pack = yaz_srw_str_to_pack(rr.record_packing);
1628 pack = Z_SRW_recordPacking_string;
1629 yaz_log(YLOG_WARN, "Back packing %s from backend",
1632 srw_res->record->recordPacking = pack;
1634 srw_res->record->recordData_buf = rr.record_data;
1635 srw_res->record->recordData_len = strlen(rr.record_data);
1636 if (rr.extra_record_data)
1638 Z_SRW_extra_record *ex =
1639 yaz_srw_get_extra_record(assoc->encode);
1640 srw_res->extra_record = ex;
1641 ex->extraRecordData_buf = rr.extra_record_data;
1642 ex->extraRecordData_len = strlen(rr.extra_record_data);
1648 /* check if path is OK (1); BAD (0) */
1649 static int check_path(const char *path)
1653 if (strstr(path, ".."))
1658 static char *read_file(const char *fname, ODR o, size_t *sz)
1661 FILE *inf = fopen(fname, "rb");
1665 fseek(inf, 0L, SEEK_END);
1668 buf = (char *) odr_malloc(o, *sz);
1669 if (fread(buf, 1, *sz, inf) != *sz)
1670 yaz_log(YLOG_WARN|YLOG_ERRNO, "short read %s", fname);
1675 static void process_http_request(association *assoc, request *req)
1677 Z_HTTP_Request *hreq = req->gdu_request->u.HTTP_Request;
1678 ODR o = assoc->encode;
1679 int r = 2; /* 2=NOT TAKEN, 1=TAKEN, 0=SOAP TAKEN */
1681 Z_SOAP *soap_package = 0;
1684 Z_HTTP_Response *hres = 0;
1686 const char *stylesheet = 0; /* for now .. set later */
1687 Z_SRW_diagnostic *diagnostic = 0;
1688 int num_diagnostic = 0;
1689 const char *host = z_HTTP_header_lookup(hreq->headers, "Host");
1691 yaz_log(log_request, "%s %s HTTP/%s", hreq->method, hreq->path, hreq->version);
1692 if (!control_association(assoc, host, 0))
1694 p = z_get_HTTP_Response(o, 404);
1697 if (r == 2 && assoc->server && assoc->server->docpath
1698 && hreq->path[0] == '/'
1700 /* check if path is a proper prefix of documentroot */
1701 strncmp(hreq->path+1, assoc->server->docpath,
1702 strlen(assoc->server->docpath))
1705 if (!check_path(hreq->path))
1707 yaz_log(YLOG_LOG, "File %s access forbidden", hreq->path+1);
1708 p = z_get_HTTP_Response(o, 404);
1712 size_t content_size = 0;
1713 char *content_buf = read_file(hreq->path+1, o, &content_size);
1716 yaz_log(YLOG_LOG, "File %s not found", hreq->path+1);
1717 p = z_get_HTTP_Response(o, 404);
1721 const char *ctype = 0;
1722 yaz_mime_types types = yaz_mime_types_create();
1724 yaz_mime_types_add(types, "xsl", "application/xml");
1725 yaz_mime_types_add(types, "xml", "application/xml");
1726 yaz_mime_types_add(types, "css", "text/css");
1727 yaz_mime_types_add(types, "html", "text/html");
1728 yaz_mime_types_add(types, "htm", "text/html");
1729 yaz_mime_types_add(types, "txt", "text/plain");
1730 yaz_mime_types_add(types, "js", "application/x-javascript");
1732 yaz_mime_types_add(types, "gif", "image/gif");
1733 yaz_mime_types_add(types, "png", "image/png");
1734 yaz_mime_types_add(types, "jpg", "image/jpeg");
1735 yaz_mime_types_add(types, "jpeg", "image/jpeg");
1737 ctype = yaz_mime_lookup_fname(types, hreq->path);
1740 yaz_log(YLOG_LOG, "No mime type for %s", hreq->path+1);
1741 p = z_get_HTTP_Response(o, 404);
1745 p = z_get_HTTP_Response(o, 200);
1746 hres = p->u.HTTP_Response;
1747 hres->content_buf = content_buf;
1748 hres->content_len = content_size;
1749 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1751 yaz_mime_types_destroy(types);
1759 r = yaz_srw_decode(hreq, &sr, &soap_package, assoc->decode, &charset);
1760 yaz_log(YLOG_DEBUG, "yaz_srw_decode returned %d", r);
1762 if (r == 2) /* not taken */
1764 r = yaz_sru_decode(hreq, &sr, &soap_package, assoc->decode, &charset,
1765 &diagnostic, &num_diagnostic);
1766 yaz_log(YLOG_DEBUG, "yaz_sru_decode returned %d", r);
1768 if (r == 0) /* decode SRW/SRU OK .. */
1770 int http_code = 200;
1771 if (sr->which == Z_SRW_searchRetrieve_request)
1774 yaz_srw_get_pdu(assoc->encode, Z_SRW_searchRetrieve_response,
1776 stylesheet = sr->u.request->stylesheet;
1779 res->u.response->diagnostics = diagnostic;
1780 res->u.response->num_diagnostics = num_diagnostic;
1784 srw_bend_search(assoc, req, sr, res, &http_code);
1786 if (http_code == 200)
1787 soap_package->u.generic->p = res;
1789 else if (sr->which == Z_SRW_explain_request)
1791 Z_SRW_PDU *res = yaz_srw_get_pdu(o, Z_SRW_explain_response,
1793 stylesheet = sr->u.explain_request->stylesheet;
1796 res->u.explain_response->diagnostics = diagnostic;
1797 res->u.explain_response->num_diagnostics = num_diagnostic;
1799 srw_bend_explain(assoc, req, sr,
1800 res->u.explain_response, &http_code);
1801 if (http_code == 200)
1802 soap_package->u.generic->p = res;
1804 else if (sr->which == Z_SRW_scan_request)
1806 Z_SRW_PDU *res = yaz_srw_get_pdu(o, Z_SRW_scan_response,
1808 stylesheet = sr->u.scan_request->stylesheet;
1811 res->u.scan_response->diagnostics = diagnostic;
1812 res->u.scan_response->num_diagnostics = num_diagnostic;
1814 srw_bend_scan(assoc, req, sr,
1815 res->u.scan_response, &http_code);
1816 if (http_code == 200)
1817 soap_package->u.generic->p = res;
1819 else if (sr->which == Z_SRW_update_request)
1821 Z_SRW_PDU *res = yaz_srw_get_pdu(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");
1871 if (charset && strlen(charset) < sizeof(ctype)-30)
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)
1951 *msg = "Unknown Error";
1952 assert(req && req->state == REQUEST_IDLE);
1953 if (req->apdu_request->which != Z_APDU_initRequest && !assoc->init)
1955 *msg = "Missing InitRequest";
1958 switch (req->apdu_request->which)
1960 case Z_APDU_initRequest:
1961 res = process_initRequest(assoc, req); break;
1962 case Z_APDU_searchRequest:
1963 res = process_searchRequest(assoc, req); break;
1964 case Z_APDU_presentRequest:
1965 res = process_presentRequest(assoc, req); break;
1966 case Z_APDU_scanRequest:
1967 if (assoc->init->bend_scan)
1968 res = process_scanRequest(assoc, req);
1971 *msg = "Cannot handle Scan APDU";
1975 case Z_APDU_extendedServicesRequest:
1976 if (assoc->init->bend_esrequest)
1977 res = process_ESRequest(assoc, req);
1980 *msg = "Cannot handle Extended Services APDU";
1984 case Z_APDU_sortRequest:
1985 if (assoc->init->bend_sort)
1986 res = process_sortRequest(assoc, req);
1989 *msg = "Cannot handle Sort APDU";
1994 process_close(assoc, req);
1996 case Z_APDU_deleteResultSetRequest:
1997 if (assoc->init->bend_delete)
1998 res = process_deleteRequest(assoc, req);
2001 *msg = "Cannot handle Delete APDU";
2005 case Z_APDU_segmentRequest:
2006 if (assoc->init->bend_segment)
2008 res = process_segmentRequest(assoc, req);
2012 *msg = "Cannot handle Segment APDU";
2016 case Z_APDU_triggerResourceControlRequest:
2019 *msg = "Bad APDU received";
2024 yaz_log(YLOG_DEBUG, " result immediately available");
2025 retval = process_z_response(assoc, req, res);
2029 yaz_log(YLOG_DEBUG, " result unavailble");
2036 * Encode response, and transfer the request structure to the outgoing queue.
2038 static int process_gdu_response(association *assoc, request *req, Z_GDU *res)
2040 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
2044 if (!z_GDU(assoc->print, &res, 0, 0))
2045 yaz_log(YLOG_WARN, "ODR print error: %s",
2046 odr_errmsg(odr_geterror(assoc->print)));
2047 odr_reset(assoc->print);
2049 if (!z_GDU(assoc->encode, &res, 0, 0))
2051 yaz_log(YLOG_WARN, "ODR error when encoding PDU: %s [element %s]",
2052 odr_errmsg(odr_geterror(assoc->decode)),
2053 odr_getelement(assoc->decode));
2056 req->response = odr_getbuf(assoc->encode, &req->len_response,
2057 &req->size_response);
2058 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
2059 odr_reset(assoc->encode);
2060 req->state = REQUEST_IDLE;
2061 request_enq(&assoc->outgoing, req);
2062 /* turn the work over to the ir_session handler */
2063 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
2064 assoc->cs_put_mask = EVENT_OUTPUT;
2065 /* Is there more work to be done? give that to the input handler too */
2068 req = request_head(&assoc->incoming);
2069 if (req && req->state == REQUEST_IDLE)
2071 request_deq(&assoc->incoming);
2072 process_gdu_request(assoc, req);
2081 * Encode response, and transfer the request structure to the outgoing queue.
2083 static int process_z_response(association *assoc, request *req, Z_APDU *res)
2085 Z_GDU *gres = (Z_GDU *) odr_malloc(assoc->encode, sizeof(*res));
2086 gres->which = Z_GDU_Z3950;
2087 gres->u.z3950 = res;
2089 return process_gdu_response(assoc, req, gres);
2092 static char *get_vhost(Z_OtherInformation *otherInfo)
2094 return yaz_oi_get_string_oid(&otherInfo, yaz_oid_userinfo_proxy, 1, 0);
2098 * Handle init request.
2099 * At the moment, we don't check the options
2100 * anywhere else in the code - we just try not to do anything that would
2101 * break a naive client. We'll toss 'em into the association block when
2102 * we need them there.
2104 static Z_APDU *process_initRequest(association *assoc, request *reqb)
2106 Z_InitRequest *req = reqb->apdu_request->u.initRequest;
2107 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
2108 Z_InitResponse *resp = apdu->u.initResponse;
2109 bend_initresult *binitres;
2111 statserv_options_block *cb = 0; /* by default no control for backend */
2113 if (control_association(assoc, get_vhost(req->otherInfo), 1))
2114 cb = statserv_getcontrol(); /* got control block for backend */
2116 if (cb && assoc->backend)
2117 (*cb->bend_close)(assoc->backend);
2119 yaz_log(log_requestdetail, "Got initRequest");
2120 if (req->implementationId)
2121 yaz_log(log_requestdetail, "Id: %s",
2122 req->implementationId);
2123 if (req->implementationName)
2124 yaz_log(log_requestdetail, "Name: %s",
2125 req->implementationName);
2126 if (req->implementationVersion)
2127 yaz_log(log_requestdetail, "Version: %s",
2128 req->implementationVersion);
2130 assoc_init_reset(assoc);
2132 assoc->init->auth = req->idAuthentication;
2133 assoc->init->referenceId = req->referenceId;
2135 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
2137 Z_CharSetandLanguageNegotiation *negotiation =
2138 yaz_get_charneg_record (req->otherInfo);
2140 negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
2141 assoc->init->charneg_request = negotiation;
2144 /* by default named_result_sets is 0 .. Enable it if client asks for it. */
2145 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
2146 assoc->init->named_result_sets = 1;
2151 if (req->implementationVersion)
2152 yaz_log(log_requestdetail, "Config: %s",
2155 iochan_settimeout(assoc->client_chan, cb->idle_timeout * 60);
2157 /* we have a backend control block, so call that init function */
2158 if (!(binitres = (*cb->bend_init)(assoc->init)))
2160 yaz_log(YLOG_WARN, "Bad response from backend.");
2163 assoc->backend = binitres->handle;
2167 /* no backend. return error */
2168 binitres = (bend_initresult *)
2169 odr_malloc(assoc->encode, sizeof(*binitres));
2170 binitres->errstring = 0;
2171 binitres->errcode = YAZ_BIB1_PERMANENT_SYSTEM_ERROR;
2172 iochan_settimeout(assoc->client_chan, 10);
2174 if ((assoc->init->bend_sort))
2175 yaz_log(YLOG_DEBUG, "Sort handler installed");
2176 if ((assoc->init->bend_search))
2177 yaz_log(YLOG_DEBUG, "Search handler installed");
2178 if ((assoc->init->bend_present))
2179 yaz_log(YLOG_DEBUG, "Present handler installed");
2180 if ((assoc->init->bend_esrequest))
2181 yaz_log(YLOG_DEBUG, "ESRequest handler installed");
2182 if ((assoc->init->bend_delete))
2183 yaz_log(YLOG_DEBUG, "Delete handler installed");
2184 if ((assoc->init->bend_scan))
2185 yaz_log(YLOG_DEBUG, "Scan handler installed");
2186 if ((assoc->init->bend_segment))
2187 yaz_log(YLOG_DEBUG, "Segment handler installed");
2189 resp->referenceId = req->referenceId;
2191 /* let's tell the client what we can do */
2192 if (ODR_MASK_GET(req->options, Z_Options_search))
2194 ODR_MASK_SET(resp->options, Z_Options_search);
2195 strcat(options, "srch");
2197 if (ODR_MASK_GET(req->options, Z_Options_present))
2199 ODR_MASK_SET(resp->options, Z_Options_present);
2200 strcat(options, " prst");
2202 if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
2203 assoc->init->bend_delete)
2205 ODR_MASK_SET(resp->options, Z_Options_delSet);
2206 strcat(options, " del");
2208 if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
2209 assoc->init->bend_esrequest)
2211 ODR_MASK_SET(resp->options, Z_Options_extendedServices);
2212 strcat(options, " extendedServices");
2214 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets)
2215 && assoc->init->named_result_sets)
2217 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
2218 strcat(options, " namedresults");
2220 if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
2222 ODR_MASK_SET(resp->options, Z_Options_scan);
2223 strcat(options, " scan");
2225 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
2227 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
2228 strcat(options, " concurrop");
2230 if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
2232 ODR_MASK_SET(resp->options, Z_Options_sort);
2233 strcat(options, " sort");
2236 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
2238 Z_OtherInformationUnit *p0;
2240 if (!assoc->init->charneg_response)
2242 if (assoc->init->query_charset)
2244 assoc->init->charneg_response = yaz_set_response_charneg(
2245 assoc->encode, assoc->init->query_charset, 0,
2246 assoc->init->records_in_same_charset);
2250 yaz_log(YLOG_WARN, "default query_charset not defined by backend");
2253 if (assoc->init->charneg_response
2254 && (p0=yaz_oi_update(&resp->otherInfo, assoc->encode, NULL, 0, 0)))
2256 p0->which = Z_OtherInfo_externallyDefinedInfo;
2257 p0->information.externallyDefinedInfo =
2258 assoc->init->charneg_response;
2259 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
2260 strcat(options, " negotiation");
2263 if (ODR_MASK_GET(req->options, Z_Options_triggerResourceCtrl))
2264 ODR_MASK_SET(resp->options, Z_Options_triggerResourceCtrl);
2266 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
2268 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
2269 assoc->version = 1; /* 1 & 2 are equivalent */
2271 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
2273 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
2276 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
2278 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
2282 yaz_log(log_requestdetail, "Negotiated to v%d: %s", assoc->version, options);
2284 if (*req->maximumRecordSize < assoc->maximumRecordSize)
2285 assoc->maximumRecordSize = *req->maximumRecordSize;
2287 if (*req->preferredMessageSize < assoc->preferredMessageSize)
2288 assoc->preferredMessageSize = *req->preferredMessageSize;
2290 resp->preferredMessageSize = &assoc->preferredMessageSize;
2291 resp->maximumRecordSize = &assoc->maximumRecordSize;
2293 resp->implementationId = odr_prepend(assoc->encode,
2294 assoc->init->implementation_id,
2295 resp->implementationId);
2297 resp->implementationName = odr_prepend(assoc->encode,
2298 assoc->init->implementation_name,
2299 odr_prepend(assoc->encode, "GFS", resp->implementationName));
2301 if (binitres->errcode)
2303 assoc->state = ASSOC_DEAD;
2304 resp->userInformationField =
2305 init_diagnostics(assoc->encode, binitres->errcode,
2306 binitres->errstring);
2310 assoc->state = ASSOC_UP;
2314 if (!req->idAuthentication)
2315 yaz_log(log_request, "Auth none");
2316 else if (req->idAuthentication->which == Z_IdAuthentication_open)
2318 const char *open = req->idAuthentication->u.open;
2319 const char *slash = strchr(open, '/');
2325 yaz_log(log_request, "Auth open %.*s", len, open);
2327 else if (req->idAuthentication->which == Z_IdAuthentication_idPass)
2329 const char *user = req->idAuthentication->u.idPass->userId;
2330 const char *group = req->idAuthentication->u.idPass->groupId;
2331 yaz_log(log_request, "Auth idPass %s %s",
2332 user ? user : "-", group ? group : "-");
2334 else if (req->idAuthentication->which
2335 == Z_IdAuthentication_anonymous)
2337 yaz_log(log_request, "Auth anonymous");
2341 yaz_log(log_request, "Auth other");
2346 WRBUF wr = wrbuf_alloc();
2347 wrbuf_printf(wr, "Init ");
2348 if (binitres->errcode)
2349 wrbuf_printf(wr, "ERROR %d", binitres->errcode);
2351 wrbuf_printf(wr, "OK -");
2352 wrbuf_printf(wr, " ID:%s Name:%s Version:%s",
2353 (req->implementationId ? req->implementationId :"-"),
2354 (req->implementationName ?
2355 req->implementationName : "-"),
2356 (req->implementationVersion ?
2357 req->implementationVersion : "-")
2359 yaz_log(log_request, "%s", wrbuf_cstr(wr));
2366 * Set the specified `errcode' and `errstring' into a UserInfo-1
2367 * external to be returned to the client in accordance with Z35.90
2368 * Implementor Agreement 5 (Returning diagnostics in an InitResponse):
2369 * http://lcweb.loc.gov/z3950/agency/agree/initdiag.html
2371 static Z_External *init_diagnostics(ODR odr, int error, const char *addinfo)
2373 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2374 addinfo ? " -- " : "", addinfo ? addinfo : "");
2375 return zget_init_diagnostics(odr, error, addinfo);
2379 * nonsurrogate diagnostic record.
2381 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
2383 Z_Records *rec = (Z_Records *) odr_malloc(assoc->encode, sizeof(*rec));
2385 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2386 addinfo ? " -- " : "", addinfo ? addinfo : "");
2388 rec->which = Z_Records_NSD;
2389 rec->u.nonSurrogateDiagnostic = zget_DefaultDiagFormat(assoc->encode,
2395 * surrogate diagnostic.
2397 static Z_NamePlusRecord *surrogatediagrec(association *assoc,
2399 int error, const char *addinfo)
2401 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2402 addinfo ? " -- " : "", addinfo ? addinfo : "");
2403 return zget_surrogateDiagRec(assoc->encode, dbname, error, addinfo);
2406 static Z_Records *pack_records(association *a, char *setname, Odr_int start,
2407 Odr_int *num, Z_RecordComposition *comp,
2408 Odr_int *next, Odr_int *pres,
2409 Z_ReferenceId *referenceId,
2410 Odr_oid *oid, int *errcode)
2412 int recno, total_length = 0, toget = *num, dumped_records = 0;
2413 Z_Records *records =
2414 (Z_Records *) odr_malloc(a->encode, sizeof(*records));
2415 Z_NamePlusRecordList *reclist =
2416 (Z_NamePlusRecordList *) odr_malloc(a->encode, sizeof(*reclist));
2417 Z_NamePlusRecord **list =
2418 (Z_NamePlusRecord **) odr_malloc(a->encode, sizeof(*list) * toget);
2420 records->which = Z_Records_DBOSD;
2421 records->u.databaseOrSurDiagnostics = reclist;
2422 reclist->num_records = 0;
2423 reclist->records = list;
2424 *pres = Z_PresentStatus_success;
2428 yaz_log(log_requestdetail, "Request to pack " ODR_INT_PRINTF "+%d %s", start, toget, setname);
2429 yaz_log(log_requestdetail, "pms=" ODR_INT_PRINTF
2430 ", mrs=" ODR_INT_PRINTF, a->preferredMessageSize,
2431 a->maximumRecordSize);
2432 for (recno = start; reclist->num_records < toget; recno++)
2435 Z_NamePlusRecord *thisrec;
2436 int this_length = 0;
2438 * we get the number of bytes allocated on the stream before any
2439 * allocation done by the backend - this should give us a reasonable
2440 * idea of the total size of the data so far.
2442 total_length = odr_total(a->encode) - dumped_records;
2448 freq.last_in_set = 0;
2449 freq.setname = setname;
2450 freq.surrogate_flag = 0;
2451 freq.number = recno;
2453 freq.request_format = oid;
2454 freq.output_format = 0;
2455 freq.stream = a->encode;
2456 freq.print = a->print;
2457 freq.referenceId = referenceId;
2460 retrieve_fetch(a, &freq);
2462 *next = freq.last_in_set ? 0 : recno + 1;
2466 if (!freq.surrogate_flag) /* non-surrogate diagnostic i.e. global */
2469 *pres = Z_PresentStatus_failure;
2470 /* for 'present request out of range',
2471 set addinfo to record position if not set */
2472 if (freq.errcode == YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE &&
2473 freq.errstring == 0)
2475 sprintf (s, "%d", recno);
2479 *errcode = freq.errcode;
2480 return diagrec(a, freq.errcode, freq.errstring);
2482 reclist->records[reclist->num_records] =
2483 surrogatediagrec(a, freq.basename, freq.errcode,
2485 reclist->num_records++;
2488 if (freq.record == 0) /* no error and no record ? */
2490 *next = 0; /* signal end-of-set and stop */
2494 this_length = freq.len;
2496 this_length = odr_total(a->encode) - total_length - dumped_records;
2497 yaz_log(YLOG_DEBUG, " fetched record, len=%d, total=%d dumped=%d",
2498 this_length, total_length, dumped_records);
2499 if (a->preferredMessageSize > 0 &&
2500 this_length + total_length > a->preferredMessageSize)
2502 /* record is small enough, really */
2503 if (this_length <= a->preferredMessageSize && recno > start)
2505 yaz_log(log_requestdetail, " Dropped last normal-sized record");
2506 *pres = Z_PresentStatus_partial_2;
2509 /* record can only be fetched by itself */
2510 if (this_length < a->maximumRecordSize)
2512 yaz_log(log_requestdetail, " Record > prefmsgsz");
2515 yaz_log(YLOG_DEBUG, " Dropped it");
2516 reclist->records[reclist->num_records] =
2517 surrogatediagrec(a, freq.basename, 16, 0);
2518 reclist->num_records++;
2519 dumped_records += this_length;
2523 else /* too big entirely */
2525 yaz_log(log_requestdetail, "Record > maxrcdsz "
2526 "this=%d max=" ODR_INT_PRINTF,
2527 this_length, a->maximumRecordSize);
2528 reclist->records[reclist->num_records] =
2529 surrogatediagrec(a, freq.basename, 17, 0);
2530 reclist->num_records++;
2531 dumped_records += this_length;
2536 if (!(thisrec = (Z_NamePlusRecord *)
2537 odr_malloc(a->encode, sizeof(*thisrec))))
2539 thisrec->databaseName = odr_strdup_null(a->encode, freq.basename);
2540 thisrec->which = Z_NamePlusRecord_databaseRecord;
2542 if (!freq.output_format)
2543 freq.output_format = freq.request_format;
2544 thisrec->u.databaseRecord = z_ext_record_oid(
2545 a->encode, freq.output_format, freq.record, freq.len);
2546 if (!thisrec->u.databaseRecord)
2548 reclist->records[reclist->num_records] = thisrec;
2549 reclist->num_records++;
2551 *num = reclist->num_records;
2555 static Z_APDU *process_searchRequest(association *assoc, request *reqb)
2557 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2558 bend_search_rr *bsrr =
2559 (bend_search_rr *)nmem_malloc(reqb->request_mem, sizeof(*bsrr));
2561 yaz_log(log_requestdetail, "Got SearchRequest.");
2562 bsrr->association = assoc;
2563 bsrr->referenceId = req->referenceId;
2564 bsrr->srw_sortKeys = 0;
2565 bsrr->srw_setname = 0;
2566 bsrr->srw_setnameIdleTime = 0;
2567 bsrr->estimated_hit_count = 0;
2568 bsrr->partial_resultset = 0;
2569 bsrr->extra_args = 0;
2570 bsrr->extra_response_data = 0;
2572 yaz_log (log_requestdetail, "ResultSet '%s'", req->resultSetName);
2573 if (req->databaseNames)
2576 for (i = 0; i < req->num_databaseNames; i++)
2577 yaz_log(log_requestdetail, "Database '%s'", req->databaseNames[i]);
2580 yaz_log_zquery_level(log_requestdetail,req->query);
2582 if (assoc->init->bend_search)
2584 bsrr->setname = req->resultSetName;
2585 bsrr->replace_set = *req->replaceIndicator;
2586 bsrr->num_bases = req->num_databaseNames;
2587 bsrr->basenames = req->databaseNames;
2588 bsrr->query = req->query;
2589 bsrr->stream = assoc->encode;
2590 nmem_transfer(odr_getmem(bsrr->stream), reqb->request_mem);
2591 bsrr->decode = assoc->decode;
2592 bsrr->print = assoc->print;
2595 bsrr->errstring = NULL;
2596 bsrr->search_info = NULL;
2598 if (assoc->server && assoc->server->cql_transform
2599 && req->query->which == Z_Query_type_104
2600 && req->query->u.type_104->which == Z_External_CQL)
2602 /* have a CQL query and a CQL to PQF transform .. */
2604 cql2pqf(bsrr->stream, req->query->u.type_104->u.cql,
2605 assoc->server->cql_transform, bsrr->query);
2607 bsrr->errcode = yaz_diag_srw_to_bib1(srw_errcode);
2610 if (assoc->server && assoc->server->ccl_transform
2611 && req->query->which == Z_Query_type_2) /*CCL*/
2613 /* have a CCL query and a CCL to PQF transform .. */
2615 ccl2pqf(bsrr->stream, req->query->u.type_2,
2616 assoc->server->ccl_transform, bsrr);
2618 bsrr->errcode = yaz_diag_srw_to_bib1(srw_errcode);
2622 (assoc->init->bend_search)(assoc->backend, bsrr);
2626 /* FIXME - make a diagnostic for it */
2627 yaz_log(YLOG_WARN,"Search not supported ?!?!");
2629 return response_searchRequest(assoc, reqb, bsrr);
2632 int bend_searchresponse(void *handle, bend_search_rr *bsrr) {return 0;}
2635 * Prepare a searchresponse based on the backend results. We probably want
2636 * to look at making the fetching of records nonblocking as well, but
2637 * so far, we'll keep things simple.
2638 * If bsrt is null, that means we're called in response to a communications
2639 * event, and we'll have to get the response for ourselves.
2641 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
2642 bend_search_rr *bsrt)
2644 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2645 Z_APDU *apdu = (Z_APDU *)odr_malloc(assoc->encode, sizeof(*apdu));
2646 Z_SearchResponse *resp = (Z_SearchResponse *)
2647 odr_malloc(assoc->encode, sizeof(*resp));
2648 Odr_int *nulint = odr_intdup(assoc->encode, 0);
2649 Odr_int *next = odr_intdup(assoc->encode, 0);
2650 Odr_int *none = odr_intdup(assoc->encode, Z_SearchResponse_none);
2651 int returnedrecs = 0;
2653 apdu->which = Z_APDU_searchResponse;
2654 apdu->u.searchResponse = resp;
2655 resp->referenceId = req->referenceId;
2656 resp->additionalSearchInfo = 0;
2657 resp->otherInfo = 0;
2658 if (!bsrt && !bend_searchresponse(assoc->backend, bsrt))
2660 yaz_log(YLOG_FATAL, "Bad result from backend");
2663 else if (bsrt->errcode)
2665 resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
2666 resp->resultCount = nulint;
2667 resp->numberOfRecordsReturned = nulint;
2668 resp->nextResultSetPosition = nulint;
2669 resp->searchStatus = odr_booldup(assoc->encode, 0);
2670 resp->resultSetStatus = none;
2671 resp->presentStatus = 0;
2675 bool_t *sr = odr_booldup(assoc->encode, 1);
2676 Odr_int *toget = odr_intdup(assoc->encode, 0);
2677 Z_RecordComposition comp, *compp = 0;
2679 yaz_log(log_requestdetail, "resultCount: " ODR_INT_PRINTF, bsrt->hits);
2682 resp->resultCount = &bsrt->hits;
2684 comp.which = Z_RecordComp_simple;
2685 /* how many records does the user agent want, then? */
2688 else if (bsrt->hits <= *req->smallSetUpperBound)
2690 *toget = bsrt->hits;
2691 if ((comp.u.simple = req->smallSetElementSetNames))
2694 else if (bsrt->hits < *req->largeSetLowerBound)
2696 *toget = *req->mediumSetPresentNumber;
2697 if (*toget > bsrt->hits)
2698 *toget = bsrt->hits;
2699 if ((comp.u.simple = req->mediumSetElementSetNames))
2705 if (*toget && !resp->records)
2707 Odr_int *presst = odr_intdup(assoc->encode, 0);
2708 /* Call bend_present if defined */
2709 if (assoc->init->bend_present)
2711 bend_present_rr *bprr = (bend_present_rr *)
2712 nmem_malloc(reqb->request_mem, sizeof(*bprr));
2713 bprr->setname = req->resultSetName;
2715 bprr->number = *toget;
2716 bprr->format = req->preferredRecordSyntax;
2718 bprr->referenceId = req->referenceId;
2719 bprr->stream = assoc->encode;
2720 bprr->print = assoc->print;
2721 bprr->association = assoc;
2723 bprr->errstring = NULL;
2724 (*assoc->init->bend_present)(assoc->backend, bprr);
2728 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2729 *resp->presentStatus = Z_PresentStatus_failure;
2734 resp->records = pack_records(
2735 assoc, req->resultSetName, 1,
2736 toget, compp, next, presst, req->referenceId,
2737 req->preferredRecordSyntax, NULL);
2740 resp->numberOfRecordsReturned = toget;
2741 returnedrecs = *toget;
2742 resp->presentStatus = presst;
2746 if (*resp->resultCount)
2748 resp->numberOfRecordsReturned = nulint;
2749 resp->presentStatus = 0;
2751 resp->nextResultSetPosition = next;
2752 resp->searchStatus = sr;
2753 resp->resultSetStatus = 0;
2754 if (bsrt->estimated_hit_count)
2756 resp->resultSetStatus = odr_intdup(assoc->encode,
2757 Z_SearchResponse_estimate);
2759 else if (bsrt->partial_resultset)
2761 resp->resultSetStatus = odr_intdup(assoc->encode,
2762 Z_SearchResponse_subset);
2765 resp->additionalSearchInfo = bsrt->search_info;
2770 WRBUF wr = wrbuf_alloc();
2772 for (i = 0 ; i < req->num_databaseNames; i++){
2774 wrbuf_printf(wr, "+");
2775 wrbuf_puts(wr, req->databaseNames[i]);
2777 wrbuf_printf(wr, " ");
2780 wrbuf_printf(wr, "ERROR %d", bsrt->errcode);
2782 wrbuf_printf(wr, "OK " ODR_INT_PRINTF, bsrt->hits);
2783 wrbuf_printf(wr, " %s 1+%d ",
2784 req->resultSetName, returnedrecs);
2785 yaz_query_to_wrbuf(wr, req->query);
2787 yaz_log(log_request, "Search %s", wrbuf_cstr(wr));
2794 * Maybe we got a little over-friendly when we designed bend_fetch to
2795 * get only one record at a time. Some backends can optimise multiple-record
2796 * fetches, and at any rate, there is some overhead involved in
2797 * all that selecting and hopping around. Problem is, of course, that the
2798 * frontend can't know ahead of time how many records it'll need to
2799 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
2800 * is downright lousy as a bulk data transfer protocol.
2802 * To start with, we'll do the fetching of records from the backend
2803 * in one operation: To save some trips in and out of the event-handler,
2804 * and to simplify the interface to pack_records. At any rate, asynch
2805 * operation is more fun in operations that have an unpredictable execution
2806 * speed - which is normally more true for search than for present.
2808 static Z_APDU *process_presentRequest(association *assoc, request *reqb)
2810 Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
2812 Z_PresentResponse *resp;
2816 const char *errstring = 0;
2818 yaz_log(log_requestdetail, "Got PresentRequest.");
2820 resp = (Z_PresentResponse *)odr_malloc(assoc->encode, sizeof(*resp));
2822 resp->presentStatus = odr_intdup(assoc->encode, 0);
2823 if (assoc->init->bend_present)
2825 bend_present_rr *bprr = (bend_present_rr *)
2826 nmem_malloc(reqb->request_mem, sizeof(*bprr));
2827 bprr->setname = req->resultSetId;
2828 bprr->start = *req->resultSetStartPoint;
2829 bprr->number = *req->numberOfRecordsRequested;
2830 bprr->format = req->preferredRecordSyntax;
2831 bprr->comp = req->recordComposition;
2832 bprr->referenceId = req->referenceId;
2833 bprr->stream = assoc->encode;
2834 bprr->print = assoc->print;
2835 bprr->association = assoc;
2837 bprr->errstring = NULL;
2838 (*assoc->init->bend_present)(assoc->backend, bprr);
2842 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2843 *resp->presentStatus = Z_PresentStatus_failure;
2844 errcode = bprr->errcode;
2845 errstring = bprr->errstring;
2848 apdu = (Z_APDU *)odr_malloc(assoc->encode, sizeof(*apdu));
2849 next = odr_intdup(assoc->encode, 0);
2850 num = odr_intdup(assoc->encode, 0);
2852 apdu->which = Z_APDU_presentResponse;
2853 apdu->u.presentResponse = resp;
2854 resp->referenceId = req->referenceId;
2855 resp->otherInfo = 0;
2859 *num = *req->numberOfRecordsRequested;
2861 pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
2862 num, req->recordComposition, next,
2863 resp->presentStatus,
2864 req->referenceId, req->preferredRecordSyntax,
2869 WRBUF wr = wrbuf_alloc();
2870 wrbuf_printf(wr, "Present ");
2872 if (*resp->presentStatus == Z_PresentStatus_failure)
2873 wrbuf_printf(wr, "ERROR %d ", errcode);
2874 else if (*resp->presentStatus == Z_PresentStatus_success)
2875 wrbuf_printf(wr, "OK - ");
2877 wrbuf_printf(wr, "Partial " ODR_INT_PRINTF " - ",
2878 *resp->presentStatus);
2880 wrbuf_printf(wr, " %s " ODR_INT_PRINTF "+" ODR_INT_PRINTF " ",
2881 req->resultSetId, *req->resultSetStartPoint,
2882 *req->numberOfRecordsRequested);
2883 yaz_log(log_request, "%s", wrbuf_cstr(wr) );
2888 resp->numberOfRecordsReturned = num;
2889 resp->nextResultSetPosition = next;
2895 * Scan was implemented rather in a hurry, and with support for only the basic
2896 * elements of the service in the backend API. Suggestions are welcome.
2898 static Z_APDU *process_scanRequest(association *assoc, request *reqb)
2900 Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
2901 Z_APDU *apdu = (Z_APDU *)odr_malloc(assoc->encode, sizeof(*apdu));
2902 Z_ScanResponse *res = (Z_ScanResponse *)
2903 odr_malloc(assoc->encode, sizeof(*res));
2904 Odr_int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
2905 Odr_int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
2906 Z_ListEntries *ents = (Z_ListEntries *)
2907 odr_malloc(assoc->encode, sizeof(*ents));
2908 Z_DiagRecs *diagrecs_p = NULL;
2909 bend_scan_rr *bsrr = (bend_scan_rr *)
2910 odr_malloc(assoc->encode, sizeof(*bsrr));
2911 struct scan_entry *save_entries;
2913 yaz_log(log_requestdetail, "Got ScanRequest");
2915 apdu->which = Z_APDU_scanResponse;
2916 apdu->u.scanResponse = res;
2917 res->referenceId = req->referenceId;
2919 /* if step is absent, set it to 0 */
2920 res->stepSize = odr_intdup(assoc->encode, 0);
2922 *res->stepSize = *req->stepSize;
2924 res->scanStatus = scanStatus;
2925 res->numberOfEntriesReturned = numberOfEntriesReturned;
2926 res->positionOfTerm = 0;
2927 res->entries = ents;
2928 ents->num_entries = 0;
2929 ents->entries = NULL;
2930 ents->num_nonsurrogateDiagnostics = 0;
2931 ents->nonsurrogateDiagnostics = NULL;
2932 res->attributeSet = 0;
2935 if (req->databaseNames)
2938 for (i = 0; i < req->num_databaseNames; i++)
2939 yaz_log(log_requestdetail, "Database '%s'", req->databaseNames[i]);
2941 bsrr->scanClause = 0;
2943 bsrr->errstring = 0;
2944 bsrr->num_bases = req->num_databaseNames;
2945 bsrr->basenames = req->databaseNames;
2946 bsrr->num_entries = *req->numberOfTermsRequested;
2947 bsrr->term = req->termListAndStartPoint;
2948 bsrr->referenceId = req->referenceId;
2949 bsrr->stream = assoc->encode;
2950 bsrr->print = assoc->print;
2951 bsrr->step_size = res->stepSize;
2952 bsrr->setname = yaz_oi_get_string_oid(&req->otherInfo,
2953 yaz_oid_userinfo_scan_set, 1, 0);
2955 /* For YAZ 2.0 and earlier it was the backend handler that
2956 initialized entries (member display_term did not exist)
2957 YAZ 2.0 and later sets 'entries' and initialize all members
2958 including 'display_term'. If YAZ 2.0 or later sees that
2959 entries was modified - we assume that it is an old handler and
2960 that 'display_term' is _not_ set.
2962 if (bsrr->num_entries > 0)
2965 bsrr->entries = (struct scan_entry *)
2966 odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
2968 for (i = 0; i<bsrr->num_entries; i++)
2970 bsrr->entries[i].term = 0;
2971 bsrr->entries[i].occurrences = 0;
2972 bsrr->entries[i].errcode = 0;
2973 bsrr->entries[i].errstring = 0;
2974 bsrr->entries[i].display_term = 0;
2977 save_entries = bsrr->entries; /* save it so we can compare later */
2979 bsrr->attributeset = req->attributeSet;
2980 log_scan_term_level(log_requestdetail, req->termListAndStartPoint,
2981 bsrr->attributeset);
2982 bsrr->term_position = req->preferredPositionInResponse ?
2983 *req->preferredPositionInResponse : 1;
2985 ((int (*)(void *, bend_scan_rr *))
2986 (*assoc->init->bend_scan))(assoc->backend, bsrr);
2989 diagrecs_p = zget_DiagRecs(assoc->encode,
2990 bsrr->errcode, bsrr->errstring);
2994 Z_Entry **tab = (Z_Entry **)
2995 odr_malloc(assoc->encode, sizeof(*tab) * bsrr->num_entries);
2997 if (bsrr->status == BEND_SCAN_PARTIAL)
2998 *scanStatus = Z_Scan_partial_5;
3000 *scanStatus = Z_Scan_success;
3001 ents->entries = tab;
3002 ents->num_entries = bsrr->num_entries;
3003 res->numberOfEntriesReturned = odr_intdup(assoc->encode,
3005 res->positionOfTerm = &bsrr->term_position;
3006 for (i = 0; i < bsrr->num_entries; i++)
3012 tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
3013 if (bsrr->entries[i].occurrences >= 0)
3015 e->which = Z_Entry_termInfo;
3016 e->u.termInfo = t = (Z_TermInfo *)
3017 odr_malloc(assoc->encode, sizeof(*t));
3018 t->suggestedAttributes = 0;
3020 if (save_entries == bsrr->entries &&
3021 bsrr->entries[i].display_term)
3023 /* the entries was _not_ set by the handler. So it's
3024 safe to test for new member display_term. It is
3027 t->displayTerm = odr_strdup(assoc->encode,
3028 bsrr->entries[i].display_term);
3030 t->alternativeTerm = 0;
3031 t->byAttributes = 0;
3032 t->otherTermInfo = 0;
3033 t->globalOccurrences = &bsrr->entries[i].occurrences;
3034 t->term = (Z_Term *)
3035 odr_malloc(assoc->encode, sizeof(*t->term));
3036 t->term->which = Z_Term_general;
3037 t->term->u.general = o =
3038 (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
3039 o->buf = (unsigned char *)
3040 odr_malloc(assoc->encode, o->len = o->size =
3041 strlen(bsrr->entries[i].term));
3042 memcpy(o->buf, bsrr->entries[i].term, o->len);
3043 yaz_log(YLOG_DEBUG, " term #%d: '%s' (" ODR_INT_PRINTF ")", i,
3044 bsrr->entries[i].term, bsrr->entries[i].occurrences);
3048 Z_DiagRecs *drecs = zget_DiagRecs(assoc->encode,
3049 bsrr->entries[i].errcode,
3050 bsrr->entries[i].errstring);
3051 assert(drecs->num_diagRecs == 1);
3052 e->which = Z_Entry_surrogateDiagnostic;
3053 assert(drecs->diagRecs[0]);
3054 e->u.surrogateDiagnostic = drecs->diagRecs[0];
3060 ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
3061 ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
3066 WRBUF wr = wrbuf_alloc();
3067 wrbuf_printf(wr, "Scan ");
3068 for (i = 0 ; i < req->num_databaseNames; i++)
3071 wrbuf_printf(wr, "+");
3072 wrbuf_puts(wr, req->databaseNames[i]);
3075 wrbuf_printf(wr, " ");
3078 wr_diag(wr, bsrr->errcode, bsrr->errstring);
3080 wrbuf_printf(wr, "OK");
3082 wrbuf_printf(wr, " " ODR_INT_PRINTF " - " ODR_INT_PRINTF "+"
3083 ODR_INT_PRINTF "+" ODR_INT_PRINTF,
3084 res->numberOfEntriesReturned ?
3085 *res->numberOfEntriesReturned : 0,
3086 (req->preferredPositionInResponse ?
3087 *req->preferredPositionInResponse : 1),
3088 *req->numberOfTermsRequested,
3089 (res->stepSize ? *res->stepSize : 1));
3092 wrbuf_printf(wr, "+%s", bsrr->setname);
3094 wrbuf_printf(wr, " ");
3095 yaz_scan_to_wrbuf(wr, req->termListAndStartPoint,
3096 bsrr->attributeset);
3097 yaz_log(log_request, "%s", wrbuf_cstr(wr) );
3103 static Z_APDU *process_sortRequest(association *assoc, request *reqb)
3106 Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
3107 Z_SortResponse *res = (Z_SortResponse *)
3108 odr_malloc(assoc->encode, sizeof(*res));
3109 bend_sort_rr *bsrr = (bend_sort_rr *)
3110 odr_malloc(assoc->encode, sizeof(*bsrr));
3112 Z_APDU *apdu = (Z_APDU *)odr_malloc(assoc->encode, sizeof(*apdu));
3114 yaz_log(log_requestdetail, "Got SortRequest.");
3116 bsrr->num_input_setnames = req->num_inputResultSetNames;
3117 for (i=0;i<req->num_inputResultSetNames;i++)
3118 yaz_log(log_requestdetail, "Input resultset: '%s'",
3119 req->inputResultSetNames[i]);
3120 bsrr->input_setnames = req->inputResultSetNames;
3121 bsrr->referenceId = req->referenceId;
3122 bsrr->output_setname = req->sortedResultSetName;
3123 yaz_log(log_requestdetail, "Output resultset: '%s'",
3124 req->sortedResultSetName);
3125 bsrr->sort_sequence = req->sortSequence;
3126 /*FIXME - dump those sequences too */
3127 bsrr->stream = assoc->encode;
3128 bsrr->print = assoc->print;
3130 bsrr->sort_status = Z_SortResponse_failure;
3132 bsrr->errstring = 0;
3134 (*assoc->init->bend_sort)(assoc->backend, bsrr);
3136 res->referenceId = bsrr->referenceId;
3137 res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
3138 res->resultSetStatus = 0;
3141 Z_DiagRecs *dr = zget_DiagRecs(assoc->encode,
3142 bsrr->errcode, bsrr->errstring);
3143 res->diagnostics = dr->diagRecs;
3144 res->num_diagnostics = dr->num_diagRecs;
3148 res->num_diagnostics = 0;
3149 res->diagnostics = 0;
3151 res->resultCount = 0;
3154 apdu->which = Z_APDU_sortResponse;
3155 apdu->u.sortResponse = res;
3158 WRBUF wr = wrbuf_alloc();
3159 wrbuf_printf(wr, "Sort ");
3161 wrbuf_printf(wr, " ERROR %d", bsrr->errcode);
3163 wrbuf_printf(wr, "OK -");
3164 wrbuf_printf(wr, " (");
3165 for (i = 0; i<req->num_inputResultSetNames; i++)
3168 wrbuf_printf(wr, "+");
3169 wrbuf_puts(wr, req->inputResultSetNames[i]);
3171 wrbuf_printf(wr, ")->%s ",req->sortedResultSetName);
3173 yaz_log(log_request, "%s", wrbuf_cstr(wr) );
3179 static Z_APDU *process_deleteRequest(association *assoc, request *reqb)
3182 Z_DeleteResultSetRequest *req =
3183 reqb->apdu_request->u.deleteResultSetRequest;
3184 Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
3185 odr_malloc(assoc->encode, sizeof(*res));
3186 bend_delete_rr *bdrr = (bend_delete_rr *)
3187 odr_malloc(assoc->encode, sizeof(*bdrr));
3188 Z_APDU *apdu = (Z_APDU *)odr_malloc(assoc->encode, sizeof(*apdu));
3190 yaz_log(log_requestdetail, "Got DeleteRequest.");
3192 bdrr->num_setnames = req->num_resultSetList;
3193 bdrr->setnames = req->resultSetList;
3194 for (i = 0; i<req->num_resultSetList; i++)
3195 yaz_log(log_requestdetail, "resultset: '%s'",
3196 req->resultSetList[i]);
3197 bdrr->stream = assoc->encode;
3198 bdrr->print = assoc->print;
3199 bdrr->function = *req->deleteFunction;
3200 bdrr->referenceId = req->referenceId;
3202 if (bdrr->num_setnames > 0)
3204 bdrr->statuses = (Odr_int*)
3205 odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
3206 bdrr->num_setnames);
3207 for (i = 0; i < bdrr->num_setnames; i++)
3208 bdrr->statuses[i] = 0;
3210 (*assoc->init->bend_delete)(assoc->backend, bdrr);
3212 res->referenceId = req->referenceId;
3214 res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
3216 res->deleteListStatuses = 0;
3217 if (bdrr->num_setnames > 0)
3220 res->deleteListStatuses = (Z_ListStatuses *)
3221 odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
3222 res->deleteListStatuses->num = bdrr->num_setnames;
3223 res->deleteListStatuses->elements =
3225 odr_malloc(assoc->encode,
3226 sizeof(*res->deleteListStatuses->elements) *
3227 bdrr->num_setnames);
3228 for (i = 0; i<bdrr->num_setnames; i++)
3230 res->deleteListStatuses->elements[i] =
3232 odr_malloc(assoc->encode,
3233 sizeof(**res->deleteListStatuses->elements));
3234 res->deleteListStatuses->elements[i]->status = bdrr->statuses+i;
3235 res->deleteListStatuses->elements[i]->id =
3236 odr_strdup(assoc->encode, bdrr->setnames[i]);
3239 res->numberNotDeleted = 0;
3240 res->bulkStatuses = 0;
3241 res->deleteMessage = 0;
3244 apdu->which = Z_APDU_deleteResultSetResponse;
3245 apdu->u.deleteResultSetResponse = res;
3248 WRBUF wr = wrbuf_alloc();
3249 wrbuf_printf(wr, "Delete ");
3250 if (bdrr->delete_status)
3251 wrbuf_printf(wr, "ERROR %d", bdrr->delete_status);
3253 wrbuf_printf(wr, "OK -");
3254 for (i = 0; i<req->num_resultSetList; i++)
3255 wrbuf_printf(wr, " %s ", req->resultSetList[i]);
3256 yaz_log(log_request, "%s", wrbuf_cstr(wr) );
3262 static void process_close(association *assoc, request *reqb)
3264 Z_Close *req = reqb->apdu_request->u.close;
3265 static char *reasons[] =
3272 "securityViolation",
3279 yaz_log(log_requestdetail, "Got Close, reason %s, message %s",
3280 reasons[*req->closeReason], req->diagnosticInformation ?
3281 req->diagnosticInformation : "NULL");
3282 if (assoc->version < 3) /* to make do_force respond with close */
3284 do_close_req(assoc, Z_Close_finished,
3285 "Association terminated by client", reqb);
3286 yaz_log(log_request,"Close OK");
3289 static Z_APDU *process_segmentRequest(association *assoc, request *reqb)
3291 bend_segment_rr req;
3293 req.segment = reqb->apdu_request->u.segmentRequest;
3294 req.stream = assoc->encode;
3295 req.decode = assoc->decode;
3296 req.print = assoc->print;
3297 req.association = assoc;
3299 (*assoc->init->bend_segment)(assoc->backend, &req);
3304 static Z_APDU *process_ESRequest(association *assoc, request *reqb)
3306 bend_esrequest_rr esrequest;
3307 const char *ext_name = "unknown";
3309 Z_ExtendedServicesRequest *req =
3310 reqb->apdu_request->u.extendedServicesRequest;
3311 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
3313 Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
3315 esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
3316 esrequest.stream = assoc->encode;
3317 esrequest.decode = assoc->decode;
3318 esrequest.print = assoc->print;
3319 esrequest.errcode = 0;
3320 esrequest.errstring = NULL;
3321 esrequest.association = assoc;
3322 esrequest.taskPackage = 0;
3323 esrequest.referenceId = req->referenceId;
3325 if (esrequest.esr && esrequest.esr->taskSpecificParameters)
3327 switch(esrequest.esr->taskSpecificParameters->which)
3329 case Z_External_itemOrder:
3330 ext_name = "ItemOrder"; break;
3331 case Z_External_update:
3332 ext_name = "Update"; break;
3333 case Z_External_update0:
3334 ext_name = "Update0"; break;
3335 case Z_External_ESAdmin:
3336 ext_name = "Admin"; break;
3341 (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
3343 resp->referenceId = req->referenceId;
3345 if (esrequest.errcode == -1)
3347 /* Backend service indicates request will be processed */
3348 yaz_log(log_request, "Extended Service: %s (accepted)", ext_name);
3349 *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
3351 else if (esrequest.errcode == 0)
3353 /* Backend service indicates request will be processed */
3354 yaz_log(log_request, "Extended Service: %s (done)", ext_name);
3355 *resp->operationStatus = Z_ExtendedServicesResponse_done;
3359 Z_DiagRecs *diagRecs =
3360 zget_DiagRecs(assoc->encode, esrequest.errcode,
3361 esrequest.errstring);
3362 /* Backend indicates error, request will not be processed */
3363 yaz_log(log_request, "Extended Service: %s (failed)", ext_name);
3364 *resp->operationStatus = Z_ExtendedServicesResponse_failure;
3365 resp->num_diagnostics = diagRecs->num_diagRecs;
3366 resp->diagnostics = diagRecs->diagRecs;
3369 WRBUF wr = wrbuf_alloc();
3370 wrbuf_diags(wr, resp->num_diagnostics, resp->diagnostics);
3371 yaz_log(log_request, "EsRequest %s", wrbuf_cstr(wr) );
3376 /* Do something with the members of bend_extendedservice */
3377 if (esrequest.taskPackage)
3379 resp->taskPackage = z_ext_record_oid(
3380 assoc->encode, yaz_oid_recsyn_extended,
3381 (const char *) esrequest.taskPackage, -1);
3383 yaz_log(YLOG_DEBUG,"Send the result apdu");
3387 int bend_assoc_is_alive(bend_association assoc)
3389 if (assoc->state == ASSOC_DEAD)
3390 return 0; /* already marked as dead. Don't check I/O chan anymore */
3392 return iochan_is_alive(assoc->client_chan);
3399 * c-file-style: "Stroustrup"
3400 * indent-tabs-mode: nil
3402 * vim: shiftwidth=4 tabstop=8 expandtab