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