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