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