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