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