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