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