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