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