Fixed bug #2068: pkg-config trouble.
[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.128 2007-09-11 08:37:53 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         record->recordSchema = odr_strdup_null(o, rr.schema);
771     }
772     if (rr.errcode)
773     {
774         *addinfo = rr.errstring;
775         return rr.errcode;
776     }
777     return 0;
778 }
779
780 static int cql2pqf(ODR odr, const char *cql, cql_transform_t ct,
781                    Z_Query *query_result)
782 {
783     /* have a CQL query and  CQL to PQF transform .. */
784     CQL_parser cp = cql_parser_create();
785     int r;
786     int srw_errcode = 0;
787     const char *add = 0;
788     char rpn_buf[5120];
789             
790     r = cql_parser_string(cp, cql);
791     if (r)
792     {
793         /* CQL syntax error */
794         srw_errcode = 10; 
795     }
796     if (!r)
797     {
798         /* Syntax OK */
799         r = cql_transform_buf(ct,
800                               cql_parser_result(cp),
801                               rpn_buf, sizeof(rpn_buf)-1);
802         if (r)
803             srw_errcode  = cql_transform_error(ct, &add);
804     }
805     if (!r)
806     {
807         /* Syntax & transform OK. */
808         /* Convert PQF string to Z39.50 to RPN query struct */
809         YAZ_PQF_Parser pp = yaz_pqf_create();
810         Z_RPNQuery *rpnquery = yaz_pqf_parse(pp, odr, rpn_buf);
811         if (!rpnquery)
812         {
813             size_t off;
814             const char *pqf_msg;
815             int code = yaz_pqf_error(pp, &pqf_msg, &off);
816             yaz_log(YLOG_WARN, "PQF Parser Error %s (code %d)",
817                     pqf_msg, code);
818             srw_errcode = 10;
819         }
820         else
821         {
822             query_result->which = Z_Query_type_1;
823             query_result->u.type_1 = rpnquery;
824         }
825         yaz_pqf_destroy(pp);
826     }
827     cql_parser_destroy(cp);
828     return srw_errcode;
829 }
830
831 static int cql2pqf_scan(ODR odr, const char *cql, cql_transform_t ct,
832                         Z_AttributesPlusTerm *result)
833 {
834     Z_Query query;
835     Z_RPNQuery *rpn;
836     int srw_error = cql2pqf(odr, cql, ct, &query);
837     if (srw_error)
838         return srw_error;
839     if (query.which != Z_Query_type_1 && query.which != Z_Query_type_101)
840         return 10; /* bad query type */
841     rpn = query.u.type_1;
842     if (!rpn->RPNStructure) 
843         return 10; /* must be structure */
844     if (rpn->RPNStructure->which != Z_RPNStructure_simple)
845         return 10; /* must be simple */
846     if (rpn->RPNStructure->u.simple->which != Z_Operand_APT)
847         return 10; /* must be attributes plus term node .. */
848     memcpy(result, rpn->RPNStructure->u.simple->u.attributesPlusTerm,
849            sizeof(*result));
850     return 0;
851 }
852                    
853
854 static int ccl2pqf(ODR odr, const Odr_oct *ccl, CCL_bibset bibset,
855                    bend_search_rr *bsrr) {
856     char *ccl0;
857     struct ccl_rpn_node *node;
858     int errcode, pos;
859
860     ccl0 = odr_strdupn(odr, (char*) ccl->buf, ccl->len);
861     if ((node = ccl_find_str(bibset, ccl0, &errcode, &pos)) == 0) {
862         bsrr->errstring = (char*) ccl_err_msg(errcode);
863         return 10;              /* Query syntax error */
864     }
865
866     bsrr->query->which = Z_Query_type_1;
867     bsrr->query->u.type_1 = ccl_rpn_query(odr, node);
868     return 0;
869 }
870
871
872 static void srw_bend_search(association *assoc, request *req,
873                             Z_SRW_PDU *sr,
874                             Z_SRW_searchRetrieveResponse *srw_res,
875                             int *http_code)
876 {
877     int srw_error = 0;
878     Z_External *ext;
879     Z_SRW_searchRetrieveRequest *srw_req = sr->u.request;
880     
881     *http_code = 200;
882     yaz_log(log_requestdetail, "Got SRW SearchRetrieveRequest");
883     srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
884     if (srw_res->num_diagnostics == 0 && assoc->init)
885     {
886         bend_search_rr rr;
887         rr.setname = "default";
888         rr.replace_set = 1;
889         rr.num_bases = 1;
890         rr.basenames = &srw_req->database;
891         rr.referenceId = 0;
892         rr.srw_sortKeys = 0;
893         rr.srw_setname = 0;
894         rr.srw_setnameIdleTime = 0;
895         rr.estimated_hit_count = 0;
896         rr.partial_resultset = 0;
897         rr.query = (Z_Query *) odr_malloc (assoc->decode, sizeof(*rr.query));
898         rr.query->u.type_1 = 0;
899         
900         if (srw_req->query_type == Z_SRW_query_type_cql)
901         {
902             if (assoc->server && assoc->server->cql_transform)
903             {
904                 int srw_errcode = cql2pqf(assoc->encode, srw_req->query.cql,
905                                           assoc->server->cql_transform,
906                                           rr.query);
907                 if (srw_errcode)
908                 {
909                     yaz_add_srw_diagnostic(assoc->encode,
910                                            &srw_res->diagnostics,
911                                            &srw_res->num_diagnostics,
912                                            srw_errcode, 0);
913                 }
914             }
915             else
916             {
917                 /* CQL query to backend. Wrap it - Z39.50 style */
918                 ext = (Z_External *) odr_malloc(assoc->decode, sizeof(*ext));
919                 ext->direct_reference = odr_getoidbystr(assoc->decode, 
920                                                         "1.2.840.10003.16.2");
921                 ext->indirect_reference = 0;
922                 ext->descriptor = 0;
923                 ext->which = Z_External_CQL;
924                 ext->u.cql = srw_req->query.cql;
925                 
926                 rr.query->which = Z_Query_type_104;
927                 rr.query->u.type_104 =  ext;
928             }
929         }
930         else if (srw_req->query_type == Z_SRW_query_type_pqf)
931         {
932             Z_RPNQuery *RPNquery;
933             YAZ_PQF_Parser pqf_parser;
934             
935             pqf_parser = yaz_pqf_create ();
936             
937             RPNquery = yaz_pqf_parse (pqf_parser, assoc->decode,
938                                       srw_req->query.pqf);
939             if (!RPNquery)
940             {
941                 const char *pqf_msg;
942                 size_t off;
943                 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
944                 yaz_log(log_requestdetail, "Parse error %d %s near offset %ld",
945                         code, pqf_msg, (long) off);
946                 srw_error = YAZ_SRW_QUERY_SYNTAX_ERROR;
947             }
948             
949             rr.query->which = Z_Query_type_1;
950             rr.query->u.type_1 =  RPNquery;
951             
952             yaz_pqf_destroy (pqf_parser);
953         }
954         else
955         {
956             yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
957                                    &srw_res->num_diagnostics,
958                                    YAZ_SRW_UNSUPP_QUERY_TYPE, 0);
959         }
960         if (rr.query->u.type_1)
961         {
962             rr.stream = assoc->encode;
963             rr.decode = assoc->decode;
964             rr.print = assoc->print;
965             rr.request = req;
966             if ( srw_req->sort.sortKeys )
967                 rr.srw_sortKeys = odr_strdup(assoc->encode, 
968                                              srw_req->sort.sortKeys );
969             rr.association = assoc;
970             rr.fd = 0;
971             rr.hits = 0;
972             rr.errcode = 0;
973             rr.errstring = 0;
974             rr.search_info = 0;
975             yaz_log_zquery_level(log_requestdetail,rr.query);
976             
977             (assoc->init->bend_search)(assoc->backend, &rr);
978             if (rr.errcode)
979             {
980                 if (rr.errcode == YAZ_BIB1_DATABASE_UNAVAILABLE)
981                 {
982                     *http_code = 404;
983                 }
984                 else
985                 {
986                     srw_error = yaz_diag_bib1_to_srw (rr.errcode);
987                     yaz_add_srw_diagnostic(assoc->encode,
988                                            &srw_res->diagnostics,
989                                            &srw_res->num_diagnostics,
990                                            srw_error, rr.errstring);
991                 }
992             }
993             else
994             {
995                 int number = srw_req->maximumRecords ? *srw_req->maximumRecords : 0;
996                 int start = srw_req->startRecord ? *srw_req->startRecord : 1;
997                 
998                 yaz_log(log_requestdetail, "Request to pack %d+%d out of %d",
999                         start, number, rr.hits);
1000                 
1001                 srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
1002                 if (rr.srw_setname)
1003                 {
1004                     srw_res->resultSetId =
1005                         odr_strdup(assoc->encode, rr.srw_setname );
1006                     srw_res->resultSetIdleTime =
1007                         odr_intdup(assoc->encode, *rr.srw_setnameIdleTime );
1008                 }
1009                 
1010                 if (start > rr.hits || start < 1)
1011                 {
1012                     /* if hits<=0 and start=1 we don't return a diagnostic */
1013                     if (start != 1)
1014                         yaz_add_srw_diagnostic(
1015                             assoc->encode, 
1016                             &srw_res->diagnostics, &srw_res->num_diagnostics,
1017                             YAZ_SRW_FIRST_RECORD_POSITION_OUT_OF_RANGE, 0);
1018                 }
1019                 else if (number > 0)
1020                 {
1021                     int i;
1022                     int ok = 1;
1023                     if (start + number > rr.hits)
1024                         number = rr.hits - start + 1;
1025                     
1026                     /* Call bend_present if defined */
1027                     if (assoc->init->bend_present)
1028                     {
1029                         bend_present_rr *bprr = (bend_present_rr*)
1030                             odr_malloc (assoc->decode, sizeof(*bprr));
1031                         bprr->setname = "default";
1032                         bprr->start = start;
1033                         bprr->number = number;
1034                         if (srw_req->recordSchema)
1035                         {
1036                             bprr->comp = (Z_RecordComposition *) odr_malloc(assoc->decode,
1037                                                                             sizeof(*bprr->comp));
1038                             bprr->comp->which = Z_RecordComp_simple;
1039                             bprr->comp->u.simple = (Z_ElementSetNames *)
1040                                 odr_malloc(assoc->decode, sizeof(Z_ElementSetNames));
1041                             bprr->comp->u.simple->which = Z_ElementSetNames_generic;
1042                             bprr->comp->u.simple->u.generic = srw_req->recordSchema;
1043                         }
1044                         else
1045                         {
1046                             bprr->comp = 0;
1047                         }
1048                         bprr->stream = assoc->encode;
1049                         bprr->referenceId = 0;
1050                         bprr->print = assoc->print;
1051                         bprr->request = req;
1052                         bprr->association = assoc;
1053                         bprr->errcode = 0;
1054                         bprr->errstring = NULL;
1055                         (*assoc->init->bend_present)(assoc->backend, bprr);
1056                         
1057                         if (!bprr->request)
1058                             return;
1059                         if (bprr->errcode)
1060                         {
1061                             srw_error = yaz_diag_bib1_to_srw (bprr->errcode);
1062                             yaz_add_srw_diagnostic(assoc->encode,
1063                                                    &srw_res->diagnostics,
1064                                                    &srw_res->num_diagnostics,
1065                                                    srw_error, bprr->errstring);
1066                             ok = 0;
1067                         }
1068                     }
1069                     
1070                     if (ok)
1071                     {
1072                         int j = 0;
1073                         int packing = Z_SRW_recordPacking_string;
1074                         if (srw_req->recordPacking)
1075                         {
1076                             packing = 
1077                                 yaz_srw_str_to_pack(srw_req->recordPacking);
1078                             if (packing == -1)
1079                                 packing = Z_SRW_recordPacking_string;
1080                         }
1081                         srw_res->records = (Z_SRW_record *)
1082                             odr_malloc(assoc->encode,
1083                                        number * sizeof(*srw_res->records));
1084                         
1085                         srw_res->extra_records = (Z_SRW_extra_record **)
1086                             odr_malloc(assoc->encode,
1087                                        number*sizeof(*srw_res->extra_records));
1088
1089                         for (i = 0; i<number; i++)
1090                         {
1091                             int errcode;
1092                             const char *addinfo = 0;
1093                             
1094                             srw_res->records[j].recordPacking = packing;
1095                             srw_res->records[j].recordData_buf = 0;
1096                             srw_res->extra_records[j] = 0;
1097                             yaz_log(YLOG_DEBUG, "srw_bend_fetch %d", i+start);
1098                             errcode = srw_bend_fetch(assoc, i+start, srw_req,
1099                                                      srw_res->records + j,
1100                                                      &addinfo);
1101                             if (errcode)
1102                             {
1103                                 yaz_add_srw_diagnostic(assoc->encode,
1104                                                        &srw_res->diagnostics,
1105                                                        &srw_res->num_diagnostics,
1106                                                        yaz_diag_bib1_to_srw (errcode),
1107                                                        addinfo);
1108                                 
1109                                 break;
1110                             }
1111                             if (srw_res->records[j].recordData_buf)
1112                                 j++;
1113                         }
1114                         srw_res->num_records = j;
1115                         if (!j)
1116                             srw_res->records = 0;
1117                     }
1118                 }
1119                 if (rr.estimated_hit_count || rr.partial_resultset)
1120                 {
1121                     yaz_add_srw_diagnostic(
1122                         assoc->encode,
1123                         &srw_res->diagnostics,
1124                         &srw_res->num_diagnostics,
1125                         YAZ_SRW_RESULT_SET_CREATED_WITH_VALID_PARTIAL_RESULTS_AVAILABLE,
1126                         0);
1127                 }
1128             }
1129         }
1130     }
1131     if (log_request)
1132     {
1133         const char *querystr = "?";
1134         const char *querytype = "?";
1135         WRBUF wr = wrbuf_alloc();
1136
1137         switch (srw_req->query_type)
1138         {
1139         case Z_SRW_query_type_cql:
1140             querytype = "CQL";
1141             querystr = srw_req->query.cql;
1142             break;
1143         case Z_SRW_query_type_pqf:
1144             querytype = "PQF";
1145             querystr = srw_req->query.pqf;
1146             break;
1147         }
1148         wrbuf_printf(wr, "SRWSearch ");
1149         wrbuf_printf(wr, srw_req->database);
1150         wrbuf_printf(wr, " ");
1151         if (srw_res->num_diagnostics)
1152             wrbuf_printf(wr, "ERROR %s", srw_res->diagnostics[0].uri);
1153         else if (*http_code != 200)
1154             wrbuf_printf(wr, "ERROR info:http/%d", *http_code);
1155         else if (srw_res->numberOfRecords)
1156         {
1157             wrbuf_printf(wr, "OK %d",
1158                          (srw_res->numberOfRecords ?
1159                           *srw_res->numberOfRecords : 0));
1160         }
1161         wrbuf_printf(wr, " %s %d+%d", 
1162                      (srw_res->resultSetId ?
1163                       srw_res->resultSetId : "-"),
1164                      (srw_req->startRecord ? *srw_req->startRecord : 1), 
1165                      srw_res->num_records);
1166         yaz_log(log_request, "%s %s: %s", wrbuf_cstr(wr), querytype, querystr);
1167         wrbuf_destroy(wr);
1168     }
1169 }
1170
1171 static char *srw_bend_explain_default(void *handle, bend_explain_rr *rr)
1172 {
1173 #if YAZ_HAVE_XML2
1174     xmlNodePtr ptr = (xmlNode *) rr->server_node_ptr;
1175     if (!ptr)
1176         return 0;
1177     for (ptr = ptr->children; ptr; ptr = ptr->next)
1178     {
1179         if (ptr->type != XML_ELEMENT_NODE)
1180             continue;
1181         if (!strcmp((const char *) ptr->name, "explain"))
1182         {
1183             int len;
1184             xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
1185             xmlChar *buf_out;
1186             char *content;
1187
1188             ptr = xmlCopyNode(ptr, 1);
1189         
1190             xmlDocSetRootElement(doc, ptr);
1191             
1192             xmlDocDumpMemory(doc, &buf_out, &len);
1193             content = (char*) odr_malloc(rr->stream, 1+len);
1194             memcpy(content, buf_out, len);
1195             content[len] = '\0';
1196             
1197             xmlFree(buf_out);
1198             xmlFreeDoc(doc);
1199             rr->explain_buf = content;
1200             return 0;
1201         }
1202     }
1203 #endif
1204     return 0;
1205 }
1206
1207 static void srw_bend_explain(association *assoc, request *req,
1208                              Z_SRW_PDU *sr,
1209                              Z_SRW_explainResponse *srw_res,
1210                              int *http_code)
1211 {
1212     Z_SRW_explainRequest *srw_req = sr->u.explain_request;
1213     yaz_log(log_requestdetail, "Got SRW ExplainRequest");
1214     *http_code = 404;
1215     srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1216     if (assoc->init)
1217     {
1218         bend_explain_rr rr;
1219         
1220         rr.stream = assoc->encode;
1221         rr.decode = assoc->decode;
1222         rr.print = assoc->print;
1223         rr.explain_buf = 0;
1224         rr.database = srw_req->database;
1225         if (assoc->server)
1226             rr.server_node_ptr = assoc->server->server_node_ptr;
1227         else
1228             rr.server_node_ptr = 0;
1229         rr.schema = "http://explain.z3950.org/dtd/2.0/";
1230         if (assoc->init->bend_explain)
1231             (*assoc->init->bend_explain)(assoc->backend, &rr);
1232         else
1233             srw_bend_explain_default(assoc->backend, &rr);
1234
1235         if (rr.explain_buf)
1236         {
1237             int packing = Z_SRW_recordPacking_string;
1238             if (srw_req->recordPacking)
1239             {
1240                 packing = 
1241                     yaz_srw_str_to_pack(srw_req->recordPacking);
1242                 if (packing == -1)
1243                     packing = Z_SRW_recordPacking_string;
1244             }
1245             srw_res->record.recordSchema = rr.schema;
1246             srw_res->record.recordPacking = packing;
1247             srw_res->record.recordData_buf = rr.explain_buf;
1248             srw_res->record.recordData_len = strlen(rr.explain_buf);
1249             srw_res->record.recordPosition = 0;
1250             *http_code = 200;
1251         }
1252     }
1253 }
1254
1255 static void srw_bend_scan(association *assoc, request *req,
1256                           Z_SRW_PDU *sr,
1257                           Z_SRW_scanResponse *srw_res,
1258                           int *http_code)
1259 {
1260     Z_SRW_scanRequest *srw_req = sr->u.scan_request;
1261     yaz_log(log_requestdetail, "Got SRW ScanRequest");
1262
1263     *http_code = 200;
1264     srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1265     if (srw_res->num_diagnostics == 0 && assoc->init)
1266     {
1267         struct scan_entry *save_entries;
1268
1269         bend_scan_rr *bsrr = (bend_scan_rr *)
1270             odr_malloc (assoc->encode, sizeof(*bsrr));
1271         bsrr->num_bases = 1;
1272         bsrr->basenames = &srw_req->database;
1273
1274         bsrr->num_entries = srw_req->maximumTerms ?
1275             *srw_req->maximumTerms : 10;
1276         bsrr->term_position = srw_req->responsePosition ?
1277             *srw_req->responsePosition : 1;
1278
1279         bsrr->errcode = 0;
1280         bsrr->errstring = 0;
1281         bsrr->referenceId = 0;
1282         bsrr->stream = assoc->encode;
1283         bsrr->print = assoc->print;
1284         bsrr->step_size = odr_intdup(assoc->decode, 0);
1285         bsrr->entries = 0;
1286         bsrr->setname = 0;
1287
1288         if (bsrr->num_entries > 0) 
1289         {
1290             int i;
1291             bsrr->entries = (struct scan_entry *) 
1292                 odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
1293                            bsrr->num_entries);
1294             for (i = 0; i<bsrr->num_entries; i++)
1295             {
1296                 bsrr->entries[i].term = 0;
1297                 bsrr->entries[i].occurrences = 0;
1298                 bsrr->entries[i].errcode = 0;
1299                 bsrr->entries[i].errstring = 0;
1300                 bsrr->entries[i].display_term = 0;
1301             }
1302         }
1303         save_entries = bsrr->entries;  /* save it so we can compare later */
1304
1305         if (srw_req->query_type == Z_SRW_query_type_pqf &&
1306             assoc->init->bend_scan)
1307         {
1308             YAZ_PQF_Parser pqf_parser = yaz_pqf_create();
1309             
1310             bsrr->term = yaz_pqf_scan(pqf_parser, assoc->decode,
1311                                       &bsrr->attributeset, 
1312                                       srw_req->scanClause.pqf); 
1313             yaz_pqf_destroy(pqf_parser);
1314             bsrr->scanClause = 0;
1315             ((int (*)(void *, bend_scan_rr *))
1316              (*assoc->init->bend_scan))(assoc->backend, bsrr);
1317         }
1318         else if (srw_req->query_type == Z_SRW_query_type_cql
1319                  && assoc->init->bend_scan && assoc->server
1320                  && assoc->server->cql_transform)
1321         {
1322             int srw_error;
1323             bsrr->scanClause = 0;
1324             bsrr->attributeset = 0;
1325             bsrr->term = (Z_AttributesPlusTerm *)
1326                 odr_malloc(assoc->decode, sizeof(*bsrr->term));
1327             srw_error = cql2pqf_scan(assoc->encode,
1328                                      srw_req->scanClause.cql,
1329                                      assoc->server->cql_transform,
1330                                      bsrr->term);
1331             if (srw_error)
1332                 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1333                                        &srw_res->num_diagnostics,
1334                                        srw_error, 0);
1335             else
1336             {
1337                 ((int (*)(void *, bend_scan_rr *))
1338                  (*assoc->init->bend_scan))(assoc->backend, bsrr);
1339             }
1340         }
1341         else if (srw_req->query_type == Z_SRW_query_type_cql
1342                  && assoc->init->bend_srw_scan)
1343         {
1344             bsrr->term = 0;
1345             bsrr->attributeset = 0;
1346             bsrr->scanClause = srw_req->scanClause.cql;
1347             ((int (*)(void *, bend_scan_rr *))
1348              (*assoc->init->bend_srw_scan))(assoc->backend, bsrr);
1349         }
1350         else
1351         {
1352             yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1353                                    &srw_res->num_diagnostics,
1354                                    YAZ_SRW_UNSUPP_OPERATION, "scan");
1355         }
1356         if (bsrr->errcode)
1357         {
1358             int srw_error;
1359             if (bsrr->errcode == YAZ_BIB1_DATABASE_UNAVAILABLE)
1360             {
1361                 *http_code = 404;
1362                 return;
1363             }
1364             srw_error = yaz_diag_bib1_to_srw (bsrr->errcode);
1365
1366             yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1367                                    &srw_res->num_diagnostics,
1368                                    srw_error, bsrr->errstring);
1369         }
1370         else if (srw_res->num_diagnostics == 0 && bsrr->num_entries)
1371         {
1372             int i;
1373             srw_res->terms = (Z_SRW_scanTerm*)
1374                 odr_malloc(assoc->encode, sizeof(*srw_res->terms) *
1375                            bsrr->num_entries);
1376
1377             srw_res->num_terms =  bsrr->num_entries;
1378             for (i = 0; i<bsrr->num_entries; i++)
1379             {
1380                 Z_SRW_scanTerm *t = srw_res->terms + i;
1381                 t->value = odr_strdup(assoc->encode, bsrr->entries[i].term);
1382                 t->numberOfRecords =
1383                     odr_intdup(assoc->encode, bsrr->entries[i].occurrences);
1384                 t->displayTerm = 0;
1385                 if (save_entries == bsrr->entries && 
1386                     bsrr->entries[i].display_term)
1387                 {
1388                     /* the entries was _not_ set by the handler. So it's
1389                        safe to test for new member display_term. It is
1390                        NULL'ed by us.
1391                     */
1392                     t->displayTerm = odr_strdup(assoc->encode, 
1393                                                 bsrr->entries[i].display_term);
1394                 }
1395                 t->whereInList = 0;
1396             }
1397         }
1398     }
1399     if (log_request)
1400     {
1401         WRBUF wr = wrbuf_alloc();
1402         const char *querytype = 0;
1403         const char *querystr = 0;
1404
1405         switch(srw_req->query_type)
1406         {
1407         case Z_SRW_query_type_pqf:
1408             querytype = "PQF";
1409             querystr = srw_req->scanClause.pqf;
1410             break;
1411         case Z_SRW_query_type_cql:
1412             querytype = "CQL";
1413             querystr = srw_req->scanClause.cql;
1414             break;
1415         default:
1416             querytype = "UNKNOWN";
1417             querystr = "";
1418         }
1419
1420         wrbuf_printf(wr, "SRWScan ");
1421         wrbuf_printf(wr, srw_req->database);
1422         wrbuf_printf(wr, " ");
1423
1424         if (srw_res->num_diagnostics)
1425             wrbuf_printf(wr, "ERROR %s - ", srw_res->diagnostics[0].uri);
1426         else if (srw_res->num_terms)
1427             wrbuf_printf(wr, "OK %d - ", srw_res->num_terms);
1428         else
1429             wrbuf_printf(wr, "OK - - ");
1430
1431         wrbuf_printf(wr, "%d+%d+0 ",
1432                      (srw_req->responsePosition ? 
1433                       *srw_req->responsePosition : 1),
1434                      (srw_req->maximumTerms ?
1435                       *srw_req->maximumTerms : 1));
1436         /* there is no step size in SRU/W ??? */
1437         wrbuf_printf(wr, "%s: %s ", querytype, querystr);
1438         yaz_log(log_request, "%s ", wrbuf_cstr(wr) );
1439         wrbuf_destroy(wr);
1440     }
1441
1442 }
1443
1444 static void srw_bend_update(association *assoc, request *req,
1445                             Z_SRW_PDU *sr,
1446                             Z_SRW_updateResponse *srw_res,
1447                             int *http_code)
1448 {
1449     Z_SRW_updateRequest *srw_req = sr->u.update_request;
1450     yaz_log(log_session, "SRWUpdate action=%s", srw_req->operation);
1451     yaz_log(YLOG_DEBUG, "num_diag = %d", srw_res->num_diagnostics );
1452     *http_code = 404;
1453     srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics, sr);
1454     if (assoc->init)
1455     {
1456         bend_update_rr rr;
1457         Z_SRW_extra_record *extra = srw_req->extra_record;
1458         
1459         rr.stream = assoc->encode;
1460         rr.print = assoc->print;
1461         rr.num_bases = 1;
1462         rr.basenames = &srw_req->database;
1463         rr.operation = srw_req->operation;
1464         rr.operation_status = "failed";
1465         rr.record_id = 0;
1466         rr.record_versions = 0;
1467         rr.num_versions = 0;
1468         rr.record_packing = "string";
1469         rr.record_schema = 0;
1470         rr.record_data = 0;
1471         rr.extra_record_data = 0;
1472         rr.extra_request_data = 0;
1473         rr.extra_response_data = 0;
1474         rr.uri = 0;
1475         rr.message = 0;
1476         rr.details = 0;
1477         
1478         *http_code = 200;
1479         if (rr.operation == 0)
1480         {
1481             yaz_add_sru_update_diagnostic(
1482                 assoc->encode, &srw_res->diagnostics,
1483                 &srw_res->num_diagnostics,
1484                 YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,
1485                 "action" );
1486             return;
1487         }
1488         yaz_log(YLOG_DEBUG, "basename = %s", rr.basenames[0] );
1489         yaz_log(YLOG_DEBUG, "Operation = %s", rr.operation );
1490         if (!strcmp( rr.operation, "delete"))
1491         {
1492             if (srw_req->record && !srw_req->record->recordSchema)
1493             {
1494                 rr.record_schema = odr_strdup(
1495                     assoc->encode,
1496                     srw_req->record->recordSchema);
1497             }
1498             if (srw_req->record)
1499             {
1500                 rr.record_data = odr_strdupn(
1501                     assoc->encode, 
1502                     srw_req->record->recordData_buf,
1503                     srw_req->record->recordData_len );
1504             }
1505             if (extra && extra->extraRecordData_len)
1506             {
1507                 rr.extra_record_data = odr_strdupn(
1508                     assoc->encode, 
1509                     extra->extraRecordData_buf,
1510                     extra->extraRecordData_len );
1511             }
1512             if (srw_req->recordId)
1513                 rr.record_id = srw_req->recordId;
1514             else if (extra && extra->recordIdentifier)
1515                 rr.record_id = extra->recordIdentifier;
1516         }
1517         else if (!strcmp(rr.operation, "replace"))
1518         {
1519             if (srw_req->recordId)
1520                 rr.record_id = srw_req->recordId;
1521             else if (extra && extra->recordIdentifier)
1522                 rr.record_id = extra->recordIdentifier;
1523             else 
1524             {
1525                 yaz_add_sru_update_diagnostic(
1526                     assoc->encode, &srw_res->diagnostics,
1527                     &srw_res->num_diagnostics,
1528                     YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,
1529                     "recordIdentifier");
1530             }
1531             if (!srw_req->record)
1532             {
1533                 yaz_add_sru_update_diagnostic(
1534                     assoc->encode, &srw_res->diagnostics,
1535                     &srw_res->num_diagnostics,
1536                     YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,
1537                     "record");
1538             }
1539             else 
1540             {
1541                 if (srw_req->record->recordSchema)
1542                     rr.record_schema = odr_strdup(
1543                         assoc->encode, srw_req->record->recordSchema);
1544                 if (srw_req->record->recordData_len )
1545                 {
1546                     rr.record_data = odr_strdupn(assoc->encode, 
1547                                                  srw_req->record->recordData_buf,
1548                                                  srw_req->record->recordData_len );
1549                 }
1550                 else 
1551                 {
1552                     yaz_add_sru_update_diagnostic(
1553                         assoc->encode, &srw_res->diagnostics,
1554                         &srw_res->num_diagnostics,
1555                         YAZ_SRU_UPDATE_MISSING_MANDATORY_ELEMENT_RECORD_REJECTED,                                              
1556                         "recordData" );
1557                 }
1558             }
1559             if (extra && extra->extraRecordData_len)
1560             {
1561                 rr.extra_record_data = odr_strdupn(
1562                     assoc->encode, 
1563                     extra->extraRecordData_buf,
1564                     extra->extraRecordData_len );
1565             }
1566         }
1567         else if (!strcmp(rr.operation, "insert"))
1568         {
1569             if (srw_req->recordId)
1570                 rr.record_id = srw_req->recordId; 
1571             else if (extra)
1572                 rr.record_id = extra->recordIdentifier;
1573             
1574             if (srw_req->record)
1575             {
1576                 if (srw_req->record->recordSchema)
1577                     rr.record_schema = odr_strdup(
1578                         assoc->encode, srw_req->record->recordSchema);
1579             
1580                 if (srw_req->record->recordData_len)
1581                     rr.record_data = odr_strdupn(
1582                         assoc->encode, 
1583                         srw_req->record->recordData_buf,
1584                         srw_req->record->recordData_len );
1585             }
1586             if (extra && extra->extraRecordData_len)
1587             {
1588                 rr.extra_record_data = odr_strdupn(
1589                     assoc->encode, 
1590                     extra->extraRecordData_buf,
1591                     extra->extraRecordData_len );
1592             }
1593         }
1594         else 
1595             yaz_add_sru_update_diagnostic(assoc->encode, &srw_res->diagnostics,
1596                                           &srw_res->num_diagnostics,
1597                                           YAZ_SRU_UPDATE_INVALID_ACTION,
1598                                           rr.operation );
1599
1600         if (srw_req->record)
1601         {
1602             const char *pack_str = 
1603                 yaz_srw_pack_to_str(srw_req->record->recordPacking);
1604             if (pack_str)
1605                 rr.record_packing = odr_strdup(assoc->encode, pack_str);
1606         }
1607
1608         if (srw_req->num_recordVersions)
1609         {
1610             rr.record_versions = srw_req->recordVersions;
1611             rr.num_versions = srw_req->num_recordVersions;
1612         }
1613         if (srw_req->extraRequestData_len)
1614         {
1615             rr.extra_request_data = odr_strdupn(assoc->encode,
1616                                                 srw_req->extraRequestData_buf,
1617                                                 srw_req->extraRequestData_len );
1618         }
1619         if (srw_res->num_diagnostics == 0)
1620         {
1621             if ( assoc->init->bend_srw_update)
1622                 (*assoc->init->bend_srw_update)(assoc->backend, &rr);
1623             else 
1624                 yaz_add_sru_update_diagnostic(
1625                     assoc->encode, &srw_res->diagnostics,
1626                     &srw_res->num_diagnostics,
1627                     YAZ_SRU_UPDATE_UNSPECIFIED_DATABASE_ERROR,
1628                     "No Update backend handler");
1629         }
1630
1631         if (rr.uri)
1632             yaz_add_srw_diagnostic_uri(assoc->encode,
1633                                        &srw_res->diagnostics,
1634                                        &srw_res->num_diagnostics,
1635                                        rr.uri, 
1636                                        rr.message,
1637                                        rr.details);
1638         srw_res->recordId = rr.record_id;
1639         srw_res->operationStatus = rr.operation_status;
1640         srw_res->recordVersions = rr.record_versions;
1641         srw_res->num_recordVersions = rr.num_versions;
1642         if (srw_res->extraResponseData_len)
1643         {
1644             srw_res->extraResponseData_buf = rr.extra_response_data;
1645             srw_res->extraResponseData_len = strlen(rr.extra_response_data);
1646         }
1647         if (srw_res->num_diagnostics == 0 && rr.record_data)
1648         {
1649             srw_res->record = yaz_srw_get_record(assoc->encode);
1650             srw_res->record->recordSchema = rr.record_schema;
1651             if (rr.record_packing)
1652             {
1653                 int pack = yaz_srw_str_to_pack(rr.record_packing);
1654
1655                 if (pack == -1)
1656                 {
1657                     pack = Z_SRW_recordPacking_string;
1658                     yaz_log(YLOG_WARN, "Back packing %s from backend",
1659                             rr.record_packing);
1660                 }
1661                 srw_res->record->recordPacking = pack;
1662             }
1663             srw_res->record->recordData_buf = rr.record_data;
1664             srw_res->record->recordData_len = strlen(rr.record_data);
1665             if (rr.extra_record_data)
1666             {
1667                 Z_SRW_extra_record *ex = 
1668                     yaz_srw_get_extra_record(assoc->encode);
1669                 srw_res->extra_record = ex;
1670                 ex->extraRecordData_buf = rr.extra_record_data;
1671                 ex->extraRecordData_len = strlen(rr.extra_record_data);
1672             }
1673         }
1674     }
1675 }
1676
1677 /* check if path is OK (1); BAD (0) */
1678 static int check_path(const char *path)
1679 {
1680     if (*path != '/')
1681         return 0;
1682     if (strstr(path, ".."))
1683         return 0;
1684     return 1;
1685 }
1686
1687 static char *read_file(const char *fname, ODR o, int *sz)
1688 {
1689     char *buf;
1690     FILE *inf = fopen(fname, "rb");
1691     if (!inf)
1692         return 0;
1693
1694     fseek(inf, 0L, SEEK_END);
1695     *sz = ftell(inf);
1696     rewind(inf);
1697     buf = (char *) odr_malloc(o, *sz);
1698     fread(buf, 1, *sz, inf);
1699     fclose(inf);
1700     return buf;     
1701 }
1702
1703 static void process_http_request(association *assoc, request *req)
1704 {
1705     Z_HTTP_Request *hreq = req->gdu_request->u.HTTP_Request;
1706     ODR o = assoc->encode;
1707     int r = 2;  /* 2=NOT TAKEN, 1=TAKEN, 0=SOAP TAKEN */
1708     Z_SRW_PDU *sr = 0;
1709     Z_SOAP *soap_package = 0;
1710     Z_GDU *p = 0;
1711     char *charset = 0;
1712     Z_HTTP_Response *hres = 0;
1713     int keepalive = 1;
1714     const char *stylesheet = 0; /* for now .. set later */
1715     Z_SRW_diagnostic *diagnostic = 0;
1716     int num_diagnostic = 0;
1717     const char *host = z_HTTP_header_lookup(hreq->headers, "Host");
1718
1719     if (!control_association(assoc, host, 0))
1720     {
1721         p = z_get_HTTP_Response(o, 404);
1722         r = 1;
1723     }
1724     if (r == 2 && assoc->server && assoc->server->docpath
1725         && hreq->path[0] == '/' 
1726         && 
1727         /* check if path is a proper prefix of documentroot */
1728         strncmp(hreq->path+1, assoc->server->docpath,
1729                 strlen(assoc->server->docpath))
1730         == 0)
1731     {   
1732         if (!check_path(hreq->path))
1733         {
1734             yaz_log(YLOG_LOG, "File %s access forbidden", hreq->path+1);
1735             p = z_get_HTTP_Response(o, 404);
1736         }
1737         else
1738         {
1739             int content_size = 0;
1740             char *content_buf = read_file(hreq->path+1, o, &content_size);
1741             if (!content_buf)
1742             {
1743                 yaz_log(YLOG_LOG, "File %s not found", hreq->path+1);
1744                 p = z_get_HTTP_Response(o, 404);
1745             }
1746             else
1747             {
1748                 const char *ctype = 0;
1749                 yaz_mime_types types = yaz_mime_types_create();
1750                 
1751                 yaz_mime_types_add(types, "xsl", "application/xml");
1752                 yaz_mime_types_add(types, "xml", "application/xml");
1753                 yaz_mime_types_add(types, "css", "text/css");
1754                 yaz_mime_types_add(types, "html", "text/html");
1755                 yaz_mime_types_add(types, "htm", "text/html");
1756                 yaz_mime_types_add(types, "txt", "text/plain");
1757                 yaz_mime_types_add(types, "js", "application/x-javascript");
1758                 
1759                 yaz_mime_types_add(types, "gif", "image/gif");
1760                 yaz_mime_types_add(types, "png", "image/png");
1761                 yaz_mime_types_add(types, "jpg", "image/jpeg");
1762                 yaz_mime_types_add(types, "jpeg", "image/jpeg");
1763                 
1764                 ctype = yaz_mime_lookup_fname(types, hreq->path);
1765                 if (!ctype)
1766                 {
1767                     yaz_log(YLOG_LOG, "No mime type for %s", hreq->path+1);
1768                     p = z_get_HTTP_Response(o, 404);
1769                 }
1770                 else
1771                 {
1772                     p = z_get_HTTP_Response(o, 200);
1773                     hres = p->u.HTTP_Response;
1774                     hres->content_buf = content_buf;
1775                     hres->content_len = content_size;
1776                     z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1777                 }
1778                 yaz_mime_types_destroy(types);
1779             }
1780         }
1781         r = 1;
1782     }
1783
1784     if (r == 2)
1785     {
1786         r = yaz_srw_decode(hreq, &sr, &soap_package, assoc->decode, &charset);
1787         yaz_log(YLOG_DEBUG, "yaz_srw_decode returned %d", r);
1788     }
1789     if (r == 2)  /* not taken */
1790     {
1791         r = yaz_sru_decode(hreq, &sr, &soap_package, assoc->decode, &charset,
1792                            &diagnostic, &num_diagnostic);
1793         yaz_log(YLOG_DEBUG, "yaz_sru_decode returned %d", r);
1794     }
1795     if (r == 0)  /* decode SRW/SRU OK .. */
1796     {
1797         int http_code = 200;
1798         if (sr->which == Z_SRW_searchRetrieve_request)
1799         {
1800             Z_SRW_PDU *res =
1801                 yaz_srw_get_pdu(assoc->encode, Z_SRW_searchRetrieve_response,
1802                                 sr->srw_version);
1803             stylesheet = sr->u.request->stylesheet;
1804             if (num_diagnostic)
1805             {
1806                 res->u.response->diagnostics = diagnostic;
1807                 res->u.response->num_diagnostics = num_diagnostic;
1808             }
1809             else
1810             {
1811                 srw_bend_search(assoc, req, sr, res->u.response, 
1812                                 &http_code);
1813             }
1814             if (http_code == 200)
1815                 soap_package->u.generic->p = res;
1816         }
1817         else if (sr->which == Z_SRW_explain_request)
1818         {
1819             Z_SRW_PDU *res = yaz_srw_get_pdu(o, Z_SRW_explain_response,
1820                                              sr->srw_version);
1821             stylesheet = sr->u.explain_request->stylesheet;
1822             if (num_diagnostic)
1823             {   
1824                 res->u.explain_response->diagnostics = diagnostic;
1825                 res->u.explain_response->num_diagnostics = num_diagnostic;
1826             }
1827             srw_bend_explain(assoc, req, sr,
1828                              res->u.explain_response, &http_code);
1829             if (http_code == 200)
1830                 soap_package->u.generic->p = res;
1831         }
1832         else if (sr->which == Z_SRW_scan_request)
1833         {
1834             Z_SRW_PDU *res = yaz_srw_get_pdu(o, Z_SRW_scan_response,
1835                                              sr->srw_version);
1836             stylesheet = sr->u.scan_request->stylesheet;
1837             if (num_diagnostic)
1838             {   
1839                 res->u.scan_response->diagnostics = diagnostic;
1840                 res->u.scan_response->num_diagnostics = num_diagnostic;
1841             }
1842             srw_bend_scan(assoc, req, sr,
1843                           res->u.scan_response, &http_code);
1844             if (http_code == 200)
1845                 soap_package->u.generic->p = res;
1846         }
1847         else if (sr->which == Z_SRW_update_request)
1848         {
1849             Z_SRW_PDU *res = yaz_srw_get_pdu(o, Z_SRW_update_response,
1850                                              sr->srw_version);
1851             yaz_log(YLOG_DEBUG, "handling SRW UpdateRequest");
1852             if (num_diagnostic)
1853             {   
1854                 res->u.update_response->diagnostics = diagnostic;
1855                 res->u.update_response->num_diagnostics = num_diagnostic;
1856             }
1857             yaz_log(YLOG_DEBUG, "num_diag = %d", res->u.update_response->num_diagnostics );
1858             srw_bend_update(assoc, req, sr,
1859                             res->u.update_response, &http_code);
1860             if (http_code == 200)
1861                 soap_package->u.generic->p = res;
1862         }
1863         else
1864         {
1865             yaz_log(log_request, "SOAP ERROR"); 
1866             /* FIXME - what error, what query */
1867             http_code = 500;
1868             z_soap_error(assoc->encode, soap_package,
1869                          "SOAP-ENV:Client", "Bad method", 0); 
1870         }
1871         if (http_code == 200 || http_code == 500)
1872         {
1873             static Z_SOAP_Handler soap_handlers[4] = {
1874 #if YAZ_HAVE_XML2
1875                 {YAZ_XMLNS_SRU_v1_1, 0, (Z_SOAP_fun) yaz_srw_codec},
1876                 {YAZ_XMLNS_SRU_v1_0, 0, (Z_SOAP_fun) yaz_srw_codec},
1877                 {YAZ_XMLNS_UPDATE_v0_9, 0, (Z_SOAP_fun) yaz_ucp_codec},
1878 #endif
1879                 {0, 0, 0}
1880             };
1881             char ctype[80];
1882             int ret;
1883             p = z_get_HTTP_Response(o, 200);
1884             hres = p->u.HTTP_Response;
1885
1886             if (!stylesheet && assoc->server)
1887                 stylesheet = assoc->server->stylesheet;
1888
1889             /* empty stylesheet means NO stylesheet */
1890             if (stylesheet && *stylesheet == '\0')
1891                 stylesheet = 0;
1892
1893             ret = z_soap_codec_enc_xsl(assoc->encode, &soap_package,
1894                                        &hres->content_buf, &hres->content_len,
1895                                        soap_handlers, charset, stylesheet);
1896             hres->code = http_code;
1897
1898             strcpy(ctype, "text/xml");
1899             if (charset && strlen(charset) < sizeof(ctype)-30)
1900             {
1901                 strcat(ctype, "; charset=");
1902                 strcat(ctype, charset);
1903             }
1904             z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1905         }
1906         else
1907             p = z_get_HTTP_Response(o, http_code);
1908     }
1909
1910     if (p == 0)
1911         p = z_get_HTTP_Response(o, 500);
1912     hres = p->u.HTTP_Response;
1913     if (!strcmp(hreq->version, "1.0")) 
1914     {
1915         const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1916         if (v && !strcmp(v, "Keep-Alive"))
1917             keepalive = 1;
1918         else
1919             keepalive = 0;
1920         hres->version = "1.0";
1921     }
1922     else
1923     {
1924         const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1925         if (v && !strcmp(v, "close"))
1926             keepalive = 0;
1927         else
1928             keepalive = 1;
1929         hres->version = "1.1";
1930     }
1931     if (!keepalive)
1932     {
1933         z_HTTP_header_add(o, &hres->headers, "Connection", "close");
1934         assoc->state = ASSOC_DEAD;
1935         assoc->cs_get_mask = 0;
1936     }
1937     else
1938     {
1939         int t;
1940         const char *alive = z_HTTP_header_lookup(hreq->headers, "Keep-Alive");
1941
1942         if (alive && isdigit(*(const unsigned char *) alive))
1943             t = atoi(alive);
1944         else
1945             t = 15;
1946         if (t < 0 || t > 3600)
1947             t = 3600;
1948         iochan_settimeout(assoc->client_chan,t);
1949         z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1950     }
1951     process_gdu_response(assoc, req, p);
1952 }
1953
1954 static void process_gdu_request(association *assoc, request *req)
1955 {
1956     if (req->gdu_request->which == Z_GDU_Z3950)
1957     {
1958         char *msg = 0;
1959         req->apdu_request = req->gdu_request->u.z3950;
1960         if (process_z_request(assoc, req, &msg) < 0)
1961             do_close_req(assoc, Z_Close_systemProblem, msg, req);
1962     }
1963     else if (req->gdu_request->which == Z_GDU_HTTP_Request)
1964         process_http_request(assoc, req);
1965     else
1966     {
1967         do_close_req(assoc, Z_Close_systemProblem, "bad protocol packet", req);
1968     }
1969 }
1970
1971 /*
1972  * Initiate request processing.
1973  */
1974 static int process_z_request(association *assoc, request *req, char **msg)
1975 {
1976     int fd = -1;
1977     Z_APDU *res;
1978     int retval;
1979     
1980     *msg = "Unknown Error";
1981     assert(req && req->state == REQUEST_IDLE);
1982     if (req->apdu_request->which != Z_APDU_initRequest && !assoc->init)
1983     {
1984         *msg = "Missing InitRequest";
1985         return -1;
1986     }
1987     switch (req->apdu_request->which)
1988     {
1989     case Z_APDU_initRequest:
1990         res = process_initRequest(assoc, req); break;
1991     case Z_APDU_searchRequest:
1992         res = process_searchRequest(assoc, req, &fd); break;
1993     case Z_APDU_presentRequest:
1994         res = process_presentRequest(assoc, req, &fd); break;
1995     case Z_APDU_scanRequest:
1996         if (assoc->init->bend_scan)
1997             res = process_scanRequest(assoc, req, &fd);
1998         else
1999         {
2000             *msg = "Cannot handle Scan APDU";
2001             return -1;
2002         }
2003         break;
2004     case Z_APDU_extendedServicesRequest:
2005         if (assoc->init->bend_esrequest)
2006             res = process_ESRequest(assoc, req, &fd);
2007         else
2008         {
2009             *msg = "Cannot handle Extended Services APDU";
2010             return -1;
2011         }
2012         break;
2013     case Z_APDU_sortRequest:
2014         if (assoc->init->bend_sort)
2015             res = process_sortRequest(assoc, req, &fd);
2016         else
2017         {
2018             *msg = "Cannot handle Sort APDU";
2019             return -1;
2020         }
2021         break;
2022     case Z_APDU_close:
2023         process_close(assoc, req);
2024         return 0;
2025     case Z_APDU_deleteResultSetRequest:
2026         if (assoc->init->bend_delete)
2027             res = process_deleteRequest(assoc, req, &fd);
2028         else
2029         {
2030             *msg = "Cannot handle Delete APDU";
2031             return -1;
2032         }
2033         break;
2034     case Z_APDU_segmentRequest:
2035         if (assoc->init->bend_segment)
2036         {
2037             res = process_segmentRequest (assoc, req);
2038         }
2039         else
2040         {
2041             *msg = "Cannot handle Segment APDU";
2042             return -1;
2043         }
2044         break;
2045     case Z_APDU_triggerResourceControlRequest:
2046         return 0;
2047     default:
2048         *msg = "Bad APDU received";
2049         return -1;
2050     }
2051     if (res)
2052     {
2053         yaz_log(YLOG_DEBUG, "  result immediately available");
2054         retval = process_z_response(assoc, req, res);
2055     }
2056     else if (fd < 0)
2057     {
2058         yaz_log(YLOG_DEBUG, "  result unavailble");
2059         retval = 0;
2060     }
2061     else /* no result yet - one will be provided later */
2062     {
2063         IOCHAN chan;
2064
2065         /* Set up an I/O handler for the fd supplied by the backend */
2066
2067         yaz_log(YLOG_DEBUG, "   establishing handler for result");
2068         req->state = REQUEST_PENDING;
2069         if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT, 0)))
2070             abort();
2071         iochan_setdata(chan, assoc);
2072         retval = 0;
2073     }
2074     return retval;
2075 }
2076
2077 /*
2078  * Handle message from the backend.
2079  */
2080 void backend_response(IOCHAN i, int event)
2081 {
2082     association *assoc = (association *)iochan_getdata(i);
2083     request *req = request_head(&assoc->incoming);
2084     Z_APDU *res;
2085     int fd;
2086
2087     yaz_log(YLOG_DEBUG, "backend_response");
2088     assert(assoc && req && req->state != REQUEST_IDLE);
2089     /* determine what it is we're waiting for */
2090     switch (req->apdu_request->which)
2091     {
2092         case Z_APDU_searchRequest:
2093             res = response_searchRequest(assoc, req, 0, &fd); break;
2094 #if 0
2095         case Z_APDU_presentRequest:
2096             res = response_presentRequest(assoc, req, 0, &fd); break;
2097         case Z_APDU_scanRequest:
2098             res = response_scanRequest(assoc, req, 0, &fd); break;
2099 #endif
2100         default:
2101             yaz_log(YLOG_FATAL, "Serious programmer's lapse or bug");
2102             abort();
2103     }
2104     if ((res && process_z_response(assoc, req, res) < 0) || fd < 0)
2105     {
2106         yaz_log(YLOG_WARN, "Fatal error when talking to backend");
2107         do_close(assoc, Z_Close_systemProblem, 0);
2108         iochan_destroy(i);
2109         return;
2110     }
2111     else if (!res) /* no result yet - try again later */
2112     {
2113         yaz_log(YLOG_DEBUG, "   no result yet");
2114         iochan_setfd(i, fd); /* in case fd has changed */
2115     }
2116 }
2117
2118 /*
2119  * Encode response, and transfer the request structure to the outgoing queue.
2120  */
2121 static int process_gdu_response(association *assoc, request *req, Z_GDU *res)
2122 {
2123     odr_setbuf(assoc->encode, req->response, req->size_response, 1);
2124
2125     if (assoc->print)
2126     {
2127         if (!z_GDU(assoc->print, &res, 0, 0))
2128             yaz_log(YLOG_WARN, "ODR print error: %s", 
2129                 odr_errmsg(odr_geterror(assoc->print)));
2130         odr_reset(assoc->print);
2131     }
2132     if (!z_GDU(assoc->encode, &res, 0, 0))
2133     {
2134         yaz_log(YLOG_WARN, "ODR error when encoding PDU: %s [element %s]",
2135                 odr_errmsg(odr_geterror(assoc->decode)),
2136                 odr_getelement(assoc->decode));
2137         return -1;
2138     }
2139     req->response = odr_getbuf(assoc->encode, &req->len_response,
2140         &req->size_response);
2141     odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
2142     odr_reset(assoc->encode);
2143     req->state = REQUEST_IDLE;
2144     request_enq(&assoc->outgoing, req);
2145     /* turn the work over to the ir_session handler */
2146     iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
2147     assoc->cs_put_mask = EVENT_OUTPUT;
2148     /* Is there more work to be done? give that to the input handler too */
2149     for (;;)
2150     {
2151         req = request_head(&assoc->incoming);
2152         if (req && req->state == REQUEST_IDLE)
2153         {
2154             request_deq(&assoc->incoming);
2155             process_gdu_request(assoc, req);
2156         }
2157         else
2158             break;
2159     }
2160     return 0;
2161 }
2162
2163 /*
2164  * Encode response, and transfer the request structure to the outgoing queue.
2165  */
2166 static int process_z_response(association *assoc, request *req, Z_APDU *res)
2167 {
2168     Z_GDU *gres = (Z_GDU *) odr_malloc(assoc->encode, sizeof(*res));
2169     gres->which = Z_GDU_Z3950;
2170     gres->u.z3950 = res;
2171
2172     return process_gdu_response(assoc, req, gres);
2173 }
2174
2175 static char *get_vhost(Z_OtherInformation *otherInfo)
2176 {
2177     return yaz_oi_get_string_oid(&otherInfo, yaz_oid_userinfo_proxy, 1, 0);
2178 }
2179
2180 /*
2181  * Handle init request.
2182  * At the moment, we don't check the options
2183  * anywhere else in the code - we just try not to do anything that would
2184  * break a naive client. We'll toss 'em into the association block when
2185  * we need them there.
2186  */
2187 static Z_APDU *process_initRequest(association *assoc, request *reqb)
2188 {
2189     Z_InitRequest *req = reqb->apdu_request->u.initRequest;
2190     Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
2191     Z_InitResponse *resp = apdu->u.initResponse;
2192     bend_initresult *binitres;
2193     char *version;
2194     char options[140];
2195     statserv_options_block *cb = 0;  /* by default no control for backend */
2196
2197     if (control_association(assoc, get_vhost(req->otherInfo), 1))
2198         cb = statserv_getcontrol();  /* got control block for backend */
2199
2200     if (cb && assoc->backend)
2201         (*cb->bend_close)(assoc->backend);
2202
2203     yaz_log(log_requestdetail, "Got initRequest");
2204     if (req->implementationId)
2205         yaz_log(log_requestdetail, "Id:        %s",
2206                 req->implementationId);
2207     if (req->implementationName)
2208         yaz_log(log_requestdetail, "Name:      %s",
2209                 req->implementationName);
2210     if (req->implementationVersion)
2211         yaz_log(log_requestdetail, "Version:   %s",
2212                 req->implementationVersion);
2213     
2214     assoc_init_reset(assoc);
2215
2216     assoc->init->auth = req->idAuthentication;
2217     assoc->init->referenceId = req->referenceId;
2218
2219     if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
2220     {
2221         Z_CharSetandLanguageNegotiation *negotiation =
2222             yaz_get_charneg_record (req->otherInfo);
2223         if (negotiation &&
2224             negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
2225             assoc->init->charneg_request = negotiation;
2226     }
2227
2228     assoc->backend = 0;
2229     if (cb)
2230     {
2231         if (req->implementationVersion)
2232             yaz_log(log_requestdetail, "Config:    %s",
2233                     cb->configname);
2234     
2235         iochan_settimeout(assoc->client_chan, cb->idle_timeout * 60);
2236         
2237         /* we have a backend control block, so call that init function */
2238         if (!(binitres = (*cb->bend_init)(assoc->init)))
2239         {
2240             yaz_log(YLOG_WARN, "Bad response from backend.");
2241             return 0;
2242         }
2243         assoc->backend = binitres->handle;
2244     }
2245     else
2246     {
2247         /* no backend. return error */
2248         binitres = (bend_initresult *)
2249             odr_malloc(assoc->encode, sizeof(*binitres));
2250         binitres->errstring = 0;
2251         binitres->errcode = YAZ_BIB1_PERMANENT_SYSTEM_ERROR;
2252         iochan_settimeout(assoc->client_chan, 10);
2253     }
2254     if ((assoc->init->bend_sort))
2255         yaz_log (YLOG_DEBUG, "Sort handler installed");
2256     if ((assoc->init->bend_search))
2257         yaz_log (YLOG_DEBUG, "Search handler installed");
2258     if ((assoc->init->bend_present))
2259         yaz_log (YLOG_DEBUG, "Present handler installed");   
2260     if ((assoc->init->bend_esrequest))
2261         yaz_log (YLOG_DEBUG, "ESRequest handler installed");   
2262     if ((assoc->init->bend_delete))
2263         yaz_log (YLOG_DEBUG, "Delete handler installed");   
2264     if ((assoc->init->bend_scan))
2265         yaz_log (YLOG_DEBUG, "Scan handler installed");   
2266     if ((assoc->init->bend_segment))
2267         yaz_log (YLOG_DEBUG, "Segment handler installed");   
2268     
2269     resp->referenceId = req->referenceId;
2270     *options = '\0';
2271     /* let's tell the client what we can do */
2272     if (ODR_MASK_GET(req->options, Z_Options_search))
2273     {
2274         ODR_MASK_SET(resp->options, Z_Options_search);
2275         strcat(options, "srch");
2276     }
2277     if (ODR_MASK_GET(req->options, Z_Options_present))
2278     {
2279         ODR_MASK_SET(resp->options, Z_Options_present);
2280         strcat(options, " prst");
2281     }
2282     if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
2283         assoc->init->bend_delete)
2284     {
2285         ODR_MASK_SET(resp->options, Z_Options_delSet);
2286         strcat(options, " del");
2287     }
2288     if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
2289         assoc->init->bend_esrequest)
2290     {
2291         ODR_MASK_SET(resp->options, Z_Options_extendedServices);
2292         strcat (options, " extendedServices");
2293     }
2294     if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
2295     {
2296         ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
2297         strcat(options, " namedresults");
2298     }
2299     if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
2300     {
2301         ODR_MASK_SET(resp->options, Z_Options_scan);
2302         strcat(options, " scan");
2303     }
2304     if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
2305     {
2306         ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
2307         strcat(options, " concurrop");
2308     }
2309     if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
2310     {
2311         ODR_MASK_SET(resp->options, Z_Options_sort);
2312         strcat(options, " sort");
2313     }
2314     
2315     if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
2316     {
2317         Z_OtherInformationUnit *p0;
2318
2319         if (!assoc->init->charneg_response)
2320         {
2321             if (assoc->init->query_charset)
2322             {
2323                 assoc->init->charneg_response = yaz_set_response_charneg(
2324                     assoc->encode, assoc->init->query_charset, 0, 
2325                     assoc->init->records_in_same_charset);
2326             }
2327             else
2328             {
2329                 yaz_log(YLOG_WARN, "default query_charset not defined by backend");
2330             }
2331         }
2332         if (assoc->init->charneg_response
2333             && (p0=yaz_oi_update(&resp->otherInfo, assoc->encode, NULL, 0, 0)))
2334         {
2335             p0->which = Z_OtherInfo_externallyDefinedInfo;
2336             p0->information.externallyDefinedInfo =
2337                 assoc->init->charneg_response;
2338             ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
2339             strcat(options, " negotiation");
2340         }
2341     }
2342     if (ODR_MASK_GET(req->options, Z_Options_triggerResourceCtrl))
2343         ODR_MASK_SET(resp->options, Z_Options_triggerResourceCtrl);
2344
2345     if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
2346     {
2347         ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
2348         assoc->version = 1; /* 1 & 2 are equivalent */
2349     }
2350     if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
2351     {
2352         ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
2353         assoc->version = 2;
2354     }
2355     if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
2356     {
2357         ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
2358         assoc->version = 3;
2359     }
2360
2361     yaz_log(log_requestdetail, "Negotiated to v%d: %s", assoc->version, options);
2362
2363     if (*req->maximumRecordSize < assoc->maximumRecordSize)
2364         assoc->maximumRecordSize = *req->maximumRecordSize;
2365
2366     if (*req->preferredMessageSize < assoc->preferredMessageSize)
2367         assoc->preferredMessageSize = *req->preferredMessageSize;
2368
2369     resp->preferredMessageSize = &assoc->preferredMessageSize;
2370     resp->maximumRecordSize = &assoc->maximumRecordSize;
2371
2372     resp->implementationId = odr_prepend(assoc->encode,
2373                 assoc->init->implementation_id,
2374                 resp->implementationId);
2375
2376     resp->implementationName = odr_prepend(assoc->encode,
2377                 assoc->init->implementation_name,
2378                 odr_prepend(assoc->encode, "GFS", resp->implementationName));
2379
2380     version = odr_strdup(assoc->encode, "$Revision: 1.128 $");
2381     if (strlen(version) > 10)   /* check for unexpanded CVS strings */
2382         version[strlen(version)-2] = '\0';
2383     resp->implementationVersion = odr_prepend(assoc->encode,
2384                 assoc->init->implementation_version,
2385                 odr_prepend(assoc->encode, &version[11],
2386                             resp->implementationVersion));
2387
2388     if (binitres->errcode)
2389     {
2390         assoc->state = ASSOC_DEAD;
2391         resp->userInformationField =
2392             init_diagnostics(assoc->encode, binitres->errcode,
2393                              binitres->errstring);
2394         *resp->result = 0;
2395     }
2396     if (log_request)
2397     {
2398         if (!req->idAuthentication)
2399             yaz_log(log_request, "Auth none");
2400         else if (req->idAuthentication->which == Z_IdAuthentication_open)
2401         {
2402             const char *open = req->idAuthentication->u.open;
2403             const char *slash = strchr(open, '/');
2404             int len;
2405             if (slash)
2406                 len = slash - open;
2407             else
2408                 len = strlen(open);
2409                 yaz_log(log_request, "Auth open %.*s", len, open);
2410         }
2411         else if (req->idAuthentication->which == Z_IdAuthentication_idPass)
2412         {
2413             const char *user = req->idAuthentication->u.idPass->userId;
2414             const char *group = req->idAuthentication->u.idPass->groupId;
2415             yaz_log(log_request, "Auth idPass %s %s",
2416                     user ? user : "-", group ? group : "-");
2417         }
2418         else if (req->idAuthentication->which 
2419                  == Z_IdAuthentication_anonymous)
2420         {
2421             yaz_log(log_request, "Auth anonymous");
2422         }
2423         else
2424         {
2425             yaz_log(log_request, "Auth other");
2426         }
2427     }
2428     if (log_request)
2429     {
2430         WRBUF wr = wrbuf_alloc();
2431         wrbuf_printf(wr, "Init ");
2432         if (binitres->errcode)
2433             wrbuf_printf(wr, "ERROR %d", binitres->errcode);
2434         else
2435             wrbuf_printf(wr, "OK -");
2436         wrbuf_printf(wr, " ID:%s Name:%s Version:%s",
2437                      (req->implementationId ? req->implementationId :"-"), 
2438                      (req->implementationName ?
2439                       req->implementationName : "-"),
2440                      (req->implementationVersion ?
2441                       req->implementationVersion : "-")
2442             );
2443         yaz_log(log_request, "%s", wrbuf_cstr(wr));
2444         wrbuf_destroy(wr);
2445     }
2446     return apdu;
2447 }
2448
2449 /*
2450  * Set the specified `errcode' and `errstring' into a UserInfo-1
2451  * external to be returned to the client in accordance with Z35.90
2452  * Implementor Agreement 5 (Returning diagnostics in an InitResponse):
2453  *      http://lcweb.loc.gov/z3950/agency/agree/initdiag.html
2454  */
2455 static Z_External *init_diagnostics(ODR odr, int error, const char *addinfo)
2456 {
2457     yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2458         addinfo ? " -- " : "", addinfo ? addinfo : "");
2459     return zget_init_diagnostics(odr, error, addinfo);
2460 }
2461
2462 /*
2463  * nonsurrogate diagnostic record.
2464  */
2465 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
2466 {
2467     Z_Records *rec = (Z_Records *) odr_malloc (assoc->encode, sizeof(*rec));
2468
2469     yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2470             addinfo ? " -- " : "", addinfo ? addinfo : "");
2471
2472     rec->which = Z_Records_NSD;
2473     rec->u.nonSurrogateDiagnostic = zget_DefaultDiagFormat(assoc->encode,
2474                                                            error, addinfo);
2475     return rec;
2476 }
2477
2478 /*
2479  * surrogate diagnostic.
2480  */
2481 static Z_NamePlusRecord *surrogatediagrec(association *assoc, 
2482                                           const char *dbname,
2483                                           int error, const char *addinfo)
2484 {
2485     yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2486             addinfo ? " -- " : "", addinfo ? addinfo : "");
2487     return zget_surrogateDiagRec(assoc->encode, dbname, error, addinfo);
2488 }
2489
2490 static Z_Records *pack_records(association *a, char *setname, int start,
2491                                int *num, Z_RecordComposition *comp,
2492                                int *next, int *pres,
2493                                Z_ReferenceId *referenceId,
2494                                Odr_oid *oid, int *errcode)
2495 {
2496     int recno, total_length = 0, toget = *num, dumped_records = 0;
2497     Z_Records *records =
2498         (Z_Records *) odr_malloc (a->encode, sizeof(*records));
2499     Z_NamePlusRecordList *reclist =
2500         (Z_NamePlusRecordList *) odr_malloc (a->encode, sizeof(*reclist));
2501     Z_NamePlusRecord **list =
2502         (Z_NamePlusRecord **) odr_malloc (a->encode, sizeof(*list) * toget);
2503
2504     records->which = Z_Records_DBOSD;
2505     records->u.databaseOrSurDiagnostics = reclist;
2506     reclist->num_records = 0;
2507     reclist->records = list;
2508     *pres = Z_PresentStatus_success;
2509     *num = 0;
2510     *next = 0;
2511
2512     yaz_log(log_requestdetail, "Request to pack %d+%d %s", start, toget, setname);
2513     yaz_log(log_requestdetail, "pms=%d, mrs=%d", a->preferredMessageSize,
2514         a->maximumRecordSize);
2515     for (recno = start; reclist->num_records < toget; recno++)
2516     {
2517         bend_fetch_rr freq;
2518         Z_NamePlusRecord *thisrec;
2519         int this_length = 0;
2520         /*
2521          * we get the number of bytes allocated on the stream before any
2522          * allocation done by the backend - this should give us a reasonable
2523          * idea of the total size of the data so far.
2524          */
2525         total_length = odr_total(a->encode) - dumped_records;
2526         freq.errcode = 0;
2527         freq.errstring = 0;
2528         freq.basename = 0;
2529         freq.len = 0;
2530         freq.record = 0;
2531         freq.last_in_set = 0;
2532         freq.setname = setname;
2533         freq.surrogate_flag = 0;
2534         freq.number = recno;
2535         freq.comp = comp;
2536         freq.request_format = oid;
2537         freq.output_format = 0;
2538         freq.stream = a->encode;
2539         freq.print = a->print;
2540         freq.referenceId = referenceId;
2541         freq.schema = 0;
2542
2543         retrieve_fetch(a, &freq);
2544
2545         *next = freq.last_in_set ? 0 : recno + 1;
2546
2547         /* backend should be able to signal whether error is system-wide
2548            or only pertaining to current record */
2549         if (freq.errcode)
2550         {
2551             if (!freq.surrogate_flag)
2552             {
2553                 char s[20];
2554                 *pres = Z_PresentStatus_failure;
2555                 /* for 'present request out of range',
2556                    set addinfo to record position if not set */
2557                 if (freq.errcode == YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE  && 
2558                                 freq.errstring == 0)
2559                 {
2560                     sprintf (s, "%d", recno);
2561                     freq.errstring = s;
2562                 }
2563                 if (errcode)
2564                     *errcode = freq.errcode;
2565                 return diagrec(a, freq.errcode, freq.errstring);
2566             }
2567             reclist->records[reclist->num_records] =
2568                 surrogatediagrec(a, freq.basename, freq.errcode,
2569                                  freq.errstring);
2570             reclist->num_records++;
2571             continue;
2572         }
2573         if (freq.record == 0)  /* no error and no record ? */
2574         {
2575             *next = 0;   /* signal end-of-set and stop */
2576             break;
2577         }
2578         if (freq.len >= 0)
2579             this_length = freq.len;
2580         else
2581             this_length = odr_total(a->encode) - total_length - dumped_records;
2582         yaz_log(YLOG_DEBUG, "  fetched record, len=%d, total=%d dumped=%d",
2583             this_length, total_length, dumped_records);
2584         if (a->preferredMessageSize > 0 &&
2585                 this_length + total_length > a->preferredMessageSize)
2586         {
2587             /* record is small enough, really */
2588             if (this_length <= a->preferredMessageSize && recno > start)
2589             {
2590                 yaz_log(log_requestdetail, "  Dropped last normal-sized record");
2591                 *pres = Z_PresentStatus_partial_2;
2592                 break;
2593             }
2594             /* record can only be fetched by itself */
2595             if (this_length < a->maximumRecordSize)
2596             {
2597                 yaz_log(log_requestdetail, "  Record > prefmsgsz");
2598                 if (toget > 1)
2599                 {
2600                     yaz_log(YLOG_DEBUG, "  Dropped it");
2601                     reclist->records[reclist->num_records] =
2602                          surrogatediagrec(a, freq.basename, 16, 0);
2603                     reclist->num_records++;
2604                     dumped_records += this_length;
2605                     continue;
2606                 }
2607             }
2608             else /* too big entirely */
2609             {
2610                 yaz_log(log_requestdetail, "Record > maxrcdsz this=%d max=%d",
2611                         this_length, a->maximumRecordSize);
2612                 reclist->records[reclist->num_records] =
2613                     surrogatediagrec(a, freq.basename, 17, 0);
2614                 reclist->num_records++;
2615                 dumped_records += this_length;
2616                 continue;
2617             }
2618         }
2619
2620         if (!(thisrec = (Z_NamePlusRecord *)
2621               odr_malloc(a->encode, sizeof(*thisrec))))
2622             return 0;
2623         thisrec->databaseName = odr_strdup_null(a->encode, freq.basename);
2624         thisrec->which = Z_NamePlusRecord_databaseRecord;
2625
2626         if (!freq.output_format)
2627             freq.output_format = freq.request_format;
2628         thisrec->u.databaseRecord = z_ext_record_oid(
2629             a->encode, freq.output_format, freq.record, freq.len);
2630         if (!thisrec->u.databaseRecord)
2631             return 0;
2632         reclist->records[reclist->num_records] = thisrec;
2633         reclist->num_records++;
2634     }
2635     *num = reclist->num_records;
2636     return records;
2637 }
2638
2639 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
2640     int *fd)
2641 {
2642     Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2643     bend_search_rr *bsrr = 
2644         (bend_search_rr *)nmem_malloc (reqb->request_mem, sizeof(*bsrr));
2645     
2646     yaz_log(log_requestdetail, "Got SearchRequest.");
2647     bsrr->fd = fd;
2648     bsrr->request = reqb;
2649     bsrr->association = assoc;
2650     bsrr->referenceId = req->referenceId;
2651     save_referenceId (reqb, bsrr->referenceId);
2652     bsrr->srw_sortKeys = 0;
2653     bsrr->srw_setname = 0;
2654     bsrr->srw_setnameIdleTime = 0;
2655     bsrr->estimated_hit_count = 0;
2656     bsrr->partial_resultset = 0;
2657
2658     yaz_log (log_requestdetail, "ResultSet '%s'", req->resultSetName);
2659     if (req->databaseNames)
2660     {
2661         int i;
2662         for (i = 0; i < req->num_databaseNames; i++)
2663             yaz_log(log_requestdetail, "Database '%s'", req->databaseNames[i]);
2664     }
2665
2666     yaz_log_zquery_level(log_requestdetail,req->query);
2667
2668     if (assoc->init->bend_search)
2669     {
2670         bsrr->setname = req->resultSetName;
2671         bsrr->replace_set = *req->replaceIndicator;
2672         bsrr->num_bases = req->num_databaseNames;
2673         bsrr->basenames = req->databaseNames;
2674         bsrr->query = req->query;
2675         bsrr->stream = assoc->encode;
2676         nmem_transfer(odr_getmem(bsrr->stream), reqb->request_mem);
2677         bsrr->decode = assoc->decode;
2678         bsrr->print = assoc->print;
2679         bsrr->hits = 0;
2680         bsrr->errcode = 0;
2681         bsrr->errstring = NULL;
2682         bsrr->search_info = NULL;
2683
2684         if (assoc->server && assoc->server->cql_transform 
2685             && req->query->which == Z_Query_type_104
2686             && req->query->u.type_104->which == Z_External_CQL)
2687         {
2688             /* have a CQL query and a CQL to PQF transform .. */
2689             int srw_errcode = 
2690                 cql2pqf(bsrr->stream, req->query->u.type_104->u.cql,
2691                         assoc->server->cql_transform, bsrr->query);
2692             if (srw_errcode)
2693                 bsrr->errcode = yaz_diag_srw_to_bib1(srw_errcode);
2694         }
2695
2696         if (assoc->server && assoc->server->ccl_transform 
2697             && req->query->which == Z_Query_type_2) /*CCL*/
2698         {
2699             /* have a CCL query and a CCL to PQF transform .. */
2700             int srw_errcode = 
2701                 ccl2pqf(bsrr->stream, req->query->u.type_2,
2702                         assoc->server->ccl_transform, bsrr);
2703             if (srw_errcode)
2704                 bsrr->errcode = yaz_diag_srw_to_bib1(srw_errcode);
2705         }
2706
2707         if (!bsrr->errcode)
2708             (assoc->init->bend_search)(assoc->backend, bsrr);
2709         if (!bsrr->request)  /* backend not ready with the search response */
2710             return 0;  /* should not be used any more */
2711     }
2712     else
2713     { 
2714         /* FIXME - make a diagnostic for it */
2715         yaz_log(YLOG_WARN,"Search not supported ?!?!");
2716     }
2717     return response_searchRequest(assoc, reqb, bsrr, fd);
2718 }
2719
2720 int bend_searchresponse(void *handle, bend_search_rr *bsrr) {return 0;}
2721
2722 /*
2723  * Prepare a searchresponse based on the backend results. We probably want
2724  * to look at making the fetching of records nonblocking as well, but
2725  * so far, we'll keep things simple.
2726  * If bsrt is null, that means we're called in response to a communications
2727  * event, and we'll have to get the response for ourselves.
2728  */
2729 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
2730     bend_search_rr *bsrt, int *fd)
2731 {
2732     Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2733     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2734     Z_SearchResponse *resp = (Z_SearchResponse *)
2735         odr_malloc (assoc->encode, sizeof(*resp));
2736     int *nulint = odr_intdup (assoc->encode, 0);
2737     int *next = odr_intdup(assoc->encode, 0);
2738     int *none = odr_intdup(assoc->encode, Z_SearchResponse_none);
2739     int returnedrecs = 0;
2740
2741     apdu->which = Z_APDU_searchResponse;
2742     apdu->u.searchResponse = resp;
2743     resp->referenceId = req->referenceId;
2744     resp->additionalSearchInfo = 0;
2745     resp->otherInfo = 0;
2746     *fd = -1;
2747     if (!bsrt && !bend_searchresponse(assoc->backend, bsrt))
2748     {
2749         yaz_log(YLOG_FATAL, "Bad result from backend");
2750         return 0;
2751     }
2752     else if (bsrt->errcode)
2753     {
2754         resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
2755         resp->resultCount = nulint;
2756         resp->numberOfRecordsReturned = nulint;
2757         resp->nextResultSetPosition = nulint;
2758         resp->searchStatus = nulint;
2759         resp->resultSetStatus = none;
2760         resp->presentStatus = 0;
2761     }
2762     else
2763     {
2764         bool_t *sr = odr_intdup(assoc->encode, 1);
2765         int *toget = odr_intdup(assoc->encode, 0);
2766         Z_RecordComposition comp, *compp = 0;
2767
2768         yaz_log (log_requestdetail, "resultCount: %d", bsrt->hits);
2769
2770         resp->records = 0;
2771         resp->resultCount = &bsrt->hits;
2772
2773         comp.which = Z_RecordComp_simple;
2774         /* how many records does the user agent want, then? */
2775         if (bsrt->hits <= *req->smallSetUpperBound)
2776         {
2777             *toget = bsrt->hits;
2778             if ((comp.u.simple = req->smallSetElementSetNames))
2779                 compp = &comp;
2780         }
2781         else if (bsrt->hits < *req->largeSetLowerBound)
2782         {
2783             *toget = *req->mediumSetPresentNumber;
2784             if (*toget > bsrt->hits)
2785                 *toget = bsrt->hits;
2786             if ((comp.u.simple = req->mediumSetElementSetNames))
2787                 compp = &comp;
2788         }
2789         else
2790             *toget = 0;
2791
2792         if (*toget && !resp->records)
2793         {
2794             int *presst = odr_intdup(assoc->encode, 0);
2795             /* Call bend_present if defined */
2796             if (assoc->init->bend_present)
2797             {
2798                 bend_present_rr *bprr = (bend_present_rr *)
2799                     nmem_malloc (reqb->request_mem, sizeof(*bprr));
2800                 bprr->setname = req->resultSetName;
2801                 bprr->start = 1;
2802                 bprr->number = *toget;
2803                 bprr->format = req->preferredRecordSyntax;
2804                 bprr->comp = compp;
2805                 bprr->referenceId = req->referenceId;
2806                 bprr->stream = assoc->encode;
2807                 bprr->print = assoc->print;
2808                 bprr->request = reqb;
2809                 bprr->association = assoc;
2810                 bprr->errcode = 0;
2811                 bprr->errstring = NULL;
2812                 (*assoc->init->bend_present)(assoc->backend, bprr);
2813
2814                 if (!bprr->request)
2815                     return 0;
2816                 if (bprr->errcode)
2817                 {
2818                     resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2819                     *resp->presentStatus = Z_PresentStatus_failure;
2820                 }
2821             }
2822
2823             if (!resp->records)
2824                 resp->records = pack_records(
2825                     assoc, req->resultSetName, 1,
2826                     toget, compp, next, presst, req->referenceId,
2827                     req->preferredRecordSyntax, NULL);
2828             if (!resp->records)
2829                 return 0;
2830             resp->numberOfRecordsReturned = toget;
2831             returnedrecs = *toget;
2832             resp->presentStatus = presst;
2833         }
2834         else
2835         {
2836             if (*resp->resultCount)
2837                 *next = 1;
2838             resp->numberOfRecordsReturned = nulint;
2839             resp->presentStatus = 0;
2840         }
2841         resp->nextResultSetPosition = next;
2842         resp->searchStatus = sr;
2843         resp->resultSetStatus = 0;
2844         if (bsrt->estimated_hit_count)
2845         {
2846             resp->resultSetStatus = odr_intdup(assoc->encode, 
2847                                                Z_SearchResponse_estimate);
2848         }
2849         else if (bsrt->partial_resultset)
2850         {
2851             resp->resultSetStatus = odr_intdup(assoc->encode, 
2852                                                Z_SearchResponse_subset);
2853         }
2854     }
2855     resp->additionalSearchInfo = bsrt->search_info;
2856
2857     if (log_request)
2858     {
2859         int i;
2860         WRBUF wr = wrbuf_alloc();
2861
2862         for (i = 0 ; i < req->num_databaseNames; i++){
2863             if (i)
2864                 wrbuf_printf(wr, "+");
2865             wrbuf_printf(wr, req->databaseNames[i]);
2866         }
2867         wrbuf_printf(wr, " ");
2868         
2869         if (bsrt->errcode)
2870             wrbuf_printf(wr, "ERROR %d", bsrt->errcode);
2871         else
2872             wrbuf_printf(wr, "OK %d", bsrt->hits);
2873         wrbuf_printf(wr, " %s 1+%d ",
2874                      req->resultSetName, returnedrecs);
2875         yaz_query_to_wrbuf(wr, req->query);
2876         
2877         yaz_log(log_request, "Search %s", wrbuf_cstr(wr));
2878         wrbuf_destroy(wr);
2879     }
2880     return apdu;
2881 }
2882
2883 /*
2884  * Maybe we got a little over-friendly when we designed bend_fetch to
2885  * get only one record at a time. Some backends can optimise multiple-record
2886  * fetches, and at any rate, there is some overhead involved in
2887  * all that selecting and hopping around. Problem is, of course, that the
2888  * frontend can't know ahead of time how many records it'll need to
2889  * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
2890  * is downright lousy as a bulk data transfer protocol.
2891  *
2892  * To start with, we'll do the fetching of records from the backend
2893  * in one operation: To save some trips in and out of the event-handler,
2894  * and to simplify the interface to pack_records. At any rate, asynch
2895  * operation is more fun in operations that have an unpredictable execution
2896  * speed - which is normally more true for search than for present.
2897  */
2898 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
2899                                       int *fd)
2900 {
2901     Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
2902     Z_APDU *apdu;
2903     Z_PresentResponse *resp;
2904     int *next;
2905     int *num;
2906     int errcode = 0;
2907     const char *errstring = 0;
2908
2909     yaz_log(log_requestdetail, "Got PresentRequest.");
2910
2911     resp = (Z_PresentResponse *)odr_malloc (assoc->encode, sizeof(*resp));
2912     resp->records = 0;
2913     resp->presentStatus = odr_intdup(assoc->encode, 0);
2914     if (assoc->init->bend_present)
2915     {
2916         bend_present_rr *bprr = (bend_present_rr *)
2917             nmem_malloc (reqb->request_mem, sizeof(*bprr));
2918         bprr->setname = req->resultSetId;
2919         bprr->start = *req->resultSetStartPoint;
2920         bprr->number = *req->numberOfRecordsRequested;
2921         bprr->format = req->preferredRecordSyntax;
2922         bprr->comp = req->recordComposition;
2923         bprr->referenceId = req->referenceId;
2924         bprr->stream = assoc->encode;
2925         bprr->print = assoc->print;
2926         bprr->request = reqb;
2927         bprr->association = assoc;
2928         bprr->errcode = 0;
2929         bprr->errstring = NULL;
2930         (*assoc->init->bend_present)(assoc->backend, bprr);
2931         
2932         if (!bprr->request)
2933             return 0; /* should not happen */
2934         if (bprr->errcode)
2935         {
2936             resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2937             *resp->presentStatus = Z_PresentStatus_failure;
2938             errcode = bprr->errcode;
2939             errstring = bprr->errstring;
2940         }
2941     }
2942     apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2943     next = odr_intdup(assoc->encode, 0);
2944     num = odr_intdup(assoc->encode, 0);
2945     
2946     apdu->which = Z_APDU_presentResponse;
2947     apdu->u.presentResponse = resp;
2948     resp->referenceId = req->referenceId;
2949     resp->otherInfo = 0;
2950     
2951     if (!resp->records)
2952     {
2953         *num = *req->numberOfRecordsRequested;
2954         resp->records =
2955             pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
2956                          num, req->recordComposition, next,
2957                          resp->presentStatus,
2958                          req->referenceId, req->preferredRecordSyntax, 
2959                          &errcode);
2960     }
2961     if (log_request)
2962     {
2963         WRBUF wr = wrbuf_alloc();
2964         wrbuf_printf(wr, "Present ");
2965
2966         if (*resp->presentStatus == Z_PresentStatus_failure)
2967             wrbuf_printf(wr, "ERROR %d ", errcode);
2968         else if (*resp->presentStatus == Z_PresentStatus_success)
2969             wrbuf_printf(wr, "OK -  ");
2970         else
2971             wrbuf_printf(wr, "Partial %d - ", *resp->presentStatus);
2972
2973         wrbuf_printf(wr, " %s %d+%d ",
2974                 req->resultSetId, *req->resultSetStartPoint,
2975                 *req->numberOfRecordsRequested);
2976         yaz_log(log_request, "%s", wrbuf_cstr(wr) );
2977         wrbuf_destroy(wr);
2978     }
2979     if (!resp->records)
2980         return 0;
2981     resp->numberOfRecordsReturned = num;
2982     resp->nextResultSetPosition = next;
2983     
2984     return apdu;
2985 }
2986
2987 /*
2988  * Scan was implemented rather in a hurry, and with support for only the basic
2989  * elements of the service in the backend API. Suggestions are welcome.
2990  */
2991 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
2992 {
2993     Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
2994     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2995     Z_ScanResponse *res = (Z_ScanResponse *)
2996         odr_malloc (assoc->encode, sizeof(*res));
2997     int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
2998     int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
2999     Z_ListEntries *ents = (Z_ListEntries *)
3000         odr_malloc (assoc->encode, sizeof(*ents));
3001     Z_DiagRecs *diagrecs_p = NULL;
3002     bend_scan_rr *bsrr = (bend_scan_rr *)
3003         odr_malloc (assoc->encode, sizeof(*bsrr));
3004     struct scan_entry *save_entries;
3005
3006     yaz_log(log_requestdetail, "Got ScanRequest");
3007
3008     apdu->which = Z_APDU_scanResponse;
3009     apdu->u.scanResponse = res;
3010     res->referenceId = req->referenceId;
3011
3012     /* if step is absent, set it to 0 */
3013     res->stepSize = odr_intdup(assoc->encode, 0);
3014     if (req->stepSize)
3015         *res->stepSize = *req->stepSize;
3016
3017     res->scanStatus = scanStatus;
3018     res->numberOfEntriesReturned = numberOfEntriesReturned;
3019     res->positionOfTerm = 0;
3020     res->entries = ents;
3021     ents->num_entries = 0;
3022     ents->entries = NULL;
3023     ents->num_nonsurrogateDiagnostics = 0;
3024     ents->nonsurrogateDiagnostics = NULL;
3025     res->attributeSet = 0;
3026     res->otherInfo = 0;
3027
3028     if (req->databaseNames)
3029     {
3030         int i;
3031         for (i = 0; i < req->num_databaseNames; i++)
3032             yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
3033     }
3034     bsrr->scanClause = 0;
3035     bsrr->errcode = 0;
3036     bsrr->errstring = 0;
3037     bsrr->num_bases = req->num_databaseNames;
3038     bsrr->basenames = req->databaseNames;
3039     bsrr->num_entries = *req->numberOfTermsRequested;
3040     bsrr->term = req->termListAndStartPoint;
3041     bsrr->referenceId = req->referenceId;
3042     bsrr->stream = assoc->encode;
3043     bsrr->print = assoc->print;
3044     bsrr->step_size = res->stepSize;
3045     bsrr->setname = yaz_oi_get_string_oid(&req->otherInfo, 
3046                                           yaz_oid_userinfo_scan_set, 1, 0);
3047     bsrr->entries = 0;
3048     /* For YAZ 2.0 and earlier it was the backend handler that
3049        initialized entries (member display_term did not exist)
3050        YAZ 2.0 and later sets 'entries'  and initialize all members
3051        including 'display_term'. If YAZ 2.0 or later sees that
3052        entries was modified - we assume that it is an old handler and
3053        that 'display_term' is _not_ set.
3054     */
3055     if (bsrr->num_entries > 0) 
3056     {
3057         int i;
3058         bsrr->entries = (struct scan_entry *)
3059             odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
3060                        bsrr->num_entries);
3061         for (i = 0; i<bsrr->num_entries; i++)
3062         {
3063             bsrr->entries[i].term = 0;
3064             bsrr->entries[i].occurrences = 0;
3065             bsrr->entries[i].errcode = 0;
3066             bsrr->entries[i].errstring = 0;
3067             bsrr->entries[i].display_term = 0;
3068         }
3069     }
3070     save_entries = bsrr->entries;  /* save it so we can compare later */
3071
3072     bsrr->attributeset = req->attributeSet;
3073     log_scan_term_level (log_requestdetail, req->termListAndStartPoint, 
3074             bsrr->attributeset);
3075     bsrr->term_position = req->preferredPositionInResponse ?
3076         *req->preferredPositionInResponse : 1;
3077
3078     ((int (*)(void *, bend_scan_rr *))
3079      (*assoc->init->bend_scan))(assoc->backend, bsrr);
3080
3081     if (bsrr->errcode)
3082         diagrecs_p = zget_DiagRecs(assoc->encode,
3083                                    bsrr->errcode, bsrr->errstring);
3084     else
3085     {
3086         int i;
3087         Z_Entry **tab = (Z_Entry **)
3088             odr_malloc (assoc->encode, sizeof(*tab) * bsrr->num_entries);
3089         
3090         if (bsrr->status == BEND_SCAN_PARTIAL)
3091             *scanStatus = Z_Scan_partial_5;
3092         else
3093             *scanStatus = Z_Scan_success;
3094         ents->entries = tab;
3095         ents->num_entries = bsrr->num_entries;
3096         res->numberOfEntriesReturned = &ents->num_entries;          
3097         res->positionOfTerm = &bsrr->term_position;
3098         for (i = 0; i < bsrr->num_entries; i++)
3099         {
3100             Z_Entry *e;
3101             Z_TermInfo *t;
3102             Odr_oct *o;
3103             
3104             tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
3105             if (bsrr->entries[i].occurrences >= 0)
3106             {
3107                 e->which = Z_Entry_termInfo;
3108                 e->u.termInfo = t = (Z_TermInfo *)
3109                     odr_malloc(assoc->encode, sizeof(*t));
3110                 t->suggestedAttributes = 0;
3111                 t->displayTerm = 0;
3112                 if (save_entries == bsrr->entries && 
3113                     bsrr->entries[i].display_term)
3114                 {
3115                     /* the entries was _not_ set by the handler. So it's
3116                        safe to test for new member display_term. It is
3117                        NULL'ed by us.
3118                     */
3119                     t->displayTerm = odr_strdup(assoc->encode,
3120                                                 bsrr->entries[i].display_term);
3121                 }
3122                 t->alternativeTerm = 0;
3123                 t->byAttributes = 0;
3124                 t->otherTermInfo = 0;
3125                 t->globalOccurrences = &bsrr->entries[i].occurrences;
3126                 t->term = (Z_Term *)
3127                     odr_malloc(assoc->encode, sizeof(*t->term));
3128                 t->term->which = Z_Term_general;
3129                 t->term->u.general = o =
3130                     (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
3131                 o->buf = (unsigned char *)
3132                     odr_malloc(assoc->encode, o->len = o->size =
3133                                strlen(bsrr->entries[i].term));
3134                 memcpy(o->buf, bsrr->entries[i].term, o->len);
3135                 yaz_log(YLOG_DEBUG, "  term #%d: '%s' (%d)", i,
3136                          bsrr->entries[i].term, bsrr->entries[i].occurrences);
3137             }
3138             else
3139             {
3140                 Z_DiagRecs *drecs = zget_DiagRecs(assoc->encode,
3141                                                   bsrr->entries[i].errcode,
3142                                                   bsrr->entries[i].errstring);
3143                 assert (drecs->num_diagRecs == 1);
3144                 e->which = Z_Entry_surrogateDiagnostic;
3145                 assert (drecs->diagRecs[0]);
3146                 e->u.surrogateDiagnostic = drecs->diagRecs[0];
3147             }
3148         }
3149     }
3150     if (diagrecs_p)
3151     {
3152         ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
3153         ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
3154     }
3155     if (log_request)
3156     {
3157         int i;
3158         WRBUF wr = wrbuf_alloc();
3159         wrbuf_printf(wr, "Scan ");
3160         for (i = 0 ; i < req->num_databaseNames; i++)
3161         {
3162             if (i)
3163                 wrbuf_printf(wr, "+");
3164             wrbuf_printf(wr, req->databaseNames[i]);
3165         }
3166
3167         wrbuf_printf(wr, " ");
3168         
3169         if (bsrr->errcode)
3170             wr_diag(wr, bsrr->errcode, bsrr->errstring);
3171         else
3172             wrbuf_printf(wr, "OK"); 
3173
3174         wrbuf_printf(wr, " %d - %d+%d+%d",
3175                      res->numberOfEntriesReturned ?
3176                      *res->numberOfEntriesReturned : 0,
3177                      (req->preferredPositionInResponse ?
3178                       *req->preferredPositionInResponse : 1),
3179                      *req->numberOfTermsRequested,
3180                      (res->stepSize ? *res->stepSize : 1));
3181         
3182         if (bsrr->setname)
3183             wrbuf_printf(wr, "+%s", bsrr->setname);
3184
3185         wrbuf_printf(wr, " ");
3186         yaz_scan_to_wrbuf(wr, req->termListAndStartPoint, 
3187                           bsrr->attributeset);
3188         yaz_log(log_request, "%s", wrbuf_cstr(wr) );
3189         wrbuf_destroy(wr);
3190     }
3191     return apdu;
3192 }
3193
3194 static Z_APDU *process_sortRequest(association *assoc, request *reqb,
3195     int *fd)
3196 {
3197     int i;
3198     Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
3199     Z_SortResponse *res = (Z_SortResponse *)
3200         odr_malloc (assoc->encode, sizeof(*res));
3201     bend_sort_rr *bsrr = (bend_sort_rr *)
3202         odr_malloc (assoc->encode, sizeof(*bsrr));
3203
3204     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
3205
3206     yaz_log(log_requestdetail, "Got SortRequest.");
3207
3208     bsrr->num_input_setnames = req->num_inputResultSetNames;
3209     for (i=0;i<req->num_inputResultSetNames;i++)
3210         yaz_log(log_requestdetail, "Input resultset: '%s'",
3211                 req->inputResultSetNames[i]);
3212     bsrr->input_setnames = req->inputResultSetNames;
3213     bsrr->referenceId = req->referenceId;
3214     bsrr->output_setname = req->sortedResultSetName;
3215     yaz_log(log_requestdetail, "Output resultset: '%s'",
3216                 req->sortedResultSetName);
3217     bsrr->sort_sequence = req->sortSequence;
3218        /*FIXME - dump those sequences too */
3219     bsrr->stream = assoc->encode;
3220     bsrr->print = assoc->print;
3221
3222     bsrr->sort_status = Z_SortResponse_failure;
3223     bsrr->errcode = 0;
3224     bsrr->errstring = 0;
3225     
3226     (*assoc->init->bend_sort)(assoc->backend, bsrr);
3227     
3228     res->referenceId = bsrr->referenceId;
3229     res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
3230     res->resultSetStatus = 0;
3231     if (bsrr->errcode)
3232     {
3233         Z_DiagRecs *dr = zget_DiagRecs(assoc->encode,
3234                                        bsrr->errcode, bsrr->errstring);
3235         res->diagnostics = dr->diagRecs;
3236         res->num_diagnostics = dr->num_diagRecs;
3237     }
3238     else
3239     {
3240         res->num_diagnostics = 0;
3241         res->diagnostics = 0;
3242     }
3243     res->resultCount = 0;
3244     res->otherInfo = 0;
3245
3246     apdu->which = Z_APDU_sortResponse;
3247     apdu->u.sortResponse = res;
3248     if (log_request)
3249     {
3250         WRBUF wr = wrbuf_alloc();
3251         wrbuf_printf(wr, "Sort ");
3252         if (bsrr->errcode)
3253             wrbuf_printf(wr, " ERROR %d", bsrr->errcode);
3254         else
3255             wrbuf_printf(wr,  "OK -");
3256         wrbuf_printf(wr, " (");
3257         for (i = 0; i<req->num_inputResultSetNames; i++)
3258         {
3259             if (i)
3260                 wrbuf_printf(wr, "+");
3261             wrbuf_printf(wr, req->inputResultSetNames[i]);
3262         }
3263         wrbuf_printf(wr, ")->%s ",req->sortedResultSetName);
3264
3265         yaz_log(log_request, "%s", wrbuf_cstr(wr) );
3266         wrbuf_destroy(wr);
3267     }
3268     return apdu;
3269 }
3270
3271 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
3272     int *fd)
3273 {
3274     int i;
3275     Z_DeleteResultSetRequest *req =
3276         reqb->apdu_request->u.deleteResultSetRequest;
3277     Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
3278         odr_malloc (assoc->encode, sizeof(*res));
3279     bend_delete_rr *bdrr = (bend_delete_rr *)
3280         odr_malloc (assoc->encode, sizeof(*bdrr));
3281     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
3282
3283     yaz_log(log_requestdetail, "Got DeleteRequest.");
3284
3285     bdrr->num_setnames = req->num_resultSetList;
3286     bdrr->setnames = req->resultSetList;
3287     for (i = 0; i<req->num_resultSetList; i++)
3288         yaz_log(log_requestdetail, "resultset: '%s'",
3289                 req->resultSetList[i]);
3290     bdrr->stream = assoc->encode;
3291     bdrr->print = assoc->print;
3292     bdrr->function = *req->deleteFunction;
3293     bdrr->referenceId = req->referenceId;
3294     bdrr->statuses = 0;
3295     if (bdrr->num_setnames > 0)
3296     {
3297         bdrr->statuses = (int*) 
3298             odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
3299                        bdrr->num_setnames);
3300         for (i = 0; i < bdrr->num_setnames; i++)
3301             bdrr->statuses[i] = 0;
3302     }
3303     (*assoc->init->bend_delete)(assoc->backend, bdrr);
3304     
3305     res->referenceId = req->referenceId;
3306
3307     res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
3308
3309     res->deleteListStatuses = 0;
3310     if (bdrr->num_setnames > 0)
3311     {
3312         int i;
3313         res->deleteListStatuses = (Z_ListStatuses *)
3314             odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
3315         res->deleteListStatuses->num = bdrr->num_setnames;
3316         res->deleteListStatuses->elements =
3317             (Z_ListStatus **)
3318             odr_malloc (assoc->encode, 
3319                         sizeof(*res->deleteListStatuses->elements) *
3320                         bdrr->num_setnames);
3321         for (i = 0; i<bdrr->num_setnames; i++)
3322         {
3323             res->deleteListStatuses->elements[i] =
3324                 (Z_ListStatus *)
3325                 odr_malloc (assoc->encode,
3326                             sizeof(**res->deleteListStatuses->elements));
3327             res->deleteListStatuses->elements[i]->status = bdrr->statuses+i;
3328             res->deleteListStatuses->elements[i]->id =
3329                 odr_strdup (assoc->encode, bdrr->setnames[i]);
3330         }
3331     }
3332     res->numberNotDeleted = 0;
3333     res->bulkStatuses = 0;
3334     res->deleteMessage = 0;
3335     res->otherInfo = 0;
3336
3337     apdu->which = Z_APDU_deleteResultSetResponse;
3338     apdu->u.deleteResultSetResponse = res;
3339     if (log_request)
3340     {
3341         WRBUF wr = wrbuf_alloc();
3342         wrbuf_printf(wr, "Delete ");
3343         if (bdrr->delete_status)
3344             wrbuf_printf(wr, "ERROR %d", bdrr->delete_status);
3345         else
3346             wrbuf_printf(wr, "OK -");
3347         for (i = 0; i<req->num_resultSetList; i++)
3348             wrbuf_printf(wr, " %s ", req->resultSetList[i]);
3349         yaz_log(log_request, "%s", wrbuf_cstr(wr) );
3350         wrbuf_destroy(wr);
3351     }
3352     return apdu;
3353 }
3354
3355 static void process_close(association *assoc, request *reqb)
3356 {
3357     Z_Close *req = reqb->apdu_request->u.close;
3358     static char *reasons[] =
3359     {
3360         "finished",
3361         "shutdown",
3362         "systemProblem",
3363         "costLimit",
3364         "resources",
3365         "securityViolation",
3366         "protocolError",
3367         "lackOfActivity",
3368         "peerAbort",
3369         "unspecified"
3370     };
3371
3372     yaz_log(log_requestdetail, "Got Close, reason %s, message %s",
3373         reasons[*req->closeReason], req->diagnosticInformation ?
3374         req->diagnosticInformation : "NULL");
3375     if (assoc->version < 3) /* to make do_force respond with close */
3376         assoc->version = 3;
3377     do_close_req(assoc, Z_Close_finished,
3378                  "Association terminated by client", reqb);
3379     yaz_log(log_request,"Close OK");
3380 }
3381
3382 void save_referenceId (request *reqb, Z_ReferenceId *refid)
3383 {
3384     if (refid)
3385     {
3386         reqb->len_refid = refid->len;
3387         reqb->refid = (char *)nmem_malloc (reqb->request_mem, refid->len);
3388         memcpy (reqb->refid, refid->buf, refid->len);
3389     }
3390     else
3391     {
3392         reqb->len_refid = 0;
3393         reqb->refid = NULL;
3394     }
3395 }
3396
3397 void bend_request_send (bend_association a, bend_request req, Z_APDU *res)
3398 {
3399     process_z_response (a, req, res);
3400 }
3401
3402 bend_request bend_request_mk (bend_association a)
3403 {
3404     request *nreq = request_get (&a->outgoing);
3405     nreq->request_mem = nmem_create ();
3406     return nreq;
3407 }
3408
3409 Z_ReferenceId *bend_request_getid (ODR odr, bend_request req)
3410 {
3411     Z_ReferenceId *id;
3412     if (!req->refid)
3413         return 0;
3414     id = (Odr_oct *)odr_malloc (odr, sizeof(*odr));
3415     id->buf = (unsigned char *)odr_malloc (odr, req->len_refid);
3416     id->len = id->size = req->len_refid;
3417     memcpy (id->buf, req->refid, req->len_refid);
3418     return id;
3419 }
3420
3421 void bend_request_destroy (bend_request *req)
3422 {
3423     nmem_destroy((*req)->request_mem);
3424     request_release(*req);
3425     *req = NULL;
3426 }
3427
3428 int bend_backend_respond (bend_association a, bend_request req)
3429 {
3430     char *msg;
3431     int r;
3432     r = process_z_request (a, req, &msg);
3433     if (r < 0)
3434         yaz_log (YLOG_WARN, "%s", msg);
3435     return r;
3436 }
3437
3438 void bend_request_setdata(bend_request r, void *p)
3439 {
3440     r->clientData = p;
3441 }
3442
3443 void *bend_request_getdata(bend_request r)
3444 {
3445     return r->clientData;
3446 }
3447
3448 static Z_APDU *process_segmentRequest (association *assoc, request *reqb)
3449 {
3450     bend_segment_rr req;
3451
3452     req.segment = reqb->apdu_request->u.segmentRequest;
3453     req.stream = assoc->encode;
3454     req.decode = assoc->decode;
3455     req.print = assoc->print;
3456     req.association = assoc;
3457     
3458     (*assoc->init->bend_segment)(assoc->backend, &req);
3459
3460     return 0;
3461 }
3462
3463 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd)
3464 {
3465     bend_esrequest_rr esrequest;
3466     const char *ext_name = "unknown";
3467
3468     Z_ExtendedServicesRequest *req =
3469         reqb->apdu_request->u.extendedServicesRequest;
3470     Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
3471
3472     Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
3473
3474     esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
3475     esrequest.stream = assoc->encode;
3476     esrequest.decode = assoc->decode;
3477     esrequest.print = assoc->print;
3478     esrequest.errcode = 0;
3479     esrequest.errstring = NULL;
3480     esrequest.request = reqb;
3481     esrequest.association = assoc;
3482     esrequest.taskPackage = 0;
3483     esrequest.referenceId = req->referenceId;
3484
3485     
3486     if (esrequest.esr && esrequest.esr->taskSpecificParameters)
3487     {
3488         switch(esrequest.esr->taskSpecificParameters->which)
3489         {
3490         case Z_External_itemOrder:
3491             ext_name = "ItemOrder"; break;
3492         case Z_External_update:
3493             ext_name = "Update"; break;
3494         case Z_External_update0:
3495             ext_name = "Update0"; break;
3496         case Z_External_ESAdmin:
3497             ext_name = "Admin"; break;
3498
3499         }
3500     }
3501
3502     (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
3503     
3504     /* If the response is being delayed, return NULL */
3505     if (esrequest.request == NULL)
3506         return(NULL);
3507
3508     resp->referenceId = req->referenceId;
3509
3510     if (esrequest.errcode == -1)
3511     {
3512         /* Backend service indicates request will be processed */
3513         yaz_log(log_request, "Extended Service: %s (accepted)", ext_name);
3514         *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
3515     }
3516     else if (esrequest.errcode == 0)
3517     {
3518         /* Backend service indicates request will be processed */
3519         yaz_log(log_request, "Extended Service: %s (done)", ext_name);
3520         *resp->operationStatus = Z_ExtendedServicesResponse_done;
3521     }
3522     else
3523     {
3524         Z_DiagRecs *diagRecs =
3525             zget_DiagRecs(assoc->encode, esrequest.errcode,
3526                           esrequest.errstring);
3527         /* Backend indicates error, request will not be processed */
3528         yaz_log(log_request, "Extended Service: %s (failed)", ext_name);
3529         *resp->operationStatus = Z_ExtendedServicesResponse_failure;
3530         resp->num_diagnostics = diagRecs->num_diagRecs;
3531         resp->diagnostics = diagRecs->diagRecs;
3532         if (log_request)
3533         {
3534             WRBUF wr = wrbuf_alloc();
3535             wrbuf_diags(wr, resp->num_diagnostics, resp->diagnostics);
3536             yaz_log(log_request, "EsRequest %s", wrbuf_cstr(wr) );
3537             wrbuf_destroy(wr);
3538         }
3539
3540     }
3541     /* Do something with the members of bend_extendedservice */
3542     if (esrequest.taskPackage)
3543     {
3544         resp->taskPackage = z_ext_record_oid(
3545             assoc->encode, yaz_oid_recsyn_extended,
3546             (const char *)  esrequest.taskPackage, -1
3547             );
3548     }
3549     yaz_log(YLOG_DEBUG,"Send the result apdu");
3550     return apdu;
3551 }
3552
3553 int bend_assoc_is_alive(bend_association assoc)
3554 {
3555     if (assoc->state == ASSOC_DEAD)
3556         return 0; /* already marked as dead. Don't check I/O chan anymore */
3557
3558     return iochan_is_alive(assoc->client_chan);
3559 }
3560
3561
3562 /*
3563  * Local variables:
3564  * c-basic-offset: 4
3565  * indent-tabs-mode: nil
3566  * End:
3567  * vim: shiftwidth=4 tabstop=8 expandtab
3568  */
3569