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