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.
39 #include <sys/types.h>
47 #define S_ISREG(x) (x & _S_IFREG)
56 #include <libxml/parser.h>
57 #include <libxml/tree.h>
60 #include <yaz/yconfig.h>
61 #include <yaz/xmalloc.h>
62 #include <yaz/comstack.h>
66 #include <yaz/proto.h>
67 #include <yaz/oid_db.h>
69 #include <yaz/logrpn.h>
70 #include <yaz/querytowrbuf.h>
71 #include <yaz/statserv.h>
72 #include <yaz/diagbib1.h>
73 #include <yaz/charneg.h>
74 #include <yaz/otherinfo.h>
75 #include <yaz/yaz-util.h>
76 #include <yaz/pquery.h>
77 #include <yaz/oid_db.h>
80 #include <yaz/backend.h>
81 #include <yaz/yaz-ccl.h>
83 static void process_gdu_request(association *assoc, request *req);
84 static int process_z_request(association *assoc, request *req, char **msg);
85 static int process_gdu_response(association *assoc, request *req, Z_GDU *res);
86 static int process_z_response(association *assoc, request *req, Z_APDU *res);
87 static Z_APDU *process_initRequest(association *assoc, request *reqb);
88 static Z_External *init_diagnostics(ODR odr, int errcode,
89 const char *errstring);
90 static Z_APDU *process_searchRequest(association *assoc, request *reqb);
91 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
92 bend_search_rr *bsrr);
93 static Z_APDU *process_presentRequest(association *assoc, request *reqb);
94 static Z_APDU *process_scanRequest(association *assoc, request *reqb);
95 static Z_APDU *process_sortRequest(association *assoc, request *reqb);
96 static void process_close(association *assoc, request *reqb);
97 static Z_APDU *process_deleteRequest(association *assoc, request *reqb);
98 static Z_APDU *process_segmentRequest(association *assoc, request *reqb);
99 static Z_APDU *process_ESRequest(association *assoc, request *reqb);
101 /* dynamic logging levels */
102 static int logbits_set = 0;
103 static int log_session = 0; /* one-line logs for session */
104 static int log_sessiondetail = 0; /* more detailed stuff */
105 static int log_request = 0; /* one-line logs for requests */
106 static int log_requestdetail = 0; /* more detailed stuff */
108 /** get_logbits sets global loglevel bits */
109 static void get_logbits(void)
110 { /* needs to be called after parsing cmd-line args that can set loglevels!*/
114 log_session = yaz_log_module_level("session");
115 log_sessiondetail = yaz_log_module_level("sessiondetail");
116 log_request = yaz_log_module_level("request");
117 log_requestdetail = yaz_log_module_level("requestdetail");
121 static void wr_diag(WRBUF w, int error, const char *addinfo)
123 wrbuf_printf(w, "ERROR %d+", error);
124 wrbuf_puts_replace_char(w, diagbib1_str(error), ' ', '_');
128 wrbuf_puts_replace_char(w, addinfo, ' ', '_');
133 static int odr_int_to_int(Odr_int v)
137 else if (v <= INT_MIN)
144 * Create and initialize a new association-handle.
145 * channel : iochannel for the current line.
146 * link : communications channel.
147 * Returns: 0 or a new association handle.
149 association *create_association(IOCHAN channel, COMSTACK link,
150 const char *apdufile)
156 if (!(anew = (association *)xmalloc(sizeof(*anew))))
160 anew->last_control = 0;
161 anew->client_chan = channel;
162 anew->client_link = link;
163 anew->cs_get_mask = 0;
164 anew->cs_put_mask = 0;
165 anew->cs_accept_mask = 0;
166 if (!(anew->decode = odr_createmem(ODR_DECODE)) ||
167 !(anew->encode = odr_createmem(ODR_ENCODE)))
169 if (apdufile && *apdufile)
173 if (!(anew->print = odr_createmem(ODR_PRINT)))
175 if (*apdufile == '@')
177 odr_setprint(anew->print, yaz_log_file());
179 else if (*apdufile != '-')
182 sprintf(filename, "%.200s.%ld", apdufile, (long)getpid());
183 if (!(f = fopen(filename, "w")))
185 yaz_log(YLOG_WARN|YLOG_ERRNO, "%s", filename);
188 setvbuf(f, 0, _IONBF, 0);
189 odr_setprint(anew->print, f);
194 anew->input_buffer = 0;
195 anew->input_buffer_len = 0;
197 anew->state = ASSOC_NEW;
198 request_initq(&anew->incoming);
199 request_initq(&anew->outgoing);
200 anew->proto = cs_getproto(link);
206 * Free association and release resources.
208 void destroy_association(association *h)
210 statserv_options_block *cb = statserv_getcontrol();
214 odr_destroy(h->decode);
215 odr_destroy(h->encode);
217 odr_destroy(h->print);
219 xfree(h->input_buffer);
221 (*cb->bend_close)(h->backend);
222 while ((req = request_deq(&h->incoming)))
223 request_release(req);
224 while ((req = request_deq(&h->outgoing)))
225 request_release(req);
226 request_delq(&h->incoming);
227 request_delq(&h->outgoing);
229 xmalloc_trav("session closed");
230 if (cb && cb->one_shot)
236 static void do_close_req(association *a, int reason, char *message,
239 Z_APDU *apdu = zget_APDU(a->encode, Z_APDU_close);
240 Z_Close *cls = apdu->u.close;
242 /* Purge request queue */
243 while (request_deq(&a->incoming));
244 while (request_deq(&a->outgoing));
247 yaz_log(log_requestdetail, "Sending Close PDU, reason=%d, message=%s",
248 reason, message ? message : "none");
249 *cls->closeReason = reason;
250 cls->diagnosticInformation = message;
251 process_z_response(a, req, apdu);
252 iochan_settimeout(a->client_chan, 20);
256 request_release(req);
257 yaz_log(log_requestdetail, "v2 client. No Close PDU");
258 iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
261 a->state = ASSOC_DEAD;
264 static void do_close(association *a, int reason, char *message)
266 request *req = request_get(&a->outgoing);
267 do_close_req(a, reason, message, req);
271 int ir_read(IOCHAN h, int event)
273 association *assoc = (association *)iochan_getdata(h);
274 COMSTACK conn = assoc->client_link;
277 if ((assoc->cs_put_mask & EVENT_INPUT) == 0 && (event & assoc->cs_get_mask))
279 yaz_log(YLOG_DEBUG, "ir_session (input)");
280 /* We aren't speaking to this fellow */
281 if (assoc->state == ASSOC_DEAD)
283 yaz_log(log_sessiondetail, "Connection closed - end of session");
285 destroy_association(assoc);
289 assoc->cs_get_mask = EVENT_INPUT;
293 int res = cs_get(conn, &assoc->input_buffer,
294 &assoc->input_buffer_len);
295 if (res < 0 && cs_errno(conn) == CSBUFSIZE)
297 yaz_log(log_session, "Connection error: %s res=%d",
298 cs_errmsg(cs_errno(conn)), res);
299 req = request_get(&assoc->incoming); /* get a new request */
300 do_close_req(assoc, Z_Close_protocolError,
301 "Incoming package too large", req);
306 yaz_log(log_session, "Connection closed by client");
307 assoc->state = ASSOC_DEAD;
310 else if (res == 1) /* incomplete read - wait for more */
312 if (conn->io_pending & CS_WANT_WRITE)
313 assoc->cs_get_mask |= EVENT_OUTPUT;
314 iochan_setflag(h, assoc->cs_get_mask);
317 /* we got a complete PDU. Let's decode it */
318 yaz_log(YLOG_DEBUG, "Got PDU, %d bytes: lead=%02X %02X %02X", res,
319 assoc->input_buffer[0] & 0xff,
320 assoc->input_buffer[1] & 0xff,
321 assoc->input_buffer[2] & 0xff);
322 req = request_get(&assoc->incoming); /* get a new request */
323 odr_reset(assoc->decode);
324 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
325 if (!z_GDU(assoc->decode, &req->gdu_request, 0, 0))
327 yaz_log(YLOG_WARN, "ODR error on incoming PDU: %s [element %s] "
329 odr_errmsg(odr_geterror(assoc->decode)),
330 odr_getelement(assoc->decode),
331 (long) odr_offset(assoc->decode));
332 if (assoc->decode->error != OHTTP)
334 yaz_log(YLOG_WARN, "PDU dump:");
335 odr_dumpBER(yaz_log_file(), assoc->input_buffer, res);
336 request_release(req);
337 do_close(assoc, Z_Close_protocolError, "Malformed package");
341 Z_GDU *p = z_get_HTTP_Response(assoc->encode, 400);
342 assoc->state = ASSOC_DEAD;
343 process_gdu_response(assoc, req, p);
347 req->request_mem = odr_extract_mem(assoc->decode);
350 if (!z_GDU(assoc->print, &req->gdu_request, 0, 0))
351 yaz_log(YLOG_WARN, "ODR print error: %s",
352 odr_errmsg(odr_geterror(assoc->print)));
353 odr_reset(assoc->print);
355 request_enq(&assoc->incoming, req);
357 while (cs_more(conn));
363 * This is where PDUs from the client are read and the further
364 * processing is initiated. Flow of control moves down through the
365 * various process_* functions below, until the encoded result comes back up
366 * to the output handler in here.
368 * h : the I/O channel that has an outstanding event.
369 * event : the current outstanding event.
371 void ir_session(IOCHAN h, int event)
374 association *assoc = (association *)iochan_getdata(h);
375 COMSTACK conn = assoc->client_link;
378 assert(h && conn && assoc);
379 if (event == EVENT_TIMEOUT)
381 if (assoc->state != ASSOC_UP)
383 yaz_log(log_session, "Timeout. Closing connection");
384 /* do we need to lod this at all */
386 destroy_association(assoc);
391 yaz_log(log_sessiondetail, "Timeout. Sending Z39.50 Close");
392 do_close(assoc, Z_Close_lackOfActivity, 0);
396 if (event & assoc->cs_accept_mask)
398 if (!cs_accept(conn))
400 yaz_log(YLOG_WARN, "accept failed");
401 destroy_association(assoc);
405 iochan_clearflag(h, EVENT_OUTPUT);
406 if (conn->io_pending)
407 { /* cs_accept didn't complete */
408 assoc->cs_accept_mask =
409 ((conn->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
410 ((conn->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
412 iochan_setflag(h, assoc->cs_accept_mask);
415 { /* cs_accept completed. Prepare for reading (cs_get) */
416 assoc->cs_accept_mask = 0;
417 assoc->cs_get_mask = EVENT_INPUT;
418 iochan_setflag(h, assoc->cs_get_mask);
422 if (event & assoc->cs_get_mask) /* input */
424 if (!ir_read(h, event))
426 req = request_head(&assoc->incoming);
427 if (req->state == REQUEST_IDLE)
429 request_deq(&assoc->incoming);
430 process_gdu_request(assoc, req);
433 if (event & assoc->cs_put_mask)
435 request *req = request_head(&assoc->outgoing);
437 assoc->cs_put_mask = 0;
438 yaz_log(YLOG_DEBUG, "ir_session (output)");
439 req->state = REQUEST_PENDING;
440 switch (res = cs_put(conn, req->response, req->len_response))
443 yaz_log(log_sessiondetail, "Connection closed by client");
445 destroy_association(assoc);
448 case 0: /* all sent - release the request structure */
449 yaz_log(YLOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
451 yaz_log(YLOG_DEBUG, "HTTP out:\n%.*s", req->len_response,
454 nmem_destroy(req->request_mem);
455 request_deq(&assoc->outgoing);
456 request_release(req);
457 if (!request_head(&assoc->outgoing))
458 { /* restore mask for cs_get operation ... */
459 iochan_clearflag(h, EVENT_OUTPUT|EVENT_INPUT);
460 iochan_setflag(h, assoc->cs_get_mask);
461 if (assoc->state == ASSOC_DEAD)
462 iochan_setevent(assoc->client_chan, EVENT_TIMEOUT);
466 assoc->cs_put_mask = EVENT_OUTPUT;
470 if (conn->io_pending & CS_WANT_WRITE)
471 assoc->cs_put_mask |= EVENT_OUTPUT;
472 if (conn->io_pending & CS_WANT_READ)
473 assoc->cs_put_mask |= EVENT_INPUT;
474 iochan_setflag(h, assoc->cs_put_mask);
477 if (event & EVENT_EXCEPT)
479 yaz_log(YLOG_WARN, "ir_session (exception)");
481 destroy_association(assoc);
486 static int process_z_request(association *assoc, request *req, char **msg);
489 static void assoc_init_reset(association *assoc)
492 assoc->init = (bend_initrequest *) xmalloc(sizeof(*assoc->init));
494 assoc->init->stream = assoc->encode;
495 assoc->init->print = assoc->print;
496 assoc->init->auth = 0;
497 assoc->init->referenceId = 0;
498 assoc->init->implementation_version = 0;
499 assoc->init->implementation_id = 0;
500 assoc->init->implementation_name = 0;
501 assoc->init->query_charset = 0;
502 assoc->init->records_in_same_charset = 0;
503 assoc->init->bend_sort = NULL;
504 assoc->init->bend_search = NULL;
505 assoc->init->bend_present = NULL;
506 assoc->init->bend_esrequest = NULL;
507 assoc->init->bend_delete = NULL;
508 assoc->init->bend_scan = NULL;
509 assoc->init->bend_segment = NULL;
510 assoc->init->bend_fetch = NULL;
511 assoc->init->bend_explain = NULL;
512 assoc->init->bend_srw_scan = NULL;
513 assoc->init->bend_srw_update = NULL;
514 assoc->init->named_result_sets = 0;
516 assoc->init->charneg_request = NULL;
517 assoc->init->charneg_response = NULL;
519 assoc->init->decode = assoc->decode;
520 assoc->init->peer_name =
521 odr_strdup(assoc->encode, cs_addrstr(assoc->client_link));
523 yaz_log(log_requestdetail, "peer %s", assoc->init->peer_name);
526 static int srw_bend_init(association *assoc, Z_SRW_diagnostic **d, int *num, Z_SRW_PDU *sr)
528 statserv_options_block *cb = statserv_getcontrol();
531 const char *encoding = "UTF-8";
533 bend_initresult *binitres;
535 yaz_log(log_requestdetail, "srw_bend_init config=%s", cb->configname);
536 assoc_init_reset(assoc);
540 Z_IdAuthentication *auth = (Z_IdAuthentication *)
541 odr_malloc(assoc->decode, sizeof(*auth));
544 len = strlen(sr->username) + 1;
546 len += strlen(sr->password) + 2;
547 auth->which = Z_IdAuthentication_open;
548 auth->u.open = (char *) odr_malloc(assoc->decode, len);
549 strcpy(auth->u.open, sr->username);
550 if (sr->password && *sr->password)
552 strcat(auth->u.open, "/");
553 strcat(auth->u.open, sr->password);
555 assoc->init->auth = auth;
559 ce = yaz_set_proposal_charneg(assoc->decode, &encoding, 1, 0, 0, 1);
560 assoc->init->charneg_request = ce->u.charNeg3;
563 if (!(binitres = (*cb->bend_init)(assoc->init)))
565 assoc->state = ASSOC_DEAD;
566 yaz_add_srw_diagnostic(assoc->encode, d, num,
567 YAZ_SRW_AUTHENTICATION_ERROR, 0);
570 assoc->backend = binitres->handle;
571 assoc->init->auth = 0;
572 if (binitres->errcode)
574 int srw_code = yaz_diag_bib1_to_srw(binitres->errcode);
575 assoc->state = ASSOC_DEAD;
576 yaz_add_srw_diagnostic(assoc->encode, d, num, srw_code,
577 binitres->errstring);
585 static int retrieve_fetch(association *assoc, bend_fetch_rr *rr)
588 yaz_record_conv_t rc = 0;
589 const char *match_schema = 0;
590 Odr_oid *match_syntax = 0;
595 const char *input_schema = yaz_get_esn(rr->comp);
596 Odr_oid *input_syntax_raw = rr->request_format;
598 const char *backend_schema = 0;
599 Odr_oid *backend_syntax = 0;
601 r = yaz_retrieval_request(assoc->server->retrieval,
609 if (r == -1) /* error ? */
611 const char *details = yaz_retrieval_get_error(
612 assoc->server->retrieval);
614 rr->errcode = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
616 rr->errstring = odr_strdup(rr->stream, details);
619 else if (r == 1 || r == 3)
621 const char *details = input_schema;
623 YAZ_BIB1_SPECIFIED_ELEMENT_SET_NAME_NOT_VALID_FOR_SPECIFIED_;
625 rr->errstring = odr_strdup(rr->stream, details);
630 rr->errcode = YAZ_BIB1_RECORD_SYNTAX_UNSUPP;
631 if (input_syntax_raw)
633 char oidbuf[OID_STR_MAX];
634 oid_oid_to_dotstring(input_syntax_raw, oidbuf);
635 rr->errstring = odr_strdup(rr->stream, oidbuf);
641 yaz_set_esn(&rr->comp, backend_schema, odr_getmem(rr->stream));
644 rr->request_format = backend_syntax;
646 (*assoc->init->bend_fetch)(assoc->backend, rr);
647 if (rc && rr->record && rr->errcode == 0 && rr->len > 0)
648 { /* post conversion must take place .. */
649 WRBUF output_record = wrbuf_alloc();
650 int r = yaz_record_conv_record(rc, rr->record, rr->len, output_record);
653 const char *details = yaz_record_conv_get_error(rc);
654 rr->errcode = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
656 rr->errstring = odr_strdup(rr->stream, details);
660 rr->len = wrbuf_len(output_record);
661 rr->record = (char *) odr_malloc(rr->stream, rr->len);
662 memcpy(rr->record, wrbuf_buf(output_record), rr->len);
664 wrbuf_destroy(output_record);
667 rr->output_format = match_syntax;
669 rr->schema = odr_strdup(rr->stream, match_schema);
671 (*assoc->init->bend_fetch)(assoc->backend, rr);
676 static int srw_bend_fetch(association *assoc, int pos,
677 Z_SRW_searchRetrieveRequest *srw_req,
678 Z_SRW_record *record,
679 const char **addinfo)
682 ODR o = assoc->encode;
684 rr.setname = "default";
687 rr.request_format = odr_oiddup(assoc->decode, yaz_oid_recsyn_xml);
689 rr.comp = (Z_RecordComposition *)
690 odr_malloc(assoc->decode, sizeof(*rr.comp));
691 rr.comp->which = Z_RecordComp_complex;
692 rr.comp->u.complex = (Z_CompSpec *)
693 odr_malloc(assoc->decode, sizeof(Z_CompSpec));
694 rr.comp->u.complex->selectAlternativeSyntax = (bool_t *)
695 odr_malloc(assoc->encode, sizeof(bool_t));
696 *rr.comp->u.complex->selectAlternativeSyntax = 0;
697 rr.comp->u.complex->num_dbSpecific = 0;
698 rr.comp->u.complex->dbSpecific = 0;
699 rr.comp->u.complex->num_recordSyntax = 0;
700 rr.comp->u.complex->recordSyntax = 0;
702 rr.comp->u.complex->generic = (Z_Specification *)
703 odr_malloc(assoc->decode, sizeof(Z_Specification));
705 /* schema uri = recordSchema (or NULL if recordSchema is not given) */
706 rr.comp->u.complex->generic->which = Z_Schema_uri;
707 rr.comp->u.complex->generic->schema.uri = srw_req->recordSchema;
709 /* ESN = recordSchema if recordSchema is present */
710 rr.comp->u.complex->generic->elementSpec = 0;
711 if (srw_req->recordSchema)
713 rr.comp->u.complex->generic->elementSpec =
714 (Z_ElementSpec *) odr_malloc(assoc->encode, sizeof(Z_ElementSpec));
715 rr.comp->u.complex->generic->elementSpec->which =
716 Z_ElementSpec_elementSetName;
717 rr.comp->u.complex->generic->elementSpec->u.elementSetName =
718 srw_req->recordSchema;
721 rr.stream = assoc->encode;
722 rr.print = assoc->print;
730 rr.surrogate_flag = 0;
731 rr.schema = srw_req->recordSchema;
733 if (!assoc->init->bend_fetch)
736 retrieve_fetch(assoc, &rr);
738 if (rr.errcode && rr.surrogate_flag)
740 int code = yaz_diag_bib1_to_srw(rr.errcode);
741 yaz_mk_sru_surrogate(o, record, pos, code, rr.errstring);
744 else if (rr.len >= 0)
746 record->recordData_buf = rr.record;
747 record->recordData_len = rr.len;
748 record->recordPosition = odr_intdup(o, pos);
749 record->recordSchema = odr_strdup_null(
750 o, rr.schema ? rr.schema : srw_req->recordSchema);
754 *addinfo = rr.errstring;
760 static int cql2pqf(ODR odr, const char *cql, cql_transform_t ct,
761 Z_Query *query_result)
763 /* have a CQL query and CQL to PQF transform .. */
764 CQL_parser cp = cql_parser_create();
770 r = cql_parser_string(cp, cql);
773 srw_errcode = YAZ_SRW_QUERY_SYNTAX_ERROR;
778 r = cql_transform_buf(ct,
779 cql_parser_result(cp),
780 rpn_buf, sizeof(rpn_buf)-1);
782 srw_errcode = cql_transform_error(ct, &add);
786 /* Syntax & transform OK. */
787 /* Convert PQF string to Z39.50 to RPN query struct */
788 YAZ_PQF_Parser pp = yaz_pqf_create();
789 Z_RPNQuery *rpnquery = yaz_pqf_parse(pp, odr, rpn_buf);
794 int code = yaz_pqf_error(pp, &pqf_msg, &off);
795 yaz_log(YLOG_WARN, "PQF Parser Error %s (code %d)",
797 srw_errcode = YAZ_SRW_QUERY_SYNTAX_ERROR;
801 query_result->which = Z_Query_type_1;
802 query_result->u.type_1 = rpnquery;
806 cql_parser_destroy(cp);
810 static int cql2pqf_scan(ODR odr, const char *cql, cql_transform_t ct,
811 Z_AttributesPlusTerm *result)
815 int srw_error = cql2pqf(odr, cql, ct, &query);
818 if (query.which != Z_Query_type_1 && query.which != Z_Query_type_101)
819 return YAZ_SRW_QUERY_SYNTAX_ERROR; /* bad query type */
820 rpn = query.u.type_1;
821 if (!rpn->RPNStructure)
822 return YAZ_SRW_QUERY_SYNTAX_ERROR; /* must be structure */
823 if (rpn->RPNStructure->which != Z_RPNStructure_simple)
824 return YAZ_SRW_QUERY_SYNTAX_ERROR; /* must be simple */
825 if (rpn->RPNStructure->u.simple->which != Z_Operand_APT)
826 return YAZ_SRW_QUERY_SYNTAX_ERROR; /* must be be attributes + term */
827 memcpy(result, rpn->RPNStructure->u.simple->u.attributesPlusTerm,
833 static int ccl2pqf(ODR odr, const Odr_oct *ccl, CCL_bibset bibset,
834 bend_search_rr *bsrr)
837 struct ccl_rpn_node *node;
840 ccl0 = odr_strdupn(odr, (char*) ccl->buf, ccl->len);
841 if ((node = ccl_find_str(bibset, ccl0, &errcode, &pos)) == 0)
843 bsrr->errstring = (char*) ccl_err_msg(errcode);
844 return YAZ_SRW_QUERY_SYNTAX_ERROR; /* Query syntax error */
847 bsrr->query->which = Z_Query_type_1;
848 bsrr->query->u.type_1 = ccl_rpn_query(odr, node);
852 static void srw_bend_search(association *assoc,
857 Z_SRW_searchRetrieveResponse *srw_res = res->u.response;
860 Z_SRW_searchRetrieveRequest *srw_req = sr->u.request;
863 yaz_log(log_requestdetail, "Got SRW SearchRetrieveRequest");
864 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
865 if (srw_res->num_diagnostics == 0 && assoc->init)
868 rr.setname = "default";
871 rr.basenames = &srw_req->database;
875 rr.srw_setnameIdleTime = 0;
876 rr.estimated_hit_count = 0;
877 rr.partial_resultset = 0;
878 rr.query = (Z_Query *) odr_malloc(assoc->decode, sizeof(*rr.query));
879 rr.query->u.type_1 = 0;
880 rr.extra_args = sr->extra_args;
881 rr.extra_response_data = 0;
883 if (srw_req->query_type == Z_SRW_query_type_cql)
885 if (assoc->server && assoc->server->cql_transform)
887 int srw_errcode = cql2pqf(assoc->encode, srw_req->query.cql,
888 assoc->server->cql_transform,
892 yaz_add_srw_diagnostic(assoc->encode,
893 &srw_res->diagnostics,
894 &srw_res->num_diagnostics,
900 /* CQL query to backend. Wrap it - Z39.50 style */
901 ext = (Z_External *) odr_malloc(assoc->decode, sizeof(*ext));
902 ext->direct_reference = odr_getoidbystr(assoc->decode,
903 "1.2.840.10003.16.2");
904 ext->indirect_reference = 0;
906 ext->which = Z_External_CQL;
907 ext->u.cql = srw_req->query.cql;
909 rr.query->which = Z_Query_type_104;
910 rr.query->u.type_104 = ext;
913 else if (srw_req->query_type == Z_SRW_query_type_pqf)
915 Z_RPNQuery *RPNquery;
916 YAZ_PQF_Parser pqf_parser;
918 pqf_parser = yaz_pqf_create();
920 RPNquery = yaz_pqf_parse(pqf_parser, assoc->decode,
926 int code = yaz_pqf_error(pqf_parser, &pqf_msg, &off);
927 yaz_log(log_requestdetail, "Parse error %d %s near offset %ld",
928 code, pqf_msg, (long) off);
929 srw_error = YAZ_SRW_QUERY_SYNTAX_ERROR;
932 rr.query->which = Z_Query_type_1;
933 rr.query->u.type_1 = RPNquery;
935 yaz_pqf_destroy(pqf_parser);
939 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
940 &srw_res->num_diagnostics,
941 YAZ_SRW_UNSUPP_QUERY_TYPE, 0);
943 if (rr.query->u.type_1)
945 rr.stream = assoc->encode;
946 rr.decode = assoc->decode;
947 rr.print = assoc->print;
948 if ( srw_req->sort.sortKeys )
949 rr.srw_sortKeys = odr_strdup(assoc->encode,
950 srw_req->sort.sortKeys );
951 rr.association = assoc;
957 yaz_log_zquery_level(log_requestdetail,rr.query);
959 (assoc->init->bend_search)(assoc->backend, &rr);
962 if (rr.errcode == YAZ_BIB1_DATABASE_UNAVAILABLE)
968 srw_error = yaz_diag_bib1_to_srw(rr.errcode);
969 yaz_add_srw_diagnostic(assoc->encode,
970 &srw_res->diagnostics,
971 &srw_res->num_diagnostics,
972 srw_error, rr.errstring);
977 int number = srw_req->maximumRecords ?
978 odr_int_to_int(*srw_req->maximumRecords) : 0;
979 int start = srw_req->startRecord ?
980 odr_int_to_int(*srw_req->startRecord) : 1;
982 yaz_log(log_requestdetail, "Request to pack %d+%d out of "
984 start, number, rr.hits);
986 srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
989 srw_res->resultSetId =
990 odr_strdup(assoc->encode, rr.srw_setname );
991 srw_res->resultSetIdleTime =
992 odr_intdup(assoc->encode, *rr.srw_setnameIdleTime );
995 if (start > rr.hits || start < 1)
997 /* if hits<=0 and start=1 we don't return a diagnostic */
999 yaz_add_srw_diagnostic(
1001 &srw_res->diagnostics, &srw_res->num_diagnostics,
1002 YAZ_SRW_FIRST_RECORD_POSITION_OUT_OF_RANGE, 0);
1004 else if (number > 0)
1008 if (start + number > rr.hits)
1009 number = odr_int_to_int(rr.hits) - start + 1;
1011 /* Call bend_present if defined */
1012 if (assoc->init->bend_present)
1014 bend_present_rr *bprr = (bend_present_rr*)
1015 odr_malloc(assoc->decode, sizeof(*bprr));
1016 bprr->setname = "default";
1017 bprr->start = start;
1018 bprr->number = number;
1019 if (srw_req->recordSchema)
1021 bprr->comp = (Z_RecordComposition *) odr_malloc(assoc->decode,
1022 sizeof(*bprr->comp));
1023 bprr->comp->which = Z_RecordComp_simple;
1024 bprr->comp->u.simple = (Z_ElementSetNames *)
1025 odr_malloc(assoc->decode, sizeof(Z_ElementSetNames));
1026 bprr->comp->u.simple->which = Z_ElementSetNames_generic;
1027 bprr->comp->u.simple->u.generic = srw_req->recordSchema;
1033 bprr->stream = assoc->encode;
1034 bprr->referenceId = 0;
1035 bprr->print = assoc->print;
1036 bprr->association = assoc;
1038 bprr->errstring = NULL;
1039 (*assoc->init->bend_present)(assoc->backend, bprr);
1043 srw_error = yaz_diag_bib1_to_srw(bprr->errcode);
1044 yaz_add_srw_diagnostic(assoc->encode,
1045 &srw_res->diagnostics,
1046 &srw_res->num_diagnostics,
1047 srw_error, bprr->errstring);
1055 int packing = Z_SRW_recordPacking_string;
1056 if (srw_req->recordPacking)
1059 yaz_srw_str_to_pack(srw_req->recordPacking);
1061 packing = Z_SRW_recordPacking_string;
1063 srw_res->records = (Z_SRW_record *)
1064 odr_malloc(assoc->encode,
1065 number * sizeof(*srw_res->records));
1067 srw_res->extra_records = (Z_SRW_extra_record **)
1068 odr_malloc(assoc->encode,
1069 number*sizeof(*srw_res->extra_records));
1071 for (i = 0; i<number; i++)
1074 const char *addinfo = 0;
1076 srw_res->records[j].recordPacking = packing;
1077 srw_res->records[j].recordData_buf = 0;
1078 srw_res->extra_records[j] = 0;
1079 yaz_log(YLOG_DEBUG, "srw_bend_fetch %d", i+start);
1080 errcode = srw_bend_fetch(assoc, i+start, srw_req,
1081 srw_res->records + j,
1085 yaz_add_srw_diagnostic(assoc->encode,
1086 &srw_res->diagnostics,
1087 &srw_res->num_diagnostics,
1088 yaz_diag_bib1_to_srw(errcode),
1093 if (srw_res->records[j].recordData_buf)
1096 srw_res->num_records = j;
1098 srw_res->records = 0;
1101 if (rr.extra_response_data)
1103 res->extraResponseData_buf = rr.extra_response_data;
1104 res->extraResponseData_len = strlen(rr.extra_response_data);
1106 if (rr.estimated_hit_count || rr.partial_resultset)
1108 yaz_add_srw_diagnostic(
1110 &srw_res->diagnostics,
1111 &srw_res->num_diagnostics,
1112 YAZ_SRW_RESULT_SET_CREATED_WITH_VALID_PARTIAL_RESULTS_AVAILABLE,
1120 const char *querystr = "?";
1121 const char *querytype = "?";
1122 WRBUF wr = wrbuf_alloc();
1124 switch (srw_req->query_type)
1126 case Z_SRW_query_type_cql:
1128 querystr = srw_req->query.cql;
1130 case Z_SRW_query_type_pqf:
1132 querystr = srw_req->query.pqf;
1135 wrbuf_printf(wr, "SRWSearch %s ", srw_req->database);
1136 if (srw_res->num_diagnostics)
1137 wrbuf_printf(wr, "ERROR %s", srw_res->diagnostics[0].uri);
1138 else if (*http_code != 200)
1139 wrbuf_printf(wr, "ERROR info:http/%d", *http_code);
1140 else if (srw_res->numberOfRecords)
1142 wrbuf_printf(wr, "OK " ODR_INT_PRINTF,
1143 (srw_res->numberOfRecords ?
1144 *srw_res->numberOfRecords : 0));
1146 wrbuf_printf(wr, " %s " ODR_INT_PRINTF "+%d",
1147 (srw_res->resultSetId ?
1148 srw_res->resultSetId : "-"),
1149 (srw_req->startRecord ? *srw_req->startRecord : 1),
1150 srw_res->num_records);
1151 yaz_log(log_request, "%s %s: %s", wrbuf_cstr(wr), querytype, querystr);
1156 static char *srw_bend_explain_default(bend_explain_rr *rr)
1159 xmlNodePtr ptr = (xmlNode *) rr->server_node_ptr;
1162 for (ptr = ptr->children; ptr; ptr = ptr->next)
1164 if (ptr->type != XML_ELEMENT_NODE)
1166 if (!strcmp((const char *) ptr->name, "explain"))
1169 xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
1173 ptr = xmlCopyNode(ptr, 1);
1175 xmlDocSetRootElement(doc, ptr);
1177 xmlDocDumpMemory(doc, &buf_out, &len);
1178 content = (char*) odr_malloc(rr->stream, 1+len);
1179 memcpy(content, buf_out, len);
1180 content[len] = '\0';
1184 rr->explain_buf = content;
1192 static void srw_bend_explain(association *assoc,
1194 Z_SRW_explainResponse *srw_res,
1197 Z_SRW_explainRequest *srw_req = sr->u.explain_request;
1198 yaz_log(log_requestdetail, "Got SRW ExplainRequest");
1200 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1205 rr.stream = assoc->encode;
1206 rr.decode = assoc->decode;
1207 rr.print = assoc->print;
1209 rr.database = srw_req->database;
1211 rr.server_node_ptr = assoc->server->server_node_ptr;
1213 rr.server_node_ptr = 0;
1214 rr.schema = "http://explain.z3950.org/dtd/2.0/";
1215 if (assoc->init->bend_explain)
1216 (*assoc->init->bend_explain)(assoc->backend, &rr);
1218 srw_bend_explain_default(&rr);
1222 int packing = Z_SRW_recordPacking_string;
1223 if (srw_req->recordPacking)
1226 yaz_srw_str_to_pack(srw_req->recordPacking);
1228 packing = Z_SRW_recordPacking_string;
1230 srw_res->record.recordSchema = rr.schema;
1231 srw_res->record.recordPacking = packing;
1232 srw_res->record.recordData_buf = rr.explain_buf;
1233 srw_res->record.recordData_len = strlen(rr.explain_buf);
1234 srw_res->record.recordPosition = 0;
1240 static void srw_bend_scan(association *assoc,
1242 Z_SRW_scanResponse *srw_res,
1245 Z_SRW_scanRequest *srw_req = sr->u.scan_request;
1246 yaz_log(log_requestdetail, "Got SRW ScanRequest");
1249 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1250 if (srw_res->num_diagnostics == 0 && assoc->init)
1253 struct scan_entry *save_entries;
1255 bend_scan_rr *bsrr = (bend_scan_rr *)
1256 odr_malloc(assoc->encode, sizeof(*bsrr));
1257 bsrr->num_bases = 1;
1258 bsrr->basenames = &srw_req->database;
1260 bsrr->num_entries = srw_req->maximumTerms ?
1261 odr_int_to_int(*srw_req->maximumTerms) : 10;
1262 bsrr->term_position = srw_req->responsePosition ?
1263 odr_int_to_int(*srw_req->responsePosition) : 1;
1266 bsrr->errstring = 0;
1267 bsrr->referenceId = 0;
1268 bsrr->stream = assoc->encode;
1269 bsrr->print = assoc->print;
1270 bsrr->step_size = &step_size;
1274 if (bsrr->num_entries > 0)
1277 bsrr->entries = (struct scan_entry *)
1278 odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
1280 for (i = 0; i<bsrr->num_entries; i++)
1282 bsrr->entries[i].term = 0;
1283 bsrr->entries[i].occurrences = 0;
1284 bsrr->entries[i].errcode = 0;
1285 bsrr->entries[i].errstring = 0;
1286 bsrr->entries[i].display_term = 0;
1289 save_entries = bsrr->entries; /* save it so we can compare later */
1291 if (srw_req->query_type == Z_SRW_query_type_pqf &&
1292 assoc->init->bend_scan)
1294 YAZ_PQF_Parser pqf_parser = yaz_pqf_create();
1296 bsrr->term = yaz_pqf_scan(pqf_parser, assoc->decode,
1297 &bsrr->attributeset,
1298 srw_req->scanClause.pqf);
1299 yaz_pqf_destroy(pqf_parser);
1300 bsrr->scanClause = 0;
1301 ((int (*)(void *, bend_scan_rr *))
1302 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1304 else if (srw_req->query_type == Z_SRW_query_type_cql
1305 && assoc->init->bend_scan && assoc->server
1306 && assoc->server->cql_transform)
1309 bsrr->scanClause = 0;
1310 bsrr->attributeset = 0;
1311 bsrr->term = (Z_AttributesPlusTerm *)
1312 odr_malloc(assoc->decode, sizeof(*bsrr->term));
1313 srw_error = cql2pqf_scan(assoc->encode,
1314 srw_req->scanClause.cql,
1315 assoc->server->cql_transform,
1318 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1319 &srw_res->num_diagnostics,
1323 ((int (*)(void *, bend_scan_rr *))
1324 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1327 else if (srw_req->query_type == Z_SRW_query_type_cql
1328 && assoc->init->bend_srw_scan)
1331 bsrr->attributeset = 0;
1332 bsrr->scanClause = srw_req->scanClause.cql;
1333 ((int (*)(void *, bend_scan_rr *))
1334 (*assoc->init->bend_srw_scan))(assoc->backend, bsrr);
1338 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1339 &srw_res->num_diagnostics,
1340 YAZ_SRW_UNSUPP_OPERATION, "scan");
1345 if (bsrr->errcode == YAZ_BIB1_DATABASE_UNAVAILABLE)
1350 srw_error = yaz_diag_bib1_to_srw(bsrr->errcode);
1352 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1353 &srw_res->num_diagnostics,
1354 srw_error, bsrr->errstring);
1356 else if (srw_res->num_diagnostics == 0 && bsrr->num_entries)
1359 srw_res->terms = (Z_SRW_scanTerm*)
1360 odr_malloc(assoc->encode, sizeof(*srw_res->terms) *
1363 srw_res->num_terms = bsrr->num_entries;
1364 for (i = 0; i<bsrr->num_entries; i++)
1366 Z_SRW_scanTerm *t = srw_res->terms + i;
1367 t->value = odr_strdup(assoc->encode, bsrr->entries[i].term);
1368 t->numberOfRecords =
1369 odr_intdup(assoc->encode, bsrr->entries[i].occurrences);
1371 if (save_entries == bsrr->entries &&
1372 bsrr->entries[i].display_term)
1374 /* the entries was _not_ set by the handler. So it's
1375 safe to test for new member display_term. It is
1378 t->displayTerm = odr_strdup(assoc->encode,
1379 bsrr->entries[i].display_term);
1387 WRBUF wr = wrbuf_alloc();
1388 const char *querytype = 0;
1389 const char *querystr = 0;
1391 switch(srw_req->query_type)
1393 case Z_SRW_query_type_pqf:
1395 querystr = srw_req->scanClause.pqf;
1397 case Z_SRW_query_type_cql:
1399 querystr = srw_req->scanClause.cql;
1402 querytype = "UNKNOWN";
1406 wrbuf_printf(wr, "SRWScan %s ", srw_req->database);
1408 if (srw_res->num_diagnostics)
1409 wrbuf_printf(wr, "ERROR %s - ", srw_res->diagnostics[0].uri);
1410 else if (srw_res->num_terms)
1411 wrbuf_printf(wr, "OK %d - ", srw_res->num_terms);
1413 wrbuf_printf(wr, "OK - - ");
1415 wrbuf_printf(wr, ODR_INT_PRINTF "+" ODR_INT_PRINTF " ",
1416 (srw_req->responsePosition ?
1417 *srw_req->responsePosition : 1),
1418 (srw_req->maximumTerms ?
1419 *srw_req->maximumTerms : 1));
1420 /* there is no step size in SRU/W ??? */
1421 wrbuf_printf(wr, "%s: %s ", querytype, querystr);
1422 yaz_log(log_request, "%s ", wrbuf_cstr(wr) );
1428 static void srw_bend_update(association *assoc,
1430 Z_SRW_updateResponse *srw_res,
1433 Z_SRW_updateRequest *srw_req = sr->u.update_request;
1434 yaz_log(log_session, "SRWUpdate action=%s", srw_req->operation);
1435 yaz_log(YLOG_DEBUG, "num_diag = %d", srw_res->num_diagnostics );
1437 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1441 Z_SRW_extra_record *extra = srw_req->extra_record;
1443 rr.stream = assoc->encode;
1444 rr.print = assoc->print;
1446 rr.basenames = &srw_req->database;
1447 rr.operation = srw_req->operation;
1448 rr.operation_status = "failed";
1450 rr.record_versions = 0;
1451 rr.num_versions = 0;
1452 rr.record_packing = "string";
1453 rr.record_schema = 0;
1455 rr.extra_record_data = 0;
1456 rr.extra_request_data = 0;
1457 rr.extra_response_data = 0;
1463 if (rr.operation == 0)
1465 yaz_add_sru_update_diagnostic(
1466 assoc->encode, &srw_res->diagnostics,
1467 &srw_res->num_diagnostics,
1468 YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,
1472 yaz_log(YLOG_DEBUG, "basename = %s", rr.basenames[0] );
1473 yaz_log(YLOG_DEBUG, "Operation = %s", rr.operation );
1474 if (!strcmp( rr.operation, "delete"))
1476 if (srw_req->record && !srw_req->record->recordSchema)
1478 rr.record_schema = odr_strdup(
1480 srw_req->record->recordSchema);
1482 if (srw_req->record)
1484 rr.record_data = odr_strdupn(
1486 srw_req->record->recordData_buf,
1487 srw_req->record->recordData_len );
1489 if (extra && extra->extraRecordData_len)
1491 rr.extra_record_data = odr_strdupn(
1493 extra->extraRecordData_buf,
1494 extra->extraRecordData_len );
1496 if (srw_req->recordId)
1497 rr.record_id = srw_req->recordId;
1498 else if (extra && extra->recordIdentifier)
1499 rr.record_id = extra->recordIdentifier;
1501 else if (!strcmp(rr.operation, "replace"))
1503 if (srw_req->recordId)
1504 rr.record_id = srw_req->recordId;
1505 else if (extra && extra->recordIdentifier)
1506 rr.record_id = extra->recordIdentifier;
1509 yaz_add_sru_update_diagnostic(
1510 assoc->encode, &srw_res->diagnostics,
1511 &srw_res->num_diagnostics,
1512 YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,
1513 "recordIdentifier");
1515 if (!srw_req->record)
1517 yaz_add_sru_update_diagnostic(
1518 assoc->encode, &srw_res->diagnostics,
1519 &srw_res->num_diagnostics,
1520 YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,
1525 if (srw_req->record->recordSchema)
1526 rr.record_schema = odr_strdup(
1527 assoc->encode, srw_req->record->recordSchema);
1528 if (srw_req->record->recordData_len )
1530 rr.record_data = odr_strdupn(assoc->encode,
1531 srw_req->record->recordData_buf,
1532 srw_req->record->recordData_len );
1536 yaz_add_sru_update_diagnostic(
1537 assoc->encode, &srw_res->diagnostics,
1538 &srw_res->num_diagnostics,
1539 YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,
1543 if (extra && extra->extraRecordData_len)
1545 rr.extra_record_data = odr_strdupn(
1547 extra->extraRecordData_buf,
1548 extra->extraRecordData_len );
1551 else if (!strcmp(rr.operation, "insert"))
1553 if (srw_req->recordId)
1554 rr.record_id = srw_req->recordId;
1556 rr.record_id = extra->recordIdentifier;
1558 if (srw_req->record)
1560 if (srw_req->record->recordSchema)
1561 rr.record_schema = odr_strdup(
1562 assoc->encode, srw_req->record->recordSchema);
1564 if (srw_req->record->recordData_len)
1565 rr.record_data = odr_strdupn(
1567 srw_req->record->recordData_buf,
1568 srw_req->record->recordData_len );
1570 if (extra && extra->extraRecordData_len)
1572 rr.extra_record_data = odr_strdupn(
1574 extra->extraRecordData_buf,
1575 extra->extraRecordData_len );
1579 yaz_add_sru_update_diagnostic(assoc->encode, &srw_res->diagnostics,
1580 &srw_res->num_diagnostics,
1581 YAZ_SRU_UPDATE_INVALID_ACTION,
1584 if (srw_req->record)
1586 const char *pack_str =
1587 yaz_srw_pack_to_str(srw_req->record->recordPacking);
1589 rr.record_packing = odr_strdup(assoc->encode, pack_str);
1592 if (srw_req->num_recordVersions)
1594 rr.record_versions = srw_req->recordVersions;
1595 rr.num_versions = srw_req->num_recordVersions;
1597 if (srw_req->extraRequestData_len)
1599 rr.extra_request_data = odr_strdupn(assoc->encode,
1600 srw_req->extraRequestData_buf,
1601 srw_req->extraRequestData_len );
1603 if (srw_res->num_diagnostics == 0)
1605 if ( assoc->init->bend_srw_update)
1606 (*assoc->init->bend_srw_update)(assoc->backend, &rr);
1608 yaz_add_sru_update_diagnostic(
1609 assoc->encode, &srw_res->diagnostics,
1610 &srw_res->num_diagnostics,
1611 YAZ_SRU_UPDATE_UNSPECIFIED_DATABASE_ERROR,
1612 "No Update backend handler");
1616 yaz_add_srw_diagnostic_uri(assoc->encode,
1617 &srw_res->diagnostics,
1618 &srw_res->num_diagnostics,
1622 srw_res->recordId = rr.record_id;
1623 srw_res->operationStatus = rr.operation_status;
1624 srw_res->recordVersions = rr.record_versions;
1625 srw_res->num_recordVersions = rr.num_versions;
1626 if (srw_res->extraResponseData_len)
1628 srw_res->extraResponseData_buf = rr.extra_response_data;
1629 srw_res->extraResponseData_len = strlen(rr.extra_response_data);
1631 if (srw_res->num_diagnostics == 0 && rr.record_data)
1633 srw_res->record = yaz_srw_get_record(assoc->encode);
1634 srw_res->record->recordSchema = rr.record_schema;
1635 if (rr.record_packing)
1637 int pack = yaz_srw_str_to_pack(rr.record_packing);
1641 pack = Z_SRW_recordPacking_string;
1642 yaz_log(YLOG_WARN, "Back packing %s from backend",
1645 srw_res->record->recordPacking = pack;
1647 srw_res->record->recordData_buf = rr.record_data;
1648 srw_res->record->recordData_len = strlen(rr.record_data);
1649 if (rr.extra_record_data)
1651 Z_SRW_extra_record *ex =
1652 yaz_srw_get_extra_record(assoc->encode);
1653 srw_res->extra_record = ex;
1654 ex->extraRecordData_buf = rr.extra_record_data;
1655 ex->extraRecordData_len = strlen(rr.extra_record_data);
1661 /* check if path is OK (1); BAD (0) */
1662 static int check_path(const char *path)
1666 if (strstr(path, ".."))
1671 static char *read_file(const char *fname, ODR o, size_t *sz)
1674 FILE *inf = fopen(fname, "rb");
1678 fseek(inf, 0L, SEEK_END);
1681 buf = (char *) odr_malloc(o, *sz);
1682 if (fread(buf, 1, *sz, inf) != *sz)
1683 yaz_log(YLOG_WARN|YLOG_ERRNO, "short read %s", fname);
1688 static void process_http_request(association *assoc, request *req)
1690 Z_HTTP_Request *hreq = req->gdu_request->u.HTTP_Request;
1691 ODR o = assoc->encode;
1692 int r = 2; /* 2=NOT TAKEN, 1=TAKEN, 0=SOAP TAKEN */
1694 Z_SOAP *soap_package = 0;
1697 Z_HTTP_Response *hres = 0;
1699 const char *stylesheet = 0; /* for now .. set later */
1700 Z_SRW_diagnostic *diagnostic = 0;
1701 int num_diagnostic = 0;
1702 const char *host = z_HTTP_header_lookup(hreq->headers, "Host");
1704 yaz_log(log_request, "%s %s HTTP/%s", hreq->method, hreq->path, hreq->version);
1705 if (!control_association(assoc, host, 0))
1707 p = z_get_HTTP_Response(o, 404);
1710 if (r == 2 && assoc->server && assoc->server->docpath
1711 && hreq->path[0] == '/'
1713 /* check if path is a proper prefix of documentroot */
1714 strncmp(hreq->path+1, assoc->server->docpath,
1715 strlen(assoc->server->docpath))
1718 if (!check_path(hreq->path))
1720 yaz_log(YLOG_LOG, "File %s access forbidden", hreq->path+1);
1721 p = z_get_HTTP_Response(o, 404);
1725 size_t content_size = 0;
1726 char *content_buf = read_file(hreq->path+1, o, &content_size);
1729 yaz_log(YLOG_LOG, "File %s not found", hreq->path+1);
1730 p = z_get_HTTP_Response(o, 404);
1734 const char *ctype = 0;
1735 yaz_mime_types types = yaz_mime_types_create();
1737 yaz_mime_types_add(types, "xsl", "application/xml");
1738 yaz_mime_types_add(types, "xml", "application/xml");
1739 yaz_mime_types_add(types, "css", "text/css");
1740 yaz_mime_types_add(types, "html", "text/html");
1741 yaz_mime_types_add(types, "htm", "text/html");
1742 yaz_mime_types_add(types, "txt", "text/plain");
1743 yaz_mime_types_add(types, "js", "application/x-javascript");
1745 yaz_mime_types_add(types, "gif", "image/gif");
1746 yaz_mime_types_add(types, "png", "image/png");
1747 yaz_mime_types_add(types, "jpg", "image/jpeg");
1748 yaz_mime_types_add(types, "jpeg", "image/jpeg");
1750 ctype = yaz_mime_lookup_fname(types, hreq->path);
1753 yaz_log(YLOG_LOG, "No mime type for %s", hreq->path+1);
1754 p = z_get_HTTP_Response(o, 404);
1758 p = z_get_HTTP_Response(o, 200);
1759 hres = p->u.HTTP_Response;
1760 hres->content_buf = content_buf;
1761 hres->content_len = content_size;
1762 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1764 yaz_mime_types_destroy(types);
1772 r = yaz_srw_decode(hreq, &sr, &soap_package, assoc->decode, &charset);
1773 yaz_log(YLOG_DEBUG, "yaz_srw_decode returned %d", r);
1775 if (r == 2) /* not taken */
1777 r = yaz_sru_decode(hreq, &sr, &soap_package, assoc->decode, &charset,
1778 &diagnostic, &num_diagnostic);
1779 yaz_log(YLOG_DEBUG, "yaz_sru_decode returned %d", r);
1781 if (r == 0) /* decode SRW/SRU OK .. */
1783 int http_code = 200;
1784 if (sr->which == Z_SRW_searchRetrieve_request)
1787 yaz_srw_get_pdu(assoc->encode, Z_SRW_searchRetrieve_response,
1789 stylesheet = sr->u.request->stylesheet;
1792 res->u.response->diagnostics = diagnostic;
1793 res->u.response->num_diagnostics = num_diagnostic;
1797 srw_bend_search(assoc, sr, res, &http_code);
1799 if (http_code == 200)
1800 soap_package->u.generic->p = res;
1802 else if (sr->which == Z_SRW_explain_request)
1804 Z_SRW_PDU *res = yaz_srw_get_pdu(o, Z_SRW_explain_response,
1806 stylesheet = sr->u.explain_request->stylesheet;
1809 res->u.explain_response->diagnostics = diagnostic;
1810 res->u.explain_response->num_diagnostics = num_diagnostic;
1812 srw_bend_explain(assoc, sr, res->u.explain_response, &http_code);
1813 if (http_code == 200)
1814 soap_package->u.generic->p = res;
1816 else if (sr->which == Z_SRW_scan_request)
1818 Z_SRW_PDU *res = yaz_srw_get_pdu(o, Z_SRW_scan_response,
1820 stylesheet = sr->u.scan_request->stylesheet;
1823 res->u.scan_response->diagnostics = diagnostic;
1824 res->u.scan_response->num_diagnostics = num_diagnostic;
1826 srw_bend_scan(assoc, sr, res->u.scan_response, &http_code);
1827 if (http_code == 200)
1828 soap_package->u.generic->p = res;
1830 else if (sr->which == Z_SRW_update_request)
1832 Z_SRW_PDU *res = yaz_srw_get_pdu(o, Z_SRW_update_response,
1834 yaz_log(YLOG_DEBUG, "handling SRW UpdateRequest");
1837 res->u.update_response->diagnostics = diagnostic;
1838 res->u.update_response->num_diagnostics = num_diagnostic;
1840 yaz_log(YLOG_DEBUG, "num_diag = %d", res->u.update_response->num_diagnostics );
1841 srw_bend_update(assoc, sr, res->u.update_response, &http_code);
1842 if (http_code == 200)
1843 soap_package->u.generic->p = res;
1847 yaz_log(log_request, "SOAP ERROR");
1848 /* FIXME - what error, what query */
1850 z_soap_error(assoc->encode, soap_package,
1851 "SOAP-ENV:Client", "Bad method", 0);
1853 if (http_code == 200 || http_code == 500)
1855 static Z_SOAP_Handler soap_handlers[4] = {
1857 {YAZ_XMLNS_SRU_v1_1, 0, (Z_SOAP_fun) yaz_srw_codec},
1858 {YAZ_XMLNS_SRU_v1_0, 0, (Z_SOAP_fun) yaz_srw_codec},
1859 {YAZ_XMLNS_UPDATE_v0_9, 0, (Z_SOAP_fun) yaz_ucp_codec},
1865 p = z_get_HTTP_Response(o, 200);
1866 hres = p->u.HTTP_Response;
1868 if (!stylesheet && assoc->server)
1869 stylesheet = assoc->server->stylesheet;
1871 /* empty stylesheet means NO stylesheet */
1872 if (stylesheet && *stylesheet == '\0')
1875 ret = z_soap_codec_enc_xsl(assoc->encode, &soap_package,
1876 &hres->content_buf, &hres->content_len,
1877 soap_handlers, charset, stylesheet);
1878 hres->code = http_code;
1880 strcpy(ctype, "text/xml");
1881 if (charset && strlen(charset) < sizeof(ctype)-30)
1883 strcat(ctype, "; charset=");
1884 strcat(ctype, charset);
1886 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1889 p = z_get_HTTP_Response(o, http_code);
1893 p = z_get_HTTP_Response(o, 500);
1894 hres = p->u.HTTP_Response;
1895 if (!strcmp(hreq->version, "1.0"))
1897 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1898 if (v && !strcmp(v, "Keep-Alive"))
1902 hres->version = "1.0";
1906 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1907 if (v && !strcmp(v, "close"))
1911 hres->version = "1.1";
1913 if (!keepalive || !assoc->last_control->keepalive)
1915 z_HTTP_header_add(o, &hres->headers, "Connection", "close");
1916 assoc->state = ASSOC_DEAD;
1917 assoc->cs_get_mask = 0;
1922 const char *alive = z_HTTP_header_lookup(hreq->headers, "Keep-Alive");
1924 if (alive && isdigit(*(const unsigned char *) alive))
1928 if (t < 0 || t > 3600)
1930 iochan_settimeout(assoc->client_chan,t);
1931 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1933 process_gdu_response(assoc, req, p);
1936 static void process_gdu_request(association *assoc, request *req)
1938 if (req->gdu_request->which == Z_GDU_Z3950)
1941 req->apdu_request = req->gdu_request->u.z3950;
1942 if (process_z_request(assoc, req, &msg) < 0)
1943 do_close_req(assoc, Z_Close_systemProblem, msg, req);
1945 else if (req->gdu_request->which == Z_GDU_HTTP_Request)
1946 process_http_request(assoc, req);
1949 do_close_req(assoc, Z_Close_systemProblem, "bad protocol packet", req);
1954 * Initiate request processing.
1956 static int process_z_request(association *assoc, request *req, char **msg)
1961 *msg = "Unknown Error";
1962 assert(req && req->state == REQUEST_IDLE);
1963 if (req->apdu_request->which != Z_APDU_initRequest && !assoc->init)
1965 *msg = "Missing InitRequest";
1968 switch (req->apdu_request->which)
1970 case Z_APDU_initRequest:
1971 res = process_initRequest(assoc, req); break;
1972 case Z_APDU_searchRequest:
1973 res = process_searchRequest(assoc, req); break;
1974 case Z_APDU_presentRequest:
1975 res = process_presentRequest(assoc, req); break;
1976 case Z_APDU_scanRequest:
1977 if (assoc->init->bend_scan)
1978 res = process_scanRequest(assoc, req);
1981 *msg = "Cannot handle Scan APDU";
1985 case Z_APDU_extendedServicesRequest:
1986 if (assoc->init->bend_esrequest)
1987 res = process_ESRequest(assoc, req);
1990 *msg = "Cannot handle Extended Services APDU";
1994 case Z_APDU_sortRequest:
1995 if (assoc->init->bend_sort)
1996 res = process_sortRequest(assoc, req);
1999 *msg = "Cannot handle Sort APDU";
2004 process_close(assoc, req);
2006 case Z_APDU_deleteResultSetRequest:
2007 if (assoc->init->bend_delete)
2008 res = process_deleteRequest(assoc, req);
2011 *msg = "Cannot handle Delete APDU";
2015 case Z_APDU_segmentRequest:
2016 if (assoc->init->bend_segment)
2018 res = process_segmentRequest(assoc, req);
2022 *msg = "Cannot handle Segment APDU";
2026 case Z_APDU_triggerResourceControlRequest:
2029 *msg = "Bad APDU received";
2034 yaz_log(YLOG_DEBUG, " result immediately available");
2035 retval = process_z_response(assoc, req, res);
2039 yaz_log(YLOG_DEBUG, " result unavailable");
2046 * Encode response, and transfer the request structure to the outgoing queue.
2048 static int process_gdu_response(association *assoc, request *req, Z_GDU *res)
2050 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
2054 if (!z_GDU(assoc->print, &res, 0, 0))
2055 yaz_log(YLOG_WARN, "ODR print error: %s",
2056 odr_errmsg(odr_geterror(assoc->print)));
2057 odr_reset(assoc->print);
2059 if (!z_GDU(assoc->encode, &res, 0, 0))
2061 yaz_log(YLOG_WARN, "ODR error when encoding PDU: %s [element %s]",
2062 odr_errmsg(odr_geterror(assoc->decode)),
2063 odr_getelement(assoc->decode));
2066 req->response = odr_getbuf(assoc->encode, &req->len_response,
2067 &req->size_response);
2068 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
2069 odr_reset(assoc->encode);
2070 req->state = REQUEST_IDLE;
2071 request_enq(&assoc->outgoing, req);
2072 /* turn the work over to the ir_session handler */
2073 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
2074 assoc->cs_put_mask = EVENT_OUTPUT;
2075 /* Is there more work to be done? give that to the input handler too */
2078 req = request_head(&assoc->incoming);
2079 if (req && req->state == REQUEST_IDLE)
2081 request_deq(&assoc->incoming);
2082 process_gdu_request(assoc, req);
2091 * Encode response, and transfer the request structure to the outgoing queue.
2093 static int process_z_response(association *assoc, request *req, Z_APDU *res)
2095 Z_GDU *gres = (Z_GDU *) odr_malloc(assoc->encode, sizeof(*gres));
2096 gres->which = Z_GDU_Z3950;
2097 gres->u.z3950 = res;
2099 return process_gdu_response(assoc, req, gres);
2102 static char *get_vhost(Z_OtherInformation *otherInfo)
2104 return yaz_oi_get_string_oid(&otherInfo, yaz_oid_userinfo_proxy, 1, 0);
2108 * Handle init request.
2109 * At the moment, we don't check the options
2110 * anywhere else in the code - we just try not to do anything that would
2111 * break a naive client. We'll toss 'em into the association block when
2112 * we need them there.
2114 static Z_APDU *process_initRequest(association *assoc, request *reqb)
2116 Z_InitRequest *req = reqb->apdu_request->u.initRequest;
2117 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
2118 Z_InitResponse *resp = apdu->u.initResponse;
2119 bend_initresult *binitres;
2121 statserv_options_block *cb = 0; /* by default no control for backend */
2123 if (control_association(assoc, get_vhost(req->otherInfo), 1))
2124 cb = statserv_getcontrol(); /* got control block for backend */
2126 if (cb && assoc->backend)
2127 (*cb->bend_close)(assoc->backend);
2129 yaz_log(log_requestdetail, "Got initRequest");
2130 if (req->implementationId)
2131 yaz_log(log_requestdetail, "Id: %s",
2132 req->implementationId);
2133 if (req->implementationName)
2134 yaz_log(log_requestdetail, "Name: %s",
2135 req->implementationName);
2136 if (req->implementationVersion)
2137 yaz_log(log_requestdetail, "Version: %s",
2138 req->implementationVersion);
2140 assoc_init_reset(assoc);
2142 assoc->init->auth = req->idAuthentication;
2143 assoc->init->referenceId = req->referenceId;
2145 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
2147 Z_CharSetandLanguageNegotiation *negotiation =
2148 yaz_get_charneg_record (req->otherInfo);
2150 negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
2151 assoc->init->charneg_request = negotiation;
2154 /* by default named_result_sets is 0 .. Enable it if client asks for it. */
2155 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
2156 assoc->init->named_result_sets = 1;
2161 if (req->implementationVersion)
2162 yaz_log(log_requestdetail, "Config: %s",
2165 iochan_settimeout(assoc->client_chan, cb->idle_timeout);
2167 /* we have a backend control block, so call that init function */
2168 if (!(binitres = (*cb->bend_init)(assoc->init)))
2170 yaz_log(YLOG_WARN, "Bad response from backend.");
2173 assoc->backend = binitres->handle;
2177 /* no backend. return error */
2178 binitres = (bend_initresult *)
2179 odr_malloc(assoc->encode, sizeof(*binitres));
2180 binitres->errstring = 0;
2181 binitres->errcode = YAZ_BIB1_PERMANENT_SYSTEM_ERROR;
2182 iochan_settimeout(assoc->client_chan, 10);
2184 if ((assoc->init->bend_sort))
2185 yaz_log(YLOG_DEBUG, "Sort handler installed");
2186 if ((assoc->init->bend_search))
2187 yaz_log(YLOG_DEBUG, "Search handler installed");
2188 if ((assoc->init->bend_present))
2189 yaz_log(YLOG_DEBUG, "Present handler installed");
2190 if ((assoc->init->bend_esrequest))
2191 yaz_log(YLOG_DEBUG, "ESRequest handler installed");
2192 if ((assoc->init->bend_delete))
2193 yaz_log(YLOG_DEBUG, "Delete handler installed");
2194 if ((assoc->init->bend_scan))
2195 yaz_log(YLOG_DEBUG, "Scan handler installed");
2196 if ((assoc->init->bend_segment))
2197 yaz_log(YLOG_DEBUG, "Segment handler installed");
2199 resp->referenceId = req->referenceId;
2201 /* let's tell the client what we can do */
2202 if (ODR_MASK_GET(req->options, Z_Options_search))
2204 ODR_MASK_SET(resp->options, Z_Options_search);
2205 strcat(options, "srch");
2207 if (ODR_MASK_GET(req->options, Z_Options_present))
2209 ODR_MASK_SET(resp->options, Z_Options_present);
2210 strcat(options, " prst");
2212 if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
2213 assoc->init->bend_delete)
2215 ODR_MASK_SET(resp->options, Z_Options_delSet);
2216 strcat(options, " del");
2218 if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
2219 assoc->init->bend_esrequest)
2221 ODR_MASK_SET(resp->options, Z_Options_extendedServices);
2222 strcat(options, " extendedServices");
2224 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets)
2225 && assoc->init->named_result_sets)
2227 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
2228 strcat(options, " namedresults");
2230 if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
2232 ODR_MASK_SET(resp->options, Z_Options_scan);
2233 strcat(options, " scan");
2235 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
2237 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
2238 strcat(options, " concurrop");
2240 if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
2242 ODR_MASK_SET(resp->options, Z_Options_sort);
2243 strcat(options, " sort");
2246 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
2248 Z_OtherInformationUnit *p0;
2250 if (!assoc->init->charneg_response)
2252 if (assoc->init->query_charset)
2254 assoc->init->charneg_response = yaz_set_response_charneg(
2255 assoc->encode, assoc->init->query_charset, 0,
2256 assoc->init->records_in_same_charset);
2260 yaz_log(YLOG_WARN, "default query_charset not defined by backend");
2263 if (assoc->init->charneg_response
2264 && (p0=yaz_oi_update(&resp->otherInfo, assoc->encode, NULL, 0, 0)))
2266 p0->which = Z_OtherInfo_externallyDefinedInfo;
2267 p0->information.externallyDefinedInfo =
2268 assoc->init->charneg_response;
2269 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
2270 strcat(options, " negotiation");
2273 if (ODR_MASK_GET(req->options, Z_Options_triggerResourceCtrl))
2274 ODR_MASK_SET(resp->options, Z_Options_triggerResourceCtrl);
2276 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
2278 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
2279 assoc->version = 1; /* 1 & 2 are equivalent */
2281 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
2283 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
2286 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
2288 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
2292 yaz_log(log_requestdetail, "Negotiated to v%d: %s", assoc->version, options);
2294 if (*req->maximumRecordSize < assoc->maximumRecordSize)
2295 assoc->maximumRecordSize = odr_int_to_int(*req->maximumRecordSize);
2297 if (*req->preferredMessageSize < assoc->preferredMessageSize)
2298 assoc->preferredMessageSize = odr_int_to_int(*req->preferredMessageSize);
2300 resp->preferredMessageSize =
2301 odr_intdup(assoc->encode, assoc->preferredMessageSize);
2302 resp->maximumRecordSize =
2303 odr_intdup(assoc->encode, assoc->maximumRecordSize);
2305 resp->implementationId = odr_prepend(assoc->encode,
2306 assoc->init->implementation_id,
2307 resp->implementationId);
2309 resp->implementationName = odr_prepend(assoc->encode,
2310 assoc->init->implementation_name,
2311 odr_prepend(assoc->encode, "GFS", resp->implementationName));
2313 if (binitres->errcode)
2315 assoc->state = ASSOC_DEAD;
2316 resp->userInformationField =
2317 init_diagnostics(assoc->encode, binitres->errcode,
2318 binitres->errstring);
2322 assoc->state = ASSOC_UP;
2326 if (!req->idAuthentication)
2327 yaz_log(log_request, "Auth none");
2328 else if (req->idAuthentication->which == Z_IdAuthentication_open)
2330 const char *open = req->idAuthentication->u.open;
2331 const char *slash = strchr(open, '/');
2337 yaz_log(log_request, "Auth open %.*s", len, open);
2339 else if (req->idAuthentication->which == Z_IdAuthentication_idPass)
2341 const char *user = req->idAuthentication->u.idPass->userId;
2342 const char *group = req->idAuthentication->u.idPass->groupId;
2343 yaz_log(log_request, "Auth idPass %s %s",
2344 user ? user : "-", group ? group : "-");
2346 else if (req->idAuthentication->which
2347 == Z_IdAuthentication_anonymous)
2349 yaz_log(log_request, "Auth anonymous");
2353 yaz_log(log_request, "Auth other");
2358 WRBUF wr = wrbuf_alloc();
2359 wrbuf_printf(wr, "Init ");
2360 if (binitres->errcode)
2361 wrbuf_printf(wr, "ERROR %d", binitres->errcode);
2363 wrbuf_printf(wr, "OK -");
2364 wrbuf_printf(wr, " ID:%s Name:%s Version:%s",
2365 (req->implementationId ? req->implementationId :"-"),
2366 (req->implementationName ?
2367 req->implementationName : "-"),
2368 (req->implementationVersion ?
2369 req->implementationVersion : "-")
2371 yaz_log(log_request, "%s", wrbuf_cstr(wr));
2378 * Set the specified `errcode' and `errstring' into a UserInfo-1
2379 * external to be returned to the client in accordance with Z35.90
2380 * Implementor Agreement 5 (Returning diagnostics in an InitResponse):
2381 * http://lcweb.loc.gov/z3950/agency/agree/initdiag.html
2383 static Z_External *init_diagnostics(ODR odr, int error, const char *addinfo)
2385 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2386 addinfo ? " -- " : "", addinfo ? addinfo : "");
2387 return zget_init_diagnostics(odr, error, addinfo);
2391 * nonsurrogate diagnostic record.
2393 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
2395 Z_Records *rec = (Z_Records *) odr_malloc(assoc->encode, sizeof(*rec));
2397 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2398 addinfo ? " -- " : "", addinfo ? addinfo : "");
2400 rec->which = Z_Records_NSD;
2401 rec->u.nonSurrogateDiagnostic = zget_DefaultDiagFormat(assoc->encode,
2407 * surrogate diagnostic.
2409 static Z_NamePlusRecord *surrogatediagrec(association *assoc,
2411 int error, const char *addinfo)
2413 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2414 addinfo ? " -- " : "", addinfo ? addinfo : "");
2415 return zget_surrogateDiagRec(assoc->encode, dbname, error, addinfo);
2418 static Z_Records *pack_records(association *a, char *setname, Odr_int start,
2419 Odr_int *num, Z_RecordComposition *comp,
2420 Odr_int *next, Odr_int *pres,
2421 Z_ReferenceId *referenceId,
2422 Odr_oid *oid, int *errcode)
2424 int recno, total_length = 0, dumped_records = 0;
2425 int toget = odr_int_to_int(*num);
2426 Z_Records *records =
2427 (Z_Records *) odr_malloc(a->encode, sizeof(*records));
2428 Z_NamePlusRecordList *reclist =
2429 (Z_NamePlusRecordList *) odr_malloc(a->encode, sizeof(*reclist));
2431 records->which = Z_Records_DBOSD;
2432 records->u.databaseOrSurDiagnostics = reclist;
2433 reclist->num_records = 0;
2436 return diagrec(a, YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE, 0);
2437 else if (toget == 0)
2438 reclist->records = odr_nullval();
2440 reclist->records = (Z_NamePlusRecord **)
2441 odr_malloc(a->encode, sizeof(*reclist->records) * toget);
2443 *pres = Z_PresentStatus_success;
2447 yaz_log(log_requestdetail, "Request to pack " ODR_INT_PRINTF "+%d %s", start, toget, setname);
2448 yaz_log(log_requestdetail, "pms=%d, mrs=%d", a->preferredMessageSize,
2449 a->maximumRecordSize);
2450 for (recno = odr_int_to_int(start); reclist->num_records < toget; recno++)
2453 Z_NamePlusRecord *thisrec;
2454 int this_length = 0;
2456 * we get the number of bytes allocated on the stream before any
2457 * allocation done by the backend - this should give us a reasonable
2458 * idea of the total size of the data so far.
2460 total_length = odr_total(a->encode) - dumped_records;
2466 freq.last_in_set = 0;
2467 freq.setname = setname;
2468 freq.surrogate_flag = 0;
2469 freq.number = recno;
2471 freq.request_format = oid;
2472 freq.output_format = 0;
2473 freq.stream = a->encode;
2474 freq.print = a->print;
2475 freq.referenceId = referenceId;
2478 retrieve_fetch(a, &freq);
2480 *next = freq.last_in_set ? 0 : recno + 1;
2484 if (!freq.surrogate_flag) /* non-surrogate diagnostic i.e. global */
2487 *pres = Z_PresentStatus_failure;
2488 /* for 'present request out of range',
2489 set addinfo to record position if not set */
2490 if (freq.errcode == YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE &&
2491 freq.errstring == 0)
2493 sprintf(s, "%d", recno);
2497 *errcode = freq.errcode;
2498 return diagrec(a, freq.errcode, freq.errstring);
2500 reclist->records[reclist->num_records] =
2501 surrogatediagrec(a, freq.basename, freq.errcode,
2503 reclist->num_records++;
2506 if (freq.record == 0) /* no error and no record ? */
2508 *pres = Z_PresentStatus_partial_4;
2509 *next = 0; /* signal end-of-set and stop */
2513 this_length = freq.len;
2515 this_length = odr_total(a->encode) - total_length - dumped_records;
2516 yaz_log(YLOG_DEBUG, " fetched record, len=%d, total=%d dumped=%d",
2517 this_length, total_length, dumped_records);
2518 if (a->preferredMessageSize > 0 &&
2519 this_length + total_length > a->preferredMessageSize)
2521 /* record is small enough, really */
2522 if (this_length <= a->preferredMessageSize && recno > start)
2524 yaz_log(log_requestdetail, " Dropped last normal-sized record");
2525 *pres = Z_PresentStatus_partial_2;
2530 /* record can only be fetched by itself */
2531 if (this_length < a->maximumRecordSize)
2533 yaz_log(log_requestdetail, " Record > prefmsgsz");
2536 yaz_log(YLOG_DEBUG, " Dropped it");
2537 reclist->records[reclist->num_records] =
2540 YAZ_BIB1_RECORD_EXCEEDS_PREFERRED_MESSAGE_SIZE, 0);
2541 reclist->num_records++;
2542 dumped_records += this_length;
2546 else /* too big entirely */
2548 yaz_log(log_requestdetail, "Record > maxrcdsz "
2550 this_length, a->maximumRecordSize);
2551 reclist->records[reclist->num_records] =
2554 YAZ_BIB1_RECORD_EXCEEDS_MAXIMUM_RECORD_SIZE, 0);
2555 reclist->num_records++;
2556 dumped_records += this_length;
2561 if (!(thisrec = (Z_NamePlusRecord *)
2562 odr_malloc(a->encode, sizeof(*thisrec))))
2564 thisrec->databaseName = odr_strdup_null(a->encode, freq.basename);
2565 thisrec->which = Z_NamePlusRecord_databaseRecord;
2567 if (!freq.output_format)
2569 yaz_log(YLOG_WARN, "bend_fetch output_format not set");
2572 thisrec->u.databaseRecord = z_ext_record_oid(
2573 a->encode, freq.output_format, freq.record, freq.len);
2574 if (!thisrec->u.databaseRecord)
2576 reclist->records[reclist->num_records] = thisrec;
2577 reclist->num_records++;
2579 *num = reclist->num_records;
2583 static Z_APDU *process_searchRequest(association *assoc, request *reqb)
2585 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2586 bend_search_rr *bsrr =
2587 (bend_search_rr *)nmem_malloc(reqb->request_mem, sizeof(*bsrr));
2589 yaz_log(log_requestdetail, "Got SearchRequest.");
2590 bsrr->association = assoc;
2591 bsrr->referenceId = req->referenceId;
2592 bsrr->srw_sortKeys = 0;
2593 bsrr->srw_setname = 0;
2594 bsrr->srw_setnameIdleTime = 0;
2595 bsrr->estimated_hit_count = 0;
2596 bsrr->partial_resultset = 0;
2597 bsrr->extra_args = 0;
2598 bsrr->extra_response_data = 0;
2600 yaz_log (log_requestdetail, "ResultSet '%s'", req->resultSetName);
2601 if (req->databaseNames)
2604 for (i = 0; i < req->num_databaseNames; i++)
2605 yaz_log(log_requestdetail, "Database '%s'", req->databaseNames[i]);
2608 yaz_log_zquery_level(log_requestdetail,req->query);
2610 if (assoc->init->bend_search)
2612 bsrr->setname = req->resultSetName;
2613 bsrr->replace_set = *req->replaceIndicator;
2614 bsrr->num_bases = req->num_databaseNames;
2615 bsrr->basenames = req->databaseNames;
2616 bsrr->query = req->query;
2617 bsrr->stream = assoc->encode;
2618 nmem_transfer(odr_getmem(bsrr->stream), reqb->request_mem);
2619 bsrr->decode = assoc->decode;
2620 bsrr->print = assoc->print;
2623 bsrr->errstring = NULL;
2624 bsrr->search_info = NULL;
2625 bsrr->search_input = req->otherInfo;
2627 if (assoc->server && assoc->server->cql_transform
2628 && req->query->which == Z_Query_type_104
2629 && req->query->u.type_104->which == Z_External_CQL)
2631 /* have a CQL query and a CQL to PQF transform .. */
2633 cql2pqf(bsrr->stream, req->query->u.type_104->u.cql,
2634 assoc->server->cql_transform, bsrr->query);
2636 bsrr->errcode = yaz_diag_srw_to_bib1(srw_errcode);
2639 if (assoc->server && assoc->server->ccl_transform
2640 && req->query->which == Z_Query_type_2) /*CCL*/
2642 /* have a CCL query and a CCL to PQF transform .. */
2644 ccl2pqf(bsrr->stream, req->query->u.type_2,
2645 assoc->server->ccl_transform, bsrr);
2647 bsrr->errcode = yaz_diag_srw_to_bib1(srw_errcode);
2651 (assoc->init->bend_search)(assoc->backend, bsrr);
2655 /* FIXME - make a diagnostic for it */
2656 yaz_log(YLOG_WARN,"Search not supported ?!?!");
2658 return response_searchRequest(assoc, reqb, bsrr);
2662 * Prepare a searchresponse based on the backend results. We probably want
2663 * to look at making the fetching of records nonblocking as well, but
2664 * so far, we'll keep things simple.
2665 * If bsrt is null, that means we're called in response to a communications
2666 * event, and we'll have to get the response for ourselves.
2668 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
2669 bend_search_rr *bsrt)
2671 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2672 Z_APDU *apdu = (Z_APDU *)odr_malloc(assoc->encode, sizeof(*apdu));
2673 Z_SearchResponse *resp = (Z_SearchResponse *)
2674 odr_malloc(assoc->encode, sizeof(*resp));
2675 Odr_int *nulint = odr_intdup(assoc->encode, 0);
2676 Odr_int *next = odr_intdup(assoc->encode, 0);
2677 Odr_int *none = odr_intdup(assoc->encode, Z_SearchResponse_none);
2678 Odr_int returnedrecs = 0;
2680 apdu->which = Z_APDU_searchResponse;
2681 apdu->u.searchResponse = resp;
2682 resp->referenceId = req->referenceId;
2683 resp->additionalSearchInfo = 0;
2684 resp->otherInfo = 0;
2687 yaz_log(YLOG_FATAL, "Bad result from backend");
2690 else if (bsrt->errcode)
2692 resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
2693 resp->resultCount = nulint;
2694 resp->numberOfRecordsReturned = nulint;
2695 resp->nextResultSetPosition = nulint;
2696 resp->searchStatus = odr_booldup(assoc->encode, 0);
2697 resp->resultSetStatus = none;
2698 resp->presentStatus = 0;
2702 bool_t *sr = odr_booldup(assoc->encode, 1);
2703 Odr_int *toget = odr_intdup(assoc->encode, 0);
2704 Z_RecordComposition comp, *compp = 0;
2706 yaz_log(log_requestdetail, "resultCount: " ODR_INT_PRINTF, bsrt->hits);
2709 resp->resultCount = &bsrt->hits;
2711 comp.which = Z_RecordComp_simple;
2712 /* how many records does the user agent want, then? */
2715 else if (bsrt->hits <= *req->smallSetUpperBound)
2717 *toget = bsrt->hits;
2718 if ((comp.u.simple = req->smallSetElementSetNames))
2721 else if (bsrt->hits < *req->largeSetLowerBound)
2723 *toget = *req->mediumSetPresentNumber;
2724 if (*toget > bsrt->hits)
2725 *toget = bsrt->hits;
2726 if ((comp.u.simple = req->mediumSetElementSetNames))
2732 if (*toget && !resp->records)
2734 Odr_int *presst = odr_intdup(assoc->encode, 0);
2735 /* Call bend_present if defined */
2736 if (assoc->init->bend_present)
2738 bend_present_rr *bprr = (bend_present_rr *)
2739 nmem_malloc(reqb->request_mem, sizeof(*bprr));
2740 bprr->setname = req->resultSetName;
2742 bprr->number = odr_int_to_int(*toget);
2743 bprr->format = req->preferredRecordSyntax;
2745 bprr->referenceId = req->referenceId;
2746 bprr->stream = assoc->encode;
2747 bprr->print = assoc->print;
2748 bprr->association = assoc;
2750 bprr->errstring = NULL;
2751 (*assoc->init->bend_present)(assoc->backend, bprr);
2755 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2756 *resp->presentStatus = Z_PresentStatus_failure;
2761 resp->records = pack_records(
2762 assoc, req->resultSetName, 1,
2763 toget, compp, next, presst, req->referenceId,
2764 req->preferredRecordSyntax, NULL);
2767 resp->numberOfRecordsReturned = toget;
2768 returnedrecs = *toget;
2769 resp->presentStatus = presst;
2773 if (*resp->resultCount)
2775 resp->numberOfRecordsReturned = nulint;
2776 resp->presentStatus = 0;
2778 resp->nextResultSetPosition = next;
2779 resp->searchStatus = sr;
2780 resp->resultSetStatus = 0;
2781 if (bsrt->estimated_hit_count)
2783 resp->resultSetStatus = odr_intdup(assoc->encode,
2784 Z_SearchResponse_estimate);
2786 else if (bsrt->partial_resultset)
2788 resp->resultSetStatus = odr_intdup(assoc->encode,
2789 Z_SearchResponse_subset);
2792 resp->additionalSearchInfo = bsrt->search_info;
2797 WRBUF wr = wrbuf_alloc();
2799 for (i = 0 ; i < req->num_databaseNames; i++)
2802 wrbuf_printf(wr, "+");
2803 wrbuf_puts(wr, req->databaseNames[i]);
2805 wrbuf_printf(wr, " ");
2808 wrbuf_printf(wr, "ERROR %d", bsrt->errcode);
2810 wrbuf_printf(wr, "OK " ODR_INT_PRINTF, bsrt->hits);
2811 wrbuf_printf(wr, " %s 1+" ODR_INT_PRINTF " ",
2812 req->resultSetName, returnedrecs);
2813 yaz_query_to_wrbuf(wr, req->query);
2815 yaz_log(log_request, "Search %s", wrbuf_cstr(wr));
2822 * Maybe we got a little over-friendly when we designed bend_fetch to
2823 * get only one record at a time. Some backends can optimise multiple-record
2824 * fetches, and at any rate, there is some overhead involved in
2825 * all that selecting and hopping around. Problem is, of course, that the
2826 * frontend can't know ahead of time how many records it'll need to
2827 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
2828 * is downright lousy as a bulk data transfer protocol.
2830 * To start with, we'll do the fetching of records from the backend
2831 * in one operation: To save some trips in and out of the event-handler,
2832 * and to simplify the interface to pack_records. At any rate, asynch
2833 * operation is more fun in operations that have an unpredictable execution
2834 * speed - which is normally more true for search than for present.
2836 static Z_APDU *process_presentRequest(association *assoc, request *reqb)
2838 Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
2840 Z_PresentResponse *resp;
2844 const char *errstring = 0;
2846 yaz_log(log_requestdetail, "Got PresentRequest.");
2848 resp = (Z_PresentResponse *)odr_malloc(assoc->encode, sizeof(*resp));
2850 resp->presentStatus = odr_intdup(assoc->encode, 0);
2851 if (assoc->init->bend_present)
2853 bend_present_rr *bprr = (bend_present_rr *)
2854 nmem_malloc(reqb->request_mem, sizeof(*bprr));
2855 bprr->setname = req->resultSetId;
2856 bprr->start = odr_int_to_int(*req->resultSetStartPoint);
2857 bprr->number = odr_int_to_int(*req->numberOfRecordsRequested);
2858 bprr->format = req->preferredRecordSyntax;
2859 bprr->comp = req->recordComposition;
2860 bprr->referenceId = req->referenceId;
2861 bprr->stream = assoc->encode;
2862 bprr->print = assoc->print;
2863 bprr->association = assoc;
2865 bprr->errstring = NULL;
2866 (*assoc->init->bend_present)(assoc->backend, bprr);
2870 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2871 *resp->presentStatus = Z_PresentStatus_failure;
2872 errcode = bprr->errcode;
2873 errstring = bprr->errstring;
2876 apdu = (Z_APDU *)odr_malloc(assoc->encode, sizeof(*apdu));
2877 next = odr_intdup(assoc->encode, 0);
2878 num = odr_intdup(assoc->encode, 0);
2880 apdu->which = Z_APDU_presentResponse;
2881 apdu->u.presentResponse = resp;
2882 resp->referenceId = req->referenceId;
2883 resp->otherInfo = 0;
2887 *num = *req->numberOfRecordsRequested;
2889 pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
2890 num, req->recordComposition, next,
2891 resp->presentStatus,
2892 req->referenceId, req->preferredRecordSyntax,
2897 WRBUF wr = wrbuf_alloc();
2898 wrbuf_printf(wr, "Present ");
2900 if (*resp->presentStatus == Z_PresentStatus_failure)
2901 wrbuf_printf(wr, "ERROR %d ", errcode);
2902 else if (*resp->presentStatus == Z_PresentStatus_success)
2903 wrbuf_printf(wr, "OK - ");
2905 wrbuf_printf(wr, "Partial " ODR_INT_PRINTF " - ",
2906 *resp->presentStatus);
2908 wrbuf_printf(wr, " %s " ODR_INT_PRINTF "+" ODR_INT_PRINTF " ",
2909 req->resultSetId, *req->resultSetStartPoint,
2910 *req->numberOfRecordsRequested);
2911 yaz_log(log_request, "%s", wrbuf_cstr(wr) );
2916 resp->numberOfRecordsReturned = num;
2917 resp->nextResultSetPosition = next;
2923 * Scan was implemented rather in a hurry, and with support for only the basic
2924 * elements of the service in the backend API. Suggestions are welcome.
2926 static Z_APDU *process_scanRequest(association *assoc, request *reqb)
2928 Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
2929 Z_APDU *apdu = (Z_APDU *)odr_malloc(assoc->encode, sizeof(*apdu));
2930 Z_ScanResponse *res = (Z_ScanResponse *)
2931 odr_malloc(assoc->encode, sizeof(*res));
2932 Odr_int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
2933 Odr_int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
2934 Z_ListEntries *ents = (Z_ListEntries *)
2935 odr_malloc(assoc->encode, sizeof(*ents));
2936 Z_DiagRecs *diagrecs_p = NULL;
2937 bend_scan_rr *bsrr = (bend_scan_rr *)
2938 odr_malloc(assoc->encode, sizeof(*bsrr));
2939 struct scan_entry *save_entries;
2942 yaz_log(log_requestdetail, "Got ScanRequest");
2944 apdu->which = Z_APDU_scanResponse;
2945 apdu->u.scanResponse = res;
2946 res->referenceId = req->referenceId;
2948 /* if step is absent, set it to 0 */
2950 step_size = odr_int_to_int(*req->stepSize);
2952 res->scanStatus = scanStatus;
2953 res->numberOfEntriesReturned = numberOfEntriesReturned;
2954 res->positionOfTerm = 0;
2955 res->entries = ents;
2956 ents->num_entries = 0;
2957 ents->entries = NULL;
2958 ents->num_nonsurrogateDiagnostics = 0;
2959 ents->nonsurrogateDiagnostics = NULL;
2960 res->attributeSet = 0;
2963 if (req->databaseNames)
2966 for (i = 0; i < req->num_databaseNames; i++)
2967 yaz_log(log_requestdetail, "Database '%s'", req->databaseNames[i]);
2969 bsrr->scanClause = 0;
2971 bsrr->errstring = 0;
2972 bsrr->num_bases = req->num_databaseNames;
2973 bsrr->basenames = req->databaseNames;
2974 bsrr->num_entries = odr_int_to_int(*req->numberOfTermsRequested);
2975 bsrr->term = req->termListAndStartPoint;
2976 bsrr->referenceId = req->referenceId;
2977 bsrr->stream = assoc->encode;
2978 bsrr->print = assoc->print;
2979 bsrr->step_size = &step_size;
2980 bsrr->setname = yaz_oi_get_string_oid(&req->otherInfo,
2981 yaz_oid_userinfo_scan_set, 1, 0);
2983 /* For YAZ 2.0 and earlier it was the backend handler that
2984 initialized entries (member display_term did not exist)
2985 YAZ 2.0 and later sets 'entries' and initialize all members
2986 including 'display_term'. If YAZ 2.0 or later sees that
2987 entries was modified - we assume that it is an old handler and
2988 that 'display_term' is _not_ set.
2990 if (bsrr->num_entries > 0)
2993 bsrr->entries = (struct scan_entry *)
2994 odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
2996 for (i = 0; i<bsrr->num_entries; i++)
2998 bsrr->entries[i].term = 0;
2999 bsrr->entries[i].occurrences = 0;
3000 bsrr->entries[i].errcode = 0;
3001 bsrr->entries[i].errstring = 0;
3002 bsrr->entries[i].display_term = 0;
3005 save_entries = bsrr->entries; /* save it so we can compare later */
3007 bsrr->attributeset = req->attributeSet;
3008 log_scan_term_level(log_requestdetail, req->termListAndStartPoint,
3009 bsrr->attributeset);
3010 bsrr->term_position = req->preferredPositionInResponse ?
3011 odr_int_to_int(*req->preferredPositionInResponse) : 1;
3013 ((int (*)(void *, bend_scan_rr *))
3014 (*assoc->init->bend_scan))(assoc->backend, bsrr);
3017 diagrecs_p = zget_DiagRecs(assoc->encode,
3018 bsrr->errcode, bsrr->errstring);
3022 Z_Entry **tab = (Z_Entry **)
3023 odr_malloc(assoc->encode, sizeof(*tab) * bsrr->num_entries);
3025 if (bsrr->status == BEND_SCAN_PARTIAL)
3026 *scanStatus = Z_Scan_partial_5;
3028 *scanStatus = Z_Scan_success;
3029 res->stepSize = odr_intdup(assoc->encode, step_size);
3030 ents->entries = tab;
3031 ents->num_entries = bsrr->num_entries;
3032 res->numberOfEntriesReturned = odr_intdup(assoc->encode,
3034 res->positionOfTerm = odr_intdup(assoc->encode, bsrr->term_position);
3035 for (i = 0; i < bsrr->num_entries; i++)
3041 tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
3042 if (bsrr->entries[i].occurrences >= 0)
3044 e->which = Z_Entry_termInfo;
3045 e->u.termInfo = t = (Z_TermInfo *)
3046 odr_malloc(assoc->encode, sizeof(*t));
3047 t->suggestedAttributes = 0;
3049 if (save_entries == bsrr->entries &&
3050 bsrr->entries[i].display_term)
3052 /* the entries was _not_ set by the handler. So it's
3053 safe to test for new member display_term. It is
3056 t->displayTerm = odr_strdup(assoc->encode,
3057 bsrr->entries[i].display_term);
3059 t->alternativeTerm = 0;
3060 t->byAttributes = 0;
3061 t->otherTermInfo = 0;
3062 t->globalOccurrences = &bsrr->entries[i].occurrences;
3063 t->term = (Z_Term *)
3064 odr_malloc(assoc->encode, sizeof(*t->term));
3065 t->term->which = Z_Term_general;
3066 t->term->u.general = o =
3067 (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
3068 o->buf = (unsigned char *)
3069 odr_malloc(assoc->encode, o->len = o->size =
3070 strlen(bsrr->entries[i].term));
3071 memcpy(o->buf, bsrr->entries[i].term, o->len);
3072 yaz_log(YLOG_DEBUG, " term #%d: '%s' (" ODR_INT_PRINTF ")", i,
3073 bsrr->entries[i].term, bsrr->entries[i].occurrences);
3077 Z_DiagRecs *drecs = zget_DiagRecs(assoc->encode,
3078 bsrr->entries[i].errcode,
3079 bsrr->entries[i].errstring);
3080 assert(drecs->num_diagRecs == 1);
3081 e->which = Z_Entry_surrogateDiagnostic;
3082 assert(drecs->diagRecs[0]);
3083 e->u.surrogateDiagnostic = drecs->diagRecs[0];
3089 ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
3090 ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
3095 WRBUF wr = wrbuf_alloc();
3096 wrbuf_printf(wr, "Scan ");
3097 for (i = 0 ; i < req->num_databaseNames; i++)
3100 wrbuf_printf(wr, "+");
3101 wrbuf_puts(wr, req->databaseNames[i]);
3104 wrbuf_printf(wr, " ");
3107 wr_diag(wr, bsrr->errcode, bsrr->errstring);
3109 wrbuf_printf(wr, "OK");
3111 wrbuf_printf(wr, " " ODR_INT_PRINTF " - " ODR_INT_PRINTF "+"
3112 ODR_INT_PRINTF "+" ODR_INT_PRINTF,
3113 res->numberOfEntriesReturned ?
3114 *res->numberOfEntriesReturned : 0,
3115 (req->preferredPositionInResponse ?
3116 *req->preferredPositionInResponse : 1),
3117 *req->numberOfTermsRequested,
3118 (res->stepSize ? *res->stepSize : 1));
3121 wrbuf_printf(wr, "+%s", bsrr->setname);
3123 wrbuf_printf(wr, " ");
3124 yaz_scan_to_wrbuf(wr, req->termListAndStartPoint,
3125 bsrr->attributeset);
3126 yaz_log(log_request, "%s", wrbuf_cstr(wr) );
3132 static Z_APDU *process_sortRequest(association *assoc, request *reqb)
3135 Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
3136 Z_SortResponse *res = (Z_SortResponse *)
3137 odr_malloc(assoc->encode, sizeof(*res));
3138 bend_sort_rr *bsrr = (bend_sort_rr *)
3139 odr_malloc(assoc->encode, sizeof(*bsrr));
3141 Z_APDU *apdu = (Z_APDU *)odr_malloc(assoc->encode, sizeof(*apdu));
3143 yaz_log(log_requestdetail, "Got SortRequest.");
3145 bsrr->num_input_setnames = req->num_inputResultSetNames;
3146 for (i=0;i<req->num_inputResultSetNames;i++)
3147 yaz_log(log_requestdetail, "Input resultset: '%s'",
3148 req->inputResultSetNames[i]);
3149 bsrr->input_setnames = req->inputResultSetNames;
3150 bsrr->referenceId = req->referenceId;
3151 bsrr->output_setname = req->sortedResultSetName;
3152 yaz_log(log_requestdetail, "Output resultset: '%s'",
3153 req->sortedResultSetName);
3154 bsrr->sort_sequence = req->sortSequence;
3155 /*FIXME - dump those sequences too */
3156 bsrr->stream = assoc->encode;
3157 bsrr->print = assoc->print;
3159 bsrr->sort_status = Z_SortResponse_failure;
3161 bsrr->errstring = 0;
3163 (*assoc->init->bend_sort)(assoc->backend, bsrr);
3165 res->referenceId = bsrr->referenceId;
3166 res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
3167 res->resultSetStatus = 0;
3170 Z_DiagRecs *dr = zget_DiagRecs(assoc->encode,
3171 bsrr->errcode, bsrr->errstring);
3172 res->diagnostics = dr->diagRecs;
3173 res->num_diagnostics = dr->num_diagRecs;
3177 res->num_diagnostics = 0;
3178 res->diagnostics = 0;
3180 res->resultCount = 0;
3183 apdu->which = Z_APDU_sortResponse;
3184 apdu->u.sortResponse = res;
3187 WRBUF wr = wrbuf_alloc();
3188 wrbuf_printf(wr, "Sort ");
3190 wrbuf_printf(wr, " ERROR %d", bsrr->errcode);
3192 wrbuf_printf(wr, "OK -");
3193 wrbuf_printf(wr, " (");
3194 for (i = 0; i<req->num_inputResultSetNames; i++)
3197 wrbuf_printf(wr, "+");
3198 wrbuf_puts(wr, req->inputResultSetNames[i]);
3200 wrbuf_printf(wr, ")->%s ",req->sortedResultSetName);
3202 yaz_log(log_request, "%s", wrbuf_cstr(wr) );
3208 static Z_APDU *process_deleteRequest(association *assoc, request *reqb)
3211 Z_DeleteResultSetRequest *req =
3212 reqb->apdu_request->u.deleteResultSetRequest;
3213 Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
3214 odr_malloc(assoc->encode, sizeof(*res));
3215 bend_delete_rr *bdrr = (bend_delete_rr *)
3216 odr_malloc(assoc->encode, sizeof(*bdrr));
3217 Z_APDU *apdu = (Z_APDU *)odr_malloc(assoc->encode, sizeof(*apdu));
3219 yaz_log(log_requestdetail, "Got DeleteRequest.");
3221 bdrr->num_setnames = req->num_resultSetList;
3222 bdrr->setnames = req->resultSetList;
3223 for (i = 0; i<req->num_resultSetList; i++)
3224 yaz_log(log_requestdetail, "resultset: '%s'",
3225 req->resultSetList[i]);
3226 bdrr->stream = assoc->encode;
3227 bdrr->print = assoc->print;
3228 bdrr->function = odr_int_to_int(*req->deleteFunction);
3229 bdrr->referenceId = req->referenceId;
3231 if (bdrr->num_setnames > 0)
3233 bdrr->statuses = (int*)
3234 odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
3235 bdrr->num_setnames);
3236 for (i = 0; i < bdrr->num_setnames; i++)
3237 bdrr->statuses[i] = 0;
3239 (*assoc->init->bend_delete)(assoc->backend, bdrr);
3241 res->referenceId = req->referenceId;
3243 res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
3245 res->deleteListStatuses = 0;
3246 if (bdrr->num_setnames > 0)
3249 res->deleteListStatuses = (Z_ListStatuses *)
3250 odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
3251 res->deleteListStatuses->num = bdrr->num_setnames;
3252 res->deleteListStatuses->elements =
3254 odr_malloc(assoc->encode,
3255 sizeof(*res->deleteListStatuses->elements) *
3256 bdrr->num_setnames);
3257 for (i = 0; i<bdrr->num_setnames; i++)
3259 res->deleteListStatuses->elements[i] =
3261 odr_malloc(assoc->encode,
3262 sizeof(**res->deleteListStatuses->elements));
3263 res->deleteListStatuses->elements[i]->status =
3264 odr_intdup(assoc->encode, bdrr->statuses[i]);
3265 res->deleteListStatuses->elements[i]->id =
3266 odr_strdup(assoc->encode, bdrr->setnames[i]);
3269 res->numberNotDeleted = 0;
3270 res->bulkStatuses = 0;
3271 res->deleteMessage = 0;
3274 apdu->which = Z_APDU_deleteResultSetResponse;
3275 apdu->u.deleteResultSetResponse = res;
3278 WRBUF wr = wrbuf_alloc();
3279 wrbuf_printf(wr, "Delete ");
3280 if (bdrr->delete_status)
3281 wrbuf_printf(wr, "ERROR %d", bdrr->delete_status);
3283 wrbuf_printf(wr, "OK -");
3284 for (i = 0; i<req->num_resultSetList; i++)
3285 wrbuf_printf(wr, " %s ", req->resultSetList[i]);
3286 yaz_log(log_request, "%s", wrbuf_cstr(wr) );
3292 static void process_close(association *assoc, request *reqb)
3294 Z_Close *req = reqb->apdu_request->u.close;
3295 static char *reasons[] =
3302 "securityViolation",
3309 yaz_log(log_requestdetail, "Got Close, reason %s, message %s",
3310 reasons[*req->closeReason], req->diagnosticInformation ?
3311 req->diagnosticInformation : "NULL");
3312 if (assoc->version < 3) /* to make do_force respond with close */
3314 do_close_req(assoc, Z_Close_finished,
3315 "Association terminated by client", reqb);
3316 yaz_log(log_request,"Close OK");
3319 static Z_APDU *process_segmentRequest(association *assoc, request *reqb)
3321 bend_segment_rr req;
3323 req.segment = reqb->apdu_request->u.segmentRequest;
3324 req.stream = assoc->encode;
3325 req.decode = assoc->decode;
3326 req.print = assoc->print;
3327 req.association = assoc;
3329 (*assoc->init->bend_segment)(assoc->backend, &req);
3334 static Z_APDU *process_ESRequest(association *assoc, request *reqb)
3336 bend_esrequest_rr esrequest;
3337 const char *ext_name = "unknown";
3339 Z_ExtendedServicesRequest *req =
3340 reqb->apdu_request->u.extendedServicesRequest;
3341 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
3343 Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
3345 esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
3346 esrequest.stream = assoc->encode;
3347 esrequest.decode = assoc->decode;
3348 esrequest.print = assoc->print;
3349 esrequest.errcode = 0;
3350 esrequest.errstring = NULL;
3351 esrequest.association = assoc;
3352 esrequest.taskPackage = 0;
3353 esrequest.referenceId = req->referenceId;
3355 if (esrequest.esr && esrequest.esr->taskSpecificParameters)
3357 switch(esrequest.esr->taskSpecificParameters->which)
3359 case Z_External_itemOrder:
3360 ext_name = "ItemOrder"; break;
3361 case Z_External_update:
3362 ext_name = "Update"; break;
3363 case Z_External_update0:
3364 ext_name = "Update0"; break;
3365 case Z_External_ESAdmin:
3366 ext_name = "Admin"; break;
3371 (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
3373 resp->referenceId = req->referenceId;
3375 if (esrequest.errcode == -1)
3377 /* Backend service indicates request will be processed */
3378 yaz_log(log_request, "Extended Service: %s (accepted)", ext_name);
3379 *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
3381 else if (esrequest.errcode == 0)
3383 /* Backend service indicates request will be processed */
3384 yaz_log(log_request, "Extended Service: %s (done)", ext_name);
3385 *resp->operationStatus = Z_ExtendedServicesResponse_done;
3389 Z_DiagRecs *diagRecs =
3390 zget_DiagRecs(assoc->encode, esrequest.errcode,
3391 esrequest.errstring);
3392 /* Backend indicates error, request will not be processed */
3393 yaz_log(log_request, "Extended Service: %s (failed)", ext_name);
3394 *resp->operationStatus = Z_ExtendedServicesResponse_failure;
3395 resp->num_diagnostics = diagRecs->num_diagRecs;
3396 resp->diagnostics = diagRecs->diagRecs;
3399 WRBUF wr = wrbuf_alloc();
3400 wrbuf_diags(wr, resp->num_diagnostics, resp->diagnostics);
3401 yaz_log(log_request, "EsRequest %s", wrbuf_cstr(wr) );
3406 /* Do something with the members of bend_extendedservice */
3407 if (esrequest.taskPackage)
3409 resp->taskPackage = z_ext_record_oid(
3410 assoc->encode, yaz_oid_recsyn_extended,
3411 (const char *) esrequest.taskPackage, -1);
3413 yaz_log(YLOG_DEBUG,"Send the result apdu");
3417 int bend_assoc_is_alive(bend_association assoc)
3419 if (assoc->state == ASSOC_DEAD)
3420 return 0; /* already marked as dead. Don't check I/O chan anymore */
3422 return iochan_is_alive(assoc->client_chan);
3429 * c-file-style: "Stroustrup"
3430 * indent-tabs-mode: nil
3432 * vim: shiftwidth=4 tabstop=8 expandtab