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