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