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