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