2 * Copyright (C) 1995-2005, Index Data ApS
3 * See the file LICENSE for details.
5 * $Id: seshigh.c,v 1.72 2006-03-16 12:30:03 adam Exp $
9 * \brief Implements GFS session logic.
11 * Frontend server logic.
13 * This code receives incoming APDUs, and handles client requests by means
16 * Some of the code is getting quite involved, compared to simpler servers -
17 * primarily because it is asynchronous both in the communication with
18 * the user and the backend. We think the complexity will pay off in
19 * the form of greater flexibility when more asynchronous facilities
22 * Memory management has become somewhat involved. In the simple case, where
23 * only one PDU is pending at a time, it will simply reuse the same memory,
24 * once it has found its working size. When we enable multiple concurrent
25 * operations, perhaps even with multiple parallel calls to the backend, it
26 * will maintain a pool of buffers for encoding and decoding, trying to
27 * minimize memory allocation/deallocation during normal operation.
37 #include <sys/types.h>
45 #define S_ISREG(x) (x & _S_IFREG)
54 #include <libxml/parser.h>
55 #include <libxml/tree.h>
58 #include <yaz/yconfig.h>
59 #include <yaz/xmalloc.h>
60 #include <yaz/comstack.h>
64 #include <yaz/proto.h>
67 #include <yaz/logrpn.h>
68 #include <yaz/querytowrbuf.h>
69 #include <yaz/statserv.h>
70 #include <yaz/diagbib1.h>
71 #include <yaz/charneg.h>
72 #include <yaz/otherinfo.h>
73 #include <yaz/yaz-util.h>
74 #include <yaz/pquery.h>
77 #include <yaz/backend.h>
79 static void process_gdu_request(association *assoc, request *req);
80 static int process_z_request(association *assoc, request *req, char **msg);
81 void backend_response(IOCHAN i, int event);
82 static int process_gdu_response(association *assoc, request *req, Z_GDU *res);
83 static int process_z_response(association *assoc, request *req, Z_APDU *res);
84 static Z_APDU *process_initRequest(association *assoc, request *reqb);
85 static Z_External *init_diagnostics(ODR odr, int errcode,
86 const char *errstring);
87 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
89 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
90 bend_search_rr *bsrr, int *fd);
91 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
93 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
94 static Z_APDU *process_sortRequest(association *assoc, request *reqb, int *fd);
95 static void process_close(association *assoc, request *reqb);
96 void save_referenceId (request *reqb, Z_ReferenceId *refid);
97 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
99 static Z_APDU *process_segmentRequest (association *assoc, request *reqb);
101 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd);
103 /* dynamic logging levels */
104 static int logbits_set = 0;
105 static int log_session = 0;
106 static int log_request = 0; /* one-line logs for requests */
107 static int log_requestdetail = 0; /* more detailed stuff */
109 /** get_logbits sets global loglevel bits */
110 static void get_logbits()
111 { /* needs to be called after parsing cmd-line args that can set loglevels!*/
115 log_session = yaz_log_module_level("session");
116 log_request = yaz_log_module_level("request");
117 log_requestdetail = yaz_log_module_level("requestdetail");
121 static void wr_diag(WRBUF w, int error, const char *addinfo)
123 wrbuf_printf(w, "ERROR [%d] %s%s%s",
124 error, diagbib1_str(error),
125 addinfo ? "--" : "", addinfo ? addinfo : "");
130 * Create and initialize a new association-handle.
131 * channel : iochannel for the current line.
132 * link : communications channel.
133 * Returns: 0 or a new association handle.
135 association *create_association(IOCHAN channel, COMSTACK link,
136 const char *apdufile)
142 if (!(anew = (association *)xmalloc(sizeof(*anew))))
146 anew->last_control = 0;
147 anew->client_chan = channel;
148 anew->client_link = link;
149 anew->cs_get_mask = 0;
150 anew->cs_put_mask = 0;
151 anew->cs_accept_mask = 0;
152 if (!(anew->decode = odr_createmem(ODR_DECODE)) ||
153 !(anew->encode = odr_createmem(ODR_ENCODE)))
155 if (apdufile && *apdufile)
159 if (!(anew->print = odr_createmem(ODR_PRINT)))
161 if (*apdufile == '@')
163 odr_setprint(anew->print, yaz_log_file());
165 else if (*apdufile != '-')
168 sprintf(filename, "%.200s.%ld", apdufile, (long)getpid());
169 if (!(f = fopen(filename, "w")))
171 yaz_log(YLOG_WARN|YLOG_ERRNO, "%s", filename);
174 setvbuf(f, 0, _IONBF, 0);
175 odr_setprint(anew->print, f);
180 anew->input_buffer = 0;
181 anew->input_buffer_len = 0;
183 anew->state = ASSOC_NEW;
184 request_initq(&anew->incoming);
185 request_initq(&anew->outgoing);
186 anew->proto = cs_getproto(link);
187 anew->cql_transform = 0;
188 anew->server_node_ptr = 0;
193 * Free association and release resources.
195 void destroy_association(association *h)
197 statserv_options_block *cb = statserv_getcontrol();
201 odr_destroy(h->decode);
202 odr_destroy(h->encode);
204 odr_destroy(h->print);
206 xfree(h->input_buffer);
208 (*cb->bend_close)(h->backend);
209 while ((req = request_deq(&h->incoming)))
210 request_release(req);
211 while ((req = request_deq(&h->outgoing)))
212 request_release(req);
213 request_delq(&h->incoming);
214 request_delq(&h->outgoing);
216 xmalloc_trav("session closed");
217 if (cb && cb->one_shot)
223 static void do_close_req(association *a, int reason, char *message,
227 Z_Close *cls = zget_Close(a->encode);
229 /* Purge request queue */
230 while (request_deq(&a->incoming));
231 while (request_deq(&a->outgoing));
234 yaz_log(log_requestdetail, "Sending Close PDU, reason=%d, message=%s",
235 reason, message ? message : "none");
236 apdu.which = Z_APDU_close;
238 *cls->closeReason = reason;
239 cls->diagnosticInformation = message;
240 process_z_response(a, req, &apdu);
241 iochan_settimeout(a->client_chan, 20);
245 request_release(req);
246 yaz_log(log_requestdetail, "v2 client. No Close PDU");
247 iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
250 a->state = ASSOC_DEAD;
253 static void do_close(association *a, int reason, char *message)
255 request *req = request_get(&a->outgoing);
256 do_close_req (a, reason, message, req);
260 * This is where PDUs from the client are read and the further
261 * processing is initiated. Flow of control moves down through the
262 * various process_* functions below, until the encoded result comes back up
263 * to the output handler in here.
265 * h : the I/O channel that has an outstanding event.
266 * event : the current outstanding event.
268 void ir_session(IOCHAN h, int event)
271 association *assoc = (association *)iochan_getdata(h);
272 COMSTACK conn = assoc->client_link;
275 assert(h && conn && assoc);
276 if (event == EVENT_TIMEOUT)
278 if (assoc->state != ASSOC_UP)
280 yaz_log(YLOG_DEBUG, "Final timeout - closing connection.");
281 /* do we need to lod this at all */
283 destroy_association(assoc);
288 yaz_log(log_session, "Session idle too long. Sending close.");
289 do_close(assoc, Z_Close_lackOfActivity, 0);
293 if (event & assoc->cs_accept_mask)
295 if (!cs_accept (conn))
297 yaz_log (YLOG_WARN, "accept failed");
298 destroy_association(assoc);
301 iochan_clearflag (h, EVENT_OUTPUT);
302 if (conn->io_pending)
303 { /* cs_accept didn't complete */
304 assoc->cs_accept_mask =
305 ((conn->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
306 ((conn->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
308 iochan_setflag (h, assoc->cs_accept_mask);
311 { /* cs_accept completed. Prepare for reading (cs_get) */
312 assoc->cs_accept_mask = 0;
313 assoc->cs_get_mask = EVENT_INPUT;
314 iochan_setflag (h, assoc->cs_get_mask);
318 if ((event & assoc->cs_get_mask) || (event & EVENT_WORK)) /* input */
320 if ((assoc->cs_put_mask & EVENT_INPUT) == 0 && (event & assoc->cs_get_mask))
322 yaz_log(YLOG_DEBUG, "ir_session (input)");
323 /* We aren't speaking to this fellow */
324 if (assoc->state == ASSOC_DEAD)
326 yaz_log(log_session, "Connection closed - end of session");
328 destroy_association(assoc);
332 assoc->cs_get_mask = EVENT_INPUT;
333 if ((res = cs_get(conn, &assoc->input_buffer,
334 &assoc->input_buffer_len)) <= 0)
336 yaz_log(log_session, "Connection closed by client");
338 destroy_association(assoc);
342 else if (res == 1) /* incomplete read - wait for more */
344 if (conn->io_pending & CS_WANT_WRITE)
345 assoc->cs_get_mask |= EVENT_OUTPUT;
346 iochan_setflag(h, assoc->cs_get_mask);
349 if (cs_more(conn)) /* more stuff - call us again later, please */
350 iochan_setevent(h, EVENT_INPUT);
352 /* we got a complete PDU. Let's decode it */
353 yaz_log(YLOG_DEBUG, "Got PDU, %d bytes: lead=%02X %02X %02X", res,
354 assoc->input_buffer[0] & 0xff,
355 assoc->input_buffer[1] & 0xff,
356 assoc->input_buffer[2] & 0xff);
357 req = request_get(&assoc->incoming); /* get a new request */
358 odr_reset(assoc->decode);
359 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
360 if (!z_GDU(assoc->decode, &req->gdu_request, 0, 0))
362 yaz_log(YLOG_WARN, "ODR error on incoming PDU: %s [element %s] "
364 odr_errmsg(odr_geterror(assoc->decode)),
365 odr_getelement(assoc->decode),
366 odr_offset(assoc->decode));
367 if (assoc->decode->error != OHTTP)
369 yaz_log(YLOG_WARN, "PDU dump:");
370 odr_dumpBER(yaz_log_file(), assoc->input_buffer, res);
371 request_release(req);
372 do_close(assoc, Z_Close_protocolError,"Malformed package");
376 Z_GDU *p = z_get_HTTP_Response(assoc->encode, 400);
377 assoc->state = ASSOC_DEAD;
378 process_gdu_response(assoc, req, p);
382 req->request_mem = odr_extract_mem(assoc->decode);
385 if (!z_GDU(assoc->print, &req->gdu_request, 0, 0))
386 yaz_log(YLOG_WARN, "ODR print error: %s",
387 odr_errmsg(odr_geterror(assoc->print)));
388 odr_reset(assoc->print);
390 request_enq(&assoc->incoming, req);
393 /* can we do something yet? */
394 req = request_head(&assoc->incoming);
395 if (req->state == REQUEST_IDLE)
397 request_deq(&assoc->incoming);
398 process_gdu_request(assoc, req);
401 if (event & assoc->cs_put_mask)
403 request *req = request_head(&assoc->outgoing);
405 assoc->cs_put_mask = 0;
406 yaz_log(YLOG_DEBUG, "ir_session (output)");
407 req->state = REQUEST_PENDING;
408 switch (res = cs_put(conn, req->response, req->len_response))
411 yaz_log(log_session, "Connection closed by client");
413 destroy_association(assoc);
416 case 0: /* all sent - release the request structure */
417 yaz_log(YLOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
419 yaz_log(YLOG_DEBUG, "HTTP out:\n%.*s", req->len_response,
422 nmem_destroy(req->request_mem);
423 request_deq(&assoc->outgoing);
424 request_release(req);
425 if (!request_head(&assoc->outgoing))
426 { /* restore mask for cs_get operation ... */
427 iochan_clearflag(h, EVENT_OUTPUT|EVENT_INPUT);
428 iochan_setflag(h, assoc->cs_get_mask);
429 if (assoc->state == ASSOC_DEAD)
430 iochan_setevent(assoc->client_chan, EVENT_TIMEOUT);
434 assoc->cs_put_mask = EVENT_OUTPUT;
438 if (conn->io_pending & CS_WANT_WRITE)
439 assoc->cs_put_mask |= EVENT_OUTPUT;
440 if (conn->io_pending & CS_WANT_READ)
441 assoc->cs_put_mask |= EVENT_INPUT;
442 iochan_setflag(h, assoc->cs_put_mask);
445 if (event & EVENT_EXCEPT)
447 yaz_log(YLOG_WARN, "ir_session (exception)");
449 destroy_association(assoc);
454 static int process_z_request(association *assoc, request *req, char **msg);
457 static void assoc_init_reset(association *assoc)
460 assoc->init = (bend_initrequest *) xmalloc (sizeof(*assoc->init));
462 assoc->init->stream = assoc->encode;
463 assoc->init->print = assoc->print;
464 assoc->init->auth = 0;
465 assoc->init->referenceId = 0;
466 assoc->init->implementation_version = 0;
467 assoc->init->implementation_id = 0;
468 assoc->init->implementation_name = 0;
469 assoc->init->bend_sort = NULL;
470 assoc->init->bend_search = NULL;
471 assoc->init->bend_present = NULL;
472 assoc->init->bend_esrequest = NULL;
473 assoc->init->bend_delete = NULL;
474 assoc->init->bend_scan = NULL;
475 assoc->init->bend_segment = NULL;
476 assoc->init->bend_fetch = NULL;
477 assoc->init->bend_explain = NULL;
478 assoc->init->bend_srw_scan = NULL;
479 assoc->init->bend_srw_update = NULL;
481 assoc->init->charneg_request = NULL;
482 assoc->init->charneg_response = NULL;
484 assoc->init->decode = assoc->decode;
485 assoc->init->peer_name =
486 odr_strdup (assoc->encode, cs_addrstr(assoc->client_link));
488 yaz_log(log_requestdetail, "peer %s", assoc->init->peer_name);
491 static int srw_bend_init(association *assoc, Z_SRW_diagnostic **d, int *num)
493 statserv_options_block *cb = statserv_getcontrol();
496 const char *encoding = "UTF-8";
498 bend_initresult *binitres;
500 yaz_log(YLOG_LOG, "srw_bend_init config=%s", cb->configname);
501 assoc_init_reset(assoc);
503 assoc->maximumRecordSize = 3000000;
504 assoc->preferredMessageSize = 3000000;
506 ce = yaz_set_proposal_charneg(assoc->decode, &encoding, 1, 0, 0, 1);
507 assoc->init->charneg_request = ce->u.charNeg3;
510 if (!(binitres = (*cb->bend_init)(assoc->init)))
512 assoc->state = ASSOC_DEAD;
513 yaz_add_srw_diagnostic(assoc->encode, d, num,
514 YAZ_SRW_AUTHENTICATION_ERROR, 0);
517 assoc->backend = binitres->handle;
518 if (binitres->errcode)
520 int srw_code = yaz_diag_bib1_to_srw(binitres->errcode);
521 assoc->state = ASSOC_DEAD;
522 yaz_add_srw_diagnostic(assoc->encode, d, num, srw_code,
523 binitres->errstring);
531 static int srw_bend_fetch(association *assoc, int pos,
532 Z_SRW_searchRetrieveRequest *srw_req,
533 Z_SRW_record *record)
536 ODR o = assoc->encode;
538 rr.setname = "default";
541 rr.request_format = VAL_TEXT_XML;
542 rr.request_format_raw = yaz_oidval_to_z3950oid(assoc->decode,
545 rr.comp = (Z_RecordComposition *)
546 odr_malloc(assoc->decode, sizeof(*rr.comp));
547 rr.comp->which = Z_RecordComp_complex;
548 rr.comp->u.complex = (Z_CompSpec *)
549 odr_malloc(assoc->decode, sizeof(Z_CompSpec));
550 rr.comp->u.complex->selectAlternativeSyntax = (bool_t *)
551 odr_malloc(assoc->encode, sizeof(bool_t));
552 *rr.comp->u.complex->selectAlternativeSyntax = 0;
553 rr.comp->u.complex->num_dbSpecific = 0;
554 rr.comp->u.complex->dbSpecific = 0;
555 rr.comp->u.complex->num_recordSyntax = 0;
556 rr.comp->u.complex->recordSyntax = 0;
558 rr.comp->u.complex->generic = (Z_Specification *)
559 odr_malloc(assoc->decode, sizeof(Z_Specification));
561 /* schema uri = recordSchema (or NULL if recordSchema is not given) */
562 rr.comp->u.complex->generic->which = Z_Schema_uri;
563 rr.comp->u.complex->generic->schema.uri = srw_req->recordSchema;
565 /* ESN = recordSchema if recordSchema is present */
566 rr.comp->u.complex->generic->elementSpec = 0;
567 if (srw_req->recordSchema)
569 rr.comp->u.complex->generic->elementSpec =
570 (Z_ElementSpec *) odr_malloc(assoc->encode, sizeof(Z_ElementSpec));
571 rr.comp->u.complex->generic->elementSpec->which =
572 Z_ElementSpec_elementSetName;
573 rr.comp->u.complex->generic->elementSpec->u.elementSetName =
574 srw_req->recordSchema;
577 rr.stream = assoc->encode;
578 rr.print = assoc->print;
584 rr.output_format = VAL_TEXT_XML;
585 rr.output_format_raw = 0;
588 rr.surrogate_flag = 0;
589 rr.schema = srw_req->recordSchema;
591 if (!assoc->init->bend_fetch)
594 (*assoc->init->bend_fetch)(assoc->backend, &rr);
596 if (rr.errcode && rr.surrogate_flag)
598 int code = yaz_diag_bib1_to_srw(rr.errcode);
599 const char *message = yaz_diag_srw_str(code);
602 len += strlen(message);
604 len += strlen(rr.errstring);
606 record->recordData_buf = odr_malloc(o, len);
608 sprintf(record->recordData_buf, "<diagnostic "
609 "xmlns=\"http://www.loc.gov/zing/srw/diagnostic/\">\n"
610 " <uri>info:srw/diagnostic/1/%d</uri>\n", code);
612 sprintf(record->recordData_buf + strlen(record->recordData_buf),
613 " <details>%s</details>\n", rr.errstring);
615 sprintf(record->recordData_buf + strlen(record->recordData_buf),
616 " <message>%s</message>\n", message);
617 sprintf(record->recordData_buf + strlen(record->recordData_buf),
619 record->recordData_len = strlen(record->recordData_buf);
620 record->recordPosition = odr_intdup(o, pos);
621 record->recordSchema = "info:srw/schema/1/diagnostics-v1.1";
624 else if (rr.len >= 0)
626 record->recordData_buf = rr.record;
627 record->recordData_len = rr.len;
628 record->recordPosition = odr_intdup(o, pos);
630 record->recordSchema = odr_strdup(o, rr.schema);
632 record->recordSchema = 0;
637 static int cql2pqf(ODR odr, const char *cql, cql_transform_t ct,
638 Z_Query *query_result)
640 /* have a CQL query and CQL to PQF transform .. */
641 CQL_parser cp = cql_parser_create();
647 r = cql_parser_string(cp, cql);
650 /* CQL syntax error */
656 r = cql_transform_buf(ct,
657 cql_parser_result(cp),
658 rpn_buf, sizeof(rpn_buf)-1);
660 srw_errcode = cql_transform_error(ct, &add);
664 /* Syntax & transform OK. */
665 /* Convert PQF string to Z39.50 to RPN query struct */
666 YAZ_PQF_Parser pp = yaz_pqf_create();
667 Z_RPNQuery *rpnquery = yaz_pqf_parse(pp, odr, rpn_buf);
672 int code = yaz_pqf_error(pp, &pqf_msg, &off);
673 yaz_log(YLOG_WARN, "PQF Parser Error %s (code %d)",
679 query_result->which = Z_Query_type_1;
680 query_result->u.type_1 = rpnquery;
684 cql_parser_destroy(cp);
688 static int cql2pqf_scan(ODR odr, const char *cql, cql_transform_t ct,
689 Z_AttributesPlusTerm *result)
693 int srw_error = cql2pqf(odr, cql, ct, &query);
696 if (query.which != Z_Query_type_1 && query.which != Z_Query_type_101)
697 return 10; /* bad query type */
698 rpn = query.u.type_1;
699 if (!rpn->RPNStructure)
700 return 10; /* must be structure */
701 if (rpn->RPNStructure->which != Z_RPNStructure_simple)
702 return 10; /* must be simple */
703 if (rpn->RPNStructure->u.simple->which != Z_Operand_APT)
704 return 10; /* must be attributes plus term node .. */
705 memcpy(result, rpn->RPNStructure->u.simple->u.attributesPlusTerm,
710 static void srw_bend_search(association *assoc, request *req,
711 Z_SRW_searchRetrieveRequest *srw_req,
712 Z_SRW_searchRetrieveResponse *srw_res,
719 yaz_log(log_requestdetail, "Got SRW SearchRetrieveRequest");
720 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics);
721 if (srw_res->num_diagnostics == 0 && assoc->init)
724 rr.setname = "default";
727 rr.basenames = &srw_req->database;
731 rr.srw_setnameIdleTime = 0;
732 rr.query = (Z_Query *) odr_malloc (assoc->decode, sizeof(*rr.query));
733 rr.query->u.type_1 = 0;
735 if (srw_req->query_type == Z_SRW_query_type_cql)
737 if (assoc->cql_transform)
739 int srw_errcode = cql2pqf(assoc->encode, srw_req->query.cql,
740 assoc->cql_transform, rr.query);
743 yaz_add_srw_diagnostic(assoc->encode,
744 &srw_res->diagnostics,
745 &srw_res->num_diagnostics,
751 /* CQL query to backend. Wrap it - Z39.50 style */
752 ext = (Z_External *) odr_malloc(assoc->decode, sizeof(*ext));
753 ext->direct_reference = odr_getoidbystr(assoc->decode,
754 "1.2.840.10003.16.2");
755 ext->indirect_reference = 0;
757 ext->which = Z_External_CQL;
758 ext->u.cql = srw_req->query.cql;
760 rr.query->which = Z_Query_type_104;
761 rr.query->u.type_104 = ext;
764 else if (srw_req->query_type == Z_SRW_query_type_pqf)
766 Z_RPNQuery *RPNquery;
767 YAZ_PQF_Parser pqf_parser;
769 pqf_parser = yaz_pqf_create ();
771 RPNquery = yaz_pqf_parse (pqf_parser, assoc->decode,
777 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
778 yaz_log(log_requestdetail, "Parse error %d %s near offset %d",
780 srw_error = YAZ_SRW_QUERY_SYNTAX_ERROR;
783 rr.query->which = Z_Query_type_1;
784 rr.query->u.type_1 = RPNquery;
786 yaz_pqf_destroy (pqf_parser);
790 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
791 &srw_res->num_diagnostics,
792 YAZ_SRW_UNSUPP_QUERY_TYPE, 0);
794 if (rr.query->u.type_1)
796 rr.stream = assoc->encode;
797 rr.decode = assoc->decode;
798 rr.print = assoc->print;
800 if ( srw_req->sort.sortKeys )
801 rr.srw_sortKeys = odr_strdup(assoc->encode,
802 srw_req->sort.sortKeys );
803 rr.association = assoc;
809 yaz_log_zquery_level(log_requestdetail,rr.query);
811 (assoc->init->bend_search)(assoc->backend, &rr);
814 if (rr.errcode == YAZ_BIB1_DATABASE_UNAVAILABLE)
820 srw_error = yaz_diag_bib1_to_srw (rr.errcode);
821 yaz_add_srw_diagnostic(assoc->encode,
822 &srw_res->diagnostics,
823 &srw_res->num_diagnostics,
824 srw_error, rr.errstring);
829 int number = srw_req->maximumRecords ? *srw_req->maximumRecords : 0;
830 int start = srw_req->startRecord ? *srw_req->startRecord : 1;
832 yaz_log(log_requestdetail, "Request to pack %d+%d out of %d",
833 start, number, rr.hits);
835 srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
838 srw_res->resultSetId =
839 odr_strdup(assoc->encode, rr.srw_setname );
840 srw_res->resultSetIdleTime =
841 odr_intdup(assoc->encode, *rr.srw_setnameIdleTime );
849 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
850 &srw_res->num_diagnostics,
851 YAZ_SRW_FIRST_RECORD_POSITION_OUT_OF_RANGE, 0);
856 int packing = Z_SRW_recordPacking_string;
857 if (start + number > rr.hits)
858 number = rr.hits - start + 1;
859 if (srw_req->recordPacking){
860 if (!strcmp(srw_req->recordPacking, "xml"))
861 packing = Z_SRW_recordPacking_XML;
862 if (!strcmp(srw_req->recordPacking, "url"))
863 packing = Z_SRW_recordPacking_URL;
865 srw_res->records = (Z_SRW_record *)
866 odr_malloc(assoc->encode,
867 number * sizeof(*srw_res->records));
869 srw_res->extra_records = (Z_SRW_extra_record **)
870 odr_malloc(assoc->encode,
871 number*sizeof(*srw_res->extra_records));
873 for (i = 0; i<number; i++)
877 srw_res->records[j].recordPacking = packing;
878 srw_res->records[j].recordData_buf = 0;
879 srw_res->extra_records[j] = 0;
880 yaz_log(YLOG_DEBUG, "srw_bend_fetch %d", i+start);
881 errcode = srw_bend_fetch(assoc, i+start, srw_req,
882 srw_res->records + j);
885 yaz_add_srw_diagnostic(assoc->encode,
886 &srw_res->diagnostics,
887 &srw_res->num_diagnostics,
888 yaz_diag_bib1_to_srw (errcode),
893 if (srw_res->records[j].recordData_buf)
896 srw_res->num_records = j;
898 srw_res->records = 0;
906 const char *querystr = "?";
907 const char *querytype = "?";
908 WRBUF wr = wrbuf_alloc();
910 switch (srw_req->query_type)
912 case Z_SRW_query_type_cql:
914 querystr = srw_req->query.cql;
916 case Z_SRW_query_type_pqf:
918 querystr = srw_req->query.pqf;
921 wrbuf_printf(wr, "SRWSearch ");
922 if (srw_res->num_diagnostics)
923 wrbuf_printf(wr, "ERROR %s", srw_res->diagnostics[0].uri);
924 else if (*http_code != 200)
925 wrbuf_printf(wr, "ERROR info:http/%d", *http_code);
926 else if (srw_res->numberOfRecords)
928 wrbuf_printf(wr, "OK %d",
929 (srw_res->numberOfRecords ?
930 *srw_res->numberOfRecords : 0));
932 wrbuf_printf(wr, " %s %d+%d",
933 (srw_res->resultSetId ?
934 srw_res->resultSetId : "-"),
935 (srw_req->startRecord ? *srw_req->startRecord : 1),
936 srw_res->num_records);
937 yaz_log(log_request, "%s %s: %s", wrbuf_buf(wr), querytype, querystr);
942 static char *srw_bend_explain_default(void *handle, bend_explain_rr *rr)
945 xmlNodePtr ptr = rr->server_node_ptr;
948 for (ptr = ptr->children; ptr; ptr = ptr->next)
950 if (ptr->type != XML_ELEMENT_NODE)
952 if (!strcmp((const char *) ptr->name, "explain"))
955 xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
959 ptr = xmlCopyNode(ptr, 1);
961 xmlDocSetRootElement(doc, ptr);
963 xmlDocDumpMemory(doc, &buf_out, &len);
964 content = (char*) odr_malloc(rr->stream, 1+len);
965 memcpy(content, buf_out, len);
970 rr->explain_buf = content;
978 static void srw_bend_explain(association *assoc, request *req,
979 Z_SRW_explainRequest *srw_req,
980 Z_SRW_explainResponse *srw_res,
983 yaz_log(log_requestdetail, "Got SRW ExplainRequest");
985 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics);
990 rr.stream = assoc->encode;
991 rr.decode = assoc->decode;
992 rr.print = assoc->print;
994 rr.database = srw_req->database;
995 rr.server_node_ptr = assoc->server_node_ptr;
996 rr.schema = "http://explain.z3950.org/dtd/2.0/";
997 if (assoc->init->bend_explain)
998 (*assoc->init->bend_explain)(assoc->backend, &rr);
1000 srw_bend_explain_default(assoc->backend, &rr);
1004 int packing = Z_SRW_recordPacking_string;
1005 if (srw_req->recordPacking)
1007 if (!strcmp(srw_req->recordPacking, "xml"))
1008 packing = Z_SRW_recordPacking_XML;
1009 else if (!strcmp(srw_req->recordPacking, "url"))
1010 packing = Z_SRW_recordPacking_URL;
1012 srw_res->record.recordSchema = rr.schema;
1013 srw_res->record.recordPacking = packing;
1014 srw_res->record.recordData_buf = rr.explain_buf;
1015 srw_res->record.recordData_len = strlen(rr.explain_buf);
1016 srw_res->record.recordPosition = 0;
1022 static void srw_bend_scan(association *assoc, request *req,
1023 Z_SRW_scanRequest *srw_req,
1024 Z_SRW_scanResponse *srw_res,
1027 yaz_log(log_requestdetail, "Got SRW ScanRequest");
1030 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics);
1031 if (srw_res->num_diagnostics == 0 && assoc->init)
1033 struct scan_entry *save_entries;
1035 bend_scan_rr *bsrr = (bend_scan_rr *)
1036 odr_malloc (assoc->encode, sizeof(*bsrr));
1037 bsrr->num_bases = 1;
1038 bsrr->basenames = &srw_req->database;
1040 bsrr->num_entries = srw_req->maximumTerms ?
1041 *srw_req->maximumTerms : 10;
1042 bsrr->term_position = srw_req->responsePosition ?
1043 *srw_req->responsePosition : 1;
1046 bsrr->errstring = 0;
1047 bsrr->referenceId = 0;
1048 bsrr->stream = assoc->encode;
1049 bsrr->print = assoc->print;
1050 bsrr->step_size = odr_intdup(assoc->decode, 0);
1053 if (bsrr->num_entries > 0)
1056 bsrr->entries = odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
1058 for (i = 0; i<bsrr->num_entries; i++)
1060 bsrr->entries[i].term = 0;
1061 bsrr->entries[i].occurrences = 0;
1062 bsrr->entries[i].errcode = 0;
1063 bsrr->entries[i].errstring = 0;
1064 bsrr->entries[i].display_term = 0;
1067 save_entries = bsrr->entries; /* save it so we can compare later */
1069 if (srw_req->query_type == Z_SRW_query_type_pqf &&
1070 assoc->init->bend_scan)
1072 Odr_oid *scan_attributeSet = 0;
1074 YAZ_PQF_Parser pqf_parser = yaz_pqf_create();
1076 bsrr->term = yaz_pqf_scan(pqf_parser, assoc->decode,
1078 srw_req->scanClause.pqf);
1079 if (scan_attributeSet &&
1080 (attset = oid_getentbyoid(scan_attributeSet)) &&
1081 (attset->oclass == CLASS_ATTSET ||
1082 attset->oclass == CLASS_GENERAL))
1083 bsrr->attributeset = attset->value;
1085 bsrr->attributeset = VAL_NONE;
1086 yaz_pqf_destroy(pqf_parser);
1087 bsrr->scanClause = 0;
1088 ((int (*)(void *, bend_scan_rr *))
1089 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1091 else if (srw_req->query_type == Z_SRW_query_type_cql
1092 && assoc->init->bend_scan && assoc->cql_transform)
1095 bsrr->scanClause = 0;
1096 bsrr->attributeset = VAL_NONE;
1097 bsrr->term = odr_malloc(assoc->decode, sizeof(*bsrr->term));
1098 srw_error = cql2pqf_scan(assoc->encode,
1099 srw_req->scanClause.cql,
1100 assoc->cql_transform,
1103 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1104 &srw_res->num_diagnostics,
1108 ((int (*)(void *, bend_scan_rr *))
1109 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1112 else if (srw_req->query_type == Z_SRW_query_type_cql
1113 && assoc->init->bend_srw_scan)
1116 bsrr->attributeset = VAL_NONE;
1117 bsrr->scanClause = srw_req->scanClause.cql;
1118 ((int (*)(void *, bend_scan_rr *))
1119 (*assoc->init->bend_srw_scan))(assoc->backend, bsrr);
1123 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1124 &srw_res->num_diagnostics,
1125 YAZ_SRW_UNSUPP_OPERATION, "scan");
1130 if (bsrr->errcode == YAZ_BIB1_DATABASE_UNAVAILABLE)
1135 srw_error = yaz_diag_bib1_to_srw (bsrr->errcode);
1137 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1138 &srw_res->num_diagnostics,
1139 srw_error, bsrr->errstring);
1141 else if (srw_res->num_diagnostics == 0 && bsrr->num_entries)
1144 srw_res->terms = (Z_SRW_scanTerm*)
1145 odr_malloc(assoc->encode, sizeof(*srw_res->terms) *
1148 srw_res->num_terms = bsrr->num_entries;
1149 for (i = 0; i<bsrr->num_entries; i++)
1151 Z_SRW_scanTerm *t = srw_res->terms + i;
1152 t->value = odr_strdup(assoc->encode, bsrr->entries[i].term);
1153 t->numberOfRecords =
1154 odr_intdup(assoc->encode, bsrr->entries[i].occurrences);
1156 if (save_entries == bsrr->entries &&
1157 bsrr->entries[i].display_term)
1159 /* the entries was _not_ set by the handler. So it's
1160 safe to test for new member display_term. It is
1163 t->displayTerm = odr_strdup(assoc->encode,
1164 bsrr->entries[i].display_term);
1172 WRBUF wr = wrbuf_alloc();
1173 const char *querytype = 0;
1174 const char *querystr = 0;
1176 switch(srw_req->query_type)
1178 case Z_SRW_query_type_pqf:
1180 querystr = srw_req->scanClause.pqf;
1182 case Z_SRW_query_type_cql:
1184 querystr = srw_req->scanClause.cql;
1187 querytype = "Unknown";
1190 wrbuf_printf(wr, "SRWScan %d+%d",
1191 (srw_req->responsePosition ?
1192 *srw_req->responsePosition : 1),
1193 (srw_req->maximumTerms ?
1194 *srw_req->maximumTerms : 1));
1195 if (srw_res->num_diagnostics)
1196 wrbuf_printf(wr, " ERROR %s", srw_res->diagnostics[0].uri);
1198 wrbuf_printf(wr, " OK -");
1199 wrbuf_printf(wr, " %s: %s", querytype, querystr);
1200 yaz_log(log_request, "%s", wrbuf_buf(wr) );
1206 static void srw_bend_update(association *assoc, request *req,
1207 Z_SRW_updateRequest *srw_req,
1208 Z_SRW_updateResponse *srw_res,
1211 yaz_log(YLOG_DEBUG, "Got SRW UpdateRequest");
1212 yaz_log(YLOG_DEBUG, "num_diag = %d", srw_res->num_diagnostics );
1214 srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics);
1219 rr.stream = assoc->encode;
1220 rr.print = assoc->print;
1222 rr.basenames = &srw_req->database;
1223 rr.operation = srw_req->operation;
1224 rr.operation_status = "failed";
1226 rr.record_version = 0;
1227 rr.record_checksum = 0;
1228 rr.record_old_version = 0;
1229 rr.record_packing = "xml";
1230 rr.record_schema = 0;
1232 rr.request_extra_record = 0;
1233 rr.response_extra_record = 0;
1234 rr.extra_request_data = 0;
1235 rr.extra_response_data = 0;
1239 yaz_log(YLOG_DEBUG, "basename = %s", rr.basenames[0] );
1240 yaz_log(YLOG_DEBUG, "Operation = %s", rr.operation );
1241 if ( !strcmp( rr.operation, "delete" ) ){
1242 if ( !srw_req->recordId ){
1243 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1244 &srw_res->num_diagnostics,
1248 rr.record_id = srw_req->recordId;
1250 if ( !srw_req->recordVersion ){
1251 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1252 &srw_res->num_diagnostics,
1253 7, "recordVersion" );
1256 rr.record_version = odr_strdup( assoc->encode,
1257 srw_req->recordVersion );
1260 if ( srw_req->recordOldVersion ){
1261 rr.record_old_version = odr_strdup(assoc->encode,
1262 srw_req->recordOldVersion );
1264 if ( srw_req->extraRequestData ){
1265 rr.extra_request_data = odr_strdup(assoc->encode,
1266 srw_req->extraRequestData );
1269 else if ( !strcmp( rr.operation, "replace" ) ){
1270 if ( !srw_req->recordId ){
1271 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1272 &srw_res->num_diagnostics,
1276 rr.record_id = srw_req->recordId;
1278 if ( srw_req->record.recordSchema == 0 ){
1279 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1280 &srw_res->num_diagnostics,
1281 7, "recordSchema" );
1284 rr.record_schema = odr_strdup(assoc->encode,
1285 srw_req->record.recordSchema );
1287 switch (srw_req->record.recordPacking)
1289 case Z_SRW_recordPacking_string:
1290 rr.record_packing = "string";
1292 case Z_SRW_recordPacking_XML:
1293 rr.record_packing = "xml";
1295 case Z_SRW_recordPacking_URL:
1296 rr.record_packing = "url";
1299 if ( srw_req->record.recordData_len ){
1300 rr.record_data = odr_strdupn(assoc->encode,
1301 srw_req->record.recordData_buf,
1302 srw_req->record.recordData_len );
1303 rr.request_extra_record = srw_req->extra_record;
1306 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1307 &srw_res->num_diagnostics,
1310 if (srw_req->extraRequestData)
1311 rr.extra_request_data = odr_strdup(assoc->encode,
1312 srw_req->extraRequestData );
1314 else if ( !strcmp( rr.operation, "insert" ) )
1316 if ( srw_req->record.recordSchema == 0 ){
1317 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1318 &srw_res->num_diagnostics,
1319 7, "recordSchema" );
1322 rr.record_schema = odr_strdup(assoc->encode,
1323 srw_req->record.recordSchema);
1325 switch (srw_req->record.recordPacking)
1327 case Z_SRW_recordPacking_string:
1328 rr.record_packing = "string";
1330 case Z_SRW_recordPacking_XML:
1331 rr.record_packing = "xml";
1333 case Z_SRW_recordPacking_URL:
1334 rr.record_packing = "url";
1338 if (srw_req->record.recordData_len)
1340 rr.record_data = odr_strdupn(assoc->encode,
1341 srw_req->record.recordData_buf,
1342 srw_req->record.recordData_len );
1343 rr.request_extra_record = srw_req->extra_record;
1346 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1347 &srw_res->num_diagnostics,
1349 if ( srw_req->extraRequestData )
1350 rr.extra_request_data = odr_strdup(assoc->encode,
1351 srw_req->extraRequestData );
1353 if (srw_res->num_diagnostics == 0)
1355 if ( assoc->init->bend_srw_update)
1356 (*assoc->init->bend_srw_update)(assoc->backend, &rr);
1358 yaz_log( YLOG_WARN, "Got No Update function!");
1363 yaz_add_srw_diagnostic(assoc->encode,
1364 &srw_res->diagnostics,
1365 &srw_res->num_diagnostics,
1366 rr.errcode, rr.errstring);
1367 srw_res->recordId = rr.record_id;
1368 srw_res->operationStatus = rr.operation_status;
1369 srw_res->recordVersion = rr.record_version;
1370 srw_res->recordChecksum = rr.record_checksum;
1371 srw_res->extraResponseData = rr.extra_response_data;
1372 srw_res->record.recordPosition = 0;
1373 if (srw_res->num_diagnostics == 0 && rr.record_data)
1375 srw_res->record.recordSchema = rr.record_schema;
1376 srw_res->record.recordPacking = srw_req->record.recordPacking;
1377 srw_res->record.recordData_buf = rr.record_data;
1378 srw_res->record.recordData_len = strlen(rr.record_data);
1379 srw_res->extra_record = rr.response_extra_record;
1383 srw_res->record.recordData_len = 0;
1388 /* check if path is OK (1); BAD (0) */
1389 static int check_path(const char *path)
1393 if (strstr(path, ".."))
1398 static char *read_file(const char *fname, ODR o, int *sz)
1401 FILE *inf = fopen(fname, "rb");
1405 fseek(inf, 0L, SEEK_END);
1408 buf = odr_malloc(o, *sz);
1409 fread(buf, 1, *sz, inf);
1414 static void process_http_request(association *assoc, request *req)
1416 Z_HTTP_Request *hreq = req->gdu_request->u.HTTP_Request;
1417 ODR o = assoc->encode;
1418 int r = 2; /* 2=NOT TAKEN, 1=TAKEN, 0=SOAP TAKEN */
1420 Z_SOAP *soap_package = 0;
1423 Z_HTTP_Response *hres = 0;
1425 const char *stylesheet = 0; /* for now .. set later */
1426 Z_SRW_diagnostic *diagnostic = 0;
1427 int num_diagnostic = 0;
1428 const char *host = z_HTTP_header_lookup(hreq->headers, "Host");
1430 if (!control_association(assoc, host, 0))
1432 p = z_get_HTTP_Response(o, 404);
1435 if (r == 2 && assoc->docpath && hreq->path[0] == '/'
1437 /* check if path is a proper prefix of documentroot */
1438 strncmp(hreq->path+1, assoc->docpath, strlen(assoc->docpath))
1441 if (!check_path(hreq->path))
1443 yaz_log(YLOG_LOG, "File %s access forbidden", hreq->path+1);
1444 p = z_get_HTTP_Response(o, 404);
1448 int content_size = 0;
1449 char *content_buf = read_file(hreq->path+1, o, &content_size);
1452 yaz_log(YLOG_LOG, "File %s not found", hreq->path+1);
1453 p = z_get_HTTP_Response(o, 404);
1457 const char *ctype = 0;
1458 yaz_mime_types types = yaz_mime_types_create();
1460 yaz_mime_types_add(types, "xsl", "application/xml");
1461 yaz_mime_types_add(types, "xml", "application/xml");
1462 yaz_mime_types_add(types, "css", "text/css");
1463 yaz_mime_types_add(types, "html", "text/html");
1464 yaz_mime_types_add(types, "htm", "text/html");
1465 yaz_mime_types_add(types, "txt", "text/plain");
1467 yaz_mime_types_add(types, "gif", "image/gif");
1468 yaz_mime_types_add(types, "png", "image/png");
1469 yaz_mime_types_add(types, "jpg", "image/jpeg");
1470 yaz_mime_types_add(types, "jpeg", "image/jpeg");
1472 ctype = yaz_mime_lookup_fname(types, hreq->path);
1475 yaz_log(YLOG_LOG, "No mime type for %s", hreq->path+1);
1476 p = z_get_HTTP_Response(o, 404);
1480 p = z_get_HTTP_Response(o, 200);
1481 hres = p->u.HTTP_Response;
1482 hres->content_buf = content_buf;
1483 hres->content_len = content_size;
1484 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1486 yaz_mime_types_destroy(types);
1494 r = yaz_srw_decode(hreq, &sr, &soap_package, assoc->decode, &charset);
1495 yaz_log(YLOG_DEBUG, "yaz_srw_decode returned %d", r);
1497 if (r == 2) /* not taken */
1499 r = yaz_sru_decode(hreq, &sr, &soap_package, assoc->decode, &charset,
1500 &diagnostic, &num_diagnostic);
1501 yaz_log(YLOG_DEBUG, "yaz_sru_decode returned %d", r);
1503 if (r == 0) /* decode SRW/SRU OK .. */
1505 int http_code = 200;
1506 if (sr->which == Z_SRW_searchRetrieve_request)
1509 yaz_srw_get(assoc->encode, Z_SRW_searchRetrieve_response);
1511 stylesheet = sr->u.request->stylesheet;
1514 res->u.response->diagnostics = diagnostic;
1515 res->u.response->num_diagnostics = num_diagnostic;
1519 srw_bend_search(assoc, req, sr->u.request, res->u.response,
1522 if (http_code == 200)
1523 soap_package->u.generic->p = res;
1525 else if (sr->which == Z_SRW_explain_request)
1527 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_explain_response);
1528 stylesheet = sr->u.explain_request->stylesheet;
1531 res->u.explain_response->diagnostics = diagnostic;
1532 res->u.explain_response->num_diagnostics = num_diagnostic;
1534 srw_bend_explain(assoc, req, sr->u.explain_request,
1535 res->u.explain_response, &http_code);
1536 if (http_code == 200)
1537 soap_package->u.generic->p = res;
1539 else if (sr->which == Z_SRW_scan_request)
1541 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_scan_response);
1542 stylesheet = sr->u.scan_request->stylesheet;
1545 res->u.scan_response->diagnostics = diagnostic;
1546 res->u.scan_response->num_diagnostics = num_diagnostic;
1548 srw_bend_scan(assoc, req, sr->u.scan_request,
1549 res->u.scan_response, &http_code);
1550 if (http_code == 200)
1551 soap_package->u.generic->p = res;
1553 else if (sr->which == Z_SRW_update_request)
1555 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_update_response);
1556 yaz_log(YLOG_DEBUG, "handling SRW UpdateRequest");
1559 res->u.update_response->diagnostics = diagnostic;
1560 res->u.update_response->num_diagnostics = num_diagnostic;
1562 yaz_log(YLOG_DEBUG, "num_diag = %d", res->u.update_response->num_diagnostics );
1563 srw_bend_update(assoc, req, sr->u.update_request,
1564 res->u.update_response, &http_code);
1565 if (http_code == 200)
1566 soap_package->u.generic->p = res;
1570 yaz_log(log_request, "SOAP ERROR");
1571 /* FIXME - what error, what query */
1573 z_soap_error(assoc->encode, soap_package,
1574 "SOAP-ENV:Client", "Bad method", 0);
1576 if (http_code == 200 || http_code == 500)
1578 static Z_SOAP_Handler soap_handlers[4] = {
1580 {"http://www.loc.gov/zing/srw/", 0,
1581 (Z_SOAP_fun) yaz_srw_codec},
1582 {"http://www.loc.gov/zing/srw/v1.0/", 0,
1583 (Z_SOAP_fun) yaz_srw_codec},
1584 {"http://www.loc.gov/zing/srw/update/", 0,
1585 (Z_SOAP_fun) yaz_ucp_codec},
1591 p = z_get_HTTP_Response(o, 200);
1592 hres = p->u.HTTP_Response;
1595 stylesheet = assoc->stylesheet;
1597 /* empty stylesheet means NO stylesheet */
1598 if (stylesheet && *stylesheet == '\0')
1601 ret = z_soap_codec_enc_xsl(assoc->encode, &soap_package,
1602 &hres->content_buf, &hres->content_len,
1603 soap_handlers, charset, stylesheet);
1604 hres->code = http_code;
1606 strcpy(ctype, "text/xml");
1609 strcat(ctype, "; charset=");
1610 strcat(ctype, charset);
1612 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1615 p = z_get_HTTP_Response(o, http_code);
1619 p = z_get_HTTP_Response(o, 500);
1620 hres = p->u.HTTP_Response;
1621 if (!strcmp(hreq->version, "1.0"))
1623 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1624 if (v && !strcmp(v, "Keep-Alive"))
1628 hres->version = "1.0";
1632 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1633 if (v && !strcmp(v, "close"))
1637 hres->version = "1.1";
1641 z_HTTP_header_add(o, &hres->headers, "Connection", "close");
1642 assoc->state = ASSOC_DEAD;
1643 assoc->cs_get_mask = 0;
1648 const char *alive = z_HTTP_header_lookup(hreq->headers, "Keep-Alive");
1650 if (alive && isdigit(*(const unsigned char *) alive))
1654 if (t < 0 || t > 3600)
1656 iochan_settimeout(assoc->client_chan,t);
1657 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1659 process_gdu_response(assoc, req, p);
1662 static void process_gdu_request(association *assoc, request *req)
1664 if (req->gdu_request->which == Z_GDU_Z3950)
1667 req->apdu_request = req->gdu_request->u.z3950;
1668 if (process_z_request(assoc, req, &msg) < 0)
1669 do_close_req(assoc, Z_Close_systemProblem, msg, req);
1671 else if (req->gdu_request->which == Z_GDU_HTTP_Request)
1672 process_http_request(assoc, req);
1675 do_close_req(assoc, Z_Close_systemProblem, "bad protocol packet", req);
1680 * Initiate request processing.
1682 static int process_z_request(association *assoc, request *req, char **msg)
1688 *msg = "Unknown Error";
1689 assert(req && req->state == REQUEST_IDLE);
1690 if (req->apdu_request->which != Z_APDU_initRequest && !assoc->init)
1692 *msg = "Missing InitRequest";
1695 switch (req->apdu_request->which)
1697 case Z_APDU_initRequest:
1698 res = process_initRequest(assoc, req); break;
1699 case Z_APDU_searchRequest:
1700 res = process_searchRequest(assoc, req, &fd); break;
1701 case Z_APDU_presentRequest:
1702 res = process_presentRequest(assoc, req, &fd); break;
1703 case Z_APDU_scanRequest:
1704 if (assoc->init->bend_scan)
1705 res = process_scanRequest(assoc, req, &fd);
1708 *msg = "Cannot handle Scan APDU";
1712 case Z_APDU_extendedServicesRequest:
1713 if (assoc->init->bend_esrequest)
1714 res = process_ESRequest(assoc, req, &fd);
1717 *msg = "Cannot handle Extended Services APDU";
1721 case Z_APDU_sortRequest:
1722 if (assoc->init->bend_sort)
1723 res = process_sortRequest(assoc, req, &fd);
1726 *msg = "Cannot handle Sort APDU";
1731 process_close(assoc, req);
1733 case Z_APDU_deleteResultSetRequest:
1734 if (assoc->init->bend_delete)
1735 res = process_deleteRequest(assoc, req, &fd);
1738 *msg = "Cannot handle Delete APDU";
1742 case Z_APDU_segmentRequest:
1743 if (assoc->init->bend_segment)
1745 res = process_segmentRequest (assoc, req);
1749 *msg = "Cannot handle Segment APDU";
1753 case Z_APDU_triggerResourceControlRequest:
1756 *msg = "Bad APDU received";
1761 yaz_log(YLOG_DEBUG, " result immediately available");
1762 retval = process_z_response(assoc, req, res);
1766 yaz_log(YLOG_DEBUG, " result unavailble");
1769 else /* no result yet - one will be provided later */
1773 /* Set up an I/O handler for the fd supplied by the backend */
1775 yaz_log(YLOG_DEBUG, " establishing handler for result");
1776 req->state = REQUEST_PENDING;
1777 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT, 0)))
1779 iochan_setdata(chan, assoc);
1786 * Handle message from the backend.
1788 void backend_response(IOCHAN i, int event)
1790 association *assoc = (association *)iochan_getdata(i);
1791 request *req = request_head(&assoc->incoming);
1795 yaz_log(YLOG_DEBUG, "backend_response");
1796 assert(assoc && req && req->state != REQUEST_IDLE);
1797 /* determine what it is we're waiting for */
1798 switch (req->apdu_request->which)
1800 case Z_APDU_searchRequest:
1801 res = response_searchRequest(assoc, req, 0, &fd); break;
1803 case Z_APDU_presentRequest:
1804 res = response_presentRequest(assoc, req, 0, &fd); break;
1805 case Z_APDU_scanRequest:
1806 res = response_scanRequest(assoc, req, 0, &fd); break;
1809 yaz_log(YLOG_FATAL, "Serious programmer's lapse or bug");
1812 if ((res && process_z_response(assoc, req, res) < 0) || fd < 0)
1814 yaz_log(YLOG_WARN, "Fatal error when talking to backend");
1815 do_close(assoc, Z_Close_systemProblem, 0);
1819 else if (!res) /* no result yet - try again later */
1821 yaz_log(YLOG_DEBUG, " no result yet");
1822 iochan_setfd(i, fd); /* in case fd has changed */
1827 * Encode response, and transfer the request structure to the outgoing queue.
1829 static int process_gdu_response(association *assoc, request *req, Z_GDU *res)
1831 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
1835 if (!z_GDU(assoc->print, &res, 0, 0))
1836 yaz_log(YLOG_WARN, "ODR print error: %s",
1837 odr_errmsg(odr_geterror(assoc->print)));
1838 odr_reset(assoc->print);
1840 if (!z_GDU(assoc->encode, &res, 0, 0))
1842 yaz_log(YLOG_WARN, "ODR error when encoding PDU: %s [element %s]",
1843 odr_errmsg(odr_geterror(assoc->decode)),
1844 odr_getelement(assoc->decode));
1847 req->response = odr_getbuf(assoc->encode, &req->len_response,
1848 &req->size_response);
1849 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
1850 odr_reset(assoc->encode);
1851 req->state = REQUEST_IDLE;
1852 request_enq(&assoc->outgoing, req);
1853 /* turn the work over to the ir_session handler */
1854 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
1855 assoc->cs_put_mask = EVENT_OUTPUT;
1856 /* Is there more work to be done? give that to the input handler too */
1858 if (request_head(&assoc->incoming))
1860 yaz_log (YLOG_DEBUG, "more work to be done");
1861 iochan_setevent(assoc->client_chan, EVENT_WORK);
1868 * Encode response, and transfer the request structure to the outgoing queue.
1870 static int process_z_response(association *assoc, request *req, Z_APDU *res)
1872 Z_GDU *gres = (Z_GDU *) odr_malloc(assoc->encode, sizeof(*res));
1873 gres->which = Z_GDU_Z3950;
1874 gres->u.z3950 = res;
1876 return process_gdu_response(assoc, req, gres);
1879 static char *get_vhost(Z_OtherInformation *otherInfo)
1881 return yaz_oi_get_string_oidval(&otherInfo, VAL_PROXY, 1, 0);
1885 * Handle init request.
1886 * At the moment, we don't check the options
1887 * anywhere else in the code - we just try not to do anything that would
1888 * break a naive client. We'll toss 'em into the association block when
1889 * we need them there.
1891 static Z_APDU *process_initRequest(association *assoc, request *reqb)
1893 Z_InitRequest *req = reqb->apdu_request->u.initRequest;
1894 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
1895 Z_InitResponse *resp = apdu->u.initResponse;
1896 bend_initresult *binitres;
1899 statserv_options_block *cb = 0; /* by default no control for backend */
1901 if (control_association(assoc, get_vhost(req->otherInfo), 1))
1902 cb = statserv_getcontrol(); /* got control block for backend */
1904 if (cb && assoc->backend)
1905 (*cb->bend_close)(assoc->backend);
1907 yaz_log(log_requestdetail, "Got initRequest");
1908 if (req->implementationId)
1909 yaz_log(log_requestdetail, "Id: %s",
1910 req->implementationId);
1911 if (req->implementationName)
1912 yaz_log(log_requestdetail, "Name: %s",
1913 req->implementationName);
1914 if (req->implementationVersion)
1915 yaz_log(log_requestdetail, "Version: %s",
1916 req->implementationVersion);
1918 assoc_init_reset(assoc);
1920 assoc->init->auth = req->idAuthentication;
1921 assoc->init->referenceId = req->referenceId;
1923 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
1925 Z_CharSetandLanguageNegotiation *negotiation =
1926 yaz_get_charneg_record (req->otherInfo);
1928 negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
1929 assoc->init->charneg_request = negotiation;
1935 if (req->implementationVersion)
1936 yaz_log(log_requestdetail, "Config: %s",
1939 iochan_settimeout(assoc->client_chan, cb->idle_timeout * 60);
1941 /* we have a backend control block, so call that init function */
1942 if (!(binitres = (*cb->bend_init)(assoc->init)))
1944 yaz_log(YLOG_WARN, "Bad response from backend.");
1947 assoc->backend = binitres->handle;
1951 /* no backend. return error */
1952 binitres = odr_malloc(assoc->encode, sizeof(*binitres));
1953 binitres->errstring = 0;
1954 binitres->errcode = YAZ_BIB1_PERMANENT_SYSTEM_ERROR;
1955 iochan_settimeout(assoc->client_chan, 10);
1957 if ((assoc->init->bend_sort))
1958 yaz_log (YLOG_DEBUG, "Sort handler installed");
1959 if ((assoc->init->bend_search))
1960 yaz_log (YLOG_DEBUG, "Search handler installed");
1961 if ((assoc->init->bend_present))
1962 yaz_log (YLOG_DEBUG, "Present handler installed");
1963 if ((assoc->init->bend_esrequest))
1964 yaz_log (YLOG_DEBUG, "ESRequest handler installed");
1965 if ((assoc->init->bend_delete))
1966 yaz_log (YLOG_DEBUG, "Delete handler installed");
1967 if ((assoc->init->bend_scan))
1968 yaz_log (YLOG_DEBUG, "Scan handler installed");
1969 if ((assoc->init->bend_segment))
1970 yaz_log (YLOG_DEBUG, "Segment handler installed");
1972 resp->referenceId = req->referenceId;
1974 /* let's tell the client what we can do */
1975 if (ODR_MASK_GET(req->options, Z_Options_search))
1977 ODR_MASK_SET(resp->options, Z_Options_search);
1978 strcat(options, "srch");
1980 if (ODR_MASK_GET(req->options, Z_Options_present))
1982 ODR_MASK_SET(resp->options, Z_Options_present);
1983 strcat(options, " prst");
1985 if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
1986 assoc->init->bend_delete)
1988 ODR_MASK_SET(resp->options, Z_Options_delSet);
1989 strcat(options, " del");
1991 if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
1992 assoc->init->bend_esrequest)
1994 ODR_MASK_SET(resp->options, Z_Options_extendedServices);
1995 strcat (options, " extendedServices");
1997 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
1999 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
2000 strcat(options, " namedresults");
2002 if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
2004 ODR_MASK_SET(resp->options, Z_Options_scan);
2005 strcat(options, " scan");
2007 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
2009 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
2010 strcat(options, " concurrop");
2012 if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
2014 ODR_MASK_SET(resp->options, Z_Options_sort);
2015 strcat(options, " sort");
2018 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel)
2019 && assoc->init->charneg_response)
2021 Z_OtherInformation **p;
2022 Z_OtherInformationUnit *p0;
2024 yaz_oi_APDU(apdu, &p);
2026 if ((p0=yaz_oi_update(p, assoc->encode, NULL, 0, 0))) {
2027 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
2029 p0->which = Z_OtherInfo_externallyDefinedInfo;
2030 p0->information.externallyDefinedInfo =
2031 assoc->init->charneg_response;
2033 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
2034 strcat(options, " negotiation");
2037 ODR_MASK_SET(resp->options, Z_Options_triggerResourceCtrl);
2039 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
2041 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
2042 assoc->version = 1; /* 1 & 2 are equivalent */
2044 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
2046 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
2049 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
2051 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
2055 yaz_log(log_requestdetail, "Negotiated to v%d: %s", assoc->version, options);
2056 assoc->maximumRecordSize = *req->maximumRecordSize;
2058 if (cb && assoc->maximumRecordSize > cb->maxrecordsize)
2059 assoc->maximumRecordSize = cb->maxrecordsize;
2060 assoc->preferredMessageSize = *req->preferredMessageSize;
2061 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
2062 assoc->preferredMessageSize = assoc->maximumRecordSize;
2064 resp->preferredMessageSize = &assoc->preferredMessageSize;
2065 resp->maximumRecordSize = &assoc->maximumRecordSize;
2067 resp->implementationId = odr_prepend(assoc->encode,
2068 assoc->init->implementation_id,
2069 resp->implementationId);
2071 resp->implementationName = odr_prepend(assoc->encode,
2072 assoc->init->implementation_name,
2073 odr_prepend(assoc->encode, "GFS", resp->implementationName));
2075 version = odr_strdup(assoc->encode, "$Revision: 1.72 $");
2076 if (strlen(version) > 10) /* check for unexpanded CVS strings */
2077 version[strlen(version)-2] = '\0';
2078 resp->implementationVersion = odr_prepend(assoc->encode,
2079 assoc->init->implementation_version,
2080 odr_prepend(assoc->encode, &version[11],
2081 resp->implementationVersion));
2083 if (binitres->errcode)
2085 assoc->state = ASSOC_DEAD;
2086 resp->userInformationField =
2087 init_diagnostics(assoc->encode, binitres->errcode,
2088 binitres->errstring);
2093 if (!req->idAuthentication)
2094 yaz_log(log_request, "Auth none");
2095 else if (req->idAuthentication->which == Z_IdAuthentication_open)
2097 const char *open = req->idAuthentication->u.open;
2098 const char *slash = strchr(open, '/');
2104 yaz_log(log_request, "Auth open %.*s", len, open);
2106 else if (req->idAuthentication->which == Z_IdAuthentication_idPass)
2108 const char *user = req->idAuthentication->u.idPass->userId;
2109 const char *group = req->idAuthentication->u.idPass->groupId;
2110 yaz_log(log_request, "Auth idPass %s %s",
2111 user ? user : "-", group ? group : "-");
2113 else if (req->idAuthentication->which
2114 == Z_IdAuthentication_anonymous)
2116 yaz_log(log_request, "Auth anonymous");
2120 yaz_log(log_request, "Auth other");
2125 WRBUF wr = wrbuf_alloc();
2126 wrbuf_printf(wr, "Init ");
2127 if (binitres->errcode)
2128 wrbuf_printf(wr, "ERROR %d", binitres->errcode);
2130 wrbuf_printf(wr, "OK -");
2131 wrbuf_printf(wr, " ID:%s Name:%s Version:%s",
2132 (req->implementationId ? req->implementationId :"-"),
2133 (req->implementationName ?
2134 req->implementationName : "-"),
2135 (req->implementationVersion ?
2136 req->implementationVersion : "-")
2138 yaz_log(log_request, "%s", wrbuf_buf(wr));
2145 * Set the specified `errcode' and `errstring' into a UserInfo-1
2146 * external to be returned to the client in accordance with Z35.90
2147 * Implementor Agreement 5 (Returning diagnostics in an InitResponse):
2148 * http://lcweb.loc.gov/z3950/agency/agree/initdiag.html
2150 static Z_External *init_diagnostics(ODR odr, int error, const char *addinfo)
2152 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2153 addinfo ? " -- " : "", addinfo ? addinfo : "");
2154 return zget_init_diagnostics(odr, error, addinfo);
2158 * nonsurrogate diagnostic record.
2160 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
2162 Z_Records *rec = (Z_Records *) odr_malloc (assoc->encode, sizeof(*rec));
2164 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2165 addinfo ? " -- " : "", addinfo ? addinfo : "");
2167 rec->which = Z_Records_NSD;
2168 rec->u.nonSurrogateDiagnostic = zget_DefaultDiagFormat(assoc->encode,
2174 * surrogate diagnostic.
2176 static Z_NamePlusRecord *surrogatediagrec(association *assoc,
2178 int error, const char *addinfo)
2180 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2181 addinfo ? " -- " : "", addinfo ? addinfo : "");
2182 return zget_surrogateDiagRec(assoc->encode, dbname, error, addinfo);
2185 static Z_Records *pack_records(association *a, char *setname, int start,
2186 int *num, Z_RecordComposition *comp,
2187 int *next, int *pres, oid_value format,
2188 Z_ReferenceId *referenceId,
2189 int *oid, int *errcode)
2191 int recno, total_length = 0, toget = *num, dumped_records = 0;
2192 Z_Records *records =
2193 (Z_Records *) odr_malloc (a->encode, sizeof(*records));
2194 Z_NamePlusRecordList *reclist =
2195 (Z_NamePlusRecordList *) odr_malloc (a->encode, sizeof(*reclist));
2196 Z_NamePlusRecord **list =
2197 (Z_NamePlusRecord **) odr_malloc (a->encode, sizeof(*list) * toget);
2199 records->which = Z_Records_DBOSD;
2200 records->u.databaseOrSurDiagnostics = reclist;
2201 reclist->num_records = 0;
2202 reclist->records = list;
2203 *pres = Z_PresentStatus_success;
2207 yaz_log(log_requestdetail, "Request to pack %d+%d %s", start, toget, setname);
2208 yaz_log(log_requestdetail, "pms=%d, mrs=%d", a->preferredMessageSize,
2209 a->maximumRecordSize);
2210 for (recno = start; reclist->num_records < toget; recno++)
2213 Z_NamePlusRecord *thisrec;
2214 int this_length = 0;
2216 * we get the number of bytes allocated on the stream before any
2217 * allocation done by the backend - this should give us a reasonable
2218 * idea of the total size of the data so far.
2220 total_length = odr_total(a->encode) - dumped_records;
2226 freq.last_in_set = 0;
2227 freq.setname = setname;
2228 freq.surrogate_flag = 0;
2229 freq.number = recno;
2231 freq.request_format = format;
2232 freq.request_format_raw = oid;
2233 freq.output_format = format;
2234 freq.output_format_raw = 0;
2235 freq.stream = a->encode;
2236 freq.print = a->print;
2237 freq.referenceId = referenceId;
2239 (*a->init->bend_fetch)(a->backend, &freq);
2241 *next = freq.last_in_set ? 0 : recno + 1;
2243 /* backend should be able to signal whether error is system-wide
2244 or only pertaining to current record */
2247 if (!freq.surrogate_flag)
2250 *pres = Z_PresentStatus_failure;
2251 /* for 'present request out of range',
2252 set addinfo to record position if not set */
2253 if (freq.errcode == YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE &&
2254 freq.errstring == 0)
2256 sprintf (s, "%d", recno);
2260 *errcode = freq.errcode;
2261 return diagrec(a, freq.errcode, freq.errstring);
2263 reclist->records[reclist->num_records] =
2264 surrogatediagrec(a, freq.basename, freq.errcode,
2266 reclist->num_records++;
2269 if (freq.record == 0) /* no error and no record ? */
2271 *next = 0; /* signal end-of-set and stop */
2275 this_length = freq.len;
2277 this_length = odr_total(a->encode) - total_length - dumped_records;
2278 yaz_log(YLOG_DEBUG, " fetched record, len=%d, total=%d dumped=%d",
2279 this_length, total_length, dumped_records);
2280 if (a->preferredMessageSize > 0 &&
2281 this_length + total_length > a->preferredMessageSize)
2283 /* record is small enough, really */
2284 if (this_length <= a->preferredMessageSize && recno > start)
2286 yaz_log(log_requestdetail, " Dropped last normal-sized record");
2287 *pres = Z_PresentStatus_partial_2;
2290 /* record can only be fetched by itself */
2291 if (this_length < a->maximumRecordSize)
2293 yaz_log(log_requestdetail, " Record > prefmsgsz");
2296 yaz_log(YLOG_DEBUG, " Dropped it");
2297 reclist->records[reclist->num_records] =
2298 surrogatediagrec(a, freq.basename, 16, 0);
2299 reclist->num_records++;
2300 dumped_records += this_length;
2304 else /* too big entirely */
2306 yaz_log(log_requestdetail, "Record > maxrcdsz this=%d max=%d",
2307 this_length, a->maximumRecordSize);
2308 reclist->records[reclist->num_records] =
2309 surrogatediagrec(a, freq.basename, 17, 0);
2310 reclist->num_records++;
2311 dumped_records += this_length;
2316 if (!(thisrec = (Z_NamePlusRecord *)
2317 odr_malloc(a->encode, sizeof(*thisrec))))
2320 thisrec->databaseName = odr_strdup(a->encode, freq.basename);
2322 thisrec->databaseName = 0;
2323 thisrec->which = Z_NamePlusRecord_databaseRecord;
2325 if (freq.output_format_raw)
2327 struct oident *ident = oid_getentbyoid(freq.output_format_raw);
2328 freq.output_format = ident->value;
2330 thisrec->u.databaseRecord = z_ext_record(a->encode, freq.output_format,
2331 freq.record, freq.len);
2332 if (!thisrec->u.databaseRecord)
2334 reclist->records[reclist->num_records] = thisrec;
2335 reclist->num_records++;
2337 *num = reclist->num_records;
2341 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
2344 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2345 bend_search_rr *bsrr =
2346 (bend_search_rr *)nmem_malloc (reqb->request_mem, sizeof(*bsrr));
2348 yaz_log(log_requestdetail, "Got SearchRequest.");
2350 bsrr->request = reqb;
2351 bsrr->association = assoc;
2352 bsrr->referenceId = req->referenceId;
2353 save_referenceId (reqb, bsrr->referenceId);
2354 bsrr->srw_sortKeys = 0;
2355 bsrr->srw_setname = 0;
2356 bsrr->srw_setnameIdleTime = 0;
2358 yaz_log (log_requestdetail, "ResultSet '%s'", req->resultSetName);
2359 if (req->databaseNames)
2362 for (i = 0; i < req->num_databaseNames; i++)
2363 yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
2366 yaz_log_zquery_level(log_requestdetail,req->query);
2368 if (assoc->init->bend_search)
2370 bsrr->setname = req->resultSetName;
2371 bsrr->replace_set = *req->replaceIndicator;
2372 bsrr->num_bases = req->num_databaseNames;
2373 bsrr->basenames = req->databaseNames;
2374 bsrr->query = req->query;
2375 bsrr->stream = assoc->encode;
2376 nmem_transfer(bsrr->stream->mem, reqb->request_mem);
2377 bsrr->decode = assoc->decode;
2378 bsrr->print = assoc->print;
2381 bsrr->errstring = NULL;
2382 bsrr->search_info = NULL;
2384 if (assoc->cql_transform &&
2385 req->query->which == Z_Query_type_104 &&
2386 req->query->u.type_104->which == Z_External_CQL)
2388 /* have a CQL query and a CQL to PQF transform .. */
2390 cql2pqf(bsrr->stream, req->query->u.type_104->u.cql,
2391 assoc->cql_transform, bsrr->query);
2393 bsrr->errcode = yaz_diag_srw_to_bib1(srw_errcode);
2396 (assoc->init->bend_search)(assoc->backend, bsrr);
2397 if (!bsrr->request) /* backend not ready with the search response */
2398 return 0; /* should not be used any more */
2402 /* FIXME - make a diagnostic for it */
2403 yaz_log(YLOG_WARN,"Search not supported ?!?!");
2405 return response_searchRequest(assoc, reqb, bsrr, fd);
2408 int bend_searchresponse(void *handle, bend_search_rr *bsrr) {return 0;}
2411 * Prepare a searchresponse based on the backend results. We probably want
2412 * to look at making the fetching of records nonblocking as well, but
2413 * so far, we'll keep things simple.
2414 * If bsrt is null, that means we're called in response to a communications
2415 * event, and we'll have to get the response for ourselves.
2417 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
2418 bend_search_rr *bsrt, int *fd)
2420 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2421 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2422 Z_SearchResponse *resp = (Z_SearchResponse *)
2423 odr_malloc (assoc->encode, sizeof(*resp));
2424 int *nulint = odr_intdup (assoc->encode, 0);
2425 bool_t *sr = odr_intdup(assoc->encode, 1);
2426 int *next = odr_intdup(assoc->encode, 0);
2427 int *none = odr_intdup(assoc->encode, Z_SearchResponse_none);
2430 apdu->which = Z_APDU_searchResponse;
2431 apdu->u.searchResponse = resp;
2432 resp->referenceId = req->referenceId;
2433 resp->additionalSearchInfo = 0;
2434 resp->otherInfo = 0;
2436 if (!bsrt && !bend_searchresponse(assoc->backend, bsrt))
2438 yaz_log(YLOG_FATAL, "Bad result from backend");
2441 else if (bsrt->errcode)
2443 resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
2444 resp->resultCount = nulint;
2445 resp->numberOfRecordsReturned = nulint;
2446 resp->nextResultSetPosition = nulint;
2447 resp->searchStatus = nulint;
2448 resp->resultSetStatus = none;
2449 resp->presentStatus = 0;
2453 int *toget = odr_intdup(assoc->encode, 0);
2454 int *presst = odr_intdup(assoc->encode, 0);
2455 Z_RecordComposition comp, *compp = 0;
2457 yaz_log (log_requestdetail, "resultCount: %d", bsrt->hits);
2460 resp->resultCount = &bsrt->hits;
2462 comp.which = Z_RecordComp_simple;
2463 /* how many records does the user agent want, then? */
2464 if (bsrt->hits <= *req->smallSetUpperBound)
2466 *toget = bsrt->hits;
2467 if ((comp.u.simple = req->smallSetElementSetNames))
2470 else if (bsrt->hits < *req->largeSetLowerBound)
2472 *toget = *req->mediumSetPresentNumber;
2473 if (*toget > bsrt->hits)
2474 *toget = bsrt->hits;
2475 if ((comp.u.simple = req->mediumSetElementSetNames))
2481 if (*toget && !resp->records)
2486 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
2489 form = prefformat->value;
2490 resp->records = pack_records(assoc, req->resultSetName, 1,
2491 toget, compp, next, presst, form, req->referenceId,
2492 req->preferredRecordSyntax, NULL);
2495 resp->numberOfRecordsReturned = toget;
2496 returnedrecs = *toget;
2497 resp->nextResultSetPosition = next;
2498 resp->searchStatus = sr;
2499 resp->resultSetStatus = 0;
2500 resp->presentStatus = presst;
2504 if (*resp->resultCount)
2506 resp->numberOfRecordsReturned = nulint;
2507 resp->nextResultSetPosition = next;
2508 resp->searchStatus = sr;
2509 resp->resultSetStatus = 0;
2510 resp->presentStatus = 0;
2513 resp->additionalSearchInfo = bsrt->search_info;
2517 WRBUF wr = wrbuf_alloc();
2519 wrbuf_printf(wr, "ERROR %d", bsrt->errcode);
2521 wrbuf_printf(wr, "OK %d", bsrt->hits);
2522 wrbuf_printf(wr, " %s 1+%d ",
2523 req->resultSetName, returnedrecs);
2524 yaz_query_to_wrbuf(wr, req->query);
2526 yaz_log(log_request, "Search %s", wrbuf_buf(wr));
2533 * Maybe we got a little over-friendly when we designed bend_fetch to
2534 * get only one record at a time. Some backends can optimise multiple-record
2535 * fetches, and at any rate, there is some overhead involved in
2536 * all that selecting and hopping around. Problem is, of course, that the
2537 * frontend can't know ahead of time how many records it'll need to
2538 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
2539 * is downright lousy as a bulk data transfer protocol.
2541 * To start with, we'll do the fetching of records from the backend
2542 * in one operation: To save some trips in and out of the event-handler,
2543 * and to simplify the interface to pack_records. At any rate, asynch
2544 * operation is more fun in operations that have an unpredictable execution
2545 * speed - which is normally more true for search than for present.
2547 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
2550 Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
2554 Z_PresentResponse *resp;
2558 const char *errstring = 0;
2560 yaz_log(log_requestdetail, "Got PresentRequest.");
2562 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
2565 form = prefformat->value;
2566 resp = (Z_PresentResponse *)odr_malloc (assoc->encode, sizeof(*resp));
2568 resp->presentStatus = odr_intdup(assoc->encode, 0);
2569 if (assoc->init->bend_present)
2571 bend_present_rr *bprr = (bend_present_rr *)
2572 nmem_malloc (reqb->request_mem, sizeof(*bprr));
2573 bprr->setname = req->resultSetId;
2574 bprr->start = *req->resultSetStartPoint;
2575 bprr->number = *req->numberOfRecordsRequested;
2576 bprr->format = form;
2577 bprr->comp = req->recordComposition;
2578 bprr->referenceId = req->referenceId;
2579 bprr->stream = assoc->encode;
2580 bprr->print = assoc->print;
2581 bprr->request = reqb;
2582 bprr->association = assoc;
2584 bprr->errstring = NULL;
2585 (*assoc->init->bend_present)(assoc->backend, bprr);
2588 return 0; /* should not happen */
2591 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2592 *resp->presentStatus = Z_PresentStatus_failure;
2593 errcode = bprr->errcode;
2594 errstring = bprr->errstring;
2597 apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2598 next = odr_intdup(assoc->encode, 0);
2599 num = odr_intdup(assoc->encode, 0);
2601 apdu->which = Z_APDU_presentResponse;
2602 apdu->u.presentResponse = resp;
2603 resp->referenceId = req->referenceId;
2604 resp->otherInfo = 0;
2608 *num = *req->numberOfRecordsRequested;
2610 pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
2611 num, req->recordComposition, next,
2612 resp->presentStatus,
2613 form, req->referenceId, req->preferredRecordSyntax,
2618 WRBUF wr = wrbuf_alloc();
2619 wrbuf_printf(wr, "Present ");
2621 if (*resp->presentStatus == Z_PresentStatus_failure)
2622 wrbuf_printf(wr, "ERROR %d", errcode);
2623 else if (*resp->presentStatus == Z_PresentStatus_success)
2624 wrbuf_printf(wr, "OK -");
2626 wrbuf_printf(wr, "Partial %d", *resp->presentStatus);
2628 wrbuf_printf(wr, " %s %d+%d ",
2629 req->resultSetId, *req->resultSetStartPoint,
2630 *req->numberOfRecordsRequested);
2631 yaz_log(log_request, "%s", wrbuf_buf(wr) );
2636 resp->numberOfRecordsReturned = num;
2637 resp->nextResultSetPosition = next;
2643 * Scan was implemented rather in a hurry, and with support for only the basic
2644 * elements of the service in the backend API. Suggestions are welcome.
2646 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
2648 Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
2649 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2650 Z_ScanResponse *res = (Z_ScanResponse *)
2651 odr_malloc (assoc->encode, sizeof(*res));
2652 int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
2653 int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
2654 Z_ListEntries *ents = (Z_ListEntries *)
2655 odr_malloc (assoc->encode, sizeof(*ents));
2656 Z_DiagRecs *diagrecs_p = NULL;
2658 bend_scan_rr *bsrr = (bend_scan_rr *)
2659 odr_malloc (assoc->encode, sizeof(*bsrr));
2660 struct scan_entry *save_entries;
2662 yaz_log(log_requestdetail, "Got ScanRequest");
2664 apdu->which = Z_APDU_scanResponse;
2665 apdu->u.scanResponse = res;
2666 res->referenceId = req->referenceId;
2668 /* if step is absent, set it to 0 */
2669 res->stepSize = odr_intdup(assoc->encode, 0);
2671 *res->stepSize = *req->stepSize;
2673 res->scanStatus = scanStatus;
2674 res->numberOfEntriesReturned = numberOfEntriesReturned;
2675 res->positionOfTerm = 0;
2676 res->entries = ents;
2677 ents->num_entries = 0;
2678 ents->entries = NULL;
2679 ents->num_nonsurrogateDiagnostics = 0;
2680 ents->nonsurrogateDiagnostics = NULL;
2681 res->attributeSet = 0;
2684 if (req->databaseNames)
2687 for (i = 0; i < req->num_databaseNames; i++)
2688 yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
2690 bsrr->scanClause = 0;
2692 bsrr->errstring = 0;
2693 bsrr->num_bases = req->num_databaseNames;
2694 bsrr->basenames = req->databaseNames;
2695 bsrr->num_entries = *req->numberOfTermsRequested;
2696 bsrr->term = req->termListAndStartPoint;
2697 bsrr->referenceId = req->referenceId;
2698 bsrr->stream = assoc->encode;
2699 bsrr->print = assoc->print;
2700 bsrr->step_size = res->stepSize;
2702 /* For YAZ 2.0 and earlier it was the backend handler that
2703 initialized entries (member display_term did not exist)
2704 YAZ 2.0 and later sets 'entries' and initialize all members
2705 including 'display_term'. If YAZ 2.0 or later sees that
2706 entries was modified - we assume that it is an old handler and
2707 that 'display_term' is _not_ set.
2709 if (bsrr->num_entries > 0)
2712 bsrr->entries = odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
2714 for (i = 0; i<bsrr->num_entries; i++)
2716 bsrr->entries[i].term = 0;
2717 bsrr->entries[i].occurrences = 0;
2718 bsrr->entries[i].errcode = 0;
2719 bsrr->entries[i].errstring = 0;
2720 bsrr->entries[i].display_term = 0;
2723 save_entries = bsrr->entries; /* save it so we can compare later */
2725 if (req->attributeSet &&
2726 (attset = oid_getentbyoid(req->attributeSet)) &&
2727 (attset->oclass == CLASS_ATTSET || attset->oclass == CLASS_GENERAL))
2728 bsrr->attributeset = attset->value;
2730 bsrr->attributeset = VAL_NONE;
2731 log_scan_term_level (log_requestdetail, req->termListAndStartPoint,
2732 bsrr->attributeset);
2733 bsrr->term_position = req->preferredPositionInResponse ?
2734 *req->preferredPositionInResponse : 1;
2736 ((int (*)(void *, bend_scan_rr *))
2737 (*assoc->init->bend_scan))(assoc->backend, bsrr);
2740 diagrecs_p = zget_DiagRecs(assoc->encode,
2741 bsrr->errcode, bsrr->errstring);
2745 Z_Entry **tab = (Z_Entry **)
2746 odr_malloc (assoc->encode, sizeof(*tab) * bsrr->num_entries);
2748 if (bsrr->status == BEND_SCAN_PARTIAL)
2749 *scanStatus = Z_Scan_partial_5;
2751 *scanStatus = Z_Scan_success;
2752 ents->entries = tab;
2753 ents->num_entries = bsrr->num_entries;
2754 res->numberOfEntriesReturned = &ents->num_entries;
2755 res->positionOfTerm = &bsrr->term_position;
2756 for (i = 0; i < bsrr->num_entries; i++)
2762 tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
2763 if (bsrr->entries[i].occurrences >= 0)
2765 e->which = Z_Entry_termInfo;
2766 e->u.termInfo = t = (Z_TermInfo *)
2767 odr_malloc(assoc->encode, sizeof(*t));
2768 t->suggestedAttributes = 0;
2770 if (save_entries == bsrr->entries &&
2771 bsrr->entries[i].display_term)
2773 /* the entries was _not_ set by the handler. So it's
2774 safe to test for new member display_term. It is
2777 t->displayTerm = odr_strdup(assoc->encode,
2778 bsrr->entries[i].display_term);
2780 t->alternativeTerm = 0;
2781 t->byAttributes = 0;
2782 t->otherTermInfo = 0;
2783 t->globalOccurrences = &bsrr->entries[i].occurrences;
2784 t->term = (Z_Term *)
2785 odr_malloc(assoc->encode, sizeof(*t->term));
2786 t->term->which = Z_Term_general;
2787 t->term->u.general = o =
2788 (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
2789 o->buf = (unsigned char *)
2790 odr_malloc(assoc->encode, o->len = o->size =
2791 strlen(bsrr->entries[i].term));
2792 memcpy(o->buf, bsrr->entries[i].term, o->len);
2793 yaz_log(YLOG_DEBUG, " term #%d: '%s' (%d)", i,
2794 bsrr->entries[i].term, bsrr->entries[i].occurrences);
2798 Z_DiagRecs *drecs = zget_DiagRecs(assoc->encode,
2799 bsrr->entries[i].errcode,
2800 bsrr->entries[i].errstring);
2801 assert (drecs->num_diagRecs == 1);
2802 e->which = Z_Entry_surrogateDiagnostic;
2803 assert (drecs->diagRecs[0]);
2804 e->u.surrogateDiagnostic = drecs->diagRecs[0];
2810 ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
2811 ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
2815 WRBUF wr = wrbuf_alloc();
2817 wr_diag(wr, bsrr->errcode, bsrr->errstring);
2818 else if (*res->scanStatus == Z_Scan_success)
2819 wrbuf_printf(wr, "OK");
2821 wrbuf_printf(wr, "Partial");
2823 wrbuf_printf(wr, " %d+%d %d ",
2824 (req->preferredPositionInResponse ?
2825 *req->preferredPositionInResponse : 1),
2826 *req->numberOfTermsRequested,
2827 (res->stepSize ? *res->stepSize : 0));
2828 yaz_scan_to_wrbuf(wr, req->termListAndStartPoint,
2829 bsrr->attributeset);
2830 yaz_log(log_request, "Scan %s", wrbuf_buf(wr) );
2836 static Z_APDU *process_sortRequest(association *assoc, request *reqb,
2840 Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
2841 Z_SortResponse *res = (Z_SortResponse *)
2842 odr_malloc (assoc->encode, sizeof(*res));
2843 bend_sort_rr *bsrr = (bend_sort_rr *)
2844 odr_malloc (assoc->encode, sizeof(*bsrr));
2846 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2848 yaz_log(log_requestdetail, "Got SortRequest.");
2850 bsrr->num_input_setnames = req->num_inputResultSetNames;
2851 for (i=0;i<req->num_inputResultSetNames;i++)
2852 yaz_log(log_requestdetail, "Input resultset: '%s'",
2853 req->inputResultSetNames[i]);
2854 bsrr->input_setnames = req->inputResultSetNames;
2855 bsrr->referenceId = req->referenceId;
2856 bsrr->output_setname = req->sortedResultSetName;
2857 yaz_log(log_requestdetail, "Output resultset: '%s'",
2858 req->sortedResultSetName);
2859 bsrr->sort_sequence = req->sortSequence;
2860 /*FIXME - dump those sequences too */
2861 bsrr->stream = assoc->encode;
2862 bsrr->print = assoc->print;
2864 bsrr->sort_status = Z_SortResponse_failure;
2866 bsrr->errstring = 0;
2868 (*assoc->init->bend_sort)(assoc->backend, bsrr);
2870 res->referenceId = bsrr->referenceId;
2871 res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
2872 res->resultSetStatus = 0;
2875 Z_DiagRecs *dr = zget_DiagRecs(assoc->encode,
2876 bsrr->errcode, bsrr->errstring);
2877 res->diagnostics = dr->diagRecs;
2878 res->num_diagnostics = dr->num_diagRecs;
2882 res->num_diagnostics = 0;
2883 res->diagnostics = 0;
2885 res->resultCount = 0;
2888 apdu->which = Z_APDU_sortResponse;
2889 apdu->u.sortResponse = res;
2892 WRBUF wr = wrbuf_alloc();
2893 wrbuf_printf(wr, "Sort ");
2895 wrbuf_printf(wr, " ERROR %d", bsrr->errcode);
2897 wrbuf_printf(wr, "OK -");
2898 wrbuf_printf(wr, " (");
2899 for (i = 0; i<req->num_inputResultSetNames; i++)
2902 wrbuf_printf(wr, ",");
2903 wrbuf_printf(wr, req->inputResultSetNames[i]);
2905 wrbuf_printf(wr, ")->%s ",req->sortedResultSetName);
2907 yaz_log(log_request, "%s", wrbuf_buf(wr) );
2913 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
2917 Z_DeleteResultSetRequest *req =
2918 reqb->apdu_request->u.deleteResultSetRequest;
2919 Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
2920 odr_malloc (assoc->encode, sizeof(*res));
2921 bend_delete_rr *bdrr = (bend_delete_rr *)
2922 odr_malloc (assoc->encode, sizeof(*bdrr));
2923 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2925 yaz_log(log_requestdetail, "Got DeleteRequest.");
2927 bdrr->num_setnames = req->num_resultSetList;
2928 bdrr->setnames = req->resultSetList;
2929 for (i = 0; i<req->num_resultSetList; i++)
2930 yaz_log(log_requestdetail, "resultset: '%s'",
2931 req->resultSetList[i]);
2932 bdrr->stream = assoc->encode;
2933 bdrr->print = assoc->print;
2934 bdrr->function = *req->deleteFunction;
2935 bdrr->referenceId = req->referenceId;
2937 if (bdrr->num_setnames > 0)
2939 bdrr->statuses = (int*)
2940 odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
2941 bdrr->num_setnames);
2942 for (i = 0; i < bdrr->num_setnames; i++)
2943 bdrr->statuses[i] = 0;
2945 (*assoc->init->bend_delete)(assoc->backend, bdrr);
2947 res->referenceId = req->referenceId;
2949 res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
2951 res->deleteListStatuses = 0;
2952 if (bdrr->num_setnames > 0)
2955 res->deleteListStatuses = (Z_ListStatuses *)
2956 odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
2957 res->deleteListStatuses->num = bdrr->num_setnames;
2958 res->deleteListStatuses->elements =
2960 odr_malloc (assoc->encode,
2961 sizeof(*res->deleteListStatuses->elements) *
2962 bdrr->num_setnames);
2963 for (i = 0; i<bdrr->num_setnames; i++)
2965 res->deleteListStatuses->elements[i] =
2967 odr_malloc (assoc->encode,
2968 sizeof(**res->deleteListStatuses->elements));
2969 res->deleteListStatuses->elements[i]->status = bdrr->statuses+i;
2970 res->deleteListStatuses->elements[i]->id =
2971 odr_strdup (assoc->encode, bdrr->setnames[i]);
2974 res->numberNotDeleted = 0;
2975 res->bulkStatuses = 0;
2976 res->deleteMessage = 0;
2979 apdu->which = Z_APDU_deleteResultSetResponse;
2980 apdu->u.deleteResultSetResponse = res;
2983 WRBUF wr = wrbuf_alloc();
2984 wrbuf_printf(wr, "Delete ");
2985 if (bdrr->delete_status)
2986 wrbuf_printf(wr, "ERROR %d", bdrr->delete_status);
2988 wrbuf_printf(wr, "OK -");
2989 for (i = 0; i<req->num_resultSetList; i++)
2990 wrbuf_printf(wr, " %s ", req->resultSetList[i]);
2991 yaz_log(log_request, "%s", wrbuf_buf(wr) );
2997 static void process_close(association *assoc, request *reqb)
2999 Z_Close *req = reqb->apdu_request->u.close;
3000 static char *reasons[] =
3007 "securityViolation",
3014 yaz_log(log_requestdetail, "Got Close, reason %s, message %s",
3015 reasons[*req->closeReason], req->diagnosticInformation ?
3016 req->diagnosticInformation : "NULL");
3017 if (assoc->version < 3) /* to make do_force respond with close */
3019 do_close_req(assoc, Z_Close_finished,
3020 "Association terminated by client", reqb);
3021 yaz_log(log_request,"Close OK");
3024 void save_referenceId (request *reqb, Z_ReferenceId *refid)
3028 reqb->len_refid = refid->len;
3029 reqb->refid = (char *)nmem_malloc (reqb->request_mem, refid->len);
3030 memcpy (reqb->refid, refid->buf, refid->len);
3034 reqb->len_refid = 0;
3039 void bend_request_send (bend_association a, bend_request req, Z_APDU *res)
3041 process_z_response (a, req, res);
3044 bend_request bend_request_mk (bend_association a)
3046 request *nreq = request_get (&a->outgoing);
3047 nreq->request_mem = nmem_create ();
3051 Z_ReferenceId *bend_request_getid (ODR odr, bend_request req)
3056 id = (Odr_oct *)odr_malloc (odr, sizeof(*odr));
3057 id->buf = (unsigned char *)odr_malloc (odr, req->len_refid);
3058 id->len = id->size = req->len_refid;
3059 memcpy (id->buf, req->refid, req->len_refid);
3063 void bend_request_destroy (bend_request *req)
3065 nmem_destroy((*req)->request_mem);
3066 request_release(*req);
3070 int bend_backend_respond (bend_association a, bend_request req)
3074 r = process_z_request (a, req, &msg);
3076 yaz_log (YLOG_WARN, "%s", msg);
3080 void bend_request_setdata(bend_request r, void *p)
3085 void *bend_request_getdata(bend_request r)
3087 return r->clientData;
3090 static Z_APDU *process_segmentRequest (association *assoc, request *reqb)
3092 bend_segment_rr req;
3094 req.segment = reqb->apdu_request->u.segmentRequest;
3095 req.stream = assoc->encode;
3096 req.decode = assoc->decode;
3097 req.print = assoc->print;
3098 req.association = assoc;
3100 (*assoc->init->bend_segment)(assoc->backend, &req);
3105 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd)
3107 bend_esrequest_rr esrequest;
3108 const char *ext_name = "unknown";
3110 Z_ExtendedServicesRequest *req =
3111 reqb->apdu_request->u.extendedServicesRequest;
3112 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
3114 Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
3116 esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
3117 esrequest.stream = assoc->encode;
3118 esrequest.decode = assoc->decode;
3119 esrequest.print = assoc->print;
3120 esrequest.errcode = 0;
3121 esrequest.errstring = NULL;
3122 esrequest.request = reqb;
3123 esrequest.association = assoc;
3124 esrequest.taskPackage = 0;
3125 esrequest.referenceId = req->referenceId;
3128 if (esrequest.esr && esrequest.esr->taskSpecificParameters)
3130 switch(esrequest.esr->taskSpecificParameters->which)
3132 case Z_External_itemOrder:
3133 ext_name = "ItemOrder"; break;
3134 case Z_External_update:
3135 ext_name = "Update"; break;
3136 case Z_External_update0:
3137 ext_name = "Update0"; break;
3138 case Z_External_ESAdmin:
3139 ext_name = "Admin"; break;
3144 (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
3146 /* If the response is being delayed, return NULL */
3147 if (esrequest.request == NULL)
3150 resp->referenceId = req->referenceId;
3152 if (esrequest.errcode == -1)
3154 /* Backend service indicates request will be processed */
3155 yaz_log(log_request, "Extended Service: %s (accepted)", ext_name);
3156 *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
3158 else if (esrequest.errcode == 0)
3160 /* Backend service indicates request will be processed */
3161 yaz_log(log_request, "Extended Service: %s (done)", ext_name);
3162 *resp->operationStatus = Z_ExtendedServicesResponse_done;
3166 Z_DiagRecs *diagRecs =
3167 zget_DiagRecs(assoc->encode, esrequest.errcode,
3168 esrequest.errstring);
3169 /* Backend indicates error, request will not be processed */
3170 yaz_log(log_request, "Extended Service: %s (failed)", ext_name);
3171 *resp->operationStatus = Z_ExtendedServicesResponse_failure;
3172 resp->num_diagnostics = diagRecs->num_diagRecs;
3173 resp->diagnostics = diagRecs->diagRecs;
3176 WRBUF wr = wrbuf_alloc();
3177 wrbuf_diags(wr, resp->num_diagnostics, resp->diagnostics);
3178 yaz_log(log_request, "EsRequest %s", wrbuf_buf(wr) );
3183 /* Do something with the members of bend_extendedservice */
3184 if (esrequest.taskPackage)
3185 resp->taskPackage = z_ext_record (assoc->encode, VAL_EXTENDED,
3186 (const char *) esrequest.taskPackage,
3188 yaz_log(YLOG_DEBUG,"Send the result apdu");
3195 * indent-tabs-mode: nil
3197 * vim: shiftwidth=4 tabstop=8 expandtab