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