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