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