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