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