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