Fixed 523: PQF parser does not properly diagnose @prox syntax errors.
[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.73 2006-03-26 21:00:09 marc 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                 yaz_mime_types_add(types, "js", "application/x-javascript");
1467                 
1468                 yaz_mime_types_add(types, "gif", "image/gif");
1469                 yaz_mime_types_add(types, "png", "image/png");
1470                 yaz_mime_types_add(types, "jpg", "image/jpeg");
1471                 yaz_mime_types_add(types, "jpeg", "image/jpeg");
1472                 
1473                 ctype = yaz_mime_lookup_fname(types, hreq->path);
1474                 if (!ctype)
1475                 {
1476                     yaz_log(YLOG_LOG, "No mime type for %s", hreq->path+1);
1477                     p = z_get_HTTP_Response(o, 404);
1478                 }
1479                 else
1480                 {
1481                     p = z_get_HTTP_Response(o, 200);
1482                     hres = p->u.HTTP_Response;
1483                     hres->content_buf = content_buf;
1484                     hres->content_len = content_size;
1485                     z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1486                 }
1487                 yaz_mime_types_destroy(types);
1488             }
1489         }
1490         r = 1;
1491     }
1492
1493     if (r == 2)
1494     {
1495         r = yaz_srw_decode(hreq, &sr, &soap_package, assoc->decode, &charset);
1496         yaz_log(YLOG_DEBUG, "yaz_srw_decode returned %d", r);
1497     }
1498     if (r == 2)  /* not taken */
1499     {
1500         r = yaz_sru_decode(hreq, &sr, &soap_package, assoc->decode, &charset,
1501                            &diagnostic, &num_diagnostic);
1502         yaz_log(YLOG_DEBUG, "yaz_sru_decode returned %d", r);
1503     }
1504     if (r == 0)  /* decode SRW/SRU OK .. */
1505     {
1506         int http_code = 200;
1507         if (sr->which == Z_SRW_searchRetrieve_request)
1508         {
1509             Z_SRW_PDU *res =
1510                 yaz_srw_get(assoc->encode, Z_SRW_searchRetrieve_response);
1511
1512             stylesheet = sr->u.request->stylesheet;
1513             if (num_diagnostic)
1514             {
1515                 res->u.response->diagnostics = diagnostic;
1516                 res->u.response->num_diagnostics = num_diagnostic;
1517             }
1518             else
1519             {
1520                 srw_bend_search(assoc, req, sr->u.request, res->u.response, 
1521                                 &http_code);
1522             }
1523             if (http_code == 200)
1524                 soap_package->u.generic->p = res;
1525         }
1526         else if (sr->which == Z_SRW_explain_request)
1527         {
1528             Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_explain_response);
1529             stylesheet = sr->u.explain_request->stylesheet;
1530             if (num_diagnostic)
1531             {   
1532                 res->u.explain_response->diagnostics = diagnostic;
1533                 res->u.explain_response->num_diagnostics = num_diagnostic;
1534             }
1535             srw_bend_explain(assoc, req, sr->u.explain_request,
1536                              res->u.explain_response, &http_code);
1537             if (http_code == 200)
1538                 soap_package->u.generic->p = res;
1539         }
1540         else if (sr->which == Z_SRW_scan_request)
1541         {
1542             Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_scan_response);
1543             stylesheet = sr->u.scan_request->stylesheet;
1544             if (num_diagnostic)
1545             {   
1546                 res->u.scan_response->diagnostics = diagnostic;
1547                 res->u.scan_response->num_diagnostics = num_diagnostic;
1548             }
1549             srw_bend_scan(assoc, req, sr->u.scan_request,
1550                           res->u.scan_response, &http_code);
1551             if (http_code == 200)
1552                 soap_package->u.generic->p = res;
1553         }
1554         else if (sr->which == Z_SRW_update_request)
1555         {
1556             Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_update_response);
1557             yaz_log(YLOG_DEBUG, "handling SRW UpdateRequest");
1558             if (num_diagnostic)
1559             {   
1560                 res->u.update_response->diagnostics = diagnostic;
1561                 res->u.update_response->num_diagnostics = num_diagnostic;
1562             }
1563             yaz_log(YLOG_DEBUG, "num_diag = %d", res->u.update_response->num_diagnostics );
1564             srw_bend_update(assoc, req, sr->u.update_request,
1565                             res->u.update_response, &http_code);
1566             if (http_code == 200)
1567                 soap_package->u.generic->p = res;
1568         }
1569         else
1570         {
1571             yaz_log(log_request, "SOAP ERROR"); 
1572             /* FIXME - what error, what query */
1573             http_code = 500;
1574             z_soap_error(assoc->encode, soap_package,
1575                          "SOAP-ENV:Client", "Bad method", 0); 
1576         }
1577         if (http_code == 200 || http_code == 500)
1578         {
1579             static Z_SOAP_Handler soap_handlers[4] = {
1580 #if HAVE_XML2
1581                 {"http://www.loc.gov/zing/srw/", 0,
1582                  (Z_SOAP_fun) yaz_srw_codec},
1583                 {"http://www.loc.gov/zing/srw/v1.0/", 0,
1584                  (Z_SOAP_fun) yaz_srw_codec},
1585                 {"http://www.loc.gov/zing/srw/update/", 0,
1586                  (Z_SOAP_fun) yaz_ucp_codec},
1587 #endif
1588                 {0, 0, 0}
1589             };
1590             char ctype[60];
1591             int ret;
1592             p = z_get_HTTP_Response(o, 200);
1593             hres = p->u.HTTP_Response;
1594
1595             if (!stylesheet)
1596                 stylesheet = assoc->stylesheet;
1597
1598             /* empty stylesheet means NO stylesheet */
1599             if (stylesheet && *stylesheet == '\0')
1600                 stylesheet = 0;
1601
1602             ret = z_soap_codec_enc_xsl(assoc->encode, &soap_package,
1603                                        &hres->content_buf, &hres->content_len,
1604                                        soap_handlers, charset, stylesheet);
1605             hres->code = http_code;
1606
1607             strcpy(ctype, "text/xml");
1608             if (charset)
1609             {
1610                 strcat(ctype, "; charset=");
1611                 strcat(ctype, charset);
1612             }
1613             z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1614         }
1615         else
1616             p = z_get_HTTP_Response(o, http_code);
1617     }
1618
1619     if (p == 0)
1620         p = z_get_HTTP_Response(o, 500);
1621     hres = p->u.HTTP_Response;
1622     if (!strcmp(hreq->version, "1.0")) 
1623     {
1624         const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1625         if (v && !strcmp(v, "Keep-Alive"))
1626             keepalive = 1;
1627         else
1628             keepalive = 0;
1629         hres->version = "1.0";
1630     }
1631     else
1632     {
1633         const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1634         if (v && !strcmp(v, "close"))
1635             keepalive = 0;
1636         else
1637             keepalive = 1;
1638         hres->version = "1.1";
1639     }
1640     if (!keepalive)
1641     {
1642         z_HTTP_header_add(o, &hres->headers, "Connection", "close");
1643         assoc->state = ASSOC_DEAD;
1644         assoc->cs_get_mask = 0;
1645     }
1646     else
1647     {
1648         int t;
1649         const char *alive = z_HTTP_header_lookup(hreq->headers, "Keep-Alive");
1650
1651         if (alive && isdigit(*(const unsigned char *) alive))
1652             t = atoi(alive);
1653         else
1654             t = 15;
1655         if (t < 0 || t > 3600)
1656             t = 3600;
1657         iochan_settimeout(assoc->client_chan,t);
1658         z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1659     }
1660     process_gdu_response(assoc, req, p);
1661 }
1662
1663 static void process_gdu_request(association *assoc, request *req)
1664 {
1665     if (req->gdu_request->which == Z_GDU_Z3950)
1666     {
1667         char *msg = 0;
1668         req->apdu_request = req->gdu_request->u.z3950;
1669         if (process_z_request(assoc, req, &msg) < 0)
1670             do_close_req(assoc, Z_Close_systemProblem, msg, req);
1671     }
1672     else if (req->gdu_request->which == Z_GDU_HTTP_Request)
1673         process_http_request(assoc, req);
1674     else
1675     {
1676         do_close_req(assoc, Z_Close_systemProblem, "bad protocol packet", req);
1677     }
1678 }
1679
1680 /*
1681  * Initiate request processing.
1682  */
1683 static int process_z_request(association *assoc, request *req, char **msg)
1684 {
1685     int fd = -1;
1686     Z_APDU *res;
1687     int retval;
1688     
1689     *msg = "Unknown Error";
1690     assert(req && req->state == REQUEST_IDLE);
1691     if (req->apdu_request->which != Z_APDU_initRequest && !assoc->init)
1692     {
1693         *msg = "Missing InitRequest";
1694         return -1;
1695     }
1696     switch (req->apdu_request->which)
1697     {
1698     case Z_APDU_initRequest:
1699         res = process_initRequest(assoc, req); break;
1700     case Z_APDU_searchRequest:
1701         res = process_searchRequest(assoc, req, &fd); break;
1702     case Z_APDU_presentRequest:
1703         res = process_presentRequest(assoc, req, &fd); break;
1704     case Z_APDU_scanRequest:
1705         if (assoc->init->bend_scan)
1706             res = process_scanRequest(assoc, req, &fd);
1707         else
1708         {
1709             *msg = "Cannot handle Scan APDU";
1710             return -1;
1711         }
1712         break;
1713     case Z_APDU_extendedServicesRequest:
1714         if (assoc->init->bend_esrequest)
1715             res = process_ESRequest(assoc, req, &fd);
1716         else
1717         {
1718             *msg = "Cannot handle Extended Services APDU";
1719             return -1;
1720         }
1721         break;
1722     case Z_APDU_sortRequest:
1723         if (assoc->init->bend_sort)
1724             res = process_sortRequest(assoc, req, &fd);
1725         else
1726         {
1727             *msg = "Cannot handle Sort APDU";
1728             return -1;
1729         }
1730         break;
1731     case Z_APDU_close:
1732         process_close(assoc, req);
1733         return 0;
1734     case Z_APDU_deleteResultSetRequest:
1735         if (assoc->init->bend_delete)
1736             res = process_deleteRequest(assoc, req, &fd);
1737         else
1738         {
1739             *msg = "Cannot handle Delete APDU";
1740             return -1;
1741         }
1742         break;
1743     case Z_APDU_segmentRequest:
1744         if (assoc->init->bend_segment)
1745         {
1746             res = process_segmentRequest (assoc, req);
1747         }
1748         else
1749         {
1750             *msg = "Cannot handle Segment APDU";
1751             return -1;
1752         }
1753         break;
1754     case Z_APDU_triggerResourceControlRequest:
1755         return 0;
1756     default:
1757         *msg = "Bad APDU received";
1758         return -1;
1759     }
1760     if (res)
1761     {
1762         yaz_log(YLOG_DEBUG, "  result immediately available");
1763         retval = process_z_response(assoc, req, res);
1764     }
1765     else if (fd < 0)
1766     {
1767         yaz_log(YLOG_DEBUG, "  result unavailble");
1768         retval = 0;
1769     }
1770     else /* no result yet - one will be provided later */
1771     {
1772         IOCHAN chan;
1773
1774         /* Set up an I/O handler for the fd supplied by the backend */
1775
1776         yaz_log(YLOG_DEBUG, "   establishing handler for result");
1777         req->state = REQUEST_PENDING;
1778         if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT, 0)))
1779             abort();
1780         iochan_setdata(chan, assoc);
1781         retval = 0;
1782     }
1783     return retval;
1784 }
1785
1786 /*
1787  * Handle message from the backend.
1788  */
1789 void backend_response(IOCHAN i, int event)
1790 {
1791     association *assoc = (association *)iochan_getdata(i);
1792     request *req = request_head(&assoc->incoming);
1793     Z_APDU *res;
1794     int fd;
1795
1796     yaz_log(YLOG_DEBUG, "backend_response");
1797     assert(assoc && req && req->state != REQUEST_IDLE);
1798     /* determine what it is we're waiting for */
1799     switch (req->apdu_request->which)
1800     {
1801         case Z_APDU_searchRequest:
1802             res = response_searchRequest(assoc, req, 0, &fd); break;
1803 #if 0
1804         case Z_APDU_presentRequest:
1805             res = response_presentRequest(assoc, req, 0, &fd); break;
1806         case Z_APDU_scanRequest:
1807             res = response_scanRequest(assoc, req, 0, &fd); break;
1808 #endif
1809         default:
1810             yaz_log(YLOG_FATAL, "Serious programmer's lapse or bug");
1811             abort();
1812     }
1813     if ((res && process_z_response(assoc, req, res) < 0) || fd < 0)
1814     {
1815         yaz_log(YLOG_WARN, "Fatal error when talking to backend");
1816         do_close(assoc, Z_Close_systemProblem, 0);
1817         iochan_destroy(i);
1818         return;
1819     }
1820     else if (!res) /* no result yet - try again later */
1821     {
1822         yaz_log(YLOG_DEBUG, "   no result yet");
1823         iochan_setfd(i, fd); /* in case fd has changed */
1824     }
1825 }
1826
1827 /*
1828  * Encode response, and transfer the request structure to the outgoing queue.
1829  */
1830 static int process_gdu_response(association *assoc, request *req, Z_GDU *res)
1831 {
1832     odr_setbuf(assoc->encode, req->response, req->size_response, 1);
1833
1834     if (assoc->print)
1835     {
1836         if (!z_GDU(assoc->print, &res, 0, 0))
1837             yaz_log(YLOG_WARN, "ODR print error: %s", 
1838                 odr_errmsg(odr_geterror(assoc->print)));
1839         odr_reset(assoc->print);
1840     }
1841     if (!z_GDU(assoc->encode, &res, 0, 0))
1842     {
1843         yaz_log(YLOG_WARN, "ODR error when encoding PDU: %s [element %s]",
1844                 odr_errmsg(odr_geterror(assoc->decode)),
1845                 odr_getelement(assoc->decode));
1846         return -1;
1847     }
1848     req->response = odr_getbuf(assoc->encode, &req->len_response,
1849         &req->size_response);
1850     odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
1851     odr_reset(assoc->encode);
1852     req->state = REQUEST_IDLE;
1853     request_enq(&assoc->outgoing, req);
1854     /* turn the work over to the ir_session handler */
1855     iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
1856     assoc->cs_put_mask = EVENT_OUTPUT;
1857     /* Is there more work to be done? give that to the input handler too */
1858 #if 1
1859     if (request_head(&assoc->incoming))
1860     {
1861         yaz_log (YLOG_DEBUG, "more work to be done");
1862         iochan_setevent(assoc->client_chan, EVENT_WORK);
1863     }
1864 #endif
1865     return 0;
1866 }
1867
1868 /*
1869  * Encode response, and transfer the request structure to the outgoing queue.
1870  */
1871 static int process_z_response(association *assoc, request *req, Z_APDU *res)
1872 {
1873     Z_GDU *gres = (Z_GDU *) odr_malloc(assoc->encode, sizeof(*res));
1874     gres->which = Z_GDU_Z3950;
1875     gres->u.z3950 = res;
1876
1877     return process_gdu_response(assoc, req, gres);
1878 }
1879
1880 static char *get_vhost(Z_OtherInformation *otherInfo)
1881 {
1882     return yaz_oi_get_string_oidval(&otherInfo, VAL_PROXY, 1, 0);
1883 }
1884
1885 /*
1886  * Handle init request.
1887  * At the moment, we don't check the options
1888  * anywhere else in the code - we just try not to do anything that would
1889  * break a naive client. We'll toss 'em into the association block when
1890  * we need them there.
1891  */
1892 static Z_APDU *process_initRequest(association *assoc, request *reqb)
1893 {
1894     Z_InitRequest *req = reqb->apdu_request->u.initRequest;
1895     Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
1896     Z_InitResponse *resp = apdu->u.initResponse;
1897     bend_initresult *binitres;
1898     char *version;
1899     char options[140];
1900     statserv_options_block *cb = 0;  /* by default no control for backend */
1901
1902     if (control_association(assoc, get_vhost(req->otherInfo), 1))
1903         cb = statserv_getcontrol();  /* got control block for backend */
1904
1905     if (cb && assoc->backend)
1906         (*cb->bend_close)(assoc->backend);
1907
1908     yaz_log(log_requestdetail, "Got initRequest");
1909     if (req->implementationId)
1910         yaz_log(log_requestdetail, "Id:        %s",
1911                 req->implementationId);
1912     if (req->implementationName)
1913         yaz_log(log_requestdetail, "Name:      %s",
1914                 req->implementationName);
1915     if (req->implementationVersion)
1916         yaz_log(log_requestdetail, "Version:   %s",
1917                 req->implementationVersion);
1918     
1919     assoc_init_reset(assoc);
1920
1921     assoc->init->auth = req->idAuthentication;
1922     assoc->init->referenceId = req->referenceId;
1923
1924     if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
1925     {
1926         Z_CharSetandLanguageNegotiation *negotiation =
1927             yaz_get_charneg_record (req->otherInfo);
1928         if (negotiation &&
1929             negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
1930             assoc->init->charneg_request = negotiation;
1931     }
1932
1933     assoc->backend = 0;
1934     if (cb)
1935     {
1936         if (req->implementationVersion)
1937             yaz_log(log_requestdetail, "Config:    %s",
1938                     cb->configname);
1939     
1940         iochan_settimeout(assoc->client_chan, cb->idle_timeout * 60);
1941         
1942         /* we have a backend control block, so call that init function */
1943         if (!(binitres = (*cb->bend_init)(assoc->init)))
1944         {
1945             yaz_log(YLOG_WARN, "Bad response from backend.");
1946             return 0;
1947         }
1948         assoc->backend = binitres->handle;
1949     }
1950     else
1951     {
1952         /* no backend. return error */
1953         binitres = odr_malloc(assoc->encode, sizeof(*binitres));
1954         binitres->errstring = 0;
1955         binitres->errcode = YAZ_BIB1_PERMANENT_SYSTEM_ERROR;
1956         iochan_settimeout(assoc->client_chan, 10);
1957     }
1958     if ((assoc->init->bend_sort))
1959         yaz_log (YLOG_DEBUG, "Sort handler installed");
1960     if ((assoc->init->bend_search))
1961         yaz_log (YLOG_DEBUG, "Search handler installed");
1962     if ((assoc->init->bend_present))
1963         yaz_log (YLOG_DEBUG, "Present handler installed");   
1964     if ((assoc->init->bend_esrequest))
1965         yaz_log (YLOG_DEBUG, "ESRequest handler installed");   
1966     if ((assoc->init->bend_delete))
1967         yaz_log (YLOG_DEBUG, "Delete handler installed");   
1968     if ((assoc->init->bend_scan))
1969         yaz_log (YLOG_DEBUG, "Scan handler installed");   
1970     if ((assoc->init->bend_segment))
1971         yaz_log (YLOG_DEBUG, "Segment handler installed");   
1972     
1973     resp->referenceId = req->referenceId;
1974     *options = '\0';
1975     /* let's tell the client what we can do */
1976     if (ODR_MASK_GET(req->options, Z_Options_search))
1977     {
1978         ODR_MASK_SET(resp->options, Z_Options_search);
1979         strcat(options, "srch");
1980     }
1981     if (ODR_MASK_GET(req->options, Z_Options_present))
1982     {
1983         ODR_MASK_SET(resp->options, Z_Options_present);
1984         strcat(options, " prst");
1985     }
1986     if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
1987         assoc->init->bend_delete)
1988     {
1989         ODR_MASK_SET(resp->options, Z_Options_delSet);
1990         strcat(options, " del");
1991     }
1992     if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
1993         assoc->init->bend_esrequest)
1994     {
1995         ODR_MASK_SET(resp->options, Z_Options_extendedServices);
1996         strcat (options, " extendedServices");
1997     }
1998     if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
1999     {
2000         ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
2001         strcat(options, " namedresults");
2002     }
2003     if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
2004     {
2005         ODR_MASK_SET(resp->options, Z_Options_scan);
2006         strcat(options, " scan");
2007     }
2008     if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
2009     {
2010         ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
2011         strcat(options, " concurrop");
2012     }
2013     if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
2014     {
2015         ODR_MASK_SET(resp->options, Z_Options_sort);
2016         strcat(options, " sort");
2017     }
2018
2019     if (ODR_MASK_GET(req->options, Z_Options_negotiationModel)
2020         && assoc->init->charneg_response)
2021     {
2022         Z_OtherInformation **p;
2023         Z_OtherInformationUnit *p0;
2024         
2025         yaz_oi_APDU(apdu, &p);
2026         
2027         if ((p0=yaz_oi_update(p, assoc->encode, NULL, 0, 0))) {
2028             ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
2029             
2030             p0->which = Z_OtherInfo_externallyDefinedInfo;
2031             p0->information.externallyDefinedInfo =
2032                 assoc->init->charneg_response;
2033         }
2034         ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
2035         strcat(options, " negotiation");
2036     }
2037         
2038     ODR_MASK_SET(resp->options, Z_Options_triggerResourceCtrl);
2039
2040     if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
2041     {
2042         ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
2043         assoc->version = 1; /* 1 & 2 are equivalent */
2044     }
2045     if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
2046     {
2047         ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
2048         assoc->version = 2;
2049     }
2050     if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
2051     {
2052         ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
2053         assoc->version = 3;
2054     }
2055
2056     yaz_log(log_requestdetail, "Negotiated to v%d: %s", assoc->version, options);
2057     assoc->maximumRecordSize = *req->maximumRecordSize;
2058
2059     if (cb && assoc->maximumRecordSize > cb->maxrecordsize)
2060         assoc->maximumRecordSize = cb->maxrecordsize;
2061     assoc->preferredMessageSize = *req->preferredMessageSize;
2062     if (assoc->preferredMessageSize > assoc->maximumRecordSize)
2063         assoc->preferredMessageSize = assoc->maximumRecordSize;
2064
2065     resp->preferredMessageSize = &assoc->preferredMessageSize;
2066     resp->maximumRecordSize = &assoc->maximumRecordSize;
2067
2068     resp->implementationId = odr_prepend(assoc->encode,
2069                 assoc->init->implementation_id,
2070                 resp->implementationId);
2071
2072     resp->implementationName = odr_prepend(assoc->encode,
2073                 assoc->init->implementation_name,
2074                 odr_prepend(assoc->encode, "GFS", resp->implementationName));
2075
2076     version = odr_strdup(assoc->encode, "$Revision: 1.73 $");
2077     if (strlen(version) > 10)   /* check for unexpanded CVS strings */
2078         version[strlen(version)-2] = '\0';
2079     resp->implementationVersion = odr_prepend(assoc->encode,
2080                 assoc->init->implementation_version,
2081                 odr_prepend(assoc->encode, &version[11],
2082                             resp->implementationVersion));
2083
2084     if (binitres->errcode)
2085     {
2086         assoc->state = ASSOC_DEAD;
2087         resp->userInformationField =
2088             init_diagnostics(assoc->encode, binitres->errcode,
2089                              binitres->errstring);
2090         *resp->result = 0;
2091     }
2092     if (log_request)
2093     {
2094         if (!req->idAuthentication)
2095             yaz_log(log_request, "Auth none");
2096         else if (req->idAuthentication->which == Z_IdAuthentication_open)
2097         {
2098             const char *open = req->idAuthentication->u.open;
2099             const char *slash = strchr(open, '/');
2100             int len;
2101             if (slash)
2102                 len = slash - open;
2103             else
2104                 len = strlen(open);
2105                 yaz_log(log_request, "Auth open %.*s", len, open);
2106         }
2107         else if (req->idAuthentication->which == Z_IdAuthentication_idPass)
2108         {
2109             const char *user = req->idAuthentication->u.idPass->userId;
2110             const char *group = req->idAuthentication->u.idPass->groupId;
2111             yaz_log(log_request, "Auth idPass %s %s",
2112                     user ? user : "-", group ? group : "-");
2113         }
2114         else if (req->idAuthentication->which 
2115                  == Z_IdAuthentication_anonymous)
2116         {
2117             yaz_log(log_request, "Auth anonymous");
2118         }
2119         else
2120         {
2121             yaz_log(log_request, "Auth other");
2122         }
2123     }
2124     if (log_request)
2125     {
2126         WRBUF wr = wrbuf_alloc();
2127         wrbuf_printf(wr, "Init ");
2128         if (binitres->errcode)
2129             wrbuf_printf(wr, "ERROR %d", binitres->errcode);
2130         else
2131             wrbuf_printf(wr, "OK -");
2132         wrbuf_printf(wr, " ID:%s Name:%s Version:%s",
2133                      (req->implementationId ? req->implementationId :"-"), 
2134                      (req->implementationName ?
2135                       req->implementationName : "-"),
2136                      (req->implementationVersion ?
2137                       req->implementationVersion : "-")
2138             );
2139         yaz_log(log_request, "%s", wrbuf_buf(wr));
2140         wrbuf_free(wr, 1);
2141     }
2142     return apdu;
2143 }
2144
2145 /*
2146  * Set the specified `errcode' and `errstring' into a UserInfo-1
2147  * external to be returned to the client in accordance with Z35.90
2148  * Implementor Agreement 5 (Returning diagnostics in an InitResponse):
2149  *      http://lcweb.loc.gov/z3950/agency/agree/initdiag.html
2150  */
2151 static Z_External *init_diagnostics(ODR odr, int error, const char *addinfo)
2152 {
2153     yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2154         addinfo ? " -- " : "", addinfo ? addinfo : "");
2155     return zget_init_diagnostics(odr, error, addinfo);
2156 }
2157
2158 /*
2159  * nonsurrogate diagnostic record.
2160  */
2161 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
2162 {
2163     Z_Records *rec = (Z_Records *) odr_malloc (assoc->encode, sizeof(*rec));
2164
2165     yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2166             addinfo ? " -- " : "", addinfo ? addinfo : "");
2167
2168     rec->which = Z_Records_NSD;
2169     rec->u.nonSurrogateDiagnostic = zget_DefaultDiagFormat(assoc->encode,
2170                                                            error, addinfo);
2171     return rec;
2172 }
2173
2174 /*
2175  * surrogate diagnostic.
2176  */
2177 static Z_NamePlusRecord *surrogatediagrec(association *assoc, 
2178                                           const char *dbname,
2179                                           int error, const char *addinfo)
2180 {
2181     yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2182             addinfo ? " -- " : "", addinfo ? addinfo : "");
2183     return zget_surrogateDiagRec(assoc->encode, dbname, error, addinfo);
2184 }
2185
2186 static Z_Records *pack_records(association *a, char *setname, int start,
2187                                int *num, Z_RecordComposition *comp,
2188                                int *next, int *pres, oid_value format,
2189                                Z_ReferenceId *referenceId,
2190                                int *oid, int *errcode)
2191 {
2192     int recno, total_length = 0, toget = *num, dumped_records = 0;
2193     Z_Records *records =
2194         (Z_Records *) odr_malloc (a->encode, sizeof(*records));
2195     Z_NamePlusRecordList *reclist =
2196         (Z_NamePlusRecordList *) odr_malloc (a->encode, sizeof(*reclist));
2197     Z_NamePlusRecord **list =
2198         (Z_NamePlusRecord **) odr_malloc (a->encode, sizeof(*list) * toget);
2199
2200     records->which = Z_Records_DBOSD;
2201     records->u.databaseOrSurDiagnostics = reclist;
2202     reclist->num_records = 0;
2203     reclist->records = list;
2204     *pres = Z_PresentStatus_success;
2205     *num = 0;
2206     *next = 0;
2207
2208     yaz_log(log_requestdetail, "Request to pack %d+%d %s", start, toget, setname);
2209     yaz_log(log_requestdetail, "pms=%d, mrs=%d", a->preferredMessageSize,
2210         a->maximumRecordSize);
2211     for (recno = start; reclist->num_records < toget; recno++)
2212     {
2213         bend_fetch_rr freq;
2214         Z_NamePlusRecord *thisrec;
2215         int this_length = 0;
2216         /*
2217          * we get the number of bytes allocated on the stream before any
2218          * allocation done by the backend - this should give us a reasonable
2219          * idea of the total size of the data so far.
2220          */
2221         total_length = odr_total(a->encode) - dumped_records;
2222         freq.errcode = 0;
2223         freq.errstring = 0;
2224         freq.basename = 0;
2225         freq.len = 0;
2226         freq.record = 0;
2227         freq.last_in_set = 0;
2228         freq.setname = setname;
2229         freq.surrogate_flag = 0;
2230         freq.number = recno;
2231         freq.comp = comp;
2232         freq.request_format = format;
2233         freq.request_format_raw = oid;
2234         freq.output_format = format;
2235         freq.output_format_raw = 0;
2236         freq.stream = a->encode;
2237         freq.print = a->print;
2238         freq.referenceId = referenceId;
2239         freq.schema = 0;
2240         (*a->init->bend_fetch)(a->backend, &freq);
2241
2242         *next = freq.last_in_set ? 0 : recno + 1;
2243
2244         /* backend should be able to signal whether error is system-wide
2245            or only pertaining to current record */
2246         if (freq.errcode)
2247         {
2248             if (!freq.surrogate_flag)
2249             {
2250                 char s[20];
2251                 *pres = Z_PresentStatus_failure;
2252                 /* for 'present request out of range',
2253                    set addinfo to record position if not set */
2254                 if (freq.errcode == YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE  && 
2255                                 freq.errstring == 0)
2256                 {
2257                     sprintf (s, "%d", recno);
2258                     freq.errstring = s;
2259                 }
2260                 if (errcode)
2261                     *errcode = freq.errcode;
2262                 return diagrec(a, freq.errcode, freq.errstring);
2263             }
2264             reclist->records[reclist->num_records] =
2265                 surrogatediagrec(a, freq.basename, freq.errcode,
2266                                  freq.errstring);
2267             reclist->num_records++;
2268             continue;
2269         }
2270         if (freq.record == 0)  /* no error and no record ? */
2271         {
2272             *next = 0;   /* signal end-of-set and stop */
2273             break;
2274         }
2275         if (freq.len >= 0)
2276             this_length = freq.len;
2277         else
2278             this_length = odr_total(a->encode) - total_length - dumped_records;
2279         yaz_log(YLOG_DEBUG, "  fetched record, len=%d, total=%d dumped=%d",
2280             this_length, total_length, dumped_records);
2281         if (a->preferredMessageSize > 0 &&
2282                 this_length + total_length > a->preferredMessageSize)
2283         {
2284             /* record is small enough, really */
2285             if (this_length <= a->preferredMessageSize && recno > start)
2286             {
2287                 yaz_log(log_requestdetail, "  Dropped last normal-sized record");
2288                 *pres = Z_PresentStatus_partial_2;
2289                 break;
2290             }
2291             /* record can only be fetched by itself */
2292             if (this_length < a->maximumRecordSize)
2293             {
2294                 yaz_log(log_requestdetail, "  Record > prefmsgsz");
2295                 if (toget > 1)
2296                 {
2297                     yaz_log(YLOG_DEBUG, "  Dropped it");
2298                     reclist->records[reclist->num_records] =
2299                          surrogatediagrec(a, freq.basename, 16, 0);
2300                     reclist->num_records++;
2301                     dumped_records += this_length;
2302                     continue;
2303                 }
2304             }
2305             else /* too big entirely */
2306             {
2307                 yaz_log(log_requestdetail, "Record > maxrcdsz this=%d max=%d",
2308                         this_length, a->maximumRecordSize);
2309                 reclist->records[reclist->num_records] =
2310                     surrogatediagrec(a, freq.basename, 17, 0);
2311                 reclist->num_records++;
2312                 dumped_records += this_length;
2313                 continue;
2314             }
2315         }
2316
2317         if (!(thisrec = (Z_NamePlusRecord *)
2318               odr_malloc(a->encode, sizeof(*thisrec))))
2319             return 0;
2320         if (freq.basename)
2321             thisrec->databaseName = odr_strdup(a->encode, freq.basename);
2322         else
2323             thisrec->databaseName = 0;
2324         thisrec->which = Z_NamePlusRecord_databaseRecord;
2325
2326         if (freq.output_format_raw)
2327         {
2328             struct oident *ident = oid_getentbyoid(freq.output_format_raw);
2329             freq.output_format = ident->value;
2330         }
2331         thisrec->u.databaseRecord = z_ext_record(a->encode, freq.output_format,
2332                                                  freq.record, freq.len);
2333         if (!thisrec->u.databaseRecord)
2334             return 0;
2335         reclist->records[reclist->num_records] = thisrec;
2336         reclist->num_records++;
2337     }
2338     *num = reclist->num_records;
2339     return records;
2340 }
2341
2342 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
2343     int *fd)
2344 {
2345     Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2346     bend_search_rr *bsrr = 
2347         (bend_search_rr *)nmem_malloc (reqb->request_mem, sizeof(*bsrr));
2348     
2349     yaz_log(log_requestdetail, "Got SearchRequest.");
2350     bsrr->fd = fd;
2351     bsrr->request = reqb;
2352     bsrr->association = assoc;
2353     bsrr->referenceId = req->referenceId;
2354     save_referenceId (reqb, bsrr->referenceId);
2355     bsrr->srw_sortKeys = 0;
2356     bsrr->srw_setname = 0;
2357     bsrr->srw_setnameIdleTime = 0;
2358
2359     yaz_log (log_requestdetail, "ResultSet '%s'", req->resultSetName);
2360     if (req->databaseNames)
2361     {
2362         int i;
2363         for (i = 0; i < req->num_databaseNames; i++)
2364             yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
2365     }
2366
2367     yaz_log_zquery_level(log_requestdetail,req->query);
2368
2369     if (assoc->init->bend_search)
2370     {
2371         bsrr->setname = req->resultSetName;
2372         bsrr->replace_set = *req->replaceIndicator;
2373         bsrr->num_bases = req->num_databaseNames;
2374         bsrr->basenames = req->databaseNames;
2375         bsrr->query = req->query;
2376         bsrr->stream = assoc->encode;
2377         nmem_transfer(bsrr->stream->mem, reqb->request_mem);
2378         bsrr->decode = assoc->decode;
2379         bsrr->print = assoc->print;
2380         bsrr->hits = 0;
2381         bsrr->errcode = 0;
2382         bsrr->errstring = NULL;
2383         bsrr->search_info = NULL;
2384
2385         if (assoc->cql_transform &&
2386             req->query->which == Z_Query_type_104 &&
2387             req->query->u.type_104->which == Z_External_CQL)
2388         {
2389             /* have a CQL query and a CQL to PQF transform .. */
2390             int srw_errcode = 
2391                 cql2pqf(bsrr->stream, req->query->u.type_104->u.cql,
2392                         assoc->cql_transform, bsrr->query);
2393             if (srw_errcode)
2394                 bsrr->errcode = yaz_diag_srw_to_bib1(srw_errcode);
2395         }
2396         if (!bsrr->errcode)
2397             (assoc->init->bend_search)(assoc->backend, bsrr);
2398         if (!bsrr->request)  /* backend not ready with the search response */
2399             return 0;  /* should not be used any more */
2400     }
2401     else
2402     { 
2403         /* FIXME - make a diagnostic for it */
2404         yaz_log(YLOG_WARN,"Search not supported ?!?!");
2405     }
2406     return response_searchRequest(assoc, reqb, bsrr, fd);
2407 }
2408
2409 int bend_searchresponse(void *handle, bend_search_rr *bsrr) {return 0;}
2410
2411 /*
2412  * Prepare a searchresponse based on the backend results. We probably want
2413  * to look at making the fetching of records nonblocking as well, but
2414  * so far, we'll keep things simple.
2415  * If bsrt is null, that means we're called in response to a communications
2416  * event, and we'll have to get the response for ourselves.
2417  */
2418 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
2419     bend_search_rr *bsrt, int *fd)
2420 {
2421     Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2422     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2423     Z_SearchResponse *resp = (Z_SearchResponse *)
2424         odr_malloc (assoc->encode, sizeof(*resp));
2425     int *nulint = odr_intdup (assoc->encode, 0);
2426     bool_t *sr = odr_intdup(assoc->encode, 1);
2427     int *next = odr_intdup(assoc->encode, 0);
2428     int *none = odr_intdup(assoc->encode, Z_SearchResponse_none);
2429     int returnedrecs=0;
2430
2431     apdu->which = Z_APDU_searchResponse;
2432     apdu->u.searchResponse = resp;
2433     resp->referenceId = req->referenceId;
2434     resp->additionalSearchInfo = 0;
2435     resp->otherInfo = 0;
2436     *fd = -1;
2437     if (!bsrt && !bend_searchresponse(assoc->backend, bsrt))
2438     {
2439         yaz_log(YLOG_FATAL, "Bad result from backend");
2440         return 0;
2441     }
2442     else if (bsrt->errcode)
2443     {
2444         resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
2445         resp->resultCount = nulint;
2446         resp->numberOfRecordsReturned = nulint;
2447         resp->nextResultSetPosition = nulint;
2448         resp->searchStatus = nulint;
2449         resp->resultSetStatus = none;
2450         resp->presentStatus = 0;
2451     }
2452     else
2453     {
2454         int *toget = odr_intdup(assoc->encode, 0);
2455         int *presst = odr_intdup(assoc->encode, 0);
2456         Z_RecordComposition comp, *compp = 0;
2457
2458         yaz_log (log_requestdetail, "resultCount: %d", bsrt->hits);
2459
2460         resp->records = 0;
2461         resp->resultCount = &bsrt->hits;
2462
2463         comp.which = Z_RecordComp_simple;
2464         /* how many records does the user agent want, then? */
2465         if (bsrt->hits <= *req->smallSetUpperBound)
2466         {
2467             *toget = bsrt->hits;
2468             if ((comp.u.simple = req->smallSetElementSetNames))
2469                 compp = &comp;
2470         }
2471         else if (bsrt->hits < *req->largeSetLowerBound)
2472         {
2473             *toget = *req->mediumSetPresentNumber;
2474             if (*toget > bsrt->hits)
2475                 *toget = bsrt->hits;
2476             if ((comp.u.simple = req->mediumSetElementSetNames))
2477                 compp = &comp;
2478         }
2479         else
2480             *toget = 0;
2481
2482         if (*toget && !resp->records)
2483         {
2484             oident *prefformat;
2485             oid_value form;
2486
2487             if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
2488                 form = VAL_NONE;
2489             else
2490                 form = prefformat->value;
2491             resp->records = pack_records(assoc, req->resultSetName, 1,
2492                                          toget, compp, next, presst, form, req->referenceId,
2493                                          req->preferredRecordSyntax, NULL);
2494             if (!resp->records)
2495                 return 0;
2496             resp->numberOfRecordsReturned = toget;
2497             returnedrecs = *toget;
2498             resp->nextResultSetPosition = next;
2499             resp->searchStatus = sr;
2500             resp->resultSetStatus = 0;
2501             resp->presentStatus = presst;
2502         }
2503         else
2504         {
2505             if (*resp->resultCount)
2506                 *next = 1;
2507             resp->numberOfRecordsReturned = nulint;
2508             resp->nextResultSetPosition = next;
2509             resp->searchStatus = sr;
2510             resp->resultSetStatus = 0;
2511             resp->presentStatus = 0;
2512         }
2513     }
2514     resp->additionalSearchInfo = bsrt->search_info;
2515
2516     if (log_request)
2517     {
2518         WRBUF wr = wrbuf_alloc();
2519         if (bsrt->errcode)
2520             wrbuf_printf(wr, "ERROR %d", bsrt->errcode);
2521         else
2522             wrbuf_printf(wr, "OK %d", bsrt->hits);
2523         wrbuf_printf(wr, " %s 1+%d ",
2524                      req->resultSetName, returnedrecs);
2525         yaz_query_to_wrbuf(wr, req->query);
2526         
2527         yaz_log(log_request, "Search %s", wrbuf_buf(wr));
2528         wrbuf_free(wr, 1);
2529     }
2530     return apdu;
2531 }
2532
2533 /*
2534  * Maybe we got a little over-friendly when we designed bend_fetch to
2535  * get only one record at a time. Some backends can optimise multiple-record
2536  * fetches, and at any rate, there is some overhead involved in
2537  * all that selecting and hopping around. Problem is, of course, that the
2538  * frontend can't know ahead of time how many records it'll need to
2539  * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
2540  * is downright lousy as a bulk data transfer protocol.
2541  *
2542  * To start with, we'll do the fetching of records from the backend
2543  * in one operation: To save some trips in and out of the event-handler,
2544  * and to simplify the interface to pack_records. At any rate, asynch
2545  * operation is more fun in operations that have an unpredictable execution
2546  * speed - which is normally more true for search than for present.
2547  */
2548 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
2549                                       int *fd)
2550 {
2551     Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
2552     oident *prefformat;
2553     oid_value form;
2554     Z_APDU *apdu;
2555     Z_PresentResponse *resp;
2556     int *next;
2557     int *num;
2558     int errcode = 0;
2559     const char *errstring = 0;
2560
2561     yaz_log(log_requestdetail, "Got PresentRequest.");
2562
2563     if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
2564         form = VAL_NONE;
2565     else
2566         form = prefformat->value;
2567     resp = (Z_PresentResponse *)odr_malloc (assoc->encode, sizeof(*resp));
2568     resp->records = 0;
2569     resp->presentStatus = odr_intdup(assoc->encode, 0);
2570     if (assoc->init->bend_present)
2571     {
2572         bend_present_rr *bprr = (bend_present_rr *)
2573             nmem_malloc (reqb->request_mem, sizeof(*bprr));
2574         bprr->setname = req->resultSetId;
2575         bprr->start = *req->resultSetStartPoint;
2576         bprr->number = *req->numberOfRecordsRequested;
2577         bprr->format = form;
2578         bprr->comp = req->recordComposition;
2579         bprr->referenceId = req->referenceId;
2580         bprr->stream = assoc->encode;
2581         bprr->print = assoc->print;
2582         bprr->request = reqb;
2583         bprr->association = assoc;
2584         bprr->errcode = 0;
2585         bprr->errstring = NULL;
2586         (*assoc->init->bend_present)(assoc->backend, bprr);
2587         
2588         if (!bprr->request)
2589             return 0; /* should not happen */
2590         if (bprr->errcode)
2591         {
2592             resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2593             *resp->presentStatus = Z_PresentStatus_failure;
2594             errcode = bprr->errcode;
2595             errstring = bprr->errstring;
2596         }
2597     }
2598     apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2599     next = odr_intdup(assoc->encode, 0);
2600     num = odr_intdup(assoc->encode, 0);
2601     
2602     apdu->which = Z_APDU_presentResponse;
2603     apdu->u.presentResponse = resp;
2604     resp->referenceId = req->referenceId;
2605     resp->otherInfo = 0;
2606     
2607     if (!resp->records)
2608     {
2609         *num = *req->numberOfRecordsRequested;
2610         resp->records =
2611             pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
2612                          num, req->recordComposition, next,
2613                          resp->presentStatus,
2614                          form, req->referenceId, req->preferredRecordSyntax, 
2615                          &errcode);
2616     }
2617     if (log_request)
2618     {
2619         WRBUF wr = wrbuf_alloc();
2620         wrbuf_printf(wr, "Present ");
2621
2622         if (*resp->presentStatus == Z_PresentStatus_failure)
2623             wrbuf_printf(wr, "ERROR %d", errcode);
2624         else if (*resp->presentStatus == Z_PresentStatus_success)
2625             wrbuf_printf(wr, "OK -");
2626         else
2627             wrbuf_printf(wr, "Partial %d", *resp->presentStatus);
2628
2629         wrbuf_printf(wr, " %s %d+%d ",
2630                 req->resultSetId, *req->resultSetStartPoint,
2631                 *req->numberOfRecordsRequested);
2632         yaz_log(log_request, "%s", wrbuf_buf(wr) );
2633         wrbuf_free(wr, 1);
2634     }
2635     if (!resp->records)
2636         return 0;
2637     resp->numberOfRecordsReturned = num;
2638     resp->nextResultSetPosition = next;
2639     
2640     return apdu;
2641 }
2642
2643 /*
2644  * Scan was implemented rather in a hurry, and with support for only the basic
2645  * elements of the service in the backend API. Suggestions are welcome.
2646  */
2647 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
2648 {
2649     Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
2650     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2651     Z_ScanResponse *res = (Z_ScanResponse *)
2652         odr_malloc (assoc->encode, sizeof(*res));
2653     int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
2654     int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
2655     Z_ListEntries *ents = (Z_ListEntries *)
2656         odr_malloc (assoc->encode, sizeof(*ents));
2657     Z_DiagRecs *diagrecs_p = NULL;
2658     oident *attset;
2659     bend_scan_rr *bsrr = (bend_scan_rr *)
2660         odr_malloc (assoc->encode, sizeof(*bsrr));
2661     struct scan_entry *save_entries;
2662
2663     yaz_log(log_requestdetail, "Got ScanRequest");
2664
2665     apdu->which = Z_APDU_scanResponse;
2666     apdu->u.scanResponse = res;
2667     res->referenceId = req->referenceId;
2668
2669     /* if step is absent, set it to 0 */
2670     res->stepSize = odr_intdup(assoc->encode, 0);
2671     if (req->stepSize)
2672         *res->stepSize = *req->stepSize;
2673
2674     res->scanStatus = scanStatus;
2675     res->numberOfEntriesReturned = numberOfEntriesReturned;
2676     res->positionOfTerm = 0;
2677     res->entries = ents;
2678     ents->num_entries = 0;
2679     ents->entries = NULL;
2680     ents->num_nonsurrogateDiagnostics = 0;
2681     ents->nonsurrogateDiagnostics = NULL;
2682     res->attributeSet = 0;
2683     res->otherInfo = 0;
2684
2685     if (req->databaseNames)
2686     {
2687         int i;
2688         for (i = 0; i < req->num_databaseNames; i++)
2689             yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
2690     }
2691     bsrr->scanClause = 0;
2692     bsrr->errcode = 0;
2693     bsrr->errstring = 0;
2694     bsrr->num_bases = req->num_databaseNames;
2695     bsrr->basenames = req->databaseNames;
2696     bsrr->num_entries = *req->numberOfTermsRequested;
2697     bsrr->term = req->termListAndStartPoint;
2698     bsrr->referenceId = req->referenceId;
2699     bsrr->stream = assoc->encode;
2700     bsrr->print = assoc->print;
2701     bsrr->step_size = res->stepSize;
2702     bsrr->entries = 0;
2703     /* For YAZ 2.0 and earlier it was the backend handler that
2704        initialized entries (member display_term did not exist)
2705        YAZ 2.0 and later sets 'entries'  and initialize all members
2706        including 'display_term'. If YAZ 2.0 or later sees that
2707        entries was modified - we assume that it is an old handler and
2708        that 'display_term' is _not_ set.
2709     */
2710     if (bsrr->num_entries > 0) 
2711     {
2712         int i;
2713         bsrr->entries = odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
2714                                    bsrr->num_entries);
2715         for (i = 0; i<bsrr->num_entries; i++)
2716         {
2717             bsrr->entries[i].term = 0;
2718             bsrr->entries[i].occurrences = 0;
2719             bsrr->entries[i].errcode = 0;
2720             bsrr->entries[i].errstring = 0;
2721             bsrr->entries[i].display_term = 0;
2722         }
2723     }
2724     save_entries = bsrr->entries;  /* save it so we can compare later */
2725
2726     if (req->attributeSet &&
2727         (attset = oid_getentbyoid(req->attributeSet)) &&
2728         (attset->oclass == CLASS_ATTSET || attset->oclass == CLASS_GENERAL))
2729         bsrr->attributeset = attset->value;
2730     else
2731         bsrr->attributeset = VAL_NONE;
2732     log_scan_term_level (log_requestdetail, req->termListAndStartPoint, 
2733             bsrr->attributeset);
2734     bsrr->term_position = req->preferredPositionInResponse ?
2735         *req->preferredPositionInResponse : 1;
2736
2737     ((int (*)(void *, bend_scan_rr *))
2738      (*assoc->init->bend_scan))(assoc->backend, bsrr);
2739
2740     if (bsrr->errcode)
2741         diagrecs_p = zget_DiagRecs(assoc->encode,
2742                                    bsrr->errcode, bsrr->errstring);
2743     else
2744     {
2745         int i;
2746         Z_Entry **tab = (Z_Entry **)
2747             odr_malloc (assoc->encode, sizeof(*tab) * bsrr->num_entries);
2748         
2749         if (bsrr->status == BEND_SCAN_PARTIAL)
2750             *scanStatus = Z_Scan_partial_5;
2751         else
2752             *scanStatus = Z_Scan_success;
2753         ents->entries = tab;
2754         ents->num_entries = bsrr->num_entries;
2755         res->numberOfEntriesReturned = &ents->num_entries;          
2756         res->positionOfTerm = &bsrr->term_position;
2757         for (i = 0; i < bsrr->num_entries; i++)
2758         {
2759             Z_Entry *e;
2760             Z_TermInfo *t;
2761             Odr_oct *o;
2762             
2763             tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
2764             if (bsrr->entries[i].occurrences >= 0)
2765             {
2766                 e->which = Z_Entry_termInfo;
2767                 e->u.termInfo = t = (Z_TermInfo *)
2768                     odr_malloc(assoc->encode, sizeof(*t));
2769                 t->suggestedAttributes = 0;
2770                 t->displayTerm = 0;
2771                 if (save_entries == bsrr->entries && 
2772                     bsrr->entries[i].display_term)
2773                 {
2774                     /* the entries was _not_ set by the handler. So it's
2775                        safe to test for new member display_term. It is
2776                        NULL'ed by us.
2777                     */
2778                     t->displayTerm = odr_strdup(assoc->encode,
2779                                                 bsrr->entries[i].display_term);
2780                 }
2781                 t->alternativeTerm = 0;
2782                 t->byAttributes = 0;
2783                 t->otherTermInfo = 0;
2784                 t->globalOccurrences = &bsrr->entries[i].occurrences;
2785                 t->term = (Z_Term *)
2786                     odr_malloc(assoc->encode, sizeof(*t->term));
2787                 t->term->which = Z_Term_general;
2788                 t->term->u.general = o =
2789                     (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
2790                 o->buf = (unsigned char *)
2791                     odr_malloc(assoc->encode, o->len = o->size =
2792                                strlen(bsrr->entries[i].term));
2793                 memcpy(o->buf, bsrr->entries[i].term, o->len);
2794                 yaz_log(YLOG_DEBUG, "  term #%d: '%s' (%d)", i,
2795                          bsrr->entries[i].term, bsrr->entries[i].occurrences);
2796             }
2797             else
2798             {
2799                 Z_DiagRecs *drecs = zget_DiagRecs(assoc->encode,
2800                                                   bsrr->entries[i].errcode,
2801                                                   bsrr->entries[i].errstring);
2802                 assert (drecs->num_diagRecs == 1);
2803                 e->which = Z_Entry_surrogateDiagnostic;
2804                 assert (drecs->diagRecs[0]);
2805                 e->u.surrogateDiagnostic = drecs->diagRecs[0];
2806             }
2807         }
2808     }
2809     if (diagrecs_p)
2810     {
2811         ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
2812         ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
2813     }
2814     if (log_request)
2815     {
2816         WRBUF wr = wrbuf_alloc();
2817         if (bsrr->errcode)
2818             wr_diag(wr, bsrr->errcode, bsrr->errstring);
2819         else if (*res->scanStatus == Z_Scan_success)
2820             wrbuf_printf(wr, "OK");
2821         else
2822             wrbuf_printf(wr, "Partial");
2823
2824         wrbuf_printf(wr, " %d+%d %d ",
2825                      (req->preferredPositionInResponse ?
2826                       *req->preferredPositionInResponse : 1),
2827                      *req->numberOfTermsRequested,
2828                      (res->stepSize ? *res->stepSize : 0));
2829         yaz_scan_to_wrbuf(wr, req->termListAndStartPoint, 
2830                           bsrr->attributeset);
2831         yaz_log(log_request, "Scan %s", wrbuf_buf(wr) );
2832         wrbuf_free(wr, 1);
2833     }
2834     return apdu;
2835 }
2836
2837 static Z_APDU *process_sortRequest(association *assoc, request *reqb,
2838     int *fd)
2839 {
2840     int i;
2841     Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
2842     Z_SortResponse *res = (Z_SortResponse *)
2843         odr_malloc (assoc->encode, sizeof(*res));
2844     bend_sort_rr *bsrr = (bend_sort_rr *)
2845         odr_malloc (assoc->encode, sizeof(*bsrr));
2846
2847     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2848
2849     yaz_log(log_requestdetail, "Got SortRequest.");
2850
2851     bsrr->num_input_setnames = req->num_inputResultSetNames;
2852     for (i=0;i<req->num_inputResultSetNames;i++)
2853         yaz_log(log_requestdetail, "Input resultset: '%s'",
2854                 req->inputResultSetNames[i]);
2855     bsrr->input_setnames = req->inputResultSetNames;
2856     bsrr->referenceId = req->referenceId;
2857     bsrr->output_setname = req->sortedResultSetName;
2858     yaz_log(log_requestdetail, "Output resultset: '%s'",
2859                 req->sortedResultSetName);
2860     bsrr->sort_sequence = req->sortSequence;
2861        /*FIXME - dump those sequences too */
2862     bsrr->stream = assoc->encode;
2863     bsrr->print = assoc->print;
2864
2865     bsrr->sort_status = Z_SortResponse_failure;
2866     bsrr->errcode = 0;
2867     bsrr->errstring = 0;
2868     
2869     (*assoc->init->bend_sort)(assoc->backend, bsrr);
2870     
2871     res->referenceId = bsrr->referenceId;
2872     res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
2873     res->resultSetStatus = 0;
2874     if (bsrr->errcode)
2875     {
2876         Z_DiagRecs *dr = zget_DiagRecs(assoc->encode,
2877                                        bsrr->errcode, bsrr->errstring);
2878         res->diagnostics = dr->diagRecs;
2879         res->num_diagnostics = dr->num_diagRecs;
2880     }
2881     else
2882     {
2883         res->num_diagnostics = 0;
2884         res->diagnostics = 0;
2885     }
2886     res->resultCount = 0;
2887     res->otherInfo = 0;
2888
2889     apdu->which = Z_APDU_sortResponse;
2890     apdu->u.sortResponse = res;
2891     if (log_request)
2892     {
2893         WRBUF wr = wrbuf_alloc();
2894         wrbuf_printf(wr, "Sort ");
2895         if (bsrr->errcode)
2896             wrbuf_printf(wr, " ERROR %d", bsrr->errcode);
2897         else
2898             wrbuf_printf(wr,  "OK -");
2899         wrbuf_printf(wr, " (");
2900         for (i = 0; i<req->num_inputResultSetNames; i++)
2901         {
2902             if (i)
2903                 wrbuf_printf(wr, ",");
2904             wrbuf_printf(wr, req->inputResultSetNames[i]);
2905         }
2906         wrbuf_printf(wr, ")->%s ",req->sortedResultSetName);
2907
2908         yaz_log(log_request, "%s", wrbuf_buf(wr) );
2909         wrbuf_free(wr, 1);
2910     }
2911     return apdu;
2912 }
2913
2914 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
2915     int *fd)
2916 {
2917     int i;
2918     Z_DeleteResultSetRequest *req =
2919         reqb->apdu_request->u.deleteResultSetRequest;
2920     Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
2921         odr_malloc (assoc->encode, sizeof(*res));
2922     bend_delete_rr *bdrr = (bend_delete_rr *)
2923         odr_malloc (assoc->encode, sizeof(*bdrr));
2924     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2925
2926     yaz_log(log_requestdetail, "Got DeleteRequest.");
2927
2928     bdrr->num_setnames = req->num_resultSetList;
2929     bdrr->setnames = req->resultSetList;
2930     for (i = 0; i<req->num_resultSetList; i++)
2931         yaz_log(log_requestdetail, "resultset: '%s'",
2932                 req->resultSetList[i]);
2933     bdrr->stream = assoc->encode;
2934     bdrr->print = assoc->print;
2935     bdrr->function = *req->deleteFunction;
2936     bdrr->referenceId = req->referenceId;
2937     bdrr->statuses = 0;
2938     if (bdrr->num_setnames > 0)
2939     {
2940         bdrr->statuses = (int*) 
2941             odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
2942                        bdrr->num_setnames);
2943         for (i = 0; i < bdrr->num_setnames; i++)
2944             bdrr->statuses[i] = 0;
2945     }
2946     (*assoc->init->bend_delete)(assoc->backend, bdrr);
2947     
2948     res->referenceId = req->referenceId;
2949
2950     res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
2951
2952     res->deleteListStatuses = 0;
2953     if (bdrr->num_setnames > 0)
2954     {
2955         int i;
2956         res->deleteListStatuses = (Z_ListStatuses *)
2957             odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
2958         res->deleteListStatuses->num = bdrr->num_setnames;
2959         res->deleteListStatuses->elements =
2960             (Z_ListStatus **)
2961             odr_malloc (assoc->encode, 
2962                         sizeof(*res->deleteListStatuses->elements) *
2963                         bdrr->num_setnames);
2964         for (i = 0; i<bdrr->num_setnames; i++)
2965         {
2966             res->deleteListStatuses->elements[i] =
2967                 (Z_ListStatus *)
2968                 odr_malloc (assoc->encode,
2969                             sizeof(**res->deleteListStatuses->elements));
2970             res->deleteListStatuses->elements[i]->status = bdrr->statuses+i;
2971             res->deleteListStatuses->elements[i]->id =
2972                 odr_strdup (assoc->encode, bdrr->setnames[i]);
2973         }
2974     }
2975     res->numberNotDeleted = 0;
2976     res->bulkStatuses = 0;
2977     res->deleteMessage = 0;
2978     res->otherInfo = 0;
2979
2980     apdu->which = Z_APDU_deleteResultSetResponse;
2981     apdu->u.deleteResultSetResponse = res;
2982     if (log_request)
2983     {
2984         WRBUF wr = wrbuf_alloc();
2985         wrbuf_printf(wr, "Delete ");
2986         if (bdrr->delete_status)
2987             wrbuf_printf(wr, "ERROR %d", bdrr->delete_status);
2988         else
2989             wrbuf_printf(wr, "OK -");
2990         for (i = 0; i<req->num_resultSetList; i++)
2991             wrbuf_printf(wr, " %s ", req->resultSetList[i]);
2992         yaz_log(log_request, "%s", wrbuf_buf(wr) );
2993         wrbuf_free(wr, 1);
2994     }
2995     return apdu;
2996 }
2997
2998 static void process_close(association *assoc, request *reqb)
2999 {
3000     Z_Close *req = reqb->apdu_request->u.close;
3001     static char *reasons[] =
3002     {
3003         "finished",
3004         "shutdown",
3005         "systemProblem",
3006         "costLimit",
3007         "resources",
3008         "securityViolation",
3009         "protocolError",
3010         "lackOfActivity",
3011         "peerAbort",
3012         "unspecified"
3013     };
3014
3015     yaz_log(log_requestdetail, "Got Close, reason %s, message %s",
3016         reasons[*req->closeReason], req->diagnosticInformation ?
3017         req->diagnosticInformation : "NULL");
3018     if (assoc->version < 3) /* to make do_force respond with close */
3019         assoc->version = 3;
3020     do_close_req(assoc, Z_Close_finished,
3021                  "Association terminated by client", reqb);
3022     yaz_log(log_request,"Close OK");
3023 }
3024
3025 void save_referenceId (request *reqb, Z_ReferenceId *refid)
3026 {
3027     if (refid)
3028     {
3029         reqb->len_refid = refid->len;
3030         reqb->refid = (char *)nmem_malloc (reqb->request_mem, refid->len);
3031         memcpy (reqb->refid, refid->buf, refid->len);
3032     }
3033     else
3034     {
3035         reqb->len_refid = 0;
3036         reqb->refid = NULL;
3037     }
3038 }
3039
3040 void bend_request_send (bend_association a, bend_request req, Z_APDU *res)
3041 {
3042     process_z_response (a, req, res);
3043 }
3044
3045 bend_request bend_request_mk (bend_association a)
3046 {
3047     request *nreq = request_get (&a->outgoing);
3048     nreq->request_mem = nmem_create ();
3049     return nreq;
3050 }
3051
3052 Z_ReferenceId *bend_request_getid (ODR odr, bend_request req)
3053 {
3054     Z_ReferenceId *id;
3055     if (!req->refid)
3056         return 0;
3057     id = (Odr_oct *)odr_malloc (odr, sizeof(*odr));
3058     id->buf = (unsigned char *)odr_malloc (odr, req->len_refid);
3059     id->len = id->size = req->len_refid;
3060     memcpy (id->buf, req->refid, req->len_refid);
3061     return id;
3062 }
3063
3064 void bend_request_destroy (bend_request *req)
3065 {
3066     nmem_destroy((*req)->request_mem);
3067     request_release(*req);
3068     *req = NULL;
3069 }
3070
3071 int bend_backend_respond (bend_association a, bend_request req)
3072 {
3073     char *msg;
3074     int r;
3075     r = process_z_request (a, req, &msg);
3076     if (r < 0)
3077         yaz_log (YLOG_WARN, "%s", msg);
3078     return r;
3079 }
3080
3081 void bend_request_setdata(bend_request r, void *p)
3082 {
3083     r->clientData = p;
3084 }
3085
3086 void *bend_request_getdata(bend_request r)
3087 {
3088     return r->clientData;
3089 }
3090
3091 static Z_APDU *process_segmentRequest (association *assoc, request *reqb)
3092 {
3093     bend_segment_rr req;
3094
3095     req.segment = reqb->apdu_request->u.segmentRequest;
3096     req.stream = assoc->encode;
3097     req.decode = assoc->decode;
3098     req.print = assoc->print;
3099     req.association = assoc;
3100     
3101     (*assoc->init->bend_segment)(assoc->backend, &req);
3102
3103     return 0;
3104 }
3105
3106 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd)
3107 {
3108     bend_esrequest_rr esrequest;
3109     const char *ext_name = "unknown";
3110
3111     Z_ExtendedServicesRequest *req =
3112         reqb->apdu_request->u.extendedServicesRequest;
3113     Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
3114
3115     Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
3116
3117     esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
3118     esrequest.stream = assoc->encode;
3119     esrequest.decode = assoc->decode;
3120     esrequest.print = assoc->print;
3121     esrequest.errcode = 0;
3122     esrequest.errstring = NULL;
3123     esrequest.request = reqb;
3124     esrequest.association = assoc;
3125     esrequest.taskPackage = 0;
3126     esrequest.referenceId = req->referenceId;
3127
3128     
3129     if (esrequest.esr && esrequest.esr->taskSpecificParameters)
3130     {
3131         switch(esrequest.esr->taskSpecificParameters->which)
3132         {
3133         case Z_External_itemOrder:
3134             ext_name = "ItemOrder"; break;
3135         case Z_External_update:
3136             ext_name = "Update"; break;
3137         case Z_External_update0:
3138             ext_name = "Update0"; break;
3139         case Z_External_ESAdmin:
3140             ext_name = "Admin"; break;
3141
3142         }
3143     }
3144
3145     (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
3146     
3147     /* If the response is being delayed, return NULL */
3148     if (esrequest.request == NULL)
3149         return(NULL);
3150
3151     resp->referenceId = req->referenceId;
3152
3153     if (esrequest.errcode == -1)
3154     {
3155         /* Backend service indicates request will be processed */
3156         yaz_log(log_request, "Extended Service: %s (accepted)", ext_name);
3157         *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
3158     }
3159     else if (esrequest.errcode == 0)
3160     {
3161         /* Backend service indicates request will be processed */
3162         yaz_log(log_request, "Extended Service: %s (done)", ext_name);
3163         *resp->operationStatus = Z_ExtendedServicesResponse_done;
3164     }
3165     else
3166     {
3167         Z_DiagRecs *diagRecs =
3168             zget_DiagRecs(assoc->encode, esrequest.errcode,
3169                           esrequest.errstring);
3170         /* Backend indicates error, request will not be processed */
3171         yaz_log(log_request, "Extended Service: %s (failed)", ext_name);
3172         *resp->operationStatus = Z_ExtendedServicesResponse_failure;
3173         resp->num_diagnostics = diagRecs->num_diagRecs;
3174         resp->diagnostics = diagRecs->diagRecs;
3175         if (log_request)
3176         {
3177             WRBUF wr = wrbuf_alloc();
3178             wrbuf_diags(wr, resp->num_diagnostics, resp->diagnostics);
3179             yaz_log(log_request, "EsRequest %s", wrbuf_buf(wr) );
3180             wrbuf_free(wr, 1);
3181         }
3182
3183     }
3184     /* Do something with the members of bend_extendedservice */
3185     if (esrequest.taskPackage)
3186         resp->taskPackage = z_ext_record (assoc->encode, VAL_EXTENDED,
3187                                          (const char *)  esrequest.taskPackage,
3188                                           -1);
3189     yaz_log(YLOG_DEBUG,"Send the result apdu");
3190     return apdu;
3191 }
3192
3193 /*
3194  * Local variables:
3195  * c-basic-offset: 4
3196  * indent-tabs-mode: nil
3197  * End:
3198  * vim: shiftwidth=4 tabstop=8 expandtab
3199  */
3200