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