Added a better SCAN.
[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.30  1995-06-05 10:53:32  quinn
8  * Added a better SCAN.
9  *
10  * Revision 1.29  1995/06/01  11:25:03  quinn
11  * Smallish.
12  *
13  * Revision 1.28  1995/06/01  11:21:01  quinn
14  * Attempting to fix a bug in pack-records. replaced break with continue
15  * for large records, according to standard.
16  *
17  * Revision 1.27  1995/05/29  08:12:06  quinn
18  * Moved oid to util
19  *
20  * Revision 1.26  1995/05/18  13:02:12  quinn
21  * Smallish.
22  *
23  * Revision 1.25  1995/05/17  08:42:26  quinn
24  * Transfer auth info to backend. Allow backend to reject init gracefully.
25  *
26  * Revision 1.24  1995/05/16  08:51:04  quinn
27  * License, documentation, and memory fixes
28  *
29  * Revision 1.23  1995/05/15  13:25:10  quinn
30  * Fixed memory bug.
31  *
32  * Revision 1.22  1995/05/15  11:56:39  quinn
33  * Asynchronous facilities. Restructuring of seshigh code.
34  *
35  * Revision 1.21  1995/05/02  08:53:19  quinn
36  * Trying in vain to fix comm with ISODE
37  *
38  * Revision 1.20  1995/04/20  15:13:00  quinn
39  * Cosmetic
40  *
41  * Revision 1.19  1995/04/18  08:15:34  quinn
42  * Added dynamic memory allocation on encoding (whew). Code is now somewhat
43  * neater. We'll make the same change for decoding one day.
44  *
45  * Revision 1.18  1995/04/17  11:28:25  quinn
46  * Smallish
47  *
48  * Revision 1.17  1995/04/10  10:23:36  quinn
49  * Some work to add scan and other things.
50  *
51  * Revision 1.16  1995/03/31  09:18:55  quinn
52  * Added logging.
53  *
54  * Revision 1.15  1995/03/30  14:03:23  quinn
55  * Added RFC1006 as separate library
56  *
57  * Revision 1.14  1995/03/30  12:18:17  quinn
58  * Fixed bug.
59  *
60  * Revision 1.13  1995/03/30  09:09:24  quinn
61  * Added state-handle and some support for asynchronous activities.
62  *
63  * Revision 1.12  1995/03/29  15:40:16  quinn
64  * Ongoing work. Statserv is now dynamic by default
65  *
66  * Revision 1.11  1995/03/28  09:16:21  quinn
67  * Added record packing to the search request
68  *
69  * Revision 1.10  1995/03/27  08:34:24  quinn
70  * Added dynamic server functionality.
71  * Released bindings to session.c (is now redundant)
72  *
73  * Revision 1.9  1995/03/22  15:01:26  quinn
74  * Adjusting record packing.
75  *
76  * Revision 1.8  1995/03/22  10:13:21  quinn
77  * Working on record packer
78  *
79  * Revision 1.7  1995/03/21  15:53:31  quinn
80  * Little changes.
81  *
82  * Revision 1.6  1995/03/21  12:30:09  quinn
83  * Beginning to add support for record packing.
84  *
85  * Revision 1.5  1995/03/17  10:44:13  quinn
86  * Added catch of null-string in makediagrec
87  *
88  * Revision 1.4  1995/03/17  10:18:08  quinn
89  * Added memory management.
90  *
91  * Revision 1.3  1995/03/16  17:42:39  quinn
92  * Little changes
93  *
94  * Revision 1.2  1995/03/16  13:29:01  quinn
95  * Partitioned server.
96  *
97  * Revision 1.1  1995/03/15  16:02:10  quinn
98  * Modded session.c to seshigh.c
99  *
100  */
101
102 /*
103  * Frontend server logic.
104  *
105  * This code receives incoming APDUs, and handles client requests by means
106  * of the backend API.
107  *
108  * Some of the code is getting quite involved, compared to simpler servers -
109  * primarily because it is asynchronous both in the communication with
110  * the user and the backend. We think the complexity will pay off in
111  * the form of greater flexibility when more asynchronous facilities
112  * are implemented.
113  *
114  * Memory management has become somewhat involved. In the simple case, where
115  * only one PDU is pending at a time, it will simply reuse the same memory,
116  * once it has found its working size. When we enable multiple concurrent
117  * operations, perhaps even with multiple parallel calls to the backend, it
118  * will maintain a pool of buffers for encoding and decoding, trying to
119  * minimize memory allocation/deallocation during normal operation.
120  *
121  * TODOs include (and will be done in order of public interest):
122  * 
123  * Support for EXPLAIN - provide simple meta-database system.
124  * Support for access control.
125  * Support for resource control.
126  * Support for extended services - primarily Item Order.
127  * Rest of Z39.50-1994
128  *
129  */
130
131 #include <stdlib.h>
132 #include <stdio.h>
133 #include <unistd.h>
134 #include <assert.h>
135
136 #include <dmalloc.h>
137 #include <comstack.h>
138 #include <eventl.h>
139 #include <session.h>
140 #include <proto.h>
141 #include <oid.h>
142 #include <log.h>
143 #include <statserv.h>
144 #include "../version.h"
145
146 #include <backend.h>
147
148 static int process_request(association *assoc);
149 void backend_response(IOCHAN i, int event);
150 static int process_response(association *assoc, request *req, Z_APDU *res);
151 static Z_APDU *process_initRequest(association *assoc, request *reqb);
152 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
153     int *fd);
154 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
155     bend_searchresult *bsrt, int *fd);
156 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
157     int *fd);
158 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
159
160 static FILE *apduf = 0; /* for use in static mode */
161 static statserv_options_block *control_block = 0;
162
163 /*
164  * Create and initialize a new association-handle.
165  *  channel  : iochannel for the current line.
166  *  link     : communications channel.
167  * Returns: 0 or a new association handle.
168  */
169 association *create_association(IOCHAN channel, COMSTACK link)
170 {
171     association *new;
172
173     if (!control_block)
174         control_block = statserv_getcontrol();
175     if (!(new = malloc(sizeof(*new))))
176         return 0;
177     new->client_chan = channel;
178     new->client_link = link;
179     if (!(new->decode = odr_createmem(ODR_DECODE)) ||
180         !(new->encode = odr_createmem(ODR_ENCODE)))
181         return 0;
182     if (*control_block->apdufile)
183     {
184         char filename[256];
185         FILE *f;
186
187         strcpy(filename, control_block->apdufile);
188         if (!(new->print = odr_createmem(ODR_PRINT)))
189             return 0;
190         if (*control_block->apdufile != '-')
191         {
192             strcpy(filename, control_block->apdufile);
193             if (!control_block->dynamic)
194             {
195                 if (!apduf)
196                 {
197                     if (!(apduf = fopen(filename, "w")))
198                     {
199                         logf(LOG_WARN|LOG_ERRNO, "%s", filename);
200                         return 0;
201                     }
202                     setvbuf(apduf, 0, _IONBF, 0);
203                 }
204                 f = apduf;
205             }
206             else 
207             {
208                 sprintf(filename + strlen(filename), ".%d", getpid());
209                 if (!(f = fopen(filename, "w")))
210                 {
211                     logf(LOG_WARN|LOG_ERRNO, "%s", filename);
212                     return 0;
213                 }
214                 setvbuf(f, 0, _IONBF, 0);
215             }
216             odr_setprint(new->print, f);
217         }
218     }
219     else
220         new->print = 0;
221     new->input_buffer = 0;
222     new->input_buffer_len = 0;
223     new->backend = 0;
224     new->rejected = 0;
225     request_initq(&new->incoming);
226     request_initq(&new->outgoing);
227     new->proto = cs_getproto(link);
228     return new;
229 }
230
231 /*
232  * Free association and release resources.
233  */
234 void destroy_association(association *h)
235 {
236     odr_destroy(h->decode);
237     odr_destroy(h->encode);
238     if (h->print)
239         odr_destroy(h->print);
240     if (h->input_buffer)
241         free(h->input_buffer);
242     if (h->backend)
243         bend_close(h->backend);
244     while (request_deq(&h->incoming));
245     while (request_deq(&h->outgoing));
246     free(h);
247 }
248
249 /*
250  * This is where PDUs from the client are read and the further
251  * processing is initiated. Flow of control moves down through the
252  * various process_* functions below, until the encoded result comes back up
253  * to the output handler in here.
254  * 
255  *  h     : the I/O channel that has an outstanding event.
256  *  event : the current outstanding event.
257  */
258 void ir_session(IOCHAN h, int event)
259 {
260     int res;
261     association *assoc = iochan_getdata(h);
262     COMSTACK conn = assoc->client_link;
263     request *req;
264
265     assert(h && conn && assoc);
266     if (event & EVENT_INPUT || event & EVENT_WORK) /* input */
267     {
268         if (event & EVENT_INPUT)
269         {
270             logf(LOG_DEBUG, "ir_session (input)");
271             assert(assoc && conn);
272             /* We aren't speaking to this fellow */
273             if (assoc->rejected)
274             {
275                 logf(LOG_LOG, "Closed connection after reject");
276                 cs_close(conn);
277                 destroy_association(assoc);
278                 iochan_destroy(h);
279                 return;
280             }
281             if ((res = cs_get(conn, &assoc->input_buffer,
282                 &assoc->input_buffer_len)) <= 0)
283             {
284                 logf(LOG_LOG, "Connection closed by client");
285                 cs_close(conn);
286                 destroy_association(assoc);
287                 iochan_destroy(h);
288                 return;
289             }
290             else if (res == 1) /* incomplete read - wait for more  */
291                 return;
292             if (cs_more(conn)) /* more stuff - call us again later, please */
293                 iochan_setevent(h, EVENT_INPUT);
294                 
295             /* we got a complete PDU. Let's decode it */
296             req = request_get(); /* get a new request structure */
297             odr_reset(assoc->decode);
298             odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
299             if (!z_APDU(assoc->decode, &req->request, 0))
300             {
301                 logf(LOG_WARN, "ODR error: %s",
302                     odr_errlist[odr_geterror(assoc->decode)]);
303                 cs_close(conn);
304                 destroy_association(assoc);
305                 iochan_destroy(h);
306                 return;
307             }
308             req->request_mem = odr_extract_mem(assoc->decode);
309             if (assoc->print && !z_APDU(assoc->print, &req->request, 0))
310             {
311                 logf(LOG_WARN, "ODR print error: %s", 
312                     odr_errlist[odr_geterror(assoc->print)]);
313                 odr_reset(assoc->print);
314             }
315             request_enq(&assoc->incoming, req);
316         }
317
318         /* can we do something yet? */
319         req = request_head(&assoc->incoming);
320         if (req->state == REQUEST_IDLE)
321             if (process_request(assoc) < 0)
322             {
323                 cs_close(conn);
324                 destroy_association(assoc);
325                 iochan_destroy(h);
326             }
327     }
328     if (event & EVENT_OUTPUT)
329     {
330         request *req = request_head(&assoc->outgoing);
331
332         logf(LOG_DEBUG, "ir_session (output)");
333         req->state = REQUEST_PENDING;
334         switch (res = cs_put(conn, req->response, req->len_response))
335         {
336             case -1:
337                 logf(LOG_LOG, "Connection closed by client");
338                 cs_close(conn);
339                 destroy_association(assoc);
340                 iochan_destroy(h);
341                 break;
342             case 0: /* all sent - release the request structure */
343                 odr_release_mem(req->request_mem);
344                 request_deq(&assoc->outgoing);
345                 request_release(req);
346                 if (!request_head(&assoc->outgoing))
347                     iochan_clearflag(h, EVENT_OUTPUT);
348                 break;
349             /* value of 1 -- partial send -- is simply ignored */
350         }
351     }
352     if (event & EVENT_EXCEPT)
353     {
354         logf(LOG_DEBUG, "ir_session (exception)");
355         cs_close(conn);
356         destroy_association(assoc);
357         iochan_destroy(h);
358     }
359 }
360
361 /*
362  * Initiate request processing.
363  */
364 static int process_request(association *assoc)
365 {
366     request *req = request_head(&assoc->incoming);
367     int fd = -1;
368     Z_APDU *res;
369
370     logf(LOG_DEBUG, "process_request");
371     assert(req && req->state == REQUEST_IDLE);
372     switch (req->request->which)
373     {
374         case Z_APDU_initRequest:
375             res = process_initRequest(assoc, req); break;
376         case Z_APDU_searchRequest:
377             res = process_searchRequest(assoc, req, &fd); break;
378         case Z_APDU_presentRequest:
379             res = process_presentRequest(assoc, req, &fd); break;
380         case Z_APDU_scanRequest:
381             res = process_scanRequest(assoc, req, &fd); break;
382         default:
383             logf(LOG_WARN, "Bad APDU received");
384             return -1;
385     }
386     if (res)
387     {
388         logf(LOG_DEBUG, "  result immediately available");
389         return process_response(assoc, req, res);
390     }
391     else if (fd < 0)
392     {
393         logf(LOG_WARN, "   bad result");
394         return -1;
395     }
396     else /* no result yet - one will be provided later */
397     {
398         IOCHAN chan;
399
400         /* Set up an I/O handler for the fd supplied by the backend */
401
402         logf(LOG_DEBUG, "   establishing handler for result");
403         req->state = REQUEST_PENDING;
404         if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT)))
405             abort();
406         iochan_setdata(chan, assoc);
407         return 0;
408     }
409 }
410
411 /*
412  * Handle message from the backend.
413  */
414 void backend_response(IOCHAN i, int event)
415 {
416     association *assoc = iochan_getdata(i);
417     request *req = request_head(&assoc->incoming);
418     Z_APDU *res;
419     int fd;
420
421     logf(LOG_DEBUG, "backend_response");
422     assert(assoc && req && req->state != REQUEST_IDLE);
423     /* determine what it is we're waiting for */
424     switch (req->request->which)
425     {
426         case Z_APDU_searchRequest:
427             res = response_searchRequest(assoc, req, 0, &fd); break;
428 #if 0
429         case Z_APDU_presentRequest:
430             res = response_presentRequest(assoc, req, 0, &fd); break;
431         case Z_APDU_scanRequest:
432             res = response_scanRequest(assoc, req, 0, &fd); break;
433 #endif
434         default:
435             logf(LOG_WARN, "Serious programmer's lapse or bug");
436             abort();
437     }
438     if ((res && process_response(assoc, req, res) < 0) || fd < 0)
439     {
440         logf(LOG_LOG, "Fatal error when talking to backend");
441         cs_close(assoc->client_link);
442         destroy_association(assoc);
443         iochan_destroy(assoc->client_chan);
444         iochan_destroy(i);
445         return;
446     }
447     else if (!res) /* no result yet - try again later */
448     {
449         logf(LOG_DEBUG, "   no result yet");
450         iochan_setfd(i, fd); /* in case fd has changed */
451     }
452 }
453
454 /*
455  * Encode response, and transfer the request structure to the outgoing queue.
456  */
457 static int process_response(association *assoc, request *req, Z_APDU *res)
458 {
459     odr_setbuf(assoc->encode, req->response, req->size_response, 1);
460     if (!z_APDU(assoc->encode, &res, 0))
461     {
462         logf(LOG_WARN, "ODR error when encoding response: %s",
463             odr_errlist[odr_geterror(assoc->decode)]);
464         return -1;
465     }
466     req->response = odr_getbuf(assoc->encode, &req->len_response,
467         &req->size_response);
468     odr_setbuf(assoc->encode, 0, 0, 0); /* don't free if we abort later */
469     odr_reset(assoc->encode);
470     if (assoc->print && !z_APDU(assoc->print, &res, 0))
471     {
472         logf(LOG_WARN, "ODR print error: %s", 
473             odr_errlist[odr_geterror(assoc->print)]);
474         odr_reset(assoc->print);
475     }
476     /* change this when we make the backend reentrant */
477     assert(req == request_head(&assoc->incoming));
478     req->state = REQUEST_IDLE;
479     request_deq(&assoc->incoming);
480     request_enq(&assoc->outgoing, req);
481     /* turn the work over to the ir_session handler */
482     iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
483     /* Is there more work to be done? give that to the input handler too */
484     if (request_head(&assoc->incoming))
485         iochan_setevent(assoc->client_chan, EVENT_WORK);
486     return 0;
487 }
488
489 /*
490  * Handle init request.
491  * At the moment, we don't check the protocol version or the options
492  * anywhere else in the code - we just try not to do anything that would
493  * break a naive client. We'll toss 'em into the association block when
494  * we need them there.
495  */
496 static Z_APDU *process_initRequest(association *assoc, request *reqb)
497 {
498     Z_InitRequest *req = reqb->request->u.initRequest;
499     Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
500     Z_InitResponse *resp = apdu->u.initResponse;
501     bend_initrequest binitreq;
502     bend_initresult *binitres;
503
504     logf(LOG_LOG, "Got initRequest");
505     if (req->implementationId)
506         logf(LOG_LOG, "Id:        %s", req->implementationId);
507     if (req->implementationName)
508         logf(LOG_LOG, "Name:      %s", req->implementationName);
509     if (req->implementationVersion)
510         logf(LOG_LOG, "Version:   %s", req->implementationVersion);
511
512     binitreq.configname = "default-config";
513     binitreq.auth = req->idAuthentication;
514     if (!(binitres = bend_init(&binitreq)))
515     {
516         logf(LOG_WARN, "Bad response from backend.");
517         return 0;
518     }
519
520     assoc->backend = binitres->handle;
521     resp->referenceId = req->referenceId;
522     /* let's tell the client what we can do */
523     if (ODR_MASK_GET(req->options, Z_Options_search))
524         ODR_MASK_SET(resp->options, Z_Options_search);
525     if (ODR_MASK_GET(req->options, Z_Options_present))
526         ODR_MASK_SET(resp->options, Z_Options_present);
527 #if 0
528     if (ODR_MASK_GET(req->options, Z_Options_delSet))
529         ODR_MASK_SET(&options, Z_Options_delSet);
530 #endif
531     if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
532         ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
533     if (ODR_MASK_GET(req->options, Z_Options_scan))
534         ODR_MASK_SET(resp->options, Z_Options_scan);
535     if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
536         ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
537
538     if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
539         ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
540     if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
541         ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
542     assoc->maximumRecordSize = *req->maximumRecordSize;
543     if (assoc->maximumRecordSize > control_block->maxrecordsize)
544         assoc->maximumRecordSize = control_block->maxrecordsize;
545     assoc->preferredMessageSize = *req->preferredMessageSize;
546     if (assoc->preferredMessageSize > assoc->maximumRecordSize)
547         assoc->preferredMessageSize = assoc->maximumRecordSize;
548     resp->preferredMessageSize = &assoc->preferredMessageSize;
549     resp->maximumRecordSize = &assoc->maximumRecordSize;
550     resp->implementationName = "Index Data/YAZ Generic Frontend Server";
551     if (binitres->errcode)
552     {
553         logf(LOG_LOG, "Connection rejected by backend.");
554         *resp->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                     total_length += 10; /* totally arbitrary */
718                     continue;
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                 total_length += 10; /* totally arbitrary */
728                 continue;
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         *next = fres->last_in_set ? 0 : recno + 1;
757     }
758     *num = reclist.num_records;
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     logf(LOG_LOG, "Got scanrequest");
930     apdu.which = Z_APDU_scanResponse;
931     apdu.u.scanResponse = &res;
932     res.referenceId = req->referenceId;
933     res.stepSize = 0;
934     res.scanStatus = &scanStatus;
935     res.numberOfEntriesReturned = &numberOfEntriesReturned;
936     res.positionOfTerm = 0;
937     res.entries = &ents;
938     ents.which = Z_ListEntries_nonSurrogateDiagnostics;
939     res.attributeSet = 0;
940
941     if (req->attributeSet && (!(attent = oid_getentbyoid(req->attributeSet)) ||
942         attent->class != CLASS_ATTSET || attent->value != VAL_BIB1))
943         ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 121, 0);
944     else if (req->stepSize && *req->stepSize > 0)
945         ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 205, 0);
946     else
947     {
948         srq.num_bases = req->num_databaseNames;
949         srq.basenames = req->databaseNames;
950         srq.num_entries = *req->numberOfTermsRequested;
951         srq.term = req->termListAndStartPoint;
952         srq.term_position = req->preferredPositionInResponse ?
953             *req->preferredPositionInResponse : 1;
954         if (!(srs = bend_scan(assoc->backend, &srq, 0)))
955             ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto, 2, 0);
956         else if (srs->errcode)
957             ents.u.nonSurrogateDiagnostics = diagrecs(assoc->proto,
958                 srs->errcode, srs->errstring);
959         else
960         {
961             int i;
962             static Z_Entries list;
963
964             if (srs->status == BEND_SCAN_PARTIAL)
965                 scanStatus = Z_Scan_partial_5;
966             else
967                 scanStatus = Z_Scan_success;
968             ents.which = Z_ListEntries_entries;
969             ents.u.entries = &list;
970             list.entries = tab;
971             for (i = 0; i < srs->num_entries; i++)
972             {
973                 Z_Entry *e;
974                 Z_TermInfo *t;
975                 Odr_oct *o;
976
977                 if (i >= SCAN_MAX_ENTRIES)
978                 {
979                     scanStatus = Z_Scan_partial_4;
980                     break;
981                 }
982                 list.entries[i] = e = odr_malloc(assoc->encode, sizeof(*e));
983                 e->which = Z_Entry_termInfo;
984                 e->u.termInfo = t = odr_malloc(assoc->encode, sizeof(*t));
985                 t->suggestedAttributes = 0;
986                 t->alternativeTerm = 0;
987                 t->byAttributes = 0;
988                 t->globalOccurrences = &srs->entries[i].occurrences;
989                 t->term = odr_malloc(assoc->encode, sizeof(*t->term));
990                 t->term->which = Z_Term_general;
991                 t->term->u.general = o = odr_malloc(assoc->encode,
992                     sizeof(Odr_oct));
993                 o->buf = odr_malloc(assoc->encode, o->len = o->size =
994                     strlen(srs->entries[i].term));
995                 memcpy(o->buf, srs->entries[i].term, o->len);
996             }
997             list.num_entries = i;
998             res.numberOfEntriesReturned = &list.num_entries;
999             res.positionOfTerm = &srs->term_position;
1000         }
1001     }
1002
1003     return &apdu;
1004 }