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