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