Added explain facility for frontend server XML config. Renamed
[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.49 2005-03-03 23:16:20 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     xmlNodePtr ptr = rr->server_node_ptr;
920     if (!ptr)
921         return 0;
922     for (ptr = ptr->children; ptr; ptr = ptr->next)
923     {
924         if (ptr->type != XML_ELEMENT_NODE)
925             continue;
926         if (!strcmp((const char *) ptr->name, "explain"))
927         {
928             int len;
929             ptr = xmlCopyNode(ptr, 1);
930
931             xmlDocPtr doc = xmlNewDoc((const xmlChar *) "1.0");
932         
933             xmlDocSetRootElement(doc, ptr);
934             
935             xmlChar *buf_out;
936             xmlDocDumpMemory(doc, &buf_out, &len);
937             char *content = (char*) odr_malloc(rr->stream, 1+len);
938             memcpy(content, buf_out, len);
939             content[len] = '\0';
940             
941             xmlFree(buf_out);
942             xmlFreeDoc(doc);
943             rr->explain_buf = content;
944             return 0;
945         }
946     }
947     return 0;
948 }
949
950 static void srw_bend_explain(association *assoc, request *req,
951                              Z_SRW_explainRequest *srw_req,
952                              Z_SRW_explainResponse *srw_res,
953                              int *http_code)
954 {
955     yaz_log(log_requestdetail, "Got SRW ExplainRequest");
956     *http_code = 404;
957     srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics);
958     if (assoc->init)
959     {
960         bend_explain_rr rr;
961         
962         rr.stream = assoc->encode;
963         rr.decode = assoc->decode;
964         rr.print = assoc->print;
965         rr.explain_buf = 0;
966         rr.database = srw_req->database;
967         rr.server_node_ptr = assoc->server_node_ptr;
968         rr.schema = "http://explain.z3950.org/dtd/2.0/";
969         if (assoc->init->bend_explain)
970             (*assoc->init->bend_explain)(assoc->backend, &rr);
971         else
972             srw_bend_explain_default(assoc->backend, &rr);
973
974         if (rr.explain_buf)
975         {
976             int packing = Z_SRW_recordPacking_string;
977             if (srw_req->recordPacking && 
978                 !strcmp(srw_req->recordPacking, "xml"))
979                 packing = Z_SRW_recordPacking_XML;
980             srw_res->record.recordSchema = rr.schema;
981             srw_res->record.recordPacking = packing;
982             srw_res->record.recordData_buf = rr.explain_buf;
983             srw_res->record.recordData_len = strlen(rr.explain_buf);
984             srw_res->record.recordPosition = 0;
985             *http_code = 200;
986         }
987     }
988 }
989
990 static void srw_bend_scan(association *assoc, request *req,
991                           Z_SRW_scanRequest *srw_req,
992                           Z_SRW_scanResponse *srw_res,
993                           int *http_code)
994 {
995     yaz_log(log_requestdetail, "Got SRW ScanRequest");
996
997     *http_code = 200;
998     srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics);
999     if (srw_res->num_diagnostics == 0 && assoc->init)
1000     {
1001         struct scan_entry *save_entries;
1002
1003         bend_scan_rr *bsrr = (bend_scan_rr *)
1004             odr_malloc (assoc->encode, sizeof(*bsrr));
1005         bsrr->num_bases = 1;
1006         bsrr->basenames = &srw_req->database;
1007
1008         bsrr->num_entries = srw_req->maximumTerms ?
1009             *srw_req->maximumTerms : 10;
1010         bsrr->term_position = srw_req->responsePosition ?
1011             *srw_req->responsePosition : 1;
1012
1013         bsrr->errcode = 0;
1014         bsrr->errstring = 0;
1015         bsrr->referenceId = 0;
1016         bsrr->stream = assoc->encode;
1017         bsrr->print = assoc->print;
1018         bsrr->step_size = odr_intdup(assoc->decode, 0);
1019         bsrr->entries = 0;
1020
1021         if (bsrr->num_entries > 0) 
1022         {
1023             int i;
1024             bsrr->entries = odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
1025                                        bsrr->num_entries);
1026             for (i = 0; i<bsrr->num_entries; i++)
1027             {
1028                 bsrr->entries[i].term = 0;
1029                 bsrr->entries[i].occurrences = 0;
1030                 bsrr->entries[i].errcode = 0;
1031                 bsrr->entries[i].errstring = 0;
1032                 bsrr->entries[i].display_term = 0;
1033             }
1034         }
1035         save_entries = bsrr->entries;  /* save it so we can compare later */
1036
1037         if (srw_req->query_type == Z_SRW_query_type_pqf &&
1038             assoc->init->bend_scan)
1039         {
1040             Odr_oid *scan_attributeSet = 0;
1041             oident *attset;
1042             YAZ_PQF_Parser pqf_parser = yaz_pqf_create();
1043             
1044             bsrr->term = yaz_pqf_scan(pqf_parser, assoc->decode,
1045                                       &scan_attributeSet, 
1046                                       srw_req->scanClause.pqf); 
1047             if (scan_attributeSet &&
1048                 (attset = oid_getentbyoid(scan_attributeSet)) &&
1049                 (attset->oclass == CLASS_ATTSET ||
1050                  attset->oclass == CLASS_GENERAL))
1051                 bsrr->attributeset = attset->value;
1052             else
1053                 bsrr->attributeset = VAL_NONE;
1054             yaz_pqf_destroy(pqf_parser);
1055             bsrr->scanClause = 0;
1056             ((int (*)(void *, bend_scan_rr *))
1057              (*assoc->init->bend_scan))(assoc->backend, bsrr);
1058         }
1059         else if (srw_req->query_type == Z_SRW_query_type_cql
1060                  && assoc->init->bend_srw_scan)
1061         {
1062             if (assoc->cql_transform)
1063             {
1064                 bsrr->scanClause = 0;
1065                 bsrr->attributeset = VAL_NONE;
1066                 bsrr->term = odr_malloc(assoc->decode, sizeof(*bsrr->term));
1067                 int srw_error = cql2pqf_scan(assoc->encode,
1068                                              srw_req->scanClause.cql,
1069                                              assoc->cql_transform,
1070                                              bsrr->term);
1071                 if (srw_error)
1072                     yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1073                                            &srw_res->num_diagnostics,
1074                                            srw_error, 0);
1075                 else
1076                 {
1077                     ((int (*)(void *, bend_scan_rr *))
1078                      (*assoc->init->bend_scan))(assoc->backend, bsrr);
1079                 }
1080             }
1081             else
1082             {
1083                 bsrr->term = 0;
1084                 bsrr->attributeset = VAL_NONE;
1085                 bsrr->scanClause = srw_req->scanClause.cql;
1086                 ((int (*)(void *, bend_scan_rr *))
1087                  (*assoc->init->bend_srw_scan))(assoc->backend, bsrr);
1088             }
1089         }
1090         else
1091         {
1092             yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1093                                    &srw_res->num_diagnostics, 4, "scan");
1094         }
1095         if (bsrr->errcode)
1096         {
1097             int srw_error;
1098             if (bsrr->errcode == 109) /* database unavailable */
1099             {
1100                 *http_code = 404;
1101                 return;
1102             }
1103             srw_error = yaz_diag_bib1_to_srw (bsrr->errcode);
1104
1105             yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1106                                    &srw_res->num_diagnostics,
1107                                    srw_error, bsrr->errstring);
1108         }
1109         else if (srw_res->num_diagnostics == 0 && bsrr->num_entries)
1110         {
1111             int i;
1112             srw_res->terms = (Z_SRW_scanTerm*)
1113                 odr_malloc(assoc->encode, sizeof(*srw_res->terms) *
1114                            bsrr->num_entries);
1115
1116             srw_res->num_terms =  bsrr->num_entries;
1117             for (i = 0; i<bsrr->num_entries; i++)
1118             {
1119                 Z_SRW_scanTerm *t = srw_res->terms + i;
1120                 t->value = odr_strdup(assoc->encode, bsrr->entries[i].term);
1121                 t->numberOfRecords =
1122                     odr_intdup(assoc->encode, bsrr->entries[i].occurrences);
1123                 t->displayTerm = 0;
1124                 if (save_entries == bsrr->entries && 
1125                     bsrr->entries[i].display_term)
1126                 {
1127                     /* the entries was _not_ set by the handler. So it's
1128                        safe to test for new member display_term. It is
1129                        NULL'ed by us.
1130                     */
1131                     t->displayTerm = odr_strdup(assoc->encode, 
1132                                                 bsrr->entries[i].display_term);
1133                 }
1134                 t->whereInList = 0;
1135             }
1136         }
1137     }
1138     if (log_request)
1139     {
1140         WRBUF wr = wrbuf_alloc();
1141         const char *querytype = 0;
1142         const char *querystr = 0;
1143
1144         switch(srw_req->query_type)
1145         {
1146         case Z_SRW_query_type_pqf:
1147             querytype = "PQF";
1148             querystr = srw_req->scanClause.pqf;
1149             break;
1150         case Z_SRW_query_type_cql:
1151             querytype = "CQL";
1152             querystr = srw_req->scanClause.cql;
1153             break;
1154         default:
1155             querytype = "Unknown";
1156             querystr = "";
1157         }
1158         wrbuf_printf(wr, "SRWScan %d+%d",
1159                      (srw_req->responsePosition ? 
1160                       *srw_req->responsePosition : 1),
1161                      (srw_req->maximumTerms ?
1162                       *srw_req->maximumTerms : 1));
1163         if (srw_res->num_diagnostics)
1164             wrbuf_printf(wr, " ERROR %s", srw_res->diagnostics[0].uri);
1165         else
1166             wrbuf_printf(wr, " OK -");
1167         wrbuf_printf(wr, " %s: %s", querytype, querystr);
1168         yaz_log(log_request, "%s", wrbuf_buf(wr) );
1169         wrbuf_free(wr, 1);
1170     }
1171
1172 }
1173
1174
1175 static void process_http_request(association *assoc, request *req)
1176 {
1177     Z_HTTP_Request *hreq = req->gdu_request->u.HTTP_Request;
1178     ODR o = assoc->encode;
1179     int r = 2;  /* 2=NOT TAKEN, 1=TAKEN, 0=SOAP TAKEN */
1180     Z_SRW_PDU *sr = 0;
1181     Z_SOAP *soap_package = 0;
1182     Z_GDU *p = 0;
1183     char *charset = 0;
1184     Z_HTTP_Response *hres = 0;
1185     int keepalive = 1;
1186     char *stylesheet = 0;
1187     Z_SRW_diagnostic *diagnostic = 0;
1188     int num_diagnostic = 0;
1189     const char *host = z_HTTP_header_lookup(hreq->headers, "Host");
1190
1191     if (!control_association(assoc, host, 0))
1192     {
1193         p = z_get_HTTP_Response(o, 404);
1194         r = 1;
1195     }
1196     if (r == 2 && !strcmp(hreq->path, "/test")) 
1197     {   
1198         p = z_get_HTTP_Response(o, 200);
1199         hres = p->u.HTTP_Response;
1200         hres->content_buf = "1234567890\n";
1201         hres->content_len = strlen(hres->content_buf);
1202         r = 1;
1203     }
1204     if (r == 2)
1205     {
1206         r = yaz_srw_decode(hreq, &sr, &soap_package, assoc->decode, &charset);
1207         yaz_log(YLOG_DEBUG, "yaz_srw_decode returned %d", r);
1208     }
1209     if (r == 2)  /* not taken */
1210     {
1211         r = yaz_sru_decode(hreq, &sr, &soap_package, assoc->decode, &charset,
1212                            &diagnostic, &num_diagnostic);
1213         yaz_log(YLOG_DEBUG, "yaz_sru_decode returned %d", r);
1214     }
1215     if (r == 0)  /* decode SRW/SRU OK .. */
1216     {
1217         int http_code = 200;
1218         if (sr->which == Z_SRW_searchRetrieve_request)
1219         {
1220             Z_SRW_PDU *res =
1221                 yaz_srw_get(assoc->encode, Z_SRW_searchRetrieve_response);
1222
1223             stylesheet = sr->u.request->stylesheet;
1224             if (num_diagnostic)
1225             {
1226                 res->u.response->diagnostics = diagnostic;
1227                 res->u.response->num_diagnostics = num_diagnostic;
1228             }
1229             else
1230             {
1231                 srw_bend_search(assoc, req, sr->u.request, res->u.response, 
1232                                 &http_code);
1233             }
1234             if (http_code == 200)
1235                 soap_package->u.generic->p = res;
1236         }
1237         else if (sr->which == Z_SRW_explain_request)
1238         {
1239             Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_explain_response);
1240             stylesheet = sr->u.explain_request->stylesheet;
1241             if (num_diagnostic)
1242             {   
1243                 res->u.explain_response->diagnostics = diagnostic;
1244                 res->u.explain_response->num_diagnostics = num_diagnostic;
1245             }
1246             srw_bend_explain(assoc, req, sr->u.explain_request,
1247                              res->u.explain_response, &http_code);
1248             if (http_code == 200)
1249                 soap_package->u.generic->p = res;
1250         }
1251         else if (sr->which == Z_SRW_scan_request)
1252         {
1253             Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_scan_response);
1254             stylesheet = sr->u.scan_request->stylesheet;
1255             if (num_diagnostic)
1256             {   
1257                 res->u.scan_response->diagnostics = diagnostic;
1258                 res->u.scan_response->num_diagnostics = num_diagnostic;
1259             }
1260             srw_bend_scan(assoc, req, sr->u.scan_request,
1261                               res->u.scan_response, &http_code);
1262             if (http_code == 200)
1263                 soap_package->u.generic->p = res;
1264         }
1265         else
1266         {
1267             yaz_log(log_request, "SOAP ERROR"); 
1268                /* FIXME - what error, what query */
1269             http_code = 500;
1270             z_soap_error(assoc->encode, soap_package,
1271                          "SOAP-ENV:Client", "Bad method", 0); 
1272         }
1273         if (http_code == 200 || http_code == 500)
1274         {
1275             static Z_SOAP_Handler soap_handlers[3] = {
1276 #if HAVE_XML2
1277                 {"http://www.loc.gov/zing/srw/", 0,
1278                  (Z_SOAP_fun) yaz_srw_codec},
1279                 {"http://www.loc.gov/zing/srw/v1.0/", 0,
1280                  (Z_SOAP_fun) yaz_srw_codec},
1281 #endif
1282                 {0, 0, 0}
1283             };
1284             char ctype[60];
1285             int ret;
1286             p = z_get_HTTP_Response(o, 200);
1287             hres = p->u.HTTP_Response;
1288             ret = z_soap_codec_enc_xsl(assoc->encode, &soap_package,
1289                                        &hres->content_buf, &hres->content_len,
1290                                        soap_handlers, charset, stylesheet);
1291             hres->code = http_code;
1292
1293             strcpy(ctype, "text/xml");
1294             if (charset)
1295             {
1296                 strcat(ctype, "; charset=");
1297                 strcat(ctype, charset);
1298             }
1299             z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1300         }
1301         else
1302             p = z_get_HTTP_Response(o, http_code);
1303     }
1304
1305     if (p == 0)
1306         p = z_get_HTTP_Response(o, 500);
1307     hres = p->u.HTTP_Response;
1308     if (!strcmp(hreq->version, "1.0")) 
1309     {
1310         const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1311         if (v && !strcmp(v, "Keep-Alive"))
1312             keepalive = 1;
1313         else
1314             keepalive = 0;
1315         hres->version = "1.0";
1316     }
1317     else
1318     {
1319         const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1320         if (v && !strcmp(v, "close"))
1321             keepalive = 0;
1322         else
1323             keepalive = 1;
1324         hres->version = "1.1";
1325     }
1326     if (!keepalive)
1327     {
1328         z_HTTP_header_add(o, &hres->headers, "Connection", "close");
1329         assoc->state = ASSOC_DEAD;
1330         assoc->cs_get_mask = 0;
1331     }
1332     else
1333     {
1334         int t;
1335         const char *alive = z_HTTP_header_lookup(hreq->headers, "Keep-Alive");
1336
1337         if (alive && isdigit(*(const unsigned char *) alive))
1338             t = atoi(alive);
1339         else
1340             t = 15;
1341         if (t < 0 || t > 3600)
1342             t = 3600;
1343         iochan_settimeout(assoc->client_chan,t);
1344         z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1345     }
1346     process_gdu_response(assoc, req, p);
1347 }
1348
1349 static void process_gdu_request(association *assoc, request *req)
1350 {
1351     if (req->gdu_request->which == Z_GDU_Z3950)
1352     {
1353         char *msg = 0;
1354         req->apdu_request = req->gdu_request->u.z3950;
1355         if (process_z_request(assoc, req, &msg) < 0)
1356             do_close_req(assoc, Z_Close_systemProblem, msg, req);
1357     }
1358     else if (req->gdu_request->which == Z_GDU_HTTP_Request)
1359         process_http_request(assoc, req);
1360     else
1361     {
1362         do_close_req(assoc, Z_Close_systemProblem, "bad protocol packet", req);
1363     }
1364 }
1365
1366 /*
1367  * Initiate request processing.
1368  */
1369 static int process_z_request(association *assoc, request *req, char **msg)
1370 {
1371     int fd = -1;
1372     Z_APDU *res;
1373     int retval;
1374     
1375     *msg = "Unknown Error";
1376     assert(req && req->state == REQUEST_IDLE);
1377     if (req->apdu_request->which != Z_APDU_initRequest && !assoc->init)
1378     {
1379         *msg = "Missing InitRequest";
1380         return -1;
1381     }
1382     switch (req->apdu_request->which)
1383     {
1384     case Z_APDU_initRequest:
1385         res = process_initRequest(assoc, req); break;
1386     case Z_APDU_searchRequest:
1387         res = process_searchRequest(assoc, req, &fd); break;
1388     case Z_APDU_presentRequest:
1389         res = process_presentRequest(assoc, req, &fd); break;
1390     case Z_APDU_scanRequest:
1391         if (assoc->init->bend_scan)
1392             res = process_scanRequest(assoc, req, &fd);
1393         else
1394         {
1395             *msg = "Cannot handle Scan APDU";
1396             return -1;
1397         }
1398         break;
1399     case Z_APDU_extendedServicesRequest:
1400         if (assoc->init->bend_esrequest)
1401             res = process_ESRequest(assoc, req, &fd);
1402         else
1403         {
1404             *msg = "Cannot handle Extended Services APDU";
1405             return -1;
1406         }
1407         break;
1408     case Z_APDU_sortRequest:
1409         if (assoc->init->bend_sort)
1410             res = process_sortRequest(assoc, req, &fd);
1411         else
1412         {
1413             *msg = "Cannot handle Sort APDU";
1414             return -1;
1415         }
1416         break;
1417     case Z_APDU_close:
1418         process_close(assoc, req);
1419         return 0;
1420     case Z_APDU_deleteResultSetRequest:
1421         if (assoc->init->bend_delete)
1422             res = process_deleteRequest(assoc, req, &fd);
1423         else
1424         {
1425             *msg = "Cannot handle Delete APDU";
1426             return -1;
1427         }
1428         break;
1429     case Z_APDU_segmentRequest:
1430         if (assoc->init->bend_segment)
1431         {
1432             res = process_segmentRequest (assoc, req);
1433         }
1434         else
1435         {
1436             *msg = "Cannot handle Segment APDU";
1437             return -1;
1438         }
1439         break;
1440     case Z_APDU_triggerResourceControlRequest:
1441         return 0;
1442     default:
1443         *msg = "Bad APDU received";
1444         return -1;
1445     }
1446     if (res)
1447     {
1448         yaz_log(YLOG_DEBUG, "  result immediately available");
1449         retval = process_z_response(assoc, req, res);
1450     }
1451     else if (fd < 0)
1452     {
1453         yaz_log(YLOG_DEBUG, "  result unavailble");
1454         retval = 0;
1455     }
1456     else /* no result yet - one will be provided later */
1457     {
1458         IOCHAN chan;
1459
1460         /* Set up an I/O handler for the fd supplied by the backend */
1461
1462         yaz_log(YLOG_DEBUG, "   establishing handler for result");
1463         req->state = REQUEST_PENDING;
1464         if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT, 0)))
1465             abort();
1466         iochan_setdata(chan, assoc);
1467         retval = 0;
1468     }
1469     return retval;
1470 }
1471
1472 /*
1473  * Handle message from the backend.
1474  */
1475 void backend_response(IOCHAN i, int event)
1476 {
1477     association *assoc = (association *)iochan_getdata(i);
1478     request *req = request_head(&assoc->incoming);
1479     Z_APDU *res;
1480     int fd;
1481
1482     yaz_log(YLOG_DEBUG, "backend_response");
1483     assert(assoc && req && req->state != REQUEST_IDLE);
1484     /* determine what it is we're waiting for */
1485     switch (req->apdu_request->which)
1486     {
1487         case Z_APDU_searchRequest:
1488             res = response_searchRequest(assoc, req, 0, &fd); break;
1489 #if 0
1490         case Z_APDU_presentRequest:
1491             res = response_presentRequest(assoc, req, 0, &fd); break;
1492         case Z_APDU_scanRequest:
1493             res = response_scanRequest(assoc, req, 0, &fd); break;
1494 #endif
1495         default:
1496             yaz_log(YLOG_FATAL, "Serious programmer's lapse or bug");
1497             abort();
1498     }
1499     if ((res && process_z_response(assoc, req, res) < 0) || fd < 0)
1500     {
1501         yaz_log(YLOG_WARN, "Fatal error when talking to backend");
1502         do_close(assoc, Z_Close_systemProblem, 0);
1503         iochan_destroy(i);
1504         return;
1505     }
1506     else if (!res) /* no result yet - try again later */
1507     {
1508         yaz_log(YLOG_DEBUG, "   no result yet");
1509         iochan_setfd(i, fd); /* in case fd has changed */
1510     }
1511 }
1512
1513 /*
1514  * Encode response, and transfer the request structure to the outgoing queue.
1515  */
1516 static int process_gdu_response(association *assoc, request *req, Z_GDU *res)
1517 {
1518     odr_setbuf(assoc->encode, req->response, req->size_response, 1);
1519
1520     if (assoc->print)
1521     {
1522         if (!z_GDU(assoc->print, &res, 0, 0))
1523             yaz_log(YLOG_WARN, "ODR print error: %s", 
1524                 odr_errmsg(odr_geterror(assoc->print)));
1525         odr_reset(assoc->print);
1526     }
1527     if (!z_GDU(assoc->encode, &res, 0, 0))
1528     {
1529         yaz_log(YLOG_WARN, "ODR error when encoding PDU: %s [element %s]",
1530                 odr_errmsg(odr_geterror(assoc->decode)),
1531                 odr_getelement(assoc->decode));
1532         return -1;
1533     }
1534     req->response = odr_getbuf(assoc->encode, &req->len_response,
1535         &req->size_response);
1536     odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
1537     odr_reset(assoc->encode);
1538     req->state = REQUEST_IDLE;
1539     request_enq(&assoc->outgoing, req);
1540     /* turn the work over to the ir_session handler */
1541     iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
1542     assoc->cs_put_mask = EVENT_OUTPUT;
1543     /* Is there more work to be done? give that to the input handler too */
1544 #if 1
1545     if (request_head(&assoc->incoming))
1546     {
1547         yaz_log (YLOG_DEBUG, "more work to be done");
1548         iochan_setevent(assoc->client_chan, EVENT_WORK);
1549     }
1550 #endif
1551     return 0;
1552 }
1553
1554 /*
1555  * Encode response, and transfer the request structure to the outgoing queue.
1556  */
1557 static int process_z_response(association *assoc, request *req, Z_APDU *res)
1558 {
1559     Z_GDU *gres = (Z_GDU *) odr_malloc(assoc->encode, sizeof(*res));
1560     gres->which = Z_GDU_Z3950;
1561     gres->u.z3950 = res;
1562
1563     return process_gdu_response(assoc, req, gres);
1564 }
1565
1566 static char *get_vhost(Z_OtherInformation *otherInfo)
1567 {
1568     return yaz_oi_get_string_oidval(&otherInfo, VAL_PROXY, 1, 0);
1569 }
1570
1571 /*
1572  * Handle init request.
1573  * At the moment, we don't check the options
1574  * anywhere else in the code - we just try not to do anything that would
1575  * break a naive client. We'll toss 'em into the association block when
1576  * we need them there.
1577  */
1578 static Z_APDU *process_initRequest(association *assoc, request *reqb)
1579 {
1580     Z_InitRequest *req = reqb->apdu_request->u.initRequest;
1581     Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
1582     Z_InitResponse *resp = apdu->u.initResponse;
1583     bend_initresult *binitres;
1584     char *version;
1585     char options[140];
1586     statserv_options_block *cb = 0;  /* by default no control for backend */
1587
1588     if (control_association(assoc, get_vhost(req->otherInfo), 1))
1589         cb = statserv_getcontrol();  /* got control block for backend */
1590     
1591     yaz_log(log_requestdetail, "Got initRequest");
1592     if (req->implementationId)
1593         yaz_log(log_requestdetail, "Id:        %s",
1594                 req->implementationId);
1595     if (req->implementationName)
1596         yaz_log(log_requestdetail, "Name:      %s",
1597                 req->implementationName);
1598     if (req->implementationVersion)
1599         yaz_log(log_requestdetail, "Version:   %s",
1600                 req->implementationVersion);
1601     
1602     assoc_init_reset(assoc);
1603
1604     assoc->init->auth = req->idAuthentication;
1605     assoc->init->referenceId = req->referenceId;
1606
1607     if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
1608     {
1609         Z_CharSetandLanguageNegotiation *negotiation =
1610             yaz_get_charneg_record (req->otherInfo);
1611         if (negotiation &&
1612             negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
1613             assoc->init->charneg_request = negotiation;
1614     }
1615     
1616     assoc->backend = 0;
1617     if (cb)
1618     {
1619         if (req->implementationVersion)
1620             yaz_log(log_requestdetail, "Config:    %s",
1621                     cb->configname);
1622     
1623         iochan_settimeout(assoc->client_chan, cb->idle_timeout * 60);
1624         
1625         /* we have a backend control block, so call that init function */
1626         if (!(binitres = (*cb->bend_init)(assoc->init)))
1627         {
1628             yaz_log(YLOG_WARN, "Bad response from backend.");
1629             return 0;
1630         }
1631         assoc->backend = binitres->handle;
1632     }
1633     else
1634     {
1635         /* no backend. return error */
1636         binitres = odr_malloc(assoc->encode, sizeof(*binitres));
1637         binitres->errstring = 0;
1638         binitres->errcode = 1;
1639         iochan_settimeout(assoc->client_chan, 10);
1640     }
1641     if ((assoc->init->bend_sort))
1642         yaz_log (YLOG_DEBUG, "Sort handler installed");
1643     if ((assoc->init->bend_search))
1644         yaz_log (YLOG_DEBUG, "Search handler installed");
1645     if ((assoc->init->bend_present))
1646         yaz_log (YLOG_DEBUG, "Present handler installed");   
1647     if ((assoc->init->bend_esrequest))
1648         yaz_log (YLOG_DEBUG, "ESRequest handler installed");   
1649     if ((assoc->init->bend_delete))
1650         yaz_log (YLOG_DEBUG, "Delete handler installed");   
1651     if ((assoc->init->bend_scan))
1652         yaz_log (YLOG_DEBUG, "Scan handler installed");   
1653     if ((assoc->init->bend_segment))
1654         yaz_log (YLOG_DEBUG, "Segment handler installed");   
1655     
1656     resp->referenceId = req->referenceId;
1657     *options = '\0';
1658     /* let's tell the client what we can do */
1659     if (ODR_MASK_GET(req->options, Z_Options_search))
1660     {
1661         ODR_MASK_SET(resp->options, Z_Options_search);
1662         strcat(options, "srch");
1663     }
1664     if (ODR_MASK_GET(req->options, Z_Options_present))
1665     {
1666         ODR_MASK_SET(resp->options, Z_Options_present);
1667         strcat(options, " prst");
1668     }
1669     if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
1670         assoc->init->bend_delete)
1671     {
1672         ODR_MASK_SET(resp->options, Z_Options_delSet);
1673         strcat(options, " del");
1674     }
1675     if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
1676         assoc->init->bend_esrequest)
1677     {
1678         ODR_MASK_SET(resp->options, Z_Options_extendedServices);
1679         strcat (options, " extendedServices");
1680     }
1681     if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
1682     {
1683         ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
1684         strcat(options, " namedresults");
1685     }
1686     if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
1687     {
1688         ODR_MASK_SET(resp->options, Z_Options_scan);
1689         strcat(options, " scan");
1690     }
1691     if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
1692     {
1693         ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
1694         strcat(options, " concurrop");
1695     }
1696     if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
1697     {
1698         ODR_MASK_SET(resp->options, Z_Options_sort);
1699         strcat(options, " sort");
1700     }
1701
1702     if (ODR_MASK_GET(req->options, Z_Options_negotiationModel)
1703         && assoc->init->charneg_response)
1704     {
1705         Z_OtherInformation **p;
1706         Z_OtherInformationUnit *p0;
1707         
1708         yaz_oi_APDU(apdu, &p);
1709         
1710         if ((p0=yaz_oi_update(p, assoc->encode, NULL, 0, 0))) {
1711             ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
1712             
1713             p0->which = Z_OtherInfo_externallyDefinedInfo;
1714             p0->information.externallyDefinedInfo =
1715                 assoc->init->charneg_response;
1716         }
1717         ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
1718         strcat(options, " negotiation");
1719     }
1720         
1721     ODR_MASK_SET(resp->options, Z_Options_triggerResourceCtrl);
1722
1723     if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
1724     {
1725         ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
1726         assoc->version = 1; /* 1 & 2 are equivalent */
1727     }
1728     if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
1729     {
1730         ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
1731         assoc->version = 2;
1732     }
1733     if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
1734     {
1735         ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
1736         assoc->version = 3;
1737     }
1738
1739     yaz_log(log_requestdetail, "Negotiated to v%d: %s", assoc->version, options);
1740     assoc->maximumRecordSize = *req->maximumRecordSize;
1741
1742     if (cb && assoc->maximumRecordSize > cb->maxrecordsize)
1743         assoc->maximumRecordSize = cb->maxrecordsize;
1744     assoc->preferredMessageSize = *req->preferredMessageSize;
1745     if (assoc->preferredMessageSize > assoc->maximumRecordSize)
1746         assoc->preferredMessageSize = assoc->maximumRecordSize;
1747
1748     resp->preferredMessageSize = &assoc->preferredMessageSize;
1749     resp->maximumRecordSize = &assoc->maximumRecordSize;
1750
1751     resp->implementationId = odr_prepend(assoc->encode,
1752                 assoc->init->implementation_id,
1753                 resp->implementationId);
1754
1755     resp->implementationName = odr_prepend(assoc->encode,
1756                 assoc->init->implementation_name,
1757                 odr_prepend(assoc->encode, "GFS", resp->implementationName));
1758
1759     version = odr_strdup(assoc->encode, "$Revision: 1.49 $");
1760     if (strlen(version) > 10)   /* check for unexpanded CVS strings */
1761         version[strlen(version)-2] = '\0';
1762     resp->implementationVersion = odr_prepend(assoc->encode,
1763                 assoc->init->implementation_version,
1764                 odr_prepend(assoc->encode, &version[11],
1765                             resp->implementationVersion));
1766
1767     if (binitres->errcode)
1768     {
1769         assoc->state = ASSOC_DEAD;
1770         resp->userInformationField =
1771             init_diagnostics(assoc->encode, binitres->errcode,
1772                              binitres->errstring);
1773         *resp->result = 0;
1774     }
1775     if (log_request)
1776     {
1777         WRBUF wr = wrbuf_alloc();
1778         wrbuf_printf(wr, "Init ");
1779         if (binitres->errcode)
1780             wrbuf_printf(wr, "ERROR %d", binitres->errcode);
1781         else
1782             wrbuf_printf(wr, "OK -");
1783         wrbuf_printf(wr, " ID:%s Name:%s Version:%s",
1784                      (req->implementationId ? req->implementationId :"-"), 
1785                      (req->implementationName ?
1786                       req->implementationName : "-"),
1787                      (req->implementationVersion ?
1788                       req->implementationVersion : "-")
1789             );
1790         yaz_log(log_request, "%s", wrbuf_buf(wr));
1791         wrbuf_free(wr, 1);
1792     }
1793     return apdu;
1794 }
1795
1796 /*
1797  * Set the specified `errcode' and `errstring' into a UserInfo-1
1798  * external to be returned to the client in accordance with Z35.90
1799  * Implementor Agreement 5 (Returning diagnostics in an InitResponse):
1800  *      http://lcweb.loc.gov/z3950/agency/agree/initdiag.html
1801  */
1802 static Z_External *init_diagnostics(ODR odr, int error, const char *addinfo)
1803 {
1804     yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
1805         addinfo ? " -- " : "", addinfo ? addinfo : "");
1806     return zget_init_diagnostics(odr, error, addinfo);
1807 }
1808
1809 /*
1810  * nonsurrogate diagnostic record.
1811  */
1812 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
1813 {
1814     Z_Records *rec = (Z_Records *) odr_malloc (assoc->encode, sizeof(*rec));
1815
1816     yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
1817             addinfo ? " -- " : "", addinfo ? addinfo : "");
1818
1819     rec->which = Z_Records_NSD;
1820     rec->u.nonSurrogateDiagnostic = zget_DefaultDiagFormat(assoc->encode,
1821                                                            error, addinfo);
1822     return rec;
1823 }
1824
1825 /*
1826  * surrogate diagnostic.
1827  */
1828 static Z_NamePlusRecord *surrogatediagrec(association *assoc, 
1829                                           const char *dbname,
1830                                           int error, const char *addinfo)
1831 {
1832     yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
1833             addinfo ? " -- " : "", addinfo ? addinfo : "");
1834     return zget_surrogateDiagRec(assoc->encode, dbname, error, addinfo);
1835 }
1836
1837 static Z_Records *pack_records(association *a, char *setname, int start,
1838                                int *num, Z_RecordComposition *comp,
1839                                int *next, int *pres, oid_value format,
1840                                Z_ReferenceId *referenceId,
1841                                int *oid, int *errcode)
1842 {
1843     int recno, total_length = 0, toget = *num, dumped_records = 0;
1844     Z_Records *records =
1845         (Z_Records *) odr_malloc (a->encode, sizeof(*records));
1846     Z_NamePlusRecordList *reclist =
1847         (Z_NamePlusRecordList *) odr_malloc (a->encode, sizeof(*reclist));
1848     Z_NamePlusRecord **list =
1849         (Z_NamePlusRecord **) odr_malloc (a->encode, sizeof(*list) * toget);
1850
1851     records->which = Z_Records_DBOSD;
1852     records->u.databaseOrSurDiagnostics = reclist;
1853     reclist->num_records = 0;
1854     reclist->records = list;
1855     *pres = Z_PresentStatus_success;
1856     *num = 0;
1857     *next = 0;
1858
1859     yaz_log(log_requestdetail, "Request to pack %d+%d %s", start, toget, setname);
1860     yaz_log(log_requestdetail, "pms=%d, mrs=%d", a->preferredMessageSize,
1861         a->maximumRecordSize);
1862     for (recno = start; reclist->num_records < toget; recno++)
1863     {
1864         bend_fetch_rr freq;
1865         Z_NamePlusRecord *thisrec;
1866         int this_length = 0;
1867         /*
1868          * we get the number of bytes allocated on the stream before any
1869          * allocation done by the backend - this should give us a reasonable
1870          * idea of the total size of the data so far.
1871          */
1872         total_length = odr_total(a->encode) - dumped_records;
1873         freq.errcode = 0;
1874         freq.errstring = 0;
1875         freq.basename = 0;
1876         freq.len = 0;
1877         freq.record = 0;
1878         freq.last_in_set = 0;
1879         freq.setname = setname;
1880         freq.surrogate_flag = 0;
1881         freq.number = recno;
1882         freq.comp = comp;
1883         freq.request_format = format;
1884         freq.request_format_raw = oid;
1885         freq.output_format = format;
1886         freq.output_format_raw = 0;
1887         freq.stream = a->encode;
1888         freq.print = a->print;
1889         freq.referenceId = referenceId;
1890         freq.schema = 0;
1891         (*a->init->bend_fetch)(a->backend, &freq);
1892         /* backend should be able to signal whether error is system-wide
1893            or only pertaining to current record */
1894         if (freq.errcode)
1895         {
1896             if (!freq.surrogate_flag)
1897             {
1898                 char s[20];
1899                 *pres = Z_PresentStatus_failure;
1900                 /* for 'present request out of range',
1901                    set addinfo to record position if not set */
1902                 if (freq.errcode == 13 && freq.errstring == 0)
1903                 {
1904                     sprintf (s, "%d", recno);
1905                     freq.errstring = s;
1906                 }
1907                 if (errcode)
1908                     *errcode = freq.errcode;
1909                 return diagrec(a, freq.errcode, freq.errstring);
1910             }
1911             reclist->records[reclist->num_records] =
1912                 surrogatediagrec(a, freq.basename, freq.errcode,
1913                                  freq.errstring);
1914             reclist->num_records++;
1915             *next = freq.last_in_set ? 0 : recno + 1;
1916             continue;
1917         }
1918         if (freq.len >= 0)
1919             this_length = freq.len;
1920         else
1921             this_length = odr_total(a->encode) - total_length - dumped_records;
1922         yaz_log(YLOG_DEBUG, "  fetched record, len=%d, total=%d dumped=%d",
1923             this_length, total_length, dumped_records);
1924         if (a->preferredMessageSize > 0 &&
1925                 this_length + total_length > a->preferredMessageSize)
1926         {
1927             /* record is small enough, really */
1928             if (this_length <= a->preferredMessageSize && recno > start)
1929             {
1930                 yaz_log(log_requestdetail, "  Dropped last normal-sized record");
1931                 *pres = Z_PresentStatus_partial_2;
1932                 break;
1933             }
1934             /* record can only be fetched by itself */
1935             if (this_length < a->maximumRecordSize)
1936             {
1937                 yaz_log(log_requestdetail, "  Record > prefmsgsz");
1938                 if (toget > 1)
1939                 {
1940                     yaz_log(YLOG_DEBUG, "  Dropped it");
1941                     reclist->records[reclist->num_records] =
1942                          surrogatediagrec(a, freq.basename, 16, 0);
1943                     reclist->num_records++;
1944                     *next = freq.last_in_set ? 0 : recno + 1;
1945                     dumped_records += this_length;
1946                     continue;
1947                 }
1948             }
1949             else /* too big entirely */
1950             {
1951                 yaz_log(log_requestdetail, "Record > maxrcdsz this=%d max=%d",
1952                         this_length, a->maximumRecordSize);
1953                 reclist->records[reclist->num_records] =
1954                     surrogatediagrec(a, freq.basename, 17, 0);
1955                 reclist->num_records++;
1956                 *next = freq.last_in_set ? 0 : recno + 1;
1957                 dumped_records += this_length;
1958                 continue;
1959             }
1960         }
1961
1962         if (!(thisrec = (Z_NamePlusRecord *)
1963               odr_malloc(a->encode, sizeof(*thisrec))))
1964             return 0;
1965         if (!(thisrec->databaseName = (char *)odr_malloc(a->encode,
1966             strlen(freq.basename) + 1)))
1967             return 0;
1968         strcpy(thisrec->databaseName, freq.basename);
1969         thisrec->which = Z_NamePlusRecord_databaseRecord;
1970
1971         if (freq.output_format_raw)
1972         {
1973             struct oident *ident = oid_getentbyoid(freq.output_format_raw);
1974             freq.output_format = ident->value;
1975         }
1976         thisrec->u.databaseRecord = z_ext_record(a->encode, freq.output_format,
1977                                                  freq.record, freq.len);
1978         if (!thisrec->u.databaseRecord)
1979             return 0;
1980         reclist->records[reclist->num_records] = thisrec;
1981         reclist->num_records++;
1982         *next = freq.last_in_set ? 0 : recno + 1;
1983     }
1984     *num = reclist->num_records;
1985     return records;
1986 }
1987
1988 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
1989     int *fd)
1990 {
1991     Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
1992     bend_search_rr *bsrr = 
1993         (bend_search_rr *)nmem_malloc (reqb->request_mem, sizeof(*bsrr));
1994     
1995     yaz_log(log_requestdetail, "Got SearchRequest.");
1996     bsrr->fd = fd;
1997     bsrr->request = reqb;
1998     bsrr->association = assoc;
1999     bsrr->referenceId = req->referenceId;
2000     save_referenceId (reqb, bsrr->referenceId);
2001
2002     yaz_log (log_requestdetail, "ResultSet '%s'", req->resultSetName);
2003     if (req->databaseNames)
2004     {
2005         int i;
2006         for (i = 0; i < req->num_databaseNames; i++)
2007             yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
2008     }
2009
2010     yaz_log_zquery_level(log_requestdetail,req->query);
2011
2012     if (assoc->init->bend_search)
2013     {
2014         bsrr->setname = req->resultSetName;
2015         bsrr->replace_set = *req->replaceIndicator;
2016         bsrr->num_bases = req->num_databaseNames;
2017         bsrr->basenames = req->databaseNames;
2018         bsrr->query = req->query;
2019         bsrr->stream = assoc->encode;
2020         nmem_transfer(bsrr->stream->mem, reqb->request_mem);
2021         bsrr->decode = assoc->decode;
2022         bsrr->print = assoc->print;
2023         bsrr->hits = 0;
2024         bsrr->errcode = 0;
2025         bsrr->errstring = NULL;
2026         bsrr->search_info = NULL;
2027
2028         if (assoc->cql_transform &&
2029             req->query->which == Z_Query_type_104 &&
2030             req->query->u.type_104->which == Z_External_CQL)
2031         {
2032             /* have a CQL query and a CQL to PQF transform .. */
2033             int srw_errcode = 
2034                 cql2pqf(bsrr->stream, req->query->u.type_104->u.cql,
2035                         assoc->cql_transform, bsrr->query);
2036             if (srw_errcode)
2037                 bsrr->errcode = yaz_diag_srw_to_bib1(srw_errcode);
2038         }
2039         if (!bsrr->errcode)
2040             (assoc->init->bend_search)(assoc->backend, bsrr);
2041         if (!bsrr->request)  /* backend not ready with the search response */
2042             return 0;  /* should not be used any more */
2043     }
2044     else
2045     { 
2046         /* FIXME - make a diagnostic for it */
2047         yaz_log(YLOG_WARN,"Search not supported ?!?!");
2048     }
2049     return response_searchRequest(assoc, reqb, bsrr, fd);
2050 }
2051
2052 int bend_searchresponse(void *handle, bend_search_rr *bsrr) {return 0;}
2053
2054 /*
2055  * Prepare a searchresponse based on the backend results. We probably want
2056  * to look at making the fetching of records nonblocking as well, but
2057  * so far, we'll keep things simple.
2058  * If bsrt is null, that means we're called in response to a communications
2059  * event, and we'll have to get the response for ourselves.
2060  */
2061 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
2062     bend_search_rr *bsrt, int *fd)
2063 {
2064     Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2065     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2066     Z_SearchResponse *resp = (Z_SearchResponse *)
2067         odr_malloc (assoc->encode, sizeof(*resp));
2068     int *nulint = odr_intdup (assoc->encode, 0);
2069     bool_t *sr = odr_intdup(assoc->encode, 1);
2070     int *next = odr_intdup(assoc->encode, 0);
2071     int *none = odr_intdup(assoc->encode, Z_SearchResponse_none);
2072     int returnedrecs=0;
2073
2074     apdu->which = Z_APDU_searchResponse;
2075     apdu->u.searchResponse = resp;
2076     resp->referenceId = req->referenceId;
2077     resp->additionalSearchInfo = 0;
2078     resp->otherInfo = 0;
2079     *fd = -1;
2080     if (!bsrt && !bend_searchresponse(assoc->backend, bsrt))
2081     {
2082         yaz_log(YLOG_FATAL, "Bad result from backend");
2083         return 0;
2084     }
2085     else if (bsrt->errcode)
2086     {
2087         resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
2088         resp->resultCount = nulint;
2089         resp->numberOfRecordsReturned = nulint;
2090         resp->nextResultSetPosition = nulint;
2091         resp->searchStatus = nulint;
2092         resp->resultSetStatus = none;
2093         resp->presentStatus = 0;
2094     }
2095     else
2096     {
2097         int *toget = odr_intdup(assoc->encode, 0);
2098         int *presst = odr_intdup(assoc->encode, 0);
2099         Z_RecordComposition comp, *compp = 0;
2100
2101         yaz_log (log_requestdetail, "resultCount: %d", bsrt->hits);
2102
2103         resp->records = 0;
2104         resp->resultCount = &bsrt->hits;
2105
2106         comp.which = Z_RecordComp_simple;
2107         /* how many records does the user agent want, then? */
2108         if (bsrt->hits <= *req->smallSetUpperBound)
2109         {
2110             *toget = bsrt->hits;
2111             if ((comp.u.simple = req->smallSetElementSetNames))
2112                 compp = &comp;
2113         }
2114         else if (bsrt->hits < *req->largeSetLowerBound)
2115         {
2116             *toget = *req->mediumSetPresentNumber;
2117             if (*toget > bsrt->hits)
2118                 *toget = bsrt->hits;
2119             if ((comp.u.simple = req->mediumSetElementSetNames))
2120                 compp = &comp;
2121         }
2122         else
2123             *toget = 0;
2124
2125         if (*toget && !resp->records)
2126         {
2127             oident *prefformat;
2128             oid_value form;
2129
2130             if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
2131                 form = VAL_NONE;
2132             else
2133                 form = prefformat->value;
2134             resp->records = pack_records(assoc, req->resultSetName, 1,
2135                                          toget, compp, next, presst, form, req->referenceId,
2136                                          req->preferredRecordSyntax, NULL);
2137             if (!resp->records)
2138                 return 0;
2139             resp->numberOfRecordsReturned = toget;
2140             returnedrecs = *toget;
2141             resp->nextResultSetPosition = next;
2142             resp->searchStatus = sr;
2143             resp->resultSetStatus = 0;
2144             resp->presentStatus = presst;
2145         }
2146         else
2147         {
2148             if (*resp->resultCount)
2149                 *next = 1;
2150             resp->numberOfRecordsReturned = nulint;
2151             resp->nextResultSetPosition = next;
2152             resp->searchStatus = sr;
2153             resp->resultSetStatus = 0;
2154             resp->presentStatus = 0;
2155         }
2156     }
2157     resp->additionalSearchInfo = bsrt->search_info;
2158
2159     if (log_request)
2160     {
2161         WRBUF wr = wrbuf_alloc();
2162         if (bsrt->errcode)
2163             wrbuf_printf(wr, "ERROR %d", bsrt->errcode);
2164         else
2165             wrbuf_printf(wr, "OK %d", bsrt->hits);
2166         wrbuf_printf(wr, " %s 1+%d ",
2167                      req->resultSetName, returnedrecs);
2168         wrbuf_put_zquery(wr, req->query);
2169         
2170         yaz_log(log_request, "Search %s", wrbuf_buf(wr));
2171         wrbuf_free(wr, 1);
2172     }
2173     return apdu;
2174 }
2175
2176 /*
2177  * Maybe we got a little over-friendly when we designed bend_fetch to
2178  * get only one record at a time. Some backends can optimise multiple-record
2179  * fetches, and at any rate, there is some overhead involved in
2180  * all that selecting and hopping around. Problem is, of course, that the
2181  * frontend can't know ahead of time how many records it'll need to
2182  * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
2183  * is downright lousy as a bulk data transfer protocol.
2184  *
2185  * To start with, we'll do the fetching of records from the backend
2186  * in one operation: To save some trips in and out of the event-handler,
2187  * and to simplify the interface to pack_records. At any rate, asynch
2188  * operation is more fun in operations that have an unpredictable execution
2189  * speed - which is normally more true for search than for present.
2190  */
2191 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
2192                                       int *fd)
2193 {
2194     Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
2195     oident *prefformat;
2196     oid_value form;
2197     Z_APDU *apdu;
2198     Z_PresentResponse *resp;
2199     int *next;
2200     int *num;
2201     int errcode = 0;
2202     const char *errstring = 0;
2203
2204     yaz_log(log_requestdetail, "Got PresentRequest.");
2205
2206     if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
2207         form = VAL_NONE;
2208     else
2209         form = prefformat->value;
2210     resp = (Z_PresentResponse *)odr_malloc (assoc->encode, sizeof(*resp));
2211     resp->records = 0;
2212     resp->presentStatus = odr_intdup(assoc->encode, 0);
2213     if (assoc->init->bend_present)
2214     {
2215         bend_present_rr *bprr = (bend_present_rr *)
2216             nmem_malloc (reqb->request_mem, sizeof(*bprr));
2217         bprr->setname = req->resultSetId;
2218         bprr->start = *req->resultSetStartPoint;
2219         bprr->number = *req->numberOfRecordsRequested;
2220         bprr->format = form;
2221         bprr->comp = req->recordComposition;
2222         bprr->referenceId = req->referenceId;
2223         bprr->stream = assoc->encode;
2224         bprr->print = assoc->print;
2225         bprr->request = reqb;
2226         bprr->association = assoc;
2227         bprr->errcode = 0;
2228         bprr->errstring = NULL;
2229         (*assoc->init->bend_present)(assoc->backend, bprr);
2230         
2231         if (!bprr->request)
2232             return 0; /* should not happen */
2233         if (bprr->errcode)
2234         {
2235             resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2236             *resp->presentStatus = Z_PresentStatus_failure;
2237             errcode = bprr->errcode;
2238             errstring = bprr->errstring;
2239         }
2240     }
2241     apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2242     next = odr_intdup(assoc->encode, 0);
2243     num = odr_intdup(assoc->encode, 0);
2244     
2245     apdu->which = Z_APDU_presentResponse;
2246     apdu->u.presentResponse = resp;
2247     resp->referenceId = req->referenceId;
2248     resp->otherInfo = 0;
2249     
2250     if (!resp->records)
2251     {
2252         *num = *req->numberOfRecordsRequested;
2253         resp->records =
2254             pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
2255                          num, req->recordComposition, next,
2256                          resp->presentStatus,
2257                          form, req->referenceId, req->preferredRecordSyntax, 
2258                          &errcode);
2259     }
2260     if (log_request)
2261     {
2262         WRBUF wr = wrbuf_alloc();
2263         wrbuf_printf(wr, "Present ");
2264
2265         if (*resp->presentStatus == Z_PresentStatus_failure)
2266             wrbuf_printf(wr, "ERROR %d", errcode);
2267         else if (*resp->presentStatus == Z_PresentStatus_success)
2268             wrbuf_printf(wr, "OK -");
2269         else
2270             wrbuf_printf(wr, "Partial %d", *resp->presentStatus);
2271
2272         wrbuf_printf(wr, " %s %d+%d ",
2273                 req->resultSetId, *req->resultSetStartPoint,
2274                 *req->numberOfRecordsRequested);
2275         yaz_log(log_request, "%s", wrbuf_buf(wr) );
2276         wrbuf_free(wr, 1);
2277     }
2278     if (!resp->records)
2279         return 0;
2280     resp->numberOfRecordsReturned = num;
2281     resp->nextResultSetPosition = next;
2282     
2283     return apdu;
2284 }
2285
2286 /*
2287  * Scan was implemented rather in a hurry, and with support for only the basic
2288  * elements of the service in the backend API. Suggestions are welcome.
2289  */
2290 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
2291 {
2292     Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
2293     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2294     Z_ScanResponse *res = (Z_ScanResponse *)
2295         odr_malloc (assoc->encode, sizeof(*res));
2296     int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
2297     int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
2298     Z_ListEntries *ents = (Z_ListEntries *)
2299         odr_malloc (assoc->encode, sizeof(*ents));
2300     Z_DiagRecs *diagrecs_p = NULL;
2301     oident *attset;
2302     bend_scan_rr *bsrr = (bend_scan_rr *)
2303         odr_malloc (assoc->encode, sizeof(*bsrr));
2304     struct scan_entry *save_entries;
2305
2306     yaz_log(log_requestdetail, "Got ScanRequest");
2307
2308     apdu->which = Z_APDU_scanResponse;
2309     apdu->u.scanResponse = res;
2310     res->referenceId = req->referenceId;
2311
2312     /* if step is absent, set it to 0 */
2313     res->stepSize = odr_intdup(assoc->encode, 0);
2314     if (req->stepSize)
2315         *res->stepSize = *req->stepSize;
2316
2317     res->scanStatus = scanStatus;
2318     res->numberOfEntriesReturned = numberOfEntriesReturned;
2319     res->positionOfTerm = 0;
2320     res->entries = ents;
2321     ents->num_entries = 0;
2322     ents->entries = NULL;
2323     ents->num_nonsurrogateDiagnostics = 0;
2324     ents->nonsurrogateDiagnostics = NULL;
2325     res->attributeSet = 0;
2326     res->otherInfo = 0;
2327
2328     if (req->databaseNames)
2329     {
2330         int i;
2331         for (i = 0; i < req->num_databaseNames; i++)
2332             yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
2333     }
2334     yaz_log(log_requestdetail, "pos %d  step %d  entries %d",
2335             *req->preferredPositionInResponse, *res->stepSize, 
2336             *req->numberOfTermsRequested);
2337     bsrr->num_bases = req->num_databaseNames;
2338     bsrr->basenames = req->databaseNames;
2339     bsrr->num_entries = *req->numberOfTermsRequested;
2340     bsrr->term = req->termListAndStartPoint;
2341     bsrr->referenceId = req->referenceId;
2342     bsrr->stream = assoc->encode;
2343     bsrr->print = assoc->print;
2344     bsrr->step_size = res->stepSize;
2345     bsrr->entries = 0;
2346     /* For YAZ 2.0 and earlier it was the backend handler that
2347        initialized entries (member display_term did not exist)
2348        YAZ 2.0 and later sets 'entries'  and initialize all members
2349        including 'display_term'. If YAZ 2.0 or later sees that
2350        entries was modified - we assume that it is an old handler and
2351        that 'display_term' is _not_ set.
2352     */
2353     if (bsrr->num_entries > 0) 
2354     {
2355         int i;
2356         bsrr->entries = odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
2357                                    bsrr->num_entries);
2358         for (i = 0; i<bsrr->num_entries; i++)
2359         {
2360             bsrr->entries[i].term = 0;
2361             bsrr->entries[i].occurrences = 0;
2362             bsrr->entries[i].errcode = 0;
2363             bsrr->entries[i].errstring = 0;
2364             bsrr->entries[i].display_term = 0;
2365         }
2366     }
2367     save_entries = bsrr->entries;  /* save it so we can compare later */
2368
2369     if (req->attributeSet &&
2370         (attset = oid_getentbyoid(req->attributeSet)) &&
2371         (attset->oclass == CLASS_ATTSET || attset->oclass == CLASS_GENERAL))
2372         bsrr->attributeset = attset->value;
2373     else
2374         bsrr->attributeset = VAL_NONE;
2375     log_scan_term_level (log_requestdetail, req->termListAndStartPoint, 
2376             bsrr->attributeset);
2377     bsrr->term_position = req->preferredPositionInResponse ?
2378         *req->preferredPositionInResponse : 1;
2379
2380     ((int (*)(void *, bend_scan_rr *))
2381      (*assoc->init->bend_scan))(assoc->backend, bsrr);
2382
2383     if (bsrr->errcode)
2384         diagrecs_p = zget_DiagRecs(assoc->encode,
2385                                    bsrr->errcode, bsrr->errstring);
2386     else
2387     {
2388         int i;
2389         Z_Entry **tab = (Z_Entry **)
2390             odr_malloc (assoc->encode, sizeof(*tab) * bsrr->num_entries);
2391         
2392         if (bsrr->status == BEND_SCAN_PARTIAL)
2393             *scanStatus = Z_Scan_partial_5;
2394         else
2395             *scanStatus = Z_Scan_success;
2396         ents->entries = tab;
2397         ents->num_entries = bsrr->num_entries;
2398         res->numberOfEntriesReturned = &ents->num_entries;          
2399         res->positionOfTerm = &bsrr->term_position;
2400         for (i = 0; i < bsrr->num_entries; i++)
2401         {
2402             Z_Entry *e;
2403             Z_TermInfo *t;
2404             Odr_oct *o;
2405             
2406             tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
2407             if (bsrr->entries[i].occurrences >= 0)
2408             {
2409                 e->which = Z_Entry_termInfo;
2410                 e->u.termInfo = t = (Z_TermInfo *)
2411                     odr_malloc(assoc->encode, sizeof(*t));
2412                 t->suggestedAttributes = 0;
2413                 t->displayTerm = 0;
2414                 if (save_entries == bsrr->entries && 
2415                     bsrr->entries[i].display_term)
2416                 {
2417                     /* the entries was _not_ set by the handler. So it's
2418                        safe to test for new member display_term. It is
2419                        NULL'ed by us.
2420                     */
2421                     t->displayTerm = odr_strdup(assoc->encode,
2422                                                 bsrr->entries[i].display_term);
2423                 }
2424                 t->alternativeTerm = 0;
2425                 t->byAttributes = 0;
2426                 t->otherTermInfo = 0;
2427                 t->globalOccurrences = &bsrr->entries[i].occurrences;
2428                 t->term = (Z_Term *)
2429                     odr_malloc(assoc->encode, sizeof(*t->term));
2430                 t->term->which = Z_Term_general;
2431                 t->term->u.general = o =
2432                     (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
2433                 o->buf = (unsigned char *)
2434                     odr_malloc(assoc->encode, o->len = o->size =
2435                                strlen(bsrr->entries[i].term));
2436                 memcpy(o->buf, bsrr->entries[i].term, o->len);
2437                 yaz_log(YLOG_DEBUG, "  term #%d: '%s' (%d)", i,
2438                          bsrr->entries[i].term, bsrr->entries[i].occurrences);
2439             }
2440             else
2441             {
2442                 Z_DiagRecs *drecs = zget_DiagRecs(assoc->encode,
2443                                                   bsrr->entries[i].errcode,
2444                                                   bsrr->entries[i].errstring);
2445                 assert (drecs->num_diagRecs == 1);
2446                 e->which = Z_Entry_surrogateDiagnostic;
2447                 assert (drecs->diagRecs[0]);
2448                 e->u.surrogateDiagnostic = drecs->diagRecs[0];
2449             }
2450         }
2451     }
2452     if (diagrecs_p)
2453     {
2454         ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
2455         ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
2456     }
2457     if (log_request)
2458     {
2459         WRBUF wr = wrbuf_alloc();
2460         if (bsrr->errcode)
2461             wr_diag(wr, bsrr->errcode, bsrr->errstring);
2462         else if (*res->scanStatus == Z_Scan_success)
2463             wrbuf_printf(wr, "OK");
2464         else
2465             wrbuf_printf(wr, "Partial");
2466
2467         wrbuf_printf(wr, " %d+%d %d ",
2468                      *req->preferredPositionInResponse, 
2469                      *req->numberOfTermsRequested,
2470                      (res->stepSize ? *res->stepSize : 0));
2471         wrbuf_scan_term(wr, req->termListAndStartPoint, 
2472                         bsrr->attributeset);
2473         
2474         yaz_log(log_request, "Scan %s", wrbuf_buf(wr) );
2475         wrbuf_free(wr, 1);
2476     }
2477     return apdu;
2478 }
2479
2480 static Z_APDU *process_sortRequest(association *assoc, request *reqb,
2481     int *fd)
2482 {
2483     int i;
2484     Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
2485     Z_SortResponse *res = (Z_SortResponse *)
2486         odr_malloc (assoc->encode, sizeof(*res));
2487     bend_sort_rr *bsrr = (bend_sort_rr *)
2488         odr_malloc (assoc->encode, sizeof(*bsrr));
2489
2490     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2491
2492     yaz_log(log_requestdetail, "Got SortRequest.");
2493
2494     bsrr->num_input_setnames = req->num_inputResultSetNames;
2495     for (i=0;i<req->num_inputResultSetNames;i++)
2496         yaz_log(log_requestdetail, "Input resultset: '%s'",
2497                 req->inputResultSetNames[i]);
2498     bsrr->input_setnames = req->inputResultSetNames;
2499     bsrr->referenceId = req->referenceId;
2500     bsrr->output_setname = req->sortedResultSetName;
2501     yaz_log(log_requestdetail, "Output resultset: '%s'",
2502                 req->sortedResultSetName);
2503     bsrr->sort_sequence = req->sortSequence;
2504        /*FIXME - dump those sequences too */
2505     bsrr->stream = assoc->encode;
2506     bsrr->print = assoc->print;
2507
2508     bsrr->sort_status = Z_SortResponse_failure;
2509     bsrr->errcode = 0;
2510     bsrr->errstring = 0;
2511     
2512     (*assoc->init->bend_sort)(assoc->backend, bsrr);
2513     
2514     res->referenceId = bsrr->referenceId;
2515     res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
2516     res->resultSetStatus = 0;
2517     if (bsrr->errcode)
2518     {
2519         Z_DiagRecs *dr = zget_DiagRecs(assoc->encode,
2520                                        bsrr->errcode, bsrr->errstring);
2521         res->diagnostics = dr->diagRecs;
2522         res->num_diagnostics = dr->num_diagRecs;
2523     }
2524     else
2525     {
2526         res->num_diagnostics = 0;
2527         res->diagnostics = 0;
2528     }
2529     res->resultCount = 0;
2530     res->otherInfo = 0;
2531
2532     apdu->which = Z_APDU_sortResponse;
2533     apdu->u.sortResponse = res;
2534     if (log_request)
2535     {
2536         WRBUF wr = wrbuf_alloc();
2537         wrbuf_printf(wr, "Sort ");
2538         if (bsrr->errcode)
2539             wrbuf_printf(wr, " ERROR %d", bsrr->errcode);
2540         else
2541             wrbuf_printf(wr,  "OK -");
2542         wrbuf_printf(wr, " (");
2543         for (i = 0; i<req->num_inputResultSetNames; i++)
2544         {
2545             if (i)
2546                 wrbuf_printf(wr, ",");
2547             wrbuf_printf(wr, req->inputResultSetNames[i]);
2548         }
2549         wrbuf_printf(wr, ")->%s ",req->sortedResultSetName);
2550
2551         yaz_log(log_request, "%s", wrbuf_buf(wr) );
2552         wrbuf_free(wr, 1);
2553     }
2554     return apdu;
2555 }
2556
2557 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
2558     int *fd)
2559 {
2560     int i;
2561     Z_DeleteResultSetRequest *req =
2562         reqb->apdu_request->u.deleteResultSetRequest;
2563     Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
2564         odr_malloc (assoc->encode, sizeof(*res));
2565     bend_delete_rr *bdrr = (bend_delete_rr *)
2566         odr_malloc (assoc->encode, sizeof(*bdrr));
2567     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2568
2569     yaz_log(log_requestdetail, "Got DeleteRequest.");
2570
2571     bdrr->num_setnames = req->num_resultSetList;
2572     bdrr->setnames = req->resultSetList;
2573     for (i = 0; i<req->num_resultSetList; i++)
2574         yaz_log(log_requestdetail, "resultset: '%s'",
2575                 req->resultSetList[i]);
2576     bdrr->stream = assoc->encode;
2577     bdrr->print = assoc->print;
2578     bdrr->function = *req->deleteFunction;
2579     bdrr->referenceId = req->referenceId;
2580     bdrr->statuses = 0;
2581     if (bdrr->num_setnames > 0)
2582     {
2583         bdrr->statuses = (int*) 
2584             odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
2585                        bdrr->num_setnames);
2586         for (i = 0; i < bdrr->num_setnames; i++)
2587             bdrr->statuses[i] = 0;
2588     }
2589     (*assoc->init->bend_delete)(assoc->backend, bdrr);
2590     
2591     res->referenceId = req->referenceId;
2592
2593     res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
2594
2595     res->deleteListStatuses = 0;
2596     if (bdrr->num_setnames > 0)
2597     {
2598         int i;
2599         res->deleteListStatuses = (Z_ListStatuses *)
2600             odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
2601         res->deleteListStatuses->num = bdrr->num_setnames;
2602         res->deleteListStatuses->elements =
2603             (Z_ListStatus **)
2604             odr_malloc (assoc->encode, 
2605                         sizeof(*res->deleteListStatuses->elements) *
2606                         bdrr->num_setnames);
2607         for (i = 0; i<bdrr->num_setnames; i++)
2608         {
2609             res->deleteListStatuses->elements[i] =
2610                 (Z_ListStatus *)
2611                 odr_malloc (assoc->encode,
2612                             sizeof(**res->deleteListStatuses->elements));
2613             res->deleteListStatuses->elements[i]->status = bdrr->statuses+i;
2614             res->deleteListStatuses->elements[i]->id =
2615                 odr_strdup (assoc->encode, bdrr->setnames[i]);
2616         }
2617     }
2618     res->numberNotDeleted = 0;
2619     res->bulkStatuses = 0;
2620     res->deleteMessage = 0;
2621     res->otherInfo = 0;
2622
2623     apdu->which = Z_APDU_deleteResultSetResponse;
2624     apdu->u.deleteResultSetResponse = res;
2625     if (log_request)
2626     {
2627         WRBUF wr = wrbuf_alloc();
2628         wrbuf_printf(wr, "Delete ");
2629         if (bdrr->delete_status)
2630             wrbuf_printf(wr, "ERROR %d", bdrr->delete_status);
2631         else
2632             wrbuf_printf(wr, "OK -");
2633         for (i = 0; i<req->num_resultSetList; i++)
2634             wrbuf_printf(wr, " %s ", req->resultSetList[i]);
2635         yaz_log(log_request, "%s", wrbuf_buf(wr) );
2636         wrbuf_free(wr, 1);
2637     }
2638     return apdu;
2639 }
2640
2641 static void process_close(association *assoc, request *reqb)
2642 {
2643     Z_Close *req = reqb->apdu_request->u.close;
2644     static char *reasons[] =
2645     {
2646         "finished",
2647         "shutdown",
2648         "systemProblem",
2649         "costLimit",
2650         "resources",
2651         "securityViolation",
2652         "protocolError",
2653         "lackOfActivity",
2654         "peerAbort",
2655         "unspecified"
2656     };
2657
2658     yaz_log(log_requestdetail, "Got Close, reason %s, message %s",
2659         reasons[*req->closeReason], req->diagnosticInformation ?
2660         req->diagnosticInformation : "NULL");
2661     if (assoc->version < 3) /* to make do_force respond with close */
2662         assoc->version = 3;
2663     do_close_req(assoc, Z_Close_finished,
2664                  "Association terminated by client", reqb);
2665     yaz_log(log_request,"Close OK");
2666 }
2667
2668 void save_referenceId (request *reqb, Z_ReferenceId *refid)
2669 {
2670     if (refid)
2671     {
2672         reqb->len_refid = refid->len;
2673         reqb->refid = (char *)nmem_malloc (reqb->request_mem, refid->len);
2674         memcpy (reqb->refid, refid->buf, refid->len);
2675     }
2676     else
2677     {
2678         reqb->len_refid = 0;
2679         reqb->refid = NULL;
2680     }
2681 }
2682
2683 void bend_request_send (bend_association a, bend_request req, Z_APDU *res)
2684 {
2685     process_z_response (a, req, res);
2686 }
2687
2688 bend_request bend_request_mk (bend_association a)
2689 {
2690     request *nreq = request_get (&a->outgoing);
2691     nreq->request_mem = nmem_create ();
2692     return nreq;
2693 }
2694
2695 Z_ReferenceId *bend_request_getid (ODR odr, bend_request req)
2696 {
2697     Z_ReferenceId *id;
2698     if (!req->refid)
2699         return 0;
2700     id = (Odr_oct *)odr_malloc (odr, sizeof(*odr));
2701     id->buf = (unsigned char *)odr_malloc (odr, req->len_refid);
2702     id->len = id->size = req->len_refid;
2703     memcpy (id->buf, req->refid, req->len_refid);
2704     return id;
2705 }
2706
2707 void bend_request_destroy (bend_request *req)
2708 {
2709     nmem_destroy((*req)->request_mem);
2710     request_release(*req);
2711     *req = NULL;
2712 }
2713
2714 int bend_backend_respond (bend_association a, bend_request req)
2715 {
2716     char *msg;
2717     int r;
2718     r = process_z_request (a, req, &msg);
2719     if (r < 0)
2720         yaz_log (YLOG_WARN, "%s", msg);
2721     return r;
2722 }
2723
2724 void bend_request_setdata(bend_request r, void *p)
2725 {
2726     r->clientData = p;
2727 }
2728
2729 void *bend_request_getdata(bend_request r)
2730 {
2731     return r->clientData;
2732 }
2733
2734 static Z_APDU *process_segmentRequest (association *assoc, request *reqb)
2735 {
2736     bend_segment_rr req;
2737
2738     req.segment = reqb->apdu_request->u.segmentRequest;
2739     req.stream = assoc->encode;
2740     req.decode = assoc->decode;
2741     req.print = assoc->print;
2742     req.association = assoc;
2743     
2744     (*assoc->init->bend_segment)(assoc->backend, &req);
2745
2746     return 0;
2747 }
2748
2749 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd)
2750 {
2751     bend_esrequest_rr esrequest;
2752
2753     Z_ExtendedServicesRequest *req =
2754         reqb->apdu_request->u.extendedServicesRequest;
2755     Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
2756
2757     Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
2758
2759     yaz_log(log_requestdetail,"Got EsRequest");
2760
2761     esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
2762     esrequest.stream = assoc->encode;
2763     esrequest.decode = assoc->decode;
2764     esrequest.print = assoc->print;
2765     esrequest.errcode = 0;
2766     esrequest.errstring = NULL;
2767     esrequest.request = reqb;
2768     esrequest.association = assoc;
2769     esrequest.taskPackage = 0;
2770     esrequest.referenceId = req->referenceId;
2771     
2772     (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
2773     
2774     /* If the response is being delayed, return NULL */
2775     if (esrequest.request == NULL)
2776         return(NULL);
2777
2778     resp->referenceId = req->referenceId;
2779
2780     if (esrequest.errcode == -1)
2781     {
2782         /* Backend service indicates request will be processed */
2783         yaz_log(log_request,"EsRequest OK: Accepted !");
2784         *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
2785     }
2786     else if (esrequest.errcode == 0)
2787     {
2788         /* Backend service indicates request will be processed */
2789         yaz_log(log_request,"EsRequest OK: Done !");
2790         *resp->operationStatus = Z_ExtendedServicesResponse_done;
2791     }
2792     else
2793     {
2794         Z_DiagRecs *diagRecs =
2795             zget_DiagRecs(assoc->encode, esrequest.errcode,
2796                           esrequest.errstring);
2797         /* Backend indicates error, request will not be processed */
2798         yaz_log(YLOG_DEBUG,"Request could not be processed...failure !");
2799         *resp->operationStatus = Z_ExtendedServicesResponse_failure;
2800         resp->num_diagnostics = diagRecs->num_diagRecs;
2801         resp->diagnostics = diagRecs->diagRecs;
2802         if (log_request)
2803         {
2804             WRBUF wr = wrbuf_alloc();
2805             wrbuf_diags(wr, resp->num_diagnostics, resp->diagnostics);
2806             yaz_log(log_request, "EsRequest %s", wrbuf_buf(wr) );
2807             wrbuf_free(wr, 1);
2808         }
2809
2810     }
2811     /* Do something with the members of bend_extendedservice */
2812     if (esrequest.taskPackage)
2813         resp->taskPackage = z_ext_record (assoc->encode, VAL_EXTENDED,
2814                                          (const char *)  esrequest.taskPackage,
2815                                           -1);
2816     yaz_log(YLOG_DEBUG,"Send the result apdu");
2817     return apdu;
2818 }
2819