1 /* This file is part of the YAZ toolkit.
2 * Copyright (C) 1995-2010 Index Data
3 * See the file LICENSE for details.
7 * \brief Implements GFS session logic.
9 * Frontend server logic.
11 * This code receives incoming APDUs, and handles client requests by means
14 * Some of the code is getting quite involved, compared to simpler servers -
15 * primarily because it is asynchronous both in the communication with
16 * the user and the backend. We think the complexity will pay off in
17 * the form of greater flexibility when more asynchronous facilities
20 * Memory management has become somewhat involved. In the simple case, where
21 * only one PDU is pending at a time, it will simply reuse the same memory,
22 * once it has found its working size. When we enable multiple concurrent
23 * operations, perhaps even with multiple parallel calls to the backend, it
24 * will maintain a pool of buffers for encoding and decoding, trying to
25 * minimize memory allocation/deallocation during normal operation.
35 #include <sys/types.h>
43 #define S_ISREG(x) (x & _S_IFREG)
52 #include <libxml/parser.h>
53 #include <libxml/tree.h>
56 #include <yaz/yconfig.h>
57 #include <yaz/xmalloc.h>
58 #include <yaz/comstack.h>
62 #include <yaz/proto.h>
63 #include <yaz/oid_db.h>
65 #include <yaz/logrpn.h>
66 #include <yaz/querytowrbuf.h>
67 #include <yaz/statserv.h>
68 #include <yaz/diagbib1.h>
69 #include <yaz/charneg.h>
70 #include <yaz/otherinfo.h>
71 #include <yaz/yaz-util.h>
72 #include <yaz/pquery.h>
73 #include <yaz/oid_db.h>
76 #include <yaz/backend.h>
77 #include <yaz/yaz-ccl.h>
79 static void process_gdu_request(association *assoc, request *req);
80 static int process_z_request(association *assoc, request *req, char **msg);
81 static int process_gdu_response(association *assoc, request *req, Z_GDU *res);
82 static int process_z_response(association *assoc, request *req, Z_APDU *res);
83 static Z_APDU *process_initRequest(association *assoc, request *reqb);
84 static Z_External *init_diagnostics(ODR odr, int errcode,
85 const char *errstring);
86 static Z_APDU *process_searchRequest(association *assoc, request *reqb);
87 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
88 bend_search_rr *bsrr);
89 static Z_APDU *process_presentRequest(association *assoc, request *reqb);
90 static Z_APDU *process_scanRequest(association *assoc, request *reqb);
91 static Z_APDU *process_sortRequest(association *assoc, request *reqb);
92 static void process_close(association *assoc, request *reqb);
93 static Z_APDU *process_deleteRequest(association *assoc, request *reqb);
94 static Z_APDU *process_segmentRequest(association *assoc, request *reqb);
95 static Z_APDU *process_ESRequest(association *assoc, request *reqb);
97 /* dynamic logging levels */
98 static int logbits_set = 0;
99 static int log_session = 0; /* one-line logs for session */
100 static int log_sessiondetail = 0; /* more detailed stuff */
101 static int log_request = 0; /* one-line logs for requests */
102 static int log_requestdetail = 0; /* more detailed stuff */
104 /** get_logbits sets global loglevel bits */
105 static void get_logbits(void)
106 { /* needs to be called after parsing cmd-line args that can set loglevels!*/
110 log_session = yaz_log_module_level("session");
111 log_sessiondetail = yaz_log_module_level("sessiondetail");
112 log_request = yaz_log_module_level("request");
113 log_requestdetail = yaz_log_module_level("requestdetail");
117 static void wr_diag(WRBUF w, int error, const char *addinfo)
119 wrbuf_printf(w, "ERROR %d+", error);
120 wrbuf_puts_replace_char(w, diagbib1_str(error), ' ', '_');
124 wrbuf_puts_replace_char(w, addinfo, ' ', '_');
130 * Create and initialize a new association-handle.
131 * channel : iochannel for the current line.
132 * link : communications channel.
133 * Returns: 0 or a new association handle.
135 association *create_association(IOCHAN channel, COMSTACK link,
136 const char *apdufile)
142 if (!(anew = (association *)xmalloc(sizeof(*anew))))
146 anew->last_control = 0;
147 anew->client_chan = channel;
148 anew->client_link = link;
149 anew->cs_get_mask = 0;
150 anew->cs_put_mask = 0;
151 anew->cs_accept_mask = 0;
152 if (!(anew->decode = odr_createmem(ODR_DECODE)) ||
153 !(anew->encode = odr_createmem(ODR_ENCODE)))
155 if (apdufile && *apdufile)
159 if (!(anew->print = odr_createmem(ODR_PRINT)))
161 if (*apdufile == '@')
163 odr_setprint(anew->print, yaz_log_file());
165 else if (*apdufile != '-')
168 sprintf(filename, "%.200s.%ld", apdufile, (long)getpid());
169 if (!(f = fopen(filename, "w")))
171 yaz_log(YLOG_WARN|YLOG_ERRNO, "%s", filename);
174 setvbuf(f, 0, _IONBF, 0);
175 odr_setprint(anew->print, f);
180 anew->input_buffer = 0;
181 anew->input_buffer_len = 0;
183 anew->state = ASSOC_NEW;
184 request_initq(&anew->incoming);
185 request_initq(&anew->outgoing);
186 anew->proto = cs_getproto(link);
192 * Free association and release resources.
194 void destroy_association(association *h)
196 statserv_options_block *cb = statserv_getcontrol();
200 odr_destroy(h->decode);
201 odr_destroy(h->encode);
203 odr_destroy(h->print);
205 xfree(h->input_buffer);
207 (*cb->bend_close)(h->backend);
208 while ((req = request_deq(&h->incoming)))
209 request_release(req);
210 while ((req = request_deq(&h->outgoing)))
211 request_release(req);
212 request_delq(&h->incoming);
213 request_delq(&h->outgoing);
215 xmalloc_trav("session closed");
216 if (cb && cb->one_shot)
222 static void do_close_req(association *a, int reason, char *message,
226 Z_Close *cls = zget_Close(a->encode);
228 /* Purge request queue */
229 while (request_deq(&a->incoming));
230 while (request_deq(&a->outgoing));
233 yaz_log(log_requestdetail, "Sending Close PDU, reason=%d, message=%s",
234 reason, message ? message : "none");
235 apdu.which = Z_APDU_close;
237 *cls->closeReason = reason;
238 cls->diagnosticInformation = message;
239 process_z_response(a, req, &apdu);
240 iochan_settimeout(a->client_chan, 20);
244 request_release(req);
245 yaz_log(log_requestdetail, "v2 client. No Close PDU");
246 iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
249 a->state = ASSOC_DEAD;
252 static void do_close(association *a, int reason, char *message)
254 request *req = request_get(&a->outgoing);
255 do_close_req(a, reason, message, req);
259 int ir_read(IOCHAN h, int event)
261 association *assoc = (association *)iochan_getdata(h);
262 COMSTACK conn = assoc->client_link;
265 if ((assoc->cs_put_mask & EVENT_INPUT) == 0 && (event & assoc->cs_get_mask))
267 yaz_log(YLOG_DEBUG, "ir_session (input)");
268 /* We aren't speaking to this fellow */
269 if (assoc->state == ASSOC_DEAD)
271 yaz_log(log_sessiondetail, "Connection closed - end of session");
273 destroy_association(assoc);
277 assoc->cs_get_mask = EVENT_INPUT;
281 int res = cs_get(conn, &assoc->input_buffer,
282 &assoc->input_buffer_len);
283 if (res < 0 && cs_errno(conn) == CSBUFSIZE)
285 yaz_log(log_session, "Connection error: %s res=%d",
286 cs_errmsg(cs_errno(conn)), res);
287 req = request_get(&assoc->incoming); /* get a new request */
288 do_close_req(assoc, Z_Close_protocolError,
289 "Incoming package too large", req);
294 yaz_log(log_session, "Connection closed by client");
295 assoc->state = ASSOC_DEAD;
298 else if (res == 1) /* incomplete read - wait for more */
300 if (conn->io_pending & CS_WANT_WRITE)
301 assoc->cs_get_mask |= EVENT_OUTPUT;
302 iochan_setflag(h, assoc->cs_get_mask);
305 /* we got a complete PDU. Let's decode it */
306 yaz_log(YLOG_DEBUG, "Got PDU, %d bytes: lead=%02X %02X %02X", res,
307 assoc->input_buffer[0] & 0xff,
308 assoc->input_buffer[1] & 0xff,
309 assoc->input_buffer[2] & 0xff);
310 req = request_get(&assoc->incoming); /* get a new request */
311 odr_reset(assoc->decode);
312 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
313 if (!z_GDU(assoc->decode, &req->gdu_request, 0, 0))
315 yaz_log(YLOG_WARN, "ODR error on incoming PDU: %s [element %s] "
317 odr_errmsg(odr_geterror(assoc->decode)),
318 odr_getelement(assoc->decode),
319 (long) odr_offset(assoc->decode));
320 if (assoc->decode->error != OHTTP)
322 yaz_log(YLOG_WARN, "PDU dump:");
323 odr_dumpBER(yaz_log_file(), assoc->input_buffer, res);
324 request_release(req);
325 do_close(assoc, Z_Close_protocolError, "Malformed package");
329 Z_GDU *p = z_get_HTTP_Response(assoc->encode, 400);
330 assoc->state = ASSOC_DEAD;
331 process_gdu_response(assoc, req, p);
335 req->request_mem = odr_extract_mem(assoc->decode);
338 if (!z_GDU(assoc->print, &req->gdu_request, 0, 0))
339 yaz_log(YLOG_WARN, "ODR print error: %s",
340 odr_errmsg(odr_geterror(assoc->print)));
341 odr_reset(assoc->print);
343 request_enq(&assoc->incoming, req);
345 while (cs_more(conn));
351 * This is where PDUs from the client are read and the further
352 * processing is initiated. Flow of control moves down through the
353 * various process_* functions below, until the encoded result comes back up
354 * to the output handler in here.
356 * h : the I/O channel that has an outstanding event.
357 * event : the current outstanding event.
359 void ir_session(IOCHAN h, int event)
362 association *assoc = (association *)iochan_getdata(h);
363 COMSTACK conn = assoc->client_link;
366 assert(h && conn && assoc);
367 if (event == EVENT_TIMEOUT)
369 if (assoc->state != ASSOC_UP)
371 yaz_log(log_session, "Timeout. Closing connection");
372 /* do we need to lod this at all */
374 destroy_association(assoc);
379 yaz_log(log_sessiondetail, "Timeout. Sending Z39.50 Close");
380 do_close(assoc, Z_Close_lackOfActivity, 0);
384 if (event & assoc->cs_accept_mask)
386 if (!cs_accept(conn))
388 yaz_log(YLOG_WARN, "accept failed");
389 destroy_association(assoc);
393 iochan_clearflag(h, EVENT_OUTPUT);
394 if (conn->io_pending)
395 { /* cs_accept didn't complete */
396 assoc->cs_accept_mask =
397 ((conn->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
398 ((conn->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
400 iochan_setflag(h, assoc->cs_accept_mask);
403 { /* cs_accept completed. Prepare for reading (cs_get) */
404 assoc->cs_accept_mask = 0;
405 assoc->cs_get_mask = EVENT_INPUT;
406 iochan_setflag(h, assoc->cs_get_mask);
410 if (event & assoc->cs_get_mask) /* input */
412 if (!ir_read(h, event))
414 req = request_head(&assoc->incoming);
415 if (req->state == REQUEST_IDLE)
417 request_deq(&assoc->incoming);
418 process_gdu_request(assoc, req);
421 if (event & assoc->cs_put_mask)
423 request *req = request_head(&assoc->outgoing);
425 assoc->cs_put_mask = 0;
426 yaz_log(YLOG_DEBUG, "ir_session (output)");
427 req->state = REQUEST_PENDING;
428 switch (res = cs_put(conn, req->response, req->len_response))
431 yaz_log(log_sessiondetail, "Connection closed by client");
433 destroy_association(assoc);
436 case 0: /* all sent - release the request structure */
437 yaz_log(YLOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
439 yaz_log(YLOG_DEBUG, "HTTP out:\n%.*s", req->len_response,
442 nmem_destroy(req->request_mem);
443 request_deq(&assoc->outgoing);
444 request_release(req);
445 if (!request_head(&assoc->outgoing))
446 { /* restore mask for cs_get operation ... */
447 iochan_clearflag(h, EVENT_OUTPUT|EVENT_INPUT);
448 iochan_setflag(h, assoc->cs_get_mask);
449 if (assoc->state == ASSOC_DEAD)
450 iochan_setevent(assoc->client_chan, EVENT_TIMEOUT);
454 assoc->cs_put_mask = EVENT_OUTPUT;
458 if (conn->io_pending & CS_WANT_WRITE)
459 assoc->cs_put_mask |= EVENT_OUTPUT;
460 if (conn->io_pending & CS_WANT_READ)
461 assoc->cs_put_mask |= EVENT_INPUT;
462 iochan_setflag(h, assoc->cs_put_mask);
465 if (event & EVENT_EXCEPT)
467 yaz_log(YLOG_WARN, "ir_session (exception)");
469 destroy_association(assoc);
474 static int process_z_request(association *assoc, request *req, char **msg);
477 static void assoc_init_reset(association *assoc)
480 assoc->init = (bend_initrequest *) xmalloc(sizeof(*assoc->init));
482 assoc->init->stream = assoc->encode;
483 assoc->init->print = assoc->print;
484 assoc->init->auth = 0;
485 assoc->init->referenceId = 0;
486 assoc->init->implementation_version = 0;
487 assoc->init->implementation_id = 0;
488 assoc->init->implementation_name = 0;
489 assoc->init->query_charset = 0;
490 assoc->init->records_in_same_charset = 0;
491 assoc->init->bend_sort = NULL;
492 assoc->init->bend_search = NULL;
493 assoc->init->bend_present = NULL;
494 assoc->init->bend_esrequest = NULL;
495 assoc->init->bend_delete = NULL;
496 assoc->init->bend_scan = NULL;
497 assoc->init->bend_segment = NULL;
498 assoc->init->bend_fetch = NULL;
499 assoc->init->bend_explain = NULL;
500 assoc->init->bend_srw_scan = NULL;
501 assoc->init->bend_srw_update = NULL;
502 assoc->init->named_result_sets = 0;
504 assoc->init->charneg_request = NULL;
505 assoc->init->charneg_response = NULL;
507 assoc->init->decode = assoc->decode;
508 assoc->init->peer_name =
509 odr_strdup(assoc->encode, cs_addrstr(assoc->client_link));
511 yaz_log(log_requestdetail, "peer %s", assoc->init->peer_name);
514 static int srw_bend_init(association *assoc, Z_SRW_diagnostic **d, int *num, Z_SRW_PDU *sr)
516 statserv_options_block *cb = statserv_getcontrol();
519 const char *encoding = "UTF-8";
521 bend_initresult *binitres;
523 yaz_log(log_requestdetail, "srw_bend_init config=%s", cb->configname);
524 assoc_init_reset(assoc);
528 Z_IdAuthentication *auth = (Z_IdAuthentication *)
529 odr_malloc(assoc->decode, sizeof(*auth));
532 len = strlen(sr->username) + 1;
534 len += strlen(sr->password) + 2;
535 auth->which = Z_IdAuthentication_open;
536 auth->u.open = (char *) odr_malloc(assoc->decode, len);
537 strcpy(auth->u.open, sr->username);
538 if (sr->password && *sr->password)
540 strcat(auth->u.open, "/");
541 strcat(auth->u.open, sr->password);
543 assoc->init->auth = auth;
547 ce = yaz_set_proposal_charneg(assoc->decode, &encoding, 1, 0, 0, 1);
548 assoc->init->charneg_request = ce->u.charNeg3;
551 if (!(binitres = (*cb->bend_init)(assoc->init)))
553 assoc->state = ASSOC_DEAD;
554 yaz_add_srw_diagnostic(assoc->encode, d, num,
555 YAZ_SRW_AUTHENTICATION_ERROR, 0);
558 assoc->backend = binitres->handle;
559 assoc->init->auth = 0;
560 if (binitres->errcode)
562 int srw_code = yaz_diag_bib1_to_srw(binitres->errcode);
563 assoc->state = ASSOC_DEAD;
564 yaz_add_srw_diagnostic(assoc->encode, d, num, srw_code,
565 binitres->errstring);
573 static int retrieve_fetch(association *assoc, bend_fetch_rr *rr)
576 yaz_record_conv_t rc = 0;
577 const char *match_schema = 0;
578 Odr_oid *match_syntax = 0;
583 const char *input_schema = yaz_get_esn(rr->comp);
584 Odr_oid *input_syntax_raw = rr->request_format;
586 const char *backend_schema = 0;
587 Odr_oid *backend_syntax = 0;
589 r = yaz_retrieval_request(assoc->server->retrieval,
597 if (r == -1) /* error ? */
599 const char *details = yaz_retrieval_get_error(
600 assoc->server->retrieval);
602 rr->errcode = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
604 rr->errstring = odr_strdup(rr->stream, details);
607 else if (r == 1 || r == 3)
609 const char *details = input_schema;
611 YAZ_BIB1_SPECIFIED_ELEMENT_SET_NAME_NOT_VALID_FOR_SPECIFIED_;
613 rr->errstring = odr_strdup(rr->stream, details);
618 rr->errcode = YAZ_BIB1_RECORD_SYNTAX_UNSUPP;
619 if (input_syntax_raw)
621 char oidbuf[OID_STR_MAX];
622 oid_oid_to_dotstring(input_syntax_raw, oidbuf);
623 rr->errstring = odr_strdup(rr->stream, oidbuf);
629 yaz_set_esn(&rr->comp, backend_schema, odr_getmem(rr->stream));
632 rr->request_format = backend_syntax;
634 (*assoc->init->bend_fetch)(assoc->backend, rr);
635 if (rc && rr->record && rr->errcode == 0 && rr->len > 0)
636 { /* post conversion must take place .. */
637 WRBUF output_record = wrbuf_alloc();
638 int r = yaz_record_conv_record(rc, rr->record, rr->len, output_record);
641 const char *details = yaz_record_conv_get_error(rc);
642 rr->errcode = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
644 rr->errstring = odr_strdup(rr->stream, details);
648 rr->len = wrbuf_len(output_record);
649 rr->record = (char *) odr_malloc(rr->stream, rr->len);
650 memcpy(rr->record, wrbuf_buf(output_record), rr->len);
652 wrbuf_destroy(output_record);
655 rr->output_format = match_syntax;
657 rr->schema = odr_strdup(rr->stream, match_schema);
659 (*assoc->init->bend_fetch)(assoc->backend, rr);
664 static int srw_bend_fetch(association *assoc, int pos,
665 Z_SRW_searchRetrieveRequest *srw_req,
666 Z_SRW_record *record,
667 const char **addinfo)
670 ODR o = assoc->encode;
672 rr.setname = "default";
675 rr.request_format = odr_oiddup(assoc->decode, yaz_oid_recsyn_xml);
677 rr.comp = (Z_RecordComposition *)
678 odr_malloc(assoc->decode, sizeof(*rr.comp));
679 rr.comp->which = Z_RecordComp_complex;
680 rr.comp->u.complex = (Z_CompSpec *)
681 odr_malloc(assoc->decode, sizeof(Z_CompSpec));
682 rr.comp->u.complex->selectAlternativeSyntax = (bool_t *)
683 odr_malloc(assoc->encode, sizeof(bool_t));
684 *rr.comp->u.complex->selectAlternativeSyntax = 0;
685 rr.comp->u.complex->num_dbSpecific = 0;
686 rr.comp->u.complex->dbSpecific = 0;
687 rr.comp->u.complex->num_recordSyntax = 0;
688 rr.comp->u.complex->recordSyntax = 0;
690 rr.comp->u.complex->generic = (Z_Specification *)
691 odr_malloc(assoc->decode, sizeof(Z_Specification));
693 /* schema uri = recordSchema (or NULL if recordSchema is not given) */
694 rr.comp->u.complex->generic->which = Z_Schema_uri;
695 rr.comp->u.complex->generic->schema.uri = srw_req->recordSchema;
697 /* ESN = recordSchema if recordSchema is present */
698 rr.comp->u.complex->generic->elementSpec = 0;
699 if (srw_req->recordSchema)
701 rr.comp->u.complex->generic->elementSpec =
702 (Z_ElementSpec *) odr_malloc(assoc->encode, sizeof(Z_ElementSpec));
703 rr.comp->u.complex->generic->elementSpec->which =
704 Z_ElementSpec_elementSetName;
705 rr.comp->u.complex->generic->elementSpec->u.elementSetName =
706 srw_req->recordSchema;
709 rr.stream = assoc->encode;
710 rr.print = assoc->print;
718 rr.surrogate_flag = 0;
719 rr.schema = srw_req->recordSchema;
721 if (!assoc->init->bend_fetch)
724 retrieve_fetch(assoc, &rr);
726 if (rr.errcode && rr.surrogate_flag)
728 int code = yaz_diag_bib1_to_srw(rr.errcode);
729 yaz_mk_sru_surrogate(o, record, pos, code, rr.errstring);
732 else if (rr.len >= 0)
734 record->recordData_buf = rr.record;
735 record->recordData_len = rr.len;
736 record->recordPosition = odr_intdup(o, pos);
737 record->recordSchema = odr_strdup_null(
738 o, rr.schema ? rr.schema : srw_req->recordSchema);
742 *addinfo = rr.errstring;
748 static int cql2pqf(ODR odr, const char *cql, cql_transform_t ct,
749 Z_Query *query_result)
751 /* have a CQL query and CQL to PQF transform .. */
752 CQL_parser cp = cql_parser_create();
758 r = cql_parser_string(cp, cql);
761 srw_errcode = YAZ_SRW_QUERY_SYNTAX_ERROR;
766 r = cql_transform_buf(ct,
767 cql_parser_result(cp),
768 rpn_buf, sizeof(rpn_buf)-1);
770 srw_errcode = cql_transform_error(ct, &add);
774 /* Syntax & transform OK. */
775 /* Convert PQF string to Z39.50 to RPN query struct */
776 YAZ_PQF_Parser pp = yaz_pqf_create();
777 Z_RPNQuery *rpnquery = yaz_pqf_parse(pp, odr, rpn_buf);
782 int code = yaz_pqf_error(pp, &pqf_msg, &off);
783 yaz_log(YLOG_WARN, "PQF Parser Error %s (code %d)",
785 srw_errcode = YAZ_SRW_QUERY_SYNTAX_ERROR;
789 query_result->which = Z_Query_type_1;
790 query_result->u.type_1 = rpnquery;
794 cql_parser_destroy(cp);
798 static int cql2pqf_scan(ODR odr, const char *cql, cql_transform_t ct,
799 Z_AttributesPlusTerm *result)
803 int srw_error = cql2pqf(odr, cql, ct, &query);
806 if (query.which != Z_Query_type_1 && query.which != Z_Query_type_101)
807 return YAZ_SRW_QUERY_SYNTAX_ERROR; /* bad query type */
808 rpn = query.u.type_1;
809 if (!rpn->RPNStructure)
810 return YAZ_SRW_QUERY_SYNTAX_ERROR; /* must be structure */
811 if (rpn->RPNStructure->which != Z_RPNStructure_simple)
812 return YAZ_SRW_QUERY_SYNTAX_ERROR; /* must be simple */
813 if (rpn->RPNStructure->u.simple->which != Z_Operand_APT)
814 return YAZ_SRW_QUERY_SYNTAX_ERROR; /* must be be attributes + term */
815 memcpy(result, rpn->RPNStructure->u.simple->u.attributesPlusTerm,
821 static int ccl2pqf(ODR odr, const Odr_oct *ccl, CCL_bibset bibset,
822 bend_search_rr *bsrr)
825 struct ccl_rpn_node *node;
828 ccl0 = odr_strdupn(odr, (char*) ccl->buf, ccl->len);
829 if ((node = ccl_find_str(bibset, ccl0, &errcode, &pos)) == 0)
831 bsrr->errstring = (char*) ccl_err_msg(errcode);
832 return YAZ_SRW_QUERY_SYNTAX_ERROR; /* Query syntax error */
835 bsrr->query->which = Z_Query_type_1;
836 bsrr->query->u.type_1 = ccl_rpn_query(odr, node);
841 static void srw_bend_search(association *assoc, request *req,
846 Z_SRW_searchRetrieveResponse *srw_res = res->u.response;
849 Z_SRW_searchRetrieveRequest *srw_req = sr->u.request;
852 yaz_log(log_requestdetail, "Got SRW SearchRetrieveRequest");
853 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
854 if (srw_res->num_diagnostics == 0 && assoc->init)
857 rr.setname = "default";
860 rr.basenames = &srw_req->database;
864 rr.srw_setnameIdleTime = 0;
865 rr.estimated_hit_count = 0;
866 rr.partial_resultset = 0;
867 rr.query = (Z_Query *) odr_malloc(assoc->decode, sizeof(*rr.query));
868 rr.query->u.type_1 = 0;
869 rr.extra_args = sr->extra_args;
870 rr.extra_response_data = 0;
872 if (srw_req->query_type == Z_SRW_query_type_cql)
874 if (assoc->server && assoc->server->cql_transform)
876 int srw_errcode = cql2pqf(assoc->encode, srw_req->query.cql,
877 assoc->server->cql_transform,
881 yaz_add_srw_diagnostic(assoc->encode,
882 &srw_res->diagnostics,
883 &srw_res->num_diagnostics,
889 /* CQL query to backend. Wrap it - Z39.50 style */
890 ext = (Z_External *) odr_malloc(assoc->decode, sizeof(*ext));
891 ext->direct_reference = odr_getoidbystr(assoc->decode,
892 "1.2.840.10003.16.2");
893 ext->indirect_reference = 0;
895 ext->which = Z_External_CQL;
896 ext->u.cql = srw_req->query.cql;
898 rr.query->which = Z_Query_type_104;
899 rr.query->u.type_104 = ext;
902 else if (srw_req->query_type == Z_SRW_query_type_pqf)
904 Z_RPNQuery *RPNquery;
905 YAZ_PQF_Parser pqf_parser;
907 pqf_parser = yaz_pqf_create();
909 RPNquery = yaz_pqf_parse(pqf_parser, assoc->decode,
915 int code = yaz_pqf_error(pqf_parser, &pqf_msg, &off);
916 yaz_log(log_requestdetail, "Parse error %d %s near offset %ld",
917 code, pqf_msg, (long) off);
918 srw_error = YAZ_SRW_QUERY_SYNTAX_ERROR;
921 rr.query->which = Z_Query_type_1;
922 rr.query->u.type_1 = RPNquery;
924 yaz_pqf_destroy(pqf_parser);
928 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
929 &srw_res->num_diagnostics,
930 YAZ_SRW_UNSUPP_QUERY_TYPE, 0);
932 if (rr.query->u.type_1)
934 rr.stream = assoc->encode;
935 rr.decode = assoc->decode;
936 rr.print = assoc->print;
937 if ( srw_req->sort.sortKeys )
938 rr.srw_sortKeys = odr_strdup(assoc->encode,
939 srw_req->sort.sortKeys );
940 rr.association = assoc;
945 yaz_log_zquery_level(log_requestdetail,rr.query);
947 (assoc->init->bend_search)(assoc->backend, &rr);
950 if (rr.errcode == YAZ_BIB1_DATABASE_UNAVAILABLE)
956 srw_error = yaz_diag_bib1_to_srw(rr.errcode);
957 yaz_add_srw_diagnostic(assoc->encode,
958 &srw_res->diagnostics,
959 &srw_res->num_diagnostics,
960 srw_error, rr.errstring);
965 int number = srw_req->maximumRecords ? *srw_req->maximumRecords : 0;
966 int start = srw_req->startRecord ? *srw_req->startRecord : 1;
968 yaz_log(log_requestdetail, "Request to pack %d+%d out of "
970 start, number, rr.hits);
972 srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
975 srw_res->resultSetId =
976 odr_strdup(assoc->encode, rr.srw_setname );
977 srw_res->resultSetIdleTime =
978 odr_intdup(assoc->encode, *rr.srw_setnameIdleTime );
981 if (start > rr.hits || start < 1)
983 /* if hits<=0 and start=1 we don't return a diagnostic */
985 yaz_add_srw_diagnostic(
987 &srw_res->diagnostics, &srw_res->num_diagnostics,
988 YAZ_SRW_FIRST_RECORD_POSITION_OUT_OF_RANGE, 0);
994 if (start + number > rr.hits)
995 number = rr.hits - start + 1;
997 /* Call bend_present if defined */
998 if (assoc->init->bend_present)
1000 bend_present_rr *bprr = (bend_present_rr*)
1001 odr_malloc(assoc->decode, sizeof(*bprr));
1002 bprr->setname = "default";
1003 bprr->start = start;
1004 bprr->number = number;
1005 if (srw_req->recordSchema)
1007 bprr->comp = (Z_RecordComposition *) odr_malloc(assoc->decode,
1008 sizeof(*bprr->comp));
1009 bprr->comp->which = Z_RecordComp_simple;
1010 bprr->comp->u.simple = (Z_ElementSetNames *)
1011 odr_malloc(assoc->decode, sizeof(Z_ElementSetNames));
1012 bprr->comp->u.simple->which = Z_ElementSetNames_generic;
1013 bprr->comp->u.simple->u.generic = srw_req->recordSchema;
1019 bprr->stream = assoc->encode;
1020 bprr->referenceId = 0;
1021 bprr->print = assoc->print;
1022 bprr->association = assoc;
1024 bprr->errstring = NULL;
1025 (*assoc->init->bend_present)(assoc->backend, bprr);
1029 srw_error = yaz_diag_bib1_to_srw(bprr->errcode);
1030 yaz_add_srw_diagnostic(assoc->encode,
1031 &srw_res->diagnostics,
1032 &srw_res->num_diagnostics,
1033 srw_error, bprr->errstring);
1041 int packing = Z_SRW_recordPacking_string;
1042 if (srw_req->recordPacking)
1045 yaz_srw_str_to_pack(srw_req->recordPacking);
1047 packing = Z_SRW_recordPacking_string;
1049 srw_res->records = (Z_SRW_record *)
1050 odr_malloc(assoc->encode,
1051 number * sizeof(*srw_res->records));
1053 srw_res->extra_records = (Z_SRW_extra_record **)
1054 odr_malloc(assoc->encode,
1055 number*sizeof(*srw_res->extra_records));
1057 for (i = 0; i<number; i++)
1060 const char *addinfo = 0;
1062 srw_res->records[j].recordPacking = packing;
1063 srw_res->records[j].recordData_buf = 0;
1064 srw_res->extra_records[j] = 0;
1065 yaz_log(YLOG_DEBUG, "srw_bend_fetch %d", i+start);
1066 errcode = srw_bend_fetch(assoc, i+start, srw_req,
1067 srw_res->records + j,
1071 yaz_add_srw_diagnostic(assoc->encode,
1072 &srw_res->diagnostics,
1073 &srw_res->num_diagnostics,
1074 yaz_diag_bib1_to_srw(errcode),
1079 if (srw_res->records[j].recordData_buf)
1082 srw_res->num_records = j;
1084 srw_res->records = 0;
1087 if (rr.extra_response_data)
1089 res->extraResponseData_buf = rr.extra_response_data;
1090 res->extraResponseData_len = strlen(rr.extra_response_data);
1092 if (rr.estimated_hit_count || rr.partial_resultset)
1094 yaz_add_srw_diagnostic(
1096 &srw_res->diagnostics,
1097 &srw_res->num_diagnostics,
1098 YAZ_SRW_RESULT_SET_CREATED_WITH_VALID_PARTIAL_RESULTS_AVAILABLE,
1106 const char *querystr = "?";
1107 const char *querytype = "?";
1108 WRBUF wr = wrbuf_alloc();
1110 switch (srw_req->query_type)
1112 case Z_SRW_query_type_cql:
1114 querystr = srw_req->query.cql;
1116 case Z_SRW_query_type_pqf:
1118 querystr = srw_req->query.pqf;
1121 wrbuf_printf(wr, "SRWSearch %s ", srw_req->database);
1122 if (srw_res->num_diagnostics)
1123 wrbuf_printf(wr, "ERROR %s", srw_res->diagnostics[0].uri);
1124 else if (*http_code != 200)
1125 wrbuf_printf(wr, "ERROR info:http/%d", *http_code);
1126 else if (srw_res->numberOfRecords)
1128 wrbuf_printf(wr, "OK " ODR_INT_PRINTF,
1129 (srw_res->numberOfRecords ?
1130 *srw_res->numberOfRecords : 0));
1132 wrbuf_printf(wr, " %s " ODR_INT_PRINTF " +%d",
1133 (srw_res->resultSetId ?
1134 srw_res->resultSetId : "-"),
1135 (srw_req->startRecord ? *srw_req->startRecord : 1),
1136 srw_res->num_records);
1137 yaz_log(log_request, "%s %s: %s", wrbuf_cstr(wr), querytype, querystr);
1142 static char *srw_bend_explain_default(void *handle, bend_explain_rr *rr)
1145 xmlNodePtr ptr = (xmlNode *) rr->server_node_ptr;
1148 for (ptr = ptr->children; ptr; ptr = ptr->next)
1150 if (ptr->type != XML_ELEMENT_NODE)
1152 if (!strcmp((const char *) ptr->name, "explain"))
1155 xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
1159 ptr = xmlCopyNode(ptr, 1);
1161 xmlDocSetRootElement(doc, ptr);
1163 xmlDocDumpMemory(doc, &buf_out, &len);
1164 content = (char*) odr_malloc(rr->stream, 1+len);
1165 memcpy(content, buf_out, len);
1166 content[len] = '\0';
1170 rr->explain_buf = content;
1178 static void srw_bend_explain(association *assoc, request *req,
1180 Z_SRW_explainResponse *srw_res,
1183 Z_SRW_explainRequest *srw_req = sr->u.explain_request;
1184 yaz_log(log_requestdetail, "Got SRW ExplainRequest");
1186 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1191 rr.stream = assoc->encode;
1192 rr.decode = assoc->decode;
1193 rr.print = assoc->print;
1195 rr.database = srw_req->database;
1197 rr.server_node_ptr = assoc->server->server_node_ptr;
1199 rr.server_node_ptr = 0;
1200 rr.schema = "http://explain.z3950.org/dtd/2.0/";
1201 if (assoc->init->bend_explain)
1202 (*assoc->init->bend_explain)(assoc->backend, &rr);
1204 srw_bend_explain_default(assoc->backend, &rr);
1208 int packing = Z_SRW_recordPacking_string;
1209 if (srw_req->recordPacking)
1212 yaz_srw_str_to_pack(srw_req->recordPacking);
1214 packing = Z_SRW_recordPacking_string;
1216 srw_res->record.recordSchema = rr.schema;
1217 srw_res->record.recordPacking = packing;
1218 srw_res->record.recordData_buf = rr.explain_buf;
1219 srw_res->record.recordData_len = strlen(rr.explain_buf);
1220 srw_res->record.recordPosition = 0;
1226 static void srw_bend_scan(association *assoc, request *req,
1228 Z_SRW_scanResponse *srw_res,
1231 Z_SRW_scanRequest *srw_req = sr->u.scan_request;
1232 yaz_log(log_requestdetail, "Got SRW ScanRequest");
1235 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1236 if (srw_res->num_diagnostics == 0 && assoc->init)
1238 struct scan_entry *save_entries;
1240 bend_scan_rr *bsrr = (bend_scan_rr *)
1241 odr_malloc(assoc->encode, sizeof(*bsrr));
1242 bsrr->num_bases = 1;
1243 bsrr->basenames = &srw_req->database;
1245 bsrr->num_entries = srw_req->maximumTerms ?
1246 *srw_req->maximumTerms : 10;
1247 bsrr->term_position = srw_req->responsePosition ?
1248 *srw_req->responsePosition : 1;
1251 bsrr->errstring = 0;
1252 bsrr->referenceId = 0;
1253 bsrr->stream = assoc->encode;
1254 bsrr->print = assoc->print;
1255 bsrr->step_size = odr_intdup(assoc->decode, 0);
1259 if (bsrr->num_entries > 0)
1262 bsrr->entries = (struct scan_entry *)
1263 odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
1265 for (i = 0; i<bsrr->num_entries; i++)
1267 bsrr->entries[i].term = 0;
1268 bsrr->entries[i].occurrences = 0;
1269 bsrr->entries[i].errcode = 0;
1270 bsrr->entries[i].errstring = 0;
1271 bsrr->entries[i].display_term = 0;
1274 save_entries = bsrr->entries; /* save it so we can compare later */
1276 if (srw_req->query_type == Z_SRW_query_type_pqf &&
1277 assoc->init->bend_scan)
1279 YAZ_PQF_Parser pqf_parser = yaz_pqf_create();
1281 bsrr->term = yaz_pqf_scan(pqf_parser, assoc->decode,
1282 &bsrr->attributeset,
1283 srw_req->scanClause.pqf);
1284 yaz_pqf_destroy(pqf_parser);
1285 bsrr->scanClause = 0;
1286 ((int (*)(void *, bend_scan_rr *))
1287 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1289 else if (srw_req->query_type == Z_SRW_query_type_cql
1290 && assoc->init->bend_scan && assoc->server
1291 && assoc->server->cql_transform)
1294 bsrr->scanClause = 0;
1295 bsrr->attributeset = 0;
1296 bsrr->term = (Z_AttributesPlusTerm *)
1297 odr_malloc(assoc->decode, sizeof(*bsrr->term));
1298 srw_error = cql2pqf_scan(assoc->encode,
1299 srw_req->scanClause.cql,
1300 assoc->server->cql_transform,
1303 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1304 &srw_res->num_diagnostics,
1308 ((int (*)(void *, bend_scan_rr *))
1309 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1312 else if (srw_req->query_type == Z_SRW_query_type_cql
1313 && assoc->init->bend_srw_scan)
1316 bsrr->attributeset = 0;
1317 bsrr->scanClause = srw_req->scanClause.cql;
1318 ((int (*)(void *, bend_scan_rr *))
1319 (*assoc->init->bend_srw_scan))(assoc->backend, bsrr);
1323 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1324 &srw_res->num_diagnostics,
1325 YAZ_SRW_UNSUPP_OPERATION, "scan");
1330 if (bsrr->errcode == YAZ_BIB1_DATABASE_UNAVAILABLE)
1335 srw_error = yaz_diag_bib1_to_srw(bsrr->errcode);
1337 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1338 &srw_res->num_diagnostics,
1339 srw_error, bsrr->errstring);
1341 else if (srw_res->num_diagnostics == 0 && bsrr->num_entries)
1344 srw_res->terms = (Z_SRW_scanTerm*)
1345 odr_malloc(assoc->encode, sizeof(*srw_res->terms) *
1348 srw_res->num_terms = bsrr->num_entries;
1349 for (i = 0; i<bsrr->num_entries; i++)
1351 Z_SRW_scanTerm *t = srw_res->terms + i;
1352 t->value = odr_strdup(assoc->encode, bsrr->entries[i].term);
1353 t->numberOfRecords =
1354 odr_intdup(assoc->encode, bsrr->entries[i].occurrences);
1356 if (save_entries == bsrr->entries &&
1357 bsrr->entries[i].display_term)
1359 /* the entries was _not_ set by the handler. So it's
1360 safe to test for new member display_term. It is
1363 t->displayTerm = odr_strdup(assoc->encode,
1364 bsrr->entries[i].display_term);
1372 WRBUF wr = wrbuf_alloc();
1373 const char *querytype = 0;
1374 const char *querystr = 0;
1376 switch(srw_req->query_type)
1378 case Z_SRW_query_type_pqf:
1380 querystr = srw_req->scanClause.pqf;
1382 case Z_SRW_query_type_cql:
1384 querystr = srw_req->scanClause.cql;
1387 querytype = "UNKNOWN";
1391 wrbuf_printf(wr, "SRWScan %s ", srw_req->database);
1393 if (srw_res->num_diagnostics)
1394 wrbuf_printf(wr, "ERROR %s - ", srw_res->diagnostics[0].uri);
1395 else if (srw_res->num_terms)
1396 wrbuf_printf(wr, "OK %d - ", srw_res->num_terms);
1398 wrbuf_printf(wr, "OK - - ");
1400 wrbuf_printf(wr, ODR_INT_PRINTF "+" ODR_INT_PRINTF " ",
1401 (srw_req->responsePosition ?
1402 *srw_req->responsePosition : 1),
1403 (srw_req->maximumTerms ?
1404 *srw_req->maximumTerms : 1));
1405 /* there is no step size in SRU/W ??? */
1406 wrbuf_printf(wr, "%s: %s ", querytype, querystr);
1407 yaz_log(log_request, "%s ", wrbuf_cstr(wr) );
1413 static void srw_bend_update(association *assoc, request *req,
1415 Z_SRW_updateResponse *srw_res,
1418 Z_SRW_updateRequest *srw_req = sr->u.update_request;
1419 yaz_log(log_session, "SRWUpdate action=%s", srw_req->operation);
1420 yaz_log(YLOG_DEBUG, "num_diag = %d", srw_res->num_diagnostics );
1422 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1426 Z_SRW_extra_record *extra = srw_req->extra_record;
1428 rr.stream = assoc->encode;
1429 rr.print = assoc->print;
1431 rr.basenames = &srw_req->database;
1432 rr.operation = srw_req->operation;
1433 rr.operation_status = "failed";
1435 rr.record_versions = 0;
1436 rr.num_versions = 0;
1437 rr.record_packing = "string";
1438 rr.record_schema = 0;
1440 rr.extra_record_data = 0;
1441 rr.extra_request_data = 0;
1442 rr.extra_response_data = 0;
1448 if (rr.operation == 0)
1450 yaz_add_sru_update_diagnostic(
1451 assoc->encode, &srw_res->diagnostics,
1452 &srw_res->num_diagnostics,
1453 YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,
1457 yaz_log(YLOG_DEBUG, "basename = %s", rr.basenames[0] );
1458 yaz_log(YLOG_DEBUG, "Operation = %s", rr.operation );
1459 if (!strcmp( rr.operation, "delete"))
1461 if (srw_req->record && !srw_req->record->recordSchema)
1463 rr.record_schema = odr_strdup(
1465 srw_req->record->recordSchema);
1467 if (srw_req->record)
1469 rr.record_data = odr_strdupn(
1471 srw_req->record->recordData_buf,
1472 srw_req->record->recordData_len );
1474 if (extra && extra->extraRecordData_len)
1476 rr.extra_record_data = odr_strdupn(
1478 extra->extraRecordData_buf,
1479 extra->extraRecordData_len );
1481 if (srw_req->recordId)
1482 rr.record_id = srw_req->recordId;
1483 else if (extra && extra->recordIdentifier)
1484 rr.record_id = extra->recordIdentifier;
1486 else if (!strcmp(rr.operation, "replace"))
1488 if (srw_req->recordId)
1489 rr.record_id = srw_req->recordId;
1490 else if (extra && extra->recordIdentifier)
1491 rr.record_id = extra->recordIdentifier;
1494 yaz_add_sru_update_diagnostic(
1495 assoc->encode, &srw_res->diagnostics,
1496 &srw_res->num_diagnostics,
1497 YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,
1498 "recordIdentifier");
1500 if (!srw_req->record)
1502 yaz_add_sru_update_diagnostic(
1503 assoc->encode, &srw_res->diagnostics,
1504 &srw_res->num_diagnostics,
1505 YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,
1510 if (srw_req->record->recordSchema)
1511 rr.record_schema = odr_strdup(
1512 assoc->encode, srw_req->record->recordSchema);
1513 if (srw_req->record->recordData_len )
1515 rr.record_data = odr_strdupn(assoc->encode,
1516 srw_req->record->recordData_buf,
1517 srw_req->record->recordData_len );
1521 yaz_add_sru_update_diagnostic(
1522 assoc->encode, &srw_res->diagnostics,
1523 &srw_res->num_diagnostics,
1524 YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,
1528 if (extra && extra->extraRecordData_len)
1530 rr.extra_record_data = odr_strdupn(
1532 extra->extraRecordData_buf,
1533 extra->extraRecordData_len );
1536 else if (!strcmp(rr.operation, "insert"))
1538 if (srw_req->recordId)
1539 rr.record_id = srw_req->recordId;
1541 rr.record_id = extra->recordIdentifier;
1543 if (srw_req->record)
1545 if (srw_req->record->recordSchema)
1546 rr.record_schema = odr_strdup(
1547 assoc->encode, srw_req->record->recordSchema);
1549 if (srw_req->record->recordData_len)
1550 rr.record_data = odr_strdupn(
1552 srw_req->record->recordData_buf,
1553 srw_req->record->recordData_len );
1555 if (extra && extra->extraRecordData_len)
1557 rr.extra_record_data = odr_strdupn(
1559 extra->extraRecordData_buf,
1560 extra->extraRecordData_len );
1564 yaz_add_sru_update_diagnostic(assoc->encode, &srw_res->diagnostics,
1565 &srw_res->num_diagnostics,
1566 YAZ_SRU_UPDATE_INVALID_ACTION,
1569 if (srw_req->record)
1571 const char *pack_str =
1572 yaz_srw_pack_to_str(srw_req->record->recordPacking);
1574 rr.record_packing = odr_strdup(assoc->encode, pack_str);
1577 if (srw_req->num_recordVersions)
1579 rr.record_versions = srw_req->recordVersions;
1580 rr.num_versions = srw_req->num_recordVersions;
1582 if (srw_req->extraRequestData_len)
1584 rr.extra_request_data = odr_strdupn(assoc->encode,
1585 srw_req->extraRequestData_buf,
1586 srw_req->extraRequestData_len );
1588 if (srw_res->num_diagnostics == 0)
1590 if ( assoc->init->bend_srw_update)
1591 (*assoc->init->bend_srw_update)(assoc->backend, &rr);
1593 yaz_add_sru_update_diagnostic(
1594 assoc->encode, &srw_res->diagnostics,
1595 &srw_res->num_diagnostics,
1596 YAZ_SRU_UPDATE_UNSPECIFIED_DATABASE_ERROR,
1597 "No Update backend handler");
1601 yaz_add_srw_diagnostic_uri(assoc->encode,
1602 &srw_res->diagnostics,
1603 &srw_res->num_diagnostics,
1607 srw_res->recordId = rr.record_id;
1608 srw_res->operationStatus = rr.operation_status;
1609 srw_res->recordVersions = rr.record_versions;
1610 srw_res->num_recordVersions = rr.num_versions;
1611 if (srw_res->extraResponseData_len)
1613 srw_res->extraResponseData_buf = rr.extra_response_data;
1614 srw_res->extraResponseData_len = strlen(rr.extra_response_data);
1616 if (srw_res->num_diagnostics == 0 && rr.record_data)
1618 srw_res->record = yaz_srw_get_record(assoc->encode);
1619 srw_res->record->recordSchema = rr.record_schema;
1620 if (rr.record_packing)
1622 int pack = yaz_srw_str_to_pack(rr.record_packing);
1626 pack = Z_SRW_recordPacking_string;
1627 yaz_log(YLOG_WARN, "Back packing %s from backend",
1630 srw_res->record->recordPacking = pack;
1632 srw_res->record->recordData_buf = rr.record_data;
1633 srw_res->record->recordData_len = strlen(rr.record_data);
1634 if (rr.extra_record_data)
1636 Z_SRW_extra_record *ex =
1637 yaz_srw_get_extra_record(assoc->encode);
1638 srw_res->extra_record = ex;
1639 ex->extraRecordData_buf = rr.extra_record_data;
1640 ex->extraRecordData_len = strlen(rr.extra_record_data);
1646 /* check if path is OK (1); BAD (0) */
1647 static int check_path(const char *path)
1651 if (strstr(path, ".."))
1656 static char *read_file(const char *fname, ODR o, size_t *sz)
1659 FILE *inf = fopen(fname, "rb");
1663 fseek(inf, 0L, SEEK_END);
1666 buf = (char *) odr_malloc(o, *sz);
1667 if (fread(buf, 1, *sz, inf) != *sz)
1668 yaz_log(YLOG_WARN|YLOG_ERRNO, "short read %s", fname);
1673 static void process_http_request(association *assoc, request *req)
1675 Z_HTTP_Request *hreq = req->gdu_request->u.HTTP_Request;
1676 ODR o = assoc->encode;
1677 int r = 2; /* 2=NOT TAKEN, 1=TAKEN, 0=SOAP TAKEN */
1679 Z_SOAP *soap_package = 0;
1682 Z_HTTP_Response *hres = 0;
1684 const char *stylesheet = 0; /* for now .. set later */
1685 Z_SRW_diagnostic *diagnostic = 0;
1686 int num_diagnostic = 0;
1687 const char *host = z_HTTP_header_lookup(hreq->headers, "Host");
1689 yaz_log(log_request, "%s %s HTTP/%s", hreq->method, hreq->path, hreq->version);
1690 if (!control_association(assoc, host, 0))
1692 p = z_get_HTTP_Response(o, 404);
1695 if (r == 2 && assoc->server && assoc->server->docpath
1696 && hreq->path[0] == '/'
1698 /* check if path is a proper prefix of documentroot */
1699 strncmp(hreq->path+1, assoc->server->docpath,
1700 strlen(assoc->server->docpath))
1703 if (!check_path(hreq->path))
1705 yaz_log(YLOG_LOG, "File %s access forbidden", hreq->path+1);
1706 p = z_get_HTTP_Response(o, 404);
1710 size_t content_size = 0;
1711 char *content_buf = read_file(hreq->path+1, o, &content_size);
1714 yaz_log(YLOG_LOG, "File %s not found", hreq->path+1);
1715 p = z_get_HTTP_Response(o, 404);
1719 const char *ctype = 0;
1720 yaz_mime_types types = yaz_mime_types_create();
1722 yaz_mime_types_add(types, "xsl", "application/xml");
1723 yaz_mime_types_add(types, "xml", "application/xml");
1724 yaz_mime_types_add(types, "css", "text/css");
1725 yaz_mime_types_add(types, "html", "text/html");
1726 yaz_mime_types_add(types, "htm", "text/html");
1727 yaz_mime_types_add(types, "txt", "text/plain");
1728 yaz_mime_types_add(types, "js", "application/x-javascript");
1730 yaz_mime_types_add(types, "gif", "image/gif");
1731 yaz_mime_types_add(types, "png", "image/png");
1732 yaz_mime_types_add(types, "jpg", "image/jpeg");
1733 yaz_mime_types_add(types, "jpeg", "image/jpeg");
1735 ctype = yaz_mime_lookup_fname(types, hreq->path);
1738 yaz_log(YLOG_LOG, "No mime type for %s", hreq->path+1);
1739 p = z_get_HTTP_Response(o, 404);
1743 p = z_get_HTTP_Response(o, 200);
1744 hres = p->u.HTTP_Response;
1745 hres->content_buf = content_buf;
1746 hres->content_len = content_size;
1747 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1749 yaz_mime_types_destroy(types);
1757 r = yaz_srw_decode(hreq, &sr, &soap_package, assoc->decode, &charset);
1758 yaz_log(YLOG_DEBUG, "yaz_srw_decode returned %d", r);
1760 if (r == 2) /* not taken */
1762 r = yaz_sru_decode(hreq, &sr, &soap_package, assoc->decode, &charset,
1763 &diagnostic, &num_diagnostic);
1764 yaz_log(YLOG_DEBUG, "yaz_sru_decode returned %d", r);
1766 if (r == 0) /* decode SRW/SRU OK .. */
1768 int http_code = 200;
1769 if (sr->which == Z_SRW_searchRetrieve_request)
1772 yaz_srw_get_pdu(assoc->encode, Z_SRW_searchRetrieve_response,
1774 stylesheet = sr->u.request->stylesheet;
1777 res->u.response->diagnostics = diagnostic;
1778 res->u.response->num_diagnostics = num_diagnostic;
1782 srw_bend_search(assoc, req, sr, res, &http_code);
1784 if (http_code == 200)
1785 soap_package->u.generic->p = res;
1787 else if (sr->which == Z_SRW_explain_request)
1789 Z_SRW_PDU *res = yaz_srw_get_pdu(o, Z_SRW_explain_response,
1791 stylesheet = sr->u.explain_request->stylesheet;
1794 res->u.explain_response->diagnostics = diagnostic;
1795 res->u.explain_response->num_diagnostics = num_diagnostic;
1797 srw_bend_explain(assoc, req, sr,
1798 res->u.explain_response, &http_code);
1799 if (http_code == 200)
1800 soap_package->u.generic->p = res;
1802 else if (sr->which == Z_SRW_scan_request)
1804 Z_SRW_PDU *res = yaz_srw_get_pdu(o, Z_SRW_scan_response,
1806 stylesheet = sr->u.scan_request->stylesheet;
1809 res->u.scan_response->diagnostics = diagnostic;
1810 res->u.scan_response->num_diagnostics = num_diagnostic;
1812 srw_bend_scan(assoc, req, sr,
1813 res->u.scan_response, &http_code);
1814 if (http_code == 200)
1815 soap_package->u.generic->p = res;
1817 else if (sr->which == Z_SRW_update_request)
1819 Z_SRW_PDU *res = yaz_srw_get_pdu(o, Z_SRW_update_response,
1821 yaz_log(YLOG_DEBUG, "handling SRW UpdateRequest");
1824 res->u.update_response->diagnostics = diagnostic;
1825 res->u.update_response->num_diagnostics = num_diagnostic;
1827 yaz_log(YLOG_DEBUG, "num_diag = %d", res->u.update_response->num_diagnostics );
1828 srw_bend_update(assoc, req, sr,
1829 res->u.update_response, &http_code);
1830 if (http_code == 200)
1831 soap_package->u.generic->p = res;
1835 yaz_log(log_request, "SOAP ERROR");
1836 /* FIXME - what error, what query */
1838 z_soap_error(assoc->encode, soap_package,
1839 "SOAP-ENV:Client", "Bad method", 0);
1841 if (http_code == 200 || http_code == 500)
1843 static Z_SOAP_Handler soap_handlers[4] = {
1845 {YAZ_XMLNS_SRU_v1_1, 0, (Z_SOAP_fun) yaz_srw_codec},
1846 {YAZ_XMLNS_SRU_v1_0, 0, (Z_SOAP_fun) yaz_srw_codec},
1847 {YAZ_XMLNS_UPDATE_v0_9, 0, (Z_SOAP_fun) yaz_ucp_codec},
1853 p = z_get_HTTP_Response(o, 200);
1854 hres = p->u.HTTP_Response;
1856 if (!stylesheet && assoc->server)
1857 stylesheet = assoc->server->stylesheet;
1859 /* empty stylesheet means NO stylesheet */
1860 if (stylesheet && *stylesheet == '\0')
1863 ret = z_soap_codec_enc_xsl(assoc->encode, &soap_package,
1864 &hres->content_buf, &hres->content_len,
1865 soap_handlers, charset, stylesheet);
1866 hres->code = http_code;
1868 strcpy(ctype, "text/xml");
1869 if (charset && strlen(charset) < sizeof(ctype)-30)
1871 strcat(ctype, "; charset=");
1872 strcat(ctype, charset);
1874 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1877 p = z_get_HTTP_Response(o, http_code);
1881 p = z_get_HTTP_Response(o, 500);
1882 hres = p->u.HTTP_Response;
1883 if (!strcmp(hreq->version, "1.0"))
1885 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1886 if (v && !strcmp(v, "Keep-Alive"))
1890 hres->version = "1.0";
1894 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1895 if (v && !strcmp(v, "close"))
1899 hres->version = "1.1";
1903 z_HTTP_header_add(o, &hres->headers, "Connection", "close");
1904 assoc->state = ASSOC_DEAD;
1905 assoc->cs_get_mask = 0;
1910 const char *alive = z_HTTP_header_lookup(hreq->headers, "Keep-Alive");
1912 if (alive && isdigit(*(const unsigned char *) alive))
1916 if (t < 0 || t > 3600)
1918 iochan_settimeout(assoc->client_chan,t);
1919 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1921 process_gdu_response(assoc, req, p);
1924 static void process_gdu_request(association *assoc, request *req)
1926 if (req->gdu_request->which == Z_GDU_Z3950)
1929 req->apdu_request = req->gdu_request->u.z3950;
1930 if (process_z_request(assoc, req, &msg) < 0)
1931 do_close_req(assoc, Z_Close_systemProblem, msg, req);
1933 else if (req->gdu_request->which == Z_GDU_HTTP_Request)
1934 process_http_request(assoc, req);
1937 do_close_req(assoc, Z_Close_systemProblem, "bad protocol packet", req);
1942 * Initiate request processing.
1944 static int process_z_request(association *assoc, request *req, char **msg)
1949 *msg = "Unknown Error";
1950 assert(req && req->state == REQUEST_IDLE);
1951 if (req->apdu_request->which != Z_APDU_initRequest && !assoc->init)
1953 *msg = "Missing InitRequest";
1956 switch (req->apdu_request->which)
1958 case Z_APDU_initRequest:
1959 res = process_initRequest(assoc, req); break;
1960 case Z_APDU_searchRequest:
1961 res = process_searchRequest(assoc, req); break;
1962 case Z_APDU_presentRequest:
1963 res = process_presentRequest(assoc, req); break;
1964 case Z_APDU_scanRequest:
1965 if (assoc->init->bend_scan)
1966 res = process_scanRequest(assoc, req);
1969 *msg = "Cannot handle Scan APDU";
1973 case Z_APDU_extendedServicesRequest:
1974 if (assoc->init->bend_esrequest)
1975 res = process_ESRequest(assoc, req);
1978 *msg = "Cannot handle Extended Services APDU";
1982 case Z_APDU_sortRequest:
1983 if (assoc->init->bend_sort)
1984 res = process_sortRequest(assoc, req);
1987 *msg = "Cannot handle Sort APDU";
1992 process_close(assoc, req);
1994 case Z_APDU_deleteResultSetRequest:
1995 if (assoc->init->bend_delete)
1996 res = process_deleteRequest(assoc, req);
1999 *msg = "Cannot handle Delete APDU";
2003 case Z_APDU_segmentRequest:
2004 if (assoc->init->bend_segment)
2006 res = process_segmentRequest(assoc, req);
2010 *msg = "Cannot handle Segment APDU";
2014 case Z_APDU_triggerResourceControlRequest:
2017 *msg = "Bad APDU received";
2022 yaz_log(YLOG_DEBUG, " result immediately available");
2023 retval = process_z_response(assoc, req, res);
2027 yaz_log(YLOG_DEBUG, " result unavailble");
2034 * Encode response, and transfer the request structure to the outgoing queue.
2036 static int process_gdu_response(association *assoc, request *req, Z_GDU *res)
2038 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
2042 if (!z_GDU(assoc->print, &res, 0, 0))
2043 yaz_log(YLOG_WARN, "ODR print error: %s",
2044 odr_errmsg(odr_geterror(assoc->print)));
2045 odr_reset(assoc->print);
2047 if (!z_GDU(assoc->encode, &res, 0, 0))
2049 yaz_log(YLOG_WARN, "ODR error when encoding PDU: %s [element %s]",
2050 odr_errmsg(odr_geterror(assoc->decode)),
2051 odr_getelement(assoc->decode));
2054 req->response = odr_getbuf(assoc->encode, &req->len_response,
2055 &req->size_response);
2056 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
2057 odr_reset(assoc->encode);
2058 req->state = REQUEST_IDLE;
2059 request_enq(&assoc->outgoing, req);
2060 /* turn the work over to the ir_session handler */
2061 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
2062 assoc->cs_put_mask = EVENT_OUTPUT;
2063 /* Is there more work to be done? give that to the input handler too */
2066 req = request_head(&assoc->incoming);
2067 if (req && req->state == REQUEST_IDLE)
2069 request_deq(&assoc->incoming);
2070 process_gdu_request(assoc, req);
2079 * Encode response, and transfer the request structure to the outgoing queue.
2081 static int process_z_response(association *assoc, request *req, Z_APDU *res)
2083 Z_GDU *gres = (Z_GDU *) odr_malloc(assoc->encode, sizeof(*res));
2084 gres->which = Z_GDU_Z3950;
2085 gres->u.z3950 = res;
2087 return process_gdu_response(assoc, req, gres);
2090 static char *get_vhost(Z_OtherInformation *otherInfo)
2092 return yaz_oi_get_string_oid(&otherInfo, yaz_oid_userinfo_proxy, 1, 0);
2096 * Handle init request.
2097 * At the moment, we don't check the options
2098 * anywhere else in the code - we just try not to do anything that would
2099 * break a naive client. We'll toss 'em into the association block when
2100 * we need them there.
2102 static Z_APDU *process_initRequest(association *assoc, request *reqb)
2104 Z_InitRequest *req = reqb->apdu_request->u.initRequest;
2105 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
2106 Z_InitResponse *resp = apdu->u.initResponse;
2107 bend_initresult *binitres;
2109 statserv_options_block *cb = 0; /* by default no control for backend */
2111 if (control_association(assoc, get_vhost(req->otherInfo), 1))
2112 cb = statserv_getcontrol(); /* got control block for backend */
2114 if (cb && assoc->backend)
2115 (*cb->bend_close)(assoc->backend);
2117 yaz_log(log_requestdetail, "Got initRequest");
2118 if (req->implementationId)
2119 yaz_log(log_requestdetail, "Id: %s",
2120 req->implementationId);
2121 if (req->implementationName)
2122 yaz_log(log_requestdetail, "Name: %s",
2123 req->implementationName);
2124 if (req->implementationVersion)
2125 yaz_log(log_requestdetail, "Version: %s",
2126 req->implementationVersion);
2128 assoc_init_reset(assoc);
2130 assoc->init->auth = req->idAuthentication;
2131 assoc->init->referenceId = req->referenceId;
2133 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
2135 Z_CharSetandLanguageNegotiation *negotiation =
2136 yaz_get_charneg_record (req->otherInfo);
2138 negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
2139 assoc->init->charneg_request = negotiation;
2142 /* by default named_result_sets is 0 .. Enable it if client asks for it. */
2143 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
2144 assoc->init->named_result_sets = 1;
2149 if (req->implementationVersion)
2150 yaz_log(log_requestdetail, "Config: %s",
2153 iochan_settimeout(assoc->client_chan, cb->idle_timeout * 60);
2155 /* we have a backend control block, so call that init function */
2156 if (!(binitres = (*cb->bend_init)(assoc->init)))
2158 yaz_log(YLOG_WARN, "Bad response from backend.");
2161 assoc->backend = binitres->handle;
2165 /* no backend. return error */
2166 binitres = (bend_initresult *)
2167 odr_malloc(assoc->encode, sizeof(*binitres));
2168 binitres->errstring = 0;
2169 binitres->errcode = YAZ_BIB1_PERMANENT_SYSTEM_ERROR;
2170 iochan_settimeout(assoc->client_chan, 10);
2172 if ((assoc->init->bend_sort))
2173 yaz_log(YLOG_DEBUG, "Sort handler installed");
2174 if ((assoc->init->bend_search))
2175 yaz_log(YLOG_DEBUG, "Search handler installed");
2176 if ((assoc->init->bend_present))
2177 yaz_log(YLOG_DEBUG, "Present handler installed");
2178 if ((assoc->init->bend_esrequest))
2179 yaz_log(YLOG_DEBUG, "ESRequest handler installed");
2180 if ((assoc->init->bend_delete))
2181 yaz_log(YLOG_DEBUG, "Delete handler installed");
2182 if ((assoc->init->bend_scan))
2183 yaz_log(YLOG_DEBUG, "Scan handler installed");
2184 if ((assoc->init->bend_segment))
2185 yaz_log(YLOG_DEBUG, "Segment handler installed");
2187 resp->referenceId = req->referenceId;
2189 /* let's tell the client what we can do */
2190 if (ODR_MASK_GET(req->options, Z_Options_search))
2192 ODR_MASK_SET(resp->options, Z_Options_search);
2193 strcat(options, "srch");
2195 if (ODR_MASK_GET(req->options, Z_Options_present))
2197 ODR_MASK_SET(resp->options, Z_Options_present);
2198 strcat(options, " prst");
2200 if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
2201 assoc->init->bend_delete)
2203 ODR_MASK_SET(resp->options, Z_Options_delSet);
2204 strcat(options, " del");
2206 if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
2207 assoc->init->bend_esrequest)
2209 ODR_MASK_SET(resp->options, Z_Options_extendedServices);
2210 strcat(options, " extendedServices");
2212 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets)
2213 && assoc->init->named_result_sets)
2215 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
2216 strcat(options, " namedresults");
2218 if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
2220 ODR_MASK_SET(resp->options, Z_Options_scan);
2221 strcat(options, " scan");
2223 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
2225 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
2226 strcat(options, " concurrop");
2228 if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
2230 ODR_MASK_SET(resp->options, Z_Options_sort);
2231 strcat(options, " sort");
2234 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
2236 Z_OtherInformationUnit *p0;
2238 if (!assoc->init->charneg_response)
2240 if (assoc->init->query_charset)
2242 assoc->init->charneg_response = yaz_set_response_charneg(
2243 assoc->encode, assoc->init->query_charset, 0,
2244 assoc->init->records_in_same_charset);
2248 yaz_log(YLOG_WARN, "default query_charset not defined by backend");
2251 if (assoc->init->charneg_response
2252 && (p0=yaz_oi_update(&resp->otherInfo, assoc->encode, NULL, 0, 0)))
2254 p0->which = Z_OtherInfo_externallyDefinedInfo;
2255 p0->information.externallyDefinedInfo =
2256 assoc->init->charneg_response;
2257 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
2258 strcat(options, " negotiation");
2261 if (ODR_MASK_GET(req->options, Z_Options_triggerResourceCtrl))
2262 ODR_MASK_SET(resp->options, Z_Options_triggerResourceCtrl);
2264 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
2266 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
2267 assoc->version = 1; /* 1 & 2 are equivalent */
2269 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
2271 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
2274 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
2276 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
2280 yaz_log(log_requestdetail, "Negotiated to v%d: %s", assoc->version, options);
2282 if (*req->maximumRecordSize < assoc->maximumRecordSize)
2283 assoc->maximumRecordSize = *req->maximumRecordSize;
2285 if (*req->preferredMessageSize < assoc->preferredMessageSize)
2286 assoc->preferredMessageSize = *req->preferredMessageSize;
2288 resp->preferredMessageSize = &assoc->preferredMessageSize;
2289 resp->maximumRecordSize = &assoc->maximumRecordSize;
2291 resp->implementationId = odr_prepend(assoc->encode,
2292 assoc->init->implementation_id,
2293 resp->implementationId);
2295 resp->implementationName = odr_prepend(assoc->encode,
2296 assoc->init->implementation_name,
2297 odr_prepend(assoc->encode, "GFS", resp->implementationName));
2299 if (binitres->errcode)
2301 assoc->state = ASSOC_DEAD;
2302 resp->userInformationField =
2303 init_diagnostics(assoc->encode, binitres->errcode,
2304 binitres->errstring);
2308 assoc->state = ASSOC_UP;
2312 if (!req->idAuthentication)
2313 yaz_log(log_request, "Auth none");
2314 else if (req->idAuthentication->which == Z_IdAuthentication_open)
2316 const char *open = req->idAuthentication->u.open;
2317 const char *slash = strchr(open, '/');
2323 yaz_log(log_request, "Auth open %.*s", len, open);
2325 else if (req->idAuthentication->which == Z_IdAuthentication_idPass)
2327 const char *user = req->idAuthentication->u.idPass->userId;
2328 const char *group = req->idAuthentication->u.idPass->groupId;
2329 yaz_log(log_request, "Auth idPass %s %s",
2330 user ? user : "-", group ? group : "-");
2332 else if (req->idAuthentication->which
2333 == Z_IdAuthentication_anonymous)
2335 yaz_log(log_request, "Auth anonymous");
2339 yaz_log(log_request, "Auth other");
2344 WRBUF wr = wrbuf_alloc();
2345 wrbuf_printf(wr, "Init ");
2346 if (binitres->errcode)
2347 wrbuf_printf(wr, "ERROR %d", binitres->errcode);
2349 wrbuf_printf(wr, "OK -");
2350 wrbuf_printf(wr, " ID:%s Name:%s Version:%s",
2351 (req->implementationId ? req->implementationId :"-"),
2352 (req->implementationName ?
2353 req->implementationName : "-"),
2354 (req->implementationVersion ?
2355 req->implementationVersion : "-")
2357 yaz_log(log_request, "%s", wrbuf_cstr(wr));
2364 * Set the specified `errcode' and `errstring' into a UserInfo-1
2365 * external to be returned to the client in accordance with Z35.90
2366 * Implementor Agreement 5 (Returning diagnostics in an InitResponse):
2367 * http://lcweb.loc.gov/z3950/agency/agree/initdiag.html
2369 static Z_External *init_diagnostics(ODR odr, int error, const char *addinfo)
2371 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2372 addinfo ? " -- " : "", addinfo ? addinfo : "");
2373 return zget_init_diagnostics(odr, error, addinfo);
2377 * nonsurrogate diagnostic record.
2379 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
2381 Z_Records *rec = (Z_Records *) odr_malloc(assoc->encode, sizeof(*rec));
2383 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2384 addinfo ? " -- " : "", addinfo ? addinfo : "");
2386 rec->which = Z_Records_NSD;
2387 rec->u.nonSurrogateDiagnostic = zget_DefaultDiagFormat(assoc->encode,
2393 * surrogate diagnostic.
2395 static Z_NamePlusRecord *surrogatediagrec(association *assoc,
2397 int error, const char *addinfo)
2399 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2400 addinfo ? " -- " : "", addinfo ? addinfo : "");
2401 return zget_surrogateDiagRec(assoc->encode, dbname, error, addinfo);
2404 static Z_Records *pack_records(association *a, char *setname, Odr_int start,
2405 Odr_int *num, Z_RecordComposition *comp,
2406 Odr_int *next, Odr_int *pres,
2407 Z_ReferenceId *referenceId,
2408 Odr_oid *oid, int *errcode)
2410 int recno, total_length = 0, toget = *num, dumped_records = 0;
2411 Z_Records *records =
2412 (Z_Records *) odr_malloc(a->encode, sizeof(*records));
2413 Z_NamePlusRecordList *reclist =
2414 (Z_NamePlusRecordList *) odr_malloc(a->encode, sizeof(*reclist));
2415 Z_NamePlusRecord **list =
2416 (Z_NamePlusRecord **) odr_malloc(a->encode, sizeof(*list) * toget);
2418 records->which = Z_Records_DBOSD;
2419 records->u.databaseOrSurDiagnostics = reclist;
2420 reclist->num_records = 0;
2421 reclist->records = list;
2422 *pres = Z_PresentStatus_success;
2426 yaz_log(log_requestdetail, "Request to pack " ODR_INT_PRINTF "+%d %s", start, toget, setname);
2427 yaz_log(log_requestdetail, "pms=" ODR_INT_PRINTF
2428 ", mrs=" ODR_INT_PRINTF, a->preferredMessageSize,
2429 a->maximumRecordSize);
2430 for (recno = start; reclist->num_records < toget; recno++)
2433 Z_NamePlusRecord *thisrec;
2434 int this_length = 0;
2436 * we get the number of bytes allocated on the stream before any
2437 * allocation done by the backend - this should give us a reasonable
2438 * idea of the total size of the data so far.
2440 total_length = odr_total(a->encode) - dumped_records;
2446 freq.last_in_set = 0;
2447 freq.setname = setname;
2448 freq.surrogate_flag = 0;
2449 freq.number = recno;
2451 freq.request_format = oid;
2452 freq.output_format = 0;
2453 freq.stream = a->encode;
2454 freq.print = a->print;
2455 freq.referenceId = referenceId;
2458 retrieve_fetch(a, &freq);
2460 *next = freq.last_in_set ? 0 : recno + 1;
2464 if (!freq.surrogate_flag) /* non-surrogate diagnostic i.e. global */
2467 *pres = Z_PresentStatus_failure;
2468 /* for 'present request out of range',
2469 set addinfo to record position if not set */
2470 if (freq.errcode == YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE &&
2471 freq.errstring == 0)
2473 sprintf(s, "%d", recno);
2477 *errcode = freq.errcode;
2478 return diagrec(a, freq.errcode, freq.errstring);
2480 reclist->records[reclist->num_records] =
2481 surrogatediagrec(a, freq.basename, freq.errcode,
2483 reclist->num_records++;
2486 if (freq.record == 0) /* no error and no record ? */
2488 *next = 0; /* signal end-of-set and stop */
2492 this_length = freq.len;
2494 this_length = odr_total(a->encode) - total_length - dumped_records;
2495 yaz_log(YLOG_DEBUG, " fetched record, len=%d, total=%d dumped=%d",
2496 this_length, total_length, dumped_records);
2497 if (a->preferredMessageSize > 0 &&
2498 this_length + total_length > a->preferredMessageSize)
2500 /* record is small enough, really */
2501 if (this_length <= a->preferredMessageSize && recno > start)
2503 yaz_log(log_requestdetail, " Dropped last normal-sized record");
2504 *pres = Z_PresentStatus_partial_2;
2507 /* record can only be fetched by itself */
2508 if (this_length < a->maximumRecordSize)
2510 yaz_log(log_requestdetail, " Record > prefmsgsz");
2513 yaz_log(YLOG_DEBUG, " Dropped it");
2514 reclist->records[reclist->num_records] =
2515 surrogatediagrec(a, freq.basename, 16, 0);
2516 reclist->num_records++;
2517 dumped_records += this_length;
2521 else /* too big entirely */
2523 yaz_log(log_requestdetail, "Record > maxrcdsz "
2524 "this=%d max=" ODR_INT_PRINTF,
2525 this_length, a->maximumRecordSize);
2526 reclist->records[reclist->num_records] =
2527 surrogatediagrec(a, freq.basename, 17, 0);
2528 reclist->num_records++;
2529 dumped_records += this_length;
2534 if (!(thisrec = (Z_NamePlusRecord *)
2535 odr_malloc(a->encode, sizeof(*thisrec))))
2537 thisrec->databaseName = odr_strdup_null(a->encode, freq.basename);
2538 thisrec->which = Z_NamePlusRecord_databaseRecord;
2540 if (!freq.output_format)
2541 freq.output_format = freq.request_format;
2542 thisrec->u.databaseRecord = z_ext_record_oid(
2543 a->encode, freq.output_format, freq.record, freq.len);
2544 if (!thisrec->u.databaseRecord)
2546 reclist->records[reclist->num_records] = thisrec;
2547 reclist->num_records++;
2549 *num = reclist->num_records;
2553 static Z_APDU *process_searchRequest(association *assoc, request *reqb)
2555 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2556 bend_search_rr *bsrr =
2557 (bend_search_rr *)nmem_malloc(reqb->request_mem, sizeof(*bsrr));
2559 yaz_log(log_requestdetail, "Got SearchRequest.");
2560 bsrr->association = assoc;
2561 bsrr->referenceId = req->referenceId;
2562 bsrr->srw_sortKeys = 0;
2563 bsrr->srw_setname = 0;
2564 bsrr->srw_setnameIdleTime = 0;
2565 bsrr->estimated_hit_count = 0;
2566 bsrr->partial_resultset = 0;
2567 bsrr->extra_args = 0;
2568 bsrr->extra_response_data = 0;
2570 yaz_log (log_requestdetail, "ResultSet '%s'", req->resultSetName);
2571 if (req->databaseNames)
2574 for (i = 0; i < req->num_databaseNames; i++)
2575 yaz_log(log_requestdetail, "Database '%s'", req->databaseNames[i]);
2578 yaz_log_zquery_level(log_requestdetail,req->query);
2580 if (assoc->init->bend_search)
2582 bsrr->setname = req->resultSetName;
2583 bsrr->replace_set = *req->replaceIndicator;
2584 bsrr->num_bases = req->num_databaseNames;
2585 bsrr->basenames = req->databaseNames;
2586 bsrr->query = req->query;
2587 bsrr->stream = assoc->encode;
2588 nmem_transfer(odr_getmem(bsrr->stream), reqb->request_mem);
2589 bsrr->decode = assoc->decode;
2590 bsrr->print = assoc->print;
2593 bsrr->errstring = NULL;
2594 bsrr->search_info = NULL;
2596 if (assoc->server && assoc->server->cql_transform
2597 && req->query->which == Z_Query_type_104
2598 && req->query->u.type_104->which == Z_External_CQL)
2600 /* have a CQL query and a CQL to PQF transform .. */
2602 cql2pqf(bsrr->stream, req->query->u.type_104->u.cql,
2603 assoc->server->cql_transform, bsrr->query);
2605 bsrr->errcode = yaz_diag_srw_to_bib1(srw_errcode);
2608 if (assoc->server && assoc->server->ccl_transform
2609 && req->query->which == Z_Query_type_2) /*CCL*/
2611 /* have a CCL query and a CCL to PQF transform .. */
2613 ccl2pqf(bsrr->stream, req->query->u.type_2,
2614 assoc->server->ccl_transform, bsrr);
2616 bsrr->errcode = yaz_diag_srw_to_bib1(srw_errcode);
2620 (assoc->init->bend_search)(assoc->backend, bsrr);
2624 /* FIXME - make a diagnostic for it */
2625 yaz_log(YLOG_WARN,"Search not supported ?!?!");
2627 return response_searchRequest(assoc, reqb, bsrr);
2631 * Prepare a searchresponse based on the backend results. We probably want
2632 * to look at making the fetching of records nonblocking as well, but
2633 * so far, we'll keep things simple.
2634 * If bsrt is null, that means we're called in response to a communications
2635 * event, and we'll have to get the response for ourselves.
2637 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
2638 bend_search_rr *bsrt)
2640 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2641 Z_APDU *apdu = (Z_APDU *)odr_malloc(assoc->encode, sizeof(*apdu));
2642 Z_SearchResponse *resp = (Z_SearchResponse *)
2643 odr_malloc(assoc->encode, sizeof(*resp));
2644 Odr_int *nulint = odr_intdup(assoc->encode, 0);
2645 Odr_int *next = odr_intdup(assoc->encode, 0);
2646 Odr_int *none = odr_intdup(assoc->encode, Z_SearchResponse_none);
2647 int returnedrecs = 0;
2649 apdu->which = Z_APDU_searchResponse;
2650 apdu->u.searchResponse = resp;
2651 resp->referenceId = req->referenceId;
2652 resp->additionalSearchInfo = 0;
2653 resp->otherInfo = 0;
2656 yaz_log(YLOG_FATAL, "Bad result from backend");
2659 else if (bsrt->errcode)
2661 resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
2662 resp->resultCount = nulint;
2663 resp->numberOfRecordsReturned = nulint;
2664 resp->nextResultSetPosition = nulint;
2665 resp->searchStatus = odr_booldup(assoc->encode, 0);
2666 resp->resultSetStatus = none;
2667 resp->presentStatus = 0;
2671 bool_t *sr = odr_booldup(assoc->encode, 1);
2672 Odr_int *toget = odr_intdup(assoc->encode, 0);
2673 Z_RecordComposition comp, *compp = 0;
2675 yaz_log(log_requestdetail, "resultCount: " ODR_INT_PRINTF, bsrt->hits);
2678 resp->resultCount = &bsrt->hits;
2680 comp.which = Z_RecordComp_simple;
2681 /* how many records does the user agent want, then? */
2684 else if (bsrt->hits <= *req->smallSetUpperBound)
2686 *toget = bsrt->hits;
2687 if ((comp.u.simple = req->smallSetElementSetNames))
2690 else if (bsrt->hits < *req->largeSetLowerBound)
2692 *toget = *req->mediumSetPresentNumber;
2693 if (*toget > bsrt->hits)
2694 *toget = bsrt->hits;
2695 if ((comp.u.simple = req->mediumSetElementSetNames))
2701 if (*toget && !resp->records)
2703 Odr_int *presst = odr_intdup(assoc->encode, 0);
2704 /* Call bend_present if defined */
2705 if (assoc->init->bend_present)
2707 bend_present_rr *bprr = (bend_present_rr *)
2708 nmem_malloc(reqb->request_mem, sizeof(*bprr));
2709 bprr->setname = req->resultSetName;
2711 bprr->number = *toget;
2712 bprr->format = req->preferredRecordSyntax;
2714 bprr->referenceId = req->referenceId;
2715 bprr->stream = assoc->encode;
2716 bprr->print = assoc->print;
2717 bprr->association = assoc;
2719 bprr->errstring = NULL;
2720 (*assoc->init->bend_present)(assoc->backend, bprr);
2724 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2725 *resp->presentStatus = Z_PresentStatus_failure;
2730 resp->records = pack_records(
2731 assoc, req->resultSetName, 1,
2732 toget, compp, next, presst, req->referenceId,
2733 req->preferredRecordSyntax, NULL);
2736 resp->numberOfRecordsReturned = toget;
2737 returnedrecs = *toget;
2738 resp->presentStatus = presst;
2742 if (*resp->resultCount)
2744 resp->numberOfRecordsReturned = nulint;
2745 resp->presentStatus = 0;
2747 resp->nextResultSetPosition = next;
2748 resp->searchStatus = sr;
2749 resp->resultSetStatus = 0;
2750 if (bsrt->estimated_hit_count)
2752 resp->resultSetStatus = odr_intdup(assoc->encode,
2753 Z_SearchResponse_estimate);
2755 else if (bsrt->partial_resultset)
2757 resp->resultSetStatus = odr_intdup(assoc->encode,
2758 Z_SearchResponse_subset);
2761 resp->additionalSearchInfo = bsrt->search_info;
2766 WRBUF wr = wrbuf_alloc();
2768 for (i = 0 ; i < req->num_databaseNames; i++)
2771 wrbuf_printf(wr, "+");
2772 wrbuf_puts(wr, req->databaseNames[i]);
2774 wrbuf_printf(wr, " ");
2777 wrbuf_printf(wr, "ERROR %d", bsrt->errcode);
2779 wrbuf_printf(wr, "OK " ODR_INT_PRINTF, bsrt->hits);
2780 wrbuf_printf(wr, " %s 1+%d ",
2781 req->resultSetName, returnedrecs);
2782 yaz_query_to_wrbuf(wr, req->query);
2784 yaz_log(log_request, "Search %s", wrbuf_cstr(wr));
2791 * Maybe we got a little over-friendly when we designed bend_fetch to
2792 * get only one record at a time. Some backends can optimise multiple-record
2793 * fetches, and at any rate, there is some overhead involved in
2794 * all that selecting and hopping around. Problem is, of course, that the
2795 * frontend can't know ahead of time how many records it'll need to
2796 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
2797 * is downright lousy as a bulk data transfer protocol.
2799 * To start with, we'll do the fetching of records from the backend
2800 * in one operation: To save some trips in and out of the event-handler,
2801 * and to simplify the interface to pack_records. At any rate, asynch
2802 * operation is more fun in operations that have an unpredictable execution
2803 * speed - which is normally more true for search than for present.
2805 static Z_APDU *process_presentRequest(association *assoc, request *reqb)
2807 Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
2809 Z_PresentResponse *resp;
2813 const char *errstring = 0;
2815 yaz_log(log_requestdetail, "Got PresentRequest.");
2817 resp = (Z_PresentResponse *)odr_malloc(assoc->encode, sizeof(*resp));
2819 resp->presentStatus = odr_intdup(assoc->encode, 0);
2820 if (assoc->init->bend_present)
2822 bend_present_rr *bprr = (bend_present_rr *)
2823 nmem_malloc(reqb->request_mem, sizeof(*bprr));
2824 bprr->setname = req->resultSetId;
2825 bprr->start = *req->resultSetStartPoint;
2826 bprr->number = *req->numberOfRecordsRequested;
2827 bprr->format = req->preferredRecordSyntax;
2828 bprr->comp = req->recordComposition;
2829 bprr->referenceId = req->referenceId;
2830 bprr->stream = assoc->encode;
2831 bprr->print = assoc->print;
2832 bprr->association = assoc;
2834 bprr->errstring = NULL;
2835 (*assoc->init->bend_present)(assoc->backend, bprr);
2839 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2840 *resp->presentStatus = Z_PresentStatus_failure;
2841 errcode = bprr->errcode;
2842 errstring = bprr->errstring;
2845 apdu = (Z_APDU *)odr_malloc(assoc->encode, sizeof(*apdu));
2846 next = odr_intdup(assoc->encode, 0);
2847 num = odr_intdup(assoc->encode, 0);
2849 apdu->which = Z_APDU_presentResponse;
2850 apdu->u.presentResponse = resp;
2851 resp->referenceId = req->referenceId;
2852 resp->otherInfo = 0;
2856 *num = *req->numberOfRecordsRequested;
2858 pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
2859 num, req->recordComposition, next,
2860 resp->presentStatus,
2861 req->referenceId, req->preferredRecordSyntax,
2866 WRBUF wr = wrbuf_alloc();
2867 wrbuf_printf(wr, "Present ");
2869 if (*resp->presentStatus == Z_PresentStatus_failure)
2870 wrbuf_printf(wr, "ERROR %d ", errcode);
2871 else if (*resp->presentStatus == Z_PresentStatus_success)
2872 wrbuf_printf(wr, "OK - ");
2874 wrbuf_printf(wr, "Partial " ODR_INT_PRINTF " - ",
2875 *resp->presentStatus);
2877 wrbuf_printf(wr, " %s " ODR_INT_PRINTF "+" ODR_INT_PRINTF " ",
2878 req->resultSetId, *req->resultSetStartPoint,
2879 *req->numberOfRecordsRequested);
2880 yaz_log(log_request, "%s", wrbuf_cstr(wr) );
2885 resp->numberOfRecordsReturned = num;
2886 resp->nextResultSetPosition = next;
2892 * Scan was implemented rather in a hurry, and with support for only the basic
2893 * elements of the service in the backend API. Suggestions are welcome.
2895 static Z_APDU *process_scanRequest(association *assoc, request *reqb)
2897 Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
2898 Z_APDU *apdu = (Z_APDU *)odr_malloc(assoc->encode, sizeof(*apdu));
2899 Z_ScanResponse *res = (Z_ScanResponse *)
2900 odr_malloc(assoc->encode, sizeof(*res));
2901 Odr_int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
2902 Odr_int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
2903 Z_ListEntries *ents = (Z_ListEntries *)
2904 odr_malloc(assoc->encode, sizeof(*ents));
2905 Z_DiagRecs *diagrecs_p = NULL;
2906 bend_scan_rr *bsrr = (bend_scan_rr *)
2907 odr_malloc(assoc->encode, sizeof(*bsrr));
2908 struct scan_entry *save_entries;
2910 yaz_log(log_requestdetail, "Got ScanRequest");
2912 apdu->which = Z_APDU_scanResponse;
2913 apdu->u.scanResponse = res;
2914 res->referenceId = req->referenceId;
2916 /* if step is absent, set it to 0 */
2917 res->stepSize = odr_intdup(assoc->encode, 0);
2919 *res->stepSize = *req->stepSize;
2921 res->scanStatus = scanStatus;
2922 res->numberOfEntriesReturned = numberOfEntriesReturned;
2923 res->positionOfTerm = 0;
2924 res->entries = ents;
2925 ents->num_entries = 0;
2926 ents->entries = NULL;
2927 ents->num_nonsurrogateDiagnostics = 0;
2928 ents->nonsurrogateDiagnostics = NULL;
2929 res->attributeSet = 0;
2932 if (req->databaseNames)
2935 for (i = 0; i < req->num_databaseNames; i++)
2936 yaz_log(log_requestdetail, "Database '%s'", req->databaseNames[i]);
2938 bsrr->scanClause = 0;
2940 bsrr->errstring = 0;
2941 bsrr->num_bases = req->num_databaseNames;
2942 bsrr->basenames = req->databaseNames;
2943 bsrr->num_entries = *req->numberOfTermsRequested;
2944 bsrr->term = req->termListAndStartPoint;
2945 bsrr->referenceId = req->referenceId;
2946 bsrr->stream = assoc->encode;
2947 bsrr->print = assoc->print;
2948 bsrr->step_size = res->stepSize;
2949 bsrr->setname = yaz_oi_get_string_oid(&req->otherInfo,
2950 yaz_oid_userinfo_scan_set, 1, 0);
2952 /* For YAZ 2.0 and earlier it was the backend handler that
2953 initialized entries (member display_term did not exist)
2954 YAZ 2.0 and later sets 'entries' and initialize all members
2955 including 'display_term'. If YAZ 2.0 or later sees that
2956 entries was modified - we assume that it is an old handler and
2957 that 'display_term' is _not_ set.
2959 if (bsrr->num_entries > 0)
2962 bsrr->entries = (struct scan_entry *)
2963 odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
2965 for (i = 0; i<bsrr->num_entries; i++)
2967 bsrr->entries[i].term = 0;
2968 bsrr->entries[i].occurrences = 0;
2969 bsrr->entries[i].errcode = 0;
2970 bsrr->entries[i].errstring = 0;
2971 bsrr->entries[i].display_term = 0;
2974 save_entries = bsrr->entries; /* save it so we can compare later */
2976 bsrr->attributeset = req->attributeSet;
2977 log_scan_term_level(log_requestdetail, req->termListAndStartPoint,
2978 bsrr->attributeset);
2979 bsrr->term_position = req->preferredPositionInResponse ?
2980 *req->preferredPositionInResponse : 1;
2982 ((int (*)(void *, bend_scan_rr *))
2983 (*assoc->init->bend_scan))(assoc->backend, bsrr);
2986 diagrecs_p = zget_DiagRecs(assoc->encode,
2987 bsrr->errcode, bsrr->errstring);
2991 Z_Entry **tab = (Z_Entry **)
2992 odr_malloc(assoc->encode, sizeof(*tab) * bsrr->num_entries);
2994 if (bsrr->status == BEND_SCAN_PARTIAL)
2995 *scanStatus = Z_Scan_partial_5;
2997 *scanStatus = Z_Scan_success;
2998 ents->entries = tab;
2999 ents->num_entries = bsrr->num_entries;
3000 res->numberOfEntriesReturned = odr_intdup(assoc->encode,
3002 res->positionOfTerm = &bsrr->term_position;
3003 for (i = 0; i < bsrr->num_entries; i++)
3009 tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
3010 if (bsrr->entries[i].occurrences >= 0)
3012 e->which = Z_Entry_termInfo;
3013 e->u.termInfo = t = (Z_TermInfo *)
3014 odr_malloc(assoc->encode, sizeof(*t));
3015 t->suggestedAttributes = 0;
3017 if (save_entries == bsrr->entries &&
3018 bsrr->entries[i].display_term)
3020 /* the entries was _not_ set by the handler. So it's
3021 safe to test for new member display_term. It is
3024 t->displayTerm = odr_strdup(assoc->encode,
3025 bsrr->entries[i].display_term);
3027 t->alternativeTerm = 0;
3028 t->byAttributes = 0;
3029 t->otherTermInfo = 0;
3030 t->globalOccurrences = &bsrr->entries[i].occurrences;
3031 t->term = (Z_Term *)
3032 odr_malloc(assoc->encode, sizeof(*t->term));
3033 t->term->which = Z_Term_general;
3034 t->term->u.general = o =
3035 (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
3036 o->buf = (unsigned char *)
3037 odr_malloc(assoc->encode, o->len = o->size =
3038 strlen(bsrr->entries[i].term));
3039 memcpy(o->buf, bsrr->entries[i].term, o->len);
3040 yaz_log(YLOG_DEBUG, " term #%d: '%s' (" ODR_INT_PRINTF ")", i,
3041 bsrr->entries[i].term, bsrr->entries[i].occurrences);
3045 Z_DiagRecs *drecs = zget_DiagRecs(assoc->encode,
3046 bsrr->entries[i].errcode,
3047 bsrr->entries[i].errstring);
3048 assert(drecs->num_diagRecs == 1);
3049 e->which = Z_Entry_surrogateDiagnostic;
3050 assert(drecs->diagRecs[0]);
3051 e->u.surrogateDiagnostic = drecs->diagRecs[0];
3057 ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
3058 ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
3063 WRBUF wr = wrbuf_alloc();
3064 wrbuf_printf(wr, "Scan ");
3065 for (i = 0 ; i < req->num_databaseNames; i++)
3068 wrbuf_printf(wr, "+");
3069 wrbuf_puts(wr, req->databaseNames[i]);
3072 wrbuf_printf(wr, " ");
3075 wr_diag(wr, bsrr->errcode, bsrr->errstring);
3077 wrbuf_printf(wr, "OK");
3079 wrbuf_printf(wr, " " ODR_INT_PRINTF " - " ODR_INT_PRINTF "+"
3080 ODR_INT_PRINTF "+" ODR_INT_PRINTF,
3081 res->numberOfEntriesReturned ?
3082 *res->numberOfEntriesReturned : 0,
3083 (req->preferredPositionInResponse ?
3084 *req->preferredPositionInResponse : 1),
3085 *req->numberOfTermsRequested,
3086 (res->stepSize ? *res->stepSize : 1));
3089 wrbuf_printf(wr, "+%s", bsrr->setname);
3091 wrbuf_printf(wr, " ");
3092 yaz_scan_to_wrbuf(wr, req->termListAndStartPoint,
3093 bsrr->attributeset);
3094 yaz_log(log_request, "%s", wrbuf_cstr(wr) );
3100 static Z_APDU *process_sortRequest(association *assoc, request *reqb)
3103 Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
3104 Z_SortResponse *res = (Z_SortResponse *)
3105 odr_malloc(assoc->encode, sizeof(*res));
3106 bend_sort_rr *bsrr = (bend_sort_rr *)
3107 odr_malloc(assoc->encode, sizeof(*bsrr));
3109 Z_APDU *apdu = (Z_APDU *)odr_malloc(assoc->encode, sizeof(*apdu));
3111 yaz_log(log_requestdetail, "Got SortRequest.");
3113 bsrr->num_input_setnames = req->num_inputResultSetNames;
3114 for (i=0;i<req->num_inputResultSetNames;i++)
3115 yaz_log(log_requestdetail, "Input resultset: '%s'",
3116 req->inputResultSetNames[i]);
3117 bsrr->input_setnames = req->inputResultSetNames;
3118 bsrr->referenceId = req->referenceId;
3119 bsrr->output_setname = req->sortedResultSetName;
3120 yaz_log(log_requestdetail, "Output resultset: '%s'",
3121 req->sortedResultSetName);
3122 bsrr->sort_sequence = req->sortSequence;
3123 /*FIXME - dump those sequences too */
3124 bsrr->stream = assoc->encode;
3125 bsrr->print = assoc->print;
3127 bsrr->sort_status = Z_SortResponse_failure;
3129 bsrr->errstring = 0;
3131 (*assoc->init->bend_sort)(assoc->backend, bsrr);
3133 res->referenceId = bsrr->referenceId;
3134 res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
3135 res->resultSetStatus = 0;
3138 Z_DiagRecs *dr = zget_DiagRecs(assoc->encode,
3139 bsrr->errcode, bsrr->errstring);
3140 res->diagnostics = dr->diagRecs;
3141 res->num_diagnostics = dr->num_diagRecs;
3145 res->num_diagnostics = 0;
3146 res->diagnostics = 0;
3148 res->resultCount = 0;
3151 apdu->which = Z_APDU_sortResponse;
3152 apdu->u.sortResponse = res;
3155 WRBUF wr = wrbuf_alloc();
3156 wrbuf_printf(wr, "Sort ");
3158 wrbuf_printf(wr, " ERROR %d", bsrr->errcode);
3160 wrbuf_printf(wr, "OK -");
3161 wrbuf_printf(wr, " (");
3162 for (i = 0; i<req->num_inputResultSetNames; i++)
3165 wrbuf_printf(wr, "+");
3166 wrbuf_puts(wr, req->inputResultSetNames[i]);
3168 wrbuf_printf(wr, ")->%s ",req->sortedResultSetName);
3170 yaz_log(log_request, "%s", wrbuf_cstr(wr) );
3176 static Z_APDU *process_deleteRequest(association *assoc, request *reqb)
3179 Z_DeleteResultSetRequest *req =
3180 reqb->apdu_request->u.deleteResultSetRequest;
3181 Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
3182 odr_malloc(assoc->encode, sizeof(*res));
3183 bend_delete_rr *bdrr = (bend_delete_rr *)
3184 odr_malloc(assoc->encode, sizeof(*bdrr));
3185 Z_APDU *apdu = (Z_APDU *)odr_malloc(assoc->encode, sizeof(*apdu));
3187 yaz_log(log_requestdetail, "Got DeleteRequest.");
3189 bdrr->num_setnames = req->num_resultSetList;
3190 bdrr->setnames = req->resultSetList;
3191 for (i = 0; i<req->num_resultSetList; i++)
3192 yaz_log(log_requestdetail, "resultset: '%s'",
3193 req->resultSetList[i]);
3194 bdrr->stream = assoc->encode;
3195 bdrr->print = assoc->print;
3196 bdrr->function = *req->deleteFunction;
3197 bdrr->referenceId = req->referenceId;
3199 if (bdrr->num_setnames > 0)
3201 bdrr->statuses = (Odr_int*)
3202 odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
3203 bdrr->num_setnames);
3204 for (i = 0; i < bdrr->num_setnames; i++)
3205 bdrr->statuses[i] = 0;
3207 (*assoc->init->bend_delete)(assoc->backend, bdrr);
3209 res->referenceId = req->referenceId;
3211 res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
3213 res->deleteListStatuses = 0;
3214 if (bdrr->num_setnames > 0)
3217 res->deleteListStatuses = (Z_ListStatuses *)
3218 odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
3219 res->deleteListStatuses->num = bdrr->num_setnames;
3220 res->deleteListStatuses->elements =
3222 odr_malloc(assoc->encode,
3223 sizeof(*res->deleteListStatuses->elements) *
3224 bdrr->num_setnames);
3225 for (i = 0; i<bdrr->num_setnames; i++)
3227 res->deleteListStatuses->elements[i] =
3229 odr_malloc(assoc->encode,
3230 sizeof(**res->deleteListStatuses->elements));
3231 res->deleteListStatuses->elements[i]->status = bdrr->statuses+i;
3232 res->deleteListStatuses->elements[i]->id =
3233 odr_strdup(assoc->encode, bdrr->setnames[i]);
3236 res->numberNotDeleted = 0;
3237 res->bulkStatuses = 0;
3238 res->deleteMessage = 0;
3241 apdu->which = Z_APDU_deleteResultSetResponse;
3242 apdu->u.deleteResultSetResponse = res;
3245 WRBUF wr = wrbuf_alloc();
3246 wrbuf_printf(wr, "Delete ");
3247 if (bdrr->delete_status)
3248 wrbuf_printf(wr, "ERROR %d", bdrr->delete_status);
3250 wrbuf_printf(wr, "OK -");
3251 for (i = 0; i<req->num_resultSetList; i++)
3252 wrbuf_printf(wr, " %s ", req->resultSetList[i]);
3253 yaz_log(log_request, "%s", wrbuf_cstr(wr) );
3259 static void process_close(association *assoc, request *reqb)
3261 Z_Close *req = reqb->apdu_request->u.close;
3262 static char *reasons[] =
3269 "securityViolation",
3276 yaz_log(log_requestdetail, "Got Close, reason %s, message %s",
3277 reasons[*req->closeReason], req->diagnosticInformation ?
3278 req->diagnosticInformation : "NULL");
3279 if (assoc->version < 3) /* to make do_force respond with close */
3281 do_close_req(assoc, Z_Close_finished,
3282 "Association terminated by client", reqb);
3283 yaz_log(log_request,"Close OK");
3286 static Z_APDU *process_segmentRequest(association *assoc, request *reqb)
3288 bend_segment_rr req;
3290 req.segment = reqb->apdu_request->u.segmentRequest;
3291 req.stream = assoc->encode;
3292 req.decode = assoc->decode;
3293 req.print = assoc->print;
3294 req.association = assoc;
3296 (*assoc->init->bend_segment)(assoc->backend, &req);
3301 static Z_APDU *process_ESRequest(association *assoc, request *reqb)
3303 bend_esrequest_rr esrequest;
3304 const char *ext_name = "unknown";
3306 Z_ExtendedServicesRequest *req =
3307 reqb->apdu_request->u.extendedServicesRequest;
3308 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
3310 Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
3312 esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
3313 esrequest.stream = assoc->encode;
3314 esrequest.decode = assoc->decode;
3315 esrequest.print = assoc->print;
3316 esrequest.errcode = 0;
3317 esrequest.errstring = NULL;
3318 esrequest.association = assoc;
3319 esrequest.taskPackage = 0;
3320 esrequest.referenceId = req->referenceId;
3322 if (esrequest.esr && esrequest.esr->taskSpecificParameters)
3324 switch(esrequest.esr->taskSpecificParameters->which)
3326 case Z_External_itemOrder:
3327 ext_name = "ItemOrder"; break;
3328 case Z_External_update:
3329 ext_name = "Update"; break;
3330 case Z_External_update0:
3331 ext_name = "Update0"; break;
3332 case Z_External_ESAdmin:
3333 ext_name = "Admin"; break;
3338 (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
3340 resp->referenceId = req->referenceId;
3342 if (esrequest.errcode == -1)
3344 /* Backend service indicates request will be processed */
3345 yaz_log(log_request, "Extended Service: %s (accepted)", ext_name);
3346 *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
3348 else if (esrequest.errcode == 0)
3350 /* Backend service indicates request will be processed */
3351 yaz_log(log_request, "Extended Service: %s (done)", ext_name);
3352 *resp->operationStatus = Z_ExtendedServicesResponse_done;
3356 Z_DiagRecs *diagRecs =
3357 zget_DiagRecs(assoc->encode, esrequest.errcode,
3358 esrequest.errstring);
3359 /* Backend indicates error, request will not be processed */
3360 yaz_log(log_request, "Extended Service: %s (failed)", ext_name);
3361 *resp->operationStatus = Z_ExtendedServicesResponse_failure;
3362 resp->num_diagnostics = diagRecs->num_diagRecs;
3363 resp->diagnostics = diagRecs->diagRecs;
3366 WRBUF wr = wrbuf_alloc();
3367 wrbuf_diags(wr, resp->num_diagnostics, resp->diagnostics);
3368 yaz_log(log_request, "EsRequest %s", wrbuf_cstr(wr) );
3373 /* Do something with the members of bend_extendedservice */
3374 if (esrequest.taskPackage)
3376 resp->taskPackage = z_ext_record_oid(
3377 assoc->encode, yaz_oid_recsyn_extended,
3378 (const char *) esrequest.taskPackage, -1);
3380 yaz_log(YLOG_DEBUG,"Send the result apdu");
3384 int bend_assoc_is_alive(bend_association assoc)
3386 if (assoc->state == ASSOC_DEAD)
3387 return 0; /* already marked as dead. Don't check I/O chan anymore */
3389 return iochan_is_alive(assoc->client_chan);
3396 * c-file-style: "Stroustrup"
3397 * indent-tabs-mode: nil
3399 * vim: shiftwidth=4 tabstop=8 expandtab