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