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