2 * Copyright (c) 1995-2001, Index Data
3 * See the file LICENSE for details.
6 * Revision 1.116 2001-05-16 07:21:36 adam
7 * Accept any OID for record syntax.
9 * Revision 1.115 2001/03/25 21:55:12 adam
10 * Added odr_intdup. Ztest server returns TaskPackage for ItemUpdate.
12 * Revision 1.114 2001/02/21 13:46:53 adam
15 * Revision 1.113 2001/01/30 21:34:17 adam
16 * Added step-size for Scan backend interface.
18 * Revision 1.112 2001/01/29 09:38:22 adam
19 * Fixed bug that made the frontend server crash when no attribute set
20 * was specified for scan.
22 * Revision 1.111 2000/11/23 10:58:32 adam
23 * SSL comstack support. Separate POSIX thread support library.
25 * Revision 1.110 2000/10/02 13:05:32 adam
26 * Fixed bug introduced by previous commit.
28 * Revision 1.109 2000/10/02 11:07:44 adam
29 * Added peer_name member for bend_init handler. Changed the YAZ
30 * client so that tcp: can be avoided in target spec.
32 * Revision 1.108 2000/09/04 08:58:15 adam
33 * Added prefix yaz_ for most logging utility functions.
35 * Revision 1.107 2000/08/31 10:20:12 adam
36 * Added member request_format and output_format for backend fetch method.
38 * Revision 1.106 2000/08/31 09:51:25 adam
39 * Added record_syntax member for fetch method (raw OID).
41 * Revision 1.105 2000/07/06 10:38:47 adam
42 * Enhanced option --enable-tcpd.
44 * Revision 1.104 2000/04/05 07:39:55 adam
45 * Added shared library support (libtool).
47 * Revision 1.103 2000/03/20 19:06:25 adam
48 * Added Segment request for fronend server. Work on admin for client.
50 * Revision 1.102 2000/03/15 12:59:49 adam
51 * Added handle member to statserv_control.
53 * Revision 1.101 2000/01/12 14:36:07 adam
54 * Added printing stream (ODR) for backend functions.
56 * Revision 1.100 1999/12/16 23:36:19 adam
57 * Implemented ILL protocol. Minor updates ASN.1 compiler.
59 * Revision 1.99 1999/11/30 13:47:12 adam
60 * Improved installation. Moved header files to include/yaz.
62 * Revision 1.98 1999/11/29 15:12:27 adam
63 * Changed the way implementationName - and version is set.
65 * Revision 1.96 1999/11/04 14:58:44 adam
66 * Added status elements for backend delete result set handler.
67 * Updated delete result result set command for client.
69 * Revision 1.95 1999/10/11 10:01:24 adam
70 * Implemented bend_sort_rr handler for frontend server.
72 * Revision 1.94 1999/08/27 09:40:32 adam
73 * Renamed logf function to yaz_log. Removed VC++ project files.
75 * Revision 1.93 1999/07/06 12:17:15 adam
76 * Added option -1 that runs server once (for profiling purposes).
78 * Revision 1.92 1999/06/17 10:54:45 adam
79 * Added facility to specify implementation version - and name
82 * Revision 1.91 1999/06/01 14:29:12 adam
83 * Work on Extended Services.
85 * Revision 1.90 1999/05/27 13:02:20 adam
86 * Assigned OID for old DB Update (VAL_DBUPDATE0).
88 * Revision 1.89 1999/05/26 15:24:26 adam
89 * Fixed minor bugs regarding DB Update (introduced by previous commit).
91 * Revision 1.88 1999/04/20 09:56:48 adam
92 * Added 'name' paramter to encoder/decoder routines (typedef Odr_fun).
93 * Modified all encoders/decoders to reflect this change.
95 * Revision 1.87 1999/03/31 11:18:25 adam
96 * Implemented odr_strdup. Added Reference ID to backend server API.
98 * Revision 1.86 1999/02/02 13:57:38 adam
99 * Uses preprocessor define WIN32 instead of WINDOWS to build code
100 * for Microsoft WIN32.
102 * Revision 1.85 1998/11/17 09:52:59 adam
103 * Fixed minor bug (introduced by previous commit).
105 * Revision 1.84 1998/11/16 16:02:32 adam
106 * Added loggin utilies, log_rpn_query and log_scan_term. These used
107 * to be part of Zebra.
109 * Revision 1.83 1998/11/03 10:09:36 adam
110 * Fixed bug regarding YC.
112 * Revision 1.82 1998/10/20 14:00:30 quinn
115 * Revision 1.81 1998/10/13 16:12:24 adam
116 * Added support for Surrogate Diagnostics for Scan Term entries.
118 * Revision 1.80 1998/09/02 12:41:53 adam
119 * Added decode stream in bend search structures.
121 * Revision 1.79 1998/08/19 16:10:08 adam
122 * Changed som member names of DeleteResultSetRequest/Response.
124 * Revision 1.78 1998/08/03 10:23:55 adam
125 * Fixed bug regarding Options for Sort.
127 * Revision 1.77 1998/07/20 12:38:42 adam
128 * Implemented delete result set service to server API.
130 * Revision 1.76 1998/05/27 16:57:07 adam
131 * Support for surrogate diagnostic records added for bend_fetch.
133 * Revision 1.75 1998/05/18 10:13:07 adam
134 * Fixed call to es_request handler - extra argument was passed.
136 * Revision 1.74 1998/03/31 15:13:20 adam
137 * Development towards compiled ASN.1.
139 * Revision 1.73 1998/03/31 11:07:45 adam
140 * Furhter work on UNIverse resource report.
141 * Added Extended Services handling in frontend server.
143 * Revision 1.72 1998/02/11 11:53:35 adam
144 * Changed code so that it compiles as C++.
146 * Revision 1.71 1998/02/10 11:03:57 adam
147 * Added support for extended handlers in backend server interface.
149 * Revision 1.70 1998/01/29 13:15:35 adam
150 * Implemented sort for the backend interface.
152 * Revision 1.69 1997/09/30 11:48:12 adam
153 * Fixed bug introduced by previous commit.
155 * Revision 1.68 1997/09/29 13:18:59 adam
156 * Added function, oid_ent_to_oid, to replace the function
157 * oid_getoidbyent, which is not thread safe.
159 * Revision 1.67 1997/09/17 12:10:40 adam
162 * Revision 1.66 1997/09/05 15:26:44 adam
163 * Added ODR encode in search and scen bend request structures.
164 * Fixed a few enums that caused trouble with C++.
166 * Revision 1.65 1997/09/01 08:53:01 adam
167 * New windows NT/95 port using MSV5.0. The test server 'ztest' was
168 * moved a separate directory. MSV5.0 project server.dsp created.
169 * As an option, the server can now operate as an NT service.
171 * Revision 1.64 1997/04/30 08:52:11 quinn
174 * Revision 1.63 1996/10/11 11:57:26 quinn
177 * Revision 1.62 1996/07/06 19:58:35 quinn
178 * System headerfiles gathered in yconfig
180 * Revision 1.61 1996/06/10 08:56:16 quinn
183 * Revision 1.60 1996/05/30 11:03:10 quinn
184 * Fixed NextresultSetPosition bug fixed.
186 * Revision 1.59 1996/05/14 09:26:46 quinn
187 * Added attribute set to scan backend
189 * Revision 1.58 1996/02/20 12:53:04 quinn
192 * Revision 1.57 1996/01/02 08:57:47 quinn
193 * Changed enums in the ASN.1 .h files to #defines. Changed oident.class to oclass
195 * Revision 1.56 1995/12/14 11:09:57 quinn
198 * Revision 1.55 1995/11/08 17:41:37 quinn
201 * Revision 1.54 1995/11/08 15:11:29 quinn
202 * Log of close transmit.
204 * Revision 1.53 1995/11/01 13:54:58 quinn
207 * Revision 1.52 1995/11/01 12:19:13 quinn
208 * Second attempt to fix same bug.
210 * Revision 1.50 1995/10/25 16:58:32 quinn
213 * Revision 1.49 1995/10/16 13:51:53 quinn
214 * Changes to provide Especs to the backend.
216 * Revision 1.48 1995/10/06 08:51:20 quinn
217 * Added Write-buffer.
219 * Revision 1.47 1995/08/29 14:24:16 quinn
220 * Added second half of close-handshake
222 * Revision 1.46 1995/08/29 11:17:58 quinn
223 * Added code to receive close
225 * Revision 1.45 1995/08/21 09:11:00 quinn
226 * Smallish fixes to suppport new formats.
228 * Revision 1.44 1995/08/17 12:45:25 quinn
229 * Fixed minor problems with GRS-1. Added support in c&s.
231 * Revision 1.43 1995/08/15 12:00:31 quinn
234 * Revision 1.42 1995/08/15 11:16:50 quinn
236 * Revision 1.41 1995/08/02 10:23:06 quinn
239 * Revision 1.40 1995/07/31 14:34:26 quinn
240 * Fixed bug in process_searchResponse (numberOfRecordsReturned).
242 * Revision 1.39 1995/06/27 13:21:00 quinn
245 * Revision 1.38 1995/06/19 12:39:11 quinn
246 * Fixed bug in timeout code. Added BER dumper.
248 * Revision 1.37 1995/06/16 13:16:14 quinn
249 * Fixed Defaultdiagformat.
251 * Revision 1.36 1995/06/16 10:31:36 quinn
252 * Added session timeout.
254 * Revision 1.35 1995/06/15 07:45:14 quinn
257 * Revision 1.34 1995/06/14 15:26:46 quinn
258 * *** empty log message ***
260 * Revision 1.33 1995/06/06 14:57:05 quinn
261 * Better diagnostics.
263 * Revision 1.32 1995/06/06 08:41:44 quinn
264 * Better diagnostics.
266 * Revision 1.31 1995/06/06 08:15:37 quinn
269 * Revision 1.30 1995/06/05 10:53:32 quinn
270 * Added a better SCAN.
272 * Revision 1.29 1995/06/01 11:25:03 quinn
275 * Revision 1.28 1995/06/01 11:21:01 quinn
276 * Attempting to fix a bug in pack-records. replaced break with continue
277 * for large records, according to standard.
279 * Revision 1.27 1995/05/29 08:12:06 quinn
282 * Revision 1.26 1995/05/18 13:02:12 quinn
285 * Revision 1.25 1995/05/17 08:42:26 quinn
286 * Transfer auth info to backend. Allow backend to reject init gracefully.
288 * Revision 1.24 1995/05/16 08:51:04 quinn
289 * License, documentation, and memory fixes
291 * Revision 1.23 1995/05/15 13:25:10 quinn
294 * Revision 1.22 1995/05/15 11:56:39 quinn
295 * Asynchronous facilities. Restructuring of seshigh code.
297 * Revision 1.21 1995/05/02 08:53:19 quinn
298 * Trying in vain to fix comm with ISODE
300 * Revision 1.20 1995/04/20 15:13:00 quinn
303 * Revision 1.19 1995/04/18 08:15:34 quinn
304 * Added dynamic memory allocation on encoding (whew). Code is now somewhat
305 * neater. We'll make the same change for decoding one day.
307 * Revision 1.18 1995/04/17 11:28:25 quinn
310 * Revision 1.17 1995/04/10 10:23:36 quinn
311 * Some work to add scan and other things.
313 * Revision 1.16 1995/03/31 09:18:55 quinn
316 * Revision 1.15 1995/03/30 14:03:23 quinn
317 * Added RFC1006 as separate library
319 * Revision 1.14 1995/03/30 12:18:17 quinn
322 * Revision 1.13 1995/03/30 09:09:24 quinn
323 * Added state-handle and some support for asynchronous activities.
325 * Revision 1.12 1995/03/29 15:40:16 quinn
326 * Ongoing work. Statserv is now dynamic by default
328 * Revision 1.11 1995/03/28 09:16:21 quinn
329 * Added record packing to the search request
331 * Revision 1.10 1995/03/27 08:34:24 quinn
332 * Added dynamic server functionality.
333 * Released bindings to session.c (is now redundant)
335 * Revision 1.9 1995/03/22 15:01:26 quinn
336 * Adjusting record packing.
338 * Revision 1.8 1995/03/22 10:13:21 quinn
339 * Working on record packer
341 * Revision 1.7 1995/03/21 15:53:31 quinn
344 * Revision 1.6 1995/03/21 12:30:09 quinn
345 * Beginning to add support for record packing.
347 * Revision 1.5 1995/03/17 10:44:13 quinn
348 * Added catch of null-string in makediagrec
350 * Revision 1.4 1995/03/17 10:18:08 quinn
351 * Added memory management.
353 * Revision 1.3 1995/03/16 17:42:39 quinn
356 * Revision 1.2 1995/03/16 13:29:01 quinn
357 * Partitioned server.
359 * Revision 1.1 1995/03/15 16:02:10 quinn
360 * Modded session.c to seshigh.c
365 * Frontend server logic.
367 * This code receives incoming APDUs, and handles client requests by means
368 * of the backend API.
370 * Some of the code is getting quite involved, compared to simpler servers -
371 * primarily because it is asynchronous both in the communication with
372 * the user and the backend. We think the complexity will pay off in
373 * the form of greater flexibility when more asynchronous facilities
376 * Memory management has become somewhat involved. In the simple case, where
377 * only one PDU is pending at a time, it will simply reuse the same memory,
378 * once it has found its working size. When we enable multiple concurrent
379 * operations, perhaps even with multiple parallel calls to the backend, it
380 * will maintain a pool of buffers for encoding and decoding, trying to
381 * minimize memory allocation/deallocation during normal operation.
383 * TODOs include (and will be done in order of public interest):
385 * Support for EXPLAIN - provide simple meta-database system.
386 * Support for access control.
387 * Support for resource control.
388 * Support for extended services - primarily Item Order.
389 * Rest of Z39.50-1994
402 #include <yaz/yconfig.h>
403 #include <yaz/xmalloc.h>
404 #include <yaz/comstack.h>
407 #include <yaz/proto.h>
410 #include <yaz/logrpn.h>
411 #include <yaz/statserv.h>
413 #include <yaz/backend.h>
415 static int process_request(association *assoc, request *req, char **msg);
416 void backend_response(IOCHAN i, int event);
417 static int process_response(association *assoc, request *req, Z_APDU *res);
418 static Z_APDU *process_initRequest(association *assoc, request *reqb);
419 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
421 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
422 bend_search_rr *bsrr, int *fd);
423 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
425 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
426 static Z_APDU *process_sortRequest(association *assoc, request *reqb, int *fd);
427 static void process_close(association *assoc, request *reqb);
428 void save_referenceId (request *reqb, Z_ReferenceId *refid);
429 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
431 static Z_APDU *process_segmentRequest (association *assoc, request *reqb);
433 static FILE *apduf = 0; /* for use in static mode */
434 static statserv_options_block *control_block = 0;
436 /* Chas: Added in from DALI */
437 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd);
438 /* Chas: End of addition from DALI */
441 * Create and initialize a new association-handle.
442 * channel : iochannel for the current line.
443 * link : communications channel.
444 * Returns: 0 or a new association handle.
446 association *create_association(IOCHAN channel, COMSTACK link)
451 control_block = statserv_getcontrol();
452 if (!(anew = (association *)xmalloc(sizeof(*anew))))
455 anew->client_chan = channel;
456 anew->client_link = link;
457 anew->cs_get_mask = 0;
458 anew->cs_put_mask = 0;
459 anew->cs_accept_mask = 0;
460 if (!(anew->decode = odr_createmem(ODR_DECODE)) ||
461 !(anew->encode = odr_createmem(ODR_ENCODE)))
463 if (*control_block->apdufile)
468 strcpy(filename, control_block->apdufile);
469 if (!(anew->print = odr_createmem(ODR_PRINT)))
471 if (*control_block->apdufile != '-')
473 strcpy(filename, control_block->apdufile);
474 if (!control_block->dynamic)
478 if (!(apduf = fopen(filename, "w")))
480 yaz_log(LOG_WARN|LOG_ERRNO, "%s", filename);
483 setvbuf(apduf, 0, _IONBF, 0);
489 sprintf(filename + strlen(filename), ".%d", getpid());
490 if (!(f = fopen(filename, "w")))
492 yaz_log(LOG_WARN|LOG_ERRNO, "%s", filename);
495 setvbuf(f, 0, _IONBF, 0);
497 odr_setprint(anew->print, f);
502 anew->input_buffer = 0;
503 anew->input_buffer_len = 0;
505 anew->state = ASSOC_NEW;
506 request_initq(&anew->incoming);
507 request_initq(&anew->outgoing);
508 anew->proto = cs_getproto(link);
513 * Free association and release resources.
515 void destroy_association(association *h)
517 statserv_options_block *cb = statserv_getcontrol();
520 odr_destroy(h->decode);
521 odr_destroy(h->encode);
523 odr_destroy(h->print);
525 xfree(h->input_buffer);
527 (*cb->bend_close)(h->backend);
528 while (request_deq(&h->incoming));
529 while (request_deq(&h->outgoing));
530 request_delq(&h->incoming);
531 request_delq(&h->outgoing);
533 if (control_block && control_block->one_shot)
537 static void do_close_req(association *a, int reason, char *message,
541 Z_Close *cls = zget_Close(a->encode);
543 /* Purge request queue */
544 while (request_deq(&a->incoming));
545 while (request_deq(&a->outgoing));
548 yaz_log(LOG_LOG, "Sending Close PDU, reason=%d, message=%s",
549 reason, message ? message : "none");
550 apdu.which = Z_APDU_close;
552 *cls->closeReason = reason;
553 cls->diagnosticInformation = message;
554 process_response(a, req, &apdu);
555 iochan_settimeout(a->client_chan, 60);
559 yaz_log(LOG_DEBUG, "v2 client. No Close PDU");
560 iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
562 a->state = ASSOC_DEAD;
565 static void do_close(association *a, int reason, char *message)
567 do_close_req (a, reason, message, request_get(&a->outgoing));
571 * This is where PDUs from the client are read and the further
572 * processing is initiated. Flow of control moves down through the
573 * various process_* functions below, until the encoded result comes back up
574 * to the output handler in here.
576 * h : the I/O channel that has an outstanding event.
577 * event : the current outstanding event.
579 void ir_session(IOCHAN h, int event)
582 association *assoc = (association *)iochan_getdata(h);
583 COMSTACK conn = assoc->client_link;
586 assert(h && conn && assoc);
587 if (event == EVENT_TIMEOUT)
589 if (assoc->state != ASSOC_UP)
591 yaz_log(LOG_LOG, "Final timeout - closing connection.");
593 destroy_association(assoc);
598 yaz_log(LOG_LOG, "Session idle too long. Sending close.");
599 do_close(assoc, Z_Close_lackOfActivity, 0);
603 if (event & assoc->cs_accept_mask)
605 yaz_log (LOG_DEBUG, "ir_session (accept)");
606 if (!cs_accept (conn))
608 yaz_log (LOG_LOG, "accept failed");
609 destroy_association(assoc);
612 iochan_clearflag (h, EVENT_OUTPUT|EVENT_OUTPUT);
613 if (conn->io_pending)
614 { /* cs_accept didn't complete */
615 assoc->cs_accept_mask =
616 ((conn->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
617 ((conn->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
619 iochan_setflag (h, assoc->cs_accept_mask);
622 { /* cs_accept completed. Prepare for reading (cs_get) */
623 assoc->cs_accept_mask = 0;
624 assoc->cs_get_mask = EVENT_INPUT;
625 iochan_setflag (h, assoc->cs_get_mask);
629 if ((event & assoc->cs_get_mask) || (event & EVENT_WORK)) /* input */
631 if ((assoc->cs_put_mask & EVENT_INPUT) == 0 && (event & assoc->cs_get_mask))
633 yaz_log(LOG_DEBUG, "ir_session (input)");
634 /* We aren't speaking to this fellow */
635 if (assoc->state == ASSOC_DEAD)
637 yaz_log(LOG_LOG, "Closed connection after reject");
639 destroy_association(assoc);
643 assoc->cs_get_mask = EVENT_INPUT;
644 if ((res = cs_get(conn, &assoc->input_buffer,
645 &assoc->input_buffer_len)) <= 0)
647 yaz_log(LOG_LOG, "Connection closed by client");
649 destroy_association(assoc);
653 else if (res == 1) /* incomplete read - wait for more */
655 if (conn->io_pending & CS_WANT_WRITE)
656 assoc->cs_get_mask |= EVENT_OUTPUT;
657 iochan_setflag(h, assoc->cs_get_mask);
660 if (cs_more(conn)) /* more stuff - call us again later, please */
661 iochan_setevent(h, EVENT_INPUT);
663 /* we got a complete PDU. Let's decode it */
664 yaz_log(LOG_DEBUG, "Got PDU, %d bytes", res);
665 req = request_get(&assoc->incoming); /* get a new request structure */
666 odr_reset(assoc->decode);
667 odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
668 if (!z_APDU(assoc->decode, &req->request, 0, 0))
670 yaz_log(LOG_LOG, "ODR error on incoming PDU: %s [near byte %d] ",
671 odr_errmsg(odr_geterror(assoc->decode)),
672 odr_offset(assoc->decode));
673 yaz_log(LOG_LOG, "PDU dump:");
674 odr_dumpBER(yaz_log_file(), assoc->input_buffer, res);
675 do_close(assoc, Z_Close_protocolError, "Malformed package");
678 req->request_mem = odr_extract_mem(assoc->decode);
679 if (assoc->print && !z_APDU(assoc->print, &req->request, 0, 0))
681 yaz_log(LOG_WARN, "ODR print error: %s",
682 odr_errmsg(odr_geterror(assoc->print)));
683 odr_reset(assoc->print);
685 request_enq(&assoc->incoming, req);
688 /* can we do something yet? */
689 req = request_head(&assoc->incoming);
690 if (req->state == REQUEST_IDLE)
693 request_deq(&assoc->incoming);
694 if (process_request(assoc, req, &msg) < 0)
695 do_close_req(assoc, Z_Close_systemProblem, msg, req);
698 if (event & assoc->cs_put_mask)
700 request *req = request_head(&assoc->outgoing);
702 assoc->cs_put_mask = 0;
703 yaz_log(LOG_DEBUG, "ir_session (output)");
704 req->state = REQUEST_PENDING;
705 switch (res = cs_put(conn, req->response, req->len_response))
708 yaz_log(LOG_LOG, "Connection closed by client");
710 destroy_association(assoc);
713 case 0: /* all sent - release the request structure */
714 yaz_log(LOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
715 nmem_destroy(req->request_mem);
716 request_deq(&assoc->outgoing);
717 request_release(req);
718 if (!request_head(&assoc->outgoing))
719 { /* restore mask for cs_get operation ... */
720 iochan_clearflag(h, EVENT_OUTPUT|EVENT_INPUT);
721 iochan_setflag(h, assoc->cs_get_mask);
725 if (conn->io_pending & CS_WANT_WRITE)
726 assoc->cs_put_mask |= EVENT_OUTPUT;
727 if (conn->io_pending & CS_WANT_READ)
728 assoc->cs_put_mask |= EVENT_INPUT;
729 iochan_setflag(h, assoc->cs_put_mask);
732 if (event & EVENT_EXCEPT)
734 yaz_log(LOG_LOG, "ir_session (exception)");
736 destroy_association(assoc);
742 * Initiate request processing.
744 static int process_request(association *assoc, request *req, char **msg)
750 *msg = "Unknown Error";
751 assert(req && req->state == REQUEST_IDLE);
752 if (req->request->which != Z_APDU_initRequest && !assoc->init)
754 *msg = "Missing InitRequest";
757 switch (req->request->which)
759 case Z_APDU_initRequest:
760 res = process_initRequest(assoc, req); break;
761 case Z_APDU_searchRequest:
762 res = process_searchRequest(assoc, req, &fd); break;
763 case Z_APDU_presentRequest:
764 res = process_presentRequest(assoc, req, &fd); break;
765 case Z_APDU_scanRequest:
766 if (assoc->init->bend_scan)
767 res = process_scanRequest(assoc, req, &fd);
770 *msg = "Cannot handle Scan APDU";
774 case Z_APDU_extendedServicesRequest:
775 if (assoc->init->bend_esrequest)
776 res = process_ESRequest(assoc, req, &fd);
779 *msg = "Cannot handle Extended Services APDU";
783 case Z_APDU_sortRequest:
784 if (assoc->init->bend_sort)
785 res = process_sortRequest(assoc, req, &fd);
788 *msg = "Cannot handle Sort APDU";
793 process_close(assoc, req);
795 case Z_APDU_deleteResultSetRequest:
796 if (assoc->init->bend_delete)
797 res = process_deleteRequest(assoc, req, &fd);
800 *msg = "Cannot handle Delete APDU";
804 case Z_APDU_segmentRequest:
805 if (assoc->init->bend_segment)
807 res = process_segmentRequest (assoc, req);
811 *msg = "Cannot handle Segment APDU";
816 *msg = "Bad APDU received";
821 yaz_log(LOG_DEBUG, " result immediately available");
822 retval = process_response(assoc, req, res);
826 yaz_log(LOG_DEBUG, " result unavailble");
829 else /* no result yet - one will be provided later */
833 /* Set up an I/O handler for the fd supplied by the backend */
835 yaz_log(LOG_DEBUG, " establishing handler for result");
836 req->state = REQUEST_PENDING;
837 if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT)))
839 iochan_setdata(chan, assoc);
846 * Handle message from the backend.
848 void backend_response(IOCHAN i, int event)
850 association *assoc = (association *)iochan_getdata(i);
851 request *req = request_head(&assoc->incoming);
855 yaz_log(LOG_DEBUG, "backend_response");
856 assert(assoc && req && req->state != REQUEST_IDLE);
857 /* determine what it is we're waiting for */
858 switch (req->request->which)
860 case Z_APDU_searchRequest:
861 res = response_searchRequest(assoc, req, 0, &fd); break;
863 case Z_APDU_presentRequest:
864 res = response_presentRequest(assoc, req, 0, &fd); break;
865 case Z_APDU_scanRequest:
866 res = response_scanRequest(assoc, req, 0, &fd); break;
869 yaz_log(LOG_WARN, "Serious programmer's lapse or bug");
872 if ((res && process_response(assoc, req, res) < 0) || fd < 0)
874 yaz_log(LOG_LOG, "Fatal error when talking to backend");
875 do_close(assoc, Z_Close_systemProblem, 0);
879 else if (!res) /* no result yet - try again later */
881 yaz_log(LOG_DEBUG, " no result yet");
882 iochan_setfd(i, fd); /* in case fd has changed */
887 * Encode response, and transfer the request structure to the outgoing queue.
889 static int process_response(association *assoc, request *req, Z_APDU *res)
891 odr_setbuf(assoc->encode, req->response, req->size_response, 1);
893 if (assoc->print && !z_APDU(assoc->print, &res, 0, 0))
895 yaz_log(LOG_WARN, "ODR print error: %s",
896 odr_errmsg(odr_geterror(assoc->print)));
897 odr_reset(assoc->print);
899 if (!z_APDU(assoc->encode, &res, 0, 0))
901 yaz_log(LOG_WARN, "ODR error when encoding response: %s",
902 odr_errmsg(odr_geterror(assoc->decode)));
905 req->response = odr_getbuf(assoc->encode, &req->len_response,
906 &req->size_response);
907 odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
908 odr_reset(assoc->encode);
909 req->state = REQUEST_IDLE;
910 request_enq(&assoc->outgoing, req);
911 /* turn the work over to the ir_session handler */
912 iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
913 assoc->cs_put_mask = EVENT_OUTPUT;
914 /* Is there more work to be done? give that to the input handler too */
916 if (request_head(&assoc->incoming))
918 yaz_log (LOG_DEBUG, "more work to be done");
919 iochan_setevent(assoc->client_chan, EVENT_WORK);
926 * Handle init request.
927 * At the moment, we don't check the options
928 * anywhere else in the code - we just try not to do anything that would
929 * break a naive client. We'll toss 'em into the association block when
930 * we need them there.
932 static Z_APDU *process_initRequest(association *assoc, request *reqb)
934 statserv_options_block *cb = statserv_getcontrol();
935 Z_InitRequest *req = reqb->request->u.initRequest;
936 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
937 Z_InitResponse *resp = apdu->u.initResponse;
938 bend_initresult *binitres;
942 assoc->init = (bend_initrequest *) xmalloc (sizeof(*assoc->init));
944 yaz_log(LOG_LOG, "Got initRequest");
945 if (req->implementationId)
946 yaz_log(LOG_LOG, "Id: %s", req->implementationId);
947 if (req->implementationName)
948 yaz_log(LOG_LOG, "Name: %s", req->implementationName);
949 if (req->implementationVersion)
950 yaz_log(LOG_LOG, "Version: %s", req->implementationVersion);
952 assoc->init->stream = assoc->encode;
953 assoc->init->print = assoc->print;
954 assoc->init->auth = req->idAuthentication;
955 assoc->init->referenceId = req->referenceId;
956 assoc->init->implementation_version = 0;
957 assoc->init->implementation_name = 0;
958 assoc->init->bend_sort = NULL;
959 assoc->init->bend_search = NULL;
960 assoc->init->bend_present = NULL;
961 assoc->init->bend_esrequest = NULL;
962 assoc->init->bend_delete = NULL;
963 assoc->init->bend_scan = NULL;
964 assoc->init->bend_segment = NULL;
965 assoc->init->bend_fetch = NULL;
967 assoc->init->peer_name =
968 odr_strdup (assoc->encode, cs_addrstr(assoc->client_link));
969 if (!(binitres = (*cb->bend_init)(assoc->init)))
971 yaz_log(LOG_WARN, "Bad response from backend.");
975 assoc->backend = binitres->handle;
976 if ((assoc->init->bend_sort))
977 yaz_log (LOG_DEBUG, "Sort handler installed");
978 if ((assoc->init->bend_search))
979 yaz_log (LOG_DEBUG, "Search handler installed");
980 if ((assoc->init->bend_present))
981 yaz_log (LOG_DEBUG, "Present handler installed");
982 if ((assoc->init->bend_esrequest))
983 yaz_log (LOG_DEBUG, "ESRequest handler installed");
984 if ((assoc->init->bend_delete))
985 yaz_log (LOG_DEBUG, "Delete handler installed");
986 if ((assoc->init->bend_scan))
987 yaz_log (LOG_DEBUG, "Scan handler installed");
988 if ((assoc->init->bend_segment))
989 yaz_log (LOG_DEBUG, "Segment handler installed");
991 resp->referenceId = req->referenceId;
993 /* let's tell the client what we can do */
994 if (ODR_MASK_GET(req->options, Z_Options_search))
996 ODR_MASK_SET(resp->options, Z_Options_search);
997 strcat(options, "srch");
999 if (ODR_MASK_GET(req->options, Z_Options_present))
1001 ODR_MASK_SET(resp->options, Z_Options_present);
1002 strcat(options, " prst");
1004 if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
1005 assoc->init->bend_delete)
1007 ODR_MASK_SET(resp->options, Z_Options_delSet);
1008 strcat(options, " del");
1010 if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
1011 assoc->init->bend_esrequest)
1013 ODR_MASK_SET(resp->options, Z_Options_extendedServices);
1014 strcat (options, " extendedServices");
1016 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
1018 ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
1019 strcat(options, " namedresults");
1021 if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
1023 ODR_MASK_SET(resp->options, Z_Options_scan);
1024 strcat(options, " scan");
1026 if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
1028 ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
1029 strcat(options, " concurop");
1031 if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
1033 ODR_MASK_SET(resp->options, Z_Options_sort);
1034 strcat(options, " sort");
1036 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
1038 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
1039 assoc->version = 2; /* 1 & 2 are equivalent */
1041 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
1043 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
1046 if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
1048 ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
1051 yaz_log(LOG_LOG, "Negotiated to v%d: %s", assoc->version, options);
1052 assoc->maximumRecordSize = *req->maximumRecordSize;
1053 if (assoc->maximumRecordSize > control_block->maxrecordsize)
1054 assoc->maximumRecordSize = control_block->maxrecordsize;
1055 assoc->preferredMessageSize = *req->preferredMessageSize;
1056 if (assoc->preferredMessageSize > assoc->maximumRecordSize)
1057 assoc->preferredMessageSize = assoc->maximumRecordSize;
1060 assoc->maximumRecordSize = 3000000;
1061 assoc->preferredMessageSize = 3000000;
1064 resp->preferredMessageSize = &assoc->preferredMessageSize;
1065 resp->maximumRecordSize = &assoc->maximumRecordSize;
1067 resp->implementationName = "GFS";
1069 if (assoc->init->implementation_name)
1072 odr_malloc (assoc->encode,
1073 strlen(assoc->init->implementation_name) + 10 +
1074 strlen(resp->implementationName));
1075 sprintf (nv, "%s / %s",
1076 resp->implementationName, assoc->init->implementation_name);
1077 resp->implementationName = nv;
1079 if (assoc->init->implementation_version)
1082 odr_malloc (assoc->encode,
1083 strlen(assoc->init->implementation_version) + 10 +
1084 strlen(resp->implementationVersion));
1085 sprintf (nv, "YAZ %s / %s",
1086 resp->implementationVersion,
1087 assoc->init->implementation_version);
1088 resp->implementationVersion = nv;
1091 if (binitres->errcode)
1093 yaz_log(LOG_LOG, "Connection rejected by backend.");
1095 assoc->state = ASSOC_DEAD;
1098 assoc->state = ASSOC_UP;
1103 * These functions should be merged.
1106 static void set_addinfo (Z_DefaultDiagFormat *dr, char *addinfo, ODR odr)
1109 dr->which = Z_DefaultDiagFormat_v2Addinfo;
1110 dr->u.v2Addinfo = odr_strdup (odr, addinfo ? addinfo : "");
1112 dr->which = Z_DiagForm_v2AddInfo;
1113 dr->addinfo = odr_strdup (odr, addinfo ? addinfo : "");
1118 * nonsurrogate diagnostic record.
1120 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
1123 Z_Records *rec = (Z_Records *)
1124 odr_malloc (assoc->encode, sizeof(*rec));
1126 int *err = odr_intdup(assoc->encode, error);
1127 Z_DiagRec *drec = (Z_DiagRec *)
1128 odr_malloc (assoc->encode, sizeof(*drec));
1129 Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
1130 odr_malloc (assoc->encode, sizeof(*dr));
1132 bib1.proto = assoc->proto;
1133 bib1.oclass = CLASS_DIAGSET;
1134 bib1.value = VAL_BIB1;
1136 yaz_log(LOG_DEBUG, "Diagnostic: %d -- %s", error, addinfo ? addinfo :
1138 rec->which = Z_Records_NSD;
1140 rec->u.nonSurrogateDiagnostic = dr;
1142 rec->u.nonSurrogateDiagnostic = drec;
1143 drec->which = Z_DiagRec_defaultFormat;
1144 drec->u.defaultFormat = dr;
1146 dr->diagnosticSetId =
1147 odr_oiddup (assoc->encode, oid_ent_to_oid(&bib1, oid));
1148 dr->condition = err;
1149 set_addinfo (dr, addinfo, assoc->encode);
1154 * surrogate diagnostic.
1156 static Z_NamePlusRecord *surrogatediagrec(association *assoc, char *dbname,
1157 int error, char *addinfo)
1160 Z_NamePlusRecord *rec = (Z_NamePlusRecord *)
1161 odr_malloc (assoc->encode, sizeof(*rec));
1162 int *err = odr_intdup(assoc->encode, error);
1164 Z_DiagRec *drec = (Z_DiagRec *)odr_malloc (assoc->encode, sizeof(*drec));
1165 Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
1166 odr_malloc (assoc->encode, sizeof(*dr));
1168 bib1.proto = assoc->proto;
1169 bib1.oclass = CLASS_DIAGSET;
1170 bib1.value = VAL_BIB1;
1172 yaz_log(LOG_DEBUG, "SurrogateDiagnotic: %d -- %s", error, addinfo);
1173 rec->databaseName = dbname;
1174 rec->which = Z_NamePlusRecord_surrogateDiagnostic;
1175 rec->u.surrogateDiagnostic = drec;
1176 drec->which = Z_DiagRec_defaultFormat;
1177 drec->u.defaultFormat = dr;
1178 dr->diagnosticSetId = odr_oiddup (assoc->encode,
1179 oid_ent_to_oid(&bib1, oid));
1180 dr->condition = err;
1181 set_addinfo (dr, addinfo, assoc->encode);
1187 * multiple nonsurrogate diagnostics.
1189 static Z_DiagRecs *diagrecs(association *assoc, int error, char *addinfo)
1192 Z_DiagRecs *recs = (Z_DiagRecs *)odr_malloc (assoc->encode, sizeof(*recs));
1193 int *err = odr_intdup(assoc->encode, error);
1195 Z_DiagRec **recp = (Z_DiagRec **)odr_malloc (assoc->encode, sizeof(*recp));
1196 Z_DiagRec *drec = (Z_DiagRec *)odr_malloc (assoc->encode, sizeof(*drec));
1197 Z_DefaultDiagFormat *rec = (Z_DefaultDiagFormat *)odr_malloc (assoc->encode, sizeof(*rec));
1199 yaz_log(LOG_DEBUG, "DiagRecs: %d -- %s", error, addinfo ? addinfo : "");
1200 bib1.proto = assoc->proto;
1201 bib1.oclass = CLASS_DIAGSET;
1202 bib1.value = VAL_BIB1;
1204 recs->num_diagRecs = 1;
1205 recs->diagRecs = recp;
1207 drec->which = Z_DiagRec_defaultFormat;
1208 drec->u.defaultFormat = rec;
1210 rec->diagnosticSetId = odr_oiddup (assoc->encode,
1211 oid_ent_to_oid(&bib1, oid));
1212 rec->condition = err;
1215 rec->which = Z_DefaultDiagFormat_v2Addinfo;
1216 rec->u.v2Addinfo = odr_strdup (assoc->encode, addinfo ? addinfo : "");
1218 rec->which = Z_DiagForm_v2AddInfo;
1219 rec->addinfo = odr_strdup (assoc->encode, addinfo ? addinfo : "");
1224 static Z_Records *pack_records(association *a, char *setname, int start,
1225 int *num, Z_RecordComposition *comp,
1226 int *next, int *pres, oid_value format,
1227 Z_ReferenceId *referenceId,
1230 int recno, total_length = 0, toget = *num, dumped_records = 0;
1231 Z_Records *records =
1232 (Z_Records *) odr_malloc (a->encode, sizeof(*records));
1233 Z_NamePlusRecordList *reclist =
1234 (Z_NamePlusRecordList *) odr_malloc (a->encode, sizeof(*reclist));
1235 Z_NamePlusRecord **list =
1236 (Z_NamePlusRecord **) odr_malloc (a->encode, sizeof(*list) * toget);
1238 records->which = Z_Records_DBOSD;
1239 records->u.databaseOrSurDiagnostics = reclist;
1240 reclist->num_records = 0;
1241 reclist->records = list;
1242 *pres = Z_PRES_SUCCESS;
1246 yaz_log(LOG_LOG, "Request to pack %d+%d", start, toget);
1247 yaz_log(LOG_DEBUG, "pms=%d, mrs=%d", a->preferredMessageSize,
1248 a->maximumRecordSize);
1249 for (recno = start; reclist->num_records < toget; recno++)
1252 Z_NamePlusRecord *thisrec;
1253 int this_length = 0;
1255 * we get the number of bytes allocated on the stream before any
1256 * allocation done by the backend - this should give us a reasonable
1257 * idea of the total size of the data so far.
1259 total_length = odr_total(a->encode) - dumped_records;
1265 freq.last_in_set = 0;
1266 freq.setname = setname;
1267 freq.surrogate_flag = 0;
1268 freq.number = recno;
1270 freq.request_format = format;
1271 freq.request_format_raw = oid;
1272 freq.output_format = format;
1273 freq.output_format_raw = 0;
1274 freq.stream = a->encode;
1275 freq.print = a->print;
1276 freq.surrogate_flag = 0;
1277 freq.referenceId = referenceId;
1278 (*a->init->bend_fetch)(a->backend, &freq);
1279 /* backend should be able to signal whether error is system-wide
1280 or only pertaining to current record */
1283 if (!freq.surrogate_flag)
1285 *pres = Z_PRES_FAILURE;
1286 return diagrec(a, freq.errcode, freq.errstring);
1288 reclist->records[reclist->num_records] =
1289 surrogatediagrec(a, freq.basename, freq.errcode,
1291 reclist->num_records++;
1292 *next = freq.last_in_set ? 0 : recno + 1;
1296 this_length = freq.len;
1298 this_length = odr_total(a->encode) - total_length;
1299 yaz_log(LOG_DEBUG, " fetched record, len=%d, total=%d",
1300 this_length, total_length);
1301 if (this_length + total_length > a->preferredMessageSize)
1303 /* record is small enough, really */
1304 if (this_length <= a->preferredMessageSize)
1306 yaz_log(LOG_DEBUG, " Dropped last normal-sized record");
1307 *pres = Z_PRES_PARTIAL_2;
1310 /* record can only be fetched by itself */
1311 if (this_length < a->maximumRecordSize)
1313 yaz_log(LOG_DEBUG, " Record > prefmsgsz");
1316 yaz_log(LOG_DEBUG, " Dropped it");
1317 reclist->records[reclist->num_records] =
1318 surrogatediagrec(a, freq.basename, 16, 0);
1319 reclist->num_records++;
1320 *next = freq.last_in_set ? 0 : recno + 1;
1321 dumped_records += this_length;
1325 else /* too big entirely */
1327 yaz_log(LOG_DEBUG, "Record > maxrcdsz");
1328 reclist->records[reclist->num_records] =
1329 surrogatediagrec(a, freq.basename, 17, 0);
1330 reclist->num_records++;
1331 *next = freq.last_in_set ? 0 : recno + 1;
1332 dumped_records += this_length;
1337 if (!(thisrec = (Z_NamePlusRecord *)
1338 odr_malloc(a->encode, sizeof(*thisrec))))
1340 if (!(thisrec->databaseName = (char *)odr_malloc(a->encode,
1341 strlen(freq.basename) + 1)))
1343 strcpy(thisrec->databaseName, freq.basename);
1344 thisrec->which = Z_NamePlusRecord_databaseRecord;
1346 if (freq.output_format_raw)
1348 struct oident *ident = oid_getentbyoid(freq.output_format_raw);
1349 freq.output_format = ident->value;
1351 thisrec->u.databaseRecord = z_ext_record(a->encode, freq.output_format,
1352 freq.record, freq.len);
1353 if (!thisrec->u.databaseRecord)
1355 reclist->records[reclist->num_records] = thisrec;
1356 reclist->num_records++;
1357 *next = freq.last_in_set ? 0 : recno + 1;
1359 *num = reclist->num_records;
1363 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
1366 Z_SearchRequest *req = reqb->request->u.searchRequest;
1367 bend_search_rr *bsrr =
1368 (bend_search_rr *)nmem_malloc (reqb->request_mem, sizeof(*bsrr));
1370 yaz_log(LOG_LOG, "Got SearchRequest.");
1372 bsrr->request = reqb;
1373 bsrr->association = assoc;
1374 bsrr->referenceId = req->referenceId;
1375 save_referenceId (reqb, bsrr->referenceId);
1377 yaz_log (LOG_LOG, "ResultSet '%s'", req->resultSetName);
1378 if (req->databaseNames)
1381 for (i = 0; i < req->num_databaseNames; i++)
1382 yaz_log (LOG_LOG, "Database '%s'", req->databaseNames[i]);
1384 switch (req->query->which)
1386 case Z_Query_type_1: case Z_Query_type_101:
1387 log_rpn_query (req->query->u.type_1);
1389 if (assoc->init->bend_search)
1391 bsrr->setname = req->resultSetName;
1392 bsrr->replace_set = *req->replaceIndicator;
1393 bsrr->num_bases = req->num_databaseNames;
1394 bsrr->basenames = req->databaseNames;
1395 bsrr->query = req->query;
1396 bsrr->stream = assoc->encode;
1397 bsrr->decode = assoc->decode;
1398 bsrr->print = assoc->print;
1401 bsrr->errstring = NULL;
1402 (assoc->init->bend_search)(assoc->backend, bsrr);
1409 bend_searchrequest bsrq;
1410 bend_searchresult *bsrt;
1412 bsrq.setname = req->resultSetName;
1413 bsrq.replace_set = *req->replaceIndicator;
1414 bsrq.num_bases = req->num_databaseNames;
1415 bsrq.basenames = req->databaseNames;
1416 bsrq.query = req->query;
1417 bsrq.referenceId = req->referenceId;
1418 bsrq.stream = assoc->encode;
1419 bsrq.decode = assoc->decode;
1420 bsrq.print = assoc->print;
1421 if (!(bsrt = bend_search (assoc->backend, &bsrq, fd)))
1423 bsrr->hits = bsrt->hits;
1424 bsrr->errcode = bsrt->errcode;
1425 bsrr->errstring = bsrt->errstring;
1428 return response_searchRequest(assoc, reqb, bsrr, fd);
1431 int bend_searchresponse(void *handle, bend_search_rr *bsrr) {return 0;}
1434 * Prepare a searchresponse based on the backend results. We probably want
1435 * to look at making the fetching of records nonblocking as well, but
1436 * so far, we'll keep things simple.
1437 * If bsrt is null, that means we're called in response to a communications
1438 * event, and we'll have to get the response for ourselves.
1440 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
1441 bend_search_rr *bsrt, int *fd)
1443 Z_SearchRequest *req = reqb->request->u.searchRequest;
1444 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1445 Z_SearchResponse *resp = (Z_SearchResponse *)
1446 odr_malloc (assoc->encode, sizeof(*resp));
1447 int *nulint = odr_intdup (assoc->encode, 0);
1448 bool_t *sr = odr_intdup(assoc->encode, 1);
1449 int *next = odr_intdup(assoc->encode, 0);
1450 int *none = odr_intdup(assoc->encode, Z_RES_NONE);
1452 apdu->which = Z_APDU_searchResponse;
1453 apdu->u.searchResponse = resp;
1454 resp->referenceId = req->referenceId;
1455 resp->additionalSearchInfo = 0;
1456 resp->otherInfo = 0;
1458 if (!bsrt && !bend_searchresponse(assoc->backend, bsrt))
1460 yaz_log(LOG_FATAL, "Bad result from backend");
1463 else if (bsrt->errcode)
1465 resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
1466 resp->resultCount = nulint;
1467 resp->numberOfRecordsReturned = nulint;
1468 resp->nextResultSetPosition = nulint;
1469 resp->searchStatus = nulint;
1470 resp->resultSetStatus = none;
1471 resp->presentStatus = 0;
1475 int *toget = odr_intdup(assoc->encode, 0);
1476 int *presst = odr_intdup(assoc->encode, 0);
1477 Z_RecordComposition comp, *compp = 0;
1480 resp->resultCount = &bsrt->hits;
1482 comp.which = Z_RecordComp_simple;
1483 /* how many records does the user agent want, then? */
1484 if (bsrt->hits <= *req->smallSetUpperBound)
1486 *toget = bsrt->hits;
1487 if ((comp.u.simple = req->smallSetElementSetNames))
1490 else if (bsrt->hits < *req->largeSetLowerBound)
1492 *toget = *req->mediumSetPresentNumber;
1493 if (*toget > bsrt->hits)
1494 *toget = bsrt->hits;
1495 if ((comp.u.simple = req->mediumSetElementSetNames))
1501 if (*toget && !resp->records)
1506 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
1509 form = prefformat->value;
1510 resp->records = pack_records(assoc, req->resultSetName, 1,
1511 toget, compp, next, presst, form, req->referenceId,
1512 req->preferredRecordSyntax);
1515 resp->numberOfRecordsReturned = toget;
1516 resp->nextResultSetPosition = next;
1517 resp->searchStatus = sr;
1518 resp->resultSetStatus = 0;
1519 resp->presentStatus = presst;
1523 if (*resp->resultCount)
1525 resp->numberOfRecordsReturned = nulint;
1526 resp->nextResultSetPosition = next;
1527 resp->searchStatus = sr;
1528 resp->resultSetStatus = 0;
1529 resp->presentStatus = 0;
1536 * Maybe we got a little over-friendly when we designed bend_fetch to
1537 * get only one record at a time. Some backends can optimise multiple-record
1538 * fetches, and at any rate, there is some overhead involved in
1539 * all that selecting and hopping around. Problem is, of course, that the
1540 * frontend can't know ahead of time how many records it'll need to
1541 * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
1542 * is downright lousy as a bulk data transfer protocol.
1544 * To start with, we'll do the fetching of records from the backend
1545 * in one operation: To save some trips in and out of the event-handler,
1546 * and to simplify the interface to pack_records. At any rate, asynch
1547 * operation is more fun in operations that have an unpredictable execution
1548 * speed - which is normally more true for search than for present.
1550 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
1553 Z_PresentRequest *req = reqb->request->u.presentRequest;
1557 Z_PresentResponse *resp;
1562 yaz_log(LOG_LOG, "Got PresentRequest.");
1564 if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
1567 form = prefformat->value;
1568 if (assoc->init->bend_present)
1570 bend_present_rr *bprr = (bend_present_rr *)
1571 nmem_malloc (reqb->request_mem, sizeof(*bprr));
1572 bprr->setname = req->resultSetId;
1573 bprr->start = *req->resultSetStartPoint;
1574 bprr->number = *req->numberOfRecordsRequested;
1575 bprr->format = form;
1576 bprr->comp = req->recordComposition;
1577 bprr->referenceId = req->referenceId;
1578 bprr->stream = assoc->encode;
1579 bprr->print = assoc->print;
1580 bprr->request = reqb;
1581 bprr->association = assoc;
1583 bprr->errstring = NULL;
1584 (*assoc->init->bend_present)(assoc->backend, bprr);
1589 apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1590 resp = (Z_PresentResponse *)odr_malloc (assoc->encode, sizeof(*resp));
1591 presst = odr_intdup(assoc->encode, 0);
1592 next = odr_intdup(assoc->encode, 0);
1593 num = odr_intdup(assoc->encode, *req->numberOfRecordsRequested);
1595 apdu->which = Z_APDU_presentResponse;
1596 apdu->u.presentResponse = resp;
1597 resp->referenceId = req->referenceId;
1598 resp->otherInfo = 0;
1601 pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
1602 num, req->recordComposition, next, presst, form,
1603 req->referenceId, req->preferredRecordSyntax);
1606 resp->numberOfRecordsReturned = num;
1607 resp->presentStatus = presst;
1608 resp->nextResultSetPosition = next;
1614 * Scan was implemented rather in a hurry, and with support for only the basic
1615 * elements of the service in the backend API. Suggestions are welcome.
1617 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
1619 Z_ScanRequest *req = reqb->request->u.scanRequest;
1620 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1621 Z_ScanResponse *res = (Z_ScanResponse *)
1622 odr_malloc (assoc->encode, sizeof(*res));
1623 int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
1624 int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
1625 Z_ListEntries *ents = (Z_ListEntries *)
1626 odr_malloc (assoc->encode, sizeof(*ents));
1627 Z_DiagRecs *diagrecs_p = NULL;
1631 yaz_log(LOG_LOG, "Got ScanRequest");
1633 apdu->which = Z_APDU_scanResponse;
1634 apdu->u.scanResponse = res;
1635 res->referenceId = req->referenceId;
1636 res->stepSize = odr_intdup(assoc->encode, 0);
1639 *res->stepSize = *req->stepSize;
1640 res->scanStatus = scanStatus;
1641 res->numberOfEntriesReturned = numberOfEntriesReturned;
1642 res->positionOfTerm = 0;
1643 res->entries = ents;
1644 ents->num_entries = 0;
1645 ents->entries = NULL;
1646 ents->num_nonsurrogateDiagnostics = 0;
1647 ents->nonsurrogateDiagnostics = NULL;
1648 res->attributeSet = 0;
1651 if (req->attributeSet && (!(attent = oid_getentbyoid(req->attributeSet)) ||
1652 attent->oclass != CLASS_ATTSET
1653 || attent->value != VAL_BIB1))
1654 diagrecs_p = diagrecs(assoc, 121, 0);
1655 else if (req->stepSize && *req->stepSize > 0)
1656 diagrecs_p = diagrecs(assoc, 205, 0);
1659 bend_scan_rr *bsrr = (bend_scan_rr *)
1660 odr_malloc (assoc->encode, sizeof(*bsrr));
1661 if (req->databaseNames)
1664 for (i = 0; i < req->num_databaseNames; i++)
1665 yaz_log (LOG_LOG, "Database '%s'", req->databaseNames[i]);
1667 bsrr->num_bases = req->num_databaseNames;
1668 bsrr->basenames = req->databaseNames;
1669 bsrr->num_entries = *req->numberOfTermsRequested;
1670 bsrr->term = req->termListAndStartPoint;
1671 bsrr->referenceId = req->referenceId;
1672 bsrr->stream = assoc->encode;
1673 bsrr->print = assoc->print;
1674 bsrr->step_size = res->stepSize;
1675 if (!(attset = oid_getentbyoid(req->attributeSet)) ||
1676 attset->oclass != CLASS_RECSYN)
1677 bsrr->attributeset = VAL_NONE;
1679 bsrr->attributeset = attset->value;
1680 log_scan_term (req->termListAndStartPoint, bsrr->attributeset);
1681 bsrr->term_position = req->preferredPositionInResponse ?
1682 *req->preferredPositionInResponse : 1;
1683 ((int (*)(void *, bend_scan_rr *))
1684 (*assoc->init->bend_scan))(assoc->backend, bsrr);
1686 diagrecs_p = diagrecs(assoc, bsrr->errcode, bsrr->errstring);
1690 Z_Entry **tab = (Z_Entry **)
1691 odr_malloc (assoc->encode, sizeof(*tab) * bsrr->num_entries);
1693 if (bsrr->status == BEND_SCAN_PARTIAL)
1694 *scanStatus = Z_Scan_partial_5;
1696 *scanStatus = Z_Scan_success;
1697 ents->entries = tab;
1698 ents->num_entries = bsrr->num_entries;
1699 res->numberOfEntriesReturned = &ents->num_entries;
1700 res->positionOfTerm = &bsrr->term_position;
1701 for (i = 0; i < bsrr->num_entries; i++)
1707 tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
1708 if (bsrr->entries[i].occurrences >= 0)
1710 e->which = Z_Entry_termInfo;
1711 e->u.termInfo = t = (Z_TermInfo *)
1712 odr_malloc(assoc->encode, sizeof(*t));
1713 t->suggestedAttributes = 0;
1715 t->alternativeTerm = 0;
1716 t->byAttributes = 0;
1717 t->otherTermInfo = 0;
1718 t->globalOccurrences = &bsrr->entries[i].occurrences;
1719 t->term = (Z_Term *)
1720 odr_malloc(assoc->encode, sizeof(*t->term));
1721 t->term->which = Z_Term_general;
1722 t->term->u.general = o =
1723 (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
1724 o->buf = (unsigned char *)
1725 odr_malloc(assoc->encode, o->len = o->size =
1726 strlen(bsrr->entries[i].term));
1727 memcpy(o->buf, bsrr->entries[i].term, o->len);
1728 yaz_log(LOG_DEBUG, " term #%d: '%s' (%d)", i,
1729 bsrr->entries[i].term, bsrr->entries[i].occurrences);
1733 Z_DiagRecs *drecs = diagrecs (assoc,
1734 bsrr->entries[i].errcode,
1735 bsrr->entries[i].errstring);
1736 assert (drecs->num_diagRecs == 1);
1737 e->which = Z_Entry_surrogateDiagnostic;
1738 assert (drecs->diagRecs[0]);
1739 e->u.surrogateDiagnostic = drecs->diagRecs[0];
1746 ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
1747 ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
1752 static Z_APDU *process_sortRequest(association *assoc, request *reqb,
1755 Z_SortRequest *req = reqb->request->u.sortRequest;
1756 Z_SortResponse *res = (Z_SortResponse *)
1757 odr_malloc (assoc->encode, sizeof(*res));
1758 bend_sort_rr *bsrr = (bend_sort_rr *)
1759 odr_malloc (assoc->encode, sizeof(*bsrr));
1761 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1763 yaz_log(LOG_LOG, "Got SortRequest.");
1766 bsrr->num_input_setnames = req->num_inputResultSetNames;
1767 bsrr->input_setnames = req->inputResultSetNames;
1769 bsrr->num_input_setnames = req->inputResultSetNames->num_strings;
1770 bsrr->input_setnames = req->inputResultSetNames->strings;
1772 bsrr->referenceId = req->referenceId;
1773 bsrr->output_setname = req->sortedResultSetName;
1774 bsrr->sort_sequence = req->sortSequence;
1775 bsrr->stream = assoc->encode;
1776 bsrr->print = assoc->print;
1778 bsrr->sort_status = Z_SortStatus_failure;
1780 bsrr->errstring = 0;
1782 (*assoc->init->bend_sort)(assoc->backend, bsrr);
1784 res->referenceId = bsrr->referenceId;
1785 res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
1786 res->resultSetStatus = 0;
1789 Z_DiagRecs *dr = diagrecs (assoc, bsrr->errcode, bsrr->errstring);
1791 res->diagnostics = dr->diagRecs;
1792 res->num_diagnostics = dr->num_diagRecs;
1794 res->diagnostics = dr;
1800 res->num_diagnostics = 0;
1802 res->diagnostics = 0;
1806 apdu->which = Z_APDU_sortResponse;
1807 apdu->u.sortResponse = res;
1811 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
1814 Z_DeleteResultSetRequest *req = reqb->request->u.deleteResultSetRequest;
1815 Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
1816 odr_malloc (assoc->encode, sizeof(*res));
1817 bend_delete_rr *bdrr = (bend_delete_rr *)
1818 odr_malloc (assoc->encode, sizeof(*bdrr));
1819 Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1821 yaz_log(LOG_LOG, "Got DeleteRequest.");
1823 bdrr->num_setnames = req->num_resultSetList;
1824 bdrr->setnames = req->resultSetList;
1825 bdrr->stream = assoc->encode;
1826 bdrr->print = assoc->print;
1827 bdrr->function = *req->deleteFunction;
1828 bdrr->referenceId = req->referenceId;
1830 if (bdrr->num_setnames > 0)
1833 bdrr->statuses = (int*)
1834 odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
1835 bdrr->num_setnames);
1836 for (i = 0; i < bdrr->num_setnames; i++)
1837 bdrr->statuses[i] = 0;
1839 (*assoc->init->bend_delete)(assoc->backend, bdrr);
1841 res->referenceId = req->referenceId;
1843 res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
1845 res->deleteListStatuses = 0;
1846 if (bdrr->num_setnames > 0)
1849 res->deleteListStatuses = (Z_ListStatuses *)
1850 odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
1851 res->deleteListStatuses->num = bdrr->num_setnames;
1852 res->deleteListStatuses->elements =
1854 odr_malloc (assoc->encode,
1855 sizeof(*res->deleteListStatuses->elements) *
1856 bdrr->num_setnames);
1857 for (i = 0; i<bdrr->num_setnames; i++)
1859 res->deleteListStatuses->elements[i] =
1861 odr_malloc (assoc->encode,
1862 sizeof(**res->deleteListStatuses->elements));
1863 res->deleteListStatuses->elements[i]->status = bdrr->statuses+i;
1864 res->deleteListStatuses->elements[i]->id =
1865 odr_strdup (assoc->encode, bdrr->setnames[i]);
1869 res->numberNotDeleted = 0;
1870 res->bulkStatuses = 0;
1871 res->deleteMessage = 0;
1874 apdu->which = Z_APDU_deleteResultSetResponse;
1875 apdu->u.deleteResultSetResponse = res;
1879 static void process_close(association *assoc, request *reqb)
1881 Z_Close *req = reqb->request->u.close;
1882 static char *reasons[] =
1889 "securityViolation",
1896 yaz_log(LOG_LOG, "Got Close, reason %s, message %s",
1897 reasons[*req->closeReason], req->diagnosticInformation ?
1898 req->diagnosticInformation : "NULL");
1899 if (assoc->version < 3) /* to make do_force respond with close */
1901 do_close_req(assoc, Z_Close_finished,
1902 "Association terminated by client", reqb);
1905 void save_referenceId (request *reqb, Z_ReferenceId *refid)
1909 reqb->len_refid = refid->len;
1910 reqb->refid = (char *)nmem_malloc (reqb->request_mem, refid->len);
1911 memcpy (reqb->refid, refid->buf, refid->len);
1915 reqb->len_refid = 0;
1920 void bend_request_send (bend_association a, bend_request req, Z_APDU *res)
1922 process_response (a, req, res);
1925 bend_request bend_request_mk (bend_association a)
1927 request *nreq = request_get (&a->outgoing);
1928 nreq->request_mem = nmem_create ();
1932 Z_ReferenceId *bend_request_getid (ODR odr, bend_request req)
1937 id = (Odr_oct *)odr_malloc (odr, sizeof(*odr));
1938 id->buf = (unsigned char *)odr_malloc (odr, req->len_refid);
1939 id->len = id->size = req->len_refid;
1940 memcpy (id->buf, req->refid, req->len_refid);
1944 void bend_request_destroy (bend_request *req)
1946 nmem_destroy((*req)->request_mem);
1947 request_release(*req);
1951 int bend_backend_respond (bend_association a, bend_request req)
1955 r = process_request (a, req, &msg);
1957 logf (LOG_WARN, "%s", msg);
1961 void bend_request_setdata(bend_request r, void *p)
1966 void *bend_request_getdata(bend_request r)
1968 return r->clientData;
1971 static Z_APDU *process_segmentRequest (association *assoc, request *reqb)
1973 bend_segment_rr request;
1975 request.segment = reqb->request->u.segmentRequest;
1976 request.stream = assoc->encode;
1977 request.decode = assoc->decode;
1978 request.print = assoc->print;
1979 request.association = assoc;
1981 (*assoc->init->bend_segment)(assoc->backend, &request);
1986 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd)
1988 bend_esrequest_rr esrequest;
1990 Z_ExtendedServicesRequest *req = reqb->request->u.extendedServicesRequest;
1991 Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
1993 Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
1995 yaz_log(LOG_DEBUG,"inside Process esRequest");
1997 esrequest.esr = reqb->request->u.extendedServicesRequest;
1998 esrequest.stream = assoc->encode;
1999 esrequest.decode = assoc->decode;
2000 esrequest.print = assoc->print;
2001 esrequest.errcode = 0;
2002 esrequest.errstring = NULL;
2003 esrequest.request = reqb;
2004 esrequest.association = assoc;
2005 esrequest.taskPackage = 0;
2006 esrequest.referenceId = req->referenceId;
2008 (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
2010 /* If the response is being delayed, return NULL */
2011 if (esrequest.request == NULL)
2014 resp->referenceId = req->referenceId;
2016 if (esrequest.errcode == -1)
2018 /* Backend service indicates request will be processed */
2019 yaz_log(LOG_DEBUG,"Request could be processed...Accepted !");
2020 *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
2022 else if (esrequest.errcode == 0)
2024 /* Backend service indicates request will be processed */
2025 yaz_log(LOG_DEBUG,"Request could be processed...Done !");
2026 *resp->operationStatus = Z_ExtendedServicesResponse_done;
2030 Z_DiagRecs *diagRecs = diagrecs (assoc, esrequest.errcode,
2031 esrequest.errstring);
2033 /* Backend indicates error, request will not be processed */
2034 yaz_log(LOG_DEBUG,"Request could not be processed...failure !");
2035 *resp->operationStatus = Z_ExtendedServicesResponse_failure;
2036 resp->num_diagnostics = diagRecs->num_diagRecs;
2037 resp->diagnostics = diagRecs->diagRecs;
2039 /* Do something with the members of bend_extendedservice */
2040 if (esrequest.taskPackage)
2041 resp->taskPackage = z_ext_record (assoc->encode, VAL_EXTENDED,
2042 (const char *) esrequest.taskPackage,
2044 yaz_log(LOG_DEBUG,"Send the result apdu");