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