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