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