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