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