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