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