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