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