ce4d41203b1d23f96d3fac1f5b1d1f80f659b06a
[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.141 2003-02-18 14:28:52 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, "Connection closed - end of session");
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     yaz_log(LOG_LOG, "Got SRW SearchRetrieveRequest");
521
522     if (!assoc->init)
523         srw_bend_init(assoc);
524
525     rr.setname = "default";
526     rr.replace_set = 1;
527     rr.num_bases = 1;
528     rr.basenames = &srw_req->database;
529     rr.referenceId = 0;
530
531     ext = (Z_External *) odr_malloc(assoc->decode, sizeof(*ext));
532     ext->direct_reference = odr_getoidbystr(assoc->decode, 
533                                             "1.2.840.10003.16.2");
534     ext->indirect_reference = 0;
535     ext->descriptor = 0;
536     ext->which = Z_External_CQL;
537     if (srw_req->query)
538         ext->u.cql = srw_req->query;
539     else
540         ext->u.cql = "noterm";
541     
542     rr.query = (Z_Query *) odr_malloc (assoc->decode, sizeof(*rr.query));
543     rr.query->which = Z_Query_type_104;
544     rr.query->u.type_104 =  ext;
545     
546     rr.stream = assoc->encode;
547     rr.decode = assoc->decode;
548     rr.print = assoc->print;
549     rr.request = req;
550     rr.association = assoc;
551     rr.fd = 0;
552     rr.hits = 0;
553     rr.errcode = 0;
554     rr.errstring = 0;
555     rr.search_info = 0;
556     yaz_log_zquery(rr.query);
557     (assoc->init->bend_search)(assoc->backend, &rr);
558     srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
559     if (rr.errcode)
560     {
561         srw_res->num_diagnostics = 1;
562         srw_res->diagnostics = (Z_SRW_diagnostic *)
563             odr_malloc(assoc->encode, sizeof(*srw_res->diagnostics));
564         srw_res->diagnostics[0].code = 
565             odr_intdup(assoc->encode, rr.errcode);
566         srw_res->diagnostics[0].details = rr.errstring;
567     }
568     else
569     {
570         srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
571         if (srw_req->maximumRecords && *srw_req->maximumRecords > 0)
572         {
573             int number = *srw_req->maximumRecords;
574             int start = 1;
575             int i;
576             if (srw_req->startRecord)
577                 start = *srw_req->startRecord;
578             if (start <= rr.hits)
579             {
580                 int j = 0;
581                 if (start + number > rr.hits)
582                     number = rr.hits - start + 1;
583                 srw_res->records = (Z_SRW_record *)
584                     odr_malloc(assoc->encode,
585                                number * sizeof(*srw_res->records));
586                 for (i = 0; i<number; i++)
587                 {
588                     srw_res->records[j].recordData_buf = 0;
589                     srw_bend_fetch(assoc, i+start, srw_req,
590                                    srw_res->records + j);
591                     if (srw_res->records[j].recordData_buf)
592                         j++;
593                 }
594                 srw_res->num_records = j;
595                 if (!j)
596                     srw_res->records = 0;
597             }
598         }
599     }
600 }
601
602 static void process_http_request(association *assoc, request *req)
603 {
604     Z_HTTP_Request *hreq = req->gdu_request->u.HTTP_Request;
605     ODR o = assoc->encode;
606     Z_GDU *p = 0;
607     Z_HTTP_Response *hres = 0;
608     int keepalive = 1;
609
610     if (!strcmp(hreq->method, "GET"))
611     {
612 #ifdef DOCDIR
613         if (strlen(hreq->path) >= 5 && strlen(hreq->path) < 80 &&
614                          !memcmp(hreq->path, "/doc/", 5))
615         {
616             FILE *f;
617             char fpath[120];
618
619             strcpy(fpath, DOCDIR);
620             strcat(fpath, hreq->path+4);
621             f = fopen(fpath, "rb");
622             if (f) {
623                 struct stat sbuf;
624                 if (fstat(fileno(f), &sbuf) || !S_ISREG(sbuf.st_mode))
625                 {
626                     fclose(f);
627                     f = 0;
628                 }
629             }
630             if (f)
631             {
632                 long sz;
633                 fseek(f, 0L, SEEK_END);
634                 sz = ftell(f);
635                 if (sz >= 0 && sz < 500000)
636                 {
637                     const char *ctype = "application/octet-stream";
638                     const char *cp;
639
640                     p = z_get_HTTP_Response(o, 200);
641                     hres = p->u.HTTP_Response;
642                     hres->content_buf = (char *) odr_malloc(o, sz + 1);
643                     hres->content_len = sz;
644                     fseek(f, 0L, SEEK_SET);
645                     fread(hres->content_buf, 1, sz, f);
646                     if ((cp = strrchr(fpath, '.'))) {
647                         cp++;
648                         if (!strcmp(cp, "png"))
649                             ctype = "image/png";
650                         else if (!strcmp(cp, "gif"))
651                             ctype = "image/gif";
652                         else if (!strcmp(cp, "xml"))
653                             ctype = "text/xml";
654                         else if (!strcmp(cp, "html"))
655                             ctype = "text/html";
656                     }
657                     z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
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         const char *content_type = z_HTTP_header_lookup(hreq->headers,
699                                                         "Content-Type");
700         const char *soap_action = z_HTTP_header_lookup(hreq->headers,
701                                                        "SOAPAction");
702         if (content_type && soap_action && 
703             !yaz_strcmp_del("text/xml", content_type, "; "))
704         {
705             Z_SOAP *soap_package = 0;
706             int ret;
707             int http_code = 500;
708
709             static Z_SOAP_Handler soap_handlers[2] = {
710                 {"http://www.loc.gov/zing/srw/v1.0/", 0,
711                                          (Z_SOAP_fun) yaz_srw_codec},
712                 {0, 0, 0}
713             };
714
715             ret = z_soap_codec(assoc->decode, &soap_package, 
716                                &hreq->content_buf, &hreq->content_len,
717                                soap_handlers);
718             
719             if (!ret && soap_package->which == Z_SOAP_generic &&
720                 soap_package->u.generic->no == 0)
721             {
722                 /* SRW package */
723                 Z_SRW_searchRetrieve *sr = soap_package->u.generic->p;
724                 
725                 if (sr->which == Z_SRW_searchRetrieve_request)
726                 {
727                     Z_SRW_searchRetrieve *res =
728                         yaz_srw_get(assoc->encode,
729                                     Z_SRW_searchRetrieve_response);
730
731                     if (!sr->u.request->database)
732                     {
733                         const char *p0 = hreq->path, *p1;
734                         if (*p0 == '/')
735                             p0++;
736                         p1 = strchr(p0, '?');
737                         if (!p1)
738                             p1 = p0 + strlen(p0);
739                         if (p1 != p0)
740                         {
741                             sr->u.request->database =
742                                 odr_malloc(assoc->decode, p1 - p0 + 1);
743                             memcpy (sr->u.request->database, p0, p1 - p0);
744                             sr->u.request->database[p1 - p0] = '\0';
745                         }
746                         else
747                             sr->u.request->database = "Default";
748                     }
749                     srw_bend_search(assoc, req, sr->u.request,
750                                     res->u.response);
751                     
752                     soap_package->u.generic->p = res;
753                     http_code = 200;
754                 }
755             }
756
757             p = z_get_HTTP_Response(o, 200);
758             hres = p->u.HTTP_Response;
759             ret = z_soap_codec(assoc->encode, &soap_package,
760                                &hres->content_buf, &hres->content_len,
761                                soap_handlers);
762             hres->code = http_code;
763             z_HTTP_header_add(o, &hres->headers, "Content-Type", "text/xml");
764         }
765         if (!p) /* still no response ? */
766             p = z_get_HTTP_Response(o, 500);
767     }
768     else
769     {
770         p = z_get_HTTP_Response(o, 405);
771         hres = p->u.HTTP_Response;
772
773         z_HTTP_header_add(o, &hres->headers, "Allow", "GET, POST");
774     }
775     hres = p->u.HTTP_Response;
776     if (!strcmp(hreq->version, "1.0")) 
777     {
778         const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
779         if (v && !strcmp(v, "Keep-Alive"))
780             keepalive = 1;
781         else
782             keepalive = 0;
783         hres->version = "1.0";
784     }
785     else
786     {
787         const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
788         if (v && !strcmp(v, "close"))
789             keepalive = 0;
790         else
791             keepalive = 1;
792         hres->version = "1.1";
793     }
794     if (!keepalive)
795     {
796         z_HTTP_header_add(o, &hres->headers, "Connection", "close");
797         assoc->state = ASSOC_DEAD;
798     }
799     else
800     {
801         int t;
802         const char *alive = z_HTTP_header_lookup(hreq->headers, "Keep-Alive");
803
804         if (alive && isdigit(*alive))
805             t = atoi(alive);
806         else
807             t = 30;
808         if (t < 0 || t > 3600)
809             t = 3600;
810         iochan_settimeout(assoc->client_chan,t);
811         z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
812     }
813     process_gdu_response(assoc, req, p);
814 }
815
816 static void process_gdu_request(association *assoc, request *req)
817 {
818     if (req->gdu_request->which == Z_GDU_Z3950)
819     {
820         char *msg = 0;
821         req->apdu_request = req->gdu_request->u.z3950;
822         if (process_z_request(assoc, req, &msg) < 0)
823             do_close_req(assoc, Z_Close_systemProblem, msg, req);
824     }
825     else if (req->gdu_request->which == Z_GDU_HTTP_Request)
826         process_http_request(assoc, req);
827     else
828     {
829         do_close_req(assoc, Z_Close_systemProblem, "bad protocol packet", req);
830     }
831 }
832
833 /*
834  * Initiate request processing.
835  */
836 static int process_z_request(association *assoc, request *req, char **msg)
837 {
838     int fd = -1;
839     Z_APDU *res;
840     int retval;
841     
842     *msg = "Unknown Error";
843     assert(req && req->state == REQUEST_IDLE);
844     if (req->apdu_request->which != Z_APDU_initRequest && !assoc->init)
845     {
846         *msg = "Missing InitRequest";
847         return -1;
848     }
849     switch (req->apdu_request->which)
850     {
851     case Z_APDU_initRequest:
852         iochan_settimeout(assoc->client_chan,
853                           statserv_getcontrol()->idle_timeout * 60);
854         res = process_initRequest(assoc, req); break;
855     case Z_APDU_searchRequest:
856         res = process_searchRequest(assoc, req, &fd); break;
857     case Z_APDU_presentRequest:
858         res = process_presentRequest(assoc, req, &fd); break;
859     case Z_APDU_scanRequest:
860         if (assoc->init->bend_scan)
861             res = process_scanRequest(assoc, req, &fd);
862         else
863         {
864             *msg = "Cannot handle Scan APDU";
865             return -1;
866         }
867         break;
868     case Z_APDU_extendedServicesRequest:
869         if (assoc->init->bend_esrequest)
870             res = process_ESRequest(assoc, req, &fd);
871         else
872         {
873             *msg = "Cannot handle Extended Services APDU";
874             return -1;
875         }
876         break;
877     case Z_APDU_sortRequest:
878         if (assoc->init->bend_sort)
879             res = process_sortRequest(assoc, req, &fd);
880         else
881         {
882             *msg = "Cannot handle Sort APDU";
883             return -1;
884         }
885         break;
886     case Z_APDU_close:
887         process_close(assoc, req);
888         return 0;
889     case Z_APDU_deleteResultSetRequest:
890         if (assoc->init->bend_delete)
891             res = process_deleteRequest(assoc, req, &fd);
892         else
893         {
894             *msg = "Cannot handle Delete APDU";
895             return -1;
896         }
897         break;
898     case Z_APDU_segmentRequest:
899         if (assoc->init->bend_segment)
900         {
901             res = process_segmentRequest (assoc, req);
902         }
903         else
904         {
905             *msg = "Cannot handle Segment APDU";
906             return -1;
907         }
908         break;
909     default:
910         *msg = "Bad APDU received";
911         return -1;
912     }
913     if (res)
914     {
915         yaz_log(LOG_DEBUG, "  result immediately available");
916         retval = process_z_response(assoc, req, res);
917     }
918     else if (fd < 0)
919     {
920         yaz_log(LOG_DEBUG, "  result unavailble");
921         retval = 0;
922     }
923     else /* no result yet - one will be provided later */
924     {
925         IOCHAN chan;
926
927         /* Set up an I/O handler for the fd supplied by the backend */
928
929         yaz_log(LOG_DEBUG, "   establishing handler for result");
930         req->state = REQUEST_PENDING;
931         if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT)))
932             abort();
933         iochan_setdata(chan, assoc);
934         retval = 0;
935     }
936     return retval;
937 }
938
939 /*
940  * Handle message from the backend.
941  */
942 void backend_response(IOCHAN i, int event)
943 {
944     association *assoc = (association *)iochan_getdata(i);
945     request *req = request_head(&assoc->incoming);
946     Z_APDU *res;
947     int fd;
948
949     yaz_log(LOG_DEBUG, "backend_response");
950     assert(assoc && req && req->state != REQUEST_IDLE);
951     /* determine what it is we're waiting for */
952     switch (req->apdu_request->which)
953     {
954         case Z_APDU_searchRequest:
955             res = response_searchRequest(assoc, req, 0, &fd); break;
956 #if 0
957         case Z_APDU_presentRequest:
958             res = response_presentRequest(assoc, req, 0, &fd); break;
959         case Z_APDU_scanRequest:
960             res = response_scanRequest(assoc, req, 0, &fd); break;
961 #endif
962         default:
963             yaz_log(LOG_WARN, "Serious programmer's lapse or bug");
964             abort();
965     }
966     if ((res && process_z_response(assoc, req, res) < 0) || fd < 0)
967     {
968         yaz_log(LOG_LOG, "Fatal error when talking to backend");
969         do_close(assoc, Z_Close_systemProblem, 0);
970         iochan_destroy(i);
971         return;
972     }
973     else if (!res) /* no result yet - try again later */
974     {
975         yaz_log(LOG_DEBUG, "   no result yet");
976         iochan_setfd(i, fd); /* in case fd has changed */
977     }
978 }
979
980 /*
981  * Encode response, and transfer the request structure to the outgoing queue.
982  */
983 static int process_gdu_response(association *assoc, request *req, Z_GDU *res)
984 {
985     odr_setbuf(assoc->encode, req->response, req->size_response, 1);
986
987     if (assoc->print && !z_GDU(assoc->print, &res, 0, 0))
988     {
989         yaz_log(LOG_WARN, "ODR print error: %s", 
990             odr_errmsg(odr_geterror(assoc->print)));
991         odr_reset(assoc->print);
992     }
993     if (!z_GDU(assoc->encode, &res, 0, 0))
994     {
995         yaz_log(LOG_WARN, "ODR error when encoding response: %s",
996             odr_errmsg(odr_geterror(assoc->decode)));
997         return -1;
998     }
999     req->response = odr_getbuf(assoc->encode, &req->len_response,
1000         &req->size_response);
1001     odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
1002     odr_reset(assoc->encode);
1003     req->state = REQUEST_IDLE;
1004     request_enq(&assoc->outgoing, req);
1005     /* turn the work over to the ir_session handler */
1006     iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
1007     assoc->cs_put_mask = EVENT_OUTPUT;
1008     /* Is there more work to be done? give that to the input handler too */
1009 #if 1
1010     if (request_head(&assoc->incoming))
1011     {
1012         yaz_log (LOG_DEBUG, "more work to be done");
1013         iochan_setevent(assoc->client_chan, EVENT_WORK);
1014     }
1015 #endif
1016     return 0;
1017 }
1018
1019 /*
1020  * Encode response, and transfer the request structure to the outgoing queue.
1021  */
1022 static int process_z_response(association *assoc, request *req, Z_APDU *res)
1023 {
1024     odr_setbuf(assoc->encode, req->response, req->size_response, 1);
1025
1026     if (assoc->print && !z_APDU(assoc->print, &res, 0, 0))
1027     {
1028         yaz_log(LOG_WARN, "ODR print error: %s", 
1029             odr_errmsg(odr_geterror(assoc->print)));
1030         odr_reset(assoc->print);
1031     }
1032     if (!z_APDU(assoc->encode, &res, 0, 0))
1033     {
1034         yaz_log(LOG_WARN, "ODR error when encoding response: %s",
1035             odr_errmsg(odr_geterror(assoc->decode)));
1036         return -1;
1037     }
1038     req->response = odr_getbuf(assoc->encode, &req->len_response,
1039         &req->size_response);
1040     odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
1041     odr_reset(assoc->encode);
1042     req->state = REQUEST_IDLE;
1043     request_enq(&assoc->outgoing, req);
1044     /* turn the work over to the ir_session handler */
1045     iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
1046     assoc->cs_put_mask = EVENT_OUTPUT;
1047     /* Is there more work to be done? give that to the input handler too */
1048 #if 1
1049     if (request_head(&assoc->incoming))
1050     {
1051         yaz_log (LOG_DEBUG, "more work to be done");
1052         iochan_setevent(assoc->client_chan, EVENT_WORK);
1053     }
1054 #endif
1055     return 0;
1056 }
1057
1058 /*
1059  * Handle init request.
1060  * At the moment, we don't check the options
1061  * anywhere else in the code - we just try not to do anything that would
1062  * break a naive client. We'll toss 'em into the association block when
1063  * we need them there.
1064  */
1065 static Z_APDU *process_initRequest(association *assoc, request *reqb)
1066 {
1067     statserv_options_block *cb = statserv_getcontrol();
1068     Z_InitRequest *req = reqb->apdu_request->u.initRequest;
1069     Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
1070     Z_InitResponse *resp = apdu->u.initResponse;
1071     bend_initresult *binitres;
1072
1073     char options[140];
1074
1075     xfree (assoc->init);
1076     assoc->init = (bend_initrequest *) xmalloc (sizeof(*assoc->init));
1077
1078     yaz_log(LOG_LOG, "Got initRequest");
1079     if (req->implementationId)
1080         yaz_log(LOG_LOG, "Id:        %s", req->implementationId);
1081     if (req->implementationName)
1082         yaz_log(LOG_LOG, "Name:      %s", req->implementationName);
1083     if (req->implementationVersion)
1084         yaz_log(LOG_LOG, "Version:   %s", req->implementationVersion);
1085
1086     assoc->init->stream = assoc->encode;
1087     assoc->init->print = assoc->print;
1088     assoc->init->auth = req->idAuthentication;
1089     assoc->init->referenceId = req->referenceId;
1090     assoc->init->implementation_version = 0;
1091     assoc->init->implementation_id = 0;
1092     assoc->init->implementation_name = 0;
1093     assoc->init->bend_sort = NULL;
1094     assoc->init->bend_search = NULL;
1095     assoc->init->bend_present = NULL;
1096     assoc->init->bend_esrequest = NULL;
1097     assoc->init->bend_delete = NULL;
1098     assoc->init->bend_scan = NULL;
1099     assoc->init->bend_segment = NULL;
1100     assoc->init->bend_fetch = NULL;
1101     assoc->init->charneg_request = NULL;
1102     assoc->init->charneg_response = NULL;
1103     assoc->init->decode = assoc->decode;
1104
1105     if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
1106     {
1107         Z_CharSetandLanguageNegotiation *negotiation =
1108             yaz_get_charneg_record (req->otherInfo);
1109         if (negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
1110             assoc->init->charneg_request = negotiation;
1111     }
1112     
1113     assoc->init->peer_name =
1114         odr_strdup (assoc->encode, cs_addrstr(assoc->client_link));
1115     if (!(binitres = (*cb->bend_init)(assoc->init)))
1116     {
1117         yaz_log(LOG_WARN, "Bad response from backend.");
1118         return 0;
1119     }
1120
1121     assoc->backend = binitres->handle;
1122     if ((assoc->init->bend_sort))
1123         yaz_log (LOG_DEBUG, "Sort handler installed");
1124     if ((assoc->init->bend_search))
1125         yaz_log (LOG_DEBUG, "Search handler installed");
1126     if ((assoc->init->bend_present))
1127         yaz_log (LOG_DEBUG, "Present handler installed");   
1128     if ((assoc->init->bend_esrequest))
1129         yaz_log (LOG_DEBUG, "ESRequest handler installed");   
1130     if ((assoc->init->bend_delete))
1131         yaz_log (LOG_DEBUG, "Delete handler installed");   
1132     if ((assoc->init->bend_scan))
1133         yaz_log (LOG_DEBUG, "Scan handler installed");   
1134     if ((assoc->init->bend_segment))
1135         yaz_log (LOG_DEBUG, "Segment handler installed");   
1136     
1137     resp->referenceId = req->referenceId;
1138     *options = '\0';
1139     /* let's tell the client what we can do */
1140     if (ODR_MASK_GET(req->options, Z_Options_search))
1141     {
1142         ODR_MASK_SET(resp->options, Z_Options_search);
1143         strcat(options, "srch");
1144     }
1145     if (ODR_MASK_GET(req->options, Z_Options_present))
1146     {
1147         ODR_MASK_SET(resp->options, Z_Options_present);
1148         strcat(options, " prst");
1149     }
1150     if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
1151         assoc->init->bend_delete)
1152     {
1153         ODR_MASK_SET(resp->options, Z_Options_delSet);
1154         strcat(options, " del");
1155     }
1156     if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
1157         assoc->init->bend_esrequest)
1158     {
1159         ODR_MASK_SET(resp->options, Z_Options_extendedServices);
1160         strcat (options, " extendedServices");
1161     }
1162     if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
1163     {
1164         ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
1165         strcat(options, " namedresults");
1166     }
1167     if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
1168     {
1169         ODR_MASK_SET(resp->options, Z_Options_scan);
1170         strcat(options, " scan");
1171     }
1172     if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
1173     {
1174         ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
1175         strcat(options, " concurrop");
1176     }
1177     if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
1178     {
1179         ODR_MASK_SET(resp->options, Z_Options_sort);
1180         strcat(options, " sort");
1181     }
1182
1183     if (ODR_MASK_GET(req->options, Z_Options_negotiationModel)
1184         && assoc->init->charneg_response)
1185     {
1186         Z_OtherInformation **p;
1187         Z_OtherInformationUnit *p0;
1188         
1189         yaz_oi_APDU(apdu, &p);
1190         
1191         if ((p0=yaz_oi_update(p, assoc->encode, NULL, 0, 0))) {
1192             ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
1193             
1194             p0->which = Z_OtherInfo_externallyDefinedInfo;
1195             p0->information.externallyDefinedInfo =
1196                 assoc->init->charneg_response;
1197         }
1198         ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
1199         strcat(options, " negotiation");
1200     }
1201
1202     if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
1203     {
1204         ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
1205         assoc->version = 2; /* 1 & 2 are equivalent */
1206     }
1207     if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
1208     {
1209         ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
1210         assoc->version = 2;
1211     }
1212     if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
1213     {
1214         ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
1215         assoc->version = 3;
1216     }
1217
1218     yaz_log(LOG_LOG, "Negotiated to v%d: %s", assoc->version, options);
1219     assoc->maximumRecordSize = *req->maximumRecordSize;
1220     if (assoc->maximumRecordSize > control_block->maxrecordsize)
1221         assoc->maximumRecordSize = control_block->maxrecordsize;
1222     assoc->preferredMessageSize = *req->preferredMessageSize;
1223     if (assoc->preferredMessageSize > assoc->maximumRecordSize)
1224         assoc->preferredMessageSize = assoc->maximumRecordSize;
1225
1226 #if 0
1227     assoc->maximumRecordSize = 3000000;
1228     assoc->preferredMessageSize = 3000000;
1229 #endif
1230
1231     resp->preferredMessageSize = &assoc->preferredMessageSize;
1232     resp->maximumRecordSize = &assoc->maximumRecordSize;
1233
1234     resp->implementationName = "GFS/YAZ";
1235
1236     if (assoc->init->implementation_id)
1237     {
1238         char *nv = (char *)
1239             odr_malloc (assoc->encode,
1240                         strlen(assoc->init->implementation_id) + 10 + 
1241                                strlen(resp->implementationId));
1242         sprintf (nv, "%s / %s",
1243                  resp->implementationId, assoc->init->implementation_id);
1244         resp->implementationId = nv;
1245     }
1246     if (assoc->init->implementation_name)
1247     {
1248         char *nv = (char *)
1249             odr_malloc (assoc->encode,
1250                         strlen(assoc->init->implementation_name) + 10 + 
1251                                strlen(resp->implementationName));
1252         sprintf (nv, "%s / %s",
1253                  resp->implementationName, assoc->init->implementation_name);
1254         resp->implementationName = nv;
1255     }
1256     if (assoc->init->implementation_version)
1257     {
1258         char *nv = (char *)
1259             odr_malloc (assoc->encode,
1260                         strlen(assoc->init->implementation_version) + 10 + 
1261                                strlen(resp->implementationVersion));
1262         sprintf (nv, "YAZ %s / %s",
1263                  resp->implementationVersion,
1264                  assoc->init->implementation_version);
1265         resp->implementationVersion = nv;
1266     }
1267
1268     if (binitres->errcode)
1269     {
1270         yaz_log(LOG_LOG, "Connection rejected by backend.");
1271         *resp->result = 0;
1272         assoc->state = ASSOC_DEAD;
1273     }
1274     else
1275         assoc->state = ASSOC_UP;
1276     return apdu;
1277 }
1278
1279 /*
1280  * These functions should be merged.
1281  */
1282
1283 static void set_addinfo (Z_DefaultDiagFormat *dr, char *addinfo, ODR odr)
1284 {
1285     dr->which = Z_DefaultDiagFormat_v2Addinfo;
1286     dr->u.v2Addinfo = odr_strdup (odr, addinfo ? addinfo : "");
1287 }
1288
1289 /*
1290  * nonsurrogate diagnostic record.
1291  */
1292 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
1293 {
1294     Z_Records *rec = (Z_Records *)
1295         odr_malloc (assoc->encode, sizeof(*rec));
1296     int *err = odr_intdup(assoc->encode, error);
1297     Z_DiagRec *drec = (Z_DiagRec *)
1298         odr_malloc (assoc->encode, sizeof(*drec));
1299     Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
1300         odr_malloc (assoc->encode, sizeof(*dr));
1301
1302     yaz_log(LOG_LOG, "[%d] %s %s%s", error, diagbib1_str(error),
1303         addinfo ? " -- " : "", addinfo ? addinfo : "");
1304     rec->which = Z_Records_NSD;
1305     rec->u.nonSurrogateDiagnostic = dr;
1306     dr->diagnosticSetId =
1307         yaz_oidval_to_z3950oid (assoc->encode, CLASS_DIAGSET, VAL_BIB1);
1308     dr->condition = err;
1309     set_addinfo (dr, addinfo, assoc->encode);
1310     return rec;
1311 }
1312
1313 /*
1314  * surrogate diagnostic.
1315  */
1316 static Z_NamePlusRecord *surrogatediagrec(association *assoc, char *dbname,
1317                                           int error, char *addinfo)
1318 {
1319     Z_NamePlusRecord *rec = (Z_NamePlusRecord *)
1320         odr_malloc (assoc->encode, sizeof(*rec));
1321     int *err = odr_intdup(assoc->encode, error);
1322     Z_DiagRec *drec = (Z_DiagRec *)odr_malloc (assoc->encode, sizeof(*drec));
1323     Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
1324         odr_malloc (assoc->encode, sizeof(*dr));
1325     
1326     yaz_log(LOG_DEBUG, "SurrogateDiagnotic: %d -- %s", error, addinfo);
1327     rec->databaseName = dbname;
1328     rec->which = Z_NamePlusRecord_surrogateDiagnostic;
1329     rec->u.surrogateDiagnostic = drec;
1330     drec->which = Z_DiagRec_defaultFormat;
1331     drec->u.defaultFormat = dr;
1332     dr->diagnosticSetId =
1333         yaz_oidval_to_z3950oid (assoc->encode, CLASS_DIAGSET, VAL_BIB1);
1334     dr->condition = err;
1335     set_addinfo (dr, addinfo, assoc->encode);
1336
1337     return rec;
1338 }
1339
1340 /*
1341  * multiple nonsurrogate diagnostics.
1342  */
1343 static Z_DiagRecs *diagrecs(association *assoc, int error, char *addinfo)
1344 {
1345     Z_DiagRecs *recs = (Z_DiagRecs *)odr_malloc (assoc->encode, sizeof(*recs));
1346     int *err = odr_intdup(assoc->encode, error);
1347     Z_DiagRec **recp = (Z_DiagRec **)odr_malloc (assoc->encode, sizeof(*recp));
1348     Z_DiagRec *drec = (Z_DiagRec *)odr_malloc (assoc->encode, sizeof(*drec));
1349     Z_DefaultDiagFormat *rec = (Z_DefaultDiagFormat *)
1350         odr_malloc (assoc->encode, sizeof(*rec));
1351
1352     yaz_log(LOG_DEBUG, "DiagRecs: %d -- %s", error, addinfo ? addinfo : "");
1353
1354     recs->num_diagRecs = 1;
1355     recs->diagRecs = recp;
1356     recp[0] = drec;
1357     drec->which = Z_DiagRec_defaultFormat;
1358     drec->u.defaultFormat = rec;
1359
1360     rec->diagnosticSetId =
1361         yaz_oidval_to_z3950oid (assoc->encode, CLASS_DIAGSET, VAL_BIB1);
1362     rec->condition = err;
1363
1364     rec->which = Z_DefaultDiagFormat_v2Addinfo;
1365     rec->u.v2Addinfo = odr_strdup (assoc->encode, addinfo ? addinfo : "");
1366     return recs;
1367 }
1368
1369 static Z_Records *pack_records(association *a, char *setname, int start,
1370                                int *num, Z_RecordComposition *comp,
1371                                int *next, int *pres, oid_value format,
1372                                Z_ReferenceId *referenceId,
1373                                int *oid)
1374 {
1375     int recno, total_length = 0, toget = *num, dumped_records = 0;
1376     Z_Records *records =
1377         (Z_Records *) odr_malloc (a->encode, sizeof(*records));
1378     Z_NamePlusRecordList *reclist =
1379         (Z_NamePlusRecordList *) odr_malloc (a->encode, sizeof(*reclist));
1380     Z_NamePlusRecord **list =
1381         (Z_NamePlusRecord **) odr_malloc (a->encode, sizeof(*list) * toget);
1382
1383     records->which = Z_Records_DBOSD;
1384     records->u.databaseOrSurDiagnostics = reclist;
1385     reclist->num_records = 0;
1386     reclist->records = list;
1387     *pres = Z_PRES_SUCCESS;
1388     *num = 0;
1389     *next = 0;
1390
1391     yaz_log(LOG_LOG, "Request to pack %d+%d+%s", start, toget, setname);
1392     yaz_log(LOG_DEBUG, "pms=%d, mrs=%d", a->preferredMessageSize,
1393         a->maximumRecordSize);
1394     for (recno = start; reclist->num_records < toget; recno++)
1395     {
1396         bend_fetch_rr freq;
1397         Z_NamePlusRecord *thisrec;
1398         int this_length = 0;
1399         /*
1400          * we get the number of bytes allocated on the stream before any
1401          * allocation done by the backend - this should give us a reasonable
1402          * idea of the total size of the data so far.
1403          */
1404         total_length = odr_total(a->encode) - dumped_records;
1405         freq.errcode = 0;
1406         freq.errstring = 0;
1407         freq.basename = 0;
1408         freq.len = 0;
1409         freq.record = 0;
1410         freq.last_in_set = 0;
1411         freq.setname = setname;
1412         freq.surrogate_flag = 0;
1413         freq.number = recno;
1414         freq.comp = comp;
1415         freq.request_format = format;
1416         freq.request_format_raw = oid;
1417         freq.output_format = format;
1418         freq.output_format_raw = 0;
1419         freq.stream = a->encode;
1420         freq.print = a->print;
1421         freq.surrogate_flag = 0;
1422         freq.referenceId = referenceId;
1423         (*a->init->bend_fetch)(a->backend, &freq);
1424         /* backend should be able to signal whether error is system-wide
1425            or only pertaining to current record */
1426         if (freq.errcode)
1427         {
1428             if (!freq.surrogate_flag)
1429             {
1430                 char s[20];
1431                 *pres = Z_PRES_FAILURE;
1432                 /* for 'present request out of range',
1433                    set addinfo to record position if not set */
1434                 if (freq.errcode == 13 && freq.errstring == 0)
1435                 {
1436                     sprintf (s, "%d", recno);
1437                     freq.errstring = s;
1438                 }
1439                 return diagrec(a, freq.errcode, freq.errstring);
1440             }
1441             reclist->records[reclist->num_records] =
1442                 surrogatediagrec(a, freq.basename, freq.errcode,
1443                                  freq.errstring);
1444             reclist->num_records++;
1445             *next = freq.last_in_set ? 0 : recno + 1;
1446             continue;
1447         }
1448         if (freq.len >= 0)
1449             this_length = freq.len;
1450         else
1451             this_length = odr_total(a->encode) - total_length;
1452         yaz_log(LOG_DEBUG, "  fetched record, len=%d, total=%d",
1453             this_length, total_length);
1454         if (this_length + total_length > a->preferredMessageSize)
1455         {
1456             /* record is small enough, really */
1457             if (this_length <= a->preferredMessageSize)
1458             {
1459                 yaz_log(LOG_DEBUG, "  Dropped last normal-sized record");
1460                 *pres = Z_PRES_PARTIAL_2;
1461                 break;
1462             }
1463             /* record can only be fetched by itself */
1464             if (this_length < a->maximumRecordSize)
1465             {
1466                 yaz_log(LOG_DEBUG, "  Record > prefmsgsz");
1467                 if (toget > 1)
1468                 {
1469                     yaz_log(LOG_DEBUG, "  Dropped it");
1470                     reclist->records[reclist->num_records] =
1471                          surrogatediagrec(a, freq.basename, 16, 0);
1472                     reclist->num_records++;
1473                     *next = freq.last_in_set ? 0 : recno + 1;
1474                     dumped_records += this_length;
1475                     continue;
1476                 }
1477             }
1478             else /* too big entirely */
1479             {
1480                 yaz_log(LOG_LOG, "Record > maxrcdsz this=%d max=%d", this_length, a->maximumRecordSize);
1481                 reclist->records[reclist->num_records] =
1482                     surrogatediagrec(a, freq.basename, 17, 0);
1483                 reclist->num_records++;
1484                 *next = freq.last_in_set ? 0 : recno + 1;
1485                 dumped_records += this_length;
1486                 continue;
1487             }
1488         }
1489
1490         if (!(thisrec = (Z_NamePlusRecord *)
1491               odr_malloc(a->encode, sizeof(*thisrec))))
1492             return 0;
1493         if (!(thisrec->databaseName = (char *)odr_malloc(a->encode,
1494             strlen(freq.basename) + 1)))
1495             return 0;
1496         strcpy(thisrec->databaseName, freq.basename);
1497         thisrec->which = Z_NamePlusRecord_databaseRecord;
1498
1499         if (freq.output_format_raw)
1500         {
1501             struct oident *ident = oid_getentbyoid(freq.output_format_raw);
1502             freq.output_format = ident->value;
1503         }
1504         thisrec->u.databaseRecord = z_ext_record(a->encode, freq.output_format,
1505                                                  freq.record, freq.len);
1506         if (!thisrec->u.databaseRecord)
1507             return 0;
1508         reclist->records[reclist->num_records] = thisrec;
1509         reclist->num_records++;
1510         *next = freq.last_in_set ? 0 : recno + 1;
1511     }
1512     *num = reclist->num_records;
1513     return records;
1514 }
1515
1516 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
1517     int *fd)
1518 {
1519     Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
1520     bend_search_rr *bsrr = 
1521         (bend_search_rr *)nmem_malloc (reqb->request_mem, sizeof(*bsrr));
1522     
1523     yaz_log(LOG_LOG, "Got SearchRequest.");
1524     bsrr->fd = fd;
1525     bsrr->request = reqb;
1526     bsrr->association = assoc;
1527     bsrr->referenceId = req->referenceId;
1528     save_referenceId (reqb, bsrr->referenceId);
1529
1530     yaz_log (LOG_LOG, "ResultSet '%s'", req->resultSetName);
1531     if (req->databaseNames)
1532     {
1533         int i;
1534         for (i = 0; i < req->num_databaseNames; i++)
1535             yaz_log (LOG_LOG, "Database '%s'", req->databaseNames[i]);
1536     }
1537     yaz_log_zquery(req->query);
1538
1539     if (assoc->init->bend_search)
1540     {
1541         bsrr->setname = req->resultSetName;
1542         bsrr->replace_set = *req->replaceIndicator;
1543         bsrr->num_bases = req->num_databaseNames;
1544         bsrr->basenames = req->databaseNames;
1545         bsrr->query = req->query;
1546         bsrr->stream = assoc->encode;
1547         bsrr->decode = assoc->decode;
1548         bsrr->print = assoc->print;
1549         bsrr->errcode = 0;
1550         bsrr->hits = 0;
1551         bsrr->errstring = NULL;
1552         bsrr->search_info = NULL;
1553         (assoc->init->bend_search)(assoc->backend, bsrr);
1554         if (!bsrr->request)
1555             return 0;
1556     }
1557     return response_searchRequest(assoc, reqb, bsrr, fd);
1558 }
1559
1560 int bend_searchresponse(void *handle, bend_search_rr *bsrr) {return 0;}
1561
1562 /*
1563  * Prepare a searchresponse based on the backend results. We probably want
1564  * to look at making the fetching of records nonblocking as well, but
1565  * so far, we'll keep things simple.
1566  * If bsrt is null, that means we're called in response to a communications
1567  * event, and we'll have to get the response for ourselves.
1568  */
1569 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
1570     bend_search_rr *bsrt, int *fd)
1571 {
1572     Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
1573     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1574     Z_SearchResponse *resp = (Z_SearchResponse *)
1575         odr_malloc (assoc->encode, sizeof(*resp));
1576     int *nulint = odr_intdup (assoc->encode, 0);
1577     bool_t *sr = odr_intdup(assoc->encode, 1);
1578     int *next = odr_intdup(assoc->encode, 0);
1579     int *none = odr_intdup(assoc->encode, Z_RES_NONE);
1580
1581     apdu->which = Z_APDU_searchResponse;
1582     apdu->u.searchResponse = resp;
1583     resp->referenceId = req->referenceId;
1584     resp->additionalSearchInfo = 0;
1585     resp->otherInfo = 0;
1586     *fd = -1;
1587     if (!bsrt && !bend_searchresponse(assoc->backend, bsrt))
1588     {
1589         yaz_log(LOG_FATAL, "Bad result from backend");
1590         return 0;
1591     }
1592     else if (bsrt->errcode)
1593     {
1594         resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
1595         resp->resultCount = nulint;
1596         resp->numberOfRecordsReturned = nulint;
1597         resp->nextResultSetPosition = nulint;
1598         resp->searchStatus = nulint;
1599         resp->resultSetStatus = none;
1600         resp->presentStatus = 0;
1601     }
1602     else
1603     {
1604         int *toget = odr_intdup(assoc->encode, 0);
1605         int *presst = odr_intdup(assoc->encode, 0);
1606         Z_RecordComposition comp, *compp = 0;
1607
1608         yaz_log (LOG_LOG, "resultCount: %d", bsrt->hits);
1609
1610         resp->records = 0;
1611         resp->resultCount = &bsrt->hits;
1612
1613         comp.which = Z_RecordComp_simple;
1614         /* how many records does the user agent want, then? */
1615         if (bsrt->hits <= *req->smallSetUpperBound)
1616         {
1617             *toget = bsrt->hits;
1618             if ((comp.u.simple = req->smallSetElementSetNames))
1619                 compp = &comp;
1620         }
1621         else if (bsrt->hits < *req->largeSetLowerBound)
1622         {
1623             *toget = *req->mediumSetPresentNumber;
1624             if (*toget > bsrt->hits)
1625                 *toget = bsrt->hits;
1626             if ((comp.u.simple = req->mediumSetElementSetNames))
1627                 compp = &comp;
1628         }
1629         else
1630             *toget = 0;
1631
1632         if (*toget && !resp->records)
1633         {
1634             oident *prefformat;
1635             oid_value form;
1636
1637             if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
1638                 form = VAL_NONE;
1639             else
1640                 form = prefformat->value;
1641             resp->records = pack_records(assoc, req->resultSetName, 1,
1642                 toget, compp, next, presst, form, req->referenceId,
1643                                          req->preferredRecordSyntax);
1644             if (!resp->records)
1645                 return 0;
1646             resp->numberOfRecordsReturned = toget;
1647             resp->nextResultSetPosition = next;
1648             resp->searchStatus = sr;
1649             resp->resultSetStatus = 0;
1650             resp->presentStatus = presst;
1651         }
1652         else
1653         {
1654             if (*resp->resultCount)
1655                 *next = 1;
1656             resp->numberOfRecordsReturned = nulint;
1657             resp->nextResultSetPosition = next;
1658             resp->searchStatus = sr;
1659             resp->resultSetStatus = 0;
1660             resp->presentStatus = 0;
1661         }
1662     }
1663     resp->additionalSearchInfo = bsrt->search_info;
1664     return apdu;
1665 }
1666
1667 /*
1668  * Maybe we got a little over-friendly when we designed bend_fetch to
1669  * get only one record at a time. Some backends can optimise multiple-record
1670  * fetches, and at any rate, there is some overhead involved in
1671  * all that selecting and hopping around. Problem is, of course, that the
1672  * frontend can't know ahead of time how many records it'll need to
1673  * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
1674  * is downright lousy as a bulk data transfer protocol.
1675  *
1676  * To start with, we'll do the fetching of records from the backend
1677  * in one operation: To save some trips in and out of the event-handler,
1678  * and to simplify the interface to pack_records. At any rate, asynch
1679  * operation is more fun in operations that have an unpredictable execution
1680  * speed - which is normally more true for search than for present.
1681  */
1682 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
1683                                       int *fd)
1684 {
1685     Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
1686     oident *prefformat;
1687     oid_value form;
1688     Z_APDU *apdu;
1689     Z_PresentResponse *resp;
1690     int *next;
1691     int *num;
1692
1693     yaz_log(LOG_LOG, "Got PresentRequest.");
1694
1695     if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
1696         form = VAL_NONE;
1697     else
1698         form = prefformat->value;
1699     resp = (Z_PresentResponse *)odr_malloc (assoc->encode, sizeof(*resp));
1700     resp->records = 0;
1701     resp->presentStatus = odr_intdup(assoc->encode, 0);
1702     if (assoc->init->bend_present)
1703     {
1704         bend_present_rr *bprr = (bend_present_rr *)
1705             nmem_malloc (reqb->request_mem, sizeof(*bprr));
1706         bprr->setname = req->resultSetId;
1707         bprr->start = *req->resultSetStartPoint;
1708         bprr->number = *req->numberOfRecordsRequested;
1709         bprr->format = form;
1710         bprr->comp = req->recordComposition;
1711         bprr->referenceId = req->referenceId;
1712         bprr->stream = assoc->encode;
1713         bprr->print = assoc->print;
1714         bprr->request = reqb;
1715         bprr->association = assoc;
1716         bprr->errcode = 0;
1717         bprr->errstring = NULL;
1718         (*assoc->init->bend_present)(assoc->backend, bprr);
1719         
1720         if (!bprr->request)
1721             return 0;
1722         if (bprr->errcode)
1723         {
1724             resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
1725             *resp->presentStatus = Z_PRES_FAILURE;
1726         }
1727     }
1728     apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1729     next = odr_intdup(assoc->encode, 0);
1730     num = odr_intdup(assoc->encode, 0);
1731     
1732     apdu->which = Z_APDU_presentResponse;
1733     apdu->u.presentResponse = resp;
1734     resp->referenceId = req->referenceId;
1735     resp->otherInfo = 0;
1736     
1737     if (!resp->records)
1738     {
1739         *num = *req->numberOfRecordsRequested;
1740         resp->records =
1741             pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
1742                      num, req->recordComposition, next, resp->presentStatus,
1743                          form, req->referenceId, req->preferredRecordSyntax);
1744     }
1745     if (!resp->records)
1746         return 0;
1747     resp->numberOfRecordsReturned = num;
1748     resp->nextResultSetPosition = next;
1749     
1750     return apdu;
1751 }
1752
1753 /*
1754  * Scan was implemented rather in a hurry, and with support for only the basic
1755  * elements of the service in the backend API. Suggestions are welcome.
1756  */
1757 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
1758 {
1759     Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
1760     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1761     Z_ScanResponse *res = (Z_ScanResponse *)
1762         odr_malloc (assoc->encode, sizeof(*res));
1763     int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
1764     int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
1765     Z_ListEntries *ents = (Z_ListEntries *)
1766         odr_malloc (assoc->encode, sizeof(*ents));
1767     Z_DiagRecs *diagrecs_p = NULL;
1768     oident *attset;
1769     bend_scan_rr *bsrr = (bend_scan_rr *)
1770         odr_malloc (assoc->encode, sizeof(*bsrr));
1771
1772     yaz_log(LOG_LOG, "Got ScanRequest");
1773
1774     apdu->which = Z_APDU_scanResponse;
1775     apdu->u.scanResponse = res;
1776     res->referenceId = req->referenceId;
1777
1778     /* if step is absent, set it to 0 */
1779     res->stepSize = odr_intdup(assoc->encode, 0);
1780     if (req->stepSize)
1781         *res->stepSize = *req->stepSize;
1782
1783     res->scanStatus = scanStatus;
1784     res->numberOfEntriesReturned = numberOfEntriesReturned;
1785     res->positionOfTerm = 0;
1786     res->entries = ents;
1787     ents->num_entries = 0;
1788     ents->entries = NULL;
1789     ents->num_nonsurrogateDiagnostics = 0;
1790     ents->nonsurrogateDiagnostics = NULL;
1791     res->attributeSet = 0;
1792     res->otherInfo = 0;
1793
1794     if (req->databaseNames)
1795     {
1796         int i;
1797         for (i = 0; i < req->num_databaseNames; i++)
1798             yaz_log (LOG_LOG, "Database '%s'", req->databaseNames[i]);
1799     }
1800     bsrr->num_bases = req->num_databaseNames;
1801     bsrr->basenames = req->databaseNames;
1802     bsrr->num_entries = *req->numberOfTermsRequested;
1803     bsrr->term = req->termListAndStartPoint;
1804     bsrr->referenceId = req->referenceId;
1805     bsrr->stream = assoc->encode;
1806     bsrr->print = assoc->print;
1807     bsrr->step_size = res->stepSize;
1808     if (req->attributeSet &&
1809         (attset = oid_getentbyoid(req->attributeSet)) &&
1810         (attset->oclass == CLASS_ATTSET || attset->oclass == CLASS_GENERAL))
1811         bsrr->attributeset = attset->value;
1812     else
1813         bsrr->attributeset = VAL_NONE;
1814     log_scan_term (req->termListAndStartPoint, bsrr->attributeset);
1815     bsrr->term_position = req->preferredPositionInResponse ?
1816         *req->preferredPositionInResponse : 1;
1817     ((int (*)(void *, bend_scan_rr *))
1818      (*assoc->init->bend_scan))(assoc->backend, bsrr);
1819     if (bsrr->errcode)
1820         diagrecs_p = diagrecs(assoc, bsrr->errcode, bsrr->errstring);
1821     else
1822     {
1823         int i;
1824         Z_Entry **tab = (Z_Entry **)
1825             odr_malloc (assoc->encode, sizeof(*tab) * bsrr->num_entries);
1826         
1827         if (bsrr->status == BEND_SCAN_PARTIAL)
1828             *scanStatus = Z_Scan_partial_5;
1829         else
1830             *scanStatus = Z_Scan_success;
1831         ents->entries = tab;
1832         ents->num_entries = bsrr->num_entries;
1833         res->numberOfEntriesReturned = &ents->num_entries;          
1834         res->positionOfTerm = &bsrr->term_position;
1835         for (i = 0; i < bsrr->num_entries; i++)
1836         {
1837             Z_Entry *e;
1838             Z_TermInfo *t;
1839             Odr_oct *o;
1840             
1841             tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
1842             if (bsrr->entries[i].occurrences >= 0)
1843             {
1844                 e->which = Z_Entry_termInfo;
1845                 e->u.termInfo = t = (Z_TermInfo *)
1846                     odr_malloc(assoc->encode, sizeof(*t));
1847                 t->suggestedAttributes = 0;
1848                 t->displayTerm = 0;
1849                 t->alternativeTerm = 0;
1850                 t->byAttributes = 0;
1851                 t->otherTermInfo = 0;
1852                 t->globalOccurrences = &bsrr->entries[i].occurrences;
1853                 t->term = (Z_Term *)
1854                     odr_malloc(assoc->encode, sizeof(*t->term));
1855                 t->term->which = Z_Term_general;
1856                 t->term->u.general = o =
1857                     (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
1858                 o->buf = (unsigned char *)
1859                     odr_malloc(assoc->encode, o->len = o->size =
1860                                strlen(bsrr->entries[i].term));
1861                 memcpy(o->buf, bsrr->entries[i].term, o->len);
1862                 yaz_log(LOG_DEBUG, "  term #%d: '%s' (%d)", i,
1863                          bsrr->entries[i].term, bsrr->entries[i].occurrences);
1864             }
1865             else
1866             {
1867                 Z_DiagRecs *drecs = diagrecs (assoc,
1868                                               bsrr->entries[i].errcode,
1869                                               bsrr->entries[i].errstring);
1870                 assert (drecs->num_diagRecs == 1);
1871                 e->which = Z_Entry_surrogateDiagnostic;
1872                 assert (drecs->diagRecs[0]);
1873                 e->u.surrogateDiagnostic = drecs->diagRecs[0];
1874             }
1875         }
1876     }
1877     if (diagrecs_p)
1878     {
1879         ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
1880         ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
1881     }
1882     return apdu;
1883 }
1884
1885 static Z_APDU *process_sortRequest(association *assoc, request *reqb,
1886     int *fd)
1887 {
1888     Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
1889     Z_SortResponse *res = (Z_SortResponse *)
1890         odr_malloc (assoc->encode, sizeof(*res));
1891     bend_sort_rr *bsrr = (bend_sort_rr *)
1892         odr_malloc (assoc->encode, sizeof(*bsrr));
1893
1894     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1895
1896     yaz_log(LOG_LOG, "Got SortRequest.");
1897
1898     bsrr->num_input_setnames = req->num_inputResultSetNames;
1899     bsrr->input_setnames = req->inputResultSetNames;
1900     bsrr->referenceId = req->referenceId;
1901     bsrr->output_setname = req->sortedResultSetName;
1902     bsrr->sort_sequence = req->sortSequence;
1903     bsrr->stream = assoc->encode;
1904     bsrr->print = assoc->print;
1905
1906     bsrr->sort_status = Z_SortStatus_failure;
1907     bsrr->errcode = 0;
1908     bsrr->errstring = 0;
1909     
1910     (*assoc->init->bend_sort)(assoc->backend, bsrr);
1911     
1912     res->referenceId = bsrr->referenceId;
1913     res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
1914     res->resultSetStatus = 0;
1915     if (bsrr->errcode)
1916     {
1917         Z_DiagRecs *dr = diagrecs (assoc, bsrr->errcode, bsrr->errstring);
1918         res->diagnostics = dr->diagRecs;
1919         res->num_diagnostics = dr->num_diagRecs;
1920     }
1921     else
1922     {
1923         res->num_diagnostics = 0;
1924         res->diagnostics = 0;
1925     }
1926     res->otherInfo = 0;
1927
1928     apdu->which = Z_APDU_sortResponse;
1929     apdu->u.sortResponse = res;
1930     return apdu;
1931 }
1932
1933 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
1934     int *fd)
1935 {
1936     Z_DeleteResultSetRequest *req =
1937         reqb->apdu_request->u.deleteResultSetRequest;
1938     Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
1939         odr_malloc (assoc->encode, sizeof(*res));
1940     bend_delete_rr *bdrr = (bend_delete_rr *)
1941         odr_malloc (assoc->encode, sizeof(*bdrr));
1942     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1943
1944     yaz_log(LOG_LOG, "Got DeleteRequest.");
1945
1946     bdrr->num_setnames = req->num_resultSetList;
1947     bdrr->setnames = req->resultSetList;
1948     bdrr->stream = assoc->encode;
1949     bdrr->print = assoc->print;
1950     bdrr->function = *req->deleteFunction;
1951     bdrr->referenceId = req->referenceId;
1952     bdrr->statuses = 0;
1953     if (bdrr->num_setnames > 0)
1954     {
1955         int i;
1956         bdrr->statuses = (int*) 
1957             odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
1958                        bdrr->num_setnames);
1959         for (i = 0; i < bdrr->num_setnames; i++)
1960             bdrr->statuses[i] = 0;
1961     }
1962     (*assoc->init->bend_delete)(assoc->backend, bdrr);
1963     
1964     res->referenceId = req->referenceId;
1965
1966     res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
1967
1968     res->deleteListStatuses = 0;
1969     if (bdrr->num_setnames > 0)
1970     {
1971         int i;
1972         res->deleteListStatuses = (Z_ListStatuses *)
1973             odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
1974         res->deleteListStatuses->num = bdrr->num_setnames;
1975         res->deleteListStatuses->elements =
1976             (Z_ListStatus **)
1977             odr_malloc (assoc->encode, 
1978                         sizeof(*res->deleteListStatuses->elements) *
1979                         bdrr->num_setnames);
1980         for (i = 0; i<bdrr->num_setnames; i++)
1981         {
1982             res->deleteListStatuses->elements[i] =
1983                 (Z_ListStatus *)
1984                 odr_malloc (assoc->encode,
1985                             sizeof(**res->deleteListStatuses->elements));
1986             res->deleteListStatuses->elements[i]->status = bdrr->statuses+i;
1987             res->deleteListStatuses->elements[i]->id =
1988                 odr_strdup (assoc->encode, bdrr->setnames[i]);
1989             
1990         }
1991     }
1992     res->numberNotDeleted = 0;
1993     res->bulkStatuses = 0;
1994     res->deleteMessage = 0;
1995     res->otherInfo = 0;
1996
1997     apdu->which = Z_APDU_deleteResultSetResponse;
1998     apdu->u.deleteResultSetResponse = res;
1999     return apdu;
2000 }
2001
2002 static void process_close(association *assoc, request *reqb)
2003 {
2004     Z_Close *req = reqb->apdu_request->u.close;
2005     static char *reasons[] =
2006     {
2007         "finished",
2008         "shutdown",
2009         "systemProblem",
2010         "costLimit",
2011         "resources",
2012         "securityViolation",
2013         "protocolError",
2014         "lackOfActivity",
2015         "peerAbort",
2016         "unspecified"
2017     };
2018
2019     yaz_log(LOG_LOG, "Got Close, reason %s, message %s",
2020         reasons[*req->closeReason], req->diagnosticInformation ?
2021         req->diagnosticInformation : "NULL");
2022     if (assoc->version < 3) /* to make do_force respond with close */
2023         assoc->version = 3;
2024     do_close_req(assoc, Z_Close_finished,
2025                  "Association terminated by client", reqb);
2026 }
2027
2028 void save_referenceId (request *reqb, Z_ReferenceId *refid)
2029 {
2030     if (refid)
2031     {
2032         reqb->len_refid = refid->len;
2033         reqb->refid = (char *)nmem_malloc (reqb->request_mem, refid->len);
2034         memcpy (reqb->refid, refid->buf, refid->len);
2035     }
2036     else
2037     {
2038         reqb->len_refid = 0;
2039         reqb->refid = NULL;
2040     }
2041 }
2042
2043 void bend_request_send (bend_association a, bend_request req, Z_APDU *res)
2044 {
2045     process_z_response (a, req, res);
2046 }
2047
2048 bend_request bend_request_mk (bend_association a)
2049 {
2050     request *nreq = request_get (&a->outgoing);
2051     nreq->request_mem = nmem_create ();
2052     return nreq;
2053 }
2054
2055 Z_ReferenceId *bend_request_getid (ODR odr, bend_request req)
2056 {
2057     Z_ReferenceId *id;
2058     if (!req->refid)
2059         return 0;
2060     id = (Odr_oct *)odr_malloc (odr, sizeof(*odr));
2061     id->buf = (unsigned char *)odr_malloc (odr, req->len_refid);
2062     id->len = id->size = req->len_refid;
2063     memcpy (id->buf, req->refid, req->len_refid);
2064     return id;
2065 }
2066
2067 void bend_request_destroy (bend_request *req)
2068 {
2069     nmem_destroy((*req)->request_mem);
2070     request_release(*req);
2071     *req = NULL;
2072 }
2073
2074 int bend_backend_respond (bend_association a, bend_request req)
2075 {
2076     char *msg;
2077     int r;
2078     r = process_z_request (a, req, &msg);
2079     if (r < 0)
2080         yaz_log (LOG_WARN, "%s", msg);
2081     return r;
2082 }
2083
2084 void bend_request_setdata(bend_request r, void *p)
2085 {
2086     r->clientData = p;
2087 }
2088
2089 void *bend_request_getdata(bend_request r)
2090 {
2091     return r->clientData;
2092 }
2093
2094 static Z_APDU *process_segmentRequest (association *assoc, request *reqb)
2095 {
2096     bend_segment_rr req;
2097
2098     req.segment = reqb->apdu_request->u.segmentRequest;
2099     req.stream = assoc->encode;
2100     req.decode = assoc->decode;
2101     req.print = assoc->print;
2102     req.association = assoc;
2103     
2104     (*assoc->init->bend_segment)(assoc->backend, &req);
2105
2106     return 0;
2107 }
2108
2109 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd)
2110 {
2111     bend_esrequest_rr esrequest;
2112
2113     Z_ExtendedServicesRequest *req =
2114         reqb->apdu_request->u.extendedServicesRequest;
2115     Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
2116
2117     Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
2118
2119     yaz_log(LOG_DEBUG,"inside Process esRequest");
2120
2121     esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
2122     esrequest.stream = assoc->encode;
2123     esrequest.decode = assoc->decode;
2124     esrequest.print = assoc->print;
2125     esrequest.errcode = 0;
2126     esrequest.errstring = NULL;
2127     esrequest.request = reqb;
2128     esrequest.association = assoc;
2129     esrequest.taskPackage = 0;
2130     esrequest.referenceId = req->referenceId;
2131     
2132     (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
2133     
2134     /* If the response is being delayed, return NULL */
2135     if (esrequest.request == NULL)
2136         return(NULL);
2137
2138     resp->referenceId = req->referenceId;
2139
2140     if (esrequest.errcode == -1)
2141     {
2142         /* Backend service indicates request will be processed */
2143         yaz_log(LOG_DEBUG,"Request could be processed...Accepted !");
2144         *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
2145     }
2146     else if (esrequest.errcode == 0)
2147     {
2148         /* Backend service indicates request will be processed */
2149         yaz_log(LOG_DEBUG,"Request could be processed...Done !");
2150         *resp->operationStatus = Z_ExtendedServicesResponse_done;
2151     }
2152     else
2153     {
2154         Z_DiagRecs *diagRecs = diagrecs (assoc, esrequest.errcode,
2155                                          esrequest.errstring);
2156
2157         /* Backend indicates error, request will not be processed */
2158         yaz_log(LOG_DEBUG,"Request could not be processed...failure !");
2159         *resp->operationStatus = Z_ExtendedServicesResponse_failure;
2160         resp->num_diagnostics = diagRecs->num_diagRecs;
2161         resp->diagnostics = diagRecs->diagRecs;
2162     }
2163     /* Do something with the members of bend_extendedservice */
2164     if (esrequest.taskPackage)
2165         resp->taskPackage = z_ext_record (assoc->encode, VAL_EXTENDED,
2166                                          (const char *)  esrequest.taskPackage,
2167                                           -1);
2168     yaz_log(LOG_DEBUG,"Send the result apdu");
2169     return apdu;
2170 }
2171