2 * Copyright (C) 1995-2005, Index Data ApS
3 * See the file LICENSE for details.
5 * $Id: seshigh.c,v 1.75 2006-04-21 10:28:07 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 (long) 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 %ld",
779 code, pqf_msg, (long) off);
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");
1466 yaz_mime_types_add(types, "js", "application/x-javascript");
1468 yaz_mime_types_add(types, "gif", "image/gif");
1469 yaz_mime_types_add(types, "png", "image/png");
1470 yaz_mime_types_add(types, "jpg", "image/jpeg");
1471 yaz_mime_types_add(types, "jpeg", "image/jpeg");
1473 ctype = yaz_mime_lookup_fname(types, hreq->path);
1476 yaz_log(YLOG_LOG, "No mime type for %s", hreq->path+1);
1477 p = z_get_HTTP_Response(o, 404);
1481 p = z_get_HTTP_Response(o, 200);
1482 hres = p->u.HTTP_Response;
1483 hres->content_buf = content_buf;
1484 hres->content_len = content_size;
1485 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1487 yaz_mime_types_destroy(types);
1495 r = yaz_srw_decode(hreq, &sr, &soap_package, assoc->decode, &charset);
1496 yaz_log(YLOG_DEBUG, "yaz_srw_decode returned %d", r);
1498 if (r == 2) /* not taken */
1500 r = yaz_sru_decode(hreq, &sr, &soap_package, assoc->decode, &charset,
1501 &diagnostic, &num_diagnostic);
1502 yaz_log(YLOG_DEBUG, "yaz_sru_decode returned %d", r);
1504 if (r == 0) /* decode SRW/SRU OK .. */
1506 int http_code = 200;
1507 if (sr->which == Z_SRW_searchRetrieve_request)
1510 yaz_srw_get(assoc->encode, Z_SRW_searchRetrieve_response);
1512 stylesheet = sr->u.request->stylesheet;
1515 res->u.response->diagnostics = diagnostic;
1516 res->u.response->num_diagnostics = num_diagnostic;
1520 srw_bend_search(assoc, req, sr->u.request, res->u.response,
1523 if (http_code == 200)
1524 soap_package->u.generic->p = res;
1526 else if (sr->which == Z_SRW_explain_request)
1528 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_explain_response);
1529 stylesheet = sr->u.explain_request->stylesheet;
1532 res->u.explain_response->diagnostics = diagnostic;
1533 res->u.explain_response->num_diagnostics = num_diagnostic;
1535 srw_bend_explain(assoc, req, sr->u.explain_request,
1536 res->u.explain_response, &http_code);
1537 if (http_code == 200)
1538 soap_package->u.generic->p = res;
1540 else if (sr->which == Z_SRW_scan_request)
1542 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_scan_response);
1543 stylesheet = sr->u.scan_request->stylesheet;
1546 res->u.scan_response->diagnostics = diagnostic;
1547 res->u.scan_response->num_diagnostics = num_diagnostic;
1549 srw_bend_scan(assoc, req, sr->u.scan_request,
1550 res->u.scan_response, &http_code);
1551 if (http_code == 200)
1552 soap_package->u.generic->p = res;
1554 else if (sr->which == Z_SRW_update_request)
1556 Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_update_response);
1557 yaz_log(YLOG_DEBUG, "handling SRW UpdateRequest");
1560 res->u.update_response->diagnostics = diagnostic;
1561 res->u.update_response->num_diagnostics = num_diagnostic;
1563 yaz_log(YLOG_DEBUG, "num_diag = %d", res->u.update_response->num_diagnostics );
1564 srw_bend_update(assoc, req, sr->u.update_request,
1565 res->u.update_response, &http_code);
1566 if (http_code == 200)
1567 soap_package->u.generic->p = res;
1571 yaz_log(log_request, "SOAP ERROR");
1572 /* FIXME - what error, what query */
1574 z_soap_error(assoc->encode, soap_package,
1575 "SOAP-ENV:Client", "Bad method", 0);
1577 if (http_code == 200 || http_code == 500)
1579 static Z_SOAP_Handler soap_handlers[4] = {
1581 {"http://www.loc.gov/zing/srw/", 0,
1582 (Z_SOAP_fun) yaz_srw_codec},
1583 {"http://www.loc.gov/zing/srw/v1.0/", 0,
1584 (Z_SOAP_fun) yaz_srw_codec},
1585 {"http://www.loc.gov/zing/srw/update/", 0,
1586 (Z_SOAP_fun) yaz_ucp_codec},
1592 p = z_get_HTTP_Response(o, 200);
1593 hres = p->u.HTTP_Response;
1596 stylesheet = assoc->stylesheet;
1598 /* empty stylesheet means NO stylesheet */
1599 if (stylesheet && *stylesheet == '\0')
1602 ret = z_soap_codec_enc_xsl(assoc->encode, &soap_package,
1603 &hres->content_buf, &hres->content_len,
1604 soap_handlers, charset, stylesheet);
1605 hres->code = http_code;
1607 strcpy(ctype, "text/xml");
1610 strcat(ctype, "; charset=");
1611 strcat(ctype, charset);
1613 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1616 p = z_get_HTTP_Response(o, http_code);
1620 p = z_get_HTTP_Response(o, 500);
1621 hres = p->u.HTTP_Response;
1622 if (!strcmp(hreq->version, "1.0"))
1624 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1625 if (v && !strcmp(v, "Keep-Alive"))
1629 hres->version = "1.0";
1633 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1634 if (v && !strcmp(v, "close"))
1638 hres->version = "1.1";
1642 z_HTTP_header_add(o, &hres->headers, "Connection", "close");
1643 assoc->state = ASSOC_DEAD;
1644 assoc->cs_get_mask = 0;
1649 const char *alive = z_HTTP_header_lookup(hreq->headers, "Keep-Alive");
1651 if (alive && isdigit(*(const unsigned char *) alive))
1655 if (t < 0 || t > 3600)
1657 iochan_settimeout(assoc->client_chan,t);
1658 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1660 process_gdu_response(assoc, req, p);
1663 static void process_gdu_request(association *assoc, request *req)
1665 if (req->gdu_request->which == Z_GDU_Z3950)
1668 req->apdu_request = req->gdu_request->u.z3950;
1669 if (process_z_request(assoc, req, &msg) < 0)
1670 do_close_req(assoc, Z_Close_systemProblem, msg, req);
1672 else if (req->gdu_request->which == Z_GDU_HTTP_Request)
1673 process_http_request(assoc, req);
1676 do_close_req(assoc, Z_Close_systemProblem, "bad protocol packet", req);
1681 * Initiate request processing.
1683 static int process_z_request(association *assoc, request *req, char **msg)
1689 *msg = "Unknown Error";
1690 assert(req && req->state == REQUEST_IDLE);
1691 if (req->apdu_request->which != Z_APDU_initRequest && !assoc->init)
1693 *msg = "Missing InitRequest";
1696 switch (req->apdu_request->which)
1698 case Z_APDU_initRequest:
1699 res = process_initRequest(assoc, req); break;
1700 case Z_APDU_searchRequest:
1701 res = process_searchRequest(assoc, req, &fd); break;
1702 case Z_APDU_presentRequest:
1703 res = process_presentRequest(assoc, req, &fd); break;
1704 case Z_APDU_scanRequest:
1705 if (assoc->init->bend_scan)
1706 res = process_scanRequest(assoc, req, &fd);
1709 *msg = "Cannot handle Scan APDU";
1713 case Z_APDU_extendedServicesRequest:
1714 if (assoc->init->bend_esrequest)
1715 res = process_ESRequest(assoc, req, &fd);
1718 *msg = "Cannot handle Extended Services APDU";
1722 case Z_APDU_sortRequest:
1723 if (assoc->init->bend_sort)
1724 res = process_sortRequest(assoc, req, &fd);
1727 *msg = "Cannot handle Sort APDU";
1732 process_close(assoc, req);
1734 case Z_APDU_deleteResultSetRequest:
1735 if (assoc->init->bend_delete)
1736 res = process_deleteRequest(assoc, req, &fd);
1739 *msg = "Cannot handle Delete APDU";
1743 case Z_APDU_segmentRequest:
1744 if (assoc->init->bend_segment)
1746 res = process_segmentRequest (assoc, req);
1750 *msg = "Cannot handle Segment APDU";
1754 case Z_APDU_triggerResourceControlRequest:
1757 *msg = "Bad APDU received";
1762 yaz_log(YLOG_DEBUG, " result immediately available");
1763 retval = process_z_response(assoc, req, res);
1767 yaz_log(YLOG_DEBUG, " result unavailble");
1770 else /* no result yet - one will be provided later */
1774 /* Set up an I/O handler for the fd supplied by the backend */
1776 yaz_log(YLOG_DEBUG, " establishing handler for result");
1777 req->state = REQUEST_PENDING;
1778 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT, 0)))
1780 iochan_setdata(chan, assoc);
1787 * Handle message from the backend.
1789 void backend_response(IOCHAN i, int event)
1791 association *assoc = (association *)iochan_getdata(i);
1792 request *req = request_head(&assoc->incoming);
1796 yaz_log(YLOG_DEBUG, "backend_response");
1797 assert(assoc && req && req->state != REQUEST_IDLE);
1798 /* determine what it is we're waiting for */
1799 switch (req->apdu_request->which)
1801 case Z_APDU_searchRequest:
1802 res = response_searchRequest(assoc, req, 0, &fd); break;
1804 case Z_APDU_presentRequest:
1805 res = response_presentRequest(assoc, req, 0, &fd); break;
1806 case Z_APDU_scanRequest:
1807 res = response_scanRequest(assoc, req, 0, &fd); break;
1810 yaz_log(YLOG_FATAL, "Serious programmer's lapse or bug");
1813 if ((res && process_z_response(assoc, req, res) < 0) || fd < 0)
1815 yaz_log(YLOG_WARN, "Fatal error when talking to backend");
1816 do_close(assoc, Z_Close_systemProblem, 0);
1820 else if (!res) /* no result yet - try again later */
1822 yaz_log(YLOG_DEBUG, " no result yet");
1823 iochan_setfd(i, fd); /* in case fd has changed */
1828 * Encode response, and transfer the request structure to the outgoing queue.
1830 static int process_gdu_response(association *assoc, request *req, Z_GDU *res)
1832 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
1836 if (!z_GDU(assoc->print, &res, 0, 0))
1837 yaz_log(YLOG_WARN, "ODR print error: %s",
1838 odr_errmsg(odr_geterror(assoc->print)));
1839 odr_reset(assoc->print);
1841 if (!z_GDU(assoc->encode, &res, 0, 0))
1843 yaz_log(YLOG_WARN, "ODR error when encoding PDU: %s [element %s]",
1844 odr_errmsg(odr_geterror(assoc->decode)),
1845 odr_getelement(assoc->decode));
1848 req->response = odr_getbuf(assoc->encode, &req->len_response,
1849 &req->size_response);
1850 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
1851 odr_reset(assoc->encode);
1852 req->state = REQUEST_IDLE;
1853 request_enq(&assoc->outgoing, req);
1854 /* turn the work over to the ir_session handler */
1855 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
1856 assoc->cs_put_mask = EVENT_OUTPUT;
1857 /* Is there more work to be done? give that to the input handler too */
1859 if (request_head(&assoc->incoming))
1861 yaz_log (YLOG_DEBUG, "more work to be done");
1862 iochan_setevent(assoc->client_chan, EVENT_WORK);
1869 * Encode response, and transfer the request structure to the outgoing queue.
1871 static int process_z_response(association *assoc, request *req, Z_APDU *res)
1873 Z_GDU *gres = (Z_GDU *) odr_malloc(assoc->encode, sizeof(*res));
1874 gres->which = Z_GDU_Z3950;
1875 gres->u.z3950 = res;
1877 return process_gdu_response(assoc, req, gres);
1880 static char *get_vhost(Z_OtherInformation *otherInfo)
1882 return yaz_oi_get_string_oidval(&otherInfo, VAL_PROXY, 1, 0);
1886 * Handle init request.
1887 * At the moment, we don't check the options
1888 * anywhere else in the code - we just try not to do anything that would
1889 * break a naive client. We'll toss 'em into the association block when
1890 * we need them there.
1892 static Z_APDU *process_initRequest(association *assoc, request *reqb)
1894 Z_InitRequest *req = reqb->apdu_request->u.initRequest;
1895 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
1896 Z_InitResponse *resp = apdu->u.initResponse;
1897 bend_initresult *binitres;
1900 statserv_options_block *cb = 0; /* by default no control for backend */
1902 if (control_association(assoc, get_vhost(req->otherInfo), 1))
1903 cb = statserv_getcontrol(); /* got control block for backend */
1905 if (cb && assoc->backend)
1906 (*cb->bend_close)(assoc->backend);
1908 yaz_log(log_requestdetail, "Got initRequest");
1909 if (req->implementationId)
1910 yaz_log(log_requestdetail, "Id: %s",
1911 req->implementationId);
1912 if (req->implementationName)
1913 yaz_log(log_requestdetail, "Name: %s",
1914 req->implementationName);
1915 if (req->implementationVersion)
1916 yaz_log(log_requestdetail, "Version: %s",
1917 req->implementationVersion);
1919 assoc_init_reset(assoc);
1921 assoc->init->auth = req->idAuthentication;
1922 assoc->init->referenceId = req->referenceId;
1924 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
1926 Z_CharSetandLanguageNegotiation *negotiation =
1927 yaz_get_charneg_record (req->otherInfo);
1929 negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
1930 assoc->init->charneg_request = negotiation;
1936 if (req->implementationVersion)
1937 yaz_log(log_requestdetail, "Config: %s",
1940 iochan_settimeout(assoc->client_chan, cb->idle_timeout * 60);
1942 /* we have a backend control block, so call that init function */
1943 if (!(binitres = (*cb->bend_init)(assoc->init)))
1945 yaz_log(YLOG_WARN, "Bad response from backend.");
1948 assoc->backend = binitres->handle;
1952 /* no backend. return error */
1953 binitres = odr_malloc(assoc->encode, sizeof(*binitres));
1954 binitres->errstring = 0;
1955 binitres->errcode = YAZ_BIB1_PERMANENT_SYSTEM_ERROR;
1956 iochan_settimeout(assoc->client_chan, 10);
1958 if ((assoc->init->bend_sort))
1959 yaz_log (YLOG_DEBUG, "Sort handler installed");
1960 if ((assoc->init->bend_search))
1961 yaz_log (YLOG_DEBUG, "Search handler installed");
1962 if ((assoc->init->bend_present))
1963 yaz_log (YLOG_DEBUG, "Present handler installed");
1964 if ((assoc->init->bend_esrequest))
1965 yaz_log (YLOG_DEBUG, "ESRequest handler installed");
1966 if ((assoc->init->bend_delete))
1967 yaz_log (YLOG_DEBUG, "Delete handler installed");
1968 if ((assoc->init->bend_scan))
1969 yaz_log (YLOG_DEBUG, "Scan handler installed");
1970 if ((assoc->init->bend_segment))
1971 yaz_log (YLOG_DEBUG, "Segment handler installed");
1973 resp->referenceId = req->referenceId;
1975 /* let's tell the client what we can do */
1976 if (ODR_MASK_GET(req->options, Z_Options_search))
1978 ODR_MASK_SET(resp->options, Z_Options_search);
1979 strcat(options, "srch");
1981 if (ODR_MASK_GET(req->options, Z_Options_present))
1983 ODR_MASK_SET(resp->options, Z_Options_present);
1984 strcat(options, " prst");
1986 if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
1987 assoc->init->bend_delete)
1989 ODR_MASK_SET(resp->options, Z_Options_delSet);
1990 strcat(options, " del");
1992 if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
1993 assoc->init->bend_esrequest)
1995 ODR_MASK_SET(resp->options, Z_Options_extendedServices);
1996 strcat (options, " extendedServices");
1998 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
2000 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
2001 strcat(options, " namedresults");
2003 if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
2005 ODR_MASK_SET(resp->options, Z_Options_scan);
2006 strcat(options, " scan");
2008 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
2010 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
2011 strcat(options, " concurrop");
2013 if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
2015 ODR_MASK_SET(resp->options, Z_Options_sort);
2016 strcat(options, " sort");
2019 if (ODR_MASK_GET(req->options, Z_Options_negotiationModel)
2020 && assoc->init->charneg_response)
2022 Z_OtherInformation **p;
2023 Z_OtherInformationUnit *p0;
2025 yaz_oi_APDU(apdu, &p);
2027 if ((p0=yaz_oi_update(p, assoc->encode, NULL, 0, 0))) {
2028 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
2030 p0->which = Z_OtherInfo_externallyDefinedInfo;
2031 p0->information.externallyDefinedInfo =
2032 assoc->init->charneg_response;
2034 ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
2035 strcat(options, " negotiation");
2038 ODR_MASK_SET(resp->options, Z_Options_triggerResourceCtrl);
2040 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
2042 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
2043 assoc->version = 1; /* 1 & 2 are equivalent */
2045 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
2047 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
2050 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
2052 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
2056 yaz_log(log_requestdetail, "Negotiated to v%d: %s", assoc->version, options);
2057 assoc->maximumRecordSize = *req->maximumRecordSize;
2059 if (cb && assoc->maximumRecordSize > cb->maxrecordsize)
2060 assoc->maximumRecordSize = cb->maxrecordsize;
2061 assoc->preferredMessageSize = *req->preferredMessageSize;
2062 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
2063 assoc->preferredMessageSize = assoc->maximumRecordSize;
2065 resp->preferredMessageSize = &assoc->preferredMessageSize;
2066 resp->maximumRecordSize = &assoc->maximumRecordSize;
2068 resp->implementationId = odr_prepend(assoc->encode,
2069 assoc->init->implementation_id,
2070 resp->implementationId);
2072 resp->implementationName = odr_prepend(assoc->encode,
2073 assoc->init->implementation_name,
2074 odr_prepend(assoc->encode, "GFS", resp->implementationName));
2076 version = odr_strdup(assoc->encode, "$Revision: 1.75 $");
2077 if (strlen(version) > 10) /* check for unexpanded CVS strings */
2078 version[strlen(version)-2] = '\0';
2079 resp->implementationVersion = odr_prepend(assoc->encode,
2080 assoc->init->implementation_version,
2081 odr_prepend(assoc->encode, &version[11],
2082 resp->implementationVersion));
2084 if (binitres->errcode)
2086 assoc->state = ASSOC_DEAD;
2087 resp->userInformationField =
2088 init_diagnostics(assoc->encode, binitres->errcode,
2089 binitres->errstring);
2094 if (!req->idAuthentication)
2095 yaz_log(log_request, "Auth none");
2096 else if (req->idAuthentication->which == Z_IdAuthentication_open)
2098 const char *open = req->idAuthentication->u.open;
2099 const char *slash = strchr(open, '/');
2105 yaz_log(log_request, "Auth open %.*s", len, open);
2107 else if (req->idAuthentication->which == Z_IdAuthentication_idPass)
2109 const char *user = req->idAuthentication->u.idPass->userId;
2110 const char *group = req->idAuthentication->u.idPass->groupId;
2111 yaz_log(log_request, "Auth idPass %s %s",
2112 user ? user : "-", group ? group : "-");
2114 else if (req->idAuthentication->which
2115 == Z_IdAuthentication_anonymous)
2117 yaz_log(log_request, "Auth anonymous");
2121 yaz_log(log_request, "Auth other");
2126 WRBUF wr = wrbuf_alloc();
2127 wrbuf_printf(wr, "Init ");
2128 if (binitres->errcode)
2129 wrbuf_printf(wr, "ERROR %d", binitres->errcode);
2131 wrbuf_printf(wr, "OK -");
2132 wrbuf_printf(wr, " ID:%s Name:%s Version:%s",
2133 (req->implementationId ? req->implementationId :"-"),
2134 (req->implementationName ?
2135 req->implementationName : "-"),
2136 (req->implementationVersion ?
2137 req->implementationVersion : "-")
2139 yaz_log(log_request, "%s", wrbuf_buf(wr));
2146 * Set the specified `errcode' and `errstring' into a UserInfo-1
2147 * external to be returned to the client in accordance with Z35.90
2148 * Implementor Agreement 5 (Returning diagnostics in an InitResponse):
2149 * http://lcweb.loc.gov/z3950/agency/agree/initdiag.html
2151 static Z_External *init_diagnostics(ODR odr, int error, const char *addinfo)
2153 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2154 addinfo ? " -- " : "", addinfo ? addinfo : "");
2155 return zget_init_diagnostics(odr, error, addinfo);
2159 * nonsurrogate diagnostic record.
2161 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
2163 Z_Records *rec = (Z_Records *) odr_malloc (assoc->encode, sizeof(*rec));
2165 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2166 addinfo ? " -- " : "", addinfo ? addinfo : "");
2168 rec->which = Z_Records_NSD;
2169 rec->u.nonSurrogateDiagnostic = zget_DefaultDiagFormat(assoc->encode,
2175 * surrogate diagnostic.
2177 static Z_NamePlusRecord *surrogatediagrec(association *assoc,
2179 int error, const char *addinfo)
2181 yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2182 addinfo ? " -- " : "", addinfo ? addinfo : "");
2183 return zget_surrogateDiagRec(assoc->encode, dbname, error, addinfo);
2186 static Z_Records *pack_records(association *a, char *setname, int start,
2187 int *num, Z_RecordComposition *comp,
2188 int *next, int *pres, oid_value format,
2189 Z_ReferenceId *referenceId,
2190 int *oid, int *errcode)
2192 int recno, total_length = 0, toget = *num, dumped_records = 0;
2193 Z_Records *records =
2194 (Z_Records *) odr_malloc (a->encode, sizeof(*records));
2195 Z_NamePlusRecordList *reclist =
2196 (Z_NamePlusRecordList *) odr_malloc (a->encode, sizeof(*reclist));
2197 Z_NamePlusRecord **list =
2198 (Z_NamePlusRecord **) odr_malloc (a->encode, sizeof(*list) * toget);
2200 records->which = Z_Records_DBOSD;
2201 records->u.databaseOrSurDiagnostics = reclist;
2202 reclist->num_records = 0;
2203 reclist->records = list;
2204 *pres = Z_PresentStatus_success;
2208 yaz_log(log_requestdetail, "Request to pack %d+%d %s", start, toget, setname);
2209 yaz_log(log_requestdetail, "pms=%d, mrs=%d", a->preferredMessageSize,
2210 a->maximumRecordSize);
2211 for (recno = start; reclist->num_records < toget; recno++)
2214 Z_NamePlusRecord *thisrec;
2215 int this_length = 0;
2217 * we get the number of bytes allocated on the stream before any
2218 * allocation done by the backend - this should give us a reasonable
2219 * idea of the total size of the data so far.
2221 total_length = odr_total(a->encode) - dumped_records;
2227 freq.last_in_set = 0;
2228 freq.setname = setname;
2229 freq.surrogate_flag = 0;
2230 freq.number = recno;
2232 freq.request_format = format;
2233 freq.request_format_raw = oid;
2234 freq.output_format = format;
2235 freq.output_format_raw = 0;
2236 freq.stream = a->encode;
2237 freq.print = a->print;
2238 freq.referenceId = referenceId;
2240 (*a->init->bend_fetch)(a->backend, &freq);
2242 *next = freq.last_in_set ? 0 : recno + 1;
2244 /* backend should be able to signal whether error is system-wide
2245 or only pertaining to current record */
2248 if (!freq.surrogate_flag)
2251 *pres = Z_PresentStatus_failure;
2252 /* for 'present request out of range',
2253 set addinfo to record position if not set */
2254 if (freq.errcode == YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE &&
2255 freq.errstring == 0)
2257 sprintf (s, "%d", recno);
2261 *errcode = freq.errcode;
2262 return diagrec(a, freq.errcode, freq.errstring);
2264 reclist->records[reclist->num_records] =
2265 surrogatediagrec(a, freq.basename, freq.errcode,
2267 reclist->num_records++;
2270 if (freq.record == 0) /* no error and no record ? */
2272 *next = 0; /* signal end-of-set and stop */
2276 this_length = freq.len;
2278 this_length = odr_total(a->encode) - total_length - dumped_records;
2279 yaz_log(YLOG_DEBUG, " fetched record, len=%d, total=%d dumped=%d",
2280 this_length, total_length, dumped_records);
2281 if (a->preferredMessageSize > 0 &&
2282 this_length + total_length > a->preferredMessageSize)
2284 /* record is small enough, really */
2285 if (this_length <= a->preferredMessageSize && recno > start)
2287 yaz_log(log_requestdetail, " Dropped last normal-sized record");
2288 *pres = Z_PresentStatus_partial_2;
2291 /* record can only be fetched by itself */
2292 if (this_length < a->maximumRecordSize)
2294 yaz_log(log_requestdetail, " Record > prefmsgsz");
2297 yaz_log(YLOG_DEBUG, " Dropped it");
2298 reclist->records[reclist->num_records] =
2299 surrogatediagrec(a, freq.basename, 16, 0);
2300 reclist->num_records++;
2301 dumped_records += this_length;
2305 else /* too big entirely */
2307 yaz_log(log_requestdetail, "Record > maxrcdsz this=%d max=%d",
2308 this_length, a->maximumRecordSize);
2309 reclist->records[reclist->num_records] =
2310 surrogatediagrec(a, freq.basename, 17, 0);
2311 reclist->num_records++;
2312 dumped_records += this_length;
2317 if (!(thisrec = (Z_NamePlusRecord *)
2318 odr_malloc(a->encode, sizeof(*thisrec))))
2321 thisrec->databaseName = odr_strdup(a->encode, freq.basename);
2323 thisrec->databaseName = 0;
2324 thisrec->which = Z_NamePlusRecord_databaseRecord;
2326 if (freq.output_format_raw)
2328 struct oident *ident = oid_getentbyoid(freq.output_format_raw);
2329 freq.output_format = ident->value;
2331 thisrec->u.databaseRecord = z_ext_record(a->encode, freq.output_format,
2332 freq.record, freq.len);
2333 if (!thisrec->u.databaseRecord)
2335 reclist->records[reclist->num_records] = thisrec;
2336 reclist->num_records++;
2338 *num = reclist->num_records;
2342 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
2345 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2346 bend_search_rr *bsrr =
2347 (bend_search_rr *)nmem_malloc (reqb->request_mem, sizeof(*bsrr));
2349 yaz_log(log_requestdetail, "Got SearchRequest.");
2351 bsrr->request = reqb;
2352 bsrr->association = assoc;
2353 bsrr->referenceId = req->referenceId;
2354 save_referenceId (reqb, bsrr->referenceId);
2355 bsrr->srw_sortKeys = 0;
2356 bsrr->srw_setname = 0;
2357 bsrr->srw_setnameIdleTime = 0;
2359 yaz_log (log_requestdetail, "ResultSet '%s'", req->resultSetName);
2360 if (req->databaseNames)
2363 for (i = 0; i < req->num_databaseNames; i++)
2364 yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
2367 yaz_log_zquery_level(log_requestdetail,req->query);
2369 if (assoc->init->bend_search)
2371 bsrr->setname = req->resultSetName;
2372 bsrr->replace_set = *req->replaceIndicator;
2373 bsrr->num_bases = req->num_databaseNames;
2374 bsrr->basenames = req->databaseNames;
2375 bsrr->query = req->query;
2376 bsrr->stream = assoc->encode;
2377 nmem_transfer(bsrr->stream->mem, reqb->request_mem);
2378 bsrr->decode = assoc->decode;
2379 bsrr->print = assoc->print;
2382 bsrr->errstring = NULL;
2383 bsrr->search_info = NULL;
2385 if (assoc->cql_transform &&
2386 req->query->which == Z_Query_type_104 &&
2387 req->query->u.type_104->which == Z_External_CQL)
2389 /* have a CQL query and a CQL to PQF transform .. */
2391 cql2pqf(bsrr->stream, req->query->u.type_104->u.cql,
2392 assoc->cql_transform, bsrr->query);
2394 bsrr->errcode = yaz_diag_srw_to_bib1(srw_errcode);
2397 (assoc->init->bend_search)(assoc->backend, bsrr);
2398 if (!bsrr->request) /* backend not ready with the search response */
2399 return 0; /* should not be used any more */
2403 /* FIXME - make a diagnostic for it */
2404 yaz_log(YLOG_WARN,"Search not supported ?!?!");
2406 return response_searchRequest(assoc, reqb, bsrr, fd);
2409 int bend_searchresponse(void *handle, bend_search_rr *bsrr) {return 0;}
2412 * Prepare a searchresponse based on the backend results. We probably want
2413 * to look at making the fetching of records nonblocking as well, but
2414 * so far, we'll keep things simple.
2415 * If bsrt is null, that means we're called in response to a communications
2416 * event, and we'll have to get the response for ourselves.
2418 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
2419 bend_search_rr *bsrt, int *fd)
2421 Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2422 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2423 Z_SearchResponse *resp = (Z_SearchResponse *)
2424 odr_malloc (assoc->encode, sizeof(*resp));
2425 int *nulint = odr_intdup (assoc->encode, 0);
2426 bool_t *sr = odr_intdup(assoc->encode, 1);
2427 int *next = odr_intdup(assoc->encode, 0);
2428 int *none = odr_intdup(assoc->encode, Z_SearchResponse_none);
2431 apdu->which = Z_APDU_searchResponse;
2432 apdu->u.searchResponse = resp;
2433 resp->referenceId = req->referenceId;
2434 resp->additionalSearchInfo = 0;
2435 resp->otherInfo = 0;
2437 if (!bsrt && !bend_searchresponse(assoc->backend, bsrt))
2439 yaz_log(YLOG_FATAL, "Bad result from backend");
2442 else if (bsrt->errcode)
2444 resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
2445 resp->resultCount = nulint;
2446 resp->numberOfRecordsReturned = nulint;
2447 resp->nextResultSetPosition = nulint;
2448 resp->searchStatus = nulint;
2449 resp->resultSetStatus = none;
2450 resp->presentStatus = 0;
2454 int *toget = odr_intdup(assoc->encode, 0);
2455 int *presst = odr_intdup(assoc->encode, 0);
2456 Z_RecordComposition comp, *compp = 0;
2458 yaz_log (log_requestdetail, "resultCount: %d", bsrt->hits);
2461 resp->resultCount = &bsrt->hits;
2463 comp.which = Z_RecordComp_simple;
2464 /* how many records does the user agent want, then? */
2465 if (bsrt->hits <= *req->smallSetUpperBound)
2467 *toget = bsrt->hits;
2468 if ((comp.u.simple = req->smallSetElementSetNames))
2471 else if (bsrt->hits < *req->largeSetLowerBound)
2473 *toget = *req->mediumSetPresentNumber;
2474 if (*toget > bsrt->hits)
2475 *toget = bsrt->hits;
2476 if ((comp.u.simple = req->mediumSetElementSetNames))
2482 if (*toget && !resp->records)
2487 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
2490 form = prefformat->value;
2491 resp->records = pack_records(assoc, req->resultSetName, 1,
2492 toget, compp, next, presst, form, req->referenceId,
2493 req->preferredRecordSyntax, NULL);
2496 resp->numberOfRecordsReturned = toget;
2497 returnedrecs = *toget;
2498 resp->nextResultSetPosition = next;
2499 resp->searchStatus = sr;
2500 resp->resultSetStatus = 0;
2501 resp->presentStatus = presst;
2505 if (*resp->resultCount)
2507 resp->numberOfRecordsReturned = nulint;
2508 resp->nextResultSetPosition = next;
2509 resp->searchStatus = sr;
2510 resp->resultSetStatus = 0;
2511 resp->presentStatus = 0;
2514 resp->additionalSearchInfo = bsrt->search_info;
2518 WRBUF wr = wrbuf_alloc();
2520 wrbuf_printf(wr, "ERROR %d", bsrt->errcode);
2522 wrbuf_printf(wr, "OK %d", bsrt->hits);
2523 wrbuf_printf(wr, " %s 1+%d ",
2524 req->resultSetName, returnedrecs);
2525 yaz_query_to_wrbuf(wr, req->query);
2527 yaz_log(log_request, "Search %s", wrbuf_buf(wr));
2534 * Maybe we got a little over-friendly when we designed bend_fetch to
2535 * get only one record at a time. Some backends can optimise multiple-record
2536 * fetches, and at any rate, there is some overhead involved in
2537 * all that selecting and hopping around. Problem is, of course, that the
2538 * frontend can't know ahead of time how many records it'll need to
2539 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
2540 * is downright lousy as a bulk data transfer protocol.
2542 * To start with, we'll do the fetching of records from the backend
2543 * in one operation: To save some trips in and out of the event-handler,
2544 * and to simplify the interface to pack_records. At any rate, asynch
2545 * operation is more fun in operations that have an unpredictable execution
2546 * speed - which is normally more true for search than for present.
2548 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
2551 Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
2555 Z_PresentResponse *resp;
2559 const char *errstring = 0;
2561 yaz_log(log_requestdetail, "Got PresentRequest.");
2563 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
2566 form = prefformat->value;
2567 resp = (Z_PresentResponse *)odr_malloc (assoc->encode, sizeof(*resp));
2569 resp->presentStatus = odr_intdup(assoc->encode, 0);
2570 if (assoc->init->bend_present)
2572 bend_present_rr *bprr = (bend_present_rr *)
2573 nmem_malloc (reqb->request_mem, sizeof(*bprr));
2574 bprr->setname = req->resultSetId;
2575 bprr->start = *req->resultSetStartPoint;
2576 bprr->number = *req->numberOfRecordsRequested;
2577 bprr->format = form;
2578 bprr->comp = req->recordComposition;
2579 bprr->referenceId = req->referenceId;
2580 bprr->stream = assoc->encode;
2581 bprr->print = assoc->print;
2582 bprr->request = reqb;
2583 bprr->association = assoc;
2585 bprr->errstring = NULL;
2586 (*assoc->init->bend_present)(assoc->backend, bprr);
2589 return 0; /* should not happen */
2592 resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2593 *resp->presentStatus = Z_PresentStatus_failure;
2594 errcode = bprr->errcode;
2595 errstring = bprr->errstring;
2598 apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2599 next = odr_intdup(assoc->encode, 0);
2600 num = odr_intdup(assoc->encode, 0);
2602 apdu->which = Z_APDU_presentResponse;
2603 apdu->u.presentResponse = resp;
2604 resp->referenceId = req->referenceId;
2605 resp->otherInfo = 0;
2609 *num = *req->numberOfRecordsRequested;
2611 pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
2612 num, req->recordComposition, next,
2613 resp->presentStatus,
2614 form, req->referenceId, req->preferredRecordSyntax,
2619 WRBUF wr = wrbuf_alloc();
2620 wrbuf_printf(wr, "Present ");
2622 if (*resp->presentStatus == Z_PresentStatus_failure)
2623 wrbuf_printf(wr, "ERROR %d", errcode);
2624 else if (*resp->presentStatus == Z_PresentStatus_success)
2625 wrbuf_printf(wr, "OK -");
2627 wrbuf_printf(wr, "Partial %d", *resp->presentStatus);
2629 wrbuf_printf(wr, " %s %d+%d ",
2630 req->resultSetId, *req->resultSetStartPoint,
2631 *req->numberOfRecordsRequested);
2632 yaz_log(log_request, "%s", wrbuf_buf(wr) );
2637 resp->numberOfRecordsReturned = num;
2638 resp->nextResultSetPosition = next;
2644 * Scan was implemented rather in a hurry, and with support for only the basic
2645 * elements of the service in the backend API. Suggestions are welcome.
2647 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
2649 Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
2650 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2651 Z_ScanResponse *res = (Z_ScanResponse *)
2652 odr_malloc (assoc->encode, sizeof(*res));
2653 int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
2654 int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
2655 Z_ListEntries *ents = (Z_ListEntries *)
2656 odr_malloc (assoc->encode, sizeof(*ents));
2657 Z_DiagRecs *diagrecs_p = NULL;
2659 bend_scan_rr *bsrr = (bend_scan_rr *)
2660 odr_malloc (assoc->encode, sizeof(*bsrr));
2661 struct scan_entry *save_entries;
2663 yaz_log(log_requestdetail, "Got ScanRequest");
2665 apdu->which = Z_APDU_scanResponse;
2666 apdu->u.scanResponse = res;
2667 res->referenceId = req->referenceId;
2669 /* if step is absent, set it to 0 */
2670 res->stepSize = odr_intdup(assoc->encode, 0);
2672 *res->stepSize = *req->stepSize;
2674 res->scanStatus = scanStatus;
2675 res->numberOfEntriesReturned = numberOfEntriesReturned;
2676 res->positionOfTerm = 0;
2677 res->entries = ents;
2678 ents->num_entries = 0;
2679 ents->entries = NULL;
2680 ents->num_nonsurrogateDiagnostics = 0;
2681 ents->nonsurrogateDiagnostics = NULL;
2682 res->attributeSet = 0;
2685 if (req->databaseNames)
2688 for (i = 0; i < req->num_databaseNames; i++)
2689 yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
2691 bsrr->scanClause = 0;
2693 bsrr->errstring = 0;
2694 bsrr->num_bases = req->num_databaseNames;
2695 bsrr->basenames = req->databaseNames;
2696 bsrr->num_entries = *req->numberOfTermsRequested;
2697 bsrr->term = req->termListAndStartPoint;
2698 bsrr->referenceId = req->referenceId;
2699 bsrr->stream = assoc->encode;
2700 bsrr->print = assoc->print;
2701 bsrr->step_size = res->stepSize;
2703 /* For YAZ 2.0 and earlier it was the backend handler that
2704 initialized entries (member display_term did not exist)
2705 YAZ 2.0 and later sets 'entries' and initialize all members
2706 including 'display_term'. If YAZ 2.0 or later sees that
2707 entries was modified - we assume that it is an old handler and
2708 that 'display_term' is _not_ set.
2710 if (bsrr->num_entries > 0)
2713 bsrr->entries = odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
2715 for (i = 0; i<bsrr->num_entries; i++)
2717 bsrr->entries[i].term = 0;
2718 bsrr->entries[i].occurrences = 0;
2719 bsrr->entries[i].errcode = 0;
2720 bsrr->entries[i].errstring = 0;
2721 bsrr->entries[i].display_term = 0;
2724 save_entries = bsrr->entries; /* save it so we can compare later */
2726 if (req->attributeSet &&
2727 (attset = oid_getentbyoid(req->attributeSet)) &&
2728 (attset->oclass == CLASS_ATTSET || attset->oclass == CLASS_GENERAL))
2729 bsrr->attributeset = attset->value;
2731 bsrr->attributeset = VAL_NONE;
2732 log_scan_term_level (log_requestdetail, req->termListAndStartPoint,
2733 bsrr->attributeset);
2734 bsrr->term_position = req->preferredPositionInResponse ?
2735 *req->preferredPositionInResponse : 1;
2737 ((int (*)(void *, bend_scan_rr *))
2738 (*assoc->init->bend_scan))(assoc->backend, bsrr);
2741 diagrecs_p = zget_DiagRecs(assoc->encode,
2742 bsrr->errcode, bsrr->errstring);
2746 Z_Entry **tab = (Z_Entry **)
2747 odr_malloc (assoc->encode, sizeof(*tab) * bsrr->num_entries);
2749 if (bsrr->status == BEND_SCAN_PARTIAL)
2750 *scanStatus = Z_Scan_partial_5;
2752 *scanStatus = Z_Scan_success;
2753 ents->entries = tab;
2754 ents->num_entries = bsrr->num_entries;
2755 res->numberOfEntriesReturned = &ents->num_entries;
2756 res->positionOfTerm = &bsrr->term_position;
2757 for (i = 0; i < bsrr->num_entries; i++)
2763 tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
2764 if (bsrr->entries[i].occurrences >= 0)
2766 e->which = Z_Entry_termInfo;
2767 e->u.termInfo = t = (Z_TermInfo *)
2768 odr_malloc(assoc->encode, sizeof(*t));
2769 t->suggestedAttributes = 0;
2771 if (save_entries == bsrr->entries &&
2772 bsrr->entries[i].display_term)
2774 /* the entries was _not_ set by the handler. So it's
2775 safe to test for new member display_term. It is
2778 t->displayTerm = odr_strdup(assoc->encode,
2779 bsrr->entries[i].display_term);
2781 t->alternativeTerm = 0;
2782 t->byAttributes = 0;
2783 t->otherTermInfo = 0;
2784 t->globalOccurrences = &bsrr->entries[i].occurrences;
2785 t->term = (Z_Term *)
2786 odr_malloc(assoc->encode, sizeof(*t->term));
2787 t->term->which = Z_Term_general;
2788 t->term->u.general = o =
2789 (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
2790 o->buf = (unsigned char *)
2791 odr_malloc(assoc->encode, o->len = o->size =
2792 strlen(bsrr->entries[i].term));
2793 memcpy(o->buf, bsrr->entries[i].term, o->len);
2794 yaz_log(YLOG_DEBUG, " term #%d: '%s' (%d)", i,
2795 bsrr->entries[i].term, bsrr->entries[i].occurrences);
2799 Z_DiagRecs *drecs = zget_DiagRecs(assoc->encode,
2800 bsrr->entries[i].errcode,
2801 bsrr->entries[i].errstring);
2802 assert (drecs->num_diagRecs == 1);
2803 e->which = Z_Entry_surrogateDiagnostic;
2804 assert (drecs->diagRecs[0]);
2805 e->u.surrogateDiagnostic = drecs->diagRecs[0];
2811 ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
2812 ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
2816 WRBUF wr = wrbuf_alloc();
2818 wr_diag(wr, bsrr->errcode, bsrr->errstring);
2819 else if (*res->scanStatus == Z_Scan_success)
2820 wrbuf_printf(wr, "OK");
2822 wrbuf_printf(wr, "Partial");
2824 wrbuf_printf(wr, " %d+%d %d ",
2825 (req->preferredPositionInResponse ?
2826 *req->preferredPositionInResponse : 1),
2827 *req->numberOfTermsRequested,
2828 (res->stepSize ? *res->stepSize : 0));
2829 yaz_scan_to_wrbuf(wr, req->termListAndStartPoint,
2830 bsrr->attributeset);
2831 yaz_log(log_request, "Scan %s", wrbuf_buf(wr) );
2837 static Z_APDU *process_sortRequest(association *assoc, request *reqb,
2841 Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
2842 Z_SortResponse *res = (Z_SortResponse *)
2843 odr_malloc (assoc->encode, sizeof(*res));
2844 bend_sort_rr *bsrr = (bend_sort_rr *)
2845 odr_malloc (assoc->encode, sizeof(*bsrr));
2847 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2849 yaz_log(log_requestdetail, "Got SortRequest.");
2851 bsrr->num_input_setnames = req->num_inputResultSetNames;
2852 for (i=0;i<req->num_inputResultSetNames;i++)
2853 yaz_log(log_requestdetail, "Input resultset: '%s'",
2854 req->inputResultSetNames[i]);
2855 bsrr->input_setnames = req->inputResultSetNames;
2856 bsrr->referenceId = req->referenceId;
2857 bsrr->output_setname = req->sortedResultSetName;
2858 yaz_log(log_requestdetail, "Output resultset: '%s'",
2859 req->sortedResultSetName);
2860 bsrr->sort_sequence = req->sortSequence;
2861 /*FIXME - dump those sequences too */
2862 bsrr->stream = assoc->encode;
2863 bsrr->print = assoc->print;
2865 bsrr->sort_status = Z_SortResponse_failure;
2867 bsrr->errstring = 0;
2869 (*assoc->init->bend_sort)(assoc->backend, bsrr);
2871 res->referenceId = bsrr->referenceId;
2872 res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
2873 res->resultSetStatus = 0;
2876 Z_DiagRecs *dr = zget_DiagRecs(assoc->encode,
2877 bsrr->errcode, bsrr->errstring);
2878 res->diagnostics = dr->diagRecs;
2879 res->num_diagnostics = dr->num_diagRecs;
2883 res->num_diagnostics = 0;
2884 res->diagnostics = 0;
2886 res->resultCount = 0;
2889 apdu->which = Z_APDU_sortResponse;
2890 apdu->u.sortResponse = res;
2893 WRBUF wr = wrbuf_alloc();
2894 wrbuf_printf(wr, "Sort ");
2896 wrbuf_printf(wr, " ERROR %d", bsrr->errcode);
2898 wrbuf_printf(wr, "OK -");
2899 wrbuf_printf(wr, " (");
2900 for (i = 0; i<req->num_inputResultSetNames; i++)
2903 wrbuf_printf(wr, ",");
2904 wrbuf_printf(wr, req->inputResultSetNames[i]);
2906 wrbuf_printf(wr, ")->%s ",req->sortedResultSetName);
2908 yaz_log(log_request, "%s", wrbuf_buf(wr) );
2914 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
2918 Z_DeleteResultSetRequest *req =
2919 reqb->apdu_request->u.deleteResultSetRequest;
2920 Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
2921 odr_malloc (assoc->encode, sizeof(*res));
2922 bend_delete_rr *bdrr = (bend_delete_rr *)
2923 odr_malloc (assoc->encode, sizeof(*bdrr));
2924 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2926 yaz_log(log_requestdetail, "Got DeleteRequest.");
2928 bdrr->num_setnames = req->num_resultSetList;
2929 bdrr->setnames = req->resultSetList;
2930 for (i = 0; i<req->num_resultSetList; i++)
2931 yaz_log(log_requestdetail, "resultset: '%s'",
2932 req->resultSetList[i]);
2933 bdrr->stream = assoc->encode;
2934 bdrr->print = assoc->print;
2935 bdrr->function = *req->deleteFunction;
2936 bdrr->referenceId = req->referenceId;
2938 if (bdrr->num_setnames > 0)
2940 bdrr->statuses = (int*)
2941 odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
2942 bdrr->num_setnames);
2943 for (i = 0; i < bdrr->num_setnames; i++)
2944 bdrr->statuses[i] = 0;
2946 (*assoc->init->bend_delete)(assoc->backend, bdrr);
2948 res->referenceId = req->referenceId;
2950 res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
2952 res->deleteListStatuses = 0;
2953 if (bdrr->num_setnames > 0)
2956 res->deleteListStatuses = (Z_ListStatuses *)
2957 odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
2958 res->deleteListStatuses->num = bdrr->num_setnames;
2959 res->deleteListStatuses->elements =
2961 odr_malloc (assoc->encode,
2962 sizeof(*res->deleteListStatuses->elements) *
2963 bdrr->num_setnames);
2964 for (i = 0; i<bdrr->num_setnames; i++)
2966 res->deleteListStatuses->elements[i] =
2968 odr_malloc (assoc->encode,
2969 sizeof(**res->deleteListStatuses->elements));
2970 res->deleteListStatuses->elements[i]->status = bdrr->statuses+i;
2971 res->deleteListStatuses->elements[i]->id =
2972 odr_strdup (assoc->encode, bdrr->setnames[i]);
2975 res->numberNotDeleted = 0;
2976 res->bulkStatuses = 0;
2977 res->deleteMessage = 0;
2980 apdu->which = Z_APDU_deleteResultSetResponse;
2981 apdu->u.deleteResultSetResponse = res;
2984 WRBUF wr = wrbuf_alloc();
2985 wrbuf_printf(wr, "Delete ");
2986 if (bdrr->delete_status)
2987 wrbuf_printf(wr, "ERROR %d", bdrr->delete_status);
2989 wrbuf_printf(wr, "OK -");
2990 for (i = 0; i<req->num_resultSetList; i++)
2991 wrbuf_printf(wr, " %s ", req->resultSetList[i]);
2992 yaz_log(log_request, "%s", wrbuf_buf(wr) );
2998 static void process_close(association *assoc, request *reqb)
3000 Z_Close *req = reqb->apdu_request->u.close;
3001 static char *reasons[] =
3008 "securityViolation",
3015 yaz_log(log_requestdetail, "Got Close, reason %s, message %s",
3016 reasons[*req->closeReason], req->diagnosticInformation ?
3017 req->diagnosticInformation : "NULL");
3018 if (assoc->version < 3) /* to make do_force respond with close */
3020 do_close_req(assoc, Z_Close_finished,
3021 "Association terminated by client", reqb);
3022 yaz_log(log_request,"Close OK");
3025 void save_referenceId (request *reqb, Z_ReferenceId *refid)
3029 reqb->len_refid = refid->len;
3030 reqb->refid = (char *)nmem_malloc (reqb->request_mem, refid->len);
3031 memcpy (reqb->refid, refid->buf, refid->len);
3035 reqb->len_refid = 0;
3040 void bend_request_send (bend_association a, bend_request req, Z_APDU *res)
3042 process_z_response (a, req, res);
3045 bend_request bend_request_mk (bend_association a)
3047 request *nreq = request_get (&a->outgoing);
3048 nreq->request_mem = nmem_create ();
3052 Z_ReferenceId *bend_request_getid (ODR odr, bend_request req)
3057 id = (Odr_oct *)odr_malloc (odr, sizeof(*odr));
3058 id->buf = (unsigned char *)odr_malloc (odr, req->len_refid);
3059 id->len = id->size = req->len_refid;
3060 memcpy (id->buf, req->refid, req->len_refid);
3064 void bend_request_destroy (bend_request *req)
3066 nmem_destroy((*req)->request_mem);
3067 request_release(*req);
3071 int bend_backend_respond (bend_association a, bend_request req)
3075 r = process_z_request (a, req, &msg);
3077 yaz_log (YLOG_WARN, "%s", msg);
3081 void bend_request_setdata(bend_request r, void *p)
3086 void *bend_request_getdata(bend_request r)
3088 return r->clientData;
3091 static Z_APDU *process_segmentRequest (association *assoc, request *reqb)
3093 bend_segment_rr req;
3095 req.segment = reqb->apdu_request->u.segmentRequest;
3096 req.stream = assoc->encode;
3097 req.decode = assoc->decode;
3098 req.print = assoc->print;
3099 req.association = assoc;
3101 (*assoc->init->bend_segment)(assoc->backend, &req);
3106 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd)
3108 bend_esrequest_rr esrequest;
3109 const char *ext_name = "unknown";
3111 Z_ExtendedServicesRequest *req =
3112 reqb->apdu_request->u.extendedServicesRequest;
3113 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
3115 Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
3117 esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
3118 esrequest.stream = assoc->encode;
3119 esrequest.decode = assoc->decode;
3120 esrequest.print = assoc->print;
3121 esrequest.errcode = 0;
3122 esrequest.errstring = NULL;
3123 esrequest.request = reqb;
3124 esrequest.association = assoc;
3125 esrequest.taskPackage = 0;
3126 esrequest.referenceId = req->referenceId;
3129 if (esrequest.esr && esrequest.esr->taskSpecificParameters)
3131 switch(esrequest.esr->taskSpecificParameters->which)
3133 case Z_External_itemOrder:
3134 ext_name = "ItemOrder"; break;
3135 case Z_External_update:
3136 ext_name = "Update"; break;
3137 case Z_External_update0:
3138 ext_name = "Update0"; break;
3139 case Z_External_ESAdmin:
3140 ext_name = "Admin"; break;
3145 (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
3147 /* If the response is being delayed, return NULL */
3148 if (esrequest.request == NULL)
3151 resp->referenceId = req->referenceId;
3153 if (esrequest.errcode == -1)
3155 /* Backend service indicates request will be processed */
3156 yaz_log(log_request, "Extended Service: %s (accepted)", ext_name);
3157 *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
3159 else if (esrequest.errcode == 0)
3161 /* Backend service indicates request will be processed */
3162 yaz_log(log_request, "Extended Service: %s (done)", ext_name);
3163 *resp->operationStatus = Z_ExtendedServicesResponse_done;
3167 Z_DiagRecs *diagRecs =
3168 zget_DiagRecs(assoc->encode, esrequest.errcode,
3169 esrequest.errstring);
3170 /* Backend indicates error, request will not be processed */
3171 yaz_log(log_request, "Extended Service: %s (failed)", ext_name);
3172 *resp->operationStatus = Z_ExtendedServicesResponse_failure;
3173 resp->num_diagnostics = diagRecs->num_diagRecs;
3174 resp->diagnostics = diagRecs->diagRecs;
3177 WRBUF wr = wrbuf_alloc();
3178 wrbuf_diags(wr, resp->num_diagnostics, resp->diagnostics);
3179 yaz_log(log_request, "EsRequest %s", wrbuf_buf(wr) );
3184 /* Do something with the members of bend_extendedservice */
3185 if (esrequest.taskPackage)
3186 resp->taskPackage = z_ext_record (assoc->encode, VAL_EXTENDED,
3187 (const char *) esrequest.taskPackage,
3189 yaz_log(YLOG_DEBUG,"Send the result apdu");
3196 * indent-tabs-mode: nil
3198 * vim: shiftwidth=4 tabstop=8 expandtab