1 /* This file is part of the YAZ toolkit.
2 * Copyright (C) 1995-2011 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.
38 #include <sys/types.h>
46 #define S_ISREG(x) (x & _S_IFREG)
55 #include <libxml/parser.h>
56 #include <libxml/tree.h>
59 #include <yaz/yconfig.h>
60 #include <yaz/xmalloc.h>
61 #include <yaz/comstack.h>
65 #include <yaz/proto.h>
66 #include <yaz/oid_db.h>
68 #include <yaz/logrpn.h>
69 #include <yaz/querytowrbuf.h>
70 #include <yaz/statserv.h>
71 #include <yaz/diagbib1.h>
72 #include <yaz/charneg.h>
73 #include <yaz/otherinfo.h>
74 #include <yaz/yaz-util.h>
75 #include <yaz/pquery.h>
76 #include <yaz/oid_db.h>
79 #include <yaz/backend.h>
80 #include <yaz/yaz-ccl.h>
82 static void process_gdu_request(association *assoc, request *req);
83 static int process_z_request(association *assoc, request *req, char **msg);
84 static int process_gdu_response(association *assoc, request *req, Z_GDU *res);
85 static int process_z_response(association *assoc, request *req, Z_APDU *res);
86 static Z_APDU *process_initRequest(association *assoc, request *reqb);
87 static Z_External *init_diagnostics(ODR odr, int errcode,
88 const char *errstring);
89 static Z_APDU *process_searchRequest(association *assoc, request *reqb);
90 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
91 bend_search_rr *bsrr);
92 static Z_APDU *process_presentRequest(association *assoc, request *reqb);
93 static Z_APDU *process_scanRequest(association *assoc, request *reqb);
94 static Z_APDU *process_sortRequest(association *assoc, request *reqb);
95 static void process_close(association *assoc, request *reqb);
96 static Z_APDU *process_deleteRequest(association *assoc, request *reqb);
97 static Z_APDU *process_segmentRequest(association *assoc, request *reqb);
98 static Z_APDU *process_ESRequest(association *assoc, request *reqb);
100 /* dynamic logging levels */
101 static int logbits_set = 0;
102 static int log_session = 0; /* one-line logs for session */
103 static int log_sessiondetail = 0; /* more detailed stuff */
104 static int log_request = 0; /* one-line logs for requests */
105 static int log_requestdetail = 0; /* more detailed stuff */
107 /** get_logbits sets global loglevel bits */
108 static void get_logbits(void)
109 { /* needs to be called after parsing cmd-line args that can set loglevels!*/
113 log_session = yaz_log_module_level("session");
114 log_sessiondetail = yaz_log_module_level("sessiondetail");
115 log_request = yaz_log_module_level("request");
116 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), ' ', '_');
127 wrbuf_puts_replace_char(w, addinfo, ' ', '_');
132 static int odr_int_to_int(Odr_int v)
136 else if (v <= INT_MIN)
143 * Create and initialize a new association-handle.
144 * channel : iochannel for the current line.
145 * link : communications channel.
146 * Returns: 0 or a new association handle.
148 association *create_association(IOCHAN channel, COMSTACK link,
149 const char *apdufile)
155 if (!(anew = (association *)xmalloc(sizeof(*anew))))
159 anew->last_control = 0;
160 anew->client_chan = channel;
161 anew->client_link = link;
162 anew->cs_get_mask = 0;
163 anew->cs_put_mask = 0;
164 anew->cs_accept_mask = 0;
165 if (!(anew->decode = odr_createmem(ODR_DECODE)) ||
166 !(anew->encode = odr_createmem(ODR_ENCODE)))
168 if (apdufile && *apdufile)
172 if (!(anew->print = odr_createmem(ODR_PRINT)))
174 if (*apdufile == '@')
176 odr_setprint(anew->print, yaz_log_file());
178 else if (*apdufile != '-')
181 sprintf(filename, "%.200s.%ld", apdufile, (long)getpid());
182 if (!(f = fopen(filename, "w")))
184 yaz_log(YLOG_WARN|YLOG_ERRNO, "%s", filename);
187 setvbuf(f, 0, _IONBF, 0);
188 odr_setprint(anew->print, f);
193 anew->input_buffer = 0;
194 anew->input_buffer_len = 0;
196 anew->state = ASSOC_NEW;
197 request_initq(&anew->incoming);
198 request_initq(&anew->outgoing);
199 anew->proto = cs_getproto(link);
205 * Free association and release resources.
207 void destroy_association(association *h)
209 statserv_options_block *cb = statserv_getcontrol();
213 odr_destroy(h->decode);
214 odr_destroy(h->encode);
216 odr_destroy(h->print);
218 xfree(h->input_buffer);
220 (*cb->bend_close)(h->backend);
221 while ((req = request_deq(&h->incoming)))
222 request_release(req);
223 while ((req = request_deq(&h->outgoing)))
224 request_release(req);
225 request_delq(&h->incoming);
226 request_delq(&h->outgoing);
228 xmalloc_trav("session closed");
231 static void do_close_req(association *a, int reason, char *message,
234 Z_APDU *apdu = zget_APDU(a->encode, Z_APDU_close);
235 Z_Close *cls = apdu->u.close;
237 /* Purge request queue */
238 while (request_deq(&a->incoming));
239 while (request_deq(&a->outgoing));
242 yaz_log(log_requestdetail, "Sending Close PDU, reason=%d, message=%s",
243 reason, message ? message : "none");
244 *cls->closeReason = reason;
245 cls->diagnosticInformation = message;
246 process_z_response(a, req, apdu);
247 iochan_settimeout(a->client_chan, 20);
251 request_release(req);
252 yaz_log(log_requestdetail, "v2 client. No Close PDU");
253 iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
256 a->state = ASSOC_DEAD;
259 static void do_close(association *a, int reason, char *message)
261 request *req = request_get(&a->outgoing);
262 do_close_req(a, reason, message, req);
266 int ir_read(IOCHAN h, int event)
268 association *assoc = (association *)iochan_getdata(h);
269 COMSTACK conn = assoc->client_link;
272 if ((assoc->cs_put_mask & EVENT_INPUT) == 0 && (event & assoc->cs_get_mask))
274 yaz_log(YLOG_DEBUG, "ir_session (input)");
275 /* We aren't speaking to this fellow */
276 if (assoc->state == ASSOC_DEAD)
278 yaz_log(log_sessiondetail, "Connection closed - end of session");
280 destroy_association(assoc);
284 assoc->cs_get_mask = EVENT_INPUT;
288 int res = cs_get(conn, &assoc->input_buffer,
289 &assoc->input_buffer_len);
290 if (res < 0 && cs_errno(conn) == CSBUFSIZE)
292 yaz_log(log_session, "Connection error: %s res=%d",
293 cs_errmsg(cs_errno(conn)), res);
294 req = request_get(&assoc->incoming); /* get a new request */
295 do_close_req(assoc, Z_Close_protocolError,
296 "Incoming package too large", req);
301 yaz_log(log_session, "Connection closed by client");
302 assoc->state = ASSOC_DEAD;
305 else if (res == 1) /* incomplete read - wait for more */
307 if (conn->io_pending & CS_WANT_WRITE)
308 assoc->cs_get_mask |= EVENT_OUTPUT;
309 iochan_setflag(h, assoc->cs_get_mask);
312 /* we got a complete PDU. Let's decode it */
313 yaz_log(YLOG_DEBUG, "Got PDU, %d bytes: lead=%02X %02X %02X", res,
314 assoc->input_buffer[0] & 0xff,
315 assoc->input_buffer[1] & 0xff,
316 assoc->input_buffer[2] & 0xff);
317 req = request_get(&assoc->incoming); /* get a new request */
318 odr_reset(assoc->decode);
319 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
320 if (!z_GDU(assoc->decode, &req->gdu_request, 0, 0))
322 yaz_log(YLOG_WARN, "ODR error on incoming PDU: %s [element %s] "
324 odr_errmsg(odr_geterror(assoc->decode)),
325 odr_getelement(assoc->decode),
326 (long) odr_offset(assoc->decode));
327 if (assoc->decode->error != OHTTP)
329 yaz_log(YLOG_WARN, "PDU dump:");
330 odr_dumpBER(yaz_log_file(), assoc->input_buffer, res);
331 request_release(req);
332 do_close(assoc, Z_Close_protocolError, "Malformed package");
336 Z_GDU *p = z_get_HTTP_Response(assoc->encode, 400);
337 assoc->state = ASSOC_DEAD;
338 process_gdu_response(assoc, req, p);
342 req->request_mem = odr_extract_mem(assoc->decode);
345 if (!z_GDU(assoc->print, &req->gdu_request, 0, 0))
346 yaz_log(YLOG_WARN, "ODR print error: %s",
347 odr_errmsg(odr_geterror(assoc->print)));
348 odr_reset(assoc->print);
350 request_enq(&assoc->incoming, req);
352 while (cs_more(conn));
358 * This is where PDUs from the client are read and the further
359 * processing is initiated. Flow of control moves down through the
360 * various process_* functions below, until the encoded result comes back up
361 * to the output handler in here.
363 * h : the I/O channel that has an outstanding event.
364 * event : the current outstanding event.
366 void ir_session(IOCHAN h, int event)
369 association *assoc = (association *)iochan_getdata(h);
370 COMSTACK conn = assoc->client_link;
373 assert(h && conn && assoc);
374 if (event == EVENT_TIMEOUT)
376 if (assoc->state != ASSOC_UP)
378 yaz_log(log_session, "Timeout. Closing connection");
379 /* do we need to lod this at all */
381 destroy_association(assoc);
386 yaz_log(log_sessiondetail, "Timeout. Sending Z39.50 Close");
387 do_close(assoc, Z_Close_lackOfActivity, 0);
391 if (event & assoc->cs_accept_mask)
393 if (!cs_accept(conn))
395 yaz_log(YLOG_WARN, "accept failed");
396 destroy_association(assoc);
400 iochan_clearflag(h, EVENT_OUTPUT);
401 if (conn->io_pending)
402 { /* cs_accept didn't complete */
403 assoc->cs_accept_mask =
404 ((conn->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
405 ((conn->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
407 iochan_setflag(h, assoc->cs_accept_mask);
410 { /* cs_accept completed. Prepare for reading (cs_get) */
411 assoc->cs_accept_mask = 0;
412 assoc->cs_get_mask = EVENT_INPUT;
413 iochan_setflag(h, assoc->cs_get_mask);
417 if (event & assoc->cs_get_mask) /* input */
419 if (!ir_read(h, event))
421 req = request_head(&assoc->incoming);
422 if (req->state == REQUEST_IDLE)
424 request_deq(&assoc->incoming);
425 process_gdu_request(assoc, req);
428 if (event & assoc->cs_put_mask)
430 request *req = request_head(&assoc->outgoing);
432 assoc->cs_put_mask = 0;
433 yaz_log(YLOG_DEBUG, "ir_session (output)");
434 req->state = REQUEST_PENDING;
435 switch (res = cs_put(conn, req->response, req->len_response))
438 yaz_log(log_sessiondetail, "Connection closed by client");
440 destroy_association(assoc);
443 case 0: /* all sent - release the request structure */
444 yaz_log(YLOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
446 yaz_log(YLOG_DEBUG, "HTTP out:\n%.*s", req->len_response,
449 nmem_destroy(req->request_mem);
450 request_deq(&assoc->outgoing);
451 request_release(req);
452 if (!request_head(&assoc->outgoing))
453 { /* restore mask for cs_get operation ... */
454 iochan_clearflag(h, EVENT_OUTPUT|EVENT_INPUT);
455 iochan_setflag(h, assoc->cs_get_mask);
456 if (assoc->state == ASSOC_DEAD)
457 iochan_setevent(assoc->client_chan, EVENT_TIMEOUT);
461 assoc->cs_put_mask = EVENT_OUTPUT;
465 if (conn->io_pending & CS_WANT_WRITE)
466 assoc->cs_put_mask |= EVENT_OUTPUT;
467 if (conn->io_pending & CS_WANT_READ)
468 assoc->cs_put_mask |= EVENT_INPUT;
469 iochan_setflag(h, assoc->cs_put_mask);
472 if (event & EVENT_EXCEPT)
474 yaz_log(YLOG_WARN, "ir_session (exception)");
476 destroy_association(assoc);
481 static int process_z_request(association *assoc, request *req, char **msg);
484 static void assoc_init_reset(association *assoc)
487 assoc->init = (bend_initrequest *) xmalloc(sizeof(*assoc->init));
489 assoc->init->stream = assoc->encode;
490 assoc->init->print = assoc->print;
491 assoc->init->auth = 0;
492 assoc->init->referenceId = 0;
493 assoc->init->implementation_version = 0;
494 assoc->init->implementation_id = 0;
495 assoc->init->implementation_name = 0;
496 assoc->init->query_charset = 0;
497 assoc->init->records_in_same_charset = 0;
498 assoc->init->bend_sort = NULL;
499 assoc->init->bend_search = NULL;
500 assoc->init->bend_present = NULL;
501 assoc->init->bend_esrequest = NULL;
502 assoc->init->bend_delete = NULL;
503 assoc->init->bend_scan = NULL;
504 assoc->init->bend_segment = NULL;
505 assoc->init->bend_fetch = NULL;
506 assoc->init->bend_explain = NULL;
507 assoc->init->bend_srw_scan = NULL;
508 assoc->init->bend_srw_update = NULL;
509 assoc->init->named_result_sets = 0;
511 assoc->init->charneg_request = NULL;
512 assoc->init->charneg_response = NULL;
514 assoc->init->decode = assoc->decode;
515 assoc->init->peer_name =
516 odr_strdup(assoc->encode, cs_addrstr(assoc->client_link));
518 yaz_log(log_requestdetail, "peer %s", assoc->init->peer_name);
521 static int srw_bend_init(association *assoc, Z_SRW_diagnostic **d, int *num, Z_SRW_PDU *sr)
523 statserv_options_block *cb = statserv_getcontrol();
526 const char *encoding = "UTF-8";
528 bend_initresult *binitres;
530 yaz_log(log_requestdetail, "srw_bend_init config=%s", cb->configname);
531 assoc_init_reset(assoc);
535 Z_IdAuthentication *auth = (Z_IdAuthentication *)
536 odr_malloc(assoc->decode, sizeof(*auth));
539 len = strlen(sr->username) + 1;
541 len += strlen(sr->password) + 2;
542 yaz_log(log_requestdetail, "username=%s password-len=%ld",
544 (sr->password ? strlen(sr->password) : 0));
545 auth->which = Z_IdAuthentication_open;
546 auth->u.open = (char *) odr_malloc(assoc->decode, len);
547 strcpy(auth->u.open, sr->username);
548 if (sr->password && *sr->password)
550 strcat(auth->u.open, "/");
551 strcat(auth->u.open, sr->password);
553 assoc->init->auth = auth;
557 ce = yaz_set_proposal_charneg(assoc->decode, &encoding, 1, 0, 0, 1);
558 assoc->init->charneg_request = ce->u.charNeg3;
561 if (!(binitres = (*cb->bend_init)(assoc->init)))
563 assoc->state = ASSOC_DEAD;
564 yaz_add_srw_diagnostic(assoc->encode, d, num,
565 YAZ_SRW_AUTHENTICATION_ERROR, 0);
568 assoc->backend = binitres->handle;
569 assoc->init->auth = 0;
570 if (binitres->errcode)
572 int srw_code = yaz_diag_bib1_to_srw(binitres->errcode);
573 assoc->state = ASSOC_DEAD;
574 yaz_add_srw_diagnostic(assoc->encode, d, num, srw_code,
575 binitres->errstring);
583 static int retrieve_fetch(association *assoc, bend_fetch_rr *rr)
586 yaz_record_conv_t rc = 0;
587 const char *match_schema = 0;
588 Odr_oid *match_syntax = 0;
593 const char *input_schema = yaz_get_esn(rr->comp);
594 Odr_oid *input_syntax_raw = rr->request_format;
596 const char *backend_schema = 0;
597 Odr_oid *backend_syntax = 0;
599 r = yaz_retrieval_request(assoc->server->retrieval,
607 if (r == -1) /* error ? */
609 const char *details = yaz_retrieval_get_error(
610 assoc->server->retrieval);
612 rr->errcode = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
614 rr->errstring = odr_strdup(rr->stream, details);
617 else if (r == 1 || r == 3)
619 const char *details = input_schema;
621 YAZ_BIB1_SPECIFIED_ELEMENT_SET_NAME_NOT_VALID_FOR_SPECIFIED_;
623 rr->errstring = odr_strdup(rr->stream, details);
628 rr->errcode = YAZ_BIB1_RECORD_SYNTAX_UNSUPP;
629 if (input_syntax_raw)
631 char oidbuf[OID_STR_MAX];
632 oid_oid_to_dotstring(input_syntax_raw, oidbuf);
633 rr->errstring = odr_strdup(rr->stream, oidbuf);
639 yaz_set_esn(&rr->comp, backend_schema, odr_getmem(rr->stream));
642 rr->request_format = backend_syntax;
644 (*assoc->init->bend_fetch)(assoc->backend, rr);
645 if (rc && rr->record && rr->errcode == 0 && rr->len > 0)
646 { /* post conversion must take place .. */
647 WRBUF output_record = wrbuf_alloc();
648 int r = yaz_record_conv_record(rc, rr->record, rr->len, output_record);
651 const char *details = yaz_record_conv_get_error(rc);
652 rr->errcode = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
654 rr->errstring = odr_strdup(rr->stream, details);
658 rr->len = wrbuf_len(output_record);
659 rr->record = (char *) odr_malloc(rr->stream, rr->len);
660 memcpy(rr->record, wrbuf_buf(output_record), rr->len);
662 wrbuf_destroy(output_record);
665 rr->output_format = match_syntax;
667 rr->schema = odr_strdup(rr->stream, match_schema);
669 (*assoc->init->bend_fetch)(assoc->backend, rr);
674 static int srw_bend_fetch(association *assoc, int pos,
675 Z_SRW_searchRetrieveRequest *srw_req,
676 Z_SRW_record *record,
677 const char **addinfo)
680 ODR o = assoc->encode;
682 rr.setname = "default";
685 rr.request_format = odr_oiddup(assoc->decode, yaz_oid_recsyn_xml);
687 rr.comp = (Z_RecordComposition *)
688 odr_malloc(assoc->decode, sizeof(*rr.comp));
689 rr.comp->which = Z_RecordComp_complex;
690 rr.comp->u.complex = (Z_CompSpec *)
691 odr_malloc(assoc->decode, sizeof(Z_CompSpec));
692 rr.comp->u.complex->selectAlternativeSyntax = (bool_t *)
693 odr_malloc(assoc->encode, sizeof(bool_t));
694 *rr.comp->u.complex->selectAlternativeSyntax = 0;
695 rr.comp->u.complex->num_dbSpecific = 0;
696 rr.comp->u.complex->dbSpecific = 0;
697 rr.comp->u.complex->num_recordSyntax = 0;
698 rr.comp->u.complex->recordSyntax = 0;
700 rr.comp->u.complex->generic = (Z_Specification *)
701 odr_malloc(assoc->decode, sizeof(Z_Specification));
703 /* schema uri = recordSchema (or NULL if recordSchema is not given) */
704 rr.comp->u.complex->generic->which = Z_Schema_uri;
705 rr.comp->u.complex->generic->schema.uri = srw_req->recordSchema;
707 /* ESN = recordSchema if recordSchema is present */
708 rr.comp->u.complex->generic->elementSpec = 0;
709 if (srw_req->recordSchema)
711 rr.comp->u.complex->generic->elementSpec =
712 (Z_ElementSpec *) odr_malloc(assoc->encode, sizeof(Z_ElementSpec));
713 rr.comp->u.complex->generic->elementSpec->which =
714 Z_ElementSpec_elementSetName;
715 rr.comp->u.complex->generic->elementSpec->u.elementSetName =
716 srw_req->recordSchema;
719 rr.stream = assoc->encode;
720 rr.print = assoc->print;
728 rr.surrogate_flag = 0;
729 rr.schema = srw_req->recordSchema;
731 if (!assoc->init->bend_fetch)
734 retrieve_fetch(assoc, &rr);
736 if (rr.errcode && rr.surrogate_flag)
738 int code = yaz_diag_bib1_to_srw(rr.errcode);
739 yaz_mk_sru_surrogate(o, record, pos, code, rr.errstring);
742 else if (rr.len >= 0)
744 record->recordData_buf = rr.record;
745 record->recordData_len = rr.len;
746 record->recordPosition = odr_intdup(o, pos);
747 record->recordSchema = odr_strdup_null(
748 o, rr.schema ? rr.schema : srw_req->recordSchema);
752 *addinfo = rr.errstring;
758 static int cql2pqf(ODR odr, const char *cql, cql_transform_t ct,
759 Z_Query *query_result)
761 /* have a CQL query and CQL to PQF transform .. */
762 CQL_parser cp = cql_parser_create();
768 r = cql_parser_string(cp, cql);
771 srw_errcode = YAZ_SRW_QUERY_SYNTAX_ERROR;
776 r = cql_transform_buf(ct,
777 cql_parser_result(cp),
778 rpn_buf, sizeof(rpn_buf)-1);
780 srw_errcode = cql_transform_error(ct, &add);
784 /* Syntax & transform OK. */
785 /* Convert PQF string to Z39.50 to RPN query struct */
786 YAZ_PQF_Parser pp = yaz_pqf_create();
787 Z_RPNQuery *rpnquery = yaz_pqf_parse(pp, odr, rpn_buf);
792 int code = yaz_pqf_error(pp, &pqf_msg, &off);
793 yaz_log(YLOG_WARN, "PQF Parser Error %s (code %d)",
795 srw_errcode = YAZ_SRW_QUERY_SYNTAX_ERROR;
799 query_result->which = Z_Query_type_1;
800 query_result->u.type_1 = rpnquery;
804 cql_parser_destroy(cp);
808 static int cql2pqf_scan(ODR odr, const char *cql, cql_transform_t ct,
809 Z_AttributesPlusTerm *result)
813 int srw_error = cql2pqf(odr, cql, ct, &query);
816 if (query.which != Z_Query_type_1 && query.which != Z_Query_type_101)
817 return YAZ_SRW_QUERY_SYNTAX_ERROR; /* bad query type */
818 rpn = query.u.type_1;
819 if (!rpn->RPNStructure)
820 return YAZ_SRW_QUERY_SYNTAX_ERROR; /* must be structure */
821 if (rpn->RPNStructure->which != Z_RPNStructure_simple)
822 return YAZ_SRW_QUERY_SYNTAX_ERROR; /* must be simple */
823 if (rpn->RPNStructure->u.simple->which != Z_Operand_APT)
824 return YAZ_SRW_QUERY_SYNTAX_ERROR; /* must be be attributes + term */
825 memcpy(result, rpn->RPNStructure->u.simple->u.attributesPlusTerm,
831 static int ccl2pqf(ODR odr, const Odr_oct *ccl, CCL_bibset bibset,
832 bend_search_rr *bsrr)
835 struct ccl_rpn_node *node;
838 ccl0 = odr_strdupn(odr, (char*) ccl->buf, ccl->len);
839 if ((node = ccl_find_str(bibset, ccl0, &errcode, &pos)) == 0)
841 bsrr->errstring = (char*) ccl_err_msg(errcode);
842 return YAZ_SRW_QUERY_SYNTAX_ERROR; /* Query syntax error */
845 bsrr->query->which = Z_Query_type_1;
846 bsrr->query->u.type_1 = ccl_rpn_query(odr, node);
850 static void srw_bend_search(association *assoc,
855 Z_SRW_searchRetrieveResponse *srw_res = res->u.response;
858 Z_SRW_searchRetrieveRequest *srw_req = sr->u.request;
861 yaz_log(log_requestdetail, "Got SRW SearchRetrieveRequest");
862 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
863 if (srw_res->num_diagnostics == 0 && assoc->init)
866 rr.setname = "default";
869 rr.basenames = &srw_req->database;
873 rr.srw_setnameIdleTime = 0;
874 rr.estimated_hit_count = 0;
875 rr.partial_resultset = 0;
876 rr.query = (Z_Query *) odr_malloc(assoc->decode, sizeof(*rr.query));
877 rr.query->u.type_1 = 0;
878 rr.extra_args = sr->extra_args;
879 rr.extra_response_data = 0;
881 if (srw_req->query_type == Z_SRW_query_type_cql)
883 if (assoc->server && assoc->server->cql_transform)
885 int srw_errcode = cql2pqf(assoc->encode, srw_req->query.cql,
886 assoc->server->cql_transform,
890 yaz_add_srw_diagnostic(assoc->encode,
891 &srw_res->diagnostics,
892 &srw_res->num_diagnostics,
898 /* CQL query to backend. Wrap it - Z39.50 style */
899 ext = (Z_External *) odr_malloc(assoc->decode, sizeof(*ext));
900 ext->direct_reference = odr_getoidbystr(assoc->decode,
901 "1.2.840.10003.16.2");
902 ext->indirect_reference = 0;
904 ext->which = Z_External_CQL;
905 ext->u.cql = srw_req->query.cql;
907 rr.query->which = Z_Query_type_104;
908 rr.query->u.type_104 = ext;
911 else if (srw_req->query_type == Z_SRW_query_type_pqf)
913 Z_RPNQuery *RPNquery;
914 YAZ_PQF_Parser pqf_parser;
916 pqf_parser = yaz_pqf_create();
918 RPNquery = yaz_pqf_parse(pqf_parser, assoc->decode,
924 int code = yaz_pqf_error(pqf_parser, &pqf_msg, &off);
925 yaz_log(log_requestdetail, "Parse error %d %s near offset %ld",
926 code, pqf_msg, (long) off);
927 srw_error = YAZ_SRW_QUERY_SYNTAX_ERROR;
930 rr.query->which = Z_Query_type_1;
931 rr.query->u.type_1 = RPNquery;
933 yaz_pqf_destroy(pqf_parser);
937 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
938 &srw_res->num_diagnostics,
939 YAZ_SRW_UNSUPP_QUERY_TYPE, 0);
941 if (rr.query->u.type_1)
943 rr.stream = assoc->encode;
944 rr.decode = assoc->decode;
945 rr.print = assoc->print;
946 if ( srw_req->sort.sortKeys )
947 rr.srw_sortKeys = odr_strdup(assoc->encode,
948 srw_req->sort.sortKeys );
949 rr.association = assoc;
955 yaz_log_zquery_level(log_requestdetail,rr.query);
957 (assoc->init->bend_search)(assoc->backend, &rr);
960 if (rr.errcode == YAZ_BIB1_DATABASE_UNAVAILABLE)
966 srw_error = yaz_diag_bib1_to_srw(rr.errcode);
967 yaz_add_srw_diagnostic(assoc->encode,
968 &srw_res->diagnostics,
969 &srw_res->num_diagnostics,
970 srw_error, rr.errstring);
975 int number = srw_req->maximumRecords ?
976 odr_int_to_int(*srw_req->maximumRecords) : 0;
977 int start = srw_req->startRecord ?
978 odr_int_to_int(*srw_req->startRecord) : 1;
980 yaz_log(log_requestdetail, "Request to pack %d+%d out of "
982 start, number, rr.hits);
984 srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
987 srw_res->resultSetId =
988 odr_strdup(assoc->encode, rr.srw_setname );
989 srw_res->resultSetIdleTime =
990 odr_intdup(assoc->encode, *rr.srw_setnameIdleTime );
993 if (start > rr.hits || start < 1)
995 /* if hits<=0 and start=1 we don't return a diagnostic */
997 yaz_add_srw_diagnostic(
999 &srw_res->diagnostics, &srw_res->num_diagnostics,
1000 YAZ_SRW_FIRST_RECORD_POSITION_OUT_OF_RANGE, 0);
1002 else if (number > 0)
1006 if (start + number > rr.hits)
1007 number = odr_int_to_int(rr.hits) - start + 1;
1009 /* Call bend_present if defined */
1010 if (assoc->init->bend_present)
1012 bend_present_rr *bprr = (bend_present_rr*)
1013 odr_malloc(assoc->decode, sizeof(*bprr));
1014 bprr->setname = "default";
1015 bprr->start = start;
1016 bprr->number = number;
1017 if (srw_req->recordSchema)
1019 bprr->comp = (Z_RecordComposition *) odr_malloc(assoc->decode,
1020 sizeof(*bprr->comp));
1021 bprr->comp->which = Z_RecordComp_simple;
1022 bprr->comp->u.simple = (Z_ElementSetNames *)
1023 odr_malloc(assoc->decode, sizeof(Z_ElementSetNames));
1024 bprr->comp->u.simple->which = Z_ElementSetNames_generic;
1025 bprr->comp->u.simple->u.generic = srw_req->recordSchema;
1031 bprr->stream = assoc->encode;
1032 bprr->referenceId = 0;
1033 bprr->print = assoc->print;
1034 bprr->association = assoc;
1036 bprr->errstring = NULL;
1037 (*assoc->init->bend_present)(assoc->backend, bprr);
1041 srw_error = yaz_diag_bib1_to_srw(bprr->errcode);
1042 yaz_add_srw_diagnostic(assoc->encode,
1043 &srw_res->diagnostics,
1044 &srw_res->num_diagnostics,
1045 srw_error, bprr->errstring);
1053 int packing = Z_SRW_recordPacking_string;
1054 if (srw_req->recordPacking)
1057 yaz_srw_str_to_pack(srw_req->recordPacking);
1059 packing = Z_SRW_recordPacking_string;
1061 srw_res->records = (Z_SRW_record *)
1062 odr_malloc(assoc->encode,
1063 number * sizeof(*srw_res->records));
1065 srw_res->extra_records = (Z_SRW_extra_record **)
1066 odr_malloc(assoc->encode,
1067 number*sizeof(*srw_res->extra_records));
1069 for (i = 0; i<number; i++)
1072 const char *addinfo = 0;
1074 srw_res->records[j].recordPacking = packing;
1075 srw_res->records[j].recordData_buf = 0;
1076 srw_res->extra_records[j] = 0;
1077 yaz_log(YLOG_DEBUG, "srw_bend_fetch %d", i+start);
1078 errcode = srw_bend_fetch(assoc, i+start, srw_req,
1079 srw_res->records + j,
1083 yaz_add_srw_diagnostic(assoc->encode,
1084 &srw_res->diagnostics,
1085 &srw_res->num_diagnostics,
1086 yaz_diag_bib1_to_srw(errcode),
1091 if (srw_res->records[j].recordData_buf)
1094 srw_res->num_records = j;
1096 srw_res->records = 0;
1099 if (rr.extra_response_data)
1101 res->extraResponseData_buf = rr.extra_response_data;
1102 res->extraResponseData_len = strlen(rr.extra_response_data);
1104 if (rr.estimated_hit_count || rr.partial_resultset)
1106 yaz_add_srw_diagnostic(
1108 &srw_res->diagnostics,
1109 &srw_res->num_diagnostics,
1110 YAZ_SRW_RESULT_SET_CREATED_WITH_VALID_PARTIAL_RESULTS_AVAILABLE,
1118 const char *querystr = "?";
1119 const char *querytype = "?";
1120 WRBUF wr = wrbuf_alloc();
1122 switch (srw_req->query_type)
1124 case Z_SRW_query_type_cql:
1126 querystr = srw_req->query.cql;
1128 case Z_SRW_query_type_pqf:
1130 querystr = srw_req->query.pqf;
1133 wrbuf_printf(wr, "SRWSearch %s ", srw_req->database);
1134 if (srw_res->num_diagnostics)
1135 wrbuf_printf(wr, "ERROR %s", srw_res->diagnostics[0].uri);
1136 else if (*http_code != 200)
1137 wrbuf_printf(wr, "ERROR info:http/%d", *http_code);
1138 else if (srw_res->numberOfRecords)
1140 wrbuf_printf(wr, "OK " ODR_INT_PRINTF,
1141 (srw_res->numberOfRecords ?
1142 *srw_res->numberOfRecords : 0));
1144 wrbuf_printf(wr, " %s " ODR_INT_PRINTF "+%d",
1145 (srw_res->resultSetId ?
1146 srw_res->resultSetId : "-"),
1147 (srw_req->startRecord ? *srw_req->startRecord : 1),
1148 srw_res->num_records);
1149 yaz_log(log_request, "%s %s: %s", wrbuf_cstr(wr), querytype, querystr);
1154 static char *srw_bend_explain_default(bend_explain_rr *rr)
1157 xmlNodePtr ptr = (xmlNode *) rr->server_node_ptr;
1160 for (ptr = ptr->children; ptr; ptr = ptr->next)
1162 if (ptr->type != XML_ELEMENT_NODE)
1164 if (!strcmp((const char *) ptr->name, "explain"))
1167 xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
1171 ptr = xmlCopyNode(ptr, 1);
1173 xmlDocSetRootElement(doc, ptr);
1175 xmlDocDumpMemory(doc, &buf_out, &len);
1176 content = (char*) odr_malloc(rr->stream, 1+len);
1177 memcpy(content, buf_out, len);
1178 content[len] = '\0';
1182 rr->explain_buf = content;
1190 static void srw_bend_explain(association *assoc,
1192 Z_SRW_explainResponse *srw_res,
1195 Z_SRW_explainRequest *srw_req = sr->u.explain_request;
1196 yaz_log(log_requestdetail, "Got SRW ExplainRequest");
1198 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1203 rr.stream = assoc->encode;
1204 rr.decode = assoc->decode;
1205 rr.print = assoc->print;
1207 rr.database = srw_req->database;
1209 rr.server_node_ptr = assoc->server->server_node_ptr;
1211 rr.server_node_ptr = 0;
1212 rr.schema = "http://explain.z3950.org/dtd/2.0/";
1213 if (assoc->init->bend_explain)
1214 (*assoc->init->bend_explain)(assoc->backend, &rr);
1216 srw_bend_explain_default(&rr);
1220 int packing = Z_SRW_recordPacking_string;
1221 if (srw_req->recordPacking)
1224 yaz_srw_str_to_pack(srw_req->recordPacking);
1226 packing = Z_SRW_recordPacking_string;
1228 srw_res->record.recordSchema = rr.schema;
1229 srw_res->record.recordPacking = packing;
1230 srw_res->record.recordData_buf = rr.explain_buf;
1231 srw_res->record.recordData_len = strlen(rr.explain_buf);
1232 srw_res->record.recordPosition = 0;
1238 static void srw_bend_scan(association *assoc,
1240 Z_SRW_scanResponse *srw_res,
1243 Z_SRW_scanRequest *srw_req = sr->u.scan_request;
1244 yaz_log(log_requestdetail, "Got SRW ScanRequest");
1247 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1248 if (srw_res->num_diagnostics == 0 && assoc->init)
1251 struct scan_entry *save_entries;
1253 bend_scan_rr *bsrr = (bend_scan_rr *)
1254 odr_malloc(assoc->encode, sizeof(*bsrr));
1255 bsrr->num_bases = 1;
1256 bsrr->basenames = &srw_req->database;
1258 bsrr->num_entries = srw_req->maximumTerms ?
1259 odr_int_to_int(*srw_req->maximumTerms) : 10;
1260 bsrr->term_position = srw_req->responsePosition ?
1261 odr_int_to_int(*srw_req->responsePosition) : 1;
1264 bsrr->errstring = 0;
1265 bsrr->referenceId = 0;
1266 bsrr->stream = assoc->encode;
1267 bsrr->print = assoc->print;
1268 bsrr->step_size = &step_size;
1272 if (bsrr->num_entries > 0)
1275 bsrr->entries = (struct scan_entry *)
1276 odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
1278 for (i = 0; i<bsrr->num_entries; i++)
1280 bsrr->entries[i].term = 0;
1281 bsrr->entries[i].occurrences = 0;
1282 bsrr->entries[i].errcode = 0;
1283 bsrr->entries[i].errstring = 0;
1284 bsrr->entries[i].display_term = 0;
1287 save_entries = bsrr->entries; /* save it so we can compare later */
1289 if (srw_req->query_type == Z_SRW_query_type_pqf &&
1290 assoc->init->bend_scan)
1292 YAZ_PQF_Parser pqf_parser = yaz_pqf_create();
1294 bsrr->term = yaz_pqf_scan(pqf_parser, assoc->decode,
1295 &bsrr->attributeset,
1296 srw_req->scanClause.pqf);
1297 yaz_pqf_destroy(pqf_parser);
1298 bsrr->scanClause = 0;
1299 ((int (*)(void *, bend_scan_rr *))
1300 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1302 else if (srw_req->query_type == Z_SRW_query_type_cql
1303 && assoc->init->bend_scan && assoc->server
1304 && assoc->server->cql_transform)
1307 bsrr->scanClause = 0;
1308 bsrr->attributeset = 0;
1309 bsrr->term = (Z_AttributesPlusTerm *)
1310 odr_malloc(assoc->decode, sizeof(*bsrr->term));
1311 srw_error = cql2pqf_scan(assoc->encode,
1312 srw_req->scanClause.cql,
1313 assoc->server->cql_transform,
1316 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1317 &srw_res->num_diagnostics,
1321 ((int (*)(void *, bend_scan_rr *))
1322 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1325 else if (srw_req->query_type == Z_SRW_query_type_cql
1326 && assoc->init->bend_srw_scan)
1329 bsrr->attributeset = 0;
1330 bsrr->scanClause = srw_req->scanClause.cql;
1331 ((int (*)(void *, bend_scan_rr *))
1332 (*assoc->init->bend_srw_scan))(assoc->backend, bsrr);
1336 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1337 &srw_res->num_diagnostics,
1338 YAZ_SRW_UNSUPP_OPERATION, "scan");
1343 if (bsrr->errcode == YAZ_BIB1_DATABASE_UNAVAILABLE)
1348 srw_error = yaz_diag_bib1_to_srw(bsrr->errcode);
1350 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1351 &srw_res->num_diagnostics,
1352 srw_error, bsrr->errstring);
1354 else if (srw_res->num_diagnostics == 0 && bsrr->num_entries)
1357 srw_res->terms = (Z_SRW_scanTerm*)
1358 odr_malloc(assoc->encode, sizeof(*srw_res->terms) *
1361 srw_res->num_terms = bsrr->num_entries;
1362 for (i = 0; i<bsrr->num_entries; i++)
1364 Z_SRW_scanTerm *t = srw_res->terms + i;
1365 t->value = odr_strdup(assoc->encode, bsrr->entries[i].term);
1366 t->numberOfRecords =
1367 odr_intdup(assoc->encode, bsrr->entries[i].occurrences);
1369 if (save_entries == bsrr->entries &&
1370 bsrr->entries[i].display_term)
1372 /* the entries was _not_ set by the handler. So it's
1373 safe to test for new member display_term. It is
1376 t->displayTerm = odr_strdup(assoc->encode,
1377 bsrr->entries[i].display_term);
1385 WRBUF wr = wrbuf_alloc();
1386 const char *querytype = 0;
1387 const char *querystr = 0;
1389 switch(srw_req->query_type)
1391 case Z_SRW_query_type_pqf:
1393 querystr = srw_req->scanClause.pqf;
1395 case Z_SRW_query_type_cql:
1397 querystr = srw_req->scanClause.cql;
1400 querytype = "UNKNOWN";
1404 wrbuf_printf(wr, "SRWScan %s ", srw_req->database);
1406 if (srw_res->num_diagnostics)
1407 wrbuf_printf(wr, "ERROR %s - ", srw_res->diagnostics[0].uri);
1408 else if (srw_res->num_terms)
1409 wrbuf_printf(wr, "OK %d - ", srw_res->num_terms);
1411 wrbuf_printf(wr, "OK - - ");
1413 wrbuf_printf(wr, ODR_INT_PRINTF "+" ODR_INT_PRINTF " ",
1414 (srw_req->responsePosition ?
1415 *srw_req->responsePosition : 1),
1416 (srw_req->maximumTerms ?
1417 *srw_req->maximumTerms : 1));
1418 /* there is no step size in SRU/W ??? */
1419 wrbuf_printf(wr, "%s: %s ", querytype, querystr);
1420 yaz_log(log_request, "%s ", wrbuf_cstr(wr) );
1426 static void srw_bend_update(association *assoc,
1428 Z_SRW_updateResponse *srw_res,
1431 Z_SRW_updateRequest *srw_req = sr->u.update_request;
1432 yaz_log(log_session, "SRWUpdate action=%s", srw_req->operation);
1433 yaz_log(YLOG_DEBUG, "num_diag = %d", srw_res->num_diagnostics );
1435 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1439 Z_SRW_extra_record *extra = srw_req->extra_record;
1441 rr.stream = assoc->encode;
1442 rr.print = assoc->print;
1444 rr.basenames = &srw_req->database;
1445 rr.operation = srw_req->operation;
1446 rr.operation_status = "failed";
1448 rr.record_versions = 0;
1449 rr.num_versions = 0;
1450 rr.record_packing = "string";
1451 rr.record_schema = 0;
1453 rr.extra_record_data = 0;
1454 rr.extra_request_data = 0;
1455 rr.extra_response_data = 0;
1461 if (rr.operation == 0)
1463 yaz_add_sru_update_diagnostic(
1464 assoc->encode, &srw_res->diagnostics,
1465 &srw_res->num_diagnostics,
1466 YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,
1470 yaz_log(YLOG_DEBUG, "basename = %s", rr.basenames[0] );
1471 yaz_log(YLOG_DEBUG, "Operation = %s", rr.operation );
1472 if (!strcmp( rr.operation, "delete"))
1474 if (srw_req->record && !srw_req->record->recordSchema)
1476 rr.record_schema = odr_strdup(
1478 srw_req->record->recordSchema);
1480 if (srw_req->record)
1482 rr.record_data = odr_strdupn(
1484 srw_req->record->recordData_buf,
1485 srw_req->record->recordData_len );
1487 if (extra && extra->extraRecordData_len)
1489 rr.extra_record_data = odr_strdupn(
1491 extra->extraRecordData_buf,
1492 extra->extraRecordData_len );
1494 if (srw_req->recordId)
1495 rr.record_id = srw_req->recordId;
1496 else if (extra && extra->recordIdentifier)
1497 rr.record_id = extra->recordIdentifier;
1499 else if (!strcmp(rr.operation, "replace"))
1501 if (srw_req->recordId)
1502 rr.record_id = srw_req->recordId;
1503 else if (extra && extra->recordIdentifier)
1504 rr.record_id = extra->recordIdentifier;
1507 yaz_add_sru_update_diagnostic(
1508 assoc->encode, &srw_res->diagnostics,
1509 &srw_res->num_diagnostics,
1510 YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,
1511 "recordIdentifier");
1513 if (!srw_req->record)
1515 yaz_add_sru_update_diagnostic(
1516 assoc->encode, &srw_res->diagnostics,
1517 &srw_res->num_diagnostics,
1518 YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,
1523 if (srw_req->record->recordSchema)
1524 rr.record_schema = odr_strdup(
1525 assoc->encode, srw_req->record->recordSchema);
1526 if (srw_req->record->recordData_len )
1528 rr.record_data = odr_strdupn(assoc->encode,
1529 srw_req->record->recordData_buf,
1530 srw_req->record->recordData_len );
1534 yaz_add_sru_update_diagnostic(
1535 assoc->encode, &srw_res->diagnostics,
1536 &srw_res->num_diagnostics,
1537 YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,
1541 if (extra && extra->extraRecordData_len)
1543 rr.extra_record_data = odr_strdupn(
1545 extra->extraRecordData_buf,
1546 extra->extraRecordData_len );
1549 else if (!strcmp(rr.operation, "insert"))
1551 if (srw_req->recordId)
1552 rr.record_id = srw_req->recordId;
1554 rr.record_id = extra->recordIdentifier;
1556 if (srw_req->record)
1558 if (srw_req->record->recordSchema)
1559 rr.record_schema = odr_strdup(
1560 assoc->encode, srw_req->record->recordSchema);
1562 if (srw_req->record->recordData_len)
1563 rr.record_data = odr_strdupn(
1565 srw_req->record->recordData_buf,
1566 srw_req->record->recordData_len );
1568 if (extra && extra->extraRecordData_len)
1570 rr.extra_record_data = odr_strdupn(
1572 extra->extraRecordData_buf,
1573 extra->extraRecordData_len );
1577 yaz_add_sru_update_diagnostic(assoc->encode, &srw_res->diagnostics,
1578 &srw_res->num_diagnostics,
1579 YAZ_SRU_UPDATE_INVALID_ACTION,
1582 if (srw_req->record)
1584 const char *pack_str =
1585 yaz_srw_pack_to_str(srw_req->record->recordPacking);
1587 rr.record_packing = odr_strdup(assoc->encode, pack_str);
1590 if (srw_req->num_recordVersions)
1592 rr.record_versions = srw_req->recordVersions;
1593 rr.num_versions = srw_req->num_recordVersions;
1595 if (srw_req->extraRequestData_len)
1597 rr.extra_request_data = odr_strdupn(assoc->encode,
1598 srw_req->extraRequestData_buf,
1599 srw_req->extraRequestData_len );
1601 if (srw_res->num_diagnostics == 0)
1603 if ( assoc->init->bend_srw_update)
1604 (*assoc->init->bend_srw_update)(assoc->backend, &rr);
1606 yaz_add_sru_update_diagnostic(
1607 assoc->encode, &srw_res->diagnostics,
1608 &srw_res->num_diagnostics,
1609 YAZ_SRU_UPDATE_UNSPECIFIED_DATABASE_ERROR,
1610 "No Update backend handler");
1614 yaz_add_srw_diagnostic_uri(assoc->encode,
1615 &srw_res->diagnostics,
1616 &srw_res->num_diagnostics,
1620 srw_res->recordId = rr.record_id;
1621 srw_res->operationStatus = rr.operation_status;
1622 srw_res->recordVersions = rr.record_versions;
1623 srw_res->num_recordVersions = rr.num_versions;
1624 if (srw_res->extraResponseData_len)
1626 srw_res->extraResponseData_buf = rr.extra_response_data;
1627 srw_res->extraResponseData_len = strlen(rr.extra_response_data);
1629 if (srw_res->num_diagnostics == 0 && rr.record_data)
1631 srw_res->record = yaz_srw_get_record(assoc->encode);
1632 srw_res->record->recordSchema = rr.record_schema;
1633 if (rr.record_packing)
1635 int pack = yaz_srw_str_to_pack(rr.record_packing);
1639 pack = Z_SRW_recordPacking_string;
1640 yaz_log(YLOG_WARN, "Back packing %s from backend",
1643 srw_res->record->recordPacking = pack;
1645 srw_res->record->recordData_buf = rr.record_data;
1646 srw_res->record->recordData_len = strlen(rr.record_data);
1647 if (rr.extra_record_data)
1649 Z_SRW_extra_record *ex =
1650 yaz_srw_get_extra_record(assoc->encode);
1651 srw_res->extra_record = ex;
1652 ex->extraRecordData_buf = rr.extra_record_data;
1653 ex->extraRecordData_len = strlen(rr.extra_record_data);
1659 /* check if path is OK (1); BAD (0) */
1660 static int check_path(const char *path)
1664 if (strstr(path, ".."))
1669 static char *read_file(const char *fname, ODR o, size_t *sz)
1672 FILE *inf = fopen(fname, "rb");
1676 fseek(inf, 0L, SEEK_END);
1679 buf = (char *) odr_malloc(o, *sz);
1680 if (fread(buf, 1, *sz, inf) != *sz)
1681 yaz_log(YLOG_WARN|YLOG_ERRNO, "short read %s", fname);
1686 static void process_http_request(association *assoc, request *req)
1688 Z_HTTP_Request *hreq = req->gdu_request->u.HTTP_Request;
1689 ODR o = assoc->encode;
1690 int r = 2; /* 2=NOT TAKEN, 1=TAKEN, 0=SOAP TAKEN */
1692 Z_SOAP *soap_package = 0;
1695 Z_HTTP_Response *hres = 0;
1697 const char *stylesheet = 0; /* for now .. set later */
1698 Z_SRW_diagnostic *diagnostic = 0;
1699 int num_diagnostic = 0;
1700 const char *host = z_HTTP_header_lookup(hreq->headers, "Host");
1702 yaz_log(log_request, "%s %s HTTP/%s", hreq->method, hreq->path, hreq->version);
1703 if (!control_association(assoc, host, 0))
1705 p = z_get_HTTP_Response(o, 404);
1708 if (r == 2 && assoc->server && assoc->server->docpath
1709 && hreq->path[0] == '/'
1711 /* check if path is a proper prefix of documentroot */
1712 strncmp(hreq->path+1, assoc->server->docpath,
1713 strlen(assoc->server->docpath))
1716 if (!check_path(hreq->path))
1718 yaz_log(YLOG_LOG, "File %s access forbidden", hreq->path+1);
1719 p = z_get_HTTP_Response(o, 404);
1723 size_t content_size = 0;
1724 char *content_buf = read_file(hreq->path+1, o, &content_size);
1727 yaz_log(YLOG_LOG, "File %s not found", hreq->path+1);
1728 p = z_get_HTTP_Response(o, 404);
1732 const char *ctype = 0;
1733 yaz_mime_types types = yaz_mime_types_create();
1735 yaz_mime_types_add(types, "xsl", "application/xml");
1736 yaz_mime_types_add(types, "xml", "application/xml");
1737 yaz_mime_types_add(types, "css", "text/css");
1738 yaz_mime_types_add(types, "html", "text/html");
1739 yaz_mime_types_add(types, "htm", "text/html");
1740 yaz_mime_types_add(types, "txt", "text/plain");
1741 yaz_mime_types_add(types, "js", "application/x-javascript");
1743 yaz_mime_types_add(types, "gif", "image/gif");
1744 yaz_mime_types_add(types, "png", "image/png");
1745 yaz_mime_types_add(types, "jpg", "image/jpeg");
1746 yaz_mime_types_add(types, "jpeg", "image/jpeg");
1748 ctype = yaz_mime_lookup_fname(types, hreq->path);
1751 yaz_log(YLOG_LOG, "No mime type for %s", hreq->path+1);
1752 p = z_get_HTTP_Response(o, 404);
1756 p = z_get_HTTP_Response(o, 200);
1757 hres = p->u.HTTP_Response;
1758 hres->content_buf = content_buf;
1759 hres->content_len = content_size;
1760 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1762 yaz_mime_types_destroy(types);
1770 r = yaz_srw_decode(hreq, &sr, &soap_package, assoc->decode, &charset);
1771 yaz_log(YLOG_DEBUG, "yaz_srw_decode returned %d", r);
1773 if (r == 2) /* not taken */
1775 r = yaz_sru_decode(hreq, &sr, &soap_package, assoc->decode, &charset,
1776 &diagnostic, &num_diagnostic);
1777 yaz_log(YLOG_DEBUG, "yaz_sru_decode returned %d", r);
1779 if (r == 0) /* decode SRW/SRU OK .. */
1781 int http_code = 200;
1782 if (sr->which == Z_SRW_searchRetrieve_request)
1785 yaz_srw_get_pdu(assoc->encode, Z_SRW_searchRetrieve_response,
1787 stylesheet = sr->u.request->stylesheet;
1790 res->u.response->diagnostics = diagnostic;
1791 res->u.response->num_diagnostics = num_diagnostic;
1795 srw_bend_search(assoc, sr, res, &http_code);
1797 if (http_code == 200)
1798 soap_package->u.generic->p = res;
1800 else if (sr->which == Z_SRW_explain_request)
1802 Z_SRW_PDU *res = yaz_srw_get_pdu(o, Z_SRW_explain_response,
1804 stylesheet = sr->u.explain_request->stylesheet;
1807 res->u.explain_response->diagnostics = diagnostic;
1808 res->u.explain_response->num_diagnostics = num_diagnostic;
1810 srw_bend_explain(assoc, sr, res->u.explain_response, &http_code);
1811 if (http_code == 200)
1812 soap_package->u.generic->p = res;
1814 else if (sr->which == Z_SRW_scan_request)
1816 Z_SRW_PDU *res = yaz_srw_get_pdu(o, Z_SRW_scan_response,
1818 stylesheet = sr->u.scan_request->stylesheet;
1821 res->u.scan_response->diagnostics = diagnostic;
1822 res->u.scan_response->num_diagnostics = num_diagnostic;
1824 srw_bend_scan(assoc, sr, res->u.scan_response, &http_code);
1825 if (http_code == 200)
1826 soap_package->u.generic->p = res;
1828 else if (sr->which == Z_SRW_update_request)
1830 Z_SRW_PDU *res = yaz_srw_get_pdu(o, Z_SRW_update_response,
1832 yaz_log(YLOG_DEBUG, "handling SRW UpdateRequest");
1835 res->u.update_response->diagnostics = diagnostic;
1836 res->u.update_response->num_diagnostics = num_diagnostic;
1838 yaz_log(YLOG_DEBUG, "num_diag = %d", res->u.update_response->num_diagnostics );
1839 srw_bend_update(assoc, sr, res->u.update_response, &http_code);
1840 if (http_code == 200)
1841 soap_package->u.generic->p = res;
1845 yaz_log(log_request, "SOAP ERROR");
1846 /* FIXME - what error, what query */
1848 z_soap_error(assoc->encode, soap_package,
1849 "SOAP-ENV:Client", "Bad method", 0);
1851 if (http_code == 200 || http_code == 500)
1853 static Z_SOAP_Handler soap_handlers[4] = {
1855 {YAZ_XMLNS_SRU_v1_1, 0, (Z_SOAP_fun) yaz_srw_codec},
1856 {YAZ_XMLNS_SRU_v1_0, 0, (Z_SOAP_fun) yaz_srw_codec},
1857 {YAZ_XMLNS_UPDATE_v0_9, 0, (Z_SOAP_fun) yaz_ucp_codec},
1863 p = z_get_HTTP_Response(o, 200);
1864 hres = p->u.HTTP_Response;
1866 if (!stylesheet && assoc->server)
1867 stylesheet = assoc->server->stylesheet;
1869 /* empty stylesheet means NO stylesheet */
1870 if (stylesheet && *stylesheet == '\0')
1873 ret = z_soap_codec_enc_xsl(assoc->encode, &soap_package,
1874 &hres->content_buf, &hres->content_len,
1875 soap_handlers, charset, stylesheet);
1876 hres->code = http_code;
1878 strcpy(ctype, "text/xml");
1879 if (charset && strlen(charset) < sizeof(ctype)-30)
1881 strcat(ctype, "; charset=");
1882 strcat(ctype, charset);
1884 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1887 p = z_get_HTTP_Response(o, http_code);
1891 p = z_get_HTTP_Response(o, 500);
1892 hres = p->u.HTTP_Response;
1893 if (!strcmp(hreq->version, "1.0"))
1895 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1896 if (v && !strcmp(v, "Keep-Alive"))
1900 hres->version = "1.0";
1904 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1905 if (v && !strcmp(v, "close"))
1909 hres->version = "1.1";
1911 if (!keepalive || !assoc->last_control->keepalive)
1913 z_HTTP_header_add(o, &hres->headers, "Connection", "close");
1914 assoc->state = ASSOC_DEAD;
1915 assoc->cs_get_mask = 0;
1920 const char *alive = z_HTTP_header_lookup(hreq->headers, "Keep-Alive");
1922 if (alive && yaz_isdigit(*(const unsigned char *) alive))
1926 if (t < 0 || t > 3600)
1928 iochan_settimeout(assoc->client_chan,t);
1929 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1931 process_gdu_response(assoc, req, p);
1934 static void process_gdu_request(association *assoc, request *req)
1936 if (req->gdu_request->which == Z_GDU_Z3950)
1939 req->apdu_request = req->gdu_request->u.z3950;
1940 if (process_z_request(assoc, req, &msg) < 0)
1941 do_close_req(assoc, Z_Close_systemProblem, msg, req);
1943 else if (req->gdu_request->which == Z_GDU_HTTP_Request)
1944 process_http_request(assoc, req);
1947 do_close_req(assoc, Z_Close_systemProblem, "bad protocol packet", req);
1952 * Initiate request processing.
1954 static int process_z_request(association *assoc, request *req, char **msg)
1959 *msg = "Unknown Error";
1960 assert(req && req->state == REQUEST_IDLE);
1961 if (req->apdu_request->which != Z_APDU_initRequest && !assoc->init)
1963 *msg = "Missing InitRequest";
1966 switch (req->apdu_request->which)
1968 case Z_APDU_initRequest:
1969 res = process_initRequest(assoc, req); break;
1970 case Z_APDU_searchRequest:
1971 res = process_searchRequest(assoc, req); break;
1972 case Z_APDU_presentRequest:
1973 res = process_presentRequest(assoc, req); break;
1974 case Z_APDU_scanRequest:
1975 if (assoc->init->bend_scan)
1976 res = process_scanRequest(assoc, req);
1979 *msg = "Cannot handle Scan APDU";
1983 case Z_APDU_extendedServicesRequest:
1984 if (assoc->init->bend_esrequest)
1985 res = process_ESRequest(assoc, req);
1988 *msg = "Cannot handle Extended Services APDU";
1992 case Z_APDU_sortRequest:
1993 if (assoc->init->bend_sort)
1994 res = process_sortRequest(assoc, req);
1997 *msg = "Cannot handle Sort APDU";
2002 process_close(assoc, req);
2004 case Z_APDU_deleteResultSetRequest:
2005 if (assoc->init->bend_delete)
2006 res = process_deleteRequest(assoc, req);
2009 *msg = "Cannot handle Delete APDU";
2013 case Z_APDU_segmentRequest:
2014 if (assoc->init->bend_segment)
2016 res = process_segmentRequest(assoc, req);
2020 *msg = "Cannot handle Segment APDU";
2024 case Z_APDU_triggerResourceControlRequest:
2027 *msg = "Bad APDU received";
2032 yaz_log(YLOG_DEBUG, " result immediately available");
2033 retval = process_z_response(assoc, req, res);
2037 yaz_log(YLOG_DEBUG, " result unavailable");
2044 * Encode response, and transfer the request structure to the outgoing queue.
2046 static int process_gdu_response(association *assoc, request *req, Z_GDU *res)
2048 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
2052 if (!z_GDU(assoc->print, &res, 0, 0))
2053 yaz_log(YLOG_WARN, "ODR print error: %s",
2054 odr_errmsg(odr_geterror(assoc->print)));
2055 odr_reset(assoc->print);
2057 if (!z_GDU(assoc->encode, &res, 0, 0))
2059 yaz_log(YLOG_WARN, "ODR error when encoding PDU: %s [element %s]",
2060 odr_errmsg(odr_geterror(assoc->decode)),
2061 odr_getelement(assoc->decode));
2064 req->response = odr_getbuf(assoc->encode, &req->len_response,
2065 &req->size_response);
2066 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
2067 odr_reset(assoc->encode);
2068 req->state = REQUEST_IDLE;
2069 request_enq(&assoc->outgoing, req);
2070 /* turn the work over to the ir_session handler */
2071 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
2072 assoc->cs_put_mask = EVENT_OUTPUT;
2073 /* Is there more work to be done? give that to the input handler too */
2076 req = request_head(&assoc->incoming);
2077 if (req && req->state == REQUEST_IDLE)
2079 request_deq(&assoc->incoming);
2080 process_gdu_request(assoc, req);
2089 * Encode response, and transfer the request structure to the outgoing queue.
2091 static int process_z_response(association *assoc, request *req, Z_APDU *res)
2093 Z_GDU *gres = (Z_GDU *) odr_malloc(assoc->encode, sizeof(*gres));
2094 gres->which = Z_GDU_Z3950;
2095 gres->u.z3950 = res;
2097 return process_gdu_response(assoc, req, gres);
2100 static char *get_vhost(Z_OtherInformation *otherInfo)
2102 return yaz_oi_get_string_oid(&otherInfo, yaz_oid_userinfo_proxy, 1, 0);
2106 * Handle init request.
2107 * At the moment, we don't check the options
2108 * anywhere else in the code - we just try not to do anything that would
2109 * break a naive client. We'll toss 'em into the association block when
2110 * we need them there.
2112 static Z_APDU *process_initRequest(association *assoc, request *reqb)
2114 Z_InitRequest *req = reqb->apdu_request->u.initRequest;
2115 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
2116 Z_InitResponse *resp = apdu->u.initResponse;
2117 bend_initresult *binitres;
2119 statserv_options_block *cb = 0; /* by default no control for backend */
2121 if (control_association(assoc, get_vhost(req->otherInfo), 1))
2122 cb = statserv_getcontrol(); /* got control block for backend */
2124 if (cb && assoc->backend)
2125 (*cb->bend_close)(assoc->backend);
2127 yaz_log(log_requestdetail, "Got initRequest");
2128 if (req->implementationId)
2129 yaz_log(log_requestdetail, "Id: %s",
2130 req->implementationId);
2131 if (req->implementationName)
2132 yaz_log(log_requestdetail, "Name: %s",
2133 req->implementationName);
2134 if (req->implementationVersion)
2135 yaz_log(log_requestdetail, "Version: %s",
2136 req->implementationVersion);
2138 assoc_init_reset(assoc);
2140 assoc->init->auth = req->idAuthentication;
2141 assoc->init->referenceId = req->referenceId;
2143 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
2145 Z_CharSetandLanguageNegotiation *negotiation =
2146 yaz_get_charneg_record (req->otherInfo);
2148 negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
2149 assoc->init->charneg_request = negotiation;
2152 /* by default named_result_sets is 0 .. Enable it if client asks for it. */
2153 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
2154 assoc->init->named_result_sets = 1;
2159 if (req->implementationVersion)
2160 yaz_log(log_requestdetail, "Config: %s",
2163 iochan_settimeout(assoc->client_chan, cb->idle_timeout);
2165 /* we have a backend control block, so call that init function */
2166 if (!(binitres = (*cb->bend_init)(assoc->init)))
2168 yaz_log(YLOG_WARN, "Bad response from backend.");
2171 assoc->backend = binitres->handle;
2175 /* no backend. return error */
2176 binitres = (bend_initresult *)
2177 odr_malloc(assoc->encode, sizeof(*binitres));
2178 binitres->errstring = 0;
2179 binitres->errcode = YAZ_BIB1_PERMANENT_SYSTEM_ERROR;
2180 iochan_settimeout(assoc->client_chan, 10);
2182 if ((assoc->init->bend_sort))
2183 yaz_log(YLOG_DEBUG, "Sort handler installed");
2184 if ((assoc->init->bend_search))
2185 yaz_log(YLOG_DEBUG, "Search handler installed");
2186 if ((assoc->init->bend_present))
2187 yaz_log(YLOG_DEBUG, "Present handler installed");
2188 if ((assoc->init->bend_esrequest))
2189 yaz_log(YLOG_DEBUG, "ESRequest handler installed");
2190 if ((assoc->init->bend_delete))
2191 yaz_log(YLOG_DEBUG, "Delete handler installed");
2192 if ((assoc->init->bend_scan))
2193 yaz_log(YLOG_DEBUG, "Scan handler installed");
2194 if ((assoc->init->bend_segment))
2195 yaz_log(YLOG_DEBUG, "Segment handler installed");
2197 resp->referenceId = req->referenceId;
2199 /* let's tell the client what we can do */
2200 if (ODR_MASK_GET(req->options, Z_Options_search))
2202 ODR_MASK_SET(resp->options, Z_Options_search);
2203 strcat(options, "srch");
2205 if (ODR_MASK_GET(req->options, Z_Options_present))
2207 ODR_MASK_SET(resp->options, Z_Options_present);
2208 strcat(options, " prst");
2210 if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
2211 assoc->init->bend_delete)
2213 ODR_MASK_SET(resp->options, Z_Options_delSet);
2214 strcat(options, " del");
2216 if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
2217 assoc->init->bend_esrequest)
2219 ODR_MASK_SET(resp->options, Z_Options_extendedServices);
2220 strcat(options, " extendedServices");
2222 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets)
2223 && assoc->init->named_result_sets)
2225 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
2226 strcat(options, " namedresults");
2228 if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
2230 ODR_MASK_SET(resp->options, Z_Options_scan);
2231 strcat(options, " scan");
2233 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
2235 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
2236 strcat(options, " concurrop");
2238 if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
2240 ODR_MASK_SET(resp->options, Z_Options_sort);
2241 strcat(options, " sort");
2244 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
2246 Z_OtherInformationUnit *p0;
2248 if (!assoc->init->charneg_response)
2250 if (assoc->init->query_charset)
2252 assoc->init->charneg_response = yaz_set_response_charneg(
2253 assoc->encode, assoc->init->query_charset, 0,
2254 assoc->init->records_in_same_charset);
2258 yaz_log(YLOG_WARN, "default query_charset not defined by backend");
2261 if (assoc->init->charneg_response
2262 && (p0=yaz_oi_update(&resp->otherInfo, assoc->encode, NULL, 0, 0)))
2264 p0->which = Z_OtherInfo_externallyDefinedInfo;
2265 p0->information.externallyDefinedInfo =
2266 assoc->init->charneg_response;
2267 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
2268 strcat(options, " negotiation");
2271 if (ODR_MASK_GET(req->options, Z_Options_triggerResourceCtrl))
2272 ODR_MASK_SET(resp->options, Z_Options_triggerResourceCtrl);
2274 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
2276 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
2277 assoc->version = 1; /* 1 & 2 are equivalent */
2279 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
2281 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
2284 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
2286 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
2290 yaz_log(log_requestdetail, "Negotiated to v%d: %s", assoc->version, options);
2292 if (*req->maximumRecordSize < assoc->maximumRecordSize)
2293 assoc->maximumRecordSize = odr_int_to_int(*req->maximumRecordSize);
2295 if (*req->preferredMessageSize < assoc->preferredMessageSize)
2296 assoc->preferredMessageSize = odr_int_to_int(*req->preferredMessageSize);
2298 resp->preferredMessageSize =
2299 odr_intdup(assoc->encode, assoc->preferredMessageSize);
2300 resp->maximumRecordSize =
2301 odr_intdup(assoc->encode, assoc->maximumRecordSize);
2303 resp->implementationId = odr_prepend(assoc->encode,
2304 assoc->init->implementation_id,
2305 resp->implementationId);
2307 resp->implementationName = odr_prepend(assoc->encode,
2308 assoc->init->implementation_name,
2309 odr_prepend(assoc->encode, "GFS", resp->implementationName));
2311 if (binitres->errcode)
2313 assoc->state = ASSOC_DEAD;
2314 resp->userInformationField =
2315 init_diagnostics(assoc->encode, binitres->errcode,
2316 binitres->errstring);
2320 assoc->state = ASSOC_UP;
2324 if (!req->idAuthentication)
2325 yaz_log(log_request, "Auth none");
2326 else if (req->idAuthentication->which == Z_IdAuthentication_open)
2328 const char *open = req->idAuthentication->u.open;
2329 const char *slash = strchr(open, '/');
2335 yaz_log(log_request, "Auth open %.*s", len, open);
2337 else if (req->idAuthentication->which == Z_IdAuthentication_idPass)
2339 const char *user = req->idAuthentication->u.idPass->userId;
2340 const char *group = req->idAuthentication->u.idPass->groupId;
2341 yaz_log(log_request, "Auth idPass %s %s",
2342 user ? user : "-", group ? group : "-");
2344 else if (req->idAuthentication->which
2345 == Z_IdAuthentication_anonymous)
2347 yaz_log(log_request, "Auth anonymous");
2351 yaz_log(log_request, "Auth other");
2356 WRBUF wr = wrbuf_alloc();
2357 wrbuf_printf(wr, "Init ");
2358 if (binitres->errcode)
2359 wrbuf_printf(wr, "ERROR %d", binitres->errcode);
2361 wrbuf_printf(wr, "OK -");
2362 wrbuf_printf(wr, " ID:%s Name:%s Version:%s",
2363 (req->implementationId ? req->implementationId :"-"),
2364 (req->implementationName ?
2365 req->implementationName : "-"),
2366 (req->implementationVersion ?
2367 req->implementationVersion : "-")
2369 yaz_log(log_request, "%s", wrbuf_cstr(wr));
2376 * Set the specified `errcode' and `errstring' into a UserInfo-1
2377 * external to be returned to the client in accordance with Z35.90
2378 * Implementor Agreement 5 (Returning diagnostics in an InitResponse):
2379 * http://lcweb.loc.gov/z3950/agency/agree/initdiag.html
2381 static Z_External *init_diagnostics(ODR odr, int error, const char *addinfo)
2383 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2384 addinfo ? " -- " : "", addinfo ? addinfo : "");
2385 return zget_init_diagnostics(odr, error, addinfo);
2389 * nonsurrogate diagnostic record.
2391 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
2393 Z_Records *rec = (Z_Records *) odr_malloc(assoc->encode, sizeof(*rec));
2395 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2396 addinfo ? " -- " : "", addinfo ? addinfo : "");
2398 rec->which = Z_Records_NSD;
2399 rec->u.nonSurrogateDiagnostic = zget_DefaultDiagFormat(assoc->encode,
2405 * surrogate diagnostic.
2407 static Z_NamePlusRecord *surrogatediagrec(association *assoc,
2409 int error, const char *addinfo)
2411 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2412 addinfo ? " -- " : "", addinfo ? addinfo : "");
2413 return zget_surrogateDiagRec(assoc->encode, dbname, error, addinfo);
2416 static Z_Records *pack_records(association *a, char *setname, Odr_int start,
2417 Odr_int *num, Z_RecordComposition *comp,
2418 Odr_int *next, Odr_int *pres,
2419 Z_ReferenceId *referenceId,
2420 Odr_oid *oid, int *errcode)
2422 int recno, total_length = 0, dumped_records = 0;
2423 int toget = odr_int_to_int(*num);
2424 Z_Records *records =
2425 (Z_Records *) odr_malloc(a->encode, sizeof(*records));
2426 Z_NamePlusRecordList *reclist =
2427 (Z_NamePlusRecordList *) odr_malloc(a->encode, sizeof(*reclist));
2429 records->which = Z_Records_DBOSD;
2430 records->u.databaseOrSurDiagnostics = reclist;
2431 reclist->num_records = 0;
2434 return diagrec(a, YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE, 0);
2435 else if (toget == 0)
2436 reclist->records = odr_nullval();
2438 reclist->records = (Z_NamePlusRecord **)
2439 odr_malloc(a->encode, sizeof(*reclist->records) * toget);
2441 *pres = Z_PresentStatus_success;
2445 yaz_log(log_requestdetail, "Request to pack " ODR_INT_PRINTF "+%d %s", start, toget, setname);
2446 yaz_log(log_requestdetail, "pms=%d, mrs=%d", a->preferredMessageSize,
2447 a->maximumRecordSize);
2448 for (recno = odr_int_to_int(start); reclist->num_records < toget; recno++)
2451 Z_NamePlusRecord *thisrec;
2452 int this_length = 0;
2454 * we get the number of bytes allocated on the stream before any
2455 * allocation done by the backend - this should give us a reasonable
2456 * idea of the total size of the data so far.
2458 total_length = odr_total(a->encode) - dumped_records;
2464 freq.last_in_set = 0;
2465 freq.setname = setname;
2466 freq.surrogate_flag = 0;
2467 freq.number = recno;
2469 freq.request_format = oid;
2470 freq.output_format = 0;
2471 freq.stream = a->encode;
2472 freq.print = a->print;
2473 freq.referenceId = referenceId;
2476 retrieve_fetch(a, &freq);
2478 *next = freq.last_in_set ? 0 : recno + 1;
2482 if (!freq.surrogate_flag) /* non-surrogate diagnostic i.e. global */
2485 *pres = Z_PresentStatus_failure;
2486 /* for 'present request out of range',
2487 set addinfo to record position if not set */
2488 if (freq.errcode == YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE &&
2489 freq.errstring == 0)
2491 sprintf(s, "%d", recno);
2495 *errcode = freq.errcode;
2496 return diagrec(a, freq.errcode, freq.errstring);
2498 reclist->records[reclist->num_records] =
2499 surrogatediagrec(a, freq.basename, freq.errcode,
2501 reclist->num_records++;
2504 if (freq.record == 0) /* no error and no record ? */
2506 *pres = Z_PresentStatus_partial_4;
2507 *next = 0; /* signal end-of-set and stop */
2511 this_length = freq.len;
2513 this_length = odr_total(a->encode) - total_length - dumped_records;
2514 yaz_log(YLOG_DEBUG, " fetched record, len=%d, total=%d dumped=%d",
2515 this_length, total_length, dumped_records);
2516 if (a->preferredMessageSize > 0 &&
2517 this_length + total_length > a->preferredMessageSize)
2519 /* record is small enough, really */
2520 if (this_length <= a->preferredMessageSize && recno > start)
2522 yaz_log(log_requestdetail, " Dropped last normal-sized record");
2523 *pres = Z_PresentStatus_partial_2;
2528 /* record can only be fetched by itself */
2529 if (this_length < a->maximumRecordSize)
2531 yaz_log(log_requestdetail, " Record > prefmsgsz");
2534 yaz_log(YLOG_DEBUG, " Dropped it");
2535 reclist->records[reclist->num_records] =
2538 YAZ_BIB1_RECORD_EXCEEDS_PREFERRED_MESSAGE_SIZE, 0);
2539 reclist->num_records++;
2540 dumped_records += this_length;
2544 else /* too big entirely */
2546 yaz_log(log_requestdetail, "Record > maxrcdsz "
2548 this_length, a->maximumRecordSize);
2549 reclist->records[reclist->num_records] =
2552 YAZ_BIB1_RECORD_EXCEEDS_MAXIMUM_RECORD_SIZE, 0);
2553 reclist->num_records++;
2554 dumped_records += this_length;
2559 if (!(thisrec = (Z_NamePlusRecord *)
2560 odr_malloc(a->encode, sizeof(*thisrec))))
2562 thisrec->databaseName = odr_strdup_null(a->encode, freq.basename);
2563 thisrec->which = Z_NamePlusRecord_databaseRecord;
2565 if (!freq.output_format)
2567 yaz_log(YLOG_WARN, "bend_fetch output_format not set");
2570 thisrec->u.databaseRecord = z_ext_record_oid(
2571 a->encode, freq.output_format, freq.record, freq.len);
2572 if (!thisrec->u.databaseRecord)
2574 reclist->records[reclist->num_records] = thisrec;
2575 reclist->num_records++;
2577 *num = reclist->num_records;
2581 static Z_APDU *process_searchRequest(association *assoc, request *reqb)
2583 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2584 bend_search_rr *bsrr =
2585 (bend_search_rr *)nmem_malloc(reqb->request_mem, sizeof(*bsrr));
2587 yaz_log(log_requestdetail, "Got SearchRequest.");
2588 bsrr->association = assoc;
2589 bsrr->referenceId = req->referenceId;
2590 bsrr->srw_sortKeys = 0;
2591 bsrr->srw_setname = 0;
2592 bsrr->srw_setnameIdleTime = 0;
2593 bsrr->estimated_hit_count = 0;
2594 bsrr->partial_resultset = 0;
2595 bsrr->extra_args = 0;
2596 bsrr->extra_response_data = 0;
2598 yaz_log (log_requestdetail, "ResultSet '%s'", req->resultSetName);
2599 if (req->databaseNames)
2602 for (i = 0; i < req->num_databaseNames; i++)
2603 yaz_log(log_requestdetail, "Database '%s'", req->databaseNames[i]);
2606 yaz_log_zquery_level(log_requestdetail,req->query);
2608 if (assoc->init->bend_search)
2610 bsrr->setname = req->resultSetName;
2611 bsrr->replace_set = *req->replaceIndicator;
2612 bsrr->num_bases = req->num_databaseNames;
2613 bsrr->basenames = req->databaseNames;
2614 bsrr->query = req->query;
2615 bsrr->stream = assoc->encode;
2616 nmem_transfer(odr_getmem(bsrr->stream), reqb->request_mem);
2617 bsrr->decode = assoc->decode;
2618 bsrr->print = assoc->print;
2621 bsrr->errstring = NULL;
2622 bsrr->search_info = NULL;
2623 bsrr->search_input = req->otherInfo;
2625 if (assoc->server && assoc->server->cql_transform
2626 && req->query->which == Z_Query_type_104
2627 && req->query->u.type_104->which == Z_External_CQL)
2629 /* have a CQL query and a CQL to PQF transform .. */
2631 cql2pqf(bsrr->stream, req->query->u.type_104->u.cql,
2632 assoc->server->cql_transform, bsrr->query);
2634 bsrr->errcode = yaz_diag_srw_to_bib1(srw_errcode);
2637 if (assoc->server && assoc->server->ccl_transform
2638 && req->query->which == Z_Query_type_2) /*CCL*/
2640 /* have a CCL query and a CCL to PQF transform .. */
2642 ccl2pqf(bsrr->stream, req->query->u.type_2,
2643 assoc->server->ccl_transform, bsrr);
2645 bsrr->errcode = yaz_diag_srw_to_bib1(srw_errcode);
2649 (assoc->init->bend_search)(assoc->backend, bsrr);
2653 /* FIXME - make a diagnostic for it */
2654 yaz_log(YLOG_WARN,"Search not supported ?!?!");
2656 return response_searchRequest(assoc, reqb, bsrr);
2660 * Prepare a searchresponse based on the backend results. We probably want
2661 * to look at making the fetching of records nonblocking as well, but
2662 * so far, we'll keep things simple.
2663 * If bsrt is null, that means we're called in response to a communications
2664 * event, and we'll have to get the response for ourselves.
2666 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
2667 bend_search_rr *bsrt)
2669 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2670 Z_APDU *apdu = (Z_APDU *)odr_malloc(assoc->encode, sizeof(*apdu));
2671 Z_SearchResponse *resp = (Z_SearchResponse *)
2672 odr_malloc(assoc->encode, sizeof(*resp));
2673 Odr_int *nulint = odr_intdup(assoc->encode, 0);
2674 Odr_int *next = odr_intdup(assoc->encode, 0);
2675 Odr_int *none = odr_intdup(assoc->encode, Z_SearchResponse_none);
2676 Odr_int returnedrecs = 0;
2678 apdu->which = Z_APDU_searchResponse;
2679 apdu->u.searchResponse = resp;
2680 resp->referenceId = req->referenceId;
2681 resp->additionalSearchInfo = 0;
2682 resp->otherInfo = 0;
2685 yaz_log(YLOG_FATAL, "Bad result from backend");
2688 else if (bsrt->errcode)
2690 resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
2691 resp->resultCount = nulint;
2692 resp->numberOfRecordsReturned = nulint;
2693 resp->nextResultSetPosition = nulint;
2694 resp->searchStatus = odr_booldup(assoc->encode, 0);
2695 resp->resultSetStatus = none;
2696 resp->presentStatus = 0;
2700 bool_t *sr = odr_booldup(assoc->encode, 1);
2701 Odr_int *toget = odr_intdup(assoc->encode, 0);
2702 Z_RecordComposition comp, *compp = 0;
2704 yaz_log(log_requestdetail, "resultCount: " ODR_INT_PRINTF, bsrt->hits);
2707 resp->resultCount = &bsrt->hits;
2709 comp.which = Z_RecordComp_simple;
2710 /* how many records does the user agent want, then? */
2713 else if (bsrt->hits <= *req->smallSetUpperBound)
2715 *toget = bsrt->hits;
2716 if ((comp.u.simple = req->smallSetElementSetNames))
2719 else if (bsrt->hits < *req->largeSetLowerBound)
2721 *toget = *req->mediumSetPresentNumber;
2722 if (*toget > bsrt->hits)
2723 *toget = bsrt->hits;
2724 if ((comp.u.simple = req->mediumSetElementSetNames))
2730 if (*toget && !resp->records)
2732 Odr_int *presst = odr_intdup(assoc->encode, 0);
2733 /* Call bend_present if defined */
2734 if (assoc->init->bend_present)
2736 bend_present_rr *bprr = (bend_present_rr *)
2737 nmem_malloc(reqb->request_mem, sizeof(*bprr));
2738 bprr->setname = req->resultSetName;
2740 bprr->number = odr_int_to_int(*toget);
2741 bprr->format = req->preferredRecordSyntax;
2743 bprr->referenceId = req->referenceId;
2744 bprr->stream = assoc->encode;
2745 bprr->print = assoc->print;
2746 bprr->association = assoc;
2748 bprr->errstring = NULL;
2749 (*assoc->init->bend_present)(assoc->backend, bprr);
2753 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2754 *resp->presentStatus = Z_PresentStatus_failure;
2759 resp->records = pack_records(
2760 assoc, req->resultSetName, 1,
2761 toget, compp, next, presst, req->referenceId,
2762 req->preferredRecordSyntax, NULL);
2765 resp->numberOfRecordsReturned = toget;
2766 returnedrecs = *toget;
2767 resp->presentStatus = presst;
2771 if (*resp->resultCount)
2773 resp->numberOfRecordsReturned = nulint;
2774 resp->presentStatus = 0;
2776 resp->nextResultSetPosition = next;
2777 resp->searchStatus = sr;
2778 resp->resultSetStatus = 0;
2779 if (bsrt->estimated_hit_count)
2781 resp->resultSetStatus = odr_intdup(assoc->encode,
2782 Z_SearchResponse_estimate);
2784 else if (bsrt->partial_resultset)
2786 resp->resultSetStatus = odr_intdup(assoc->encode,
2787 Z_SearchResponse_subset);
2790 resp->additionalSearchInfo = bsrt->search_info;
2795 WRBUF wr = wrbuf_alloc();
2797 for (i = 0 ; i < req->num_databaseNames; i++)
2800 wrbuf_printf(wr, "+");
2801 wrbuf_puts(wr, req->databaseNames[i]);
2803 wrbuf_printf(wr, " ");
2806 wrbuf_printf(wr, "ERROR %d", bsrt->errcode);
2808 wrbuf_printf(wr, "OK " ODR_INT_PRINTF, bsrt->hits);
2809 wrbuf_printf(wr, " %s 1+" ODR_INT_PRINTF " ",
2810 req->resultSetName, returnedrecs);
2811 yaz_query_to_wrbuf(wr, req->query);
2813 yaz_log(log_request, "Search %s", wrbuf_cstr(wr));
2820 * Maybe we got a little over-friendly when we designed bend_fetch to
2821 * get only one record at a time. Some backends can optimise multiple-record
2822 * fetches, and at any rate, there is some overhead involved in
2823 * all that selecting and hopping around. Problem is, of course, that the
2824 * frontend can't know ahead of time how many records it'll need to
2825 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
2826 * is downright lousy as a bulk data transfer protocol.
2828 * To start with, we'll do the fetching of records from the backend
2829 * in one operation: To save some trips in and out of the event-handler,
2830 * and to simplify the interface to pack_records. At any rate, asynch
2831 * operation is more fun in operations that have an unpredictable execution
2832 * speed - which is normally more true for search than for present.
2834 static Z_APDU *process_presentRequest(association *assoc, request *reqb)
2836 Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
2838 Z_PresentResponse *resp;
2842 const char *errstring = 0;
2844 yaz_log(log_requestdetail, "Got PresentRequest.");
2846 resp = (Z_PresentResponse *)odr_malloc(assoc->encode, sizeof(*resp));
2848 resp->presentStatus = odr_intdup(assoc->encode, 0);
2849 if (assoc->init->bend_present)
2851 bend_present_rr *bprr = (bend_present_rr *)
2852 nmem_malloc(reqb->request_mem, sizeof(*bprr));
2853 bprr->setname = req->resultSetId;
2854 bprr->start = odr_int_to_int(*req->resultSetStartPoint);
2855 bprr->number = odr_int_to_int(*req->numberOfRecordsRequested);
2856 bprr->format = req->preferredRecordSyntax;
2857 bprr->comp = req->recordComposition;
2858 bprr->referenceId = req->referenceId;
2859 bprr->stream = assoc->encode;
2860 bprr->print = assoc->print;
2861 bprr->association = assoc;
2863 bprr->errstring = NULL;
2864 (*assoc->init->bend_present)(assoc->backend, bprr);
2868 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2869 *resp->presentStatus = Z_PresentStatus_failure;
2870 errcode = bprr->errcode;
2871 errstring = bprr->errstring;
2874 apdu = (Z_APDU *)odr_malloc(assoc->encode, sizeof(*apdu));
2875 next = odr_intdup(assoc->encode, 0);
2876 num = odr_intdup(assoc->encode, 0);
2878 apdu->which = Z_APDU_presentResponse;
2879 apdu->u.presentResponse = resp;
2880 resp->referenceId = req->referenceId;
2881 resp->otherInfo = 0;
2885 *num = *req->numberOfRecordsRequested;
2887 pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
2888 num, req->recordComposition, next,
2889 resp->presentStatus,
2890 req->referenceId, req->preferredRecordSyntax,
2895 WRBUF wr = wrbuf_alloc();
2896 wrbuf_printf(wr, "Present ");
2898 if (*resp->presentStatus == Z_PresentStatus_failure)
2899 wrbuf_printf(wr, "ERROR %d ", errcode);
2900 else if (*resp->presentStatus == Z_PresentStatus_success)
2901 wrbuf_printf(wr, "OK - ");
2903 wrbuf_printf(wr, "Partial " ODR_INT_PRINTF " - ",
2904 *resp->presentStatus);
2906 wrbuf_printf(wr, " %s " ODR_INT_PRINTF "+" ODR_INT_PRINTF " ",
2907 req->resultSetId, *req->resultSetStartPoint,
2908 *req->numberOfRecordsRequested);
2909 yaz_log(log_request, "%s", wrbuf_cstr(wr) );
2914 resp->numberOfRecordsReturned = num;
2915 resp->nextResultSetPosition = next;
2921 * Scan was implemented rather in a hurry, and with support for only the basic
2922 * elements of the service in the backend API. Suggestions are welcome.
2924 static Z_APDU *process_scanRequest(association *assoc, request *reqb)
2926 Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
2927 Z_APDU *apdu = (Z_APDU *)odr_malloc(assoc->encode, sizeof(*apdu));
2928 Z_ScanResponse *res = (Z_ScanResponse *)
2929 odr_malloc(assoc->encode, sizeof(*res));
2930 Odr_int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
2931 Odr_int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
2932 Z_ListEntries *ents = (Z_ListEntries *)
2933 odr_malloc(assoc->encode, sizeof(*ents));
2934 Z_DiagRecs *diagrecs_p = NULL;
2935 bend_scan_rr *bsrr = (bend_scan_rr *)
2936 odr_malloc(assoc->encode, sizeof(*bsrr));
2937 struct scan_entry *save_entries;
2940 yaz_log(log_requestdetail, "Got ScanRequest");
2942 apdu->which = Z_APDU_scanResponse;
2943 apdu->u.scanResponse = res;
2944 res->referenceId = req->referenceId;
2946 /* if step is absent, set it to 0 */
2948 step_size = odr_int_to_int(*req->stepSize);
2950 res->scanStatus = scanStatus;
2951 res->numberOfEntriesReturned = numberOfEntriesReturned;
2952 res->positionOfTerm = 0;
2953 res->entries = ents;
2954 ents->num_entries = 0;
2955 ents->entries = NULL;
2956 ents->num_nonsurrogateDiagnostics = 0;
2957 ents->nonsurrogateDiagnostics = NULL;
2958 res->attributeSet = 0;
2961 if (req->databaseNames)
2964 for (i = 0; i < req->num_databaseNames; i++)
2965 yaz_log(log_requestdetail, "Database '%s'", req->databaseNames[i]);
2967 bsrr->scanClause = 0;
2969 bsrr->errstring = 0;
2970 bsrr->num_bases = req->num_databaseNames;
2971 bsrr->basenames = req->databaseNames;
2972 bsrr->num_entries = odr_int_to_int(*req->numberOfTermsRequested);
2973 bsrr->term = req->termListAndStartPoint;
2974 bsrr->referenceId = req->referenceId;
2975 bsrr->stream = assoc->encode;
2976 bsrr->print = assoc->print;
2977 bsrr->step_size = &step_size;
2978 bsrr->setname = yaz_oi_get_string_oid(&req->otherInfo,
2979 yaz_oid_userinfo_scan_set, 1, 0);
2981 /* For YAZ 2.0 and earlier it was the backend handler that
2982 initialized entries (member display_term did not exist)
2983 YAZ 2.0 and later sets 'entries' and initialize all members
2984 including 'display_term'. If YAZ 2.0 or later sees that
2985 entries was modified - we assume that it is an old handler and
2986 that 'display_term' is _not_ set.
2988 if (bsrr->num_entries > 0)
2991 bsrr->entries = (struct scan_entry *)
2992 odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
2994 for (i = 0; i<bsrr->num_entries; i++)
2996 bsrr->entries[i].term = 0;
2997 bsrr->entries[i].occurrences = 0;
2998 bsrr->entries[i].errcode = 0;
2999 bsrr->entries[i].errstring = 0;
3000 bsrr->entries[i].display_term = 0;
3003 save_entries = bsrr->entries; /* save it so we can compare later */
3005 bsrr->attributeset = req->attributeSet;
3006 log_scan_term_level(log_requestdetail, req->termListAndStartPoint,
3007 bsrr->attributeset);
3008 bsrr->term_position = req->preferredPositionInResponse ?
3009 odr_int_to_int(*req->preferredPositionInResponse) : 1;
3011 ((int (*)(void *, bend_scan_rr *))
3012 (*assoc->init->bend_scan))(assoc->backend, bsrr);
3015 diagrecs_p = zget_DiagRecs(assoc->encode,
3016 bsrr->errcode, bsrr->errstring);
3020 Z_Entry **tab = (Z_Entry **)
3021 odr_malloc(assoc->encode, sizeof(*tab) * bsrr->num_entries);
3023 if (bsrr->status == BEND_SCAN_PARTIAL)
3024 *scanStatus = Z_Scan_partial_5;
3026 *scanStatus = Z_Scan_success;
3027 res->stepSize = odr_intdup(assoc->encode, step_size);
3028 ents->entries = tab;
3029 ents->num_entries = bsrr->num_entries;
3030 res->numberOfEntriesReturned = odr_intdup(assoc->encode,
3032 res->positionOfTerm = odr_intdup(assoc->encode, bsrr->term_position);
3033 for (i = 0; i < bsrr->num_entries; i++)
3039 tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
3040 if (bsrr->entries[i].occurrences >= 0)
3042 e->which = Z_Entry_termInfo;
3043 e->u.termInfo = t = (Z_TermInfo *)
3044 odr_malloc(assoc->encode, sizeof(*t));
3045 t->suggestedAttributes = 0;
3047 if (save_entries == bsrr->entries &&
3048 bsrr->entries[i].display_term)
3050 /* the entries was _not_ set by the handler. So it's
3051 safe to test for new member display_term. It is
3054 t->displayTerm = odr_strdup(assoc->encode,
3055 bsrr->entries[i].display_term);
3057 t->alternativeTerm = 0;
3058 t->byAttributes = 0;
3059 t->otherTermInfo = 0;
3060 t->globalOccurrences = &bsrr->entries[i].occurrences;
3061 t->term = (Z_Term *)
3062 odr_malloc(assoc->encode, sizeof(*t->term));
3063 t->term->which = Z_Term_general;
3064 t->term->u.general = o =
3065 (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
3066 o->buf = (unsigned char *)
3067 odr_malloc(assoc->encode, o->len = o->size =
3068 strlen(bsrr->entries[i].term));
3069 memcpy(o->buf, bsrr->entries[i].term, o->len);
3070 yaz_log(YLOG_DEBUG, " term #%d: '%s' (" ODR_INT_PRINTF ")", i,
3071 bsrr->entries[i].term, bsrr->entries[i].occurrences);
3075 Z_DiagRecs *drecs = zget_DiagRecs(assoc->encode,
3076 bsrr->entries[i].errcode,
3077 bsrr->entries[i].errstring);
3078 assert(drecs->num_diagRecs == 1);
3079 e->which = Z_Entry_surrogateDiagnostic;
3080 assert(drecs->diagRecs[0]);
3081 e->u.surrogateDiagnostic = drecs->diagRecs[0];
3087 ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
3088 ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
3093 WRBUF wr = wrbuf_alloc();
3094 wrbuf_printf(wr, "Scan ");
3095 for (i = 0 ; i < req->num_databaseNames; i++)
3098 wrbuf_printf(wr, "+");
3099 wrbuf_puts(wr, req->databaseNames[i]);
3102 wrbuf_printf(wr, " ");
3105 wr_diag(wr, bsrr->errcode, bsrr->errstring);
3107 wrbuf_printf(wr, "OK");
3109 wrbuf_printf(wr, " " ODR_INT_PRINTF " - " ODR_INT_PRINTF "+"
3110 ODR_INT_PRINTF "+" ODR_INT_PRINTF,
3111 res->numberOfEntriesReturned ?
3112 *res->numberOfEntriesReturned : 0,
3113 (req->preferredPositionInResponse ?
3114 *req->preferredPositionInResponse : 1),
3115 *req->numberOfTermsRequested,
3116 (res->stepSize ? *res->stepSize : 1));
3119 wrbuf_printf(wr, "+%s", bsrr->setname);
3121 wrbuf_printf(wr, " ");
3122 yaz_scan_to_wrbuf(wr, req->termListAndStartPoint,
3123 bsrr->attributeset);
3124 yaz_log(log_request, "%s", wrbuf_cstr(wr) );
3130 static Z_APDU *process_sortRequest(association *assoc, request *reqb)
3133 Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
3134 Z_SortResponse *res = (Z_SortResponse *)
3135 odr_malloc(assoc->encode, sizeof(*res));
3136 bend_sort_rr *bsrr = (bend_sort_rr *)
3137 odr_malloc(assoc->encode, sizeof(*bsrr));
3139 Z_APDU *apdu = (Z_APDU *)odr_malloc(assoc->encode, sizeof(*apdu));
3141 yaz_log(log_requestdetail, "Got SortRequest.");
3143 bsrr->num_input_setnames = req->num_inputResultSetNames;
3144 for (i=0;i<req->num_inputResultSetNames;i++)
3145 yaz_log(log_requestdetail, "Input resultset: '%s'",
3146 req->inputResultSetNames[i]);
3147 bsrr->input_setnames = req->inputResultSetNames;
3148 bsrr->referenceId = req->referenceId;
3149 bsrr->output_setname = req->sortedResultSetName;
3150 yaz_log(log_requestdetail, "Output resultset: '%s'",
3151 req->sortedResultSetName);
3152 bsrr->sort_sequence = req->sortSequence;
3153 /*FIXME - dump those sequences too */
3154 bsrr->stream = assoc->encode;
3155 bsrr->print = assoc->print;
3157 bsrr->sort_status = Z_SortResponse_failure;
3159 bsrr->errstring = 0;
3161 (*assoc->init->bend_sort)(assoc->backend, bsrr);
3163 res->referenceId = bsrr->referenceId;
3164 res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
3165 res->resultSetStatus = 0;
3168 Z_DiagRecs *dr = zget_DiagRecs(assoc->encode,
3169 bsrr->errcode, bsrr->errstring);
3170 res->diagnostics = dr->diagRecs;
3171 res->num_diagnostics = dr->num_diagRecs;
3175 res->num_diagnostics = 0;
3176 res->diagnostics = 0;
3178 res->resultCount = 0;
3181 apdu->which = Z_APDU_sortResponse;
3182 apdu->u.sortResponse = res;
3185 WRBUF wr = wrbuf_alloc();
3186 wrbuf_printf(wr, "Sort ");
3188 wrbuf_printf(wr, " ERROR %d", bsrr->errcode);
3190 wrbuf_printf(wr, "OK -");
3191 wrbuf_printf(wr, " (");
3192 for (i = 0; i<req->num_inputResultSetNames; i++)
3195 wrbuf_printf(wr, "+");
3196 wrbuf_puts(wr, req->inputResultSetNames[i]);
3198 wrbuf_printf(wr, ")->%s ",req->sortedResultSetName);
3200 yaz_log(log_request, "%s", wrbuf_cstr(wr) );
3206 static Z_APDU *process_deleteRequest(association *assoc, request *reqb)
3209 Z_DeleteResultSetRequest *req =
3210 reqb->apdu_request->u.deleteResultSetRequest;
3211 Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
3212 odr_malloc(assoc->encode, sizeof(*res));
3213 bend_delete_rr *bdrr = (bend_delete_rr *)
3214 odr_malloc(assoc->encode, sizeof(*bdrr));
3215 Z_APDU *apdu = (Z_APDU *)odr_malloc(assoc->encode, sizeof(*apdu));
3217 yaz_log(log_requestdetail, "Got DeleteRequest.");
3219 bdrr->num_setnames = req->num_resultSetList;
3220 bdrr->setnames = req->resultSetList;
3221 for (i = 0; i<req->num_resultSetList; i++)
3222 yaz_log(log_requestdetail, "resultset: '%s'",
3223 req->resultSetList[i]);
3224 bdrr->stream = assoc->encode;
3225 bdrr->print = assoc->print;
3226 bdrr->function = odr_int_to_int(*req->deleteFunction);
3227 bdrr->referenceId = req->referenceId;
3229 if (bdrr->num_setnames > 0)
3231 bdrr->statuses = (int*)
3232 odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
3233 bdrr->num_setnames);
3234 for (i = 0; i < bdrr->num_setnames; i++)
3235 bdrr->statuses[i] = 0;
3237 (*assoc->init->bend_delete)(assoc->backend, bdrr);
3239 res->referenceId = req->referenceId;
3241 res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
3243 res->deleteListStatuses = 0;
3244 if (bdrr->num_setnames > 0)
3247 res->deleteListStatuses = (Z_ListStatuses *)
3248 odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
3249 res->deleteListStatuses->num = bdrr->num_setnames;
3250 res->deleteListStatuses->elements =
3252 odr_malloc(assoc->encode,
3253 sizeof(*res->deleteListStatuses->elements) *
3254 bdrr->num_setnames);
3255 for (i = 0; i<bdrr->num_setnames; i++)
3257 res->deleteListStatuses->elements[i] =
3259 odr_malloc(assoc->encode,
3260 sizeof(**res->deleteListStatuses->elements));
3261 res->deleteListStatuses->elements[i]->status =
3262 odr_intdup(assoc->encode, bdrr->statuses[i]);
3263 res->deleteListStatuses->elements[i]->id =
3264 odr_strdup(assoc->encode, bdrr->setnames[i]);
3267 res->numberNotDeleted = 0;
3268 res->bulkStatuses = 0;
3269 res->deleteMessage = 0;
3272 apdu->which = Z_APDU_deleteResultSetResponse;
3273 apdu->u.deleteResultSetResponse = res;
3276 WRBUF wr = wrbuf_alloc();
3277 wrbuf_printf(wr, "Delete ");
3278 if (bdrr->delete_status)
3279 wrbuf_printf(wr, "ERROR %d", bdrr->delete_status);
3281 wrbuf_printf(wr, "OK -");
3282 for (i = 0; i<req->num_resultSetList; i++)
3283 wrbuf_printf(wr, " %s ", req->resultSetList[i]);
3284 yaz_log(log_request, "%s", wrbuf_cstr(wr) );
3290 static void process_close(association *assoc, request *reqb)
3292 Z_Close *req = reqb->apdu_request->u.close;
3293 static char *reasons[] =
3300 "securityViolation",
3307 yaz_log(log_requestdetail, "Got Close, reason %s, message %s",
3308 reasons[*req->closeReason], req->diagnosticInformation ?
3309 req->diagnosticInformation : "NULL");
3310 if (assoc->version < 3) /* to make do_force respond with close */
3312 do_close_req(assoc, Z_Close_finished,
3313 "Association terminated by client", reqb);
3314 yaz_log(log_request,"Close OK");
3317 static Z_APDU *process_segmentRequest(association *assoc, request *reqb)
3319 bend_segment_rr req;
3321 req.segment = reqb->apdu_request->u.segmentRequest;
3322 req.stream = assoc->encode;
3323 req.decode = assoc->decode;
3324 req.print = assoc->print;
3325 req.association = assoc;
3327 (*assoc->init->bend_segment)(assoc->backend, &req);
3332 static Z_APDU *process_ESRequest(association *assoc, request *reqb)
3334 bend_esrequest_rr esrequest;
3335 const char *ext_name = "unknown";
3337 Z_ExtendedServicesRequest *req =
3338 reqb->apdu_request->u.extendedServicesRequest;
3339 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
3341 Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
3343 esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
3344 esrequest.stream = assoc->encode;
3345 esrequest.decode = assoc->decode;
3346 esrequest.print = assoc->print;
3347 esrequest.errcode = 0;
3348 esrequest.errstring = NULL;
3349 esrequest.association = assoc;
3350 esrequest.taskPackage = 0;
3351 esrequest.referenceId = req->referenceId;
3353 if (esrequest.esr && esrequest.esr->taskSpecificParameters)
3355 switch(esrequest.esr->taskSpecificParameters->which)
3357 case Z_External_itemOrder:
3358 ext_name = "ItemOrder"; break;
3359 case Z_External_update:
3360 ext_name = "Update"; break;
3361 case Z_External_update0:
3362 ext_name = "Update0"; break;
3363 case Z_External_ESAdmin:
3364 ext_name = "Admin"; break;
3369 (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
3371 resp->referenceId = req->referenceId;
3373 if (esrequest.errcode == -1)
3375 /* Backend service indicates request will be processed */
3376 yaz_log(log_request, "Extended Service: %s (accepted)", ext_name);
3377 *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
3379 else if (esrequest.errcode == 0)
3381 /* Backend service indicates request will be processed */
3382 yaz_log(log_request, "Extended Service: %s (done)", ext_name);
3383 *resp->operationStatus = Z_ExtendedServicesResponse_done;
3387 Z_DiagRecs *diagRecs =
3388 zget_DiagRecs(assoc->encode, esrequest.errcode,
3389 esrequest.errstring);
3390 /* Backend indicates error, request will not be processed */
3391 yaz_log(log_request, "Extended Service: %s (failed)", ext_name);
3392 *resp->operationStatus = Z_ExtendedServicesResponse_failure;
3393 resp->num_diagnostics = diagRecs->num_diagRecs;
3394 resp->diagnostics = diagRecs->diagRecs;
3397 WRBUF wr = wrbuf_alloc();
3398 wrbuf_diags(wr, resp->num_diagnostics, resp->diagnostics);
3399 yaz_log(log_request, "EsRequest %s", wrbuf_cstr(wr) );
3404 /* Do something with the members of bend_extendedservice */
3405 if (esrequest.taskPackage)
3407 resp->taskPackage = z_ext_record_oid(
3408 assoc->encode, yaz_oid_recsyn_extended,
3409 (const char *) esrequest.taskPackage, -1);
3411 yaz_log(YLOG_DEBUG,"Send the result apdu");
3415 int bend_assoc_is_alive(bend_association assoc)
3417 if (assoc->state == ASSOC_DEAD)
3418 return 0; /* already marked as dead. Don't check I/O chan anymore */
3420 return iochan_is_alive(assoc->client_chan);
3427 * c-file-style: "Stroustrup"
3428 * indent-tabs-mode: nil
3430 * vim: shiftwidth=4 tabstop=8 expandtab