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