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