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