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>
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(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(o, Z_SRW_explain_response,
1884 stylesheet = sr->u.explain_request->stylesheet;
1887 res->u.explain_response->diagnostics = diagnostic;
1888 res->u.explain_response->num_diagnostics = num_diagnostic;
1890 srw_bend_explain(assoc, hreq->headers,
1891 sr, res->u.explain_response, &http_code);
1892 if (http_code == 200)
1893 soap_package->u.generic->p = res;
1895 else if (sr->which == Z_SRW_scan_request)
1897 Z_SRW_PDU *res = yaz_srw_get_pdu(o, Z_SRW_scan_response,
1899 stylesheet = sr->u.scan_request->stylesheet;
1902 res->u.scan_response->diagnostics = diagnostic;
1903 res->u.scan_response->num_diagnostics = num_diagnostic;
1905 srw_bend_scan(assoc, hreq->headers, sr, res, &http_code);
1906 if (http_code == 200)
1907 soap_package->u.generic->p = res;
1909 else if (sr->which == Z_SRW_update_request)
1911 Z_SRW_PDU *res = yaz_srw_get_pdu(o, Z_SRW_update_response,
1913 yaz_log(YLOG_DEBUG, "handling SRW UpdateRequest");
1916 res->u.update_response->diagnostics = diagnostic;
1917 res->u.update_response->num_diagnostics = num_diagnostic;
1919 yaz_log(YLOG_DEBUG, "num_diag = %d", res->u.update_response->num_diagnostics );
1920 srw_bend_update(assoc, hreq->headers,
1921 sr, res->u.update_response, &http_code);
1922 if (http_code == 200)
1923 soap_package->u.generic->p = res;
1927 yaz_log(log_request, "SOAP ERROR");
1928 /* FIXME - what error, what query */
1930 z_soap_error(assoc->encode, soap_package,
1931 "SOAP-ENV:Client", "Bad method", 0);
1933 if (http_code == 200 || http_code == 500)
1935 static Z_SOAP_Handler soap_handlers[4] = {
1937 {YAZ_XMLNS_SRU_v1_1, 0, (Z_SOAP_fun) yaz_srw_codec},
1938 {YAZ_XMLNS_SRU_v1_0, 0, (Z_SOAP_fun) yaz_srw_codec},
1939 {YAZ_XMLNS_UPDATE_v0_9, 0, (Z_SOAP_fun) yaz_ucp_codec},
1944 p = z_get_HTTP_Response(o, 200);
1945 hres = p->u.HTTP_Response;
1947 if (!stylesheet && assoc->server)
1948 stylesheet = assoc->server->stylesheet;
1950 /* empty stylesheet means NO stylesheet */
1951 if (stylesheet && *stylesheet == '\0')
1954 z_soap_codec_enc_xsl(assoc->encode, &soap_package,
1955 &hres->content_buf, &hres->content_len,
1956 soap_handlers, charset, stylesheet);
1957 hres->code = http_code;
1959 strcpy(ctype, "text/xml");
1960 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1963 p = z_get_HTTP_Response(o, http_code);
1967 p = z_get_HTTP_Response(o, 500);
1968 hres = p->u.HTTP_Response;
1969 if (!strcmp(hreq->version, "1.0"))
1971 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1972 if (v && !strcmp(v, "Keep-Alive"))
1976 hres->version = "1.0";
1980 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1981 if (v && !strcmp(v, "close"))
1985 hres->version = "1.1";
1987 if (!keepalive || !assoc->last_control->keepalive)
1989 z_HTTP_header_add(o, &hres->headers, "Connection", "close");
1990 assoc->state = ASSOC_DEAD;
1991 assoc->cs_get_mask = 0;
1996 const char *alive = z_HTTP_header_lookup(hreq->headers, "Keep-Alive");
1998 if (alive && yaz_isdigit(*(const unsigned char *) alive))
2002 if (t < 0 || t > 3600)
2004 iochan_settimeout(assoc->client_chan,t);
2005 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
2007 process_gdu_response(assoc, req, p);
2010 static void process_gdu_request(association *assoc, request *req)
2012 if (req->gdu_request->which == Z_GDU_Z3950)
2015 req->apdu_request = req->gdu_request->u.z3950;
2016 if (process_z_request(assoc, req, &msg) < 0)
2017 do_close_req(assoc, Z_Close_systemProblem, msg, req);
2019 else if (req->gdu_request->which == Z_GDU_HTTP_Request)
2020 process_http_request(assoc, req);
2023 do_close_req(assoc, Z_Close_systemProblem, "bad protocol packet", req);
2028 * Initiate request processing.
2030 static int process_z_request(association *assoc, request *req, char **msg)
2035 *msg = "Unknown Error";
2036 assert(req && req->state == REQUEST_IDLE);
2037 if (req->apdu_request->which != Z_APDU_initRequest && !assoc->init)
2039 *msg = "Missing InitRequest";
2042 switch (req->apdu_request->which)
2044 case Z_APDU_initRequest:
2045 res = process_initRequest(assoc, req); break;
2046 case Z_APDU_searchRequest:
2047 res = process_searchRequest(assoc, req); break;
2048 case Z_APDU_presentRequest:
2049 res = process_presentRequest(assoc, req); break;
2050 case Z_APDU_scanRequest:
2051 if (assoc->init->bend_scan)
2052 res = process_scanRequest(assoc, req);
2055 *msg = "Cannot handle Scan APDU";
2059 case Z_APDU_extendedServicesRequest:
2060 if (assoc->init->bend_esrequest)
2061 res = process_ESRequest(assoc, req);
2064 *msg = "Cannot handle Extended Services APDU";
2068 case Z_APDU_sortRequest:
2069 if (assoc->init->bend_sort)
2070 res = process_sortRequest(assoc, req);
2073 *msg = "Cannot handle Sort APDU";
2078 process_close(assoc, req);
2080 case Z_APDU_deleteResultSetRequest:
2081 if (assoc->init->bend_delete)
2082 res = process_deleteRequest(assoc, req);
2085 *msg = "Cannot handle Delete APDU";
2089 case Z_APDU_segmentRequest:
2090 if (assoc->init->bend_segment)
2092 res = process_segmentRequest(assoc, req);
2096 *msg = "Cannot handle Segment APDU";
2100 case Z_APDU_triggerResourceControlRequest:
2103 *msg = "Bad APDU received";
2108 yaz_log(YLOG_DEBUG, " result immediately available");
2109 retval = process_z_response(assoc, req, res);
2113 yaz_log(YLOG_DEBUG, " result unavailable");
2120 * Encode response, and transfer the request structure to the outgoing queue.
2122 static int process_gdu_response(association *assoc, request *req, Z_GDU *res)
2124 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
2128 if (!z_GDU(assoc->print, &res, 0, 0))
2129 yaz_log(YLOG_WARN, "ODR print error: %s",
2130 odr_errmsg(odr_geterror(assoc->print)));
2131 odr_reset(assoc->print);
2133 if (!z_GDU(assoc->encode, &res, 0, 0))
2135 yaz_log(YLOG_WARN, "ODR error when encoding PDU: %s [element %s]",
2136 odr_errmsg(odr_geterror(assoc->decode)),
2137 odr_getelement(assoc->decode));
2140 req->response = odr_getbuf(assoc->encode, &req->len_response,
2141 &req->size_response);
2142 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
2143 odr_reset(assoc->encode);
2144 req->state = REQUEST_IDLE;
2145 request_enq(&assoc->outgoing, req);
2146 /* turn the work over to the ir_session handler */
2147 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
2148 assoc->cs_put_mask = EVENT_OUTPUT;
2149 /* Is there more work to be done? give that to the input handler too */
2152 req = request_head(&assoc->incoming);
2153 if (req && req->state == REQUEST_IDLE)
2155 request_deq(&assoc->incoming);
2156 process_gdu_request(assoc, req);
2165 * Encode response, and transfer the request structure to the outgoing queue.
2167 static int process_z_response(association *assoc, request *req, Z_APDU *res)
2169 Z_GDU *gres = (Z_GDU *) odr_malloc(assoc->encode, sizeof(*gres));
2170 gres->which = Z_GDU_Z3950;
2171 gres->u.z3950 = res;
2173 return process_gdu_response(assoc, req, gres);
2176 static char *get_vhost(Z_OtherInformation *otherInfo)
2178 return yaz_oi_get_string_oid(&otherInfo, yaz_oid_userinfo_proxy, 1, 0);
2182 * Handle init request.
2183 * At the moment, we don't check the options
2184 * anywhere else in the code - we just try not to do anything that would
2185 * break a naive client. We'll toss 'em into the association block when
2186 * we need them there.
2188 static Z_APDU *process_initRequest(association *assoc, request *reqb)
2190 Z_InitRequest *req = reqb->apdu_request->u.initRequest;
2191 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
2192 Z_InitResponse *resp = apdu->u.initResponse;
2193 bend_initresult *binitres;
2195 statserv_options_block *cb = 0; /* by default no control for backend */
2197 if (control_association(assoc, get_vhost(req->otherInfo), 1))
2198 cb = statserv_getcontrol(); /* got control block for backend */
2200 if (cb && assoc->backend)
2201 (*cb->bend_close)(assoc->backend);
2203 yaz_log(log_requestdetail, "Got initRequest");
2204 if (req->implementationId)
2205 yaz_log(log_requestdetail, "Id: %s",
2206 req->implementationId);
2207 if (req->implementationName)
2208 yaz_log(log_requestdetail, "Name: %s",
2209 req->implementationName);
2210 if (req->implementationVersion)
2211 yaz_log(log_requestdetail, "Version: %s",
2212 req->implementationVersion);
2214 assoc_init_reset(assoc,
2215 yaz_oi_get_string_oid(&req->otherInfo,
2216 yaz_oid_userinfo_client_ip, 1, 0));
2217 assoc->init->auth = req->idAuthentication;
2218 assoc->init->referenceId = req->referenceId;
2220 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
2222 Z_CharSetandLanguageNegotiation *negotiation =
2223 yaz_get_charneg_record (req->otherInfo);
2225 negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
2226 assoc->init->charneg_request = negotiation;
2229 /* by default named_result_sets is 0 .. Enable it if client asks for it. */
2230 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
2231 assoc->init->named_result_sets = 1;
2236 if (req->implementationVersion)
2237 yaz_log(log_requestdetail, "Config: %s",
2240 iochan_settimeout(assoc->client_chan, cb->idle_timeout);
2242 /* we have a backend control block, so call that init function */
2243 if (!(binitres = (*cb->bend_init)(assoc->init)))
2245 yaz_log(YLOG_WARN, "Bad response from backend.");
2248 assoc->backend = binitres->handle;
2252 /* no backend. return error */
2253 binitres = (bend_initresult *)
2254 odr_malloc(assoc->encode, sizeof(*binitres));
2255 binitres->errstring = 0;
2256 binitres->errcode = YAZ_BIB1_PERMANENT_SYSTEM_ERROR;
2257 iochan_settimeout(assoc->client_chan, 10);
2259 if ((assoc->init->bend_sort))
2260 yaz_log(YLOG_DEBUG, "Sort handler installed");
2261 if ((assoc->init->bend_search))
2262 yaz_log(YLOG_DEBUG, "Search handler installed");
2263 if ((assoc->init->bend_present))
2264 yaz_log(YLOG_DEBUG, "Present handler installed");
2265 if ((assoc->init->bend_esrequest))
2266 yaz_log(YLOG_DEBUG, "ESRequest handler installed");
2267 if ((assoc->init->bend_delete))
2268 yaz_log(YLOG_DEBUG, "Delete handler installed");
2269 if ((assoc->init->bend_scan))
2270 yaz_log(YLOG_DEBUG, "Scan handler installed");
2271 if ((assoc->init->bend_segment))
2272 yaz_log(YLOG_DEBUG, "Segment handler installed");
2274 resp->referenceId = req->referenceId;
2276 /* let's tell the client what we can do */
2277 if (ODR_MASK_GET(req->options, Z_Options_search))
2279 ODR_MASK_SET(resp->options, Z_Options_search);
2280 strcat(options, "srch");
2282 if (ODR_MASK_GET(req->options, Z_Options_present))
2284 ODR_MASK_SET(resp->options, Z_Options_present);
2285 strcat(options, " prst");
2287 if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
2288 assoc->init->bend_delete)
2290 ODR_MASK_SET(resp->options, Z_Options_delSet);
2291 strcat(options, " del");
2293 if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
2294 assoc->init->bend_esrequest)
2296 ODR_MASK_SET(resp->options, Z_Options_extendedServices);
2297 strcat(options, " extendedServices");
2299 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets)
2300 && assoc->init->named_result_sets)
2302 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
2303 strcat(options, " namedresults");
2305 if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
2307 ODR_MASK_SET(resp->options, Z_Options_scan);
2308 strcat(options, " scan");
2310 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
2312 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
2313 strcat(options, " concurrop");
2315 if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
2317 ODR_MASK_SET(resp->options, Z_Options_sort);
2318 strcat(options, " sort");
2321 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
2323 Z_OtherInformationUnit *p0;
2325 if (!assoc->init->charneg_response)
2327 if (assoc->init->query_charset)
2329 assoc->init->charneg_response = yaz_set_response_charneg(
2330 assoc->encode, assoc->init->query_charset, 0,
2331 assoc->init->records_in_same_charset);
2335 yaz_log(YLOG_WARN, "default query_charset not defined by backend");
2338 if (assoc->init->charneg_response
2339 && (p0=yaz_oi_update(&resp->otherInfo, assoc->encode, NULL, 0, 0)))
2341 p0->which = Z_OtherInfo_externallyDefinedInfo;
2342 p0->information.externallyDefinedInfo =
2343 assoc->init->charneg_response;
2344 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
2345 strcat(options, " negotiation");
2348 if (ODR_MASK_GET(req->options, Z_Options_triggerResourceCtrl))
2349 ODR_MASK_SET(resp->options, Z_Options_triggerResourceCtrl);
2351 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
2353 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
2354 assoc->version = 1; /* 1 & 2 are equivalent */
2356 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
2358 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
2361 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
2363 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
2367 yaz_log(log_requestdetail, "Negotiated to v%d: %s", assoc->version, options);
2369 if (*req->maximumRecordSize < assoc->maximumRecordSize)
2370 assoc->maximumRecordSize = odr_int_to_int(*req->maximumRecordSize);
2372 if (*req->preferredMessageSize < assoc->preferredMessageSize)
2373 assoc->preferredMessageSize = odr_int_to_int(*req->preferredMessageSize);
2375 resp->preferredMessageSize =
2376 odr_intdup(assoc->encode, assoc->preferredMessageSize);
2377 resp->maximumRecordSize =
2378 odr_intdup(assoc->encode, assoc->maximumRecordSize);
2380 resp->implementationId = odr_prepend(assoc->encode,
2381 assoc->init->implementation_id,
2382 resp->implementationId);
2384 resp->implementationVersion = odr_prepend(assoc->encode,
2385 assoc->init->implementation_version,
2386 resp->implementationVersion);
2388 resp->implementationName = odr_prepend(assoc->encode,
2389 assoc->init->implementation_name,
2390 odr_prepend(assoc->encode, "GFS", resp->implementationName));
2392 if (binitres->errcode)
2394 assoc->state = ASSOC_DEAD;
2395 resp->userInformationField =
2396 init_diagnostics(assoc->encode, binitres->errcode,
2397 binitres->errstring);
2401 assoc->state = ASSOC_UP;
2405 if (!req->idAuthentication)
2406 yaz_log(log_request, "Auth none");
2407 else if (req->idAuthentication->which == Z_IdAuthentication_open)
2409 const char *open = req->idAuthentication->u.open;
2410 const char *slash = strchr(open, '/');
2416 yaz_log(log_request, "Auth open %.*s", len, open);
2418 else if (req->idAuthentication->which == Z_IdAuthentication_idPass)
2420 const char *user = req->idAuthentication->u.idPass->userId;
2421 const char *group = req->idAuthentication->u.idPass->groupId;
2422 yaz_log(log_request, "Auth idPass %s %s",
2423 user ? user : "-", group ? group : "-");
2425 else if (req->idAuthentication->which
2426 == Z_IdAuthentication_anonymous)
2428 yaz_log(log_request, "Auth anonymous");
2432 yaz_log(log_request, "Auth other");
2437 WRBUF wr = wrbuf_alloc();
2438 wrbuf_printf(wr, "Init ");
2439 if (binitres->errcode)
2440 wrbuf_printf(wr, "ERROR %d", binitres->errcode);
2442 wrbuf_printf(wr, "OK -");
2443 wrbuf_printf(wr, " ID:%s Name:%s Version:%s",
2444 (req->implementationId ? req->implementationId :"-"),
2445 (req->implementationName ?
2446 req->implementationName : "-"),
2447 (req->implementationVersion ?
2448 req->implementationVersion : "-")
2450 yaz_log(log_request, "%s", wrbuf_cstr(wr));
2457 * Set the specified `errcode' and `errstring' into a UserInfo-1
2458 * external to be returned to the client in accordance with Z35.90
2459 * Implementor Agreement 5 (Returning diagnostics in an InitResponse):
2460 * http://lcweb.loc.gov/z3950/agency/agree/initdiag.html
2462 static Z_External *init_diagnostics(ODR odr, int error, const char *addinfo)
2464 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2465 addinfo ? " -- " : "", addinfo ? addinfo : "");
2466 return zget_init_diagnostics(odr, error, addinfo);
2470 * nonsurrogate diagnostic record.
2472 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
2474 Z_Records *rec = (Z_Records *) odr_malloc(assoc->encode, sizeof(*rec));
2476 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2477 addinfo ? " -- " : "", addinfo ? addinfo : "");
2479 rec->which = Z_Records_NSD;
2480 rec->u.nonSurrogateDiagnostic = zget_DefaultDiagFormat(assoc->encode,
2486 * surrogate diagnostic.
2488 static Z_NamePlusRecord *surrogatediagrec(association *assoc,
2490 int error, const char *addinfo)
2492 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2493 addinfo ? " -- " : "", addinfo ? addinfo : "");
2494 return zget_surrogateDiagRec(assoc->encode, dbname, error, addinfo);
2497 static Z_Records *pack_records(association *a, char *setname, Odr_int start,
2498 Odr_int *num, Z_RecordComposition *comp,
2499 Odr_int *next, Odr_int *pres,
2500 Z_ReferenceId *referenceId,
2501 Odr_oid *oid, int *errcode)
2503 int recno, total_length = 0, dumped_records = 0;
2504 int toget = odr_int_to_int(*num);
2505 Z_Records *records =
2506 (Z_Records *) odr_malloc(a->encode, sizeof(*records));
2507 Z_NamePlusRecordList *reclist =
2508 (Z_NamePlusRecordList *) odr_malloc(a->encode, sizeof(*reclist));
2510 records->which = Z_Records_DBOSD;
2511 records->u.databaseOrSurDiagnostics = reclist;
2512 reclist->num_records = 0;
2515 return diagrec(a, YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE, 0);
2516 else if (toget == 0)
2517 reclist->records = odr_nullval();
2519 reclist->records = (Z_NamePlusRecord **)
2520 odr_malloc(a->encode, sizeof(*reclist->records) * toget);
2522 *pres = Z_PresentStatus_success;
2526 yaz_log(log_requestdetail, "Request to pack " ODR_INT_PRINTF "+%d %s", start, toget, setname);
2527 yaz_log(log_requestdetail, "pms=%d, mrs=%d", a->preferredMessageSize,
2528 a->maximumRecordSize);
2529 for (recno = odr_int_to_int(start); reclist->num_records < toget; recno++)
2532 Z_NamePlusRecord *thisrec;
2533 int this_length = 0;
2535 * we get the number of bytes allocated on the stream before any
2536 * allocation done by the backend - this should give us a reasonable
2537 * idea of the total size of the data so far.
2539 total_length = odr_total(a->encode) - dumped_records;
2545 freq.last_in_set = 0;
2546 freq.setname = setname;
2547 freq.surrogate_flag = 0;
2548 freq.number = recno;
2550 freq.request_format = oid;
2551 freq.output_format = 0;
2552 freq.stream = a->encode;
2553 freq.print = a->print;
2554 freq.referenceId = referenceId;
2557 retrieve_fetch(a, &freq);
2559 *next = freq.last_in_set ? 0 : recno + 1;
2563 if (!freq.surrogate_flag) /* non-surrogate diagnostic i.e. global */
2566 *pres = Z_PresentStatus_failure;
2567 /* for 'present request out of range',
2568 set addinfo to record position if not set */
2569 if (freq.errcode == YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE &&
2570 freq.errstring == 0)
2572 sprintf(s, "%d", recno);
2576 *errcode = freq.errcode;
2577 return diagrec(a, freq.errcode, freq.errstring);
2579 reclist->records[reclist->num_records] =
2580 surrogatediagrec(a, freq.basename, freq.errcode,
2582 reclist->num_records++;
2585 if (freq.record == 0) /* no error and no record ? */
2587 *pres = Z_PresentStatus_partial_4;
2588 *next = 0; /* signal end-of-set and stop */
2592 this_length = freq.len;
2594 this_length = odr_total(a->encode) - total_length - dumped_records;
2595 yaz_log(YLOG_DEBUG, " fetched record, len=%d, total=%d dumped=%d",
2596 this_length, total_length, dumped_records);
2597 if (a->preferredMessageSize > 0 &&
2598 this_length + total_length > a->preferredMessageSize)
2600 /* record is small enough, really */
2601 if (this_length <= a->preferredMessageSize && recno > start)
2603 yaz_log(log_requestdetail, " Dropped last normal-sized record");
2604 *pres = Z_PresentStatus_partial_2;
2609 /* record can only be fetched by itself */
2610 if (this_length < a->maximumRecordSize)
2612 yaz_log(log_requestdetail, " Record > prefmsgsz");
2615 yaz_log(YLOG_DEBUG, " Dropped it");
2616 reclist->records[reclist->num_records] =
2619 YAZ_BIB1_RECORD_EXCEEDS_PREFERRED_MESSAGE_SIZE, 0);
2620 reclist->num_records++;
2621 dumped_records += this_length;
2625 else /* too big entirely */
2627 yaz_log(log_requestdetail, "Record > maxrcdsz "
2629 this_length, a->maximumRecordSize);
2630 reclist->records[reclist->num_records] =
2633 YAZ_BIB1_RECORD_EXCEEDS_MAXIMUM_RECORD_SIZE, 0);
2634 reclist->num_records++;
2635 dumped_records += this_length;
2640 if (!(thisrec = (Z_NamePlusRecord *)
2641 odr_malloc(a->encode, sizeof(*thisrec))))
2643 thisrec->databaseName = odr_strdup_null(a->encode, freq.basename);
2644 thisrec->which = Z_NamePlusRecord_databaseRecord;
2646 if (!freq.output_format)
2648 yaz_log(YLOG_WARN, "bend_fetch output_format not set");
2651 thisrec->u.databaseRecord = z_ext_record_oid(
2652 a->encode, freq.output_format, freq.record, freq.len);
2653 if (!thisrec->u.databaseRecord)
2655 reclist->records[reclist->num_records] = thisrec;
2656 reclist->num_records++;
2657 if (freq.last_in_set)
2660 *num = reclist->num_records;
2664 static Z_APDU *process_searchRequest(association *assoc, request *reqb)
2666 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2667 bend_search_rr *bsrr =
2668 (bend_search_rr *)nmem_malloc(reqb->request_mem, sizeof(*bsrr));
2670 yaz_log(log_requestdetail, "Got SearchRequest.");
2671 bsrr->association = assoc;
2672 bsrr->referenceId = req->referenceId;
2673 bsrr->srw_sortKeys = 0;
2674 bsrr->srw_setname = 0;
2675 bsrr->srw_setnameIdleTime = 0;
2676 bsrr->estimated_hit_count = 0;
2677 bsrr->partial_resultset = 0;
2678 bsrr->extra_args = 0;
2679 bsrr->extra_response_data = 0;
2681 yaz_log(log_requestdetail, "ResultSet '%s'", req->resultSetName);
2682 if (req->databaseNames)
2685 for (i = 0; i < req->num_databaseNames; i++)
2686 yaz_log(log_requestdetail, "Database '%s'", req->databaseNames[i]);
2689 yaz_log_zquery_level(log_requestdetail,req->query);
2691 if (assoc->init->bend_search)
2693 bsrr->setname = req->resultSetName;
2694 bsrr->replace_set = *req->replaceIndicator;
2695 bsrr->num_bases = req->num_databaseNames;
2696 bsrr->basenames = req->databaseNames;
2697 bsrr->query = req->query;
2698 bsrr->stream = assoc->encode;
2699 nmem_transfer(odr_getmem(bsrr->stream), reqb->request_mem);
2700 bsrr->decode = assoc->decode;
2701 bsrr->print = assoc->print;
2704 bsrr->errstring = NULL;
2705 bsrr->search_info = NULL;
2706 bsrr->search_input = req->additionalSearchInfo;
2707 if (!bsrr->search_input)
2708 bsrr->search_input = req->otherInfo;
2709 bsrr->present_number = *req->mediumSetPresentNumber;
2711 if (assoc->server && assoc->server->cql_transform
2712 && req->query->which == Z_Query_type_104
2713 && req->query->u.type_104->which == Z_External_CQL)
2715 /* have a CQL query and a CQL to PQF transform .. */
2717 cql2pqf(bsrr->stream, req->query->u.type_104->u.cql,
2718 assoc->server->cql_transform, bsrr->query,
2719 &bsrr->srw_sortKeys);
2721 bsrr->errcode = yaz_diag_srw_to_bib1(srw_errcode);
2724 if (assoc->server && assoc->server->ccl_transform
2725 && req->query->which == Z_Query_type_2) /*CCL*/
2727 /* have a CCL query and a CCL to PQF transform .. */
2729 ccl2pqf(bsrr->stream, req->query->u.type_2,
2730 assoc->server->ccl_transform, bsrr);
2732 bsrr->errcode = yaz_diag_srw_to_bib1(srw_errcode);
2736 (assoc->init->bend_search)(assoc->backend, bsrr);
2740 /* FIXME - make a diagnostic for it */
2741 yaz_log(YLOG_WARN,"Search not supported ?!?!");
2743 return response_searchRequest(assoc, reqb, bsrr);
2747 * Prepare a searchresponse based on the backend results. We probably want
2748 * to look at making the fetching of records nonblocking as well, but
2749 * so far, we'll keep things simple.
2750 * If bsrt is null, that means we're called in response to a communications
2751 * event, and we'll have to get the response for ourselves.
2753 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
2754 bend_search_rr *bsrt)
2756 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2757 Z_APDU *apdu = (Z_APDU *)odr_malloc(assoc->encode, sizeof(*apdu));
2758 Z_SearchResponse *resp = (Z_SearchResponse *)
2759 odr_malloc(assoc->encode, sizeof(*resp));
2760 Odr_int *nulint = odr_intdup(assoc->encode, 0);
2761 Odr_int *next = odr_intdup(assoc->encode, 0);
2762 Odr_int *none = odr_intdup(assoc->encode, Z_SearchResponse_none);
2763 Odr_int returnedrecs = 0;
2765 apdu->which = Z_APDU_searchResponse;
2766 apdu->u.searchResponse = resp;
2767 resp->referenceId = req->referenceId;
2768 resp->additionalSearchInfo = 0;
2769 resp->otherInfo = 0;
2772 yaz_log(YLOG_FATAL, "Bad result from backend");
2775 else if (bsrt->errcode)
2777 resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
2778 resp->resultCount = nulint;
2779 resp->numberOfRecordsReturned = nulint;
2780 resp->nextResultSetPosition = nulint;
2781 resp->searchStatus = odr_booldup(assoc->encode, 0);
2782 resp->resultSetStatus = none;
2783 resp->presentStatus = 0;
2787 bool_t *sr = odr_booldup(assoc->encode, 1);
2788 Odr_int *toget = odr_intdup(assoc->encode, 0);
2789 Z_RecordComposition comp, *compp = 0;
2791 yaz_log(log_requestdetail, "resultCount: " ODR_INT_PRINTF, bsrt->hits);
2794 resp->resultCount = &bsrt->hits;
2796 comp.which = Z_RecordComp_simple;
2797 /* how many records does the user agent want, then? */
2800 else if (bsrt->hits <= *req->smallSetUpperBound)
2802 *toget = bsrt->hits;
2803 if ((comp.u.simple = req->smallSetElementSetNames))
2806 else if (bsrt->hits < *req->largeSetLowerBound)
2808 *toget = *req->mediumSetPresentNumber;
2809 if (*toget > bsrt->hits)
2810 *toget = bsrt->hits;
2811 if ((comp.u.simple = req->mediumSetElementSetNames))
2817 if (*toget && !resp->records)
2819 Odr_int *presst = odr_intdup(assoc->encode, 0);
2820 /* Call bend_present if defined */
2821 if (assoc->init->bend_present)
2823 bend_present_rr *bprr = (bend_present_rr *)
2824 nmem_malloc(reqb->request_mem, sizeof(*bprr));
2825 bprr->setname = req->resultSetName;
2827 bprr->number = odr_int_to_int(*toget);
2828 bprr->format = req->preferredRecordSyntax;
2830 bprr->referenceId = req->referenceId;
2831 bprr->stream = assoc->encode;
2832 bprr->print = assoc->print;
2833 bprr->association = assoc;
2835 bprr->errstring = NULL;
2836 (*assoc->init->bend_present)(assoc->backend, bprr);
2840 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2841 *resp->presentStatus = Z_PresentStatus_failure;
2846 resp->records = pack_records(
2847 assoc, req->resultSetName, 1,
2848 toget, compp, next, presst, req->referenceId,
2849 req->preferredRecordSyntax, NULL);
2852 resp->numberOfRecordsReturned = toget;
2853 returnedrecs = *toget;
2854 resp->presentStatus = presst;
2858 if (*resp->resultCount)
2860 resp->numberOfRecordsReturned = nulint;
2861 resp->presentStatus = 0;
2863 resp->nextResultSetPosition = next;
2864 resp->searchStatus = sr;
2865 resp->resultSetStatus = 0;
2866 if (bsrt->estimated_hit_count)
2868 resp->resultSetStatus = odr_intdup(assoc->encode,
2869 Z_SearchResponse_estimate);
2871 else if (bsrt->partial_resultset)
2873 resp->resultSetStatus = odr_intdup(assoc->encode,
2874 Z_SearchResponse_subset);
2877 resp->additionalSearchInfo = bsrt->search_info;
2882 WRBUF wr = wrbuf_alloc();
2884 for (i = 0 ; i < req->num_databaseNames; i++)
2887 wrbuf_printf(wr, "+");
2888 wrbuf_puts(wr, req->databaseNames[i]);
2890 wrbuf_printf(wr, " ");
2893 wrbuf_printf(wr, "ERROR %d", bsrt->errcode);
2895 wrbuf_printf(wr, "OK " ODR_INT_PRINTF, bsrt->hits);
2896 wrbuf_printf(wr, " %s 1+" ODR_INT_PRINTF " ",
2897 req->resultSetName, returnedrecs);
2898 yaz_query_to_wrbuf(wr, req->query);
2900 yaz_log(log_request, "Search %s", wrbuf_cstr(wr));
2907 * Maybe we got a little over-friendly when we designed bend_fetch to
2908 * get only one record at a time. Some backends can optimise multiple-record
2909 * fetches, and at any rate, there is some overhead involved in
2910 * all that selecting and hopping around. Problem is, of course, that the
2911 * frontend can't know ahead of time how many records it'll need to
2912 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
2913 * is downright lousy as a bulk data transfer protocol.
2915 * To start with, we'll do the fetching of records from the backend
2916 * in one operation: To save some trips in and out of the event-handler,
2917 * and to simplify the interface to pack_records. At any rate, asynch
2918 * operation is more fun in operations that have an unpredictable execution
2919 * speed - which is normally more true for search than for present.
2921 static Z_APDU *process_presentRequest(association *assoc, request *reqb)
2923 Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
2925 Z_PresentResponse *resp;
2930 yaz_log(log_requestdetail, "Got PresentRequest.");
2932 resp = (Z_PresentResponse *)odr_malloc(assoc->encode, sizeof(*resp));
2934 resp->presentStatus = odr_intdup(assoc->encode, 0);
2935 if (assoc->init->bend_present)
2937 bend_present_rr *bprr = (bend_present_rr *)
2938 nmem_malloc(reqb->request_mem, sizeof(*bprr));
2939 bprr->setname = req->resultSetId;
2940 bprr->start = odr_int_to_int(*req->resultSetStartPoint);
2941 bprr->number = odr_int_to_int(*req->numberOfRecordsRequested);
2942 bprr->format = req->preferredRecordSyntax;
2943 bprr->comp = req->recordComposition;
2944 bprr->referenceId = req->referenceId;
2945 bprr->stream = assoc->encode;
2946 bprr->print = assoc->print;
2947 bprr->association = assoc;
2949 bprr->errstring = NULL;
2950 (*assoc->init->bend_present)(assoc->backend, bprr);
2954 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2955 *resp->presentStatus = Z_PresentStatus_failure;
2956 errcode = bprr->errcode;
2959 apdu = (Z_APDU *)odr_malloc(assoc->encode, sizeof(*apdu));
2960 next = odr_intdup(assoc->encode, 0);
2961 num = odr_intdup(assoc->encode, 0);
2963 apdu->which = Z_APDU_presentResponse;
2964 apdu->u.presentResponse = resp;
2965 resp->referenceId = req->referenceId;
2966 resp->otherInfo = 0;
2970 *num = *req->numberOfRecordsRequested;
2972 pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
2973 num, req->recordComposition, next,
2974 resp->presentStatus,
2975 req->referenceId, req->preferredRecordSyntax,
2980 WRBUF wr = wrbuf_alloc();
2981 wrbuf_printf(wr, "Present ");
2983 if (*resp->presentStatus == Z_PresentStatus_failure)
2984 wrbuf_printf(wr, "ERROR %d ", errcode);
2985 else if (*resp->presentStatus == Z_PresentStatus_success)
2986 wrbuf_printf(wr, "OK - ");
2988 wrbuf_printf(wr, "Partial " ODR_INT_PRINTF " - ",
2989 *resp->presentStatus);
2991 wrbuf_printf(wr, " %s " ODR_INT_PRINTF "+" ODR_INT_PRINTF " ",
2992 req->resultSetId, *req->resultSetStartPoint,
2993 *req->numberOfRecordsRequested);
2994 yaz_log(log_request, "%s", wrbuf_cstr(wr) );
2999 resp->numberOfRecordsReturned = num;
3000 resp->nextResultSetPosition = next;
3006 * Scan was implemented rather in a hurry, and with support for only the basic
3007 * elements of the service in the backend API. Suggestions are welcome.
3009 static Z_APDU *process_scanRequest(association *assoc, request *reqb)
3011 Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
3012 Z_APDU *apdu = (Z_APDU *)odr_malloc(assoc->encode, sizeof(*apdu));
3013 Z_ScanResponse *res = (Z_ScanResponse *)
3014 odr_malloc(assoc->encode, sizeof(*res));
3015 Odr_int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
3016 Odr_int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
3017 Z_ListEntries *ents = (Z_ListEntries *)
3018 odr_malloc(assoc->encode, sizeof(*ents));
3019 Z_DiagRecs *diagrecs_p = NULL;
3020 bend_scan_rr *bsrr = (bend_scan_rr *)
3021 odr_malloc(assoc->encode, sizeof(*bsrr));
3022 struct scan_entry *save_entries;
3025 yaz_log(log_requestdetail, "Got ScanRequest");
3027 apdu->which = Z_APDU_scanResponse;
3028 apdu->u.scanResponse = res;
3029 res->referenceId = req->referenceId;
3031 /* if step is absent, set it to 0 */
3033 step_size = odr_int_to_int(*req->stepSize);
3036 res->scanStatus = scanStatus;
3037 res->numberOfEntriesReturned = numberOfEntriesReturned;
3038 res->positionOfTerm = 0;
3039 res->entries = ents;
3040 ents->num_entries = 0;
3041 ents->entries = NULL;
3042 ents->num_nonsurrogateDiagnostics = 0;
3043 ents->nonsurrogateDiagnostics = NULL;
3044 res->attributeSet = 0;
3047 if (req->databaseNames)
3050 for (i = 0; i < req->num_databaseNames; i++)
3051 yaz_log(log_requestdetail, "Database '%s'", req->databaseNames[i]);
3053 bsrr->scanClause = 0;
3055 bsrr->errstring = 0;
3056 bsrr->num_bases = req->num_databaseNames;
3057 bsrr->basenames = req->databaseNames;
3058 bsrr->num_entries = odr_int_to_int(*req->numberOfTermsRequested);
3059 bsrr->term = req->termListAndStartPoint;
3060 bsrr->referenceId = req->referenceId;
3061 bsrr->stream = assoc->encode;
3062 bsrr->print = assoc->print;
3063 bsrr->step_size = &step_size;
3064 bsrr->setname = yaz_oi_get_string_oid(&req->otherInfo,
3065 yaz_oid_userinfo_scan_set, 1, 0);
3067 bsrr->extra_args = 0;
3068 bsrr->extra_response_data = 0;
3069 /* For YAZ 2.0 and earlier it was the backend handler that
3070 initialized entries (member display_term did not exist)
3071 YAZ 2.0 and later sets 'entries' and initialize all members
3072 including 'display_term'. If YAZ 2.0 or later sees that
3073 entries was modified - we assume that it is an old handler and
3074 that 'display_term' is _not_ set.
3076 if (bsrr->num_entries > 0)
3079 bsrr->entries = (struct scan_entry *)
3080 odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
3082 for (i = 0; i<bsrr->num_entries; i++)
3084 bsrr->entries[i].term = 0;
3085 bsrr->entries[i].occurrences = 0;
3086 bsrr->entries[i].errcode = 0;
3087 bsrr->entries[i].errstring = 0;
3088 bsrr->entries[i].display_term = 0;
3091 save_entries = bsrr->entries; /* save it so we can compare later */
3093 bsrr->attributeset = req->attributeSet;
3094 log_scan_term_level(log_requestdetail, req->termListAndStartPoint,
3095 bsrr->attributeset);
3096 bsrr->term_position = req->preferredPositionInResponse ?
3097 odr_int_to_int(*req->preferredPositionInResponse) : 1;
3099 ((int (*)(void *, bend_scan_rr *))
3100 (*assoc->init->bend_scan))(assoc->backend, bsrr);
3103 diagrecs_p = zget_DiagRecs(assoc->encode,
3104 bsrr->errcode, bsrr->errstring);
3108 Z_Entry **tab = (Z_Entry **)
3109 odr_malloc(assoc->encode, sizeof(*tab) * bsrr->num_entries);
3111 if (bsrr->status == BEND_SCAN_PARTIAL)
3112 *scanStatus = Z_Scan_partial_5;
3114 *scanStatus = Z_Scan_success;
3115 res->stepSize = odr_intdup(assoc->encode, step_size);
3116 ents->entries = tab;
3117 ents->num_entries = bsrr->num_entries;
3118 res->numberOfEntriesReturned = odr_intdup(assoc->encode,
3120 res->positionOfTerm = odr_intdup(assoc->encode, bsrr->term_position);
3121 for (i = 0; i < bsrr->num_entries; i++)
3126 tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
3127 if (bsrr->entries[i].occurrences >= 0)
3129 e->which = Z_Entry_termInfo;
3130 e->u.termInfo = t = (Z_TermInfo *)
3131 odr_malloc(assoc->encode, sizeof(*t));
3132 t->suggestedAttributes = 0;
3134 if (save_entries == bsrr->entries &&
3135 bsrr->entries[i].display_term)
3137 /* the entries was _not_ set by the handler. So it's
3138 safe to test for new member display_term. It is
3141 t->displayTerm = odr_strdup(assoc->encode,
3142 bsrr->entries[i].display_term);
3144 t->alternativeTerm = 0;
3145 t->byAttributes = 0;
3146 t->otherTermInfo = 0;
3147 t->globalOccurrences = &bsrr->entries[i].occurrences;
3148 t->term = (Z_Term *)
3149 odr_malloc(assoc->encode, sizeof(*t->term));
3150 t->term->which = Z_Term_general;
3151 t->term->u.general =
3152 odr_create_Odr_oct(assoc->encode,
3153 bsrr->entries[i].term,
3154 strlen(bsrr->entries[i].term));
3155 yaz_log(YLOG_DEBUG, " term #%d: '%s' (" ODR_INT_PRINTF ")", i,
3156 bsrr->entries[i].term, bsrr->entries[i].occurrences);
3160 Z_DiagRecs *drecs = zget_DiagRecs(assoc->encode,
3161 bsrr->entries[i].errcode,
3162 bsrr->entries[i].errstring);
3163 assert(drecs->num_diagRecs == 1);
3164 e->which = Z_Entry_surrogateDiagnostic;
3165 assert(drecs->diagRecs[0]);
3166 e->u.surrogateDiagnostic = drecs->diagRecs[0];
3172 ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
3173 ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
3178 WRBUF wr = wrbuf_alloc();
3179 wrbuf_printf(wr, "Scan ");
3180 for (i = 0 ; i < req->num_databaseNames; i++)
3183 wrbuf_printf(wr, "+");
3184 wrbuf_puts(wr, req->databaseNames[i]);
3187 wrbuf_printf(wr, " ");
3190 wr_diag(wr, bsrr->errcode, bsrr->errstring);
3192 wrbuf_printf(wr, "OK");
3194 wrbuf_printf(wr, " " ODR_INT_PRINTF " - " ODR_INT_PRINTF "+"
3195 ODR_INT_PRINTF "+" ODR_INT_PRINTF,
3196 res->numberOfEntriesReturned ?
3197 *res->numberOfEntriesReturned : 0,
3198 (req->preferredPositionInResponse ?
3199 *req->preferredPositionInResponse : 1),
3200 *req->numberOfTermsRequested,
3201 (res->stepSize ? *res->stepSize : 1));
3204 wrbuf_printf(wr, "+%s", bsrr->setname);
3206 wrbuf_printf(wr, " ");
3207 yaz_scan_to_wrbuf(wr, req->termListAndStartPoint,
3208 bsrr->attributeset);
3209 yaz_log(log_request, "%s", wrbuf_cstr(wr) );
3215 static Z_APDU *process_sortRequest(association *assoc, request *reqb)
3218 Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
3219 Z_SortResponse *res = (Z_SortResponse *)
3220 odr_malloc(assoc->encode, sizeof(*res));
3221 bend_sort_rr *bsrr = (bend_sort_rr *)
3222 odr_malloc(assoc->encode, sizeof(*bsrr));
3224 Z_APDU *apdu = (Z_APDU *)odr_malloc(assoc->encode, sizeof(*apdu));
3226 yaz_log(log_requestdetail, "Got SortRequest.");
3228 bsrr->num_input_setnames = req->num_inputResultSetNames;
3229 for (i=0;i<req->num_inputResultSetNames;i++)
3230 yaz_log(log_requestdetail, "Input resultset: '%s'",
3231 req->inputResultSetNames[i]);
3232 bsrr->input_setnames = req->inputResultSetNames;
3233 bsrr->referenceId = req->referenceId;
3234 bsrr->output_setname = req->sortedResultSetName;
3235 yaz_log(log_requestdetail, "Output resultset: '%s'",
3236 req->sortedResultSetName);
3237 bsrr->sort_sequence = req->sortSequence;
3238 /*FIXME - dump those sequences too */
3239 bsrr->stream = assoc->encode;
3240 bsrr->print = assoc->print;
3242 bsrr->sort_status = Z_SortResponse_failure;
3244 bsrr->errstring = 0;
3246 (*assoc->init->bend_sort)(assoc->backend, bsrr);
3248 res->referenceId = bsrr->referenceId;
3249 res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
3250 res->resultSetStatus = 0;
3253 Z_DiagRecs *dr = zget_DiagRecs(assoc->encode,
3254 bsrr->errcode, bsrr->errstring);
3255 res->diagnostics = dr->diagRecs;
3256 res->num_diagnostics = dr->num_diagRecs;
3260 res->num_diagnostics = 0;
3261 res->diagnostics = 0;
3263 res->resultCount = 0;
3266 apdu->which = Z_APDU_sortResponse;
3267 apdu->u.sortResponse = res;
3270 WRBUF wr = wrbuf_alloc();
3271 wrbuf_printf(wr, "Sort ");
3273 wrbuf_printf(wr, " ERROR %d", bsrr->errcode);
3275 wrbuf_printf(wr, "OK -");
3276 wrbuf_printf(wr, " (");
3277 for (i = 0; i<req->num_inputResultSetNames; i++)
3280 wrbuf_printf(wr, "+");
3281 wrbuf_puts(wr, req->inputResultSetNames[i]);
3283 wrbuf_printf(wr, ")->%s ",req->sortedResultSetName);
3285 yaz_log(log_request, "%s", wrbuf_cstr(wr) );
3291 static Z_APDU *process_deleteRequest(association *assoc, request *reqb)
3294 Z_DeleteResultSetRequest *req =
3295 reqb->apdu_request->u.deleteResultSetRequest;
3296 Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
3297 odr_malloc(assoc->encode, sizeof(*res));
3298 bend_delete_rr *bdrr = (bend_delete_rr *)
3299 odr_malloc(assoc->encode, sizeof(*bdrr));
3300 Z_APDU *apdu = (Z_APDU *)odr_malloc(assoc->encode, sizeof(*apdu));
3302 yaz_log(log_requestdetail, "Got DeleteRequest.");
3304 bdrr->num_setnames = req->num_resultSetList;
3305 bdrr->setnames = req->resultSetList;
3306 for (i = 0; i<req->num_resultSetList; i++)
3307 yaz_log(log_requestdetail, "resultset: '%s'",
3308 req->resultSetList[i]);
3309 bdrr->stream = assoc->encode;
3310 bdrr->print = assoc->print;
3311 bdrr->function = odr_int_to_int(*req->deleteFunction);
3312 bdrr->referenceId = req->referenceId;
3314 if (bdrr->num_setnames > 0)
3316 bdrr->statuses = (int*)
3317 odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
3318 bdrr->num_setnames);
3319 for (i = 0; i < bdrr->num_setnames; i++)
3320 bdrr->statuses[i] = 0;
3322 (*assoc->init->bend_delete)(assoc->backend, bdrr);
3324 res->referenceId = req->referenceId;
3326 res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
3328 res->deleteListStatuses = 0;
3329 if (bdrr->num_setnames > 0)
3332 res->deleteListStatuses = (Z_ListStatuses *)
3333 odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
3334 res->deleteListStatuses->num = bdrr->num_setnames;
3335 res->deleteListStatuses->elements =
3337 odr_malloc(assoc->encode,
3338 sizeof(*res->deleteListStatuses->elements) *
3339 bdrr->num_setnames);
3340 for (i = 0; i<bdrr->num_setnames; i++)
3342 res->deleteListStatuses->elements[i] =
3344 odr_malloc(assoc->encode,
3345 sizeof(**res->deleteListStatuses->elements));
3346 res->deleteListStatuses->elements[i]->status =
3347 odr_intdup(assoc->encode, bdrr->statuses[i]);
3348 res->deleteListStatuses->elements[i]->id =
3349 odr_strdup(assoc->encode, bdrr->setnames[i]);
3352 res->numberNotDeleted = 0;
3353 res->bulkStatuses = 0;
3354 res->deleteMessage = 0;
3357 apdu->which = Z_APDU_deleteResultSetResponse;
3358 apdu->u.deleteResultSetResponse = res;
3361 WRBUF wr = wrbuf_alloc();
3362 wrbuf_printf(wr, "Delete ");
3363 if (bdrr->delete_status)
3364 wrbuf_printf(wr, "ERROR %d", bdrr->delete_status);
3366 wrbuf_printf(wr, "OK -");
3367 for (i = 0; i<req->num_resultSetList; i++)
3368 wrbuf_printf(wr, " %s ", req->resultSetList[i]);
3369 yaz_log(log_request, "%s", wrbuf_cstr(wr) );
3375 static void process_close(association *assoc, request *reqb)
3377 Z_Close *req = reqb->apdu_request->u.close;
3378 static char *reasons[] =
3385 "securityViolation",
3392 yaz_log(log_requestdetail, "Got Close, reason %s, message %s",
3393 reasons[*req->closeReason], req->diagnosticInformation ?
3394 req->diagnosticInformation : "NULL");
3395 if (assoc->version < 3) /* to make do_force respond with close */
3397 do_close_req(assoc, Z_Close_finished,
3398 "Association terminated by client", reqb);
3399 yaz_log(log_request,"Close OK");
3402 static Z_APDU *process_segmentRequest(association *assoc, request *reqb)
3404 bend_segment_rr req;
3406 req.segment = reqb->apdu_request->u.segmentRequest;
3407 req.stream = assoc->encode;
3408 req.decode = assoc->decode;
3409 req.print = assoc->print;
3410 req.association = assoc;
3412 (*assoc->init->bend_segment)(assoc->backend, &req);
3417 static Z_APDU *process_ESRequest(association *assoc, request *reqb)
3419 bend_esrequest_rr esrequest;
3420 const char *ext_name = "unknown";
3422 Z_ExtendedServicesRequest *req =
3423 reqb->apdu_request->u.extendedServicesRequest;
3424 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
3426 Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
3428 esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
3429 esrequest.stream = assoc->encode;
3430 esrequest.decode = assoc->decode;
3431 esrequest.print = assoc->print;
3432 esrequest.errcode = 0;
3433 esrequest.errstring = NULL;
3434 esrequest.association = assoc;
3435 esrequest.taskPackage = 0;
3436 esrequest.referenceId = req->referenceId;
3438 if (esrequest.esr && esrequest.esr->taskSpecificParameters)
3440 switch(esrequest.esr->taskSpecificParameters->which)
3442 case Z_External_itemOrder:
3443 ext_name = "ItemOrder"; break;
3444 case Z_External_update:
3445 ext_name = "Update"; break;
3446 case Z_External_update0:
3447 ext_name = "Update0"; break;
3448 case Z_External_ESAdmin:
3449 ext_name = "Admin"; break;
3454 (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
3456 resp->referenceId = req->referenceId;
3458 if (esrequest.errcode == -1)
3460 /* Backend service indicates request will be processed */
3461 yaz_log(log_request, "Extended Service: %s (accepted)", ext_name);
3462 *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
3464 else if (esrequest.errcode == 0)
3466 /* Backend service indicates request will be processed */
3467 yaz_log(log_request, "Extended Service: %s (done)", ext_name);
3468 *resp->operationStatus = Z_ExtendedServicesResponse_done;
3472 Z_DiagRecs *diagRecs =
3473 zget_DiagRecs(assoc->encode, esrequest.errcode,
3474 esrequest.errstring);
3475 /* Backend indicates error, request will not be processed */
3476 yaz_log(log_request, "Extended Service: %s (failed)", ext_name);
3477 *resp->operationStatus = Z_ExtendedServicesResponse_failure;
3478 resp->num_diagnostics = diagRecs->num_diagRecs;
3479 resp->diagnostics = diagRecs->diagRecs;
3482 WRBUF wr = wrbuf_alloc();
3483 wrbuf_diags(wr, resp->num_diagnostics, resp->diagnostics);
3484 yaz_log(log_request, "EsRequest %s", wrbuf_cstr(wr) );
3489 /* Do something with the members of bend_extendedservice */
3490 if (esrequest.taskPackage)
3492 resp->taskPackage = z_ext_record_oid(
3493 assoc->encode, yaz_oid_recsyn_extended,
3494 (const char *) esrequest.taskPackage, -1);
3496 yaz_log(YLOG_DEBUG,"Send the result apdu");
3500 int bend_assoc_is_alive(bend_association assoc)
3502 if (assoc->state == ASSOC_DEAD)
3503 return 0; /* already marked as dead. Don't check I/O chan anymore */
3505 return iochan_is_alive(assoc->client_chan);
3512 * c-file-style: "Stroustrup"
3513 * indent-tabs-mode: nil
3515 * vim: shiftwidth=4 tabstop=8 expandtab