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