If a CCL qualifier mapping file has been specified, then incoming CCL
[yaz-moved-to-github.git] / src / seshigh.c
1 /*
2  * Copyright (C) 1995-2007, Index Data ApS
3  * See the file LICENSE for details.
4  *
5  * $Id: seshigh.c,v 1.124 2007-08-13 16:43:59 mike Exp $
6  */
7 /**
8  * \file seshigh.c
9  * \brief Implements GFS session logic.
10  *
11  * Frontend server logic.
12  *
13  * This code receives incoming APDUs, and handles client requests by means
14  * of the backend API.
15  *
16  * Some of the code is getting quite involved, compared to simpler servers -
17  * primarily because it is asynchronous both in the communication with
18  * the user and the backend. We think the complexity will pay off in
19  * the form of greater flexibility when more asynchronous facilities
20  * are implemented.
21  *
22  * Memory management has become somewhat involved. In the simple case, where
23  * only one PDU is pending at a time, it will simply reuse the same memory,
24  * once it has found its working size. When we enable multiple concurrent
25  * operations, perhaps even with multiple parallel calls to the backend, it
26  * will maintain a pool of buffers for encoding and decoding, trying to
27  * minimize memory allocation/deallocation during normal operation.
28  *
29  */
30
31 #include <stdlib.h>
32 #include <stdio.h>
33 #include <assert.h>
34 #include <ctype.h>
35
36 #if HAVE_SYS_TYPES_H
37 #include <sys/types.h>
38 #endif
39 #if HAVE_SYS_STAT_H
40 #include <sys/stat.h>
41 #endif
42
43 #ifdef WIN32
44 #include <io.h>
45 #define S_ISREG(x) (x & _S_IFREG)
46 #include <process.h>
47 #endif
48
49 #if HAVE_UNISTD_H
50 #include <unistd.h>
51 #endif
52
53 #if YAZ_HAVE_XML2
54 #include <libxml/parser.h>
55 #include <libxml/tree.h>
56 #endif
57
58 #include <yaz/yconfig.h>
59 #include <yaz/xmalloc.h>
60 #include <yaz/comstack.h>
61 #include "eventl.h"
62 #include "session.h"
63 #include "mime.h"
64 #include <yaz/proto.h>
65 #include <yaz/oid_db.h>
66 #include <yaz/log.h>
67 #include <yaz/logrpn.h>
68 #include <yaz/querytowrbuf.h>
69 #include <yaz/statserv.h>
70 #include <yaz/diagbib1.h>
71 #include <yaz/charneg.h>
72 #include <yaz/otherinfo.h>
73 #include <yaz/yaz-util.h>
74 #include <yaz/pquery.h>
75 #include <yaz/oid_db.h>
76
77 #include <yaz/srw.h>
78 #include <yaz/backend.h>
79 #include <yaz/yaz-ccl.h>
80
81 static void process_gdu_request(association *assoc, request *req);
82 static int process_z_request(association *assoc, request *req, char **msg);
83 void backend_response(IOCHAN i, int event);
84 static int process_gdu_response(association *assoc, request *req, Z_GDU *res);
85 static int process_z_response(association *assoc, request *req, Z_APDU *res);
86 static Z_APDU *process_initRequest(association *assoc, request *reqb);
87 static Z_External *init_diagnostics(ODR odr, int errcode,
88                                     const char *errstring);
89 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
90     int *fd);
91 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
92     bend_search_rr *bsrr, int *fd);
93 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
94     int *fd);
95 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
96 static Z_APDU *process_sortRequest(association *assoc, request *reqb, int *fd);
97 static void process_close(association *assoc, request *reqb);
98 void save_referenceId (request *reqb, Z_ReferenceId *refid);
99 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
100     int *fd);
101 static Z_APDU *process_segmentRequest (association *assoc, request *reqb);
102
103 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd);
104
105 /* dynamic logging levels */
106 static int logbits_set = 0;
107 static int log_session = 0; /* one-line logs for session */
108 static int log_sessiondetail = 0; /* more detailed stuff */
109 static int log_request = 0; /* one-line logs for requests */
110 static int log_requestdetail = 0;  /* more detailed stuff */
111
112 /** get_logbits sets global loglevel bits */
113 static void get_logbits(void)
114 { /* needs to be called after parsing cmd-line args that can set loglevels!*/
115     if (!logbits_set)
116     {
117         logbits_set = 1;
118         log_session = yaz_log_module_level("session"); 
119         log_sessiondetail = yaz_log_module_level("sessiondetail");
120         log_request = yaz_log_module_level("request");
121         log_requestdetail = yaz_log_module_level("requestdetail"); 
122     }
123 }
124
125
126
127 static void wr_diag(WRBUF w, int error, const char *addinfo)
128 {
129     wrbuf_printf(w, "ERROR %d+", error);
130     wrbuf_puts_replace_char(w, diagbib1_str(error), ' ', '_');
131     if (addinfo){
132         wrbuf_puts(w, "+");
133         wrbuf_puts_replace_char(w, addinfo, ' ', '_');
134     }
135     
136     wrbuf_puts(w, " ");    
137 }
138
139
140 /*
141  * Create and initialize a new association-handle.
142  *  channel  : iochannel for the current line.
143  *  link     : communications channel.
144  * Returns: 0 or a new association handle.
145  */
146 association *create_association(IOCHAN channel, COMSTACK link,
147                                 const char *apdufile)
148 {
149     association *anew;
150
151     if (!logbits_set)
152         get_logbits();
153     if (!(anew = (association *)xmalloc(sizeof(*anew))))
154         return 0;
155     anew->init = 0;
156     anew->version = 0;
157     anew->last_control = 0;
158     anew->client_chan = channel;
159     anew->client_link = link;
160     anew->cs_get_mask = 0;
161     anew->cs_put_mask = 0;
162     anew->cs_accept_mask = 0;
163     if (!(anew->decode = odr_createmem(ODR_DECODE)) ||
164         !(anew->encode = odr_createmem(ODR_ENCODE)))
165         return 0;
166     if (apdufile && *apdufile)
167     {
168         FILE *f;
169
170         if (!(anew->print = odr_createmem(ODR_PRINT)))
171             return 0;
172         if (*apdufile == '@')
173         {
174             odr_setprint(anew->print, yaz_log_file());
175         }       
176         else if (*apdufile != '-')
177         {
178             char filename[256];
179             sprintf(filename, "%.200s.%ld", apdufile, (long)getpid());
180             if (!(f = fopen(filename, "w")))
181             {
182                 yaz_log(YLOG_WARN|YLOG_ERRNO, "%s", filename);
183                 return 0;
184             }
185             setvbuf(f, 0, _IONBF, 0);
186             odr_setprint(anew->print, f);
187         }
188     }
189     else
190         anew->print = 0;
191     anew->input_buffer = 0;
192     anew->input_buffer_len = 0;
193     anew->backend = 0;
194     anew->state = ASSOC_NEW;
195     request_initq(&anew->incoming);
196     request_initq(&anew->outgoing);
197     anew->proto = cs_getproto(link);
198     anew->server = 0;
199     return anew;
200 }
201
202 /*
203  * Free association and release resources.
204  */
205 void destroy_association(association *h)
206 {
207     statserv_options_block *cb = statserv_getcontrol();
208     request *req;
209
210     xfree(h->init);
211     odr_destroy(h->decode);
212     odr_destroy(h->encode);
213     if (h->print)
214         odr_destroy(h->print);
215     if (h->input_buffer)
216     xfree(h->input_buffer);
217     if (h->backend)
218         (*cb->bend_close)(h->backend);
219     while ((req = request_deq(&h->incoming)))
220         request_release(req);
221     while ((req = request_deq(&h->outgoing)))
222         request_release(req);
223     request_delq(&h->incoming);
224     request_delq(&h->outgoing);
225     xfree(h);
226     xmalloc_trav("session closed");
227     if (cb && cb->one_shot)
228     {
229         exit (0);
230     }
231 }
232
233 static void do_close_req(association *a, int reason, char *message,
234                          request *req)
235 {
236     Z_APDU apdu;
237     Z_Close *cls = zget_Close(a->encode);
238     
239     /* Purge request queue */
240     while (request_deq(&a->incoming));
241     while (request_deq(&a->outgoing));
242     if (a->version >= 3)
243     {
244         yaz_log(log_requestdetail, "Sending Close PDU, reason=%d, message=%s",
245             reason, message ? message : "none");
246         apdu.which = Z_APDU_close;
247         apdu.u.close = cls;
248         *cls->closeReason = reason;
249         cls->diagnosticInformation = message;
250         process_z_response(a, req, &apdu);
251         iochan_settimeout(a->client_chan, 20);
252     }
253     else
254     {
255         request_release(req);
256         yaz_log(log_requestdetail, "v2 client. No Close PDU");
257         iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
258         a->cs_put_mask = 0;
259     }
260     a->state = ASSOC_DEAD;
261 }
262
263 static void do_close(association *a, int reason, char *message)
264 {
265     request *req = request_get(&a->outgoing);
266     do_close_req (a, reason, message, req);
267 }
268
269
270 int ir_read(IOCHAN h, int event)
271 {
272     association *assoc = (association *)iochan_getdata(h);
273     COMSTACK conn = assoc->client_link;
274     request *req;
275     
276     if ((assoc->cs_put_mask & EVENT_INPUT) == 0 && (event & assoc->cs_get_mask))
277     {
278         yaz_log(YLOG_DEBUG, "ir_session (input)");
279         /* We aren't speaking to this fellow */
280         if (assoc->state == ASSOC_DEAD)
281         {
282             yaz_log(log_sessiondetail, "Connection closed - end of session");
283             cs_close(conn);
284             destroy_association(assoc);
285             iochan_destroy(h);
286             return 0;
287         }
288         assoc->cs_get_mask = EVENT_INPUT;
289
290         do
291         {
292             int res = cs_get(conn, &assoc->input_buffer,
293                              &assoc->input_buffer_len);
294             if (res < 0 && cs_errno(conn) == CSBUFSIZE)
295             {
296                 yaz_log(log_session, "Connection error: %s res=%d",
297                         cs_errmsg(cs_errno(conn)), res);
298                 req = request_get(&assoc->incoming); /* get a new request */
299                 do_close_req(assoc, Z_Close_protocolError, 
300                              "Incoming package too large", req);
301                 return 0;
302             }
303             else if (res <= 0)
304             {
305                 yaz_log(log_session, "Connection closed by client");
306                 assoc->state = ASSOC_DEAD;
307                 return 0;
308             }
309             else if (res == 1) /* incomplete read - wait for more  */
310             {
311                 if (conn->io_pending & CS_WANT_WRITE)
312                     assoc->cs_get_mask |= EVENT_OUTPUT;
313                 iochan_setflag(h, assoc->cs_get_mask);
314                 return 0;
315             }
316             /* we got a complete PDU. Let's decode it */
317             yaz_log(YLOG_DEBUG, "Got PDU, %d bytes: lead=%02X %02X %02X", res,
318                     assoc->input_buffer[0] & 0xff,
319                     assoc->input_buffer[1] & 0xff,
320                     assoc->input_buffer[2] & 0xff);
321             req = request_get(&assoc->incoming); /* get a new request */
322             odr_reset(assoc->decode);
323             odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
324             if (!z_GDU(assoc->decode, &req->gdu_request, 0, 0))
325             {
326                 yaz_log(YLOG_WARN, "ODR error on incoming PDU: %s [element %s] "
327                         "[near byte %ld] ",
328                         odr_errmsg(odr_geterror(assoc->decode)),
329                         odr_getelement(assoc->decode),
330                         (long) odr_offset(assoc->decode));
331                 if (assoc->decode->error != OHTTP)
332                 {
333                     yaz_log(YLOG_WARN, "PDU dump:");
334                     odr_dumpBER(yaz_log_file(), assoc->input_buffer, res);
335                     request_release(req);
336                     do_close(assoc, Z_Close_protocolError, "Malformed package");
337                 }
338                 else
339                 {
340                     Z_GDU *p = z_get_HTTP_Response(assoc->encode, 400);
341                     assoc->state = ASSOC_DEAD;
342                     process_gdu_response(assoc, req, p);
343                 }
344                 return 0;
345             }
346             req->request_mem = odr_extract_mem(assoc->decode);
347             if (assoc->print) 
348             {
349                 if (!z_GDU(assoc->print, &req->gdu_request, 0, 0))
350                     yaz_log(YLOG_WARN, "ODR print error: %s", 
351                             odr_errmsg(odr_geterror(assoc->print)));
352                 odr_reset(assoc->print);
353             }
354             request_enq(&assoc->incoming, req);
355         }
356         while (cs_more(conn));
357     }
358     return 1;
359 }
360
361 /*
362  * This is where PDUs from the client are read and the further
363  * processing is initiated. Flow of control moves down through the
364  * various process_* functions below, until the encoded result comes back up
365  * to the output handler in here.
366  * 
367  *  h     : the I/O channel that has an outstanding event.
368  *  event : the current outstanding event.
369  */
370 void ir_session(IOCHAN h, int event)
371 {
372     int res;
373     association *assoc = (association *)iochan_getdata(h);
374     COMSTACK conn = assoc->client_link;
375     request *req;
376
377     assert(h && conn && assoc);
378     if (event == EVENT_TIMEOUT)
379     {
380         if (assoc->state != ASSOC_UP)
381         {
382             yaz_log(YLOG_DEBUG, "Final timeout - closing connection.");
383             /* do we need to lod this at all */
384             cs_close(conn);
385             destroy_association(assoc);
386             iochan_destroy(h);
387         }
388         else
389         {
390             yaz_log(log_sessiondetail, 
391                     "Session idle too long. Sending close.");
392             do_close(assoc, Z_Close_lackOfActivity, 0);
393         }
394         return;
395     }
396     if (event & assoc->cs_accept_mask)
397     {
398         if (!cs_accept (conn))
399         {
400             yaz_log (YLOG_WARN, "accept failed");
401             destroy_association(assoc);
402             iochan_destroy(h);
403         }
404         iochan_clearflag (h, EVENT_OUTPUT);
405         if (conn->io_pending) 
406         {   /* cs_accept didn't complete */
407             assoc->cs_accept_mask = 
408                 ((conn->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
409                 ((conn->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
410
411             iochan_setflag (h, assoc->cs_accept_mask);
412         }
413         else
414         {   /* cs_accept completed. Prepare for reading (cs_get) */
415             assoc->cs_accept_mask = 0;
416             assoc->cs_get_mask = EVENT_INPUT;
417             iochan_setflag (h, assoc->cs_get_mask);
418         }
419         return;
420     }
421     if (event & assoc->cs_get_mask) /* input */
422     {
423         if (!ir_read(h, event))
424             return;
425         req = request_head(&assoc->incoming);
426         if (req->state == REQUEST_IDLE)
427         {
428             request_deq(&assoc->incoming);
429             process_gdu_request(assoc, req);
430         }
431     }
432     if (event & assoc->cs_put_mask)
433     {
434         request *req = request_head(&assoc->outgoing);
435
436         assoc->cs_put_mask = 0;
437         yaz_log(YLOG_DEBUG, "ir_session (output)");
438         req->state = REQUEST_PENDING;
439         switch (res = cs_put(conn, req->response, req->len_response))
440         {
441         case -1:
442             yaz_log(log_sessiondetail, "Connection closed by client");
443             cs_close(conn);
444             destroy_association(assoc);
445             iochan_destroy(h);
446             break;
447         case 0: /* all sent - release the request structure */
448             yaz_log(YLOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
449 #if 0
450             yaz_log(YLOG_DEBUG, "HTTP out:\n%.*s", req->len_response,
451                     req->response);
452 #endif
453             nmem_destroy(req->request_mem);
454             request_deq(&assoc->outgoing);
455             request_release(req);
456             if (!request_head(&assoc->outgoing))
457             {   /* restore mask for cs_get operation ... */
458                 iochan_clearflag(h, EVENT_OUTPUT|EVENT_INPUT);
459                 iochan_setflag(h, assoc->cs_get_mask);
460                 if (assoc->state == ASSOC_DEAD)
461                     iochan_setevent(assoc->client_chan, EVENT_TIMEOUT);
462             }
463             else
464             {
465                 assoc->cs_put_mask = EVENT_OUTPUT;
466             }
467             break;
468         default:
469             if (conn->io_pending & CS_WANT_WRITE)
470                 assoc->cs_put_mask |= EVENT_OUTPUT;
471             if (conn->io_pending & CS_WANT_READ)
472                 assoc->cs_put_mask |= EVENT_INPUT;
473             iochan_setflag(h, assoc->cs_put_mask);
474         }
475     }
476     if (event & EVENT_EXCEPT)
477     {
478         yaz_log(YLOG_WARN, "ir_session (exception)");
479         cs_close(conn);
480         destroy_association(assoc);
481         iochan_destroy(h);
482     }
483 }
484
485 static int process_z_request(association *assoc, request *req, char **msg);
486
487
488 static void assoc_init_reset(association *assoc)
489 {
490     xfree (assoc->init);
491     assoc->init = (bend_initrequest *) xmalloc (sizeof(*assoc->init));
492
493     assoc->init->stream = assoc->encode;
494     assoc->init->print = assoc->print;
495     assoc->init->auth = 0;
496     assoc->init->referenceId = 0;
497     assoc->init->implementation_version = 0;
498     assoc->init->implementation_id = 0;
499     assoc->init->implementation_name = 0;
500     assoc->init->query_charset = 0;
501     assoc->init->records_in_same_charset = 0;
502     assoc->init->bend_sort = NULL;
503     assoc->init->bend_search = NULL;
504     assoc->init->bend_present = NULL;
505     assoc->init->bend_esrequest = NULL;
506     assoc->init->bend_delete = NULL;
507     assoc->init->bend_scan = NULL;
508     assoc->init->bend_segment = NULL;
509     assoc->init->bend_fetch = NULL;
510     assoc->init->bend_explain = NULL;
511     assoc->init->bend_srw_scan = NULL;
512     assoc->init->bend_srw_update = NULL;
513
514     assoc->init->charneg_request = NULL;
515     assoc->init->charneg_response = NULL;
516
517     assoc->init->decode = assoc->decode;
518     assoc->init->peer_name = 
519         odr_strdup (assoc->encode, cs_addrstr(assoc->client_link));
520
521     yaz_log(log_requestdetail, "peer %s", assoc->init->peer_name);
522 }
523
524 static int srw_bend_init(association *assoc, Z_SRW_diagnostic **d, int *num, Z_SRW_PDU *sr)
525 {
526     statserv_options_block *cb = statserv_getcontrol();
527     if (!assoc->init)
528     {
529         const char *encoding = "UTF-8";
530         Z_External *ce;
531         bend_initresult *binitres;
532
533         yaz_log(log_requestdetail, "srw_bend_init config=%s", cb->configname);
534         assoc_init_reset(assoc);
535         
536         if (sr->username)
537         {
538             Z_IdAuthentication *auth = (Z_IdAuthentication *)
539                 odr_malloc(assoc->decode, sizeof(*auth));
540             int len;
541
542             len = strlen(sr->username) + 1;
543             if (sr->password) 
544                 len += strlen(sr->password) + 2;
545             auth->which = Z_IdAuthentication_open;
546             auth->u.open = (char *) odr_malloc(assoc->decode, len);
547             strcpy(auth->u.open, sr->username);
548             if (sr->password && *sr->password)
549             {
550                 strcat(auth->u.open, "/");
551                 strcat(auth->u.open, sr->password);
552             }
553             assoc->init->auth = auth;
554         }
555
556 #if 1
557         ce = yaz_set_proposal_charneg(assoc->decode, &encoding, 1, 0, 0, 1);
558         assoc->init->charneg_request = ce->u.charNeg3;
559 #endif
560         assoc->backend = 0;
561         if (!(binitres = (*cb->bend_init)(assoc->init)))
562         {
563             assoc->state = ASSOC_DEAD;
564             yaz_add_srw_diagnostic(assoc->encode, d, num,
565                             YAZ_SRW_AUTHENTICATION_ERROR, 0);
566             return 0;
567         }
568         assoc->backend = binitres->handle;
569         assoc->init->auth = 0;
570         if (binitres->errcode)
571         {
572             int srw_code = yaz_diag_bib1_to_srw(binitres->errcode);
573             assoc->state = ASSOC_DEAD;
574             yaz_add_srw_diagnostic(assoc->encode, d, num, srw_code,
575                                    binitres->errstring);
576             return 0;
577         }
578         return 1;
579     }
580     return 1;
581 }
582
583 static int retrieve_fetch(association *assoc, bend_fetch_rr *rr)
584 {
585 #if YAZ_HAVE_XML2
586     yaz_record_conv_t rc = 0;
587     const char *match_schema = 0;
588     Odr_oid *match_syntax = 0;
589
590     if (assoc->server)
591     {
592         int r;
593         const char *input_schema = yaz_get_esn(rr->comp);
594         Odr_oid *input_syntax_raw = rr->request_format;
595         
596         const char *backend_schema = 0;
597         Odr_oid *backend_syntax = 0;
598
599         r = yaz_retrieval_request(assoc->server->retrieval,
600                                   input_schema,
601                                   input_syntax_raw,
602                                   &match_schema,
603                                   &match_syntax,
604                                   &rc,
605                                   &backend_schema,
606                                   &backend_syntax);
607         if (r == -1) /* error ? */
608         {
609             const char *details = yaz_retrieval_get_error(
610                 assoc->server->retrieval);
611
612             rr->errcode = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
613             if (details)
614                 rr->errstring = odr_strdup(rr->stream, details);
615             return -1;
616         }
617         else if (r == 1 || r == 3)
618         {
619             const char *details = input_schema;
620             rr->errcode =
621                 YAZ_BIB1_SPECIFIED_ELEMENT_SET_NAME_NOT_VALID_FOR_SPECIFIED_;
622             if (details)
623                 rr->errstring = odr_strdup(rr->stream, details);
624             return -1;
625         }
626         else if (r == 2)
627         {
628             rr->errcode = YAZ_BIB1_RECORD_SYNTAX_UNSUPP;
629             if (input_syntax_raw)
630             {
631                 char oidbuf[OID_STR_MAX];
632                 oid_oid_to_dotstring(input_syntax_raw, oidbuf);
633                 rr->errstring = odr_strdup(rr->stream, oidbuf);
634             }
635             return -1;
636         }
637         if (backend_schema)
638         {
639             yaz_set_esn(&rr->comp, backend_schema, odr_getmem(rr->stream));
640         }
641         if (backend_syntax)
642             rr->request_format = backend_syntax;
643     }
644     (*assoc->init->bend_fetch)(assoc->backend, rr);
645     if (rc && rr->record && rr->errcode == 0 && rr->len > 0)
646     {   /* post conversion must take place .. */
647         WRBUF output_record = wrbuf_alloc();
648         int r = yaz_record_conv_record(rc, rr->record, rr->len, output_record);
649         if (r)
650         {
651             const char *details = yaz_record_conv_get_error(rc);
652             rr->errcode = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
653             if (details)
654                 rr->errstring = odr_strdup(rr->stream, details);
655         }
656         else
657         {
658             rr->len = wrbuf_len(output_record);
659             rr->record = (char *) odr_malloc(rr->stream, rr->len);
660             memcpy(rr->record, wrbuf_buf(output_record), rr->len);
661         }
662         wrbuf_destroy(output_record);
663     }
664     if (match_syntax)
665         rr->output_format = match_syntax;
666     if (match_schema)
667         rr->schema = odr_strdup(rr->stream, match_schema);
668     return 0;
669 #else
670     (*assoc->init->bend_fetch)(assoc->backend, rr);
671 #endif
672     return 0;
673 }
674
675 static int srw_bend_fetch(association *assoc, int pos,
676                           Z_SRW_searchRetrieveRequest *srw_req,
677                           Z_SRW_record *record,
678                           const char **addinfo)
679 {
680     bend_fetch_rr rr;
681     ODR o = assoc->encode;
682
683     rr.setname = "default";
684     rr.number = pos;
685     rr.referenceId = 0;
686     rr.request_format = odr_oiddup(assoc->decode, yaz_oid_recsyn_xml);
687
688     rr.comp = (Z_RecordComposition *)
689             odr_malloc(assoc->decode, sizeof(*rr.comp));
690     rr.comp->which = Z_RecordComp_complex;
691     rr.comp->u.complex = (Z_CompSpec *)
692             odr_malloc(assoc->decode, sizeof(Z_CompSpec));
693     rr.comp->u.complex->selectAlternativeSyntax = (bool_t *)
694         odr_malloc(assoc->encode, sizeof(bool_t));
695     *rr.comp->u.complex->selectAlternativeSyntax = 0;    
696     rr.comp->u.complex->num_dbSpecific = 0;
697     rr.comp->u.complex->dbSpecific = 0;
698     rr.comp->u.complex->num_recordSyntax = 0; 
699     rr.comp->u.complex->recordSyntax = 0;
700
701     rr.comp->u.complex->generic = (Z_Specification *) 
702             odr_malloc(assoc->decode, sizeof(Z_Specification));
703
704     /* schema uri = recordSchema (or NULL if recordSchema is not given) */
705     rr.comp->u.complex->generic->which = Z_Schema_uri;
706     rr.comp->u.complex->generic->schema.uri = srw_req->recordSchema;
707
708     /* ESN = recordSchema if recordSchema is present */
709     rr.comp->u.complex->generic->elementSpec = 0;
710     if (srw_req->recordSchema)
711     {
712         rr.comp->u.complex->generic->elementSpec = 
713             (Z_ElementSpec *) odr_malloc(assoc->encode, sizeof(Z_ElementSpec));
714         rr.comp->u.complex->generic->elementSpec->which = 
715             Z_ElementSpec_elementSetName;
716         rr.comp->u.complex->generic->elementSpec->u.elementSetName =
717             srw_req->recordSchema;
718     }
719     
720     rr.stream = assoc->encode;
721     rr.print = assoc->print;
722
723     rr.basename = 0;
724     rr.len = 0;
725     rr.record = 0;
726     rr.last_in_set = 0;
727     rr.errcode = 0;
728     rr.errstring = 0;
729     rr.surrogate_flag = 0;
730     rr.schema = srw_req->recordSchema;
731
732     if (!assoc->init->bend_fetch)
733         return 1;
734
735     retrieve_fetch(assoc, &rr);
736
737     if (rr.errcode && rr.surrogate_flag)
738     {
739         int code = yaz_diag_bib1_to_srw(rr.errcode);
740         const char *message = yaz_diag_srw_str(code);
741         int len = 200;
742         if (message)
743             len += strlen(message);
744         if (rr.errstring)
745             len += strlen(rr.errstring);
746
747         record->recordData_buf = (char *) odr_malloc(o, len);
748         
749         sprintf(record->recordData_buf, "<diagnostic "
750                 "xmlns=\"http://www.loc.gov/zing/srw/diagnostic/\">\n"
751                 " <uri>info:srw/diagnostic/1/%d</uri>\n", code);
752         if (rr.errstring)
753             sprintf(record->recordData_buf + strlen(record->recordData_buf),
754                     " <details>%s</details>\n", rr.errstring);
755         if (message)
756             sprintf(record->recordData_buf + strlen(record->recordData_buf),
757                     " <message>%s</message>\n", message);
758         sprintf(record->recordData_buf + strlen(record->recordData_buf),
759                 "</diagnostic>\n");
760         record->recordData_len = strlen(record->recordData_buf);
761         record->recordPosition = odr_intdup(o, pos);
762         record->recordSchema = "info:srw/schema/1/diagnostics-v1.1";
763         return 0;
764     }
765     else if (rr.len >= 0)
766     {
767         record->recordData_buf = rr.record;
768         record->recordData_len = rr.len;
769         record->recordPosition = odr_intdup(o, pos);
770         if (rr.schema)
771             record->recordSchema = odr_strdup(o, rr.schema);
772         else
773             record->recordSchema = 0;
774     }
775     if (rr.errcode)
776     {
777         *addinfo = rr.errstring;
778         return rr.errcode;
779     }
780     return 0;
781 }
782
783 static int cql2pqf(ODR odr, const char *cql, cql_transform_t ct,
784                    Z_Query *query_result)
785 {
786     /* have a CQL query and  CQL to PQF transform .. */
787     CQL_parser cp = cql_parser_create();
788     int r;
789     int srw_errcode = 0;
790     const char *add = 0;
791     char rpn_buf[5120];
792             
793     r = cql_parser_string(cp, cql);
794     if (r)
795     {
796         /* CQL syntax error */
797         srw_errcode = 10; 
798     }
799     if (!r)
800     {
801         /* Syntax OK */
802         r = cql_transform_buf(ct,
803                               cql_parser_result(cp),
804                               rpn_buf, sizeof(rpn_buf)-1);
805         if (r)
806             srw_errcode  = cql_transform_error(ct, &add);
807     }
808     if (!r)
809     {
810         /* Syntax & transform OK. */
811         /* Convert PQF string to Z39.50 to RPN query struct */
812         YAZ_PQF_Parser pp = yaz_pqf_create();
813         Z_RPNQuery *rpnquery = yaz_pqf_parse(pp, odr, rpn_buf);
814         if (!rpnquery)
815         {
816             size_t off;
817             const char *pqf_msg;
818             int code = yaz_pqf_error(pp, &pqf_msg, &off);
819             yaz_log(YLOG_WARN, "PQF Parser Error %s (code %d)",
820                     pqf_msg, code);
821             srw_errcode = 10;
822         }
823         else
824         {
825             query_result->which = Z_Query_type_1;
826             query_result->u.type_1 = rpnquery;
827         }
828         yaz_pqf_destroy(pp);
829     }
830     cql_parser_destroy(cp);
831     return srw_errcode;
832 }
833
834 static int cql2pqf_scan(ODR odr, const char *cql, cql_transform_t ct,
835                         Z_AttributesPlusTerm *result)
836 {
837     Z_Query query;
838     Z_RPNQuery *rpn;
839     int srw_error = cql2pqf(odr, cql, ct, &query);
840     if (srw_error)
841         return srw_error;
842     if (query.which != Z_Query_type_1 && query.which != Z_Query_type_101)
843         return 10; /* bad query type */
844     rpn = query.u.type_1;
845     if (!rpn->RPNStructure) 
846         return 10; /* must be structure */
847     if (rpn->RPNStructure->which != Z_RPNStructure_simple)
848         return 10; /* must be simple */
849     if (rpn->RPNStructure->u.simple->which != Z_Operand_APT)
850         return 10; /* must be attributes plus term node .. */
851     memcpy(result, rpn->RPNStructure->u.simple->u.attributesPlusTerm,
852            sizeof(*result));
853     return 0;
854 }
855                    
856
857 static int ccl2pqf(ODR odr, const Odr_oct *ccl, CCL_bibset bibset,
858                    bend_search_rr *bsrr) {
859     char *ccl0;
860     struct ccl_rpn_node *node;
861     int errcode, pos;
862
863     ccl0 = odr_strdupn(odr, (char*) ccl->buf, ccl->len);
864     if ((node = ccl_find_str(bibset, ccl0, &errcode, &pos)) == 0) {
865         bsrr->errstring = (char*) ccl_err_msg(errcode);
866         return 10;              /* Query syntax error */
867     }
868
869     bsrr->query->which = Z_Query_type_1;
870     bsrr->query->u.type_1 = ccl_rpn_query(odr, node);
871     return 0;
872 }
873
874
875 static void srw_bend_search(association *assoc, request *req,
876                             Z_SRW_PDU *sr,
877                             Z_SRW_searchRetrieveResponse *srw_res,
878                             int *http_code)
879 {
880     int srw_error = 0;
881     Z_External *ext;
882     Z_SRW_searchRetrieveRequest *srw_req = sr->u.request;
883     
884     *http_code = 200;
885     yaz_log(log_requestdetail, "Got SRW SearchRetrieveRequest");
886     srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
887     if (srw_res->num_diagnostics == 0 && assoc->init)
888     {
889         bend_search_rr rr;
890         rr.setname = "default";
891         rr.replace_set = 1;
892         rr.num_bases = 1;
893         rr.basenames = &srw_req->database;
894         rr.referenceId = 0;
895         rr.srw_sortKeys = 0;
896         rr.srw_setname = 0;
897         rr.srw_setnameIdleTime = 0;
898         rr.estimated_hit_count = 0;
899         rr.partial_resultset = 0;
900         rr.query = (Z_Query *) odr_malloc (assoc->decode, sizeof(*rr.query));
901         rr.query->u.type_1 = 0;
902         
903         if (srw_req->query_type == Z_SRW_query_type_cql)
904         {
905             if (assoc->server && assoc->server->cql_transform)
906             {
907                 int srw_errcode = cql2pqf(assoc->encode, srw_req->query.cql,
908                                           assoc->server->cql_transform,
909                                           rr.query);
910                 if (srw_errcode)
911                 {
912                     yaz_add_srw_diagnostic(assoc->encode,
913                                            &srw_res->diagnostics,
914                                            &srw_res->num_diagnostics,
915                                            srw_errcode, 0);
916                 }
917             }
918             else
919             {
920                 /* CQL query to backend. Wrap it - Z39.50 style */
921                 ext = (Z_External *) odr_malloc(assoc->decode, sizeof(*ext));
922                 ext->direct_reference = odr_getoidbystr(assoc->decode, 
923                                                         "1.2.840.10003.16.2");
924                 ext->indirect_reference = 0;
925                 ext->descriptor = 0;
926                 ext->which = Z_External_CQL;
927                 ext->u.cql = srw_req->query.cql;
928                 
929                 rr.query->which = Z_Query_type_104;
930                 rr.query->u.type_104 =  ext;
931             }
932         }
933         else if (srw_req->query_type == Z_SRW_query_type_pqf)
934         {
935             Z_RPNQuery *RPNquery;
936             YAZ_PQF_Parser pqf_parser;
937             
938             pqf_parser = yaz_pqf_create ();
939             
940             RPNquery = yaz_pqf_parse (pqf_parser, assoc->decode,
941                                       srw_req->query.pqf);
942             if (!RPNquery)
943             {
944                 const char *pqf_msg;
945                 size_t off;
946                 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
947                 yaz_log(log_requestdetail, "Parse error %d %s near offset %ld",
948                         code, pqf_msg, (long) off);
949                 srw_error = YAZ_SRW_QUERY_SYNTAX_ERROR;
950             }
951             
952             rr.query->which = Z_Query_type_1;
953             rr.query->u.type_1 =  RPNquery;
954             
955             yaz_pqf_destroy (pqf_parser);
956         }
957         else
958         {
959             yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
960                                    &srw_res->num_diagnostics,
961                                    YAZ_SRW_UNSUPP_QUERY_TYPE, 0);
962         }
963         if (rr.query->u.type_1)
964         {
965             rr.stream = assoc->encode;
966             rr.decode = assoc->decode;
967             rr.print = assoc->print;
968             rr.request = req;
969             if ( srw_req->sort.sortKeys )
970                 rr.srw_sortKeys = odr_strdup(assoc->encode, 
971                                              srw_req->sort.sortKeys );
972             rr.association = assoc;
973             rr.fd = 0;
974             rr.hits = 0;
975             rr.errcode = 0;
976             rr.errstring = 0;
977             rr.search_info = 0;
978             yaz_log_zquery_level(log_requestdetail,rr.query);
979             
980             (assoc->init->bend_search)(assoc->backend, &rr);
981             if (rr.errcode)
982             {
983                 if (rr.errcode == YAZ_BIB1_DATABASE_UNAVAILABLE)
984                 {
985                     *http_code = 404;
986                 }
987                 else
988                 {
989                     srw_error = yaz_diag_bib1_to_srw (rr.errcode);
990                     yaz_add_srw_diagnostic(assoc->encode,
991                                            &srw_res->diagnostics,
992                                            &srw_res->num_diagnostics,
993                                            srw_error, rr.errstring);
994                 }
995             }
996             else
997             {
998                 int number = srw_req->maximumRecords ? *srw_req->maximumRecords : 0;
999                 int start = srw_req->startRecord ? *srw_req->startRecord : 1;
1000                 
1001                 yaz_log(log_requestdetail, "Request to pack %d+%d out of %d",
1002                         start, number, rr.hits);
1003                 
1004                 srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
1005                 if (rr.srw_setname)
1006                 {
1007                     srw_res->resultSetId =
1008                         odr_strdup(assoc->encode, rr.srw_setname );
1009                     srw_res->resultSetIdleTime =
1010                         odr_intdup(assoc->encode, *rr.srw_setnameIdleTime );
1011                 }
1012                 
1013                 if (start > rr.hits || start < 1)
1014                 {
1015                     /* if hits<=0 and start=1 we don't return a diagnostic */
1016                     if (start != 1)
1017                         yaz_add_srw_diagnostic(
1018                             assoc->encode, 
1019                             &srw_res->diagnostics, &srw_res->num_diagnostics,
1020                             YAZ_SRW_FIRST_RECORD_POSITION_OUT_OF_RANGE, 0);
1021                 }
1022                 else if (number > 0)
1023                 {
1024                     int i;
1025                     int ok = 1;
1026                     if (start + number > rr.hits)
1027                         number = rr.hits - start + 1;
1028                     
1029                     /* Call bend_present if defined */
1030                     if (assoc->init->bend_present)
1031                     {
1032                         bend_present_rr *bprr = (bend_present_rr*)
1033                             odr_malloc (assoc->decode, sizeof(*bprr));
1034                         bprr->setname = "default";
1035                         bprr->start = start;
1036                         bprr->number = number;
1037                         if (srw_req->recordSchema)
1038                         {
1039                             bprr->comp = (Z_RecordComposition *) odr_malloc(assoc->decode,
1040                                                                             sizeof(*bprr->comp));
1041                             bprr->comp->which = Z_RecordComp_simple;
1042                             bprr->comp->u.simple = (Z_ElementSetNames *)
1043                                 odr_malloc(assoc->decode, sizeof(Z_ElementSetNames));
1044                             bprr->comp->u.simple->which = Z_ElementSetNames_generic;
1045                             bprr->comp->u.simple->u.generic = srw_req->recordSchema;
1046                         }
1047                         else
1048                         {
1049                             bprr->comp = 0;
1050                         }
1051                         bprr->stream = assoc->encode;
1052                         bprr->referenceId = 0;
1053                         bprr->print = assoc->print;
1054                         bprr->request = req;
1055                         bprr->association = assoc;
1056                         bprr->errcode = 0;
1057                         bprr->errstring = NULL;
1058                         (*assoc->init->bend_present)(assoc->backend, bprr);
1059                         
1060                         if (!bprr->request)
1061                             return;
1062                         if (bprr->errcode)
1063                         {
1064                             srw_error = yaz_diag_bib1_to_srw (bprr->errcode);
1065                             yaz_add_srw_diagnostic(assoc->encode,
1066                                                    &srw_res->diagnostics,
1067                                                    &srw_res->num_diagnostics,
1068                                                    srw_error, bprr->errstring);
1069                             ok = 0;
1070                         }
1071                     }
1072                     
1073                     if (ok)
1074                     {
1075                         int j = 0;
1076                         int packing = Z_SRW_recordPacking_string;
1077                         if (srw_req->recordPacking)
1078                         {
1079                             packing = 
1080                                 yaz_srw_str_to_pack(srw_req->recordPacking);
1081                             if (packing == -1)
1082                                 packing = Z_SRW_recordPacking_string;
1083                         }
1084                         srw_res->records = (Z_SRW_record *)
1085                             odr_malloc(assoc->encode,
1086                                        number * sizeof(*srw_res->records));
1087                         
1088                         srw_res->extra_records = (Z_SRW_extra_record **)
1089                             odr_malloc(assoc->encode,
1090                                        number*sizeof(*srw_res->extra_records));
1091
1092                         for (i = 0; i<number; i++)
1093                         {
1094                             int errcode;
1095                             const char *addinfo = 0;
1096                             
1097                             srw_res->records[j].recordPacking = packing;
1098                             srw_res->records[j].recordData_buf = 0;
1099                             srw_res->extra_records[j] = 0;
1100                             yaz_log(YLOG_DEBUG, "srw_bend_fetch %d", i+start);
1101                             errcode = srw_bend_fetch(assoc, i+start, srw_req,
1102                                                      srw_res->records + j,
1103                                                      &addinfo);
1104                             if (errcode)
1105                             {
1106                                 yaz_add_srw_diagnostic(assoc->encode,
1107                                                        &srw_res->diagnostics,
1108                                                        &srw_res->num_diagnostics,
1109                                                        yaz_diag_bib1_to_srw (errcode),
1110                                                        addinfo);
1111                                 
1112                                 break;
1113                             }
1114                             if (srw_res->records[j].recordData_buf)
1115                                 j++;
1116                         }
1117                         srw_res->num_records = j;
1118                         if (!j)
1119                             srw_res->records = 0;
1120                     }
1121                 }
1122                 if (rr.estimated_hit_count || rr.partial_resultset)
1123                 {
1124                     yaz_add_srw_diagnostic(
1125                         assoc->encode,
1126                         &srw_res->diagnostics,
1127                         &srw_res->num_diagnostics,
1128                         YAZ_SRW_RESULT_SET_CREATED_WITH_VALID_PARTIAL_RESULTS_AVAILABLE,
1129                         0);
1130                 }
1131             }
1132         }
1133     }
1134     if (log_request)
1135     {
1136         const char *querystr = "?";
1137         const char *querytype = "?";
1138         WRBUF wr = wrbuf_alloc();
1139
1140         switch (srw_req->query_type)
1141         {
1142         case Z_SRW_query_type_cql:
1143             querytype = "CQL";
1144             querystr = srw_req->query.cql;
1145             break;
1146         case Z_SRW_query_type_pqf:
1147             querytype = "PQF";
1148             querystr = srw_req->query.pqf;
1149             break;
1150         }
1151         wrbuf_printf(wr, "SRWSearch ");
1152         wrbuf_printf(wr, srw_req->database);
1153         wrbuf_printf(wr, " ");
1154         if (srw_res->num_diagnostics)
1155             wrbuf_printf(wr, "ERROR %s", srw_res->diagnostics[0].uri);
1156         else if (*http_code != 200)
1157             wrbuf_printf(wr, "ERROR info:http/%d", *http_code);
1158         else if (srw_res->numberOfRecords)
1159         {
1160             wrbuf_printf(wr, "OK %d",
1161                          (srw_res->numberOfRecords ?
1162                           *srw_res->numberOfRecords : 0));
1163         }
1164         wrbuf_printf(wr, " %s %d+%d", 
1165                      (srw_res->resultSetId ?
1166                       srw_res->resultSetId : "-"),
1167                      (srw_req->startRecord ? *srw_req->startRecord : 1), 
1168                      srw_res->num_records);
1169         yaz_log(log_request, "%s %s: %s", wrbuf_cstr(wr), querytype, querystr);
1170         wrbuf_destroy(wr);
1171     }
1172 }
1173
1174 static char *srw_bend_explain_default(void *handle, bend_explain_rr *rr)
1175 {
1176 #if YAZ_HAVE_XML2
1177     xmlNodePtr ptr = (xmlNode *) rr->server_node_ptr;
1178     if (!ptr)
1179         return 0;
1180     for (ptr = ptr->children; ptr; ptr = ptr->next)
1181     {
1182         if (ptr->type != XML_ELEMENT_NODE)
1183             continue;
1184         if (!strcmp((const char *) ptr->name, "explain"))
1185         {
1186             int len;
1187             xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
1188             xmlChar *buf_out;
1189             char *content;
1190
1191             ptr = xmlCopyNode(ptr, 1);
1192         
1193             xmlDocSetRootElement(doc, ptr);
1194             
1195             xmlDocDumpMemory(doc, &buf_out, &len);
1196             content = (char*) odr_malloc(rr->stream, 1+len);
1197             memcpy(content, buf_out, len);
1198             content[len] = '\0';
1199             
1200             xmlFree(buf_out);
1201             xmlFreeDoc(doc);
1202             rr->explain_buf = content;
1203             return 0;
1204         }
1205     }
1206 #endif
1207     return 0;
1208 }
1209
1210 static void srw_bend_explain(association *assoc, request *req,
1211                              Z_SRW_PDU *sr,
1212                              Z_SRW_explainResponse *srw_res,
1213                              int *http_code)
1214 {
1215     Z_SRW_explainRequest *srw_req = sr->u.explain_request;
1216     yaz_log(log_requestdetail, "Got SRW ExplainRequest");
1217     *http_code = 404;
1218     srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1219     if (assoc->init)
1220     {
1221         bend_explain_rr rr;
1222         
1223         rr.stream = assoc->encode;
1224         rr.decode = assoc->decode;
1225         rr.print = assoc->print;
1226         rr.explain_buf = 0;
1227         rr.database = srw_req->database;
1228         if (assoc->server)
1229             rr.server_node_ptr = assoc->server->server_node_ptr;
1230         else
1231             rr.server_node_ptr = 0;
1232         rr.schema = "http://explain.z3950.org/dtd/2.0/";
1233         if (assoc->init->bend_explain)
1234             (*assoc->init->bend_explain)(assoc->backend, &rr);
1235         else
1236             srw_bend_explain_default(assoc->backend, &rr);
1237
1238         if (rr.explain_buf)
1239         {
1240             int packing = Z_SRW_recordPacking_string;
1241             if (srw_req->recordPacking)
1242             {
1243                 packing = 
1244                     yaz_srw_str_to_pack(srw_req->recordPacking);
1245                 if (packing == -1)
1246                     packing = Z_SRW_recordPacking_string;
1247             }
1248             srw_res->record.recordSchema = rr.schema;
1249             srw_res->record.recordPacking = packing;
1250             srw_res->record.recordData_buf = rr.explain_buf;
1251             srw_res->record.recordData_len = strlen(rr.explain_buf);
1252             srw_res->record.recordPosition = 0;
1253             *http_code = 200;
1254         }
1255     }
1256 }
1257
1258 static void srw_bend_scan(association *assoc, request *req,
1259                           Z_SRW_PDU *sr,
1260                           Z_SRW_scanResponse *srw_res,
1261                           int *http_code)
1262 {
1263     Z_SRW_scanRequest *srw_req = sr->u.scan_request;
1264     yaz_log(log_requestdetail, "Got SRW ScanRequest");
1265
1266     *http_code = 200;
1267     srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1268     if (srw_res->num_diagnostics == 0 && assoc->init)
1269     {
1270         struct scan_entry *save_entries;
1271
1272         bend_scan_rr *bsrr = (bend_scan_rr *)
1273             odr_malloc (assoc->encode, sizeof(*bsrr));
1274         bsrr->num_bases = 1;
1275         bsrr->basenames = &srw_req->database;
1276
1277         bsrr->num_entries = srw_req->maximumTerms ?
1278             *srw_req->maximumTerms : 10;
1279         bsrr->term_position = srw_req->responsePosition ?
1280             *srw_req->responsePosition : 1;
1281
1282         bsrr->errcode = 0;
1283         bsrr->errstring = 0;
1284         bsrr->referenceId = 0;
1285         bsrr->stream = assoc->encode;
1286         bsrr->print = assoc->print;
1287         bsrr->step_size = odr_intdup(assoc->decode, 0);
1288         bsrr->entries = 0;
1289         bsrr->setname = 0;
1290
1291         if (bsrr->num_entries > 0) 
1292         {
1293             int i;
1294             bsrr->entries = (struct scan_entry *) 
1295                 odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
1296                            bsrr->num_entries);
1297             for (i = 0; i<bsrr->num_entries; i++)
1298             {
1299                 bsrr->entries[i].term = 0;
1300                 bsrr->entries[i].occurrences = 0;
1301                 bsrr->entries[i].errcode = 0;
1302                 bsrr->entries[i].errstring = 0;
1303                 bsrr->entries[i].display_term = 0;
1304             }
1305         }
1306         save_entries = bsrr->entries;  /* save it so we can compare later */
1307
1308         if (srw_req->query_type == Z_SRW_query_type_pqf &&
1309             assoc->init->bend_scan)
1310         {
1311             YAZ_PQF_Parser pqf_parser = yaz_pqf_create();
1312             
1313             bsrr->term = yaz_pqf_scan(pqf_parser, assoc->decode,
1314                                       &bsrr->attributeset, 
1315                                       srw_req->scanClause.pqf); 
1316             yaz_pqf_destroy(pqf_parser);
1317             bsrr->scanClause = 0;
1318             ((int (*)(void *, bend_scan_rr *))
1319              (*assoc->init->bend_scan))(assoc->backend, bsrr);
1320         }
1321         else if (srw_req->query_type == Z_SRW_query_type_cql
1322                  && assoc->init->bend_scan && assoc->server
1323                  && assoc->server->cql_transform)
1324         {
1325             int srw_error;
1326             bsrr->scanClause = 0;
1327             bsrr->attributeset = 0;
1328             bsrr->term = (Z_AttributesPlusTerm *)
1329                 odr_malloc(assoc->decode, sizeof(*bsrr->term));
1330             srw_error = cql2pqf_scan(assoc->encode,
1331                                      srw_req->scanClause.cql,
1332                                      assoc->server->cql_transform,
1333                                      bsrr->term);
1334             if (srw_error)
1335                 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1336                                        &srw_res->num_diagnostics,
1337                                        srw_error, 0);
1338             else
1339             {
1340                 ((int (*)(void *, bend_scan_rr *))
1341                  (*assoc->init->bend_scan))(assoc->backend, bsrr);
1342             }
1343         }
1344         else if (srw_req->query_type == Z_SRW_query_type_cql
1345                  && assoc->init->bend_srw_scan)
1346         {
1347             bsrr->term = 0;
1348             bsrr->attributeset = 0;
1349             bsrr->scanClause = srw_req->scanClause.cql;
1350             ((int (*)(void *, bend_scan_rr *))
1351              (*assoc->init->bend_srw_scan))(assoc->backend, bsrr);
1352         }
1353         else
1354         {
1355             yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1356                                    &srw_res->num_diagnostics,
1357                                    YAZ_SRW_UNSUPP_OPERATION, "scan");
1358         }
1359         if (bsrr->errcode)
1360         {
1361             int srw_error;
1362             if (bsrr->errcode == YAZ_BIB1_DATABASE_UNAVAILABLE)
1363             {
1364                 *http_code = 404;
1365                 return;
1366             }
1367             srw_error = yaz_diag_bib1_to_srw (bsrr->errcode);
1368
1369             yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1370                                    &srw_res->num_diagnostics,
1371                                    srw_error, bsrr->errstring);
1372         }
1373         else if (srw_res->num_diagnostics == 0 && bsrr->num_entries)
1374         {
1375             int i;
1376             srw_res->terms = (Z_SRW_scanTerm*)
1377                 odr_malloc(assoc->encode, sizeof(*srw_res->terms) *
1378                            bsrr->num_entries);
1379
1380             srw_res->num_terms =  bsrr->num_entries;
1381             for (i = 0; i<bsrr->num_entries; i++)
1382             {
1383                 Z_SRW_scanTerm *t = srw_res->terms + i;
1384                 t->value = odr_strdup(assoc->encode, bsrr->entries[i].term);
1385                 t->numberOfRecords =
1386                     odr_intdup(assoc->encode, bsrr->entries[i].occurrences);
1387                 t->displayTerm = 0;
1388                 if (save_entries == bsrr->entries && 
1389                     bsrr->entries[i].display_term)
1390                 {
1391                     /* the entries was _not_ set by the handler. So it's
1392                        safe to test for new member display_term. It is
1393                        NULL'ed by us.
1394                     */
1395                     t->displayTerm = odr_strdup(assoc->encode, 
1396                                                 bsrr->entries[i].display_term);
1397                 }
1398                 t->whereInList = 0;
1399             }
1400         }
1401     }
1402     if (log_request)
1403     {
1404         WRBUF wr = wrbuf_alloc();
1405         const char *querytype = 0;
1406         const char *querystr = 0;
1407
1408         switch(srw_req->query_type)
1409         {
1410         case Z_SRW_query_type_pqf:
1411             querytype = "PQF";
1412             querystr = srw_req->scanClause.pqf;
1413             break;
1414         case Z_SRW_query_type_cql:
1415             querytype = "CQL";
1416             querystr = srw_req->scanClause.cql;
1417             break;
1418         default:
1419             querytype = "UNKNOWN";
1420             querystr = "";
1421         }
1422
1423         wrbuf_printf(wr, "SRWScan ");
1424         wrbuf_printf(wr, srw_req->database);
1425         wrbuf_printf(wr, " ");
1426
1427         if (srw_res->num_diagnostics)
1428             wrbuf_printf(wr, "ERROR %s - ", srw_res->diagnostics[0].uri);
1429         else if (srw_res->num_terms)
1430             wrbuf_printf(wr, "OK %d - ", srw_res->num_terms);
1431         else
1432             wrbuf_printf(wr, "OK - - ");
1433
1434         wrbuf_printf(wr, "%d+%d+0 ",
1435                      (srw_req->responsePosition ? 
1436                       *srw_req->responsePosition : 1),
1437                      (srw_req->maximumTerms ?
1438                       *srw_req->maximumTerms : 1));
1439         /* there is no step size in SRU/W ??? */
1440         wrbuf_printf(wr, "%s: %s ", querytype, querystr);
1441         yaz_log(log_request, "%s ", wrbuf_cstr(wr) );
1442         wrbuf_destroy(wr);
1443     }
1444
1445 }
1446
1447 static void srw_bend_update(association *assoc, request *req,
1448                             Z_SRW_PDU *sr,
1449                             Z_SRW_updateResponse *srw_res,
1450                             int *http_code)
1451 {
1452     Z_SRW_updateRequest *srw_req = sr->u.update_request;
1453     yaz_log(log_session, "SRWUpdate action=%s", srw_req->operation);
1454     yaz_log(YLOG_DEBUG, "num_diag = %d", srw_res->num_diagnostics );
1455     *http_code = 404;
1456     srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1457     if (assoc->init)
1458     {
1459         bend_update_rr rr;
1460         Z_SRW_extra_record *extra = srw_req->extra_record;
1461         
1462         rr.stream = assoc->encode;
1463         rr.print = assoc->print;
1464         rr.num_bases = 1;
1465         rr.basenames = &srw_req->database;
1466         rr.operation = srw_req->operation;
1467         rr.operation_status = "failed";
1468         rr.record_id = 0;
1469         rr.record_versions = 0;
1470         rr.num_versions = 0;
1471         rr.record_packing = "string";
1472         rr.record_schema = 0;
1473         rr.record_data = 0;
1474         rr.extra_record_data = 0;
1475         rr.extra_request_data = 0;
1476         rr.extra_response_data = 0;
1477         rr.uri = 0;
1478         rr.message = 0;
1479         rr.details = 0;
1480         
1481         *http_code = 200;
1482         if (rr.operation == 0)
1483         {
1484             yaz_add_sru_update_diagnostic(
1485                 assoc->encode, &srw_res->diagnostics,
1486                 &srw_res->num_diagnostics,
1487                 YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,
1488                 "action" );
1489             return;
1490         }
1491         yaz_log(YLOG_DEBUG, "basename = %s", rr.basenames[0] );
1492         yaz_log(YLOG_DEBUG, "Operation = %s", rr.operation );
1493         if (!strcmp( rr.operation, "delete"))
1494         {
1495             if (srw_req->record && !srw_req->record->recordSchema)
1496             {
1497                 rr.record_schema = odr_strdup(
1498                     assoc->encode,
1499                     srw_req->record->recordSchema);
1500             }
1501             if (srw_req->record)
1502             {
1503                 rr.record_data = odr_strdupn(
1504                     assoc->encode, 
1505                     srw_req->record->recordData_buf,
1506                     srw_req->record->recordData_len );
1507             }
1508             if (extra && extra->extraRecordData_len)
1509             {
1510                 rr.extra_record_data = odr_strdupn(
1511                     assoc->encode, 
1512                     extra->extraRecordData_buf,
1513                     extra->extraRecordData_len );
1514             }
1515             if (srw_req->recordId)
1516                 rr.record_id = srw_req->recordId;
1517             else if (extra && extra->recordIdentifier)
1518                 rr.record_id = extra->recordIdentifier;
1519         }
1520         else if (!strcmp(rr.operation, "replace"))
1521         {
1522             if (srw_req->recordId)
1523                 rr.record_id = srw_req->recordId;
1524             else if (extra && extra->recordIdentifier)
1525                 rr.record_id = extra->recordIdentifier;
1526             else 
1527             {
1528                 yaz_add_sru_update_diagnostic(
1529                     assoc->encode, &srw_res->diagnostics,
1530                     &srw_res->num_diagnostics,
1531                     YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,
1532                     "recordIdentifier");
1533             }
1534             if (!srw_req->record)
1535             {
1536                 yaz_add_sru_update_diagnostic(
1537                     assoc->encode, &srw_res->diagnostics,
1538                     &srw_res->num_diagnostics,
1539                     YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,
1540                     "record");
1541             }
1542             else 
1543             {
1544                 if (srw_req->record->recordSchema)
1545                     rr.record_schema = odr_strdup(
1546                         assoc->encode, srw_req->record->recordSchema);
1547                 if (srw_req->record->recordData_len )
1548                 {
1549                     rr.record_data = odr_strdupn(assoc->encode, 
1550                                                  srw_req->record->recordData_buf,
1551                                                  srw_req->record->recordData_len );
1552                 }
1553                 else 
1554                 {
1555                     yaz_add_sru_update_diagnostic(
1556                         assoc->encode, &srw_res->diagnostics,
1557                         &srw_res->num_diagnostics,
1558                         YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,                                              
1559                         "recordData" );
1560                 }
1561             }
1562             if (extra && extra->extraRecordData_len)
1563             {
1564                 rr.extra_record_data = odr_strdupn(
1565                     assoc->encode, 
1566                     extra->extraRecordData_buf,
1567                     extra->extraRecordData_len );
1568             }
1569         }
1570         else if (!strcmp(rr.operation, "insert"))
1571         {
1572             if (srw_req->recordId)
1573                 rr.record_id = srw_req->recordId; 
1574             else if (extra)
1575                 rr.record_id = extra->recordIdentifier;
1576             
1577             if (srw_req->record)
1578             {
1579                 if (srw_req->record->recordSchema)
1580                     rr.record_schema = odr_strdup(
1581                         assoc->encode, srw_req->record->recordSchema);
1582             
1583                 if (srw_req->record->recordData_len)
1584                     rr.record_data = odr_strdupn(
1585                         assoc->encode, 
1586                         srw_req->record->recordData_buf,
1587                         srw_req->record->recordData_len );
1588             }
1589             if (extra && extra->extraRecordData_len)
1590             {
1591                 rr.extra_record_data = odr_strdupn(
1592                     assoc->encode, 
1593                     extra->extraRecordData_buf,
1594                     extra->extraRecordData_len );
1595             }
1596         }
1597         else 
1598             yaz_add_sru_update_diagnostic(assoc->encode, &srw_res->diagnostics,
1599                                           &srw_res->num_diagnostics,
1600                                           YAZ_SRU_UPDATE_INVALID_ACTION,
1601                                           rr.operation );
1602
1603         if (srw_req->record)
1604         {
1605             const char *pack_str = 
1606                 yaz_srw_pack_to_str(srw_req->record->recordPacking);
1607             if (pack_str)
1608                 rr.record_packing = odr_strdup(assoc->encode, pack_str);
1609         }
1610
1611         if (srw_req->num_recordVersions)
1612         {
1613             rr.record_versions = srw_req->recordVersions;
1614             rr.num_versions = srw_req->num_recordVersions;
1615         }
1616         if (srw_req->extraRequestData_len)
1617         {
1618             rr.extra_request_data = odr_strdupn(assoc->encode,
1619                                                 srw_req->extraRequestData_buf,
1620                                                 srw_req->extraRequestData_len );
1621         }
1622         if (srw_res->num_diagnostics == 0)
1623         {
1624             if ( assoc->init->bend_srw_update)
1625                 (*assoc->init->bend_srw_update)(assoc->backend, &rr);
1626             else 
1627                 yaz_add_sru_update_diagnostic(
1628                     assoc->encode, &srw_res->diagnostics,
1629                     &srw_res->num_diagnostics,
1630                     YAZ_SRU_UPDATE_UNSPECIFIED_DATABASE_ERROR,
1631                     "No Update backend handler");
1632         }
1633
1634         if (rr.uri)
1635             yaz_add_srw_diagnostic_uri(assoc->encode,
1636                                        &srw_res->diagnostics,
1637                                        &srw_res->num_diagnostics,
1638                                        rr.uri, 
1639                                        rr.message,
1640                                        rr.details);
1641         srw_res->recordId = rr.record_id;
1642         srw_res->operationStatus = rr.operation_status;
1643         srw_res->recordVersions = rr.record_versions;
1644         srw_res->num_recordVersions = rr.num_versions;
1645         if (srw_res->extraResponseData_len)
1646         {
1647             srw_res->extraResponseData_buf = rr.extra_response_data;
1648             srw_res->extraResponseData_len = strlen(rr.extra_response_data);
1649         }
1650         if (srw_res->num_diagnostics == 0 && rr.record_data)
1651         {
1652             srw_res->record = yaz_srw_get_record(assoc->encode);
1653             srw_res->record->recordSchema = rr.record_schema;
1654             if (rr.record_packing)
1655             {
1656                 int pack = yaz_srw_str_to_pack(rr.record_packing);
1657
1658                 if (pack == -1)
1659                 {
1660                     pack = Z_SRW_recordPacking_string;
1661                     yaz_log(YLOG_WARN, "Back packing %s from backend",
1662                             rr.record_packing);
1663                 }
1664                 srw_res->record->recordPacking = pack;
1665             }
1666             srw_res->record->recordData_buf = rr.record_data;
1667             srw_res->record->recordData_len = strlen(rr.record_data);
1668             if (rr.extra_record_data)
1669             {
1670                 Z_SRW_extra_record *ex = 
1671                     yaz_srw_get_extra_record(assoc->encode);
1672                 srw_res->extra_record = ex;
1673                 ex->extraRecordData_buf = rr.extra_record_data;
1674                 ex->extraRecordData_len = strlen(rr.extra_record_data);
1675             }
1676         }
1677     }
1678 }
1679
1680 /* check if path is OK (1); BAD (0) */
1681 static int check_path(const char *path)
1682 {
1683     if (*path != '/')
1684         return 0;
1685     if (strstr(path, ".."))
1686         return 0;
1687     return 1;
1688 }
1689
1690 static char *read_file(const char *fname, ODR o, int *sz)
1691 {
1692     char *buf;
1693     FILE *inf = fopen(fname, "rb");
1694     if (!inf)
1695         return 0;
1696
1697     fseek(inf, 0L, SEEK_END);
1698     *sz = ftell(inf);
1699     rewind(inf);
1700     buf = (char *) odr_malloc(o, *sz);
1701     fread(buf, 1, *sz, inf);
1702     fclose(inf);
1703     return buf;     
1704 }
1705
1706 static void process_http_request(association *assoc, request *req)
1707 {
1708     Z_HTTP_Request *hreq = req->gdu_request->u.HTTP_Request;
1709     ODR o = assoc->encode;
1710     int r = 2;  /* 2=NOT TAKEN, 1=TAKEN, 0=SOAP TAKEN */
1711     Z_SRW_PDU *sr = 0;
1712     Z_SOAP *soap_package = 0;
1713     Z_GDU *p = 0;
1714     char *charset = 0;
1715     Z_HTTP_Response *hres = 0;
1716     int keepalive = 1;
1717     const char *stylesheet = 0; /* for now .. set later */
1718     Z_SRW_diagnostic *diagnostic = 0;
1719     int num_diagnostic = 0;
1720     const char *host = z_HTTP_header_lookup(hreq->headers, "Host");
1721
1722     if (!control_association(assoc, host, 0))
1723     {
1724         p = z_get_HTTP_Response(o, 404);
1725         r = 1;
1726     }
1727     if (r == 2 && assoc->server && assoc->server->docpath
1728         && hreq->path[0] == '/' 
1729         && 
1730         /* check if path is a proper prefix of documentroot */
1731         strncmp(hreq->path+1, assoc->server->docpath,
1732                 strlen(assoc->server->docpath))
1733         == 0)
1734     {   
1735         if (!check_path(hreq->path))
1736         {
1737             yaz_log(YLOG_LOG, "File %s access forbidden", hreq->path+1);
1738             p = z_get_HTTP_Response(o, 404);
1739         }
1740         else
1741         {
1742             int content_size = 0;
1743             char *content_buf = read_file(hreq->path+1, o, &content_size);
1744             if (!content_buf)
1745             {
1746                 yaz_log(YLOG_LOG, "File %s not found", hreq->path+1);
1747                 p = z_get_HTTP_Response(o, 404);
1748             }
1749             else
1750             {
1751                 const char *ctype = 0;
1752                 yaz_mime_types types = yaz_mime_types_create();
1753                 
1754                 yaz_mime_types_add(types, "xsl", "application/xml");
1755                 yaz_mime_types_add(types, "xml", "application/xml");
1756                 yaz_mime_types_add(types, "css", "text/css");
1757                 yaz_mime_types_add(types, "html", "text/html");
1758                 yaz_mime_types_add(types, "htm", "text/html");
1759                 yaz_mime_types_add(types, "txt", "text/plain");
1760                 yaz_mime_types_add(types, "js", "application/x-javascript");
1761                 
1762                 yaz_mime_types_add(types, "gif", "image/gif");
1763                 yaz_mime_types_add(types, "png", "image/png");
1764                 yaz_mime_types_add(types, "jpg", "image/jpeg");
1765                 yaz_mime_types_add(types, "jpeg", "image/jpeg");
1766                 
1767                 ctype = yaz_mime_lookup_fname(types, hreq->path);
1768                 if (!ctype)
1769                 {
1770                     yaz_log(YLOG_LOG, "No mime type for %s", hreq->path+1);
1771                     p = z_get_HTTP_Response(o, 404);
1772                 }
1773                 else
1774                 {
1775                     p = z_get_HTTP_Response(o, 200);
1776                     hres = p->u.HTTP_Response;
1777                     hres->content_buf = content_buf;
1778                     hres->content_len = content_size;
1779                     z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1780                 }
1781                 yaz_mime_types_destroy(types);
1782             }
1783         }
1784         r = 1;
1785     }
1786
1787     if (r == 2)
1788     {
1789         r = yaz_srw_decode(hreq, &sr, &soap_package, assoc->decode, &charset);
1790         yaz_log(YLOG_DEBUG, "yaz_srw_decode returned %d", r);
1791     }
1792     if (r == 2)  /* not taken */
1793     {
1794         r = yaz_sru_decode(hreq, &sr, &soap_package, assoc->decode, &charset,
1795                            &diagnostic, &num_diagnostic);
1796         yaz_log(YLOG_DEBUG, "yaz_sru_decode returned %d", r);
1797     }
1798     if (r == 0)  /* decode SRW/SRU OK .. */
1799     {
1800         int http_code = 200;
1801         if (sr->which == Z_SRW_searchRetrieve_request)
1802         {
1803             Z_SRW_PDU *res =
1804                 yaz_srw_get(assoc->encode, Z_SRW_searchRetrieve_response);
1805
1806             stylesheet = sr->u.request->stylesheet;
1807             if (num_diagnostic)
1808             {
1809                 res->u.response->diagnostics = diagnostic;
1810                 res->u.response->num_diagnostics = num_diagnostic;
1811             }
1812             else
1813             {
1814                 srw_bend_search(assoc, req, sr, res->u.response, 
1815                                 &http_code);
1816             }
1817             if (http_code == 200)
1818                 soap_package->u.generic->p = res;
1819         }
1820         else if (sr->which == Z_SRW_explain_request)
1821         {
1822             Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_explain_response);
1823             stylesheet = sr->u.explain_request->stylesheet;
1824             if (num_diagnostic)
1825             {   
1826                 res->u.explain_response->diagnostics = diagnostic;
1827                 res->u.explain_response->num_diagnostics = num_diagnostic;
1828             }
1829             srw_bend_explain(assoc, req, sr,
1830                              res->u.explain_response, &http_code);
1831             if (http_code == 200)
1832                 soap_package->u.generic->p = res;
1833         }
1834         else if (sr->which == Z_SRW_scan_request)
1835         {
1836             Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_scan_response);
1837             stylesheet = sr->u.scan_request->stylesheet;
1838             if (num_diagnostic)
1839             {   
1840                 res->u.scan_response->diagnostics = diagnostic;
1841                 res->u.scan_response->num_diagnostics = num_diagnostic;
1842             }
1843             srw_bend_scan(assoc, req, sr,
1844                           res->u.scan_response, &http_code);
1845             if (http_code == 200)
1846                 soap_package->u.generic->p = res;
1847         }
1848         else if (sr->which == Z_SRW_update_request)
1849         {
1850             Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_update_response);
1851             yaz_log(YLOG_DEBUG, "handling SRW UpdateRequest");
1852             if (num_diagnostic)
1853             {   
1854                 res->u.update_response->diagnostics = diagnostic;
1855                 res->u.update_response->num_diagnostics = num_diagnostic;
1856             }
1857             yaz_log(YLOG_DEBUG, "num_diag = %d", res->u.update_response->num_diagnostics );
1858             srw_bend_update(assoc, req, sr,
1859                             res->u.update_response, &http_code);
1860             if (http_code == 200)
1861                 soap_package->u.generic->p = res;
1862         }
1863         else
1864         {
1865             yaz_log(log_request, "SOAP ERROR"); 
1866             /* FIXME - what error, what query */
1867             http_code = 500;
1868             z_soap_error(assoc->encode, soap_package,
1869                          "SOAP-ENV:Client", "Bad method", 0); 
1870         }
1871         if (http_code == 200 || http_code == 500)
1872         {
1873             static Z_SOAP_Handler soap_handlers[4] = {
1874 #if YAZ_HAVE_XML2
1875                 {YAZ_XMLNS_SRU_v1_1, 0, (Z_SOAP_fun) yaz_srw_codec},
1876                 {YAZ_XMLNS_SRU_v1_0, 0, (Z_SOAP_fun) yaz_srw_codec},
1877                 {YAZ_XMLNS_UPDATE_v0_9, 0, (Z_SOAP_fun) yaz_ucp_codec},
1878 #endif
1879                 {0, 0, 0}
1880             };
1881             char ctype[80];
1882             int ret;
1883             p = z_get_HTTP_Response(o, 200);
1884             hres = p->u.HTTP_Response;
1885
1886             if (!stylesheet && assoc->server)
1887                 stylesheet = assoc->server->stylesheet;
1888
1889             /* empty stylesheet means NO stylesheet */
1890             if (stylesheet && *stylesheet == '\0')
1891                 stylesheet = 0;
1892
1893             ret = z_soap_codec_enc_xsl(assoc->encode, &soap_package,
1894                                        &hres->content_buf, &hres->content_len,
1895                                        soap_handlers, charset, stylesheet);
1896             hres->code = http_code;
1897
1898             strcpy(ctype, "text/xml");
1899             if (charset && strlen(charset) < sizeof(ctype)-30)
1900             {
1901                 strcat(ctype, "; charset=");
1902                 strcat(ctype, charset);
1903             }
1904             z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1905         }
1906         else
1907             p = z_get_HTTP_Response(o, http_code);
1908     }
1909
1910     if (p == 0)
1911         p = z_get_HTTP_Response(o, 500);
1912     hres = p->u.HTTP_Response;
1913     if (!strcmp(hreq->version, "1.0")) 
1914     {
1915         const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1916         if (v && !strcmp(v, "Keep-Alive"))
1917             keepalive = 1;
1918         else
1919             keepalive = 0;
1920         hres->version = "1.0";
1921     }
1922     else
1923     {
1924         const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1925         if (v && !strcmp(v, "close"))
1926             keepalive = 0;
1927         else
1928             keepalive = 1;
1929         hres->version = "1.1";
1930     }
1931     if (!keepalive)
1932     {
1933         z_HTTP_header_add(o, &hres->headers, "Connection", "close");
1934         assoc->state = ASSOC_DEAD;
1935         assoc->cs_get_mask = 0;
1936     }
1937     else
1938     {
1939         int t;
1940         const char *alive = z_HTTP_header_lookup(hreq->headers, "Keep-Alive");
1941
1942         if (alive && isdigit(*(const unsigned char *) alive))
1943             t = atoi(alive);
1944         else
1945             t = 15;
1946         if (t < 0 || t > 3600)
1947             t = 3600;
1948         iochan_settimeout(assoc->client_chan,t);
1949         z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1950     }
1951     process_gdu_response(assoc, req, p);
1952 }
1953
1954 static void process_gdu_request(association *assoc, request *req)
1955 {
1956     if (req->gdu_request->which == Z_GDU_Z3950)
1957     {
1958         char *msg = 0;
1959         req->apdu_request = req->gdu_request->u.z3950;
1960         if (process_z_request(assoc, req, &msg) < 0)
1961             do_close_req(assoc, Z_Close_systemProblem, msg, req);
1962     }
1963     else if (req->gdu_request->which == Z_GDU_HTTP_Request)
1964         process_http_request(assoc, req);
1965     else
1966     {
1967         do_close_req(assoc, Z_Close_systemProblem, "bad protocol packet", req);
1968     }
1969 }
1970
1971 /*
1972  * Initiate request processing.
1973  */
1974 static int process_z_request(association *assoc, request *req, char **msg)
1975 {
1976     int fd = -1;
1977     Z_APDU *res;
1978     int retval;
1979     
1980     *msg = "Unknown Error";
1981     assert(req && req->state == REQUEST_IDLE);
1982     if (req->apdu_request->which != Z_APDU_initRequest && !assoc->init)
1983     {
1984         *msg = "Missing InitRequest";
1985         return -1;
1986     }
1987     switch (req->apdu_request->which)
1988     {
1989     case Z_APDU_initRequest:
1990         res = process_initRequest(assoc, req); break;
1991     case Z_APDU_searchRequest:
1992         res = process_searchRequest(assoc, req, &fd); break;
1993     case Z_APDU_presentRequest:
1994         res = process_presentRequest(assoc, req, &fd); break;
1995     case Z_APDU_scanRequest:
1996         if (assoc->init->bend_scan)
1997             res = process_scanRequest(assoc, req, &fd);
1998         else
1999         {
2000             *msg = "Cannot handle Scan APDU";
2001             return -1;
2002         }
2003         break;
2004     case Z_APDU_extendedServicesRequest:
2005         if (assoc->init->bend_esrequest)
2006             res = process_ESRequest(assoc, req, &fd);
2007         else
2008         {
2009             *msg = "Cannot handle Extended Services APDU";
2010             return -1;
2011         }
2012         break;
2013     case Z_APDU_sortRequest:
2014         if (assoc->init->bend_sort)
2015             res = process_sortRequest(assoc, req, &fd);
2016         else
2017         {
2018             *msg = "Cannot handle Sort APDU";
2019             return -1;
2020         }
2021         break;
2022     case Z_APDU_close:
2023         process_close(assoc, req);
2024         return 0;
2025     case Z_APDU_deleteResultSetRequest:
2026         if (assoc->init->bend_delete)
2027             res = process_deleteRequest(assoc, req, &fd);
2028         else
2029         {
2030             *msg = "Cannot handle Delete APDU";
2031             return -1;
2032         }
2033         break;
2034     case Z_APDU_segmentRequest:
2035         if (assoc->init->bend_segment)
2036         {
2037             res = process_segmentRequest (assoc, req);
2038         }
2039         else
2040         {
2041             *msg = "Cannot handle Segment APDU";
2042             return -1;
2043         }
2044         break;
2045     case Z_APDU_triggerResourceControlRequest:
2046         return 0;
2047     default:
2048         *msg = "Bad APDU received";
2049         return -1;
2050     }
2051     if (res)
2052     {
2053         yaz_log(YLOG_DEBUG, "  result immediately available");
2054         retval = process_z_response(assoc, req, res);
2055     }
2056     else if (fd < 0)
2057     {
2058         yaz_log(YLOG_DEBUG, "  result unavailble");
2059         retval = 0;
2060     }
2061     else /* no result yet - one will be provided later */
2062     {
2063         IOCHAN chan;
2064
2065         /* Set up an I/O handler for the fd supplied by the backend */
2066
2067         yaz_log(YLOG_DEBUG, "   establishing handler for result");
2068         req->state = REQUEST_PENDING;
2069         if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT, 0)))
2070             abort();
2071         iochan_setdata(chan, assoc);
2072         retval = 0;
2073     }
2074     return retval;
2075 }
2076
2077 /*
2078  * Handle message from the backend.
2079  */
2080 void backend_response(IOCHAN i, int event)
2081 {
2082     association *assoc = (association *)iochan_getdata(i);
2083     request *req = request_head(&assoc->incoming);
2084     Z_APDU *res;
2085     int fd;
2086
2087     yaz_log(YLOG_DEBUG, "backend_response");
2088     assert(assoc && req && req->state != REQUEST_IDLE);
2089     /* determine what it is we're waiting for */
2090     switch (req->apdu_request->which)
2091     {
2092         case Z_APDU_searchRequest:
2093             res = response_searchRequest(assoc, req, 0, &fd); break;
2094 #if 0
2095         case Z_APDU_presentRequest:
2096             res = response_presentRequest(assoc, req, 0, &fd); break;
2097         case Z_APDU_scanRequest:
2098             res = response_scanRequest(assoc, req, 0, &fd); break;
2099 #endif
2100         default:
2101             yaz_log(YLOG_FATAL, "Serious programmer's lapse or bug");
2102             abort();
2103     }
2104     if ((res && process_z_response(assoc, req, res) < 0) || fd < 0)
2105     {
2106         yaz_log(YLOG_WARN, "Fatal error when talking to backend");
2107         do_close(assoc, Z_Close_systemProblem, 0);
2108         iochan_destroy(i);
2109         return;
2110     }
2111     else if (!res) /* no result yet - try again later */
2112     {
2113         yaz_log(YLOG_DEBUG, "   no result yet");
2114         iochan_setfd(i, fd); /* in case fd has changed */
2115     }
2116 }
2117
2118 /*
2119  * Encode response, and transfer the request structure to the outgoing queue.
2120  */
2121 static int process_gdu_response(association *assoc, request *req, Z_GDU *res)
2122 {
2123     odr_setbuf(assoc->encode, req->response, req->size_response, 1);
2124
2125     if (assoc->print)
2126     {
2127         if (!z_GDU(assoc->print, &res, 0, 0))
2128             yaz_log(YLOG_WARN, "ODR print error: %s", 
2129                 odr_errmsg(odr_geterror(assoc->print)));
2130         odr_reset(assoc->print);
2131     }
2132     if (!z_GDU(assoc->encode, &res, 0, 0))
2133     {
2134         yaz_log(YLOG_WARN, "ODR error when encoding PDU: %s [element %s]",
2135                 odr_errmsg(odr_geterror(assoc->decode)),
2136                 odr_getelement(assoc->decode));
2137         return -1;
2138     }
2139     req->response = odr_getbuf(assoc->encode, &req->len_response,
2140         &req->size_response);
2141     odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
2142     odr_reset(assoc->encode);
2143     req->state = REQUEST_IDLE;
2144     request_enq(&assoc->outgoing, req);
2145     /* turn the work over to the ir_session handler */
2146     iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
2147     assoc->cs_put_mask = EVENT_OUTPUT;
2148     /* Is there more work to be done? give that to the input handler too */
2149     for (;;)
2150     {
2151         req = request_head(&assoc->incoming);
2152         if (req && req->state == REQUEST_IDLE)
2153         {
2154             request_deq(&assoc->incoming);
2155             process_gdu_request(assoc, req);
2156         }
2157         else
2158             break;
2159     }
2160     return 0;
2161 }
2162
2163 /*
2164  * Encode response, and transfer the request structure to the outgoing queue.
2165  */
2166 static int process_z_response(association *assoc, request *req, Z_APDU *res)
2167 {
2168     Z_GDU *gres = (Z_GDU *) odr_malloc(assoc->encode, sizeof(*res));
2169     gres->which = Z_GDU_Z3950;
2170     gres->u.z3950 = res;
2171
2172     return process_gdu_response(assoc, req, gres);
2173 }
2174
2175 static char *get_vhost(Z_OtherInformation *otherInfo)
2176 {
2177     return yaz_oi_get_string_oid(&otherInfo, yaz_oid_userinfo_proxy, 1, 0);
2178 }
2179
2180 /*
2181  * Handle init request.
2182  * At the moment, we don't check the options
2183  * anywhere else in the code - we just try not to do anything that would
2184  * break a naive client. We'll toss 'em into the association block when
2185  * we need them there.
2186  */
2187 static Z_APDU *process_initRequest(association *assoc, request *reqb)
2188 {
2189     Z_InitRequest *req = reqb->apdu_request->u.initRequest;
2190     Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
2191     Z_InitResponse *resp = apdu->u.initResponse;
2192     bend_initresult *binitres;
2193     char *version;
2194     char options[140];
2195     statserv_options_block *cb = 0;  /* by default no control for backend */
2196
2197     if (control_association(assoc, get_vhost(req->otherInfo), 1))
2198         cb = statserv_getcontrol();  /* got control block for backend */
2199
2200     if (cb && assoc->backend)
2201         (*cb->bend_close)(assoc->backend);
2202
2203     yaz_log(log_requestdetail, "Got initRequest");
2204     if (req->implementationId)
2205         yaz_log(log_requestdetail, "Id:        %s",
2206                 req->implementationId);
2207     if (req->implementationName)
2208         yaz_log(log_requestdetail, "Name:      %s",
2209                 req->implementationName);
2210     if (req->implementationVersion)
2211         yaz_log(log_requestdetail, "Version:   %s",
2212                 req->implementationVersion);
2213     
2214     assoc_init_reset(assoc);
2215
2216     assoc->init->auth = req->idAuthentication;
2217     assoc->init->referenceId = req->referenceId;
2218
2219     if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
2220     {
2221         Z_CharSetandLanguageNegotiation *negotiation =
2222             yaz_get_charneg_record (req->otherInfo);
2223         if (negotiation &&
2224             negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
2225             assoc->init->charneg_request = negotiation;
2226     }
2227
2228     assoc->backend = 0;
2229     if (cb)
2230     {
2231         if (req->implementationVersion)
2232             yaz_log(log_requestdetail, "Config:    %s",
2233                     cb->configname);
2234     
2235         iochan_settimeout(assoc->client_chan, cb->idle_timeout * 60);
2236         
2237         /* we have a backend control block, so call that init function */
2238         if (!(binitres = (*cb->bend_init)(assoc->init)))
2239         {
2240             yaz_log(YLOG_WARN, "Bad response from backend.");
2241             return 0;
2242         }
2243         assoc->backend = binitres->handle;
2244     }
2245     else
2246     {
2247         /* no backend. return error */
2248         binitres = (bend_initresult *)
2249             odr_malloc(assoc->encode, sizeof(*binitres));
2250         binitres->errstring = 0;
2251         binitres->errcode = YAZ_BIB1_PERMANENT_SYSTEM_ERROR;
2252         iochan_settimeout(assoc->client_chan, 10);
2253     }
2254     if ((assoc->init->bend_sort))
2255         yaz_log (YLOG_DEBUG, "Sort handler installed");
2256     if ((assoc->init->bend_search))
2257         yaz_log (YLOG_DEBUG, "Search handler installed");
2258     if ((assoc->init->bend_present))
2259         yaz_log (YLOG_DEBUG, "Present handler installed");   
2260     if ((assoc->init->bend_esrequest))
2261         yaz_log (YLOG_DEBUG, "ESRequest handler installed");   
2262     if ((assoc->init->bend_delete))
2263         yaz_log (YLOG_DEBUG, "Delete handler installed");   
2264     if ((assoc->init->bend_scan))
2265         yaz_log (YLOG_DEBUG, "Scan handler installed");   
2266     if ((assoc->init->bend_segment))
2267         yaz_log (YLOG_DEBUG, "Segment handler installed");   
2268     
2269     resp->referenceId = req->referenceId;
2270     *options = '\0';
2271     /* let's tell the client what we can do */
2272     if (ODR_MASK_GET(req->options, Z_Options_search))
2273     {
2274         ODR_MASK_SET(resp->options, Z_Options_search);
2275         strcat(options, "srch");
2276     }
2277     if (ODR_MASK_GET(req->options, Z_Options_present))
2278     {
2279         ODR_MASK_SET(resp->options, Z_Options_present);
2280         strcat(options, " prst");
2281     }
2282     if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
2283         assoc->init->bend_delete)
2284     {
2285         ODR_MASK_SET(resp->options, Z_Options_delSet);
2286         strcat(options, " del");
2287     }
2288     if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
2289         assoc->init->bend_esrequest)
2290     {
2291         ODR_MASK_SET(resp->options, Z_Options_extendedServices);
2292         strcat (options, " extendedServices");
2293     }
2294     if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
2295     {
2296         ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
2297         strcat(options, " namedresults");
2298     }
2299     if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
2300     {
2301         ODR_MASK_SET(resp->options, Z_Options_scan);
2302         strcat(options, " scan");
2303     }
2304     if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
2305     {
2306         ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
2307         strcat(options, " concurrop");
2308     }
2309     if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
2310     {
2311         ODR_MASK_SET(resp->options, Z_Options_sort);
2312         strcat(options, " sort");
2313     }
2314     
2315     if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
2316     {
2317         Z_OtherInformationUnit *p0;
2318
2319         if (!assoc->init->charneg_response)
2320         {
2321             if (assoc->init->query_charset)
2322             {
2323                 assoc->init->charneg_response = yaz_set_response_charneg(
2324                     assoc->encode, assoc->init->query_charset, 0, 
2325                     assoc->init->records_in_same_charset);
2326             }
2327             else
2328             {
2329                 yaz_log(YLOG_WARN, "default query_charset not defined by backend");
2330             }
2331         }
2332         if (assoc->init->charneg_response
2333             && (p0=yaz_oi_update(&resp->otherInfo, assoc->encode, NULL, 0, 0)))
2334         {
2335             p0->which = Z_OtherInfo_externallyDefinedInfo;
2336             p0->information.externallyDefinedInfo =
2337                 assoc->init->charneg_response;
2338             ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
2339             strcat(options, " negotiation");
2340         }
2341     }
2342     if (ODR_MASK_GET(req->options, Z_Options_triggerResourceCtrl))
2343         ODR_MASK_SET(resp->options, Z_Options_triggerResourceCtrl);
2344
2345     if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
2346     {
2347         ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
2348         assoc->version = 1; /* 1 & 2 are equivalent */
2349     }
2350     if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
2351     {
2352         ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
2353         assoc->version = 2;
2354     }
2355     if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
2356     {
2357         ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
2358         assoc->version = 3;
2359     }
2360
2361     yaz_log(log_requestdetail, "Negotiated to v%d: %s", assoc->version, options);
2362
2363     if (*req->maximumRecordSize < assoc->maximumRecordSize)
2364         assoc->maximumRecordSize = *req->maximumRecordSize;
2365
2366     if (*req->preferredMessageSize < assoc->preferredMessageSize)
2367         assoc->preferredMessageSize = *req->preferredMessageSize;
2368
2369     resp->preferredMessageSize = &assoc->preferredMessageSize;
2370     resp->maximumRecordSize = &assoc->maximumRecordSize;
2371
2372     resp->implementationId = odr_prepend(assoc->encode,
2373                 assoc->init->implementation_id,
2374                 resp->implementationId);
2375
2376     resp->implementationName = odr_prepend(assoc->encode,
2377                 assoc->init->implementation_name,
2378                 odr_prepend(assoc->encode, "GFS", resp->implementationName));
2379
2380     version = odr_strdup(assoc->encode, "$Revision: 1.124 $");
2381     if (strlen(version) > 10)   /* check for unexpanded CVS strings */
2382         version[strlen(version)-2] = '\0';
2383     resp->implementationVersion = odr_prepend(assoc->encode,
2384                 assoc->init->implementation_version,
2385                 odr_prepend(assoc->encode, &version[11],
2386                             resp->implementationVersion));
2387
2388     if (binitres->errcode)
2389     {
2390         assoc->state = ASSOC_DEAD;
2391         resp->userInformationField =
2392             init_diagnostics(assoc->encode, binitres->errcode,
2393                              binitres->errstring);
2394         *resp->result = 0;
2395     }
2396     if (log_request)
2397     {
2398         if (!req->idAuthentication)
2399             yaz_log(log_request, "Auth none");
2400         else if (req->idAuthentication->which == Z_IdAuthentication_open)
2401         {
2402             const char *open = req->idAuthentication->u.open;
2403             const char *slash = strchr(open, '/');
2404             int len;
2405             if (slash)
2406                 len = slash - open;
2407             else
2408                 len = strlen(open);
2409                 yaz_log(log_request, "Auth open %.*s", len, open);
2410         }
2411         else if (req->idAuthentication->which == Z_IdAuthentication_idPass)
2412         {
2413             const char *user = req->idAuthentication->u.idPass->userId;
2414             const char *group = req->idAuthentication->u.idPass->groupId;
2415             yaz_log(log_request, "Auth idPass %s %s",
2416                     user ? user : "-", group ? group : "-");
2417         }
2418         else if (req->idAuthentication->which 
2419                  == Z_IdAuthentication_anonymous)
2420         {
2421             yaz_log(log_request, "Auth anonymous");
2422         }
2423         else
2424         {
2425             yaz_log(log_request, "Auth other");
2426         }
2427     }
2428     if (log_request)
2429     {
2430         WRBUF wr = wrbuf_alloc();
2431         wrbuf_printf(wr, "Init ");
2432         if (binitres->errcode)
2433             wrbuf_printf(wr, "ERROR %d", binitres->errcode);
2434         else
2435             wrbuf_printf(wr, "OK -");
2436         wrbuf_printf(wr, " ID:%s Name:%s Version:%s",
2437                      (req->implementationId ? req->implementationId :"-"), 
2438                      (req->implementationName ?
2439                       req->implementationName : "-"),
2440                      (req->implementationVersion ?
2441                       req->implementationVersion : "-")
2442             );
2443         yaz_log(log_request, "%s", wrbuf_cstr(wr));
2444         wrbuf_destroy(wr);
2445     }
2446     return apdu;
2447 }
2448
2449 /*
2450  * Set the specified `errcode' and `errstring' into a UserInfo-1
2451  * external to be returned to the client in accordance with Z35.90
2452  * Implementor Agreement 5 (Returning diagnostics in an InitResponse):
2453  *      http://lcweb.loc.gov/z3950/agency/agree/initdiag.html
2454  */
2455 static Z_External *init_diagnostics(ODR odr, int error, const char *addinfo)
2456 {
2457     yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2458         addinfo ? " -- " : "", addinfo ? addinfo : "");
2459     return zget_init_diagnostics(odr, error, addinfo);
2460 }
2461
2462 /*
2463  * nonsurrogate diagnostic record.
2464  */
2465 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
2466 {
2467     Z_Records *rec = (Z_Records *) odr_malloc (assoc->encode, sizeof(*rec));
2468
2469     yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2470             addinfo ? " -- " : "", addinfo ? addinfo : "");
2471
2472     rec->which = Z_Records_NSD;
2473     rec->u.nonSurrogateDiagnostic = zget_DefaultDiagFormat(assoc->encode,
2474                                                            error, addinfo);
2475     return rec;
2476 }
2477
2478 /*
2479  * surrogate diagnostic.
2480  */
2481 static Z_NamePlusRecord *surrogatediagrec(association *assoc, 
2482                                           const char *dbname,
2483                                           int error, const char *addinfo)
2484 {
2485     yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2486             addinfo ? " -- " : "", addinfo ? addinfo : "");
2487     return zget_surrogateDiagRec(assoc->encode, dbname, error, addinfo);
2488 }
2489
2490 static Z_Records *pack_records(association *a, char *setname, int start,
2491                                int *num, Z_RecordComposition *comp,
2492                                int *next, int *pres,
2493                                Z_ReferenceId *referenceId,
2494                                Odr_oid *oid, int *errcode)
2495 {
2496     int recno, total_length = 0, toget = *num, dumped_records = 0;
2497     Z_Records *records =
2498         (Z_Records *) odr_malloc (a->encode, sizeof(*records));
2499     Z_NamePlusRecordList *reclist =
2500         (Z_NamePlusRecordList *) odr_malloc (a->encode, sizeof(*reclist));
2501     Z_NamePlusRecord **list =
2502         (Z_NamePlusRecord **) odr_malloc (a->encode, sizeof(*list) * toget);
2503
2504     records->which = Z_Records_DBOSD;
2505     records->u.databaseOrSurDiagnostics = reclist;
2506     reclist->num_records = 0;
2507     reclist->records = list;
2508     *pres = Z_PresentStatus_success;
2509     *num = 0;
2510     *next = 0;
2511
2512     yaz_log(log_requestdetail, "Request to pack %d+%d %s", start, toget, setname);
2513     yaz_log(log_requestdetail, "pms=%d, mrs=%d", a->preferredMessageSize,
2514         a->maximumRecordSize);
2515     for (recno = start; reclist->num_records < toget; recno++)
2516     {
2517         bend_fetch_rr freq;
2518         Z_NamePlusRecord *thisrec;
2519         int this_length = 0;
2520         /*
2521          * we get the number of bytes allocated on the stream before any
2522          * allocation done by the backend - this should give us a reasonable
2523          * idea of the total size of the data so far.
2524          */
2525         total_length = odr_total(a->encode) - dumped_records;
2526         freq.errcode = 0;
2527         freq.errstring = 0;
2528         freq.basename = 0;
2529         freq.len = 0;
2530         freq.record = 0;
2531         freq.last_in_set = 0;
2532         freq.setname = setname;
2533         freq.surrogate_flag = 0;
2534         freq.number = recno;
2535         freq.comp = comp;
2536         freq.request_format = oid;
2537         freq.output_format = 0;
2538         freq.stream = a->encode;
2539         freq.print = a->print;
2540         freq.referenceId = referenceId;
2541         freq.schema = 0;
2542
2543         retrieve_fetch(a, &freq);
2544
2545         *next = freq.last_in_set ? 0 : recno + 1;
2546
2547         /* backend should be able to signal whether error is system-wide
2548            or only pertaining to current record */
2549         if (freq.errcode)
2550         {
2551             if (!freq.surrogate_flag)
2552             {
2553                 char s[20];
2554                 *pres = Z_PresentStatus_failure;
2555                 /* for 'present request out of range',
2556                    set addinfo to record position if not set */
2557                 if (freq.errcode == YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE  && 
2558                                 freq.errstring == 0)
2559                 {
2560                     sprintf (s, "%d", recno);
2561                     freq.errstring = s;
2562                 }
2563                 if (errcode)
2564                     *errcode = freq.errcode;
2565                 return diagrec(a, freq.errcode, freq.errstring);
2566             }
2567             reclist->records[reclist->num_records] =
2568                 surrogatediagrec(a, freq.basename, freq.errcode,
2569                                  freq.errstring);
2570             reclist->num_records++;
2571             continue;
2572         }
2573         if (freq.record == 0)  /* no error and no record ? */
2574         {
2575             *next = 0;   /* signal end-of-set and stop */
2576             break;
2577         }
2578         if (freq.len >= 0)
2579             this_length = freq.len;
2580         else
2581             this_length = odr_total(a->encode) - total_length - dumped_records;
2582         yaz_log(YLOG_DEBUG, "  fetched record, len=%d, total=%d dumped=%d",
2583             this_length, total_length, dumped_records);
2584         if (a->preferredMessageSize > 0 &&
2585                 this_length + total_length > a->preferredMessageSize)
2586         {
2587             /* record is small enough, really */
2588             if (this_length <= a->preferredMessageSize && recno > start)
2589             {
2590                 yaz_log(log_requestdetail, "  Dropped last normal-sized record");
2591                 *pres = Z_PresentStatus_partial_2;
2592                 break;
2593             }
2594             /* record can only be fetched by itself */
2595             if (this_length < a->maximumRecordSize)
2596             {
2597                 yaz_log(log_requestdetail, "  Record > prefmsgsz");
2598                 if (toget > 1)
2599                 {
2600                     yaz_log(YLOG_DEBUG, "  Dropped it");
2601                     reclist->records[reclist->num_records] =
2602                          surrogatediagrec(a, freq.basename, 16, 0);
2603                     reclist->num_records++;
2604                     dumped_records += this_length;
2605                     continue;
2606                 }
2607             }
2608             else /* too big entirely */
2609             {
2610                 yaz_log(log_requestdetail, "Record > maxrcdsz this=%d max=%d",
2611                         this_length, a->maximumRecordSize);
2612                 reclist->records[reclist->num_records] =
2613                     surrogatediagrec(a, freq.basename, 17, 0);
2614                 reclist->num_records++;
2615                 dumped_records += this_length;
2616                 continue;
2617             }
2618         }
2619
2620         if (!(thisrec = (Z_NamePlusRecord *)
2621               odr_malloc(a->encode, sizeof(*thisrec))))
2622             return 0;
2623         if (freq.basename)
2624             thisrec->databaseName = odr_strdup(a->encode, freq.basename);
2625         else
2626             thisrec->databaseName = 0;
2627         thisrec->which = Z_NamePlusRecord_databaseRecord;
2628
2629         if (!freq.output_format)
2630             freq.output_format = freq.request_format;
2631         thisrec->u.databaseRecord = z_ext_record_oid(
2632             a->encode, freq.output_format, freq.record, freq.len);
2633         if (!thisrec->u.databaseRecord)
2634             return 0;
2635         reclist->records[reclist->num_records] = thisrec;
2636         reclist->num_records++;
2637     }
2638     *num = reclist->num_records;
2639     return records;
2640 }
2641
2642 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
2643     int *fd)
2644 {
2645     Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2646     bend_search_rr *bsrr = 
2647         (bend_search_rr *)nmem_malloc (reqb->request_mem, sizeof(*bsrr));
2648     
2649     yaz_log(log_requestdetail, "Got SearchRequest.");
2650     bsrr->fd = fd;
2651     bsrr->request = reqb;
2652     bsrr->association = assoc;
2653     bsrr->referenceId = req->referenceId;
2654     save_referenceId (reqb, bsrr->referenceId);
2655     bsrr->srw_sortKeys = 0;
2656     bsrr->srw_setname = 0;
2657     bsrr->srw_setnameIdleTime = 0;
2658     bsrr->estimated_hit_count = 0;
2659     bsrr->partial_resultset = 0;
2660
2661     yaz_log (log_requestdetail, "ResultSet '%s'", req->resultSetName);
2662     if (req->databaseNames)
2663     {
2664         int i;
2665         for (i = 0; i < req->num_databaseNames; i++)
2666             yaz_log(log_requestdetail, "Database '%s'", req->databaseNames[i]);
2667     }
2668
2669     yaz_log_zquery_level(log_requestdetail,req->query);
2670
2671     if (assoc->init->bend_search)
2672     {
2673         bsrr->setname = req->resultSetName;
2674         bsrr->replace_set = *req->replaceIndicator;
2675         bsrr->num_bases = req->num_databaseNames;
2676         bsrr->basenames = req->databaseNames;
2677         bsrr->query = req->query;
2678         bsrr->stream = assoc->encode;
2679         nmem_transfer(odr_getmem(bsrr->stream), reqb->request_mem);
2680         bsrr->decode = assoc->decode;
2681         bsrr->print = assoc->print;
2682         bsrr->hits = 0;
2683         bsrr->errcode = 0;
2684         bsrr->errstring = NULL;
2685         bsrr->search_info = NULL;
2686
2687         if (assoc->server && assoc->server->cql_transform 
2688             && req->query->which == Z_Query_type_104
2689             && req->query->u.type_104->which == Z_External_CQL)
2690         {
2691             /* have a CQL query and a CQL to PQF transform .. */
2692             int srw_errcode = 
2693                 cql2pqf(bsrr->stream, req->query->u.type_104->u.cql,
2694                         assoc->server->cql_transform, bsrr->query);
2695             if (srw_errcode)
2696                 bsrr->errcode = yaz_diag_srw_to_bib1(srw_errcode);
2697         }
2698
2699         if (assoc->server && assoc->server->ccl_transform 
2700             && req->query->which == Z_Query_type_2) /*CCL*/
2701         {
2702             /* have a CCL query and a CCL to PQF transform .. */
2703             int srw_errcode = 
2704                 ccl2pqf(bsrr->stream, req->query->u.type_2,
2705                         assoc->server->ccl_transform, bsrr);
2706             if (srw_errcode)
2707                 bsrr->errcode = yaz_diag_srw_to_bib1(srw_errcode);
2708         }
2709
2710         if (!bsrr->errcode)
2711             (assoc->init->bend_search)(assoc->backend, bsrr);
2712         if (!bsrr->request)  /* backend not ready with the search response */
2713             return 0;  /* should not be used any more */
2714     }
2715     else
2716     { 
2717         /* FIXME - make a diagnostic for it */
2718         yaz_log(YLOG_WARN,"Search not supported ?!?!");
2719     }
2720     return response_searchRequest(assoc, reqb, bsrr, fd);
2721 }
2722
2723 int bend_searchresponse(void *handle, bend_search_rr *bsrr) {return 0;}
2724
2725 /*
2726  * Prepare a searchresponse based on the backend results. We probably want
2727  * to look at making the fetching of records nonblocking as well, but
2728  * so far, we'll keep things simple.
2729  * If bsrt is null, that means we're called in response to a communications
2730  * event, and we'll have to get the response for ourselves.
2731  */
2732 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
2733     bend_search_rr *bsrt, int *fd)
2734 {
2735     Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2736     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2737     Z_SearchResponse *resp = (Z_SearchResponse *)
2738         odr_malloc (assoc->encode, sizeof(*resp));
2739     int *nulint = odr_intdup (assoc->encode, 0);
2740     int *next = odr_intdup(assoc->encode, 0);
2741     int *none = odr_intdup(assoc->encode, Z_SearchResponse_none);
2742     int returnedrecs = 0;
2743
2744     apdu->which = Z_APDU_searchResponse;
2745     apdu->u.searchResponse = resp;
2746     resp->referenceId = req->referenceId;
2747     resp->additionalSearchInfo = 0;
2748     resp->otherInfo = 0;
2749     *fd = -1;
2750     if (!bsrt && !bend_searchresponse(assoc->backend, bsrt))
2751     {
2752         yaz_log(YLOG_FATAL, "Bad result from backend");
2753         return 0;
2754     }
2755     else if (bsrt->errcode)
2756     {
2757         resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
2758         resp->resultCount = nulint;
2759         resp->numberOfRecordsReturned = nulint;
2760         resp->nextResultSetPosition = nulint;
2761         resp->searchStatus = nulint;
2762         resp->resultSetStatus = none;
2763         resp->presentStatus = 0;
2764     }
2765     else
2766     {
2767         bool_t *sr = odr_intdup(assoc->encode, 1);
2768         int *toget = odr_intdup(assoc->encode, 0);
2769         Z_RecordComposition comp, *compp = 0;
2770
2771         yaz_log (log_requestdetail, "resultCount: %d", bsrt->hits);
2772
2773         resp->records = 0;
2774         resp->resultCount = &bsrt->hits;
2775
2776         comp.which = Z_RecordComp_simple;
2777         /* how many records does the user agent want, then? */
2778         if (bsrt->hits <= *req->smallSetUpperBound)
2779         {
2780             *toget = bsrt->hits;
2781             if ((comp.u.simple = req->smallSetElementSetNames))
2782                 compp = &comp;
2783         }
2784         else if (bsrt->hits < *req->largeSetLowerBound)
2785         {
2786             *toget = *req->mediumSetPresentNumber;
2787             if (*toget > bsrt->hits)
2788                 *toget = bsrt->hits;
2789             if ((comp.u.simple = req->mediumSetElementSetNames))
2790                 compp = &comp;
2791         }
2792         else
2793             *toget = 0;
2794
2795         if (*toget && !resp->records)
2796         {
2797             int *presst = odr_intdup(assoc->encode, 0);
2798             /* Call bend_present if defined */
2799             if (assoc->init->bend_present)
2800             {
2801                 bend_present_rr *bprr = (bend_present_rr *)
2802                     nmem_malloc (reqb->request_mem, sizeof(*bprr));
2803                 bprr->setname = req->resultSetName;
2804                 bprr->start = 1;
2805                 bprr->number = *toget;
2806                 bprr->format = req->preferredRecordSyntax;
2807                 bprr->comp = compp;
2808                 bprr->referenceId = req->referenceId;
2809                 bprr->stream = assoc->encode;
2810                 bprr->print = assoc->print;
2811                 bprr->request = reqb;
2812                 bprr->association = assoc;
2813                 bprr->errcode = 0;
2814                 bprr->errstring = NULL;
2815                 (*assoc->init->bend_present)(assoc->backend, bprr);
2816
2817                 if (!bprr->request)
2818                     return 0;
2819                 if (bprr->errcode)
2820                 {
2821                     resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2822                     *resp->presentStatus = Z_PresentStatus_failure;
2823                 }
2824             }
2825
2826             if (!resp->records)
2827                 resp->records = pack_records(
2828                     assoc, req->resultSetName, 1,
2829                     toget, compp, next, presst, req->referenceId,
2830                     req->preferredRecordSyntax, NULL);
2831             if (!resp->records)
2832                 return 0;
2833             resp->numberOfRecordsReturned = toget;
2834             returnedrecs = *toget;
2835             resp->presentStatus = presst;
2836         }
2837         else
2838         {
2839             if (*resp->resultCount)
2840                 *next = 1;
2841             resp->numberOfRecordsReturned = nulint;
2842             resp->presentStatus = 0;
2843         }
2844         resp->nextResultSetPosition = next;
2845         resp->searchStatus = sr;
2846         resp->resultSetStatus = 0;
2847         if (bsrt->estimated_hit_count)
2848         {
2849             resp->resultSetStatus = odr_intdup(assoc->encode, 
2850                                                Z_SearchResponse_estimate);
2851         }
2852         else if (bsrt->partial_resultset)
2853         {
2854             resp->resultSetStatus = odr_intdup(assoc->encode, 
2855                                                Z_SearchResponse_subset);
2856         }
2857     }
2858     resp->additionalSearchInfo = bsrt->search_info;
2859
2860     if (log_request)
2861     {
2862         int i;
2863         WRBUF wr = wrbuf_alloc();
2864
2865         for (i = 0 ; i < req->num_databaseNames; i++){
2866             if (i)
2867                 wrbuf_printf(wr, "+");
2868             wrbuf_printf(wr, req->databaseNames[i]);
2869         }
2870         wrbuf_printf(wr, " ");
2871         
2872         if (bsrt->errcode)
2873             wrbuf_printf(wr, "ERROR %d", bsrt->errcode);
2874         else
2875             wrbuf_printf(wr, "OK %d", bsrt->hits);
2876         wrbuf_printf(wr, " %s 1+%d ",
2877                      req->resultSetName, returnedrecs);
2878         yaz_query_to_wrbuf(wr, req->query);
2879         
2880         yaz_log(log_request, "Search %s", wrbuf_cstr(wr));
2881         wrbuf_destroy(wr);
2882     }
2883     return apdu;
2884 }
2885
2886 /*
2887  * Maybe we got a little over-friendly when we designed bend_fetch to
2888  * get only one record at a time. Some backends can optimise multiple-record
2889  * fetches, and at any rate, there is some overhead involved in
2890  * all that selecting and hopping around. Problem is, of course, that the
2891  * frontend can't know ahead of time how many records it'll need to
2892  * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
2893  * is downright lousy as a bulk data transfer protocol.
2894  *
2895  * To start with, we'll do the fetching of records from the backend
2896  * in one operation: To save some trips in and out of the event-handler,
2897  * and to simplify the interface to pack_records. At any rate, asynch
2898  * operation is more fun in operations that have an unpredictable execution
2899  * speed - which is normally more true for search than for present.
2900  */
2901 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
2902                                       int *fd)
2903 {
2904     Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
2905     Z_APDU *apdu;
2906     Z_PresentResponse *resp;
2907     int *next;
2908     int *num;
2909     int errcode = 0;
2910     const char *errstring = 0;
2911
2912     yaz_log(log_requestdetail, "Got PresentRequest.");
2913
2914     resp = (Z_PresentResponse *)odr_malloc (assoc->encode, sizeof(*resp));
2915     resp->records = 0;
2916     resp->presentStatus = odr_intdup(assoc->encode, 0);
2917     if (assoc->init->bend_present)
2918     {
2919         bend_present_rr *bprr = (bend_present_rr *)
2920             nmem_malloc (reqb->request_mem, sizeof(*bprr));
2921         bprr->setname = req->resultSetId;
2922         bprr->start = *req->resultSetStartPoint;
2923         bprr->number = *req->numberOfRecordsRequested;
2924         bprr->format = req->preferredRecordSyntax;
2925         bprr->comp = req->recordComposition;
2926         bprr->referenceId = req->referenceId;
2927         bprr->stream = assoc->encode;
2928         bprr->print = assoc->print;
2929         bprr->request = reqb;
2930         bprr->association = assoc;
2931         bprr->errcode = 0;
2932         bprr->errstring = NULL;
2933         (*assoc->init->bend_present)(assoc->backend, bprr);
2934         
2935         if (!bprr->request)
2936             return 0; /* should not happen */
2937         if (bprr->errcode)
2938         {
2939             resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2940             *resp->presentStatus = Z_PresentStatus_failure;
2941             errcode = bprr->errcode;
2942             errstring = bprr->errstring;
2943         }
2944     }
2945     apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2946     next = odr_intdup(assoc->encode, 0);
2947     num = odr_intdup(assoc->encode, 0);
2948     
2949     apdu->which = Z_APDU_presentResponse;
2950     apdu->u.presentResponse = resp;
2951     resp->referenceId = req->referenceId;
2952     resp->otherInfo = 0;
2953     
2954     if (!resp->records)
2955     {
2956         *num = *req->numberOfRecordsRequested;
2957         resp->records =
2958             pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
2959                          num, req->recordComposition, next,
2960                          resp->presentStatus,
2961                          req->referenceId, req->preferredRecordSyntax, 
2962                          &errcode);
2963     }
2964     if (log_request)
2965     {
2966         WRBUF wr = wrbuf_alloc();
2967         wrbuf_printf(wr, "Present ");
2968
2969         if (*resp->presentStatus == Z_PresentStatus_failure)
2970             wrbuf_printf(wr, "ERROR %d ", errcode);
2971         else if (*resp->presentStatus == Z_PresentStatus_success)
2972             wrbuf_printf(wr, "OK -  ");
2973         else
2974             wrbuf_printf(wr, "Partial %d - ", *resp->presentStatus);
2975
2976         wrbuf_printf(wr, " %s %d+%d ",
2977                 req->resultSetId, *req->resultSetStartPoint,
2978                 *req->numberOfRecordsRequested);
2979         yaz_log(log_request, "%s", wrbuf_cstr(wr) );
2980         wrbuf_destroy(wr);
2981     }
2982     if (!resp->records)
2983         return 0;
2984     resp->numberOfRecordsReturned = num;
2985     resp->nextResultSetPosition = next;
2986     
2987     return apdu;
2988 }
2989
2990 /*
2991  * Scan was implemented rather in a hurry, and with support for only the basic
2992  * elements of the service in the backend API. Suggestions are welcome.
2993  */
2994 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
2995 {
2996     Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
2997     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2998     Z_ScanResponse *res = (Z_ScanResponse *)
2999         odr_malloc (assoc->encode, sizeof(*res));
3000     int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
3001     int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
3002     Z_ListEntries *ents = (Z_ListEntries *)
3003         odr_malloc (assoc->encode, sizeof(*ents));
3004     Z_DiagRecs *diagrecs_p = NULL;
3005     bend_scan_rr *bsrr = (bend_scan_rr *)
3006         odr_malloc (assoc->encode, sizeof(*bsrr));
3007     struct scan_entry *save_entries;
3008
3009     yaz_log(log_requestdetail, "Got ScanRequest");
3010
3011     apdu->which = Z_APDU_scanResponse;
3012     apdu->u.scanResponse = res;
3013     res->referenceId = req->referenceId;
3014
3015     /* if step is absent, set it to 0 */
3016     res->stepSize = odr_intdup(assoc->encode, 0);
3017     if (req->stepSize)
3018         *res->stepSize = *req->stepSize;
3019
3020     res->scanStatus = scanStatus;
3021     res->numberOfEntriesReturned = numberOfEntriesReturned;
3022     res->positionOfTerm = 0;
3023     res->entries = ents;
3024     ents->num_entries = 0;
3025     ents->entries = NULL;
3026     ents->num_nonsurrogateDiagnostics = 0;
3027     ents->nonsurrogateDiagnostics = NULL;
3028     res->attributeSet = 0;
3029     res->otherInfo = 0;
3030
3031     if (req->databaseNames)
3032     {
3033         int i;
3034         for (i = 0; i < req->num_databaseNames; i++)
3035             yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
3036     }
3037     bsrr->scanClause = 0;
3038     bsrr->errcode = 0;
3039     bsrr->errstring = 0;
3040     bsrr->num_bases = req->num_databaseNames;
3041     bsrr->basenames = req->databaseNames;
3042     bsrr->num_entries = *req->numberOfTermsRequested;
3043     bsrr->term = req->termListAndStartPoint;
3044     bsrr->referenceId = req->referenceId;
3045     bsrr->stream = assoc->encode;
3046     bsrr->print = assoc->print;
3047     bsrr->step_size = res->stepSize;
3048     bsrr->setname = yaz_oi_get_string_oid(&req->otherInfo, 
3049                                           yaz_oid_userinfo_scan_set, 1, 0);
3050     bsrr->entries = 0;
3051     /* For YAZ 2.0 and earlier it was the backend handler that
3052        initialized entries (member display_term did not exist)
3053        YAZ 2.0 and later sets 'entries'  and initialize all members
3054        including 'display_term'. If YAZ 2.0 or later sees that
3055        entries was modified - we assume that it is an old handler and
3056        that 'display_term' is _not_ set.
3057     */
3058     if (bsrr->num_entries > 0) 
3059     {
3060         int i;
3061         bsrr->entries = (struct scan_entry *)
3062             odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
3063                        bsrr->num_entries);
3064         for (i = 0; i<bsrr->num_entries; i++)
3065         {
3066             bsrr->entries[i].term = 0;
3067             bsrr->entries[i].occurrences = 0;
3068             bsrr->entries[i].errcode = 0;
3069             bsrr->entries[i].errstring = 0;
3070             bsrr->entries[i].display_term = 0;
3071         }
3072     }
3073     save_entries = bsrr->entries;  /* save it so we can compare later */
3074
3075     bsrr->attributeset = req->attributeSet;
3076     log_scan_term_level (log_requestdetail, req->termListAndStartPoint, 
3077             bsrr->attributeset);
3078     bsrr->term_position = req->preferredPositionInResponse ?
3079         *req->preferredPositionInResponse : 1;
3080
3081     ((int (*)(void *, bend_scan_rr *))
3082      (*assoc->init->bend_scan))(assoc->backend, bsrr);
3083
3084     if (bsrr->errcode)
3085         diagrecs_p = zget_DiagRecs(assoc->encode,
3086                                    bsrr->errcode, bsrr->errstring);
3087     else
3088     {
3089         int i;
3090         Z_Entry **tab = (Z_Entry **)
3091             odr_malloc (assoc->encode, sizeof(*tab) * bsrr->num_entries);
3092         
3093         if (bsrr->status == BEND_SCAN_PARTIAL)
3094             *scanStatus = Z_Scan_partial_5;
3095         else
3096             *scanStatus = Z_Scan_success;
3097         ents->entries = tab;
3098         ents->num_entries = bsrr->num_entries;
3099         res->numberOfEntriesReturned = &ents->num_entries;          
3100         res->positionOfTerm = &bsrr->term_position;
3101         for (i = 0; i < bsrr->num_entries; i++)
3102         {
3103             Z_Entry *e;
3104             Z_TermInfo *t;
3105             Odr_oct *o;
3106             
3107             tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
3108             if (bsrr->entries[i].occurrences >= 0)
3109             {
3110                 e->which = Z_Entry_termInfo;
3111                 e->u.termInfo = t = (Z_TermInfo *)
3112                     odr_malloc(assoc->encode, sizeof(*t));
3113                 t->suggestedAttributes = 0;
3114                 t->displayTerm = 0;
3115                 if (save_entries == bsrr->entries && 
3116                     bsrr->entries[i].display_term)
3117                 {
3118                     /* the entries was _not_ set by the handler. So it's
3119                        safe to test for new member display_term. It is
3120                        NULL'ed by us.
3121                     */
3122                     t->displayTerm = odr_strdup(assoc->encode,
3123                                                 bsrr->entries[i].display_term);
3124                 }
3125                 t->alternativeTerm = 0;
3126                 t->byAttributes = 0;
3127                 t->otherTermInfo = 0;
3128                 t->globalOccurrences = &bsrr->entries[i].occurrences;
3129                 t->term = (Z_Term *)
3130                     odr_malloc(assoc->encode, sizeof(*t->term));
3131                 t->term->which = Z_Term_general;
3132                 t->term->u.general = o =
3133                     (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
3134                 o->buf = (unsigned char *)
3135                     odr_malloc(assoc->encode, o->len = o->size =
3136                                strlen(bsrr->entries[i].term));
3137                 memcpy(o->buf, bsrr->entries[i].term, o->len);
3138                 yaz_log(YLOG_DEBUG, "  term #%d: '%s' (%d)", i,
3139                          bsrr->entries[i].term, bsrr->entries[i].occurrences);
3140             }
3141             else
3142             {
3143                 Z_DiagRecs *drecs = zget_DiagRecs(assoc->encode,
3144                                                   bsrr->entries[i].errcode,
3145                                                   bsrr->entries[i].errstring);
3146                 assert (drecs->num_diagRecs == 1);
3147                 e->which = Z_Entry_surrogateDiagnostic;
3148                 assert (drecs->diagRecs[0]);
3149                 e->u.surrogateDiagnostic = drecs->diagRecs[0];
3150             }
3151         }
3152     }
3153     if (diagrecs_p)
3154     {
3155         ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
3156         ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
3157     }
3158     if (log_request)
3159     {
3160         int i;
3161         WRBUF wr = wrbuf_alloc();
3162         wrbuf_printf(wr, "Scan ");
3163         for (i = 0 ; i < req->num_databaseNames; i++)
3164         {
3165             if (i)
3166                 wrbuf_printf(wr, "+");
3167             wrbuf_printf(wr, req->databaseNames[i]);
3168         }
3169
3170         wrbuf_printf(wr, " ");
3171         
3172         if (bsrr->errcode)
3173             wr_diag(wr, bsrr->errcode, bsrr->errstring);
3174         else
3175             wrbuf_printf(wr, "OK"); 
3176
3177         wrbuf_printf(wr, " %d - %d+%d+%d",
3178                      res->numberOfEntriesReturned ?
3179                      *res->numberOfEntriesReturned : 0,
3180                      (req->preferredPositionInResponse ?
3181                       *req->preferredPositionInResponse : 1),
3182                      *req->numberOfTermsRequested,
3183                      (res->stepSize ? *res->stepSize : 1));
3184         
3185         if (bsrr->setname)
3186             wrbuf_printf(wr, "+%s", bsrr->setname);
3187
3188         wrbuf_printf(wr, " ");
3189         yaz_scan_to_wrbuf(wr, req->termListAndStartPoint, 
3190                           bsrr->attributeset);
3191         yaz_log(log_request, "%s", wrbuf_cstr(wr) );
3192         wrbuf_destroy(wr);
3193     }
3194     return apdu;
3195 }
3196
3197 static Z_APDU *process_sortRequest(association *assoc, request *reqb,
3198     int *fd)
3199 {
3200     int i;
3201     Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
3202     Z_SortResponse *res = (Z_SortResponse *)
3203         odr_malloc (assoc->encode, sizeof(*res));
3204     bend_sort_rr *bsrr = (bend_sort_rr *)
3205         odr_malloc (assoc->encode, sizeof(*bsrr));
3206
3207     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
3208
3209     yaz_log(log_requestdetail, "Got SortRequest.");
3210
3211     bsrr->num_input_setnames = req->num_inputResultSetNames;
3212     for (i=0;i<req->num_inputResultSetNames;i++)
3213         yaz_log(log_requestdetail, "Input resultset: '%s'",
3214                 req->inputResultSetNames[i]);
3215     bsrr->input_setnames = req->inputResultSetNames;
3216     bsrr->referenceId = req->referenceId;
3217     bsrr->output_setname = req->sortedResultSetName;
3218     yaz_log(log_requestdetail, "Output resultset: '%s'",
3219                 req->sortedResultSetName);
3220     bsrr->sort_sequence = req->sortSequence;
3221        /*FIXME - dump those sequences too */
3222     bsrr->stream = assoc->encode;
3223     bsrr->print = assoc->print;
3224
3225     bsrr->sort_status = Z_SortResponse_failure;
3226     bsrr->errcode = 0;
3227     bsrr->errstring = 0;
3228     
3229     (*assoc->init->bend_sort)(assoc->backend, bsrr);
3230     
3231     res->referenceId = bsrr->referenceId;
3232     res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
3233     res->resultSetStatus = 0;
3234     if (bsrr->errcode)
3235     {
3236         Z_DiagRecs *dr = zget_DiagRecs(assoc->encode,
3237                                        bsrr->errcode, bsrr->errstring);
3238         res->diagnostics = dr->diagRecs;
3239         res->num_diagnostics = dr->num_diagRecs;
3240     }
3241     else
3242     {
3243         res->num_diagnostics = 0;
3244         res->diagnostics = 0;
3245     }
3246     res->resultCount = 0;
3247     res->otherInfo = 0;
3248
3249     apdu->which = Z_APDU_sortResponse;
3250     apdu->u.sortResponse = res;
3251     if (log_request)
3252     {
3253         WRBUF wr = wrbuf_alloc();
3254         wrbuf_printf(wr, "Sort ");
3255         if (bsrr->errcode)
3256             wrbuf_printf(wr, " ERROR %d", bsrr->errcode);
3257         else
3258             wrbuf_printf(wr,  "OK -");
3259         wrbuf_printf(wr, " (");
3260         for (i = 0; i<req->num_inputResultSetNames; i++)
3261         {
3262             if (i)
3263                 wrbuf_printf(wr, "+");
3264             wrbuf_printf(wr, req->inputResultSetNames[i]);
3265         }
3266         wrbuf_printf(wr, ")->%s ",req->sortedResultSetName);
3267
3268         yaz_log(log_request, "%s", wrbuf_cstr(wr) );
3269         wrbuf_destroy(wr);
3270     }
3271     return apdu;
3272 }
3273
3274 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
3275     int *fd)
3276 {
3277     int i;
3278     Z_DeleteResultSetRequest *req =
3279         reqb->apdu_request->u.deleteResultSetRequest;
3280     Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
3281         odr_malloc (assoc->encode, sizeof(*res));
3282     bend_delete_rr *bdrr = (bend_delete_rr *)
3283         odr_malloc (assoc->encode, sizeof(*bdrr));
3284     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
3285
3286     yaz_log(log_requestdetail, "Got DeleteRequest.");
3287
3288     bdrr->num_setnames = req->num_resultSetList;
3289     bdrr->setnames = req->resultSetList;
3290     for (i = 0; i<req->num_resultSetList; i++)
3291         yaz_log(log_requestdetail, "resultset: '%s'",
3292                 req->resultSetList[i]);
3293     bdrr->stream = assoc->encode;
3294     bdrr->print = assoc->print;
3295     bdrr->function = *req->deleteFunction;
3296     bdrr->referenceId = req->referenceId;
3297     bdrr->statuses = 0;
3298     if (bdrr->num_setnames > 0)
3299     {
3300         bdrr->statuses = (int*) 
3301             odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
3302                        bdrr->num_setnames);
3303         for (i = 0; i < bdrr->num_setnames; i++)
3304             bdrr->statuses[i] = 0;
3305     }
3306     (*assoc->init->bend_delete)(assoc->backend, bdrr);
3307     
3308     res->referenceId = req->referenceId;
3309
3310     res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
3311
3312     res->deleteListStatuses = 0;
3313     if (bdrr->num_setnames > 0)
3314     {
3315         int i;
3316         res->deleteListStatuses = (Z_ListStatuses *)
3317             odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
3318         res->deleteListStatuses->num = bdrr->num_setnames;
3319         res->deleteListStatuses->elements =
3320             (Z_ListStatus **)
3321             odr_malloc (assoc->encode, 
3322                         sizeof(*res->deleteListStatuses->elements) *
3323                         bdrr->num_setnames);
3324         for (i = 0; i<bdrr->num_setnames; i++)
3325         {
3326             res->deleteListStatuses->elements[i] =
3327                 (Z_ListStatus *)
3328                 odr_malloc (assoc->encode,
3329                             sizeof(**res->deleteListStatuses->elements));
3330             res->deleteListStatuses->elements[i]->status = bdrr->statuses+i;
3331             res->deleteListStatuses->elements[i]->id =
3332                 odr_strdup (assoc->encode, bdrr->setnames[i]);
3333         }
3334     }
3335     res->numberNotDeleted = 0;
3336     res->bulkStatuses = 0;
3337     res->deleteMessage = 0;
3338     res->otherInfo = 0;
3339
3340     apdu->which = Z_APDU_deleteResultSetResponse;
3341     apdu->u.deleteResultSetResponse = res;
3342     if (log_request)
3343     {
3344         WRBUF wr = wrbuf_alloc();
3345         wrbuf_printf(wr, "Delete ");
3346         if (bdrr->delete_status)
3347             wrbuf_printf(wr, "ERROR %d", bdrr->delete_status);
3348         else
3349             wrbuf_printf(wr, "OK -");
3350         for (i = 0; i<req->num_resultSetList; i++)
3351             wrbuf_printf(wr, " %s ", req->resultSetList[i]);
3352         yaz_log(log_request, "%s", wrbuf_cstr(wr) );
3353         wrbuf_destroy(wr);
3354     }
3355     return apdu;
3356 }
3357
3358 static void process_close(association *assoc, request *reqb)
3359 {
3360     Z_Close *req = reqb->apdu_request->u.close;
3361     static char *reasons[] =
3362     {
3363         "finished",
3364         "shutdown",
3365         "systemProblem",
3366         "costLimit",
3367         "resources",
3368         "securityViolation",
3369         "protocolError",
3370         "lackOfActivity",
3371         "peerAbort",
3372         "unspecified"
3373     };
3374
3375     yaz_log(log_requestdetail, "Got Close, reason %s, message %s",
3376         reasons[*req->closeReason], req->diagnosticInformation ?
3377         req->diagnosticInformation : "NULL");
3378     if (assoc->version < 3) /* to make do_force respond with close */
3379         assoc->version = 3;
3380     do_close_req(assoc, Z_Close_finished,
3381                  "Association terminated by client", reqb);
3382     yaz_log(log_request,"Close OK");
3383 }
3384
3385 void save_referenceId (request *reqb, Z_ReferenceId *refid)
3386 {
3387     if (refid)
3388     {
3389         reqb->len_refid = refid->len;
3390         reqb->refid = (char *)nmem_malloc (reqb->request_mem, refid->len);
3391         memcpy (reqb->refid, refid->buf, refid->len);
3392     }
3393     else
3394     {
3395         reqb->len_refid = 0;
3396         reqb->refid = NULL;
3397     }
3398 }
3399
3400 void bend_request_send (bend_association a, bend_request req, Z_APDU *res)
3401 {
3402     process_z_response (a, req, res);
3403 }
3404
3405 bend_request bend_request_mk (bend_association a)
3406 {
3407     request *nreq = request_get (&a->outgoing);
3408     nreq->request_mem = nmem_create ();
3409     return nreq;
3410 }
3411
3412 Z_ReferenceId *bend_request_getid (ODR odr, bend_request req)
3413 {
3414     Z_ReferenceId *id;
3415     if (!req->refid)
3416         return 0;
3417     id = (Odr_oct *)odr_malloc (odr, sizeof(*odr));
3418     id->buf = (unsigned char *)odr_malloc (odr, req->len_refid);
3419     id->len = id->size = req->len_refid;
3420     memcpy (id->buf, req->refid, req->len_refid);
3421     return id;
3422 }
3423
3424 void bend_request_destroy (bend_request *req)
3425 {
3426     nmem_destroy((*req)->request_mem);
3427     request_release(*req);
3428     *req = NULL;
3429 }
3430
3431 int bend_backend_respond (bend_association a, bend_request req)
3432 {
3433     char *msg;
3434     int r;
3435     r = process_z_request (a, req, &msg);
3436     if (r < 0)
3437         yaz_log (YLOG_WARN, "%s", msg);
3438     return r;
3439 }
3440
3441 void bend_request_setdata(bend_request r, void *p)
3442 {
3443     r->clientData = p;
3444 }
3445
3446 void *bend_request_getdata(bend_request r)
3447 {
3448     return r->clientData;
3449 }
3450
3451 static Z_APDU *process_segmentRequest (association *assoc, request *reqb)
3452 {
3453     bend_segment_rr req;
3454
3455     req.segment = reqb->apdu_request->u.segmentRequest;
3456     req.stream = assoc->encode;
3457     req.decode = assoc->decode;
3458     req.print = assoc->print;
3459     req.association = assoc;
3460     
3461     (*assoc->init->bend_segment)(assoc->backend, &req);
3462
3463     return 0;
3464 }
3465
3466 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd)
3467 {
3468     bend_esrequest_rr esrequest;
3469     const char *ext_name = "unknown";
3470
3471     Z_ExtendedServicesRequest *req =
3472         reqb->apdu_request->u.extendedServicesRequest;
3473     Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
3474
3475     Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
3476
3477     esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
3478     esrequest.stream = assoc->encode;
3479     esrequest.decode = assoc->decode;
3480     esrequest.print = assoc->print;
3481     esrequest.errcode = 0;
3482     esrequest.errstring = NULL;
3483     esrequest.request = reqb;
3484     esrequest.association = assoc;
3485     esrequest.taskPackage = 0;
3486     esrequest.referenceId = req->referenceId;
3487
3488     
3489     if (esrequest.esr && esrequest.esr->taskSpecificParameters)
3490     {
3491         switch(esrequest.esr->taskSpecificParameters->which)
3492         {
3493         case Z_External_itemOrder:
3494             ext_name = "ItemOrder"; break;
3495         case Z_External_update:
3496             ext_name = "Update"; break;
3497         case Z_External_update0:
3498             ext_name = "Update0"; break;
3499         case Z_External_ESAdmin:
3500             ext_name = "Admin"; break;
3501
3502         }
3503     }
3504
3505     (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
3506     
3507     /* If the response is being delayed, return NULL */
3508     if (esrequest.request == NULL)
3509         return(NULL);
3510
3511     resp->referenceId = req->referenceId;
3512
3513     if (esrequest.errcode == -1)
3514     {
3515         /* Backend service indicates request will be processed */
3516         yaz_log(log_request, "Extended Service: %s (accepted)", ext_name);
3517         *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
3518     }
3519     else if (esrequest.errcode == 0)
3520     {
3521         /* Backend service indicates request will be processed */
3522         yaz_log(log_request, "Extended Service: %s (done)", ext_name);
3523         *resp->operationStatus = Z_ExtendedServicesResponse_done;
3524     }
3525     else
3526     {
3527         Z_DiagRecs *diagRecs =
3528             zget_DiagRecs(assoc->encode, esrequest.errcode,
3529                           esrequest.errstring);
3530         /* Backend indicates error, request will not be processed */
3531         yaz_log(log_request, "Extended Service: %s (failed)", ext_name);
3532         *resp->operationStatus = Z_ExtendedServicesResponse_failure;
3533         resp->num_diagnostics = diagRecs->num_diagRecs;
3534         resp->diagnostics = diagRecs->diagRecs;
3535         if (log_request)
3536         {
3537             WRBUF wr = wrbuf_alloc();
3538             wrbuf_diags(wr, resp->num_diagnostics, resp->diagnostics);
3539             yaz_log(log_request, "EsRequest %s", wrbuf_cstr(wr) );
3540             wrbuf_destroy(wr);
3541         }
3542
3543     }
3544     /* Do something with the members of bend_extendedservice */
3545     if (esrequest.taskPackage)
3546     {
3547         resp->taskPackage = z_ext_record_oid(
3548             assoc->encode, yaz_oid_recsyn_extended,
3549             (const char *)  esrequest.taskPackage, -1
3550             );
3551     }
3552     yaz_log(YLOG_DEBUG,"Send the result apdu");
3553     return apdu;
3554 }
3555
3556 int bend_assoc_is_alive(bend_association assoc)
3557 {
3558     if (assoc->state == ASSOC_DEAD)
3559         return 0; /* already marked as dead. Don't check I/O chan anymore */
3560
3561     return iochan_is_alive(assoc->client_chan);
3562 }
3563
3564
3565 /*
3566  * Local variables:
3567  * c-basic-offset: 4
3568  * indent-tabs-mode: nil
3569  * End:
3570  * vim: shiftwidth=4 tabstop=8 expandtab
3571  */
3572