Implementation_name and implementation_version copied verbatim.
[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.97  1999-11-29 14:36:28  adam
8  * Implementation_name and implementation_version copied verbatim.
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 <yconfig.h>
339 #include <stdlib.h>
340 #include <stdio.h>
341 #ifdef WIN32
342 #include <process.h>
343 #else
344 #include <unistd.h>
345 #endif
346 #include <assert.h>
347
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 = "Index Data/YAZ Generic Frontend Server";
932
933     if (binitreq.implementation_name)
934         resp->implementationName = binitreq.implementation_name;
935     if (binitreq.implementation_version)
936         resp->implementationVersion = binitreq.implementation_version;
937
938     if (binitres->errcode)
939     {
940         yaz_log(LOG_LOG, "Connection rejected by backend.");
941         *resp->result = 0;
942         assoc->state = ASSOC_DEAD;
943     }
944     else
945         assoc->state = ASSOC_UP;
946     return apdu;
947 }
948
949 /*
950  * These functions should be merged.
951  */
952
953 static void set_addinfo (Z_DefaultDiagFormat *dr, char *addinfo)
954 {
955 #if ASN_COMPILED
956     dr->which = Z_DefaultDiagFormat_v2Addinfo;
957     dr->u.v2Addinfo = addinfo ? addinfo : "";
958 #else
959     dr->which = Z_DiagForm_v2AddInfo;
960     dr->addinfo = addinfo ? addinfo : "";
961 #endif
962 }
963
964 /*
965  * nonsurrogate diagnostic record.
966  */
967 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
968 {
969     int oid[OID_SIZE];
970     Z_Records *rec = (Z_Records *)
971         odr_malloc (assoc->encode, sizeof(*rec));
972     oident bib1;
973     int *err = (int *)
974         odr_malloc (assoc->encode, sizeof(*err));
975     Z_DiagRec *drec = (Z_DiagRec *)
976         odr_malloc (assoc->encode, sizeof(*drec));
977     Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
978         odr_malloc (assoc->encode, sizeof(*dr));
979
980     bib1.proto = assoc->proto;
981     bib1.oclass = CLASS_DIAGSET;
982     bib1.value = VAL_BIB1;
983
984     yaz_log(LOG_DEBUG, "Diagnostic: %d -- %s", error, addinfo ? addinfo :
985         "NULL");
986     *err = error;
987     rec->which = Z_Records_NSD;
988 #if ASN_COMPILED
989     rec->u.nonSurrogateDiagnostic = dr;
990 #else
991     rec->u.nonSurrogateDiagnostic = drec;
992     drec->which = Z_DiagRec_defaultFormat;
993     drec->u.defaultFormat = dr;
994 #endif
995     dr->diagnosticSetId =
996         odr_oiddup (assoc->encode, oid_ent_to_oid(&bib1, oid));
997     dr->condition = err;
998     set_addinfo (dr, addinfo);
999     return rec;
1000 }
1001
1002 /*
1003  * surrogate diagnostic.
1004  */
1005 static Z_NamePlusRecord *surrogatediagrec(association *assoc, char *dbname,
1006                                           int error, char *addinfo)
1007 {
1008     int oid[OID_SIZE];
1009     Z_NamePlusRecord *rec = (Z_NamePlusRecord *)
1010         odr_malloc (assoc->encode, sizeof(*rec));
1011     int *err = (int *)odr_malloc (assoc->encode, sizeof(*err));
1012     oident bib1;
1013     Z_DiagRec *drec = (Z_DiagRec *)odr_malloc (assoc->encode, sizeof(*drec));
1014     Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
1015         odr_malloc (assoc->encode, sizeof(*dr));
1016     
1017     bib1.proto = assoc->proto;
1018     bib1.oclass = CLASS_DIAGSET;
1019     bib1.value = VAL_BIB1;
1020
1021     yaz_log(LOG_DEBUG, "SurrogateDiagnotic: %d -- %s", error, addinfo);
1022     *err = error;
1023     rec->databaseName = dbname;
1024     rec->which = Z_NamePlusRecord_surrogateDiagnostic;
1025     rec->u.surrogateDiagnostic = drec;
1026     drec->which = Z_DiagRec_defaultFormat;
1027     drec->u.defaultFormat = dr;
1028     dr->diagnosticSetId = odr_oiddup (assoc->encode,
1029                                       oid_ent_to_oid(&bib1, oid));
1030     dr->condition = err;
1031     set_addinfo (dr, addinfo);
1032
1033     return rec;
1034 }
1035
1036 /*
1037  * multiple nonsurrogate diagnostics.
1038  */
1039 static Z_DiagRecs *diagrecs(association *assoc, int error, char *addinfo)
1040 {
1041     int oid[OID_SIZE];
1042     Z_DiagRecs *recs = (Z_DiagRecs *)odr_malloc (assoc->encode, sizeof(*recs));
1043     int *err = (int *)odr_malloc (assoc->encode, sizeof(*err));
1044     oident bib1;
1045     Z_DiagRec **recp = (Z_DiagRec **)odr_malloc (assoc->encode, sizeof(*recp));
1046     Z_DiagRec *drec = (Z_DiagRec *)odr_malloc (assoc->encode, sizeof(*drec));
1047     Z_DefaultDiagFormat *rec = (Z_DefaultDiagFormat *)odr_malloc (assoc->encode, sizeof(*rec));
1048
1049     yaz_log(LOG_DEBUG, "DiagRecs: %d -- %s", error, addinfo ? addinfo : "");
1050     bib1.proto = assoc->proto;
1051     bib1.oclass = CLASS_DIAGSET;
1052     bib1.value = VAL_BIB1;
1053
1054     *err = error;
1055     recs->num_diagRecs = 1;
1056     recs->diagRecs = recp;
1057     recp[0] = drec;
1058     drec->which = Z_DiagRec_defaultFormat;
1059     drec->u.defaultFormat = rec;
1060
1061     rec->diagnosticSetId = odr_oiddup (assoc->encode,
1062                                       oid_ent_to_oid(&bib1, oid));
1063     rec->condition = err;
1064
1065 #ifdef ASN_COMPILED
1066     rec->which = Z_DefaultDiagFormat_v2Addinfo;
1067     rec->u.v2Addinfo = addinfo ? addinfo : "";
1068 #else
1069     rec->which = Z_DiagForm_v2AddInfo;
1070     rec->addinfo = addinfo ? addinfo : "";
1071 #endif
1072     return recs;
1073 }
1074
1075 static Z_Records *pack_records(association *a, char *setname, int start,
1076                                 int *num, Z_RecordComposition *comp,
1077                                 int *next, int *pres, oid_value format,
1078                                 Z_ReferenceId *referenceId)
1079 {
1080     int recno, total_length = 0, toget = *num, dumped_records = 0;
1081     Z_Records *records =
1082         (Z_Records *) odr_malloc (a->encode, sizeof(*records));
1083     Z_NamePlusRecordList *reclist =
1084         (Z_NamePlusRecordList *) odr_malloc (a->encode, sizeof(*reclist));
1085     Z_NamePlusRecord **list =
1086         (Z_NamePlusRecord **) odr_malloc (a->encode, sizeof(*list) * toget);
1087
1088     records->which = Z_Records_DBOSD;
1089     records->u.databaseOrSurDiagnostics = reclist;
1090     reclist->num_records = 0;
1091     reclist->records = list;
1092     *pres = Z_PRES_SUCCESS;
1093     *num = 0;
1094     *next = 0;
1095
1096     yaz_log(LOG_LOG, "Request to pack %d+%d", start, toget);
1097     yaz_log(LOG_DEBUG, "pms=%d, mrs=%d", a->preferredMessageSize,
1098         a->maximumRecordSize);
1099     for (recno = start; reclist->num_records < toget; recno++)
1100     {
1101         bend_fetchrequest freq;
1102         bend_fetchresult *fres;
1103         Z_NamePlusRecord *thisrec;
1104         int this_length = 0;
1105         /*
1106          * we get the number of bytes allocated on the stream before any
1107          * allocation done by the backend - this should give us a reasonable
1108          * idea of the total size of the data so far.
1109          */
1110         total_length = odr_total(a->encode) - dumped_records;
1111         freq.setname = setname;
1112         freq.number = recno;
1113         freq.comp = comp;
1114         freq.format = format;
1115         freq.stream = a->encode;
1116         freq.surrogate_flag = 0;
1117         freq.referenceId = referenceId;
1118         if (!(fres = bend_fetch(a->backend, &freq, 0)))
1119         {
1120             *pres = Z_PRES_FAILURE;
1121             return diagrec(a, 2, "Backend interface problem");
1122         }
1123         /* backend should be able to signal whether error is system-wide
1124            or only pertaining to current record */
1125         if (fres->errcode)
1126         {
1127             if (!freq.surrogate_flag)
1128             {
1129                 *pres = Z_PRES_FAILURE;
1130                 return diagrec(a, fres->errcode, fres->errstring);
1131             }
1132             reclist->records[reclist->num_records] =
1133                 surrogatediagrec(a, fres->basename, fres->errcode,
1134                                  fres->errstring);
1135             reclist->num_records++;
1136             *next = fres->last_in_set ? 0 : recno + 1;
1137             continue;
1138         }
1139         if (fres->len >= 0)
1140             this_length = fres->len;
1141         else
1142             this_length = odr_total(a->encode) - total_length;
1143         yaz_log(LOG_DEBUG, "  fetched record, len=%d, total=%d",
1144             this_length, total_length);
1145         if (this_length + total_length > a->preferredMessageSize)
1146         {
1147             /* record is small enough, really */
1148             if (this_length <= a->preferredMessageSize)
1149             {
1150                 yaz_log(LOG_DEBUG, "  Dropped last normal-sized record");
1151                 *pres = Z_PRES_PARTIAL_2;
1152                 break;
1153             }
1154             /* record can only be fetched by itself */
1155             if (this_length < a->maximumRecordSize)
1156             {
1157                 yaz_log(LOG_DEBUG, "  Record > prefmsgsz");
1158                 if (toget > 1)
1159                 {
1160                     yaz_log(LOG_DEBUG, "  Dropped it");
1161                     reclist->records[reclist->num_records] =
1162                          surrogatediagrec(a, fres->basename, 16, 0);
1163                     reclist->num_records++;
1164                     *next = fres->last_in_set ? 0 : recno + 1;
1165                     dumped_records += this_length;
1166                     continue;
1167                 }
1168             }
1169             else /* too big entirely */
1170             {
1171                 yaz_log(LOG_DEBUG, "Record > maxrcdsz");
1172                 reclist->records[reclist->num_records] =
1173                     surrogatediagrec(a, fres->basename, 17, 0);
1174                 reclist->num_records++;
1175                 *next = fres->last_in_set ? 0 : recno + 1;
1176                 dumped_records += this_length;
1177                 continue;
1178             }
1179         }
1180
1181         if (!(thisrec = (Z_NamePlusRecord *)
1182               odr_malloc(a->encode, sizeof(*thisrec))))
1183             return 0;
1184         if (!(thisrec->databaseName = (char *)odr_malloc(a->encode,
1185             strlen(fres->basename) + 1)))
1186             return 0;
1187         strcpy(thisrec->databaseName, fres->basename);
1188         thisrec->which = Z_NamePlusRecord_databaseRecord;
1189         thisrec->u.databaseRecord = z_ext_record(a->encode, fres->format,
1190                                                  fres->record, fres->len);
1191         if (!thisrec->u.databaseRecord)
1192             return 0;
1193         reclist->records[reclist->num_records] = thisrec;
1194         reclist->num_records++;
1195         *next = fres->last_in_set ? 0 : recno + 1;
1196     }
1197     *num = reclist->num_records;
1198     return records;
1199 }
1200
1201 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
1202     int *fd)
1203 {
1204     Z_SearchRequest *req = reqb->request->u.searchRequest;
1205     bend_search_rr *bsrr = 
1206         (bend_search_rr *)nmem_malloc (reqb->request_mem, sizeof(*bsrr));
1207     
1208     yaz_log(LOG_LOG, "Got SearchRequest.");
1209     bsrr->fd = fd;
1210     bsrr->request = reqb;
1211     bsrr->association = assoc;
1212     bsrr->referenceId = req->referenceId;
1213     save_referenceId (reqb, bsrr->referenceId);
1214
1215     yaz_log (LOG_LOG, "ResultSet '%s'", req->resultSetName);
1216     if (req->databaseNames)
1217     {
1218         int i;
1219         for (i = 0; i < req->num_databaseNames; i++)
1220             yaz_log (LOG_LOG, "Database '%s'", req->databaseNames[i]);
1221     }
1222     switch (req->query->which)
1223     {
1224     case Z_Query_type_1: case Z_Query_type_101:
1225         log_rpn_query (req->query->u.type_1);
1226     }
1227     if (assoc->bend_search)
1228     {
1229         bsrr->setname = req->resultSetName;
1230         bsrr->replace_set = *req->replaceIndicator;
1231         bsrr->num_bases = req->num_databaseNames;
1232         bsrr->basenames = req->databaseNames;
1233         bsrr->query = req->query;
1234         bsrr->stream = assoc->encode;
1235         bsrr->decode = assoc->decode;
1236         bsrr->errcode = 0;
1237         bsrr->hits = 0;
1238         bsrr->errstring = NULL;
1239         ((int (*)(void *, bend_search_rr *))(assoc->bend_search))
1240             (assoc->backend, bsrr);
1241         if (!bsrr->request)
1242             return 0;
1243     }
1244     else
1245     {
1246         bend_searchrequest bsrq;
1247         bend_searchresult *bsrt;
1248
1249         bsrq.setname = req->resultSetName;
1250         bsrq.replace_set = *req->replaceIndicator;
1251         bsrq.num_bases = req->num_databaseNames;
1252         bsrq.basenames = req->databaseNames;
1253         bsrq.query = req->query;
1254         bsrq.referenceId = req->referenceId;
1255         bsrq.stream = assoc->encode;
1256         bsrq.decode = assoc->decode;
1257         if (!(bsrt = bend_search (assoc->backend, &bsrq, fd)))
1258             return 0;
1259         bsrr->hits = bsrt->hits;
1260         bsrr->errcode = bsrt->errcode;
1261         bsrr->errstring = bsrt->errstring;
1262     }
1263     return response_searchRequest(assoc, reqb, bsrr, fd);
1264 }
1265
1266 int bend_searchresponse(void *handle, bend_search_rr *bsrr) {return 0;}
1267
1268 /*
1269  * Prepare a searchresponse based on the backend results. We probably want
1270  * to look at making the fetching of records nonblocking as well, but
1271  * so far, we'll keep things simple.
1272  * If bsrt is null, that means we're called in response to a communications
1273  * event, and we'll have to get the response for ourselves.
1274  */
1275 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
1276     bend_search_rr *bsrt, int *fd)
1277 {
1278     Z_SearchRequest *req = reqb->request->u.searchRequest;
1279     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1280     Z_SearchResponse *resp = (Z_SearchResponse *)
1281         odr_malloc (assoc->encode, sizeof(*resp));
1282     int *nulint = (int *)odr_malloc (assoc->encode, sizeof(*nulint));
1283     bool_t *sr = (bool_t *)odr_malloc (assoc->encode, sizeof(*sr));
1284     int *next = (int *)odr_malloc (assoc->encode, sizeof(*next));
1285     int *none = (int *)odr_malloc (assoc->encode, sizeof(*none));
1286
1287     *nulint = 0;
1288     *sr = 1;
1289     *next = 0;
1290     *none = Z_RES_NONE;
1291
1292     apdu->which = Z_APDU_searchResponse;
1293     apdu->u.searchResponse = resp;
1294     resp->referenceId = req->referenceId;
1295     resp->additionalSearchInfo = 0;
1296     resp->otherInfo = 0;
1297     *fd = -1;
1298     if (!bsrt && !bend_searchresponse(assoc->backend, bsrt))
1299     {
1300         yaz_log(LOG_FATAL, "Bad result from backend");
1301         return 0;
1302     }
1303     else if (bsrt->errcode)
1304     {
1305         resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
1306         resp->resultCount = nulint;
1307         resp->numberOfRecordsReturned = nulint;
1308         resp->nextResultSetPosition = nulint;
1309         resp->searchStatus = nulint;
1310         resp->resultSetStatus = none;
1311         resp->presentStatus = 0;
1312     }
1313     else
1314     {
1315         int *toget = (int *)odr_malloc (assoc->encode, sizeof(*toget));
1316         int *presst = (int *)odr_malloc (assoc->encode, sizeof(*presst));
1317         Z_RecordComposition comp, *compp = 0;
1318
1319         *toget = 0;
1320         *presst = 0;
1321         resp->records = 0;
1322         resp->resultCount = &bsrt->hits;
1323
1324         comp.which = Z_RecordComp_simple;
1325         /* how many records does the user agent want, then? */
1326         if (bsrt->hits <= *req->smallSetUpperBound)
1327         {
1328             *toget = bsrt->hits;
1329             if ((comp.u.simple = req->smallSetElementSetNames))
1330                 compp = &comp;
1331         }
1332         else if (bsrt->hits < *req->largeSetLowerBound)
1333         {
1334             *toget = *req->mediumSetPresentNumber;
1335             if (*toget > bsrt->hits)
1336                 *toget = bsrt->hits;
1337             if ((comp.u.simple = req->mediumSetElementSetNames))
1338                 compp = &comp;
1339         }
1340         else
1341             *toget = 0;
1342
1343         if (*toget && !resp->records)
1344         {
1345             oident *prefformat;
1346             oid_value form;
1347
1348             if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1349                 prefformat->oclass != CLASS_RECSYN)
1350                 form = VAL_NONE;
1351             else
1352                 form = prefformat->value;
1353             resp->records = pack_records(assoc, req->resultSetName, 1,
1354                 toget, compp, next, presst, form, req->referenceId);
1355             if (!resp->records)
1356                 return 0;
1357             resp->numberOfRecordsReturned = toget;
1358             resp->nextResultSetPosition = next;
1359             resp->searchStatus = sr;
1360             resp->resultSetStatus = 0;
1361             resp->presentStatus = presst;
1362         }
1363         else
1364         {
1365             if (*resp->resultCount)
1366                 *next = 1;
1367             resp->numberOfRecordsReturned = nulint;
1368             resp->nextResultSetPosition = next;
1369             resp->searchStatus = sr;
1370             resp->resultSetStatus = 0;
1371             resp->presentStatus = 0;
1372         }
1373     }
1374     return apdu;
1375 }
1376
1377 /*
1378  * Maybe we got a little over-friendly when we designed bend_fetch to
1379  * get only one record at a time. Some backends can optimise multiple-record
1380  * fetches, and at any rate, there is some overhead involved in
1381  * all that selecting and hopping around. Problem is, of course, that the
1382  * frontend can't know ahead of time how many records it'll need to
1383  * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
1384  * is downright lousy as a bulk data transfer protocol.
1385  *
1386  * To start with, we'll do the fetching of records from the backend
1387  * in one operation: To save some trips in and out of the event-handler,
1388  * and to simplify the interface to pack_records. At any rate, asynch
1389  * operation is more fun in operations that have an unpredictable execution
1390  * speed - which is normally more true for search than for present.
1391  */
1392 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
1393     int *fd)
1394 {
1395     Z_PresentRequest *req = reqb->request->u.presentRequest;
1396     oident *prefformat;
1397     oid_value form;
1398     Z_APDU *apdu;
1399     Z_PresentResponse *resp;
1400     int *presst;
1401     int *next;
1402     int *num;
1403
1404     yaz_log(LOG_LOG, "Got PresentRequest.");
1405
1406     if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1407         prefformat->oclass != CLASS_RECSYN)
1408         form = VAL_NONE;
1409     else
1410         form = prefformat->value;
1411     if (assoc->bend_present)
1412     {
1413         bend_present_rr *bprr = (bend_present_rr *)
1414             nmem_malloc (reqb->request_mem, sizeof(*bprr));
1415         bprr->setname = req->resultSetId;
1416         bprr->start = *req->resultSetStartPoint;
1417         bprr->number = *req->numberOfRecordsRequested;
1418         bprr->format = form;
1419         bprr->comp = req->recordComposition;
1420         bprr->referenceId = req->referenceId;
1421         bprr->stream = assoc->encode;
1422         bprr->request = reqb;
1423         bprr->association = assoc;
1424         bprr->errcode = 0;
1425         bprr->errstring = NULL;
1426         ((int (*)(void *, bend_present_rr *))(*assoc->bend_present))(
1427             assoc->backend, bprr);
1428         
1429         if (!bprr->request)
1430             return 0;
1431     }
1432     apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1433     resp = (Z_PresentResponse *)odr_malloc (assoc->encode, sizeof(*resp));
1434     presst = (int *)odr_malloc (assoc->encode, sizeof(*presst));
1435     next = (int *)odr_malloc (assoc->encode, sizeof(*next));
1436     num = (int *)odr_malloc (assoc->encode, sizeof(*num));
1437     *presst = 0;
1438     *next = 0;
1439     *num = *req->numberOfRecordsRequested;
1440     
1441     apdu->which = Z_APDU_presentResponse;
1442     apdu->u.presentResponse = resp;
1443     resp->referenceId = req->referenceId;
1444     resp->otherInfo = 0;
1445     
1446     resp->records =
1447         pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
1448                      num, req->recordComposition, next, presst, form,
1449                      req->referenceId);
1450     if (!resp->records)
1451         return 0;
1452     resp->numberOfRecordsReturned = num;
1453     resp->presentStatus = presst;
1454     resp->nextResultSetPosition = next;
1455     
1456     return apdu;
1457 }
1458
1459 static int bend_default_scan (void *handle, bend_scan_rr *rr)
1460 {
1461     bend_scanrequest srq;
1462     bend_scanresult *srs;
1463
1464     srq.num_bases = rr->num_bases;
1465     srq.basenames = rr->basenames;
1466     srq.attributeset = rr->attributeset;
1467     srq.referenceId = rr->referenceId;
1468     srq.term = rr->term;
1469     srq.term_position = rr->term_position;
1470     srq.num_entries = rr->num_entries;
1471     srq.stream = rr->stream;
1472     
1473     srs = bend_scan(handle, &srq, 0);
1474
1475     rr->term_position = srs->term_position;
1476     rr->num_entries = srs->num_entries;
1477     rr->entries = srs->entries;
1478     rr->status = srs->status;
1479     rr->errcode = srs->errcode;
1480     rr->errstring = srs->errstring;
1481     return 0;
1482 }
1483
1484 /*
1485  * Scan was implemented rather in a hurry, and with support for only the basic
1486  * elements of the service in the backend API. Suggestions are welcome.
1487  */
1488 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
1489 {
1490     Z_ScanRequest *req = reqb->request->u.scanRequest;
1491     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1492     Z_ScanResponse *res = (Z_ScanResponse *)
1493         odr_malloc (assoc->encode, sizeof(*res));
1494     int *scanStatus = (int *)
1495         odr_malloc (assoc->encode, sizeof(*scanStatus));
1496     int *numberOfEntriesReturned = (int *)
1497         odr_malloc (assoc->encode, sizeof(*numberOfEntriesReturned));
1498     Z_ListEntries *ents = (Z_ListEntries *)
1499         odr_malloc (assoc->encode, sizeof(*ents));
1500     Z_DiagRecs *diagrecs_p = NULL;
1501     oident *attent;
1502     oident *attset;
1503
1504     yaz_log(LOG_LOG, "Got ScanRequest");
1505     *scanStatus = Z_Scan_failure;
1506     *numberOfEntriesReturned = 0;
1507
1508     apdu->which = Z_APDU_scanResponse;
1509     apdu->u.scanResponse = res;
1510     res->referenceId = req->referenceId;
1511     res->stepSize = 0;
1512     res->scanStatus = scanStatus;
1513     res->numberOfEntriesReturned = numberOfEntriesReturned;
1514     res->positionOfTerm = 0;
1515     res->entries = ents;
1516     ents->num_entries = 0;
1517     ents->entries = NULL;
1518     ents->num_nonsurrogateDiagnostics = 0;
1519     ents->nonsurrogateDiagnostics = NULL;
1520     res->attributeSet = 0;
1521     res->otherInfo = 0;
1522
1523     if (req->attributeSet && (!(attent = oid_getentbyoid(req->attributeSet)) ||
1524                               attent->oclass != CLASS_ATTSET
1525                               || attent->value != VAL_BIB1))
1526         diagrecs_p = diagrecs(assoc, 121, 0);
1527     else if (req->stepSize && *req->stepSize > 0)
1528         diagrecs_p = diagrecs(assoc, 205, 0);
1529     else
1530     {
1531         bend_scan_rr *bsrr = (bend_scan_rr *)
1532             odr_malloc (assoc->encode, sizeof(*bsrr));
1533         if (req->databaseNames)
1534         {
1535             int i;
1536             for (i = 0; i < req->num_databaseNames; i++)
1537                 yaz_log (LOG_LOG, "Database '%s'", req->databaseNames[i]);
1538         }
1539         bsrr->num_bases = req->num_databaseNames;
1540         bsrr->basenames = req->databaseNames;
1541         bsrr->num_entries = *req->numberOfTermsRequested;
1542         bsrr->term = req->termListAndStartPoint;
1543         bsrr->referenceId = req->referenceId;
1544         bsrr->stream = assoc->encode;
1545         if (!(attset = oid_getentbyoid(req->attributeSet)) ||
1546             attset->oclass != CLASS_RECSYN)
1547             bsrr->attributeset = VAL_NONE;
1548         else
1549             bsrr->attributeset = attset->value;
1550         log_scan_term (req->termListAndStartPoint, attset->value);
1551         bsrr->term_position = req->preferredPositionInResponse ?
1552             *req->preferredPositionInResponse : 1;
1553         ((int (*)(void *, bend_scan_rr *))(*assoc->bend_scan))(assoc->backend,
1554                                                                bsrr);
1555         if (bsrr->errcode)
1556             diagrecs_p = diagrecs(assoc, bsrr->errcode, bsrr->errstring);
1557         else
1558         {
1559             int i;
1560             Z_Entry **tab = (Z_Entry **)
1561                 odr_malloc (assoc->encode, sizeof(*tab) * bsrr->num_entries);
1562             
1563             if (bsrr->status == BEND_SCAN_PARTIAL)
1564                 *scanStatus = Z_Scan_partial_5;
1565             else
1566                 *scanStatus = Z_Scan_success;
1567             ents->entries = tab;
1568             ents->num_entries = bsrr->num_entries;
1569             res->numberOfEntriesReturned = &ents->num_entries;      
1570             res->positionOfTerm = &bsrr->term_position;
1571             for (i = 0; i < bsrr->num_entries; i++)
1572             {
1573                 Z_Entry *e;
1574                 Z_TermInfo *t;
1575                 Odr_oct *o;
1576                 
1577                 tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
1578                 if (bsrr->entries[i].occurrences >= 0)
1579                 {
1580                     e->which = Z_Entry_termInfo;
1581                     e->u.termInfo = t = (Z_TermInfo *)
1582                         odr_malloc(assoc->encode, sizeof(*t));
1583                     t->suggestedAttributes = 0;
1584                     t->displayTerm = 0;
1585                     t->alternativeTerm = 0;
1586                     t->byAttributes = 0;
1587                     t->otherTermInfo = 0;
1588                     t->globalOccurrences = &bsrr->entries[i].occurrences;
1589                     t->term = (Z_Term *)
1590                         odr_malloc(assoc->encode, sizeof(*t->term));
1591                     t->term->which = Z_Term_general;
1592                     t->term->u.general = o =
1593                         (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
1594                     o->buf = (unsigned char *)
1595                         odr_malloc(assoc->encode, o->len = o->size =
1596                                    strlen(bsrr->entries[i].term));
1597                     memcpy(o->buf, bsrr->entries[i].term, o->len);
1598                     yaz_log(LOG_DEBUG, "  term #%d: '%s' (%d)", i,
1599                          bsrr->entries[i].term, bsrr->entries[i].occurrences);
1600                 }
1601                 else
1602                 {
1603                     Z_DiagRecs *drecs = diagrecs (assoc,
1604                                                   bsrr->entries[i].errcode,
1605                                                   bsrr->entries[i].errstring);
1606                     assert (drecs->num_diagRecs == 1);
1607                     e->which = Z_Entry_surrogateDiagnostic;
1608                     assert (drecs->diagRecs[0]);
1609                     e->u.surrogateDiagnostic = drecs->diagRecs[0];
1610                 }
1611             }
1612         }
1613     }
1614     if (diagrecs_p)
1615     {
1616         ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
1617         ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
1618     }
1619     return apdu;
1620 }
1621
1622 static Z_APDU *process_sortRequest(association *assoc, request *reqb,
1623     int *fd)
1624 {
1625     Z_SortRequest *req = reqb->request->u.sortRequest;
1626     Z_SortResponse *res = (Z_SortResponse *)
1627         odr_malloc (assoc->encode, sizeof(*res));
1628     bend_sort_rr *bsrr = (bend_sort_rr *)
1629         odr_malloc (assoc->encode, sizeof(*bsrr));
1630
1631     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1632
1633     yaz_log(LOG_LOG, "Got SortRequest.");
1634
1635 #ifdef ASN_COMPILED
1636     bsrr->num_input_setnames = req->num_inputResultSetNames;
1637     bsrr->input_setnames = req->inputResultSetNames;
1638 #else
1639     bsrr->num_input_setnames = req->inputResultSetNames->num_strings;
1640     bsrr->input_setnames = req->inputResultSetNames->strings;
1641 #endif
1642     bsrr->referenceId = req->referenceId;
1643     bsrr->output_setname = req->sortedResultSetName;
1644     bsrr->sort_sequence = req->sortSequence;
1645     bsrr->stream = assoc->encode;
1646
1647     bsrr->sort_status = Z_SortStatus_failure;
1648     bsrr->errcode = 0;
1649     bsrr->errstring = 0;
1650     
1651     ((int (*)(void *, bend_sort_rr *))(*assoc->bend_sort))(assoc->backend,
1652                                                            bsrr);
1653     
1654     res->referenceId = bsrr->referenceId;
1655     res->sortStatus = (int *)
1656         odr_malloc (assoc->encode, sizeof(*res->sortStatus));
1657     *res->sortStatus = bsrr->sort_status;
1658     res->resultSetStatus = 0;
1659     if (bsrr->errcode)
1660     {
1661         Z_DiagRecs *dr = diagrecs (assoc, bsrr->errcode, bsrr->errstring);
1662 #ifdef ASN_COMPILED
1663         res->diagnostics = dr->diagRecs;
1664         res->num_diagnostics = dr->num_diagRecs;
1665 #else
1666         res->diagnostics = dr;
1667 #endif
1668     }
1669     else
1670     {
1671 #ifdef ASN_COMPILED
1672         res->num_diagnostics = 0;
1673 #endif
1674         res->diagnostics = 0;
1675     }
1676     res->otherInfo = 0;
1677
1678     apdu->which = Z_APDU_sortResponse;
1679     apdu->u.sortResponse = res;
1680     return apdu;
1681 }
1682
1683 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
1684     int *fd)
1685 {
1686     Z_DeleteResultSetRequest *req = reqb->request->u.deleteResultSetRequest;
1687     Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
1688         odr_malloc (assoc->encode, sizeof(*res));
1689     bend_delete_rr *bdrr = (bend_delete_rr *)
1690         odr_malloc (assoc->encode, sizeof(*bdrr));
1691     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1692
1693     yaz_log(LOG_LOG, "Got DeleteRequest.");
1694
1695     bdrr->num_setnames = req->num_resultSetList;
1696     bdrr->setnames = req->resultSetList;
1697     bdrr->stream = assoc->encode;
1698     bdrr->function = *req->deleteFunction;
1699     bdrr->referenceId = req->referenceId;
1700     bdrr->statuses = 0;
1701     if (bdrr->num_setnames > 0)
1702     {
1703         int i;
1704         bdrr->statuses = odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
1705                                     bdrr->num_setnames);
1706         for (i = 0; i < bdrr->num_setnames; i++)
1707             bdrr->statuses[i] = 0;
1708     }
1709     ((int (*)(void *, bend_delete_rr *))
1710      (*assoc->bend_delete))(assoc->backend, bdrr);
1711     
1712     res->referenceId = req->referenceId;
1713
1714     res->deleteOperationStatus = (int *)
1715         odr_malloc (assoc->encode, sizeof(*res->deleteOperationStatus));
1716     *res->deleteOperationStatus = bdrr->delete_status;
1717
1718     res->deleteListStatuses = 0;
1719     if (bdrr->num_setnames > 0)
1720     {
1721         int i;
1722         res->deleteListStatuses = odr_malloc(assoc->encode,
1723                                              sizeof(*res->deleteListStatuses));
1724         res->deleteListStatuses->num = bdrr->num_setnames;
1725         res->deleteListStatuses->elements =
1726             odr_malloc (assoc->encode,
1727                         sizeof(*res->deleteListStatuses->elements) *
1728                         bdrr->num_setnames);
1729         for (i = 0; i<bdrr->num_setnames; i++)
1730         {
1731             res->deleteListStatuses->elements[i] =
1732                 odr_malloc (assoc->encode,
1733                             sizeof(**res->deleteListStatuses->elements));
1734             res->deleteListStatuses->elements[i]->status = bdrr->statuses+i;
1735             res->deleteListStatuses->elements[i]->id =
1736                 odr_strdup (assoc->encode, bdrr->setnames[i]);
1737             
1738         }
1739     }
1740     res->numberNotDeleted = 0;
1741     res->bulkStatuses = 0;
1742     res->deleteMessage = 0;
1743     res->otherInfo = 0;
1744
1745     apdu->which = Z_APDU_deleteResultSetResponse;
1746     apdu->u.deleteResultSetResponse = res;
1747     return apdu;
1748 }
1749
1750 static void process_close(association *assoc, request *reqb)
1751 {
1752     Z_Close *req = reqb->request->u.close;
1753     static char *reasons[] =
1754     {
1755         "finished",
1756         "shutdown",
1757         "systemProblem",
1758         "costLimit",
1759         "resources",
1760         "securityViolation",
1761         "protocolError",
1762         "lackOfActivity",
1763         "peerAbort",
1764         "unspecified"
1765     };
1766
1767     yaz_log(LOG_LOG, "Got Close, reason %s, message %s",
1768         reasons[*req->closeReason], req->diagnosticInformation ?
1769         req->diagnosticInformation : "NULL");
1770     if (assoc->version < 3) /* to make do_force respond with close */
1771         assoc->version = 3;
1772     do_close_req(assoc, Z_Close_finished,
1773                  "Association terminated by client", reqb);
1774 }
1775
1776 void save_referenceId (request *reqb, Z_ReferenceId *refid)
1777 {
1778     if (refid)
1779     {
1780         reqb->len_refid = refid->len;
1781         reqb->refid = (char *)nmem_malloc (reqb->request_mem, refid->len);
1782         memcpy (reqb->refid, refid->buf, refid->len);
1783     }
1784     else
1785     {
1786         reqb->len_refid = 0;
1787         reqb->refid = NULL;
1788     }
1789 }
1790
1791 void bend_request_send (bend_association a, bend_request req, Z_APDU *res)
1792 {
1793     process_response (a, req, res);
1794 }
1795
1796 bend_request bend_request_mk (bend_association a)
1797 {
1798     request *nreq = request_get (&a->outgoing);
1799     nreq->request_mem = nmem_create ();
1800     return nreq;
1801 }
1802
1803 Z_ReferenceId *bend_request_getid (ODR odr, bend_request req)
1804 {
1805     Z_ReferenceId *id;
1806     if (!req->refid)
1807         return 0;
1808     id = (Odr_oct *)odr_malloc (odr, sizeof(*odr));
1809     id->buf = (unsigned char *)odr_malloc (odr, req->len_refid);
1810     id->len = id->size = req->len_refid;
1811     memcpy (id->buf, req->refid, req->len_refid);
1812     return id;
1813 }
1814
1815 void bend_request_destroy (bend_request *req)
1816 {
1817     nmem_destroy((*req)->request_mem);
1818     request_release(*req);
1819     *req = NULL;
1820 }
1821
1822 int bend_backend_respond (bend_association a, bend_request req)
1823 {
1824     char *msg;
1825     int r;
1826     r = process_request (a, req, &msg);
1827     if (r < 0)
1828         logf (LOG_WARN, "%s", msg);
1829     return r;
1830 }
1831
1832 void bend_request_setdata(bend_request r, void *p)
1833 {
1834     r->clientData = p;
1835 }
1836
1837 void *bend_request_getdata(bend_request r)
1838 {
1839     return r->clientData;
1840 }
1841
1842 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd)
1843 {
1844     bend_esrequest_rr esrequest;
1845
1846     Z_ExtendedServicesRequest *req = reqb->request->u.extendedServicesRequest;
1847     Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
1848
1849     Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
1850
1851     yaz_log(LOG_DEBUG,"inside Process esRequest");
1852
1853     esrequest.esr = reqb->request->u.extendedServicesRequest;
1854     esrequest.stream = assoc->encode;
1855     esrequest.errcode = 0;
1856     esrequest.errstring = NULL;
1857     esrequest.request = reqb;
1858     esrequest.association = assoc;
1859     esrequest.referenceId = req->referenceId;
1860     
1861     ((int (*)(void *, bend_esrequest_rr *))(*assoc->bend_esrequest))
1862         (assoc->backend, &esrequest);
1863     
1864     /* If the response is being delayed, return NULL */
1865     if (esrequest.request == NULL)
1866         return(NULL);
1867
1868     resp->referenceId = req->referenceId;
1869
1870     if (esrequest.errcode == -1)
1871     {
1872         /* Backend service indicates request will be processed */
1873         yaz_log(LOG_DEBUG,"Request could be processed...Accepted !");
1874         *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
1875     }
1876     else if (esrequest.errcode == 0)
1877     {
1878         /* Backend service indicates request will be processed */
1879         yaz_log(LOG_DEBUG,"Request could be processed...Done !");
1880         *resp->operationStatus = Z_ExtendedServicesResponse_done;
1881     }
1882     else
1883     {
1884         Z_DiagRecs *diagRecs = diagrecs (assoc, esrequest.errcode,
1885                                          esrequest.errstring);
1886
1887         /* Backend indicates error, request will not be processed */
1888         yaz_log(LOG_DEBUG,"Request could not be processed...failure !");
1889         *resp->operationStatus = Z_ExtendedServicesResponse_failure;
1890         resp->num_diagnostics = diagRecs->num_diagRecs;
1891         resp->diagnostics = diagRecs->diagRecs;
1892     }
1893     /* Do something with the members of bend_extendedservice */
1894
1895     yaz_log(LOG_DEBUG,"Send the result apdu");
1896     return apdu;
1897 }