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