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