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