1 /* This file is part of the YAZ toolkit.
2 * Copyright (C) Index Data
3 * See the file LICENSE for details.
7 * \brief Implements GFS session logic.
9 * Frontend server logic.
11 * This code receives incoming APDUs, and handles client requests by means
14 * Some of the code is getting quite involved, compared to simpler servers -
15 * primarily because it is asynchronous both in the communication with
16 * the user and the backend. We think the complexity will pay off in
17 * the form of greater flexibility when more asynchronous facilities
20 * Memory management has become somewhat involved. In the simple case, where
21 * only one PDU is pending at a time, it will simply reuse the same memory,
22 * once it has found its working size. When we enable multiple concurrent
23 * operations, perhaps even with multiple parallel calls to the backend, it
24 * will maintain a pool of buffers for encoding and decoding, trying to
25 * minimize memory allocation/deallocation during normal operation.
38 #include <sys/types.h>
46 #define S_ISREG(x) (x & _S_IFREG)
55 #include <libxml/parser.h>
56 #include <libxml/tree.h>
59 #include <yaz/facet.h>
60 #include <yaz/xmalloc.h>
61 #include <yaz/comstack.h>
65 #include <yaz/proto.h>
66 #include <yaz/oid_db.h>
68 #include <yaz/logrpn.h>
69 #include <yaz/querytowrbuf.h>
70 #include <yaz/statserv.h>
71 #include <yaz/diagbib1.h>
72 #include <yaz/charneg.h>
73 #include <yaz/otherinfo.h>
74 #include <yaz/yaz-util.h>
75 #include <yaz/pquery.h>
76 #include <yaz/oid_db.h>
77 #include <yaz/query-charset.h>
79 #include <yaz/backend.h>
80 #include <yaz/yaz-ccl.h>
82 static void process_gdu_request(association *assoc, request *req);
83 static int process_z_request(association *assoc, request *req, char **msg);
84 static int process_gdu_response(association *assoc, request *req, Z_GDU *res);
85 static int process_z_response(association *assoc, request *req, Z_APDU *res);
86 static Z_APDU *process_initRequest(association *assoc, request *reqb);
87 static Z_External *init_diagnostics(ODR odr, int errcode,
88 const char *errstring);
89 static Z_APDU *process_searchRequest(association *assoc, request *reqb);
90 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
91 bend_search_rr *bsrr);
92 static Z_APDU *process_presentRequest(association *assoc, request *reqb);
93 static Z_APDU *process_scanRequest(association *assoc, request *reqb);
94 static Z_APDU *process_sortRequest(association *assoc, request *reqb);
95 static void process_close(association *assoc, request *reqb);
96 static Z_APDU *process_deleteRequest(association *assoc, request *reqb);
97 static Z_APDU *process_segmentRequest(association *assoc, request *reqb);
98 static Z_APDU *process_ESRequest(association *assoc, request *reqb);
100 /* dynamic logging levels */
101 static int logbits_set = 0;
102 static int log_session = 0; /* one-line logs for session */
103 static int log_sessiondetail = 0; /* more detailed stuff */
104 static int log_request = 0; /* one-line logs for requests */
105 static int log_requestdetail = 0; /* more detailed stuff */
107 /** get_logbits sets global loglevel bits */
108 static void get_logbits(void)
109 { /* needs to be called after parsing cmd-line args that can set loglevels!*/
113 log_session = yaz_log_module_level("session");
114 log_sessiondetail = yaz_log_module_level("sessiondetail");
115 log_request = yaz_log_module_level("request");
116 log_requestdetail = yaz_log_module_level("requestdetail");
120 static void wr_diag(WRBUF w, int error, const char *addinfo)
122 wrbuf_printf(w, "ERROR %d+", error);
123 wrbuf_puts_replace_char(w, diagbib1_str(error), ' ', '_');
127 wrbuf_puts_replace_char(w, addinfo, ' ', '_');
132 static int odr_int_to_int(Odr_int v)
136 else if (v <= INT_MIN)
143 * Create and initialize a new association-handle.
144 * channel : iochannel for the current line.
145 * link : communications channel.
146 * Returns: 0 or a new association handle.
148 association *create_association(IOCHAN channel, COMSTACK link,
149 const char *apdufile)
155 if (!(anew = (association *)xmalloc(sizeof(*anew))))
159 anew->last_control = 0;
160 anew->client_chan = channel;
161 anew->client_link = link;
162 anew->cs_get_mask = 0;
163 anew->cs_put_mask = 0;
164 anew->cs_accept_mask = 0;
165 if (!(anew->decode = odr_createmem(ODR_DECODE)) ||
166 !(anew->encode = odr_createmem(ODR_ENCODE)))
168 if (apdufile && *apdufile)
172 if (!(anew->print = odr_createmem(ODR_PRINT)))
174 if (*apdufile == '@')
176 odr_setprint(anew->print, yaz_log_file());
178 else if (*apdufile != '-')
181 sprintf(filename, "%.200s.%ld", apdufile, (long)getpid());
182 if (!(f = fopen(filename, "w")))
184 yaz_log(YLOG_WARN|YLOG_ERRNO, "%s", filename);
187 setvbuf(f, 0, _IONBF, 0);
188 odr_setprint(anew->print, f);
193 anew->input_buffer = 0;
194 anew->input_buffer_len = 0;
196 anew->state = ASSOC_NEW;
197 request_initq(&anew->incoming);
198 request_initq(&anew->outgoing);
199 anew->proto = cs_getproto(link);
205 * Free association and release resources.
207 void destroy_association(association *h)
209 statserv_options_block *cb = statserv_getcontrol();
213 odr_destroy(h->decode);
214 odr_destroy(h->encode);
216 odr_destroy(h->print);
218 xfree(h->input_buffer);
220 (*cb->bend_close)(h->backend);
221 while ((req = request_deq(&h->incoming)))
222 request_release(req);
223 while ((req = request_deq(&h->outgoing)))
224 request_release(req);
225 request_delq(&h->incoming);
226 request_delq(&h->outgoing);
228 xmalloc_trav("session closed");
231 static void do_close_req(association *a, int reason, char *message,
234 Z_APDU *apdu = zget_APDU(a->encode, Z_APDU_close);
235 Z_Close *cls = apdu->u.close;
237 /* Purge request queue */
238 while (request_deq(&a->incoming));
239 while (request_deq(&a->outgoing));
242 yaz_log(log_requestdetail, "Sending Close PDU, reason=%d, message=%s",
243 reason, message ? message : "none");
244 *cls->closeReason = reason;
245 cls->diagnosticInformation = message;
246 process_z_response(a, req, apdu);
247 iochan_settimeout(a->client_chan, 20);
251 request_release(req);
252 yaz_log(log_requestdetail, "v2 client. No Close PDU");
253 iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
256 a->state = ASSOC_DEAD;
259 static void do_close(association *a, int reason, char *message)
261 request *req = request_get(&a->outgoing);
262 do_close_req(a, reason, message, req);
266 int ir_read(IOCHAN h, int event)
268 association *assoc = (association *)iochan_getdata(h);
269 COMSTACK conn = assoc->client_link;
272 if ((assoc->cs_put_mask & EVENT_INPUT) == 0 && (event & assoc->cs_get_mask))
274 /* We aren't speaking to this fellow */
275 if (assoc->state == ASSOC_DEAD)
277 yaz_log(log_session, "Connection closed - end of session");
279 destroy_association(assoc);
283 assoc->cs_get_mask = EVENT_INPUT;
287 int res = cs_get(conn, &assoc->input_buffer,
288 &assoc->input_buffer_len);
289 if (res < 0 && cs_errno(conn) == CSBUFSIZE)
291 yaz_log(log_session, "Connection error: %s res=%d",
292 cs_errmsg(cs_errno(conn)), res);
293 req = request_get(&assoc->incoming); /* get a new request */
294 do_close_req(assoc, Z_Close_protocolError,
295 "Incoming package too large", req);
300 assoc->state = ASSOC_DEAD;
301 yaz_log(log_session, "Connection closed by client");
304 else if (res == 1) /* incomplete read - wait for more */
306 if (conn->io_pending & CS_WANT_WRITE)
307 assoc->cs_get_mask |= EVENT_OUTPUT;
308 iochan_setflag(h, assoc->cs_get_mask);
311 /* we got a complete PDU. Let's decode it */
312 yaz_log(YLOG_DEBUG, "Got PDU, %d bytes: lead=%02X %02X %02X", res,
313 assoc->input_buffer[0] & 0xff,
314 assoc->input_buffer[1] & 0xff,
315 assoc->input_buffer[2] & 0xff);
316 req = request_get(&assoc->incoming); /* get a new request */
317 odr_reset(assoc->decode);
318 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
319 if (!z_GDU(assoc->decode, &req->gdu_request, 0, 0))
321 yaz_log(YLOG_WARN, "ODR error on incoming PDU: %s [element %s] "
323 odr_errmsg(odr_geterror(assoc->decode)),
324 odr_getelement(assoc->decode),
325 (long) odr_offset(assoc->decode));
326 if (assoc->decode->error != OHTTP)
328 yaz_log(YLOG_WARN, "PDU dump:");
329 odr_dumpBER(yaz_log_file(), assoc->input_buffer, res);
330 request_release(req);
331 do_close(assoc, Z_Close_protocolError, "Malformed package");
335 Z_GDU *p = z_get_HTTP_Response(assoc->encode, 400);
336 assoc->state = ASSOC_DEAD;
337 process_gdu_response(assoc, req, p);
341 req->request_mem = odr_extract_mem(assoc->decode);
344 if (!z_GDU(assoc->print, &req->gdu_request, 0, 0))
345 yaz_log(YLOG_WARN, "ODR print error: %s",
346 odr_errmsg(odr_geterror(assoc->print)));
347 odr_reset(assoc->print);
349 request_enq(&assoc->incoming, req);
351 while (cs_more(conn));
357 * This is where PDUs from the client are read and the further
358 * processing is initiated. Flow of control moves down through the
359 * various process_* functions below, until the encoded result comes back up
360 * to the output handler in here.
362 * h : the I/O channel that has an outstanding event.
363 * event : the current outstanding event.
365 void ir_session(IOCHAN h, int event)
368 association *assoc = (association *)iochan_getdata(h);
369 COMSTACK conn = assoc->client_link;
372 assert(h && conn && assoc);
373 if (event == EVENT_TIMEOUT)
375 if (assoc->state != ASSOC_UP)
377 yaz_log(log_session, "Timeout. Closing connection");
378 /* do we need to lod this at all */
380 destroy_association(assoc);
385 yaz_log(log_sessiondetail, "Timeout. Sending Z39.50 Close");
386 do_close(assoc, Z_Close_lackOfActivity, 0);
390 if (event & assoc->cs_accept_mask)
392 if (!cs_accept(conn))
394 yaz_log(YLOG_WARN, "accept failed");
395 destroy_association(assoc);
399 iochan_clearflag(h, EVENT_OUTPUT);
400 if (conn->io_pending)
401 { /* cs_accept didn't complete */
402 assoc->cs_accept_mask =
403 ((conn->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
404 ((conn->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
406 iochan_setflag(h, assoc->cs_accept_mask);
409 { /* cs_accept completed. Prepare for reading (cs_get) */
410 assoc->cs_accept_mask = 0;
411 assoc->cs_get_mask = EVENT_INPUT;
412 iochan_setflag(h, assoc->cs_get_mask);
416 if (event & assoc->cs_get_mask) /* input */
418 if (!ir_read(h, event))
420 req = request_head(&assoc->incoming);
421 if (req->state == REQUEST_IDLE)
423 request_deq(&assoc->incoming);
424 process_gdu_request(assoc, req);
427 if (event & assoc->cs_put_mask)
429 request *req = request_head(&assoc->outgoing);
431 assoc->cs_put_mask = 0;
432 yaz_log(YLOG_DEBUG, "ir_session (output)");
433 req->state = REQUEST_PENDING;
434 switch (res = cs_put(conn, req->response, req->len_response))
437 yaz_log(log_sessiondetail, "Connection closed by client");
439 destroy_association(assoc);
442 case 0: /* all sent - release the request structure */
443 yaz_log(YLOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
445 yaz_log(YLOG_DEBUG, "HTTP out:\n%.*s", req->len_response,
448 request_deq(&assoc->outgoing);
449 request_release(req);
450 if (!request_head(&assoc->outgoing))
451 { /* restore mask for cs_get operation ... */
452 iochan_clearflag(h, EVENT_OUTPUT|EVENT_INPUT);
453 iochan_setflag(h, assoc->cs_get_mask);
454 if (assoc->state == ASSOC_DEAD)
455 iochan_setevent(assoc->client_chan, EVENT_TIMEOUT);
459 assoc->cs_put_mask = EVENT_OUTPUT;
463 if (conn->io_pending & CS_WANT_WRITE)
464 assoc->cs_put_mask |= EVENT_OUTPUT;
465 if (conn->io_pending & CS_WANT_READ)
466 assoc->cs_put_mask |= EVENT_INPUT;
467 iochan_setflag(h, assoc->cs_put_mask);
470 if (event & EVENT_EXCEPT)
472 yaz_log(YLOG_WARN, "ir_session (exception)");
474 destroy_association(assoc);
479 static int process_z_request(association *assoc, request *req, char **msg);
482 static void assoc_init_reset(association *assoc, const char *peer_name1)
484 const char *peer_name2 = cs_addrstr(assoc->client_link);
487 assoc->init = (bend_initrequest *) xmalloc(sizeof(*assoc->init));
489 assoc->init->stream = assoc->encode;
490 assoc->init->print = assoc->print;
491 assoc->init->auth = 0;
492 assoc->init->referenceId = 0;
493 assoc->init->implementation_version = 0;
494 assoc->init->implementation_id = 0;
495 assoc->init->implementation_name = 0;
496 assoc->init->query_charset = 0;
497 assoc->init->records_in_same_charset = 0;
498 assoc->init->bend_sort = NULL;
499 assoc->init->bend_search = NULL;
500 assoc->init->bend_present = NULL;
501 assoc->init->bend_esrequest = NULL;
502 assoc->init->bend_delete = NULL;
503 assoc->init->bend_scan = NULL;
504 assoc->init->bend_segment = NULL;
505 assoc->init->bend_fetch = NULL;
506 assoc->init->bend_explain = NULL;
507 assoc->init->bend_srw_scan = NULL;
508 assoc->init->bend_srw_update = NULL;
509 assoc->init->named_result_sets = 0;
511 assoc->init->charneg_request = NULL;
512 assoc->init->charneg_response = NULL;
514 assoc->init->decode = assoc->decode;
516 assoc->init->peer_name = (char *)
517 odr_malloc(assoc->encode,
518 (peer_name1 ? strlen(peer_name1) : 0)
519 + 4 + strlen(peer_name2));
520 strcpy(assoc->init->peer_name, "");
523 strcat(assoc->init->peer_name, peer_name1);
524 strcat(assoc->init->peer_name, ", ");
526 strcat(assoc->init->peer_name, peer_name2);
528 yaz_log(log_requestdetail, "peer %s", assoc->init->peer_name);
531 static int srw_bend_init(association *assoc, Z_HTTP_Header *headers,
532 Z_SRW_diagnostic **d, int *num, Z_SRW_PDU *sr)
534 statserv_options_block *cb = statserv_getcontrol();
537 const char *encoding = "UTF-8";
539 bend_initresult *binitres;
541 yaz_log(log_requestdetail, "srw_bend_init config=%s", cb->configname);
542 assoc_init_reset(assoc, z_HTTP_header_lookup(headers, "X-Forwarded-For"));
546 Z_IdAuthentication *auth = (Z_IdAuthentication *)
547 odr_malloc(assoc->decode, sizeof(*auth));
550 len = strlen(sr->username) + 1;
552 len += strlen(sr->password) + 2;
553 yaz_log(log_requestdetail, "username=%s password-len=%ld",
555 (sr->password ? strlen(sr->password) : 0));
556 auth->which = Z_IdAuthentication_open;
557 auth->u.open = (char *) odr_malloc(assoc->decode, len);
558 strcpy(auth->u.open, sr->username);
559 if (sr->password && *sr->password)
561 strcat(auth->u.open, "/");
562 strcat(auth->u.open, sr->password);
564 assoc->init->auth = auth;
568 ce = yaz_set_proposal_charneg(assoc->decode, &encoding, 1, 0, 0, 1);
569 assoc->init->charneg_request = ce->u.charNeg3;
572 if (!(binitres = (*cb->bend_init)(assoc->init)))
574 assoc->state = ASSOC_DEAD;
575 yaz_add_srw_diagnostic(assoc->encode, d, num,
576 YAZ_SRW_AUTHENTICATION_ERROR, 0);
579 assoc->backend = binitres->handle;
580 assoc->init->auth = 0;
581 if (binitres->errcode)
583 int srw_code = yaz_diag_bib1_to_srw(binitres->errcode);
584 assoc->state = ASSOC_DEAD;
585 yaz_add_srw_diagnostic(assoc->encode, d, num, srw_code,
586 binitres->errstring);
594 static int retrieve_fetch(association *assoc, bend_fetch_rr *rr)
597 yaz_record_conv_t rc = 0;
598 const char *match_schema = 0;
599 Odr_oid *match_syntax = 0;
604 const char *input_schema = yaz_get_esn(rr->comp);
605 Odr_oid *input_syntax_raw = rr->request_format;
607 const char *backend_schema = 0;
608 Odr_oid *backend_syntax = 0;
610 r = yaz_retrieval_request(assoc->server->retrieval,
618 if (r == -1) /* error ? */
620 const char *details = yaz_retrieval_get_error(
621 assoc->server->retrieval);
623 rr->errcode = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
625 rr->errstring = odr_strdup(rr->stream, details);
628 else if (r == 1 || r == 3)
630 const char *details = input_schema;
632 YAZ_BIB1_SPECIFIED_ELEMENT_SET_NAME_NOT_VALID_FOR_SPECIFIED_;
634 rr->errstring = odr_strdup(rr->stream, details);
639 rr->errcode = YAZ_BIB1_RECORD_SYNTAX_UNSUPP;
640 if (input_syntax_raw)
642 char oidbuf[OID_STR_MAX];
643 oid_oid_to_dotstring(input_syntax_raw, oidbuf);
644 rr->errstring = odr_strdup(rr->stream, oidbuf);
650 yaz_set_esn(&rr->comp, backend_schema, odr_getmem(rr->stream));
653 rr->request_format = backend_syntax;
655 (*assoc->init->bend_fetch)(assoc->backend, rr);
656 if (rc && rr->record && rr->errcode == 0)
657 { /* post conversion must take place .. */
658 WRBUF output_record = wrbuf_alloc();
660 const char *details = 0;
663 r = yaz_record_conv_record(rc, rr->record, rr->len, output_record);
665 details = yaz_record_conv_get_error(rc);
667 else if (rr->len == -1 && rr->output_format &&
668 !oid_oidcmp(rr->output_format, yaz_oid_recsyn_opac))
670 r = yaz_record_conv_opac_record(
671 rc, (Z_OPACRecord *) rr->record, output_record);
673 details = yaz_record_conv_get_error(rc);
675 if (r == 0 && match_syntax &&
676 !oid_oidcmp(match_syntax, yaz_oid_recsyn_opac))
678 yaz_marc_t mt = yaz_marc_create();
679 Z_OPACRecord *opac = 0;
680 if (yaz_xml_to_opac(mt, wrbuf_buf(output_record),
681 wrbuf_len(output_record),
682 &opac, 0 /* iconv */, rr->stream->mem, 0)
686 rr->record = (char *) opac;
690 details = "XML to OPAC conversion failed";
693 yaz_marc_destroy(mt);
697 rr->len = wrbuf_len(output_record);
698 rr->record = (char *) odr_malloc(rr->stream, rr->len);
699 memcpy(rr->record, wrbuf_buf(output_record), rr->len);
703 rr->errcode = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
704 rr->surrogate_flag = 1;
706 rr->errstring = odr_strdup(rr->stream, details);
708 wrbuf_destroy(output_record);
711 rr->output_format = match_syntax;
713 rr->schema = odr_strdup(rr->stream, match_schema);
715 (*assoc->init->bend_fetch)(assoc->backend, rr);
720 static int srw_bend_fetch(association *assoc, int pos,
721 Z_SRW_searchRetrieveRequest *srw_req,
722 Z_SRW_record *record,
723 const char **addinfo, int *last_in_set)
726 ODR o = assoc->encode;
728 rr.setname = "default";
731 rr.request_format = odr_oiddup(assoc->decode, yaz_oid_recsyn_xml);
733 rr.comp = (Z_RecordComposition *)
734 odr_malloc(assoc->decode, sizeof(*rr.comp));
735 rr.comp->which = Z_RecordComp_complex;
736 rr.comp->u.complex = (Z_CompSpec *)
737 odr_malloc(assoc->decode, sizeof(Z_CompSpec));
738 rr.comp->u.complex->selectAlternativeSyntax = (bool_t *)
739 odr_malloc(assoc->encode, sizeof(bool_t));
740 *rr.comp->u.complex->selectAlternativeSyntax = 0;
741 rr.comp->u.complex->num_dbSpecific = 0;
742 rr.comp->u.complex->dbSpecific = 0;
743 rr.comp->u.complex->num_recordSyntax = 0;
744 rr.comp->u.complex->recordSyntax = 0;
746 rr.comp->u.complex->generic = (Z_Specification *)
747 odr_malloc(assoc->decode, sizeof(Z_Specification));
749 /* schema uri = recordSchema (or NULL if recordSchema is not given) */
750 rr.comp->u.complex->generic->which = Z_Schema_uri;
751 rr.comp->u.complex->generic->schema.uri = srw_req->recordSchema;
753 /* ESN = recordSchema if recordSchema is present */
754 rr.comp->u.complex->generic->elementSpec = 0;
755 if (srw_req->recordSchema)
757 rr.comp->u.complex->generic->elementSpec =
758 (Z_ElementSpec *) odr_malloc(assoc->encode, sizeof(Z_ElementSpec));
759 rr.comp->u.complex->generic->elementSpec->which =
760 Z_ElementSpec_elementSetName;
761 rr.comp->u.complex->generic->elementSpec->u.elementSetName =
762 srw_req->recordSchema;
765 rr.stream = assoc->encode;
766 rr.print = assoc->print;
774 rr.surrogate_flag = 0;
775 rr.schema = srw_req->recordSchema;
777 if (!assoc->init->bend_fetch)
780 retrieve_fetch(assoc, &rr);
782 *last_in_set = rr.last_in_set;
784 if (rr.errcode && rr.surrogate_flag)
786 int code = yaz_diag_bib1_to_srw(rr.errcode);
787 yaz_mk_sru_surrogate(o, record, pos, code, rr.errstring);
790 else if (rr.len >= 0)
792 record->recordData_buf = rr.record;
793 record->recordData_len = rr.len;
794 record->recordPosition = odr_intdup(o, pos);
795 record->recordSchema = odr_strdup_null(
796 o, rr.schema ? rr.schema : srw_req->recordSchema);
800 *addinfo = rr.errstring;
806 static int cql2pqf(ODR odr, const char *cql, cql_transform_t ct,
807 Z_Query *query_result, char **sortkeys_p)
809 /* have a CQL query and CQL to PQF transform .. */
810 CQL_parser cp = cql_parser_create();
814 WRBUF rpn_buf = wrbuf_alloc();
817 r = cql_parser_string(cp, cql);
820 srw_errcode = YAZ_SRW_QUERY_SYNTAX_ERROR;
824 struct cql_node *cn = cql_parser_result(cp);
827 r = cql_transform(ct, cn, wrbuf_vp_puts, rpn_buf);
829 srw_errcode = cql_transform_error(ct, &add);
833 int r = cql_sortby_to_sortkeys_buf(cn, out, sizeof(out)-1);
838 yaz_log(log_requestdetail, "srw_sortKeys '%s'", out);
839 *sortkeys_p = odr_strdup(odr, out);
843 yaz_log(log_requestdetail, "failed to create srw_sortKeys");
844 srw_errcode = YAZ_SRW_UNSUPP_SORT_TYPE;
850 /* Syntax & transform OK. */
851 /* Convert PQF string to Z39.50 to RPN query struct */
852 YAZ_PQF_Parser pp = yaz_pqf_create();
853 Z_RPNQuery *rpnquery = yaz_pqf_parse(pp, odr, wrbuf_cstr(rpn_buf));
858 int code = yaz_pqf_error(pp, &pqf_msg, &off);
859 yaz_log(YLOG_WARN, "PQF Parser Error %s (code %d)",
861 srw_errcode = YAZ_SRW_QUERY_SYNTAX_ERROR;
865 query_result->which = Z_Query_type_1;
866 query_result->u.type_1 = rpnquery;
870 cql_parser_destroy(cp);
871 wrbuf_destroy(rpn_buf);
875 static int cql2pqf_scan(ODR odr, const char *cql, cql_transform_t ct,
876 Z_AttributesPlusTerm *result)
881 int srw_error = cql2pqf(odr, cql, ct, &query, &sortkeys);
884 if (query.which != Z_Query_type_1 && query.which != Z_Query_type_101)
885 return YAZ_SRW_QUERY_SYNTAX_ERROR; /* bad query type */
886 rpn = query.u.type_1;
887 if (!rpn->RPNStructure)
888 return YAZ_SRW_QUERY_SYNTAX_ERROR; /* must be structure */
889 if (rpn->RPNStructure->which != Z_RPNStructure_simple)
890 return YAZ_SRW_QUERY_SYNTAX_ERROR; /* must be simple */
891 if (rpn->RPNStructure->u.simple->which != Z_Operand_APT)
892 return YAZ_SRW_QUERY_SYNTAX_ERROR; /* must be be attributes + term */
893 memcpy(result, rpn->RPNStructure->u.simple->u.attributesPlusTerm,
899 static int ccl2pqf(ODR odr, const Odr_oct *ccl, CCL_bibset bibset,
900 bend_search_rr *bsrr)
903 struct ccl_rpn_node *node;
906 ccl0 = odr_strdupn(odr, (char*) ccl->buf, ccl->len);
907 if ((node = ccl_find_str(bibset, ccl0, &errcode, &pos)) == 0)
909 bsrr->errstring = (char*) ccl_err_msg(errcode);
910 return YAZ_SRW_QUERY_SYNTAX_ERROR; /* Query syntax error */
913 bsrr->query->which = Z_Query_type_1;
914 bsrr->query->u.type_1 = ccl_rpn_query(odr, node);
918 static void srw_bend_search(association *assoc,
919 Z_HTTP_Header *headers,
924 Z_SRW_searchRetrieveResponse *srw_res = res->u.response;
927 Z_SRW_searchRetrieveRequest *srw_req = sr->u.request;
930 yaz_log(log_requestdetail, "Got SRW SearchRetrieveRequest");
931 srw_bend_init(assoc, headers,
932 &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
933 if (srw_res->num_diagnostics == 0 && assoc->init)
936 rr.setname = "default";
939 rr.basenames = &srw_req->database;
943 rr.srw_setnameIdleTime = 0;
944 rr.estimated_hit_count = 0;
945 rr.partial_resultset = 0;
946 rr.query = (Z_Query *) odr_malloc(assoc->decode, sizeof(*rr.query));
947 rr.query->u.type_1 = 0;
948 rr.extra_args = sr->extra_args;
949 rr.extra_response_data = 0;
950 rr.present_number = srw_req->maximumRecords ?
951 *srw_req->maximumRecords : 0;
953 if (!srw_req->queryType || !strcmp(srw_req->queryType, "cql"))
955 if (assoc->server && assoc->server->cql_transform)
957 int srw_errcode = cql2pqf(assoc->encode, srw_req->query,
958 assoc->server->cql_transform,
964 yaz_add_srw_diagnostic(assoc->encode,
965 &srw_res->diagnostics,
966 &srw_res->num_diagnostics,
972 /* CQL query to backend. Wrap it - Z39.50 style */
973 ext = (Z_External *) odr_malloc(assoc->decode, sizeof(*ext));
974 ext->direct_reference = odr_getoidbystr(assoc->decode,
975 "1.2.840.10003.16.2");
976 ext->indirect_reference = 0;
978 ext->which = Z_External_CQL;
979 ext->u.cql = srw_req->query;
981 rr.query->which = Z_Query_type_104;
982 rr.query->u.type_104 = ext;
985 else if (!strcmp(srw_req->queryType, "pqf"))
987 Z_RPNQuery *RPNquery;
988 YAZ_PQF_Parser pqf_parser;
990 pqf_parser = yaz_pqf_create();
992 RPNquery = yaz_pqf_parse(pqf_parser, assoc->decode, srw_req->query);
997 int code = yaz_pqf_error(pqf_parser, &pqf_msg, &off);
998 yaz_log(log_requestdetail, "Parse error %d %s near offset %ld",
999 code, pqf_msg, (long) off);
1000 srw_error = YAZ_SRW_QUERY_SYNTAX_ERROR;
1003 rr.query->which = Z_Query_type_1;
1004 rr.query->u.type_1 = RPNquery;
1006 yaz_pqf_destroy(pqf_parser);
1010 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1011 &srw_res->num_diagnostics,
1012 YAZ_SRW_UNSUPP_QUERY_TYPE, 0);
1014 if (rr.query->u.type_1)
1016 rr.stream = assoc->encode;
1017 rr.decode = assoc->decode;
1018 rr.print = assoc->print;
1019 if (srw_req->sort.sortKeys)
1020 rr.srw_sortKeys = odr_strdup(assoc->encode,
1021 srw_req->sort.sortKeys);
1022 rr.association = assoc;
1027 rr.search_input = 0;
1029 if (srw_req->facetList)
1030 yaz_oi_set_facetlist(&rr.search_input, assoc->encode,
1031 srw_req->facetList);
1033 yaz_log_zquery_level(log_requestdetail,rr.query);
1035 (assoc->init->bend_search)(assoc->backend, &rr);
1038 if (rr.errcode == YAZ_BIB1_DATABASE_UNAVAILABLE)
1044 srw_error = yaz_diag_bib1_to_srw(rr.errcode);
1045 yaz_add_srw_diagnostic(assoc->encode,
1046 &srw_res->diagnostics,
1047 &srw_res->num_diagnostics,
1048 srw_error, rr.errstring);
1053 int number = srw_req->maximumRecords ?
1054 odr_int_to_int(*srw_req->maximumRecords) : 0;
1055 int start = srw_req->startRecord ?
1056 odr_int_to_int(*srw_req->startRecord) : 1;
1058 yaz_log(log_requestdetail, "Request to pack %d+%d out of "
1060 start, number, rr.hits);
1062 srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
1065 srw_res->resultSetId =
1066 odr_strdup(assoc->encode, rr.srw_setname );
1067 srw_res->resultSetIdleTime =
1068 odr_intdup(assoc->encode, *rr.srw_setnameIdleTime );
1071 srw_res->facetList = yaz_oi_get_facetlist(&rr.search_info);
1072 if (start > rr.hits || start < 1)
1074 /* if hits<=0 and start=1 we don't return a diagnostic */
1076 yaz_add_srw_diagnostic(
1078 &srw_res->diagnostics, &srw_res->num_diagnostics,
1079 YAZ_SRW_FIRST_RECORD_POSITION_OUT_OF_RANGE, 0);
1081 else if (number > 0)
1085 if (start + number > rr.hits)
1086 number = odr_int_to_int(rr.hits) - start + 1;
1088 /* Call bend_present if defined */
1089 if (assoc->init->bend_present)
1091 bend_present_rr *bprr = (bend_present_rr*)
1092 odr_malloc(assoc->decode, sizeof(*bprr));
1093 bprr->setname = "default";
1094 bprr->start = start;
1095 bprr->number = number;
1096 if (srw_req->recordSchema)
1098 bprr->comp = (Z_RecordComposition *) odr_malloc(assoc->decode,
1099 sizeof(*bprr->comp));
1100 bprr->comp->which = Z_RecordComp_simple;
1101 bprr->comp->u.simple = (Z_ElementSetNames *)
1102 odr_malloc(assoc->decode, sizeof(Z_ElementSetNames));
1103 bprr->comp->u.simple->which = Z_ElementSetNames_generic;
1104 bprr->comp->u.simple->u.generic = srw_req->recordSchema;
1110 bprr->stream = assoc->encode;
1111 bprr->referenceId = 0;
1112 bprr->print = assoc->print;
1113 bprr->association = assoc;
1115 bprr->errstring = NULL;
1116 (*assoc->init->bend_present)(assoc->backend, bprr);
1120 srw_error = yaz_diag_bib1_to_srw(bprr->errcode);
1121 yaz_add_srw_diagnostic(assoc->encode,
1122 &srw_res->diagnostics,
1123 &srw_res->num_diagnostics,
1124 srw_error, bprr->errstring);
1132 int packing = Z_SRW_recordPacking_string;
1133 if (srw_req->recordPacking)
1136 yaz_srw_str_to_pack(srw_req->recordPacking);
1138 packing = Z_SRW_recordPacking_string;
1140 srw_res->records = (Z_SRW_record *)
1141 odr_malloc(assoc->encode,
1142 number * sizeof(*srw_res->records));
1144 srw_res->extra_records = (Z_SRW_extra_record **)
1145 odr_malloc(assoc->encode,
1146 number*sizeof(*srw_res->extra_records));
1148 for (i = 0; i<number; i++)
1151 int last_in_set = 0;
1152 const char *addinfo = 0;
1154 srw_res->records[j].recordPacking = packing;
1155 srw_res->records[j].recordData_buf = 0;
1156 srw_res->extra_records[j] = 0;
1157 yaz_log(YLOG_DEBUG, "srw_bend_fetch %d", i+start);
1158 errcode = srw_bend_fetch(assoc, i+start, srw_req,
1159 srw_res->records + j,
1160 &addinfo, &last_in_set);
1163 yaz_add_srw_diagnostic(assoc->encode,
1164 &srw_res->diagnostics,
1165 &srw_res->num_diagnostics,
1166 yaz_diag_bib1_to_srw(errcode),
1171 if (srw_res->records[j].recordData_buf)
1176 srw_res->num_records = j;
1178 srw_res->records = 0;
1181 if (rr.extra_response_data)
1183 res->extraResponseData_buf = rr.extra_response_data;
1184 res->extraResponseData_len = strlen(rr.extra_response_data);
1186 if (strcmp(res->srw_version, "2.") > 0)
1188 if (rr.estimated_hit_count)
1189 srw_res->resultCountPrecision =
1190 odr_strdup(assoc->encode, "estimate");
1191 else if (rr.partial_resultset)
1192 srw_res->resultCountPrecision =
1193 odr_strdup(assoc->encode, "minimum");
1195 srw_res->resultCountPrecision =
1196 odr_strdup(assoc->encode, "exact");
1198 else if (rr.estimated_hit_count || rr.partial_resultset)
1200 yaz_add_srw_diagnostic(
1202 &srw_res->diagnostics,
1203 &srw_res->num_diagnostics,
1204 YAZ_SRW_RESULT_SET_CREATED_WITH_VALID_PARTIAL_RESULTS_AVAILABLE,
1212 WRBUF wr = wrbuf_alloc();
1214 wrbuf_printf(wr, "SRWSearch %s ", srw_req->database);
1215 if (srw_res->num_diagnostics)
1216 wrbuf_printf(wr, "ERROR %s", srw_res->diagnostics[0].uri);
1217 else if (*http_code != 200)
1218 wrbuf_printf(wr, "ERROR info:http/%d", *http_code);
1219 else if (srw_res->numberOfRecords)
1221 wrbuf_printf(wr, "OK " ODR_INT_PRINTF,
1222 (srw_res->numberOfRecords ?
1223 *srw_res->numberOfRecords : 0));
1225 wrbuf_printf(wr, " %s " ODR_INT_PRINTF "+%d",
1226 (srw_res->resultSetId ?
1227 srw_res->resultSetId : "-"),
1228 (srw_req->startRecord ? *srw_req->startRecord : 1),
1229 srw_res->num_records);
1230 yaz_log(log_request, "%s %s: %s", wrbuf_cstr(wr), srw_req->queryType,
1236 static char *srw_bend_explain_default(bend_explain_rr *rr)
1239 xmlNodePtr ptr = (xmlNode *) rr->server_node_ptr;
1242 for (ptr = ptr->children; ptr; ptr = ptr->next)
1244 if (ptr->type != XML_ELEMENT_NODE)
1246 if (!strcmp((const char *) ptr->name, "explain"))
1249 xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
1253 ptr = xmlCopyNode(ptr, 1);
1255 xmlDocSetRootElement(doc, ptr);
1257 xmlDocDumpMemory(doc, &buf_out, &len);
1258 content = (char*) odr_malloc(rr->stream, 1+len);
1259 memcpy(content, buf_out, len);
1260 content[len] = '\0';
1264 rr->explain_buf = content;
1272 static void srw_bend_explain(association *assoc,
1273 Z_HTTP_Header *headers,
1275 Z_SRW_explainResponse *srw_res,
1278 Z_SRW_explainRequest *srw_req = sr->u.explain_request;
1279 yaz_log(log_requestdetail, "Got SRW ExplainRequest");
1280 srw_bend_init(assoc, headers,
1281 &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1282 if (!assoc->init && srw_res->num_diagnostics == 0)
1288 rr.stream = assoc->encode;
1289 rr.decode = assoc->decode;
1290 rr.print = assoc->print;
1292 rr.database = srw_req->database;
1294 rr.server_node_ptr = assoc->server->server_node_ptr;
1296 rr.server_node_ptr = 0;
1297 rr.schema = "http://explain.z3950.org/dtd/2.0/";
1298 if (assoc->init->bend_explain)
1299 (*assoc->init->bend_explain)(assoc->backend, &rr);
1301 srw_bend_explain_default(&rr);
1305 int packing = Z_SRW_recordPacking_string;
1306 if (srw_req->recordPacking)
1309 yaz_srw_str_to_pack(srw_req->recordPacking);
1311 packing = Z_SRW_recordPacking_string;
1313 srw_res->record.recordSchema = rr.schema;
1314 srw_res->record.recordPacking = packing;
1315 srw_res->record.recordData_buf = rr.explain_buf;
1316 srw_res->record.recordData_len = strlen(rr.explain_buf);
1317 srw_res->record.recordPosition = 0;
1323 static void srw_bend_scan(association *assoc,
1324 Z_HTTP_Header *headers,
1329 Z_SRW_scanRequest *srw_req = sr->u.scan_request;
1330 Z_SRW_scanResponse *srw_res = res->u.scan_response;
1331 yaz_log(log_requestdetail, "Got SRW ScanRequest");
1334 srw_bend_init(assoc, headers,
1335 &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1336 if (srw_res->num_diagnostics == 0 && assoc->init)
1339 struct scan_entry *save_entries;
1341 bend_scan_rr *bsrr = (bend_scan_rr *)
1342 odr_malloc(assoc->encode, sizeof(*bsrr));
1343 bsrr->num_bases = 1;
1344 bsrr->basenames = &srw_req->database;
1346 bsrr->num_entries = srw_req->maximumTerms ?
1347 odr_int_to_int(*srw_req->maximumTerms) : 10;
1348 bsrr->term_position = srw_req->responsePosition ?
1349 odr_int_to_int(*srw_req->responsePosition) : 1;
1352 bsrr->errstring = 0;
1353 bsrr->referenceId = 0;
1354 bsrr->stream = assoc->encode;
1355 bsrr->print = assoc->print;
1356 bsrr->step_size = &step_size;
1359 bsrr->extra_args = sr->extra_args;
1360 bsrr->extra_response_data = 0;
1362 if (bsrr->num_entries > 0)
1365 bsrr->entries = (struct scan_entry *)
1366 odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
1368 for (i = 0; i<bsrr->num_entries; i++)
1370 bsrr->entries[i].term = 0;
1371 bsrr->entries[i].occurrences = 0;
1372 bsrr->entries[i].errcode = 0;
1373 bsrr->entries[i].errstring = 0;
1374 bsrr->entries[i].display_term = 0;
1377 save_entries = bsrr->entries; /* save it so we can compare later */
1379 if (srw_req->queryType && !strcmp(srw_req->queryType, "pqf") &&
1380 assoc->init->bend_scan)
1382 YAZ_PQF_Parser pqf_parser = yaz_pqf_create();
1384 bsrr->term = yaz_pqf_scan(pqf_parser, assoc->decode,
1385 &bsrr->attributeset,
1386 srw_req->scanClause);
1387 yaz_pqf_destroy(pqf_parser);
1388 bsrr->scanClause = 0;
1389 ((int (*)(void *, bend_scan_rr *))
1390 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1392 else if ((!srw_req->queryType || !strcmp(srw_req->queryType, "cql"))
1393 && assoc->init->bend_scan && assoc->server
1394 && assoc->server->cql_transform)
1397 bsrr->scanClause = 0;
1398 bsrr->attributeset = 0;
1399 bsrr->term = (Z_AttributesPlusTerm *)
1400 odr_malloc(assoc->decode, sizeof(*bsrr->term));
1401 srw_error = cql2pqf_scan(assoc->encode,
1402 srw_req->scanClause,
1403 assoc->server->cql_transform,
1406 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1407 &srw_res->num_diagnostics,
1411 ((int (*)(void *, bend_scan_rr *))
1412 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1415 else if ((!srw_req->queryType || !strcmp(srw_req->queryType, "cql"))
1416 && assoc->init->bend_srw_scan)
1419 bsrr->attributeset = 0;
1420 bsrr->scanClause = srw_req->scanClause;
1421 ((int (*)(void *, bend_scan_rr *))
1422 (*assoc->init->bend_srw_scan))(assoc->backend, bsrr);
1426 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1427 &srw_res->num_diagnostics,
1428 YAZ_SRW_UNSUPP_OPERATION, "scan");
1430 if (bsrr->extra_response_data)
1432 res->extraResponseData_buf = bsrr->extra_response_data;
1433 res->extraResponseData_len = strlen(bsrr->extra_response_data);
1438 if (bsrr->errcode == YAZ_BIB1_DATABASE_UNAVAILABLE)
1443 srw_error = yaz_diag_bib1_to_srw(bsrr->errcode);
1445 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1446 &srw_res->num_diagnostics,
1447 srw_error, bsrr->errstring);
1449 else if (srw_res->num_diagnostics == 0 && bsrr->num_entries)
1452 srw_res->terms = (Z_SRW_scanTerm*)
1453 odr_malloc(assoc->encode, sizeof(*srw_res->terms) *
1456 srw_res->num_terms = bsrr->num_entries;
1457 for (i = 0; i<bsrr->num_entries; i++)
1459 Z_SRW_scanTerm *t = srw_res->terms + i;
1460 t->value = odr_strdup(assoc->encode, bsrr->entries[i].term);
1461 t->numberOfRecords =
1462 odr_intdup(assoc->encode, bsrr->entries[i].occurrences);
1464 if (save_entries == bsrr->entries &&
1465 bsrr->entries[i].display_term)
1467 /* the entries was _not_ set by the handler. So it's
1468 safe to test for new member display_term. It is
1471 t->displayTerm = odr_strdup(assoc->encode,
1472 bsrr->entries[i].display_term);
1480 WRBUF wr = wrbuf_alloc();
1481 wrbuf_printf(wr, "SRWScan %s ", srw_req->database);
1483 if (srw_res->num_diagnostics)
1484 wrbuf_printf(wr, "ERROR %s - ", srw_res->diagnostics[0].uri);
1485 else if (srw_res->num_terms)
1486 wrbuf_printf(wr, "OK %d - ", srw_res->num_terms);
1488 wrbuf_printf(wr, "OK - - ");
1490 wrbuf_printf(wr, ODR_INT_PRINTF "+" ODR_INT_PRINTF " ",
1491 (srw_req->responsePosition ?
1492 *srw_req->responsePosition : 1),
1493 (srw_req->maximumTerms ?
1494 *srw_req->maximumTerms : 1));
1495 /* there is no step size in SRU/W ??? */
1496 wrbuf_printf(wr, "%s: %s ", srw_req->queryType, srw_req->scanClause);
1497 yaz_log(log_request, "%s ", wrbuf_cstr(wr) );
1503 static void srw_bend_update(association *assoc,
1504 Z_HTTP_Header *headers,
1506 Z_SRW_updateResponse *srw_res,
1509 Z_SRW_updateRequest *srw_req = sr->u.update_request;
1510 yaz_log(log_session, "SRWUpdate action=%s", srw_req->operation);
1511 yaz_log(YLOG_DEBUG, "num_diag = %d", srw_res->num_diagnostics );
1512 srw_bend_init(assoc, headers,
1513 &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1514 if (!assoc->init && srw_res->num_diagnostics == 0)
1519 Z_SRW_extra_record *extra = srw_req->extra_record;
1521 rr.stream = assoc->encode;
1522 rr.print = assoc->print;
1524 rr.basenames = &srw_req->database;
1525 rr.operation = srw_req->operation;
1526 rr.operation_status = "failed";
1528 rr.record_versions = 0;
1529 rr.num_versions = 0;
1530 rr.record_packing = "string";
1531 rr.record_schema = 0;
1533 rr.extra_record_data = 0;
1534 rr.extra_request_data = 0;
1535 rr.extra_response_data = 0;
1541 if (rr.operation == 0)
1543 yaz_add_sru_update_diagnostic(
1544 assoc->encode, &srw_res->diagnostics,
1545 &srw_res->num_diagnostics,
1546 YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,
1550 yaz_log(YLOG_DEBUG, "basename = %s", rr.basenames[0] );
1551 yaz_log(YLOG_DEBUG, "Operation = %s", rr.operation );
1552 if (!strcmp( rr.operation, "delete"))
1554 if (srw_req->record && !srw_req->record->recordSchema)
1556 rr.record_schema = odr_strdup(
1558 srw_req->record->recordSchema);
1560 if (srw_req->record)
1562 rr.record_data = odr_strdupn(
1564 srw_req->record->recordData_buf,
1565 srw_req->record->recordData_len );
1567 if (extra && extra->extraRecordData_len)
1569 rr.extra_record_data = odr_strdupn(
1571 extra->extraRecordData_buf,
1572 extra->extraRecordData_len );
1574 if (srw_req->recordId)
1575 rr.record_id = srw_req->recordId;
1576 else if (extra && extra->recordIdentifier)
1577 rr.record_id = extra->recordIdentifier;
1579 else if (!strcmp(rr.operation, "replace"))
1581 if (srw_req->recordId)
1582 rr.record_id = srw_req->recordId;
1583 else if (extra && extra->recordIdentifier)
1584 rr.record_id = extra->recordIdentifier;
1587 yaz_add_sru_update_diagnostic(
1588 assoc->encode, &srw_res->diagnostics,
1589 &srw_res->num_diagnostics,
1590 YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,
1591 "recordIdentifier");
1593 if (!srw_req->record)
1595 yaz_add_sru_update_diagnostic(
1596 assoc->encode, &srw_res->diagnostics,
1597 &srw_res->num_diagnostics,
1598 YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,
1603 if (srw_req->record->recordSchema)
1604 rr.record_schema = odr_strdup(
1605 assoc->encode, srw_req->record->recordSchema);
1606 if (srw_req->record->recordData_len )
1608 rr.record_data = odr_strdupn(assoc->encode,
1609 srw_req->record->recordData_buf,
1610 srw_req->record->recordData_len );
1614 yaz_add_sru_update_diagnostic(
1615 assoc->encode, &srw_res->diagnostics,
1616 &srw_res->num_diagnostics,
1617 YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,
1621 if (extra && extra->extraRecordData_len)
1623 rr.extra_record_data = odr_strdupn(
1625 extra->extraRecordData_buf,
1626 extra->extraRecordData_len );
1629 else if (!strcmp(rr.operation, "insert"))
1631 if (srw_req->recordId)
1632 rr.record_id = srw_req->recordId;
1634 rr.record_id = extra->recordIdentifier;
1636 if (srw_req->record)
1638 if (srw_req->record->recordSchema)
1639 rr.record_schema = odr_strdup(
1640 assoc->encode, srw_req->record->recordSchema);
1642 if (srw_req->record->recordData_len)
1643 rr.record_data = odr_strdupn(
1645 srw_req->record->recordData_buf,
1646 srw_req->record->recordData_len );
1648 if (extra && extra->extraRecordData_len)
1650 rr.extra_record_data = odr_strdupn(
1652 extra->extraRecordData_buf,
1653 extra->extraRecordData_len );
1657 yaz_add_sru_update_diagnostic(assoc->encode, &srw_res->diagnostics,
1658 &srw_res->num_diagnostics,
1659 YAZ_SRU_UPDATE_INVALID_ACTION,
1662 if (srw_req->record)
1664 const char *pack_str =
1665 yaz_srw_pack_to_str(srw_req->record->recordPacking);
1667 rr.record_packing = odr_strdup(assoc->encode, pack_str);
1670 if (srw_req->num_recordVersions)
1672 rr.record_versions = srw_req->recordVersions;
1673 rr.num_versions = srw_req->num_recordVersions;
1675 if (srw_req->extraRequestData_len)
1677 rr.extra_request_data = odr_strdupn(assoc->encode,
1678 srw_req->extraRequestData_buf,
1679 srw_req->extraRequestData_len );
1681 if (srw_res->num_diagnostics == 0)
1683 if ( assoc->init->bend_srw_update)
1684 (*assoc->init->bend_srw_update)(assoc->backend, &rr);
1686 yaz_add_sru_update_diagnostic(
1687 assoc->encode, &srw_res->diagnostics,
1688 &srw_res->num_diagnostics,
1689 YAZ_SRU_UPDATE_UNSPECIFIED_DATABASE_ERROR,
1690 "No Update backend handler");
1694 yaz_add_srw_diagnostic_uri(assoc->encode,
1695 &srw_res->diagnostics,
1696 &srw_res->num_diagnostics,
1700 srw_res->recordId = rr.record_id;
1701 srw_res->operationStatus = rr.operation_status;
1702 srw_res->recordVersions = rr.record_versions;
1703 srw_res->num_recordVersions = rr.num_versions;
1704 if (srw_res->extraResponseData_len)
1706 srw_res->extraResponseData_buf = rr.extra_response_data;
1707 srw_res->extraResponseData_len = strlen(rr.extra_response_data);
1709 if (srw_res->num_diagnostics == 0 && rr.record_data)
1711 srw_res->record = yaz_srw_get_record(assoc->encode);
1712 srw_res->record->recordSchema = rr.record_schema;
1713 if (rr.record_packing)
1715 int pack = yaz_srw_str_to_pack(rr.record_packing);
1719 pack = Z_SRW_recordPacking_string;
1720 yaz_log(YLOG_WARN, "Back packing %s from backend",
1723 srw_res->record->recordPacking = pack;
1725 srw_res->record->recordData_buf = rr.record_data;
1726 srw_res->record->recordData_len = strlen(rr.record_data);
1727 if (rr.extra_record_data)
1729 Z_SRW_extra_record *ex =
1730 yaz_srw_get_extra_record(assoc->encode);
1731 srw_res->extra_record = ex;
1732 ex->extraRecordData_buf = rr.extra_record_data;
1733 ex->extraRecordData_len = strlen(rr.extra_record_data);
1739 /* check if path is OK (1); BAD (0) */
1740 static int check_path(const char *path)
1744 if (strstr(path, ".."))
1749 static char *read_file(const char *fname, ODR o, size_t *sz)
1752 FILE *inf = fopen(fname, "rb");
1756 fseek(inf, 0L, SEEK_END);
1759 buf = (char *) odr_malloc(o, *sz);
1760 if (fread(buf, 1, *sz, inf) != *sz)
1761 yaz_log(YLOG_WARN|YLOG_ERRNO, "short read %s", fname);
1766 static void process_http_request(association *assoc, request *req)
1768 Z_HTTP_Request *hreq = req->gdu_request->u.HTTP_Request;
1769 ODR o = assoc->encode;
1770 int r = 2; /* 2=NOT TAKEN, 1=TAKEN, 0=SOAP TAKEN */
1772 Z_SOAP *soap_package = 0;
1775 Z_HTTP_Response *hres = 0;
1777 const char *stylesheet = 0; /* for now .. set later */
1778 Z_SRW_diagnostic *diagnostic = 0;
1779 int num_diagnostic = 0;
1780 const char *host = z_HTTP_header_lookup(hreq->headers, "Host");
1782 yaz_log(log_request, "%s %s HTTP/%s", hreq->method, hreq->path, hreq->version);
1783 if (!control_association(assoc, host, 0))
1785 p = z_get_HTTP_Response(o, 404);
1788 if (r == 2 && assoc->server && assoc->server->docpath
1789 && hreq->path[0] == '/'
1791 /* check if path is a proper prefix of documentroot */
1792 strncmp(hreq->path+1, assoc->server->docpath,
1793 strlen(assoc->server->docpath))
1796 if (!check_path(hreq->path))
1798 yaz_log(YLOG_LOG, "File %s access forbidden", hreq->path+1);
1799 p = z_get_HTTP_Response(o, 404);
1803 size_t content_size = 0;
1804 char *content_buf = read_file(hreq->path+1, o, &content_size);
1807 yaz_log(YLOG_LOG, "File %s not found", hreq->path+1);
1808 p = z_get_HTTP_Response(o, 404);
1812 const char *ctype = 0;
1813 yaz_mime_types types = yaz_mime_types_create();
1815 yaz_mime_types_add(types, "xsl", "application/xml");
1816 yaz_mime_types_add(types, "xml", "application/xml");
1817 yaz_mime_types_add(types, "css", "text/css");
1818 yaz_mime_types_add(types, "html", "text/html");
1819 yaz_mime_types_add(types, "htm", "text/html");
1820 yaz_mime_types_add(types, "txt", "text/plain");
1821 yaz_mime_types_add(types, "js", "application/x-javascript");
1823 yaz_mime_types_add(types, "gif", "image/gif");
1824 yaz_mime_types_add(types, "png", "image/png");
1825 yaz_mime_types_add(types, "jpg", "image/jpeg");
1826 yaz_mime_types_add(types, "jpeg", "image/jpeg");
1828 ctype = yaz_mime_lookup_fname(types, hreq->path);
1831 yaz_log(YLOG_LOG, "No mime type for %s", hreq->path+1);
1832 p = z_get_HTTP_Response(o, 404);
1836 p = z_get_HTTP_Response(o, 200);
1837 hres = p->u.HTTP_Response;
1838 hres->content_buf = content_buf;
1839 hres->content_len = content_size;
1840 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1842 yaz_mime_types_destroy(types);
1850 r = yaz_srw_decode(hreq, &sr, &soap_package, assoc->decode, &charset);
1851 yaz_log(YLOG_DEBUG, "yaz_srw_decode returned %d", r);
1853 if (r == 2) /* not taken */
1855 r = yaz_sru_decode(hreq, &sr, &soap_package, assoc->decode, &charset,
1856 &diagnostic, &num_diagnostic);
1857 yaz_log(YLOG_DEBUG, "yaz_sru_decode returned %d", r);
1859 if (r == 0) /* decode SRW/SRU OK .. */
1861 int http_code = 200;
1862 if (sr->which == Z_SRW_searchRetrieve_request)
1865 yaz_srw_get_pdu_e(assoc->encode, Z_SRW_searchRetrieve_response,
1867 stylesheet = sr->u.request->stylesheet;
1870 res->u.response->diagnostics = diagnostic;
1871 res->u.response->num_diagnostics = num_diagnostic;
1875 srw_bend_search(assoc, hreq->headers, sr, res, &http_code);
1877 if (http_code == 200)
1878 soap_package->u.generic->p = res;
1880 else if (sr->which == Z_SRW_explain_request)
1882 Z_SRW_PDU *res = yaz_srw_get_pdu_e(o, Z_SRW_explain_response, sr);
1883 stylesheet = sr->u.explain_request->stylesheet;
1886 res->u.explain_response->diagnostics = diagnostic;
1887 res->u.explain_response->num_diagnostics = num_diagnostic;
1889 srw_bend_explain(assoc, hreq->headers,
1890 sr, res->u.explain_response, &http_code);
1891 if (http_code == 200)
1892 soap_package->u.generic->p = res;
1894 else if (sr->which == Z_SRW_scan_request)
1896 Z_SRW_PDU *res = yaz_srw_get_pdu_e(o, Z_SRW_scan_response, sr);
1897 stylesheet = sr->u.scan_request->stylesheet;
1900 res->u.scan_response->diagnostics = diagnostic;
1901 res->u.scan_response->num_diagnostics = num_diagnostic;
1903 srw_bend_scan(assoc, hreq->headers, sr, res, &http_code);
1904 if (http_code == 200)
1905 soap_package->u.generic->p = res;
1907 else if (sr->which == Z_SRW_update_request)
1909 Z_SRW_PDU *res = yaz_srw_get_pdu(o, Z_SRW_update_response,
1911 yaz_log(YLOG_DEBUG, "handling SRW UpdateRequest");
1914 res->u.update_response->diagnostics = diagnostic;
1915 res->u.update_response->num_diagnostics = num_diagnostic;
1917 yaz_log(YLOG_DEBUG, "num_diag = %d", res->u.update_response->num_diagnostics );
1918 srw_bend_update(assoc, hreq->headers,
1919 sr, res->u.update_response, &http_code);
1920 if (http_code == 200)
1921 soap_package->u.generic->p = res;
1925 yaz_log(log_request, "SOAP ERROR");
1926 /* FIXME - what error, what query */
1928 z_soap_error(assoc->encode, soap_package,
1929 "SOAP-ENV:Client", "Bad method", 0);
1931 if (http_code == 200 || http_code == 500)
1933 static Z_SOAP_Handler soap_handlers[4] = {
1935 {YAZ_XMLNS_SRU_v1_1, 0, (Z_SOAP_fun) yaz_srw_codec},
1936 {YAZ_XMLNS_SRU_v1_0, 0, (Z_SOAP_fun) yaz_srw_codec},
1937 {YAZ_XMLNS_UPDATE_v0_9, 0, (Z_SOAP_fun) yaz_ucp_codec},
1942 p = z_get_HTTP_Response(o, 200);
1943 hres = p->u.HTTP_Response;
1945 if (!stylesheet && assoc->server)
1946 stylesheet = assoc->server->stylesheet;
1948 /* empty stylesheet means NO stylesheet */
1949 if (stylesheet && *stylesheet == '\0')
1952 z_soap_codec_enc_xsl(assoc->encode, &soap_package,
1953 &hres->content_buf, &hres->content_len,
1954 soap_handlers, charset, stylesheet);
1955 hres->code = http_code;
1957 strcpy(ctype, "text/xml");
1958 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1961 p = z_get_HTTP_Response(o, http_code);
1965 p = z_get_HTTP_Response(o, 500);
1966 hres = p->u.HTTP_Response;
1967 if (!strcmp(hreq->version, "1.0"))
1969 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1970 if (v && !strcmp(v, "Keep-Alive"))
1974 hres->version = "1.0";
1978 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1979 if (v && !strcmp(v, "close"))
1983 hres->version = "1.1";
1985 if (!keepalive || !assoc->last_control->keepalive)
1987 z_HTTP_header_add(o, &hres->headers, "Connection", "close");
1988 assoc->state = ASSOC_DEAD;
1989 assoc->cs_get_mask = 0;
1994 const char *alive = z_HTTP_header_lookup(hreq->headers, "Keep-Alive");
1996 if (alive && yaz_isdigit(*(const unsigned char *) alive))
2000 if (t < 0 || t > 3600)
2002 iochan_settimeout(assoc->client_chan,t);
2003 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
2005 process_gdu_response(assoc, req, p);
2008 static void process_gdu_request(association *assoc, request *req)
2010 if (req->gdu_request->which == Z_GDU_Z3950)
2013 req->apdu_request = req->gdu_request->u.z3950;
2014 if (process_z_request(assoc, req, &msg) < 0)
2015 do_close_req(assoc, Z_Close_systemProblem, msg, req);
2017 else if (req->gdu_request->which == Z_GDU_HTTP_Request)
2018 process_http_request(assoc, req);
2021 do_close_req(assoc, Z_Close_systemProblem, "bad protocol packet", req);
2026 * Initiate request processing.
2028 static int process_z_request(association *assoc, request *req, char **msg)
2033 *msg = "Unknown Error";
2034 assert(req && req->state == REQUEST_IDLE);
2035 if (req->apdu_request->which != Z_APDU_initRequest && !assoc->init)
2037 *msg = "Missing InitRequest";
2040 switch (req->apdu_request->which)
2042 case Z_APDU_initRequest:
2043 res = process_initRequest(assoc, req); break;
2044 case Z_APDU_searchRequest:
2045 res = process_searchRequest(assoc, req); break;
2046 case Z_APDU_presentRequest:
2047 res = process_presentRequest(assoc, req); break;
2048 case Z_APDU_scanRequest:
2049 if (assoc->init->bend_scan)
2050 res = process_scanRequest(assoc, req);
2053 *msg = "Cannot handle Scan APDU";
2057 case Z_APDU_extendedServicesRequest:
2058 if (assoc->init->bend_esrequest)
2059 res = process_ESRequest(assoc, req);
2062 *msg = "Cannot handle Extended Services APDU";
2066 case Z_APDU_sortRequest:
2067 if (assoc->init->bend_sort)
2068 res = process_sortRequest(assoc, req);
2071 *msg = "Cannot handle Sort APDU";
2076 process_close(assoc, req);
2078 case Z_APDU_deleteResultSetRequest:
2079 if (assoc->init->bend_delete)
2080 res = process_deleteRequest(assoc, req);
2083 *msg = "Cannot handle Delete APDU";
2087 case Z_APDU_segmentRequest:
2088 if (assoc->init->bend_segment)
2090 res = process_segmentRequest(assoc, req);
2094 *msg = "Cannot handle Segment APDU";
2098 case Z_APDU_triggerResourceControlRequest:
2101 *msg = "Bad APDU received";
2106 yaz_log(YLOG_DEBUG, " result immediately available");
2107 retval = process_z_response(assoc, req, res);
2111 yaz_log(YLOG_DEBUG, " result unavailable");
2118 * Encode response, and transfer the request structure to the outgoing queue.
2120 static int process_gdu_response(association *assoc, request *req, Z_GDU *res)
2122 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
2126 if (!z_GDU(assoc->print, &res, 0, 0))
2127 yaz_log(YLOG_WARN, "ODR print error: %s",
2128 odr_errmsg(odr_geterror(assoc->print)));
2129 odr_reset(assoc->print);
2131 if (!z_GDU(assoc->encode, &res, 0, 0))
2133 yaz_log(YLOG_WARN, "ODR error when encoding PDU: %s [element %s]",
2134 odr_errmsg(odr_geterror(assoc->decode)),
2135 odr_getelement(assoc->decode));
2138 req->response = odr_getbuf(assoc->encode, &req->len_response,
2139 &req->size_response);
2140 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
2141 odr_reset(assoc->encode);
2142 req->state = REQUEST_IDLE;
2143 request_enq(&assoc->outgoing, req);
2144 /* turn the work over to the ir_session handler */
2145 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
2146 assoc->cs_put_mask = EVENT_OUTPUT;
2147 /* Is there more work to be done? give that to the input handler too */
2150 req = request_head(&assoc->incoming);
2151 if (req && req->state == REQUEST_IDLE)
2153 request_deq(&assoc->incoming);
2154 process_gdu_request(assoc, req);
2163 * Encode response, and transfer the request structure to the outgoing queue.
2165 static int process_z_response(association *assoc, request *req, Z_APDU *res)
2167 Z_GDU *gres = (Z_GDU *) odr_malloc(assoc->encode, sizeof(*gres));
2168 gres->which = Z_GDU_Z3950;
2169 gres->u.z3950 = res;
2171 return process_gdu_response(assoc, req, gres);
2174 static char *get_vhost(Z_OtherInformation *otherInfo)
2176 return yaz_oi_get_string_oid(&otherInfo, yaz_oid_userinfo_proxy, 1, 0);
2180 * Handle init request.
2181 * At the moment, we don't check the options
2182 * anywhere else in the code - we just try not to do anything that would
2183 * break a naive client. We'll toss 'em into the association block when
2184 * we need them there.
2186 static Z_APDU *process_initRequest(association *assoc, request *reqb)
2188 Z_InitRequest *req = reqb->apdu_request->u.initRequest;
2189 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
2190 Z_InitResponse *resp = apdu->u.initResponse;
2191 bend_initresult *binitres;
2193 statserv_options_block *cb = 0; /* by default no control for backend */
2195 if (control_association(assoc, get_vhost(req->otherInfo), 1))
2196 cb = statserv_getcontrol(); /* got control block for backend */
2198 if (cb && assoc->backend)
2199 (*cb->bend_close)(assoc->backend);
2201 yaz_log(log_requestdetail, "Got initRequest");
2202 if (req->implementationId)
2203 yaz_log(log_requestdetail, "Id: %s",
2204 req->implementationId);
2205 if (req->implementationName)
2206 yaz_log(log_requestdetail, "Name: %s",
2207 req->implementationName);
2208 if (req->implementationVersion)
2209 yaz_log(log_requestdetail, "Version: %s",
2210 req->implementationVersion);
2212 assoc_init_reset(assoc,
2213 yaz_oi_get_string_oid(&req->otherInfo,
2214 yaz_oid_userinfo_client_ip, 1, 0));
2215 assoc->init->auth = req->idAuthentication;
2216 assoc->init->referenceId = req->referenceId;
2218 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
2220 Z_CharSetandLanguageNegotiation *negotiation =
2221 yaz_get_charneg_record (req->otherInfo);
2223 negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
2224 assoc->init->charneg_request = negotiation;
2227 /* by default named_result_sets is 0 .. Enable it if client asks for it. */
2228 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
2229 assoc->init->named_result_sets = 1;
2234 if (req->implementationVersion)
2235 yaz_log(log_requestdetail, "Config: %s",
2238 iochan_settimeout(assoc->client_chan, cb->idle_timeout);
2240 /* we have a backend control block, so call that init function */
2241 if (!(binitres = (*cb->bend_init)(assoc->init)))
2243 yaz_log(YLOG_WARN, "Bad response from backend.");
2246 assoc->backend = binitres->handle;
2250 /* no backend. return error */
2251 binitres = (bend_initresult *)
2252 odr_malloc(assoc->encode, sizeof(*binitres));
2253 binitres->errstring = 0;
2254 binitres->errcode = YAZ_BIB1_PERMANENT_SYSTEM_ERROR;
2255 iochan_settimeout(assoc->client_chan, 10);
2257 if ((assoc->init->bend_sort))
2258 yaz_log(YLOG_DEBUG, "Sort handler installed");
2259 if ((assoc->init->bend_search))
2260 yaz_log(YLOG_DEBUG, "Search handler installed");
2261 if ((assoc->init->bend_present))
2262 yaz_log(YLOG_DEBUG, "Present handler installed");
2263 if ((assoc->init->bend_esrequest))
2264 yaz_log(YLOG_DEBUG, "ESRequest handler installed");
2265 if ((assoc->init->bend_delete))
2266 yaz_log(YLOG_DEBUG, "Delete handler installed");
2267 if ((assoc->init->bend_scan))
2268 yaz_log(YLOG_DEBUG, "Scan handler installed");
2269 if ((assoc->init->bend_segment))
2270 yaz_log(YLOG_DEBUG, "Segment handler installed");
2272 resp->referenceId = req->referenceId;
2274 /* let's tell the client what we can do */
2275 if (ODR_MASK_GET(req->options, Z_Options_search))
2277 ODR_MASK_SET(resp->options, Z_Options_search);
2278 strcat(options, "srch");
2280 if (ODR_MASK_GET(req->options, Z_Options_present))
2282 ODR_MASK_SET(resp->options, Z_Options_present);
2283 strcat(options, " prst");
2285 if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
2286 assoc->init->bend_delete)
2288 ODR_MASK_SET(resp->options, Z_Options_delSet);
2289 strcat(options, " del");
2291 if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
2292 assoc->init->bend_esrequest)
2294 ODR_MASK_SET(resp->options, Z_Options_extendedServices);
2295 strcat(options, " extendedServices");
2297 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets)
2298 && assoc->init->named_result_sets)
2300 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
2301 strcat(options, " namedresults");
2303 if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
2305 ODR_MASK_SET(resp->options, Z_Options_scan);
2306 strcat(options, " scan");
2308 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
2310 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
2311 strcat(options, " concurrop");
2313 if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
2315 ODR_MASK_SET(resp->options, Z_Options_sort);
2316 strcat(options, " sort");
2319 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
2321 Z_OtherInformationUnit *p0;
2323 if (!assoc->init->charneg_response)
2325 if (assoc->init->query_charset)
2327 assoc->init->charneg_response = yaz_set_response_charneg(
2328 assoc->encode, assoc->init->query_charset, 0,
2329 assoc->init->records_in_same_charset);
2333 yaz_log(YLOG_WARN, "default query_charset not defined by backend");
2336 if (assoc->init->charneg_response
2337 && (p0=yaz_oi_update(&resp->otherInfo, assoc->encode, NULL, 0, 0)))
2339 p0->which = Z_OtherInfo_externallyDefinedInfo;
2340 p0->information.externallyDefinedInfo =
2341 assoc->init->charneg_response;
2342 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
2343 strcat(options, " negotiation");
2346 if (ODR_MASK_GET(req->options, Z_Options_triggerResourceCtrl))
2347 ODR_MASK_SET(resp->options, Z_Options_triggerResourceCtrl);
2349 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
2351 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
2352 assoc->version = 1; /* 1 & 2 are equivalent */
2354 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
2356 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
2359 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
2361 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
2365 yaz_log(log_requestdetail, "Negotiated to v%d: %s", assoc->version, options);
2367 if (*req->maximumRecordSize < assoc->maximumRecordSize)
2368 assoc->maximumRecordSize = odr_int_to_int(*req->maximumRecordSize);
2370 if (*req->preferredMessageSize < assoc->preferredMessageSize)
2371 assoc->preferredMessageSize = odr_int_to_int(*req->preferredMessageSize);
2373 resp->preferredMessageSize =
2374 odr_intdup(assoc->encode, assoc->preferredMessageSize);
2375 resp->maximumRecordSize =
2376 odr_intdup(assoc->encode, assoc->maximumRecordSize);
2378 resp->implementationId = odr_prepend(assoc->encode,
2379 assoc->init->implementation_id,
2380 resp->implementationId);
2382 resp->implementationVersion = odr_prepend(assoc->encode,
2383 assoc->init->implementation_version,
2384 resp->implementationVersion);
2386 resp->implementationName = odr_prepend(assoc->encode,
2387 assoc->init->implementation_name,
2388 odr_prepend(assoc->encode, "GFS", resp->implementationName));
2390 if (binitres->errcode)
2392 assoc->state = ASSOC_DEAD;
2393 resp->userInformationField =
2394 init_diagnostics(assoc->encode, binitres->errcode,
2395 binitres->errstring);
2399 assoc->state = ASSOC_UP;
2403 if (!req->idAuthentication)
2404 yaz_log(log_request, "Auth none");
2405 else if (req->idAuthentication->which == Z_IdAuthentication_open)
2407 const char *open = req->idAuthentication->u.open;
2408 const char *slash = strchr(open, '/');
2414 yaz_log(log_request, "Auth open %.*s", len, open);
2416 else if (req->idAuthentication->which == Z_IdAuthentication_idPass)
2418 const char *user = req->idAuthentication->u.idPass->userId;
2419 const char *group = req->idAuthentication->u.idPass->groupId;
2420 yaz_log(log_request, "Auth idPass %s %s",
2421 user ? user : "-", group ? group : "-");
2423 else if (req->idAuthentication->which
2424 == Z_IdAuthentication_anonymous)
2426 yaz_log(log_request, "Auth anonymous");
2430 yaz_log(log_request, "Auth other");
2435 WRBUF wr = wrbuf_alloc();
2436 wrbuf_printf(wr, "Init ");
2437 if (binitres->errcode)
2438 wrbuf_printf(wr, "ERROR %d", binitres->errcode);
2440 wrbuf_printf(wr, "OK -");
2441 wrbuf_printf(wr, " ID:%s Name:%s Version:%s",
2442 (req->implementationId ? req->implementationId :"-"),
2443 (req->implementationName ?
2444 req->implementationName : "-"),
2445 (req->implementationVersion ?
2446 req->implementationVersion : "-")
2448 yaz_log(log_request, "%s", wrbuf_cstr(wr));
2455 * Set the specified `errcode' and `errstring' into a UserInfo-1
2456 * external to be returned to the client in accordance with Z35.90
2457 * Implementor Agreement 5 (Returning diagnostics in an InitResponse):
2458 * http://lcweb.loc.gov/z3950/agency/agree/initdiag.html
2460 static Z_External *init_diagnostics(ODR odr, int error, const char *addinfo)
2462 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2463 addinfo ? " -- " : "", addinfo ? addinfo : "");
2464 return zget_init_diagnostics(odr, error, addinfo);
2468 * nonsurrogate diagnostic record.
2470 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
2472 Z_Records *rec = (Z_Records *) odr_malloc(assoc->encode, sizeof(*rec));
2474 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2475 addinfo ? " -- " : "", addinfo ? addinfo : "");
2477 rec->which = Z_Records_NSD;
2478 rec->u.nonSurrogateDiagnostic = zget_DefaultDiagFormat(assoc->encode,
2484 * surrogate diagnostic.
2486 static Z_NamePlusRecord *surrogatediagrec(association *assoc,
2488 int error, const char *addinfo)
2490 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2491 addinfo ? " -- " : "", addinfo ? addinfo : "");
2492 return zget_surrogateDiagRec(assoc->encode, dbname, error, addinfo);
2495 static Z_Records *pack_records(association *a, char *setname, Odr_int start,
2496 Odr_int *num, Z_RecordComposition *comp,
2497 Odr_int *next, Odr_int *pres,
2498 Z_ReferenceId *referenceId,
2499 Odr_oid *oid, int *errcode)
2501 int recno, dumped_records = 0;
2502 int toget = odr_int_to_int(*num);
2503 Z_Records *records =
2504 (Z_Records *) odr_malloc(a->encode, sizeof(*records));
2505 Z_NamePlusRecordList *reclist =
2506 (Z_NamePlusRecordList *) odr_malloc(a->encode, sizeof(*reclist));
2508 records->which = Z_Records_DBOSD;
2509 records->u.databaseOrSurDiagnostics = reclist;
2510 reclist->num_records = 0;
2513 return diagrec(a, YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE, 0);
2514 else if (toget == 0)
2515 reclist->records = odr_nullval();
2517 reclist->records = (Z_NamePlusRecord **)
2518 odr_malloc(a->encode, sizeof(*reclist->records) * toget);
2520 *pres = Z_PresentStatus_success;
2524 yaz_log(log_requestdetail, "Request to pack " ODR_INT_PRINTF "+%d %s", start, toget, setname);
2525 yaz_log(log_requestdetail, "pms=%d, mrs=%d", a->preferredMessageSize,
2526 a->maximumRecordSize);
2527 for (recno = odr_int_to_int(start); reclist->num_records < toget; recno++)
2530 Z_NamePlusRecord *thisrec;
2531 Odr_int this_length = 0;
2533 * we get the number of bytes allocated on the stream before any
2534 * allocation done by the backend - this should give us a reasonable
2535 * idea of the total size of the data so far.
2537 Odr_int total_length = odr_total(a->encode) - dumped_records;
2543 freq.last_in_set = 0;
2544 freq.setname = setname;
2545 freq.surrogate_flag = 0;
2546 freq.number = recno;
2548 freq.request_format = oid;
2549 freq.output_format = 0;
2550 freq.stream = a->encode;
2551 freq.print = a->print;
2552 freq.referenceId = referenceId;
2555 retrieve_fetch(a, &freq);
2557 *next = freq.last_in_set ? 0 : recno + 1;
2561 if (!freq.surrogate_flag) /* non-surrogate diagnostic i.e. global */
2564 *pres = Z_PresentStatus_failure;
2565 /* for 'present request out of range',
2566 set addinfo to record position if not set */
2567 if (freq.errcode == YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE &&
2568 freq.errstring == 0)
2570 sprintf(s, "%d", recno);
2574 *errcode = freq.errcode;
2575 return diagrec(a, freq.errcode, freq.errstring);
2577 reclist->records[reclist->num_records] =
2578 surrogatediagrec(a, freq.basename, freq.errcode,
2580 reclist->num_records++;
2583 if (freq.record == 0) /* no error and no record ? */
2585 *pres = Z_PresentStatus_partial_4;
2586 *next = 0; /* signal end-of-set and stop */
2590 this_length = freq.len;
2592 this_length = odr_total(a->encode) - total_length - dumped_records;
2593 yaz_log(log_requestdetail, " fetched record, len=" ODR_INT_PRINTF
2594 " total=" ODR_INT_PRINTF " dumped=%d",
2595 this_length, total_length, dumped_records);
2596 if (a->preferredMessageSize > 0 &&
2597 this_length + total_length > a->preferredMessageSize)
2599 /* record is small enough, really */
2600 if (this_length <= a->preferredMessageSize && recno > start)
2602 yaz_log(log_requestdetail, " Dropped last normal-sized record");
2603 *pres = Z_PresentStatus_partial_2;
2608 /* record can only be fetched by itself */
2609 if (this_length < a->maximumRecordSize)
2611 yaz_log(log_requestdetail, " Record > prefmsgsz");
2614 yaz_log(YLOG_DEBUG, " Dropped it");
2615 reclist->records[reclist->num_records] =
2618 YAZ_BIB1_RECORD_EXCEEDS_PREFERRED_MESSAGE_SIZE, 0);
2619 reclist->num_records++;
2620 dumped_records += this_length;
2624 else /* too big entirely */
2626 yaz_log(log_requestdetail, "Record > maxrcdsz "
2627 "this=" ODR_INT_PRINTF " max=%d",
2628 this_length, a->maximumRecordSize);
2629 reclist->records[reclist->num_records] =
2632 YAZ_BIB1_RECORD_EXCEEDS_MAXIMUM_RECORD_SIZE, 0);
2633 reclist->num_records++;
2634 dumped_records += this_length;
2639 if (!(thisrec = (Z_NamePlusRecord *)
2640 odr_malloc(a->encode, sizeof(*thisrec))))
2642 thisrec->databaseName = odr_strdup_null(a->encode, freq.basename);
2643 thisrec->which = Z_NamePlusRecord_databaseRecord;
2645 if (!freq.output_format)
2647 yaz_log(YLOG_WARN, "bend_fetch output_format not set");
2650 thisrec->u.databaseRecord = z_ext_record_oid(
2651 a->encode, freq.output_format, freq.record, freq.len);
2652 if (!thisrec->u.databaseRecord)
2654 reclist->records[reclist->num_records] = thisrec;
2655 reclist->num_records++;
2656 if (freq.last_in_set)
2659 *num = reclist->num_records;
2663 static Z_APDU *process_searchRequest(association *assoc, request *reqb)
2665 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2666 bend_search_rr *bsrr =
2667 (bend_search_rr *)nmem_malloc(reqb->request_mem, sizeof(*bsrr));
2669 yaz_log(log_requestdetail, "Got SearchRequest.");
2670 bsrr->association = assoc;
2671 bsrr->referenceId = req->referenceId;
2672 bsrr->srw_sortKeys = 0;
2673 bsrr->srw_setname = 0;
2674 bsrr->srw_setnameIdleTime = 0;
2675 bsrr->estimated_hit_count = 0;
2676 bsrr->partial_resultset = 0;
2677 bsrr->extra_args = 0;
2678 bsrr->extra_response_data = 0;
2680 yaz_log(log_requestdetail, "ResultSet '%s'", req->resultSetName);
2681 if (req->databaseNames)
2684 for (i = 0; i < req->num_databaseNames; i++)
2685 yaz_log(log_requestdetail, "Database '%s'", req->databaseNames[i]);
2688 yaz_log_zquery_level(log_requestdetail,req->query);
2690 if (assoc->init->bend_search)
2692 bsrr->setname = req->resultSetName;
2693 bsrr->replace_set = *req->replaceIndicator;
2694 bsrr->num_bases = req->num_databaseNames;
2695 bsrr->basenames = req->databaseNames;
2696 bsrr->query = req->query;
2697 bsrr->stream = assoc->encode;
2698 nmem_transfer(odr_getmem(bsrr->stream), reqb->request_mem);
2699 bsrr->decode = assoc->decode;
2700 bsrr->print = assoc->print;
2703 bsrr->errstring = NULL;
2704 bsrr->search_info = NULL;
2705 bsrr->search_input = req->additionalSearchInfo;
2706 if (!bsrr->search_input)
2707 bsrr->search_input = req->otherInfo;
2708 bsrr->present_number = *req->mediumSetPresentNumber;
2710 if (assoc->server && assoc->server->client_query_charset &&
2711 req->query->which == Z_Query_type_1)
2714 yaz_iconv_open("UTF-8", assoc->server->client_query_charset);
2717 yaz_query_charset_convert_rpnquery(req->query->u.type_1,
2719 yaz_iconv_close(cd);
2723 if (assoc->server && assoc->server->cql_transform
2724 && req->query->which == Z_Query_type_104
2725 && req->query->u.type_104->which == Z_External_CQL)
2727 /* have a CQL query and a CQL to PQF transform .. */
2729 cql2pqf(bsrr->stream, req->query->u.type_104->u.cql,
2730 assoc->server->cql_transform, bsrr->query,
2731 &bsrr->srw_sortKeys);
2733 bsrr->errcode = yaz_diag_srw_to_bib1(srw_errcode);
2736 if (assoc->server && assoc->server->ccl_transform
2737 && req->query->which == Z_Query_type_2) /*CCL*/
2739 /* have a CCL query and a CCL to PQF transform .. */
2741 ccl2pqf(bsrr->stream, req->query->u.type_2,
2742 assoc->server->ccl_transform, bsrr);
2744 bsrr->errcode = yaz_diag_srw_to_bib1(srw_errcode);
2748 (assoc->init->bend_search)(assoc->backend, bsrr);
2752 /* FIXME - make a diagnostic for it */
2753 yaz_log(YLOG_WARN,"Search not supported ?!?!");
2755 return response_searchRequest(assoc, reqb, bsrr);
2759 * Prepare a searchresponse based on the backend results. We probably want
2760 * to look at making the fetching of records nonblocking as well, but
2761 * so far, we'll keep things simple.
2762 * If bsrt is null, that means we're called in response to a communications
2763 * event, and we'll have to get the response for ourselves.
2765 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
2766 bend_search_rr *bsrt)
2768 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2769 Z_APDU *apdu = (Z_APDU *)odr_malloc(assoc->encode, sizeof(*apdu));
2770 Z_SearchResponse *resp = (Z_SearchResponse *)
2771 odr_malloc(assoc->encode, sizeof(*resp));
2772 Odr_int *nulint = odr_intdup(assoc->encode, 0);
2773 Odr_int *next = odr_intdup(assoc->encode, 0);
2774 Odr_int *none = odr_intdup(assoc->encode, Z_SearchResponse_none);
2775 Odr_int returnedrecs = 0;
2777 apdu->which = Z_APDU_searchResponse;
2778 apdu->u.searchResponse = resp;
2779 resp->referenceId = req->referenceId;
2780 resp->additionalSearchInfo = 0;
2781 resp->otherInfo = 0;
2784 yaz_log(YLOG_FATAL, "Bad result from backend");
2787 else if (bsrt->errcode)
2789 resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
2790 resp->resultCount = nulint;
2791 resp->numberOfRecordsReturned = nulint;
2792 resp->nextResultSetPosition = nulint;
2793 resp->searchStatus = odr_booldup(assoc->encode, 0);
2794 resp->resultSetStatus = none;
2795 resp->presentStatus = 0;
2799 bool_t *sr = odr_booldup(assoc->encode, 1);
2800 Odr_int *toget = odr_intdup(assoc->encode, 0);
2801 Z_RecordComposition comp, *compp = 0;
2803 yaz_log(log_requestdetail, "resultCount: " ODR_INT_PRINTF, bsrt->hits);
2806 resp->resultCount = &bsrt->hits;
2808 comp.which = Z_RecordComp_simple;
2809 /* how many records does the user agent want, then? */
2812 else if (bsrt->hits <= *req->smallSetUpperBound)
2814 *toget = bsrt->hits;
2815 if ((comp.u.simple = req->smallSetElementSetNames))
2818 else if (bsrt->hits < *req->largeSetLowerBound)
2820 *toget = *req->mediumSetPresentNumber;
2821 if (*toget > bsrt->hits)
2822 *toget = bsrt->hits;
2823 if ((comp.u.simple = req->mediumSetElementSetNames))
2829 if (*toget && !resp->records)
2831 Odr_int *presst = odr_intdup(assoc->encode, 0);
2832 /* Call bend_present if defined */
2833 if (assoc->init->bend_present)
2835 bend_present_rr *bprr = (bend_present_rr *)
2836 nmem_malloc(reqb->request_mem, sizeof(*bprr));
2837 bprr->setname = req->resultSetName;
2839 bprr->number = odr_int_to_int(*toget);
2840 bprr->format = req->preferredRecordSyntax;
2842 bprr->referenceId = req->referenceId;
2843 bprr->stream = assoc->encode;
2844 bprr->print = assoc->print;
2845 bprr->association = assoc;
2847 bprr->errstring = NULL;
2848 (*assoc->init->bend_present)(assoc->backend, bprr);
2852 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2853 *resp->presentStatus = Z_PresentStatus_failure;
2858 resp->records = pack_records(
2859 assoc, req->resultSetName, 1,
2860 toget, compp, next, presst, req->referenceId,
2861 req->preferredRecordSyntax, NULL);
2864 resp->numberOfRecordsReturned = toget;
2865 returnedrecs = *toget;
2866 resp->presentStatus = presst;
2870 if (*resp->resultCount)
2872 resp->numberOfRecordsReturned = nulint;
2873 resp->presentStatus = 0;
2875 resp->nextResultSetPosition = next;
2876 resp->searchStatus = sr;
2877 resp->resultSetStatus = 0;
2878 if (bsrt->estimated_hit_count)
2880 resp->resultSetStatus = odr_intdup(assoc->encode,
2881 Z_SearchResponse_estimate);
2883 else if (bsrt->partial_resultset)
2885 resp->resultSetStatus = odr_intdup(assoc->encode,
2886 Z_SearchResponse_subset);
2889 resp->additionalSearchInfo = bsrt->search_info;
2894 WRBUF wr = wrbuf_alloc();
2896 for (i = 0 ; i < req->num_databaseNames; i++)
2899 wrbuf_printf(wr, "+");
2900 wrbuf_puts(wr, req->databaseNames[i]);
2902 wrbuf_printf(wr, " ");
2905 wrbuf_printf(wr, "ERROR %d", bsrt->errcode);
2907 wrbuf_printf(wr, "OK " ODR_INT_PRINTF, bsrt->hits);
2908 wrbuf_printf(wr, " %s 1+" ODR_INT_PRINTF " ",
2909 req->resultSetName, returnedrecs);
2910 yaz_query_to_wrbuf(wr, req->query);
2912 yaz_log(log_request, "Search %s", wrbuf_cstr(wr));
2919 * Maybe we got a little over-friendly when we designed bend_fetch to
2920 * get only one record at a time. Some backends can optimise multiple-record
2921 * fetches, and at any rate, there is some overhead involved in
2922 * all that selecting and hopping around. Problem is, of course, that the
2923 * frontend can't know ahead of time how many records it'll need to
2924 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
2925 * is downright lousy as a bulk data transfer protocol.
2927 * To start with, we'll do the fetching of records from the backend
2928 * in one operation: To save some trips in and out of the event-handler,
2929 * and to simplify the interface to pack_records. At any rate, asynch
2930 * operation is more fun in operations that have an unpredictable execution
2931 * speed - which is normally more true for search than for present.
2933 static Z_APDU *process_presentRequest(association *assoc, request *reqb)
2935 Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
2937 Z_PresentResponse *resp;
2942 yaz_log(log_requestdetail, "Got PresentRequest.");
2944 resp = (Z_PresentResponse *)odr_malloc(assoc->encode, sizeof(*resp));
2946 resp->presentStatus = odr_intdup(assoc->encode, 0);
2947 if (assoc->init->bend_present)
2949 bend_present_rr *bprr = (bend_present_rr *)
2950 nmem_malloc(reqb->request_mem, sizeof(*bprr));
2951 bprr->setname = req->resultSetId;
2952 bprr->start = odr_int_to_int(*req->resultSetStartPoint);
2953 bprr->number = odr_int_to_int(*req->numberOfRecordsRequested);
2954 bprr->format = req->preferredRecordSyntax;
2955 bprr->comp = req->recordComposition;
2956 bprr->referenceId = req->referenceId;
2957 bprr->stream = assoc->encode;
2958 bprr->print = assoc->print;
2959 bprr->association = assoc;
2961 bprr->errstring = NULL;
2962 (*assoc->init->bend_present)(assoc->backend, bprr);
2966 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2967 *resp->presentStatus = Z_PresentStatus_failure;
2968 errcode = bprr->errcode;
2971 apdu = (Z_APDU *)odr_malloc(assoc->encode, sizeof(*apdu));
2972 next = odr_intdup(assoc->encode, 0);
2973 num = odr_intdup(assoc->encode, 0);
2975 apdu->which = Z_APDU_presentResponse;
2976 apdu->u.presentResponse = resp;
2977 resp->referenceId = req->referenceId;
2978 resp->otherInfo = 0;
2982 *num = *req->numberOfRecordsRequested;
2984 pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
2985 num, req->recordComposition, next,
2986 resp->presentStatus,
2987 req->referenceId, req->preferredRecordSyntax,
2992 WRBUF wr = wrbuf_alloc();
2993 wrbuf_printf(wr, "Present ");
2995 if (*resp->presentStatus == Z_PresentStatus_failure)
2996 wrbuf_printf(wr, "ERROR %d ", errcode);
2997 else if (*resp->presentStatus == Z_PresentStatus_success)
2998 wrbuf_printf(wr, "OK - ");
3000 wrbuf_printf(wr, "Partial " ODR_INT_PRINTF " - ",
3001 *resp->presentStatus);
3003 wrbuf_printf(wr, " %s " ODR_INT_PRINTF "+" ODR_INT_PRINTF " ",
3004 req->resultSetId, *req->resultSetStartPoint,
3005 *req->numberOfRecordsRequested);
3006 yaz_log(log_request, "%s", wrbuf_cstr(wr) );
3011 resp->numberOfRecordsReturned = num;
3012 resp->nextResultSetPosition = next;
3018 * Scan was implemented rather in a hurry, and with support for only the basic
3019 * elements of the service in the backend API. Suggestions are welcome.
3021 static Z_APDU *process_scanRequest(association *assoc, request *reqb)
3023 Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
3024 Z_APDU *apdu = (Z_APDU *)odr_malloc(assoc->encode, sizeof(*apdu));
3025 Z_ScanResponse *res = (Z_ScanResponse *)
3026 odr_malloc(assoc->encode, sizeof(*res));
3027 Odr_int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
3028 Odr_int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
3029 Z_ListEntries *ents = (Z_ListEntries *)
3030 odr_malloc(assoc->encode, sizeof(*ents));
3031 Z_DiagRecs *diagrecs_p = NULL;
3032 bend_scan_rr *bsrr = (bend_scan_rr *)
3033 odr_malloc(assoc->encode, sizeof(*bsrr));
3034 struct scan_entry *save_entries;
3037 yaz_log(log_requestdetail, "Got ScanRequest");
3039 apdu->which = Z_APDU_scanResponse;
3040 apdu->u.scanResponse = res;
3041 res->referenceId = req->referenceId;
3043 /* if step is absent, set it to 0 */
3045 step_size = odr_int_to_int(*req->stepSize);
3048 res->scanStatus = scanStatus;
3049 res->numberOfEntriesReturned = numberOfEntriesReturned;
3050 res->positionOfTerm = 0;
3051 res->entries = ents;
3052 ents->num_entries = 0;
3053 ents->entries = NULL;
3054 ents->num_nonsurrogateDiagnostics = 0;
3055 ents->nonsurrogateDiagnostics = NULL;
3056 res->attributeSet = 0;
3059 if (req->databaseNames)
3062 for (i = 0; i < req->num_databaseNames; i++)
3063 yaz_log(log_requestdetail, "Database '%s'", req->databaseNames[i]);
3065 bsrr->scanClause = 0;
3067 bsrr->errstring = 0;
3068 bsrr->num_bases = req->num_databaseNames;
3069 bsrr->basenames = req->databaseNames;
3070 bsrr->num_entries = odr_int_to_int(*req->numberOfTermsRequested);
3071 bsrr->term = req->termListAndStartPoint;
3072 bsrr->referenceId = req->referenceId;
3073 bsrr->stream = assoc->encode;
3074 bsrr->print = assoc->print;
3075 bsrr->step_size = &step_size;
3076 bsrr->setname = yaz_oi_get_string_oid(&req->otherInfo,
3077 yaz_oid_userinfo_scan_set, 1, 0);
3079 bsrr->extra_args = 0;
3080 bsrr->extra_response_data = 0;
3081 /* For YAZ 2.0 and earlier it was the backend handler that
3082 initialized entries (member display_term did not exist)
3083 YAZ 2.0 and later sets 'entries' and initialize all members
3084 including 'display_term'. If YAZ 2.0 or later sees that
3085 entries was modified - we assume that it is an old handler and
3086 that 'display_term' is _not_ set.
3088 if (bsrr->num_entries > 0)
3091 bsrr->entries = (struct scan_entry *)
3092 odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
3094 for (i = 0; i<bsrr->num_entries; i++)
3096 bsrr->entries[i].term = 0;
3097 bsrr->entries[i].occurrences = 0;
3098 bsrr->entries[i].errcode = 0;
3099 bsrr->entries[i].errstring = 0;
3100 bsrr->entries[i].display_term = 0;
3103 save_entries = bsrr->entries; /* save it so we can compare later */
3105 bsrr->attributeset = req->attributeSet;
3106 log_scan_term_level(log_requestdetail, req->termListAndStartPoint,
3107 bsrr->attributeset);
3108 bsrr->term_position = req->preferredPositionInResponse ?
3109 odr_int_to_int(*req->preferredPositionInResponse) : 1;
3111 ((int (*)(void *, bend_scan_rr *))
3112 (*assoc->init->bend_scan))(assoc->backend, bsrr);
3115 diagrecs_p = zget_DiagRecs(assoc->encode,
3116 bsrr->errcode, bsrr->errstring);
3120 Z_Entry **tab = (Z_Entry **)
3121 odr_malloc(assoc->encode, sizeof(*tab) * bsrr->num_entries);
3123 if (bsrr->status == BEND_SCAN_PARTIAL)
3124 *scanStatus = Z_Scan_partial_5;
3126 *scanStatus = Z_Scan_success;
3127 res->stepSize = odr_intdup(assoc->encode, step_size);
3128 ents->entries = tab;
3129 ents->num_entries = bsrr->num_entries;
3130 res->numberOfEntriesReturned = odr_intdup(assoc->encode,
3132 res->positionOfTerm = odr_intdup(assoc->encode, bsrr->term_position);
3133 for (i = 0; i < bsrr->num_entries; i++)
3138 tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
3139 if (bsrr->entries[i].occurrences >= 0)
3141 e->which = Z_Entry_termInfo;
3142 e->u.termInfo = t = (Z_TermInfo *)
3143 odr_malloc(assoc->encode, sizeof(*t));
3144 t->suggestedAttributes = 0;
3146 if (save_entries == bsrr->entries &&
3147 bsrr->entries[i].display_term)
3149 /* the entries was _not_ set by the handler. So it's
3150 safe to test for new member display_term. It is
3153 t->displayTerm = odr_strdup(assoc->encode,
3154 bsrr->entries[i].display_term);
3156 t->alternativeTerm = 0;
3157 t->byAttributes = 0;
3158 t->otherTermInfo = 0;
3159 t->globalOccurrences = &bsrr->entries[i].occurrences;
3160 t->term = (Z_Term *)
3161 odr_malloc(assoc->encode, sizeof(*t->term));
3162 t->term->which = Z_Term_general;
3163 t->term->u.general =
3164 odr_create_Odr_oct(assoc->encode,
3165 bsrr->entries[i].term,
3166 strlen(bsrr->entries[i].term));
3167 yaz_log(YLOG_DEBUG, " term #%d: '%s' (" ODR_INT_PRINTF ")", i,
3168 bsrr->entries[i].term, bsrr->entries[i].occurrences);
3172 Z_DiagRecs *drecs = zget_DiagRecs(assoc->encode,
3173 bsrr->entries[i].errcode,
3174 bsrr->entries[i].errstring);
3175 assert(drecs->num_diagRecs == 1);
3176 e->which = Z_Entry_surrogateDiagnostic;
3177 assert(drecs->diagRecs[0]);
3178 e->u.surrogateDiagnostic = drecs->diagRecs[0];
3184 ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
3185 ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
3190 WRBUF wr = wrbuf_alloc();
3191 wrbuf_printf(wr, "Scan ");
3192 for (i = 0 ; i < req->num_databaseNames; i++)
3195 wrbuf_printf(wr, "+");
3196 wrbuf_puts(wr, req->databaseNames[i]);
3199 wrbuf_printf(wr, " ");
3202 wr_diag(wr, bsrr->errcode, bsrr->errstring);
3204 wrbuf_printf(wr, "OK");
3206 wrbuf_printf(wr, " " ODR_INT_PRINTF " - " ODR_INT_PRINTF "+"
3207 ODR_INT_PRINTF "+" ODR_INT_PRINTF,
3208 res->numberOfEntriesReturned ?
3209 *res->numberOfEntriesReturned : 0,
3210 (req->preferredPositionInResponse ?
3211 *req->preferredPositionInResponse : 1),
3212 *req->numberOfTermsRequested,
3213 (res->stepSize ? *res->stepSize : 1));
3216 wrbuf_printf(wr, "+%s", bsrr->setname);
3218 wrbuf_printf(wr, " ");
3219 yaz_scan_to_wrbuf(wr, req->termListAndStartPoint,
3220 bsrr->attributeset);
3221 yaz_log(log_request, "%s", wrbuf_cstr(wr) );
3227 static Z_APDU *process_sortRequest(association *assoc, request *reqb)
3230 Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
3231 Z_SortResponse *res = (Z_SortResponse *)
3232 odr_malloc(assoc->encode, sizeof(*res));
3233 bend_sort_rr *bsrr = (bend_sort_rr *)
3234 odr_malloc(assoc->encode, sizeof(*bsrr));
3236 Z_APDU *apdu = (Z_APDU *)odr_malloc(assoc->encode, sizeof(*apdu));
3238 yaz_log(log_requestdetail, "Got SortRequest.");
3240 bsrr->num_input_setnames = req->num_inputResultSetNames;
3241 for (i=0;i<req->num_inputResultSetNames;i++)
3242 yaz_log(log_requestdetail, "Input resultset: '%s'",
3243 req->inputResultSetNames[i]);
3244 bsrr->input_setnames = req->inputResultSetNames;
3245 bsrr->referenceId = req->referenceId;
3246 bsrr->output_setname = req->sortedResultSetName;
3247 yaz_log(log_requestdetail, "Output resultset: '%s'",
3248 req->sortedResultSetName);
3249 bsrr->sort_sequence = req->sortSequence;
3250 /*FIXME - dump those sequences too */
3251 bsrr->stream = assoc->encode;
3252 bsrr->print = assoc->print;
3254 bsrr->sort_status = Z_SortResponse_failure;
3256 bsrr->errstring = 0;
3258 (*assoc->init->bend_sort)(assoc->backend, bsrr);
3260 res->referenceId = bsrr->referenceId;
3261 res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
3262 res->resultSetStatus = 0;
3265 Z_DiagRecs *dr = zget_DiagRecs(assoc->encode,
3266 bsrr->errcode, bsrr->errstring);
3267 res->diagnostics = dr->diagRecs;
3268 res->num_diagnostics = dr->num_diagRecs;
3272 res->num_diagnostics = 0;
3273 res->diagnostics = 0;
3275 res->resultCount = 0;
3278 apdu->which = Z_APDU_sortResponse;
3279 apdu->u.sortResponse = res;
3282 WRBUF wr = wrbuf_alloc();
3283 wrbuf_printf(wr, "Sort ");
3285 wrbuf_printf(wr, " ERROR %d", bsrr->errcode);
3287 wrbuf_printf(wr, "OK -");
3288 wrbuf_printf(wr, " (");
3289 for (i = 0; i<req->num_inputResultSetNames; i++)
3292 wrbuf_printf(wr, "+");
3293 wrbuf_puts(wr, req->inputResultSetNames[i]);
3295 wrbuf_printf(wr, ")->%s ",req->sortedResultSetName);
3297 yaz_log(log_request, "%s", wrbuf_cstr(wr) );
3303 static Z_APDU *process_deleteRequest(association *assoc, request *reqb)
3306 Z_DeleteResultSetRequest *req =
3307 reqb->apdu_request->u.deleteResultSetRequest;
3308 Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
3309 odr_malloc(assoc->encode, sizeof(*res));
3310 bend_delete_rr *bdrr = (bend_delete_rr *)
3311 odr_malloc(assoc->encode, sizeof(*bdrr));
3312 Z_APDU *apdu = (Z_APDU *)odr_malloc(assoc->encode, sizeof(*apdu));
3314 yaz_log(log_requestdetail, "Got DeleteRequest.");
3316 bdrr->num_setnames = req->num_resultSetList;
3317 bdrr->setnames = req->resultSetList;
3318 for (i = 0; i<req->num_resultSetList; i++)
3319 yaz_log(log_requestdetail, "resultset: '%s'",
3320 req->resultSetList[i]);
3321 bdrr->stream = assoc->encode;
3322 bdrr->print = assoc->print;
3323 bdrr->function = odr_int_to_int(*req->deleteFunction);
3324 bdrr->referenceId = req->referenceId;
3326 if (bdrr->num_setnames > 0)
3328 bdrr->statuses = (int*)
3329 odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
3330 bdrr->num_setnames);
3331 for (i = 0; i < bdrr->num_setnames; i++)
3332 bdrr->statuses[i] = 0;
3334 (*assoc->init->bend_delete)(assoc->backend, bdrr);
3336 res->referenceId = req->referenceId;
3338 res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
3340 res->deleteListStatuses = 0;
3341 if (bdrr->num_setnames > 0)
3344 res->deleteListStatuses = (Z_ListStatuses *)
3345 odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
3346 res->deleteListStatuses->num = bdrr->num_setnames;
3347 res->deleteListStatuses->elements =
3349 odr_malloc(assoc->encode,
3350 sizeof(*res->deleteListStatuses->elements) *
3351 bdrr->num_setnames);
3352 for (i = 0; i<bdrr->num_setnames; i++)
3354 res->deleteListStatuses->elements[i] =
3356 odr_malloc(assoc->encode,
3357 sizeof(**res->deleteListStatuses->elements));
3358 res->deleteListStatuses->elements[i]->status =
3359 odr_intdup(assoc->encode, bdrr->statuses[i]);
3360 res->deleteListStatuses->elements[i]->id =
3361 odr_strdup(assoc->encode, bdrr->setnames[i]);
3364 res->numberNotDeleted = 0;
3365 res->bulkStatuses = 0;
3366 res->deleteMessage = 0;
3369 apdu->which = Z_APDU_deleteResultSetResponse;
3370 apdu->u.deleteResultSetResponse = res;
3373 WRBUF wr = wrbuf_alloc();
3374 wrbuf_printf(wr, "Delete ");
3375 if (bdrr->delete_status)
3376 wrbuf_printf(wr, "ERROR %d", bdrr->delete_status);
3378 wrbuf_printf(wr, "OK -");
3379 for (i = 0; i<req->num_resultSetList; i++)
3380 wrbuf_printf(wr, " %s ", req->resultSetList[i]);
3381 yaz_log(log_request, "%s", wrbuf_cstr(wr) );
3387 static void process_close(association *assoc, request *reqb)
3389 Z_Close *req = reqb->apdu_request->u.close;
3390 static char *reasons[] =
3397 "securityViolation",
3404 yaz_log(log_requestdetail, "Got Close, reason %s, message %s",
3405 reasons[*req->closeReason], req->diagnosticInformation ?
3406 req->diagnosticInformation : "NULL");
3407 if (assoc->version < 3) /* to make do_force respond with close */
3409 do_close_req(assoc, Z_Close_finished,
3410 "Association terminated by client", reqb);
3411 yaz_log(log_request,"Close OK");
3414 static Z_APDU *process_segmentRequest(association *assoc, request *reqb)
3416 bend_segment_rr req;
3418 req.segment = reqb->apdu_request->u.segmentRequest;
3419 req.stream = assoc->encode;
3420 req.decode = assoc->decode;
3421 req.print = assoc->print;
3422 req.association = assoc;
3424 (*assoc->init->bend_segment)(assoc->backend, &req);
3429 static Z_APDU *process_ESRequest(association *assoc, request *reqb)
3431 bend_esrequest_rr esrequest;
3432 const char *ext_name = "unknown";
3434 Z_ExtendedServicesRequest *req =
3435 reqb->apdu_request->u.extendedServicesRequest;
3436 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
3438 Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
3440 esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
3441 esrequest.stream = assoc->encode;
3442 esrequest.decode = assoc->decode;
3443 esrequest.print = assoc->print;
3444 esrequest.errcode = 0;
3445 esrequest.errstring = NULL;
3446 esrequest.association = assoc;
3447 esrequest.taskPackage = 0;
3448 esrequest.referenceId = req->referenceId;
3450 if (esrequest.esr && esrequest.esr->taskSpecificParameters)
3452 switch(esrequest.esr->taskSpecificParameters->which)
3454 case Z_External_itemOrder:
3455 ext_name = "ItemOrder"; break;
3456 case Z_External_update:
3457 ext_name = "Update"; break;
3458 case Z_External_update0:
3459 ext_name = "Update0"; break;
3460 case Z_External_ESAdmin:
3461 ext_name = "Admin"; break;
3466 (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
3468 resp->referenceId = req->referenceId;
3470 if (esrequest.errcode == -1)
3472 /* Backend service indicates request will be processed */
3473 yaz_log(log_request, "Extended Service: %s (accepted)", ext_name);
3474 *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
3476 else if (esrequest.errcode == 0)
3478 /* Backend service indicates request will be processed */
3479 yaz_log(log_request, "Extended Service: %s (done)", ext_name);
3480 *resp->operationStatus = Z_ExtendedServicesResponse_done;
3484 Z_DiagRecs *diagRecs =
3485 zget_DiagRecs(assoc->encode, esrequest.errcode,
3486 esrequest.errstring);
3487 /* Backend indicates error, request will not be processed */
3488 yaz_log(log_request, "Extended Service: %s (failed)", ext_name);
3489 *resp->operationStatus = Z_ExtendedServicesResponse_failure;
3490 resp->num_diagnostics = diagRecs->num_diagRecs;
3491 resp->diagnostics = diagRecs->diagRecs;
3494 WRBUF wr = wrbuf_alloc();
3495 wrbuf_diags(wr, resp->num_diagnostics, resp->diagnostics);
3496 yaz_log(log_request, "EsRequest %s", wrbuf_cstr(wr) );
3501 /* Do something with the members of bend_extendedservice */
3502 if (esrequest.taskPackage)
3504 resp->taskPackage = z_ext_record_oid(
3505 assoc->encode, yaz_oid_recsyn_extended,
3506 (const char *) esrequest.taskPackage, -1);
3508 yaz_log(YLOG_DEBUG,"Send the result apdu");
3512 int bend_assoc_is_alive(bend_association assoc)
3514 if (assoc->state == ASSOC_DEAD)
3515 return 0; /* already marked as dead. Don't check I/O chan anymore */
3517 return iochan_is_alive(assoc->client_chan);
3524 * c-file-style: "Stroustrup"
3525 * indent-tabs-mode: nil
3527 * vim: shiftwidth=4 tabstop=8 expandtab