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