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