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