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