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