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