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