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