Version 5.4.0
[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 #include <yaz/query-charset.h>
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_e(assoc->encode, Z_SRW_searchRetrieve_response,
1866                                   sr);
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_e(o, Z_SRW_explain_response, sr);
1883             stylesheet = sr->u.explain_request->stylesheet;
1884             if (num_diagnostic)
1885             {
1886                 res->u.explain_response->diagnostics = diagnostic;
1887                 res->u.explain_response->num_diagnostics = num_diagnostic;
1888             }
1889             srw_bend_explain(assoc, hreq->headers,
1890                              sr, res->u.explain_response, &http_code);
1891             if (http_code == 200)
1892                 soap_package->u.generic->p = res;
1893         }
1894         else if (sr->which == Z_SRW_scan_request)
1895         {
1896             Z_SRW_PDU *res = yaz_srw_get_pdu_e(o, Z_SRW_scan_response, sr);
1897             stylesheet = sr->u.scan_request->stylesheet;
1898             if (num_diagnostic)
1899             {
1900                 res->u.scan_response->diagnostics = diagnostic;
1901                 res->u.scan_response->num_diagnostics = num_diagnostic;
1902             }
1903             srw_bend_scan(assoc, hreq->headers, sr, res, &http_code);
1904             if (http_code == 200)
1905                 soap_package->u.generic->p = res;
1906         }
1907         else if (sr->which == Z_SRW_update_request)
1908         {
1909             Z_SRW_PDU *res = yaz_srw_get_pdu(o, Z_SRW_update_response,
1910                                              sr->srw_version);
1911             yaz_log(YLOG_DEBUG, "handling SRW UpdateRequest");
1912             if (num_diagnostic)
1913             {
1914                 res->u.update_response->diagnostics = diagnostic;
1915                 res->u.update_response->num_diagnostics = num_diagnostic;
1916             }
1917             yaz_log(YLOG_DEBUG, "num_diag = %d", res->u.update_response->num_diagnostics );
1918             srw_bend_update(assoc, hreq->headers,
1919                             sr, res->u.update_response, &http_code);
1920             if (http_code == 200)
1921                 soap_package->u.generic->p = res;
1922         }
1923         else
1924         {
1925             yaz_log(log_request, "SOAP ERROR");
1926             /* FIXME - what error, what query */
1927             http_code = 500;
1928             z_soap_error(assoc->encode, soap_package,
1929                          "SOAP-ENV:Client", "Bad method", 0);
1930         }
1931         if (http_code == 200 || http_code == 500)
1932         {
1933             static Z_SOAP_Handler soap_handlers[4] = {
1934 #if YAZ_HAVE_XML2
1935                 {YAZ_XMLNS_SRU_v1_1, 0, (Z_SOAP_fun) yaz_srw_codec},
1936                 {YAZ_XMLNS_SRU_v1_0, 0, (Z_SOAP_fun) yaz_srw_codec},
1937                 {YAZ_XMLNS_UPDATE_v0_9, 0, (Z_SOAP_fun) yaz_ucp_codec},
1938 #endif
1939                 {0, 0, 0}
1940             };
1941             char ctype[80];
1942             p = z_get_HTTP_Response(o, 200);
1943             hres = p->u.HTTP_Response;
1944
1945             if (!stylesheet && assoc->server)
1946                 stylesheet = assoc->server->stylesheet;
1947
1948             /* empty stylesheet means NO stylesheet */
1949             if (stylesheet && *stylesheet == '\0')
1950                 stylesheet = 0;
1951
1952             z_soap_codec_enc_xsl(assoc->encode, &soap_package,
1953                                  &hres->content_buf, &hres->content_len,
1954                                  soap_handlers, charset, stylesheet);
1955             hres->code = http_code;
1956
1957             strcpy(ctype, "text/xml");
1958             z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1959         }
1960         else
1961             p = z_get_HTTP_Response(o, http_code);
1962     }
1963
1964     if (p == 0)
1965         p = z_get_HTTP_Response(o, 500);
1966     hres = p->u.HTTP_Response;
1967     if (!strcmp(hreq->version, "1.0"))
1968     {
1969         const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1970         if (v && !strcmp(v, "Keep-Alive"))
1971             keepalive = 1;
1972         else
1973             keepalive = 0;
1974         hres->version = "1.0";
1975     }
1976     else
1977     {
1978         const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1979         if (v && !strcmp(v, "close"))
1980             keepalive = 0;
1981         else
1982             keepalive = 1;
1983         hres->version = "1.1";
1984     }
1985     if (!keepalive || !assoc->last_control->keepalive)
1986     {
1987         z_HTTP_header_add(o, &hres->headers, "Connection", "close");
1988         assoc->state = ASSOC_DEAD;
1989         assoc->cs_get_mask = 0;
1990     }
1991     else
1992     {
1993         int t;
1994         const char *alive = z_HTTP_header_lookup(hreq->headers, "Keep-Alive");
1995
1996         if (alive && yaz_isdigit(*(const unsigned char *) alive))
1997             t = atoi(alive);
1998         else
1999             t = 15;
2000         if (t < 0 || t > 3600)
2001             t = 3600;
2002         iochan_settimeout(assoc->client_chan,t);
2003         z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
2004     }
2005     process_gdu_response(assoc, req, p);
2006 }
2007
2008 static void process_gdu_request(association *assoc, request *req)
2009 {
2010     if (req->gdu_request->which == Z_GDU_Z3950)
2011     {
2012         char *msg = 0;
2013         req->apdu_request = req->gdu_request->u.z3950;
2014         if (process_z_request(assoc, req, &msg) < 0)
2015             do_close_req(assoc, Z_Close_systemProblem, msg, req);
2016     }
2017     else if (req->gdu_request->which == Z_GDU_HTTP_Request)
2018         process_http_request(assoc, req);
2019     else
2020     {
2021         do_close_req(assoc, Z_Close_systemProblem, "bad protocol packet", req);
2022     }
2023 }
2024
2025 /*
2026  * Initiate request processing.
2027  */
2028 static int process_z_request(association *assoc, request *req, char **msg)
2029 {
2030     Z_APDU *res;
2031     int retval;
2032
2033     *msg = "Unknown Error";
2034     assert(req && req->state == REQUEST_IDLE);
2035     if (req->apdu_request->which != Z_APDU_initRequest && !assoc->init)
2036     {
2037         *msg = "Missing InitRequest";
2038         return -1;
2039     }
2040     switch (req->apdu_request->which)
2041     {
2042     case Z_APDU_initRequest:
2043         res = process_initRequest(assoc, req); break;
2044     case Z_APDU_searchRequest:
2045         res = process_searchRequest(assoc, req); break;
2046     case Z_APDU_presentRequest:
2047         res = process_presentRequest(assoc, req); break;
2048     case Z_APDU_scanRequest:
2049         if (assoc->init->bend_scan)
2050             res = process_scanRequest(assoc, req);
2051         else
2052         {
2053             *msg = "Cannot handle Scan APDU";
2054             return -1;
2055         }
2056         break;
2057     case Z_APDU_extendedServicesRequest:
2058         if (assoc->init->bend_esrequest)
2059             res = process_ESRequest(assoc, req);
2060         else
2061         {
2062             *msg = "Cannot handle Extended Services APDU";
2063             return -1;
2064         }
2065         break;
2066     case Z_APDU_sortRequest:
2067         if (assoc->init->bend_sort)
2068             res = process_sortRequest(assoc, req);
2069         else
2070         {
2071             *msg = "Cannot handle Sort APDU";
2072             return -1;
2073         }
2074         break;
2075     case Z_APDU_close:
2076         process_close(assoc, req);
2077         return 0;
2078     case Z_APDU_deleteResultSetRequest:
2079         if (assoc->init->bend_delete)
2080             res = process_deleteRequest(assoc, req);
2081         else
2082         {
2083             *msg = "Cannot handle Delete APDU";
2084             return -1;
2085         }
2086         break;
2087     case Z_APDU_segmentRequest:
2088         if (assoc->init->bend_segment)
2089         {
2090             res = process_segmentRequest(assoc, req);
2091         }
2092         else
2093         {
2094             *msg = "Cannot handle Segment APDU";
2095             return -1;
2096         }
2097         break;
2098     case Z_APDU_triggerResourceControlRequest:
2099         return 0;
2100     default:
2101         *msg = "Bad APDU received";
2102         return -1;
2103     }
2104     if (res)
2105     {
2106         yaz_log(YLOG_DEBUG, "  result immediately available");
2107         retval = process_z_response(assoc, req, res);
2108     }
2109     else
2110     {
2111         yaz_log(YLOG_DEBUG, "  result unavailable");
2112         retval = -1;
2113     }
2114     return retval;
2115 }
2116
2117 /*
2118  * Encode response, and transfer the request structure to the outgoing queue.
2119  */
2120 static int process_gdu_response(association *assoc, request *req, Z_GDU *res)
2121 {
2122     odr_setbuf(assoc->encode, req->response, req->size_response, 1);
2123
2124     if (assoc->print)
2125     {
2126         if (!z_GDU(assoc->print, &res, 0, 0))
2127             yaz_log(YLOG_WARN, "ODR print error: %s",
2128                 odr_errmsg(odr_geterror(assoc->print)));
2129         odr_reset(assoc->print);
2130     }
2131     if (!z_GDU(assoc->encode, &res, 0, 0))
2132     {
2133         yaz_log(YLOG_WARN, "ODR error when encoding PDU: %s [element %s]",
2134                 odr_errmsg(odr_geterror(assoc->decode)),
2135                 odr_getelement(assoc->decode));
2136         return -1;
2137     }
2138     req->response = odr_getbuf(assoc->encode, &req->len_response,
2139         &req->size_response);
2140     odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
2141     odr_reset(assoc->encode);
2142     req->state = REQUEST_IDLE;
2143     request_enq(&assoc->outgoing, req);
2144     /* turn the work over to the ir_session handler */
2145     iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
2146     assoc->cs_put_mask = EVENT_OUTPUT;
2147     /* Is there more work to be done? give that to the input handler too */
2148     for (;;)
2149     {
2150         req = request_head(&assoc->incoming);
2151         if (req && req->state == REQUEST_IDLE)
2152         {
2153             request_deq(&assoc->incoming);
2154             process_gdu_request(assoc, req);
2155         }
2156         else
2157             break;
2158     }
2159     return 0;
2160 }
2161
2162 /*
2163  * Encode response, and transfer the request structure to the outgoing queue.
2164  */
2165 static int process_z_response(association *assoc, request *req, Z_APDU *res)
2166 {
2167     Z_GDU *gres = (Z_GDU *) odr_malloc(assoc->encode, sizeof(*gres));
2168     gres->which = Z_GDU_Z3950;
2169     gres->u.z3950 = res;
2170
2171     return process_gdu_response(assoc, req, gres);
2172 }
2173
2174 static char *get_vhost(Z_OtherInformation *otherInfo)
2175 {
2176     return yaz_oi_get_string_oid(&otherInfo, yaz_oid_userinfo_proxy, 1, 0);
2177 }
2178
2179 /*
2180  * Handle init request.
2181  * At the moment, we don't check the options
2182  * anywhere else in the code - we just try not to do anything that would
2183  * break a naive client. We'll toss 'em into the association block when
2184  * we need them there.
2185  */
2186 static Z_APDU *process_initRequest(association *assoc, request *reqb)
2187 {
2188     Z_InitRequest *req = reqb->apdu_request->u.initRequest;
2189     Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
2190     Z_InitResponse *resp = apdu->u.initResponse;
2191     bend_initresult *binitres;
2192     char options[140];
2193     statserv_options_block *cb = 0;  /* by default no control for backend */
2194
2195     if (control_association(assoc, get_vhost(req->otherInfo), 1))
2196         cb = statserv_getcontrol();  /* got control block for backend */
2197
2198     if (cb && assoc->backend)
2199         (*cb->bend_close)(assoc->backend);
2200
2201     yaz_log(log_requestdetail, "Got initRequest");
2202     if (req->implementationId)
2203         yaz_log(log_requestdetail, "Id:        %s",
2204                 req->implementationId);
2205     if (req->implementationName)
2206         yaz_log(log_requestdetail, "Name:      %s",
2207                 req->implementationName);
2208     if (req->implementationVersion)
2209         yaz_log(log_requestdetail, "Version:   %s",
2210                 req->implementationVersion);
2211
2212     assoc_init_reset(assoc, 
2213                      yaz_oi_get_string_oid(&req->otherInfo,
2214                                            yaz_oid_userinfo_client_ip, 1, 0));
2215     assoc->init->auth = req->idAuthentication;
2216     assoc->init->referenceId = req->referenceId;
2217
2218     if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
2219     {
2220         Z_CharSetandLanguageNegotiation *negotiation =
2221             yaz_get_charneg_record (req->otherInfo);
2222         if (negotiation &&
2223             negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
2224             assoc->init->charneg_request = negotiation;
2225     }
2226
2227     /* by default named_result_sets is 0 .. Enable it if client asks for it. */
2228     if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
2229         assoc->init->named_result_sets = 1;
2230
2231     assoc->backend = 0;
2232     if (cb)
2233     {
2234         if (req->implementationVersion)
2235             yaz_log(log_requestdetail, "Config:    %s",
2236                     cb->configname);
2237
2238         iochan_settimeout(assoc->client_chan, cb->idle_timeout);
2239
2240         /* we have a backend control block, so call that init function */
2241         if (!(binitres = (*cb->bend_init)(assoc->init)))
2242         {
2243             yaz_log(YLOG_WARN, "Bad response from backend.");
2244             return 0;
2245         }
2246         assoc->backend = binitres->handle;
2247     }
2248     else
2249     {
2250         /* no backend. return error */
2251         binitres = (bend_initresult *)
2252             odr_malloc(assoc->encode, sizeof(*binitres));
2253         binitres->errstring = 0;
2254         binitres->errcode = YAZ_BIB1_PERMANENT_SYSTEM_ERROR;
2255         iochan_settimeout(assoc->client_chan, 10);
2256     }
2257     if ((assoc->init->bend_sort))
2258         yaz_log(YLOG_DEBUG, "Sort handler installed");
2259     if ((assoc->init->bend_search))
2260         yaz_log(YLOG_DEBUG, "Search handler installed");
2261     if ((assoc->init->bend_present))
2262         yaz_log(YLOG_DEBUG, "Present handler installed");
2263     if ((assoc->init->bend_esrequest))
2264         yaz_log(YLOG_DEBUG, "ESRequest handler installed");
2265     if ((assoc->init->bend_delete))
2266         yaz_log(YLOG_DEBUG, "Delete handler installed");
2267     if ((assoc->init->bend_scan))
2268         yaz_log(YLOG_DEBUG, "Scan handler installed");
2269     if ((assoc->init->bend_segment))
2270         yaz_log(YLOG_DEBUG, "Segment handler installed");
2271
2272     resp->referenceId = req->referenceId;
2273     *options = '\0';
2274     /* let's tell the client what we can do */
2275     if (ODR_MASK_GET(req->options, Z_Options_search))
2276     {
2277         ODR_MASK_SET(resp->options, Z_Options_search);
2278         strcat(options, "srch");
2279     }
2280     if (ODR_MASK_GET(req->options, Z_Options_present))
2281     {
2282         ODR_MASK_SET(resp->options, Z_Options_present);
2283         strcat(options, " prst");
2284     }
2285     if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
2286         assoc->init->bend_delete)
2287     {
2288         ODR_MASK_SET(resp->options, Z_Options_delSet);
2289         strcat(options, " del");
2290     }
2291     if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
2292         assoc->init->bend_esrequest)
2293     {
2294         ODR_MASK_SET(resp->options, Z_Options_extendedServices);
2295         strcat(options, " extendedServices");
2296     }
2297     if (ODR_MASK_GET(req->options, Z_Options_namedResultSets)
2298         && assoc->init->named_result_sets)
2299     {
2300         ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
2301         strcat(options, " namedresults");
2302     }
2303     if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
2304     {
2305         ODR_MASK_SET(resp->options, Z_Options_scan);
2306         strcat(options, " scan");
2307     }
2308     if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
2309     {
2310         ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
2311         strcat(options, " concurrop");
2312     }
2313     if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
2314     {
2315         ODR_MASK_SET(resp->options, Z_Options_sort);
2316         strcat(options, " sort");
2317     }
2318
2319     if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
2320     {
2321         Z_OtherInformationUnit *p0;
2322
2323         if (!assoc->init->charneg_response)
2324         {
2325             if (assoc->init->query_charset)
2326             {
2327                 assoc->init->charneg_response = yaz_set_response_charneg(
2328                     assoc->encode, assoc->init->query_charset, 0,
2329                     assoc->init->records_in_same_charset);
2330             }
2331             else
2332             {
2333                 yaz_log(YLOG_WARN, "default query_charset not defined by backend");
2334             }
2335         }
2336         if (assoc->init->charneg_response
2337             && (p0=yaz_oi_update(&resp->otherInfo, assoc->encode, NULL, 0, 0)))
2338         {
2339             p0->which = Z_OtherInfo_externallyDefinedInfo;
2340             p0->information.externallyDefinedInfo =
2341                 assoc->init->charneg_response;
2342             ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
2343             strcat(options, " negotiation");
2344         }
2345     }
2346     if (ODR_MASK_GET(req->options, Z_Options_triggerResourceCtrl))
2347         ODR_MASK_SET(resp->options, Z_Options_triggerResourceCtrl);
2348
2349     if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
2350     {
2351         ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
2352         assoc->version = 1; /* 1 & 2 are equivalent */
2353     }
2354     if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
2355     {
2356         ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
2357         assoc->version = 2;
2358     }
2359     if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
2360     {
2361         ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
2362         assoc->version = 3;
2363     }
2364
2365     yaz_log(log_requestdetail, "Negotiated to v%d: %s", assoc->version, options);
2366
2367     if (*req->maximumRecordSize < assoc->maximumRecordSize)
2368         assoc->maximumRecordSize = odr_int_to_int(*req->maximumRecordSize);
2369
2370     if (*req->preferredMessageSize < assoc->preferredMessageSize)
2371         assoc->preferredMessageSize = odr_int_to_int(*req->preferredMessageSize);
2372
2373     resp->preferredMessageSize =
2374         odr_intdup(assoc->encode, assoc->preferredMessageSize);
2375     resp->maximumRecordSize =
2376         odr_intdup(assoc->encode, assoc->maximumRecordSize);
2377
2378     resp->implementationId = odr_prepend(assoc->encode,
2379                 assoc->init->implementation_id,
2380                 resp->implementationId);
2381
2382     resp->implementationVersion = odr_prepend(assoc->encode,
2383                 assoc->init->implementation_version,
2384                 resp->implementationVersion);
2385
2386     resp->implementationName = odr_prepend(assoc->encode,
2387                 assoc->init->implementation_name,
2388                 odr_prepend(assoc->encode, "GFS", resp->implementationName));
2389
2390     if (binitres->errcode)
2391     {
2392         assoc->state = ASSOC_DEAD;
2393         resp->userInformationField =
2394             init_diagnostics(assoc->encode, binitres->errcode,
2395                              binitres->errstring);
2396         *resp->result = 0;
2397     }
2398     else
2399         assoc->state = ASSOC_UP;
2400
2401     if (log_request)
2402     {
2403         if (!req->idAuthentication)
2404             yaz_log(log_request, "Auth none");
2405         else if (req->idAuthentication->which == Z_IdAuthentication_open)
2406         {
2407             const char *open = req->idAuthentication->u.open;
2408             const char *slash = strchr(open, '/');
2409             int len;
2410             if (slash)
2411                 len = slash - open;
2412             else
2413                 len = strlen(open);
2414                 yaz_log(log_request, "Auth open %.*s", len, open);
2415         }
2416         else if (req->idAuthentication->which == Z_IdAuthentication_idPass)
2417         {
2418             const char *user = req->idAuthentication->u.idPass->userId;
2419             const char *group = req->idAuthentication->u.idPass->groupId;
2420             yaz_log(log_request, "Auth idPass %s %s",
2421                     user ? user : "-", group ? group : "-");
2422         }
2423         else if (req->idAuthentication->which
2424                  == Z_IdAuthentication_anonymous)
2425         {
2426             yaz_log(log_request, "Auth anonymous");
2427         }
2428         else
2429         {
2430             yaz_log(log_request, "Auth other");
2431         }
2432     }
2433     if (log_request)
2434     {
2435         WRBUF wr = wrbuf_alloc();
2436         wrbuf_printf(wr, "Init ");
2437         if (binitres->errcode)
2438             wrbuf_printf(wr, "ERROR %d", binitres->errcode);
2439         else
2440             wrbuf_printf(wr, "OK -");
2441         wrbuf_printf(wr, " ID:%s Name:%s Version:%s",
2442                      (req->implementationId ? req->implementationId :"-"),
2443                      (req->implementationName ?
2444                       req->implementationName : "-"),
2445                      (req->implementationVersion ?
2446                       req->implementationVersion : "-")
2447             );
2448         yaz_log(log_request, "%s", wrbuf_cstr(wr));
2449         wrbuf_destroy(wr);
2450     }
2451     return apdu;
2452 }
2453
2454 /*
2455  * Set the specified `errcode' and `errstring' into a UserInfo-1
2456  * external to be returned to the client in accordance with Z35.90
2457  * Implementor Agreement 5 (Returning diagnostics in an InitResponse):
2458  *      http://lcweb.loc.gov/z3950/agency/agree/initdiag.html
2459  */
2460 static Z_External *init_diagnostics(ODR odr, int error, const char *addinfo)
2461 {
2462     yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2463         addinfo ? " -- " : "", addinfo ? addinfo : "");
2464     return zget_init_diagnostics(odr, error, addinfo);
2465 }
2466
2467 /*
2468  * nonsurrogate diagnostic record.
2469  */
2470 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
2471 {
2472     Z_Records *rec = (Z_Records *) odr_malloc(assoc->encode, sizeof(*rec));
2473
2474     yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2475             addinfo ? " -- " : "", addinfo ? addinfo : "");
2476
2477     rec->which = Z_Records_NSD;
2478     rec->u.nonSurrogateDiagnostic = zget_DefaultDiagFormat(assoc->encode,
2479                                                            error, addinfo);
2480     return rec;
2481 }
2482
2483 /*
2484  * surrogate diagnostic.
2485  */
2486 static Z_NamePlusRecord *surrogatediagrec(association *assoc,
2487                                           const char *dbname,
2488                                           int error, const char *addinfo)
2489 {
2490     yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2491             addinfo ? " -- " : "", addinfo ? addinfo : "");
2492     return zget_surrogateDiagRec(assoc->encode, dbname, error, addinfo);
2493 }
2494
2495 static Z_Records *pack_records(association *a, char *setname, Odr_int start,
2496                                Odr_int *num, Z_RecordComposition *comp,
2497                                Odr_int *next, Odr_int *pres,
2498                                Z_ReferenceId *referenceId,
2499                                Odr_oid *oid, int *errcode)
2500 {
2501     int recno, dumped_records = 0;
2502     int toget = odr_int_to_int(*num);
2503     Z_Records *records =
2504         (Z_Records *) odr_malloc(a->encode, sizeof(*records));
2505     Z_NamePlusRecordList *reclist =
2506         (Z_NamePlusRecordList *) odr_malloc(a->encode, sizeof(*reclist));
2507
2508     records->which = Z_Records_DBOSD;
2509     records->u.databaseOrSurDiagnostics = reclist;
2510     reclist->num_records = 0;
2511
2512     if (toget < 0)
2513         return diagrec(a, YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE, 0);
2514     else if (toget == 0)
2515         reclist->records = odr_nullval();
2516     else
2517         reclist->records = (Z_NamePlusRecord **)
2518             odr_malloc(a->encode, sizeof(*reclist->records) * toget);
2519
2520     *pres = Z_PresentStatus_success;
2521     *num = 0;
2522     *next = 0;
2523
2524     yaz_log(log_requestdetail, "Request to pack " ODR_INT_PRINTF "+%d %s", start, toget, setname);
2525     yaz_log(log_requestdetail, "pms=%d, mrs=%d", a->preferredMessageSize,
2526         a->maximumRecordSize);
2527     for (recno = odr_int_to_int(start); reclist->num_records < toget; recno++)
2528     {
2529         bend_fetch_rr freq;
2530         Z_NamePlusRecord *thisrec;
2531         Odr_int this_length = 0;
2532         /*
2533          * we get the number of bytes allocated on the stream before any
2534          * allocation done by the backend - this should give us a reasonable
2535          * idea of the total size of the data so far.
2536          */
2537         Odr_int total_length = odr_total(a->encode) - dumped_records;
2538         freq.errcode = 0;
2539         freq.errstring = 0;
2540         freq.basename = 0;
2541         freq.len = 0;
2542         freq.record = 0;
2543         freq.last_in_set = 0;
2544         freq.setname = setname;
2545         freq.surrogate_flag = 0;
2546         freq.number = recno;
2547         freq.comp = comp;
2548         freq.request_format = oid;
2549         freq.output_format = 0;
2550         freq.stream = a->encode;
2551         freq.print = a->print;
2552         freq.referenceId = referenceId;
2553         freq.schema = 0;
2554
2555         retrieve_fetch(a, &freq);
2556
2557         *next = freq.last_in_set ? 0 : recno + 1;
2558
2559         if (freq.errcode)
2560         {
2561             if (!freq.surrogate_flag) /* non-surrogate diagnostic i.e. global */
2562             {
2563                 char s[20];
2564                 *pres = Z_PresentStatus_failure;
2565                 /* for 'present request out of range',
2566                    set addinfo to record position if not set */
2567                 if (freq.errcode == YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE  &&
2568                                 freq.errstring == 0)
2569                 {
2570                     sprintf(s, "%d", recno);
2571                     freq.errstring = s;
2572                 }
2573                 if (errcode)
2574                     *errcode = freq.errcode;
2575                 return diagrec(a, freq.errcode, freq.errstring);
2576             }
2577             reclist->records[reclist->num_records] =
2578                 surrogatediagrec(a, freq.basename, freq.errcode,
2579                                  freq.errstring);
2580             reclist->num_records++;
2581             continue;
2582         }
2583         if (freq.record == 0)  /* no error and no record ? */
2584         {
2585             *pres = Z_PresentStatus_partial_4;
2586             *next = 0;   /* signal end-of-set and stop */
2587             break;
2588         }
2589         if (freq.len >= 0)
2590             this_length = freq.len;
2591         else
2592             this_length = odr_total(a->encode) - total_length - dumped_records;
2593         yaz_log(log_requestdetail, "  fetched record, len=" ODR_INT_PRINTF
2594                 " total=" ODR_INT_PRINTF " dumped=%d",
2595                 this_length, total_length, dumped_records);
2596         if (a->preferredMessageSize > 0 &&
2597             this_length + total_length > a->preferredMessageSize)
2598         {
2599             /* record is small enough, really */
2600             if (this_length <= a->preferredMessageSize && recno > start)
2601             {
2602                 yaz_log(log_requestdetail, "  Dropped last normal-sized record");
2603                 *pres = Z_PresentStatus_partial_2;
2604                 if (*next > 0)
2605                     (*next)--;
2606                 break;
2607             }
2608             /* record can only be fetched by itself */
2609             if (this_length < a->maximumRecordSize)
2610             {
2611                 yaz_log(log_requestdetail, "  Record > prefmsgsz");
2612                 if (toget > 1)
2613                 {
2614                     yaz_log(YLOG_DEBUG, "  Dropped it");
2615                     reclist->records[reclist->num_records] =
2616                          surrogatediagrec(
2617                              a, freq.basename,
2618                              YAZ_BIB1_RECORD_EXCEEDS_PREFERRED_MESSAGE_SIZE, 0);
2619                     reclist->num_records++;
2620                     dumped_records += this_length;
2621                     continue;
2622                 }
2623             }
2624             else /* too big entirely */
2625             {
2626                 yaz_log(log_requestdetail, "Record > maxrcdsz "
2627                         "this=" ODR_INT_PRINTF " max=%d",
2628                         this_length, a->maximumRecordSize);
2629                 reclist->records[reclist->num_records] =
2630                     surrogatediagrec(
2631                         a, freq.basename,
2632                         YAZ_BIB1_RECORD_EXCEEDS_MAXIMUM_RECORD_SIZE, 0);
2633                 reclist->num_records++;
2634                 dumped_records += this_length;
2635                 continue;
2636             }
2637         }
2638
2639         if (!(thisrec = (Z_NamePlusRecord *)
2640               odr_malloc(a->encode, sizeof(*thisrec))))
2641             return 0;
2642         thisrec->databaseName = odr_strdup_null(a->encode, freq.basename);
2643         thisrec->which = Z_NamePlusRecord_databaseRecord;
2644
2645         if (!freq.output_format)
2646         {
2647             yaz_log(YLOG_WARN, "bend_fetch output_format not set");
2648             return 0;
2649         }
2650         thisrec->u.databaseRecord = z_ext_record_oid(
2651             a->encode, freq.output_format, freq.record, freq.len);
2652         if (!thisrec->u.databaseRecord)
2653             return 0;
2654         reclist->records[reclist->num_records] = thisrec;
2655         reclist->num_records++;
2656         if (freq.last_in_set)
2657             break;
2658     }
2659     *num = reclist->num_records;
2660     return records;
2661 }
2662
2663 static Z_APDU *process_searchRequest(association *assoc, request *reqb)
2664 {
2665     Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2666     bend_search_rr *bsrr =
2667         (bend_search_rr *)nmem_malloc(reqb->request_mem, sizeof(*bsrr));
2668
2669     yaz_log(log_requestdetail, "Got SearchRequest.");
2670     bsrr->association = assoc;
2671     bsrr->referenceId = req->referenceId;
2672     bsrr->srw_sortKeys = 0;
2673     bsrr->srw_setname = 0;
2674     bsrr->srw_setnameIdleTime = 0;
2675     bsrr->estimated_hit_count = 0;
2676     bsrr->partial_resultset = 0;
2677     bsrr->extra_args = 0;
2678     bsrr->extra_response_data = 0;
2679
2680     yaz_log(log_requestdetail, "ResultSet '%s'", req->resultSetName);
2681     if (req->databaseNames)
2682     {
2683         int i;
2684         for (i = 0; i < req->num_databaseNames; i++)
2685             yaz_log(log_requestdetail, "Database '%s'", req->databaseNames[i]);
2686     }
2687
2688     yaz_log_zquery_level(log_requestdetail,req->query);
2689
2690     if (assoc->init->bend_search)
2691     {
2692         bsrr->setname = req->resultSetName;
2693         bsrr->replace_set = *req->replaceIndicator;
2694         bsrr->num_bases = req->num_databaseNames;
2695         bsrr->basenames = req->databaseNames;
2696         bsrr->query = req->query;
2697         bsrr->stream = assoc->encode;
2698         nmem_transfer(odr_getmem(bsrr->stream), reqb->request_mem);
2699         bsrr->decode = assoc->decode;
2700         bsrr->print = assoc->print;
2701         bsrr->hits = 0;
2702         bsrr->errcode = 0;
2703         bsrr->errstring = NULL;
2704         bsrr->search_info = NULL;
2705         bsrr->search_input = req->additionalSearchInfo;
2706         if (!bsrr->search_input)
2707             bsrr->search_input = req->otherInfo;
2708         bsrr->present_number = *req->mediumSetPresentNumber;
2709
2710         if (assoc->server && assoc->server->client_query_charset &&
2711             req->query->which == Z_Query_type_1)
2712         {
2713             yaz_iconv_t cd =
2714                 yaz_iconv_open("UTF-8", assoc->server->client_query_charset);
2715             if (cd)
2716             {
2717                 yaz_query_charset_convert_rpnquery(req->query->u.type_1,
2718                                                    assoc->decode, cd);
2719                 yaz_iconv_close(cd);
2720             }
2721         }
2722
2723         if (assoc->server && assoc->server->cql_transform
2724             && req->query->which == Z_Query_type_104
2725             && req->query->u.type_104->which == Z_External_CQL)
2726         {
2727             /* have a CQL query and a CQL to PQF transform .. */
2728             int srw_errcode =
2729                 cql2pqf(bsrr->stream, req->query->u.type_104->u.cql,
2730                         assoc->server->cql_transform, bsrr->query,
2731                         &bsrr->srw_sortKeys);
2732             if (srw_errcode)
2733                 bsrr->errcode = yaz_diag_srw_to_bib1(srw_errcode);
2734         }
2735
2736         if (assoc->server && assoc->server->ccl_transform
2737             && req->query->which == Z_Query_type_2) /*CCL*/
2738         {
2739             /* have a CCL query and a CCL to PQF transform .. */
2740             int srw_errcode =
2741                 ccl2pqf(bsrr->stream, req->query->u.type_2,
2742                         assoc->server->ccl_transform, bsrr);
2743             if (srw_errcode)
2744                 bsrr->errcode = yaz_diag_srw_to_bib1(srw_errcode);
2745         }
2746
2747         if (!bsrr->errcode)
2748             (assoc->init->bend_search)(assoc->backend, bsrr);
2749     }
2750     else
2751     {
2752         /* FIXME - make a diagnostic for it */
2753         yaz_log(YLOG_WARN,"Search not supported ?!?!");
2754     }
2755     return response_searchRequest(assoc, reqb, bsrr);
2756 }
2757
2758 /*
2759  * Prepare a searchresponse based on the backend results. We probably want
2760  * to look at making the fetching of records nonblocking as well, but
2761  * so far, we'll keep things simple.
2762  * If bsrt is null, that means we're called in response to a communications
2763  * event, and we'll have to get the response for ourselves.
2764  */
2765 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
2766                                       bend_search_rr *bsrt)
2767 {
2768     Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2769     Z_APDU *apdu = (Z_APDU *)odr_malloc(assoc->encode, sizeof(*apdu));
2770     Z_SearchResponse *resp = (Z_SearchResponse *)
2771         odr_malloc(assoc->encode, sizeof(*resp));
2772     Odr_int *nulint = odr_intdup(assoc->encode, 0);
2773     Odr_int *next = odr_intdup(assoc->encode, 0);
2774     Odr_int *none = odr_intdup(assoc->encode, Z_SearchResponse_none);
2775     Odr_int returnedrecs = 0;
2776
2777     apdu->which = Z_APDU_searchResponse;
2778     apdu->u.searchResponse = resp;
2779     resp->referenceId = req->referenceId;
2780     resp->additionalSearchInfo = 0;
2781     resp->otherInfo = 0;
2782     if (!bsrt)
2783     {
2784         yaz_log(YLOG_FATAL, "Bad result from backend");
2785         return 0;
2786     }
2787     else if (bsrt->errcode)
2788     {
2789         resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
2790         resp->resultCount = nulint;
2791         resp->numberOfRecordsReturned = nulint;
2792         resp->nextResultSetPosition = nulint;
2793         resp->searchStatus = odr_booldup(assoc->encode, 0);
2794         resp->resultSetStatus = none;
2795         resp->presentStatus = 0;
2796     }
2797     else
2798     {
2799         bool_t *sr = odr_booldup(assoc->encode, 1);
2800         Odr_int *toget = odr_intdup(assoc->encode, 0);
2801         Z_RecordComposition comp, *compp = 0;
2802
2803         yaz_log(log_requestdetail, "resultCount: " ODR_INT_PRINTF, bsrt->hits);
2804
2805         resp->records = 0;
2806         resp->resultCount = &bsrt->hits;
2807
2808         comp.which = Z_RecordComp_simple;
2809         /* how many records does the user agent want, then? */
2810         if (bsrt->hits < 0)
2811             *toget = 0;
2812         else if (bsrt->hits <= *req->smallSetUpperBound)
2813         {
2814             *toget = bsrt->hits;
2815             if ((comp.u.simple = req->smallSetElementSetNames))
2816                 compp = &comp;
2817         }
2818         else if (bsrt->hits < *req->largeSetLowerBound)
2819         {
2820             *toget = *req->mediumSetPresentNumber;
2821             if (*toget > bsrt->hits)
2822                 *toget = bsrt->hits;
2823             if ((comp.u.simple = req->mediumSetElementSetNames))
2824                 compp = &comp;
2825         }
2826         else
2827             *toget = 0;
2828
2829         if (*toget && !resp->records)
2830         {
2831             Odr_int *presst = odr_intdup(assoc->encode, 0);
2832             /* Call bend_present if defined */
2833             if (assoc->init->bend_present)
2834             {
2835                 bend_present_rr *bprr = (bend_present_rr *)
2836                     nmem_malloc(reqb->request_mem, sizeof(*bprr));
2837                 bprr->setname = req->resultSetName;
2838                 bprr->start = 1;
2839                 bprr->number = odr_int_to_int(*toget);
2840                 bprr->format = req->preferredRecordSyntax;
2841                 bprr->comp = compp;
2842                 bprr->referenceId = req->referenceId;
2843                 bprr->stream = assoc->encode;
2844                 bprr->print = assoc->print;
2845                 bprr->association = assoc;
2846                 bprr->errcode = 0;
2847                 bprr->errstring = NULL;
2848                 (*assoc->init->bend_present)(assoc->backend, bprr);
2849
2850                 if (bprr->errcode)
2851                 {
2852                     resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2853                     *resp->presentStatus = Z_PresentStatus_failure;
2854                 }
2855             }
2856
2857             if (!resp->records)
2858                 resp->records = pack_records(
2859                     assoc, req->resultSetName, 1,
2860                     toget, compp, next, presst, req->referenceId,
2861                     req->preferredRecordSyntax, NULL);
2862             if (!resp->records)
2863                 return 0;
2864             resp->numberOfRecordsReturned = toget;
2865             returnedrecs = *toget;
2866             resp->presentStatus = presst;
2867         }
2868         else
2869         {
2870             if (*resp->resultCount)
2871                 *next = 1;
2872             resp->numberOfRecordsReturned = nulint;
2873             resp->presentStatus = 0;
2874         }
2875         resp->nextResultSetPosition = next;
2876         resp->searchStatus = sr;
2877         resp->resultSetStatus = 0;
2878         if (bsrt->estimated_hit_count)
2879         {
2880             resp->resultSetStatus = odr_intdup(assoc->encode,
2881                                                Z_SearchResponse_estimate);
2882         }
2883         else if (bsrt->partial_resultset)
2884         {
2885             resp->resultSetStatus = odr_intdup(assoc->encode,
2886                                                Z_SearchResponse_subset);
2887         }
2888     }
2889     resp->additionalSearchInfo = bsrt->search_info;
2890
2891     if (log_request)
2892     {
2893         int i;
2894         WRBUF wr = wrbuf_alloc();
2895
2896         for (i = 0 ; i < req->num_databaseNames; i++)
2897         {
2898             if (i)
2899                 wrbuf_printf(wr, "+");
2900             wrbuf_puts(wr, req->databaseNames[i]);
2901         }
2902         wrbuf_printf(wr, " ");
2903
2904         if (bsrt->errcode)
2905             wrbuf_printf(wr, "ERROR %d", bsrt->errcode);
2906         else
2907             wrbuf_printf(wr, "OK " ODR_INT_PRINTF, bsrt->hits);
2908         wrbuf_printf(wr, " %s 1+" ODR_INT_PRINTF " ",
2909                      req->resultSetName, returnedrecs);
2910         yaz_query_to_wrbuf(wr, req->query);
2911
2912         yaz_log(log_request, "Search %s", wrbuf_cstr(wr));
2913         wrbuf_destroy(wr);
2914     }
2915     return apdu;
2916 }
2917
2918 /*
2919  * Maybe we got a little over-friendly when we designed bend_fetch to
2920  * get only one record at a time. Some backends can optimise multiple-record
2921  * fetches, and at any rate, there is some overhead involved in
2922  * all that selecting and hopping around. Problem is, of course, that the
2923  * frontend can't know ahead of time how many records it'll need to
2924  * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
2925  * is downright lousy as a bulk data transfer protocol.
2926  *
2927  * To start with, we'll do the fetching of records from the backend
2928  * in one operation: To save some trips in and out of the event-handler,
2929  * and to simplify the interface to pack_records. At any rate, asynch
2930  * operation is more fun in operations that have an unpredictable execution
2931  * speed - which is normally more true for search than for present.
2932  */
2933 static Z_APDU *process_presentRequest(association *assoc, request *reqb)
2934 {
2935     Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
2936     Z_APDU *apdu;
2937     Z_PresentResponse *resp;
2938     Odr_int *next;
2939     Odr_int *num;
2940     int errcode = 0;
2941
2942     yaz_log(log_requestdetail, "Got PresentRequest.");
2943
2944     resp = (Z_PresentResponse *)odr_malloc(assoc->encode, sizeof(*resp));
2945     resp->records = 0;
2946     resp->presentStatus = odr_intdup(assoc->encode, 0);
2947     if (assoc->init->bend_present)
2948     {
2949         bend_present_rr *bprr = (bend_present_rr *)
2950             nmem_malloc(reqb->request_mem, sizeof(*bprr));
2951         bprr->setname = req->resultSetId;
2952         bprr->start = odr_int_to_int(*req->resultSetStartPoint);
2953         bprr->number = odr_int_to_int(*req->numberOfRecordsRequested);
2954         bprr->format = req->preferredRecordSyntax;
2955         bprr->comp = req->recordComposition;
2956         bprr->referenceId = req->referenceId;
2957         bprr->stream = assoc->encode;
2958         bprr->print = assoc->print;
2959         bprr->association = assoc;
2960         bprr->errcode = 0;
2961         bprr->errstring = NULL;
2962         (*assoc->init->bend_present)(assoc->backend, bprr);
2963
2964         if (bprr->errcode)
2965         {
2966             resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2967             *resp->presentStatus = Z_PresentStatus_failure;
2968             errcode = bprr->errcode;
2969         }
2970     }
2971     apdu = (Z_APDU *)odr_malloc(assoc->encode, sizeof(*apdu));
2972     next = odr_intdup(assoc->encode, 0);
2973     num = odr_intdup(assoc->encode, 0);
2974
2975     apdu->which = Z_APDU_presentResponse;
2976     apdu->u.presentResponse = resp;
2977     resp->referenceId = req->referenceId;
2978     resp->otherInfo = 0;
2979
2980     if (!resp->records)
2981     {
2982         *num = *req->numberOfRecordsRequested;
2983         resp->records =
2984             pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
2985                          num, req->recordComposition, next,
2986                          resp->presentStatus,
2987                          req->referenceId, req->preferredRecordSyntax,
2988                          &errcode);
2989     }
2990     if (log_request)
2991     {
2992         WRBUF wr = wrbuf_alloc();
2993         wrbuf_printf(wr, "Present ");
2994
2995         if (*resp->presentStatus == Z_PresentStatus_failure)
2996             wrbuf_printf(wr, "ERROR %d ", errcode);
2997         else if (*resp->presentStatus == Z_PresentStatus_success)
2998             wrbuf_printf(wr, "OK -  ");
2999         else
3000             wrbuf_printf(wr, "Partial " ODR_INT_PRINTF " - ",
3001                          *resp->presentStatus);
3002
3003         wrbuf_printf(wr, " %s " ODR_INT_PRINTF "+" ODR_INT_PRINTF " ",
3004                 req->resultSetId, *req->resultSetStartPoint,
3005                 *req->numberOfRecordsRequested);
3006         yaz_log(log_request, "%s", wrbuf_cstr(wr) );
3007         wrbuf_destroy(wr);
3008     }
3009     if (!resp->records)
3010         return 0;
3011     resp->numberOfRecordsReturned = num;
3012     resp->nextResultSetPosition = next;
3013
3014     return apdu;
3015 }
3016
3017 /*
3018  * Scan was implemented rather in a hurry, and with support for only the basic
3019  * elements of the service in the backend API. Suggestions are welcome.
3020  */
3021 static Z_APDU *process_scanRequest(association *assoc, request *reqb)
3022 {
3023     Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
3024     Z_APDU *apdu = (Z_APDU *)odr_malloc(assoc->encode, sizeof(*apdu));
3025     Z_ScanResponse *res = (Z_ScanResponse *)
3026         odr_malloc(assoc->encode, sizeof(*res));
3027     Odr_int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
3028     Odr_int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
3029     Z_ListEntries *ents = (Z_ListEntries *)
3030         odr_malloc(assoc->encode, sizeof(*ents));
3031     Z_DiagRecs *diagrecs_p = NULL;
3032     bend_scan_rr *bsrr = (bend_scan_rr *)
3033         odr_malloc(assoc->encode, sizeof(*bsrr));
3034     struct scan_entry *save_entries;
3035     int step_size = 0;
3036
3037     yaz_log(log_requestdetail, "Got ScanRequest");
3038
3039     apdu->which = Z_APDU_scanResponse;
3040     apdu->u.scanResponse = res;
3041     res->referenceId = req->referenceId;
3042
3043     /* if step is absent, set it to 0 */
3044     if (req->stepSize)
3045         step_size = odr_int_to_int(*req->stepSize);
3046
3047     res->stepSize = 0;
3048     res->scanStatus = scanStatus;
3049     res->numberOfEntriesReturned = numberOfEntriesReturned;
3050     res->positionOfTerm = 0;
3051     res->entries = ents;
3052     ents->num_entries = 0;
3053     ents->entries = NULL;
3054     ents->num_nonsurrogateDiagnostics = 0;
3055     ents->nonsurrogateDiagnostics = NULL;
3056     res->attributeSet = 0;
3057     res->otherInfo = 0;
3058
3059     if (req->databaseNames)
3060     {
3061         int i;
3062         for (i = 0; i < req->num_databaseNames; i++)
3063             yaz_log(log_requestdetail, "Database '%s'", req->databaseNames[i]);
3064     }
3065     bsrr->scanClause = 0;
3066     bsrr->errcode = 0;
3067     bsrr->errstring = 0;
3068     bsrr->num_bases = req->num_databaseNames;
3069     bsrr->basenames = req->databaseNames;
3070     bsrr->num_entries = odr_int_to_int(*req->numberOfTermsRequested);
3071     bsrr->term = req->termListAndStartPoint;
3072     bsrr->referenceId = req->referenceId;
3073     bsrr->stream = assoc->encode;
3074     bsrr->print = assoc->print;
3075     bsrr->step_size = &step_size;
3076     bsrr->setname = yaz_oi_get_string_oid(&req->otherInfo,
3077                                           yaz_oid_userinfo_scan_set, 1, 0);
3078     bsrr->entries = 0;
3079     bsrr->extra_args = 0;
3080     bsrr->extra_response_data = 0;
3081     /* For YAZ 2.0 and earlier it was the backend handler that
3082        initialized entries (member display_term did not exist)
3083        YAZ 2.0 and later sets 'entries'  and initialize all members
3084        including 'display_term'. If YAZ 2.0 or later sees that
3085        entries was modified - we assume that it is an old handler and
3086        that 'display_term' is _not_ set.
3087     */
3088     if (bsrr->num_entries > 0)
3089     {
3090         int i;
3091         bsrr->entries = (struct scan_entry *)
3092             odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
3093                        bsrr->num_entries);
3094         for (i = 0; i<bsrr->num_entries; i++)
3095         {
3096             bsrr->entries[i].term = 0;
3097             bsrr->entries[i].occurrences = 0;
3098             bsrr->entries[i].errcode = 0;
3099             bsrr->entries[i].errstring = 0;
3100             bsrr->entries[i].display_term = 0;
3101         }
3102     }
3103     save_entries = bsrr->entries;  /* save it so we can compare later */
3104
3105     bsrr->attributeset = req->attributeSet;
3106     log_scan_term_level(log_requestdetail, req->termListAndStartPoint,
3107                         bsrr->attributeset);
3108     bsrr->term_position = req->preferredPositionInResponse ?
3109         odr_int_to_int(*req->preferredPositionInResponse) : 1;
3110
3111     ((int (*)(void *, bend_scan_rr *))
3112      (*assoc->init->bend_scan))(assoc->backend, bsrr);
3113
3114     if (bsrr->errcode)
3115         diagrecs_p = zget_DiagRecs(assoc->encode,
3116                                    bsrr->errcode, bsrr->errstring);
3117     else
3118     {
3119         int i;
3120         Z_Entry **tab = (Z_Entry **)
3121             odr_malloc(assoc->encode, sizeof(*tab) * bsrr->num_entries);
3122
3123         if (bsrr->status == BEND_SCAN_PARTIAL)
3124             *scanStatus = Z_Scan_partial_5;
3125         else
3126             *scanStatus = Z_Scan_success;
3127         res->stepSize = odr_intdup(assoc->encode, step_size);
3128         ents->entries = tab;
3129         ents->num_entries = bsrr->num_entries;
3130         res->numberOfEntriesReturned = odr_intdup(assoc->encode,
3131                                                    ents->num_entries);
3132         res->positionOfTerm = odr_intdup(assoc->encode, bsrr->term_position);
3133         for (i = 0; i < bsrr->num_entries; i++)
3134         {
3135             Z_Entry *e;
3136             Z_TermInfo *t;
3137
3138             tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
3139             if (bsrr->entries[i].occurrences >= 0)
3140             {
3141                 e->which = Z_Entry_termInfo;
3142                 e->u.termInfo = t = (Z_TermInfo *)
3143                     odr_malloc(assoc->encode, sizeof(*t));
3144                 t->suggestedAttributes = 0;
3145                 t->displayTerm = 0;
3146                 if (save_entries == bsrr->entries &&
3147                     bsrr->entries[i].display_term)
3148                 {
3149                     /* the entries was _not_ set by the handler. So it's
3150                        safe to test for new member display_term. It is
3151                        NULL'ed by us.
3152                     */
3153                     t->displayTerm = odr_strdup(assoc->encode,
3154                                                 bsrr->entries[i].display_term);
3155                 }
3156                 t->alternativeTerm = 0;
3157                 t->byAttributes = 0;
3158                 t->otherTermInfo = 0;
3159                 t->globalOccurrences = &bsrr->entries[i].occurrences;
3160                 t->term = (Z_Term *)
3161                     odr_malloc(assoc->encode, sizeof(*t->term));
3162                 t->term->which = Z_Term_general;
3163                 t->term->u.general =
3164                     odr_create_Odr_oct(assoc->encode,
3165                                        bsrr->entries[i].term,
3166                                        strlen(bsrr->entries[i].term));
3167                 yaz_log(YLOG_DEBUG, "  term #%d: '%s' (" ODR_INT_PRINTF ")", i,
3168                          bsrr->entries[i].term, bsrr->entries[i].occurrences);
3169             }
3170             else
3171             {
3172                 Z_DiagRecs *drecs = zget_DiagRecs(assoc->encode,
3173                                                   bsrr->entries[i].errcode,
3174                                                   bsrr->entries[i].errstring);
3175                 assert(drecs->num_diagRecs == 1);
3176                 e->which = Z_Entry_surrogateDiagnostic;
3177                 assert(drecs->diagRecs[0]);
3178                 e->u.surrogateDiagnostic = drecs->diagRecs[0];
3179             }
3180         }
3181     }
3182     if (diagrecs_p)
3183     {
3184         ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
3185         ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
3186     }
3187     if (log_request)
3188     {
3189         int i;
3190         WRBUF wr = wrbuf_alloc();
3191         wrbuf_printf(wr, "Scan ");
3192         for (i = 0 ; i < req->num_databaseNames; i++)
3193         {
3194             if (i)
3195                 wrbuf_printf(wr, "+");
3196             wrbuf_puts(wr, req->databaseNames[i]);
3197         }
3198
3199         wrbuf_printf(wr, " ");
3200
3201         if (bsrr->errcode)
3202             wr_diag(wr, bsrr->errcode, bsrr->errstring);
3203         else
3204             wrbuf_printf(wr, "OK");
3205
3206         wrbuf_printf(wr, " " ODR_INT_PRINTF " - " ODR_INT_PRINTF "+"
3207                      ODR_INT_PRINTF "+" ODR_INT_PRINTF,
3208                      res->numberOfEntriesReturned ?
3209                      *res->numberOfEntriesReturned : 0,
3210                      (req->preferredPositionInResponse ?
3211                       *req->preferredPositionInResponse : 1),
3212                      *req->numberOfTermsRequested,
3213                      (res->stepSize ? *res->stepSize : 1));
3214
3215         if (bsrr->setname)
3216             wrbuf_printf(wr, "+%s", bsrr->setname);
3217
3218         wrbuf_printf(wr, " ");
3219         yaz_scan_to_wrbuf(wr, req->termListAndStartPoint,
3220                           bsrr->attributeset);
3221         yaz_log(log_request, "%s", wrbuf_cstr(wr) );
3222         wrbuf_destroy(wr);
3223     }
3224     return apdu;
3225 }
3226
3227 static Z_APDU *process_sortRequest(association *assoc, request *reqb)
3228 {
3229     int i;
3230     Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
3231     Z_SortResponse *res = (Z_SortResponse *)
3232         odr_malloc(assoc->encode, sizeof(*res));
3233     bend_sort_rr *bsrr = (bend_sort_rr *)
3234         odr_malloc(assoc->encode, sizeof(*bsrr));
3235
3236     Z_APDU *apdu = (Z_APDU *)odr_malloc(assoc->encode, sizeof(*apdu));
3237
3238     yaz_log(log_requestdetail, "Got SortRequest.");
3239
3240     bsrr->num_input_setnames = req->num_inputResultSetNames;
3241     for (i=0;i<req->num_inputResultSetNames;i++)
3242         yaz_log(log_requestdetail, "Input resultset: '%s'",
3243                 req->inputResultSetNames[i]);
3244     bsrr->input_setnames = req->inputResultSetNames;
3245     bsrr->referenceId = req->referenceId;
3246     bsrr->output_setname = req->sortedResultSetName;
3247     yaz_log(log_requestdetail, "Output resultset: '%s'",
3248                 req->sortedResultSetName);
3249     bsrr->sort_sequence = req->sortSequence;
3250        /*FIXME - dump those sequences too */
3251     bsrr->stream = assoc->encode;
3252     bsrr->print = assoc->print;
3253
3254     bsrr->sort_status = Z_SortResponse_failure;
3255     bsrr->errcode = 0;
3256     bsrr->errstring = 0;
3257
3258     (*assoc->init->bend_sort)(assoc->backend, bsrr);
3259
3260     res->referenceId = bsrr->referenceId;
3261     res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
3262     res->resultSetStatus = 0;
3263     if (bsrr->errcode)
3264     {
3265         Z_DiagRecs *dr = zget_DiagRecs(assoc->encode,
3266                                        bsrr->errcode, bsrr->errstring);
3267         res->diagnostics = dr->diagRecs;
3268         res->num_diagnostics = dr->num_diagRecs;
3269     }
3270     else
3271     {
3272         res->num_diagnostics = 0;
3273         res->diagnostics = 0;
3274     }
3275     res->resultCount = 0;
3276     res->otherInfo = 0;
3277
3278     apdu->which = Z_APDU_sortResponse;
3279     apdu->u.sortResponse = res;
3280     if (log_request)
3281     {
3282         WRBUF wr = wrbuf_alloc();
3283         wrbuf_printf(wr, "Sort ");
3284         if (bsrr->errcode)
3285             wrbuf_printf(wr, " ERROR %d", bsrr->errcode);
3286         else
3287             wrbuf_printf(wr,  "OK -");
3288         wrbuf_printf(wr, " (");
3289         for (i = 0; i<req->num_inputResultSetNames; i++)
3290         {
3291             if (i)
3292                 wrbuf_printf(wr, "+");
3293             wrbuf_puts(wr, req->inputResultSetNames[i]);
3294         }
3295         wrbuf_printf(wr, ")->%s ",req->sortedResultSetName);
3296
3297         yaz_log(log_request, "%s", wrbuf_cstr(wr) );
3298         wrbuf_destroy(wr);
3299     }
3300     return apdu;
3301 }
3302
3303 static Z_APDU *process_deleteRequest(association *assoc, request *reqb)
3304 {
3305     int i;
3306     Z_DeleteResultSetRequest *req =
3307         reqb->apdu_request->u.deleteResultSetRequest;
3308     Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
3309         odr_malloc(assoc->encode, sizeof(*res));
3310     bend_delete_rr *bdrr = (bend_delete_rr *)
3311         odr_malloc(assoc->encode, sizeof(*bdrr));
3312     Z_APDU *apdu = (Z_APDU *)odr_malloc(assoc->encode, sizeof(*apdu));
3313
3314     yaz_log(log_requestdetail, "Got DeleteRequest.");
3315
3316     bdrr->num_setnames = req->num_resultSetList;
3317     bdrr->setnames = req->resultSetList;
3318     for (i = 0; i<req->num_resultSetList; i++)
3319         yaz_log(log_requestdetail, "resultset: '%s'",
3320                 req->resultSetList[i]);
3321     bdrr->stream = assoc->encode;
3322     bdrr->print = assoc->print;
3323     bdrr->function = odr_int_to_int(*req->deleteFunction);
3324     bdrr->referenceId = req->referenceId;
3325     bdrr->statuses = 0;
3326     if (bdrr->num_setnames > 0)
3327     {
3328         bdrr->statuses = (int*)
3329             odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
3330                        bdrr->num_setnames);
3331         for (i = 0; i < bdrr->num_setnames; i++)
3332             bdrr->statuses[i] = 0;
3333     }
3334     (*assoc->init->bend_delete)(assoc->backend, bdrr);
3335
3336     res->referenceId = req->referenceId;
3337
3338     res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
3339
3340     res->deleteListStatuses = 0;
3341     if (bdrr->num_setnames > 0)
3342     {
3343         int i;
3344         res->deleteListStatuses = (Z_ListStatuses *)
3345             odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
3346         res->deleteListStatuses->num = bdrr->num_setnames;
3347         res->deleteListStatuses->elements =
3348             (Z_ListStatus **)
3349             odr_malloc(assoc->encode,
3350                         sizeof(*res->deleteListStatuses->elements) *
3351                         bdrr->num_setnames);
3352         for (i = 0; i<bdrr->num_setnames; i++)
3353         {
3354             res->deleteListStatuses->elements[i] =
3355                 (Z_ListStatus *)
3356                 odr_malloc(assoc->encode,
3357                             sizeof(**res->deleteListStatuses->elements));
3358             res->deleteListStatuses->elements[i]->status =
3359                 odr_intdup(assoc->encode, bdrr->statuses[i]);
3360             res->deleteListStatuses->elements[i]->id =
3361                 odr_strdup(assoc->encode, bdrr->setnames[i]);
3362         }
3363     }
3364     res->numberNotDeleted = 0;
3365     res->bulkStatuses = 0;
3366     res->deleteMessage = 0;
3367     res->otherInfo = 0;
3368
3369     apdu->which = Z_APDU_deleteResultSetResponse;
3370     apdu->u.deleteResultSetResponse = res;
3371     if (log_request)
3372     {
3373         WRBUF wr = wrbuf_alloc();
3374         wrbuf_printf(wr, "Delete ");
3375         if (bdrr->delete_status)
3376             wrbuf_printf(wr, "ERROR %d", bdrr->delete_status);
3377         else
3378             wrbuf_printf(wr, "OK -");
3379         for (i = 0; i<req->num_resultSetList; i++)
3380             wrbuf_printf(wr, " %s ", req->resultSetList[i]);
3381         yaz_log(log_request, "%s", wrbuf_cstr(wr) );
3382         wrbuf_destroy(wr);
3383     }
3384     return apdu;
3385 }
3386
3387 static void process_close(association *assoc, request *reqb)
3388 {
3389     Z_Close *req = reqb->apdu_request->u.close;
3390     static char *reasons[] =
3391     {
3392         "finished",
3393         "shutdown",
3394         "systemProblem",
3395         "costLimit",
3396         "resources",
3397         "securityViolation",
3398         "protocolError",
3399         "lackOfActivity",
3400         "peerAbort",
3401         "unspecified"
3402     };
3403
3404     yaz_log(log_requestdetail, "Got Close, reason %s, message %s",
3405         reasons[*req->closeReason], req->diagnosticInformation ?
3406         req->diagnosticInformation : "NULL");
3407     if (assoc->version < 3) /* to make do_force respond with close */
3408         assoc->version = 3;
3409     do_close_req(assoc, Z_Close_finished,
3410                  "Association terminated by client", reqb);
3411     yaz_log(log_request,"Close OK");
3412 }
3413
3414 static Z_APDU *process_segmentRequest(association *assoc, request *reqb)
3415 {
3416     bend_segment_rr req;
3417
3418     req.segment = reqb->apdu_request->u.segmentRequest;
3419     req.stream = assoc->encode;
3420     req.decode = assoc->decode;
3421     req.print = assoc->print;
3422     req.association = assoc;
3423
3424     (*assoc->init->bend_segment)(assoc->backend, &req);
3425
3426     return 0;
3427 }
3428
3429 static Z_APDU *process_ESRequest(association *assoc, request *reqb)
3430 {
3431     bend_esrequest_rr esrequest;
3432     const char *ext_name = "unknown";
3433
3434     Z_ExtendedServicesRequest *req =
3435         reqb->apdu_request->u.extendedServicesRequest;
3436     Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
3437
3438     Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
3439
3440     esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
3441     esrequest.stream = assoc->encode;
3442     esrequest.decode = assoc->decode;
3443     esrequest.print = assoc->print;
3444     esrequest.errcode = 0;
3445     esrequest.errstring = NULL;
3446     esrequest.association = assoc;
3447     esrequest.taskPackage = 0;
3448     esrequest.referenceId = req->referenceId;
3449
3450     if (esrequest.esr && esrequest.esr->taskSpecificParameters)
3451     {
3452         switch(esrequest.esr->taskSpecificParameters->which)
3453         {
3454         case Z_External_itemOrder:
3455             ext_name = "ItemOrder"; break;
3456         case Z_External_update:
3457             ext_name = "Update"; break;
3458         case Z_External_update0:
3459             ext_name = "Update0"; break;
3460         case Z_External_ESAdmin:
3461             ext_name = "Admin"; break;
3462
3463         }
3464     }
3465
3466     (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
3467
3468     resp->referenceId = req->referenceId;
3469
3470     if (esrequest.errcode == -1)
3471     {
3472         /* Backend service indicates request will be processed */
3473         yaz_log(log_request, "Extended Service: %s (accepted)", ext_name);
3474         *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
3475     }
3476     else if (esrequest.errcode == 0)
3477     {
3478         /* Backend service indicates request will be processed */
3479         yaz_log(log_request, "Extended Service: %s (done)", ext_name);
3480         *resp->operationStatus = Z_ExtendedServicesResponse_done;
3481     }
3482     else
3483     {
3484         Z_DiagRecs *diagRecs =
3485             zget_DiagRecs(assoc->encode, esrequest.errcode,
3486                           esrequest.errstring);
3487         /* Backend indicates error, request will not be processed */
3488         yaz_log(log_request, "Extended Service: %s (failed)", ext_name);
3489         *resp->operationStatus = Z_ExtendedServicesResponse_failure;
3490         resp->num_diagnostics = diagRecs->num_diagRecs;
3491         resp->diagnostics = diagRecs->diagRecs;
3492         if (log_request)
3493         {
3494             WRBUF wr = wrbuf_alloc();
3495             wrbuf_diags(wr, resp->num_diagnostics, resp->diagnostics);
3496             yaz_log(log_request, "EsRequest %s", wrbuf_cstr(wr) );
3497             wrbuf_destroy(wr);
3498         }
3499
3500     }
3501     /* Do something with the members of bend_extendedservice */
3502     if (esrequest.taskPackage)
3503     {
3504         resp->taskPackage = z_ext_record_oid(
3505             assoc->encode, yaz_oid_recsyn_extended,
3506             (const char *)  esrequest.taskPackage, -1);
3507     }
3508     yaz_log(YLOG_DEBUG,"Send the result apdu");
3509     return apdu;
3510 }
3511
3512 int bend_assoc_is_alive(bend_association assoc)
3513 {
3514     if (assoc->state == ASSOC_DEAD)
3515         return 0; /* already marked as dead. Don't check I/O chan anymore */
3516
3517     return iochan_is_alive(assoc->client_chan);
3518 }
3519
3520
3521 /*
3522  * Local variables:
3523  * c-basic-offset: 4
3524  * c-file-style: "Stroustrup"
3525  * indent-tabs-mode: nil
3526  * End:
3527  * vim: shiftwidth=4 tabstop=8 expandtab
3528  */
3529