b19cc62539e10d5d1505617a29e52caaa6b21d02
[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.136 2003-02-17 14:35:42 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         exit (0);
185 }
186
187 static void do_close_req(association *a, int reason, char *message,
188                          request *req)
189 {
190     Z_APDU apdu;
191     Z_Close *cls = zget_Close(a->encode);
192     
193     /* Purge request queue */
194     while (request_deq(&a->incoming));
195     while (request_deq(&a->outgoing));
196     if (a->version >= 3)
197     {
198         yaz_log(LOG_LOG, "Sending Close PDU, reason=%d, message=%s",
199             reason, message ? message : "none");
200         apdu.which = Z_APDU_close;
201         apdu.u.close = cls;
202         *cls->closeReason = reason;
203         cls->diagnosticInformation = message;
204         process_z_response(a, req, &apdu);
205         iochan_settimeout(a->client_chan, 60);
206     }
207     else
208     {
209         yaz_log(LOG_DEBUG, "v2 client. No Close PDU");
210         iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
211     }
212     a->state = ASSOC_DEAD;
213 }
214
215 static void do_close(association *a, int reason, char *message)
216 {
217     do_close_req (a, reason, message, request_get(&a->outgoing));
218 }
219
220 /*
221  * This is where PDUs from the client are read and the further
222  * processing is initiated. Flow of control moves down through the
223  * various process_* functions below, until the encoded result comes back up
224  * to the output handler in here.
225  * 
226  *  h     : the I/O channel that has an outstanding event.
227  *  event : the current outstanding event.
228  */
229 void ir_session(IOCHAN h, int event)
230 {
231     int res;
232     association *assoc = (association *)iochan_getdata(h);
233     COMSTACK conn = assoc->client_link;
234     request *req;
235
236     assert(h && conn && assoc);
237     if (event == EVENT_TIMEOUT)
238     {
239         if (assoc->state != ASSOC_UP)
240         {
241             yaz_log(LOG_LOG, "Final timeout - closing connection.");
242             cs_close(conn);
243             destroy_association(assoc);
244             iochan_destroy(h);
245         }
246         else
247         {
248             yaz_log(LOG_LOG, "Session idle too long. Sending close.");
249             do_close(assoc, Z_Close_lackOfActivity, 0);
250         }
251         return;
252     }
253     if (event & assoc->cs_accept_mask)
254     {
255         yaz_log (LOG_DEBUG, "ir_session (accept)");
256         if (!cs_accept (conn))
257         {
258             yaz_log (LOG_LOG, "accept failed");
259             destroy_association(assoc);
260             iochan_destroy(h);
261         }
262         iochan_clearflag (h, EVENT_OUTPUT|EVENT_OUTPUT);
263         if (conn->io_pending) 
264         {   /* cs_accept didn't complete */
265             assoc->cs_accept_mask = 
266                 ((conn->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
267                 ((conn->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
268
269             iochan_setflag (h, assoc->cs_accept_mask);
270         }
271         else
272         {   /* cs_accept completed. Prepare for reading (cs_get) */
273             assoc->cs_accept_mask = 0;
274             assoc->cs_get_mask = EVENT_INPUT;
275             iochan_setflag (h, assoc->cs_get_mask);
276         }
277         return;
278     }
279     if ((event & assoc->cs_get_mask) || (event & EVENT_WORK)) /* input */
280     {
281         if ((assoc->cs_put_mask & EVENT_INPUT) == 0 && (event & assoc->cs_get_mask))
282         {
283             yaz_log(LOG_DEBUG, "ir_session (input)");
284             /* We aren't speaking to this fellow */
285             if (assoc->state == ASSOC_DEAD)
286             {
287                 yaz_log(LOG_LOG, "Closed connection after reject");
288                 cs_close(conn);
289                 destroy_association(assoc);
290                 iochan_destroy(h);
291                 return;
292             }
293             assoc->cs_get_mask = EVENT_INPUT;
294             if ((res = cs_get(conn, &assoc->input_buffer,
295                 &assoc->input_buffer_len)) <= 0)
296             {
297                 yaz_log(LOG_LOG, "Connection closed by client");
298                 cs_close(conn);
299                 destroy_association(assoc);
300                 iochan_destroy(h);
301                 return;
302             }
303             else if (res == 1) /* incomplete read - wait for more  */
304             {
305                 if (conn->io_pending & CS_WANT_WRITE)
306                     assoc->cs_get_mask |= EVENT_OUTPUT;
307                 iochan_setflag(h, assoc->cs_get_mask);
308                 return;
309             }
310             if (cs_more(conn)) /* more stuff - call us again later, please */
311                 iochan_setevent(h, EVENT_INPUT);
312                 
313             /* we got a complete PDU. Let's decode it */
314             yaz_log(LOG_DEBUG, "Got PDU, %d bytes: lead=%02X %02X %02X", res,
315                             assoc->input_buffer[0] & 0xff,
316                             assoc->input_buffer[1] & 0xff,
317                             assoc->input_buffer[2] & 0xff);
318             req = request_get(&assoc->incoming); /* get a new request structure */
319             odr_reset(assoc->decode);
320             odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
321             if (!z_GDU(assoc->decode, &req->gdu_request, 0, 0))
322             {
323                 yaz_log(LOG_LOG, "ODR error on incoming PDU: %s [near byte %d] ",
324                         odr_errmsg(odr_geterror(assoc->decode)),
325                         odr_offset(assoc->decode));
326                 if (assoc->decode->error != OHTTP)
327                 {
328                     yaz_log(LOG_LOG, "PDU dump:");
329                     odr_dumpBER(yaz_log_file(), assoc->input_buffer, res);
330                     do_close(assoc, Z_Close_protocolError, "Malformed package");
331                 }
332                 else
333                 {
334                     Z_GDU *p = z_get_HTTP_Response(assoc->encode, 400);
335                     assoc->state = ASSOC_DEAD;
336                     process_gdu_response(assoc, req, p);
337                 }
338                 return;
339             }
340             req->request_mem = odr_extract_mem(assoc->decode);
341             if (assoc->print && !z_GDU(assoc->print, &req->gdu_request, 0, 0))
342             {
343                 yaz_log(LOG_WARN, "ODR print error: %s", 
344                     odr_errmsg(odr_geterror(assoc->print)));
345                 odr_reset(assoc->print);
346             }
347             request_enq(&assoc->incoming, req);
348         }
349
350         /* can we do something yet? */
351         req = request_head(&assoc->incoming);
352         if (req->state == REQUEST_IDLE)
353         {
354             request_deq(&assoc->incoming);
355             process_gdu_request(assoc, req);
356         }
357     }
358     if (event & assoc->cs_put_mask)
359     {
360         request *req = request_head(&assoc->outgoing);
361
362         assoc->cs_put_mask = 0;
363         yaz_log(LOG_DEBUG, "ir_session (output)");
364         req->state = REQUEST_PENDING;
365         switch (res = cs_put(conn, req->response, req->len_response))
366         {
367         case -1:
368             yaz_log(LOG_LOG, "Connection closed by client");
369             cs_close(conn);
370             destroy_association(assoc);
371             iochan_destroy(h);
372             break;
373         case 0: /* all sent - release the request structure */
374             yaz_log(LOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
375 #if 0
376             yaz_log(LOG_DEBUG, "HTTP out:\n%.*s", req->len_response,
377                     req->response);
378 #endif
379             nmem_destroy(req->request_mem);
380             request_deq(&assoc->outgoing);
381             request_release(req);
382             if (!request_head(&assoc->outgoing))
383             {   /* restore mask for cs_get operation ... */
384                 iochan_clearflag(h, EVENT_OUTPUT|EVENT_INPUT);
385                 iochan_setflag(h, assoc->cs_get_mask);
386                 yaz_log(LOG_LOG, "queue empty mask=%d", assoc->cs_get_mask);
387                 if (assoc->state == ASSOC_DEAD)
388                     iochan_setevent(assoc->client_chan, EVENT_TIMEOUT);
389             }
390             else
391             {
392                 assoc->cs_put_mask = EVENT_OUTPUT;
393                 yaz_log(LOG_LOG, "queue not empty");
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_Specification_uri;
482     rr.comp->u.complex->generic->u.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         z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
801     }
802     process_gdu_response(assoc, req, p);
803 }
804
805 static void process_gdu_request(association *assoc, request *req)
806 {
807     if (req->gdu_request->which == Z_GDU_Z3950)
808     {
809         char *msg = 0;
810         req->apdu_request = req->gdu_request->u.z3950;
811         if (process_z_request(assoc, req, &msg) < 0)
812             do_close_req(assoc, Z_Close_systemProblem, msg, req);
813     }
814     else if (req->gdu_request->which == Z_GDU_HTTP_Request)
815         process_http_request(assoc, req);
816     else
817     {
818         do_close_req(assoc, Z_Close_systemProblem, "bad protocol packet", req);
819     }
820 }
821
822 /*
823  * Initiate request processing.
824  */
825 static int process_z_request(association *assoc, request *req, char **msg)
826 {
827     int fd = -1;
828     Z_APDU *res;
829     int retval;
830     
831     *msg = "Unknown Error";
832     assert(req && req->state == REQUEST_IDLE);
833     if (req->apdu_request->which != Z_APDU_initRequest && !assoc->init)
834     {
835         *msg = "Missing InitRequest";
836         return -1;
837     }
838     switch (req->apdu_request->which)
839     {
840     case Z_APDU_initRequest:
841         res = process_initRequest(assoc, req); break;
842     case Z_APDU_searchRequest:
843         res = process_searchRequest(assoc, req, &fd); break;
844     case Z_APDU_presentRequest:
845         res = process_presentRequest(assoc, req, &fd); break;
846     case Z_APDU_scanRequest:
847         if (assoc->init->bend_scan)
848             res = process_scanRequest(assoc, req, &fd);
849         else
850         {
851             *msg = "Cannot handle Scan APDU";
852             return -1;
853         }
854         break;
855     case Z_APDU_extendedServicesRequest:
856         if (assoc->init->bend_esrequest)
857             res = process_ESRequest(assoc, req, &fd);
858         else
859         {
860             *msg = "Cannot handle Extended Services APDU";
861             return -1;
862         }
863         break;
864     case Z_APDU_sortRequest:
865         if (assoc->init->bend_sort)
866             res = process_sortRequest(assoc, req, &fd);
867         else
868         {
869             *msg = "Cannot handle Sort APDU";
870             return -1;
871         }
872         break;
873     case Z_APDU_close:
874         process_close(assoc, req);
875         return 0;
876     case Z_APDU_deleteResultSetRequest:
877         if (assoc->init->bend_delete)
878             res = process_deleteRequest(assoc, req, &fd);
879         else
880         {
881             *msg = "Cannot handle Delete APDU";
882             return -1;
883         }
884         break;
885     case Z_APDU_segmentRequest:
886         if (assoc->init->bend_segment)
887         {
888             res = process_segmentRequest (assoc, req);
889         }
890         else
891         {
892             *msg = "Cannot handle Segment APDU";
893             return -1;
894         }
895         break;
896     default:
897         *msg = "Bad APDU received";
898         return -1;
899     }
900     if (res)
901     {
902         yaz_log(LOG_DEBUG, "  result immediately available");
903         retval = process_z_response(assoc, req, res);
904     }
905     else if (fd < 0)
906     {
907         yaz_log(LOG_DEBUG, "  result unavailble");
908         retval = 0;
909     }
910     else /* no result yet - one will be provided later */
911     {
912         IOCHAN chan;
913
914         /* Set up an I/O handler for the fd supplied by the backend */
915
916         yaz_log(LOG_DEBUG, "   establishing handler for result");
917         req->state = REQUEST_PENDING;
918         if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT)))
919             abort();
920         iochan_setdata(chan, assoc);
921         retval = 0;
922     }
923     return retval;
924 }
925
926 /*
927  * Handle message from the backend.
928  */
929 void backend_response(IOCHAN i, int event)
930 {
931     association *assoc = (association *)iochan_getdata(i);
932     request *req = request_head(&assoc->incoming);
933     Z_APDU *res;
934     int fd;
935
936     yaz_log(LOG_DEBUG, "backend_response");
937     assert(assoc && req && req->state != REQUEST_IDLE);
938     /* determine what it is we're waiting for */
939     switch (req->apdu_request->which)
940     {
941         case Z_APDU_searchRequest:
942             res = response_searchRequest(assoc, req, 0, &fd); break;
943 #if 0
944         case Z_APDU_presentRequest:
945             res = response_presentRequest(assoc, req, 0, &fd); break;
946         case Z_APDU_scanRequest:
947             res = response_scanRequest(assoc, req, 0, &fd); break;
948 #endif
949         default:
950             yaz_log(LOG_WARN, "Serious programmer's lapse or bug");
951             abort();
952     }
953     if ((res && process_z_response(assoc, req, res) < 0) || fd < 0)
954     {
955         yaz_log(LOG_LOG, "Fatal error when talking to backend");
956         do_close(assoc, Z_Close_systemProblem, 0);
957         iochan_destroy(i);
958         return;
959     }
960     else if (!res) /* no result yet - try again later */
961     {
962         yaz_log(LOG_DEBUG, "   no result yet");
963         iochan_setfd(i, fd); /* in case fd has changed */
964     }
965 }
966
967 /*
968  * Encode response, and transfer the request structure to the outgoing queue.
969  */
970 static int process_gdu_response(association *assoc, request *req, Z_GDU *res)
971 {
972     odr_setbuf(assoc->encode, req->response, req->size_response, 1);
973
974     if (assoc->print && !z_GDU(assoc->print, &res, 0, 0))
975     {
976         yaz_log(LOG_WARN, "ODR print error: %s", 
977             odr_errmsg(odr_geterror(assoc->print)));
978         odr_reset(assoc->print);
979     }
980     if (!z_GDU(assoc->encode, &res, 0, 0))
981     {
982         yaz_log(LOG_WARN, "ODR error when encoding response: %s",
983             odr_errmsg(odr_geterror(assoc->decode)));
984         return -1;
985     }
986     req->response = odr_getbuf(assoc->encode, &req->len_response,
987         &req->size_response);
988     odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
989     odr_reset(assoc->encode);
990     req->state = REQUEST_IDLE;
991     request_enq(&assoc->outgoing, req);
992     /* turn the work over to the ir_session handler */
993     iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
994     assoc->cs_put_mask = EVENT_OUTPUT;
995     /* Is there more work to be done? give that to the input handler too */
996 #if 1
997     if (request_head(&assoc->incoming))
998     {
999         yaz_log (LOG_DEBUG, "more work to be done");
1000         iochan_setevent(assoc->client_chan, EVENT_WORK);
1001     }
1002 #endif
1003     return 0;
1004 }
1005
1006 /*
1007  * Encode response, and transfer the request structure to the outgoing queue.
1008  */
1009 static int process_z_response(association *assoc, request *req, Z_APDU *res)
1010 {
1011     odr_setbuf(assoc->encode, req->response, req->size_response, 1);
1012
1013     if (assoc->print && !z_APDU(assoc->print, &res, 0, 0))
1014     {
1015         yaz_log(LOG_WARN, "ODR print error: %s", 
1016             odr_errmsg(odr_geterror(assoc->print)));
1017         odr_reset(assoc->print);
1018     }
1019     if (!z_APDU(assoc->encode, &res, 0, 0))
1020     {
1021         yaz_log(LOG_WARN, "ODR error when encoding response: %s",
1022             odr_errmsg(odr_geterror(assoc->decode)));
1023         return -1;
1024     }
1025     req->response = odr_getbuf(assoc->encode, &req->len_response,
1026         &req->size_response);
1027     odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
1028     odr_reset(assoc->encode);
1029     req->state = REQUEST_IDLE;
1030     request_enq(&assoc->outgoing, req);
1031     /* turn the work over to the ir_session handler */
1032     iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
1033     assoc->cs_put_mask = EVENT_OUTPUT;
1034     /* Is there more work to be done? give that to the input handler too */
1035 #if 1
1036     if (request_head(&assoc->incoming))
1037     {
1038         yaz_log (LOG_DEBUG, "more work to be done");
1039         iochan_setevent(assoc->client_chan, EVENT_WORK);
1040     }
1041 #endif
1042     return 0;
1043 }
1044
1045 /*
1046  * Handle init request.
1047  * At the moment, we don't check the options
1048  * anywhere else in the code - we just try not to do anything that would
1049  * break a naive client. We'll toss 'em into the association block when
1050  * we need them there.
1051  */
1052 static Z_APDU *process_initRequest(association *assoc, request *reqb)
1053 {
1054     statserv_options_block *cb = statserv_getcontrol();
1055     Z_InitRequest *req = reqb->apdu_request->u.initRequest;
1056     Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
1057     Z_InitResponse *resp = apdu->u.initResponse;
1058     bend_initresult *binitres;
1059
1060     char options[140];
1061
1062     xfree (assoc->init);
1063     assoc->init = (bend_initrequest *) xmalloc (sizeof(*assoc->init));
1064
1065     yaz_log(LOG_LOG, "Got initRequest");
1066     if (req->implementationId)
1067         yaz_log(LOG_LOG, "Id:        %s", req->implementationId);
1068     if (req->implementationName)
1069         yaz_log(LOG_LOG, "Name:      %s", req->implementationName);
1070     if (req->implementationVersion)
1071         yaz_log(LOG_LOG, "Version:   %s", req->implementationVersion);
1072
1073     assoc->init->stream = assoc->encode;
1074     assoc->init->print = assoc->print;
1075     assoc->init->auth = req->idAuthentication;
1076     assoc->init->referenceId = req->referenceId;
1077     assoc->init->implementation_version = 0;
1078     assoc->init->implementation_id = 0;
1079     assoc->init->implementation_name = 0;
1080     assoc->init->bend_sort = NULL;
1081     assoc->init->bend_search = NULL;
1082     assoc->init->bend_present = NULL;
1083     assoc->init->bend_esrequest = NULL;
1084     assoc->init->bend_delete = NULL;
1085     assoc->init->bend_scan = NULL;
1086     assoc->init->bend_segment = NULL;
1087     assoc->init->bend_fetch = NULL;
1088     assoc->init->charneg_request = NULL;
1089     assoc->init->charneg_response = NULL;
1090     assoc->init->decode = assoc->decode;
1091
1092     if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
1093     {
1094         Z_CharSetandLanguageNegotiation *negotiation =
1095             yaz_get_charneg_record (req->otherInfo);
1096         if (negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
1097             assoc->init->charneg_request = negotiation;
1098     }
1099     
1100     assoc->init->peer_name =
1101         odr_strdup (assoc->encode, cs_addrstr(assoc->client_link));
1102     if (!(binitres = (*cb->bend_init)(assoc->init)))
1103     {
1104         yaz_log(LOG_WARN, "Bad response from backend.");
1105         return 0;
1106     }
1107
1108     assoc->backend = binitres->handle;
1109     if ((assoc->init->bend_sort))
1110         yaz_log (LOG_DEBUG, "Sort handler installed");
1111     if ((assoc->init->bend_search))
1112         yaz_log (LOG_DEBUG, "Search handler installed");
1113     if ((assoc->init->bend_present))
1114         yaz_log (LOG_DEBUG, "Present handler installed");   
1115     if ((assoc->init->bend_esrequest))
1116         yaz_log (LOG_DEBUG, "ESRequest handler installed");   
1117     if ((assoc->init->bend_delete))
1118         yaz_log (LOG_DEBUG, "Delete handler installed");   
1119     if ((assoc->init->bend_scan))
1120         yaz_log (LOG_DEBUG, "Scan handler installed");   
1121     if ((assoc->init->bend_segment))
1122         yaz_log (LOG_DEBUG, "Segment handler installed");   
1123     
1124     resp->referenceId = req->referenceId;
1125     *options = '\0';
1126     /* let's tell the client what we can do */
1127     if (ODR_MASK_GET(req->options, Z_Options_search))
1128     {
1129         ODR_MASK_SET(resp->options, Z_Options_search);
1130         strcat(options, "srch");
1131     }
1132     if (ODR_MASK_GET(req->options, Z_Options_present))
1133     {
1134         ODR_MASK_SET(resp->options, Z_Options_present);
1135         strcat(options, " prst");
1136     }
1137     if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
1138         assoc->init->bend_delete)
1139     {
1140         ODR_MASK_SET(resp->options, Z_Options_delSet);
1141         strcat(options, " del");
1142     }
1143     if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
1144         assoc->init->bend_esrequest)
1145     {
1146         ODR_MASK_SET(resp->options, Z_Options_extendedServices);
1147         strcat (options, " extendedServices");
1148     }
1149     if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
1150     {
1151         ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
1152         strcat(options, " namedresults");
1153     }
1154     if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
1155     {
1156         ODR_MASK_SET(resp->options, Z_Options_scan);
1157         strcat(options, " scan");
1158     }
1159     if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
1160     {
1161         ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
1162         strcat(options, " concurrop");
1163     }
1164     if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
1165     {
1166         ODR_MASK_SET(resp->options, Z_Options_sort);
1167         strcat(options, " sort");
1168     }
1169
1170     if (ODR_MASK_GET(req->options, Z_Options_negotiationModel)
1171         && assoc->init->charneg_response)
1172     {
1173         Z_OtherInformation **p;
1174         Z_OtherInformationUnit *p0;
1175         
1176         yaz_oi_APDU(apdu, &p);
1177         
1178         if ((p0=yaz_oi_update(p, assoc->encode, NULL, 0, 0))) {
1179             ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
1180             
1181             p0->which = Z_OtherInfo_externallyDefinedInfo;
1182             p0->information.externallyDefinedInfo =
1183                 assoc->init->charneg_response;
1184         }
1185         ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
1186         strcat(options, " negotiation");
1187     }
1188
1189     if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
1190     {
1191         ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
1192         assoc->version = 2; /* 1 & 2 are equivalent */
1193     }
1194     if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
1195     {
1196         ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
1197         assoc->version = 2;
1198     }
1199     if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
1200     {
1201         ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
1202         assoc->version = 3;
1203     }
1204
1205     yaz_log(LOG_LOG, "Negotiated to v%d: %s", assoc->version, options);
1206     assoc->maximumRecordSize = *req->maximumRecordSize;
1207     if (assoc->maximumRecordSize > control_block->maxrecordsize)
1208         assoc->maximumRecordSize = control_block->maxrecordsize;
1209     assoc->preferredMessageSize = *req->preferredMessageSize;
1210     if (assoc->preferredMessageSize > assoc->maximumRecordSize)
1211         assoc->preferredMessageSize = assoc->maximumRecordSize;
1212
1213 #if 0
1214     assoc->maximumRecordSize = 3000000;
1215     assoc->preferredMessageSize = 3000000;
1216 #endif
1217
1218     resp->preferredMessageSize = &assoc->preferredMessageSize;
1219     resp->maximumRecordSize = &assoc->maximumRecordSize;
1220
1221     resp->implementationName = "GFS/YAZ";
1222
1223     if (assoc->init->implementation_id)
1224     {
1225         char *nv = (char *)
1226             odr_malloc (assoc->encode,
1227                         strlen(assoc->init->implementation_id) + 10 + 
1228                                strlen(resp->implementationId));
1229         sprintf (nv, "%s / %s",
1230                  resp->implementationId, assoc->init->implementation_id);
1231         resp->implementationId = nv;
1232     }
1233     if (assoc->init->implementation_name)
1234     {
1235         char *nv = (char *)
1236             odr_malloc (assoc->encode,
1237                         strlen(assoc->init->implementation_name) + 10 + 
1238                                strlen(resp->implementationName));
1239         sprintf (nv, "%s / %s",
1240                  resp->implementationName, assoc->init->implementation_name);
1241         resp->implementationName = nv;
1242     }
1243     if (assoc->init->implementation_version)
1244     {
1245         char *nv = (char *)
1246             odr_malloc (assoc->encode,
1247                         strlen(assoc->init->implementation_version) + 10 + 
1248                                strlen(resp->implementationVersion));
1249         sprintf (nv, "YAZ %s / %s",
1250                  resp->implementationVersion,
1251                  assoc->init->implementation_version);
1252         resp->implementationVersion = nv;
1253     }
1254
1255     if (binitres->errcode)
1256     {
1257         yaz_log(LOG_LOG, "Connection rejected by backend.");
1258         *resp->result = 0;
1259         assoc->state = ASSOC_DEAD;
1260     }
1261     else
1262         assoc->state = ASSOC_UP;
1263     return apdu;
1264 }
1265
1266 /*
1267  * These functions should be merged.
1268  */
1269
1270 static void set_addinfo (Z_DefaultDiagFormat *dr, char *addinfo, ODR odr)
1271 {
1272     dr->which = Z_DefaultDiagFormat_v2Addinfo;
1273     dr->u.v2Addinfo = odr_strdup (odr, addinfo ? addinfo : "");
1274 }
1275
1276 /*
1277  * nonsurrogate diagnostic record.
1278  */
1279 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
1280 {
1281     Z_Records *rec = (Z_Records *)
1282         odr_malloc (assoc->encode, sizeof(*rec));
1283     int *err = odr_intdup(assoc->encode, error);
1284     Z_DiagRec *drec = (Z_DiagRec *)
1285         odr_malloc (assoc->encode, sizeof(*drec));
1286     Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
1287         odr_malloc (assoc->encode, sizeof(*dr));
1288
1289     yaz_log(LOG_LOG, "[%d] %s %s%s", error, diagbib1_str(error),
1290         addinfo ? " -- " : "", addinfo ? addinfo : "");
1291     rec->which = Z_Records_NSD;
1292     rec->u.nonSurrogateDiagnostic = dr;
1293     dr->diagnosticSetId =
1294         yaz_oidval_to_z3950oid (assoc->encode, CLASS_DIAGSET, VAL_BIB1);
1295     dr->condition = err;
1296     set_addinfo (dr, addinfo, assoc->encode);
1297     return rec;
1298 }
1299
1300 /*
1301  * surrogate diagnostic.
1302  */
1303 static Z_NamePlusRecord *surrogatediagrec(association *assoc, char *dbname,
1304                                           int error, char *addinfo)
1305 {
1306     Z_NamePlusRecord *rec = (Z_NamePlusRecord *)
1307         odr_malloc (assoc->encode, sizeof(*rec));
1308     int *err = odr_intdup(assoc->encode, error);
1309     Z_DiagRec *drec = (Z_DiagRec *)odr_malloc (assoc->encode, sizeof(*drec));
1310     Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
1311         odr_malloc (assoc->encode, sizeof(*dr));
1312     
1313     yaz_log(LOG_DEBUG, "SurrogateDiagnotic: %d -- %s", error, addinfo);
1314     rec->databaseName = dbname;
1315     rec->which = Z_NamePlusRecord_surrogateDiagnostic;
1316     rec->u.surrogateDiagnostic = drec;
1317     drec->which = Z_DiagRec_defaultFormat;
1318     drec->u.defaultFormat = dr;
1319     dr->diagnosticSetId =
1320         yaz_oidval_to_z3950oid (assoc->encode, CLASS_DIAGSET, VAL_BIB1);
1321     dr->condition = err;
1322     set_addinfo (dr, addinfo, assoc->encode);
1323
1324     return rec;
1325 }
1326
1327 /*
1328  * multiple nonsurrogate diagnostics.
1329  */
1330 static Z_DiagRecs *diagrecs(association *assoc, int error, char *addinfo)
1331 {
1332     Z_DiagRecs *recs = (Z_DiagRecs *)odr_malloc (assoc->encode, sizeof(*recs));
1333     int *err = odr_intdup(assoc->encode, error);
1334     Z_DiagRec **recp = (Z_DiagRec **)odr_malloc (assoc->encode, sizeof(*recp));
1335     Z_DiagRec *drec = (Z_DiagRec *)odr_malloc (assoc->encode, sizeof(*drec));
1336     Z_DefaultDiagFormat *rec = (Z_DefaultDiagFormat *)
1337         odr_malloc (assoc->encode, sizeof(*rec));
1338
1339     yaz_log(LOG_DEBUG, "DiagRecs: %d -- %s", error, addinfo ? addinfo : "");
1340
1341     recs->num_diagRecs = 1;
1342     recs->diagRecs = recp;
1343     recp[0] = drec;
1344     drec->which = Z_DiagRec_defaultFormat;
1345     drec->u.defaultFormat = rec;
1346
1347     rec->diagnosticSetId =
1348         yaz_oidval_to_z3950oid (assoc->encode, CLASS_DIAGSET, VAL_BIB1);
1349     rec->condition = err;
1350
1351     rec->which = Z_DefaultDiagFormat_v2Addinfo;
1352     rec->u.v2Addinfo = odr_strdup (assoc->encode, addinfo ? addinfo : "");
1353     return recs;
1354 }
1355
1356 static Z_Records *pack_records(association *a, char *setname, int start,
1357                                int *num, Z_RecordComposition *comp,
1358                                int *next, int *pres, oid_value format,
1359                                Z_ReferenceId *referenceId,
1360                                int *oid)
1361 {
1362     int recno, total_length = 0, toget = *num, dumped_records = 0;
1363     Z_Records *records =
1364         (Z_Records *) odr_malloc (a->encode, sizeof(*records));
1365     Z_NamePlusRecordList *reclist =
1366         (Z_NamePlusRecordList *) odr_malloc (a->encode, sizeof(*reclist));
1367     Z_NamePlusRecord **list =
1368         (Z_NamePlusRecord **) odr_malloc (a->encode, sizeof(*list) * toget);
1369
1370     records->which = Z_Records_DBOSD;
1371     records->u.databaseOrSurDiagnostics = reclist;
1372     reclist->num_records = 0;
1373     reclist->records = list;
1374     *pres = Z_PRES_SUCCESS;
1375     *num = 0;
1376     *next = 0;
1377
1378     yaz_log(LOG_LOG, "Request to pack %d+%d+%s", start, toget, setname);
1379     yaz_log(LOG_DEBUG, "pms=%d, mrs=%d", a->preferredMessageSize,
1380         a->maximumRecordSize);
1381     for (recno = start; reclist->num_records < toget; recno++)
1382     {
1383         bend_fetch_rr freq;
1384         Z_NamePlusRecord *thisrec;
1385         int this_length = 0;
1386         /*
1387          * we get the number of bytes allocated on the stream before any
1388          * allocation done by the backend - this should give us a reasonable
1389          * idea of the total size of the data so far.
1390          */
1391         total_length = odr_total(a->encode) - dumped_records;
1392         freq.errcode = 0;
1393         freq.errstring = 0;
1394         freq.basename = 0;
1395         freq.len = 0;
1396         freq.record = 0;
1397         freq.last_in_set = 0;
1398         freq.setname = setname;
1399         freq.surrogate_flag = 0;
1400         freq.number = recno;
1401         freq.comp = comp;
1402         freq.request_format = format;
1403         freq.request_format_raw = oid;
1404         freq.output_format = format;
1405         freq.output_format_raw = 0;
1406         freq.stream = a->encode;
1407         freq.print = a->print;
1408         freq.surrogate_flag = 0;
1409         freq.referenceId = referenceId;
1410         (*a->init->bend_fetch)(a->backend, &freq);
1411         /* backend should be able to signal whether error is system-wide
1412            or only pertaining to current record */
1413         if (freq.errcode)
1414         {
1415             if (!freq.surrogate_flag)
1416             {
1417                 char s[20];
1418                 *pres = Z_PRES_FAILURE;
1419                 /* for 'present request out of range',
1420                    set addinfo to record position if not set */
1421                 if (freq.errcode == 13 && freq.errstring == 0)
1422                 {
1423                     sprintf (s, "%d", recno);
1424                     freq.errstring = s;
1425                 }
1426                 return diagrec(a, freq.errcode, freq.errstring);
1427             }
1428             reclist->records[reclist->num_records] =
1429                 surrogatediagrec(a, freq.basename, freq.errcode,
1430                                  freq.errstring);
1431             reclist->num_records++;
1432             *next = freq.last_in_set ? 0 : recno + 1;
1433             continue;
1434         }
1435         if (freq.len >= 0)
1436             this_length = freq.len;
1437         else
1438             this_length = odr_total(a->encode) - total_length;
1439         yaz_log(LOG_DEBUG, "  fetched record, len=%d, total=%d",
1440             this_length, total_length);
1441         if (this_length + total_length > a->preferredMessageSize)
1442         {
1443             /* record is small enough, really */
1444             if (this_length <= a->preferredMessageSize)
1445             {
1446                 yaz_log(LOG_DEBUG, "  Dropped last normal-sized record");
1447                 *pres = Z_PRES_PARTIAL_2;
1448                 break;
1449             }
1450             /* record can only be fetched by itself */
1451             if (this_length < a->maximumRecordSize)
1452             {
1453                 yaz_log(LOG_DEBUG, "  Record > prefmsgsz");
1454                 if (toget > 1)
1455                 {
1456                     yaz_log(LOG_DEBUG, "  Dropped it");
1457                     reclist->records[reclist->num_records] =
1458                          surrogatediagrec(a, freq.basename, 16, 0);
1459                     reclist->num_records++;
1460                     *next = freq.last_in_set ? 0 : recno + 1;
1461                     dumped_records += this_length;
1462                     continue;
1463                 }
1464             }
1465             else /* too big entirely */
1466             {
1467                 yaz_log(LOG_LOG, "Record > maxrcdsz this=%d max=%d", this_length, a->maximumRecordSize);
1468                 reclist->records[reclist->num_records] =
1469                     surrogatediagrec(a, freq.basename, 17, 0);
1470                 reclist->num_records++;
1471                 *next = freq.last_in_set ? 0 : recno + 1;
1472                 dumped_records += this_length;
1473                 continue;
1474             }
1475         }
1476
1477         if (!(thisrec = (Z_NamePlusRecord *)
1478               odr_malloc(a->encode, sizeof(*thisrec))))
1479             return 0;
1480         if (!(thisrec->databaseName = (char *)odr_malloc(a->encode,
1481             strlen(freq.basename) + 1)))
1482             return 0;
1483         strcpy(thisrec->databaseName, freq.basename);
1484         thisrec->which = Z_NamePlusRecord_databaseRecord;
1485
1486         if (freq.output_format_raw)
1487         {
1488             struct oident *ident = oid_getentbyoid(freq.output_format_raw);
1489             freq.output_format = ident->value;
1490         }
1491         thisrec->u.databaseRecord = z_ext_record(a->encode, freq.output_format,
1492                                                  freq.record, freq.len);
1493         if (!thisrec->u.databaseRecord)
1494             return 0;
1495         reclist->records[reclist->num_records] = thisrec;
1496         reclist->num_records++;
1497         *next = freq.last_in_set ? 0 : recno + 1;
1498     }
1499     *num = reclist->num_records;
1500     return records;
1501 }
1502
1503 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
1504     int *fd)
1505 {
1506     Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
1507     bend_search_rr *bsrr = 
1508         (bend_search_rr *)nmem_malloc (reqb->request_mem, sizeof(*bsrr));
1509     
1510     yaz_log(LOG_LOG, "Got SearchRequest.");
1511     bsrr->fd = fd;
1512     bsrr->request = reqb;
1513     bsrr->association = assoc;
1514     bsrr->referenceId = req->referenceId;
1515     save_referenceId (reqb, bsrr->referenceId);
1516
1517     yaz_log (LOG_LOG, "ResultSet '%s'", req->resultSetName);
1518     if (req->databaseNames)
1519     {
1520         int i;
1521         for (i = 0; i < req->num_databaseNames; i++)
1522             yaz_log (LOG_LOG, "Database '%s'", req->databaseNames[i]);
1523     }
1524     yaz_log_zquery(req->query);
1525
1526     if (assoc->init->bend_search)
1527     {
1528         bsrr->setname = req->resultSetName;
1529         bsrr->replace_set = *req->replaceIndicator;
1530         bsrr->num_bases = req->num_databaseNames;
1531         bsrr->basenames = req->databaseNames;
1532         bsrr->query = req->query;
1533         bsrr->stream = assoc->encode;
1534         bsrr->decode = assoc->decode;
1535         bsrr->print = assoc->print;
1536         bsrr->errcode = 0;
1537         bsrr->hits = 0;
1538         bsrr->errstring = NULL;
1539         bsrr->search_info = NULL;
1540         (assoc->init->bend_search)(assoc->backend, bsrr);
1541         if (!bsrr->request)
1542             return 0;
1543     }
1544     return response_searchRequest(assoc, reqb, bsrr, fd);
1545 }
1546
1547 int bend_searchresponse(void *handle, bend_search_rr *bsrr) {return 0;}
1548
1549 /*
1550  * Prepare a searchresponse based on the backend results. We probably want
1551  * to look at making the fetching of records nonblocking as well, but
1552  * so far, we'll keep things simple.
1553  * If bsrt is null, that means we're called in response to a communications
1554  * event, and we'll have to get the response for ourselves.
1555  */
1556 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
1557     bend_search_rr *bsrt, int *fd)
1558 {
1559     Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
1560     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1561     Z_SearchResponse *resp = (Z_SearchResponse *)
1562         odr_malloc (assoc->encode, sizeof(*resp));
1563     int *nulint = odr_intdup (assoc->encode, 0);
1564     bool_t *sr = odr_intdup(assoc->encode, 1);
1565     int *next = odr_intdup(assoc->encode, 0);
1566     int *none = odr_intdup(assoc->encode, Z_RES_NONE);
1567
1568     apdu->which = Z_APDU_searchResponse;
1569     apdu->u.searchResponse = resp;
1570     resp->referenceId = req->referenceId;
1571     resp->additionalSearchInfo = 0;
1572     resp->otherInfo = 0;
1573     *fd = -1;
1574     if (!bsrt && !bend_searchresponse(assoc->backend, bsrt))
1575     {
1576         yaz_log(LOG_FATAL, "Bad result from backend");
1577         return 0;
1578     }
1579     else if (bsrt->errcode)
1580     {
1581         resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
1582         resp->resultCount = nulint;
1583         resp->numberOfRecordsReturned = nulint;
1584         resp->nextResultSetPosition = nulint;
1585         resp->searchStatus = nulint;
1586         resp->resultSetStatus = none;
1587         resp->presentStatus = 0;
1588     }
1589     else
1590     {
1591         int *toget = odr_intdup(assoc->encode, 0);
1592         int *presst = odr_intdup(assoc->encode, 0);
1593         Z_RecordComposition comp, *compp = 0;
1594
1595         yaz_log (LOG_LOG, "resultCount: %d", bsrt->hits);
1596
1597         resp->records = 0;
1598         resp->resultCount = &bsrt->hits;
1599
1600         comp.which = Z_RecordComp_simple;
1601         /* how many records does the user agent want, then? */
1602         if (bsrt->hits <= *req->smallSetUpperBound)
1603         {
1604             *toget = bsrt->hits;
1605             if ((comp.u.simple = req->smallSetElementSetNames))
1606                 compp = &comp;
1607         }
1608         else if (bsrt->hits < *req->largeSetLowerBound)
1609         {
1610             *toget = *req->mediumSetPresentNumber;
1611             if (*toget > bsrt->hits)
1612                 *toget = bsrt->hits;
1613             if ((comp.u.simple = req->mediumSetElementSetNames))
1614                 compp = &comp;
1615         }
1616         else
1617             *toget = 0;
1618
1619         if (*toget && !resp->records)
1620         {
1621             oident *prefformat;
1622             oid_value form;
1623
1624             if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
1625                 form = VAL_NONE;
1626             else
1627                 form = prefformat->value;
1628             resp->records = pack_records(assoc, req->resultSetName, 1,
1629                 toget, compp, next, presst, form, req->referenceId,
1630                                          req->preferredRecordSyntax);
1631             if (!resp->records)
1632                 return 0;
1633             resp->numberOfRecordsReturned = toget;
1634             resp->nextResultSetPosition = next;
1635             resp->searchStatus = sr;
1636             resp->resultSetStatus = 0;
1637             resp->presentStatus = presst;
1638         }
1639         else
1640         {
1641             if (*resp->resultCount)
1642                 *next = 1;
1643             resp->numberOfRecordsReturned = nulint;
1644             resp->nextResultSetPosition = next;
1645             resp->searchStatus = sr;
1646             resp->resultSetStatus = 0;
1647             resp->presentStatus = 0;
1648         }
1649     }
1650     resp->additionalSearchInfo = bsrt->search_info;
1651     return apdu;
1652 }
1653
1654 /*
1655  * Maybe we got a little over-friendly when we designed bend_fetch to
1656  * get only one record at a time. Some backends can optimise multiple-record
1657  * fetches, and at any rate, there is some overhead involved in
1658  * all that selecting and hopping around. Problem is, of course, that the
1659  * frontend can't know ahead of time how many records it'll need to
1660  * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
1661  * is downright lousy as a bulk data transfer protocol.
1662  *
1663  * To start with, we'll do the fetching of records from the backend
1664  * in one operation: To save some trips in and out of the event-handler,
1665  * and to simplify the interface to pack_records. At any rate, asynch
1666  * operation is more fun in operations that have an unpredictable execution
1667  * speed - which is normally more true for search than for present.
1668  */
1669 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
1670                                       int *fd)
1671 {
1672     Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
1673     oident *prefformat;
1674     oid_value form;
1675     Z_APDU *apdu;
1676     Z_PresentResponse *resp;
1677     int *next;
1678     int *num;
1679
1680     yaz_log(LOG_LOG, "Got PresentRequest.");
1681
1682     if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
1683         form = VAL_NONE;
1684     else
1685         form = prefformat->value;
1686     resp = (Z_PresentResponse *)odr_malloc (assoc->encode, sizeof(*resp));
1687     resp->records = 0;
1688     resp->presentStatus = odr_intdup(assoc->encode, 0);
1689     if (assoc->init->bend_present)
1690     {
1691         bend_present_rr *bprr = (bend_present_rr *)
1692             nmem_malloc (reqb->request_mem, sizeof(*bprr));
1693         bprr->setname = req->resultSetId;
1694         bprr->start = *req->resultSetStartPoint;
1695         bprr->number = *req->numberOfRecordsRequested;
1696         bprr->format = form;
1697         bprr->comp = req->recordComposition;
1698         bprr->referenceId = req->referenceId;
1699         bprr->stream = assoc->encode;
1700         bprr->print = assoc->print;
1701         bprr->request = reqb;
1702         bprr->association = assoc;
1703         bprr->errcode = 0;
1704         bprr->errstring = NULL;
1705         (*assoc->init->bend_present)(assoc->backend, bprr);
1706         
1707         if (!bprr->request)
1708             return 0;
1709         if (bprr->errcode)
1710         {
1711             resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
1712             *resp->presentStatus = Z_PRES_FAILURE;
1713         }
1714     }
1715     apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1716     next = odr_intdup(assoc->encode, 0);
1717     num = odr_intdup(assoc->encode, 0);
1718     
1719     apdu->which = Z_APDU_presentResponse;
1720     apdu->u.presentResponse = resp;
1721     resp->referenceId = req->referenceId;
1722     resp->otherInfo = 0;
1723     
1724     if (!resp->records)
1725     {
1726         *num = *req->numberOfRecordsRequested;
1727         resp->records =
1728             pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
1729                      num, req->recordComposition, next, resp->presentStatus,
1730                          form, req->referenceId, req->preferredRecordSyntax);
1731     }
1732     if (!resp->records)
1733         return 0;
1734     resp->numberOfRecordsReturned = num;
1735     resp->nextResultSetPosition = next;
1736     
1737     return apdu;
1738 }
1739
1740 /*
1741  * Scan was implemented rather in a hurry, and with support for only the basic
1742  * elements of the service in the backend API. Suggestions are welcome.
1743  */
1744 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
1745 {
1746     Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
1747     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1748     Z_ScanResponse *res = (Z_ScanResponse *)
1749         odr_malloc (assoc->encode, sizeof(*res));
1750     int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
1751     int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
1752     Z_ListEntries *ents = (Z_ListEntries *)
1753         odr_malloc (assoc->encode, sizeof(*ents));
1754     Z_DiagRecs *diagrecs_p = NULL;
1755     oident *attset;
1756     bend_scan_rr *bsrr = (bend_scan_rr *)
1757         odr_malloc (assoc->encode, sizeof(*bsrr));
1758
1759     yaz_log(LOG_LOG, "Got ScanRequest");
1760
1761     apdu->which = Z_APDU_scanResponse;
1762     apdu->u.scanResponse = res;
1763     res->referenceId = req->referenceId;
1764
1765     /* if step is absent, set it to 0 */
1766     res->stepSize = odr_intdup(assoc->encode, 0);
1767     if (req->stepSize)
1768         *res->stepSize = *req->stepSize;
1769
1770     res->scanStatus = scanStatus;
1771     res->numberOfEntriesReturned = numberOfEntriesReturned;
1772     res->positionOfTerm = 0;
1773     res->entries = ents;
1774     ents->num_entries = 0;
1775     ents->entries = NULL;
1776     ents->num_nonsurrogateDiagnostics = 0;
1777     ents->nonsurrogateDiagnostics = NULL;
1778     res->attributeSet = 0;
1779     res->otherInfo = 0;
1780
1781     if (req->databaseNames)
1782     {
1783         int i;
1784         for (i = 0; i < req->num_databaseNames; i++)
1785             yaz_log (LOG_LOG, "Database '%s'", req->databaseNames[i]);
1786     }
1787     bsrr->num_bases = req->num_databaseNames;
1788     bsrr->basenames = req->databaseNames;
1789     bsrr->num_entries = *req->numberOfTermsRequested;
1790     bsrr->term = req->termListAndStartPoint;
1791     bsrr->referenceId = req->referenceId;
1792     bsrr->stream = assoc->encode;
1793     bsrr->print = assoc->print;
1794     bsrr->step_size = res->stepSize;
1795     if (req->attributeSet &&
1796         (attset = oid_getentbyoid(req->attributeSet)) &&
1797         (attset->oclass == CLASS_ATTSET || attset->oclass == CLASS_GENERAL))
1798         bsrr->attributeset = attset->value;
1799     else
1800         bsrr->attributeset = VAL_NONE;
1801     log_scan_term (req->termListAndStartPoint, bsrr->attributeset);
1802     bsrr->term_position = req->preferredPositionInResponse ?
1803         *req->preferredPositionInResponse : 1;
1804     ((int (*)(void *, bend_scan_rr *))
1805      (*assoc->init->bend_scan))(assoc->backend, bsrr);
1806     if (bsrr->errcode)
1807         diagrecs_p = diagrecs(assoc, bsrr->errcode, bsrr->errstring);
1808     else
1809     {
1810         int i;
1811         Z_Entry **tab = (Z_Entry **)
1812             odr_malloc (assoc->encode, sizeof(*tab) * bsrr->num_entries);
1813         
1814         if (bsrr->status == BEND_SCAN_PARTIAL)
1815             *scanStatus = Z_Scan_partial_5;
1816         else
1817             *scanStatus = Z_Scan_success;
1818         ents->entries = tab;
1819         ents->num_entries = bsrr->num_entries;
1820         res->numberOfEntriesReturned = &ents->num_entries;          
1821         res->positionOfTerm = &bsrr->term_position;
1822         for (i = 0; i < bsrr->num_entries; i++)
1823         {
1824             Z_Entry *e;
1825             Z_TermInfo *t;
1826             Odr_oct *o;
1827             
1828             tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
1829             if (bsrr->entries[i].occurrences >= 0)
1830             {
1831                 e->which = Z_Entry_termInfo;
1832                 e->u.termInfo = t = (Z_TermInfo *)
1833                     odr_malloc(assoc->encode, sizeof(*t));
1834                 t->suggestedAttributes = 0;
1835                 t->displayTerm = 0;
1836                 t->alternativeTerm = 0;
1837                 t->byAttributes = 0;
1838                 t->otherTermInfo = 0;
1839                 t->globalOccurrences = &bsrr->entries[i].occurrences;
1840                 t->term = (Z_Term *)
1841                     odr_malloc(assoc->encode, sizeof(*t->term));
1842                 t->term->which = Z_Term_general;
1843                 t->term->u.general = o =
1844                     (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
1845                 o->buf = (unsigned char *)
1846                     odr_malloc(assoc->encode, o->len = o->size =
1847                                strlen(bsrr->entries[i].term));
1848                 memcpy(o->buf, bsrr->entries[i].term, o->len);
1849                 yaz_log(LOG_DEBUG, "  term #%d: '%s' (%d)", i,
1850                          bsrr->entries[i].term, bsrr->entries[i].occurrences);
1851             }
1852             else
1853             {
1854                 Z_DiagRecs *drecs = diagrecs (assoc,
1855                                               bsrr->entries[i].errcode,
1856                                               bsrr->entries[i].errstring);
1857                 assert (drecs->num_diagRecs == 1);
1858                 e->which = Z_Entry_surrogateDiagnostic;
1859                 assert (drecs->diagRecs[0]);
1860                 e->u.surrogateDiagnostic = drecs->diagRecs[0];
1861             }
1862         }
1863     }
1864     if (diagrecs_p)
1865     {
1866         ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
1867         ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
1868     }
1869     return apdu;
1870 }
1871
1872 static Z_APDU *process_sortRequest(association *assoc, request *reqb,
1873     int *fd)
1874 {
1875     Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
1876     Z_SortResponse *res = (Z_SortResponse *)
1877         odr_malloc (assoc->encode, sizeof(*res));
1878     bend_sort_rr *bsrr = (bend_sort_rr *)
1879         odr_malloc (assoc->encode, sizeof(*bsrr));
1880
1881     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1882
1883     yaz_log(LOG_LOG, "Got SortRequest.");
1884
1885     bsrr->num_input_setnames = req->num_inputResultSetNames;
1886     bsrr->input_setnames = req->inputResultSetNames;
1887     bsrr->referenceId = req->referenceId;
1888     bsrr->output_setname = req->sortedResultSetName;
1889     bsrr->sort_sequence = req->sortSequence;
1890     bsrr->stream = assoc->encode;
1891     bsrr->print = assoc->print;
1892
1893     bsrr->sort_status = Z_SortStatus_failure;
1894     bsrr->errcode = 0;
1895     bsrr->errstring = 0;
1896     
1897     (*assoc->init->bend_sort)(assoc->backend, bsrr);
1898     
1899     res->referenceId = bsrr->referenceId;
1900     res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
1901     res->resultSetStatus = 0;
1902     if (bsrr->errcode)
1903     {
1904         Z_DiagRecs *dr = diagrecs (assoc, bsrr->errcode, bsrr->errstring);
1905         res->diagnostics = dr->diagRecs;
1906         res->num_diagnostics = dr->num_diagRecs;
1907     }
1908     else
1909     {
1910         res->num_diagnostics = 0;
1911         res->diagnostics = 0;
1912     }
1913     res->otherInfo = 0;
1914
1915     apdu->which = Z_APDU_sortResponse;
1916     apdu->u.sortResponse = res;
1917     return apdu;
1918 }
1919
1920 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
1921     int *fd)
1922 {
1923     Z_DeleteResultSetRequest *req =
1924         reqb->apdu_request->u.deleteResultSetRequest;
1925     Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
1926         odr_malloc (assoc->encode, sizeof(*res));
1927     bend_delete_rr *bdrr = (bend_delete_rr *)
1928         odr_malloc (assoc->encode, sizeof(*bdrr));
1929     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1930
1931     yaz_log(LOG_LOG, "Got DeleteRequest.");
1932
1933     bdrr->num_setnames = req->num_resultSetList;
1934     bdrr->setnames = req->resultSetList;
1935     bdrr->stream = assoc->encode;
1936     bdrr->print = assoc->print;
1937     bdrr->function = *req->deleteFunction;
1938     bdrr->referenceId = req->referenceId;
1939     bdrr->statuses = 0;
1940     if (bdrr->num_setnames > 0)
1941     {
1942         int i;
1943         bdrr->statuses = (int*) 
1944             odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
1945                        bdrr->num_setnames);
1946         for (i = 0; i < bdrr->num_setnames; i++)
1947             bdrr->statuses[i] = 0;
1948     }
1949     (*assoc->init->bend_delete)(assoc->backend, bdrr);
1950     
1951     res->referenceId = req->referenceId;
1952
1953     res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
1954
1955     res->deleteListStatuses = 0;
1956     if (bdrr->num_setnames > 0)
1957     {
1958         int i;
1959         res->deleteListStatuses = (Z_ListStatuses *)
1960             odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
1961         res->deleteListStatuses->num = bdrr->num_setnames;
1962         res->deleteListStatuses->elements =
1963             (Z_ListStatus **)
1964             odr_malloc (assoc->encode, 
1965                         sizeof(*res->deleteListStatuses->elements) *
1966                         bdrr->num_setnames);
1967         for (i = 0; i<bdrr->num_setnames; i++)
1968         {
1969             res->deleteListStatuses->elements[i] =
1970                 (Z_ListStatus *)
1971                 odr_malloc (assoc->encode,
1972                             sizeof(**res->deleteListStatuses->elements));
1973             res->deleteListStatuses->elements[i]->status = bdrr->statuses+i;
1974             res->deleteListStatuses->elements[i]->id =
1975                 odr_strdup (assoc->encode, bdrr->setnames[i]);
1976             
1977         }
1978     }
1979     res->numberNotDeleted = 0;
1980     res->bulkStatuses = 0;
1981     res->deleteMessage = 0;
1982     res->otherInfo = 0;
1983
1984     apdu->which = Z_APDU_deleteResultSetResponse;
1985     apdu->u.deleteResultSetResponse = res;
1986     return apdu;
1987 }
1988
1989 static void process_close(association *assoc, request *reqb)
1990 {
1991     Z_Close *req = reqb->apdu_request->u.close;
1992     static char *reasons[] =
1993     {
1994         "finished",
1995         "shutdown",
1996         "systemProblem",
1997         "costLimit",
1998         "resources",
1999         "securityViolation",
2000         "protocolError",
2001         "lackOfActivity",
2002         "peerAbort",
2003         "unspecified"
2004     };
2005
2006     yaz_log(LOG_LOG, "Got Close, reason %s, message %s",
2007         reasons[*req->closeReason], req->diagnosticInformation ?
2008         req->diagnosticInformation : "NULL");
2009     if (assoc->version < 3) /* to make do_force respond with close */
2010         assoc->version = 3;
2011     do_close_req(assoc, Z_Close_finished,
2012                  "Association terminated by client", reqb);
2013 }
2014
2015 void save_referenceId (request *reqb, Z_ReferenceId *refid)
2016 {
2017     if (refid)
2018     {
2019         reqb->len_refid = refid->len;
2020         reqb->refid = (char *)nmem_malloc (reqb->request_mem, refid->len);
2021         memcpy (reqb->refid, refid->buf, refid->len);
2022     }
2023     else
2024     {
2025         reqb->len_refid = 0;
2026         reqb->refid = NULL;
2027     }
2028 }
2029
2030 void bend_request_send (bend_association a, bend_request req, Z_APDU *res)
2031 {
2032     process_z_response (a, req, res);
2033 }
2034
2035 bend_request bend_request_mk (bend_association a)
2036 {
2037     request *nreq = request_get (&a->outgoing);
2038     nreq->request_mem = nmem_create ();
2039     return nreq;
2040 }
2041
2042 Z_ReferenceId *bend_request_getid (ODR odr, bend_request req)
2043 {
2044     Z_ReferenceId *id;
2045     if (!req->refid)
2046         return 0;
2047     id = (Odr_oct *)odr_malloc (odr, sizeof(*odr));
2048     id->buf = (unsigned char *)odr_malloc (odr, req->len_refid);
2049     id->len = id->size = req->len_refid;
2050     memcpy (id->buf, req->refid, req->len_refid);
2051     return id;
2052 }
2053
2054 void bend_request_destroy (bend_request *req)
2055 {
2056     nmem_destroy((*req)->request_mem);
2057     request_release(*req);
2058     *req = NULL;
2059 }
2060
2061 int bend_backend_respond (bend_association a, bend_request req)
2062 {
2063     char *msg;
2064     int r;
2065     r = process_z_request (a, req, &msg);
2066     if (r < 0)
2067         yaz_log (LOG_WARN, "%s", msg);
2068     return r;
2069 }
2070
2071 void bend_request_setdata(bend_request r, void *p)
2072 {
2073     r->clientData = p;
2074 }
2075
2076 void *bend_request_getdata(bend_request r)
2077 {
2078     return r->clientData;
2079 }
2080
2081 static Z_APDU *process_segmentRequest (association *assoc, request *reqb)
2082 {
2083     bend_segment_rr req;
2084
2085     req.segment = reqb->apdu_request->u.segmentRequest;
2086     req.stream = assoc->encode;
2087     req.decode = assoc->decode;
2088     req.print = assoc->print;
2089     req.association = assoc;
2090     
2091     (*assoc->init->bend_segment)(assoc->backend, &req);
2092
2093     return 0;
2094 }
2095
2096 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd)
2097 {
2098     bend_esrequest_rr esrequest;
2099
2100     Z_ExtendedServicesRequest *req =
2101         reqb->apdu_request->u.extendedServicesRequest;
2102     Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
2103
2104     Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
2105
2106     yaz_log(LOG_DEBUG,"inside Process esRequest");
2107
2108     esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
2109     esrequest.stream = assoc->encode;
2110     esrequest.decode = assoc->decode;
2111     esrequest.print = assoc->print;
2112     esrequest.errcode = 0;
2113     esrequest.errstring = NULL;
2114     esrequest.request = reqb;
2115     esrequest.association = assoc;
2116     esrequest.taskPackage = 0;
2117     esrequest.referenceId = req->referenceId;
2118     
2119     (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
2120     
2121     /* If the response is being delayed, return NULL */
2122     if (esrequest.request == NULL)
2123         return(NULL);
2124
2125     resp->referenceId = req->referenceId;
2126
2127     if (esrequest.errcode == -1)
2128     {
2129         /* Backend service indicates request will be processed */
2130         yaz_log(LOG_DEBUG,"Request could be processed...Accepted !");
2131         *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
2132     }
2133     else if (esrequest.errcode == 0)
2134     {
2135         /* Backend service indicates request will be processed */
2136         yaz_log(LOG_DEBUG,"Request could be processed...Done !");
2137         *resp->operationStatus = Z_ExtendedServicesResponse_done;
2138     }
2139     else
2140     {
2141         Z_DiagRecs *diagRecs = diagrecs (assoc, esrequest.errcode,
2142                                          esrequest.errstring);
2143
2144         /* Backend indicates error, request will not be processed */
2145         yaz_log(LOG_DEBUG,"Request could not be processed...failure !");
2146         *resp->operationStatus = Z_ExtendedServicesResponse_failure;
2147         resp->num_diagnostics = diagRecs->num_diagRecs;
2148         resp->diagnostics = diagRecs->diagRecs;
2149     }
2150     /* Do something with the members of bend_extendedservice */
2151     if (esrequest.taskPackage)
2152         resp->taskPackage = z_ext_record (assoc->encode, VAL_EXTENDED,
2153                                          (const char *)  esrequest.taskPackage,
2154                                           -1);
2155     yaz_log(LOG_DEBUG,"Send the result apdu");
2156     return apdu;
2157 }
2158