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