2 * Copyright (c) 1995-2001, Index Data
3 * See the file LICENSE for details.
6 * Revision 1.114 2001-02-21 13:46:53 adam
9 * Revision 1.113 2001/01/30 21:34:17 adam
10 * Added step-size for Scan backend interface.
12 * Revision 1.112 2001/01/29 09:38:22 adam
13 * Fixed bug that made the frontend server crash when no attribute set
14 * was specified for scan.
16 * Revision 1.111 2000/11/23 10:58:32 adam
17 * SSL comstack support. Separate POSIX thread support library.
19 * Revision 1.110 2000/10/02 13:05:32 adam
20 * Fixed bug introduced by previous commit.
22 * Revision 1.109 2000/10/02 11:07:44 adam
23 * Added peer_name member for bend_init handler. Changed the YAZ
24 * client so that tcp: can be avoided in target spec.
26 * Revision 1.108 2000/09/04 08:58:15 adam
27 * Added prefix yaz_ for most logging utility functions.
29 * Revision 1.107 2000/08/31 10:20:12 adam
30 * Added member request_format and output_format for backend fetch method.
32 * Revision 1.106 2000/08/31 09:51:25 adam
33 * Added record_syntax member for fetch method (raw OID).
35 * Revision 1.105 2000/07/06 10:38:47 adam
36 * Enhanced option --enable-tcpd.
38 * Revision 1.104 2000/04/05 07:39:55 adam
39 * Added shared library support (libtool).
41 * Revision 1.103 2000/03/20 19:06:25 adam
42 * Added Segment request for fronend server. Work on admin for client.
44 * Revision 1.102 2000/03/15 12:59:49 adam
45 * Added handle member to statserv_control.
47 * Revision 1.101 2000/01/12 14:36:07 adam
48 * Added printing stream (ODR) for backend functions.
50 * Revision 1.100 1999/12/16 23:36:19 adam
51 * Implemented ILL protocol. Minor updates ASN.1 compiler.
53 * Revision 1.99 1999/11/30 13:47:12 adam
54 * Improved installation. Moved header files to include/yaz.
56 * Revision 1.98 1999/11/29 15:12:27 adam
57 * Changed the way implementationName - and version is set.
59 * Revision 1.96 1999/11/04 14:58:44 adam
60 * Added status elements for backend delete result set handler.
61 * Updated delete result result set command for client.
63 * Revision 1.95 1999/10/11 10:01:24 adam
64 * Implemented bend_sort_rr handler for frontend server.
66 * Revision 1.94 1999/08/27 09:40:32 adam
67 * Renamed logf function to yaz_log. Removed VC++ project files.
69 * Revision 1.93 1999/07/06 12:17:15 adam
70 * Added option -1 that runs server once (for profiling purposes).
72 * Revision 1.92 1999/06/17 10:54:45 adam
73 * Added facility to specify implementation version - and name
76 * Revision 1.91 1999/06/01 14:29:12 adam
77 * Work on Extended Services.
79 * Revision 1.90 1999/05/27 13:02:20 adam
80 * Assigned OID for old DB Update (VAL_DBUPDATE0).
82 * Revision 1.89 1999/05/26 15:24:26 adam
83 * Fixed minor bugs regarding DB Update (introduced by previous commit).
85 * Revision 1.88 1999/04/20 09:56:48 adam
86 * Added 'name' paramter to encoder/decoder routines (typedef Odr_fun).
87 * Modified all encoders/decoders to reflect this change.
89 * Revision 1.87 1999/03/31 11:18:25 adam
90 * Implemented odr_strdup. Added Reference ID to backend server API.
92 * Revision 1.86 1999/02/02 13:57:38 adam
93 * Uses preprocessor define WIN32 instead of WINDOWS to build code
94 * for Microsoft WIN32.
96 * Revision 1.85 1998/11/17 09:52:59 adam
97 * Fixed minor bug (introduced by previous commit).
99 * Revision 1.84 1998/11/16 16:02:32 adam
100 * Added loggin utilies, log_rpn_query and log_scan_term. These used
101 * to be part of Zebra.
103 * Revision 1.83 1998/11/03 10:09:36 adam
104 * Fixed bug regarding YC.
106 * Revision 1.82 1998/10/20 14:00:30 quinn
109 * Revision 1.81 1998/10/13 16:12:24 adam
110 * Added support for Surrogate Diagnostics for Scan Term entries.
112 * Revision 1.80 1998/09/02 12:41:53 adam
113 * Added decode stream in bend search structures.
115 * Revision 1.79 1998/08/19 16:10:08 adam
116 * Changed som member names of DeleteResultSetRequest/Response.
118 * Revision 1.78 1998/08/03 10:23:55 adam
119 * Fixed bug regarding Options for Sort.
121 * Revision 1.77 1998/07/20 12:38:42 adam
122 * Implemented delete result set service to server API.
124 * Revision 1.76 1998/05/27 16:57:07 adam
125 * Support for surrogate diagnostic records added for bend_fetch.
127 * Revision 1.75 1998/05/18 10:13:07 adam
128 * Fixed call to es_request handler - extra argument was passed.
130 * Revision 1.74 1998/03/31 15:13:20 adam
131 * Development towards compiled ASN.1.
133 * Revision 1.73 1998/03/31 11:07:45 adam
134 * Furhter work on UNIverse resource report.
135 * Added Extended Services handling in frontend server.
137 * Revision 1.72 1998/02/11 11:53:35 adam
138 * Changed code so that it compiles as C++.
140 * Revision 1.71 1998/02/10 11:03:57 adam
141 * Added support for extended handlers in backend server interface.
143 * Revision 1.70 1998/01/29 13:15:35 adam
144 * Implemented sort for the backend interface.
146 * Revision 1.69 1997/09/30 11:48:12 adam
147 * Fixed bug introduced by previous commit.
149 * Revision 1.68 1997/09/29 13:18:59 adam
150 * Added function, oid_ent_to_oid, to replace the function
151 * oid_getoidbyent, which is not thread safe.
153 * Revision 1.67 1997/09/17 12:10:40 adam
156 * Revision 1.66 1997/09/05 15:26:44 adam
157 * Added ODR encode in search and scen bend request structures.
158 * Fixed a few enums that caused trouble with C++.
160 * Revision 1.65 1997/09/01 08:53:01 adam
161 * New windows NT/95 port using MSV5.0. The test server 'ztest' was
162 * moved a separate directory. MSV5.0 project server.dsp created.
163 * As an option, the server can now operate as an NT service.
165 * Revision 1.64 1997/04/30 08:52:11 quinn
168 * Revision 1.63 1996/10/11 11:57:26 quinn
171 * Revision 1.62 1996/07/06 19:58:35 quinn
172 * System headerfiles gathered in yconfig
174 * Revision 1.61 1996/06/10 08:56:16 quinn
177 * Revision 1.60 1996/05/30 11:03:10 quinn
178 * Fixed NextresultSetPosition bug fixed.
180 * Revision 1.59 1996/05/14 09:26:46 quinn
181 * Added attribute set to scan backend
183 * Revision 1.58 1996/02/20 12:53:04 quinn
186 * Revision 1.57 1996/01/02 08:57:47 quinn
187 * Changed enums in the ASN.1 .h files to #defines. Changed oident.class to oclass
189 * Revision 1.56 1995/12/14 11:09:57 quinn
192 * Revision 1.55 1995/11/08 17:41:37 quinn
195 * Revision 1.54 1995/11/08 15:11:29 quinn
196 * Log of close transmit.
198 * Revision 1.53 1995/11/01 13:54:58 quinn
201 * Revision 1.52 1995/11/01 12:19:13 quinn
202 * Second attempt to fix same bug.
204 * Revision 1.50 1995/10/25 16:58:32 quinn
207 * Revision 1.49 1995/10/16 13:51:53 quinn
208 * Changes to provide Especs to the backend.
210 * Revision 1.48 1995/10/06 08:51:20 quinn
211 * Added Write-buffer.
213 * Revision 1.47 1995/08/29 14:24:16 quinn
214 * Added second half of close-handshake
216 * Revision 1.46 1995/08/29 11:17:58 quinn
217 * Added code to receive close
219 * Revision 1.45 1995/08/21 09:11:00 quinn
220 * Smallish fixes to suppport new formats.
222 * Revision 1.44 1995/08/17 12:45:25 quinn
223 * Fixed minor problems with GRS-1. Added support in c&s.
225 * Revision 1.43 1995/08/15 12:00:31 quinn
228 * Revision 1.42 1995/08/15 11:16:50 quinn
230 * Revision 1.41 1995/08/02 10:23:06 quinn
233 * Revision 1.40 1995/07/31 14:34:26 quinn
234 * Fixed bug in process_searchResponse (numberOfRecordsReturned).
236 * Revision 1.39 1995/06/27 13:21:00 quinn
239 * Revision 1.38 1995/06/19 12:39:11 quinn
240 * Fixed bug in timeout code. Added BER dumper.
242 * Revision 1.37 1995/06/16 13:16:14 quinn
243 * Fixed Defaultdiagformat.
245 * Revision 1.36 1995/06/16 10:31:36 quinn
246 * Added session timeout.
248 * Revision 1.35 1995/06/15 07:45:14 quinn
251 * Revision 1.34 1995/06/14 15:26:46 quinn
252 * *** empty log message ***
254 * Revision 1.33 1995/06/06 14:57:05 quinn
255 * Better diagnostics.
257 * Revision 1.32 1995/06/06 08:41:44 quinn
258 * Better diagnostics.
260 * Revision 1.31 1995/06/06 08:15:37 quinn
263 * Revision 1.30 1995/06/05 10:53:32 quinn
264 * Added a better SCAN.
266 * Revision 1.29 1995/06/01 11:25:03 quinn
269 * Revision 1.28 1995/06/01 11:21:01 quinn
270 * Attempting to fix a bug in pack-records. replaced break with continue
271 * for large records, according to standard.
273 * Revision 1.27 1995/05/29 08:12:06 quinn
276 * Revision 1.26 1995/05/18 13:02:12 quinn
279 * Revision 1.25 1995/05/17 08:42:26 quinn
280 * Transfer auth info to backend. Allow backend to reject init gracefully.
282 * Revision 1.24 1995/05/16 08:51:04 quinn
283 * License, documentation, and memory fixes
285 * Revision 1.23 1995/05/15 13:25:10 quinn
288 * Revision 1.22 1995/05/15 11:56:39 quinn
289 * Asynchronous facilities. Restructuring of seshigh code.
291 * Revision 1.21 1995/05/02 08:53:19 quinn
292 * Trying in vain to fix comm with ISODE
294 * Revision 1.20 1995/04/20 15:13:00 quinn
297 * Revision 1.19 1995/04/18 08:15:34 quinn
298 * Added dynamic memory allocation on encoding (whew). Code is now somewhat
299 * neater. We'll make the same change for decoding one day.
301 * Revision 1.18 1995/04/17 11:28:25 quinn
304 * Revision 1.17 1995/04/10 10:23:36 quinn
305 * Some work to add scan and other things.
307 * Revision 1.16 1995/03/31 09:18:55 quinn
310 * Revision 1.15 1995/03/30 14:03:23 quinn
311 * Added RFC1006 as separate library
313 * Revision 1.14 1995/03/30 12:18:17 quinn
316 * Revision 1.13 1995/03/30 09:09:24 quinn
317 * Added state-handle and some support for asynchronous activities.
319 * Revision 1.12 1995/03/29 15:40:16 quinn
320 * Ongoing work. Statserv is now dynamic by default
322 * Revision 1.11 1995/03/28 09:16:21 quinn
323 * Added record packing to the search request
325 * Revision 1.10 1995/03/27 08:34:24 quinn
326 * Added dynamic server functionality.
327 * Released bindings to session.c (is now redundant)
329 * Revision 1.9 1995/03/22 15:01:26 quinn
330 * Adjusting record packing.
332 * Revision 1.8 1995/03/22 10:13:21 quinn
333 * Working on record packer
335 * Revision 1.7 1995/03/21 15:53:31 quinn
338 * Revision 1.6 1995/03/21 12:30:09 quinn
339 * Beginning to add support for record packing.
341 * Revision 1.5 1995/03/17 10:44:13 quinn
342 * Added catch of null-string in makediagrec
344 * Revision 1.4 1995/03/17 10:18:08 quinn
345 * Added memory management.
347 * Revision 1.3 1995/03/16 17:42:39 quinn
350 * Revision 1.2 1995/03/16 13:29:01 quinn
351 * Partitioned server.
353 * Revision 1.1 1995/03/15 16:02:10 quinn
354 * Modded session.c to seshigh.c
359 * Frontend server logic.
361 * This code receives incoming APDUs, and handles client requests by means
362 * of the backend API.
364 * Some of the code is getting quite involved, compared to simpler servers -
365 * primarily because it is asynchronous both in the communication with
366 * the user and the backend. We think the complexity will pay off in
367 * the form of greater flexibility when more asynchronous facilities
370 * Memory management has become somewhat involved. In the simple case, where
371 * only one PDU is pending at a time, it will simply reuse the same memory,
372 * once it has found its working size. When we enable multiple concurrent
373 * operations, perhaps even with multiple parallel calls to the backend, it
374 * will maintain a pool of buffers for encoding and decoding, trying to
375 * minimize memory allocation/deallocation during normal operation.
377 * TODOs include (and will be done in order of public interest):
379 * Support for EXPLAIN - provide simple meta-database system.
380 * Support for access control.
381 * Support for resource control.
382 * Support for extended services - primarily Item Order.
383 * Rest of Z39.50-1994
396 #include <yaz/yconfig.h>
397 #include <yaz/xmalloc.h>
398 #include <yaz/comstack.h>
401 #include <yaz/proto.h>
404 #include <yaz/logrpn.h>
405 #include <yaz/statserv.h>
407 #include <yaz/backend.h>
409 static int process_request(association *assoc, request *req, char **msg);
410 void backend_response(IOCHAN i, int event);
411 static int process_response(association *assoc, request *req, Z_APDU *res);
412 static Z_APDU *process_initRequest(association *assoc, request *reqb);
413 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
415 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
416 bend_search_rr *bsrr, int *fd);
417 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
419 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
420 static Z_APDU *process_sortRequest(association *assoc, request *reqb, int *fd);
421 static void process_close(association *assoc, request *reqb);
422 void save_referenceId (request *reqb, Z_ReferenceId *refid);
423 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
425 static Z_APDU *process_segmentRequest (association *assoc, request *reqb);
427 static FILE *apduf = 0; /* for use in static mode */
428 static statserv_options_block *control_block = 0;
430 /* Chas: Added in from DALI */
431 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd);
432 /* Chas: End of addition from DALI */
435 * Create and initialize a new association-handle.
436 * channel : iochannel for the current line.
437 * link : communications channel.
438 * Returns: 0 or a new association handle.
440 association *create_association(IOCHAN channel, COMSTACK link)
445 control_block = statserv_getcontrol();
446 if (!(anew = (association *)xmalloc(sizeof(*anew))))
449 anew->client_chan = channel;
450 anew->client_link = link;
451 anew->cs_get_mask = 0;
452 anew->cs_put_mask = 0;
453 anew->cs_accept_mask = 0;
454 if (!(anew->decode = odr_createmem(ODR_DECODE)) ||
455 !(anew->encode = odr_createmem(ODR_ENCODE)))
457 if (*control_block->apdufile)
462 strcpy(filename, control_block->apdufile);
463 if (!(anew->print = odr_createmem(ODR_PRINT)))
465 if (*control_block->apdufile != '-')
467 strcpy(filename, control_block->apdufile);
468 if (!control_block->dynamic)
472 if (!(apduf = fopen(filename, "w")))
474 yaz_log(LOG_WARN|LOG_ERRNO, "%s", filename);
477 setvbuf(apduf, 0, _IONBF, 0);
483 sprintf(filename + strlen(filename), ".%d", getpid());
484 if (!(f = fopen(filename, "w")))
486 yaz_log(LOG_WARN|LOG_ERRNO, "%s", filename);
489 setvbuf(f, 0, _IONBF, 0);
491 odr_setprint(anew->print, f);
496 anew->input_buffer = 0;
497 anew->input_buffer_len = 0;
499 anew->state = ASSOC_NEW;
500 request_initq(&anew->incoming);
501 request_initq(&anew->outgoing);
502 anew->proto = cs_getproto(link);
507 * Free association and release resources.
509 void destroy_association(association *h)
511 statserv_options_block *cb = statserv_getcontrol();
514 odr_destroy(h->decode);
515 odr_destroy(h->encode);
517 odr_destroy(h->print);
519 xfree(h->input_buffer);
521 (*cb->bend_close)(h->backend);
522 while (request_deq(&h->incoming));
523 while (request_deq(&h->outgoing));
524 request_delq(&h->incoming);
525 request_delq(&h->outgoing);
527 if (control_block && control_block->one_shot)
531 static void do_close_req(association *a, int reason, char *message,
535 Z_Close *cls = zget_Close(a->encode);
537 /* Purge request queue */
538 while (request_deq(&a->incoming));
539 while (request_deq(&a->outgoing));
542 yaz_log(LOG_LOG, "Sending Close PDU, reason=%d, message=%s",
543 reason, message ? message : "none");
544 apdu.which = Z_APDU_close;
546 *cls->closeReason = reason;
547 cls->diagnosticInformation = message;
548 process_response(a, req, &apdu);
549 iochan_settimeout(a->client_chan, 60);
553 yaz_log(LOG_DEBUG, "v2 client. No Close PDU");
554 iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
556 a->state = ASSOC_DEAD;
559 static void do_close(association *a, int reason, char *message)
561 do_close_req (a, reason, message, request_get(&a->outgoing));
565 * This is where PDUs from the client are read and the further
566 * processing is initiated. Flow of control moves down through the
567 * various process_* functions below, until the encoded result comes back up
568 * to the output handler in here.
570 * h : the I/O channel that has an outstanding event.
571 * event : the current outstanding event.
573 void ir_session(IOCHAN h, int event)
576 association *assoc = (association *)iochan_getdata(h);
577 COMSTACK conn = assoc->client_link;
580 assert(h && conn && assoc);
581 if (event == EVENT_TIMEOUT)
583 if (assoc->state != ASSOC_UP)
585 yaz_log(LOG_LOG, "Final timeout - closing connection.");
587 destroy_association(assoc);
592 yaz_log(LOG_LOG, "Session idle too long. Sending close.");
593 do_close(assoc, Z_Close_lackOfActivity, 0);
597 if (event & assoc->cs_accept_mask)
599 yaz_log (LOG_DEBUG, "ir_session (accept)");
600 if (!cs_accept (conn))
602 yaz_log (LOG_LOG, "accept failed");
603 destroy_association(assoc);
606 iochan_clearflag (h, EVENT_OUTPUT|EVENT_OUTPUT);
607 if (conn->io_pending)
608 { /* cs_accept didn't complete */
609 assoc->cs_accept_mask =
610 ((conn->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
611 ((conn->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
613 iochan_setflag (h, assoc->cs_accept_mask);
616 { /* cs_accept completed. Prepare for reading (cs_get) */
617 assoc->cs_accept_mask = 0;
618 assoc->cs_get_mask = EVENT_INPUT;
619 iochan_setflag (h, assoc->cs_get_mask);
623 if ((event & assoc->cs_get_mask) || (event & EVENT_WORK)) /* input */
625 if ((assoc->cs_put_mask & EVENT_INPUT) == 0 && (event & assoc->cs_get_mask))
627 yaz_log(LOG_DEBUG, "ir_session (input)");
628 /* We aren't speaking to this fellow */
629 if (assoc->state == ASSOC_DEAD)
631 yaz_log(LOG_LOG, "Closed connection after reject");
633 destroy_association(assoc);
637 assoc->cs_get_mask = EVENT_INPUT;
638 if ((res = cs_get(conn, &assoc->input_buffer,
639 &assoc->input_buffer_len)) <= 0)
641 yaz_log(LOG_LOG, "Connection closed by client");
643 destroy_association(assoc);
647 else if (res == 1) /* incomplete read - wait for more */
649 if (conn->io_pending & CS_WANT_WRITE)
650 assoc->cs_get_mask |= EVENT_OUTPUT;
651 iochan_setflag(h, assoc->cs_get_mask);
654 if (cs_more(conn)) /* more stuff - call us again later, please */
655 iochan_setevent(h, EVENT_INPUT);
657 /* we got a complete PDU. Let's decode it */
658 yaz_log(LOG_DEBUG, "Got PDU, %d bytes", res);
659 req = request_get(&assoc->incoming); /* get a new request structure */
660 odr_reset(assoc->decode);
661 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
662 if (!z_APDU(assoc->decode, &req->request, 0, 0))
664 yaz_log(LOG_LOG, "ODR error on incoming PDU: %s [near byte %d] ",
665 odr_errmsg(odr_geterror(assoc->decode)),
666 odr_offset(assoc->decode));
667 yaz_log(LOG_LOG, "PDU dump:");
668 odr_dumpBER(yaz_log_file(), assoc->input_buffer, res);
669 do_close(assoc, Z_Close_protocolError, "Malformed package");
672 req->request_mem = odr_extract_mem(assoc->decode);
673 if (assoc->print && !z_APDU(assoc->print, &req->request, 0, 0))
675 yaz_log(LOG_WARN, "ODR print error: %s",
676 odr_errmsg(odr_geterror(assoc->print)));
677 odr_reset(assoc->print);
679 request_enq(&assoc->incoming, req);
682 /* can we do something yet? */
683 req = request_head(&assoc->incoming);
684 if (req->state == REQUEST_IDLE)
687 request_deq(&assoc->incoming);
688 if (process_request(assoc, req, &msg) < 0)
689 do_close_req(assoc, Z_Close_systemProblem, msg, req);
692 if (event & assoc->cs_put_mask)
694 request *req = request_head(&assoc->outgoing);
696 assoc->cs_put_mask = 0;
697 yaz_log(LOG_DEBUG, "ir_session (output)");
698 req->state = REQUEST_PENDING;
699 switch (res = cs_put(conn, req->response, req->len_response))
702 yaz_log(LOG_LOG, "Connection closed by client");
704 destroy_association(assoc);
707 case 0: /* all sent - release the request structure */
708 yaz_log(LOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
709 nmem_destroy(req->request_mem);
710 request_deq(&assoc->outgoing);
711 request_release(req);
712 if (!request_head(&assoc->outgoing))
713 { /* restore mask for cs_get operation ... */
714 iochan_clearflag(h, EVENT_OUTPUT|EVENT_INPUT);
715 iochan_setflag(h, assoc->cs_get_mask);
719 if (conn->io_pending & CS_WANT_WRITE)
720 assoc->cs_put_mask |= EVENT_OUTPUT;
721 if (conn->io_pending & CS_WANT_READ)
722 assoc->cs_put_mask |= EVENT_INPUT;
723 iochan_setflag(h, assoc->cs_put_mask);
726 if (event & EVENT_EXCEPT)
728 yaz_log(LOG_LOG, "ir_session (exception)");
730 destroy_association(assoc);
736 * Initiate request processing.
738 static int process_request(association *assoc, request *req, char **msg)
744 *msg = "Unknown Error";
745 assert(req && req->state == REQUEST_IDLE);
746 if (req->request->which != Z_APDU_initRequest && !assoc->init)
748 *msg = "Missing InitRequest";
751 switch (req->request->which)
753 case Z_APDU_initRequest:
754 res = process_initRequest(assoc, req); break;
755 case Z_APDU_searchRequest:
756 res = process_searchRequest(assoc, req, &fd); break;
757 case Z_APDU_presentRequest:
758 res = process_presentRequest(assoc, req, &fd); break;
759 case Z_APDU_scanRequest:
760 if (assoc->init->bend_scan)
761 res = process_scanRequest(assoc, req, &fd);
764 *msg = "Cannot handle Scan APDU";
768 case Z_APDU_extendedServicesRequest:
769 if (assoc->init->bend_esrequest)
770 res = process_ESRequest(assoc, req, &fd);
773 *msg = "Cannot handle Extended Services APDU";
777 case Z_APDU_sortRequest:
778 if (assoc->init->bend_sort)
779 res = process_sortRequest(assoc, req, &fd);
782 *msg = "Cannot handle Sort APDU";
787 process_close(assoc, req);
789 case Z_APDU_deleteResultSetRequest:
790 if (assoc->init->bend_delete)
791 res = process_deleteRequest(assoc, req, &fd);
794 *msg = "Cannot handle Delete APDU";
798 case Z_APDU_segmentRequest:
799 if (assoc->init->bend_segment)
801 res = process_segmentRequest (assoc, req);
805 *msg = "Cannot handle Segment APDU";
810 *msg = "Bad APDU received";
815 yaz_log(LOG_DEBUG, " result immediately available");
816 retval = process_response(assoc, req, res);
820 yaz_log(LOG_DEBUG, " result unavailble");
823 else /* no result yet - one will be provided later */
827 /* Set up an I/O handler for the fd supplied by the backend */
829 yaz_log(LOG_DEBUG, " establishing handler for result");
830 req->state = REQUEST_PENDING;
831 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT)))
833 iochan_setdata(chan, assoc);
840 * Handle message from the backend.
842 void backend_response(IOCHAN i, int event)
844 association *assoc = (association *)iochan_getdata(i);
845 request *req = request_head(&assoc->incoming);
849 yaz_log(LOG_DEBUG, "backend_response");
850 assert(assoc && req && req->state != REQUEST_IDLE);
851 /* determine what it is we're waiting for */
852 switch (req->request->which)
854 case Z_APDU_searchRequest:
855 res = response_searchRequest(assoc, req, 0, &fd); break;
857 case Z_APDU_presentRequest:
858 res = response_presentRequest(assoc, req, 0, &fd); break;
859 case Z_APDU_scanRequest:
860 res = response_scanRequest(assoc, req, 0, &fd); break;
863 yaz_log(LOG_WARN, "Serious programmer's lapse or bug");
866 if ((res && process_response(assoc, req, res) < 0) || fd < 0)
868 yaz_log(LOG_LOG, "Fatal error when talking to backend");
869 do_close(assoc, Z_Close_systemProblem, 0);
873 else if (!res) /* no result yet - try again later */
875 yaz_log(LOG_DEBUG, " no result yet");
876 iochan_setfd(i, fd); /* in case fd has changed */
881 * Encode response, and transfer the request structure to the outgoing queue.
883 static int process_response(association *assoc, request *req, Z_APDU *res)
885 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
886 if (!z_APDU(assoc->encode, &res, 0, 0))
888 yaz_log(LOG_WARN, "ODR error when encoding response: %s",
889 odr_errmsg(odr_geterror(assoc->decode)));
890 odr_reset(assoc->encode);
893 req->response = odr_getbuf(assoc->encode, &req->len_response,
894 &req->size_response);
895 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
896 if (assoc->print && !z_APDU(assoc->print, &res, 0, 0))
898 yaz_log(LOG_WARN, "ODR print error: %s",
899 odr_errmsg(odr_geterror(assoc->print)));
900 odr_reset(assoc->print);
902 odr_reset(assoc->encode);
903 req->state = REQUEST_IDLE;
904 request_enq(&assoc->outgoing, req);
905 /* turn the work over to the ir_session handler */
906 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
907 assoc->cs_put_mask = EVENT_OUTPUT;
908 /* Is there more work to be done? give that to the input handler too */
910 if (request_head(&assoc->incoming))
912 yaz_log (LOG_DEBUG, "more work to be done");
913 iochan_setevent(assoc->client_chan, EVENT_WORK);
920 * Handle init request.
921 * At the moment, we don't check the options
922 * anywhere else in the code - we just try not to do anything that would
923 * break a naive client. We'll toss 'em into the association block when
924 * we need them there.
926 static Z_APDU *process_initRequest(association *assoc, request *reqb)
928 statserv_options_block *cb = statserv_getcontrol();
929 Z_InitRequest *req = reqb->request->u.initRequest;
930 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
931 Z_InitResponse *resp = apdu->u.initResponse;
932 bend_initresult *binitres;
936 assoc->init = (bend_initrequest *) xmalloc (sizeof(*assoc->init));
938 yaz_log(LOG_LOG, "Got initRequest");
939 if (req->implementationId)
940 yaz_log(LOG_LOG, "Id: %s", req->implementationId);
941 if (req->implementationName)
942 yaz_log(LOG_LOG, "Name: %s", req->implementationName);
943 if (req->implementationVersion)
944 yaz_log(LOG_LOG, "Version: %s", req->implementationVersion);
946 assoc->init->stream = assoc->encode;
947 assoc->init->print = assoc->print;
948 assoc->init->auth = req->idAuthentication;
949 assoc->init->referenceId = req->referenceId;
950 assoc->init->implementation_version = 0;
951 assoc->init->implementation_name = 0;
952 assoc->init->bend_sort = NULL;
953 assoc->init->bend_search = NULL;
954 assoc->init->bend_present = NULL;
955 assoc->init->bend_esrequest = NULL;
956 assoc->init->bend_delete = NULL;
957 assoc->init->bend_scan = NULL;
958 assoc->init->bend_segment = NULL;
959 assoc->init->bend_fetch = NULL;
961 assoc->init->peer_name =
962 odr_strdup (assoc->encode, cs_addrstr(assoc->client_link));
963 if (!(binitres = (*cb->bend_init)(assoc->init)))
965 yaz_log(LOG_WARN, "Bad response from backend.");
969 assoc->backend = binitres->handle;
970 if ((assoc->init->bend_sort))
971 yaz_log (LOG_DEBUG, "Sort handler installed");
972 if ((assoc->init->bend_search))
973 yaz_log (LOG_DEBUG, "Search handler installed");
974 if ((assoc->init->bend_present))
975 yaz_log (LOG_DEBUG, "Present handler installed");
976 if ((assoc->init->bend_esrequest))
977 yaz_log (LOG_DEBUG, "ESRequest handler installed");
978 if ((assoc->init->bend_delete))
979 yaz_log (LOG_DEBUG, "Delete handler installed");
980 if ((assoc->init->bend_scan))
981 yaz_log (LOG_DEBUG, "Scan handler installed");
982 if ((assoc->init->bend_segment))
983 yaz_log (LOG_DEBUG, "Segment handler installed");
985 resp->referenceId = req->referenceId;
987 /* let's tell the client what we can do */
988 if (ODR_MASK_GET(req->options, Z_Options_search))
990 ODR_MASK_SET(resp->options, Z_Options_search);
991 strcat(options, "srch");
993 if (ODR_MASK_GET(req->options, Z_Options_present))
995 ODR_MASK_SET(resp->options, Z_Options_present);
996 strcat(options, " prst");
998 if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
999 assoc->init->bend_delete)
1001 ODR_MASK_SET(resp->options, Z_Options_delSet);
1002 strcat(options, " del");
1004 if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
1005 assoc->init->bend_esrequest)
1007 ODR_MASK_SET(resp->options, Z_Options_extendedServices);
1008 strcat (options, " extendedServices");
1010 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
1012 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
1013 strcat(options, " namedresults");
1015 if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
1017 ODR_MASK_SET(resp->options, Z_Options_scan);
1018 strcat(options, " scan");
1020 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
1022 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
1023 strcat(options, " concurop");
1025 if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
1027 ODR_MASK_SET(resp->options, Z_Options_sort);
1028 strcat(options, " sort");
1030 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
1032 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
1033 assoc->version = 2; /* 1 & 2 are equivalent */
1035 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
1037 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
1040 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
1042 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
1045 yaz_log(LOG_LOG, "Negotiated to v%d: %s", assoc->version, options);
1046 assoc->maximumRecordSize = *req->maximumRecordSize;
1047 if (assoc->maximumRecordSize > control_block->maxrecordsize)
1048 assoc->maximumRecordSize = control_block->maxrecordsize;
1049 assoc->preferredMessageSize = *req->preferredMessageSize;
1050 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
1051 assoc->preferredMessageSize = assoc->maximumRecordSize;
1054 assoc->maximumRecordSize = 3000000;
1055 assoc->preferredMessageSize = 3000000;
1058 resp->preferredMessageSize = &assoc->preferredMessageSize;
1059 resp->maximumRecordSize = &assoc->maximumRecordSize;
1061 resp->implementationName = "GFS";
1063 if (assoc->init->implementation_name)
1066 odr_malloc (assoc->encode,
1067 strlen(assoc->init->implementation_name) + 10 +
1068 strlen(resp->implementationName));
1069 sprintf (nv, "%s / %s",
1070 resp->implementationName, assoc->init->implementation_name);
1071 resp->implementationName = nv;
1073 if (assoc->init->implementation_version)
1076 odr_malloc (assoc->encode,
1077 strlen(assoc->init->implementation_version) + 10 +
1078 strlen(resp->implementationVersion));
1079 sprintf (nv, "YAZ %s / %s",
1080 resp->implementationVersion,
1081 assoc->init->implementation_version);
1082 resp->implementationVersion = nv;
1085 if (binitres->errcode)
1087 yaz_log(LOG_LOG, "Connection rejected by backend.");
1089 assoc->state = ASSOC_DEAD;
1092 assoc->state = ASSOC_UP;
1097 * These functions should be merged.
1100 static void set_addinfo (Z_DefaultDiagFormat *dr, char *addinfo, ODR odr)
1103 dr->which = Z_DefaultDiagFormat_v2Addinfo;
1104 dr->u.v2Addinfo = odr_strdup (odr, addinfo ? addinfo : "");
1106 dr->which = Z_DiagForm_v2AddInfo;
1107 dr->addinfo = odr_strdup (odr, addinfo ? addinfo : "");
1112 * nonsurrogate diagnostic record.
1114 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
1117 Z_Records *rec = (Z_Records *)
1118 odr_malloc (assoc->encode, sizeof(*rec));
1121 odr_malloc (assoc->encode, sizeof(*err));
1122 Z_DiagRec *drec = (Z_DiagRec *)
1123 odr_malloc (assoc->encode, sizeof(*drec));
1124 Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
1125 odr_malloc (assoc->encode, sizeof(*dr));
1127 bib1.proto = assoc->proto;
1128 bib1.oclass = CLASS_DIAGSET;
1129 bib1.value = VAL_BIB1;
1131 yaz_log(LOG_DEBUG, "Diagnostic: %d -- %s", error, addinfo ? addinfo :
1134 rec->which = Z_Records_NSD;
1136 rec->u.nonSurrogateDiagnostic = dr;
1138 rec->u.nonSurrogateDiagnostic = drec;
1139 drec->which = Z_DiagRec_defaultFormat;
1140 drec->u.defaultFormat = dr;
1142 dr->diagnosticSetId =
1143 odr_oiddup (assoc->encode, oid_ent_to_oid(&bib1, oid));
1144 dr->condition = err;
1145 set_addinfo (dr, addinfo, assoc->encode);
1150 * surrogate diagnostic.
1152 static Z_NamePlusRecord *surrogatediagrec(association *assoc, char *dbname,
1153 int error, char *addinfo)
1156 Z_NamePlusRecord *rec = (Z_NamePlusRecord *)
1157 odr_malloc (assoc->encode, sizeof(*rec));
1158 int *err = (int *)odr_malloc (assoc->encode, sizeof(*err));
1160 Z_DiagRec *drec = (Z_DiagRec *)odr_malloc (assoc->encode, sizeof(*drec));
1161 Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
1162 odr_malloc (assoc->encode, sizeof(*dr));
1164 bib1.proto = assoc->proto;
1165 bib1.oclass = CLASS_DIAGSET;
1166 bib1.value = VAL_BIB1;
1168 yaz_log(LOG_DEBUG, "SurrogateDiagnotic: %d -- %s", error, addinfo);
1170 rec->databaseName = dbname;
1171 rec->which = Z_NamePlusRecord_surrogateDiagnostic;
1172 rec->u.surrogateDiagnostic = drec;
1173 drec->which = Z_DiagRec_defaultFormat;
1174 drec->u.defaultFormat = dr;
1175 dr->diagnosticSetId = odr_oiddup (assoc->encode,
1176 oid_ent_to_oid(&bib1, oid));
1177 dr->condition = err;
1178 set_addinfo (dr, addinfo, assoc->encode);
1184 * multiple nonsurrogate diagnostics.
1186 static Z_DiagRecs *diagrecs(association *assoc, int error, char *addinfo)
1189 Z_DiagRecs *recs = (Z_DiagRecs *)odr_malloc (assoc->encode, sizeof(*recs));
1190 int *err = (int *)odr_malloc (assoc->encode, sizeof(*err));
1192 Z_DiagRec **recp = (Z_DiagRec **)odr_malloc (assoc->encode, sizeof(*recp));
1193 Z_DiagRec *drec = (Z_DiagRec *)odr_malloc (assoc->encode, sizeof(*drec));
1194 Z_DefaultDiagFormat *rec = (Z_DefaultDiagFormat *)odr_malloc (assoc->encode, sizeof(*rec));
1196 yaz_log(LOG_DEBUG, "DiagRecs: %d -- %s", error, addinfo ? addinfo : "");
1197 bib1.proto = assoc->proto;
1198 bib1.oclass = CLASS_DIAGSET;
1199 bib1.value = VAL_BIB1;
1202 recs->num_diagRecs = 1;
1203 recs->diagRecs = recp;
1205 drec->which = Z_DiagRec_defaultFormat;
1206 drec->u.defaultFormat = rec;
1208 rec->diagnosticSetId = odr_oiddup (assoc->encode,
1209 oid_ent_to_oid(&bib1, oid));
1210 rec->condition = err;
1213 rec->which = Z_DefaultDiagFormat_v2Addinfo;
1214 rec->u.v2Addinfo = odr_strdup (assoc->encode, addinfo ? addinfo : "");
1216 rec->which = Z_DiagForm_v2AddInfo;
1217 rec->addinfo = odr_strdup (assoc->encode, addinfo ? addinfo : "");
1222 static Z_Records *pack_records(association *a, char *setname, int start,
1223 int *num, Z_RecordComposition *comp,
1224 int *next, int *pres, oid_value format,
1225 Z_ReferenceId *referenceId,
1228 int recno, total_length = 0, toget = *num, dumped_records = 0;
1229 Z_Records *records =
1230 (Z_Records *) odr_malloc (a->encode, sizeof(*records));
1231 Z_NamePlusRecordList *reclist =
1232 (Z_NamePlusRecordList *) odr_malloc (a->encode, sizeof(*reclist));
1233 Z_NamePlusRecord **list =
1234 (Z_NamePlusRecord **) odr_malloc (a->encode, sizeof(*list) * toget);
1236 records->which = Z_Records_DBOSD;
1237 records->u.databaseOrSurDiagnostics = reclist;
1238 reclist->num_records = 0;
1239 reclist->records = list;
1240 *pres = Z_PRES_SUCCESS;
1244 yaz_log(LOG_LOG, "Request to pack %d+%d", start, toget);
1245 yaz_log(LOG_DEBUG, "pms=%d, mrs=%d", a->preferredMessageSize,
1246 a->maximumRecordSize);
1247 for (recno = start; reclist->num_records < toget; recno++)
1250 Z_NamePlusRecord *thisrec;
1251 int this_length = 0;
1253 * we get the number of bytes allocated on the stream before any
1254 * allocation done by the backend - this should give us a reasonable
1255 * idea of the total size of the data so far.
1257 total_length = odr_total(a->encode) - dumped_records;
1263 freq.last_in_set = 0;
1264 freq.setname = setname;
1265 freq.surrogate_flag = 0;
1266 freq.number = recno;
1268 freq.request_format = format;
1269 freq.request_format_raw = oid;
1270 freq.output_format = format;
1271 freq.output_format_raw = 0;
1272 freq.stream = a->encode;
1273 freq.print = a->print;
1274 freq.surrogate_flag = 0;
1275 freq.referenceId = referenceId;
1276 (*a->init->bend_fetch)(a->backend, &freq);
1277 /* backend should be able to signal whether error is system-wide
1278 or only pertaining to current record */
1281 if (!freq.surrogate_flag)
1283 *pres = Z_PRES_FAILURE;
1284 return diagrec(a, freq.errcode, freq.errstring);
1286 reclist->records[reclist->num_records] =
1287 surrogatediagrec(a, freq.basename, freq.errcode,
1289 reclist->num_records++;
1290 *next = freq.last_in_set ? 0 : recno + 1;
1294 this_length = freq.len;
1296 this_length = odr_total(a->encode) - total_length;
1297 yaz_log(LOG_DEBUG, " fetched record, len=%d, total=%d",
1298 this_length, total_length);
1299 if (this_length + total_length > a->preferredMessageSize)
1301 /* record is small enough, really */
1302 if (this_length <= a->preferredMessageSize)
1304 yaz_log(LOG_DEBUG, " Dropped last normal-sized record");
1305 *pres = Z_PRES_PARTIAL_2;
1308 /* record can only be fetched by itself */
1309 if (this_length < a->maximumRecordSize)
1311 yaz_log(LOG_DEBUG, " Record > prefmsgsz");
1314 yaz_log(LOG_DEBUG, " Dropped it");
1315 reclist->records[reclist->num_records] =
1316 surrogatediagrec(a, freq.basename, 16, 0);
1317 reclist->num_records++;
1318 *next = freq.last_in_set ? 0 : recno + 1;
1319 dumped_records += this_length;
1323 else /* too big entirely */
1325 yaz_log(LOG_DEBUG, "Record > maxrcdsz");
1326 reclist->records[reclist->num_records] =
1327 surrogatediagrec(a, freq.basename, 17, 0);
1328 reclist->num_records++;
1329 *next = freq.last_in_set ? 0 : recno + 1;
1330 dumped_records += this_length;
1335 if (!(thisrec = (Z_NamePlusRecord *)
1336 odr_malloc(a->encode, sizeof(*thisrec))))
1338 if (!(thisrec->databaseName = (char *)odr_malloc(a->encode,
1339 strlen(freq.basename) + 1)))
1341 strcpy(thisrec->databaseName, freq.basename);
1342 thisrec->which = Z_NamePlusRecord_databaseRecord;
1344 if (freq.output_format_raw)
1346 struct oident *ident = oid_getentbyoid(freq.output_format_raw);
1347 freq.output_format = ident->value;
1349 thisrec->u.databaseRecord = z_ext_record(a->encode, freq.output_format,
1350 freq.record, freq.len);
1351 if (!thisrec->u.databaseRecord)
1353 reclist->records[reclist->num_records] = thisrec;
1354 reclist->num_records++;
1355 *next = freq.last_in_set ? 0 : recno + 1;
1357 *num = reclist->num_records;
1361 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
1364 Z_SearchRequest *req = reqb->request->u.searchRequest;
1365 bend_search_rr *bsrr =
1366 (bend_search_rr *)nmem_malloc (reqb->request_mem, sizeof(*bsrr));
1368 yaz_log(LOG_LOG, "Got SearchRequest.");
1370 bsrr->request = reqb;
1371 bsrr->association = assoc;
1372 bsrr->referenceId = req->referenceId;
1373 save_referenceId (reqb, bsrr->referenceId);
1375 yaz_log (LOG_LOG, "ResultSet '%s'", req->resultSetName);
1376 if (req->databaseNames)
1379 for (i = 0; i < req->num_databaseNames; i++)
1380 yaz_log (LOG_LOG, "Database '%s'", req->databaseNames[i]);
1382 switch (req->query->which)
1384 case Z_Query_type_1: case Z_Query_type_101:
1385 log_rpn_query (req->query->u.type_1);
1387 if (assoc->init->bend_search)
1389 bsrr->setname = req->resultSetName;
1390 bsrr->replace_set = *req->replaceIndicator;
1391 bsrr->num_bases = req->num_databaseNames;
1392 bsrr->basenames = req->databaseNames;
1393 bsrr->query = req->query;
1394 bsrr->stream = assoc->encode;
1395 bsrr->decode = assoc->decode;
1396 bsrr->print = assoc->print;
1399 bsrr->errstring = NULL;
1400 (assoc->init->bend_search)(assoc->backend, bsrr);
1407 bend_searchrequest bsrq;
1408 bend_searchresult *bsrt;
1410 bsrq.setname = req->resultSetName;
1411 bsrq.replace_set = *req->replaceIndicator;
1412 bsrq.num_bases = req->num_databaseNames;
1413 bsrq.basenames = req->databaseNames;
1414 bsrq.query = req->query;
1415 bsrq.referenceId = req->referenceId;
1416 bsrq.stream = assoc->encode;
1417 bsrq.decode = assoc->decode;
1418 bsrq.print = assoc->print;
1419 if (!(bsrt = bend_search (assoc->backend, &bsrq, fd)))
1421 bsrr->hits = bsrt->hits;
1422 bsrr->errcode = bsrt->errcode;
1423 bsrr->errstring = bsrt->errstring;
1426 return response_searchRequest(assoc, reqb, bsrr, fd);
1429 int bend_searchresponse(void *handle, bend_search_rr *bsrr) {return 0;}
1432 * Prepare a searchresponse based on the backend results. We probably want
1433 * to look at making the fetching of records nonblocking as well, but
1434 * so far, we'll keep things simple.
1435 * If bsrt is null, that means we're called in response to a communications
1436 * event, and we'll have to get the response for ourselves.
1438 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
1439 bend_search_rr *bsrt, int *fd)
1441 Z_SearchRequest *req = reqb->request->u.searchRequest;
1442 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1443 Z_SearchResponse *resp = (Z_SearchResponse *)
1444 odr_malloc (assoc->encode, sizeof(*resp));
1445 int *nulint = (int *)odr_malloc (assoc->encode, sizeof(*nulint));
1446 bool_t *sr = (bool_t *)odr_malloc (assoc->encode, sizeof(*sr));
1447 int *next = (int *)odr_malloc (assoc->encode, sizeof(*next));
1448 int *none = (int *)odr_malloc (assoc->encode, sizeof(*none));
1455 apdu->which = Z_APDU_searchResponse;
1456 apdu->u.searchResponse = resp;
1457 resp->referenceId = req->referenceId;
1458 resp->additionalSearchInfo = 0;
1459 resp->otherInfo = 0;
1461 if (!bsrt && !bend_searchresponse(assoc->backend, bsrt))
1463 yaz_log(LOG_FATAL, "Bad result from backend");
1466 else if (bsrt->errcode)
1468 resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
1469 resp->resultCount = nulint;
1470 resp->numberOfRecordsReturned = nulint;
1471 resp->nextResultSetPosition = nulint;
1472 resp->searchStatus = nulint;
1473 resp->resultSetStatus = none;
1474 resp->presentStatus = 0;
1478 int *toget = (int *)odr_malloc (assoc->encode, sizeof(*toget));
1479 int *presst = (int *)odr_malloc (assoc->encode, sizeof(*presst));
1480 Z_RecordComposition comp, *compp = 0;
1485 resp->resultCount = &bsrt->hits;
1487 comp.which = Z_RecordComp_simple;
1488 /* how many records does the user agent want, then? */
1489 if (bsrt->hits <= *req->smallSetUpperBound)
1491 *toget = bsrt->hits;
1492 if ((comp.u.simple = req->smallSetElementSetNames))
1495 else if (bsrt->hits < *req->largeSetLowerBound)
1497 *toget = *req->mediumSetPresentNumber;
1498 if (*toget > bsrt->hits)
1499 *toget = bsrt->hits;
1500 if ((comp.u.simple = req->mediumSetElementSetNames))
1506 if (*toget && !resp->records)
1511 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1512 prefformat->oclass != CLASS_RECSYN)
1515 form = prefformat->value;
1516 resp->records = pack_records(assoc, req->resultSetName, 1,
1517 toget, compp, next, presst, form, req->referenceId,
1518 req->preferredRecordSyntax);
1521 resp->numberOfRecordsReturned = toget;
1522 resp->nextResultSetPosition = next;
1523 resp->searchStatus = sr;
1524 resp->resultSetStatus = 0;
1525 resp->presentStatus = presst;
1529 if (*resp->resultCount)
1531 resp->numberOfRecordsReturned = nulint;
1532 resp->nextResultSetPosition = next;
1533 resp->searchStatus = sr;
1534 resp->resultSetStatus = 0;
1535 resp->presentStatus = 0;
1542 * Maybe we got a little over-friendly when we designed bend_fetch to
1543 * get only one record at a time. Some backends can optimise multiple-record
1544 * fetches, and at any rate, there is some overhead involved in
1545 * all that selecting and hopping around. Problem is, of course, that the
1546 * frontend can't know ahead of time how many records it'll need to
1547 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
1548 * is downright lousy as a bulk data transfer protocol.
1550 * To start with, we'll do the fetching of records from the backend
1551 * in one operation: To save some trips in and out of the event-handler,
1552 * and to simplify the interface to pack_records. At any rate, asynch
1553 * operation is more fun in operations that have an unpredictable execution
1554 * speed - which is normally more true for search than for present.
1556 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
1559 Z_PresentRequest *req = reqb->request->u.presentRequest;
1563 Z_PresentResponse *resp;
1568 yaz_log(LOG_LOG, "Got PresentRequest.");
1570 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1571 prefformat->oclass != CLASS_RECSYN)
1574 form = prefformat->value;
1575 if (assoc->init->bend_present)
1577 bend_present_rr *bprr = (bend_present_rr *)
1578 nmem_malloc (reqb->request_mem, sizeof(*bprr));
1579 bprr->setname = req->resultSetId;
1580 bprr->start = *req->resultSetStartPoint;
1581 bprr->number = *req->numberOfRecordsRequested;
1582 bprr->format = form;
1583 bprr->comp = req->recordComposition;
1584 bprr->referenceId = req->referenceId;
1585 bprr->stream = assoc->encode;
1586 bprr->print = assoc->print;
1587 bprr->request = reqb;
1588 bprr->association = assoc;
1590 bprr->errstring = NULL;
1591 (*assoc->init->bend_present)(assoc->backend, bprr);
1596 apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1597 resp = (Z_PresentResponse *)odr_malloc (assoc->encode, sizeof(*resp));
1598 presst = (int *)odr_malloc (assoc->encode, sizeof(*presst));
1599 next = (int *)odr_malloc (assoc->encode, sizeof(*next));
1600 num = (int *)odr_malloc (assoc->encode, sizeof(*num));
1603 *num = *req->numberOfRecordsRequested;
1605 apdu->which = Z_APDU_presentResponse;
1606 apdu->u.presentResponse = resp;
1607 resp->referenceId = req->referenceId;
1608 resp->otherInfo = 0;
1611 pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
1612 num, req->recordComposition, next, presst, form,
1613 req->referenceId, req->preferredRecordSyntax);
1616 resp->numberOfRecordsReturned = num;
1617 resp->presentStatus = presst;
1618 resp->nextResultSetPosition = next;
1624 * Scan was implemented rather in a hurry, and with support for only the basic
1625 * elements of the service in the backend API. Suggestions are welcome.
1627 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
1629 Z_ScanRequest *req = reqb->request->u.scanRequest;
1630 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1631 Z_ScanResponse *res = (Z_ScanResponse *)
1632 odr_malloc (assoc->encode, sizeof(*res));
1633 int *scanStatus = (int *)
1634 odr_malloc (assoc->encode, sizeof(*scanStatus));
1635 int *numberOfEntriesReturned = (int *)
1636 odr_malloc (assoc->encode, sizeof(*numberOfEntriesReturned));
1637 Z_ListEntries *ents = (Z_ListEntries *)
1638 odr_malloc (assoc->encode, sizeof(*ents));
1639 Z_DiagRecs *diagrecs_p = NULL;
1643 yaz_log(LOG_LOG, "Got ScanRequest");
1644 *scanStatus = Z_Scan_failure;
1645 *numberOfEntriesReturned = 0;
1647 apdu->which = Z_APDU_scanResponse;
1648 apdu->u.scanResponse = res;
1649 res->referenceId = req->referenceId;
1650 res->stepSize = (int*) odr_malloc (assoc->encode, sizeof(*res->stepSize));
1653 *res->stepSize = *req->stepSize;
1654 res->scanStatus = scanStatus;
1655 res->numberOfEntriesReturned = numberOfEntriesReturned;
1656 res->positionOfTerm = 0;
1657 res->entries = ents;
1658 ents->num_entries = 0;
1659 ents->entries = NULL;
1660 ents->num_nonsurrogateDiagnostics = 0;
1661 ents->nonsurrogateDiagnostics = NULL;
1662 res->attributeSet = 0;
1665 if (req->attributeSet && (!(attent = oid_getentbyoid(req->attributeSet)) ||
1666 attent->oclass != CLASS_ATTSET
1667 || attent->value != VAL_BIB1))
1668 diagrecs_p = diagrecs(assoc, 121, 0);
1669 else if (req->stepSize && *req->stepSize > 0)
1670 diagrecs_p = diagrecs(assoc, 205, 0);
1673 bend_scan_rr *bsrr = (bend_scan_rr *)
1674 odr_malloc (assoc->encode, sizeof(*bsrr));
1675 if (req->databaseNames)
1678 for (i = 0; i < req->num_databaseNames; i++)
1679 yaz_log (LOG_LOG, "Database '%s'", req->databaseNames[i]);
1681 bsrr->num_bases = req->num_databaseNames;
1682 bsrr->basenames = req->databaseNames;
1683 bsrr->num_entries = *req->numberOfTermsRequested;
1684 bsrr->term = req->termListAndStartPoint;
1685 bsrr->referenceId = req->referenceId;
1686 bsrr->stream = assoc->encode;
1687 bsrr->print = assoc->print;
1688 bsrr->step_size = res->stepSize;
1689 if (!(attset = oid_getentbyoid(req->attributeSet)) ||
1690 attset->oclass != CLASS_RECSYN)
1691 bsrr->attributeset = VAL_NONE;
1693 bsrr->attributeset = attset->value;
1694 log_scan_term (req->termListAndStartPoint, bsrr->attributeset);
1695 bsrr->term_position = req->preferredPositionInResponse ?
1696 *req->preferredPositionInResponse : 1;
1697 ((int (*)(void *, bend_scan_rr *))
1698 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1700 diagrecs_p = diagrecs(assoc, bsrr->errcode, bsrr->errstring);
1704 Z_Entry **tab = (Z_Entry **)
1705 odr_malloc (assoc->encode, sizeof(*tab) * bsrr->num_entries);
1707 if (bsrr->status == BEND_SCAN_PARTIAL)
1708 *scanStatus = Z_Scan_partial_5;
1710 *scanStatus = Z_Scan_success;
1711 ents->entries = tab;
1712 ents->num_entries = bsrr->num_entries;
1713 res->numberOfEntriesReturned = &ents->num_entries;
1714 res->positionOfTerm = &bsrr->term_position;
1715 for (i = 0; i < bsrr->num_entries; i++)
1721 tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
1722 if (bsrr->entries[i].occurrences >= 0)
1724 e->which = Z_Entry_termInfo;
1725 e->u.termInfo = t = (Z_TermInfo *)
1726 odr_malloc(assoc->encode, sizeof(*t));
1727 t->suggestedAttributes = 0;
1729 t->alternativeTerm = 0;
1730 t->byAttributes = 0;
1731 t->otherTermInfo = 0;
1732 t->globalOccurrences = &bsrr->entries[i].occurrences;
1733 t->term = (Z_Term *)
1734 odr_malloc(assoc->encode, sizeof(*t->term));
1735 t->term->which = Z_Term_general;
1736 t->term->u.general = o =
1737 (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
1738 o->buf = (unsigned char *)
1739 odr_malloc(assoc->encode, o->len = o->size =
1740 strlen(bsrr->entries[i].term));
1741 memcpy(o->buf, bsrr->entries[i].term, o->len);
1742 yaz_log(LOG_DEBUG, " term #%d: '%s' (%d)", i,
1743 bsrr->entries[i].term, bsrr->entries[i].occurrences);
1747 Z_DiagRecs *drecs = diagrecs (assoc,
1748 bsrr->entries[i].errcode,
1749 bsrr->entries[i].errstring);
1750 assert (drecs->num_diagRecs == 1);
1751 e->which = Z_Entry_surrogateDiagnostic;
1752 assert (drecs->diagRecs[0]);
1753 e->u.surrogateDiagnostic = drecs->diagRecs[0];
1760 ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
1761 ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
1766 static Z_APDU *process_sortRequest(association *assoc, request *reqb,
1769 Z_SortRequest *req = reqb->request->u.sortRequest;
1770 Z_SortResponse *res = (Z_SortResponse *)
1771 odr_malloc (assoc->encode, sizeof(*res));
1772 bend_sort_rr *bsrr = (bend_sort_rr *)
1773 odr_malloc (assoc->encode, sizeof(*bsrr));
1775 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1777 yaz_log(LOG_LOG, "Got SortRequest.");
1780 bsrr->num_input_setnames = req->num_inputResultSetNames;
1781 bsrr->input_setnames = req->inputResultSetNames;
1783 bsrr->num_input_setnames = req->inputResultSetNames->num_strings;
1784 bsrr->input_setnames = req->inputResultSetNames->strings;
1786 bsrr->referenceId = req->referenceId;
1787 bsrr->output_setname = req->sortedResultSetName;
1788 bsrr->sort_sequence = req->sortSequence;
1789 bsrr->stream = assoc->encode;
1790 bsrr->print = assoc->print;
1792 bsrr->sort_status = Z_SortStatus_failure;
1794 bsrr->errstring = 0;
1796 (*assoc->init->bend_sort)(assoc->backend, bsrr);
1798 res->referenceId = bsrr->referenceId;
1799 res->sortStatus = (int *)
1800 odr_malloc (assoc->encode, sizeof(*res->sortStatus));
1801 *res->sortStatus = bsrr->sort_status;
1802 res->resultSetStatus = 0;
1805 Z_DiagRecs *dr = diagrecs (assoc, bsrr->errcode, bsrr->errstring);
1807 res->diagnostics = dr->diagRecs;
1808 res->num_diagnostics = dr->num_diagRecs;
1810 res->diagnostics = dr;
1816 res->num_diagnostics = 0;
1818 res->diagnostics = 0;
1822 apdu->which = Z_APDU_sortResponse;
1823 apdu->u.sortResponse = res;
1827 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
1830 Z_DeleteResultSetRequest *req = reqb->request->u.deleteResultSetRequest;
1831 Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
1832 odr_malloc (assoc->encode, sizeof(*res));
1833 bend_delete_rr *bdrr = (bend_delete_rr *)
1834 odr_malloc (assoc->encode, sizeof(*bdrr));
1835 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1837 yaz_log(LOG_LOG, "Got DeleteRequest.");
1839 bdrr->num_setnames = req->num_resultSetList;
1840 bdrr->setnames = req->resultSetList;
1841 bdrr->stream = assoc->encode;
1842 bdrr->print = assoc->print;
1843 bdrr->function = *req->deleteFunction;
1844 bdrr->referenceId = req->referenceId;
1846 if (bdrr->num_setnames > 0)
1849 bdrr->statuses = (int*)
1850 odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
1851 bdrr->num_setnames);
1852 for (i = 0; i < bdrr->num_setnames; i++)
1853 bdrr->statuses[i] = 0;
1855 (*assoc->init->bend_delete)(assoc->backend, bdrr);
1857 res->referenceId = req->referenceId;
1859 res->deleteOperationStatus = (int *)
1860 odr_malloc (assoc->encode, sizeof(*res->deleteOperationStatus));
1861 *res->deleteOperationStatus = bdrr->delete_status;
1863 res->deleteListStatuses = 0;
1864 if (bdrr->num_setnames > 0)
1867 res->deleteListStatuses = (Z_ListStatuses *)
1868 odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
1869 res->deleteListStatuses->num = bdrr->num_setnames;
1870 res->deleteListStatuses->elements =
1872 odr_malloc (assoc->encode,
1873 sizeof(*res->deleteListStatuses->elements) *
1874 bdrr->num_setnames);
1875 for (i = 0; i<bdrr->num_setnames; i++)
1877 res->deleteListStatuses->elements[i] =
1879 odr_malloc (assoc->encode,
1880 sizeof(**res->deleteListStatuses->elements));
1881 res->deleteListStatuses->elements[i]->status = bdrr->statuses+i;
1882 res->deleteListStatuses->elements[i]->id =
1883 odr_strdup (assoc->encode, bdrr->setnames[i]);
1887 res->numberNotDeleted = 0;
1888 res->bulkStatuses = 0;
1889 res->deleteMessage = 0;
1892 apdu->which = Z_APDU_deleteResultSetResponse;
1893 apdu->u.deleteResultSetResponse = res;
1897 static void process_close(association *assoc, request *reqb)
1899 Z_Close *req = reqb->request->u.close;
1900 static char *reasons[] =
1907 "securityViolation",
1914 yaz_log(LOG_LOG, "Got Close, reason %s, message %s",
1915 reasons[*req->closeReason], req->diagnosticInformation ?
1916 req->diagnosticInformation : "NULL");
1917 if (assoc->version < 3) /* to make do_force respond with close */
1919 do_close_req(assoc, Z_Close_finished,
1920 "Association terminated by client", reqb);
1923 void save_referenceId (request *reqb, Z_ReferenceId *refid)
1927 reqb->len_refid = refid->len;
1928 reqb->refid = (char *)nmem_malloc (reqb->request_mem, refid->len);
1929 memcpy (reqb->refid, refid->buf, refid->len);
1933 reqb->len_refid = 0;
1938 void bend_request_send (bend_association a, bend_request req, Z_APDU *res)
1940 process_response (a, req, res);
1943 bend_request bend_request_mk (bend_association a)
1945 request *nreq = request_get (&a->outgoing);
1946 nreq->request_mem = nmem_create ();
1950 Z_ReferenceId *bend_request_getid (ODR odr, bend_request req)
1955 id = (Odr_oct *)odr_malloc (odr, sizeof(*odr));
1956 id->buf = (unsigned char *)odr_malloc (odr, req->len_refid);
1957 id->len = id->size = req->len_refid;
1958 memcpy (id->buf, req->refid, req->len_refid);
1962 void bend_request_destroy (bend_request *req)
1964 nmem_destroy((*req)->request_mem);
1965 request_release(*req);
1969 int bend_backend_respond (bend_association a, bend_request req)
1973 r = process_request (a, req, &msg);
1975 logf (LOG_WARN, "%s", msg);
1979 void bend_request_setdata(bend_request r, void *p)
1984 void *bend_request_getdata(bend_request r)
1986 return r->clientData;
1989 static Z_APDU *process_segmentRequest (association *assoc, request *reqb)
1991 bend_segment_rr request;
1993 request.segment = reqb->request->u.segmentRequest;
1994 request.stream = assoc->encode;
1995 request.decode = assoc->decode;
1996 request.print = assoc->print;
1997 request.association = assoc;
1999 (*assoc->init->bend_segment)(assoc->backend, &request);
2004 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd)
2006 bend_esrequest_rr esrequest;
2008 Z_ExtendedServicesRequest *req = reqb->request->u.extendedServicesRequest;
2009 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
2011 Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
2013 yaz_log(LOG_DEBUG,"inside Process esRequest");
2015 esrequest.esr = reqb->request->u.extendedServicesRequest;
2016 esrequest.stream = assoc->encode;
2017 esrequest.decode = assoc->decode;
2018 esrequest.print = assoc->print;
2019 esrequest.errcode = 0;
2020 esrequest.errstring = NULL;
2021 esrequest.request = reqb;
2022 esrequest.association = assoc;
2023 esrequest.referenceId = req->referenceId;
2025 (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
2027 /* If the response is being delayed, return NULL */
2028 if (esrequest.request == NULL)
2031 resp->referenceId = req->referenceId;
2033 if (esrequest.errcode == -1)
2035 /* Backend service indicates request will be processed */
2036 yaz_log(LOG_DEBUG,"Request could be processed...Accepted !");
2037 *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
2039 else if (esrequest.errcode == 0)
2041 /* Backend service indicates request will be processed */
2042 yaz_log(LOG_DEBUG,"Request could be processed...Done !");
2043 *resp->operationStatus = Z_ExtendedServicesResponse_done;
2047 Z_DiagRecs *diagRecs = diagrecs (assoc, esrequest.errcode,
2048 esrequest.errstring);
2050 /* Backend indicates error, request will not be processed */
2051 yaz_log(LOG_DEBUG,"Request could not be processed...failure !");
2052 *resp->operationStatus = Z_ExtendedServicesResponse_failure;
2053 resp->num_diagnostics = diagRecs->num_diagRecs;
2054 resp->diagnostics = diagRecs->diagRecs;
2056 /* Do something with the members of bend_extendedservice */
2058 yaz_log(LOG_DEBUG,"Send the result apdu");