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