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