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