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