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