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