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