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