Log of close transmit.
[yaz-moved-to-github.git] / server / seshigh.c
1 /*
2  * Copyright (c) 1995, Index Data
3  * See the file LICENSE for details.
4  * Sebastian Hammer, Adam Dickmeiss
5  *
6  * $Log: seshigh.c,v $
7  * Revision 1.54  1995-11-08 15:11:29  quinn
8  * Log of close transmit.
9  *
10  * Revision 1.53  1995/11/01  13:54:58  quinn
11  * Minor adjustments
12  *
13  * Revision 1.52  1995/11/01  12:19:13  quinn
14  * Second attempt to fix same bug.
15  *
16  * Revision 1.50  1995/10/25  16:58:32  quinn
17  * Simple.
18  *
19  * Revision 1.49  1995/10/16  13:51:53  quinn
20  * Changes to provide Especs to the backend.
21  *
22  * Revision 1.48  1995/10/06  08:51:20  quinn
23  * Added Write-buffer.
24  *
25  * Revision 1.47  1995/08/29  14:24:16  quinn
26  * Added second half of close-handshake
27  *
28  * Revision 1.46  1995/08/29  11:17:58  quinn
29  * Added code to receive close
30  *
31  * Revision 1.45  1995/08/21  09:11:00  quinn
32  * Smallish fixes to suppport new formats.
33  *
34  * Revision 1.44  1995/08/17  12:45:25  quinn
35  * Fixed minor problems with GRS-1. Added support in c&s.
36  *
37  * Revision 1.43  1995/08/15  12:00:31  quinn
38  * Updated External
39  *
40  * Revision 1.42  1995/08/15  11:16:50  quinn
41  *
42  * Revision 1.41  1995/08/02  10:23:06  quinn
43  * Smallish
44  *
45  * Revision 1.40  1995/07/31  14:34:26  quinn
46  * Fixed bug in process_searchResponse (numberOfRecordsReturned).
47  *
48  * Revision 1.39  1995/06/27  13:21:00  quinn
49  * SUTRS support
50  *
51  * Revision 1.38  1995/06/19  12:39:11  quinn
52  * Fixed bug in timeout code. Added BER dumper.
53  *
54  * Revision 1.37  1995/06/16  13:16:14  quinn
55  * Fixed Defaultdiagformat.
56  *
57  * Revision 1.36  1995/06/16  10:31:36  quinn
58  * Added session timeout.
59  *
60  * Revision 1.35  1995/06/15  07:45:14  quinn
61  * Moving to v3.
62  *
63  * Revision 1.34  1995/06/14  15:26:46  quinn
64  * *** empty log message ***
65  *
66  * Revision 1.33  1995/06/06  14:57:05  quinn
67  * Better diagnostics.
68  *
69  * Revision 1.32  1995/06/06  08:41:44  quinn
70  * Better diagnostics.
71  *
72  * Revision 1.31  1995/06/06  08:15:37  quinn
73  * Cosmetic.
74  *
75  * Revision 1.30  1995/06/05  10:53:32  quinn
76  * Added a better SCAN.
77  *
78  * Revision 1.29  1995/06/01  11:25:03  quinn
79  * Smallish.
80  *
81  * Revision 1.28  1995/06/01  11:21:01  quinn
82  * Attempting to fix a bug in pack-records. replaced break with continue
83  * for large records, according to standard.
84  *
85  * Revision 1.27  1995/05/29  08:12:06  quinn
86  * Moved oid to util
87  *
88  * Revision 1.26  1995/05/18  13:02:12  quinn
89  * Smallish.
90  *
91  * Revision 1.25  1995/05/17  08:42:26  quinn
92  * Transfer auth info to backend. Allow backend to reject init gracefully.
93  *
94  * Revision 1.24  1995/05/16  08:51:04  quinn
95  * License, documentation, and memory fixes
96  *
97  * Revision 1.23  1995/05/15  13:25:10  quinn
98  * Fixed memory bug.
99  *
100  * Revision 1.22  1995/05/15  11:56:39  quinn
101  * Asynchronous facilities. Restructuring of seshigh code.
102  *
103  * Revision 1.21  1995/05/02  08:53:19  quinn
104  * Trying in vain to fix comm with ISODE
105  *
106  * Revision 1.20  1995/04/20  15:13:00  quinn
107  * Cosmetic
108  *
109  * Revision 1.19  1995/04/18  08:15:34  quinn
110  * Added dynamic memory allocation on encoding (whew). Code is now somewhat
111  * neater. We'll make the same change for decoding one day.
112  *
113  * Revision 1.18  1995/04/17  11:28:25  quinn
114  * Smallish
115  *
116  * Revision 1.17  1995/04/10  10:23:36  quinn
117  * Some work to add scan and other things.
118  *
119  * Revision 1.16  1995/03/31  09:18:55  quinn
120  * Added logging.
121  *
122  * Revision 1.15  1995/03/30  14:03:23  quinn
123  * Added RFC1006 as separate library
124  *
125  * Revision 1.14  1995/03/30  12:18:17  quinn
126  * Fixed bug.
127  *
128  * Revision 1.13  1995/03/30  09:09:24  quinn
129  * Added state-handle and some support for asynchronous activities.
130  *
131  * Revision 1.12  1995/03/29  15:40:16  quinn
132  * Ongoing work. Statserv is now dynamic by default
133  *
134  * Revision 1.11  1995/03/28  09:16:21  quinn
135  * Added record packing to the search request
136  *
137  * Revision 1.10  1995/03/27  08:34:24  quinn
138  * Added dynamic server functionality.
139  * Released bindings to session.c (is now redundant)
140  *
141  * Revision 1.9  1995/03/22  15:01:26  quinn
142  * Adjusting record packing.
143  *
144  * Revision 1.8  1995/03/22  10:13:21  quinn
145  * Working on record packer
146  *
147  * Revision 1.7  1995/03/21  15:53:31  quinn
148  * Little changes.
149  *
150  * Revision 1.6  1995/03/21  12:30:09  quinn
151  * Beginning to add support for record packing.
152  *
153  * Revision 1.5  1995/03/17  10:44:13  quinn
154  * Added catch of null-string in makediagrec
155  *
156  * Revision 1.4  1995/03/17  10:18:08  quinn
157  * Added memory management.
158  *
159  * Revision 1.3  1995/03/16  17:42:39  quinn
160  * Little changes
161  *
162  * Revision 1.2  1995/03/16  13:29:01  quinn
163  * Partitioned server.
164  *
165  * Revision 1.1  1995/03/15  16:02:10  quinn
166  * Modded session.c to seshigh.c
167  *
168  */
169
170 /*
171  * Frontend server logic.
172  *
173  * This code receives incoming APDUs, and handles client requests by means
174  * of the backend API.
175  *
176  * Some of the code is getting quite involved, compared to simpler servers -
177  * primarily because it is asynchronous both in the communication with
178  * the user and the backend. We think the complexity will pay off in
179  * the form of greater flexibility when more asynchronous facilities
180  * are implemented.
181  *
182  * Memory management has become somewhat involved. In the simple case, where
183  * only one PDU is pending at a time, it will simply reuse the same memory,
184  * once it has found its working size. When we enable multiple concurrent
185  * operations, perhaps even with multiple parallel calls to the backend, it
186  * will maintain a pool of buffers for encoding and decoding, trying to
187  * minimize memory allocation/deallocation during normal operation.
188  *
189  * TODOs include (and will be done in order of public interest):
190  * 
191  * Support for EXPLAIN - provide simple meta-database system.
192  * Support for access control.
193  * Support for resource control.
194  * Support for extended services - primarily Item Order.
195  * Rest of Z39.50-1994
196  *
197  */
198
199 #include <stdlib.h>
200 #include <stdio.h>
201 #include <unistd.h>
202 #include <assert.h>
203 #include <sys/time.h>
204
205 #include <xmalloc.h>
206 #include <comstack.h>
207 #include <eventl.h>
208 #include <session.h>
209 #include <proto.h>
210 #include <oid.h>
211 #include <log.h>
212 #include <statserv.h>
213
214 #include <backend.h>
215
216 static int process_request(association *assoc);
217 void backend_response(IOCHAN i, int event);
218 static int process_response(association *assoc, request *req, Z_APDU *res);
219 static Z_APDU *process_initRequest(association *assoc, request *reqb);
220 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
221     int *fd);
222 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
223     bend_searchresult *bsrt, int *fd);
224 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
225     int *fd);
226 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
227 static void process_close(association *assoc, request *reqb);
228
229 static FILE *apduf = 0; /* for use in static mode */
230 static statserv_options_block *control_block = 0;
231
232 /*
233  * Create and initialize a new association-handle.
234  *  channel  : iochannel for the current line.
235  *  link     : communications channel.
236  * Returns: 0 or a new association handle.
237  */
238 association *create_association(IOCHAN channel, COMSTACK link)
239 {
240     association *new;
241
242     if (!control_block)
243         control_block = statserv_getcontrol();
244     if (!(new = xmalloc(sizeof(*new))))
245         return 0;
246     new->client_chan = channel;
247     new->client_link = link;
248     if (!(new->decode = odr_createmem(ODR_DECODE)) ||
249         !(new->encode = odr_createmem(ODR_ENCODE)))
250         return 0;
251     if (*control_block->apdufile)
252     {
253         char filename[256];
254         FILE *f;
255
256         strcpy(filename, control_block->apdufile);
257         if (!(new->print = odr_createmem(ODR_PRINT)))
258             return 0;
259         if (*control_block->apdufile != '-')
260         {
261             strcpy(filename, control_block->apdufile);
262             if (!control_block->dynamic)
263             {
264                 if (!apduf)
265                 {
266                     if (!(apduf = fopen(filename, "w")))
267                     {
268                         logf(LOG_WARN|LOG_ERRNO, "%s", filename);
269                         return 0;
270                     }
271                     setvbuf(apduf, 0, _IONBF, 0);
272                 }
273                 f = apduf;
274             }
275             else 
276             {
277                 sprintf(filename + strlen(filename), ".%d", getpid());
278                 if (!(f = fopen(filename, "w")))
279                 {
280                     logf(LOG_WARN|LOG_ERRNO, "%s", filename);
281                     return 0;
282                 }
283                 setvbuf(f, 0, _IONBF, 0);
284             }
285             odr_setprint(new->print, f);
286         }
287     }
288     else
289         new->print = 0;
290     new->input_buffer = 0;
291     new->input_buffer_len = 0;
292     new->backend = 0;
293     new->state = ASSOC_NEW;
294     request_initq(&new->incoming);
295     request_initq(&new->outgoing);
296     new->proto = cs_getproto(link);
297     return new;
298 }
299
300 /*
301  * Free association and release resources.
302  */
303 void destroy_association(association *h)
304 {
305     odr_destroy(h->decode);
306     odr_destroy(h->encode);
307     if (h->print)
308         odr_destroy(h->print);
309     if (h->input_buffer)
310     xfree(h->input_buffer);
311     if (h->backend)
312         bend_close(h->backend);
313     while (request_deq(&h->incoming));
314     while (request_deq(&h->outgoing));
315    xfree(h);
316 }
317
318 static void do_close(association *a, int reason, char *message)
319 {
320     Z_APDU apdu;
321     Z_Close *cls = zget_Close(a->encode);
322     request *req = request_get();
323
324     /* Purge request queue */
325     while (request_deq(&a->incoming));
326     while (request_deq(&a->outgoing));
327     if (a->version >= 3)
328     {
329         logf(LOG_LOG, "Sending Close PDU, reason=%d, message=%s",
330             reason, message ? message : "none");
331         apdu.which = Z_APDU_close;
332         apdu.u.close = cls;
333         *cls->closeReason = reason;
334         cls->diagnosticInformation = message;
335         process_response(a, req, &apdu);
336         iochan_settimeout(a->client_chan, 60);
337     }
338     else
339     {
340         logf(LOG_DEBUG, "v2 client. No Close PDU");
341         iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
342     }
343     a->state = ASSOC_DEAD;
344 }
345
346 /*
347  * This is where PDUs from the client are read and the further
348  * processing is initiated. Flow of control moves down through the
349  * various process_* functions below, until the encoded result comes back up
350  * to the output handler in here.
351  * 
352  *  h     : the I/O channel that has an outstanding event.
353  *  event : the current outstanding event.
354  */
355 void ir_session(IOCHAN h, int event)
356 {
357     int res;
358     association *assoc = iochan_getdata(h);
359     COMSTACK conn = assoc->client_link;
360     request *req;
361
362     assert(h && conn && assoc);
363     if (event == EVENT_TIMEOUT)
364     {
365         if (assoc->state != ASSOC_UP)
366         {
367             logf(LOG_LOG, "Final timeout - closing connection.");
368             cs_close(conn);
369             destroy_association(assoc);
370             iochan_destroy(h);
371         }
372         else
373         {
374             logf(LOG_LOG, "Session idle too long. Sending close.");
375             do_close(assoc, Z_Close_lackOfActivity, 0);
376         }
377         return;
378     }
379     if (event & EVENT_INPUT || event & EVENT_WORK) /* input */
380     {
381         if (event & EVENT_INPUT)
382         {
383             logf(LOG_DEBUG, "ir_session (input)");
384             assert(assoc && conn);
385             /* We aren't speaking to this fellow */
386             if (assoc->state == ASSOC_DEAD)
387             {
388                 logf(LOG_LOG, "Closed connection after reject");
389                 cs_close(conn);
390                 destroy_association(assoc);
391                 iochan_destroy(h);
392                 return;
393             }
394             if ((res = cs_get(conn, &assoc->input_buffer,
395                 &assoc->input_buffer_len)) <= 0)
396             {
397                 logf(LOG_LOG, "Connection closed by client");
398                 cs_close(conn);
399                 destroy_association(assoc);
400                 iochan_destroy(h);
401                 return;
402             }
403             else if (res == 1) /* incomplete read - wait for more  */
404                 return;
405             if (cs_more(conn)) /* more stuff - call us again later, please */
406                 iochan_setevent(h, EVENT_INPUT);
407                 
408             /* we got a complete PDU. Let's decode it */
409             logf(LOG_DEBUG, "Got PDU, %d bytes", res);
410             req = request_get(); /* get a new request structure */
411             odr_reset(assoc->decode);
412             odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
413             if (!z_APDU(assoc->decode, &req->request, 0))
414             {
415                 logf(LOG_LOG, "ODR error on incoming PDU: %s [near byte %d] ",
416                     odr_errlist[odr_geterror(assoc->decode)],
417                     odr_offset(assoc->decode));
418                 logf(LOG_LOG, "PDU dump:");
419                 odr_dumpBER(log_file(), assoc->input_buffer, res);
420                 do_close(assoc, Z_Close_protocolError, "Malformed package");
421                 return;
422             }
423             req->request_mem = odr_extract_mem(assoc->decode);
424             if (assoc->print && !z_APDU(assoc->print, &req->request, 0))
425             {
426                 logf(LOG_WARN, "ODR print error: %s", 
427                     odr_errlist[odr_geterror(assoc->print)]);
428                 odr_reset(assoc->print);
429             }
430             request_enq(&assoc->incoming, req);
431         }
432
433         /* can we do something yet? */
434         req = request_head(&assoc->incoming);
435         if (req->state == REQUEST_IDLE)
436             if (process_request(assoc) < 0)
437                 do_close(assoc, Z_Close_systemProblem, "Unknown error");
438     }
439     if (event & EVENT_OUTPUT)
440     {
441         request *req = request_head(&assoc->outgoing);
442
443         logf(LOG_DEBUG, "ir_session (output)");
444         req->state = REQUEST_PENDING;
445         switch (res = cs_put(conn, req->response, req->len_response))
446         {
447             case -1:
448                 logf(LOG_LOG, "Connection closed by client");
449                 cs_close(conn);
450                 destroy_association(assoc);
451                 iochan_destroy(h);
452                 break;
453             case 0: /* all sent - release the request structure */
454                 logf(LOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
455                 odr_release_mem(req->request_mem);
456                 request_deq(&assoc->outgoing);
457                 request_release(req);
458                 if (!request_head(&assoc->outgoing))
459                     iochan_clearflag(h, EVENT_OUTPUT);
460                 break;
461             /* value of 1 -- partial send -- is simply ignored */
462         }
463     }
464     if (event & EVENT_EXCEPT)
465     {
466         logf(LOG_DEBUG, "ir_session (exception)");
467         cs_close(conn);
468         destroy_association(assoc);
469         iochan_destroy(h);
470     }
471 }
472
473 /*
474  * Initiate request processing.
475  */
476 static int process_request(association *assoc)
477 {
478     request *req = request_head(&assoc->incoming);
479     int fd = -1;
480     Z_APDU *res;
481
482     logf(LOG_DEBUG, "process_request");
483     assert(req && req->state == REQUEST_IDLE);
484     switch (req->request->which)
485     {
486         case Z_APDU_initRequest:
487             res = process_initRequest(assoc, req); break;
488         case Z_APDU_searchRequest:
489             res = process_searchRequest(assoc, req, &fd); break;
490         case Z_APDU_presentRequest:
491             res = process_presentRequest(assoc, req, &fd); break;
492         case Z_APDU_scanRequest:
493             res = process_scanRequest(assoc, req, &fd); break;
494         case Z_APDU_close:
495             process_close(assoc, req); return 0;
496         default:
497             logf(LOG_WARN, "Bad APDU received");
498             return -1;
499     }
500     if (res)
501     {
502         logf(LOG_DEBUG, "  result immediately available");
503         return process_response(assoc, req, res);
504     }
505     else if (fd < 0)
506     {
507         logf(LOG_WARN, "   bad result");
508         return -1;
509     }
510     else /* no result yet - one will be provided later */
511     {
512         IOCHAN chan;
513
514         /* Set up an I/O handler for the fd supplied by the backend */
515
516         logf(LOG_DEBUG, "   establishing handler for result");
517         req->state = REQUEST_PENDING;
518         if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT)))
519             abort();
520         iochan_setdata(chan, assoc);
521         return 0;
522     }
523 }
524
525 /*
526  * Handle message from the backend.
527  */
528 void backend_response(IOCHAN i, int event)
529 {
530     association *assoc = iochan_getdata(i);
531     request *req = request_head(&assoc->incoming);
532     Z_APDU *res;
533     int fd;
534
535     logf(LOG_DEBUG, "backend_response");
536     assert(assoc && req && req->state != REQUEST_IDLE);
537     /* determine what it is we're waiting for */
538     switch (req->request->which)
539     {
540         case Z_APDU_searchRequest:
541             res = response_searchRequest(assoc, req, 0, &fd); break;
542 #if 0
543         case Z_APDU_presentRequest:
544             res = response_presentRequest(assoc, req, 0, &fd); break;
545         case Z_APDU_scanRequest:
546             res = response_scanRequest(assoc, req, 0, &fd); break;
547 #endif
548         default:
549             logf(LOG_WARN, "Serious programmer's lapse or bug");
550             abort();
551     }
552     if ((res && process_response(assoc, req, res) < 0) || fd < 0)
553     {
554         logf(LOG_LOG, "Fatal error when talking to backend");
555         do_close(assoc, Z_Close_systemProblem, 0);
556         iochan_destroy(i);
557         return;
558     }
559     else if (!res) /* no result yet - try again later */
560     {
561         logf(LOG_DEBUG, "   no result yet");
562         iochan_setfd(i, fd); /* in case fd has changed */
563     }
564 }
565
566 /*
567  * Encode response, and transfer the request structure to the outgoing queue.
568  */
569 static int process_response(association *assoc, request *req, Z_APDU *res)
570 {
571     odr_setbuf(assoc->encode, req->response, req->size_response, 1);
572     if (!z_APDU(assoc->encode, &res, 0))
573     {
574         logf(LOG_WARN, "ODR error when encoding response: %s",
575             odr_errlist[odr_geterror(assoc->decode)]);
576         return -1;
577     }
578     req->response = odr_getbuf(assoc->encode, &req->len_response,
579         &req->size_response);
580     odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
581     odr_reset(assoc->encode);
582     if (assoc->print && !z_APDU(assoc->print, &res, 0))
583     {
584         logf(LOG_WARN, "ODR print error: %s", 
585             odr_errlist[odr_geterror(assoc->print)]);
586         odr_reset(assoc->print);
587     }
588     /* change this when we make the backend reentrant */
589     if (req == request_head(&assoc->incoming))
590     {
591         req->state = REQUEST_IDLE;
592         request_deq(&assoc->incoming);
593     }
594     request_enq(&assoc->outgoing, req);
595     /* turn the work over to the ir_session handler */
596     iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
597     /* Is there more work to be done? give that to the input handler too */
598     if (request_head(&assoc->incoming))
599         iochan_setevent(assoc->client_chan, EVENT_WORK);
600     return 0;
601 }
602
603 /*
604  * Handle init request.
605  * At the moment, we don't check the options
606  * anywhere else in the code - we just try not to do anything that would
607  * break a naive client. We'll toss 'em into the association block when
608  * we need them there.
609  */
610 static Z_APDU *process_initRequest(association *assoc, request *reqb)
611 {
612     Z_InitRequest *req = reqb->request->u.initRequest;
613     Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
614     Z_InitResponse *resp = apdu->u.initResponse;
615     bend_initrequest binitreq;
616     bend_initresult *binitres;
617     char options[100];
618
619     logf(LOG_LOG, "Got initRequest");
620     if (req->implementationId)
621         logf(LOG_LOG, "Id:        %s", req->implementationId);
622     if (req->implementationName)
623         logf(LOG_LOG, "Name:      %s", req->implementationName);
624     if (req->implementationVersion)
625         logf(LOG_LOG, "Version:   %s", req->implementationVersion);
626
627     binitreq.configname = "default-config";
628     binitreq.auth = req->idAuthentication;
629     if (!(binitres = bend_init(&binitreq)))
630     {
631         logf(LOG_WARN, "Bad response from backend.");
632         return 0;
633     }
634
635     assoc->backend = binitres->handle;
636     resp->referenceId = req->referenceId;
637     *options = '\0';
638     /* let's tell the client what we can do */
639     if (ODR_MASK_GET(req->options, Z_Options_search))
640     {
641         ODR_MASK_SET(resp->options, Z_Options_search);
642         strcat(options, "srch");
643     }
644     if (ODR_MASK_GET(req->options, Z_Options_present))
645     {
646         ODR_MASK_SET(resp->options, Z_Options_present);
647         strcat(options, " prst");
648     }
649 #if 0
650     if (ODR_MASK_GET(req->options, Z_Options_delSet))
651     {
652         ODR_MASK_SET(&options, Z_Options_delSet);
653         strcat(options, " del");
654     }
655 #endif
656     if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
657     {
658         ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
659         strcat(options, " namedresults");
660     }
661     if (ODR_MASK_GET(req->options, Z_Options_scan))
662     {
663         ODR_MASK_SET(resp->options, Z_Options_scan);
664         strcat(options, " scan");
665     }
666     if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
667     {
668         ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
669         strcat(options, " concurop");
670     }
671
672     if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
673     {
674         ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
675         assoc->version = 2; /* 1 & 2 are equivalent */
676     }
677     if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
678     {
679         ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
680         assoc->version = 2;
681     }
682     if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
683     {
684         ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
685         assoc->version = 3;
686     }
687     logf(LOG_LOG, "Negotiated to v%d: %s", assoc->version, options);
688     assoc->maximumRecordSize = *req->maximumRecordSize;
689     if (assoc->maximumRecordSize > control_block->maxrecordsize)
690         assoc->maximumRecordSize = control_block->maxrecordsize;
691     assoc->preferredMessageSize = *req->preferredMessageSize;
692     if (assoc->preferredMessageSize > assoc->maximumRecordSize)
693         assoc->preferredMessageSize = assoc->maximumRecordSize;
694     resp->preferredMessageSize = &assoc->preferredMessageSize;
695     resp->maximumRecordSize = &assoc->maximumRecordSize;
696     resp->implementationName = "Index Data/YAZ Generic Frontend Server";
697     if (binitres->errcode)
698     {
699         logf(LOG_LOG, "Connection rejected by backend.");
700         *resp->result = 0;
701         assoc->state = ASSOC_DEAD;
702     }
703     else
704         assoc->state = ASSOC_UP;
705     return apdu;
706 }
707
708 /*
709  * These functions should be merged.
710  */
711
712 /*
713  * nonsurrogate diagnostic record.
714  */
715 static Z_Records *diagrec(oid_proto proto, int error, char *addinfo)
716 {
717     static Z_Records rec;
718     oident bib1;
719     static int err;
720 #ifdef Z_95
721     static Z_DiagRec drec;
722     static Z_DefaultDiagFormat dr;
723 #else
724     static Z_DiagRec dr;
725 #endif
726
727     bib1.proto = proto;
728     bib1.class = CLASS_DIAGSET;
729     bib1.value = VAL_BIB1;
730
731     logf(LOG_DEBUG, "Diagnostic: %d -- %s", error, addinfo ? addinfo :
732         "NULL");
733     err = error;
734     rec.which = Z_Records_NSD;
735 #ifdef Z_95
736     rec.u.nonSurrogateDiagnostic = &drec;
737     drec.which = Z_DiagRec_defaultFormat;
738     drec.u.defaultFormat = &dr;
739 #else
740     rec.u.nonSurrogateDiagnostic = &dr;
741 #endif
742     dr.diagnosticSetId = oid_getoidbyent(&bib1);
743     dr.condition = &err;
744     dr.which = Z_DiagForm_v2AddInfo;
745     dr.addinfo = addinfo ? addinfo : "";
746     return &rec;
747 }
748
749 /*
750  * surrogate diagnostic.
751  */
752 static Z_NamePlusRecord *surrogatediagrec(oid_proto proto, char *dbname,
753                                             int error, char *addinfo)
754 {
755     static Z_NamePlusRecord rec;
756     static int err;
757     oident bib1;
758 #ifdef Z_95
759     static Z_DiagRec drec;
760     static Z_DefaultDiagFormat dr;
761 #else
762     static Z_DiagRec dr;
763 #endif
764
765     bib1.proto = proto;
766     bib1.class = CLASS_DIAGSET;
767     bib1.value = VAL_BIB1;
768
769     logf(LOG_DEBUG, "SurrogateDiagnotic: %d -- %s", error, addinfo);
770     err = error;
771     rec.databaseName = dbname;
772     rec.which = Z_NamePlusRecord_surrogateDiagnostic;
773 #ifdef Z_95
774     rec.u.surrogateDiagnostic = &drec;
775     drec.which = Z_DiagRec_defaultFormat;
776     drec.u.defaultFormat = &dr;
777 #else
778     rec.u.surrogateDiagnostic = &dr;
779 #endif
780     dr.diagnosticSetId = oid_getoidbyent(&bib1);
781     dr.condition = &err;
782     dr.which = Z_DiagForm_v2AddInfo;
783     dr.addinfo = addinfo ? addinfo : "";
784     return &rec;
785 }
786
787 /*
788  * multiple nonsurrogate diagnostics.
789  */
790 static Z_DiagRecs *diagrecs(oid_proto proto, int error, char *addinfo)
791 {
792     static Z_DiagRecs recs;
793     static int err;
794     oident bib1;
795 #ifdef Z_95
796     static Z_DiagRec *recp[1], drec;
797     static Z_DefaultDiagFormat rec;
798 #else
799     static Z_DiagRec *recp[1], rec;
800 #endif
801
802     logf(LOG_DEBUG, "DiagRecs: %d -- %s", error, addinfo);
803     bib1.proto = proto;
804     bib1.class = CLASS_DIAGSET;
805     bib1.value = VAL_BIB1;
806
807     err = error;
808     recs.num_diagRecs = 1;
809     recs.diagRecs = recp;
810 #ifdef Z_95
811     recp[0] = &drec;
812     drec.which = Z_DiagRec_defaultFormat;
813     drec.u.defaultFormat = &rec;
814 #else
815     recp[0] = &rec;
816 #endif
817     rec.diagnosticSetId = oid_getoidbyent(&bib1);
818     rec.condition = &err;
819     rec.which = Z_DiagForm_v2AddInfo;
820     rec.addinfo = addinfo ? addinfo : "";
821     return &recs;
822 }
823
824 #define MAX_RECORDS 256
825
826 static Z_Records *pack_records(association *a, char *setname, int start,
827                                 int *num, Z_RecordComposition *comp,
828                                 int *next, int *pres, oid_value format)
829 {
830     int recno, total_length = 0, toget = *num;
831     static Z_Records records;
832     static Z_NamePlusRecordList reclist;
833     static Z_NamePlusRecord *list[MAX_RECORDS];
834     oident recform;
835
836     records.which = Z_Records_DBOSD;
837     records.u.databaseOrSurDiagnostics = &reclist;
838     reclist.num_records = 0;
839     reclist.records = list;
840     *pres = Z_PRES_SUCCESS;
841     *num = 0;
842     *next = 0;
843
844     logf(LOG_DEBUG, "Request to pack %d+%d", start, toget);
845     logf(LOG_DEBUG, "pms=%d, mrs=%d", a->preferredMessageSize,
846         a->maximumRecordSize);
847     for (recno = start; reclist.num_records < toget; recno++)
848     {
849         bend_fetchrequest freq;
850         bend_fetchresult *fres;
851         Z_NamePlusRecord *thisrec;
852         Z_DatabaseRecord *thisext;
853         int this_length;
854
855         /*
856          * we get the number of bytes allocated on the stream before any
857          * allocation done by the backend - this should give us a reasonable
858          * idea of the total size of the data so far.
859          */
860         total_length = odr_total(a->encode);
861         if (reclist.num_records == MAX_RECORDS - 1)
862         {
863             *pres = Z_PRES_PARTIAL_2;
864             break;
865         }
866         freq.setname = setname;
867         freq.number = recno;
868         freq.comp = comp;
869         freq.format = format;
870         freq.stream = a->encode;
871         if (!(fres = bend_fetch(a->backend, &freq, 0)))
872         {
873             *pres = Z_PRES_FAILURE;
874             return diagrec(a->proto, 2, "Backend interface problem");
875         }
876         /* backend should be able to signal whether error is system-wide
877            or only pertaining to current record */
878         if (fres->errcode)
879         {
880             *pres = Z_PRES_FAILURE;
881             return diagrec(a->proto, fres->errcode, fres->errstring);
882         }
883         if (fres->len >= 0)
884             this_length = fres->len;
885         else
886             this_length = odr_total(a->encode) - total_length;
887         logf(LOG_DEBUG, "  fetched record, len=%d, total=%d",
888             this_length, total_length);
889         if (this_length + total_length > a->preferredMessageSize)
890         {
891             /* record is small enough, really */
892             if (this_length <= a->preferredMessageSize)
893             {
894                 logf(LOG_DEBUG, "  Dropped last normal-sized record");
895                 *pres = Z_PRES_PARTIAL_2;
896                 break;
897             }
898             /* record can only be fetched by itself */
899             if (this_length < a->maximumRecordSize)
900             {
901                 logf(LOG_DEBUG, "  Record > prefmsgsz");
902                 if (toget > 1)
903                 {
904                     logf(LOG_DEBUG, "  Dropped it");
905                     reclist.records[reclist.num_records] =
906                          surrogatediagrec(a->proto, fres->basename, 16, 0);
907                     reclist.num_records++;
908                     continue;
909                 }
910             }
911             else /* too big entirely */
912             {
913                 logf(LOG_DEBUG, "Record > maxrcdsz");
914                 reclist.records[reclist.num_records] =
915                     surrogatediagrec(a->proto, fres->basename, 17, 0);
916                 reclist.num_records++;
917                 continue;
918             }
919         }
920         if (!(thisrec = odr_malloc(a->encode, sizeof(*thisrec))))
921             return 0;
922         if (!(thisrec->databaseName = odr_malloc(a->encode,
923             strlen(fres->basename) + 1)))
924             return 0;
925         strcpy(thisrec->databaseName, fres->basename);
926         thisrec->which = Z_NamePlusRecord_databaseRecord;
927         if (!(thisrec->u.databaseRecord = thisext = odr_malloc(a->encode,
928             sizeof(Z_DatabaseRecord))))
929             return 0;
930         recform.proto = a->proto;
931         recform.class = CLASS_RECSYN;
932         recform.value = fres->format;
933         thisext->direct_reference = odr_oiddup(a->encode,
934             oid_getoidbyent(&recform));
935         thisext->indirect_reference = 0;
936         thisext->descriptor = 0;
937         if (fres->len < 0) /* Structured data */
938         {
939             switch (fres->format)
940             {
941                 case VAL_SUTRS: thisext->which = Z_External_sutrs; break;
942                 case VAL_GRS1: thisext->which = Z_External_grs1; break;
943                 case VAL_EXPLAIN: thisext->which = Z_External_explainRecord;
944                     break;
945
946                 default:
947                     logf(LOG_FATAL, "Unknown structured format from backend.");
948                     return 0;
949             }
950
951             /*
952              * We cheat on the pointers here. Obviously, the record field
953              * of the backend-fetch structure should have been a union for
954              * correctness, but we're stuck with this for backwards
955              * compatibility.
956              */
957             thisext->u.grs1 = (Z_GenericRecord*) fres->record;
958         }
959         else if (fres->format == VAL_SUTRS) /* SUTRS is a single-ASN.1-type */
960         {
961             Odr_oct *sutrs = odr_malloc(a->encode, sizeof(*sutrs));
962
963             thisext->which = Z_External_sutrs;
964             thisext->u.sutrs = sutrs;
965             sutrs->buf = odr_malloc(a->encode, fres->len);
966             sutrs->len = sutrs->size = fres->len;
967             memcpy(sutrs->buf, fres->record, fres->len);
968         }
969         else /* octet-aligned record. */
970         {
971             thisext->which = Z_External_octet;
972             if (!(thisext->u.octet_aligned = odr_malloc(a->encode,
973                 sizeof(Odr_oct))))
974                 return 0;
975             if (!(thisext->u.octet_aligned->buf = odr_malloc(a->encode,
976                 fres->len)))
977                 return 0;
978             memcpy(thisext->u.octet_aligned->buf, fres->record, fres->len);
979             thisext->u.octet_aligned->len = thisext->u.octet_aligned->size =
980                 fres->len;
981         }
982         reclist.records[reclist.num_records] = thisrec;
983         reclist.num_records++;
984         *next = fres->last_in_set ? 0 : recno + 1;
985     }
986     *num = reclist.num_records;
987     return &records;
988 }
989
990 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
991     int *fd)
992 {
993     Z_SearchRequest *req = reqb->request->u.searchRequest;
994     bend_searchrequest bsrq;
995     bend_searchresult *bsrt;
996
997     logf(LOG_LOG, "Got SearchRequest.");
998
999     bsrq.setname = req->resultSetName;
1000     bsrq.replace_set = *req->replaceIndicator;
1001     bsrq.num_bases = req->num_databaseNames;
1002     bsrq.basenames = req->databaseNames;
1003     bsrq.query = req->query;
1004
1005     if (!(bsrt = bend_search(assoc->backend, &bsrq, fd)))
1006         return 0;
1007     return response_searchRequest(assoc, reqb, bsrt, fd);
1008 }
1009
1010 bend_searchresult *bend_searchresponse(void *handle) {return 0;}
1011
1012 /*
1013  * Prepare a searchresponse based on the backend results. We probably want
1014  * to look at making the fetching of records nonblocking as well, but
1015  * so far, we'll keep things simple.
1016  * If bsrt is null, that means we're called in response to a communications
1017  * event, and we'll have to get the response for ourselves.
1018  */
1019 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
1020     bend_searchresult *bsrt, int *fd)
1021 {
1022     Z_SearchRequest *req = reqb->request->u.searchRequest;
1023     static Z_APDU apdu;
1024     static Z_SearchResponse resp;
1025     static int nulint = 0;
1026     static bool_t sr = 1;
1027     static int next = 0;
1028     static int none = Z_RES_NONE;
1029
1030     apdu.which = Z_APDU_searchResponse;
1031     apdu.u.searchResponse = &resp;
1032     resp.referenceId = req->referenceId;
1033 #ifdef Z_95
1034     resp.additionalSearchInfo = 0;
1035     resp.otherInfo = 0;
1036 #endif
1037     *fd = -1;
1038     if (!bsrt && !(bsrt = bend_searchresponse(assoc->backend)))
1039     {
1040         logf(LOG_FATAL, "Bad result from backend");
1041         return 0;
1042     }
1043     else if (bsrt->errcode)
1044     {
1045         resp.records = diagrec(assoc->proto, bsrt->errcode,
1046             bsrt->errstring);
1047         resp.resultCount = &nulint;
1048         resp.numberOfRecordsReturned = &nulint;
1049         resp.nextResultSetPosition = &nulint;
1050         resp.searchStatus = &nulint;
1051         resp.resultSetStatus = &none;
1052         resp.presentStatus = 0;
1053     }
1054     else
1055     {
1056         static int toget;
1057         Z_RecordComposition comp, *compp = 0;
1058         static int presst = 0;
1059
1060         resp.records = 0;
1061         resp.resultCount = &bsrt->hits;
1062
1063         comp.which = Z_RecordComp_simple;
1064         /* how many records does the user agent want, then? */
1065         if (bsrt->hits <= *req->smallSetUpperBound)
1066         {
1067             toget = bsrt->hits;
1068             if ((comp.u.simple = req->smallSetElementSetNames))
1069                 compp = &comp;
1070         }
1071         else if (bsrt->hits < *req->largeSetLowerBound)
1072         {
1073             toget = *req->mediumSetPresentNumber;
1074             if (toget > bsrt->hits)
1075                 toget = bsrt->hits;
1076             if ((comp.u.simple = req->mediumSetElementSetNames))
1077                 compp = &comp;
1078         }
1079         else
1080             toget = 0;
1081
1082         if (toget && !resp.records)
1083         {
1084             oident *prefformat;
1085             oid_value form;
1086
1087             if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1088                 prefformat->class != CLASS_RECSYN)
1089                 form = VAL_NONE;
1090             else
1091                 form = prefformat->value;
1092             resp.records = pack_records(assoc, req->resultSetName, 1,
1093                 &toget, compp, &next, &presst, form);
1094             if (!resp.records)
1095                 return 0;
1096             resp.numberOfRecordsReturned = &toget;
1097             resp.nextResultSetPosition = &next;
1098             resp.searchStatus = &sr;
1099             resp.resultSetStatus = 0;
1100             resp.presentStatus = &presst;
1101         }
1102         else
1103         {
1104             if (*resp.resultCount)
1105                 next = 1;
1106             resp.numberOfRecordsReturned = &nulint;
1107             resp.nextResultSetPosition = &next;
1108             resp.searchStatus = &sr;
1109             resp.resultSetStatus = 0;
1110             resp.presentStatus = 0;
1111         }
1112     }
1113     return &apdu;
1114 }
1115
1116 /*
1117  * Maybe we got a little over-friendly when we designed bend_fetch to
1118  * get only one record at a time. Some backends can optimise multiple-record
1119  * fetches, and at any rate, there is some overhead involved in
1120  * all that selecting and hopping around. Problem is, of course, that the
1121  * frontend can't know ahead of time how many records it'll need to
1122  * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
1123  * is downright lousy as a bulk data transfer protocol.
1124  *
1125  * To start with, we'll do the fetching of records from the backend
1126  * in one operation: To save some trips in and out of the event-handler,
1127  * and to simplify the interface to pack_records. At any rate, asynch
1128  * operation is more fun in operations that have an unpredictable execution
1129  * speed - which is normally more true for search than for present.
1130  */
1131 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
1132     int *fd)
1133 {
1134     Z_PresentRequest *req = reqb->request->u.presentRequest;
1135     static Z_APDU apdu;
1136     static Z_PresentResponse resp;
1137     static int presst, next, num;
1138     oident *prefformat;
1139     oid_value form;
1140
1141
1142     logf(LOG_LOG, "Got PresentRequest.");
1143     apdu.which = Z_APDU_presentResponse;
1144     apdu.u.presentResponse = &resp;
1145     resp.referenceId = req->referenceId;
1146 #ifdef Z_95
1147     resp.otherInfo = 0;
1148 #endif
1149
1150     if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)) ||
1151         prefformat->class != CLASS_RECSYN)
1152         form = VAL_NONE;
1153     else
1154         form = prefformat->value;
1155     num = *req->numberOfRecordsRequested;
1156     resp.records = pack_records(assoc, req->resultSetId,
1157         *req->resultSetStartPoint, &num, req->recordComposition, &next,
1158         &presst, form);
1159     if (!resp.records)
1160         return 0;
1161     resp.numberOfRecordsReturned = &num;
1162     resp.presentStatus = &presst;
1163     resp.nextResultSetPosition = &next;
1164
1165     return &apdu;
1166 }
1167
1168 /*
1169  * Scan was implemented rather in a hurry, and with support for only the basic
1170  * elements of the service in the backend API. Suggestions are welcome.
1171  */
1172 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
1173 {
1174     Z_ScanRequest *req = reqb->request->u.scanRequest;
1175     static Z_APDU apdu;
1176     static Z_ScanResponse res;
1177     static int scanStatus = Z_Scan_failure;
1178     static int numberOfEntriesReturned = 0;
1179     oident *attent;
1180     static Z_ListEntries ents;
1181 #define SCAN_MAX_ENTRIES 200
1182     static Z_Entry *tab[SCAN_MAX_ENTRIES];
1183     bend_scanrequest srq;
1184     bend_scanresult *srs;
1185
1186     logf(LOG_LOG, "Got scanrequest");
1187     apdu.which = Z_APDU_scanResponse;
1188     apdu.u.scanResponse = &res;
1189     res.referenceId = req->referenceId;
1190     res.stepSize = 0;
1191     res.scanStatus = &scanStatus;
1192     res.numberOfEntriesReturned = &numberOfEntriesReturned;
1193     res.positionOfTerm = 0;
1194     res.entries = &ents;
1195     ents.which = Z_ListEntries_nonSurrogateDiagnostics;
1196     res.attributeSet = 0;
1197 #ifdef Z_95
1198     res.otherInfo = 0;
1199 #endif
1200
1201     if (req->attributeSet && (!(attent = oid_getentbyoid(req->attributeSet)) ||
1202         attent->class != CLASS_ATTSET || attent->value != VAL_BIB1))
1203         ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 121, 0);
1204     else if (req->stepSize && *req->stepSize > 0)
1205         ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 205, 0);
1206     else
1207     {
1208         if (req->termListAndStartPoint->term->which == Z_Term_general)
1209             logf(LOG_DEBUG, " term: '%.*s'",
1210                 req->termListAndStartPoint->term->u.general->len,
1211                 req->termListAndStartPoint->term->u.general->buf);
1212         srq.num_bases = req->num_databaseNames;
1213         srq.basenames = req->databaseNames;
1214         srq.num_entries = *req->numberOfTermsRequested;
1215         srq.term = req->termListAndStartPoint;
1216         srq.term_position = req->preferredPositionInResponse ?
1217             *req->preferredPositionInResponse : 1;
1218         if (!(srs = bend_scan(assoc->backend, &srq, 0)))
1219             ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 2, 0);
1220         else if (srs->errcode)
1221             ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto,
1222                 srs->errcode, srs->errstring);
1223         else
1224         {
1225             int i;
1226             static Z_Entries list;
1227
1228             if (srs->status == BEND_SCAN_PARTIAL)
1229                 scanStatus = Z_Scan_partial_5;
1230             else
1231                 scanStatus = Z_Scan_success;
1232             ents.which = Z_ListEntries_entries;
1233             ents.u.entries = &list;
1234             list.entries = tab;
1235             for (i = 0; i < srs->num_entries; i++)
1236             {
1237                 Z_Entry *e;
1238                 Z_TermInfo *t;
1239                 Odr_oct *o;
1240
1241                 if (i >= SCAN_MAX_ENTRIES)
1242                 {
1243                     scanStatus = Z_Scan_partial_4;
1244                     break;
1245                 }
1246                 list.entries[i] = e = odr_malloc(assoc->encode, sizeof(*e));
1247                 e->which = Z_Entry_termInfo;
1248                 e->u.termInfo = t = odr_malloc(assoc->encode, sizeof(*t));
1249                 t->suggestedAttributes = 0;
1250                 t->alternativeTerm = 0;
1251                 t->byAttributes = 0;
1252                 t->globalOccurrences = &srs->entries[i].occurrences;
1253                 t->term = odr_malloc(assoc->encode, sizeof(*t->term));
1254                 t->term->which = Z_Term_general;
1255                 t->term->u.general = o = odr_malloc(assoc->encode,
1256                     sizeof(Odr_oct));
1257                 o->buf = odr_malloc(assoc->encode, o->len = o->size =
1258                     strlen(srs->entries[i].term));
1259                 memcpy(o->buf, srs->entries[i].term, o->len);
1260                 logf(LOG_DEBUG, "  term #%d: '%s' (%d)", i,
1261                     srs->entries[i].term, srs->entries[i].occurrences);
1262             }
1263             list.num_entries = i;
1264             res.numberOfEntriesReturned = &list.num_entries;
1265             res.positionOfTerm = &srs->term_position;
1266         }
1267     }
1268
1269     return &apdu;
1270 }
1271
1272 static void process_close(association *assoc, request *reqb)
1273 {
1274     Z_Close *req = reqb->request->u.close;
1275     static char *reasons[] =
1276     {
1277         "finished",
1278         "shutdown",
1279         "systemProblem",
1280         "costLimit",
1281         "resources",
1282         "securityViolation",
1283         "protocolError",
1284         "lackOfActivity",
1285         "peerAbort",
1286         "unspecified"
1287     };
1288
1289     logf(LOG_LOG, "Got close, reason %s, message %s",
1290         reasons[*req->closeReason], req->diagnosticInformation ?
1291         req->diagnosticInformation : "NULL");
1292     if (assoc->version < 3) /* to make do_force respond with close */
1293         assoc->version = 3;
1294     do_close(assoc, Z_Close_finished, "Association terminated by client");
1295 }