568b2bc2cca133297e666b7ce431291ebccf818f
[yaz-moved-to-github.git] / server / seshigh.c
1 /*
2  * Copyright (c) 1995-2001, Index Data
3  * See the file LICENSE for details.
4  *
5  * $Log: seshigh.c,v $
6  * Revision 1.115  2001-03-25 21:55:12  adam
7  * Added odr_intdup. Ztest server returns TaskPackage for ItemUpdate.
8  *
9  * Revision 1.114  2001/02/21 13:46:53  adam
10  * C++ fixes.
11  *
12  * Revision 1.113  2001/01/30 21:34:17  adam
13  * Added step-size for Scan backend interface.
14  *
15  * Revision 1.112  2001/01/29 09:38:22  adam
16  * Fixed bug that made the frontend server crash when no attribute set
17  * was specified for scan.
18  *
19  * Revision 1.111  2000/11/23 10:58:32  adam
20  * SSL comstack support. Separate POSIX thread support library.
21  *
22  * Revision 1.110  2000/10/02 13:05:32  adam
23  * Fixed bug introduced by previous commit.
24  *
25  * Revision 1.109  2000/10/02 11:07:44  adam
26  * Added peer_name member for bend_init handler. Changed the YAZ
27  * client so that tcp: can be avoided in target spec.
28  *
29  * Revision 1.108  2000/09/04 08:58:15  adam
30  * Added prefix yaz_ for most logging utility functions.
31  *
32  * Revision 1.107  2000/08/31 10:20:12  adam
33  * Added member request_format and output_format for backend fetch method.
34  *
35  * Revision 1.106  2000/08/31 09:51:25  adam
36  * Added record_syntax member for fetch method (raw OID).
37  *
38  * Revision 1.105  2000/07/06 10:38:47  adam
39  * Enhanced option --enable-tcpd.
40  *
41  * Revision 1.104  2000/04/05 07:39:55  adam
42  * Added shared library support (libtool).
43  *
44  * Revision 1.103  2000/03/20 19:06:25  adam
45  * Added Segment request for fronend server. Work on admin for client.
46  *
47  * Revision 1.102  2000/03/15 12:59:49  adam
48  * Added handle member to statserv_control.
49  *
50  * Revision 1.101  2000/01/12 14:36:07  adam
51  * Added printing stream (ODR) for backend functions.
52  *
53  * Revision 1.100  1999/12/16 23:36:19  adam
54  * Implemented ILL protocol. Minor updates ASN.1 compiler.
55  *
56  * Revision 1.99  1999/11/30 13:47:12  adam
57  * Improved installation. Moved header files to include/yaz.
58  *
59  * Revision 1.98  1999/11/29 15:12:27  adam
60  * Changed the way implementationName - and version is set.
61  *
62  * Revision 1.96  1999/11/04 14:58:44  adam
63  * Added status elements for backend delete result set handler.
64  * Updated delete result result set command for client.
65  *
66  * Revision 1.95  1999/10/11 10:01:24  adam
67  * Implemented bend_sort_rr handler for frontend server.
68  *
69  * Revision 1.94  1999/08/27 09:40:32  adam
70  * Renamed logf function to yaz_log. Removed VC++ project files.
71  *
72  * Revision 1.93  1999/07/06 12:17:15  adam
73  * Added option -1 that runs server once (for profiling purposes).
74  *
75  * Revision 1.92  1999/06/17 10:54:45  adam
76  * Added facility to specify implementation version - and name
77  * for server.
78  *
79  * Revision 1.91  1999/06/01 14:29:12  adam
80  * Work on Extended Services.
81  *
82  * Revision 1.90  1999/05/27 13:02:20  adam
83  * Assigned OID for old DB Update (VAL_DBUPDATE0).
84  *
85  * Revision 1.89  1999/05/26 15:24:26  adam
86  * Fixed minor bugs regarding DB Update (introduced by previous commit).
87  *
88  * Revision 1.88  1999/04/20 09:56:48  adam
89  * Added 'name' paramter to encoder/decoder routines (typedef Odr_fun).
90  * Modified all encoders/decoders to reflect this change.
91  *
92  * Revision 1.87  1999/03/31 11:18:25  adam
93  * Implemented odr_strdup. Added Reference ID to backend server API.
94  *
95  * Revision 1.86  1999/02/02 13:57:38  adam
96  * Uses preprocessor define WIN32 instead of WINDOWS to build code
97  * for Microsoft WIN32.
98  *
99  * Revision 1.85  1998/11/17 09:52:59  adam
100  * Fixed minor bug (introduced by previous commit).
101  *
102  * Revision 1.84  1998/11/16 16:02:32  adam
103  * Added loggin utilies, log_rpn_query and log_scan_term. These used
104  * to be part of Zebra.
105  *
106  * Revision 1.83  1998/11/03 10:09:36  adam
107  * Fixed bug regarding YC.
108  *
109  * Revision 1.82  1998/10/20 14:00:30  quinn
110  * Fixed Scan
111  *
112  * Revision 1.81  1998/10/13 16:12:24  adam
113  * Added support for Surrogate Diagnostics for Scan Term entries.
114  *
115  * Revision 1.80  1998/09/02 12:41:53  adam
116  * Added decode stream in bend search structures.
117  *
118  * Revision 1.79  1998/08/19 16:10:08  adam
119  * Changed som member names of DeleteResultSetRequest/Response.
120  *
121  * Revision 1.78  1998/08/03 10:23:55  adam
122  * Fixed bug regarding Options for Sort.
123  *
124  * Revision 1.77  1998/07/20 12:38:42  adam
125  * Implemented delete result set service to server API.
126  *
127  * Revision 1.76  1998/05/27 16:57:07  adam
128  * Support for surrogate diagnostic records added for bend_fetch.
129  *
130  * Revision 1.75  1998/05/18 10:13:07  adam
131  * Fixed call to es_request handler - extra argument was passed.
132  *
133  * Revision 1.74  1998/03/31 15:13:20  adam
134  * Development towards compiled ASN.1.
135  *
136  * Revision 1.73  1998/03/31 11:07:45  adam
137  * Furhter work on UNIverse resource report.
138  * Added Extended Services handling in frontend server.
139  *
140  * Revision 1.72  1998/02/11 11:53:35  adam
141  * Changed code so that it compiles as C++.
142  *
143  * Revision 1.71  1998/02/10 11:03:57  adam
144  * Added support for extended handlers in backend server interface.
145  *
146  * Revision 1.70  1998/01/29 13:15:35  adam
147  * Implemented sort for the backend interface.
148  *
149  * Revision 1.69  1997/09/30 11:48:12  adam
150  * Fixed bug introduced by previous commit.
151  *
152  * Revision 1.68  1997/09/29 13:18:59  adam
153  * Added function, oid_ent_to_oid, to replace the function
154  * oid_getoidbyent, which is not thread safe.
155  *
156  * Revision 1.67  1997/09/17 12:10:40  adam
157  * YAZ version 1.4.
158  *
159  * Revision 1.66  1997/09/05 15:26:44  adam
160  * Added ODR encode in search and scen bend request structures.
161  * Fixed a few enums that caused trouble with C++.
162  *
163  * Revision 1.65  1997/09/01 08:53:01  adam
164  * New windows NT/95 port using MSV5.0. The test server 'ztest' was
165  * moved a separate directory. MSV5.0 project server.dsp created.
166  * As an option, the server can now operate as an NT service.
167  *
168  * Revision 1.64  1997/04/30 08:52:11  quinn
169  * Null
170  *
171  * Revision 1.63  1996/10/11  11:57:26  quinn
172  * Smallish
173  *
174  * Revision 1.62  1996/07/06  19:58:35  quinn
175  * System headerfiles gathered in yconfig
176  *
177  * Revision 1.61  1996/06/10  08:56:16  quinn
178  * Work on Summary.
179  *
180  * Revision 1.60  1996/05/30  11:03:10  quinn
181  * Fixed NextresultSetPosition bug fixed.
182  *
183  * Revision 1.59  1996/05/14  09:26:46  quinn
184  * Added attribute set to scan backend
185  *
186  * Revision 1.58  1996/02/20  12:53:04  quinn
187  * Chanes to SCAN
188  *
189  * Revision 1.57  1996/01/02  08:57:47  quinn
190  * Changed enums in the ASN.1 .h files to #defines. Changed oident.class to oclass
191  *
192  * Revision 1.56  1995/12/14  11:09:57  quinn
193  * Work on Explain
194  *
195  * Revision 1.55  1995/11/08  17:41:37  quinn
196  * Smallish.
197  *
198  * Revision 1.54  1995/11/08  15:11:29  quinn
199  * Log of close transmit.
200  *
201  * Revision 1.53  1995/11/01  13:54:58  quinn
202  * Minor adjustments
203  *
204  * Revision 1.52  1995/11/01  12:19:13  quinn
205  * Second attempt to fix same bug.
206  *
207  * Revision 1.50  1995/10/25  16:58:32  quinn
208  * Simple.
209  *
210  * Revision 1.49  1995/10/16  13:51:53  quinn
211  * Changes to provide Especs to the backend.
212  *
213  * Revision 1.48  1995/10/06  08:51:20  quinn
214  * Added Write-buffer.
215  *
216  * Revision 1.47  1995/08/29  14:24:16  quinn
217  * Added second half of close-handshake
218  *
219  * Revision 1.46  1995/08/29  11:17:58  quinn
220  * Added code to receive close
221  *
222  * Revision 1.45  1995/08/21  09:11:00  quinn
223  * Smallish fixes to suppport new formats.
224  *
225  * Revision 1.44  1995/08/17  12:45:25  quinn
226  * Fixed minor problems with GRS-1. Added support in c&s.
227  *
228  * Revision 1.43  1995/08/15  12:00:31  quinn
229  * Updated External
230  *
231  * Revision 1.42  1995/08/15  11:16:50  quinn
232  *
233  * Revision 1.41  1995/08/02  10:23:06  quinn
234  * Smallish
235  *
236  * Revision 1.40  1995/07/31  14:34:26  quinn
237  * Fixed bug in process_searchResponse (numberOfRecordsReturned).
238  *
239  * Revision 1.39  1995/06/27  13:21:00  quinn
240  * SUTRS support
241  *
242  * Revision 1.38  1995/06/19  12:39:11  quinn
243  * Fixed bug in timeout code. Added BER dumper.
244  *
245  * Revision 1.37  1995/06/16  13:16:14  quinn
246  * Fixed Defaultdiagformat.
247  *
248  * Revision 1.36  1995/06/16  10:31:36  quinn
249  * Added session timeout.
250  *
251  * Revision 1.35  1995/06/15  07:45:14  quinn
252  * Moving to v3.
253  *
254  * Revision 1.34  1995/06/14  15:26:46  quinn
255  * *** empty log message ***
256  *
257  * Revision 1.33  1995/06/06  14:57:05  quinn
258  * Better diagnostics.
259  *
260  * Revision 1.32  1995/06/06  08:41:44  quinn
261  * Better diagnostics.
262  *
263  * Revision 1.31  1995/06/06  08:15:37  quinn
264  * Cosmetic.
265  *
266  * Revision 1.30  1995/06/05  10:53:32  quinn
267  * Added a better SCAN.
268  *
269  * Revision 1.29  1995/06/01  11:25:03  quinn
270  * Smallish.
271  *
272  * Revision 1.28  1995/06/01  11:21:01  quinn
273  * Attempting to fix a bug in pack-records. replaced break with continue
274  * for large records, according to standard.
275  *
276  * Revision 1.27  1995/05/29  08:12:06  quinn
277  * Moved oid to util
278  *
279  * Revision 1.26  1995/05/18  13:02:12  quinn
280  * Smallish.
281  *
282  * Revision 1.25  1995/05/17  08:42:26  quinn
283  * Transfer auth info to backend. Allow backend to reject init gracefully.
284  *
285  * Revision 1.24  1995/05/16  08:51:04  quinn
286  * License, documentation, and memory fixes
287  *
288  * Revision 1.23  1995/05/15  13:25:10  quinn
289  * Fixed memory bug.
290  *
291  * Revision 1.22  1995/05/15  11:56:39  quinn
292  * Asynchronous facilities. Restructuring of seshigh code.
293  *
294  * Revision 1.21  1995/05/02  08:53:19  quinn
295  * Trying in vain to fix comm with ISODE
296  *
297  * Revision 1.20  1995/04/20  15:13:00  quinn
298  * Cosmetic
299  *
300  * Revision 1.19  1995/04/18  08:15:34  quinn
301  * Added dynamic memory allocation on encoding (whew). Code is now somewhat
302  * neater. We'll make the same change for decoding one day.
303  *
304  * Revision 1.18  1995/04/17  11:28:25  quinn
305  * Smallish
306  *
307  * Revision 1.17  1995/04/10  10:23:36  quinn
308  * Some work to add scan and other things.
309  *
310  * Revision 1.16  1995/03/31  09:18:55  quinn
311  * Added logging.
312  *
313  * Revision 1.15  1995/03/30  14:03:23  quinn
314  * Added RFC1006 as separate library
315  *
316  * Revision 1.14  1995/03/30  12:18:17  quinn
317  * Fixed bug.
318  *
319  * Revision 1.13  1995/03/30  09:09:24  quinn
320  * Added state-handle and some support for asynchronous activities.
321  *
322  * Revision 1.12  1995/03/29  15:40:16  quinn
323  * Ongoing work. Statserv is now dynamic by default
324  *
325  * Revision 1.11  1995/03/28  09:16:21  quinn
326  * Added record packing to the search request
327  *
328  * Revision 1.10  1995/03/27  08:34:24  quinn
329  * Added dynamic server functionality.
330  * Released bindings to session.c (is now redundant)
331  *
332  * Revision 1.9  1995/03/22  15:01:26  quinn
333  * Adjusting record packing.
334  *
335  * Revision 1.8  1995/03/22  10:13:21  quinn
336  * Working on record packer
337  *
338  * Revision 1.7  1995/03/21  15:53:31  quinn
339  * Little changes.
340  *
341  * Revision 1.6  1995/03/21  12:30:09  quinn
342  * Beginning to add support for record packing.
343  *
344  * Revision 1.5  1995/03/17  10:44:13  quinn
345  * Added catch of null-string in makediagrec
346  *
347  * Revision 1.4  1995/03/17  10:18:08  quinn
348  * Added memory management.
349  *
350  * Revision 1.3  1995/03/16  17:42:39  quinn
351  * Little changes
352  *
353  * Revision 1.2  1995/03/16  13:29:01  quinn
354  * Partitioned server.
355  *
356  * Revision 1.1  1995/03/15  16:02:10  quinn
357  * Modded session.c to seshigh.c
358  *
359  */
360
361 /*
362  * Frontend server logic.
363  *
364  * This code receives incoming APDUs, and handles client requests by means
365  * of the backend API.
366  *
367  * Some of the code is getting quite involved, compared to simpler servers -
368  * primarily because it is asynchronous both in the communication with
369  * the user and the backend. We think the complexity will pay off in
370  * the form of greater flexibility when more asynchronous facilities
371  * are implemented.
372  *
373  * Memory management has become somewhat involved. In the simple case, where
374  * only one PDU is pending at a time, it will simply reuse the same memory,
375  * once it has found its working size. When we enable multiple concurrent
376  * operations, perhaps even with multiple parallel calls to the backend, it
377  * will maintain a pool of buffers for encoding and decoding, trying to
378  * minimize memory allocation/deallocation during normal operation.
379  *
380  * TODOs include (and will be done in order of public interest):
381  * 
382  * Support for EXPLAIN - provide simple meta-database system.
383  * Support for access control.
384  * Support for resource control.
385  * Support for extended services - primarily Item Order.
386  * Rest of Z39.50-1994
387  *
388  */
389
390 #include <stdlib.h>
391 #include <stdio.h>
392 #ifdef WIN32
393 #include <process.h>
394 #else
395 #include <unistd.h>
396 #endif
397 #include <assert.h>
398
399 #include <yaz/yconfig.h>
400 #include <yaz/xmalloc.h>
401 #include <yaz/comstack.h>
402 #include "eventl.h"
403 #include "session.h"
404 #include <yaz/proto.h>
405 #include <yaz/oid.h>
406 #include <yaz/log.h>
407 #include <yaz/logrpn.h>
408 #include <yaz/statserv.h>
409
410 #include <yaz/backend.h>
411
412 static int process_request(association *assoc, request *req, char **msg);
413 void backend_response(IOCHAN i, int event);
414 static int process_response(association *assoc, request *req, Z_APDU *res);
415 static Z_APDU *process_initRequest(association *assoc, request *reqb);
416 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
417     int *fd);
418 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
419     bend_search_rr *bsrr, int *fd);
420 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
421     int *fd);
422 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
423 static Z_APDU *process_sortRequest(association *assoc, request *reqb, int *fd);
424 static void process_close(association *assoc, request *reqb);
425 void save_referenceId (request *reqb, Z_ReferenceId *refid);
426 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
427     int *fd);
428 static Z_APDU *process_segmentRequest (association *assoc, request *reqb);
429
430 static FILE *apduf = 0; /* for use in static mode */
431 static statserv_options_block *control_block = 0;
432
433 /* Chas: Added in from DALI */
434 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd);
435 /* Chas: End of addition from DALI */
436
437 /*
438  * Create and initialize a new association-handle.
439  *  channel  : iochannel for the current line.
440  *  link     : communications channel.
441  * Returns: 0 or a new association handle.
442  */
443 association *create_association(IOCHAN channel, COMSTACK link)
444 {
445     association *anew;
446
447     if (!control_block)
448         control_block = statserv_getcontrol();
449     if (!(anew = (association *)xmalloc(sizeof(*anew))))
450         return 0;
451     anew->init = 0;
452     anew->client_chan = channel;
453     anew->client_link = link;
454     anew->cs_get_mask = 0;
455     anew->cs_put_mask = 0;
456     anew->cs_accept_mask = 0;
457     if (!(anew->decode = odr_createmem(ODR_DECODE)) ||
458         !(anew->encode = odr_createmem(ODR_ENCODE)))
459         return 0;
460     if (*control_block->apdufile)
461     {
462         char filename[256];
463         FILE *f;
464
465         strcpy(filename, control_block->apdufile);
466         if (!(anew->print = odr_createmem(ODR_PRINT)))
467             return 0;
468         if (*control_block->apdufile != '-')
469         {
470             strcpy(filename, control_block->apdufile);
471             if (!control_block->dynamic)
472             {
473                 if (!apduf)
474                 {
475                     if (!(apduf = fopen(filename, "w")))
476                     {
477                         yaz_log(LOG_WARN|LOG_ERRNO, "%s", filename);
478                         return 0;
479                     }
480                     setvbuf(apduf, 0, _IONBF, 0);
481                 }
482                 f = apduf;
483             }
484             else 
485             {
486                 sprintf(filename + strlen(filename), ".%d", getpid());
487                 if (!(f = fopen(filename, "w")))
488                 {
489                     yaz_log(LOG_WARN|LOG_ERRNO, "%s", filename);
490                     return 0;
491                 }
492                 setvbuf(f, 0, _IONBF, 0);
493             }
494             odr_setprint(anew->print, f);
495         }
496     }
497     else
498         anew->print = 0;
499     anew->input_buffer = 0;
500     anew->input_buffer_len = 0;
501     anew->backend = 0;
502     anew->state = ASSOC_NEW;
503     request_initq(&anew->incoming);
504     request_initq(&anew->outgoing);
505     anew->proto = cs_getproto(link);
506     return anew;
507 }
508
509 /*
510  * Free association and release resources.
511  */
512 void destroy_association(association *h)
513 {
514     statserv_options_block *cb = statserv_getcontrol();
515
516     xfree(h->init);
517     odr_destroy(h->decode);
518     odr_destroy(h->encode);
519     if (h->print)
520         odr_destroy(h->print);
521     if (h->input_buffer)
522     xfree(h->input_buffer);
523     if (h->backend)
524         (*cb->bend_close)(h->backend);
525     while (request_deq(&h->incoming));
526     while (request_deq(&h->outgoing));
527     request_delq(&h->incoming);
528     request_delq(&h->outgoing);
529     xfree(h);
530     if (control_block && control_block->one_shot)
531         exit (0);
532 }
533
534 static void do_close_req(association *a, int reason, char *message,
535                          request *req)
536 {
537     Z_APDU apdu;
538     Z_Close *cls = zget_Close(a->encode);
539     
540     /* Purge request queue */
541     while (request_deq(&a->incoming));
542     while (request_deq(&a->outgoing));
543     if (a->version >= 3)
544     {
545         yaz_log(LOG_LOG, "Sending Close PDU, reason=%d, message=%s",
546             reason, message ? message : "none");
547         apdu.which = Z_APDU_close;
548         apdu.u.close = cls;
549         *cls->closeReason = reason;
550         cls->diagnosticInformation = message;
551         process_response(a, req, &apdu);
552         iochan_settimeout(a->client_chan, 60);
553     }
554     else
555     {
556         yaz_log(LOG_DEBUG, "v2 client. No Close PDU");
557         iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
558     }
559     a->state = ASSOC_DEAD;
560 }
561
562 static void do_close(association *a, int reason, char *message)
563 {
564     do_close_req (a, reason, message, request_get(&a->outgoing));
565 }
566
567 /*
568  * This is where PDUs from the client are read and the further
569  * processing is initiated. Flow of control moves down through the
570  * various process_* functions below, until the encoded result comes back up
571  * to the output handler in here.
572  * 
573  *  h     : the I/O channel that has an outstanding event.
574  *  event : the current outstanding event.
575  */
576 void ir_session(IOCHAN h, int event)
577 {
578     int res;
579     association *assoc = (association *)iochan_getdata(h);
580     COMSTACK conn = assoc->client_link;
581     request *req;
582
583     assert(h && conn && assoc);
584     if (event == EVENT_TIMEOUT)
585     {
586         if (assoc->state != ASSOC_UP)
587         {
588             yaz_log(LOG_LOG, "Final timeout - closing connection.");
589             cs_close(conn);
590             destroy_association(assoc);
591             iochan_destroy(h);
592         }
593         else
594         {
595             yaz_log(LOG_LOG, "Session idle too long. Sending close.");
596             do_close(assoc, Z_Close_lackOfActivity, 0);
597         }
598         return;
599     }
600     if (event & assoc->cs_accept_mask)
601     {
602         yaz_log (LOG_DEBUG, "ir_session (accept)");
603         if (!cs_accept (conn))
604         {
605             yaz_log (LOG_LOG, "accept failed");
606             destroy_association(assoc);
607             iochan_destroy(h);
608         }
609         iochan_clearflag (h, EVENT_OUTPUT|EVENT_OUTPUT);
610         if (conn->io_pending) 
611         {   /* cs_accept didn't complete */
612             assoc->cs_accept_mask = 
613                 ((conn->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
614                 ((conn->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
615
616             iochan_setflag (h, assoc->cs_accept_mask);
617         }
618         else
619         {   /* cs_accept completed. Prepare for reading (cs_get) */
620             assoc->cs_accept_mask = 0;
621             assoc->cs_get_mask = EVENT_INPUT;
622             iochan_setflag (h, assoc->cs_get_mask);
623         }
624         return;
625     }
626     if ((event & assoc->cs_get_mask) || (event & EVENT_WORK)) /* input */
627     {
628         if ((assoc->cs_put_mask & EVENT_INPUT) == 0 && (event & assoc->cs_get_mask))
629         {
630             yaz_log(LOG_DEBUG, "ir_session (input)");
631             /* We aren't speaking to this fellow */
632             if (assoc->state == ASSOC_DEAD)
633             {
634                 yaz_log(LOG_LOG, "Closed connection after reject");
635                 cs_close(conn);
636                 destroy_association(assoc);
637                 iochan_destroy(h);
638                 return;
639             }
640             assoc->cs_get_mask = EVENT_INPUT;
641             if ((res = cs_get(conn, &assoc->input_buffer,
642                 &assoc->input_buffer_len)) <= 0)
643             {
644                 yaz_log(LOG_LOG, "Connection closed by client");
645                 cs_close(conn);
646                 destroy_association(assoc);
647                 iochan_destroy(h);
648                 return;
649             }
650             else if (res == 1) /* incomplete read - wait for more  */
651             {
652                 if (conn->io_pending & CS_WANT_WRITE)
653                     assoc->cs_get_mask |= EVENT_OUTPUT;
654                 iochan_setflag(h, assoc->cs_get_mask);
655                 return;
656             }
657             if (cs_more(conn)) /* more stuff - call us again later, please */
658                 iochan_setevent(h, EVENT_INPUT);
659                 
660             /* we got a complete PDU. Let's decode it */
661             yaz_log(LOG_DEBUG, "Got PDU, %d bytes", res);
662             req = request_get(&assoc->incoming); /* get a new request structure */
663             odr_reset(assoc->decode);
664             odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
665             if (!z_APDU(assoc->decode, &req->request, 0, 0))
666             {
667                 yaz_log(LOG_LOG, "ODR error on incoming PDU: %s [near byte %d] ",
668                         odr_errmsg(odr_geterror(assoc->decode)),
669                         odr_offset(assoc->decode));
670                 yaz_log(LOG_LOG, "PDU dump:");
671                 odr_dumpBER(yaz_log_file(), assoc->input_buffer, res);
672                 do_close(assoc, Z_Close_protocolError, "Malformed package");
673                 return;
674             }
675             req->request_mem = odr_extract_mem(assoc->decode);
676             if (assoc->print && !z_APDU(assoc->print, &req->request, 0, 0))
677             {
678                 yaz_log(LOG_WARN, "ODR print error: %s", 
679                     odr_errmsg(odr_geterror(assoc->print)));
680                 odr_reset(assoc->print);
681             }
682             request_enq(&assoc->incoming, req);
683         }
684
685         /* can we do something yet? */
686         req = request_head(&assoc->incoming);
687         if (req->state == REQUEST_IDLE)
688         {
689             char *msg;
690             request_deq(&assoc->incoming);
691             if (process_request(assoc, req, &msg) < 0)
692                 do_close_req(assoc, Z_Close_systemProblem, msg, req);
693         }
694     }
695     if (event & assoc->cs_put_mask)
696     {
697         request *req = request_head(&assoc->outgoing);
698
699         assoc->cs_put_mask = 0;
700         yaz_log(LOG_DEBUG, "ir_session (output)");
701         req->state = REQUEST_PENDING;
702         switch (res = cs_put(conn, req->response, req->len_response))
703         {
704         case -1:
705             yaz_log(LOG_LOG, "Connection closed by client");
706             cs_close(conn);
707             destroy_association(assoc);
708             iochan_destroy(h);
709             break;
710         case 0: /* all sent - release the request structure */
711             yaz_log(LOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
712             nmem_destroy(req->request_mem);
713             request_deq(&assoc->outgoing);
714             request_release(req);
715             if (!request_head(&assoc->outgoing))
716             {   /* restore mask for cs_get operation ... */
717                 iochan_clearflag(h, EVENT_OUTPUT|EVENT_INPUT);
718                 iochan_setflag(h, assoc->cs_get_mask);
719             }
720             break;
721         default:
722             if (conn->io_pending & CS_WANT_WRITE)
723                 assoc->cs_put_mask |= EVENT_OUTPUT;
724             if (conn->io_pending & CS_WANT_READ)
725                 assoc->cs_put_mask |= EVENT_INPUT;
726             iochan_setflag(h, assoc->cs_put_mask);
727         }
728     }
729     if (event & EVENT_EXCEPT)
730     {
731         yaz_log(LOG_LOG, "ir_session (exception)");
732         cs_close(conn);
733         destroy_association(assoc);
734         iochan_destroy(h);
735     }
736 }
737
738 /*
739  * Initiate request processing.
740  */
741 static int process_request(association *assoc, request *req, char **msg)
742 {
743     int fd = -1;
744     Z_APDU *res;
745     int retval;
746     
747     *msg = "Unknown Error";
748     assert(req && req->state == REQUEST_IDLE);
749     if (req->request->which != Z_APDU_initRequest && !assoc->init)
750     {
751         *msg = "Missing InitRequest";
752         return -1;
753     }
754     switch (req->request->which)
755     {
756     case Z_APDU_initRequest:
757         res = process_initRequest(assoc, req); break;
758     case Z_APDU_searchRequest:
759         res = process_searchRequest(assoc, req, &fd); break;
760     case Z_APDU_presentRequest:
761         res = process_presentRequest(assoc, req, &fd); break;
762     case Z_APDU_scanRequest:
763         if (assoc->init->bend_scan)
764             res = process_scanRequest(assoc, req, &fd);
765         else
766         {
767             *msg = "Cannot handle Scan APDU";
768             return -1;
769         }
770         break;
771     case Z_APDU_extendedServicesRequest:
772         if (assoc->init->bend_esrequest)
773             res = process_ESRequest(assoc, req, &fd);
774         else
775         {
776             *msg = "Cannot handle Extended Services APDU";
777             return -1;
778         }
779         break;
780     case Z_APDU_sortRequest:
781         if (assoc->init->bend_sort)
782             res = process_sortRequest(assoc, req, &fd);
783         else
784         {
785             *msg = "Cannot handle Sort APDU";
786             return -1;
787         }
788         break;
789     case Z_APDU_close:
790         process_close(assoc, req);
791         return 0;
792     case Z_APDU_deleteResultSetRequest:
793         if (assoc->init->bend_delete)
794             res = process_deleteRequest(assoc, req, &fd);
795         else
796         {
797             *msg = "Cannot handle Delete APDU";
798             return -1;
799         }
800         break;
801     case Z_APDU_segmentRequest:
802         if (assoc->init->bend_segment)
803         {
804             res = process_segmentRequest (assoc, req);
805         }
806         else
807         {
808             *msg = "Cannot handle Segment APDU";
809             return -1;
810         }
811         break;
812     default:
813         *msg = "Bad APDU received";
814         return -1;
815     }
816     if (res)
817     {
818         yaz_log(LOG_DEBUG, "  result immediately available");
819         retval = process_response(assoc, req, res);
820     }
821     else if (fd < 0)
822     {
823         yaz_log(LOG_DEBUG, "  result unavailble");
824         retval = 0;
825     }
826     else /* no result yet - one will be provided later */
827     {
828         IOCHAN chan;
829
830         /* Set up an I/O handler for the fd supplied by the backend */
831
832         yaz_log(LOG_DEBUG, "   establishing handler for result");
833         req->state = REQUEST_PENDING;
834         if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT)))
835             abort();
836         iochan_setdata(chan, assoc);
837         retval = 0;
838     }
839     return retval;
840 }
841
842 /*
843  * Handle message from the backend.
844  */
845 void backend_response(IOCHAN i, int event)
846 {
847     association *assoc = (association *)iochan_getdata(i);
848     request *req = request_head(&assoc->incoming);
849     Z_APDU *res;
850     int fd;
851
852     yaz_log(LOG_DEBUG, "backend_response");
853     assert(assoc && req && req->state != REQUEST_IDLE);
854     /* determine what it is we're waiting for */
855     switch (req->request->which)
856     {
857         case Z_APDU_searchRequest:
858             res = response_searchRequest(assoc, req, 0, &fd); break;
859 #if 0
860         case Z_APDU_presentRequest:
861             res = response_presentRequest(assoc, req, 0, &fd); break;
862         case Z_APDU_scanRequest:
863             res = response_scanRequest(assoc, req, 0, &fd); break;
864 #endif
865         default:
866             yaz_log(LOG_WARN, "Serious programmer's lapse or bug");
867             abort();
868     }
869     if ((res && process_response(assoc, req, res) < 0) || fd < 0)
870     {
871         yaz_log(LOG_LOG, "Fatal error when talking to backend");
872         do_close(assoc, Z_Close_systemProblem, 0);
873         iochan_destroy(i);
874         return;
875     }
876     else if (!res) /* no result yet - try again later */
877     {
878         yaz_log(LOG_DEBUG, "   no result yet");
879         iochan_setfd(i, fd); /* in case fd has changed */
880     }
881 }
882
883 /*
884  * Encode response, and transfer the request structure to the outgoing queue.
885  */
886 static int process_response(association *assoc, request *req, Z_APDU *res)
887 {
888     odr_setbuf(assoc->encode, req->response, req->size_response, 1);
889
890     if (assoc->print && !z_APDU(assoc->print, &res, 0, 0))
891     {
892         yaz_log(LOG_WARN, "ODR print error: %s", 
893             odr_errmsg(odr_geterror(assoc->print)));
894         odr_reset(assoc->print);
895     }
896     if (!z_APDU(assoc->encode, &res, 0, 0))
897     {
898         yaz_log(LOG_WARN, "ODR error when encoding response: %s",
899             odr_errmsg(odr_geterror(assoc->decode)));
900         return -1;
901     }
902     req->response = odr_getbuf(assoc->encode, &req->len_response,
903         &req->size_response);
904     odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
905     odr_reset(assoc->encode);
906     req->state = REQUEST_IDLE;
907     request_enq(&assoc->outgoing, req);
908     /* turn the work over to the ir_session handler */
909     iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
910     assoc->cs_put_mask = EVENT_OUTPUT;
911     /* Is there more work to be done? give that to the input handler too */
912 #if 1
913     if (request_head(&assoc->incoming))
914     {
915         yaz_log (LOG_DEBUG, "more work to be done");
916         iochan_setevent(assoc->client_chan, EVENT_WORK);
917     }
918 #endif
919     return 0;
920 }
921
922 /*
923  * Handle init request.
924  * At the moment, we don't check the options
925  * anywhere else in the code - we just try not to do anything that would
926  * break a naive client. We'll toss 'em into the association block when
927  * we need them there.
928  */
929 static Z_APDU *process_initRequest(association *assoc, request *reqb)
930 {
931     statserv_options_block *cb = statserv_getcontrol();
932     Z_InitRequest *req = reqb->request->u.initRequest;
933     Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
934     Z_InitResponse *resp = apdu->u.initResponse;
935     bend_initresult *binitres;
936     char options[100];
937
938     xfree (assoc->init);
939     assoc->init = (bend_initrequest *) xmalloc (sizeof(*assoc->init));
940
941     yaz_log(LOG_LOG, "Got initRequest");
942     if (req->implementationId)
943         yaz_log(LOG_LOG, "Id:        %s", req->implementationId);
944     if (req->implementationName)
945         yaz_log(LOG_LOG, "Name:      %s", req->implementationName);
946     if (req->implementationVersion)
947         yaz_log(LOG_LOG, "Version:   %s", req->implementationVersion);
948
949     assoc->init->stream = assoc->encode;
950     assoc->init->print = assoc->print;
951     assoc->init->auth = req->idAuthentication;
952     assoc->init->referenceId = req->referenceId;
953     assoc->init->implementation_version = 0;
954     assoc->init->implementation_name = 0;
955     assoc->init->bend_sort = NULL;
956     assoc->init->bend_search = NULL;
957     assoc->init->bend_present = NULL;
958     assoc->init->bend_esrequest = NULL;
959     assoc->init->bend_delete = NULL;
960     assoc->init->bend_scan = NULL;
961     assoc->init->bend_segment = NULL;
962     assoc->init->bend_fetch = NULL;
963     
964     assoc->init->peer_name =
965         odr_strdup (assoc->encode, cs_addrstr(assoc->client_link));
966     if (!(binitres = (*cb->bend_init)(assoc->init)))
967     {
968         yaz_log(LOG_WARN, "Bad response from backend.");
969         return 0;
970     }
971
972     assoc->backend = binitres->handle;
973     if ((assoc->init->bend_sort))
974         yaz_log (LOG_DEBUG, "Sort handler installed");
975     if ((assoc->init->bend_search))
976         yaz_log (LOG_DEBUG, "Search handler installed");
977     if ((assoc->init->bend_present))
978         yaz_log (LOG_DEBUG, "Present handler installed");   
979     if ((assoc->init->bend_esrequest))
980         yaz_log (LOG_DEBUG, "ESRequest handler installed");   
981     if ((assoc->init->bend_delete))
982         yaz_log (LOG_DEBUG, "Delete handler installed");   
983     if ((assoc->init->bend_scan))
984         yaz_log (LOG_DEBUG, "Scan handler installed");   
985     if ((assoc->init->bend_segment))
986         yaz_log (LOG_DEBUG, "Segment handler installed");   
987     
988     resp->referenceId = req->referenceId;
989     *options = '\0';
990     /* let's tell the client what we can do */
991     if (ODR_MASK_GET(req->options, Z_Options_search))
992     {
993         ODR_MASK_SET(resp->options, Z_Options_search);
994         strcat(options, "srch");
995     }
996     if (ODR_MASK_GET(req->options, Z_Options_present))
997     {
998         ODR_MASK_SET(resp->options, Z_Options_present);
999         strcat(options, " prst");
1000     }
1001     if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
1002         assoc->init->bend_delete)
1003     {
1004         ODR_MASK_SET(resp->options, Z_Options_delSet);
1005         strcat(options, " del");
1006     }
1007     if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
1008         assoc->init->bend_esrequest)
1009     {
1010         ODR_MASK_SET(resp->options, Z_Options_extendedServices);
1011         strcat (options, " extendedServices");
1012     }
1013     if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
1014     {
1015         ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
1016         strcat(options, " namedresults");
1017     }
1018     if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
1019     {
1020         ODR_MASK_SET(resp->options, Z_Options_scan);
1021         strcat(options, " scan");
1022     }
1023     if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
1024     {
1025         ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
1026         strcat(options, " concurop");
1027     }
1028     if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
1029     {
1030         ODR_MASK_SET(resp->options, Z_Options_sort);
1031         strcat(options, " sort");
1032     }
1033     if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
1034     {
1035         ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
1036         assoc->version = 2; /* 1 & 2 are equivalent */
1037     }
1038     if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
1039     {
1040         ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
1041         assoc->version = 2;
1042     }
1043     if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
1044     {
1045         ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
1046         assoc->version = 3;
1047     }
1048     yaz_log(LOG_LOG, "Negotiated to v%d: %s", assoc->version, options);
1049     assoc->maximumRecordSize = *req->maximumRecordSize;
1050     if (assoc->maximumRecordSize > control_block->maxrecordsize)
1051         assoc->maximumRecordSize = control_block->maxrecordsize;
1052     assoc->preferredMessageSize = *req->preferredMessageSize;
1053     if (assoc->preferredMessageSize > assoc->maximumRecordSize)
1054         assoc->preferredMessageSize = assoc->maximumRecordSize;
1055
1056 #if 0
1057     assoc->maximumRecordSize = 3000000;
1058     assoc->preferredMessageSize = 3000000;
1059 #endif
1060
1061     resp->preferredMessageSize = &assoc->preferredMessageSize;
1062     resp->maximumRecordSize = &assoc->maximumRecordSize;
1063
1064     resp->implementationName = "GFS";
1065
1066     if (assoc->init->implementation_name)
1067     {
1068         char *nv = (char *)
1069             odr_malloc (assoc->encode,
1070                         strlen(assoc->init->implementation_name) + 10 + 
1071                                strlen(resp->implementationName));
1072         sprintf (nv, "%s / %s",
1073                  resp->implementationName, assoc->init->implementation_name);
1074         resp->implementationName = nv;
1075     }
1076     if (assoc->init->implementation_version)
1077     {
1078         char *nv = (char *)
1079             odr_malloc (assoc->encode,
1080                         strlen(assoc->init->implementation_version) + 10 + 
1081                                strlen(resp->implementationVersion));
1082         sprintf (nv, "YAZ %s / %s",
1083                  resp->implementationVersion,
1084                  assoc->init->implementation_version);
1085         resp->implementationVersion = nv;
1086     }
1087
1088     if (binitres->errcode)
1089     {
1090         yaz_log(LOG_LOG, "Connection rejected by backend.");
1091         *resp->result = 0;
1092         assoc->state = ASSOC_DEAD;
1093     }
1094     else
1095         assoc->state = ASSOC_UP;
1096     return apdu;
1097 }
1098
1099 /*
1100  * These functions should be merged.
1101  */
1102
1103 static void set_addinfo (Z_DefaultDiagFormat *dr, char *addinfo, ODR odr)
1104 {
1105 #if ASN_COMPILED
1106     dr->which = Z_DefaultDiagFormat_v2Addinfo;
1107     dr->u.v2Addinfo = odr_strdup (odr, addinfo ? addinfo : "");
1108 #else
1109     dr->which = Z_DiagForm_v2AddInfo;
1110     dr->addinfo = odr_strdup (odr, addinfo ? addinfo : "");
1111 #endif
1112 }
1113
1114 /*
1115  * nonsurrogate diagnostic record.
1116  */
1117 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
1118 {
1119     int oid[OID_SIZE];
1120     Z_Records *rec = (Z_Records *)
1121         odr_malloc (assoc->encode, sizeof(*rec));
1122     oident bib1;
1123     int *err = odr_intdup(assoc->encode, error);
1124     Z_DiagRec *drec = (Z_DiagRec *)
1125         odr_malloc (assoc->encode, sizeof(*drec));
1126     Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
1127         odr_malloc (assoc->encode, sizeof(*dr));
1128
1129     bib1.proto = assoc->proto;
1130     bib1.oclass = CLASS_DIAGSET;
1131     bib1.value = VAL_BIB1;
1132
1133     yaz_log(LOG_DEBUG, "Diagnostic: %d -- %s", error, addinfo ? addinfo :
1134         "NULL");
1135     rec->which = Z_Records_NSD;
1136 #if ASN_COMPILED
1137     rec->u.nonSurrogateDiagnostic = dr;
1138 #else
1139     rec->u.nonSurrogateDiagnostic = drec;
1140     drec->which = Z_DiagRec_defaultFormat;
1141     drec->u.defaultFormat = dr;
1142 #endif
1143     dr->diagnosticSetId =
1144         odr_oiddup (assoc->encode, oid_ent_to_oid(&bib1, oid));
1145     dr->condition = err;
1146     set_addinfo (dr, addinfo, assoc->encode);
1147     return rec;
1148 }
1149
1150 /*
1151  * surrogate diagnostic.
1152  */
1153 static Z_NamePlusRecord *surrogatediagrec(association *assoc, char *dbname,
1154                                           int error, char *addinfo)
1155 {
1156     int oid[OID_SIZE];
1157     Z_NamePlusRecord *rec = (Z_NamePlusRecord *)
1158         odr_malloc (assoc->encode, sizeof(*rec));
1159     int *err = odr_intdup(assoc->encode, error);
1160     oident bib1;
1161     Z_DiagRec *drec = (Z_DiagRec *)odr_malloc (assoc->encode, sizeof(*drec));
1162     Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
1163         odr_malloc (assoc->encode, sizeof(*dr));
1164     
1165     bib1.proto = assoc->proto;
1166     bib1.oclass = CLASS_DIAGSET;
1167     bib1.value = VAL_BIB1;
1168
1169     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);
1179
1180     return rec;
1181 }
1182
1183 /*
1184  * multiple nonsurrogate diagnostics.
1185  */
1186 static Z_DiagRecs *diagrecs(association *assoc, int error, char *addinfo)
1187 {
1188     int oid[OID_SIZE];
1189     Z_DiagRecs *recs = (Z_DiagRecs *)odr_malloc (assoc->encode, sizeof(*recs));
1190     int *err = odr_intdup(assoc->encode, error);
1191     oident bib1;
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));
1195
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;
1200
1201     recs->num_diagRecs = 1;
1202     recs->diagRecs = recp;
1203     recp[0] = drec;
1204     drec->which = Z_DiagRec_defaultFormat;
1205     drec->u.defaultFormat = rec;
1206
1207     rec->diagnosticSetId = odr_oiddup (assoc->encode,
1208                                       oid_ent_to_oid(&bib1, oid));
1209     rec->condition = err;
1210
1211 #ifdef ASN_COMPILED
1212     rec->which = Z_DefaultDiagFormat_v2Addinfo;
1213     rec->u.v2Addinfo = odr_strdup (assoc->encode, addinfo ? addinfo : "");
1214 #else
1215     rec->which = Z_DiagForm_v2AddInfo;
1216     rec->addinfo = odr_strdup (assoc->encode, addinfo ? addinfo : "");
1217 #endif
1218     return recs;
1219 }
1220
1221 static Z_Records *pack_records(association *a, char *setname, int start,
1222                                int *num, Z_RecordComposition *comp,
1223                                int *next, int *pres, oid_value format,
1224                                Z_ReferenceId *referenceId,
1225                                int *oid)
1226 {
1227     int recno, total_length = 0, toget = *num, dumped_records = 0;
1228     Z_Records *records =
1229         (Z_Records *) odr_malloc (a->encode, sizeof(*records));
1230     Z_NamePlusRecordList *reclist =
1231         (Z_NamePlusRecordList *) odr_malloc (a->encode, sizeof(*reclist));
1232     Z_NamePlusRecord **list =
1233         (Z_NamePlusRecord **) odr_malloc (a->encode, sizeof(*list) * toget);
1234
1235     records->which = Z_Records_DBOSD;
1236     records->u.databaseOrSurDiagnostics = reclist;
1237     reclist->num_records = 0;
1238     reclist->records = list;
1239     *pres = Z_PRES_SUCCESS;
1240     *num = 0;
1241     *next = 0;
1242
1243     yaz_log(LOG_LOG, "Request to pack %d+%d", start, toget);
1244     yaz_log(LOG_DEBUG, "pms=%d, mrs=%d", a->preferredMessageSize,
1245         a->maximumRecordSize);
1246     for (recno = start; reclist->num_records < toget; recno++)
1247     {
1248         bend_fetch_rr freq;
1249         Z_NamePlusRecord *thisrec;
1250         int this_length = 0;
1251         /*
1252          * we get the number of bytes allocated on the stream before any
1253          * allocation done by the backend - this should give us a reasonable
1254          * idea of the total size of the data so far.
1255          */
1256         total_length = odr_total(a->encode) - dumped_records;
1257         freq.errcode = 0;
1258         freq.errstring = 0;
1259         freq.basename = 0;
1260         freq.len = 0;
1261         freq.record = 0;
1262         freq.last_in_set = 0;
1263         freq.setname = setname;
1264         freq.surrogate_flag = 0;
1265         freq.number = recno;
1266         freq.comp = comp;
1267         freq.request_format = format;
1268         freq.request_format_raw = oid;
1269         freq.output_format = format;
1270         freq.output_format_raw = 0;
1271         freq.stream = a->encode;
1272         freq.print = a->print;
1273         freq.surrogate_flag = 0;
1274         freq.referenceId = referenceId;
1275         (*a->init->bend_fetch)(a->backend, &freq);
1276         /* backend should be able to signal whether error is system-wide
1277            or only pertaining to current record */
1278         if (freq.errcode)
1279         {
1280             if (!freq.surrogate_flag)
1281             {
1282                 *pres = Z_PRES_FAILURE;
1283                 return diagrec(a, freq.errcode, freq.errstring);
1284             }
1285             reclist->records[reclist->num_records] =
1286                 surrogatediagrec(a, freq.basename, freq.errcode,
1287                                  freq.errstring);
1288             reclist->num_records++;
1289             *next = freq.last_in_set ? 0 : recno + 1;
1290             continue;
1291         }
1292         if (freq.len >= 0)
1293             this_length = freq.len;
1294         else
1295             this_length = odr_total(a->encode) - total_length;
1296         yaz_log(LOG_DEBUG, "  fetched record, len=%d, total=%d",
1297             this_length, total_length);
1298         if (this_length + total_length > a->preferredMessageSize)
1299         {
1300             /* record is small enough, really */
1301             if (this_length <= a->preferredMessageSize)
1302             {
1303                 yaz_log(LOG_DEBUG, "  Dropped last normal-sized record");
1304                 *pres = Z_PRES_PARTIAL_2;
1305                 break;
1306             }
1307             /* record can only be fetched by itself */
1308             if (this_length < a->maximumRecordSize)
1309             {
1310                 yaz_log(LOG_DEBUG, "  Record > prefmsgsz");
1311                 if (toget > 1)
1312                 {
1313                     yaz_log(LOG_DEBUG, "  Dropped it");
1314                     reclist->records[reclist->num_records] =
1315                          surrogatediagrec(a, freq.basename, 16, 0);
1316                     reclist->num_records++;
1317                     *next = freq.last_in_set ? 0 : recno + 1;
1318                     dumped_records += this_length;
1319                     continue;
1320                 }
1321             }
1322             else /* too big entirely */
1323             {
1324                 yaz_log(LOG_DEBUG, "Record > maxrcdsz");
1325                 reclist->records[reclist->num_records] =
1326                     surrogatediagrec(a, freq.basename, 17, 0);
1327                 reclist->num_records++;
1328                 *next = freq.last_in_set ? 0 : recno + 1;
1329                 dumped_records += this_length;
1330                 continue;
1331             }
1332         }
1333
1334         if (!(thisrec = (Z_NamePlusRecord *)
1335               odr_malloc(a->encode, sizeof(*thisrec))))
1336             return 0;
1337         if (!(thisrec->databaseName = (char *)odr_malloc(a->encode,
1338             strlen(freq.basename) + 1)))
1339             return 0;
1340         strcpy(thisrec->databaseName, freq.basename);
1341         thisrec->which = Z_NamePlusRecord_databaseRecord;
1342
1343         if (freq.output_format_raw)
1344         {
1345             struct oident *ident = oid_getentbyoid(freq.output_format_raw);
1346             freq.output_format = ident->value;
1347         }
1348         thisrec->u.databaseRecord = z_ext_record(a->encode, freq.output_format,
1349                                                  freq.record, freq.len);
1350         if (!thisrec->u.databaseRecord)
1351             return 0;
1352         reclist->records[reclist->num_records] = thisrec;
1353         reclist->num_records++;
1354         *next = freq.last_in_set ? 0 : recno + 1;
1355     }
1356     *num = reclist->num_records;
1357     return records;
1358 }
1359
1360 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
1361     int *fd)
1362 {
1363     Z_SearchRequest *req = reqb->request->u.searchRequest;
1364     bend_search_rr *bsrr = 
1365         (bend_search_rr *)nmem_malloc (reqb->request_mem, sizeof(*bsrr));
1366     
1367     yaz_log(LOG_LOG, "Got SearchRequest.");
1368     bsrr->fd = fd;
1369     bsrr->request = reqb;
1370     bsrr->association = assoc;
1371     bsrr->referenceId = req->referenceId;
1372     save_referenceId (reqb, bsrr->referenceId);
1373
1374     yaz_log (LOG_LOG, "ResultSet '%s'", req->resultSetName);
1375     if (req->databaseNames)
1376     {
1377         int i;
1378         for (i = 0; i < req->num_databaseNames; i++)
1379             yaz_log (LOG_LOG, "Database '%s'", req->databaseNames[i]);
1380     }
1381     switch (req->query->which)
1382     {
1383     case Z_Query_type_1: case Z_Query_type_101:
1384         log_rpn_query (req->query->u.type_1);
1385     }
1386     if (assoc->init->bend_search)
1387     {
1388         bsrr->setname = req->resultSetName;
1389         bsrr->replace_set = *req->replaceIndicator;
1390         bsrr->num_bases = req->num_databaseNames;
1391         bsrr->basenames = req->databaseNames;
1392         bsrr->query = req->query;
1393         bsrr->stream = assoc->encode;
1394         bsrr->decode = assoc->decode;
1395         bsrr->print = assoc->print;
1396         bsrr->errcode = 0;
1397         bsrr->hits = 0;
1398         bsrr->errstring = NULL;
1399         (assoc->init->bend_search)(assoc->backend, bsrr);
1400         if (!bsrr->request)
1401             return 0;
1402     }
1403 #if 0
1404     else
1405     {
1406         bend_searchrequest bsrq;
1407         bend_searchresult *bsrt;
1408
1409         bsrq.setname = req->resultSetName;
1410         bsrq.replace_set = *req->replaceIndicator;
1411         bsrq.num_bases = req->num_databaseNames;
1412         bsrq.basenames = req->databaseNames;
1413         bsrq.query = req->query;
1414         bsrq.referenceId = req->referenceId;
1415         bsrq.stream = assoc->encode;
1416         bsrq.decode = assoc->decode;
1417         bsrq.print = assoc->print;
1418         if (!(bsrt = bend_search (assoc->backend, &bsrq, fd)))
1419             return 0;
1420         bsrr->hits = bsrt->hits;
1421         bsrr->errcode = bsrt->errcode;
1422         bsrr->errstring = bsrt->errstring;
1423     }
1424 #endif
1425     return response_searchRequest(assoc, reqb, bsrr, fd);
1426 }
1427
1428 int bend_searchresponse(void *handle, bend_search_rr *bsrr) {return 0;}
1429
1430 /*
1431  * Prepare a searchresponse based on the backend results. We probably want
1432  * to look at making the fetching of records nonblocking as well, but
1433  * so far, we'll keep things simple.
1434  * If bsrt is null, that means we're called in response to a communications
1435  * event, and we'll have to get the response for ourselves.
1436  */
1437 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
1438     bend_search_rr *bsrt, int *fd)
1439 {
1440     Z_SearchRequest *req = reqb->request->u.searchRequest;
1441     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1442     Z_SearchResponse *resp = (Z_SearchResponse *)
1443         odr_malloc (assoc->encode, sizeof(*resp));
1444     int *nulint = odr_intdup (assoc->encode, 0);
1445     bool_t *sr = odr_intdup(assoc->encode, 1);
1446     int *next = odr_intdup(assoc->encode, 0);
1447     int *none = odr_intdup(assoc->encode, Z_RES_NONE);
1448
1449     apdu->which = Z_APDU_searchResponse;
1450     apdu->u.searchResponse = resp;
1451     resp->referenceId = req->referenceId;
1452     resp->additionalSearchInfo = 0;
1453     resp->otherInfo = 0;
1454     *fd = -1;
1455     if (!bsrt && !bend_searchresponse(assoc->backend, bsrt))
1456     {
1457         yaz_log(LOG_FATAL, "Bad result from backend");
1458         return 0;
1459     }
1460     else if (bsrt->errcode)
1461     {
1462         resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
1463         resp->resultCount = nulint;
1464         resp->numberOfRecordsReturned = nulint;
1465         resp->nextResultSetPosition = nulint;
1466         resp->searchStatus = nulint;
1467         resp->resultSetStatus = none;
1468         resp->presentStatus = 0;
1469     }
1470     else
1471     {
1472         int *toget = odr_intdup(assoc->encode, 0);
1473         int *presst = odr_intdup(assoc->encode, 0);
1474         Z_RecordComposition comp, *compp = 0;
1475
1476         resp->records = 0;
1477         resp->resultCount = &bsrt->hits;
1478
1479         comp.which = Z_RecordComp_simple;
1480         /* how many records does the user agent want, then? */
1481         if (bsrt->hits <= *req->smallSetUpperBound)
1482         {
1483             *toget = bsrt->hits;
1484             if ((comp.u.simple = req->smallSetElementSetNames))
1485                 compp = &comp;
1486         }
1487         else if (bsrt->hits < *req->largeSetLowerBound)
1488         {
1489             *toget = *req->mediumSetPresentNumber;
1490             if (*toget > bsrt->hits)
1491                 *toget = bsrt->hits;
1492             if ((comp.u.simple = req->mediumSetElementSetNames))
1493                 compp = &comp;
1494         }
1495         else
1496             *toget = 0;
1497
1498         if (*toget && !resp->records)
1499         {
1500             oident *prefformat;
1501             oid_value form;
1502
1503             if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1504                 prefformat->oclass != CLASS_RECSYN)
1505                 form = VAL_NONE;
1506             else
1507                 form = prefformat->value;
1508             resp->records = pack_records(assoc, req->resultSetName, 1,
1509                 toget, compp, next, presst, form, req->referenceId,
1510                                          req->preferredRecordSyntax);
1511             if (!resp->records)
1512                 return 0;
1513             resp->numberOfRecordsReturned = toget;
1514             resp->nextResultSetPosition = next;
1515             resp->searchStatus = sr;
1516             resp->resultSetStatus = 0;
1517             resp->presentStatus = presst;
1518         }
1519         else
1520         {
1521             if (*resp->resultCount)
1522                 *next = 1;
1523             resp->numberOfRecordsReturned = nulint;
1524             resp->nextResultSetPosition = next;
1525             resp->searchStatus = sr;
1526             resp->resultSetStatus = 0;
1527             resp->presentStatus = 0;
1528         }
1529     }
1530     return apdu;
1531 }
1532
1533 /*
1534  * Maybe we got a little over-friendly when we designed bend_fetch to
1535  * get only one record at a time. Some backends can optimise multiple-record
1536  * fetches, and at any rate, there is some overhead involved in
1537  * all that selecting and hopping around. Problem is, of course, that the
1538  * frontend can't know ahead of time how many records it'll need to
1539  * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
1540  * is downright lousy as a bulk data transfer protocol.
1541  *
1542  * To start with, we'll do the fetching of records from the backend
1543  * in one operation: To save some trips in and out of the event-handler,
1544  * and to simplify the interface to pack_records. At any rate, asynch
1545  * operation is more fun in operations that have an unpredictable execution
1546  * speed - which is normally more true for search than for present.
1547  */
1548 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
1549                                       int *fd)
1550 {
1551     Z_PresentRequest *req = reqb->request->u.presentRequest;
1552     oident *prefformat;
1553     oid_value form;
1554     Z_APDU *apdu;
1555     Z_PresentResponse *resp;
1556     int *presst;
1557     int *next;
1558     int *num;
1559
1560     yaz_log(LOG_LOG, "Got PresentRequest.");
1561
1562     if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1563         prefformat->oclass != CLASS_RECSYN)
1564         form = VAL_NONE;
1565     else
1566         form = prefformat->value;
1567     if (assoc->init->bend_present)
1568     {
1569         bend_present_rr *bprr = (bend_present_rr *)
1570             nmem_malloc (reqb->request_mem, sizeof(*bprr));
1571         bprr->setname = req->resultSetId;
1572         bprr->start = *req->resultSetStartPoint;
1573         bprr->number = *req->numberOfRecordsRequested;
1574         bprr->format = form;
1575         bprr->comp = req->recordComposition;
1576         bprr->referenceId = req->referenceId;
1577         bprr->stream = assoc->encode;
1578         bprr->print = assoc->print;
1579         bprr->request = reqb;
1580         bprr->association = assoc;
1581         bprr->errcode = 0;
1582         bprr->errstring = NULL;
1583         (*assoc->init->bend_present)(assoc->backend, bprr);
1584         
1585         if (!bprr->request)
1586             return 0;
1587     }
1588     apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1589     resp = (Z_PresentResponse *)odr_malloc (assoc->encode, sizeof(*resp));
1590     presst = odr_intdup(assoc->encode, 0);
1591     next = odr_intdup(assoc->encode, 0);
1592     num = odr_intdup(assoc->encode, *req->numberOfRecordsRequested);
1593     
1594     apdu->which = Z_APDU_presentResponse;
1595     apdu->u.presentResponse = resp;
1596     resp->referenceId = req->referenceId;
1597     resp->otherInfo = 0;
1598     
1599     resp->records =
1600         pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
1601                      num, req->recordComposition, next, presst, form,
1602                      req->referenceId, req->preferredRecordSyntax);
1603     if (!resp->records)
1604         return 0;
1605     resp->numberOfRecordsReturned = num;
1606     resp->presentStatus = presst;
1607     resp->nextResultSetPosition = next;
1608     
1609     return apdu;
1610 }
1611
1612 /*
1613  * Scan was implemented rather in a hurry, and with support for only the basic
1614  * elements of the service in the backend API. Suggestions are welcome.
1615  */
1616 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
1617 {
1618     Z_ScanRequest *req = reqb->request->u.scanRequest;
1619     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1620     Z_ScanResponse *res = (Z_ScanResponse *)
1621         odr_malloc (assoc->encode, sizeof(*res));
1622     int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
1623     int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
1624     Z_ListEntries *ents = (Z_ListEntries *)
1625         odr_malloc (assoc->encode, sizeof(*ents));
1626     Z_DiagRecs *diagrecs_p = NULL;
1627     oident *attent;
1628     oident *attset;
1629
1630     yaz_log(LOG_LOG, "Got ScanRequest");
1631
1632     apdu->which = Z_APDU_scanResponse;
1633     apdu->u.scanResponse = res;
1634     res->referenceId = req->referenceId;
1635     res->stepSize = odr_intdup(assoc->encode, 0);
1636
1637     if (req->stepSize)
1638         *res->stepSize = *req->stepSize;
1639     res->scanStatus = scanStatus;
1640     res->numberOfEntriesReturned = numberOfEntriesReturned;
1641     res->positionOfTerm = 0;
1642     res->entries = ents;
1643     ents->num_entries = 0;
1644     ents->entries = NULL;
1645     ents->num_nonsurrogateDiagnostics = 0;
1646     ents->nonsurrogateDiagnostics = NULL;
1647     res->attributeSet = 0;
1648     res->otherInfo = 0;
1649
1650     if (req->attributeSet && (!(attent = oid_getentbyoid(req->attributeSet)) ||
1651                               attent->oclass != CLASS_ATTSET
1652                               || attent->value != VAL_BIB1))
1653         diagrecs_p = diagrecs(assoc, 121, 0);
1654     else if (req->stepSize && *req->stepSize > 0)
1655         diagrecs_p = diagrecs(assoc, 205, 0);
1656     else
1657     {
1658         bend_scan_rr *bsrr = (bend_scan_rr *)
1659             odr_malloc (assoc->encode, sizeof(*bsrr));
1660         if (req->databaseNames)
1661         {
1662             int i;
1663             for (i = 0; i < req->num_databaseNames; i++)
1664                 yaz_log (LOG_LOG, "Database '%s'", req->databaseNames[i]);
1665         }
1666         bsrr->num_bases = req->num_databaseNames;
1667         bsrr->basenames = req->databaseNames;
1668         bsrr->num_entries = *req->numberOfTermsRequested;
1669         bsrr->term = req->termListAndStartPoint;
1670         bsrr->referenceId = req->referenceId;
1671         bsrr->stream = assoc->encode;
1672         bsrr->print = assoc->print;
1673         bsrr->step_size = res->stepSize;
1674         if (!(attset = oid_getentbyoid(req->attributeSet)) ||
1675             attset->oclass != CLASS_RECSYN)
1676             bsrr->attributeset = VAL_NONE;
1677         else
1678             bsrr->attributeset = attset->value;
1679         log_scan_term (req->termListAndStartPoint, bsrr->attributeset);
1680         bsrr->term_position = req->preferredPositionInResponse ?
1681             *req->preferredPositionInResponse : 1;
1682         ((int (*)(void *, bend_scan_rr *))
1683          (*assoc->init->bend_scan))(assoc->backend, bsrr);
1684         if (bsrr->errcode)
1685             diagrecs_p = diagrecs(assoc, bsrr->errcode, bsrr->errstring);
1686         else
1687         {
1688             int i;
1689             Z_Entry **tab = (Z_Entry **)
1690                 odr_malloc (assoc->encode, sizeof(*tab) * bsrr->num_entries);
1691             
1692             if (bsrr->status == BEND_SCAN_PARTIAL)
1693                 *scanStatus = Z_Scan_partial_5;
1694             else
1695                 *scanStatus = Z_Scan_success;
1696             ents->entries = tab;
1697             ents->num_entries = bsrr->num_entries;
1698             res->numberOfEntriesReturned = &ents->num_entries;      
1699             res->positionOfTerm = &bsrr->term_position;
1700             for (i = 0; i < bsrr->num_entries; i++)
1701             {
1702                 Z_Entry *e;
1703                 Z_TermInfo *t;
1704                 Odr_oct *o;
1705                 
1706                 tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
1707                 if (bsrr->entries[i].occurrences >= 0)
1708                 {
1709                     e->which = Z_Entry_termInfo;
1710                     e->u.termInfo = t = (Z_TermInfo *)
1711                         odr_malloc(assoc->encode, sizeof(*t));
1712                     t->suggestedAttributes = 0;
1713                     t->displayTerm = 0;
1714                     t->alternativeTerm = 0;
1715                     t->byAttributes = 0;
1716                     t->otherTermInfo = 0;
1717                     t->globalOccurrences = &bsrr->entries[i].occurrences;
1718                     t->term = (Z_Term *)
1719                         odr_malloc(assoc->encode, sizeof(*t->term));
1720                     t->term->which = Z_Term_general;
1721                     t->term->u.general = o =
1722                         (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
1723                     o->buf = (unsigned char *)
1724                         odr_malloc(assoc->encode, o->len = o->size =
1725                                    strlen(bsrr->entries[i].term));
1726                     memcpy(o->buf, bsrr->entries[i].term, o->len);
1727                     yaz_log(LOG_DEBUG, "  term #%d: '%s' (%d)", i,
1728                          bsrr->entries[i].term, bsrr->entries[i].occurrences);
1729                 }
1730                 else
1731                 {
1732                     Z_DiagRecs *drecs = diagrecs (assoc,
1733                                                   bsrr->entries[i].errcode,
1734                                                   bsrr->entries[i].errstring);
1735                     assert (drecs->num_diagRecs == 1);
1736                     e->which = Z_Entry_surrogateDiagnostic;
1737                     assert (drecs->diagRecs[0]);
1738                     e->u.surrogateDiagnostic = drecs->diagRecs[0];
1739                 }
1740             }
1741         }
1742     }
1743     if (diagrecs_p)
1744     {
1745         ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
1746         ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
1747     }
1748     return apdu;
1749 }
1750
1751 static Z_APDU *process_sortRequest(association *assoc, request *reqb,
1752     int *fd)
1753 {
1754     Z_SortRequest *req = reqb->request->u.sortRequest;
1755     Z_SortResponse *res = (Z_SortResponse *)
1756         odr_malloc (assoc->encode, sizeof(*res));
1757     bend_sort_rr *bsrr = (bend_sort_rr *)
1758         odr_malloc (assoc->encode, sizeof(*bsrr));
1759
1760     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1761
1762     yaz_log(LOG_LOG, "Got SortRequest.");
1763
1764 #ifdef ASN_COMPILED
1765     bsrr->num_input_setnames = req->num_inputResultSetNames;
1766     bsrr->input_setnames = req->inputResultSetNames;
1767 #else
1768     bsrr->num_input_setnames = req->inputResultSetNames->num_strings;
1769     bsrr->input_setnames = req->inputResultSetNames->strings;
1770 #endif
1771     bsrr->referenceId = req->referenceId;
1772     bsrr->output_setname = req->sortedResultSetName;
1773     bsrr->sort_sequence = req->sortSequence;
1774     bsrr->stream = assoc->encode;
1775     bsrr->print = assoc->print;
1776
1777     bsrr->sort_status = Z_SortStatus_failure;
1778     bsrr->errcode = 0;
1779     bsrr->errstring = 0;
1780     
1781     (*assoc->init->bend_sort)(assoc->backend, bsrr);
1782     
1783     res->referenceId = bsrr->referenceId;
1784     res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
1785     res->resultSetStatus = 0;
1786     if (bsrr->errcode)
1787     {
1788         Z_DiagRecs *dr = diagrecs (assoc, bsrr->errcode, bsrr->errstring);
1789 #ifdef ASN_COMPILED
1790         res->diagnostics = dr->diagRecs;
1791         res->num_diagnostics = dr->num_diagRecs;
1792 #else
1793         res->diagnostics = dr;
1794 #endif
1795     }
1796     else
1797     {
1798 #ifdef ASN_COMPILED
1799         res->num_diagnostics = 0;
1800 #endif
1801         res->diagnostics = 0;
1802     }
1803     res->otherInfo = 0;
1804
1805     apdu->which = Z_APDU_sortResponse;
1806     apdu->u.sortResponse = res;
1807     return apdu;
1808 }
1809
1810 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
1811     int *fd)
1812 {
1813     Z_DeleteResultSetRequest *req = reqb->request->u.deleteResultSetRequest;
1814     Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
1815         odr_malloc (assoc->encode, sizeof(*res));
1816     bend_delete_rr *bdrr = (bend_delete_rr *)
1817         odr_malloc (assoc->encode, sizeof(*bdrr));
1818     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1819
1820     yaz_log(LOG_LOG, "Got DeleteRequest.");
1821
1822     bdrr->num_setnames = req->num_resultSetList;
1823     bdrr->setnames = req->resultSetList;
1824     bdrr->stream = assoc->encode;
1825     bdrr->print = assoc->print;
1826     bdrr->function = *req->deleteFunction;
1827     bdrr->referenceId = req->referenceId;
1828     bdrr->statuses = 0;
1829     if (bdrr->num_setnames > 0)
1830     {
1831         int i;
1832         bdrr->statuses = (int*) 
1833             odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
1834                        bdrr->num_setnames);
1835         for (i = 0; i < bdrr->num_setnames; i++)
1836             bdrr->statuses[i] = 0;
1837     }
1838     (*assoc->init->bend_delete)(assoc->backend, bdrr);
1839     
1840     res->referenceId = req->referenceId;
1841
1842     res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
1843
1844     res->deleteListStatuses = 0;
1845     if (bdrr->num_setnames > 0)
1846     {
1847         int i;
1848         res->deleteListStatuses = (Z_ListStatuses *)
1849             odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
1850         res->deleteListStatuses->num = bdrr->num_setnames;
1851         res->deleteListStatuses->elements =
1852             (Z_ListStatus **)
1853             odr_malloc (assoc->encode, 
1854                         sizeof(*res->deleteListStatuses->elements) *
1855                         bdrr->num_setnames);
1856         for (i = 0; i<bdrr->num_setnames; i++)
1857         {
1858             res->deleteListStatuses->elements[i] =
1859                 (Z_ListStatus *)
1860                 odr_malloc (assoc->encode,
1861                             sizeof(**res->deleteListStatuses->elements));
1862             res->deleteListStatuses->elements[i]->status = bdrr->statuses+i;
1863             res->deleteListStatuses->elements[i]->id =
1864                 odr_strdup (assoc->encode, bdrr->setnames[i]);
1865             
1866         }
1867     }
1868     res->numberNotDeleted = 0;
1869     res->bulkStatuses = 0;
1870     res->deleteMessage = 0;
1871     res->otherInfo = 0;
1872
1873     apdu->which = Z_APDU_deleteResultSetResponse;
1874     apdu->u.deleteResultSetResponse = res;
1875     return apdu;
1876 }
1877
1878 static void process_close(association *assoc, request *reqb)
1879 {
1880     Z_Close *req = reqb->request->u.close;
1881     static char *reasons[] =
1882     {
1883         "finished",
1884         "shutdown",
1885         "systemProblem",
1886         "costLimit",
1887         "resources",
1888         "securityViolation",
1889         "protocolError",
1890         "lackOfActivity",
1891         "peerAbort",
1892         "unspecified"
1893     };
1894
1895     yaz_log(LOG_LOG, "Got Close, reason %s, message %s",
1896         reasons[*req->closeReason], req->diagnosticInformation ?
1897         req->diagnosticInformation : "NULL");
1898     if (assoc->version < 3) /* to make do_force respond with close */
1899         assoc->version = 3;
1900     do_close_req(assoc, Z_Close_finished,
1901                  "Association terminated by client", reqb);
1902 }
1903
1904 void save_referenceId (request *reqb, Z_ReferenceId *refid)
1905 {
1906     if (refid)
1907     {
1908         reqb->len_refid = refid->len;
1909         reqb->refid = (char *)nmem_malloc (reqb->request_mem, refid->len);
1910         memcpy (reqb->refid, refid->buf, refid->len);
1911     }
1912     else
1913     {
1914         reqb->len_refid = 0;
1915         reqb->refid = NULL;
1916     }
1917 }
1918
1919 void bend_request_send (bend_association a, bend_request req, Z_APDU *res)
1920 {
1921     process_response (a, req, res);
1922 }
1923
1924 bend_request bend_request_mk (bend_association a)
1925 {
1926     request *nreq = request_get (&a->outgoing);
1927     nreq->request_mem = nmem_create ();
1928     return nreq;
1929 }
1930
1931 Z_ReferenceId *bend_request_getid (ODR odr, bend_request req)
1932 {
1933     Z_ReferenceId *id;
1934     if (!req->refid)
1935         return 0;
1936     id = (Odr_oct *)odr_malloc (odr, sizeof(*odr));
1937     id->buf = (unsigned char *)odr_malloc (odr, req->len_refid);
1938     id->len = id->size = req->len_refid;
1939     memcpy (id->buf, req->refid, req->len_refid);
1940     return id;
1941 }
1942
1943 void bend_request_destroy (bend_request *req)
1944 {
1945     nmem_destroy((*req)->request_mem);
1946     request_release(*req);
1947     *req = NULL;
1948 }
1949
1950 int bend_backend_respond (bend_association a, bend_request req)
1951 {
1952     char *msg;
1953     int r;
1954     r = process_request (a, req, &msg);
1955     if (r < 0)
1956         logf (LOG_WARN, "%s", msg);
1957     return r;
1958 }
1959
1960 void bend_request_setdata(bend_request r, void *p)
1961 {
1962     r->clientData = p;
1963 }
1964
1965 void *bend_request_getdata(bend_request r)
1966 {
1967     return r->clientData;
1968 }
1969
1970 static Z_APDU *process_segmentRequest (association *assoc, request *reqb)
1971 {
1972     bend_segment_rr request;
1973
1974     request.segment = reqb->request->u.segmentRequest;
1975     request.stream = assoc->encode;
1976     request.decode = assoc->decode;
1977     request.print = assoc->print;
1978     request.association = assoc;
1979     
1980     (*assoc->init->bend_segment)(assoc->backend, &request);
1981
1982     return 0;
1983 }
1984
1985 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd)
1986 {
1987     bend_esrequest_rr esrequest;
1988
1989     Z_ExtendedServicesRequest *req = reqb->request->u.extendedServicesRequest;
1990     Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
1991
1992     Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
1993
1994     yaz_log(LOG_DEBUG,"inside Process esRequest");
1995
1996     esrequest.esr = reqb->request->u.extendedServicesRequest;
1997     esrequest.stream = assoc->encode;
1998     esrequest.decode = assoc->decode;
1999     esrequest.print = assoc->print;
2000     esrequest.errcode = 0;
2001     esrequest.errstring = NULL;
2002     esrequest.request = reqb;
2003     esrequest.association = assoc;
2004     esrequest.taskPackage = 0;
2005     esrequest.referenceId = req->referenceId;
2006     
2007     (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
2008     
2009     /* If the response is being delayed, return NULL */
2010     if (esrequest.request == NULL)
2011         return(NULL);
2012
2013     resp->referenceId = req->referenceId;
2014
2015     if (esrequest.errcode == -1)
2016     {
2017         /* Backend service indicates request will be processed */
2018         yaz_log(LOG_DEBUG,"Request could be processed...Accepted !");
2019         *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
2020     }
2021     else if (esrequest.errcode == 0)
2022     {
2023         /* Backend service indicates request will be processed */
2024         yaz_log(LOG_DEBUG,"Request could be processed...Done !");
2025         *resp->operationStatus = Z_ExtendedServicesResponse_done;
2026     }
2027     else
2028     {
2029         Z_DiagRecs *diagRecs = diagrecs (assoc, esrequest.errcode,
2030                                          esrequest.errstring);
2031
2032         /* Backend indicates error, request will not be processed */
2033         yaz_log(LOG_DEBUG,"Request could not be processed...failure !");
2034         *resp->operationStatus = Z_ExtendedServicesResponse_failure;
2035         resp->num_diagnostics = diagRecs->num_diagRecs;
2036         resp->diagnostics = diagRecs->diagRecs;
2037     }
2038     /* Do something with the members of bend_extendedservice */
2039     if (esrequest.taskPackage)
2040         resp->taskPackage = z_ext_record (assoc->encode, VAL_EXTENDED,
2041                                          (const char *)  esrequest.taskPackage,
2042                                           -1);
2043     yaz_log(LOG_DEBUG,"Send the result apdu");
2044     return apdu;
2045 }