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