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