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