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