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