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