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