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