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