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