Added support for multi-homed YAZ frontend server. A backend config
[yaz-moved-to-github.git] / src / seshigh.c
1 /*
2  * Copyright (C) 1995-2005, Index Data ApS
3  * See the file LICENSE for details.
4  *
5  * $Id: seshigh.c,v 1.47 2005-02-01 14:46:47 adam Exp $
6  */
7 /**
8  * \file seshigh.c
9  * \brief Implements GFS session logic.
10  *
11  * Frontend server logic.
12  *
13  * This code receives incoming APDUs, and handles client requests by means
14  * of the backend API.
15  *
16  * Some of the code is getting quite involved, compared to simpler servers -
17  * primarily because it is asynchronous both in the communication with
18  * the user and the backend. We think the complexity will pay off in
19  * the form of greater flexibility when more asynchronous facilities
20  * are implemented.
21  *
22  * Memory management has become somewhat involved. In the simple case, where
23  * only one PDU is pending at a time, it will simply reuse the same memory,
24  * once it has found its working size. When we enable multiple concurrent
25  * operations, perhaps even with multiple parallel calls to the backend, it
26  * will maintain a pool of buffers for encoding and decoding, trying to
27  * minimize memory allocation/deallocation during normal operation.
28  *
29  */
30
31 #include <stdlib.h>
32 #include <stdio.h>
33 #include <assert.h>
34 #include <ctype.h>
35
36 #if HAVE_SYS_TYPES_H
37 #include <sys/types.h>
38 #endif
39 #if HAVE_SYS_STAT_H
40 #include <sys/stat.h>
41 #endif
42
43 #ifdef WIN32
44 #include <io.h>
45 #define S_ISREG(x) (x & _S_IFREG)
46 #include <process.h>
47 #endif
48
49 #if HAVE_UNISTD_H
50 #include <unistd.h>
51 #endif
52
53 #include <yaz/yconfig.h>
54 #include <yaz/xmalloc.h>
55 #include <yaz/comstack.h>
56 #include "eventl.h"
57 #include "session.h"
58 #include <yaz/proto.h>
59 #include <yaz/oid.h>
60 #include <yaz/log.h>
61 #include <yaz/logrpn.h>
62 #include <yaz/statserv.h>
63 #include <yaz/diagbib1.h>
64 #include <yaz/charneg.h>
65 #include <yaz/otherinfo.h>
66 #include <yaz/yaz-util.h>
67 #include <yaz/pquery.h>
68
69 #include <yaz/srw.h>
70 #include <yaz/backend.h>
71
72 static void process_gdu_request(association *assoc, request *req);
73 static int process_z_request(association *assoc, request *req, char **msg);
74 void backend_response(IOCHAN i, int event);
75 static int process_gdu_response(association *assoc, request *req, Z_GDU *res);
76 static int process_z_response(association *assoc, request *req, Z_APDU *res);
77 static Z_APDU *process_initRequest(association *assoc, request *reqb);
78 static Z_External *init_diagnostics(ODR odr, int errcode,
79                                     const char *errstring);
80 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
81     int *fd);
82 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
83     bend_search_rr *bsrr, int *fd);
84 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
85     int *fd);
86 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
87 static Z_APDU *process_sortRequest(association *assoc, request *reqb, int *fd);
88 static void process_close(association *assoc, request *reqb);
89 void save_referenceId (request *reqb, Z_ReferenceId *refid);
90 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
91     int *fd);
92 static Z_APDU *process_segmentRequest (association *assoc, request *reqb);
93
94 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd);
95
96 /* dynamic logging levels */
97 static int logbits_set = 0;
98 static int log_session = 0; 
99 static int log_request = 0; /* one-line logs for requests */
100 static int log_requestdetail = 0;  /* more detailed stuff */
101
102 /** get_logbits sets global loglevel bits */
103 static void get_logbits()
104 { /* needs to be called after parsing cmd-line args that can set loglevels!*/
105     if (!logbits_set)
106     {
107         logbits_set = 1;
108         log_session = yaz_log_module_level("session"); 
109         log_request = yaz_log_module_level("request"); 
110         log_requestdetail = yaz_log_module_level("requestdetail"); 
111     }
112 }
113
114 static void wr_diag(WRBUF w, int error, const char *addinfo)
115 {
116     wrbuf_printf(w, "ERROR [%d] %s%s%s",
117                  error, diagbib1_str(error),
118                  addinfo ? "--" : "", addinfo ? addinfo : "");
119 }
120
121
122 /*
123  * Create and initialize a new association-handle.
124  *  channel  : iochannel for the current line.
125  *  link     : communications channel.
126  * Returns: 0 or a new association handle.
127  */
128 association *create_association(IOCHAN channel, COMSTACK link,
129                                 const char *apdufile)
130 {
131     association *anew;
132
133     if (!logbits_set)
134         get_logbits();
135     if (!(anew = (association *)xmalloc(sizeof(*anew))))
136         return 0;
137     anew->init = 0;
138     anew->version = 0;
139     anew->last_control = 0;
140     anew->client_chan = channel;
141     anew->client_link = link;
142     anew->cs_get_mask = 0;
143     anew->cs_put_mask = 0;
144     anew->cs_accept_mask = 0;
145     if (!(anew->decode = odr_createmem(ODR_DECODE)) ||
146         !(anew->encode = odr_createmem(ODR_ENCODE)))
147         return 0;
148     if (apdufile && *apdufile)
149     {
150         FILE *f;
151
152         if (!(anew->print = odr_createmem(ODR_PRINT)))
153             return 0;
154         if (*apdufile == '@')
155         {
156             odr_setprint(anew->print, yaz_log_file());
157         }       
158         else if (*apdufile != '-')
159         {
160             char filename[256];
161             sprintf(filename, "%.200s.%ld", apdufile, (long)getpid());
162             if (!(f = fopen(filename, "w")))
163             {
164                 yaz_log(YLOG_WARN|YLOG_ERRNO, "%s", filename);
165                 return 0;
166             }
167             setvbuf(f, 0, _IONBF, 0);
168             odr_setprint(anew->print, f);
169         }
170     }
171     else
172         anew->print = 0;
173     anew->input_buffer = 0;
174     anew->input_buffer_len = 0;
175     anew->backend = 0;
176     anew->state = ASSOC_NEW;
177     request_initq(&anew->incoming);
178     request_initq(&anew->outgoing);
179     anew->proto = cs_getproto(link);
180     return anew;
181 }
182
183 /*
184  * Free association and release resources.
185  */
186 void destroy_association(association *h)
187 {
188     statserv_options_block *cb = statserv_getcontrol();
189     request *req;
190
191     xfree(h->init);
192     odr_destroy(h->decode);
193     odr_destroy(h->encode);
194     if (h->print)
195         odr_destroy(h->print);
196     if (h->input_buffer)
197     xfree(h->input_buffer);
198     if (h->backend)
199         (*cb->bend_close)(h->backend);
200     while ((req = request_deq(&h->incoming)))
201         request_release(req);
202     while ((req = request_deq(&h->outgoing)))
203         request_release(req);
204     request_delq(&h->incoming);
205     request_delq(&h->outgoing);
206     xfree(h);
207     xmalloc_trav("session closed");
208     if (cb && cb->one_shot)
209     {
210         exit (0);
211     }
212 }
213
214 static void do_close_req(association *a, int reason, char *message,
215                          request *req)
216 {
217     Z_APDU apdu;
218     Z_Close *cls = zget_Close(a->encode);
219     
220     /* Purge request queue */
221     while (request_deq(&a->incoming));
222     while (request_deq(&a->outgoing));
223     if (a->version >= 3)
224     {
225         yaz_log(log_requestdetail, "Sending Close PDU, reason=%d, message=%s",
226             reason, message ? message : "none");
227         apdu.which = Z_APDU_close;
228         apdu.u.close = cls;
229         *cls->closeReason = reason;
230         cls->diagnosticInformation = message;
231         process_z_response(a, req, &apdu);
232         iochan_settimeout(a->client_chan, 20);
233     }
234     else
235     {
236         request_release(req);
237         yaz_log(log_requestdetail, "v2 client. No Close PDU");
238         iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
239     }
240     a->state = ASSOC_DEAD;
241 }
242
243 static void do_close(association *a, int reason, char *message)
244 {
245     request *req = request_get(&a->outgoing);
246     do_close_req (a, reason, message, req);
247 }
248
249 /*
250  * This is where PDUs from the client are read and the further
251  * processing is initiated. Flow of control moves down through the
252  * various process_* functions below, until the encoded result comes back up
253  * to the output handler in here.
254  * 
255  *  h     : the I/O channel that has an outstanding event.
256  *  event : the current outstanding event.
257  */
258 void ir_session(IOCHAN h, int event)
259 {
260     int res;
261     association *assoc = (association *)iochan_getdata(h);
262     COMSTACK conn = assoc->client_link;
263     request *req;
264
265     assert(h && conn && assoc);
266     if (event == EVENT_TIMEOUT)
267     {
268         if (assoc->state != ASSOC_UP)
269         {
270             yaz_log(YLOG_DEBUG, "Final timeout - closing connection.");
271             /* do we need to lod this at all */
272             cs_close(conn);
273             destroy_association(assoc);
274             iochan_destroy(h);
275         }
276         else
277         {
278             yaz_log(log_session, "Session idle too long. Sending close.");
279             do_close(assoc, Z_Close_lackOfActivity, 0);
280         }
281         return;
282     }
283     if (event & assoc->cs_accept_mask)
284     {
285         if (!cs_accept (conn))
286         {
287             yaz_log (YLOG_WARN, "accept failed");
288             destroy_association(assoc);
289             iochan_destroy(h);
290         }
291         iochan_clearflag (h, EVENT_OUTPUT);
292         if (conn->io_pending) 
293         {   /* cs_accept didn't complete */
294             assoc->cs_accept_mask = 
295                 ((conn->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
296                 ((conn->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
297
298             iochan_setflag (h, assoc->cs_accept_mask);
299         }
300         else
301         {   /* cs_accept completed. Prepare for reading (cs_get) */
302             assoc->cs_accept_mask = 0;
303             assoc->cs_get_mask = EVENT_INPUT;
304             iochan_setflag (h, assoc->cs_get_mask);
305         }
306         return;
307     }
308     if ((event & assoc->cs_get_mask) || (event & EVENT_WORK)) /* input */
309     {
310         if ((assoc->cs_put_mask & EVENT_INPUT) == 0 && (event & assoc->cs_get_mask))
311         {
312             yaz_log(YLOG_DEBUG, "ir_session (input)");
313             /* We aren't speaking to this fellow */
314             if (assoc->state == ASSOC_DEAD)
315             {
316                 yaz_log(log_session, "Connection closed - end of session");
317                 cs_close(conn);
318                 destroy_association(assoc);
319                 iochan_destroy(h);
320                 return;
321             }
322             assoc->cs_get_mask = EVENT_INPUT;
323             if ((res = cs_get(conn, &assoc->input_buffer,
324                 &assoc->input_buffer_len)) <= 0)
325             {
326                 yaz_log(log_session, "Connection closed by client");
327                 cs_close(conn);
328                 destroy_association(assoc);
329                 iochan_destroy(h);
330                 return;
331             }
332             else if (res == 1) /* incomplete read - wait for more  */
333             {
334                 if (conn->io_pending & CS_WANT_WRITE)
335                     assoc->cs_get_mask |= EVENT_OUTPUT;
336                 iochan_setflag(h, assoc->cs_get_mask);
337                 return;
338             }
339             if (cs_more(conn)) /* more stuff - call us again later, please */
340                 iochan_setevent(h, EVENT_INPUT);
341                 
342             /* we got a complete PDU. Let's decode it */
343             yaz_log(YLOG_DEBUG, "Got PDU, %d bytes: lead=%02X %02X %02X", res,
344                             assoc->input_buffer[0] & 0xff,
345                             assoc->input_buffer[1] & 0xff,
346                             assoc->input_buffer[2] & 0xff);
347             req = request_get(&assoc->incoming); /* get a new request */
348             odr_reset(assoc->decode);
349             odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
350             if (!z_GDU(assoc->decode, &req->gdu_request, 0, 0))
351             {
352                 yaz_log(YLOG_WARN, "ODR error on incoming PDU: %s [element %s] "
353                         "[near byte %d] ",
354                         odr_errmsg(odr_geterror(assoc->decode)),
355                         odr_getelement(assoc->decode),
356                         odr_offset(assoc->decode));
357                 if (assoc->decode->error != OHTTP)
358                 {
359                     yaz_log(YLOG_WARN, "PDU dump:");
360                     odr_dumpBER(yaz_log_file(), assoc->input_buffer, res);
361                     request_release(req);
362                     do_close(assoc, Z_Close_protocolError,"Malformed package");
363                 }
364                 else
365                 {
366                     Z_GDU *p = z_get_HTTP_Response(assoc->encode, 400);
367                     assoc->state = ASSOC_DEAD;
368                     process_gdu_response(assoc, req, p);
369                 }
370                 return;
371             }
372             req->request_mem = odr_extract_mem(assoc->decode);
373             if (assoc->print) 
374             {
375                 if (!z_GDU(assoc->print, &req->gdu_request, 0, 0))
376                     yaz_log(YLOG_WARN, "ODR print error: %s", 
377                        odr_errmsg(odr_geterror(assoc->print)));
378                 odr_reset(assoc->print);
379             }
380             request_enq(&assoc->incoming, req);
381         }
382
383         /* can we do something yet? */
384         req = request_head(&assoc->incoming);
385         if (req->state == REQUEST_IDLE)
386         {
387             request_deq(&assoc->incoming);
388             process_gdu_request(assoc, req);
389         }
390     }
391     if (event & assoc->cs_put_mask)
392     {
393         request *req = request_head(&assoc->outgoing);
394
395         assoc->cs_put_mask = 0;
396         yaz_log(YLOG_DEBUG, "ir_session (output)");
397         req->state = REQUEST_PENDING;
398         switch (res = cs_put(conn, req->response, req->len_response))
399         {
400         case -1:
401             yaz_log(log_session, "Connection closed by client");
402             cs_close(conn);
403             destroy_association(assoc);
404             iochan_destroy(h);
405             break;
406         case 0: /* all sent - release the request structure */
407             yaz_log(YLOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
408 #if 0
409             yaz_log(YLOG_DEBUG, "HTTP out:\n%.*s", req->len_response,
410                     req->response);
411 #endif
412             nmem_destroy(req->request_mem);
413             request_deq(&assoc->outgoing);
414             request_release(req);
415             if (!request_head(&assoc->outgoing))
416             {   /* restore mask for cs_get operation ... */
417                 iochan_clearflag(h, EVENT_OUTPUT|EVENT_INPUT);
418                 iochan_setflag(h, assoc->cs_get_mask);
419                 if (assoc->state == ASSOC_DEAD)
420                     iochan_setevent(assoc->client_chan, EVENT_TIMEOUT);
421             }
422             else
423             {
424                 assoc->cs_put_mask = EVENT_OUTPUT;
425             }
426             break;
427         default:
428             if (conn->io_pending & CS_WANT_WRITE)
429                 assoc->cs_put_mask |= EVENT_OUTPUT;
430             if (conn->io_pending & CS_WANT_READ)
431                 assoc->cs_put_mask |= EVENT_INPUT;
432             iochan_setflag(h, assoc->cs_put_mask);
433         }
434     }
435     if (event & EVENT_EXCEPT)
436     {
437         yaz_log(YLOG_WARN, "ir_session (exception)");
438         cs_close(conn);
439         destroy_association(assoc);
440         iochan_destroy(h);
441     }
442 }
443
444 static int process_z_request(association *assoc, request *req, char **msg);
445
446
447 static void assoc_init_reset(association *assoc)
448 {
449     xfree (assoc->init);
450     assoc->init = (bend_initrequest *) xmalloc (sizeof(*assoc->init));
451
452     assoc->init->stream = assoc->encode;
453     assoc->init->print = assoc->print;
454     assoc->init->auth = 0;
455     assoc->init->referenceId = 0;
456     assoc->init->implementation_version = 0;
457     assoc->init->implementation_id = 0;
458     assoc->init->implementation_name = 0;
459     assoc->init->bend_sort = NULL;
460     assoc->init->bend_search = NULL;
461     assoc->init->bend_present = NULL;
462     assoc->init->bend_esrequest = NULL;
463     assoc->init->bend_delete = NULL;
464     assoc->init->bend_scan = NULL;
465     assoc->init->bend_segment = NULL;
466     assoc->init->bend_fetch = NULL;
467     assoc->init->bend_explain = NULL;
468     assoc->init->bend_srw_scan = NULL;
469
470     assoc->init->charneg_request = NULL;
471     assoc->init->charneg_response = NULL;
472
473     assoc->init->decode = assoc->decode;
474     assoc->init->peer_name = 
475         odr_strdup (assoc->encode, cs_addrstr(assoc->client_link));
476
477     yaz_log(log_requestdetail, "peer %s", assoc->init->peer_name);
478
479
480 }
481
482 static int srw_bend_init(association *assoc, Z_SRW_diagnostic **d, int *num)
483 {
484     statserv_options_block *cb = statserv_getcontrol();
485     if (!assoc->init)
486     {
487         const char *encoding = "UTF-8";
488         Z_External *ce;
489         bend_initresult *binitres;
490
491         yaz_log(YLOG_LOG, "srw_bend_init config=%s", cb->configname);
492         assoc_init_reset(assoc);
493         
494         assoc->maximumRecordSize = 3000000;
495         assoc->preferredMessageSize = 3000000;
496 #if 1
497         ce = yaz_set_proposal_charneg(assoc->decode, &encoding, 1, 0, 0, 1);
498         assoc->init->charneg_request = ce->u.charNeg3;
499 #endif
500         assoc->backend = 0;
501         if (!(binitres = (*cb->bend_init)(assoc->init)))
502         {
503             assoc->state = ASSOC_DEAD;
504             yaz_add_srw_diagnostic(assoc->encode, d, num, 3, 0);
505             return 0;
506         }
507         assoc->backend = binitres->handle;
508         if (binitres->errcode)
509         {
510             assoc->state = ASSOC_DEAD;
511             yaz_add_srw_diagnostic(assoc->encode, d, num, binitres->errcode,
512                                    binitres->errstring);
513             return 0;
514         }
515         return 1;
516     }
517     return 1;
518 }
519
520 static int srw_bend_fetch(association *assoc, int pos,
521                           Z_SRW_searchRetrieveRequest *srw_req,
522                           Z_SRW_record *record)
523 {
524     bend_fetch_rr rr;
525     ODR o = assoc->encode;
526
527     rr.setname = "default";
528     rr.number = pos;
529     rr.referenceId = 0;
530     rr.request_format = VAL_TEXT_XML;
531     rr.request_format_raw = yaz_oidval_to_z3950oid(assoc->decode,
532                                                    CLASS_TRANSYN,
533                                                    VAL_TEXT_XML);
534     rr.comp = (Z_RecordComposition *)
535             odr_malloc(assoc->decode, sizeof(*rr.comp));
536     rr.comp->which = Z_RecordComp_complex;
537     rr.comp->u.complex = (Z_CompSpec *)
538             odr_malloc(assoc->decode, sizeof(Z_CompSpec));
539     rr.comp->u.complex->selectAlternativeSyntax = (bool_t *)
540         odr_malloc(assoc->encode, sizeof(bool_t));
541     *rr.comp->u.complex->selectAlternativeSyntax = 0;    
542     rr.comp->u.complex->num_dbSpecific = 0;
543     rr.comp->u.complex->dbSpecific = 0;
544     rr.comp->u.complex->num_recordSyntax = 0; 
545     rr.comp->u.complex->recordSyntax = 0;
546
547     rr.comp->u.complex->generic = (Z_Specification *) 
548             odr_malloc(assoc->decode, sizeof(Z_Specification));
549
550     /* schema uri = recordSchema (or NULL if recordSchema is not given) */
551     rr.comp->u.complex->generic->which = Z_Schema_uri;
552     rr.comp->u.complex->generic->schema.uri = srw_req->recordSchema;
553
554     /* ESN = recordSchema if recordSchema is present */
555     rr.comp->u.complex->generic->elementSpec = 0;
556     if (srw_req->recordSchema)
557     {
558         rr.comp->u.complex->generic->elementSpec = 
559             (Z_ElementSpec *) odr_malloc(assoc->encode, sizeof(Z_ElementSpec));
560         rr.comp->u.complex->generic->elementSpec->which = 
561             Z_ElementSpec_elementSetName;
562         rr.comp->u.complex->generic->elementSpec->u.elementSetName =
563             srw_req->recordSchema;
564     }
565     
566     rr.stream = assoc->encode;
567     rr.print = assoc->print;
568
569     rr.basename = 0;
570     rr.len = 0;
571     rr.record = 0;
572     rr.last_in_set = 0;
573     rr.output_format = VAL_TEXT_XML;
574     rr.output_format_raw = 0;
575     rr.errcode = 0;
576     rr.errstring = 0;
577     rr.surrogate_flag = 0;
578     rr.schema = srw_req->recordSchema;
579
580     if (!assoc->init->bend_fetch)
581         return 1;
582
583     (*assoc->init->bend_fetch)(assoc->backend, &rr);
584
585     if (rr.errcode && rr.surrogate_flag)
586     {
587         int code = yaz_diag_bib1_to_srw(rr.errcode);
588         const char *message = yaz_diag_srw_str(code);
589         int len = 200;
590         if (message)
591             len += strlen(message);
592         if (rr.errstring)
593             len += strlen(rr.errstring);
594
595         record->recordData_buf = odr_malloc(o, len);
596         
597         sprintf(record->recordData_buf, "<diagnostic "
598                 "xmlns=\"http://www.loc.gov/zing/srw/diagnostic/\">\n"
599                 " <uri>info:srw/diagnostic/1/%d</uri>\n", code);
600         if (rr.errstring)
601             sprintf(record->recordData_buf + strlen(record->recordData_buf),
602                     " <details>%s</details>\n", rr.errstring);
603         if (message)
604             sprintf(record->recordData_buf + strlen(record->recordData_buf),
605                     " <message>%s</message>\n", message);
606         sprintf(record->recordData_buf + strlen(record->recordData_buf),
607                 "</diagnostic>\n");
608         record->recordData_len = strlen(record->recordData_buf);
609         record->recordPosition = odr_intdup(o, pos);
610         record->recordSchema = "info:srw/schema/1/diagnostics-v1.1";
611         return 0;
612     }
613     else if (rr.len >= 0)
614     {
615         record->recordData_buf = rr.record;
616         record->recordData_len = rr.len;
617         record->recordPosition = odr_intdup(o, pos);
618         if (rr.schema)
619             record->recordSchema = odr_strdup(o, rr.schema);
620         else
621             record->recordSchema = 0;
622     }
623     return rr.errcode;
624 }
625
626 static void srw_bend_search(association *assoc, request *req,
627                             Z_SRW_searchRetrieveRequest *srw_req,
628                             Z_SRW_searchRetrieveResponse *srw_res,
629                             int *http_code)
630 {
631     int srw_error = 0;
632     Z_External *ext;
633     
634     *http_code = 200;
635     yaz_log(log_requestdetail, "Got SRW SearchRetrieveRequest");
636     srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics);
637     if (srw_req->sort_type != Z_SRW_sort_type_none)
638         yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
639                                &srw_res->num_diagnostics, 80, 0);
640     else if (srw_res->num_diagnostics == 0 && assoc->init)
641     {
642         bend_search_rr rr;
643         rr.setname = "default";
644         rr.replace_set = 1;
645         rr.num_bases = 1;
646         rr.basenames = &srw_req->database;
647         rr.referenceId = 0;
648         
649         rr.query = (Z_Query *) odr_malloc (assoc->decode, sizeof(*rr.query));
650         
651         if (srw_req->query_type == Z_SRW_query_type_cql)
652         {
653             ext = (Z_External *) odr_malloc(assoc->decode, sizeof(*ext));
654             ext->direct_reference = odr_getoidbystr(assoc->decode, 
655                                                     "1.2.840.10003.16.2");
656             ext->indirect_reference = 0;
657             ext->descriptor = 0;
658             ext->which = Z_External_CQL;
659             ext->u.cql = srw_req->query.cql;
660             
661             rr.query->which = Z_Query_type_104;
662             rr.query->u.type_104 =  ext;
663         }
664         else if (srw_req->query_type == Z_SRW_query_type_pqf)
665         {
666             Z_RPNQuery *RPNquery;
667             YAZ_PQF_Parser pqf_parser;
668             
669             pqf_parser = yaz_pqf_create ();
670             
671             RPNquery = yaz_pqf_parse (pqf_parser, assoc->decode,
672                                       srw_req->query.pqf);
673             if (!RPNquery)
674             {
675                 const char *pqf_msg;
676                 size_t off;
677                 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
678                 yaz_log(log_requestdetail, "Parse error %d %s near offset %d",
679                         code, pqf_msg, off);
680                 srw_error = 10;
681             }
682             
683             rr.query->which = Z_Query_type_1;
684             rr.query->u.type_1 =  RPNquery;
685             
686             yaz_pqf_destroy (pqf_parser);
687         }
688         else
689         {
690             rr.query->u.type_1 = 0;
691             yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
692                                    &srw_res->num_diagnostics, 11, 0);
693         }
694         if (rr.query->u.type_1)
695         {
696             rr.stream = assoc->encode;
697             rr.decode = assoc->decode;
698             rr.print = assoc->print;
699             rr.request = req;
700             rr.association = assoc;
701             rr.fd = 0;
702             rr.hits = 0;
703             rr.errcode = 0;
704             rr.errstring = 0;
705             rr.search_info = 0;
706             yaz_log_zquery_level(log_requestdetail,rr.query);
707             
708             (assoc->init->bend_search)(assoc->backend, &rr);
709             if (rr.errcode)
710             {
711                 if (rr.errcode == 109) /* database unavailable */
712                 {
713                     *http_code = 404;
714                 }
715                 else
716                 {
717                     srw_error = yaz_diag_bib1_to_srw (rr.errcode);
718                     yaz_add_srw_diagnostic(assoc->encode,
719                                            &srw_res->diagnostics,
720                                            &srw_res->num_diagnostics,
721                                            srw_error, rr.errstring);
722                 }
723             }
724             else
725             {
726                 int number = srw_req->maximumRecords ? *srw_req->maximumRecords : 0;
727                 int start = srw_req->startRecord ? *srw_req->startRecord : 1;
728                 
729                 yaz_log(log_requestdetail, "Request to pack %d+%d out of %d",
730                         start, number, rr.hits);
731                 
732                 srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
733                 if (number > 0)
734                 {
735                     int i;
736                     
737                     if (start > rr.hits)
738                     {
739                         yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
740                                                &srw_res->num_diagnostics,
741                                                61, 0);
742                     }
743                     else
744                     {
745                         int j = 0;
746                         int packing = Z_SRW_recordPacking_string;
747                         if (start + number > rr.hits)
748                             number = rr.hits - start + 1;
749                         if (srw_req->recordPacking && 
750                             !strcmp(srw_req->recordPacking, "xml"))
751                             packing = Z_SRW_recordPacking_XML;
752                         srw_res->records = (Z_SRW_record *)
753                             odr_malloc(assoc->encode,
754                                        number * sizeof(*srw_res->records));
755                         for (i = 0; i<number; i++)
756                         {
757                         int errcode;
758                         
759                         srw_res->records[j].recordPacking = packing;
760                         srw_res->records[j].recordData_buf = 0;
761                         yaz_log(YLOG_DEBUG, "srw_bend_fetch %d", i+start);
762                         errcode = srw_bend_fetch(assoc, i+start, srw_req,
763                                                  srw_res->records + j);
764                         if (errcode)
765                         {
766                             yaz_add_srw_diagnostic(assoc->encode,
767                                                    &srw_res->diagnostics,
768                                                    &srw_res->num_diagnostics,
769                                                    yaz_diag_bib1_to_srw (errcode),
770                                                    rr.errstring);
771
772                             break;
773                         }
774                         if (srw_res->records[j].recordData_buf)
775                             j++;
776                         }
777                         srw_res->num_records = j;
778                         if (!j)
779                             srw_res->records = 0;
780                     }
781                 }
782             }
783         }
784     }
785     if (log_request)
786     {
787         const char *querystr = "?";
788         const char *querytype = "?";
789         WRBUF wr = wrbuf_alloc();
790
791         switch (srw_req->query_type)
792         {
793         case Z_SRW_query_type_cql:
794             querytype = "CQL";
795             querystr = srw_req->query.cql;
796             break;
797         case Z_SRW_query_type_pqf:
798             querytype = "PQF";
799             querystr = srw_req->query.pqf;
800             break;
801         }
802         wrbuf_printf(wr, "SRWSearch ");
803         if (srw_res->num_diagnostics)
804             wrbuf_printf(wr, "ERROR %s", srw_res->diagnostics[0].uri);
805         else if (*http_code != 200)
806             wrbuf_printf(wr, "ERROR info:http/%d", *http_code);
807         else if (srw_res->numberOfRecords)
808         {
809             wrbuf_printf(wr, "OK %d",
810                          (srw_res->numberOfRecords ?
811                           *srw_res->numberOfRecords : 0));
812         }
813         wrbuf_printf(wr, " %s %d+%d", 
814                      (srw_res->resultSetId ?
815                       srw_res->resultSetId : "-"),
816                      (srw_req->startRecord ? *srw_req->startRecord : 1), 
817                      srw_res->num_records);
818         yaz_log(log_request, "%s %s: %s", wrbuf_buf(wr), querytype, querystr);
819         wrbuf_free(wr, 1);
820     }
821 }
822
823 static void srw_bend_explain(association *assoc, request *req,
824                              Z_SRW_explainRequest *srw_req,
825                              Z_SRW_explainResponse *srw_res,
826                              int *http_code)
827 {
828     yaz_log(log_requestdetail, "Got SRW ExplainRequest");
829     *http_code = 404;
830     srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics);
831     if (assoc->init && assoc->init->bend_explain)
832     {
833         bend_explain_rr rr;
834
835         rr.stream = assoc->encode;
836         rr.decode = assoc->decode;
837         rr.print = assoc->print;
838         rr.explain_buf = 0;
839         rr.database = srw_req->database;
840         rr.schema = "http://explain.z3950.org/dtd/2.0/";
841         (*assoc->init->bend_explain)(assoc->backend, &rr);
842         if (rr.explain_buf)
843         {
844             int packing = Z_SRW_recordPacking_string;
845             if (srw_req->recordPacking && 
846                 !strcmp(srw_req->recordPacking, "xml"))
847                 packing = Z_SRW_recordPacking_XML;
848             srw_res->record.recordSchema = rr.schema;
849             srw_res->record.recordPacking = packing;
850             srw_res->record.recordData_buf = rr.explain_buf;
851             srw_res->record.recordData_len = strlen(rr.explain_buf);
852             srw_res->record.recordPosition = 0;
853             *http_code = 200;
854         }
855     }
856 }
857
858 static void srw_bend_scan(association *assoc, request *req,
859                           Z_SRW_scanRequest *srw_req,
860                           Z_SRW_scanResponse *srw_res,
861                           int *http_code)
862 {
863     yaz_log(log_requestdetail, "Got SRW ScanRequest");
864
865     *http_code = 200;
866     srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics);
867     if (srw_res->num_diagnostics == 0 && assoc->init)
868     {
869         struct scan_entry *save_entries;
870
871         bend_scan_rr *bsrr = (bend_scan_rr *)
872             odr_malloc (assoc->encode, sizeof(*bsrr));
873         bsrr->num_bases = 1;
874         bsrr->basenames = &srw_req->database;
875
876         bsrr->num_entries = srw_req->maximumTerms ?
877             *srw_req->maximumTerms : 10;
878         bsrr->term_position = srw_req->responsePosition ?
879             *srw_req->responsePosition : 1;
880
881         bsrr->errcode = 0;
882         bsrr->errstring = 0;
883         bsrr->referenceId = 0;
884         bsrr->stream = assoc->encode;
885         bsrr->print = assoc->print;
886         bsrr->step_size = odr_intdup(assoc->decode, 0);
887         bsrr->entries = 0;
888
889         if (bsrr->num_entries > 0) 
890         {
891             int i;
892             bsrr->entries = odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
893                                        bsrr->num_entries);
894             for (i = 0; i<bsrr->num_entries; i++)
895             {
896                 bsrr->entries[i].term = 0;
897                 bsrr->entries[i].occurrences = 0;
898                 bsrr->entries[i].errcode = 0;
899                 bsrr->entries[i].errstring = 0;
900                 bsrr->entries[i].display_term = 0;
901             }
902         }
903         save_entries = bsrr->entries;  /* save it so we can compare later */
904
905         if (srw_req->query_type == Z_SRW_query_type_pqf &&
906             assoc->init->bend_scan)
907         {
908             Odr_oid *scan_attributeSet = 0;
909             oident *attset;
910             YAZ_PQF_Parser pqf_parser = yaz_pqf_create();
911             
912             bsrr->term = yaz_pqf_scan(pqf_parser, assoc->decode,
913                                       &scan_attributeSet, 
914                                       srw_req->scanClause.pqf); 
915             if (scan_attributeSet &&
916                 (attset = oid_getentbyoid(scan_attributeSet)) &&
917                 (attset->oclass == CLASS_ATTSET ||
918                  attset->oclass == CLASS_GENERAL))
919                 bsrr->attributeset = attset->value;
920             else
921                 bsrr->attributeset = VAL_NONE;
922             yaz_pqf_destroy(pqf_parser);
923             bsrr->scanClause = 0;
924             ((int (*)(void *, bend_scan_rr *))
925              (*assoc->init->bend_scan))(assoc->backend, bsrr);
926         }
927         else if (srw_req->query_type == Z_SRW_query_type_cql
928                  && assoc->init->bend_srw_scan)
929         {
930             bsrr->term = 0;
931             bsrr->attributeset = VAL_NONE;
932             bsrr->scanClause = srw_req->scanClause.cql;
933             ((int (*)(void *, bend_scan_rr *))
934              (*assoc->init->bend_srw_scan))(assoc->backend, bsrr);
935         }
936         else
937         {
938             yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
939                                    &srw_res->num_diagnostics, 4, "scan");
940         }
941         if (bsrr->errcode)
942         {
943             int srw_error;
944             if (bsrr->errcode == 109) /* database unavailable */
945             {
946                 *http_code = 404;
947                 return;
948             }
949             srw_error = yaz_diag_bib1_to_srw (bsrr->errcode);
950
951             yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
952                                    &srw_res->num_diagnostics,
953                                    srw_error, bsrr->errstring);
954         }
955         else if (srw_res->num_diagnostics == 0 && bsrr->num_entries)
956         {
957             int i;
958             srw_res->terms = (Z_SRW_scanTerm*)
959                 odr_malloc(assoc->encode, sizeof(*srw_res->terms) *
960                            bsrr->num_entries);
961
962             srw_res->num_terms =  bsrr->num_entries;
963             for (i = 0; i<bsrr->num_entries; i++)
964             {
965                 Z_SRW_scanTerm *t = srw_res->terms + i;
966                 t->value = odr_strdup(assoc->encode, bsrr->entries[i].term);
967                 t->numberOfRecords =
968                     odr_intdup(assoc->encode, bsrr->entries[i].occurrences);
969                 t->displayTerm = 0;
970                 if (save_entries == bsrr->entries && 
971                     bsrr->entries[i].display_term)
972                 {
973                     /* the entries was _not_ set by the handler. So it's
974                        safe to test for new member display_term. It is
975                        NULL'ed by us.
976                     */
977                     t->displayTerm = odr_strdup(assoc->encode, 
978                                                 bsrr->entries[i].display_term);
979                 }
980                 t->whereInList = 0;
981             }
982         }
983     }
984     if (log_request)
985     {
986         WRBUF wr = wrbuf_alloc();
987         const char *querytype = 0;
988         const char *querystr = 0;
989
990         switch(srw_req->query_type)
991         {
992         case Z_SRW_query_type_pqf:
993             querytype = "PQF";
994             querystr = srw_req->scanClause.pqf;
995             break;
996         case Z_SRW_query_type_cql:
997             querytype = "CQL";
998             querystr = srw_req->scanClause.cql;
999             break;
1000         default:
1001             querytype = "Unknown";
1002             querystr = "";
1003         }
1004         wrbuf_printf(wr, "SRWScan %d+%d",
1005                      (srw_req->responsePosition ? 
1006                       *srw_req->responsePosition : 1),
1007                      (srw_req->maximumTerms ?
1008                       *srw_req->maximumTerms : 1));
1009         if (srw_res->num_diagnostics)
1010             wrbuf_printf(wr, " ERROR %s", srw_res->diagnostics[0].uri);
1011         else
1012             wrbuf_printf(wr, " OK -");
1013         wrbuf_printf(wr, " %s: %s", querytype, querystr);
1014         yaz_log(log_request, "%s", wrbuf_buf(wr) );
1015         wrbuf_free(wr, 1);
1016     }
1017
1018 }
1019
1020
1021 static void process_http_request(association *assoc, request *req)
1022 {
1023     Z_HTTP_Request *hreq = req->gdu_request->u.HTTP_Request;
1024     ODR o = assoc->encode;
1025     int r = 2;  /* 2=NOT TAKEN, 1=TAKEN, 0=SOAP TAKEN */
1026     Z_SRW_PDU *sr = 0;
1027     Z_SOAP *soap_package = 0;
1028     Z_GDU *p = 0;
1029     char *charset = 0;
1030     Z_HTTP_Response *hres = 0;
1031     int keepalive = 1;
1032     char *stylesheet = 0;
1033     Z_SRW_diagnostic *diagnostic = 0;
1034     int num_diagnostic = 0;
1035     const char *host = z_HTTP_header_lookup(hreq->headers, "Host");
1036
1037     if (!control_association(assoc, host, 0))
1038     {
1039         p = z_get_HTTP_Response(o, 404);
1040         r = 1;
1041     }
1042     if (r == 2 && !strcmp(hreq->path, "/test")) 
1043     {   
1044         p = z_get_HTTP_Response(o, 200);
1045         hres = p->u.HTTP_Response;
1046         hres->content_buf = "1234567890\n";
1047         hres->content_len = strlen(hres->content_buf);
1048         r = 1;
1049     }
1050     if (r == 2)
1051     {
1052         r = yaz_srw_decode(hreq, &sr, &soap_package, assoc->decode, &charset);
1053         yaz_log(YLOG_DEBUG, "yaz_srw_decode returned %d", r);
1054     }
1055     if (r == 2)  /* not taken */
1056     {
1057         r = yaz_sru_decode(hreq, &sr, &soap_package, assoc->decode, &charset,
1058                            &diagnostic, &num_diagnostic);
1059         yaz_log(YLOG_DEBUG, "yaz_sru_decode returned %d", r);
1060     }
1061     if (r == 0)  /* decode SRW/SRU OK .. */
1062     {
1063         int http_code = 200;
1064         if (sr->which == Z_SRW_searchRetrieve_request)
1065         {
1066             Z_SRW_PDU *res =
1067                 yaz_srw_get(assoc->encode, Z_SRW_searchRetrieve_response);
1068
1069             stylesheet = sr->u.request->stylesheet;
1070             if (num_diagnostic)
1071             {
1072                 res->u.response->diagnostics = diagnostic;
1073                 res->u.response->num_diagnostics = num_diagnostic;
1074             }
1075             else
1076             {
1077                 srw_bend_search(assoc, req, sr->u.request, res->u.response, 
1078                                 &http_code);
1079             }
1080             if (http_code == 200)
1081                 soap_package->u.generic->p = res;
1082         }
1083         else if (sr->which == Z_SRW_explain_request)
1084         {
1085             Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_explain_response);
1086             stylesheet = sr->u.explain_request->stylesheet;
1087             if (num_diagnostic)
1088             {   
1089                 res->u.explain_response->diagnostics = diagnostic;
1090                 res->u.explain_response->num_diagnostics = num_diagnostic;
1091             }
1092             srw_bend_explain(assoc, req, sr->u.explain_request,
1093                              res->u.explain_response, &http_code);
1094             if (http_code == 200)
1095                 soap_package->u.generic->p = res;
1096         }
1097         else if (sr->which == Z_SRW_scan_request)
1098         {
1099             Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_scan_response);
1100             stylesheet = sr->u.scan_request->stylesheet;
1101             if (num_diagnostic)
1102             {   
1103                 res->u.scan_response->diagnostics = diagnostic;
1104                 res->u.scan_response->num_diagnostics = num_diagnostic;
1105             }
1106             srw_bend_scan(assoc, req, sr->u.scan_request,
1107                               res->u.scan_response, &http_code);
1108             if (http_code == 200)
1109                 soap_package->u.generic->p = res;
1110         }
1111         else
1112         {
1113             yaz_log(log_request, "SOAP ERROR"); 
1114                /* FIXME - what error, what query */
1115             http_code = 500;
1116             z_soap_error(assoc->encode, soap_package,
1117                          "SOAP-ENV:Client", "Bad method", 0); 
1118         }
1119         if (http_code == 200 || http_code == 500)
1120         {
1121             static Z_SOAP_Handler soap_handlers[3] = {
1122 #if HAVE_XML2
1123                 {"http://www.loc.gov/zing/srw/", 0,
1124                  (Z_SOAP_fun) yaz_srw_codec},
1125                 {"http://www.loc.gov/zing/srw/v1.0/", 0,
1126                  (Z_SOAP_fun) yaz_srw_codec},
1127 #endif
1128                 {0, 0, 0}
1129             };
1130             char ctype[60];
1131             int ret;
1132             p = z_get_HTTP_Response(o, 200);
1133             hres = p->u.HTTP_Response;
1134             ret = z_soap_codec_enc_xsl(assoc->encode, &soap_package,
1135                                        &hres->content_buf, &hres->content_len,
1136                                        soap_handlers, charset, stylesheet);
1137             hres->code = http_code;
1138
1139             strcpy(ctype, "text/xml");
1140             if (charset)
1141             {
1142                 strcat(ctype, "; charset=");
1143                 strcat(ctype, charset);
1144             }
1145             z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1146         }
1147         else
1148             p = z_get_HTTP_Response(o, http_code);
1149     }
1150
1151     if (p == 0)
1152         p = z_get_HTTP_Response(o, 500);
1153     hres = p->u.HTTP_Response;
1154     if (!strcmp(hreq->version, "1.0")) 
1155     {
1156         const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1157         if (v && !strcmp(v, "Keep-Alive"))
1158             keepalive = 1;
1159         else
1160             keepalive = 0;
1161         hres->version = "1.0";
1162     }
1163     else
1164     {
1165         const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1166         if (v && !strcmp(v, "close"))
1167             keepalive = 0;
1168         else
1169             keepalive = 1;
1170         hres->version = "1.1";
1171     }
1172     if (!keepalive)
1173     {
1174         z_HTTP_header_add(o, &hres->headers, "Connection", "close");
1175         assoc->state = ASSOC_DEAD;
1176         assoc->cs_get_mask = 0;
1177     }
1178     else
1179     {
1180         int t;
1181         const char *alive = z_HTTP_header_lookup(hreq->headers, "Keep-Alive");
1182
1183         if (alive && isdigit(*(const unsigned char *) alive))
1184             t = atoi(alive);
1185         else
1186             t = 15;
1187         if (t < 0 || t > 3600)
1188             t = 3600;
1189         iochan_settimeout(assoc->client_chan,t);
1190         z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1191     }
1192     process_gdu_response(assoc, req, p);
1193 }
1194
1195 static void process_gdu_request(association *assoc, request *req)
1196 {
1197     if (req->gdu_request->which == Z_GDU_Z3950)
1198     {
1199         char *msg = 0;
1200         req->apdu_request = req->gdu_request->u.z3950;
1201         if (process_z_request(assoc, req, &msg) < 0)
1202             do_close_req(assoc, Z_Close_systemProblem, msg, req);
1203     }
1204     else if (req->gdu_request->which == Z_GDU_HTTP_Request)
1205         process_http_request(assoc, req);
1206     else
1207     {
1208         do_close_req(assoc, Z_Close_systemProblem, "bad protocol packet", req);
1209     }
1210 }
1211
1212 /*
1213  * Initiate request processing.
1214  */
1215 static int process_z_request(association *assoc, request *req, char **msg)
1216 {
1217     int fd = -1;
1218     Z_APDU *res;
1219     int retval;
1220     
1221     *msg = "Unknown Error";
1222     assert(req && req->state == REQUEST_IDLE);
1223     if (req->apdu_request->which != Z_APDU_initRequest && !assoc->init)
1224     {
1225         *msg = "Missing InitRequest";
1226         return -1;
1227     }
1228     switch (req->apdu_request->which)
1229     {
1230     case Z_APDU_initRequest:
1231         res = process_initRequest(assoc, req); break;
1232     case Z_APDU_searchRequest:
1233         res = process_searchRequest(assoc, req, &fd); break;
1234     case Z_APDU_presentRequest:
1235         res = process_presentRequest(assoc, req, &fd); break;
1236     case Z_APDU_scanRequest:
1237         if (assoc->init->bend_scan)
1238             res = process_scanRequest(assoc, req, &fd);
1239         else
1240         {
1241             *msg = "Cannot handle Scan APDU";
1242             return -1;
1243         }
1244         break;
1245     case Z_APDU_extendedServicesRequest:
1246         if (assoc->init->bend_esrequest)
1247             res = process_ESRequest(assoc, req, &fd);
1248         else
1249         {
1250             *msg = "Cannot handle Extended Services APDU";
1251             return -1;
1252         }
1253         break;
1254     case Z_APDU_sortRequest:
1255         if (assoc->init->bend_sort)
1256             res = process_sortRequest(assoc, req, &fd);
1257         else
1258         {
1259             *msg = "Cannot handle Sort APDU";
1260             return -1;
1261         }
1262         break;
1263     case Z_APDU_close:
1264         process_close(assoc, req);
1265         return 0;
1266     case Z_APDU_deleteResultSetRequest:
1267         if (assoc->init->bend_delete)
1268             res = process_deleteRequest(assoc, req, &fd);
1269         else
1270         {
1271             *msg = "Cannot handle Delete APDU";
1272             return -1;
1273         }
1274         break;
1275     case Z_APDU_segmentRequest:
1276         if (assoc->init->bend_segment)
1277         {
1278             res = process_segmentRequest (assoc, req);
1279         }
1280         else
1281         {
1282             *msg = "Cannot handle Segment APDU";
1283             return -1;
1284         }
1285         break;
1286     case Z_APDU_triggerResourceControlRequest:
1287         return 0;
1288     default:
1289         *msg = "Bad APDU received";
1290         return -1;
1291     }
1292     if (res)
1293     {
1294         yaz_log(YLOG_DEBUG, "  result immediately available");
1295         retval = process_z_response(assoc, req, res);
1296     }
1297     else if (fd < 0)
1298     {
1299         yaz_log(YLOG_DEBUG, "  result unavailble");
1300         retval = 0;
1301     }
1302     else /* no result yet - one will be provided later */
1303     {
1304         IOCHAN chan;
1305
1306         /* Set up an I/O handler for the fd supplied by the backend */
1307
1308         yaz_log(YLOG_DEBUG, "   establishing handler for result");
1309         req->state = REQUEST_PENDING;
1310         if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT, 0)))
1311             abort();
1312         iochan_setdata(chan, assoc);
1313         retval = 0;
1314     }
1315     return retval;
1316 }
1317
1318 /*
1319  * Handle message from the backend.
1320  */
1321 void backend_response(IOCHAN i, int event)
1322 {
1323     association *assoc = (association *)iochan_getdata(i);
1324     request *req = request_head(&assoc->incoming);
1325     Z_APDU *res;
1326     int fd;
1327
1328     yaz_log(YLOG_DEBUG, "backend_response");
1329     assert(assoc && req && req->state != REQUEST_IDLE);
1330     /* determine what it is we're waiting for */
1331     switch (req->apdu_request->which)
1332     {
1333         case Z_APDU_searchRequest:
1334             res = response_searchRequest(assoc, req, 0, &fd); break;
1335 #if 0
1336         case Z_APDU_presentRequest:
1337             res = response_presentRequest(assoc, req, 0, &fd); break;
1338         case Z_APDU_scanRequest:
1339             res = response_scanRequest(assoc, req, 0, &fd); break;
1340 #endif
1341         default:
1342             yaz_log(YLOG_FATAL, "Serious programmer's lapse or bug");
1343             abort();
1344     }
1345     if ((res && process_z_response(assoc, req, res) < 0) || fd < 0)
1346     {
1347         yaz_log(YLOG_WARN, "Fatal error when talking to backend");
1348         do_close(assoc, Z_Close_systemProblem, 0);
1349         iochan_destroy(i);
1350         return;
1351     }
1352     else if (!res) /* no result yet - try again later */
1353     {
1354         yaz_log(YLOG_DEBUG, "   no result yet");
1355         iochan_setfd(i, fd); /* in case fd has changed */
1356     }
1357 }
1358
1359 /*
1360  * Encode response, and transfer the request structure to the outgoing queue.
1361  */
1362 static int process_gdu_response(association *assoc, request *req, Z_GDU *res)
1363 {
1364     odr_setbuf(assoc->encode, req->response, req->size_response, 1);
1365
1366     if (assoc->print)
1367     {
1368         if (!z_GDU(assoc->print, &res, 0, 0))
1369             yaz_log(YLOG_WARN, "ODR print error: %s", 
1370                 odr_errmsg(odr_geterror(assoc->print)));
1371         odr_reset(assoc->print);
1372     }
1373     if (!z_GDU(assoc->encode, &res, 0, 0))
1374     {
1375         yaz_log(YLOG_WARN, "ODR error when encoding PDU: %s [element %s]",
1376                 odr_errmsg(odr_geterror(assoc->decode)),
1377                 odr_getelement(assoc->decode));
1378         return -1;
1379     }
1380     req->response = odr_getbuf(assoc->encode, &req->len_response,
1381         &req->size_response);
1382     odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
1383     odr_reset(assoc->encode);
1384     req->state = REQUEST_IDLE;
1385     request_enq(&assoc->outgoing, req);
1386     /* turn the work over to the ir_session handler */
1387     iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
1388     assoc->cs_put_mask = EVENT_OUTPUT;
1389     /* Is there more work to be done? give that to the input handler too */
1390 #if 1
1391     if (request_head(&assoc->incoming))
1392     {
1393         yaz_log (YLOG_DEBUG, "more work to be done");
1394         iochan_setevent(assoc->client_chan, EVENT_WORK);
1395     }
1396 #endif
1397     return 0;
1398 }
1399
1400 /*
1401  * Encode response, and transfer the request structure to the outgoing queue.
1402  */
1403 static int process_z_response(association *assoc, request *req, Z_APDU *res)
1404 {
1405     Z_GDU *gres = (Z_GDU *) odr_malloc(assoc->encode, sizeof(*res));
1406     gres->which = Z_GDU_Z3950;
1407     gres->u.z3950 = res;
1408
1409     return process_gdu_response(assoc, req, gres);
1410 }
1411
1412 static char *get_vhost(Z_OtherInformation *otherInfo)
1413 {
1414     return yaz_oi_get_string_oidval(&otherInfo, VAL_PROXY, 1, 0);
1415 }
1416
1417 /*
1418  * Handle init request.
1419  * At the moment, we don't check the options
1420  * anywhere else in the code - we just try not to do anything that would
1421  * break a naive client. We'll toss 'em into the association block when
1422  * we need them there.
1423  */
1424 static Z_APDU *process_initRequest(association *assoc, request *reqb)
1425 {
1426     Z_InitRequest *req = reqb->apdu_request->u.initRequest;
1427     Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
1428     Z_InitResponse *resp = apdu->u.initResponse;
1429     bend_initresult *binitres;
1430     char *version;
1431     char options[140];
1432     statserv_options_block *cb = 0;  /* by default no control for backend */
1433
1434     if (control_association(assoc, get_vhost(req->otherInfo), 1))
1435         cb = statserv_getcontrol();  /* got control block for backend */
1436     
1437     yaz_log(log_requestdetail, "Got initRequest");
1438     if (req->implementationId)
1439         yaz_log(log_requestdetail, "Id:        %s",
1440                 req->implementationId);
1441     if (req->implementationName)
1442         yaz_log(log_requestdetail, "Name:      %s",
1443                 req->implementationName);
1444     if (req->implementationVersion)
1445         yaz_log(log_requestdetail, "Version:   %s",
1446                 req->implementationVersion);
1447     
1448     assoc_init_reset(assoc);
1449
1450     assoc->init->auth = req->idAuthentication;
1451     assoc->init->referenceId = req->referenceId;
1452
1453     if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
1454     {
1455         Z_CharSetandLanguageNegotiation *negotiation =
1456             yaz_get_charneg_record (req->otherInfo);
1457         if (negotiation &&
1458             negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
1459             assoc->init->charneg_request = negotiation;
1460     }
1461     
1462     assoc->backend = 0;
1463     if (cb)
1464     {
1465         if (req->implementationVersion)
1466             yaz_log(log_requestdetail, "Config:    %s",
1467                     cb->configname);
1468     
1469         iochan_settimeout(assoc->client_chan, cb->idle_timeout * 60);
1470         
1471         /* we have a backend control block, so call that init function */
1472         if (!(binitres = (*cb->bend_init)(assoc->init)))
1473         {
1474             yaz_log(YLOG_WARN, "Bad response from backend.");
1475             return 0;
1476         }
1477         assoc->backend = binitres->handle;
1478     }
1479     else
1480     {
1481         /* no backend. return error */
1482         binitres = odr_malloc(assoc->encode, sizeof(*binitres));
1483         binitres->errstring = 0;
1484         binitres->errcode = 1;
1485         iochan_settimeout(assoc->client_chan, 10);
1486     }
1487     if ((assoc->init->bend_sort))
1488         yaz_log (YLOG_DEBUG, "Sort handler installed");
1489     if ((assoc->init->bend_search))
1490         yaz_log (YLOG_DEBUG, "Search handler installed");
1491     if ((assoc->init->bend_present))
1492         yaz_log (YLOG_DEBUG, "Present handler installed");   
1493     if ((assoc->init->bend_esrequest))
1494         yaz_log (YLOG_DEBUG, "ESRequest handler installed");   
1495     if ((assoc->init->bend_delete))
1496         yaz_log (YLOG_DEBUG, "Delete handler installed");   
1497     if ((assoc->init->bend_scan))
1498         yaz_log (YLOG_DEBUG, "Scan handler installed");   
1499     if ((assoc->init->bend_segment))
1500         yaz_log (YLOG_DEBUG, "Segment handler installed");   
1501     
1502     resp->referenceId = req->referenceId;
1503     *options = '\0';
1504     /* let's tell the client what we can do */
1505     if (ODR_MASK_GET(req->options, Z_Options_search))
1506     {
1507         ODR_MASK_SET(resp->options, Z_Options_search);
1508         strcat(options, "srch");
1509     }
1510     if (ODR_MASK_GET(req->options, Z_Options_present))
1511     {
1512         ODR_MASK_SET(resp->options, Z_Options_present);
1513         strcat(options, " prst");
1514     }
1515     if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
1516         assoc->init->bend_delete)
1517     {
1518         ODR_MASK_SET(resp->options, Z_Options_delSet);
1519         strcat(options, " del");
1520     }
1521     if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
1522         assoc->init->bend_esrequest)
1523     {
1524         ODR_MASK_SET(resp->options, Z_Options_extendedServices);
1525         strcat (options, " extendedServices");
1526     }
1527     if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
1528     {
1529         ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
1530         strcat(options, " namedresults");
1531     }
1532     if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
1533     {
1534         ODR_MASK_SET(resp->options, Z_Options_scan);
1535         strcat(options, " scan");
1536     }
1537     if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
1538     {
1539         ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
1540         strcat(options, " concurrop");
1541     }
1542     if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
1543     {
1544         ODR_MASK_SET(resp->options, Z_Options_sort);
1545         strcat(options, " sort");
1546     }
1547
1548     if (ODR_MASK_GET(req->options, Z_Options_negotiationModel)
1549         && assoc->init->charneg_response)
1550     {
1551         Z_OtherInformation **p;
1552         Z_OtherInformationUnit *p0;
1553         
1554         yaz_oi_APDU(apdu, &p);
1555         
1556         if ((p0=yaz_oi_update(p, assoc->encode, NULL, 0, 0))) {
1557             ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
1558             
1559             p0->which = Z_OtherInfo_externallyDefinedInfo;
1560             p0->information.externallyDefinedInfo =
1561                 assoc->init->charneg_response;
1562         }
1563         ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
1564         strcat(options, " negotiation");
1565     }
1566         
1567     ODR_MASK_SET(resp->options, Z_Options_triggerResourceCtrl);
1568
1569     if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
1570     {
1571         ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
1572         assoc->version = 1; /* 1 & 2 are equivalent */
1573     }
1574     if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
1575     {
1576         ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
1577         assoc->version = 2;
1578     }
1579     if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
1580     {
1581         ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
1582         assoc->version = 3;
1583     }
1584
1585     yaz_log(log_requestdetail, "Negotiated to v%d: %s", assoc->version, options);
1586     assoc->maximumRecordSize = *req->maximumRecordSize;
1587
1588     if (cb && assoc->maximumRecordSize > cb->maxrecordsize)
1589         assoc->maximumRecordSize = cb->maxrecordsize;
1590     assoc->preferredMessageSize = *req->preferredMessageSize;
1591     if (assoc->preferredMessageSize > assoc->maximumRecordSize)
1592         assoc->preferredMessageSize = assoc->maximumRecordSize;
1593
1594     resp->preferredMessageSize = &assoc->preferredMessageSize;
1595     resp->maximumRecordSize = &assoc->maximumRecordSize;
1596
1597     resp->implementationId = odr_prepend(assoc->encode,
1598                 assoc->init->implementation_id,
1599                 resp->implementationId);
1600
1601     resp->implementationName = odr_prepend(assoc->encode,
1602                 assoc->init->implementation_name,
1603                 odr_prepend(assoc->encode, "GFS", resp->implementationName));
1604
1605     version = odr_strdup(assoc->encode, "$Revision: 1.47 $");
1606     if (strlen(version) > 10)   /* check for unexpanded CVS strings */
1607         version[strlen(version)-2] = '\0';
1608     resp->implementationVersion = odr_prepend(assoc->encode,
1609                 assoc->init->implementation_version,
1610                 odr_prepend(assoc->encode, &version[11],
1611                             resp->implementationVersion));
1612
1613     if (binitres->errcode)
1614     {
1615         assoc->state = ASSOC_DEAD;
1616         resp->userInformationField =
1617             init_diagnostics(assoc->encode, binitres->errcode,
1618                              binitres->errstring);
1619         *resp->result = 0;
1620     }
1621     if (log_request)
1622     {
1623         WRBUF wr = wrbuf_alloc();
1624         wrbuf_printf(wr, "Init ");
1625         if (binitres->errcode)
1626             wrbuf_printf(wr, "ERROR %d", binitres->errcode);
1627         else
1628             wrbuf_printf(wr, "OK -");
1629         wrbuf_printf(wr, " ID:%s Name:%s Version:%s",
1630                      (req->implementationId ? req->implementationId :"-"), 
1631                      (req->implementationName ?
1632                       req->implementationName : "-"),
1633                      (req->implementationVersion ?
1634                       req->implementationVersion : "-")
1635             );
1636         yaz_log(log_request, "%s", wrbuf_buf(wr));
1637         wrbuf_free(wr, 1);
1638     }
1639     return apdu;
1640 }
1641
1642 /*
1643  * Set the specified `errcode' and `errstring' into a UserInfo-1
1644  * external to be returned to the client in accordance with Z35.90
1645  * Implementor Agreement 5 (Returning diagnostics in an InitResponse):
1646  *      http://lcweb.loc.gov/z3950/agency/agree/initdiag.html
1647  */
1648 static Z_External *init_diagnostics(ODR odr, int error, const char *addinfo)
1649 {
1650     yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
1651         addinfo ? " -- " : "", addinfo ? addinfo : "");
1652     return zget_init_diagnostics(odr, error, addinfo);
1653 }
1654
1655 /*
1656  * nonsurrogate diagnostic record.
1657  */
1658 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
1659 {
1660     Z_Records *rec = (Z_Records *) odr_malloc (assoc->encode, sizeof(*rec));
1661
1662     yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
1663             addinfo ? " -- " : "", addinfo ? addinfo : "");
1664
1665     rec->which = Z_Records_NSD;
1666     rec->u.nonSurrogateDiagnostic = zget_DefaultDiagFormat(assoc->encode,
1667                                                            error, addinfo);
1668     return rec;
1669 }
1670
1671 /*
1672  * surrogate diagnostic.
1673  */
1674 static Z_NamePlusRecord *surrogatediagrec(association *assoc, 
1675                                           const char *dbname,
1676                                           int error, const char *addinfo)
1677 {
1678     yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
1679             addinfo ? " -- " : "", addinfo ? addinfo : "");
1680     return zget_surrogateDiagRec(assoc->encode, dbname, error, addinfo);
1681 }
1682
1683 static Z_Records *pack_records(association *a, char *setname, int start,
1684                                int *num, Z_RecordComposition *comp,
1685                                int *next, int *pres, oid_value format,
1686                                Z_ReferenceId *referenceId,
1687                                int *oid, int *errcode)
1688 {
1689     int recno, total_length = 0, toget = *num, dumped_records = 0;
1690     Z_Records *records =
1691         (Z_Records *) odr_malloc (a->encode, sizeof(*records));
1692     Z_NamePlusRecordList *reclist =
1693         (Z_NamePlusRecordList *) odr_malloc (a->encode, sizeof(*reclist));
1694     Z_NamePlusRecord **list =
1695         (Z_NamePlusRecord **) odr_malloc (a->encode, sizeof(*list) * toget);
1696
1697     records->which = Z_Records_DBOSD;
1698     records->u.databaseOrSurDiagnostics = reclist;
1699     reclist->num_records = 0;
1700     reclist->records = list;
1701     *pres = Z_PresentStatus_success;
1702     *num = 0;
1703     *next = 0;
1704
1705     yaz_log(log_requestdetail, "Request to pack %d+%d %s", start, toget, setname);
1706     yaz_log(log_requestdetail, "pms=%d, mrs=%d", a->preferredMessageSize,
1707         a->maximumRecordSize);
1708     for (recno = start; reclist->num_records < toget; recno++)
1709     {
1710         bend_fetch_rr freq;
1711         Z_NamePlusRecord *thisrec;
1712         int this_length = 0;
1713         /*
1714          * we get the number of bytes allocated on the stream before any
1715          * allocation done by the backend - this should give us a reasonable
1716          * idea of the total size of the data so far.
1717          */
1718         total_length = odr_total(a->encode) - dumped_records;
1719         freq.errcode = 0;
1720         freq.errstring = 0;
1721         freq.basename = 0;
1722         freq.len = 0;
1723         freq.record = 0;
1724         freq.last_in_set = 0;
1725         freq.setname = setname;
1726         freq.surrogate_flag = 0;
1727         freq.number = recno;
1728         freq.comp = comp;
1729         freq.request_format = format;
1730         freq.request_format_raw = oid;
1731         freq.output_format = format;
1732         freq.output_format_raw = 0;
1733         freq.stream = a->encode;
1734         freq.print = a->print;
1735         freq.referenceId = referenceId;
1736         freq.schema = 0;
1737         (*a->init->bend_fetch)(a->backend, &freq);
1738         /* backend should be able to signal whether error is system-wide
1739            or only pertaining to current record */
1740         if (freq.errcode)
1741         {
1742             if (!freq.surrogate_flag)
1743             {
1744                 char s[20];
1745                 *pres = Z_PresentStatus_failure;
1746                 /* for 'present request out of range',
1747                    set addinfo to record position if not set */
1748                 if (freq.errcode == 13 && freq.errstring == 0)
1749                 {
1750                     sprintf (s, "%d", recno);
1751                     freq.errstring = s;
1752                 }
1753                 if (errcode)
1754                     *errcode = freq.errcode;
1755                 return diagrec(a, freq.errcode, freq.errstring);
1756             }
1757             reclist->records[reclist->num_records] =
1758                 surrogatediagrec(a, freq.basename, freq.errcode,
1759                                  freq.errstring);
1760             reclist->num_records++;
1761             *next = freq.last_in_set ? 0 : recno + 1;
1762             continue;
1763         }
1764         if (freq.len >= 0)
1765             this_length = freq.len;
1766         else
1767             this_length = odr_total(a->encode) - total_length - dumped_records;
1768         yaz_log(YLOG_DEBUG, "  fetched record, len=%d, total=%d dumped=%d",
1769             this_length, total_length, dumped_records);
1770         if (a->preferredMessageSize > 0 &&
1771                 this_length + total_length > a->preferredMessageSize)
1772         {
1773             /* record is small enough, really */
1774             if (this_length <= a->preferredMessageSize && recno > start)
1775             {
1776                 yaz_log(log_requestdetail, "  Dropped last normal-sized record");
1777                 *pres = Z_PresentStatus_partial_2;
1778                 break;
1779             }
1780             /* record can only be fetched by itself */
1781             if (this_length < a->maximumRecordSize)
1782             {
1783                 yaz_log(log_requestdetail, "  Record > prefmsgsz");
1784                 if (toget > 1)
1785                 {
1786                     yaz_log(YLOG_DEBUG, "  Dropped it");
1787                     reclist->records[reclist->num_records] =
1788                          surrogatediagrec(a, freq.basename, 16, 0);
1789                     reclist->num_records++;
1790                     *next = freq.last_in_set ? 0 : recno + 1;
1791                     dumped_records += this_length;
1792                     continue;
1793                 }
1794             }
1795             else /* too big entirely */
1796             {
1797                 yaz_log(log_requestdetail, "Record > maxrcdsz this=%d max=%d",
1798                         this_length, a->maximumRecordSize);
1799                 reclist->records[reclist->num_records] =
1800                     surrogatediagrec(a, freq.basename, 17, 0);
1801                 reclist->num_records++;
1802                 *next = freq.last_in_set ? 0 : recno + 1;
1803                 dumped_records += this_length;
1804                 continue;
1805             }
1806         }
1807
1808         if (!(thisrec = (Z_NamePlusRecord *)
1809               odr_malloc(a->encode, sizeof(*thisrec))))
1810             return 0;
1811         if (!(thisrec->databaseName = (char *)odr_malloc(a->encode,
1812             strlen(freq.basename) + 1)))
1813             return 0;
1814         strcpy(thisrec->databaseName, freq.basename);
1815         thisrec->which = Z_NamePlusRecord_databaseRecord;
1816
1817         if (freq.output_format_raw)
1818         {
1819             struct oident *ident = oid_getentbyoid(freq.output_format_raw);
1820             freq.output_format = ident->value;
1821         }
1822         thisrec->u.databaseRecord = z_ext_record(a->encode, freq.output_format,
1823                                                  freq.record, freq.len);
1824         if (!thisrec->u.databaseRecord)
1825             return 0;
1826         reclist->records[reclist->num_records] = thisrec;
1827         reclist->num_records++;
1828         *next = freq.last_in_set ? 0 : recno + 1;
1829     }
1830     *num = reclist->num_records;
1831     return records;
1832 }
1833
1834 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
1835     int *fd)
1836 {
1837     Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
1838     bend_search_rr *bsrr = 
1839         (bend_search_rr *)nmem_malloc (reqb->request_mem, sizeof(*bsrr));
1840     
1841     yaz_log(log_requestdetail, "Got SearchRequest.");
1842     bsrr->fd = fd;
1843     bsrr->request = reqb;
1844     bsrr->association = assoc;
1845     bsrr->referenceId = req->referenceId;
1846     save_referenceId (reqb, bsrr->referenceId);
1847
1848     yaz_log (log_requestdetail, "ResultSet '%s'", req->resultSetName);
1849     if (req->databaseNames)
1850     {
1851         int i;
1852         for (i = 0; i < req->num_databaseNames; i++)
1853             yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
1854     }
1855
1856     yaz_log_zquery_level(log_requestdetail,req->query);
1857
1858     if (assoc->init->bend_search)
1859     {
1860         bsrr->setname = req->resultSetName;
1861         bsrr->replace_set = *req->replaceIndicator;
1862         bsrr->num_bases = req->num_databaseNames;
1863         bsrr->basenames = req->databaseNames;
1864         bsrr->query = req->query;
1865         bsrr->stream = assoc->encode;
1866         nmem_transfer(bsrr->stream->mem, reqb->request_mem);
1867         bsrr->decode = assoc->decode;
1868         bsrr->print = assoc->print;
1869         bsrr->errcode = 0;
1870         bsrr->hits = 0;
1871         bsrr->errstring = NULL;
1872         bsrr->search_info = NULL;
1873         (assoc->init->bend_search)(assoc->backend, bsrr);
1874         if (!bsrr->request)  /* backend not ready with the search response */
1875             return 0;  /* should not be used any more */
1876     }
1877     else
1878     { 
1879         /* FIXME - make a diagnostic for it */
1880         yaz_log(YLOG_WARN,"Search not supported ?!?!");
1881     }
1882     return response_searchRequest(assoc, reqb, bsrr, fd);
1883 }
1884
1885 int bend_searchresponse(void *handle, bend_search_rr *bsrr) {return 0;}
1886
1887 /*
1888  * Prepare a searchresponse based on the backend results. We probably want
1889  * to look at making the fetching of records nonblocking as well, but
1890  * so far, we'll keep things simple.
1891  * If bsrt is null, that means we're called in response to a communications
1892  * event, and we'll have to get the response for ourselves.
1893  */
1894 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
1895     bend_search_rr *bsrt, int *fd)
1896 {
1897     Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
1898     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
1899     Z_SearchResponse *resp = (Z_SearchResponse *)
1900         odr_malloc (assoc->encode, sizeof(*resp));
1901     int *nulint = odr_intdup (assoc->encode, 0);
1902     bool_t *sr = odr_intdup(assoc->encode, 1);
1903     int *next = odr_intdup(assoc->encode, 0);
1904     int *none = odr_intdup(assoc->encode, Z_SearchResponse_none);
1905     int returnedrecs=0;
1906
1907     apdu->which = Z_APDU_searchResponse;
1908     apdu->u.searchResponse = resp;
1909     resp->referenceId = req->referenceId;
1910     resp->additionalSearchInfo = 0;
1911     resp->otherInfo = 0;
1912     *fd = -1;
1913     if (!bsrt && !bend_searchresponse(assoc->backend, bsrt))
1914     {
1915         yaz_log(YLOG_FATAL, "Bad result from backend");
1916         return 0;
1917     }
1918     else if (bsrt->errcode)
1919     {
1920         resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
1921         resp->resultCount = nulint;
1922         resp->numberOfRecordsReturned = nulint;
1923         resp->nextResultSetPosition = nulint;
1924         resp->searchStatus = nulint;
1925         resp->resultSetStatus = none;
1926         resp->presentStatus = 0;
1927     }
1928     else
1929     {
1930         int *toget = odr_intdup(assoc->encode, 0);
1931         int *presst = odr_intdup(assoc->encode, 0);
1932         Z_RecordComposition comp, *compp = 0;
1933
1934         yaz_log (log_requestdetail, "resultCount: %d", bsrt->hits);
1935
1936         resp->records = 0;
1937         resp->resultCount = &bsrt->hits;
1938
1939         comp.which = Z_RecordComp_simple;
1940         /* how many records does the user agent want, then? */
1941         if (bsrt->hits <= *req->smallSetUpperBound)
1942         {
1943             *toget = bsrt->hits;
1944             if ((comp.u.simple = req->smallSetElementSetNames))
1945                 compp = &comp;
1946         }
1947         else if (bsrt->hits < *req->largeSetLowerBound)
1948         {
1949             *toget = *req->mediumSetPresentNumber;
1950             if (*toget > bsrt->hits)
1951                 *toget = bsrt->hits;
1952             if ((comp.u.simple = req->mediumSetElementSetNames))
1953                 compp = &comp;
1954         }
1955         else
1956             *toget = 0;
1957
1958         if (*toget && !resp->records)
1959         {
1960             oident *prefformat;
1961             oid_value form;
1962
1963             if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
1964                 form = VAL_NONE;
1965             else
1966                 form = prefformat->value;
1967             resp->records = pack_records(assoc, req->resultSetName, 1,
1968                                          toget, compp, next, presst, form, req->referenceId,
1969                                          req->preferredRecordSyntax, NULL);
1970             if (!resp->records)
1971                 return 0;
1972             resp->numberOfRecordsReturned = toget;
1973             returnedrecs = *toget;
1974             resp->nextResultSetPosition = next;
1975             resp->searchStatus = sr;
1976             resp->resultSetStatus = 0;
1977             resp->presentStatus = presst;
1978         }
1979         else
1980         {
1981             if (*resp->resultCount)
1982                 *next = 1;
1983             resp->numberOfRecordsReturned = nulint;
1984             resp->nextResultSetPosition = next;
1985             resp->searchStatus = sr;
1986             resp->resultSetStatus = 0;
1987             resp->presentStatus = 0;
1988         }
1989     }
1990     resp->additionalSearchInfo = bsrt->search_info;
1991
1992     if (log_request)
1993     {
1994         WRBUF wr = wrbuf_alloc();
1995         if (bsrt->errcode)
1996             wrbuf_printf(wr, "ERROR %d", bsrt->errcode);
1997         else
1998             wrbuf_printf(wr, "OK %d", bsrt->hits);
1999         wrbuf_printf(wr, " %s 1+%d ",
2000                      req->resultSetName, returnedrecs);
2001         wrbuf_put_zquery(wr, req->query);
2002         
2003         yaz_log(log_request, "Search %s", wrbuf_buf(wr));
2004         wrbuf_free(wr, 1);
2005     }
2006     return apdu;
2007 }
2008
2009 /*
2010  * Maybe we got a little over-friendly when we designed bend_fetch to
2011  * get only one record at a time. Some backends can optimise multiple-record
2012  * fetches, and at any rate, there is some overhead involved in
2013  * all that selecting and hopping around. Problem is, of course, that the
2014  * frontend can't know ahead of time how many records it'll need to
2015  * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
2016  * is downright lousy as a bulk data transfer protocol.
2017  *
2018  * To start with, we'll do the fetching of records from the backend
2019  * in one operation: To save some trips in and out of the event-handler,
2020  * and to simplify the interface to pack_records. At any rate, asynch
2021  * operation is more fun in operations that have an unpredictable execution
2022  * speed - which is normally more true for search than for present.
2023  */
2024 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
2025                                       int *fd)
2026 {
2027     Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
2028     oident *prefformat;
2029     oid_value form;
2030     Z_APDU *apdu;
2031     Z_PresentResponse *resp;
2032     int *next;
2033     int *num;
2034     int errcode = 0;
2035     const char *errstring = 0;
2036
2037     yaz_log(log_requestdetail, "Got PresentRequest.");
2038
2039     if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
2040         form = VAL_NONE;
2041     else
2042         form = prefformat->value;
2043     resp = (Z_PresentResponse *)odr_malloc (assoc->encode, sizeof(*resp));
2044     resp->records = 0;
2045     resp->presentStatus = odr_intdup(assoc->encode, 0);
2046     if (assoc->init->bend_present)
2047     {
2048         bend_present_rr *bprr = (bend_present_rr *)
2049             nmem_malloc (reqb->request_mem, sizeof(*bprr));
2050         bprr->setname = req->resultSetId;
2051         bprr->start = *req->resultSetStartPoint;
2052         bprr->number = *req->numberOfRecordsRequested;
2053         bprr->format = form;
2054         bprr->comp = req->recordComposition;
2055         bprr->referenceId = req->referenceId;
2056         bprr->stream = assoc->encode;
2057         bprr->print = assoc->print;
2058         bprr->request = reqb;
2059         bprr->association = assoc;
2060         bprr->errcode = 0;
2061         bprr->errstring = NULL;
2062         (*assoc->init->bend_present)(assoc->backend, bprr);
2063         
2064         if (!bprr->request)
2065             return 0; /* should not happen */
2066         if (bprr->errcode)
2067         {
2068             resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2069             *resp->presentStatus = Z_PresentStatus_failure;
2070             errcode = bprr->errcode;
2071             errstring = bprr->errstring;
2072         }
2073     }
2074     apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2075     next = odr_intdup(assoc->encode, 0);
2076     num = odr_intdup(assoc->encode, 0);
2077     
2078     apdu->which = Z_APDU_presentResponse;
2079     apdu->u.presentResponse = resp;
2080     resp->referenceId = req->referenceId;
2081     resp->otherInfo = 0;
2082     
2083     if (!resp->records)
2084     {
2085         *num = *req->numberOfRecordsRequested;
2086         resp->records =
2087             pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
2088                          num, req->recordComposition, next,
2089                          resp->presentStatus,
2090                          form, req->referenceId, req->preferredRecordSyntax, 
2091                          &errcode);
2092     }
2093     if (log_request)
2094     {
2095         WRBUF wr = wrbuf_alloc();
2096         wrbuf_printf(wr, "Present ");
2097
2098         if (*resp->presentStatus == Z_PresentStatus_failure)
2099             wrbuf_printf(wr, "ERROR %d", errcode);
2100         else if (*resp->presentStatus == Z_PresentStatus_success)
2101             wrbuf_printf(wr, "OK -");
2102         else
2103             wrbuf_printf(wr, "Partial %d", *resp->presentStatus);
2104
2105         wrbuf_printf(wr, " %s %d+%d ",
2106                 req->resultSetId, *req->resultSetStartPoint,
2107                 *req->numberOfRecordsRequested);
2108         yaz_log(log_request, "%s", wrbuf_buf(wr) );
2109         wrbuf_free(wr, 1);
2110     }
2111     if (!resp->records)
2112         return 0;
2113     resp->numberOfRecordsReturned = num;
2114     resp->nextResultSetPosition = next;
2115     
2116     return apdu;
2117 }
2118
2119 /*
2120  * Scan was implemented rather in a hurry, and with support for only the basic
2121  * elements of the service in the backend API. Suggestions are welcome.
2122  */
2123 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
2124 {
2125     Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
2126     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2127     Z_ScanResponse *res = (Z_ScanResponse *)
2128         odr_malloc (assoc->encode, sizeof(*res));
2129     int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
2130     int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
2131     Z_ListEntries *ents = (Z_ListEntries *)
2132         odr_malloc (assoc->encode, sizeof(*ents));
2133     Z_DiagRecs *diagrecs_p = NULL;
2134     oident *attset;
2135     bend_scan_rr *bsrr = (bend_scan_rr *)
2136         odr_malloc (assoc->encode, sizeof(*bsrr));
2137     struct scan_entry *save_entries;
2138
2139     yaz_log(log_requestdetail, "Got ScanRequest");
2140
2141     apdu->which = Z_APDU_scanResponse;
2142     apdu->u.scanResponse = res;
2143     res->referenceId = req->referenceId;
2144
2145     /* if step is absent, set it to 0 */
2146     res->stepSize = odr_intdup(assoc->encode, 0);
2147     if (req->stepSize)
2148         *res->stepSize = *req->stepSize;
2149
2150     res->scanStatus = scanStatus;
2151     res->numberOfEntriesReturned = numberOfEntriesReturned;
2152     res->positionOfTerm = 0;
2153     res->entries = ents;
2154     ents->num_entries = 0;
2155     ents->entries = NULL;
2156     ents->num_nonsurrogateDiagnostics = 0;
2157     ents->nonsurrogateDiagnostics = NULL;
2158     res->attributeSet = 0;
2159     res->otherInfo = 0;
2160
2161     if (req->databaseNames)
2162     {
2163         int i;
2164         for (i = 0; i < req->num_databaseNames; i++)
2165             yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
2166     }
2167     yaz_log(log_requestdetail, "pos %d  step %d  entries %d",
2168             *req->preferredPositionInResponse, *res->stepSize, 
2169             *req->numberOfTermsRequested);
2170     bsrr->num_bases = req->num_databaseNames;
2171     bsrr->basenames = req->databaseNames;
2172     bsrr->num_entries = *req->numberOfTermsRequested;
2173     bsrr->term = req->termListAndStartPoint;
2174     bsrr->referenceId = req->referenceId;
2175     bsrr->stream = assoc->encode;
2176     bsrr->print = assoc->print;
2177     bsrr->step_size = res->stepSize;
2178     bsrr->entries = 0;
2179     /* For YAZ 2.0 and earlier it was the backend handler that
2180        initialized entries (member display_term did not exist)
2181        YAZ 2.0 and later sets 'entries'  and initialize all members
2182        including 'display_term'. If YAZ 2.0 or later sees that
2183        entries was modified - we assume that it is an old handler and
2184        that 'display_term' is _not_ set.
2185     */
2186     if (bsrr->num_entries > 0) 
2187     {
2188         int i;
2189         bsrr->entries = odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
2190                                    bsrr->num_entries);
2191         for (i = 0; i<bsrr->num_entries; i++)
2192         {
2193             bsrr->entries[i].term = 0;
2194             bsrr->entries[i].occurrences = 0;
2195             bsrr->entries[i].errcode = 0;
2196             bsrr->entries[i].errstring = 0;
2197             bsrr->entries[i].display_term = 0;
2198         }
2199     }
2200     save_entries = bsrr->entries;  /* save it so we can compare later */
2201
2202     if (req->attributeSet &&
2203         (attset = oid_getentbyoid(req->attributeSet)) &&
2204         (attset->oclass == CLASS_ATTSET || attset->oclass == CLASS_GENERAL))
2205         bsrr->attributeset = attset->value;
2206     else
2207         bsrr->attributeset = VAL_NONE;
2208     log_scan_term_level (log_requestdetail, req->termListAndStartPoint, 
2209             bsrr->attributeset);
2210     bsrr->term_position = req->preferredPositionInResponse ?
2211         *req->preferredPositionInResponse : 1;
2212
2213     ((int (*)(void *, bend_scan_rr *))
2214      (*assoc->init->bend_scan))(assoc->backend, bsrr);
2215
2216     if (bsrr->errcode)
2217         diagrecs_p = zget_DiagRecs(assoc->encode,
2218                                    bsrr->errcode, bsrr->errstring);
2219     else
2220     {
2221         int i;
2222         Z_Entry **tab = (Z_Entry **)
2223             odr_malloc (assoc->encode, sizeof(*tab) * bsrr->num_entries);
2224         
2225         if (bsrr->status == BEND_SCAN_PARTIAL)
2226             *scanStatus = Z_Scan_partial_5;
2227         else
2228             *scanStatus = Z_Scan_success;
2229         ents->entries = tab;
2230         ents->num_entries = bsrr->num_entries;
2231         res->numberOfEntriesReturned = &ents->num_entries;          
2232         res->positionOfTerm = &bsrr->term_position;
2233         for (i = 0; i < bsrr->num_entries; i++)
2234         {
2235             Z_Entry *e;
2236             Z_TermInfo *t;
2237             Odr_oct *o;
2238             
2239             tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
2240             if (bsrr->entries[i].occurrences >= 0)
2241             {
2242                 e->which = Z_Entry_termInfo;
2243                 e->u.termInfo = t = (Z_TermInfo *)
2244                     odr_malloc(assoc->encode, sizeof(*t));
2245                 t->suggestedAttributes = 0;
2246                 t->displayTerm = 0;
2247                 if (save_entries == bsrr->entries && 
2248                     bsrr->entries[i].display_term)
2249                 {
2250                     /* the entries was _not_ set by the handler. So it's
2251                        safe to test for new member display_term. It is
2252                        NULL'ed by us.
2253                     */
2254                     t->displayTerm = odr_strdup(assoc->encode,
2255                                                 bsrr->entries[i].display_term);
2256                 }
2257                 t->alternativeTerm = 0;
2258                 t->byAttributes = 0;
2259                 t->otherTermInfo = 0;
2260                 t->globalOccurrences = &bsrr->entries[i].occurrences;
2261                 t->term = (Z_Term *)
2262                     odr_malloc(assoc->encode, sizeof(*t->term));
2263                 t->term->which = Z_Term_general;
2264                 t->term->u.general = o =
2265                     (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
2266                 o->buf = (unsigned char *)
2267                     odr_malloc(assoc->encode, o->len = o->size =
2268                                strlen(bsrr->entries[i].term));
2269                 memcpy(o->buf, bsrr->entries[i].term, o->len);
2270                 yaz_log(YLOG_DEBUG, "  term #%d: '%s' (%d)", i,
2271                          bsrr->entries[i].term, bsrr->entries[i].occurrences);
2272             }
2273             else
2274             {
2275                 Z_DiagRecs *drecs = zget_DiagRecs(assoc->encode,
2276                                                   bsrr->entries[i].errcode,
2277                                                   bsrr->entries[i].errstring);
2278                 assert (drecs->num_diagRecs == 1);
2279                 e->which = Z_Entry_surrogateDiagnostic;
2280                 assert (drecs->diagRecs[0]);
2281                 e->u.surrogateDiagnostic = drecs->diagRecs[0];
2282             }
2283         }
2284     }
2285     if (diagrecs_p)
2286     {
2287         ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
2288         ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
2289     }
2290     if (log_request)
2291     {
2292         WRBUF wr = wrbuf_alloc();
2293         if (bsrr->errcode)
2294             wr_diag(wr, bsrr->errcode, bsrr->errstring);
2295         else if (*res->scanStatus == Z_Scan_success)
2296             wrbuf_printf(wr, "OK");
2297         else
2298             wrbuf_printf(wr, "Partial");
2299
2300         wrbuf_printf(wr, " %d+%d %d ",
2301                      *req->preferredPositionInResponse, 
2302                      *req->numberOfTermsRequested,
2303                      (res->stepSize ? *res->stepSize : 0));
2304         wrbuf_scan_term(wr, req->termListAndStartPoint, 
2305                         bsrr->attributeset);
2306         
2307         yaz_log(log_request, "Scan %s", wrbuf_buf(wr) );
2308         wrbuf_free(wr, 1);
2309     }
2310     return apdu;
2311 }
2312
2313 static Z_APDU *process_sortRequest(association *assoc, request *reqb,
2314     int *fd)
2315 {
2316     int i;
2317     Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
2318     Z_SortResponse *res = (Z_SortResponse *)
2319         odr_malloc (assoc->encode, sizeof(*res));
2320     bend_sort_rr *bsrr = (bend_sort_rr *)
2321         odr_malloc (assoc->encode, sizeof(*bsrr));
2322
2323     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2324
2325     yaz_log(log_requestdetail, "Got SortRequest.");
2326
2327     bsrr->num_input_setnames = req->num_inputResultSetNames;
2328     for (i=0;i<req->num_inputResultSetNames;i++)
2329         yaz_log(log_requestdetail, "Input resultset: '%s'",
2330                 req->inputResultSetNames[i]);
2331     bsrr->input_setnames = req->inputResultSetNames;
2332     bsrr->referenceId = req->referenceId;
2333     bsrr->output_setname = req->sortedResultSetName;
2334     yaz_log(log_requestdetail, "Output resultset: '%s'",
2335                 req->sortedResultSetName);
2336     bsrr->sort_sequence = req->sortSequence;
2337        /*FIXME - dump those sequences too */
2338     bsrr->stream = assoc->encode;
2339     bsrr->print = assoc->print;
2340
2341     bsrr->sort_status = Z_SortResponse_failure;
2342     bsrr->errcode = 0;
2343     bsrr->errstring = 0;
2344     
2345     (*assoc->init->bend_sort)(assoc->backend, bsrr);
2346     
2347     res->referenceId = bsrr->referenceId;
2348     res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
2349     res->resultSetStatus = 0;
2350     if (bsrr->errcode)
2351     {
2352         Z_DiagRecs *dr = zget_DiagRecs(assoc->encode,
2353                                        bsrr->errcode, bsrr->errstring);
2354         res->diagnostics = dr->diagRecs;
2355         res->num_diagnostics = dr->num_diagRecs;
2356     }
2357     else
2358     {
2359         res->num_diagnostics = 0;
2360         res->diagnostics = 0;
2361     }
2362     res->resultCount = 0;
2363     res->otherInfo = 0;
2364
2365     apdu->which = Z_APDU_sortResponse;
2366     apdu->u.sortResponse = res;
2367     if (log_request)
2368     {
2369         WRBUF wr = wrbuf_alloc();
2370         wrbuf_printf(wr, "Sort ");
2371         if (bsrr->errcode)
2372             wrbuf_printf(wr, " ERROR %d", bsrr->errcode);
2373         else
2374             wrbuf_printf(wr,  "OK -");
2375         wrbuf_printf(wr, " (");
2376         for (i = 0; i<req->num_inputResultSetNames; i++)
2377         {
2378             if (i)
2379                 wrbuf_printf(wr, ",");
2380             wrbuf_printf(wr, req->inputResultSetNames[i]);
2381         }
2382         wrbuf_printf(wr, ")->%s ",req->sortedResultSetName);
2383
2384         yaz_log(log_request, "%s", wrbuf_buf(wr) );
2385         wrbuf_free(wr, 1);
2386     }
2387     return apdu;
2388 }
2389
2390 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
2391     int *fd)
2392 {
2393     int i;
2394     Z_DeleteResultSetRequest *req =
2395         reqb->apdu_request->u.deleteResultSetRequest;
2396     Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
2397         odr_malloc (assoc->encode, sizeof(*res));
2398     bend_delete_rr *bdrr = (bend_delete_rr *)
2399         odr_malloc (assoc->encode, sizeof(*bdrr));
2400     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2401
2402     yaz_log(log_requestdetail, "Got DeleteRequest.");
2403
2404     bdrr->num_setnames = req->num_resultSetList;
2405     bdrr->setnames = req->resultSetList;
2406     for (i = 0; i<req->num_resultSetList; i++)
2407         yaz_log(log_requestdetail, "resultset: '%s'",
2408                 req->resultSetList[i]);
2409     bdrr->stream = assoc->encode;
2410     bdrr->print = assoc->print;
2411     bdrr->function = *req->deleteFunction;
2412     bdrr->referenceId = req->referenceId;
2413     bdrr->statuses = 0;
2414     if (bdrr->num_setnames > 0)
2415     {
2416         bdrr->statuses = (int*) 
2417             odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
2418                        bdrr->num_setnames);
2419         for (i = 0; i < bdrr->num_setnames; i++)
2420             bdrr->statuses[i] = 0;
2421     }
2422     (*assoc->init->bend_delete)(assoc->backend, bdrr);
2423     
2424     res->referenceId = req->referenceId;
2425
2426     res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
2427
2428     res->deleteListStatuses = 0;
2429     if (bdrr->num_setnames > 0)
2430     {
2431         int i;
2432         res->deleteListStatuses = (Z_ListStatuses *)
2433             odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
2434         res->deleteListStatuses->num = bdrr->num_setnames;
2435         res->deleteListStatuses->elements =
2436             (Z_ListStatus **)
2437             odr_malloc (assoc->encode, 
2438                         sizeof(*res->deleteListStatuses->elements) *
2439                         bdrr->num_setnames);
2440         for (i = 0; i<bdrr->num_setnames; i++)
2441         {
2442             res->deleteListStatuses->elements[i] =
2443                 (Z_ListStatus *)
2444                 odr_malloc (assoc->encode,
2445                             sizeof(**res->deleteListStatuses->elements));
2446             res->deleteListStatuses->elements[i]->status = bdrr->statuses+i;
2447             res->deleteListStatuses->elements[i]->id =
2448                 odr_strdup (assoc->encode, bdrr->setnames[i]);
2449         }
2450     }
2451     res->numberNotDeleted = 0;
2452     res->bulkStatuses = 0;
2453     res->deleteMessage = 0;
2454     res->otherInfo = 0;
2455
2456     apdu->which = Z_APDU_deleteResultSetResponse;
2457     apdu->u.deleteResultSetResponse = res;
2458     if (log_request)
2459     {
2460         WRBUF wr = wrbuf_alloc();
2461         wrbuf_printf(wr, "Delete ");
2462         if (bdrr->delete_status)
2463             wrbuf_printf(wr, "ERROR %d", bdrr->delete_status);
2464         else
2465             wrbuf_printf(wr, "OK -");
2466         for (i = 0; i<req->num_resultSetList; i++)
2467             wrbuf_printf(wr, " %s ", req->resultSetList[i]);
2468         yaz_log(log_request, "%s", wrbuf_buf(wr) );
2469         wrbuf_free(wr, 1);
2470     }
2471     return apdu;
2472 }
2473
2474 static void process_close(association *assoc, request *reqb)
2475 {
2476     Z_Close *req = reqb->apdu_request->u.close;
2477     static char *reasons[] =
2478     {
2479         "finished",
2480         "shutdown",
2481         "systemProblem",
2482         "costLimit",
2483         "resources",
2484         "securityViolation",
2485         "protocolError",
2486         "lackOfActivity",
2487         "peerAbort",
2488         "unspecified"
2489     };
2490
2491     yaz_log(log_requestdetail, "Got Close, reason %s, message %s",
2492         reasons[*req->closeReason], req->diagnosticInformation ?
2493         req->diagnosticInformation : "NULL");
2494     if (assoc->version < 3) /* to make do_force respond with close */
2495         assoc->version = 3;
2496     do_close_req(assoc, Z_Close_finished,
2497                  "Association terminated by client", reqb);
2498     yaz_log(log_request,"Close OK");
2499 }
2500
2501 void save_referenceId (request *reqb, Z_ReferenceId *refid)
2502 {
2503     if (refid)
2504     {
2505         reqb->len_refid = refid->len;
2506         reqb->refid = (char *)nmem_malloc (reqb->request_mem, refid->len);
2507         memcpy (reqb->refid, refid->buf, refid->len);
2508     }
2509     else
2510     {
2511         reqb->len_refid = 0;
2512         reqb->refid = NULL;
2513     }
2514 }
2515
2516 void bend_request_send (bend_association a, bend_request req, Z_APDU *res)
2517 {
2518     process_z_response (a, req, res);
2519 }
2520
2521 bend_request bend_request_mk (bend_association a)
2522 {
2523     request *nreq = request_get (&a->outgoing);
2524     nreq->request_mem = nmem_create ();
2525     return nreq;
2526 }
2527
2528 Z_ReferenceId *bend_request_getid (ODR odr, bend_request req)
2529 {
2530     Z_ReferenceId *id;
2531     if (!req->refid)
2532         return 0;
2533     id = (Odr_oct *)odr_malloc (odr, sizeof(*odr));
2534     id->buf = (unsigned char *)odr_malloc (odr, req->len_refid);
2535     id->len = id->size = req->len_refid;
2536     memcpy (id->buf, req->refid, req->len_refid);
2537     return id;
2538 }
2539
2540 void bend_request_destroy (bend_request *req)
2541 {
2542     nmem_destroy((*req)->request_mem);
2543     request_release(*req);
2544     *req = NULL;
2545 }
2546
2547 int bend_backend_respond (bend_association a, bend_request req)
2548 {
2549     char *msg;
2550     int r;
2551     r = process_z_request (a, req, &msg);
2552     if (r < 0)
2553         yaz_log (YLOG_WARN, "%s", msg);
2554     return r;
2555 }
2556
2557 void bend_request_setdata(bend_request r, void *p)
2558 {
2559     r->clientData = p;
2560 }
2561
2562 void *bend_request_getdata(bend_request r)
2563 {
2564     return r->clientData;
2565 }
2566
2567 static Z_APDU *process_segmentRequest (association *assoc, request *reqb)
2568 {
2569     bend_segment_rr req;
2570
2571     req.segment = reqb->apdu_request->u.segmentRequest;
2572     req.stream = assoc->encode;
2573     req.decode = assoc->decode;
2574     req.print = assoc->print;
2575     req.association = assoc;
2576     
2577     (*assoc->init->bend_segment)(assoc->backend, &req);
2578
2579     return 0;
2580 }
2581
2582 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd)
2583 {
2584     bend_esrequest_rr esrequest;
2585
2586     Z_ExtendedServicesRequest *req =
2587         reqb->apdu_request->u.extendedServicesRequest;
2588     Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
2589
2590     Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
2591
2592     yaz_log(log_requestdetail,"Got EsRequest");
2593
2594     esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
2595     esrequest.stream = assoc->encode;
2596     esrequest.decode = assoc->decode;
2597     esrequest.print = assoc->print;
2598     esrequest.errcode = 0;
2599     esrequest.errstring = NULL;
2600     esrequest.request = reqb;
2601     esrequest.association = assoc;
2602     esrequest.taskPackage = 0;
2603     esrequest.referenceId = req->referenceId;
2604     
2605     (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
2606     
2607     /* If the response is being delayed, return NULL */
2608     if (esrequest.request == NULL)
2609         return(NULL);
2610
2611     resp->referenceId = req->referenceId;
2612
2613     if (esrequest.errcode == -1)
2614     {
2615         /* Backend service indicates request will be processed */
2616         yaz_log(log_request,"EsRequest OK: Accepted !");
2617         *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
2618     }
2619     else if (esrequest.errcode == 0)
2620     {
2621         /* Backend service indicates request will be processed */
2622         yaz_log(log_request,"EsRequest OK: Done !");
2623         *resp->operationStatus = Z_ExtendedServicesResponse_done;
2624     }
2625     else
2626     {
2627         Z_DiagRecs *diagRecs =
2628             zget_DiagRecs(assoc->encode, esrequest.errcode,
2629                           esrequest.errstring);
2630         /* Backend indicates error, request will not be processed */
2631         yaz_log(YLOG_DEBUG,"Request could not be processed...failure !");
2632         *resp->operationStatus = Z_ExtendedServicesResponse_failure;
2633         resp->num_diagnostics = diagRecs->num_diagRecs;
2634         resp->diagnostics = diagRecs->diagRecs;
2635         if (log_request)
2636         {
2637             WRBUF wr = wrbuf_alloc();
2638             wrbuf_diags(wr, resp->num_diagnostics, resp->diagnostics);
2639             yaz_log(log_request, "EsRequest %s", wrbuf_buf(wr) );
2640             wrbuf_free(wr, 1);
2641         }
2642
2643     }
2644     /* Do something with the members of bend_extendedservice */
2645     if (esrequest.taskPackage)
2646         resp->taskPackage = z_ext_record (assoc->encode, VAL_EXTENDED,
2647                                          (const char *)  esrequest.taskPackage,
2648                                           -1);
2649     yaz_log(YLOG_DEBUG,"Send the result apdu");
2650     return apdu;
2651 }
2652