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