Yikes! Yesterday's "defensive programming" introduced a bug (D'oh!)
[yaz-moved-to-github.git] / src / seshigh.c
1 /*
2  * Copyright (C) 1995-2005, Index Data ApS
3  * See the file LICENSE for details.
4  *
5  * $Id: seshigh.c,v 1.65 2005-11-09 17:47:11 adam Exp $
6  */
7 /**
8  * \file seshigh.c
9  * \brief Implements GFS session logic.
10  *
11  * Frontend server logic.
12  *
13  * This code receives incoming APDUs, and handles client requests by means
14  * of the backend API.
15  *
16  * Some of the code is getting quite involved, compared to simpler servers -
17  * primarily because it is asynchronous both in the communication with
18  * the user and the backend. We think the complexity will pay off in
19  * the form of greater flexibility when more asynchronous facilities
20  * are implemented.
21  *
22  * Memory management has become somewhat involved. In the simple case, where
23  * only one PDU is pending at a time, it will simply reuse the same memory,
24  * once it has found its working size. When we enable multiple concurrent
25  * operations, perhaps even with multiple parallel calls to the backend, it
26  * will maintain a pool of buffers for encoding and decoding, trying to
27  * minimize memory allocation/deallocation during normal operation.
28  *
29  */
30
31 #include <stdlib.h>
32 #include <stdio.h>
33 #include <assert.h>
34 #include <ctype.h>
35
36 #if HAVE_SYS_TYPES_H
37 #include <sys/types.h>
38 #endif
39 #if HAVE_SYS_STAT_H
40 #include <sys/stat.h>
41 #endif
42
43 #ifdef WIN32
44 #include <io.h>
45 #define S_ISREG(x) (x & _S_IFREG)
46 #include <process.h>
47 #endif
48
49 #if HAVE_UNISTD_H
50 #include <unistd.h>
51 #endif
52
53 #if HAVE_XML2
54 #include <libxml/parser.h>
55 #include <libxml/tree.h>
56 #endif
57
58 #include <yaz/yconfig.h>
59 #include <yaz/xmalloc.h>
60 #include <yaz/comstack.h>
61 #include "eventl.h"
62 #include "session.h"
63 #include <yaz/proto.h>
64 #include <yaz/oid.h>
65 #include <yaz/log.h>
66 #include <yaz/logrpn.h>
67 #include <yaz/statserv.h>
68 #include <yaz/diagbib1.h>
69 #include <yaz/charneg.h>
70 #include <yaz/otherinfo.h>
71 #include <yaz/yaz-util.h>
72 #include <yaz/pquery.h>
73
74 #include <yaz/srw.h>
75 #include <yaz/backend.h>
76
77 static void process_gdu_request(association *assoc, request *req);
78 static int process_z_request(association *assoc, request *req, char **msg);
79 void backend_response(IOCHAN i, int event);
80 static int process_gdu_response(association *assoc, request *req, Z_GDU *res);
81 static int process_z_response(association *assoc, request *req, Z_APDU *res);
82 static Z_APDU *process_initRequest(association *assoc, request *reqb);
83 static Z_External *init_diagnostics(ODR odr, int errcode,
84                                     const char *errstring);
85 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
86     int *fd);
87 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
88     bend_search_rr *bsrr, int *fd);
89 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
90     int *fd);
91 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd);
92 static Z_APDU *process_sortRequest(association *assoc, request *reqb, int *fd);
93 static void process_close(association *assoc, request *reqb);
94 void save_referenceId (request *reqb, Z_ReferenceId *refid);
95 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
96     int *fd);
97 static Z_APDU *process_segmentRequest (association *assoc, request *reqb);
98
99 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd);
100
101 /* dynamic logging levels */
102 static int logbits_set = 0;
103 static int log_session = 0; 
104 static int log_request = 0; /* one-line logs for requests */
105 static int log_requestdetail = 0;  /* more detailed stuff */
106
107 /** get_logbits sets global loglevel bits */
108 static void get_logbits()
109 { /* needs to be called after parsing cmd-line args that can set loglevels!*/
110     if (!logbits_set)
111     {
112         logbits_set = 1;
113         log_session = yaz_log_module_level("session"); 
114         log_request = yaz_log_module_level("request"); 
115         log_requestdetail = yaz_log_module_level("requestdetail"); 
116     }
117 }
118
119 static void wr_diag(WRBUF w, int error, const char *addinfo)
120 {
121     wrbuf_printf(w, "ERROR [%d] %s%s%s",
122                  error, diagbib1_str(error),
123                  addinfo ? "--" : "", addinfo ? addinfo : "");
124 }
125
126
127 /*
128  * Create and initialize a new association-handle.
129  *  channel  : iochannel for the current line.
130  *  link     : communications channel.
131  * Returns: 0 or a new association handle.
132  */
133 association *create_association(IOCHAN channel, COMSTACK link,
134                                 const char *apdufile)
135 {
136     association *anew;
137
138     if (!logbits_set)
139         get_logbits();
140     if (!(anew = (association *)xmalloc(sizeof(*anew))))
141         return 0;
142     anew->init = 0;
143     anew->version = 0;
144     anew->last_control = 0;
145     anew->client_chan = channel;
146     anew->client_link = link;
147     anew->cs_get_mask = 0;
148     anew->cs_put_mask = 0;
149     anew->cs_accept_mask = 0;
150     if (!(anew->decode = odr_createmem(ODR_DECODE)) ||
151         !(anew->encode = odr_createmem(ODR_ENCODE)))
152         return 0;
153     if (apdufile && *apdufile)
154     {
155         FILE *f;
156
157         if (!(anew->print = odr_createmem(ODR_PRINT)))
158             return 0;
159         if (*apdufile == '@')
160         {
161             odr_setprint(anew->print, yaz_log_file());
162         }       
163         else if (*apdufile != '-')
164         {
165             char filename[256];
166             sprintf(filename, "%.200s.%ld", apdufile, (long)getpid());
167             if (!(f = fopen(filename, "w")))
168             {
169                 yaz_log(YLOG_WARN|YLOG_ERRNO, "%s", filename);
170                 return 0;
171             }
172             setvbuf(f, 0, _IONBF, 0);
173             odr_setprint(anew->print, f);
174         }
175     }
176     else
177         anew->print = 0;
178     anew->input_buffer = 0;
179     anew->input_buffer_len = 0;
180     anew->backend = 0;
181     anew->state = ASSOC_NEW;
182     request_initq(&anew->incoming);
183     request_initq(&anew->outgoing);
184     anew->proto = cs_getproto(link);
185     anew->cql_transform = 0;
186     anew->server_node_ptr = 0;
187     return anew;
188 }
189
190 /*
191  * Free association and release resources.
192  */
193 void destroy_association(association *h)
194 {
195     statserv_options_block *cb = statserv_getcontrol();
196     request *req;
197
198     xfree(h->init);
199     odr_destroy(h->decode);
200     odr_destroy(h->encode);
201     if (h->print)
202         odr_destroy(h->print);
203     if (h->input_buffer)
204     xfree(h->input_buffer);
205     if (h->backend)
206         (*cb->bend_close)(h->backend);
207     while ((req = request_deq(&h->incoming)))
208         request_release(req);
209     while ((req = request_deq(&h->outgoing)))
210         request_release(req);
211     request_delq(&h->incoming);
212     request_delq(&h->outgoing);
213     xfree(h);
214     xmalloc_trav("session closed");
215     if (cb && cb->one_shot)
216     {
217         exit (0);
218     }
219 }
220
221 static void do_close_req(association *a, int reason, char *message,
222                          request *req)
223 {
224     Z_APDU apdu;
225     Z_Close *cls = zget_Close(a->encode);
226     
227     /* Purge request queue */
228     while (request_deq(&a->incoming));
229     while (request_deq(&a->outgoing));
230     if (a->version >= 3)
231     {
232         yaz_log(log_requestdetail, "Sending Close PDU, reason=%d, message=%s",
233             reason, message ? message : "none");
234         apdu.which = Z_APDU_close;
235         apdu.u.close = cls;
236         *cls->closeReason = reason;
237         cls->diagnosticInformation = message;
238         process_z_response(a, req, &apdu);
239         iochan_settimeout(a->client_chan, 20);
240     }
241     else
242     {
243         request_release(req);
244         yaz_log(log_requestdetail, "v2 client. No Close PDU");
245         iochan_setevent(a->client_chan, EVENT_TIMEOUT); /* force imm close */
246         a->cs_put_mask = 0;
247     }
248     a->state = ASSOC_DEAD;
249 }
250
251 static void do_close(association *a, int reason, char *message)
252 {
253     request *req = request_get(&a->outgoing);
254     do_close_req (a, reason, message, req);
255 }
256
257 /*
258  * This is where PDUs from the client are read and the further
259  * processing is initiated. Flow of control moves down through the
260  * various process_* functions below, until the encoded result comes back up
261  * to the output handler in here.
262  * 
263  *  h     : the I/O channel that has an outstanding event.
264  *  event : the current outstanding event.
265  */
266 void ir_session(IOCHAN h, int event)
267 {
268     int res;
269     association *assoc = (association *)iochan_getdata(h);
270     COMSTACK conn = assoc->client_link;
271     request *req;
272
273     assert(h && conn && assoc);
274     if (event == EVENT_TIMEOUT)
275     {
276         if (assoc->state != ASSOC_UP)
277         {
278             yaz_log(YLOG_DEBUG, "Final timeout - closing connection.");
279             /* do we need to lod this at all */
280             cs_close(conn);
281             destroy_association(assoc);
282             iochan_destroy(h);
283         }
284         else
285         {
286             yaz_log(log_session, "Session idle too long. Sending close.");
287             do_close(assoc, Z_Close_lackOfActivity, 0);
288         }
289         return;
290     }
291     if (event & assoc->cs_accept_mask)
292     {
293         if (!cs_accept (conn))
294         {
295             yaz_log (YLOG_WARN, "accept failed");
296             destroy_association(assoc);
297             iochan_destroy(h);
298         }
299         iochan_clearflag (h, EVENT_OUTPUT);
300         if (conn->io_pending) 
301         {   /* cs_accept didn't complete */
302             assoc->cs_accept_mask = 
303                 ((conn->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
304                 ((conn->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
305
306             iochan_setflag (h, assoc->cs_accept_mask);
307         }
308         else
309         {   /* cs_accept completed. Prepare for reading (cs_get) */
310             assoc->cs_accept_mask = 0;
311             assoc->cs_get_mask = EVENT_INPUT;
312             iochan_setflag (h, assoc->cs_get_mask);
313         }
314         return;
315     }
316     if ((event & assoc->cs_get_mask) || (event & EVENT_WORK)) /* input */
317     {
318         if ((assoc->cs_put_mask & EVENT_INPUT) == 0 && (event & assoc->cs_get_mask))
319         {
320             yaz_log(YLOG_DEBUG, "ir_session (input)");
321             /* We aren't speaking to this fellow */
322             if (assoc->state == ASSOC_DEAD)
323             {
324                 yaz_log(log_session, "Connection closed - end of session");
325                 cs_close(conn);
326                 destroy_association(assoc);
327                 iochan_destroy(h);
328                 return;
329             }
330             assoc->cs_get_mask = EVENT_INPUT;
331             if ((res = cs_get(conn, &assoc->input_buffer,
332                 &assoc->input_buffer_len)) <= 0)
333             {
334                 yaz_log(log_session, "Connection closed by client");
335                 cs_close(conn);
336                 destroy_association(assoc);
337                 iochan_destroy(h);
338                 return;
339             }
340             else if (res == 1) /* incomplete read - wait for more  */
341             {
342                 if (conn->io_pending & CS_WANT_WRITE)
343                     assoc->cs_get_mask |= EVENT_OUTPUT;
344                 iochan_setflag(h, assoc->cs_get_mask);
345                 return;
346             }
347             if (cs_more(conn)) /* more stuff - call us again later, please */
348                 iochan_setevent(h, EVENT_INPUT);
349                 
350             /* we got a complete PDU. Let's decode it */
351             yaz_log(YLOG_DEBUG, "Got PDU, %d bytes: lead=%02X %02X %02X", res,
352                             assoc->input_buffer[0] & 0xff,
353                             assoc->input_buffer[1] & 0xff,
354                             assoc->input_buffer[2] & 0xff);
355             req = request_get(&assoc->incoming); /* get a new request */
356             odr_reset(assoc->decode);
357             odr_setbuf(assoc->decode, assoc->input_buffer, res, 0);
358             if (!z_GDU(assoc->decode, &req->gdu_request, 0, 0))
359             {
360                 yaz_log(YLOG_WARN, "ODR error on incoming PDU: %s [element %s] "
361                         "[near byte %d] ",
362                         odr_errmsg(odr_geterror(assoc->decode)),
363                         odr_getelement(assoc->decode),
364                         odr_offset(assoc->decode));
365                 if (assoc->decode->error != OHTTP)
366                 {
367                     yaz_log(YLOG_WARN, "PDU dump:");
368                     odr_dumpBER(yaz_log_file(), assoc->input_buffer, res);
369                     request_release(req);
370                     do_close(assoc, Z_Close_protocolError,"Malformed package");
371                 }
372                 else
373                 {
374                     Z_GDU *p = z_get_HTTP_Response(assoc->encode, 400);
375                     assoc->state = ASSOC_DEAD;
376                     process_gdu_response(assoc, req, p);
377                 }
378                 return;
379             }
380             req->request_mem = odr_extract_mem(assoc->decode);
381             if (assoc->print) 
382             {
383                 if (!z_GDU(assoc->print, &req->gdu_request, 0, 0))
384                     yaz_log(YLOG_WARN, "ODR print error: %s", 
385                        odr_errmsg(odr_geterror(assoc->print)));
386                 odr_reset(assoc->print);
387             }
388             request_enq(&assoc->incoming, req);
389         }
390
391         /* can we do something yet? */
392         req = request_head(&assoc->incoming);
393         if (req->state == REQUEST_IDLE)
394         {
395             request_deq(&assoc->incoming);
396             process_gdu_request(assoc, req);
397         }
398     }
399     if (event & assoc->cs_put_mask)
400     {
401         request *req = request_head(&assoc->outgoing);
402
403         assoc->cs_put_mask = 0;
404         yaz_log(YLOG_DEBUG, "ir_session (output)");
405         req->state = REQUEST_PENDING;
406         switch (res = cs_put(conn, req->response, req->len_response))
407         {
408         case -1:
409             yaz_log(log_session, "Connection closed by client");
410             cs_close(conn);
411             destroy_association(assoc);
412             iochan_destroy(h);
413             break;
414         case 0: /* all sent - release the request structure */
415             yaz_log(YLOG_DEBUG, "Wrote PDU, %d bytes", req->len_response);
416 #if 0
417             yaz_log(YLOG_DEBUG, "HTTP out:\n%.*s", req->len_response,
418                     req->response);
419 #endif
420             nmem_destroy(req->request_mem);
421             request_deq(&assoc->outgoing);
422             request_release(req);
423             if (!request_head(&assoc->outgoing))
424             {   /* restore mask for cs_get operation ... */
425                 iochan_clearflag(h, EVENT_OUTPUT|EVENT_INPUT);
426                 iochan_setflag(h, assoc->cs_get_mask);
427                 if (assoc->state == ASSOC_DEAD)
428                     iochan_setevent(assoc->client_chan, EVENT_TIMEOUT);
429             }
430             else
431             {
432                 assoc->cs_put_mask = EVENT_OUTPUT;
433             }
434             break;
435         default:
436             if (conn->io_pending & CS_WANT_WRITE)
437                 assoc->cs_put_mask |= EVENT_OUTPUT;
438             if (conn->io_pending & CS_WANT_READ)
439                 assoc->cs_put_mask |= EVENT_INPUT;
440             iochan_setflag(h, assoc->cs_put_mask);
441         }
442     }
443     if (event & EVENT_EXCEPT)
444     {
445         yaz_log(YLOG_WARN, "ir_session (exception)");
446         cs_close(conn);
447         destroy_association(assoc);
448         iochan_destroy(h);
449     }
450 }
451
452 static int process_z_request(association *assoc, request *req, char **msg);
453
454
455 static void assoc_init_reset(association *assoc)
456 {
457     xfree (assoc->init);
458     assoc->init = (bend_initrequest *) xmalloc (sizeof(*assoc->init));
459
460     assoc->init->stream = assoc->encode;
461     assoc->init->print = assoc->print;
462     assoc->init->auth = 0;
463     assoc->init->referenceId = 0;
464     assoc->init->implementation_version = 0;
465     assoc->init->implementation_id = 0;
466     assoc->init->implementation_name = 0;
467     assoc->init->bend_sort = NULL;
468     assoc->init->bend_search = NULL;
469     assoc->init->bend_present = NULL;
470     assoc->init->bend_esrequest = NULL;
471     assoc->init->bend_delete = NULL;
472     assoc->init->bend_scan = NULL;
473     assoc->init->bend_segment = NULL;
474     assoc->init->bend_fetch = NULL;
475     assoc->init->bend_explain = NULL;
476     assoc->init->bend_srw_scan = NULL;
477     assoc->init->bend_srw_update = NULL;
478
479     assoc->init->charneg_request = NULL;
480     assoc->init->charneg_response = NULL;
481
482     assoc->init->decode = assoc->decode;
483     assoc->init->peer_name = 
484         odr_strdup (assoc->encode, cs_addrstr(assoc->client_link));
485
486     yaz_log(log_requestdetail, "peer %s", assoc->init->peer_name);
487 }
488
489 static int srw_bend_init(association *assoc, Z_SRW_diagnostic **d, int *num)
490 {
491     statserv_options_block *cb = statserv_getcontrol();
492     if (!assoc->init)
493     {
494         const char *encoding = "UTF-8";
495         Z_External *ce;
496         bend_initresult *binitres;
497
498         yaz_log(YLOG_LOG, "srw_bend_init config=%s", cb->configname);
499         assoc_init_reset(assoc);
500         
501         assoc->maximumRecordSize = 3000000;
502         assoc->preferredMessageSize = 3000000;
503 #if 1
504         ce = yaz_set_proposal_charneg(assoc->decode, &encoding, 1, 0, 0, 1);
505         assoc->init->charneg_request = ce->u.charNeg3;
506 #endif
507         assoc->backend = 0;
508         if (!(binitres = (*cb->bend_init)(assoc->init)))
509         {
510             assoc->state = ASSOC_DEAD;
511             yaz_add_srw_diagnostic(assoc->encode, d, num,
512                             YAZ_SRW_AUTHENTICATION_ERROR, 0);
513             return 0;
514         }
515         assoc->backend = binitres->handle;
516         if (binitres->errcode)
517         {
518             assoc->state = ASSOC_DEAD;
519             yaz_add_srw_diagnostic(assoc->encode, d, num, binitres->errcode,
520                                    binitres->errstring);
521             return 0;
522         }
523         return 1;
524     }
525     return 1;
526 }
527
528 static int srw_bend_fetch(association *assoc, int pos,
529                           Z_SRW_searchRetrieveRequest *srw_req,
530                           Z_SRW_record *record)
531 {
532     bend_fetch_rr rr;
533     ODR o = assoc->encode;
534
535     rr.setname = "default";
536     rr.number = pos;
537     rr.referenceId = 0;
538     rr.request_format = VAL_TEXT_XML;
539     rr.request_format_raw = yaz_oidval_to_z3950oid(assoc->decode,
540                                                    CLASS_TRANSYN,
541                                                    VAL_TEXT_XML);
542     rr.comp = (Z_RecordComposition *)
543             odr_malloc(assoc->decode, sizeof(*rr.comp));
544     rr.comp->which = Z_RecordComp_complex;
545     rr.comp->u.complex = (Z_CompSpec *)
546             odr_malloc(assoc->decode, sizeof(Z_CompSpec));
547     rr.comp->u.complex->selectAlternativeSyntax = (bool_t *)
548         odr_malloc(assoc->encode, sizeof(bool_t));
549     *rr.comp->u.complex->selectAlternativeSyntax = 0;    
550     rr.comp->u.complex->num_dbSpecific = 0;
551     rr.comp->u.complex->dbSpecific = 0;
552     rr.comp->u.complex->num_recordSyntax = 0; 
553     rr.comp->u.complex->recordSyntax = 0;
554
555     rr.comp->u.complex->generic = (Z_Specification *) 
556             odr_malloc(assoc->decode, sizeof(Z_Specification));
557
558     /* schema uri = recordSchema (or NULL if recordSchema is not given) */
559     rr.comp->u.complex->generic->which = Z_Schema_uri;
560     rr.comp->u.complex->generic->schema.uri = srw_req->recordSchema;
561
562     /* ESN = recordSchema if recordSchema is present */
563     rr.comp->u.complex->generic->elementSpec = 0;
564     if (srw_req->recordSchema)
565     {
566         rr.comp->u.complex->generic->elementSpec = 
567             (Z_ElementSpec *) odr_malloc(assoc->encode, sizeof(Z_ElementSpec));
568         rr.comp->u.complex->generic->elementSpec->which = 
569             Z_ElementSpec_elementSetName;
570         rr.comp->u.complex->generic->elementSpec->u.elementSetName =
571             srw_req->recordSchema;
572     }
573     
574     rr.stream = assoc->encode;
575     rr.print = assoc->print;
576
577     rr.basename = 0;
578     rr.len = 0;
579     rr.record = 0;
580     rr.last_in_set = 0;
581     rr.output_format = VAL_TEXT_XML;
582     rr.output_format_raw = 0;
583     rr.errcode = 0;
584     rr.errstring = 0;
585     rr.surrogate_flag = 0;
586     rr.schema = srw_req->recordSchema;
587
588     if (!assoc->init->bend_fetch)
589         return 1;
590
591     (*assoc->init->bend_fetch)(assoc->backend, &rr);
592
593     if (rr.errcode && rr.surrogate_flag)
594     {
595         int code = yaz_diag_bib1_to_srw(rr.errcode);
596         const char *message = yaz_diag_srw_str(code);
597         int len = 200;
598         if (message)
599             len += strlen(message);
600         if (rr.errstring)
601             len += strlen(rr.errstring);
602
603         record->recordData_buf = odr_malloc(o, len);
604         
605         sprintf(record->recordData_buf, "<diagnostic "
606                 "xmlns=\"http://www.loc.gov/zing/srw/diagnostic/\">\n"
607                 " <uri>info:srw/diagnostic/1/%d</uri>\n", code);
608         if (rr.errstring)
609             sprintf(record->recordData_buf + strlen(record->recordData_buf),
610                     " <details>%s</details>\n", rr.errstring);
611         if (message)
612             sprintf(record->recordData_buf + strlen(record->recordData_buf),
613                     " <message>%s</message>\n", message);
614         sprintf(record->recordData_buf + strlen(record->recordData_buf),
615                 "</diagnostic>\n");
616         record->recordData_len = strlen(record->recordData_buf);
617         record->recordPosition = odr_intdup(o, pos);
618         record->recordSchema = "info:srw/schema/1/diagnostics-v1.1";
619         return 0;
620     }
621     else if (rr.len >= 0)
622     {
623         record->recordData_buf = rr.record;
624         record->recordData_len = rr.len;
625         record->recordPosition = odr_intdup(o, pos);
626         if (rr.schema)
627             record->recordSchema = odr_strdup(o, rr.schema);
628         else
629             record->recordSchema = 0;
630     }
631     return rr.errcode;
632 }
633
634 static int cql2pqf(ODR odr, const char *cql, cql_transform_t ct,
635                    Z_Query *query_result)
636 {
637     /* have a CQL query and  CQL to PQF transform .. */
638     CQL_parser cp = cql_parser_create();
639     int r;
640     int srw_errcode = 0;
641     const char *add = 0;
642     char rpn_buf[512];
643             
644     r = cql_parser_string(cp, cql);
645     if (r)
646     {
647         /* CQL syntax error */
648         srw_errcode = 10; 
649     }
650     if (!r)
651     {
652         /* Syntax OK */
653         r = cql_transform_buf(ct,
654                               cql_parser_result(cp),
655                               rpn_buf, sizeof(rpn_buf)-1);
656         if (r)
657             srw_errcode  = cql_transform_error(ct, &add);
658     }
659     if (!r)
660     {
661         /* Syntax & transform OK. */
662         /* Convert PQF string to Z39.50 to RPN query struct */
663         YAZ_PQF_Parser pp = yaz_pqf_create();
664         Z_RPNQuery *rpnquery = yaz_pqf_parse(pp, odr, rpn_buf);
665         if (!rpnquery)
666         {
667             size_t off;
668             const char *pqf_msg;
669             int code = yaz_pqf_error(pp, &pqf_msg, &off);
670             yaz_log(YLOG_WARN, "PQF Parser Error %s (code %d)",
671                     pqf_msg, code);
672             srw_errcode = 10;
673         }
674         else
675         {
676             query_result->which = Z_Query_type_1;
677             query_result->u.type_1 = rpnquery;
678         }
679         yaz_pqf_destroy(pp);
680     }
681     cql_parser_destroy(cp);
682     return srw_errcode;
683 }
684
685 static int cql2pqf_scan(ODR odr, const char *cql, cql_transform_t ct,
686                         Z_AttributesPlusTerm *result)
687 {
688     Z_Query query;
689     Z_RPNQuery *rpn;
690     int srw_error = cql2pqf(odr, cql, ct, &query);
691     if (srw_error)
692         return srw_error;
693     if (query.which != Z_Query_type_1 && query.which != Z_Query_type_101)
694         return 10; /* bad query type */
695     rpn = query.u.type_1;
696     if (!rpn->RPNStructure) 
697         return 10; /* must be structure */
698     if (rpn->RPNStructure->which != Z_RPNStructure_simple)
699         return 10; /* must be simple */
700     if (rpn->RPNStructure->u.simple->which != Z_Operand_APT)
701         return 10; /* must be attributes plus term node .. */
702     memcpy(result, rpn->RPNStructure->u.simple->u.attributesPlusTerm,
703            sizeof(*result));
704     return 0;
705 }
706                    
707 static void srw_bend_search(association *assoc, request *req,
708                             Z_SRW_searchRetrieveRequest *srw_req,
709                             Z_SRW_searchRetrieveResponse *srw_res,
710                             int *http_code)
711 {
712     int srw_error = 0;
713     Z_External *ext;
714     
715     *http_code = 200;
716     yaz_log(log_requestdetail, "Got SRW SearchRetrieveRequest");
717     srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics);
718     if (srw_res->num_diagnostics == 0 && assoc->init)
719     {
720         bend_search_rr rr;
721         rr.setname = "default";
722         rr.replace_set = 1;
723         rr.num_bases = 1;
724         rr.basenames = &srw_req->database;
725         rr.referenceId = 0;
726         rr.srw_sortKeys = 0;
727         rr.srw_setname = 0;
728         rr.srw_setnameIdleTime = 0;
729         rr.query = (Z_Query *) odr_malloc (assoc->decode, sizeof(*rr.query));
730         rr.query->u.type_1 = 0;
731         
732         if (srw_req->query_type == Z_SRW_query_type_cql)
733         {
734             if (assoc->cql_transform)
735             {
736                 int srw_errcode = cql2pqf(assoc->encode, srw_req->query.cql,
737                                           assoc->cql_transform, rr.query);
738                 if (srw_errcode)
739                 {
740                     yaz_add_srw_diagnostic(assoc->encode,
741                                            &srw_res->diagnostics,
742                                            &srw_res->num_diagnostics,
743                                            srw_errcode, 0);
744                 }
745             }
746             else
747             {
748                 /* CQL query to backend. Wrap it - Z39.50 style */
749                 ext = (Z_External *) odr_malloc(assoc->decode, sizeof(*ext));
750                 ext->direct_reference = odr_getoidbystr(assoc->decode, 
751                                                         "1.2.840.10003.16.2");
752                 ext->indirect_reference = 0;
753                 ext->descriptor = 0;
754                 ext->which = Z_External_CQL;
755                 ext->u.cql = srw_req->query.cql;
756                 
757                 rr.query->which = Z_Query_type_104;
758                 rr.query->u.type_104 =  ext;
759             }
760         }
761         else if (srw_req->query_type == Z_SRW_query_type_pqf)
762         {
763             Z_RPNQuery *RPNquery;
764             YAZ_PQF_Parser pqf_parser;
765             
766             pqf_parser = yaz_pqf_create ();
767             
768             RPNquery = yaz_pqf_parse (pqf_parser, assoc->decode,
769                                       srw_req->query.pqf);
770             if (!RPNquery)
771             {
772                 const char *pqf_msg;
773                 size_t off;
774                 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
775                 yaz_log(log_requestdetail, "Parse error %d %s near offset %d",
776                         code, pqf_msg, off);
777                 srw_error = YAZ_SRW_QUERY_SYNTAX_ERROR;
778             }
779             
780             rr.query->which = Z_Query_type_1;
781             rr.query->u.type_1 =  RPNquery;
782             
783             yaz_pqf_destroy (pqf_parser);
784         }
785         else
786         {
787             yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
788                                    &srw_res->num_diagnostics,
789                                    YAZ_SRW_UNSUPP_QUERY_TYPE, 0);
790         }
791         if (rr.query->u.type_1)
792         {
793             rr.stream = assoc->encode;
794             rr.decode = assoc->decode;
795             rr.print = assoc->print;
796             rr.request = req;
797             if ( srw_req->sort.sortKeys )
798                 rr.srw_sortKeys = odr_strdup(assoc->encode, 
799                                              srw_req->sort.sortKeys );
800             rr.association = assoc;
801             rr.fd = 0;
802             rr.hits = 0;
803             rr.errcode = 0;
804             rr.errstring = 0;
805             rr.search_info = 0;
806             yaz_log_zquery_level(log_requestdetail,rr.query);
807             
808             (assoc->init->bend_search)(assoc->backend, &rr);
809             if (rr.errcode)
810             {
811                 if (rr.errcode == YAZ_BIB1_DATABASE_UNAVAILABLE)
812                 {
813                     *http_code = 404;
814                 }
815                 else
816                 {
817                     srw_error = yaz_diag_bib1_to_srw (rr.errcode);
818                     yaz_add_srw_diagnostic(assoc->encode,
819                                            &srw_res->diagnostics,
820                                            &srw_res->num_diagnostics,
821                                            srw_error, rr.errstring);
822                 }
823             }
824             else
825             {
826                 int number = srw_req->maximumRecords ? *srw_req->maximumRecords : 0;
827                 int start = srw_req->startRecord ? *srw_req->startRecord : 1;
828                 
829                 yaz_log(log_requestdetail, "Request to pack %d+%d out of %d",
830                         start, number, rr.hits);
831                 
832                 srw_res->numberOfRecords = odr_intdup(assoc->encode, rr.hits);
833                 if (rr.srw_setname)
834                 {
835                     srw_res->resultSetId =
836                         odr_strdup(assoc->encode, rr.srw_setname );
837                     srw_res->resultSetIdleTime =
838                         odr_intdup(assoc->encode, *rr.srw_setnameIdleTime );
839                 }
840                 if (number > 0)
841                 {
842                     int i;
843                     
844                     if (start > rr.hits)
845                     {
846                         yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
847                                                &srw_res->num_diagnostics,
848                                                YAZ_SRW_FIRST_RECORD_POSITION_OUT_OF_RANGE, 0);
849                     }
850                     else
851                     {
852                         int j = 0;
853                         int packing = Z_SRW_recordPacking_string;
854                         if (start + number > rr.hits)
855                             number = rr.hits - start + 1;
856                         if (srw_req->recordPacking){
857                             if (!strcmp(srw_req->recordPacking, "xml"))
858                                 packing = Z_SRW_recordPacking_XML;
859                             if (!strcmp(srw_req->recordPacking, "url"))
860                                 packing = Z_SRW_recordPacking_URL;
861                         }
862                         srw_res->records = (Z_SRW_record *)
863                             odr_malloc(assoc->encode,
864                                        number * sizeof(*srw_res->records));
865                         
866                         srw_res->extra_records = (Z_SRW_extra_record **)
867                             odr_malloc(assoc->encode,
868                                        number*sizeof(*srw_res->extra_records));
869
870                         for (i = 0; i<number; i++)
871                         {
872                             int errcode;
873                             
874                             srw_res->records[j].recordPacking = packing;
875                             srw_res->records[j].recordData_buf = 0;
876                             srw_res->extra_records[j] = 0;
877                             yaz_log(YLOG_DEBUG, "srw_bend_fetch %d", i+start);
878                             errcode = srw_bend_fetch(assoc, i+start, srw_req,
879                                                      srw_res->records + j);
880                             if (errcode)
881                             {
882                                 yaz_add_srw_diagnostic(assoc->encode,
883                                                        &srw_res->diagnostics,
884                                                        &srw_res->num_diagnostics,
885                                                        yaz_diag_bib1_to_srw (errcode),
886                                                        rr.errstring);
887                                 
888                                 break;
889                             }
890                             if (srw_res->records[j].recordData_buf)
891                                 j++;
892                         }
893                         srw_res->num_records = j;
894                         if (!j)
895                             srw_res->records = 0;
896                     }
897                 }
898             }
899         }
900     }
901     if (log_request)
902     {
903         const char *querystr = "?";
904         const char *querytype = "?";
905         WRBUF wr = wrbuf_alloc();
906
907         switch (srw_req->query_type)
908         {
909         case Z_SRW_query_type_cql:
910             querytype = "CQL";
911             querystr = srw_req->query.cql;
912             break;
913         case Z_SRW_query_type_pqf:
914             querytype = "PQF";
915             querystr = srw_req->query.pqf;
916             break;
917         }
918         wrbuf_printf(wr, "SRWSearch ");
919         if (srw_res->num_diagnostics)
920             wrbuf_printf(wr, "ERROR %s", srw_res->diagnostics[0].uri);
921         else if (*http_code != 200)
922             wrbuf_printf(wr, "ERROR info:http/%d", *http_code);
923         else if (srw_res->numberOfRecords)
924         {
925             wrbuf_printf(wr, "OK %d",
926                          (srw_res->numberOfRecords ?
927                           *srw_res->numberOfRecords : 0));
928         }
929         wrbuf_printf(wr, " %s %d+%d", 
930                      (srw_res->resultSetId ?
931                       srw_res->resultSetId : "-"),
932                      (srw_req->startRecord ? *srw_req->startRecord : 1), 
933                      srw_res->num_records);
934         yaz_log(log_request, "%s %s: %s", wrbuf_buf(wr), querytype, querystr);
935         wrbuf_free(wr, 1);
936     }
937 }
938
939 static char *srw_bend_explain_default(void *handle, bend_explain_rr *rr)
940 {
941 #if HAVE_XML2
942     xmlNodePtr ptr = rr->server_node_ptr;
943     if (!ptr)
944         return 0;
945     for (ptr = ptr->children; ptr; ptr = ptr->next)
946     {
947         if (ptr->type != XML_ELEMENT_NODE)
948             continue;
949         if (!strcmp((const char *) ptr->name, "explain"))
950         {
951             int len;
952             xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
953             xmlChar *buf_out;
954             char *content;
955
956             ptr = xmlCopyNode(ptr, 1);
957         
958             xmlDocSetRootElement(doc, ptr);
959             
960             xmlDocDumpMemory(doc, &buf_out, &len);
961             content = (char*) odr_malloc(rr->stream, 1+len);
962             memcpy(content, buf_out, len);
963             content[len] = '\0';
964             
965             xmlFree(buf_out);
966             xmlFreeDoc(doc);
967             rr->explain_buf = content;
968             return 0;
969         }
970     }
971 #endif
972     return 0;
973 }
974
975 static void srw_bend_explain(association *assoc, request *req,
976                              Z_SRW_explainRequest *srw_req,
977                              Z_SRW_explainResponse *srw_res,
978                              int *http_code)
979 {
980     yaz_log(log_requestdetail, "Got SRW ExplainRequest");
981     *http_code = 404;
982     srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics);
983     if (assoc->init)
984     {
985         bend_explain_rr rr;
986         
987         rr.stream = assoc->encode;
988         rr.decode = assoc->decode;
989         rr.print = assoc->print;
990         rr.explain_buf = 0;
991         rr.database = srw_req->database;
992         rr.server_node_ptr = assoc->server_node_ptr;
993         rr.schema = "http://explain.z3950.org/dtd/2.0/";
994         if (assoc->init->bend_explain)
995             (*assoc->init->bend_explain)(assoc->backend, &rr);
996         else
997             srw_bend_explain_default(assoc->backend, &rr);
998
999         if (rr.explain_buf)
1000         {
1001             int packing = Z_SRW_recordPacking_string;
1002             if (srw_req->recordPacking)
1003             {
1004                 if (!strcmp(srw_req->recordPacking, "xml"))
1005                     packing = Z_SRW_recordPacking_XML;
1006                 else if (!strcmp(srw_req->recordPacking, "url"))
1007                     packing = Z_SRW_recordPacking_URL;
1008             }
1009             srw_res->record.recordSchema = rr.schema;
1010             srw_res->record.recordPacking = packing;
1011             srw_res->record.recordData_buf = rr.explain_buf;
1012             srw_res->record.recordData_len = strlen(rr.explain_buf);
1013             srw_res->record.recordPosition = 0;
1014             *http_code = 200;
1015         }
1016     }
1017 }
1018
1019 static void srw_bend_scan(association *assoc, request *req,
1020                           Z_SRW_scanRequest *srw_req,
1021                           Z_SRW_scanResponse *srw_res,
1022                           int *http_code)
1023 {
1024     yaz_log(log_requestdetail, "Got SRW ScanRequest");
1025
1026     *http_code = 200;
1027     srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics);
1028     if (srw_res->num_diagnostics == 0 && assoc->init)
1029     {
1030         struct scan_entry *save_entries;
1031
1032         bend_scan_rr *bsrr = (bend_scan_rr *)
1033             odr_malloc (assoc->encode, sizeof(*bsrr));
1034         bsrr->num_bases = 1;
1035         bsrr->basenames = &srw_req->database;
1036
1037         bsrr->num_entries = srw_req->maximumTerms ?
1038             *srw_req->maximumTerms : 10;
1039         bsrr->term_position = srw_req->responsePosition ?
1040             *srw_req->responsePosition : 1;
1041
1042         bsrr->errcode = 0;
1043         bsrr->errstring = 0;
1044         bsrr->referenceId = 0;
1045         bsrr->stream = assoc->encode;
1046         bsrr->print = assoc->print;
1047         bsrr->step_size = odr_intdup(assoc->decode, 0);
1048         bsrr->entries = 0;
1049
1050         if (bsrr->num_entries > 0) 
1051         {
1052             int i;
1053             bsrr->entries = odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
1054                                        bsrr->num_entries);
1055             for (i = 0; i<bsrr->num_entries; i++)
1056             {
1057                 bsrr->entries[i].term = 0;
1058                 bsrr->entries[i].occurrences = 0;
1059                 bsrr->entries[i].errcode = 0;
1060                 bsrr->entries[i].errstring = 0;
1061                 bsrr->entries[i].display_term = 0;
1062             }
1063         }
1064         save_entries = bsrr->entries;  /* save it so we can compare later */
1065
1066         if (srw_req->query_type == Z_SRW_query_type_pqf &&
1067             assoc->init->bend_scan)
1068         {
1069             Odr_oid *scan_attributeSet = 0;
1070             oident *attset;
1071             YAZ_PQF_Parser pqf_parser = yaz_pqf_create();
1072             
1073             bsrr->term = yaz_pqf_scan(pqf_parser, assoc->decode,
1074                                       &scan_attributeSet, 
1075                                       srw_req->scanClause.pqf); 
1076             if (scan_attributeSet &&
1077                 (attset = oid_getentbyoid(scan_attributeSet)) &&
1078                 (attset->oclass == CLASS_ATTSET ||
1079                  attset->oclass == CLASS_GENERAL))
1080                 bsrr->attributeset = attset->value;
1081             else
1082                 bsrr->attributeset = VAL_NONE;
1083             yaz_pqf_destroy(pqf_parser);
1084             bsrr->scanClause = 0;
1085             ((int (*)(void *, bend_scan_rr *))
1086              (*assoc->init->bend_scan))(assoc->backend, bsrr);
1087         }
1088         else if (srw_req->query_type == Z_SRW_query_type_cql
1089                  && assoc->init->bend_srw_scan)
1090         {
1091             if (assoc->cql_transform)
1092             {
1093                 int srw_error;
1094                 bsrr->scanClause = 0;
1095                 bsrr->attributeset = VAL_NONE;
1096                 bsrr->term = odr_malloc(assoc->decode, sizeof(*bsrr->term));
1097                 srw_error = cql2pqf_scan(assoc->encode,
1098                                              srw_req->scanClause.cql,
1099                                              assoc->cql_transform,
1100                                              bsrr->term);
1101                 if (srw_error)
1102                     yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1103                                            &srw_res->num_diagnostics,
1104                                            srw_error, 0);
1105                 else
1106                 {
1107                     ((int (*)(void *, bend_scan_rr *))
1108                      (*assoc->init->bend_scan))(assoc->backend, bsrr);
1109                 }
1110             }
1111             else
1112             {
1113                 bsrr->term = 0;
1114                 bsrr->attributeset = VAL_NONE;
1115                 bsrr->scanClause = srw_req->scanClause.cql;
1116                 ((int (*)(void *, bend_scan_rr *))
1117                  (*assoc->init->bend_srw_scan))(assoc->backend, bsrr);
1118             }
1119         }
1120         else
1121         {
1122             yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1123                                    &srw_res->num_diagnostics,
1124                                    YAZ_SRW_UNSUPP_OPERATION, "scan");
1125         }
1126         if (bsrr->errcode)
1127         {
1128             int srw_error;
1129             if (bsrr->errcode == YAZ_BIB1_DATABASE_UNAVAILABLE)
1130             {
1131                 *http_code = 404;
1132                 return;
1133             }
1134             srw_error = yaz_diag_bib1_to_srw (bsrr->errcode);
1135
1136             yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1137                                    &srw_res->num_diagnostics,
1138                                    srw_error, bsrr->errstring);
1139         }
1140         else if (srw_res->num_diagnostics == 0 && bsrr->num_entries)
1141         {
1142             int i;
1143             srw_res->terms = (Z_SRW_scanTerm*)
1144                 odr_malloc(assoc->encode, sizeof(*srw_res->terms) *
1145                            bsrr->num_entries);
1146
1147             srw_res->num_terms =  bsrr->num_entries;
1148             for (i = 0; i<bsrr->num_entries; i++)
1149             {
1150                 Z_SRW_scanTerm *t = srw_res->terms + i;
1151                 t->value = odr_strdup(assoc->encode, bsrr->entries[i].term);
1152                 t->numberOfRecords =
1153                     odr_intdup(assoc->encode, bsrr->entries[i].occurrences);
1154                 t->displayTerm = 0;
1155                 if (save_entries == bsrr->entries && 
1156                     bsrr->entries[i].display_term)
1157                 {
1158                     /* the entries was _not_ set by the handler. So it's
1159                        safe to test for new member display_term. It is
1160                        NULL'ed by us.
1161                     */
1162                     t->displayTerm = odr_strdup(assoc->encode, 
1163                                                 bsrr->entries[i].display_term);
1164                 }
1165                 t->whereInList = 0;
1166             }
1167         }
1168     }
1169     if (log_request)
1170     {
1171         WRBUF wr = wrbuf_alloc();
1172         const char *querytype = 0;
1173         const char *querystr = 0;
1174
1175         switch(srw_req->query_type)
1176         {
1177         case Z_SRW_query_type_pqf:
1178             querytype = "PQF";
1179             querystr = srw_req->scanClause.pqf;
1180             break;
1181         case Z_SRW_query_type_cql:
1182             querytype = "CQL";
1183             querystr = srw_req->scanClause.cql;
1184             break;
1185         default:
1186             querytype = "Unknown";
1187             querystr = "";
1188         }
1189         wrbuf_printf(wr, "SRWScan %d+%d",
1190                      (srw_req->responsePosition ? 
1191                       *srw_req->responsePosition : 1),
1192                      (srw_req->maximumTerms ?
1193                       *srw_req->maximumTerms : 1));
1194         if (srw_res->num_diagnostics)
1195             wrbuf_printf(wr, " ERROR %s", srw_res->diagnostics[0].uri);
1196         else
1197             wrbuf_printf(wr, " OK -");
1198         wrbuf_printf(wr, " %s: %s", querytype, querystr);
1199         yaz_log(log_request, "%s", wrbuf_buf(wr) );
1200         wrbuf_free(wr, 1);
1201     }
1202
1203 }
1204
1205 static void srw_bend_update(association *assoc, request *req,
1206                             Z_SRW_updateRequest *srw_req,
1207                             Z_SRW_updateResponse *srw_res,
1208                             int *http_code)
1209 {
1210     yaz_log(YLOG_DEBUG, "Got SRW UpdateRequest");
1211     yaz_log(YLOG_DEBUG, "num_diag = %d", srw_res->num_diagnostics );
1212     *http_code = 404;
1213     srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics);
1214     if (assoc->init)
1215     {
1216         bend_update_rr rr;
1217         
1218         rr.stream = assoc->encode;
1219         rr.print = assoc->print;
1220         rr.num_bases = 1;
1221         rr.basenames = &srw_req->database;
1222         rr.operation = srw_req->operation;
1223         rr.operation_status = "failed";
1224         rr.record_id = 0;
1225         rr.record_version = 0;
1226         rr.record_checksum = 0;
1227         rr.record_old_version = 0;
1228         rr.record_packing = "xml";
1229         rr.record_schema = 0;
1230         rr.record_data = 0;
1231         rr.request_extra_record = 0;
1232         rr.response_extra_record = 0;
1233         rr.extra_request_data = 0;
1234         rr.extra_response_data = 0;
1235         rr.errcode = 0;
1236         rr.errstring = 0;
1237
1238         yaz_log(YLOG_DEBUG, "basename = %s", rr.basenames[0] );
1239         yaz_log(YLOG_DEBUG, "Operation = %s", rr.operation );
1240         if ( !strcmp( rr.operation, "delete" ) ){
1241             if ( !srw_req->recordId ){
1242                 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1243                                        &srw_res->num_diagnostics,
1244                                        7, "recordId" );
1245             }
1246             else {
1247                 rr.record_id = srw_req->recordId;
1248             }
1249             if (  !srw_req->recordVersion ){
1250                 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1251                                        &srw_res->num_diagnostics,
1252                                        7, "recordVersion" );
1253             }
1254             else {
1255                 rr.record_version = odr_strdup( assoc->encode,
1256                                                 srw_req->recordVersion );
1257                 
1258             }
1259             if ( srw_req->recordOldVersion ){
1260                 rr.record_old_version = odr_strdup(assoc->encode,
1261                                                    srw_req->recordOldVersion );
1262             }
1263             if ( srw_req->extraRequestData ){
1264                 rr.extra_request_data = odr_strdup(assoc->encode,
1265                                                    srw_req->extraRequestData );
1266             }
1267         }
1268         else if ( !strcmp( rr.operation, "replace" ) ){
1269             if ( !srw_req->recordId ){
1270                 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1271                                        &srw_res->num_diagnostics,
1272                                        7, "recordId" );
1273             }
1274             else {
1275                 rr.record_id = srw_req->recordId;
1276             }
1277             if ( srw_req->record.recordSchema == 0 ){
1278                 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1279                                        &srw_res->num_diagnostics,
1280                                        7, "recordSchema" );
1281             }
1282             else {
1283                 rr.record_schema = odr_strdup(assoc->encode,
1284                                               srw_req->record.recordSchema );
1285             }
1286             switch (srw_req->record.recordPacking)
1287             {
1288             case Z_SRW_recordPacking_string: 
1289                 rr.record_packing = "string";
1290                 break;
1291             case Z_SRW_recordPacking_XML: 
1292                 rr.record_packing = "xml";
1293                 break;
1294             case Z_SRW_recordPacking_URL: 
1295                 rr.record_packing = "url";
1296                 break;
1297             }
1298             if ( srw_req->record.recordData_len ){
1299                 rr.record_data = odr_strdupn(assoc->encode, 
1300                                              srw_req->record.recordData_buf,
1301                                              srw_req->record.recordData_len );
1302                 rr.request_extra_record = srw_req->extra_record;
1303             }
1304             else {
1305                 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1306                                        &srw_res->num_diagnostics,
1307                                        7, "recordData" );
1308             }
1309             if (srw_req->extraRequestData)
1310                 rr.extra_request_data = odr_strdup(assoc->encode,
1311                                                    srw_req->extraRequestData );
1312         }
1313         else if ( !strcmp( rr.operation, "insert" ) )
1314         {
1315             if ( srw_req->record.recordSchema == 0 ){
1316                 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1317                                        &srw_res->num_diagnostics,
1318                                        7, "recordSchema" );
1319             }
1320             else {
1321                 rr.record_schema = odr_strdup(assoc->encode,
1322                                               srw_req->record.recordSchema);
1323             }
1324             switch (srw_req->record.recordPacking)
1325             {
1326             case Z_SRW_recordPacking_string: 
1327                 rr.record_packing = "string";
1328                 break;
1329             case Z_SRW_recordPacking_XML: 
1330                 rr.record_packing = "xml";
1331                 break;
1332             case Z_SRW_recordPacking_URL: 
1333                 rr.record_packing = "url";
1334                 break;
1335             }
1336             
1337             if (srw_req->record.recordData_len)
1338             {
1339                 rr.record_data = odr_strdupn(assoc->encode, 
1340                                              srw_req->record.recordData_buf,
1341                                              srw_req->record.recordData_len );
1342                 rr.request_extra_record = srw_req->extra_record;
1343             }
1344             else
1345                 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1346                                        &srw_res->num_diagnostics,
1347                                        7, "recordData" );
1348             if ( srw_req->extraRequestData )
1349                 rr.extra_request_data = odr_strdup(assoc->encode,
1350                                                    srw_req->extraRequestData );
1351         }
1352         if (srw_res->num_diagnostics == 0)
1353         {
1354             if ( assoc->init->bend_srw_update)
1355                 (*assoc->init->bend_srw_update)(assoc->backend, &rr);
1356             else {
1357                 yaz_log( YLOG_WARN, "Got No Update function!");
1358                 return;
1359             }
1360         }
1361         if (rr.errcode)
1362             yaz_add_srw_diagnostic(assoc->encode,
1363                                    &srw_res->diagnostics,
1364                                    &srw_res->num_diagnostics,
1365                                    rr.errcode, rr.errstring);
1366         srw_res->recordId = rr.record_id;
1367         srw_res->operationStatus = rr.operation_status;
1368         srw_res->recordVersion = rr.record_version;
1369         srw_res->recordChecksum = rr.record_checksum;
1370         srw_res->extraResponseData = rr.extra_response_data;
1371         srw_res->record.recordPosition = 0;
1372         if (srw_res->num_diagnostics == 0 && rr.record_data)
1373         {
1374             srw_res->record.recordSchema = rr.record_schema;
1375             srw_res->record.recordPacking = srw_req->record.recordPacking;
1376             srw_res->record.recordData_buf = rr.record_data;
1377             srw_res->record.recordData_len = strlen(rr.record_data);
1378             srw_res->extra_record = rr.response_extra_record;
1379                 
1380         }
1381         else
1382             srw_res->record.recordData_len = 0;
1383         *http_code = 200;
1384     }
1385 }
1386
1387 static void process_http_request(association *assoc, request *req)
1388 {
1389     Z_HTTP_Request *hreq = req->gdu_request->u.HTTP_Request;
1390     ODR o = assoc->encode;
1391     int r = 2;  /* 2=NOT TAKEN, 1=TAKEN, 0=SOAP TAKEN */
1392     Z_SRW_PDU *sr = 0;
1393     Z_SOAP *soap_package = 0;
1394     Z_GDU *p = 0;
1395     char *charset = 0;
1396     Z_HTTP_Response *hres = 0;
1397     int keepalive = 1;
1398     char *stylesheet = 0;
1399     Z_SRW_diagnostic *diagnostic = 0;
1400     int num_diagnostic = 0;
1401     const char *host = z_HTTP_header_lookup(hreq->headers, "Host");
1402
1403     if (!control_association(assoc, host, 0))
1404     {
1405         p = z_get_HTTP_Response(o, 404);
1406         r = 1;
1407     }
1408     if (r == 2 && !strcmp(hreq->path, "/test")) 
1409     {   
1410         p = z_get_HTTP_Response(o, 200);
1411         hres = p->u.HTTP_Response;
1412         hres->content_buf = "1234567890\n";
1413         hres->content_len = strlen(hres->content_buf);
1414         r = 1;
1415     }
1416     if (r == 2)
1417     {
1418         r = yaz_srw_decode(hreq, &sr, &soap_package, assoc->decode, &charset);
1419         yaz_log(YLOG_DEBUG, "yaz_srw_decode returned %d", r);
1420     }
1421     if (r == 2)  /* not taken */
1422     {
1423         r = yaz_sru_decode(hreq, &sr, &soap_package, assoc->decode, &charset,
1424                            &diagnostic, &num_diagnostic);
1425         yaz_log(YLOG_DEBUG, "yaz_sru_decode returned %d", r);
1426     }
1427     if (r == 0)  /* decode SRW/SRU OK .. */
1428     {
1429         int http_code = 200;
1430         if (sr->which == Z_SRW_searchRetrieve_request)
1431         {
1432             Z_SRW_PDU *res =
1433                 yaz_srw_get(assoc->encode, Z_SRW_searchRetrieve_response);
1434
1435             stylesheet = sr->u.request->stylesheet;
1436             if (num_diagnostic)
1437             {
1438                 res->u.response->diagnostics = diagnostic;
1439                 res->u.response->num_diagnostics = num_diagnostic;
1440             }
1441             else
1442             {
1443                 srw_bend_search(assoc, req, sr->u.request, res->u.response, 
1444                                 &http_code);
1445             }
1446             if (http_code == 200)
1447                 soap_package->u.generic->p = res;
1448         }
1449         else if (sr->which == Z_SRW_explain_request)
1450         {
1451             Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_explain_response);
1452             stylesheet = sr->u.explain_request->stylesheet;
1453             if (num_diagnostic)
1454             {   
1455                 res->u.explain_response->diagnostics = diagnostic;
1456                 res->u.explain_response->num_diagnostics = num_diagnostic;
1457             }
1458             srw_bend_explain(assoc, req, sr->u.explain_request,
1459                              res->u.explain_response, &http_code);
1460             if (http_code == 200)
1461                 soap_package->u.generic->p = res;
1462         }
1463         else if (sr->which == Z_SRW_scan_request)
1464         {
1465             Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_scan_response);
1466             stylesheet = sr->u.scan_request->stylesheet;
1467             if (num_diagnostic)
1468             {   
1469                 res->u.scan_response->diagnostics = diagnostic;
1470                 res->u.scan_response->num_diagnostics = num_diagnostic;
1471             }
1472             srw_bend_scan(assoc, req, sr->u.scan_request,
1473                           res->u.scan_response, &http_code);
1474             if (http_code == 200)
1475                 soap_package->u.generic->p = res;
1476         }
1477         else if (sr->which == Z_SRW_update_request)
1478         {
1479             Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_update_response);
1480             yaz_log(YLOG_DEBUG, "handling SRW UpdateRequest");
1481             if (num_diagnostic)
1482             {   
1483                 res->u.update_response->diagnostics = diagnostic;
1484                 res->u.update_response->num_diagnostics = num_diagnostic;
1485             }
1486             yaz_log(YLOG_DEBUG, "num_diag = %d", res->u.update_response->num_diagnostics );
1487             srw_bend_update(assoc, req, sr->u.update_request,
1488                             res->u.update_response, &http_code);
1489             if (http_code == 200)
1490                 soap_package->u.generic->p = res;
1491         }
1492         else
1493         {
1494             yaz_log(log_request, "SOAP ERROR"); 
1495             /* FIXME - what error, what query */
1496             http_code = 500;
1497             z_soap_error(assoc->encode, soap_package,
1498                          "SOAP-ENV:Client", "Bad method", 0); 
1499         }
1500         if (http_code == 200 || http_code == 500)
1501         {
1502             static Z_SOAP_Handler soap_handlers[4] = {
1503 #if HAVE_XML2
1504                 {"http://www.loc.gov/zing/srw/", 0,
1505                  (Z_SOAP_fun) yaz_srw_codec},
1506                 {"http://www.loc.gov/zing/srw/v1.0/", 0,
1507                  (Z_SOAP_fun) yaz_srw_codec},
1508                 {"http://www.loc.gov/zing/srw/update/", 0,
1509                  (Z_SOAP_fun) yaz_ucp_codec},
1510 #endif
1511                 {0, 0, 0}
1512             };
1513             char ctype[60];
1514             int ret;
1515             p = z_get_HTTP_Response(o, 200);
1516             hres = p->u.HTTP_Response;
1517             ret = z_soap_codec_enc_xsl(assoc->encode, &soap_package,
1518                                        &hres->content_buf, &hres->content_len,
1519                                        soap_handlers, charset, stylesheet);
1520             hres->code = http_code;
1521
1522             strcpy(ctype, "text/xml");
1523             if (charset)
1524             {
1525                 strcat(ctype, "; charset=");
1526                 strcat(ctype, charset);
1527             }
1528             z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1529         }
1530         else
1531             p = z_get_HTTP_Response(o, http_code);
1532     }
1533
1534     if (p == 0)
1535         p = z_get_HTTP_Response(o, 500);
1536     hres = p->u.HTTP_Response;
1537     if (!strcmp(hreq->version, "1.0")) 
1538     {
1539         const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1540         if (v && !strcmp(v, "Keep-Alive"))
1541             keepalive = 1;
1542         else
1543             keepalive = 0;
1544         hres->version = "1.0";
1545     }
1546     else
1547     {
1548         const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1549         if (v && !strcmp(v, "close"))
1550             keepalive = 0;
1551         else
1552             keepalive = 1;
1553         hres->version = "1.1";
1554     }
1555     if (!keepalive)
1556     {
1557         z_HTTP_header_add(o, &hres->headers, "Connection", "close");
1558         assoc->state = ASSOC_DEAD;
1559         assoc->cs_get_mask = 0;
1560     }
1561     else
1562     {
1563         int t;
1564         const char *alive = z_HTTP_header_lookup(hreq->headers, "Keep-Alive");
1565
1566         if (alive && isdigit(*(const unsigned char *) alive))
1567             t = atoi(alive);
1568         else
1569             t = 15;
1570         if (t < 0 || t > 3600)
1571             t = 3600;
1572         iochan_settimeout(assoc->client_chan,t);
1573         z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1574     }
1575     process_gdu_response(assoc, req, p);
1576 }
1577
1578 static void process_gdu_request(association *assoc, request *req)
1579 {
1580     if (req->gdu_request->which == Z_GDU_Z3950)
1581     {
1582         char *msg = 0;
1583         req->apdu_request = req->gdu_request->u.z3950;
1584         if (process_z_request(assoc, req, &msg) < 0)
1585             do_close_req(assoc, Z_Close_systemProblem, msg, req);
1586     }
1587     else if (req->gdu_request->which == Z_GDU_HTTP_Request)
1588         process_http_request(assoc, req);
1589     else
1590     {
1591         do_close_req(assoc, Z_Close_systemProblem, "bad protocol packet", req);
1592     }
1593 }
1594
1595 /*
1596  * Initiate request processing.
1597  */
1598 static int process_z_request(association *assoc, request *req, char **msg)
1599 {
1600     int fd = -1;
1601     Z_APDU *res;
1602     int retval;
1603     
1604     *msg = "Unknown Error";
1605     assert(req && req->state == REQUEST_IDLE);
1606     if (req->apdu_request->which != Z_APDU_initRequest && !assoc->init)
1607     {
1608         *msg = "Missing InitRequest";
1609         return -1;
1610     }
1611     switch (req->apdu_request->which)
1612     {
1613     case Z_APDU_initRequest:
1614         res = process_initRequest(assoc, req); break;
1615     case Z_APDU_searchRequest:
1616         res = process_searchRequest(assoc, req, &fd); break;
1617     case Z_APDU_presentRequest:
1618         res = process_presentRequest(assoc, req, &fd); break;
1619     case Z_APDU_scanRequest:
1620         if (assoc->init->bend_scan)
1621             res = process_scanRequest(assoc, req, &fd);
1622         else
1623         {
1624             *msg = "Cannot handle Scan APDU";
1625             return -1;
1626         }
1627         break;
1628     case Z_APDU_extendedServicesRequest:
1629         if (assoc->init->bend_esrequest)
1630             res = process_ESRequest(assoc, req, &fd);
1631         else
1632         {
1633             *msg = "Cannot handle Extended Services APDU";
1634             return -1;
1635         }
1636         break;
1637     case Z_APDU_sortRequest:
1638         if (assoc->init->bend_sort)
1639             res = process_sortRequest(assoc, req, &fd);
1640         else
1641         {
1642             *msg = "Cannot handle Sort APDU";
1643             return -1;
1644         }
1645         break;
1646     case Z_APDU_close:
1647         process_close(assoc, req);
1648         return 0;
1649     case Z_APDU_deleteResultSetRequest:
1650         if (assoc->init->bend_delete)
1651             res = process_deleteRequest(assoc, req, &fd);
1652         else
1653         {
1654             *msg = "Cannot handle Delete APDU";
1655             return -1;
1656         }
1657         break;
1658     case Z_APDU_segmentRequest:
1659         if (assoc->init->bend_segment)
1660         {
1661             res = process_segmentRequest (assoc, req);
1662         }
1663         else
1664         {
1665             *msg = "Cannot handle Segment APDU";
1666             return -1;
1667         }
1668         break;
1669     case Z_APDU_triggerResourceControlRequest:
1670         return 0;
1671     default:
1672         *msg = "Bad APDU received";
1673         return -1;
1674     }
1675     if (res)
1676     {
1677         yaz_log(YLOG_DEBUG, "  result immediately available");
1678         retval = process_z_response(assoc, req, res);
1679     }
1680     else if (fd < 0)
1681     {
1682         yaz_log(YLOG_DEBUG, "  result unavailble");
1683         retval = 0;
1684     }
1685     else /* no result yet - one will be provided later */
1686     {
1687         IOCHAN chan;
1688
1689         /* Set up an I/O handler for the fd supplied by the backend */
1690
1691         yaz_log(YLOG_DEBUG, "   establishing handler for result");
1692         req->state = REQUEST_PENDING;
1693         if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT, 0)))
1694             abort();
1695         iochan_setdata(chan, assoc);
1696         retval = 0;
1697     }
1698     return retval;
1699 }
1700
1701 /*
1702  * Handle message from the backend.
1703  */
1704 void backend_response(IOCHAN i, int event)
1705 {
1706     association *assoc = (association *)iochan_getdata(i);
1707     request *req = request_head(&assoc->incoming);
1708     Z_APDU *res;
1709     int fd;
1710
1711     yaz_log(YLOG_DEBUG, "backend_response");
1712     assert(assoc && req && req->state != REQUEST_IDLE);
1713     /* determine what it is we're waiting for */
1714     switch (req->apdu_request->which)
1715     {
1716         case Z_APDU_searchRequest:
1717             res = response_searchRequest(assoc, req, 0, &fd); break;
1718 #if 0
1719         case Z_APDU_presentRequest:
1720             res = response_presentRequest(assoc, req, 0, &fd); break;
1721         case Z_APDU_scanRequest:
1722             res = response_scanRequest(assoc, req, 0, &fd); break;
1723 #endif
1724         default:
1725             yaz_log(YLOG_FATAL, "Serious programmer's lapse or bug");
1726             abort();
1727     }
1728     if ((res && process_z_response(assoc, req, res) < 0) || fd < 0)
1729     {
1730         yaz_log(YLOG_WARN, "Fatal error when talking to backend");
1731         do_close(assoc, Z_Close_systemProblem, 0);
1732         iochan_destroy(i);
1733         return;
1734     }
1735     else if (!res) /* no result yet - try again later */
1736     {
1737         yaz_log(YLOG_DEBUG, "   no result yet");
1738         iochan_setfd(i, fd); /* in case fd has changed */
1739     }
1740 }
1741
1742 /*
1743  * Encode response, and transfer the request structure to the outgoing queue.
1744  */
1745 static int process_gdu_response(association *assoc, request *req, Z_GDU *res)
1746 {
1747     odr_setbuf(assoc->encode, req->response, req->size_response, 1);
1748
1749     if (assoc->print)
1750     {
1751         if (!z_GDU(assoc->print, &res, 0, 0))
1752             yaz_log(YLOG_WARN, "ODR print error: %s", 
1753                 odr_errmsg(odr_geterror(assoc->print)));
1754         odr_reset(assoc->print);
1755     }
1756     if (!z_GDU(assoc->encode, &res, 0, 0))
1757     {
1758         yaz_log(YLOG_WARN, "ODR error when encoding PDU: %s [element %s]",
1759                 odr_errmsg(odr_geterror(assoc->decode)),
1760                 odr_getelement(assoc->decode));
1761         return -1;
1762     }
1763     req->response = odr_getbuf(assoc->encode, &req->len_response,
1764         &req->size_response);
1765     odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
1766     odr_reset(assoc->encode);
1767     req->state = REQUEST_IDLE;
1768     request_enq(&assoc->outgoing, req);
1769     /* turn the work over to the ir_session handler */
1770     iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
1771     assoc->cs_put_mask = EVENT_OUTPUT;
1772     /* Is there more work to be done? give that to the input handler too */
1773 #if 1
1774     if (request_head(&assoc->incoming))
1775     {
1776         yaz_log (YLOG_DEBUG, "more work to be done");
1777         iochan_setevent(assoc->client_chan, EVENT_WORK);
1778     }
1779 #endif
1780     return 0;
1781 }
1782
1783 /*
1784  * Encode response, and transfer the request structure to the outgoing queue.
1785  */
1786 static int process_z_response(association *assoc, request *req, Z_APDU *res)
1787 {
1788     Z_GDU *gres = (Z_GDU *) odr_malloc(assoc->encode, sizeof(*res));
1789     gres->which = Z_GDU_Z3950;
1790     gres->u.z3950 = res;
1791
1792     return process_gdu_response(assoc, req, gres);
1793 }
1794
1795 static char *get_vhost(Z_OtherInformation *otherInfo)
1796 {
1797     return yaz_oi_get_string_oidval(&otherInfo, VAL_PROXY, 1, 0);
1798 }
1799
1800 /*
1801  * Handle init request.
1802  * At the moment, we don't check the options
1803  * anywhere else in the code - we just try not to do anything that would
1804  * break a naive client. We'll toss 'em into the association block when
1805  * we need them there.
1806  */
1807 static Z_APDU *process_initRequest(association *assoc, request *reqb)
1808 {
1809     Z_InitRequest *req = reqb->apdu_request->u.initRequest;
1810     Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
1811     Z_InitResponse *resp = apdu->u.initResponse;
1812     bend_initresult *binitres;
1813     char *version;
1814     char options[140];
1815     statserv_options_block *cb = 0;  /* by default no control for backend */
1816
1817     if (control_association(assoc, get_vhost(req->otherInfo), 1))
1818         cb = statserv_getcontrol();  /* got control block for backend */
1819
1820     if (cb && assoc->backend)
1821         (*cb->bend_close)(assoc->backend);
1822
1823     yaz_log(log_requestdetail, "Got initRequest");
1824     if (req->implementationId)
1825         yaz_log(log_requestdetail, "Id:        %s",
1826                 req->implementationId);
1827     if (req->implementationName)
1828         yaz_log(log_requestdetail, "Name:      %s",
1829                 req->implementationName);
1830     if (req->implementationVersion)
1831         yaz_log(log_requestdetail, "Version:   %s",
1832                 req->implementationVersion);
1833     
1834     assoc_init_reset(assoc);
1835
1836     assoc->init->auth = req->idAuthentication;
1837     assoc->init->referenceId = req->referenceId;
1838
1839     if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
1840     {
1841         Z_CharSetandLanguageNegotiation *negotiation =
1842             yaz_get_charneg_record (req->otherInfo);
1843         if (negotiation &&
1844             negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
1845             assoc->init->charneg_request = negotiation;
1846     }
1847
1848     assoc->backend = 0;
1849     if (cb)
1850     {
1851         if (req->implementationVersion)
1852             yaz_log(log_requestdetail, "Config:    %s",
1853                     cb->configname);
1854     
1855         iochan_settimeout(assoc->client_chan, cb->idle_timeout * 60);
1856         
1857         /* we have a backend control block, so call that init function */
1858         if (!(binitres = (*cb->bend_init)(assoc->init)))
1859         {
1860             yaz_log(YLOG_WARN, "Bad response from backend.");
1861             return 0;
1862         }
1863         assoc->backend = binitres->handle;
1864     }
1865     else
1866     {
1867         /* no backend. return error */
1868         binitres = odr_malloc(assoc->encode, sizeof(*binitres));
1869         binitres->errstring = 0;
1870         binitres->errcode = YAZ_BIB1_PERMANENT_SYSTEM_ERROR;
1871         iochan_settimeout(assoc->client_chan, 10);
1872     }
1873     if ((assoc->init->bend_sort))
1874         yaz_log (YLOG_DEBUG, "Sort handler installed");
1875     if ((assoc->init->bend_search))
1876         yaz_log (YLOG_DEBUG, "Search handler installed");
1877     if ((assoc->init->bend_present))
1878         yaz_log (YLOG_DEBUG, "Present handler installed");   
1879     if ((assoc->init->bend_esrequest))
1880         yaz_log (YLOG_DEBUG, "ESRequest handler installed");   
1881     if ((assoc->init->bend_delete))
1882         yaz_log (YLOG_DEBUG, "Delete handler installed");   
1883     if ((assoc->init->bend_scan))
1884         yaz_log (YLOG_DEBUG, "Scan handler installed");   
1885     if ((assoc->init->bend_segment))
1886         yaz_log (YLOG_DEBUG, "Segment handler installed");   
1887     
1888     resp->referenceId = req->referenceId;
1889     *options = '\0';
1890     /* let's tell the client what we can do */
1891     if (ODR_MASK_GET(req->options, Z_Options_search))
1892     {
1893         ODR_MASK_SET(resp->options, Z_Options_search);
1894         strcat(options, "srch");
1895     }
1896     if (ODR_MASK_GET(req->options, Z_Options_present))
1897     {
1898         ODR_MASK_SET(resp->options, Z_Options_present);
1899         strcat(options, " prst");
1900     }
1901     if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
1902         assoc->init->bend_delete)
1903     {
1904         ODR_MASK_SET(resp->options, Z_Options_delSet);
1905         strcat(options, " del");
1906     }
1907     if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
1908         assoc->init->bend_esrequest)
1909     {
1910         ODR_MASK_SET(resp->options, Z_Options_extendedServices);
1911         strcat (options, " extendedServices");
1912     }
1913     if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
1914     {
1915         ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
1916         strcat(options, " namedresults");
1917     }
1918     if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
1919     {
1920         ODR_MASK_SET(resp->options, Z_Options_scan);
1921         strcat(options, " scan");
1922     }
1923     if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
1924     {
1925         ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
1926         strcat(options, " concurrop");
1927     }
1928     if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
1929     {
1930         ODR_MASK_SET(resp->options, Z_Options_sort);
1931         strcat(options, " sort");
1932     }
1933
1934     if (ODR_MASK_GET(req->options, Z_Options_negotiationModel)
1935         && assoc->init->charneg_response)
1936     {
1937         Z_OtherInformation **p;
1938         Z_OtherInformationUnit *p0;
1939         
1940         yaz_oi_APDU(apdu, &p);
1941         
1942         if ((p0=yaz_oi_update(p, assoc->encode, NULL, 0, 0))) {
1943             ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
1944             
1945             p0->which = Z_OtherInfo_externallyDefinedInfo;
1946             p0->information.externallyDefinedInfo =
1947                 assoc->init->charneg_response;
1948         }
1949         ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
1950         strcat(options, " negotiation");
1951     }
1952         
1953     ODR_MASK_SET(resp->options, Z_Options_triggerResourceCtrl);
1954
1955     if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
1956     {
1957         ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
1958         assoc->version = 1; /* 1 & 2 are equivalent */
1959     }
1960     if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
1961     {
1962         ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
1963         assoc->version = 2;
1964     }
1965     if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
1966     {
1967         ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
1968         assoc->version = 3;
1969     }
1970
1971     yaz_log(log_requestdetail, "Negotiated to v%d: %s", assoc->version, options);
1972     assoc->maximumRecordSize = *req->maximumRecordSize;
1973
1974     if (cb && assoc->maximumRecordSize > cb->maxrecordsize)
1975         assoc->maximumRecordSize = cb->maxrecordsize;
1976     assoc->preferredMessageSize = *req->preferredMessageSize;
1977     if (assoc->preferredMessageSize > assoc->maximumRecordSize)
1978         assoc->preferredMessageSize = assoc->maximumRecordSize;
1979
1980     resp->preferredMessageSize = &assoc->preferredMessageSize;
1981     resp->maximumRecordSize = &assoc->maximumRecordSize;
1982
1983     resp->implementationId = odr_prepend(assoc->encode,
1984                 assoc->init->implementation_id,
1985                 resp->implementationId);
1986
1987     resp->implementationName = odr_prepend(assoc->encode,
1988                 assoc->init->implementation_name,
1989                 odr_prepend(assoc->encode, "GFS", resp->implementationName));
1990
1991     version = odr_strdup(assoc->encode, "$Revision: 1.65 $");
1992     if (strlen(version) > 10)   /* check for unexpanded CVS strings */
1993         version[strlen(version)-2] = '\0';
1994     resp->implementationVersion = odr_prepend(assoc->encode,
1995                 assoc->init->implementation_version,
1996                 odr_prepend(assoc->encode, &version[11],
1997                             resp->implementationVersion));
1998
1999     if (binitres->errcode)
2000     {
2001         assoc->state = ASSOC_DEAD;
2002         resp->userInformationField =
2003             init_diagnostics(assoc->encode, binitres->errcode,
2004                              binitres->errstring);
2005         *resp->result = 0;
2006     }
2007     if (log_request)
2008     {
2009         if (!req->idAuthentication)
2010             yaz_log(log_request, "Auth none");
2011         else if (req->idAuthentication->which == Z_IdAuthentication_open)
2012         {
2013             const char *open = req->idAuthentication->u.open;
2014             const char *slash = strchr(open, '/');
2015             int len;
2016             if (slash)
2017                 len = slash - open;
2018             else
2019                 len = strlen(open);
2020                 yaz_log(log_request, "Auth open %.*s", len, open);
2021         }
2022         else if (req->idAuthentication->which == Z_IdAuthentication_idPass)
2023         {
2024             const char *user = req->idAuthentication->u.idPass->userId;
2025             const char *group = req->idAuthentication->u.idPass->groupId;
2026             yaz_log(log_request, "Auth idPass %s %s",
2027                     user ? user : "-", group ? group : "-");
2028         }
2029         else if (req->idAuthentication->which 
2030                  == Z_IdAuthentication_anonymous)
2031         {
2032             yaz_log(log_request, "Auth anonymous");
2033         }
2034         else
2035         {
2036             yaz_log(log_request, "Auth other");
2037         }
2038     }
2039     if (log_request)
2040     {
2041         WRBUF wr = wrbuf_alloc();
2042         wrbuf_printf(wr, "Init ");
2043         if (binitres->errcode)
2044             wrbuf_printf(wr, "ERROR %d", binitres->errcode);
2045         else
2046             wrbuf_printf(wr, "OK -");
2047         wrbuf_printf(wr, " ID:%s Name:%s Version:%s",
2048                      (req->implementationId ? req->implementationId :"-"), 
2049                      (req->implementationName ?
2050                       req->implementationName : "-"),
2051                      (req->implementationVersion ?
2052                       req->implementationVersion : "-")
2053             );
2054         yaz_log(log_request, "%s", wrbuf_buf(wr));
2055         wrbuf_free(wr, 1);
2056     }
2057     return apdu;
2058 }
2059
2060 /*
2061  * Set the specified `errcode' and `errstring' into a UserInfo-1
2062  * external to be returned to the client in accordance with Z35.90
2063  * Implementor Agreement 5 (Returning diagnostics in an InitResponse):
2064  *      http://lcweb.loc.gov/z3950/agency/agree/initdiag.html
2065  */
2066 static Z_External *init_diagnostics(ODR odr, int error, const char *addinfo)
2067 {
2068     yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2069         addinfo ? " -- " : "", addinfo ? addinfo : "");
2070     return zget_init_diagnostics(odr, error, addinfo);
2071 }
2072
2073 /*
2074  * nonsurrogate diagnostic record.
2075  */
2076 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
2077 {
2078     Z_Records *rec = (Z_Records *) odr_malloc (assoc->encode, sizeof(*rec));
2079
2080     yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2081             addinfo ? " -- " : "", addinfo ? addinfo : "");
2082
2083     rec->which = Z_Records_NSD;
2084     rec->u.nonSurrogateDiagnostic = zget_DefaultDiagFormat(assoc->encode,
2085                                                            error, addinfo);
2086     return rec;
2087 }
2088
2089 /*
2090  * surrogate diagnostic.
2091  */
2092 static Z_NamePlusRecord *surrogatediagrec(association *assoc, 
2093                                           const char *dbname,
2094                                           int error, const char *addinfo)
2095 {
2096     yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2097             addinfo ? " -- " : "", addinfo ? addinfo : "");
2098     return zget_surrogateDiagRec(assoc->encode, dbname, error, addinfo);
2099 }
2100
2101 static Z_Records *pack_records(association *a, char *setname, int start,
2102                                int *num, Z_RecordComposition *comp,
2103                                int *next, int *pres, oid_value format,
2104                                Z_ReferenceId *referenceId,
2105                                int *oid, int *errcode)
2106 {
2107     int recno, total_length = 0, toget = *num, dumped_records = 0;
2108     Z_Records *records =
2109         (Z_Records *) odr_malloc (a->encode, sizeof(*records));
2110     Z_NamePlusRecordList *reclist =
2111         (Z_NamePlusRecordList *) odr_malloc (a->encode, sizeof(*reclist));
2112     Z_NamePlusRecord **list =
2113         (Z_NamePlusRecord **) odr_malloc (a->encode, sizeof(*list) * toget);
2114
2115     records->which = Z_Records_DBOSD;
2116     records->u.databaseOrSurDiagnostics = reclist;
2117     reclist->num_records = 0;
2118     reclist->records = list;
2119     *pres = Z_PresentStatus_success;
2120     *num = 0;
2121     *next = 0;
2122
2123     yaz_log(log_requestdetail, "Request to pack %d+%d %s", start, toget, setname);
2124     yaz_log(log_requestdetail, "pms=%d, mrs=%d", a->preferredMessageSize,
2125         a->maximumRecordSize);
2126     for (recno = start; reclist->num_records < toget; recno++)
2127     {
2128         bend_fetch_rr freq;
2129         Z_NamePlusRecord *thisrec;
2130         int this_length = 0;
2131         /*
2132          * we get the number of bytes allocated on the stream before any
2133          * allocation done by the backend - this should give us a reasonable
2134          * idea of the total size of the data so far.
2135          */
2136         total_length = odr_total(a->encode) - dumped_records;
2137         freq.errcode = 0;
2138         freq.errstring = 0;
2139         freq.basename = 0;
2140         freq.len = 0;
2141         freq.record = 0;
2142         freq.last_in_set = 0;
2143         freq.setname = setname;
2144         freq.surrogate_flag = 0;
2145         freq.number = recno;
2146         freq.comp = comp;
2147         freq.request_format = format;
2148         freq.request_format_raw = oid;
2149         freq.output_format = format;
2150         freq.output_format_raw = 0;
2151         freq.stream = a->encode;
2152         freq.print = a->print;
2153         freq.referenceId = referenceId;
2154         freq.schema = 0;
2155         (*a->init->bend_fetch)(a->backend, &freq);
2156
2157         *next = freq.last_in_set ? 0 : recno + 1;
2158
2159         /* backend should be able to signal whether error is system-wide
2160            or only pertaining to current record */
2161         if (freq.errcode)
2162         {
2163             if (!freq.surrogate_flag)
2164             {
2165                 char s[20];
2166                 *pres = Z_PresentStatus_failure;
2167                 /* for 'present request out of range',
2168                    set addinfo to record position if not set */
2169                 if (freq.errcode == YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE  && 
2170                                 freq.errstring == 0)
2171                 {
2172                     sprintf (s, "%d", recno);
2173                     freq.errstring = s;
2174                 }
2175                 if (errcode)
2176                     *errcode = freq.errcode;
2177                 return diagrec(a, freq.errcode, freq.errstring);
2178             }
2179             reclist->records[reclist->num_records] =
2180                 surrogatediagrec(a, freq.basename, freq.errcode,
2181                                  freq.errstring);
2182             reclist->num_records++;
2183             continue;
2184         }
2185         if (freq.record == 0)  /* no error and no record ? */
2186         {
2187             *next = 0;   /* signal end-of-set and stop */
2188             break;
2189         }
2190         if (freq.len >= 0)
2191             this_length = freq.len;
2192         else
2193             this_length = odr_total(a->encode) - total_length - dumped_records;
2194         yaz_log(YLOG_DEBUG, "  fetched record, len=%d, total=%d dumped=%d",
2195             this_length, total_length, dumped_records);
2196         if (a->preferredMessageSize > 0 &&
2197                 this_length + total_length > a->preferredMessageSize)
2198         {
2199             /* record is small enough, really */
2200             if (this_length <= a->preferredMessageSize && recno > start)
2201             {
2202                 yaz_log(log_requestdetail, "  Dropped last normal-sized record");
2203                 *pres = Z_PresentStatus_partial_2;
2204                 break;
2205             }
2206             /* record can only be fetched by itself */
2207             if (this_length < a->maximumRecordSize)
2208             {
2209                 yaz_log(log_requestdetail, "  Record > prefmsgsz");
2210                 if (toget > 1)
2211                 {
2212                     yaz_log(YLOG_DEBUG, "  Dropped it");
2213                     reclist->records[reclist->num_records] =
2214                          surrogatediagrec(a, freq.basename, 16, 0);
2215                     reclist->num_records++;
2216                     dumped_records += this_length;
2217                     continue;
2218                 }
2219             }
2220             else /* too big entirely */
2221             {
2222                 yaz_log(log_requestdetail, "Record > maxrcdsz this=%d max=%d",
2223                         this_length, a->maximumRecordSize);
2224                 reclist->records[reclist->num_records] =
2225                     surrogatediagrec(a, freq.basename, 17, 0);
2226                 reclist->num_records++;
2227                 dumped_records += this_length;
2228                 continue;
2229             }
2230         }
2231
2232         if (!(thisrec = (Z_NamePlusRecord *)
2233               odr_malloc(a->encode, sizeof(*thisrec))))
2234             return 0;
2235         if (freq.basename)
2236             thisrec->databaseName = odr_strdup(a->encode, freq.basename);
2237         else
2238             thisrec->databaseName = 0;
2239         thisrec->which = Z_NamePlusRecord_databaseRecord;
2240
2241         if (freq.output_format_raw)
2242         {
2243             struct oident *ident = oid_getentbyoid(freq.output_format_raw);
2244             freq.output_format = ident->value;
2245         }
2246         thisrec->u.databaseRecord = z_ext_record(a->encode, freq.output_format,
2247                                                  freq.record, freq.len);
2248         if (!thisrec->u.databaseRecord)
2249             return 0;
2250         reclist->records[reclist->num_records] = thisrec;
2251         reclist->num_records++;
2252     }
2253     *num = reclist->num_records;
2254     return records;
2255 }
2256
2257 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
2258     int *fd)
2259 {
2260     Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2261     bend_search_rr *bsrr = 
2262         (bend_search_rr *)nmem_malloc (reqb->request_mem, sizeof(*bsrr));
2263     
2264     yaz_log(log_requestdetail, "Got SearchRequest.");
2265     bsrr->fd = fd;
2266     bsrr->request = reqb;
2267     bsrr->association = assoc;
2268     bsrr->referenceId = req->referenceId;
2269     save_referenceId (reqb, bsrr->referenceId);
2270     bsrr->srw_sortKeys = 0;
2271     bsrr->srw_setname = 0;
2272     bsrr->srw_setnameIdleTime = 0;
2273
2274     yaz_log (log_requestdetail, "ResultSet '%s'", req->resultSetName);
2275     if (req->databaseNames)
2276     {
2277         int i;
2278         for (i = 0; i < req->num_databaseNames; i++)
2279             yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
2280     }
2281
2282     yaz_log_zquery_level(log_requestdetail,req->query);
2283
2284     if (assoc->init->bend_search)
2285     {
2286         bsrr->setname = req->resultSetName;
2287         bsrr->replace_set = *req->replaceIndicator;
2288         bsrr->num_bases = req->num_databaseNames;
2289         bsrr->basenames = req->databaseNames;
2290         bsrr->query = req->query;
2291         bsrr->stream = assoc->encode;
2292         nmem_transfer(bsrr->stream->mem, reqb->request_mem);
2293         bsrr->decode = assoc->decode;
2294         bsrr->print = assoc->print;
2295         bsrr->hits = 0;
2296         bsrr->errcode = 0;
2297         bsrr->errstring = NULL;
2298         bsrr->search_info = NULL;
2299
2300         if (assoc->cql_transform &&
2301             req->query->which == Z_Query_type_104 &&
2302             req->query->u.type_104->which == Z_External_CQL)
2303         {
2304             /* have a CQL query and a CQL to PQF transform .. */
2305             int srw_errcode = 
2306                 cql2pqf(bsrr->stream, req->query->u.type_104->u.cql,
2307                         assoc->cql_transform, bsrr->query);
2308             if (srw_errcode)
2309                 bsrr->errcode = yaz_diag_srw_to_bib1(srw_errcode);
2310         }
2311         if (!bsrr->errcode)
2312             (assoc->init->bend_search)(assoc->backend, bsrr);
2313         if (!bsrr->request)  /* backend not ready with the search response */
2314             return 0;  /* should not be used any more */
2315     }
2316     else
2317     { 
2318         /* FIXME - make a diagnostic for it */
2319         yaz_log(YLOG_WARN,"Search not supported ?!?!");
2320     }
2321     return response_searchRequest(assoc, reqb, bsrr, fd);
2322 }
2323
2324 int bend_searchresponse(void *handle, bend_search_rr *bsrr) {return 0;}
2325
2326 /*
2327  * Prepare a searchresponse based on the backend results. We probably want
2328  * to look at making the fetching of records nonblocking as well, but
2329  * so far, we'll keep things simple.
2330  * If bsrt is null, that means we're called in response to a communications
2331  * event, and we'll have to get the response for ourselves.
2332  */
2333 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
2334     bend_search_rr *bsrt, int *fd)
2335 {
2336     Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2337     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2338     Z_SearchResponse *resp = (Z_SearchResponse *)
2339         odr_malloc (assoc->encode, sizeof(*resp));
2340     int *nulint = odr_intdup (assoc->encode, 0);
2341     bool_t *sr = odr_intdup(assoc->encode, 1);
2342     int *next = odr_intdup(assoc->encode, 0);
2343     int *none = odr_intdup(assoc->encode, Z_SearchResponse_none);
2344     int returnedrecs=0;
2345
2346     apdu->which = Z_APDU_searchResponse;
2347     apdu->u.searchResponse = resp;
2348     resp->referenceId = req->referenceId;
2349     resp->additionalSearchInfo = 0;
2350     resp->otherInfo = 0;
2351     *fd = -1;
2352     if (!bsrt && !bend_searchresponse(assoc->backend, bsrt))
2353     {
2354         yaz_log(YLOG_FATAL, "Bad result from backend");
2355         return 0;
2356     }
2357     else if (bsrt->errcode)
2358     {
2359         resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
2360         resp->resultCount = nulint;
2361         resp->numberOfRecordsReturned = nulint;
2362         resp->nextResultSetPosition = nulint;
2363         resp->searchStatus = nulint;
2364         resp->resultSetStatus = none;
2365         resp->presentStatus = 0;
2366     }
2367     else
2368     {
2369         int *toget = odr_intdup(assoc->encode, 0);
2370         int *presst = odr_intdup(assoc->encode, 0);
2371         Z_RecordComposition comp, *compp = 0;
2372
2373         yaz_log (log_requestdetail, "resultCount: %d", bsrt->hits);
2374
2375         resp->records = 0;
2376         resp->resultCount = &bsrt->hits;
2377
2378         comp.which = Z_RecordComp_simple;
2379         /* how many records does the user agent want, then? */
2380         if (bsrt->hits <= *req->smallSetUpperBound)
2381         {
2382             *toget = bsrt->hits;
2383             if ((comp.u.simple = req->smallSetElementSetNames))
2384                 compp = &comp;
2385         }
2386         else if (bsrt->hits < *req->largeSetLowerBound)
2387         {
2388             *toget = *req->mediumSetPresentNumber;
2389             if (*toget > bsrt->hits)
2390                 *toget = bsrt->hits;
2391             if ((comp.u.simple = req->mediumSetElementSetNames))
2392                 compp = &comp;
2393         }
2394         else
2395             *toget = 0;
2396
2397         if (*toget && !resp->records)
2398         {
2399             oident *prefformat;
2400             oid_value form;
2401
2402             if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
2403                 form = VAL_NONE;
2404             else
2405                 form = prefformat->value;
2406             resp->records = pack_records(assoc, req->resultSetName, 1,
2407                                          toget, compp, next, presst, form, req->referenceId,
2408                                          req->preferredRecordSyntax, NULL);
2409             if (!resp->records)
2410                 return 0;
2411             resp->numberOfRecordsReturned = toget;
2412             returnedrecs = *toget;
2413             resp->nextResultSetPosition = next;
2414             resp->searchStatus = sr;
2415             resp->resultSetStatus = 0;
2416             resp->presentStatus = presst;
2417         }
2418         else
2419         {
2420             if (*resp->resultCount)
2421                 *next = 1;
2422             resp->numberOfRecordsReturned = nulint;
2423             resp->nextResultSetPosition = next;
2424             resp->searchStatus = sr;
2425             resp->resultSetStatus = 0;
2426             resp->presentStatus = 0;
2427         }
2428     }
2429     resp->additionalSearchInfo = bsrt->search_info;
2430
2431     if (log_request)
2432     {
2433         WRBUF wr = wrbuf_alloc();
2434         if (bsrt->errcode)
2435             wrbuf_printf(wr, "ERROR %d", bsrt->errcode);
2436         else
2437             wrbuf_printf(wr, "OK %d", bsrt->hits);
2438         wrbuf_printf(wr, " %s 1+%d ",
2439                      req->resultSetName, returnedrecs);
2440         wrbuf_put_zquery(wr, req->query);
2441         
2442         yaz_log(log_request, "Search %s", wrbuf_buf(wr));
2443         wrbuf_free(wr, 1);
2444     }
2445     return apdu;
2446 }
2447
2448 /*
2449  * Maybe we got a little over-friendly when we designed bend_fetch to
2450  * get only one record at a time. Some backends can optimise multiple-record
2451  * fetches, and at any rate, there is some overhead involved in
2452  * all that selecting and hopping around. Problem is, of course, that the
2453  * frontend can't know ahead of time how many records it'll need to
2454  * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
2455  * is downright lousy as a bulk data transfer protocol.
2456  *
2457  * To start with, we'll do the fetching of records from the backend
2458  * in one operation: To save some trips in and out of the event-handler,
2459  * and to simplify the interface to pack_records. At any rate, asynch
2460  * operation is more fun in operations that have an unpredictable execution
2461  * speed - which is normally more true for search than for present.
2462  */
2463 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
2464                                       int *fd)
2465 {
2466     Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
2467     oident *prefformat;
2468     oid_value form;
2469     Z_APDU *apdu;
2470     Z_PresentResponse *resp;
2471     int *next;
2472     int *num;
2473     int errcode = 0;
2474     const char *errstring = 0;
2475
2476     yaz_log(log_requestdetail, "Got PresentRequest.");
2477
2478     if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
2479         form = VAL_NONE;
2480     else
2481         form = prefformat->value;
2482     resp = (Z_PresentResponse *)odr_malloc (assoc->encode, sizeof(*resp));
2483     resp->records = 0;
2484     resp->presentStatus = odr_intdup(assoc->encode, 0);
2485     if (assoc->init->bend_present)
2486     {
2487         bend_present_rr *bprr = (bend_present_rr *)
2488             nmem_malloc (reqb->request_mem, sizeof(*bprr));
2489         bprr->setname = req->resultSetId;
2490         bprr->start = *req->resultSetStartPoint;
2491         bprr->number = *req->numberOfRecordsRequested;
2492         bprr->format = form;
2493         bprr->comp = req->recordComposition;
2494         bprr->referenceId = req->referenceId;
2495         bprr->stream = assoc->encode;
2496         bprr->print = assoc->print;
2497         bprr->request = reqb;
2498         bprr->association = assoc;
2499         bprr->errcode = 0;
2500         bprr->errstring = NULL;
2501         (*assoc->init->bend_present)(assoc->backend, bprr);
2502         
2503         if (!bprr->request)
2504             return 0; /* should not happen */
2505         if (bprr->errcode)
2506         {
2507             resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2508             *resp->presentStatus = Z_PresentStatus_failure;
2509             errcode = bprr->errcode;
2510             errstring = bprr->errstring;
2511         }
2512     }
2513     apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2514     next = odr_intdup(assoc->encode, 0);
2515     num = odr_intdup(assoc->encode, 0);
2516     
2517     apdu->which = Z_APDU_presentResponse;
2518     apdu->u.presentResponse = resp;
2519     resp->referenceId = req->referenceId;
2520     resp->otherInfo = 0;
2521     
2522     if (!resp->records)
2523     {
2524         *num = *req->numberOfRecordsRequested;
2525         resp->records =
2526             pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
2527                          num, req->recordComposition, next,
2528                          resp->presentStatus,
2529                          form, req->referenceId, req->preferredRecordSyntax, 
2530                          &errcode);
2531     }
2532     if (log_request)
2533     {
2534         WRBUF wr = wrbuf_alloc();
2535         wrbuf_printf(wr, "Present ");
2536
2537         if (*resp->presentStatus == Z_PresentStatus_failure)
2538             wrbuf_printf(wr, "ERROR %d", errcode);
2539         else if (*resp->presentStatus == Z_PresentStatus_success)
2540             wrbuf_printf(wr, "OK -");
2541         else
2542             wrbuf_printf(wr, "Partial %d", *resp->presentStatus);
2543
2544         wrbuf_printf(wr, " %s %d+%d ",
2545                 req->resultSetId, *req->resultSetStartPoint,
2546                 *req->numberOfRecordsRequested);
2547         yaz_log(log_request, "%s", wrbuf_buf(wr) );
2548         wrbuf_free(wr, 1);
2549     }
2550     if (!resp->records)
2551         return 0;
2552     resp->numberOfRecordsReturned = num;
2553     resp->nextResultSetPosition = next;
2554     
2555     return apdu;
2556 }
2557
2558 /*
2559  * Scan was implemented rather in a hurry, and with support for only the basic
2560  * elements of the service in the backend API. Suggestions are welcome.
2561  */
2562 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
2563 {
2564     Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
2565     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2566     Z_ScanResponse *res = (Z_ScanResponse *)
2567         odr_malloc (assoc->encode, sizeof(*res));
2568     int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
2569     int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
2570     Z_ListEntries *ents = (Z_ListEntries *)
2571         odr_malloc (assoc->encode, sizeof(*ents));
2572     Z_DiagRecs *diagrecs_p = NULL;
2573     oident *attset;
2574     bend_scan_rr *bsrr = (bend_scan_rr *)
2575         odr_malloc (assoc->encode, sizeof(*bsrr));
2576     struct scan_entry *save_entries;
2577
2578     yaz_log(log_requestdetail, "Got ScanRequest");
2579
2580     apdu->which = Z_APDU_scanResponse;
2581     apdu->u.scanResponse = res;
2582     res->referenceId = req->referenceId;
2583
2584     /* if step is absent, set it to 0 */
2585     res->stepSize = odr_intdup(assoc->encode, 0);
2586     if (req->stepSize)
2587         *res->stepSize = *req->stepSize;
2588
2589     res->scanStatus = scanStatus;
2590     res->numberOfEntriesReturned = numberOfEntriesReturned;
2591     res->positionOfTerm = 0;
2592     res->entries = ents;
2593     ents->num_entries = 0;
2594     ents->entries = NULL;
2595     ents->num_nonsurrogateDiagnostics = 0;
2596     ents->nonsurrogateDiagnostics = NULL;
2597     res->attributeSet = 0;
2598     res->otherInfo = 0;
2599
2600     if (req->databaseNames)
2601     {
2602         int i;
2603         for (i = 0; i < req->num_databaseNames; i++)
2604             yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
2605     }
2606     bsrr->scanClause = 0;
2607     bsrr->errcode = 0;
2608     bsrr->errstring = 0;
2609     bsrr->num_bases = req->num_databaseNames;
2610     bsrr->basenames = req->databaseNames;
2611     bsrr->num_entries = *req->numberOfTermsRequested;
2612     bsrr->term = req->termListAndStartPoint;
2613     bsrr->referenceId = req->referenceId;
2614     bsrr->stream = assoc->encode;
2615     bsrr->print = assoc->print;
2616     bsrr->step_size = res->stepSize;
2617     bsrr->entries = 0;
2618     /* For YAZ 2.0 and earlier it was the backend handler that
2619        initialized entries (member display_term did not exist)
2620        YAZ 2.0 and later sets 'entries'  and initialize all members
2621        including 'display_term'. If YAZ 2.0 or later sees that
2622        entries was modified - we assume that it is an old handler and
2623        that 'display_term' is _not_ set.
2624     */
2625     if (bsrr->num_entries > 0) 
2626     {
2627         int i;
2628         bsrr->entries = odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
2629                                    bsrr->num_entries);
2630         for (i = 0; i<bsrr->num_entries; i++)
2631         {
2632             bsrr->entries[i].term = 0;
2633             bsrr->entries[i].occurrences = 0;
2634             bsrr->entries[i].errcode = 0;
2635             bsrr->entries[i].errstring = 0;
2636             bsrr->entries[i].display_term = 0;
2637         }
2638     }
2639     save_entries = bsrr->entries;  /* save it so we can compare later */
2640
2641     if (req->attributeSet &&
2642         (attset = oid_getentbyoid(req->attributeSet)) &&
2643         (attset->oclass == CLASS_ATTSET || attset->oclass == CLASS_GENERAL))
2644         bsrr->attributeset = attset->value;
2645     else
2646         bsrr->attributeset = VAL_NONE;
2647     log_scan_term_level (log_requestdetail, req->termListAndStartPoint, 
2648             bsrr->attributeset);
2649     bsrr->term_position = req->preferredPositionInResponse ?
2650         *req->preferredPositionInResponse : 1;
2651
2652     ((int (*)(void *, bend_scan_rr *))
2653      (*assoc->init->bend_scan))(assoc->backend, bsrr);
2654
2655     if (bsrr->errcode)
2656         diagrecs_p = zget_DiagRecs(assoc->encode,
2657                                    bsrr->errcode, bsrr->errstring);
2658     else
2659     {
2660         int i;
2661         Z_Entry **tab = (Z_Entry **)
2662             odr_malloc (assoc->encode, sizeof(*tab) * bsrr->num_entries);
2663         
2664         if (bsrr->status == BEND_SCAN_PARTIAL)
2665             *scanStatus = Z_Scan_partial_5;
2666         else
2667             *scanStatus = Z_Scan_success;
2668         ents->entries = tab;
2669         ents->num_entries = bsrr->num_entries;
2670         res->numberOfEntriesReturned = &ents->num_entries;          
2671         res->positionOfTerm = &bsrr->term_position;
2672         for (i = 0; i < bsrr->num_entries; i++)
2673         {
2674             Z_Entry *e;
2675             Z_TermInfo *t;
2676             Odr_oct *o;
2677             
2678             tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
2679             if (bsrr->entries[i].occurrences >= 0)
2680             {
2681                 e->which = Z_Entry_termInfo;
2682                 e->u.termInfo = t = (Z_TermInfo *)
2683                     odr_malloc(assoc->encode, sizeof(*t));
2684                 t->suggestedAttributes = 0;
2685                 t->displayTerm = 0;
2686                 if (save_entries == bsrr->entries && 
2687                     bsrr->entries[i].display_term)
2688                 {
2689                     /* the entries was _not_ set by the handler. So it's
2690                        safe to test for new member display_term. It is
2691                        NULL'ed by us.
2692                     */
2693                     t->displayTerm = odr_strdup(assoc->encode,
2694                                                 bsrr->entries[i].display_term);
2695                 }
2696                 t->alternativeTerm = 0;
2697                 t->byAttributes = 0;
2698                 t->otherTermInfo = 0;
2699                 t->globalOccurrences = &bsrr->entries[i].occurrences;
2700                 t->term = (Z_Term *)
2701                     odr_malloc(assoc->encode, sizeof(*t->term));
2702                 t->term->which = Z_Term_general;
2703                 t->term->u.general = o =
2704                     (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
2705                 o->buf = (unsigned char *)
2706                     odr_malloc(assoc->encode, o->len = o->size =
2707                                strlen(bsrr->entries[i].term));
2708                 memcpy(o->buf, bsrr->entries[i].term, o->len);
2709                 yaz_log(YLOG_DEBUG, "  term #%d: '%s' (%d)", i,
2710                          bsrr->entries[i].term, bsrr->entries[i].occurrences);
2711             }
2712             else
2713             {
2714                 Z_DiagRecs *drecs = zget_DiagRecs(assoc->encode,
2715                                                   bsrr->entries[i].errcode,
2716                                                   bsrr->entries[i].errstring);
2717                 assert (drecs->num_diagRecs == 1);
2718                 e->which = Z_Entry_surrogateDiagnostic;
2719                 assert (drecs->diagRecs[0]);
2720                 e->u.surrogateDiagnostic = drecs->diagRecs[0];
2721             }
2722         }
2723     }
2724     if (diagrecs_p)
2725     {
2726         ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
2727         ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
2728     }
2729     if (log_request)
2730     {
2731         WRBUF wr = wrbuf_alloc();
2732         if (bsrr->errcode)
2733             wr_diag(wr, bsrr->errcode, bsrr->errstring);
2734         else if (*res->scanStatus == Z_Scan_success)
2735             wrbuf_printf(wr, "OK");
2736         else
2737             wrbuf_printf(wr, "Partial");
2738
2739         wrbuf_printf(wr, " %d+%d %d ",
2740                      (req->preferredPositionInResponse ?
2741                       *req->preferredPositionInResponse : 1),
2742                      *req->numberOfTermsRequested,
2743                      (res->stepSize ? *res->stepSize : 0));
2744         wrbuf_scan_term(wr, req->termListAndStartPoint, 
2745                         bsrr->attributeset);
2746         
2747         yaz_log(log_request, "Scan %s", wrbuf_buf(wr) );
2748         wrbuf_free(wr, 1);
2749     }
2750     return apdu;
2751 }
2752
2753 static Z_APDU *process_sortRequest(association *assoc, request *reqb,
2754     int *fd)
2755 {
2756     int i;
2757     Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
2758     Z_SortResponse *res = (Z_SortResponse *)
2759         odr_malloc (assoc->encode, sizeof(*res));
2760     bend_sort_rr *bsrr = (bend_sort_rr *)
2761         odr_malloc (assoc->encode, sizeof(*bsrr));
2762
2763     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2764
2765     yaz_log(log_requestdetail, "Got SortRequest.");
2766
2767     bsrr->num_input_setnames = req->num_inputResultSetNames;
2768     for (i=0;i<req->num_inputResultSetNames;i++)
2769         yaz_log(log_requestdetail, "Input resultset: '%s'",
2770                 req->inputResultSetNames[i]);
2771     bsrr->input_setnames = req->inputResultSetNames;
2772     bsrr->referenceId = req->referenceId;
2773     bsrr->output_setname = req->sortedResultSetName;
2774     yaz_log(log_requestdetail, "Output resultset: '%s'",
2775                 req->sortedResultSetName);
2776     bsrr->sort_sequence = req->sortSequence;
2777        /*FIXME - dump those sequences too */
2778     bsrr->stream = assoc->encode;
2779     bsrr->print = assoc->print;
2780
2781     bsrr->sort_status = Z_SortResponse_failure;
2782     bsrr->errcode = 0;
2783     bsrr->errstring = 0;
2784     
2785     (*assoc->init->bend_sort)(assoc->backend, bsrr);
2786     
2787     res->referenceId = bsrr->referenceId;
2788     res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
2789     res->resultSetStatus = 0;
2790     if (bsrr->errcode)
2791     {
2792         Z_DiagRecs *dr = zget_DiagRecs(assoc->encode,
2793                                        bsrr->errcode, bsrr->errstring);
2794         res->diagnostics = dr->diagRecs;
2795         res->num_diagnostics = dr->num_diagRecs;
2796     }
2797     else
2798     {
2799         res->num_diagnostics = 0;
2800         res->diagnostics = 0;
2801     }
2802     res->resultCount = 0;
2803     res->otherInfo = 0;
2804
2805     apdu->which = Z_APDU_sortResponse;
2806     apdu->u.sortResponse = res;
2807     if (log_request)
2808     {
2809         WRBUF wr = wrbuf_alloc();
2810         wrbuf_printf(wr, "Sort ");
2811         if (bsrr->errcode)
2812             wrbuf_printf(wr, " ERROR %d", bsrr->errcode);
2813         else
2814             wrbuf_printf(wr,  "OK -");
2815         wrbuf_printf(wr, " (");
2816         for (i = 0; i<req->num_inputResultSetNames; i++)
2817         {
2818             if (i)
2819                 wrbuf_printf(wr, ",");
2820             wrbuf_printf(wr, req->inputResultSetNames[i]);
2821         }
2822         wrbuf_printf(wr, ")->%s ",req->sortedResultSetName);
2823
2824         yaz_log(log_request, "%s", wrbuf_buf(wr) );
2825         wrbuf_free(wr, 1);
2826     }
2827     return apdu;
2828 }
2829
2830 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
2831     int *fd)
2832 {
2833     int i;
2834     Z_DeleteResultSetRequest *req =
2835         reqb->apdu_request->u.deleteResultSetRequest;
2836     Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
2837         odr_malloc (assoc->encode, sizeof(*res));
2838     bend_delete_rr *bdrr = (bend_delete_rr *)
2839         odr_malloc (assoc->encode, sizeof(*bdrr));
2840     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2841
2842     yaz_log(log_requestdetail, "Got DeleteRequest.");
2843
2844     bdrr->num_setnames = req->num_resultSetList;
2845     bdrr->setnames = req->resultSetList;
2846     for (i = 0; i<req->num_resultSetList; i++)
2847         yaz_log(log_requestdetail, "resultset: '%s'",
2848                 req->resultSetList[i]);
2849     bdrr->stream = assoc->encode;
2850     bdrr->print = assoc->print;
2851     bdrr->function = *req->deleteFunction;
2852     bdrr->referenceId = req->referenceId;
2853     bdrr->statuses = 0;
2854     if (bdrr->num_setnames > 0)
2855     {
2856         bdrr->statuses = (int*) 
2857             odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
2858                        bdrr->num_setnames);
2859         for (i = 0; i < bdrr->num_setnames; i++)
2860             bdrr->statuses[i] = 0;
2861     }
2862     (*assoc->init->bend_delete)(assoc->backend, bdrr);
2863     
2864     res->referenceId = req->referenceId;
2865
2866     res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
2867
2868     res->deleteListStatuses = 0;
2869     if (bdrr->num_setnames > 0)
2870     {
2871         int i;
2872         res->deleteListStatuses = (Z_ListStatuses *)
2873             odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
2874         res->deleteListStatuses->num = bdrr->num_setnames;
2875         res->deleteListStatuses->elements =
2876             (Z_ListStatus **)
2877             odr_malloc (assoc->encode, 
2878                         sizeof(*res->deleteListStatuses->elements) *
2879                         bdrr->num_setnames);
2880         for (i = 0; i<bdrr->num_setnames; i++)
2881         {
2882             res->deleteListStatuses->elements[i] =
2883                 (Z_ListStatus *)
2884                 odr_malloc (assoc->encode,
2885                             sizeof(**res->deleteListStatuses->elements));
2886             res->deleteListStatuses->elements[i]->status = bdrr->statuses+i;
2887             res->deleteListStatuses->elements[i]->id =
2888                 odr_strdup (assoc->encode, bdrr->setnames[i]);
2889         }
2890     }
2891     res->numberNotDeleted = 0;
2892     res->bulkStatuses = 0;
2893     res->deleteMessage = 0;
2894     res->otherInfo = 0;
2895
2896     apdu->which = Z_APDU_deleteResultSetResponse;
2897     apdu->u.deleteResultSetResponse = res;
2898     if (log_request)
2899     {
2900         WRBUF wr = wrbuf_alloc();
2901         wrbuf_printf(wr, "Delete ");
2902         if (bdrr->delete_status)
2903             wrbuf_printf(wr, "ERROR %d", bdrr->delete_status);
2904         else
2905             wrbuf_printf(wr, "OK -");
2906         for (i = 0; i<req->num_resultSetList; i++)
2907             wrbuf_printf(wr, " %s ", req->resultSetList[i]);
2908         yaz_log(log_request, "%s", wrbuf_buf(wr) );
2909         wrbuf_free(wr, 1);
2910     }
2911     return apdu;
2912 }
2913
2914 static void process_close(association *assoc, request *reqb)
2915 {
2916     Z_Close *req = reqb->apdu_request->u.close;
2917     static char *reasons[] =
2918     {
2919         "finished",
2920         "shutdown",
2921         "systemProblem",
2922         "costLimit",
2923         "resources",
2924         "securityViolation",
2925         "protocolError",
2926         "lackOfActivity",
2927         "peerAbort",
2928         "unspecified"
2929     };
2930
2931     yaz_log(log_requestdetail, "Got Close, reason %s, message %s",
2932         reasons[*req->closeReason], req->diagnosticInformation ?
2933         req->diagnosticInformation : "NULL");
2934     if (assoc->version < 3) /* to make do_force respond with close */
2935         assoc->version = 3;
2936     do_close_req(assoc, Z_Close_finished,
2937                  "Association terminated by client", reqb);
2938     yaz_log(log_request,"Close OK");
2939 }
2940
2941 void save_referenceId (request *reqb, Z_ReferenceId *refid)
2942 {
2943     if (refid)
2944     {
2945         reqb->len_refid = refid->len;
2946         reqb->refid = (char *)nmem_malloc (reqb->request_mem, refid->len);
2947         memcpy (reqb->refid, refid->buf, refid->len);
2948     }
2949     else
2950     {
2951         reqb->len_refid = 0;
2952         reqb->refid = NULL;
2953     }
2954 }
2955
2956 void bend_request_send (bend_association a, bend_request req, Z_APDU *res)
2957 {
2958     process_z_response (a, req, res);
2959 }
2960
2961 bend_request bend_request_mk (bend_association a)
2962 {
2963     request *nreq = request_get (&a->outgoing);
2964     nreq->request_mem = nmem_create ();
2965     return nreq;
2966 }
2967
2968 Z_ReferenceId *bend_request_getid (ODR odr, bend_request req)
2969 {
2970     Z_ReferenceId *id;
2971     if (!req->refid)
2972         return 0;
2973     id = (Odr_oct *)odr_malloc (odr, sizeof(*odr));
2974     id->buf = (unsigned char *)odr_malloc (odr, req->len_refid);
2975     id->len = id->size = req->len_refid;
2976     memcpy (id->buf, req->refid, req->len_refid);
2977     return id;
2978 }
2979
2980 void bend_request_destroy (bend_request *req)
2981 {
2982     nmem_destroy((*req)->request_mem);
2983     request_release(*req);
2984     *req = NULL;
2985 }
2986
2987 int bend_backend_respond (bend_association a, bend_request req)
2988 {
2989     char *msg;
2990     int r;
2991     r = process_z_request (a, req, &msg);
2992     if (r < 0)
2993         yaz_log (YLOG_WARN, "%s", msg);
2994     return r;
2995 }
2996
2997 void bend_request_setdata(bend_request r, void *p)
2998 {
2999     r->clientData = p;
3000 }
3001
3002 void *bend_request_getdata(bend_request r)
3003 {
3004     return r->clientData;
3005 }
3006
3007 static Z_APDU *process_segmentRequest (association *assoc, request *reqb)
3008 {
3009     bend_segment_rr req;
3010
3011     req.segment = reqb->apdu_request->u.segmentRequest;
3012     req.stream = assoc->encode;
3013     req.decode = assoc->decode;
3014     req.print = assoc->print;
3015     req.association = assoc;
3016     
3017     (*assoc->init->bend_segment)(assoc->backend, &req);
3018
3019     return 0;
3020 }
3021
3022 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd)
3023 {
3024     bend_esrequest_rr esrequest;
3025
3026     Z_ExtendedServicesRequest *req =
3027         reqb->apdu_request->u.extendedServicesRequest;
3028     Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
3029
3030     Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
3031
3032     yaz_log(log_requestdetail,"Got EsRequest");
3033
3034     esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
3035     esrequest.stream = assoc->encode;
3036     esrequest.decode = assoc->decode;
3037     esrequest.print = assoc->print;
3038     esrequest.errcode = 0;
3039     esrequest.errstring = NULL;
3040     esrequest.request = reqb;
3041     esrequest.association = assoc;
3042     esrequest.taskPackage = 0;
3043     esrequest.referenceId = req->referenceId;
3044     
3045     (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
3046     
3047     /* If the response is being delayed, return NULL */
3048     if (esrequest.request == NULL)
3049         return(NULL);
3050
3051     resp->referenceId = req->referenceId;
3052
3053     if (esrequest.errcode == -1)
3054     {
3055         /* Backend service indicates request will be processed */
3056         yaz_log(log_request,"EsRequest OK: Accepted !");
3057         *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
3058     }
3059     else if (esrequest.errcode == 0)
3060     {
3061         /* Backend service indicates request will be processed */
3062         yaz_log(log_request,"EsRequest OK: Done !");
3063         *resp->operationStatus = Z_ExtendedServicesResponse_done;
3064     }
3065     else
3066     {
3067         Z_DiagRecs *diagRecs =
3068             zget_DiagRecs(assoc->encode, esrequest.errcode,
3069                           esrequest.errstring);
3070         /* Backend indicates error, request will not be processed */
3071         yaz_log(YLOG_DEBUG,"Request could not be processed...failure !");
3072         *resp->operationStatus = Z_ExtendedServicesResponse_failure;
3073         resp->num_diagnostics = diagRecs->num_diagRecs;
3074         resp->diagnostics = diagRecs->diagRecs;
3075         if (log_request)
3076         {
3077             WRBUF wr = wrbuf_alloc();
3078             wrbuf_diags(wr, resp->num_diagnostics, resp->diagnostics);
3079             yaz_log(log_request, "EsRequest %s", wrbuf_buf(wr) );
3080             wrbuf_free(wr, 1);
3081         }
3082
3083     }
3084     /* Do something with the members of bend_extendedservice */
3085     if (esrequest.taskPackage)
3086         resp->taskPackage = z_ext_record (assoc->encode, VAL_EXTENDED,
3087                                          (const char *)  esrequest.taskPackage,
3088                                           -1);
3089     yaz_log(YLOG_DEBUG,"Send the result apdu");
3090     return apdu;
3091 }
3092
3093 /*
3094  * Local variables:
3095  * c-basic-offset: 4
3096  * indent-tabs-mode: nil
3097  * End:
3098  * vim: shiftwidth=4 tabstop=8 expandtab
3099  */
3100