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