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