SRW, CQL, 2003
[yaz-moved-to-github.git] / server / seshigh.c
1 /*
2  * Copyright (c) 1995-2003, Index Data
3  * See the file LICENSE for details.
4  *
5  * $Id: seshigh.c,v 1.133 2003-01-06 08:20:28 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     yaz_log_zquery(req->query);
1051
1052     if (assoc->init->bend_search)
1053     {
1054         bsrr->setname = req->resultSetName;
1055         bsrr->replace_set = *req->replaceIndicator;
1056         bsrr->num_bases = req->num_databaseNames;
1057         bsrr->basenames = req->databaseNames;
1058         bsrr->query = req->query;
1059         bsrr->stream = assoc->encode;
1060         bsrr->decode = assoc->decode;
1061         bsrr->print = assoc->print;
1062         bsrr->errcode = 0;
1063         bsrr->hits = 0;
1064         bsrr->errstring = NULL;
1065         bsrr->search_info = NULL;
1066         (assoc->init->bend_search)(assoc->backend, bsrr);
1067         if (!bsrr->request)
1068             return 0;
1069     }
1070     return response_searchRequest(assoc, reqb, bsrr, fd);
1071 }
1072
1073 int bend_searchresponse(void *handle, bend_search_rr *bsrr) {return 0;}
1074
1075 /*
1076  * Prepare a searchresponse based on the backend results. We probably want
1077  * to look at making the fetching of records nonblocking as well, but
1078  * so far, we'll keep things simple.
1079  * If bsrt is null, that means we're called in response to a communications
1080  * event, and we'll have to get the response for ourselves.
1081  */
1082 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
1083     bend_search_rr *bsrt, int *fd)
1084 {
1085     Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
1086     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1087     Z_SearchResponse *resp = (Z_SearchResponse *)
1088         odr_malloc (assoc->encode, sizeof(*resp));
1089     int *nulint = odr_intdup (assoc->encode, 0);
1090     bool_t *sr = odr_intdup(assoc->encode, 1);
1091     int *next = odr_intdup(assoc->encode, 0);
1092     int *none = odr_intdup(assoc->encode, Z_RES_NONE);
1093
1094     apdu->which = Z_APDU_searchResponse;
1095     apdu->u.searchResponse = resp;
1096     resp->referenceId = req->referenceId;
1097     resp->additionalSearchInfo = 0;
1098     resp->otherInfo = 0;
1099     *fd = -1;
1100     if (!bsrt && !bend_searchresponse(assoc->backend, bsrt))
1101     {
1102         yaz_log(LOG_FATAL, "Bad result from backend");
1103         return 0;
1104     }
1105     else if (bsrt->errcode)
1106     {
1107         resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
1108         resp->resultCount = nulint;
1109         resp->numberOfRecordsReturned = nulint;
1110         resp->nextResultSetPosition = nulint;
1111         resp->searchStatus = nulint;
1112         resp->resultSetStatus = none;
1113         resp->presentStatus = 0;
1114     }
1115     else
1116     {
1117         int *toget = odr_intdup(assoc->encode, 0);
1118         int *presst = odr_intdup(assoc->encode, 0);
1119         Z_RecordComposition comp, *compp = 0;
1120
1121         yaz_log (LOG_LOG, "resultCount: %d", bsrt->hits);
1122
1123         resp->records = 0;
1124         resp->resultCount = &bsrt->hits;
1125
1126         comp.which = Z_RecordComp_simple;
1127         /* how many records does the user agent want, then? */
1128         if (bsrt->hits <= *req->smallSetUpperBound)
1129         {
1130             *toget = bsrt->hits;
1131             if ((comp.u.simple = req->smallSetElementSetNames))
1132                 compp = &comp;
1133         }
1134         else if (bsrt->hits < *req->largeSetLowerBound)
1135         {
1136             *toget = *req->mediumSetPresentNumber;
1137             if (*toget > bsrt->hits)
1138                 *toget = bsrt->hits;
1139             if ((comp.u.simple = req->mediumSetElementSetNames))
1140                 compp = &comp;
1141         }
1142         else
1143             *toget = 0;
1144
1145         if (*toget && !resp->records)
1146         {
1147             oident *prefformat;
1148             oid_value form;
1149
1150             if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
1151                 form = VAL_NONE;
1152             else
1153                 form = prefformat->value;
1154             resp->records = pack_records(assoc, req->resultSetName, 1,
1155                 toget, compp, next, presst, form, req->referenceId,
1156                                          req->preferredRecordSyntax);
1157             if (!resp->records)
1158                 return 0;
1159             resp->numberOfRecordsReturned = toget;
1160             resp->nextResultSetPosition = next;
1161             resp->searchStatus = sr;
1162             resp->resultSetStatus = 0;
1163             resp->presentStatus = presst;
1164         }
1165         else
1166         {
1167             if (*resp->resultCount)
1168                 *next = 1;
1169             resp->numberOfRecordsReturned = nulint;
1170             resp->nextResultSetPosition = next;
1171             resp->searchStatus = sr;
1172             resp->resultSetStatus = 0;
1173             resp->presentStatus = 0;
1174         }
1175     }
1176     resp->additionalSearchInfo = bsrt->search_info;
1177     return apdu;
1178 }
1179
1180 /*
1181  * Maybe we got a little over-friendly when we designed bend_fetch to
1182  * get only one record at a time. Some backends can optimise multiple-record
1183  * fetches, and at any rate, there is some overhead involved in
1184  * all that selecting and hopping around. Problem is, of course, that the
1185  * frontend can't know ahead of time how many records it'll need to
1186  * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
1187  * is downright lousy as a bulk data transfer protocol.
1188  *
1189  * To start with, we'll do the fetching of records from the backend
1190  * in one operation: To save some trips in and out of the event-handler,
1191  * and to simplify the interface to pack_records. At any rate, asynch
1192  * operation is more fun in operations that have an unpredictable execution
1193  * speed - which is normally more true for search than for present.
1194  */
1195 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
1196                                       int *fd)
1197 {
1198     Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
1199     oident *prefformat;
1200     oid_value form;
1201     Z_APDU *apdu;
1202     Z_PresentResponse *resp;
1203     int *next;
1204     int *num;
1205
1206     yaz_log(LOG_LOG, "Got PresentRequest.");
1207
1208     if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
1209         form = VAL_NONE;
1210     else
1211         form = prefformat->value;
1212     resp = (Z_PresentResponse *)odr_malloc (assoc->encode, sizeof(*resp));
1213     resp->records = 0;
1214     resp->presentStatus = odr_intdup(assoc->encode, 0);
1215     if (assoc->init->bend_present)
1216     {
1217         bend_present_rr *bprr = (bend_present_rr *)
1218             nmem_malloc (reqb->request_mem, sizeof(*bprr));
1219         bprr->setname = req->resultSetId;
1220         bprr->start = *req->resultSetStartPoint;
1221         bprr->number = *req->numberOfRecordsRequested;
1222         bprr->format = form;
1223         bprr->comp = req->recordComposition;
1224         bprr->referenceId = req->referenceId;
1225         bprr->stream = assoc->encode;
1226         bprr->print = assoc->print;
1227         bprr->request = reqb;
1228         bprr->association = assoc;
1229         bprr->errcode = 0;
1230         bprr->errstring = NULL;
1231         (*assoc->init->bend_present)(assoc->backend, bprr);
1232         
1233         if (!bprr->request)
1234             return 0;
1235         if (bprr->errcode)
1236         {
1237             resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
1238             *resp->presentStatus = Z_PRES_FAILURE;
1239         }
1240     }
1241     apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1242     next = odr_intdup(assoc->encode, 0);
1243     num = odr_intdup(assoc->encode, 0);
1244     
1245     apdu->which = Z_APDU_presentResponse;
1246     apdu->u.presentResponse = resp;
1247     resp->referenceId = req->referenceId;
1248     resp->otherInfo = 0;
1249     
1250     if (!resp->records)
1251     {
1252         *num = *req->numberOfRecordsRequested;
1253         resp->records =
1254             pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
1255                      num, req->recordComposition, next, resp->presentStatus,
1256                          form, req->referenceId, req->preferredRecordSyntax);
1257     }
1258     if (!resp->records)
1259         return 0;
1260     resp->numberOfRecordsReturned = num;
1261     resp->nextResultSetPosition = next;
1262     
1263     return apdu;
1264 }
1265
1266 /*
1267  * Scan was implemented rather in a hurry, and with support for only the basic
1268  * elements of the service in the backend API. Suggestions are welcome.
1269  */
1270 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
1271 {
1272     Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
1273     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1274     Z_ScanResponse *res = (Z_ScanResponse *)
1275         odr_malloc (assoc->encode, sizeof(*res));
1276     int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
1277     int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
1278     Z_ListEntries *ents = (Z_ListEntries *)
1279         odr_malloc (assoc->encode, sizeof(*ents));
1280     Z_DiagRecs *diagrecs_p = NULL;
1281     oident *attset;
1282     bend_scan_rr *bsrr = (bend_scan_rr *)
1283         odr_malloc (assoc->encode, sizeof(*bsrr));
1284
1285     yaz_log(LOG_LOG, "Got ScanRequest");
1286
1287     apdu->which = Z_APDU_scanResponse;
1288     apdu->u.scanResponse = res;
1289     res->referenceId = req->referenceId;
1290
1291     /* if step is absent, set it to 0 */
1292     res->stepSize = odr_intdup(assoc->encode, 0);
1293     if (req->stepSize)
1294         *res->stepSize = *req->stepSize;
1295
1296     res->scanStatus = scanStatus;
1297     res->numberOfEntriesReturned = numberOfEntriesReturned;
1298     res->positionOfTerm = 0;
1299     res->entries = ents;
1300     ents->num_entries = 0;
1301     ents->entries = NULL;
1302     ents->num_nonsurrogateDiagnostics = 0;
1303     ents->nonsurrogateDiagnostics = NULL;
1304     res->attributeSet = 0;
1305     res->otherInfo = 0;
1306
1307     if (req->databaseNames)
1308     {
1309         int i;
1310         for (i = 0; i < req->num_databaseNames; i++)
1311             yaz_log (LOG_LOG, "Database '%s'", req->databaseNames[i]);
1312     }
1313     bsrr->num_bases = req->num_databaseNames;
1314     bsrr->basenames = req->databaseNames;
1315     bsrr->num_entries = *req->numberOfTermsRequested;
1316     bsrr->term = req->termListAndStartPoint;
1317     bsrr->referenceId = req->referenceId;
1318     bsrr->stream = assoc->encode;
1319     bsrr->print = assoc->print;
1320     bsrr->step_size = res->stepSize;
1321     if (req->attributeSet &&
1322         (attset = oid_getentbyoid(req->attributeSet)) &&
1323         (attset->oclass == CLASS_ATTSET || attset->oclass == CLASS_GENERAL))
1324         bsrr->attributeset = attset->value;
1325     else
1326         bsrr->attributeset = VAL_NONE;
1327     log_scan_term (req->termListAndStartPoint, bsrr->attributeset);
1328     bsrr->term_position = req->preferredPositionInResponse ?
1329         *req->preferredPositionInResponse : 1;
1330     ((int (*)(void *, bend_scan_rr *))
1331      (*assoc->init->bend_scan))(assoc->backend, bsrr);
1332     if (bsrr->errcode)
1333         diagrecs_p = diagrecs(assoc, bsrr->errcode, bsrr->errstring);
1334     else
1335     {
1336         int i;
1337         Z_Entry **tab = (Z_Entry **)
1338             odr_malloc (assoc->encode, sizeof(*tab) * bsrr->num_entries);
1339         
1340         if (bsrr->status == BEND_SCAN_PARTIAL)
1341             *scanStatus = Z_Scan_partial_5;
1342         else
1343             *scanStatus = Z_Scan_success;
1344         ents->entries = tab;
1345         ents->num_entries = bsrr->num_entries;
1346         res->numberOfEntriesReturned = &ents->num_entries;          
1347         res->positionOfTerm = &bsrr->term_position;
1348         for (i = 0; i < bsrr->num_entries; i++)
1349         {
1350             Z_Entry *e;
1351             Z_TermInfo *t;
1352             Odr_oct *o;
1353             
1354             tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
1355             if (bsrr->entries[i].occurrences >= 0)
1356             {
1357                 e->which = Z_Entry_termInfo;
1358                 e->u.termInfo = t = (Z_TermInfo *)
1359                     odr_malloc(assoc->encode, sizeof(*t));
1360                 t->suggestedAttributes = 0;
1361                 t->displayTerm = 0;
1362                 t->alternativeTerm = 0;
1363                 t->byAttributes = 0;
1364                 t->otherTermInfo = 0;
1365                 t->globalOccurrences = &bsrr->entries[i].occurrences;
1366                 t->term = (Z_Term *)
1367                     odr_malloc(assoc->encode, sizeof(*t->term));
1368                 t->term->which = Z_Term_general;
1369                 t->term->u.general = o =
1370                     (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
1371                 o->buf = (unsigned char *)
1372                     odr_malloc(assoc->encode, o->len = o->size =
1373                                strlen(bsrr->entries[i].term));
1374                 memcpy(o->buf, bsrr->entries[i].term, o->len);
1375                 yaz_log(LOG_DEBUG, "  term #%d: '%s' (%d)", i,
1376                          bsrr->entries[i].term, bsrr->entries[i].occurrences);
1377             }
1378             else
1379             {
1380                 Z_DiagRecs *drecs = diagrecs (assoc,
1381                                               bsrr->entries[i].errcode,
1382                                               bsrr->entries[i].errstring);
1383                 assert (drecs->num_diagRecs == 1);
1384                 e->which = Z_Entry_surrogateDiagnostic;
1385                 assert (drecs->diagRecs[0]);
1386                 e->u.surrogateDiagnostic = drecs->diagRecs[0];
1387             }
1388         }
1389     }
1390     if (diagrecs_p)
1391     {
1392         ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
1393         ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
1394     }
1395     return apdu;
1396 }
1397
1398 static Z_APDU *process_sortRequest(association *assoc, request *reqb,
1399     int *fd)
1400 {
1401     Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
1402     Z_SortResponse *res = (Z_SortResponse *)
1403         odr_malloc (assoc->encode, sizeof(*res));
1404     bend_sort_rr *bsrr = (bend_sort_rr *)
1405         odr_malloc (assoc->encode, sizeof(*bsrr));
1406
1407     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1408
1409     yaz_log(LOG_LOG, "Got SortRequest.");
1410
1411     bsrr->num_input_setnames = req->num_inputResultSetNames;
1412     bsrr->input_setnames = req->inputResultSetNames;
1413     bsrr->referenceId = req->referenceId;
1414     bsrr->output_setname = req->sortedResultSetName;
1415     bsrr->sort_sequence = req->sortSequence;
1416     bsrr->stream = assoc->encode;
1417     bsrr->print = assoc->print;
1418
1419     bsrr->sort_status = Z_SortStatus_failure;
1420     bsrr->errcode = 0;
1421     bsrr->errstring = 0;
1422     
1423     (*assoc->init->bend_sort)(assoc->backend, bsrr);
1424     
1425     res->referenceId = bsrr->referenceId;
1426     res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
1427     res->resultSetStatus = 0;
1428     if (bsrr->errcode)
1429     {
1430         Z_DiagRecs *dr = diagrecs (assoc, bsrr->errcode, bsrr->errstring);
1431         res->diagnostics = dr->diagRecs;
1432         res->num_diagnostics = dr->num_diagRecs;
1433     }
1434     else
1435     {
1436         res->num_diagnostics = 0;
1437         res->diagnostics = 0;
1438     }
1439     res->otherInfo = 0;
1440
1441     apdu->which = Z_APDU_sortResponse;
1442     apdu->u.sortResponse = res;
1443     return apdu;
1444 }
1445
1446 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
1447     int *fd)
1448 {
1449     Z_DeleteResultSetRequest *req =
1450         reqb->apdu_request->u.deleteResultSetRequest;
1451     Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
1452         odr_malloc (assoc->encode, sizeof(*res));
1453     bend_delete_rr *bdrr = (bend_delete_rr *)
1454         odr_malloc (assoc->encode, sizeof(*bdrr));
1455     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1456
1457     yaz_log(LOG_LOG, "Got DeleteRequest.");
1458
1459     bdrr->num_setnames = req->num_resultSetList;
1460     bdrr->setnames = req->resultSetList;
1461     bdrr->stream = assoc->encode;
1462     bdrr->print = assoc->print;
1463     bdrr->function = *req->deleteFunction;
1464     bdrr->referenceId = req->referenceId;
1465     bdrr->statuses = 0;
1466     if (bdrr->num_setnames > 0)
1467     {
1468         int i;
1469         bdrr->statuses = (int*) 
1470             odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
1471                        bdrr->num_setnames);
1472         for (i = 0; i < bdrr->num_setnames; i++)
1473             bdrr->statuses[i] = 0;
1474     }
1475     (*assoc->init->bend_delete)(assoc->backend, bdrr);
1476     
1477     res->referenceId = req->referenceId;
1478
1479     res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
1480
1481     res->deleteListStatuses = 0;
1482     if (bdrr->num_setnames > 0)
1483     {
1484         int i;
1485         res->deleteListStatuses = (Z_ListStatuses *)
1486             odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
1487         res->deleteListStatuses->num = bdrr->num_setnames;
1488         res->deleteListStatuses->elements =
1489             (Z_ListStatus **)
1490             odr_malloc (assoc->encode, 
1491                         sizeof(*res->deleteListStatuses->elements) *
1492                         bdrr->num_setnames);
1493         for (i = 0; i<bdrr->num_setnames; i++)
1494         {
1495             res->deleteListStatuses->elements[i] =
1496                 (Z_ListStatus *)
1497                 odr_malloc (assoc->encode,
1498                             sizeof(**res->deleteListStatuses->elements));
1499             res->deleteListStatuses->elements[i]->status = bdrr->statuses+i;
1500             res->deleteListStatuses->elements[i]->id =
1501                 odr_strdup (assoc->encode, bdrr->setnames[i]);
1502             
1503         }
1504     }
1505     res->numberNotDeleted = 0;
1506     res->bulkStatuses = 0;
1507     res->deleteMessage = 0;
1508     res->otherInfo = 0;
1509
1510     apdu->which = Z_APDU_deleteResultSetResponse;
1511     apdu->u.deleteResultSetResponse = res;
1512     return apdu;
1513 }
1514
1515 static void process_close(association *assoc, request *reqb)
1516 {
1517     Z_Close *req = reqb->apdu_request->u.close;
1518     static char *reasons[] =
1519     {
1520         "finished",
1521         "shutdown",
1522         "systemProblem",
1523         "costLimit",
1524         "resources",
1525         "securityViolation",
1526         "protocolError",
1527         "lackOfActivity",
1528         "peerAbort",
1529         "unspecified"
1530     };
1531
1532     yaz_log(LOG_LOG, "Got Close, reason %s, message %s",
1533         reasons[*req->closeReason], req->diagnosticInformation ?
1534         req->diagnosticInformation : "NULL");
1535     if (assoc->version < 3) /* to make do_force respond with close */
1536         assoc->version = 3;
1537     do_close_req(assoc, Z_Close_finished,
1538                  "Association terminated by client", reqb);
1539 }
1540
1541 void save_referenceId (request *reqb, Z_ReferenceId *refid)
1542 {
1543     if (refid)
1544     {
1545         reqb->len_refid = refid->len;
1546         reqb->refid = (char *)nmem_malloc (reqb->request_mem, refid->len);
1547         memcpy (reqb->refid, refid->buf, refid->len);
1548     }
1549     else
1550     {
1551         reqb->len_refid = 0;
1552         reqb->refid = NULL;
1553     }
1554 }
1555
1556 void bend_request_send (bend_association a, bend_request req, Z_APDU *res)
1557 {
1558     process_response (a, req, res);
1559 }
1560
1561 bend_request bend_request_mk (bend_association a)
1562 {
1563     request *nreq = request_get (&a->outgoing);
1564     nreq->request_mem = nmem_create ();
1565     return nreq;
1566 }
1567
1568 Z_ReferenceId *bend_request_getid (ODR odr, bend_request req)
1569 {
1570     Z_ReferenceId *id;
1571     if (!req->refid)
1572         return 0;
1573     id = (Odr_oct *)odr_malloc (odr, sizeof(*odr));
1574     id->buf = (unsigned char *)odr_malloc (odr, req->len_refid);
1575     id->len = id->size = req->len_refid;
1576     memcpy (id->buf, req->refid, req->len_refid);
1577     return id;
1578 }
1579
1580 void bend_request_destroy (bend_request *req)
1581 {
1582     nmem_destroy((*req)->request_mem);
1583     request_release(*req);
1584     *req = NULL;
1585 }
1586
1587 int bend_backend_respond (bend_association a, bend_request req)
1588 {
1589     char *msg;
1590     int r;
1591     r = process_request (a, req, &msg);
1592     if (r < 0)
1593         yaz_log (LOG_WARN, "%s", msg);
1594     return r;
1595 }
1596
1597 void bend_request_setdata(bend_request r, void *p)
1598 {
1599     r->clientData = p;
1600 }
1601
1602 void *bend_request_getdata(bend_request r)
1603 {
1604     return r->clientData;
1605 }
1606
1607 static Z_APDU *process_segmentRequest (association *assoc, request *reqb)
1608 {
1609     bend_segment_rr req;
1610
1611     req.segment = reqb->apdu_request->u.segmentRequest;
1612     req.stream = assoc->encode;
1613     req.decode = assoc->decode;
1614     req.print = assoc->print;
1615     req.association = assoc;
1616     
1617     (*assoc->init->bend_segment)(assoc->backend, &req);
1618
1619     return 0;
1620 }
1621
1622 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd)
1623 {
1624     bend_esrequest_rr esrequest;
1625
1626     Z_ExtendedServicesRequest *req = reqb->apdu_request->u.extendedServicesRequest;
1627     Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
1628
1629     Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
1630
1631     yaz_log(LOG_DEBUG,"inside Process esRequest");
1632
1633     esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
1634     esrequest.stream = assoc->encode;
1635     esrequest.decode = assoc->decode;
1636     esrequest.print = assoc->print;
1637     esrequest.errcode = 0;
1638     esrequest.errstring = NULL;
1639     esrequest.request = reqb;
1640     esrequest.association = assoc;
1641     esrequest.taskPackage = 0;
1642     esrequest.referenceId = req->referenceId;
1643     
1644     (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
1645     
1646     /* If the response is being delayed, return NULL */
1647     if (esrequest.request == NULL)
1648         return(NULL);
1649
1650     resp->referenceId = req->referenceId;
1651
1652     if (esrequest.errcode == -1)
1653     {
1654         /* Backend service indicates request will be processed */
1655         yaz_log(LOG_DEBUG,"Request could be processed...Accepted !");
1656         *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
1657     }
1658     else if (esrequest.errcode == 0)
1659     {
1660         /* Backend service indicates request will be processed */
1661         yaz_log(LOG_DEBUG,"Request could be processed...Done !");
1662         *resp->operationStatus = Z_ExtendedServicesResponse_done;
1663     }
1664     else
1665     {
1666         Z_DiagRecs *diagRecs = diagrecs (assoc, esrequest.errcode,
1667                                          esrequest.errstring);
1668
1669         /* Backend indicates error, request will not be processed */
1670         yaz_log(LOG_DEBUG,"Request could not be processed...failure !");
1671         *resp->operationStatus = Z_ExtendedServicesResponse_failure;
1672         resp->num_diagnostics = diagRecs->num_diagRecs;
1673         resp->diagnostics = diagRecs->diagRecs;
1674     }
1675     /* Do something with the members of bend_extendedservice */
1676     if (esrequest.taskPackage)
1677         resp->taskPackage = z_ext_record (assoc->encode, VAL_EXTENDED,
1678                                          (const char *)  esrequest.taskPackage,
1679                                           -1);
1680     yaz_log(LOG_DEBUG,"Send the result apdu");
1681     return apdu;
1682 }