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