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