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