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