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