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