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