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