Fixed bug in GFS: bend_scan handler was not called when PQF-to-CQL conversion
[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.67 2006-02-27 21:31:33 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_scan && assoc->cql_transform)
1091         {
1092             int srw_error;
1093             bsrr->scanClause = 0;
1094             bsrr->attributeset = VAL_NONE;
1095             bsrr->term = odr_malloc(assoc->decode, sizeof(*bsrr->term));
1096             srw_error = cql2pqf_scan(assoc->encode,
1097                                      srw_req->scanClause.cql,
1098                                      assoc->cql_transform,
1099                                      bsrr->term);
1100             if (srw_error)
1101                 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1102                                        &srw_res->num_diagnostics,
1103                                        srw_error, 0);
1104             else
1105             {
1106                 ((int (*)(void *, bend_scan_rr *))
1107                  (*assoc->init->bend_scan))(assoc->backend, bsrr);
1108             }
1109         }
1110         else if (srw_req->query_type == Z_SRW_query_type_cql
1111                  && assoc->init->bend_srw_scan)
1112         {
1113             bsrr->term = 0;
1114             bsrr->attributeset = VAL_NONE;
1115             bsrr->scanClause = srw_req->scanClause.cql;
1116             ((int (*)(void *, bend_scan_rr *))
1117              (*assoc->init->bend_srw_scan))(assoc->backend, bsrr);
1118         }
1119         else
1120         {
1121             yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1122                                    &srw_res->num_diagnostics,
1123                                    YAZ_SRW_UNSUPP_OPERATION, "scan");
1124         }
1125         if (bsrr->errcode)
1126         {
1127             int srw_error;
1128             if (bsrr->errcode == YAZ_BIB1_DATABASE_UNAVAILABLE)
1129             {
1130                 *http_code = 404;
1131                 return;
1132             }
1133             srw_error = yaz_diag_bib1_to_srw (bsrr->errcode);
1134
1135             yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1136                                    &srw_res->num_diagnostics,
1137                                    srw_error, bsrr->errstring);
1138         }
1139         else if (srw_res->num_diagnostics == 0 && bsrr->num_entries)
1140         {
1141             int i;
1142             srw_res->terms = (Z_SRW_scanTerm*)
1143                 odr_malloc(assoc->encode, sizeof(*srw_res->terms) *
1144                            bsrr->num_entries);
1145
1146             srw_res->num_terms =  bsrr->num_entries;
1147             for (i = 0; i<bsrr->num_entries; i++)
1148             {
1149                 Z_SRW_scanTerm *t = srw_res->terms + i;
1150                 t->value = odr_strdup(assoc->encode, bsrr->entries[i].term);
1151                 t->numberOfRecords =
1152                     odr_intdup(assoc->encode, bsrr->entries[i].occurrences);
1153                 t->displayTerm = 0;
1154                 if (save_entries == bsrr->entries && 
1155                     bsrr->entries[i].display_term)
1156                 {
1157                     /* the entries was _not_ set by the handler. So it's
1158                        safe to test for new member display_term. It is
1159                        NULL'ed by us.
1160                     */
1161                     t->displayTerm = odr_strdup(assoc->encode, 
1162                                                 bsrr->entries[i].display_term);
1163                 }
1164                 t->whereInList = 0;
1165             }
1166         }
1167     }
1168     if (log_request)
1169     {
1170         WRBUF wr = wrbuf_alloc();
1171         const char *querytype = 0;
1172         const char *querystr = 0;
1173
1174         switch(srw_req->query_type)
1175         {
1176         case Z_SRW_query_type_pqf:
1177             querytype = "PQF";
1178             querystr = srw_req->scanClause.pqf;
1179             break;
1180         case Z_SRW_query_type_cql:
1181             querytype = "CQL";
1182             querystr = srw_req->scanClause.cql;
1183             break;
1184         default:
1185             querytype = "Unknown";
1186             querystr = "";
1187         }
1188         wrbuf_printf(wr, "SRWScan %d+%d",
1189                      (srw_req->responsePosition ? 
1190                       *srw_req->responsePosition : 1),
1191                      (srw_req->maximumTerms ?
1192                       *srw_req->maximumTerms : 1));
1193         if (srw_res->num_diagnostics)
1194             wrbuf_printf(wr, " ERROR %s", srw_res->diagnostics[0].uri);
1195         else
1196             wrbuf_printf(wr, " OK -");
1197         wrbuf_printf(wr, " %s: %s", querytype, querystr);
1198         yaz_log(log_request, "%s", wrbuf_buf(wr) );
1199         wrbuf_free(wr, 1);
1200     }
1201
1202 }
1203
1204 static void srw_bend_update(association *assoc, request *req,
1205                             Z_SRW_updateRequest *srw_req,
1206                             Z_SRW_updateResponse *srw_res,
1207                             int *http_code)
1208 {
1209     yaz_log(YLOG_DEBUG, "Got SRW UpdateRequest");
1210     yaz_log(YLOG_DEBUG, "num_diag = %d", srw_res->num_diagnostics );
1211     *http_code = 404;
1212     srw_bend_init(assoc, &srw_res->diagnostics, &srw_res->num_diagnostics);
1213     if (assoc->init)
1214     {
1215         bend_update_rr rr;
1216         
1217         rr.stream = assoc->encode;
1218         rr.print = assoc->print;
1219         rr.num_bases = 1;
1220         rr.basenames = &srw_req->database;
1221         rr.operation = srw_req->operation;
1222         rr.operation_status = "failed";
1223         rr.record_id = 0;
1224         rr.record_version = 0;
1225         rr.record_checksum = 0;
1226         rr.record_old_version = 0;
1227         rr.record_packing = "xml";
1228         rr.record_schema = 0;
1229         rr.record_data = 0;
1230         rr.request_extra_record = 0;
1231         rr.response_extra_record = 0;
1232         rr.extra_request_data = 0;
1233         rr.extra_response_data = 0;
1234         rr.errcode = 0;
1235         rr.errstring = 0;
1236
1237         yaz_log(YLOG_DEBUG, "basename = %s", rr.basenames[0] );
1238         yaz_log(YLOG_DEBUG, "Operation = %s", rr.operation );
1239         if ( !strcmp( rr.operation, "delete" ) ){
1240             if ( !srw_req->recordId ){
1241                 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1242                                        &srw_res->num_diagnostics,
1243                                        7, "recordId" );
1244             }
1245             else {
1246                 rr.record_id = srw_req->recordId;
1247             }
1248             if (  !srw_req->recordVersion ){
1249                 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1250                                        &srw_res->num_diagnostics,
1251                                        7, "recordVersion" );
1252             }
1253             else {
1254                 rr.record_version = odr_strdup( assoc->encode,
1255                                                 srw_req->recordVersion );
1256                 
1257             }
1258             if ( srw_req->recordOldVersion ){
1259                 rr.record_old_version = odr_strdup(assoc->encode,
1260                                                    srw_req->recordOldVersion );
1261             }
1262             if ( srw_req->extraRequestData ){
1263                 rr.extra_request_data = odr_strdup(assoc->encode,
1264                                                    srw_req->extraRequestData );
1265             }
1266         }
1267         else if ( !strcmp( rr.operation, "replace" ) ){
1268             if ( !srw_req->recordId ){
1269                 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1270                                        &srw_res->num_diagnostics,
1271                                        7, "recordId" );
1272             }
1273             else {
1274                 rr.record_id = srw_req->recordId;
1275             }
1276             if ( srw_req->record.recordSchema == 0 ){
1277                 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1278                                        &srw_res->num_diagnostics,
1279                                        7, "recordSchema" );
1280             }
1281             else {
1282                 rr.record_schema = odr_strdup(assoc->encode,
1283                                               srw_req->record.recordSchema );
1284             }
1285             switch (srw_req->record.recordPacking)
1286             {
1287             case Z_SRW_recordPacking_string: 
1288                 rr.record_packing = "string";
1289                 break;
1290             case Z_SRW_recordPacking_XML: 
1291                 rr.record_packing = "xml";
1292                 break;
1293             case Z_SRW_recordPacking_URL: 
1294                 rr.record_packing = "url";
1295                 break;
1296             }
1297             if ( srw_req->record.recordData_len ){
1298                 rr.record_data = odr_strdupn(assoc->encode, 
1299                                              srw_req->record.recordData_buf,
1300                                              srw_req->record.recordData_len );
1301                 rr.request_extra_record = srw_req->extra_record;
1302             }
1303             else {
1304                 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1305                                        &srw_res->num_diagnostics,
1306                                        7, "recordData" );
1307             }
1308             if (srw_req->extraRequestData)
1309                 rr.extra_request_data = odr_strdup(assoc->encode,
1310                                                    srw_req->extraRequestData );
1311         }
1312         else if ( !strcmp( rr.operation, "insert" ) )
1313         {
1314             if ( srw_req->record.recordSchema == 0 ){
1315                 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1316                                        &srw_res->num_diagnostics,
1317                                        7, "recordSchema" );
1318             }
1319             else {
1320                 rr.record_schema = odr_strdup(assoc->encode,
1321                                               srw_req->record.recordSchema);
1322             }
1323             switch (srw_req->record.recordPacking)
1324             {
1325             case Z_SRW_recordPacking_string: 
1326                 rr.record_packing = "string";
1327                 break;
1328             case Z_SRW_recordPacking_XML: 
1329                 rr.record_packing = "xml";
1330                 break;
1331             case Z_SRW_recordPacking_URL: 
1332                 rr.record_packing = "url";
1333                 break;
1334             }
1335             
1336             if (srw_req->record.recordData_len)
1337             {
1338                 rr.record_data = odr_strdupn(assoc->encode, 
1339                                              srw_req->record.recordData_buf,
1340                                              srw_req->record.recordData_len );
1341                 rr.request_extra_record = srw_req->extra_record;
1342             }
1343             else
1344                 yaz_add_srw_diagnostic(assoc->encode, &srw_res->diagnostics,
1345                                        &srw_res->num_diagnostics,
1346                                        7, "recordData" );
1347             if ( srw_req->extraRequestData )
1348                 rr.extra_request_data = odr_strdup(assoc->encode,
1349                                                    srw_req->extraRequestData );
1350         }
1351         if (srw_res->num_diagnostics == 0)
1352         {
1353             if ( assoc->init->bend_srw_update)
1354                 (*assoc->init->bend_srw_update)(assoc->backend, &rr);
1355             else {
1356                 yaz_log( YLOG_WARN, "Got No Update function!");
1357                 return;
1358             }
1359         }
1360         if (rr.errcode)
1361             yaz_add_srw_diagnostic(assoc->encode,
1362                                    &srw_res->diagnostics,
1363                                    &srw_res->num_diagnostics,
1364                                    rr.errcode, rr.errstring);
1365         srw_res->recordId = rr.record_id;
1366         srw_res->operationStatus = rr.operation_status;
1367         srw_res->recordVersion = rr.record_version;
1368         srw_res->recordChecksum = rr.record_checksum;
1369         srw_res->extraResponseData = rr.extra_response_data;
1370         srw_res->record.recordPosition = 0;
1371         if (srw_res->num_diagnostics == 0 && rr.record_data)
1372         {
1373             srw_res->record.recordSchema = rr.record_schema;
1374             srw_res->record.recordPacking = srw_req->record.recordPacking;
1375             srw_res->record.recordData_buf = rr.record_data;
1376             srw_res->record.recordData_len = strlen(rr.record_data);
1377             srw_res->extra_record = rr.response_extra_record;
1378                 
1379         }
1380         else
1381             srw_res->record.recordData_len = 0;
1382         *http_code = 200;
1383     }
1384 }
1385
1386 static void process_http_request(association *assoc, request *req)
1387 {
1388     Z_HTTP_Request *hreq = req->gdu_request->u.HTTP_Request;
1389     ODR o = assoc->encode;
1390     int r = 2;  /* 2=NOT TAKEN, 1=TAKEN, 0=SOAP TAKEN */
1391     Z_SRW_PDU *sr = 0;
1392     Z_SOAP *soap_package = 0;
1393     Z_GDU *p = 0;
1394     char *charset = 0;
1395     Z_HTTP_Response *hres = 0;
1396     int keepalive = 1;
1397     char *stylesheet = 0;
1398     Z_SRW_diagnostic *diagnostic = 0;
1399     int num_diagnostic = 0;
1400     const char *host = z_HTTP_header_lookup(hreq->headers, "Host");
1401
1402     if (!control_association(assoc, host, 0))
1403     {
1404         p = z_get_HTTP_Response(o, 404);
1405         r = 1;
1406     }
1407     if (r == 2 && !strcmp(hreq->path, "/test")) 
1408     {   
1409         p = z_get_HTTP_Response(o, 200);
1410         hres = p->u.HTTP_Response;
1411         hres->content_buf = "1234567890\n";
1412         hres->content_len = strlen(hres->content_buf);
1413         r = 1;
1414     }
1415     if (r == 2)
1416     {
1417         r = yaz_srw_decode(hreq, &sr, &soap_package, assoc->decode, &charset);
1418         yaz_log(YLOG_DEBUG, "yaz_srw_decode returned %d", r);
1419     }
1420     if (r == 2)  /* not taken */
1421     {
1422         r = yaz_sru_decode(hreq, &sr, &soap_package, assoc->decode, &charset,
1423                            &diagnostic, &num_diagnostic);
1424         yaz_log(YLOG_DEBUG, "yaz_sru_decode returned %d", r);
1425     }
1426     if (r == 0)  /* decode SRW/SRU OK .. */
1427     {
1428         int http_code = 200;
1429         if (sr->which == Z_SRW_searchRetrieve_request)
1430         {
1431             Z_SRW_PDU *res =
1432                 yaz_srw_get(assoc->encode, Z_SRW_searchRetrieve_response);
1433
1434             stylesheet = sr->u.request->stylesheet;
1435             if (num_diagnostic)
1436             {
1437                 res->u.response->diagnostics = diagnostic;
1438                 res->u.response->num_diagnostics = num_diagnostic;
1439             }
1440             else
1441             {
1442                 srw_bend_search(assoc, req, sr->u.request, res->u.response, 
1443                                 &http_code);
1444             }
1445             if (http_code == 200)
1446                 soap_package->u.generic->p = res;
1447         }
1448         else if (sr->which == Z_SRW_explain_request)
1449         {
1450             Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_explain_response);
1451             stylesheet = sr->u.explain_request->stylesheet;
1452             if (num_diagnostic)
1453             {   
1454                 res->u.explain_response->diagnostics = diagnostic;
1455                 res->u.explain_response->num_diagnostics = num_diagnostic;
1456             }
1457             srw_bend_explain(assoc, req, sr->u.explain_request,
1458                              res->u.explain_response, &http_code);
1459             if (http_code == 200)
1460                 soap_package->u.generic->p = res;
1461         }
1462         else if (sr->which == Z_SRW_scan_request)
1463         {
1464             Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_scan_response);
1465             stylesheet = sr->u.scan_request->stylesheet;
1466             if (num_diagnostic)
1467             {   
1468                 res->u.scan_response->diagnostics = diagnostic;
1469                 res->u.scan_response->num_diagnostics = num_diagnostic;
1470             }
1471             srw_bend_scan(assoc, req, sr->u.scan_request,
1472                           res->u.scan_response, &http_code);
1473             if (http_code == 200)
1474                 soap_package->u.generic->p = res;
1475         }
1476         else if (sr->which == Z_SRW_update_request)
1477         {
1478             Z_SRW_PDU *res = yaz_srw_get(o, Z_SRW_update_response);
1479             yaz_log(YLOG_DEBUG, "handling SRW UpdateRequest");
1480             if (num_diagnostic)
1481             {   
1482                 res->u.update_response->diagnostics = diagnostic;
1483                 res->u.update_response->num_diagnostics = num_diagnostic;
1484             }
1485             yaz_log(YLOG_DEBUG, "num_diag = %d", res->u.update_response->num_diagnostics );
1486             srw_bend_update(assoc, req, sr->u.update_request,
1487                             res->u.update_response, &http_code);
1488             if (http_code == 200)
1489                 soap_package->u.generic->p = res;
1490         }
1491         else
1492         {
1493             yaz_log(log_request, "SOAP ERROR"); 
1494             /* FIXME - what error, what query */
1495             http_code = 500;
1496             z_soap_error(assoc->encode, soap_package,
1497                          "SOAP-ENV:Client", "Bad method", 0); 
1498         }
1499         if (http_code == 200 || http_code == 500)
1500         {
1501             static Z_SOAP_Handler soap_handlers[4] = {
1502 #if HAVE_XML2
1503                 {"http://www.loc.gov/zing/srw/", 0,
1504                  (Z_SOAP_fun) yaz_srw_codec},
1505                 {"http://www.loc.gov/zing/srw/v1.0/", 0,
1506                  (Z_SOAP_fun) yaz_srw_codec},
1507                 {"http://www.loc.gov/zing/srw/update/", 0,
1508                  (Z_SOAP_fun) yaz_ucp_codec},
1509 #endif
1510                 {0, 0, 0}
1511             };
1512             char ctype[60];
1513             int ret;
1514             p = z_get_HTTP_Response(o, 200);
1515             hres = p->u.HTTP_Response;
1516             ret = z_soap_codec_enc_xsl(assoc->encode, &soap_package,
1517                                        &hres->content_buf, &hres->content_len,
1518                                        soap_handlers, charset, stylesheet);
1519             hres->code = http_code;
1520
1521             strcpy(ctype, "text/xml");
1522             if (charset)
1523             {
1524                 strcat(ctype, "; charset=");
1525                 strcat(ctype, charset);
1526             }
1527             z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1528         }
1529         else
1530             p = z_get_HTTP_Response(o, http_code);
1531     }
1532
1533     if (p == 0)
1534         p = z_get_HTTP_Response(o, 500);
1535     hres = p->u.HTTP_Response;
1536     if (!strcmp(hreq->version, "1.0")) 
1537     {
1538         const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1539         if (v && !strcmp(v, "Keep-Alive"))
1540             keepalive = 1;
1541         else
1542             keepalive = 0;
1543         hres->version = "1.0";
1544     }
1545     else
1546     {
1547         const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1548         if (v && !strcmp(v, "close"))
1549             keepalive = 0;
1550         else
1551             keepalive = 1;
1552         hres->version = "1.1";
1553     }
1554     if (!keepalive)
1555     {
1556         z_HTTP_header_add(o, &hres->headers, "Connection", "close");
1557         assoc->state = ASSOC_DEAD;
1558         assoc->cs_get_mask = 0;
1559     }
1560     else
1561     {
1562         int t;
1563         const char *alive = z_HTTP_header_lookup(hreq->headers, "Keep-Alive");
1564
1565         if (alive && isdigit(*(const unsigned char *) alive))
1566             t = atoi(alive);
1567         else
1568             t = 15;
1569         if (t < 0 || t > 3600)
1570             t = 3600;
1571         iochan_settimeout(assoc->client_chan,t);
1572         z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1573     }
1574     process_gdu_response(assoc, req, p);
1575 }
1576
1577 static void process_gdu_request(association *assoc, request *req)
1578 {
1579     if (req->gdu_request->which == Z_GDU_Z3950)
1580     {
1581         char *msg = 0;
1582         req->apdu_request = req->gdu_request->u.z3950;
1583         if (process_z_request(assoc, req, &msg) < 0)
1584             do_close_req(assoc, Z_Close_systemProblem, msg, req);
1585     }
1586     else if (req->gdu_request->which == Z_GDU_HTTP_Request)
1587         process_http_request(assoc, req);
1588     else
1589     {
1590         do_close_req(assoc, Z_Close_systemProblem, "bad protocol packet", req);
1591     }
1592 }
1593
1594 /*
1595  * Initiate request processing.
1596  */
1597 static int process_z_request(association *assoc, request *req, char **msg)
1598 {
1599     int fd = -1;
1600     Z_APDU *res;
1601     int retval;
1602     
1603     *msg = "Unknown Error";
1604     assert(req && req->state == REQUEST_IDLE);
1605     if (req->apdu_request->which != Z_APDU_initRequest && !assoc->init)
1606     {
1607         *msg = "Missing InitRequest";
1608         return -1;
1609     }
1610     switch (req->apdu_request->which)
1611     {
1612     case Z_APDU_initRequest:
1613         res = process_initRequest(assoc, req); break;
1614     case Z_APDU_searchRequest:
1615         res = process_searchRequest(assoc, req, &fd); break;
1616     case Z_APDU_presentRequest:
1617         res = process_presentRequest(assoc, req, &fd); break;
1618     case Z_APDU_scanRequest:
1619         if (assoc->init->bend_scan)
1620             res = process_scanRequest(assoc, req, &fd);
1621         else
1622         {
1623             *msg = "Cannot handle Scan APDU";
1624             return -1;
1625         }
1626         break;
1627     case Z_APDU_extendedServicesRequest:
1628         if (assoc->init->bend_esrequest)
1629             res = process_ESRequest(assoc, req, &fd);
1630         else
1631         {
1632             *msg = "Cannot handle Extended Services APDU";
1633             return -1;
1634         }
1635         break;
1636     case Z_APDU_sortRequest:
1637         if (assoc->init->bend_sort)
1638             res = process_sortRequest(assoc, req, &fd);
1639         else
1640         {
1641             *msg = "Cannot handle Sort APDU";
1642             return -1;
1643         }
1644         break;
1645     case Z_APDU_close:
1646         process_close(assoc, req);
1647         return 0;
1648     case Z_APDU_deleteResultSetRequest:
1649         if (assoc->init->bend_delete)
1650             res = process_deleteRequest(assoc, req, &fd);
1651         else
1652         {
1653             *msg = "Cannot handle Delete APDU";
1654             return -1;
1655         }
1656         break;
1657     case Z_APDU_segmentRequest:
1658         if (assoc->init->bend_segment)
1659         {
1660             res = process_segmentRequest (assoc, req);
1661         }
1662         else
1663         {
1664             *msg = "Cannot handle Segment APDU";
1665             return -1;
1666         }
1667         break;
1668     case Z_APDU_triggerResourceControlRequest:
1669         return 0;
1670     default:
1671         *msg = "Bad APDU received";
1672         return -1;
1673     }
1674     if (res)
1675     {
1676         yaz_log(YLOG_DEBUG, "  result immediately available");
1677         retval = process_z_response(assoc, req, res);
1678     }
1679     else if (fd < 0)
1680     {
1681         yaz_log(YLOG_DEBUG, "  result unavailble");
1682         retval = 0;
1683     }
1684     else /* no result yet - one will be provided later */
1685     {
1686         IOCHAN chan;
1687
1688         /* Set up an I/O handler for the fd supplied by the backend */
1689
1690         yaz_log(YLOG_DEBUG, "   establishing handler for result");
1691         req->state = REQUEST_PENDING;
1692         if (!(chan = iochan_create(fd, backend_response, EVENT_INPUT, 0)))
1693             abort();
1694         iochan_setdata(chan, assoc);
1695         retval = 0;
1696     }
1697     return retval;
1698 }
1699
1700 /*
1701  * Handle message from the backend.
1702  */
1703 void backend_response(IOCHAN i, int event)
1704 {
1705     association *assoc = (association *)iochan_getdata(i);
1706     request *req = request_head(&assoc->incoming);
1707     Z_APDU *res;
1708     int fd;
1709
1710     yaz_log(YLOG_DEBUG, "backend_response");
1711     assert(assoc && req && req->state != REQUEST_IDLE);
1712     /* determine what it is we're waiting for */
1713     switch (req->apdu_request->which)
1714     {
1715         case Z_APDU_searchRequest:
1716             res = response_searchRequest(assoc, req, 0, &fd); break;
1717 #if 0
1718         case Z_APDU_presentRequest:
1719             res = response_presentRequest(assoc, req, 0, &fd); break;
1720         case Z_APDU_scanRequest:
1721             res = response_scanRequest(assoc, req, 0, &fd); break;
1722 #endif
1723         default:
1724             yaz_log(YLOG_FATAL, "Serious programmer's lapse or bug");
1725             abort();
1726     }
1727     if ((res && process_z_response(assoc, req, res) < 0) || fd < 0)
1728     {
1729         yaz_log(YLOG_WARN, "Fatal error when talking to backend");
1730         do_close(assoc, Z_Close_systemProblem, 0);
1731         iochan_destroy(i);
1732         return;
1733     }
1734     else if (!res) /* no result yet - try again later */
1735     {
1736         yaz_log(YLOG_DEBUG, "   no result yet");
1737         iochan_setfd(i, fd); /* in case fd has changed */
1738     }
1739 }
1740
1741 /*
1742  * Encode response, and transfer the request structure to the outgoing queue.
1743  */
1744 static int process_gdu_response(association *assoc, request *req, Z_GDU *res)
1745 {
1746     odr_setbuf(assoc->encode, req->response, req->size_response, 1);
1747
1748     if (assoc->print)
1749     {
1750         if (!z_GDU(assoc->print, &res, 0, 0))
1751             yaz_log(YLOG_WARN, "ODR print error: %s", 
1752                 odr_errmsg(odr_geterror(assoc->print)));
1753         odr_reset(assoc->print);
1754     }
1755     if (!z_GDU(assoc->encode, &res, 0, 0))
1756     {
1757         yaz_log(YLOG_WARN, "ODR error when encoding PDU: %s [element %s]",
1758                 odr_errmsg(odr_geterror(assoc->decode)),
1759                 odr_getelement(assoc->decode));
1760         return -1;
1761     }
1762     req->response = odr_getbuf(assoc->encode, &req->len_response,
1763         &req->size_response);
1764     odr_setbuf(assoc->encode, 0, 0, 0); /* don'txfree if we abort later */
1765     odr_reset(assoc->encode);
1766     req->state = REQUEST_IDLE;
1767     request_enq(&assoc->outgoing, req);
1768     /* turn the work over to the ir_session handler */
1769     iochan_setflag(assoc->client_chan, EVENT_OUTPUT);
1770     assoc->cs_put_mask = EVENT_OUTPUT;
1771     /* Is there more work to be done? give that to the input handler too */
1772 #if 1
1773     if (request_head(&assoc->incoming))
1774     {
1775         yaz_log (YLOG_DEBUG, "more work to be done");
1776         iochan_setevent(assoc->client_chan, EVENT_WORK);
1777     }
1778 #endif
1779     return 0;
1780 }
1781
1782 /*
1783  * Encode response, and transfer the request structure to the outgoing queue.
1784  */
1785 static int process_z_response(association *assoc, request *req, Z_APDU *res)
1786 {
1787     Z_GDU *gres = (Z_GDU *) odr_malloc(assoc->encode, sizeof(*res));
1788     gres->which = Z_GDU_Z3950;
1789     gres->u.z3950 = res;
1790
1791     return process_gdu_response(assoc, req, gres);
1792 }
1793
1794 static char *get_vhost(Z_OtherInformation *otherInfo)
1795 {
1796     return yaz_oi_get_string_oidval(&otherInfo, VAL_PROXY, 1, 0);
1797 }
1798
1799 /*
1800  * Handle init request.
1801  * At the moment, we don't check the options
1802  * anywhere else in the code - we just try not to do anything that would
1803  * break a naive client. We'll toss 'em into the association block when
1804  * we need them there.
1805  */
1806 static Z_APDU *process_initRequest(association *assoc, request *reqb)
1807 {
1808     Z_InitRequest *req = reqb->apdu_request->u.initRequest;
1809     Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_initResponse);
1810     Z_InitResponse *resp = apdu->u.initResponse;
1811     bend_initresult *binitres;
1812     char *version;
1813     char options[140];
1814     statserv_options_block *cb = 0;  /* by default no control for backend */
1815
1816     if (control_association(assoc, get_vhost(req->otherInfo), 1))
1817         cb = statserv_getcontrol();  /* got control block for backend */
1818
1819     if (cb && assoc->backend)
1820         (*cb->bend_close)(assoc->backend);
1821
1822     yaz_log(log_requestdetail, "Got initRequest");
1823     if (req->implementationId)
1824         yaz_log(log_requestdetail, "Id:        %s",
1825                 req->implementationId);
1826     if (req->implementationName)
1827         yaz_log(log_requestdetail, "Name:      %s",
1828                 req->implementationName);
1829     if (req->implementationVersion)
1830         yaz_log(log_requestdetail, "Version:   %s",
1831                 req->implementationVersion);
1832     
1833     assoc_init_reset(assoc);
1834
1835     assoc->init->auth = req->idAuthentication;
1836     assoc->init->referenceId = req->referenceId;
1837
1838     if (ODR_MASK_GET(req->options, Z_Options_negotiationModel))
1839     {
1840         Z_CharSetandLanguageNegotiation *negotiation =
1841             yaz_get_charneg_record (req->otherInfo);
1842         if (negotiation &&
1843             negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
1844             assoc->init->charneg_request = negotiation;
1845     }
1846
1847     assoc->backend = 0;
1848     if (cb)
1849     {
1850         if (req->implementationVersion)
1851             yaz_log(log_requestdetail, "Config:    %s",
1852                     cb->configname);
1853     
1854         iochan_settimeout(assoc->client_chan, cb->idle_timeout * 60);
1855         
1856         /* we have a backend control block, so call that init function */
1857         if (!(binitres = (*cb->bend_init)(assoc->init)))
1858         {
1859             yaz_log(YLOG_WARN, "Bad response from backend.");
1860             return 0;
1861         }
1862         assoc->backend = binitres->handle;
1863     }
1864     else
1865     {
1866         /* no backend. return error */
1867         binitres = odr_malloc(assoc->encode, sizeof(*binitres));
1868         binitres->errstring = 0;
1869         binitres->errcode = YAZ_BIB1_PERMANENT_SYSTEM_ERROR;
1870         iochan_settimeout(assoc->client_chan, 10);
1871     }
1872     if ((assoc->init->bend_sort))
1873         yaz_log (YLOG_DEBUG, "Sort handler installed");
1874     if ((assoc->init->bend_search))
1875         yaz_log (YLOG_DEBUG, "Search handler installed");
1876     if ((assoc->init->bend_present))
1877         yaz_log (YLOG_DEBUG, "Present handler installed");   
1878     if ((assoc->init->bend_esrequest))
1879         yaz_log (YLOG_DEBUG, "ESRequest handler installed");   
1880     if ((assoc->init->bend_delete))
1881         yaz_log (YLOG_DEBUG, "Delete handler installed");   
1882     if ((assoc->init->bend_scan))
1883         yaz_log (YLOG_DEBUG, "Scan handler installed");   
1884     if ((assoc->init->bend_segment))
1885         yaz_log (YLOG_DEBUG, "Segment handler installed");   
1886     
1887     resp->referenceId = req->referenceId;
1888     *options = '\0';
1889     /* let's tell the client what we can do */
1890     if (ODR_MASK_GET(req->options, Z_Options_search))
1891     {
1892         ODR_MASK_SET(resp->options, Z_Options_search);
1893         strcat(options, "srch");
1894     }
1895     if (ODR_MASK_GET(req->options, Z_Options_present))
1896     {
1897         ODR_MASK_SET(resp->options, Z_Options_present);
1898         strcat(options, " prst");
1899     }
1900     if (ODR_MASK_GET(req->options, Z_Options_delSet) &&
1901         assoc->init->bend_delete)
1902     {
1903         ODR_MASK_SET(resp->options, Z_Options_delSet);
1904         strcat(options, " del");
1905     }
1906     if (ODR_MASK_GET(req->options, Z_Options_extendedServices) &&
1907         assoc->init->bend_esrequest)
1908     {
1909         ODR_MASK_SET(resp->options, Z_Options_extendedServices);
1910         strcat (options, " extendedServices");
1911     }
1912     if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
1913     {
1914         ODR_MASK_SET(resp->options, Z_Options_namedResultSets);
1915         strcat(options, " namedresults");
1916     }
1917     if (ODR_MASK_GET(req->options, Z_Options_scan) && assoc->init->bend_scan)
1918     {
1919         ODR_MASK_SET(resp->options, Z_Options_scan);
1920         strcat(options, " scan");
1921     }
1922     if (ODR_MASK_GET(req->options, Z_Options_concurrentOperations))
1923     {
1924         ODR_MASK_SET(resp->options, Z_Options_concurrentOperations);
1925         strcat(options, " concurrop");
1926     }
1927     if (ODR_MASK_GET(req->options, Z_Options_sort) && assoc->init->bend_sort)
1928     {
1929         ODR_MASK_SET(resp->options, Z_Options_sort);
1930         strcat(options, " sort");
1931     }
1932
1933     if (ODR_MASK_GET(req->options, Z_Options_negotiationModel)
1934         && assoc->init->charneg_response)
1935     {
1936         Z_OtherInformation **p;
1937         Z_OtherInformationUnit *p0;
1938         
1939         yaz_oi_APDU(apdu, &p);
1940         
1941         if ((p0=yaz_oi_update(p, assoc->encode, NULL, 0, 0))) {
1942             ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
1943             
1944             p0->which = Z_OtherInfo_externallyDefinedInfo;
1945             p0->information.externallyDefinedInfo =
1946                 assoc->init->charneg_response;
1947         }
1948         ODR_MASK_SET(resp->options, Z_Options_negotiationModel);
1949         strcat(options, " negotiation");
1950     }
1951         
1952     ODR_MASK_SET(resp->options, Z_Options_triggerResourceCtrl);
1953
1954     if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_1))
1955     {
1956         ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_1);
1957         assoc->version = 1; /* 1 & 2 are equivalent */
1958     }
1959     if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_2))
1960     {
1961         ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_2);
1962         assoc->version = 2;
1963     }
1964     if (ODR_MASK_GET(req->protocolVersion, Z_ProtocolVersion_3))
1965     {
1966         ODR_MASK_SET(resp->protocolVersion, Z_ProtocolVersion_3);
1967         assoc->version = 3;
1968     }
1969
1970     yaz_log(log_requestdetail, "Negotiated to v%d: %s", assoc->version, options);
1971     assoc->maximumRecordSize = *req->maximumRecordSize;
1972
1973     if (cb && assoc->maximumRecordSize > cb->maxrecordsize)
1974         assoc->maximumRecordSize = cb->maxrecordsize;
1975     assoc->preferredMessageSize = *req->preferredMessageSize;
1976     if (assoc->preferredMessageSize > assoc->maximumRecordSize)
1977         assoc->preferredMessageSize = assoc->maximumRecordSize;
1978
1979     resp->preferredMessageSize = &assoc->preferredMessageSize;
1980     resp->maximumRecordSize = &assoc->maximumRecordSize;
1981
1982     resp->implementationId = odr_prepend(assoc->encode,
1983                 assoc->init->implementation_id,
1984                 resp->implementationId);
1985
1986     resp->implementationName = odr_prepend(assoc->encode,
1987                 assoc->init->implementation_name,
1988                 odr_prepend(assoc->encode, "GFS", resp->implementationName));
1989
1990     version = odr_strdup(assoc->encode, "$Revision: 1.67 $");
1991     if (strlen(version) > 10)   /* check for unexpanded CVS strings */
1992         version[strlen(version)-2] = '\0';
1993     resp->implementationVersion = odr_prepend(assoc->encode,
1994                 assoc->init->implementation_version,
1995                 odr_prepend(assoc->encode, &version[11],
1996                             resp->implementationVersion));
1997
1998     if (binitres->errcode)
1999     {
2000         assoc->state = ASSOC_DEAD;
2001         resp->userInformationField =
2002             init_diagnostics(assoc->encode, binitres->errcode,
2003                              binitres->errstring);
2004         *resp->result = 0;
2005     }
2006     if (log_request)
2007     {
2008         if (!req->idAuthentication)
2009             yaz_log(log_request, "Auth none");
2010         else if (req->idAuthentication->which == Z_IdAuthentication_open)
2011         {
2012             const char *open = req->idAuthentication->u.open;
2013             const char *slash = strchr(open, '/');
2014             int len;
2015             if (slash)
2016                 len = slash - open;
2017             else
2018                 len = strlen(open);
2019                 yaz_log(log_request, "Auth open %.*s", len, open);
2020         }
2021         else if (req->idAuthentication->which == Z_IdAuthentication_idPass)
2022         {
2023             const char *user = req->idAuthentication->u.idPass->userId;
2024             const char *group = req->idAuthentication->u.idPass->groupId;
2025             yaz_log(log_request, "Auth idPass %s %s",
2026                     user ? user : "-", group ? group : "-");
2027         }
2028         else if (req->idAuthentication->which 
2029                  == Z_IdAuthentication_anonymous)
2030         {
2031             yaz_log(log_request, "Auth anonymous");
2032         }
2033         else
2034         {
2035             yaz_log(log_request, "Auth other");
2036         }
2037     }
2038     if (log_request)
2039     {
2040         WRBUF wr = wrbuf_alloc();
2041         wrbuf_printf(wr, "Init ");
2042         if (binitres->errcode)
2043             wrbuf_printf(wr, "ERROR %d", binitres->errcode);
2044         else
2045             wrbuf_printf(wr, "OK -");
2046         wrbuf_printf(wr, " ID:%s Name:%s Version:%s",
2047                      (req->implementationId ? req->implementationId :"-"), 
2048                      (req->implementationName ?
2049                       req->implementationName : "-"),
2050                      (req->implementationVersion ?
2051                       req->implementationVersion : "-")
2052             );
2053         yaz_log(log_request, "%s", wrbuf_buf(wr));
2054         wrbuf_free(wr, 1);
2055     }
2056     return apdu;
2057 }
2058
2059 /*
2060  * Set the specified `errcode' and `errstring' into a UserInfo-1
2061  * external to be returned to the client in accordance with Z35.90
2062  * Implementor Agreement 5 (Returning diagnostics in an InitResponse):
2063  *      http://lcweb.loc.gov/z3950/agency/agree/initdiag.html
2064  */
2065 static Z_External *init_diagnostics(ODR odr, int error, const char *addinfo)
2066 {
2067     yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2068         addinfo ? " -- " : "", addinfo ? addinfo : "");
2069     return zget_init_diagnostics(odr, error, addinfo);
2070 }
2071
2072 /*
2073  * nonsurrogate diagnostic record.
2074  */
2075 static Z_Records *diagrec(association *assoc, int error, char *addinfo)
2076 {
2077     Z_Records *rec = (Z_Records *) odr_malloc (assoc->encode, sizeof(*rec));
2078
2079     yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2080             addinfo ? " -- " : "", addinfo ? addinfo : "");
2081
2082     rec->which = Z_Records_NSD;
2083     rec->u.nonSurrogateDiagnostic = zget_DefaultDiagFormat(assoc->encode,
2084                                                            error, addinfo);
2085     return rec;
2086 }
2087
2088 /*
2089  * surrogate diagnostic.
2090  */
2091 static Z_NamePlusRecord *surrogatediagrec(association *assoc, 
2092                                           const char *dbname,
2093                                           int error, const char *addinfo)
2094 {
2095     yaz_log(log_requestdetail, "[%d] %s%s%s", error, diagbib1_str(error),
2096             addinfo ? " -- " : "", addinfo ? addinfo : "");
2097     return zget_surrogateDiagRec(assoc->encode, dbname, error, addinfo);
2098 }
2099
2100 static Z_Records *pack_records(association *a, char *setname, int start,
2101                                int *num, Z_RecordComposition *comp,
2102                                int *next, int *pres, oid_value format,
2103                                Z_ReferenceId *referenceId,
2104                                int *oid, int *errcode)
2105 {
2106     int recno, total_length = 0, toget = *num, dumped_records = 0;
2107     Z_Records *records =
2108         (Z_Records *) odr_malloc (a->encode, sizeof(*records));
2109     Z_NamePlusRecordList *reclist =
2110         (Z_NamePlusRecordList *) odr_malloc (a->encode, sizeof(*reclist));
2111     Z_NamePlusRecord **list =
2112         (Z_NamePlusRecord **) odr_malloc (a->encode, sizeof(*list) * toget);
2113
2114     records->which = Z_Records_DBOSD;
2115     records->u.databaseOrSurDiagnostics = reclist;
2116     reclist->num_records = 0;
2117     reclist->records = list;
2118     *pres = Z_PresentStatus_success;
2119     *num = 0;
2120     *next = 0;
2121
2122     yaz_log(log_requestdetail, "Request to pack %d+%d %s", start, toget, setname);
2123     yaz_log(log_requestdetail, "pms=%d, mrs=%d", a->preferredMessageSize,
2124         a->maximumRecordSize);
2125     for (recno = start; reclist->num_records < toget; recno++)
2126     {
2127         bend_fetch_rr freq;
2128         Z_NamePlusRecord *thisrec;
2129         int this_length = 0;
2130         /*
2131          * we get the number of bytes allocated on the stream before any
2132          * allocation done by the backend - this should give us a reasonable
2133          * idea of the total size of the data so far.
2134          */
2135         total_length = odr_total(a->encode) - dumped_records;
2136         freq.errcode = 0;
2137         freq.errstring = 0;
2138         freq.basename = 0;
2139         freq.len = 0;
2140         freq.record = 0;
2141         freq.last_in_set = 0;
2142         freq.setname = setname;
2143         freq.surrogate_flag = 0;
2144         freq.number = recno;
2145         freq.comp = comp;
2146         freq.request_format = format;
2147         freq.request_format_raw = oid;
2148         freq.output_format = format;
2149         freq.output_format_raw = 0;
2150         freq.stream = a->encode;
2151         freq.print = a->print;
2152         freq.referenceId = referenceId;
2153         freq.schema = 0;
2154         (*a->init->bend_fetch)(a->backend, &freq);
2155
2156         *next = freq.last_in_set ? 0 : recno + 1;
2157
2158         /* backend should be able to signal whether error is system-wide
2159            or only pertaining to current record */
2160         if (freq.errcode)
2161         {
2162             if (!freq.surrogate_flag)
2163             {
2164                 char s[20];
2165                 *pres = Z_PresentStatus_failure;
2166                 /* for 'present request out of range',
2167                    set addinfo to record position if not set */
2168                 if (freq.errcode == YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE  && 
2169                                 freq.errstring == 0)
2170                 {
2171                     sprintf (s, "%d", recno);
2172                     freq.errstring = s;
2173                 }
2174                 if (errcode)
2175                     *errcode = freq.errcode;
2176                 return diagrec(a, freq.errcode, freq.errstring);
2177             }
2178             reclist->records[reclist->num_records] =
2179                 surrogatediagrec(a, freq.basename, freq.errcode,
2180                                  freq.errstring);
2181             reclist->num_records++;
2182             continue;
2183         }
2184         if (freq.record == 0)  /* no error and no record ? */
2185         {
2186             *next = 0;   /* signal end-of-set and stop */
2187             break;
2188         }
2189         if (freq.len >= 0)
2190             this_length = freq.len;
2191         else
2192             this_length = odr_total(a->encode) - total_length - dumped_records;
2193         yaz_log(YLOG_DEBUG, "  fetched record, len=%d, total=%d dumped=%d",
2194             this_length, total_length, dumped_records);
2195         if (a->preferredMessageSize > 0 &&
2196                 this_length + total_length > a->preferredMessageSize)
2197         {
2198             /* record is small enough, really */
2199             if (this_length <= a->preferredMessageSize && recno > start)
2200             {
2201                 yaz_log(log_requestdetail, "  Dropped last normal-sized record");
2202                 *pres = Z_PresentStatus_partial_2;
2203                 break;
2204             }
2205             /* record can only be fetched by itself */
2206             if (this_length < a->maximumRecordSize)
2207             {
2208                 yaz_log(log_requestdetail, "  Record > prefmsgsz");
2209                 if (toget > 1)
2210                 {
2211                     yaz_log(YLOG_DEBUG, "  Dropped it");
2212                     reclist->records[reclist->num_records] =
2213                          surrogatediagrec(a, freq.basename, 16, 0);
2214                     reclist->num_records++;
2215                     dumped_records += this_length;
2216                     continue;
2217                 }
2218             }
2219             else /* too big entirely */
2220             {
2221                 yaz_log(log_requestdetail, "Record > maxrcdsz this=%d max=%d",
2222                         this_length, a->maximumRecordSize);
2223                 reclist->records[reclist->num_records] =
2224                     surrogatediagrec(a, freq.basename, 17, 0);
2225                 reclist->num_records++;
2226                 dumped_records += this_length;
2227                 continue;
2228             }
2229         }
2230
2231         if (!(thisrec = (Z_NamePlusRecord *)
2232               odr_malloc(a->encode, sizeof(*thisrec))))
2233             return 0;
2234         if (freq.basename)
2235             thisrec->databaseName = odr_strdup(a->encode, freq.basename);
2236         else
2237             thisrec->databaseName = 0;
2238         thisrec->which = Z_NamePlusRecord_databaseRecord;
2239
2240         if (freq.output_format_raw)
2241         {
2242             struct oident *ident = oid_getentbyoid(freq.output_format_raw);
2243             freq.output_format = ident->value;
2244         }
2245         thisrec->u.databaseRecord = z_ext_record(a->encode, freq.output_format,
2246                                                  freq.record, freq.len);
2247         if (!thisrec->u.databaseRecord)
2248             return 0;
2249         reclist->records[reclist->num_records] = thisrec;
2250         reclist->num_records++;
2251     }
2252     *num = reclist->num_records;
2253     return records;
2254 }
2255
2256 static Z_APDU *process_searchRequest(association *assoc, request *reqb,
2257     int *fd)
2258 {
2259     Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2260     bend_search_rr *bsrr = 
2261         (bend_search_rr *)nmem_malloc (reqb->request_mem, sizeof(*bsrr));
2262     
2263     yaz_log(log_requestdetail, "Got SearchRequest.");
2264     bsrr->fd = fd;
2265     bsrr->request = reqb;
2266     bsrr->association = assoc;
2267     bsrr->referenceId = req->referenceId;
2268     save_referenceId (reqb, bsrr->referenceId);
2269     bsrr->srw_sortKeys = 0;
2270     bsrr->srw_setname = 0;
2271     bsrr->srw_setnameIdleTime = 0;
2272
2273     yaz_log (log_requestdetail, "ResultSet '%s'", req->resultSetName);
2274     if (req->databaseNames)
2275     {
2276         int i;
2277         for (i = 0; i < req->num_databaseNames; i++)
2278             yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
2279     }
2280
2281     yaz_log_zquery_level(log_requestdetail,req->query);
2282
2283     if (assoc->init->bend_search)
2284     {
2285         bsrr->setname = req->resultSetName;
2286         bsrr->replace_set = *req->replaceIndicator;
2287         bsrr->num_bases = req->num_databaseNames;
2288         bsrr->basenames = req->databaseNames;
2289         bsrr->query = req->query;
2290         bsrr->stream = assoc->encode;
2291         nmem_transfer(bsrr->stream->mem, reqb->request_mem);
2292         bsrr->decode = assoc->decode;
2293         bsrr->print = assoc->print;
2294         bsrr->hits = 0;
2295         bsrr->errcode = 0;
2296         bsrr->errstring = NULL;
2297         bsrr->search_info = NULL;
2298
2299         if (assoc->cql_transform &&
2300             req->query->which == Z_Query_type_104 &&
2301             req->query->u.type_104->which == Z_External_CQL)
2302         {
2303             /* have a CQL query and a CQL to PQF transform .. */
2304             int srw_errcode = 
2305                 cql2pqf(bsrr->stream, req->query->u.type_104->u.cql,
2306                         assoc->cql_transform, bsrr->query);
2307             if (srw_errcode)
2308                 bsrr->errcode = yaz_diag_srw_to_bib1(srw_errcode);
2309         }
2310         if (!bsrr->errcode)
2311             (assoc->init->bend_search)(assoc->backend, bsrr);
2312         if (!bsrr->request)  /* backend not ready with the search response */
2313             return 0;  /* should not be used any more */
2314     }
2315     else
2316     { 
2317         /* FIXME - make a diagnostic for it */
2318         yaz_log(YLOG_WARN,"Search not supported ?!?!");
2319     }
2320     return response_searchRequest(assoc, reqb, bsrr, fd);
2321 }
2322
2323 int bend_searchresponse(void *handle, bend_search_rr *bsrr) {return 0;}
2324
2325 /*
2326  * Prepare a searchresponse based on the backend results. We probably want
2327  * to look at making the fetching of records nonblocking as well, but
2328  * so far, we'll keep things simple.
2329  * If bsrt is null, that means we're called in response to a communications
2330  * event, and we'll have to get the response for ourselves.
2331  */
2332 static Z_APDU *response_searchRequest(association *assoc, request *reqb,
2333     bend_search_rr *bsrt, int *fd)
2334 {
2335     Z_SearchRequest *req = reqb->apdu_request->u.searchRequest;
2336     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2337     Z_SearchResponse *resp = (Z_SearchResponse *)
2338         odr_malloc (assoc->encode, sizeof(*resp));
2339     int *nulint = odr_intdup (assoc->encode, 0);
2340     bool_t *sr = odr_intdup(assoc->encode, 1);
2341     int *next = odr_intdup(assoc->encode, 0);
2342     int *none = odr_intdup(assoc->encode, Z_SearchResponse_none);
2343     int returnedrecs=0;
2344
2345     apdu->which = Z_APDU_searchResponse;
2346     apdu->u.searchResponse = resp;
2347     resp->referenceId = req->referenceId;
2348     resp->additionalSearchInfo = 0;
2349     resp->otherInfo = 0;
2350     *fd = -1;
2351     if (!bsrt && !bend_searchresponse(assoc->backend, bsrt))
2352     {
2353         yaz_log(YLOG_FATAL, "Bad result from backend");
2354         return 0;
2355     }
2356     else if (bsrt->errcode)
2357     {
2358         resp->records = diagrec(assoc, bsrt->errcode, bsrt->errstring);
2359         resp->resultCount = nulint;
2360         resp->numberOfRecordsReturned = nulint;
2361         resp->nextResultSetPosition = nulint;
2362         resp->searchStatus = nulint;
2363         resp->resultSetStatus = none;
2364         resp->presentStatus = 0;
2365     }
2366     else
2367     {
2368         int *toget = odr_intdup(assoc->encode, 0);
2369         int *presst = odr_intdup(assoc->encode, 0);
2370         Z_RecordComposition comp, *compp = 0;
2371
2372         yaz_log (log_requestdetail, "resultCount: %d", bsrt->hits);
2373
2374         resp->records = 0;
2375         resp->resultCount = &bsrt->hits;
2376
2377         comp.which = Z_RecordComp_simple;
2378         /* how many records does the user agent want, then? */
2379         if (bsrt->hits <= *req->smallSetUpperBound)
2380         {
2381             *toget = bsrt->hits;
2382             if ((comp.u.simple = req->smallSetElementSetNames))
2383                 compp = &comp;
2384         }
2385         else if (bsrt->hits < *req->largeSetLowerBound)
2386         {
2387             *toget = *req->mediumSetPresentNumber;
2388             if (*toget > bsrt->hits)
2389                 *toget = bsrt->hits;
2390             if ((comp.u.simple = req->mediumSetElementSetNames))
2391                 compp = &comp;
2392         }
2393         else
2394             *toget = 0;
2395
2396         if (*toget && !resp->records)
2397         {
2398             oident *prefformat;
2399             oid_value form;
2400
2401             if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
2402                 form = VAL_NONE;
2403             else
2404                 form = prefformat->value;
2405             resp->records = pack_records(assoc, req->resultSetName, 1,
2406                                          toget, compp, next, presst, form, req->referenceId,
2407                                          req->preferredRecordSyntax, NULL);
2408             if (!resp->records)
2409                 return 0;
2410             resp->numberOfRecordsReturned = toget;
2411             returnedrecs = *toget;
2412             resp->nextResultSetPosition = next;
2413             resp->searchStatus = sr;
2414             resp->resultSetStatus = 0;
2415             resp->presentStatus = presst;
2416         }
2417         else
2418         {
2419             if (*resp->resultCount)
2420                 *next = 1;
2421             resp->numberOfRecordsReturned = nulint;
2422             resp->nextResultSetPosition = next;
2423             resp->searchStatus = sr;
2424             resp->resultSetStatus = 0;
2425             resp->presentStatus = 0;
2426         }
2427     }
2428     resp->additionalSearchInfo = bsrt->search_info;
2429
2430     if (log_request)
2431     {
2432         WRBUF wr = wrbuf_alloc();
2433         if (bsrt->errcode)
2434             wrbuf_printf(wr, "ERROR %d", bsrt->errcode);
2435         else
2436             wrbuf_printf(wr, "OK %d", bsrt->hits);
2437         wrbuf_printf(wr, " %s 1+%d ",
2438                      req->resultSetName, returnedrecs);
2439         yaz_query_to_wrbuf(wr, req->query);
2440         
2441         yaz_log(log_request, "Search %s", wrbuf_buf(wr));
2442         wrbuf_free(wr, 1);
2443     }
2444     return apdu;
2445 }
2446
2447 /*
2448  * Maybe we got a little over-friendly when we designed bend_fetch to
2449  * get only one record at a time. Some backends can optimise multiple-record
2450  * fetches, and at any rate, there is some overhead involved in
2451  * all that selecting and hopping around. Problem is, of course, that the
2452  * frontend can't know ahead of time how many records it'll need to
2453  * fill the negotiated PDU size. Annoying. Segmentation or not, Z/SR
2454  * is downright lousy as a bulk data transfer protocol.
2455  *
2456  * To start with, we'll do the fetching of records from the backend
2457  * in one operation: To save some trips in and out of the event-handler,
2458  * and to simplify the interface to pack_records. At any rate, asynch
2459  * operation is more fun in operations that have an unpredictable execution
2460  * speed - which is normally more true for search than for present.
2461  */
2462 static Z_APDU *process_presentRequest(association *assoc, request *reqb,
2463                                       int *fd)
2464 {
2465     Z_PresentRequest *req = reqb->apdu_request->u.presentRequest;
2466     oident *prefformat;
2467     oid_value form;
2468     Z_APDU *apdu;
2469     Z_PresentResponse *resp;
2470     int *next;
2471     int *num;
2472     int errcode = 0;
2473     const char *errstring = 0;
2474
2475     yaz_log(log_requestdetail, "Got PresentRequest.");
2476
2477     if (!(prefformat = oid_getentbyoid(req->preferredRecordSyntax)))
2478         form = VAL_NONE;
2479     else
2480         form = prefformat->value;
2481     resp = (Z_PresentResponse *)odr_malloc (assoc->encode, sizeof(*resp));
2482     resp->records = 0;
2483     resp->presentStatus = odr_intdup(assoc->encode, 0);
2484     if (assoc->init->bend_present)
2485     {
2486         bend_present_rr *bprr = (bend_present_rr *)
2487             nmem_malloc (reqb->request_mem, sizeof(*bprr));
2488         bprr->setname = req->resultSetId;
2489         bprr->start = *req->resultSetStartPoint;
2490         bprr->number = *req->numberOfRecordsRequested;
2491         bprr->format = form;
2492         bprr->comp = req->recordComposition;
2493         bprr->referenceId = req->referenceId;
2494         bprr->stream = assoc->encode;
2495         bprr->print = assoc->print;
2496         bprr->request = reqb;
2497         bprr->association = assoc;
2498         bprr->errcode = 0;
2499         bprr->errstring = NULL;
2500         (*assoc->init->bend_present)(assoc->backend, bprr);
2501         
2502         if (!bprr->request)
2503             return 0; /* should not happen */
2504         if (bprr->errcode)
2505         {
2506             resp->records = diagrec(assoc, bprr->errcode, bprr->errstring);
2507             *resp->presentStatus = Z_PresentStatus_failure;
2508             errcode = bprr->errcode;
2509             errstring = bprr->errstring;
2510         }
2511     }
2512     apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2513     next = odr_intdup(assoc->encode, 0);
2514     num = odr_intdup(assoc->encode, 0);
2515     
2516     apdu->which = Z_APDU_presentResponse;
2517     apdu->u.presentResponse = resp;
2518     resp->referenceId = req->referenceId;
2519     resp->otherInfo = 0;
2520     
2521     if (!resp->records)
2522     {
2523         *num = *req->numberOfRecordsRequested;
2524         resp->records =
2525             pack_records(assoc, req->resultSetId, *req->resultSetStartPoint,
2526                          num, req->recordComposition, next,
2527                          resp->presentStatus,
2528                          form, req->referenceId, req->preferredRecordSyntax, 
2529                          &errcode);
2530     }
2531     if (log_request)
2532     {
2533         WRBUF wr = wrbuf_alloc();
2534         wrbuf_printf(wr, "Present ");
2535
2536         if (*resp->presentStatus == Z_PresentStatus_failure)
2537             wrbuf_printf(wr, "ERROR %d", errcode);
2538         else if (*resp->presentStatus == Z_PresentStatus_success)
2539             wrbuf_printf(wr, "OK -");
2540         else
2541             wrbuf_printf(wr, "Partial %d", *resp->presentStatus);
2542
2543         wrbuf_printf(wr, " %s %d+%d ",
2544                 req->resultSetId, *req->resultSetStartPoint,
2545                 *req->numberOfRecordsRequested);
2546         yaz_log(log_request, "%s", wrbuf_buf(wr) );
2547         wrbuf_free(wr, 1);
2548     }
2549     if (!resp->records)
2550         return 0;
2551     resp->numberOfRecordsReturned = num;
2552     resp->nextResultSetPosition = next;
2553     
2554     return apdu;
2555 }
2556
2557 /*
2558  * Scan was implemented rather in a hurry, and with support for only the basic
2559  * elements of the service in the backend API. Suggestions are welcome.
2560  */
2561 static Z_APDU *process_scanRequest(association *assoc, request *reqb, int *fd)
2562 {
2563     Z_ScanRequest *req = reqb->apdu_request->u.scanRequest;
2564     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2565     Z_ScanResponse *res = (Z_ScanResponse *)
2566         odr_malloc (assoc->encode, sizeof(*res));
2567     int *scanStatus = odr_intdup(assoc->encode, Z_Scan_failure);
2568     int *numberOfEntriesReturned = odr_intdup(assoc->encode, 0);
2569     Z_ListEntries *ents = (Z_ListEntries *)
2570         odr_malloc (assoc->encode, sizeof(*ents));
2571     Z_DiagRecs *diagrecs_p = NULL;
2572     oident *attset;
2573     bend_scan_rr *bsrr = (bend_scan_rr *)
2574         odr_malloc (assoc->encode, sizeof(*bsrr));
2575     struct scan_entry *save_entries;
2576
2577     yaz_log(log_requestdetail, "Got ScanRequest");
2578
2579     apdu->which = Z_APDU_scanResponse;
2580     apdu->u.scanResponse = res;
2581     res->referenceId = req->referenceId;
2582
2583     /* if step is absent, set it to 0 */
2584     res->stepSize = odr_intdup(assoc->encode, 0);
2585     if (req->stepSize)
2586         *res->stepSize = *req->stepSize;
2587
2588     res->scanStatus = scanStatus;
2589     res->numberOfEntriesReturned = numberOfEntriesReturned;
2590     res->positionOfTerm = 0;
2591     res->entries = ents;
2592     ents->num_entries = 0;
2593     ents->entries = NULL;
2594     ents->num_nonsurrogateDiagnostics = 0;
2595     ents->nonsurrogateDiagnostics = NULL;
2596     res->attributeSet = 0;
2597     res->otherInfo = 0;
2598
2599     if (req->databaseNames)
2600     {
2601         int i;
2602         for (i = 0; i < req->num_databaseNames; i++)
2603             yaz_log (log_requestdetail, "Database '%s'", req->databaseNames[i]);
2604     }
2605     bsrr->scanClause = 0;
2606     bsrr->errcode = 0;
2607     bsrr->errstring = 0;
2608     bsrr->num_bases = req->num_databaseNames;
2609     bsrr->basenames = req->databaseNames;
2610     bsrr->num_entries = *req->numberOfTermsRequested;
2611     bsrr->term = req->termListAndStartPoint;
2612     bsrr->referenceId = req->referenceId;
2613     bsrr->stream = assoc->encode;
2614     bsrr->print = assoc->print;
2615     bsrr->step_size = res->stepSize;
2616     bsrr->entries = 0;
2617     /* For YAZ 2.0 and earlier it was the backend handler that
2618        initialized entries (member display_term did not exist)
2619        YAZ 2.0 and later sets 'entries'  and initialize all members
2620        including 'display_term'. If YAZ 2.0 or later sees that
2621        entries was modified - we assume that it is an old handler and
2622        that 'display_term' is _not_ set.
2623     */
2624     if (bsrr->num_entries > 0) 
2625     {
2626         int i;
2627         bsrr->entries = odr_malloc(assoc->decode, sizeof(*bsrr->entries) *
2628                                    bsrr->num_entries);
2629         for (i = 0; i<bsrr->num_entries; i++)
2630         {
2631             bsrr->entries[i].term = 0;
2632             bsrr->entries[i].occurrences = 0;
2633             bsrr->entries[i].errcode = 0;
2634             bsrr->entries[i].errstring = 0;
2635             bsrr->entries[i].display_term = 0;
2636         }
2637     }
2638     save_entries = bsrr->entries;  /* save it so we can compare later */
2639
2640     if (req->attributeSet &&
2641         (attset = oid_getentbyoid(req->attributeSet)) &&
2642         (attset->oclass == CLASS_ATTSET || attset->oclass == CLASS_GENERAL))
2643         bsrr->attributeset = attset->value;
2644     else
2645         bsrr->attributeset = VAL_NONE;
2646     log_scan_term_level (log_requestdetail, req->termListAndStartPoint, 
2647             bsrr->attributeset);
2648     bsrr->term_position = req->preferredPositionInResponse ?
2649         *req->preferredPositionInResponse : 1;
2650
2651     ((int (*)(void *, bend_scan_rr *))
2652      (*assoc->init->bend_scan))(assoc->backend, bsrr);
2653
2654     if (bsrr->errcode)
2655         diagrecs_p = zget_DiagRecs(assoc->encode,
2656                                    bsrr->errcode, bsrr->errstring);
2657     else
2658     {
2659         int i;
2660         Z_Entry **tab = (Z_Entry **)
2661             odr_malloc (assoc->encode, sizeof(*tab) * bsrr->num_entries);
2662         
2663         if (bsrr->status == BEND_SCAN_PARTIAL)
2664             *scanStatus = Z_Scan_partial_5;
2665         else
2666             *scanStatus = Z_Scan_success;
2667         ents->entries = tab;
2668         ents->num_entries = bsrr->num_entries;
2669         res->numberOfEntriesReturned = &ents->num_entries;          
2670         res->positionOfTerm = &bsrr->term_position;
2671         for (i = 0; i < bsrr->num_entries; i++)
2672         {
2673             Z_Entry *e;
2674             Z_TermInfo *t;
2675             Odr_oct *o;
2676             
2677             tab[i] = e = (Z_Entry *)odr_malloc(assoc->encode, sizeof(*e));
2678             if (bsrr->entries[i].occurrences >= 0)
2679             {
2680                 e->which = Z_Entry_termInfo;
2681                 e->u.termInfo = t = (Z_TermInfo *)
2682                     odr_malloc(assoc->encode, sizeof(*t));
2683                 t->suggestedAttributes = 0;
2684                 t->displayTerm = 0;
2685                 if (save_entries == bsrr->entries && 
2686                     bsrr->entries[i].display_term)
2687                 {
2688                     /* the entries was _not_ set by the handler. So it's
2689                        safe to test for new member display_term. It is
2690                        NULL'ed by us.
2691                     */
2692                     t->displayTerm = odr_strdup(assoc->encode,
2693                                                 bsrr->entries[i].display_term);
2694                 }
2695                 t->alternativeTerm = 0;
2696                 t->byAttributes = 0;
2697                 t->otherTermInfo = 0;
2698                 t->globalOccurrences = &bsrr->entries[i].occurrences;
2699                 t->term = (Z_Term *)
2700                     odr_malloc(assoc->encode, sizeof(*t->term));
2701                 t->term->which = Z_Term_general;
2702                 t->term->u.general = o =
2703                     (Odr_oct *)odr_malloc(assoc->encode, sizeof(Odr_oct));
2704                 o->buf = (unsigned char *)
2705                     odr_malloc(assoc->encode, o->len = o->size =
2706                                strlen(bsrr->entries[i].term));
2707                 memcpy(o->buf, bsrr->entries[i].term, o->len);
2708                 yaz_log(YLOG_DEBUG, "  term #%d: '%s' (%d)", i,
2709                          bsrr->entries[i].term, bsrr->entries[i].occurrences);
2710             }
2711             else
2712             {
2713                 Z_DiagRecs *drecs = zget_DiagRecs(assoc->encode,
2714                                                   bsrr->entries[i].errcode,
2715                                                   bsrr->entries[i].errstring);
2716                 assert (drecs->num_diagRecs == 1);
2717                 e->which = Z_Entry_surrogateDiagnostic;
2718                 assert (drecs->diagRecs[0]);
2719                 e->u.surrogateDiagnostic = drecs->diagRecs[0];
2720             }
2721         }
2722     }
2723     if (diagrecs_p)
2724     {
2725         ents->num_nonsurrogateDiagnostics = diagrecs_p->num_diagRecs;
2726         ents->nonsurrogateDiagnostics = diagrecs_p->diagRecs;
2727     }
2728     if (log_request)
2729     {
2730         WRBUF wr = wrbuf_alloc();
2731         if (bsrr->errcode)
2732             wr_diag(wr, bsrr->errcode, bsrr->errstring);
2733         else if (*res->scanStatus == Z_Scan_success)
2734             wrbuf_printf(wr, "OK");
2735         else
2736             wrbuf_printf(wr, "Partial");
2737
2738         wrbuf_printf(wr, " %d+%d %d ",
2739                      (req->preferredPositionInResponse ?
2740                       *req->preferredPositionInResponse : 1),
2741                      *req->numberOfTermsRequested,
2742                      (res->stepSize ? *res->stepSize : 0));
2743         yaz_scan_to_wrbuf(wr, req->termListAndStartPoint, 
2744                           bsrr->attributeset);
2745         yaz_log(log_request, "Scan %s", wrbuf_buf(wr) );
2746         wrbuf_free(wr, 1);
2747     }
2748     return apdu;
2749 }
2750
2751 static Z_APDU *process_sortRequest(association *assoc, request *reqb,
2752     int *fd)
2753 {
2754     int i;
2755     Z_SortRequest *req = reqb->apdu_request->u.sortRequest;
2756     Z_SortResponse *res = (Z_SortResponse *)
2757         odr_malloc (assoc->encode, sizeof(*res));
2758     bend_sort_rr *bsrr = (bend_sort_rr *)
2759         odr_malloc (assoc->encode, sizeof(*bsrr));
2760
2761     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2762
2763     yaz_log(log_requestdetail, "Got SortRequest.");
2764
2765     bsrr->num_input_setnames = req->num_inputResultSetNames;
2766     for (i=0;i<req->num_inputResultSetNames;i++)
2767         yaz_log(log_requestdetail, "Input resultset: '%s'",
2768                 req->inputResultSetNames[i]);
2769     bsrr->input_setnames = req->inputResultSetNames;
2770     bsrr->referenceId = req->referenceId;
2771     bsrr->output_setname = req->sortedResultSetName;
2772     yaz_log(log_requestdetail, "Output resultset: '%s'",
2773                 req->sortedResultSetName);
2774     bsrr->sort_sequence = req->sortSequence;
2775        /*FIXME - dump those sequences too */
2776     bsrr->stream = assoc->encode;
2777     bsrr->print = assoc->print;
2778
2779     bsrr->sort_status = Z_SortResponse_failure;
2780     bsrr->errcode = 0;
2781     bsrr->errstring = 0;
2782     
2783     (*assoc->init->bend_sort)(assoc->backend, bsrr);
2784     
2785     res->referenceId = bsrr->referenceId;
2786     res->sortStatus = odr_intdup(assoc->encode, bsrr->sort_status);
2787     res->resultSetStatus = 0;
2788     if (bsrr->errcode)
2789     {
2790         Z_DiagRecs *dr = zget_DiagRecs(assoc->encode,
2791                                        bsrr->errcode, bsrr->errstring);
2792         res->diagnostics = dr->diagRecs;
2793         res->num_diagnostics = dr->num_diagRecs;
2794     }
2795     else
2796     {
2797         res->num_diagnostics = 0;
2798         res->diagnostics = 0;
2799     }
2800     res->resultCount = 0;
2801     res->otherInfo = 0;
2802
2803     apdu->which = Z_APDU_sortResponse;
2804     apdu->u.sortResponse = res;
2805     if (log_request)
2806     {
2807         WRBUF wr = wrbuf_alloc();
2808         wrbuf_printf(wr, "Sort ");
2809         if (bsrr->errcode)
2810             wrbuf_printf(wr, " ERROR %d", bsrr->errcode);
2811         else
2812             wrbuf_printf(wr,  "OK -");
2813         wrbuf_printf(wr, " (");
2814         for (i = 0; i<req->num_inputResultSetNames; i++)
2815         {
2816             if (i)
2817                 wrbuf_printf(wr, ",");
2818             wrbuf_printf(wr, req->inputResultSetNames[i]);
2819         }
2820         wrbuf_printf(wr, ")->%s ",req->sortedResultSetName);
2821
2822         yaz_log(log_request, "%s", wrbuf_buf(wr) );
2823         wrbuf_free(wr, 1);
2824     }
2825     return apdu;
2826 }
2827
2828 static Z_APDU *process_deleteRequest(association *assoc, request *reqb,
2829     int *fd)
2830 {
2831     int i;
2832     Z_DeleteResultSetRequest *req =
2833         reqb->apdu_request->u.deleteResultSetRequest;
2834     Z_DeleteResultSetResponse *res = (Z_DeleteResultSetResponse *)
2835         odr_malloc (assoc->encode, sizeof(*res));
2836     bend_delete_rr *bdrr = (bend_delete_rr *)
2837         odr_malloc (assoc->encode, sizeof(*bdrr));
2838     Z_APDU *apdu = (Z_APDU *)odr_malloc (assoc->encode, sizeof(*apdu));
2839
2840     yaz_log(log_requestdetail, "Got DeleteRequest.");
2841
2842     bdrr->num_setnames = req->num_resultSetList;
2843     bdrr->setnames = req->resultSetList;
2844     for (i = 0; i<req->num_resultSetList; i++)
2845         yaz_log(log_requestdetail, "resultset: '%s'",
2846                 req->resultSetList[i]);
2847     bdrr->stream = assoc->encode;
2848     bdrr->print = assoc->print;
2849     bdrr->function = *req->deleteFunction;
2850     bdrr->referenceId = req->referenceId;
2851     bdrr->statuses = 0;
2852     if (bdrr->num_setnames > 0)
2853     {
2854         bdrr->statuses = (int*) 
2855             odr_malloc(assoc->encode, sizeof(*bdrr->statuses) *
2856                        bdrr->num_setnames);
2857         for (i = 0; i < bdrr->num_setnames; i++)
2858             bdrr->statuses[i] = 0;
2859     }
2860     (*assoc->init->bend_delete)(assoc->backend, bdrr);
2861     
2862     res->referenceId = req->referenceId;
2863
2864     res->deleteOperationStatus = odr_intdup(assoc->encode,bdrr->delete_status);
2865
2866     res->deleteListStatuses = 0;
2867     if (bdrr->num_setnames > 0)
2868     {
2869         int i;
2870         res->deleteListStatuses = (Z_ListStatuses *)
2871             odr_malloc(assoc->encode, sizeof(*res->deleteListStatuses));
2872         res->deleteListStatuses->num = bdrr->num_setnames;
2873         res->deleteListStatuses->elements =
2874             (Z_ListStatus **)
2875             odr_malloc (assoc->encode, 
2876                         sizeof(*res->deleteListStatuses->elements) *
2877                         bdrr->num_setnames);
2878         for (i = 0; i<bdrr->num_setnames; i++)
2879         {
2880             res->deleteListStatuses->elements[i] =
2881                 (Z_ListStatus *)
2882                 odr_malloc (assoc->encode,
2883                             sizeof(**res->deleteListStatuses->elements));
2884             res->deleteListStatuses->elements[i]->status = bdrr->statuses+i;
2885             res->deleteListStatuses->elements[i]->id =
2886                 odr_strdup (assoc->encode, bdrr->setnames[i]);
2887         }
2888     }
2889     res->numberNotDeleted = 0;
2890     res->bulkStatuses = 0;
2891     res->deleteMessage = 0;
2892     res->otherInfo = 0;
2893
2894     apdu->which = Z_APDU_deleteResultSetResponse;
2895     apdu->u.deleteResultSetResponse = res;
2896     if (log_request)
2897     {
2898         WRBUF wr = wrbuf_alloc();
2899         wrbuf_printf(wr, "Delete ");
2900         if (bdrr->delete_status)
2901             wrbuf_printf(wr, "ERROR %d", bdrr->delete_status);
2902         else
2903             wrbuf_printf(wr, "OK -");
2904         for (i = 0; i<req->num_resultSetList; i++)
2905             wrbuf_printf(wr, " %s ", req->resultSetList[i]);
2906         yaz_log(log_request, "%s", wrbuf_buf(wr) );
2907         wrbuf_free(wr, 1);
2908     }
2909     return apdu;
2910 }
2911
2912 static void process_close(association *assoc, request *reqb)
2913 {
2914     Z_Close *req = reqb->apdu_request->u.close;
2915     static char *reasons[] =
2916     {
2917         "finished",
2918         "shutdown",
2919         "systemProblem",
2920         "costLimit",
2921         "resources",
2922         "securityViolation",
2923         "protocolError",
2924         "lackOfActivity",
2925         "peerAbort",
2926         "unspecified"
2927     };
2928
2929     yaz_log(log_requestdetail, "Got Close, reason %s, message %s",
2930         reasons[*req->closeReason], req->diagnosticInformation ?
2931         req->diagnosticInformation : "NULL");
2932     if (assoc->version < 3) /* to make do_force respond with close */
2933         assoc->version = 3;
2934     do_close_req(assoc, Z_Close_finished,
2935                  "Association terminated by client", reqb);
2936     yaz_log(log_request,"Close OK");
2937 }
2938
2939 void save_referenceId (request *reqb, Z_ReferenceId *refid)
2940 {
2941     if (refid)
2942     {
2943         reqb->len_refid = refid->len;
2944         reqb->refid = (char *)nmem_malloc (reqb->request_mem, refid->len);
2945         memcpy (reqb->refid, refid->buf, refid->len);
2946     }
2947     else
2948     {
2949         reqb->len_refid = 0;
2950         reqb->refid = NULL;
2951     }
2952 }
2953
2954 void bend_request_send (bend_association a, bend_request req, Z_APDU *res)
2955 {
2956     process_z_response (a, req, res);
2957 }
2958
2959 bend_request bend_request_mk (bend_association a)
2960 {
2961     request *nreq = request_get (&a->outgoing);
2962     nreq->request_mem = nmem_create ();
2963     return nreq;
2964 }
2965
2966 Z_ReferenceId *bend_request_getid (ODR odr, bend_request req)
2967 {
2968     Z_ReferenceId *id;
2969     if (!req->refid)
2970         return 0;
2971     id = (Odr_oct *)odr_malloc (odr, sizeof(*odr));
2972     id->buf = (unsigned char *)odr_malloc (odr, req->len_refid);
2973     id->len = id->size = req->len_refid;
2974     memcpy (id->buf, req->refid, req->len_refid);
2975     return id;
2976 }
2977
2978 void bend_request_destroy (bend_request *req)
2979 {
2980     nmem_destroy((*req)->request_mem);
2981     request_release(*req);
2982     *req = NULL;
2983 }
2984
2985 int bend_backend_respond (bend_association a, bend_request req)
2986 {
2987     char *msg;
2988     int r;
2989     r = process_z_request (a, req, &msg);
2990     if (r < 0)
2991         yaz_log (YLOG_WARN, "%s", msg);
2992     return r;
2993 }
2994
2995 void bend_request_setdata(bend_request r, void *p)
2996 {
2997     r->clientData = p;
2998 }
2999
3000 void *bend_request_getdata(bend_request r)
3001 {
3002     return r->clientData;
3003 }
3004
3005 static Z_APDU *process_segmentRequest (association *assoc, request *reqb)
3006 {
3007     bend_segment_rr req;
3008
3009     req.segment = reqb->apdu_request->u.segmentRequest;
3010     req.stream = assoc->encode;
3011     req.decode = assoc->decode;
3012     req.print = assoc->print;
3013     req.association = assoc;
3014     
3015     (*assoc->init->bend_segment)(assoc->backend, &req);
3016
3017     return 0;
3018 }
3019
3020 static Z_APDU *process_ESRequest(association *assoc, request *reqb, int *fd)
3021 {
3022     bend_esrequest_rr esrequest;
3023
3024     Z_ExtendedServicesRequest *req =
3025         reqb->apdu_request->u.extendedServicesRequest;
3026     Z_APDU *apdu = zget_APDU(assoc->encode, Z_APDU_extendedServicesResponse);
3027
3028     Z_ExtendedServicesResponse *resp = apdu->u.extendedServicesResponse;
3029
3030     yaz_log(log_requestdetail,"Got EsRequest");
3031
3032     esrequest.esr = reqb->apdu_request->u.extendedServicesRequest;
3033     esrequest.stream = assoc->encode;
3034     esrequest.decode = assoc->decode;
3035     esrequest.print = assoc->print;
3036     esrequest.errcode = 0;
3037     esrequest.errstring = NULL;
3038     esrequest.request = reqb;
3039     esrequest.association = assoc;
3040     esrequest.taskPackage = 0;
3041     esrequest.referenceId = req->referenceId;
3042     
3043     (*assoc->init->bend_esrequest)(assoc->backend, &esrequest);
3044     
3045     /* If the response is being delayed, return NULL */
3046     if (esrequest.request == NULL)
3047         return(NULL);
3048
3049     resp->referenceId = req->referenceId;
3050
3051     if (esrequest.errcode == -1)
3052     {
3053         /* Backend service indicates request will be processed */
3054         yaz_log(log_request,"EsRequest OK: Accepted !");
3055         *resp->operationStatus = Z_ExtendedServicesResponse_accepted;
3056     }
3057     else if (esrequest.errcode == 0)
3058     {
3059         /* Backend service indicates request will be processed */
3060         yaz_log(log_request,"EsRequest OK: Done !");
3061         *resp->operationStatus = Z_ExtendedServicesResponse_done;
3062     }
3063     else
3064     {
3065         Z_DiagRecs *diagRecs =
3066             zget_DiagRecs(assoc->encode, esrequest.errcode,
3067                           esrequest.errstring);
3068         /* Backend indicates error, request will not be processed */
3069         yaz_log(YLOG_DEBUG,"Request could not be processed...failure !");
3070         *resp->operationStatus = Z_ExtendedServicesResponse_failure;
3071         resp->num_diagnostics = diagRecs->num_diagRecs;
3072         resp->diagnostics = diagRecs->diagRecs;
3073         if (log_request)
3074         {
3075             WRBUF wr = wrbuf_alloc();
3076             wrbuf_diags(wr, resp->num_diagnostics, resp->diagnostics);
3077             yaz_log(log_request, "EsRequest %s", wrbuf_buf(wr) );
3078             wrbuf_free(wr, 1);
3079         }
3080
3081     }
3082     /* Do something with the members of bend_extendedservice */
3083     if (esrequest.taskPackage)
3084         resp->taskPackage = z_ext_record (assoc->encode, VAL_EXTENDED,
3085                                          (const char *)  esrequest.taskPackage,
3086                                           -1);
3087     yaz_log(YLOG_DEBUG,"Send the result apdu");
3088     return apdu;
3089 }
3090
3091 /*
3092  * Local variables:
3093  * c-basic-offset: 4
3094  * indent-tabs-mode: nil
3095  * End:
3096  * vim: shiftwidth=4 tabstop=8 expandtab
3097  */
3098