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