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