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