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