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