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