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