Temporarily enable full log for access from IP with NIS GROUP client
[yazproxy-moved-to-github.git] / src / yaz-proxy.cpp
1 /* $Id: yaz-proxy.cpp,v 1.54 2006-04-12 11:55:42 adam Exp $
2    Copyright (c) 1998-2006, Index Data.
3
4 This file is part of the yazproxy.
5
6 YAZ proxy is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 2, or (at your option) any later
9 version.
10
11 YAZ proxy is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with YAZ proxy; see the file LICENSE.  If not, write to the
18 Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
19 02111-1307, USA.
20  */
21
22 #ifdef WIN32
23 #define HAVE_SYS_STAT_H 1
24 #define HAVE_SYS_TYPES_H 1
25 #endif
26
27 #if HAVE_UNISTD_H
28 #include <unistd.h>
29 #endif
30 #if HAVE_SYS_TIME_H
31 #include <sys/time.h>
32 #endif
33 #if HAVE_SYS_TYPES_H
34 #include <sys/types.h>
35 #endif
36 #if HAVE_SYS_STAT_H
37 #include <sys/stat.h>
38 #endif
39
40 #include <assert.h>
41 #include <stdlib.h>
42 #include <time.h>
43 #include <fcntl.h>
44
45 #include <yaz/srw.h>
46 #include <yaz/marcdisp.h>
47 #include <yaz/yaz-iconv.h>
48 #include <yaz/log.h>
49 #include <yaz/diagbib1.h>
50 #include "proxyp.h"
51 #include <yaz/pquery.h>
52 #include <yaz/otherinfo.h>
53 #include <yaz/charneg.h>
54 #include "msg-thread.h"
55
56 using namespace yazpp_1;
57
58 #ifdef WIN32
59 #define strncasecmp _strnicmp
60 #endif
61
62 #define USE_AUTH_MSG 1
63
64 #if USE_AUTH_MSG
65 class YAZ_EXPORT Auth_Msg : public IMsg_Thread {
66 public:
67     int m_ret;
68     IMsg_Thread *handle();
69     void result();
70     Yaz_Proxy *m_proxy;
71     NMEM m_nmem;
72     char *m_apdu_buf;
73     int m_apdu_len;
74     Auth_Msg();
75     virtual ~Auth_Msg();
76 };
77
78 Auth_Msg::Auth_Msg()
79 {
80     m_nmem = nmem_create();
81 }
82
83 Auth_Msg::~Auth_Msg()
84 {
85     nmem_destroy(m_nmem);
86 }
87
88 IMsg_Thread *Auth_Msg::handle()
89 {
90     ODR decode = odr_createmem(ODR_DECODE);
91     Z_APDU *apdu;
92
93     odr_setbuf(decode, m_apdu_buf, m_apdu_len, 0);
94     int r = z_APDU(decode, &apdu, 0, 0);
95     if (!r)
96     {
97         yaz_log(YLOG_WARN, "decode failed in Auth_Msg::handle");
98     }
99     else
100     {
101         m_ret = m_proxy->handle_authentication(apdu);
102     }
103     odr_destroy(decode);
104     return this;
105 }
106
107 void Auth_Msg::result()
108 {
109     if (m_proxy->dec_ref(false))
110     {
111         yaz_log(YLOG_LOG, "Auth_Msg::proxy deleted meanwhile");
112     }
113     else
114     {
115         odr_setbuf(m_proxy->odr_decode(), m_apdu_buf, m_apdu_len, 0);
116         Z_APDU *apdu = 0;
117         int r = z_APDU(m_proxy->odr_decode(), &apdu, 0, 0);
118         if (!r)
119             yaz_log(YLOG_LOG, "Auth_Msg::result z_APDU failed");
120         m_proxy->result_authentication(apdu, m_ret);
121     }
122     delete this;
123 }
124
125 #endif
126
127 void Yaz_Proxy::result_authentication(Z_APDU *apdu, int ret)
128 {
129     if (apdu == 0 || ret == 0)
130     {
131         Z_APDU *apdu_reject = zget_APDU(odr_encode(), Z_APDU_initResponse);
132         *apdu_reject->u.initResponse->result = 0;
133         send_to_client(apdu_reject);
134         dec_ref(false);
135     }
136     else
137     {
138         if (apdu->which == Z_APDU_initRequest)
139         {
140             Yaz_ProxyConfig *cfg = check_reconfigure();
141             if (cfg)
142                 cfg->target_authentication(m_default_target, odr_encode(), 
143                                            apdu->u.initRequest);
144         }
145         handle_incoming_Z_PDU_2(apdu);
146     }
147 }
148
149 static const char *apdu_name(Z_APDU *apdu)
150 {
151     switch (apdu->which)
152     {
153     case Z_APDU_initRequest:
154         return "initRequest";
155     case Z_APDU_initResponse:
156         return "initResponse";
157     case Z_APDU_searchRequest:
158         return "searchRequest";
159     case Z_APDU_searchResponse:
160         return "searchResponse";
161     case Z_APDU_presentRequest:
162         return "presentRequest";
163     case Z_APDU_presentResponse:
164         return "presentResponse";
165     case Z_APDU_deleteResultSetRequest:
166         return "deleteResultSetRequest";
167     case Z_APDU_deleteResultSetResponse:
168         return "deleteResultSetResponse";
169     case Z_APDU_scanRequest:
170         return "scanRequest";
171     case Z_APDU_scanResponse:
172         return "scanResponse";
173     case Z_APDU_sortRequest:
174         return "sortRequest";
175     case Z_APDU_sortResponse:
176         return "sortResponse";
177     case Z_APDU_extendedServicesRequest:
178         return "extendedServicesRequest";
179     case Z_APDU_extendedServicesResponse:
180         return "extendedServicesResponse";
181     case Z_APDU_close:
182         return "close";
183     }
184     return "other";
185 }
186
187 static const char *gdu_name(Z_GDU *gdu)
188 {
189     switch(gdu->which)
190     {
191     case Z_GDU_Z3950:
192         return apdu_name(gdu->u.z3950);
193     case Z_GDU_HTTP_Request:
194         return "HTTP Request";
195     case Z_GDU_HTTP_Response:
196         return "HTTP Response";
197     }
198     return "Unknown request/response";
199 }
200
201 Yaz_Proxy::Yaz_Proxy(IPDU_Observable *the_PDU_Observable,
202                      ISocketObservable *the_socket_observable,
203                      Yaz_Proxy *parent)
204     :
205     Z_Assoc(the_PDU_Observable),
206     m_bw_stat(60), m_pdu_stat(60), m_search_stat(60)
207 {
208     m_PDU_Observable = the_PDU_Observable;
209     m_socket_observable = the_socket_observable;
210     m_client = 0;
211     m_parent = parent;
212     m_clientPool = 0;
213     m_seqno = 1;
214     m_keepalive_limit_bw = 500000;
215     m_keepalive_limit_pdu = 1000;
216     m_proxyTarget = 0;
217     m_default_target = 0;
218     m_proxy_negotiation_charset = 0;
219     m_proxy_negotiation_lang = 0;
220     m_proxy_negotiation_default_charset = 0;
221     m_charset_converter = new Yaz_CharsetConverter;
222     m_max_clients = 150;
223     m_log_mask = 0;
224     m_seed = time(0);
225     m_client_idletime = 600;
226     m_target_idletime = 600;
227     m_optimize = xstrdup ("1");
228     strcpy(m_session_str, "0 ");
229     m_session_no = 0;
230     m_bytes_sent = 0;
231     m_bytes_recv = 0;
232     m_bw_max = 0;
233     m_pdu_max = 0;
234     m_search_max = 0;
235     m_max_connect = 0;
236     m_max_connect_period = 0;
237     m_limit_connect = 0;
238     m_limit_connect_period = 0;
239     m_timeout_mode = timeout_normal;
240     m_timeout_gdu = 0;
241     m_max_record_retrieve = 0;
242     m_reconfig_flag = 0;
243     m_config_fname = 0;
244     m_request_no = 0;
245     m_flag_invalid_session = 0;
246     m_referenceId = 0;
247     m_referenceId_mem = nmem_create();
248     m_config = 0;
249     m_marcxml_mode = none;
250     m_stylesheet_xsp = 0;
251     m_stylesheet_nprl = 0;
252     m_stylesheet_apdu = 0;
253     m_s2z_stylesheet = 0;
254     m_s2z_database = 0;
255     m_schema = 0;
256     m_backend_type = 0;
257     m_backend_charset = 0;
258     m_frontend_type = 0;
259     m_initRequest_apdu = 0;
260     m_initRequest_mem = 0;
261     m_initRequest_preferredMessageSize = 0;
262     m_initRequest_maximumRecordSize = 0;
263     m_initRequest_options = 0;
264     m_initRequest_version = 0;
265     m_initRequest_oi_negotiation_charsets = 0;
266     m_initRequest_oi_negotiation_num_charsets = 0;
267     m_initRequest_oi_negotiation_langs = 0;
268     m_initRequest_oi_negotiation_num_langs = 0;
269     m_initRequest_oi_negotiation_selected = 0;
270     m_apdu_invalid_session = 0;
271     m_mem_invalid_session = 0;
272     m_s2z_odr_init = 0;
273     m_s2z_odr_search = 0;
274     m_s2z_init_apdu = 0;
275     m_s2z_search_apdu = 0;
276     m_s2z_present_apdu = 0;
277     m_http_keepalive = 0;
278     m_http_version = 0;
279     m_soap_ns = 0;
280     m_s2z_packing = Z_SRW_recordPacking_string;
281 #if HAVE_GETTIMEOFDAY
282     m_time_tv = xmalloc(sizeof(struct timeval));
283     struct timeval *tv = (struct timeval *) m_time_tv;
284     tv->tv_sec = 0;
285     tv->tv_usec = 0;
286 #else
287     m_time_tv = 0;
288 #endif
289     m_usemarcon_ini_stage1 = 0;
290     m_usemarcon_ini_stage2 = 0;
291     m_usemarcon = new Yaz_usemarcon();
292     if (!m_parent)
293         low_socket_open();
294     m_my_thread = 0;
295     m_ref_count = 1;
296     m_main_ptr_dec = false;
297     m_peername = 0;
298     m_initial_reduce = 0;
299 }
300
301 void Yaz_Proxy::inc_ref()
302 {
303     m_ref_count++;
304 }
305
306 Yaz_Proxy::~Yaz_Proxy()
307 {
308     yaz_log(YLOG_LOG, "%sClosed %d/%d sent/recv bytes total", m_session_str,
309             m_bytes_sent, m_bytes_recv);
310     nmem_destroy(m_initRequest_mem);
311     nmem_destroy(m_mem_invalid_session);
312     nmem_destroy(m_referenceId_mem);
313
314     xfree(m_proxyTarget);
315     xfree(m_default_target);
316     xfree(m_proxy_negotiation_charset);
317     xfree(m_proxy_negotiation_lang);
318     xfree(m_proxy_negotiation_default_charset);
319     delete m_charset_converter;
320     xfree(m_optimize);
321
322 #if HAVE_XSLT
323     if (m_stylesheet_xsp)
324         xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
325 #endif
326     xfree (m_time_tv);
327
328     xfree (m_peername);
329     xfree (m_schema);
330     xfree (m_backend_type);
331     xfree (m_backend_charset);
332     xfree (m_usemarcon_ini_stage1);
333     xfree (m_usemarcon_ini_stage2);
334     delete m_usemarcon;
335     if (m_s2z_odr_init)
336         odr_destroy(m_s2z_odr_init);
337     if (m_s2z_odr_search)
338         odr_destroy(m_s2z_odr_search);
339     if (!m_parent)
340         low_socket_close();
341     if (!m_parent)
342         delete m_my_thread;
343     delete m_config;
344 }
345
346 void Yaz_Proxy::set_debug_mode(int mode)
347 {
348     m_debug_mode = mode;
349 }
350
351 int Yaz_Proxy::set_config(const char *config)
352 {
353     delete m_config;
354     m_config = new Yaz_ProxyConfig();
355     xfree(m_config_fname);
356     m_config_fname = xstrdup(config);
357     int r = m_config->read_xml(config);
358     if (!r)
359     {
360         int period = 60;
361         m_config->get_generic_info(&m_log_mask, &m_max_clients,
362                                    &m_max_connect, &m_limit_connect, &period);
363         m_connect.set_period(period);
364     }
365     return r;
366 }
367
368 void Yaz_Proxy::set_default_target(const char *target)
369 {
370     xfree (m_default_target);
371     m_default_target = 0;
372     if (target)
373         m_default_target = (char *) xstrdup (target);
374 }
375
376 void Yaz_Proxy::set_proxy_negotiation (const char *charset, const char *lang,
377                                        const char *default_charset)
378 {
379     yaz_log(YLOG_LOG, "%sSet the proxy negotiation: charset to '%s', "
380         "default charset to '%s', language to '%s'", m_session_str, 
381         charset?charset:"none",
382         default_charset?default_charset:"none",
383         lang?lang:"none");
384     xfree (m_proxy_negotiation_charset);
385     xfree (m_proxy_negotiation_lang);
386     m_proxy_negotiation_charset = m_proxy_negotiation_lang = 0;
387     if (charset)
388         m_proxy_negotiation_charset = (char *) xstrdup (charset);
389     if (lang)
390         m_proxy_negotiation_lang = (char *) xstrdup (lang);
391     if (default_charset)
392         m_proxy_negotiation_default_charset =
393             (char *) xstrdup (default_charset);
394 }
395
396 Yaz_ProxyConfig *Yaz_Proxy::check_reconfigure()
397 {
398     if (m_parent)
399         return m_parent->check_reconfigure();
400
401     Yaz_ProxyConfig *cfg = m_config;
402     if (m_reconfig_flag)
403     {
404         yaz_log(YLOG_LOG, "reconfigure");
405         yaz_log_reopen();
406         if (m_config_fname && cfg)
407         {
408             yaz_log(YLOG_LOG, "reconfigure config %s", m_config_fname);
409             int r = cfg->read_xml(m_config_fname);
410             if (r)
411                 yaz_log(YLOG_WARN, "reconfigure failed");
412             else
413             {
414                 m_log_mask = 0;
415                 int period = 60;
416                 cfg->get_generic_info(&m_log_mask, &m_max_clients,
417                                       &m_max_connect, &m_limit_connect,
418                                       &period);
419                 m_connect.set_period(period);
420             }
421         }
422         else
423             yaz_log(YLOG_LOG, "reconfigure");
424         m_reconfig_flag = 0;
425     }
426     return cfg;
427 }
428
429 IPDU_Observer *Yaz_Proxy::sessionNotify(IPDU_Observable
430                                         *the_PDU_Observable, int fd)
431 {
432     check_reconfigure();
433
434     char session_str[200];
435     const char *peername = the_PDU_Observable->getpeername();
436     if (m_log_mask & PROXY_LOG_IP_CLIENT)
437         sprintf(session_str, "%ld:%d %s 0 ",
438                 (long) time(0), m_session_no, peername);
439     else
440         sprintf(session_str, "%ld:%d 0 ",
441                 (long) time(0), m_session_no);        
442     m_session_no++;
443
444     yaz_log (YLOG_LOG, "%sNew session %s", session_str, peername);
445
446     m_connect.cleanup(false);
447     m_connect.add_connect(peername);
448
449     int connect_total = m_connect.get_total(peername);
450     int connect_max = m_max_connect;
451     if (connect_max && connect_total > connect_max)
452     {
453         yaz_log(YLOG_LOG, "%sconnect not accepted total=%d max=%d",
454                 session_str, connect_total, connect_max);
455         return 0;
456     }
457     yaz_log(YLOG_LOG, "%sconnect accepted total=%d", session_str,
458             connect_total);
459     
460     Yaz_Proxy *new_proxy = new Yaz_Proxy(the_PDU_Observable,
461                                          m_socket_observable, this);
462
463     if (m_limit_connect)
464         new_proxy->m_initial_reduce = connect_total / m_limit_connect;
465
466     new_proxy->m_config = 0;
467     new_proxy->m_config_fname = 0;
468     new_proxy->timeout(m_client_idletime);
469     new_proxy->m_target_idletime = m_target_idletime;
470     new_proxy->set_default_target(m_default_target);
471     new_proxy->m_max_clients = m_max_clients;
472     new_proxy->m_log_mask = m_log_mask;
473
474     if (!strcmp(peername, "tcp:163.121.19.82")) // NIS GROUP
475         new_proxy->m_log_mask = 255;
476
477     new_proxy->set_APDU_log(get_APDU_log());
478     if (new_proxy->m_log_mask & PROXY_LOG_APDU_CLIENT)
479         new_proxy->set_APDU_yazlog(1);
480     else
481         new_proxy->set_APDU_yazlog(0);
482     strcpy(new_proxy->m_session_str, session_str);
483     new_proxy->m_peername = xstrdup(peername);
484     new_proxy->set_proxy_negotiation(m_proxy_negotiation_charset,
485         m_proxy_negotiation_lang, m_proxy_negotiation_default_charset);
486     // create thread object the first time we get an incoming connection
487     if (!m_my_thread)
488         m_my_thread = new Msg_Thread(m_socket_observable, 1);
489     new_proxy->m_my_thread = m_my_thread;
490     return new_proxy;
491 }
492
493 char *Yaz_Proxy::get_cookie(Z_OtherInformation **otherInfo)
494 {
495     int oid[OID_SIZE];
496     Z_OtherInformationUnit *oi;
497     struct oident ent;
498     ent.proto = PROTO_Z3950;
499     ent.oclass = CLASS_USERINFO;
500     ent.value = (oid_value) VAL_COOKIE;
501     assert (oid_ent_to_oid (&ent, oid));
502
503     if (oid_ent_to_oid (&ent, oid) &&
504         (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
505         oi->which == Z_OtherInfo_characterInfo)
506         return oi->information.characterInfo;
507     return 0;
508 }
509 char *Yaz_Proxy::get_proxy(Z_OtherInformation **otherInfo)
510 {
511     int oid[OID_SIZE];
512     Z_OtherInformationUnit *oi;
513     struct oident ent;
514     ent.proto = PROTO_Z3950;
515     ent.oclass = CLASS_USERINFO;
516     ent.value = (oid_value) VAL_PROXY;
517     if (oid_ent_to_oid (&ent, oid) &&
518         (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
519         oi->which == Z_OtherInfo_characterInfo)
520         return oi->information.characterInfo;
521     return 0;
522 }
523 const char *Yaz_Proxy::load_balance(const char **url)
524 {
525     int zurl_in_use[MAX_ZURL_PLEX];
526     int zurl_in_spare[MAX_ZURL_PLEX];
527     Yaz_ProxyClient *c;
528     int i;
529
530     for (i = 0; i<MAX_ZURL_PLEX; i++)
531     {
532         zurl_in_use[i] = 0;
533         zurl_in_spare[i] = 0;
534     }
535     for (c = m_parent->m_clientPool; c; c = c->m_next)
536     {
537         for (i = 0; url[i]; i++)
538             if (!strcmp(url[i], c->get_hostname()))
539             {
540                 zurl_in_use[i]++;
541                 if (c->m_cookie == 0 && c->m_server == 0 && c->m_waiting == 0)
542                     zurl_in_spare[i]++;
543             }
544     }
545     int min_use = 100000;
546     int spare_for_min = 0;
547     int max_spare = 0;
548     const char *ret_min = 0;
549     const char *ret_spare = 0;
550     for (i = 0; url[i]; i++)
551     {
552         yaz_log(YLOG_DEBUG, "%szurl=%s use=%d spare=%d",
553                 m_session_str, url[i], zurl_in_use[i], zurl_in_spare[i]);
554         if (min_use > zurl_in_use[i])
555         {
556             ret_min = url[i];
557             min_use = zurl_in_use[i];
558             spare_for_min = zurl_in_spare[i];
559         }
560         if (max_spare < zurl_in_spare[i])
561         {
562             ret_spare = url[i];
563             max_spare = zurl_in_spare[i];
564         }
565     }
566     return ret_min;
567 }
568
569 Yaz_ProxyClient *Yaz_Proxy::get_client(Z_APDU *apdu, const char *cookie,
570                                        const char *proxy_host)
571 {
572     assert (m_parent);
573     Yaz_Proxy *parent = m_parent;
574     Yaz_ProxyClient *c = m_client;
575
576     if (!m_proxyTarget)
577     {
578         const char *url[MAX_ZURL_PLEX];
579         Yaz_ProxyConfig *cfg = check_reconfigure();
580         if (proxy_host)
581         {
582             if (parent && parent->m_debug_mode)
583             {
584                 // only to be enabled for debugging...
585                 if (!strcmp(proxy_host, "stop"))
586                     exit(0);
587             }
588             xfree(m_default_target);
589             m_default_target = xstrdup(proxy_host);
590         }
591         proxy_host = m_default_target;
592         int client_idletime = -1;
593         const char *cql2rpn_fname = 0;
594         const char *negotiation_charset = 0;
595         const char *negotiation_lang = 0;
596         const char *query_charset = 0;
597         const char *default_client_query_charset = 0;
598         url[0] = m_default_target;
599         url[1] = 0;
600         if (cfg)
601         {
602             int pre_init = 0;
603             cfg->get_target_info(proxy_host, url, &m_bw_max,
604                                  &m_pdu_max, &m_max_record_retrieve,
605                                  &m_search_max,
606                                  &m_target_idletime, &client_idletime,
607                                  &parent->m_max_clients,
608                                  &m_keepalive_limit_bw,
609                                  &m_keepalive_limit_pdu,
610                                  &pre_init,
611                                  &cql2rpn_fname,
612                                  &negotiation_charset,
613                                  &negotiation_lang,
614                                  &query_charset,
615                                  &default_client_query_charset);
616         }
617         if (client_idletime != -1)
618         {
619             m_client_idletime = client_idletime;
620             timeout(m_client_idletime);
621         }
622         if (cql2rpn_fname)
623             m_cql2rpn.set_pqf_file(cql2rpn_fname);
624         if (negotiation_charset || negotiation_lang || default_client_query_charset)
625         {
626             set_proxy_negotiation(negotiation_charset,
627                 negotiation_lang, default_client_query_charset);
628         }
629         m_charset_converter->set_target_query_charset(query_charset);
630         if (!url[0])
631         {
632             yaz_log(YLOG_LOG, "%sNo default target", m_session_str);
633             return 0;
634         }
635         // we don't handle multiplexing for cookie session, so we just
636         // pick the first one in this case (anonymous users will be able
637         // to use any backend)
638         if (cookie && *cookie)
639             m_proxyTarget = (char*) xstrdup(url[0]);
640         else
641             m_proxyTarget = (char*) xstrdup(load_balance(url));
642     }
643     if (cookie && *cookie)
644     {   // search in sessions with a cookie
645         for (c = parent->m_clientPool; c; c = c->m_next)
646         {
647             assert (c->m_prev);
648             assert (*c->m_prev == c);
649             if (c->m_cookie && !strcmp(cookie,c->m_cookie) &&
650                 !strcmp(m_proxyTarget, c->get_hostname()))
651             {
652                 // Found it in cache
653                 // The following handles "cancel"
654                 // If connection is busy (waiting for PDU) and
655                 // we have an initRequest we can safely do re-open
656                 if (c->m_waiting && apdu->which == Z_APDU_initRequest)
657                 {
658                     yaz_log (YLOG_LOG, "%s REOPEN target=%s", m_session_str,
659                              c->get_hostname());
660                     c->close();
661                     c->m_init_flag = 0;
662
663                     c->m_last_ok = 0;
664                     c->m_cache.clear();
665                     c->m_last_resultCount = 0;
666                     c->m_sr_transform = 0;
667                     c->m_waiting = 0;
668                     c->m_resultSetStartPoint = 0;
669                     c->m_target_idletime = m_target_idletime;
670                     if (c->client(m_proxyTarget))
671                     {
672                         delete c;
673                         return 0;
674                     }
675                     c->timeout(30);
676                 }
677                 c->m_seqno = parent->m_seqno;
678                 if (c->m_server && c->m_server != this)
679                     c->m_server->m_client = 0;
680                 c->m_server = this;
681                 (parent->m_seqno)++;
682                 yaz_log (YLOG_DEBUG, "get_client 1 %p %p", this, c);
683                 return c;
684             }
685         }
686     }
687     else if (!c && apdu->which == Z_APDU_initRequest )
688     {
689         // anonymous sessions without cookie.
690         // if authentication is set it is NOT anonymous se we can't share them.
691         // If charset and lang negotiation is use it is NOT anonymous session too.
692         for (c = parent->m_clientPool; c; c = c->m_next)
693         {
694             assert(c->m_prev);
695             assert(*c->m_prev == c);
696             if (c->m_server == 0 && c->m_cookie == 0 &&  c->m_waiting == 0 
697                 && c->compare_idAuthentication(apdu)
698                 && c->compare_charset(apdu)
699                 && !strcmp(m_proxyTarget, c->get_hostname()))
700             {
701                 // found it in cache
702                 yaz_log (YLOG_LOG, "%sREUSE %d %s",
703                          m_session_str, parent->m_seqno, c->get_hostname());
704                 
705                 c->m_seqno = parent->m_seqno;
706                 assert(c->m_server == 0);
707                 c->m_server = this;
708
709                 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
710                     c->set_APDU_yazlog(1);
711                 else
712                     c->set_APDU_yazlog(0);
713
714                 (parent->m_seqno)++;
715
716                 parent->pre_init();
717
718                 return c;
719             }
720         }
721     }
722     if (!m_client)
723     {
724         if (apdu->which != Z_APDU_initRequest)
725         {
726             yaz_log (YLOG_LOG, "%sno init request as first PDU", m_session_str);
727             return 0;
728         }
729         // go through list of clients - and find the lowest/oldest one.
730         Yaz_ProxyClient *c_min = 0;
731         int min_seq = -1;
732         int no_of_clients = 0;
733         if (parent->m_clientPool)
734             yaz_log (YLOG_DEBUG, "Existing sessions");
735         for (c = parent->m_clientPool; c; c = c->m_next)
736         {
737             yaz_log (YLOG_DEBUG, " Session %-3d wait=%d %s cookie=%s", c->m_seqno,
738                                c->m_waiting, c->get_hostname(),
739                                c->m_cookie ? c->m_cookie : "");
740             no_of_clients++;
741             if (min_seq < 0 || c->m_seqno < min_seq)
742             {
743                 min_seq = c->m_seqno;
744                 c_min = c;
745             }
746         }
747         if (no_of_clients >= parent->m_max_clients)
748         {
749             c = c_min;
750             if (c->m_waiting || strcmp(m_proxyTarget, c->get_hostname()))
751             {
752                 yaz_log (YLOG_LOG, "%sMAXCLIENTS %d Destroy %d",
753                          m_session_str, parent->m_max_clients, c->m_seqno);
754                 if (c->m_server && c->m_server != this)
755                     c->m_server->dec_ref(true);
756             }
757             else
758             {
759                 yaz_log (YLOG_LOG, "%sMAXCLIENTS %d Reuse %d %d %s",
760                          m_session_str, parent->m_max_clients,
761                          c->m_seqno, parent->m_seqno, c->get_hostname());
762                 xfree (c->m_cookie);
763                 c->m_cookie = 0;
764                 if (cookie)
765                     c->m_cookie = xstrdup(cookie);
766                 c->m_seqno = parent->m_seqno;
767                 if (c->m_server && c->m_server != this)
768                 {
769                     c->m_server->m_client = 0;
770                     c->m_server->dec_ref(true);
771                 }
772                 (parent->m_seqno)++;
773                 c->m_target_idletime = m_target_idletime;
774                 c->timeout(m_target_idletime);
775
776                 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
777                     c->set_APDU_yazlog(1);
778                 else
779                     c->set_APDU_yazlog(0);
780
781                 return c;
782             }
783         }
784         else
785         {
786             yaz_log (YLOG_LOG, "%sNEW %d %s",
787                      m_session_str, parent->m_seqno, m_proxyTarget);
788             c = new Yaz_ProxyClient(m_PDU_Observable->clone(), parent);
789             c->m_next = parent->m_clientPool;
790             if (c->m_next)
791                 c->m_next->m_prev = &c->m_next;
792             parent->m_clientPool = c;
793             c->m_prev = &parent->m_clientPool;
794         }
795
796         xfree (c->m_cookie);
797         c->m_cookie = 0;
798         if (cookie)
799             c->m_cookie = xstrdup(cookie);
800
801         c->m_seqno = parent->m_seqno;
802         c->m_init_flag = 0;
803         c->m_last_resultCount = 0;
804         c->m_last_ok = 0;
805         c->m_cache.clear();
806         c->m_sr_transform = 0;
807         c->m_waiting = 0;
808         c->m_resultSetStartPoint = 0;
809         (parent->m_seqno)++;
810         if (c->client(m_proxyTarget))
811         {
812             delete c;
813             return 0;
814         }
815         c->m_target_idletime = m_target_idletime;
816         c->timeout(30);
817
818         if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
819             c->set_APDU_yazlog(1);
820         else
821             c->set_APDU_yazlog(0);
822
823         c->set_idAuthentication(apdu);
824     }
825     yaz_log (YLOG_DEBUG, "get_client 3 %p %p", this, c);
826     return c;
827 }
828
829 void Yaz_Proxy::display_diagrecs(Z_DiagRec **pp, int num)
830 {
831     int i;
832     for (i = 0; i<num; i++)
833     {
834         oident *ent;
835         Z_DefaultDiagFormat *r;
836         Z_DiagRec *p = pp[i];
837         if (p->which != Z_DiagRec_defaultFormat)
838         {
839             yaz_log(YLOG_LOG, "%sError no diagnostics", m_session_str);
840             return;
841         }
842         else
843             r = p->u.defaultFormat;
844         if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
845             ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
846             yaz_log(YLOG_LOG, "%sError unknown diagnostic set", m_session_str);
847         switch (r->which)
848         {
849         case Z_DefaultDiagFormat_v2Addinfo:
850             yaz_log(YLOG_LOG, "%sError %d %s:%s",
851                     m_session_str,
852                     *r->condition, diagbib1_str(*r->condition),
853                     r->u.v2Addinfo);
854             break;
855         case Z_DefaultDiagFormat_v3Addinfo:
856             yaz_log(YLOG_LOG, "%sError %d %s:%s",
857                     m_session_str,
858                     *r->condition, diagbib1_str(*r->condition),
859                     r->u.v3Addinfo);
860             break;
861         }
862     }
863 }
864
865 int Yaz_Proxy::convert_xsl(Z_NamePlusRecordList *p, Z_APDU *apdu)
866 {
867     if (!m_stylesheet_xsp || p->num_records <= 0)
868     {
869         return 0;  /* no XSLT to be done ... */
870     }
871
872     m_stylesheet_offset = 0;
873     m_stylesheet_nprl = p;
874     m_stylesheet_apdu = apdu;
875     m_timeout_mode = timeout_xsl;
876
877     timeout(0);
878     return 1;
879 }
880
881 void Yaz_Proxy::convert_xsl_delay()
882 {
883 #if HAVE_XSLT
884     Z_NamePlusRecord *npr = m_stylesheet_nprl->records[m_stylesheet_offset];
885     if (npr->which == Z_NamePlusRecord_databaseRecord)
886     {
887         Z_External *r = npr->u.databaseRecord;
888         if (r->which == Z_External_octet)
889         {
890 #if 0
891             fwrite((char*) r->u.octet_aligned->buf, 1, r->u.octet_aligned->len, stdout);
892 #endif
893             xmlDocPtr res, doc = xmlParseMemory(
894                 (char*) r->u.octet_aligned->buf,
895                 r->u.octet_aligned->len);
896
897
898             yaz_log(YLOG_LOG, "%sXSLT convert %d",
899                     m_session_str, m_stylesheet_offset);
900             res = xsltApplyStylesheet((xsltStylesheetPtr) m_stylesheet_xsp,
901                                       doc, 0);
902
903             if (res)
904             {
905                 xmlChar *out_buf;
906                 int out_len;
907                 xmlDocDumpFormatMemory (res, &out_buf, &out_len, 1);
908
909                 m_stylesheet_nprl->records[m_stylesheet_offset]->
910                     u.databaseRecord =
911                     z_ext_record(odr_encode(), VAL_TEXT_XML,
912                                  (char*) out_buf, out_len);
913                 xmlFree(out_buf);
914                 xmlFreeDoc(res);
915             }
916
917             xmlFreeDoc(doc);
918         }
919     }
920 #endif
921     m_stylesheet_offset++;
922     if (m_stylesheet_offset == m_stylesheet_nprl->num_records)
923     {
924         m_timeout_mode = timeout_normal;
925         m_stylesheet_nprl = 0;
926 #if HAVE_XSLT
927         if (m_stylesheet_xsp)
928             xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
929 #endif
930         m_stylesheet_xsp = 0;
931         timeout(m_client_idletime);
932         send_PDU_convert(m_stylesheet_apdu);
933     }
934     else
935         timeout(0);
936 }
937
938 void Yaz_Proxy::convert_to_frontend_type(Z_NamePlusRecordList *p)
939 {
940     if (m_frontend_type != VAL_NONE)
941     {
942         int i;
943         for (i = 0; i < p->num_records; i++)
944         {
945             Z_NamePlusRecord *npr = p->records[i];
946             if (npr->which == Z_NamePlusRecord_databaseRecord)
947             {
948                 Z_External *r = npr->u.databaseRecord;
949                 if (r->which == Z_External_octet)
950                 {
951 #if HAVE_USEMARCON
952                     if (m_usemarcon_ini_stage1 && *m_usemarcon_ini_stage1)
953                     {
954                         if (!m_usemarcon->m_stage1)
955                         {
956                             m_usemarcon->m_stage1 = new CDetails();
957                         }
958                         m_usemarcon->m_stage1->SetIniFileName(m_usemarcon_ini_stage1);
959                         m_usemarcon->m_stage1->SetMarcRecord((char*) r->u.octet_aligned->buf, r->u.octet_aligned->len);
960                         int res = m_usemarcon->m_stage1->Start();
961                         if (res == 0)
962                         {
963                             char *converted;
964                             int convlen;
965                             m_usemarcon->m_stage1->GetMarcRecord(converted, convlen);
966                             if (m_usemarcon_ini_stage2 && *m_usemarcon_ini_stage2)
967                             {
968                                 if (!m_usemarcon->m_stage2)
969                                 {
970                                     m_usemarcon->m_stage2 = new CDetails();
971                                 }
972                                 m_usemarcon->m_stage2->SetIniFileName(m_usemarcon_ini_stage2);
973                                 m_usemarcon->m_stage2->SetMarcRecord(converted, convlen);
974                                 res = m_usemarcon->m_stage2->Start();
975                                 if (res == 0)
976                                 {
977                                     free(converted);
978                                     m_usemarcon->m_stage2->GetMarcRecord(converted, convlen);
979                                 }
980                                 else
981                                 {
982                                     yaz_log(YLOG_LOG, "%sUSEMARCON stage 2 error %d", m_session_str, res);
983                                 }
984                             }
985                             npr->u.databaseRecord =
986                                 z_ext_record(odr_encode(),
987                                              m_frontend_type,
988                                              converted,
989                                              strlen(converted));
990                             free(converted);
991                         }
992                         else
993                         {
994                             yaz_log(YLOG_LOG, "%sUSEMARCON stage 1 error %d", m_session_str, res);
995                         }
996                         continue;
997                     }
998 #endif
999 /* HAVE_USEMARCON */
1000                     npr->u.databaseRecord =
1001                         z_ext_record(odr_encode(),
1002                                      m_frontend_type,
1003                                      (char*) r->u.octet_aligned->buf,
1004                                      r->u.octet_aligned->len);
1005                 }
1006             }
1007         }
1008     }
1009 }
1010
1011 void Yaz_Proxy::convert_records_charset(Z_NamePlusRecordList *p,
1012                                         const char *backend_charset)
1013 {
1014     int sel =   m_charset_converter->get_client_charset_selected();
1015     const char *client_record_charset =
1016         m_charset_converter->get_client_query_charset();
1017     if (sel && backend_charset && client_record_charset &&
1018         strcmp(backend_charset, client_record_charset))
1019     {
1020         int i;
1021         yaz_iconv_t cd = yaz_iconv_open(client_record_charset,
1022                                         backend_charset);
1023         yaz_marc_t mt = yaz_marc_create();
1024         yaz_marc_xml(mt, YAZ_MARC_ISO2709);
1025         yaz_marc_iconv(mt, cd);
1026         for (i = 0; i < p->num_records; i++)
1027         {
1028             Z_NamePlusRecord *npr = p->records[i];
1029             if (npr->which == Z_NamePlusRecord_databaseRecord)
1030             {
1031                 Z_External *r = npr->u.databaseRecord;
1032                 oident *ent = oid_getentbyoid(r->direct_reference);
1033                 if (!ent || ent->value == VAL_NONE)
1034                     continue;
1035
1036                 if (ent->value == VAL_SUTRS)
1037                 {
1038                     WRBUF w = wrbuf_alloc();
1039
1040                     wrbuf_iconv_write(w, cd,  (char*) r->u.octet_aligned->buf,
1041                                       r->u.octet_aligned->len);
1042                     npr->u.databaseRecord =
1043                         z_ext_record(odr_encode(), ent->value, wrbuf_buf(w),
1044                                      wrbuf_len(w));
1045                     wrbuf_free(w, 1);
1046                 }
1047                 else if (ent->value == VAL_TEXT_XML)
1048                 {
1049                     ;
1050                 }
1051                 else if (r->which == Z_External_octet)
1052                 {
1053                     int rlen;
1054                     char *result;
1055                     if (yaz_marc_decode_buf(mt,
1056                                             (char*) r->u.octet_aligned->buf,
1057                                             r->u.octet_aligned->len,
1058                                             &result, &rlen))
1059                     {
1060                         npr->u.databaseRecord =
1061                             z_ext_record(odr_encode(), ent->value, result, rlen);
1062                         yaz_log(YLOG_LOG, "%sRecoding MARC record",
1063                                 m_session_str);
1064                     }
1065                 }
1066             }
1067         }
1068         if (cd)
1069             yaz_iconv_close(cd);
1070         yaz_marc_destroy(mt);
1071     }
1072 }
1073
1074 void Yaz_Proxy::convert_to_marcxml(Z_NamePlusRecordList *p,
1075                                    const char *backend_charset)
1076 {
1077     int i;
1078     if (!backend_charset)
1079         backend_charset = "MARC-8";
1080     yaz_iconv_t cd = yaz_iconv_open("UTF-8", backend_charset);
1081     yaz_marc_t mt = yaz_marc_create();
1082     yaz_marc_xml(mt, YAZ_MARC_MARCXML);
1083     yaz_marc_iconv(mt, cd);
1084     for (i = 0; i < p->num_records; i++)
1085     {
1086         Z_NamePlusRecord *npr = p->records[i];
1087         if (npr->which == Z_NamePlusRecord_databaseRecord)
1088         {
1089             Z_External *r = npr->u.databaseRecord;
1090             if (r->which == Z_External_OPAC)
1091             {
1092                 WRBUF w = wrbuf_alloc();
1093
1094                 yaz_opac_decode_wrbuf(mt, r->u.opac, w);
1095                 npr->u.databaseRecord = z_ext_record(
1096                     odr_encode(), VAL_TEXT_XML,
1097                     wrbuf_buf(w), wrbuf_len(w)
1098                     );
1099                 wrbuf_free(w, 1);
1100             }
1101             else if (r->which == Z_External_octet)
1102             {
1103                 int rlen;
1104                 char *result;
1105                 if (yaz_marc_decode_buf(mt, (char*) r->u.octet_aligned->buf,
1106                                         r->u.octet_aligned->len,
1107                                         &result, &rlen))
1108                 {
1109                     npr->u.databaseRecord =
1110                         z_ext_record(odr_encode(), VAL_TEXT_XML, result, rlen);
1111                 }
1112             }
1113         }
1114     }
1115     if (cd)
1116         yaz_iconv_close(cd);
1117     yaz_marc_destroy(mt);
1118 }
1119
1120 void Yaz_Proxy::logtime()
1121 {
1122 #if HAVE_GETTIMEOFDAY
1123     struct timeval *tv = (struct timeval*) m_time_tv;
1124     if (tv->tv_sec)
1125     {
1126         struct timeval tv1;
1127         gettimeofday(&tv1, 0);
1128         long diff = (tv1.tv_sec - tv->tv_sec)*1000000 +
1129             (tv1.tv_usec - tv->tv_usec);
1130         if (diff >= 0)
1131             yaz_log(YLOG_LOG, "%sElapsed %ld.%03ld", m_session_str,
1132                     diff/1000000, (diff/1000)%1000);
1133     }
1134     tv->tv_sec = 0;
1135     tv->tv_usec = 0;
1136 #endif
1137 }
1138
1139 int Yaz_Proxy::send_http_response(int code)
1140 {
1141     ODR o = odr_encode();
1142     Z_GDU *gdu = z_get_HTTP_Response(o, code);
1143     Z_HTTP_Response *hres = gdu->u.HTTP_Response;
1144     if (m_http_version)
1145         hres->version = odr_strdup(o, m_http_version);
1146     if (m_http_keepalive)
1147         z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1148     else
1149         timeout(0);
1150
1151     if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1152     {
1153         yaz_log (YLOG_LOG, "%sSending %s to client", m_session_str,
1154                  gdu_name(gdu));
1155     }
1156     int len;
1157     int r = send_GDU(gdu, &len);
1158     m_bytes_sent += len;
1159     m_bw_stat.add_bytes(len);
1160     logtime();
1161
1162     recv_GDU_more(true);
1163
1164     return r;
1165 }
1166
1167 int Yaz_Proxy::send_srw_response(Z_SRW_PDU *srw_pdu, int http_code /* = 200 */)
1168 {
1169     ODR o = odr_encode();
1170     const char *ctype = "text/xml";
1171     Z_GDU *gdu = z_get_HTTP_Response(o, http_code);
1172     Z_HTTP_Response *hres = gdu->u.HTTP_Response;
1173     if (m_http_version)
1174         hres->version = odr_strdup(o, m_http_version);
1175     z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1176     if (m_http_keepalive)
1177         z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1178     else
1179         timeout(0);
1180     if (http_code == 401)
1181         z_HTTP_header_add(o, &hres->headers, "WWW-Authenticate", "Basic realm=\"YAZ Proxy\"");
1182
1183     static Z_SOAP_Handler soap_handlers[2] = {
1184 #if HAVE_XSLT
1185         {"http://www.loc.gov/zing/srw/", 0,
1186          (Z_SOAP_fun) yaz_srw_codec},
1187 #endif
1188         {0, 0, 0}
1189     };
1190
1191     Z_SOAP *soap_package = (Z_SOAP*) odr_malloc(o, sizeof(Z_SOAP));
1192     soap_package->which = Z_SOAP_generic;
1193     soap_package->u.generic =
1194         (Z_SOAP_Generic *) odr_malloc(o,  sizeof(*soap_package->u.generic));
1195     soap_package->u.generic->no = 0;
1196     soap_package->u.generic->ns = soap_handlers[0].ns;
1197     soap_package->u.generic->p = (void *) srw_pdu;
1198     soap_package->ns = m_soap_ns;
1199     z_soap_codec_enc_xsl(o, &soap_package,
1200                          &hres->content_buf, &hres->content_len,
1201                          soap_handlers, 0, m_s2z_stylesheet);
1202     if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1203     {
1204         yaz_log (YLOG_LOG, "%sSending %s to client", m_session_str,
1205                  gdu_name(gdu));
1206     }
1207     int len;
1208     int r = send_GDU(gdu, &len);
1209     m_bytes_sent += len;
1210     m_bw_stat.add_bytes(len);
1211     logtime();
1212
1213     recv_GDU_more(true);
1214
1215     return r;
1216 }
1217
1218 int Yaz_Proxy::send_to_srw_client_error(int srw_error, const char *add)
1219 {
1220     ODR o = odr_encode();
1221     Z_SRW_diagnostic *diagnostic = (Z_SRW_diagnostic *)
1222         odr_malloc(o, sizeof(*diagnostic));
1223     int num_diagnostic = 1;
1224     yaz_mk_std_diagnostic(o, diagnostic, srw_error, add);
1225     return send_srw_search_response(diagnostic, num_diagnostic, srw_error == 3 ? 401 : 200);
1226 }
1227
1228 int Yaz_Proxy::z_to_srw_diag(ODR o, Z_SRW_searchRetrieveResponse *srw_res,
1229                              Z_DefaultDiagFormat *ddf)
1230 {
1231     int bib1_code = *ddf->condition;
1232     if (bib1_code == 109)
1233         return 404;
1234     srw_res->num_diagnostics = 1;
1235     srw_res->diagnostics = (Z_SRW_diagnostic *)
1236         odr_malloc(o, sizeof(*srw_res->diagnostics));
1237     yaz_mk_std_diagnostic(o, srw_res->diagnostics,
1238                           yaz_diag_bib1_to_srw(*ddf->condition),
1239                           ddf->u.v2Addinfo);
1240     return 0;
1241 }
1242
1243 int Yaz_Proxy::send_to_srw_client_ok(int hits, Z_Records *records, int start)
1244 {
1245     ODR o = odr_encode();
1246     Z_SRW_PDU *srw_pdu = yaz_srw_get(o, Z_SRW_searchRetrieve_response);
1247     Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
1248
1249     srw_res->numberOfRecords = odr_intdup (o, hits);
1250     if (records && records->which == Z_Records_DBOSD)
1251     {
1252         srw_res->num_records =
1253             records->u.databaseOrSurDiagnostics->num_records;
1254         int i;
1255         srw_res->records = (Z_SRW_record *)
1256             odr_malloc(o, srw_res->num_records * sizeof(Z_SRW_record));
1257         for (i = 0; i < srw_res->num_records; i++)
1258         {
1259             Z_NamePlusRecord *npr = records->u.databaseOrSurDiagnostics->records[i];
1260             if (npr->which != Z_NamePlusRecord_databaseRecord)
1261             {
1262                 srw_res->records[i].recordSchema = "diagnostic";
1263                 srw_res->records[i].recordPacking = m_s2z_packing;
1264                 srw_res->records[i].recordData_buf = "67";
1265                 srw_res->records[i].recordData_len = 2;
1266                 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
1267                 continue;
1268             }
1269             Z_External *r = npr->u.databaseRecord;
1270             oident *ent = oid_getentbyoid(r->direct_reference);
1271             if (r->which == Z_External_octet && ent->value == VAL_TEXT_XML)
1272             {
1273                 srw_res->records[i].recordSchema = m_schema;
1274                 srw_res->records[i].recordPacking = m_s2z_packing;
1275                 srw_res->records[i].recordData_buf = (char*)
1276                     r->u.octet_aligned->buf;
1277                 srw_res->records[i].recordData_len = r->u.octet_aligned->len;
1278                 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
1279             }
1280             else
1281             {
1282                 srw_res->records[i].recordSchema = "diagnostic";
1283                 srw_res->records[i].recordPacking = m_s2z_packing;
1284                 srw_res->records[i].recordData_buf = "67";
1285                 srw_res->records[i].recordData_len = 2;
1286                 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
1287             }
1288         }
1289     }
1290     if (records && records->which == Z_Records_NSD)
1291     {
1292         int http_code;
1293         http_code = z_to_srw_diag(odr_encode(), srw_res,
1294                                    records->u.nonSurrogateDiagnostic);
1295         if (http_code)
1296             return send_http_response(http_code);
1297     }
1298     return send_srw_response(srw_pdu);
1299
1300 }
1301
1302 int Yaz_Proxy::send_srw_search_response(Z_SRW_diagnostic *diagnostics,
1303                                         int num_diagnostics, int http_code /* = 200 */)
1304 {
1305     ODR o = odr_encode();
1306     Z_SRW_PDU *srw_pdu = yaz_srw_get(o, Z_SRW_searchRetrieve_response);
1307     Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
1308
1309     srw_res->num_diagnostics = num_diagnostics;
1310     srw_res->diagnostics = diagnostics;
1311     return send_srw_response(srw_pdu, http_code);
1312 }
1313
1314 int Yaz_Proxy::send_srw_explain_response(Z_SRW_diagnostic *diagnostics,
1315                                         int num_diagnostics)
1316 {
1317     Yaz_ProxyConfig *cfg = check_reconfigure();
1318     if (cfg)
1319     {
1320         int len;
1321         char *b = cfg->get_explain_doc(odr_encode(), 0 /* target */,
1322                                        m_s2z_database, &len);
1323         if (b)
1324         {
1325             Z_SRW_PDU *res = yaz_srw_get(odr_encode(), Z_SRW_explain_response);
1326             Z_SRW_explainResponse *er = res->u.explain_response;
1327
1328             er->record.recordData_buf = b;
1329             er->record.recordData_len = len;
1330             er->record.recordPacking = m_s2z_packing;
1331             er->record.recordSchema = "http://explain.z3950.org/dtd/2.0/";
1332
1333             er->diagnostics = diagnostics;
1334             er->num_diagnostics = num_diagnostics;
1335             return send_srw_response(res);
1336         }
1337     }
1338     return send_http_response(404);
1339 }
1340
1341 int Yaz_Proxy::send_PDU_convert(Z_APDU *apdu)
1342 {
1343     if (m_http_version)
1344     {
1345         if (apdu->which == Z_APDU_initResponse)
1346         {
1347             Z_InitResponse *res = apdu->u.initResponse;
1348             if (*res->result == 0)
1349             {
1350                 send_to_srw_client_error(3, 0);
1351             }
1352             else if (!m_s2z_search_apdu)
1353             {
1354                 send_srw_explain_response(0, 0);
1355             }
1356             else
1357             {
1358                 handle_incoming_Z_PDU(m_s2z_search_apdu);
1359             }
1360         }
1361         else if (m_s2z_search_apdu && apdu->which == Z_APDU_searchResponse)
1362         {
1363             m_s2z_search_apdu = 0;
1364             Z_SearchResponse *res = apdu->u.searchResponse;
1365             m_s2z_hit_count = *res->resultCount;
1366             if (res->records && res->records->which == Z_Records_NSD)
1367             {
1368                 send_to_srw_client_ok(0, res->records, 1);
1369             }
1370             else if (m_s2z_present_apdu && m_s2z_hit_count > 0)
1371             {
1372                 // adjust
1373                 Z_PresentRequest *pr = m_s2z_present_apdu->u.presentRequest;
1374
1375                 if (*pr->resultSetStartPoint <= m_s2z_hit_count)
1376                 {
1377                     if (*pr->numberOfRecordsRequested+ *pr->resultSetStartPoint
1378                         > m_s2z_hit_count)
1379                         *pr->numberOfRecordsRequested =
1380                             1 + m_s2z_hit_count - *pr->resultSetStartPoint;
1381                 }
1382                 handle_incoming_Z_PDU(m_s2z_present_apdu);
1383             }
1384             else
1385             {
1386                 m_s2z_present_apdu = 0;
1387                 send_to_srw_client_ok(m_s2z_hit_count, res->records, 1);
1388             }
1389         }
1390         else if (m_s2z_present_apdu && apdu->which == Z_APDU_presentResponse)
1391         {
1392             int start =
1393                 *m_s2z_present_apdu->u.presentRequest->resultSetStartPoint;
1394
1395             m_s2z_present_apdu = 0;
1396             Z_PresentResponse *res = apdu->u.presentResponse;
1397             send_to_srw_client_ok(m_s2z_hit_count, res->records, start);
1398         }
1399     }
1400     else
1401     {
1402         int len = 0;
1403         if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1404             yaz_log (YLOG_LOG, "%sSending %s to client", m_session_str,
1405                      apdu_name(apdu));
1406         int r = send_Z_PDU(apdu, &len);
1407         m_bytes_sent += len;
1408         m_bw_stat.add_bytes(len);
1409         logtime();
1410         return r;
1411     }
1412     return 0;
1413 }
1414
1415 int Yaz_Proxy::send_to_client(Z_APDU *apdu)
1416 {
1417     int kill_session = 0;
1418     Z_ReferenceId **new_id = get_referenceIdP(apdu);
1419
1420     if (new_id)
1421         *new_id = m_referenceId;
1422
1423     if (apdu->which == Z_APDU_searchResponse)
1424     {
1425         Z_SearchResponse *sr = apdu->u.searchResponse;
1426         Z_Records *p = sr->records;
1427         if (p && p->which == Z_Records_NSD)
1428         {
1429             Z_DiagRec dr, *dr_p = &dr;
1430             dr.which = Z_DiagRec_defaultFormat;
1431             dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1432
1433             *sr->searchStatus = 0;
1434             display_diagrecs(&dr_p, 1);
1435         }
1436         else
1437         {
1438             if (p && p->which == Z_Records_DBOSD)
1439             {
1440                 if (m_backend_type
1441 #if HAVE_USEMARCON
1442                     || m_usemarcon_ini_stage1 || m_usemarcon_ini_stage2
1443 #endif
1444                     )
1445                     convert_to_frontend_type(p->u.databaseOrSurDiagnostics);
1446                 if (m_marcxml_mode == marcxml)
1447                     convert_to_marcxml(p->u.databaseOrSurDiagnostics,
1448                                        m_backend_charset);
1449                 else
1450                     convert_records_charset(p->u.databaseOrSurDiagnostics,
1451                                             m_backend_charset);
1452                 if (convert_xsl(p->u.databaseOrSurDiagnostics, apdu))
1453                     return 0;
1454
1455             }
1456             if (sr->resultCount)
1457             {
1458                 yaz_log(YLOG_LOG, "%s%d hits", m_session_str,
1459                         *sr->resultCount);
1460                 if (*sr->resultCount < 0)
1461                 {
1462                     m_flag_invalid_session = 1;
1463                     kill_session = 1;
1464
1465                     *sr->searchStatus = 0;
1466                     sr->records =
1467                         create_nonSurrogateDiagnostics(odr_encode(), 2, 0);
1468                     *sr->resultCount = 0;
1469                 }
1470             }
1471         }
1472     }
1473     else if (apdu->which == Z_APDU_presentResponse)
1474     {
1475         Z_PresentResponse *sr = apdu->u.presentResponse;
1476         Z_Records *p = sr->records;
1477         if (p && p->which == Z_Records_NSD)
1478         {
1479             Z_DiagRec dr, *dr_p = &dr;
1480             dr.which = Z_DiagRec_defaultFormat;
1481             dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1482             if (*sr->presentStatus == Z_PresentStatus_success)
1483                 *sr->presentStatus = Z_PresentStatus_failure;
1484             display_diagrecs(&dr_p, 1);
1485         }
1486         if (p && p->which == Z_Records_DBOSD)
1487         {
1488             if (m_backend_type
1489 #if HAVE_USEMARCON
1490                 || m_usemarcon_ini_stage1 || m_usemarcon_ini_stage2
1491 #endif
1492                 )
1493                 convert_to_frontend_type(p->u.databaseOrSurDiagnostics);
1494             if (m_marcxml_mode == marcxml)
1495                 convert_to_marcxml(p->u.databaseOrSurDiagnostics,
1496                                    m_backend_charset);
1497             else
1498                 convert_records_charset(p->u.databaseOrSurDiagnostics,
1499                                         m_backend_charset);
1500             if (convert_xsl(p->u.databaseOrSurDiagnostics, apdu))
1501                 return 0;
1502         }
1503     }
1504     else if (apdu->which == Z_APDU_initResponse)
1505     {
1506         //Get and check negotiation record
1507         //from init response.
1508         handle_charset_lang_negotiation(apdu);
1509
1510         if (m_initRequest_options)
1511         {
1512             Z_Options *nopt =
1513                 (Odr_bitmask *)odr_malloc(odr_encode(),
1514                                           sizeof(Odr_bitmask));
1515             ODR_MASK_ZERO(nopt);
1516
1517             int i;
1518             for (i = 0; i<24; i++)
1519                 if (ODR_MASK_GET(m_initRequest_options, i) &&
1520                     ODR_MASK_GET(apdu->u.initResponse->options, i))
1521                     ODR_MASK_SET(nopt, i);
1522             apdu->u.initResponse->options = nopt;
1523         }
1524         if (m_initRequest_version)
1525         {
1526             Z_ProtocolVersion *nopt =
1527                 (Odr_bitmask *)odr_malloc(odr_encode(),
1528                                           sizeof(Odr_bitmask));
1529             ODR_MASK_ZERO(nopt);
1530
1531             int i;
1532             for (i = 0; i<8; i++)
1533                 if (ODR_MASK_GET(m_initRequest_version, i) &&
1534                     ODR_MASK_GET(apdu->u.initResponse->protocolVersion, i))
1535                     ODR_MASK_SET(nopt, i);
1536             apdu->u.initResponse->protocolVersion = nopt;
1537         }
1538         apdu->u.initResponse->preferredMessageSize =
1539             odr_intdup(odr_encode(),
1540                        m_client->m_initResponse_preferredMessageSize >
1541                        m_initRequest_preferredMessageSize ?
1542                        m_initRequest_preferredMessageSize :
1543                        m_client->m_initResponse_preferredMessageSize);
1544         apdu->u.initResponse->maximumRecordSize =
1545             odr_intdup(odr_encode(),
1546                        m_client->m_initResponse_maximumRecordSize >
1547                        m_initRequest_maximumRecordSize ?
1548                        m_initRequest_maximumRecordSize :
1549                        m_client->m_initResponse_maximumRecordSize);
1550     }
1551
1552     int r = send_PDU_convert(apdu);
1553     if (r)
1554         return r;
1555     if (kill_session)
1556     {
1557         delete m_client;
1558         m_client = 0;
1559         m_parent->pre_init();
1560     }
1561     return r;
1562 }
1563
1564 void Yaz_ProxyClient::set_idAuthentication(Z_APDU *apdu)
1565 {
1566     Z_IdAuthentication *t = apdu->u.initRequest->idAuthentication;
1567     
1568     odr_reset(m_idAuthentication_odr);
1569     z_IdAuthentication(m_idAuthentication_odr, &t, 1, 0);
1570     m_idAuthentication_ber_buf =
1571         odr_getbuf(m_idAuthentication_odr, 
1572                    &m_idAuthentication_ber_size, 0);
1573 }
1574
1575 bool Yaz_ProxyClient::compare_charset(Z_APDU *apdu)
1576 {
1577     return true;
1578 }
1579
1580 bool Yaz_ProxyClient::compare_idAuthentication(Z_APDU *apdu)
1581 {
1582     Z_IdAuthentication *t = apdu->u.initRequest->idAuthentication;
1583     ODR odr = odr_createmem(ODR_ENCODE);
1584
1585     z_IdAuthentication(odr, &t, 1, 0);
1586     int sz;
1587     char *buf = odr_getbuf(odr, &sz, 0);
1588     if (buf && m_idAuthentication_ber_buf
1589         && sz == m_idAuthentication_ber_size
1590         && !memcmp(m_idAuthentication_ber_buf, buf, sz))
1591     {
1592         odr_destroy(odr);
1593         return true;
1594     }
1595     odr_destroy(odr);
1596     if (!buf && !m_idAuthentication_ber_buf)
1597         return true;
1598     return false;
1599 }
1600
1601 int Yaz_ProxyClient::send_to_target(Z_APDU *apdu)
1602 {
1603     int len = 0;
1604     const char *apdu_name_tmp = apdu_name(apdu);
1605     int r = send_Z_PDU(apdu, &len);
1606     if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
1607         yaz_log (YLOG_LOG, "%sSending %s to %s %d bytes",
1608                  get_session_str(),
1609                  apdu_name_tmp, get_hostname(), len);
1610     m_bytes_sent += len;
1611     return r;
1612 }
1613
1614 Z_APDU *Yaz_Proxy::result_set_optimize(Z_APDU *apdu)
1615 {
1616     if (apdu->which == Z_APDU_presentRequest)
1617     {
1618         Z_PresentRequest *pr = apdu->u.presentRequest;
1619         int toget = *pr->numberOfRecordsRequested;
1620         int start = *pr->resultSetStartPoint;
1621
1622         yaz_log(YLOG_LOG, "%sPresent %s %d+%d", m_session_str,
1623                 pr->resultSetId, start, toget);
1624
1625         if (*m_parent->m_optimize == '0')
1626             return apdu;
1627
1628         if (!m_client->m_last_resultSetId)
1629         {
1630             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1631             new_apdu->u.presentResponse->records =
1632                 create_nonSurrogateDiagnostics(odr_encode(), 30,
1633                                                pr->resultSetId);
1634             send_to_client(new_apdu);
1635             return 0;
1636         }
1637         if (!strcmp(m_client->m_last_resultSetId, pr->resultSetId))
1638         {
1639             if (start+toget-1 > m_client->m_last_resultCount)
1640             {
1641                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1642                 new_apdu->u.presentResponse->records =
1643                     create_nonSurrogateDiagnostics(odr_encode(), 13, 0);
1644                 send_to_client(new_apdu);
1645                 return 0;
1646             }
1647             Z_NamePlusRecordList *npr;
1648 #if 0
1649             yaz_log(YLOG_LOG, "%sCache lookup %d+%d syntax=%s",
1650                     m_session_str, start, toget, yaz_z3950oid_to_str(
1651                         pr->preferredRecordSyntax, &oclass));
1652 #endif
1653             if (m_client->m_cache.lookup (odr_encode(), &npr, start, toget,
1654                                           pr->preferredRecordSyntax,
1655                                           pr->recordComposition))
1656             {
1657                 yaz_log (YLOG_LOG, "%sReturned cached records for present request",
1658                          m_session_str);
1659                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1660                 new_apdu->u.presentResponse->referenceId = pr->referenceId;
1661
1662                 new_apdu->u.presentResponse->numberOfRecordsReturned
1663                     = odr_intdup(odr_encode(), toget);
1664
1665                 new_apdu->u.presentResponse->records = (Z_Records*)
1666                     odr_malloc(odr_encode(), sizeof(Z_Records));
1667                 new_apdu->u.presentResponse->records->which = Z_Records_DBOSD;
1668                 new_apdu->u.presentResponse->records->u.databaseOrSurDiagnostics = npr;
1669                 new_apdu->u.presentResponse->nextResultSetPosition =
1670                     odr_intdup(odr_encode(), start+toget);
1671
1672                 send_to_client(new_apdu);
1673                 return 0;
1674             }
1675         }
1676     }
1677
1678     if (apdu->which != Z_APDU_searchRequest)
1679         return apdu;
1680     Z_SearchRequest *sr = apdu->u.searchRequest;
1681     Yaz_Z_Query *this_query = new Yaz_Z_Query;
1682     Yaz_Z_Databases this_databases;
1683
1684     this_databases.set(sr->num_databaseNames, (const char **)
1685                        sr->databaseNames);
1686
1687     this_query->set_Z_Query(sr->query);
1688
1689     char query_str[120];
1690     this_query->print(query_str, sizeof(query_str)-1);
1691     yaz_log(YLOG_LOG, "%sSearch %s", m_session_str, query_str);
1692
1693     if (*m_parent->m_optimize != '0' &&
1694         m_client->m_last_ok && m_client->m_last_query &&
1695         m_client->m_last_query->match(this_query) &&
1696         !strcmp(m_client->m_last_resultSetId, sr->resultSetName) &&
1697         m_client->m_last_databases.match(this_databases))
1698     {
1699         delete this_query;
1700         if (m_client->m_last_resultCount > *sr->smallSetUpperBound &&
1701             m_client->m_last_resultCount < *sr->largeSetLowerBound)
1702         {
1703             Z_NamePlusRecordList *npr;
1704             int toget = *sr->mediumSetPresentNumber;
1705             Z_RecordComposition *comp = 0;
1706
1707             if (toget > m_client->m_last_resultCount)
1708                 toget = m_client->m_last_resultCount;
1709
1710             if (sr->mediumSetElementSetNames)
1711             {
1712                 comp = (Z_RecordComposition *)
1713                     odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
1714                 comp->which = Z_RecordComp_simple;
1715                 comp->u.simple = sr->mediumSetElementSetNames;
1716             }
1717
1718             if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
1719                                           sr->preferredRecordSyntax, comp))
1720             {
1721                 yaz_log (YLOG_LOG, "%sReturned cached records for medium set",
1722                          m_session_str);
1723                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1724                 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1725                 new_apdu->u.searchResponse->resultCount =
1726                     &m_client->m_last_resultCount;
1727
1728                 new_apdu->u.searchResponse->numberOfRecordsReturned
1729                     = odr_intdup(odr_encode(), toget);
1730
1731                 new_apdu->u.searchResponse->presentStatus =
1732                     odr_intdup(odr_encode(), Z_PresentStatus_success);
1733                 new_apdu->u.searchResponse->records = (Z_Records*)
1734                     odr_malloc(odr_encode(), sizeof(Z_Records));
1735                 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
1736                 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
1737                 new_apdu->u.searchResponse->nextResultSetPosition =
1738                     odr_intdup(odr_encode(), toget+1);
1739                 send_to_client(new_apdu);
1740                 return 0;
1741             }
1742             else
1743             {
1744                 // medium Set
1745                 // send present request (medium size)
1746                 yaz_log (YLOG_LOG, "%sOptimizing search for medium set",
1747                          m_session_str);
1748
1749                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
1750                 Z_PresentRequest *pr = new_apdu->u.presentRequest;
1751                 pr->referenceId = sr->referenceId;
1752                 pr->resultSetId = sr->resultSetName;
1753                 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
1754                 *pr->numberOfRecordsRequested = toget;
1755                 pr->recordComposition = comp;
1756                 m_client->m_sr_transform = 1;
1757                 return new_apdu;
1758             }
1759         }
1760         else if (m_client->m_last_resultCount >= *sr->largeSetLowerBound ||
1761             m_client->m_last_resultCount <= 0)
1762         {
1763             // large set. Return pseudo-search response immediately
1764             yaz_log (YLOG_LOG, "%sOptimizing search for large set",
1765                      m_session_str);
1766             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1767             new_apdu->u.searchResponse->referenceId = sr->referenceId;
1768             new_apdu->u.searchResponse->resultCount =
1769                 &m_client->m_last_resultCount;
1770             send_to_client(new_apdu);
1771             return 0;
1772         }
1773         else
1774         {
1775             Z_NamePlusRecordList *npr;
1776             int toget = m_client->m_last_resultCount;
1777             Z_RecordComposition *comp = 0;
1778             // small set
1779             // send a present request (small set)
1780
1781             if (sr->smallSetElementSetNames)
1782             {
1783                 comp = (Z_RecordComposition *)
1784                     odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
1785                 comp->which = Z_RecordComp_simple;
1786                 comp->u.simple = sr->smallSetElementSetNames;
1787             }
1788
1789             if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
1790                                           sr->preferredRecordSyntax, comp))
1791             {
1792                 yaz_log (YLOG_LOG, "%sReturned cached records for small set",
1793                          m_session_str);
1794                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1795                 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1796                 new_apdu->u.searchResponse->resultCount =
1797                     &m_client->m_last_resultCount;
1798
1799                 new_apdu->u.searchResponse->numberOfRecordsReturned
1800                     = odr_intdup(odr_encode(), toget);
1801
1802                 new_apdu->u.searchResponse->presentStatus =
1803                     odr_intdup(odr_encode(), Z_PresentStatus_success);
1804                 new_apdu->u.searchResponse->records = (Z_Records*)
1805                     odr_malloc(odr_encode(), sizeof(Z_Records));
1806                 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
1807                 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
1808                 new_apdu->u.searchResponse->nextResultSetPosition =
1809                     odr_intdup(odr_encode(), toget+1);
1810                 send_to_client(new_apdu);
1811                 return 0;
1812             }
1813             else
1814             {
1815                 yaz_log (YLOG_LOG, "%sOptimizing search for small set",
1816                          m_session_str);
1817                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
1818                 Z_PresentRequest *pr = new_apdu->u.presentRequest;
1819                 pr->referenceId = sr->referenceId;
1820                 pr->resultSetId = sr->resultSetName;
1821                 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
1822                 *pr->numberOfRecordsRequested = toget;
1823                 pr->recordComposition = comp;
1824                 m_client->m_sr_transform = 1;
1825                 return new_apdu;
1826             }
1827         }
1828     }
1829     else  // query doesn't match
1830     {
1831         delete m_client->m_last_query;
1832         m_client->m_last_query = this_query;
1833         m_client->m_last_ok = 0;
1834         m_client->m_cache.clear();
1835         m_client->m_resultSetStartPoint = 0;
1836
1837         xfree (m_client->m_last_resultSetId);
1838         m_client->m_last_resultSetId = xstrdup (sr->resultSetName);
1839
1840         m_client->m_last_databases.set(sr->num_databaseNames,
1841                                        (const char **) sr->databaseNames);
1842     }
1843     return apdu;
1844 }
1845
1846
1847 void Yaz_Proxy::inc_request_no()
1848 {
1849     char *cp = m_session_str + strlen(m_session_str)-1;
1850     if (*cp == ' ')
1851         cp--;
1852     while (*cp && *cp != ' ')
1853         cp--;
1854     if (*cp)
1855         sprintf(cp+1, "%d ", m_request_no);
1856 }
1857
1858 void Yaz_Proxy::recv_GDU(Z_GDU *apdu, int len)
1859 {
1860     inc_request_no();
1861
1862     m_bytes_recv += len;
1863
1864     if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1865         yaz_log (YLOG_LOG, "%sReceiving %s from client %d bytes",
1866                  m_session_str, gdu_name(apdu), len);
1867
1868 #if HAVE_GETTIMEOFDAY
1869     gettimeofday((struct timeval *) m_time_tv, 0);
1870 #endif
1871     m_bw_stat.add_bytes(len);
1872     m_pdu_stat.add_bytes(1);
1873
1874     GDU *gdu = new GDU(apdu);
1875     m_in_queue.enqueue(gdu);
1876
1877     recv_GDU_more(false);
1878 }
1879
1880 void Yaz_Proxy::recv_GDU_reduce(GDU *gdu)
1881 {
1882     int reduce = m_initial_reduce; // initial reduce from connect phase..
1883     m_initial_reduce = 0;  // reset it..
1884
1885     int bw_total = m_bw_stat.get_total();
1886     int pdu_total = m_pdu_stat.get_total();
1887     int search_total = m_search_stat.get_total();
1888
1889     assert(m_timeout_mode == timeout_busy);
1890     assert(m_timeout_gdu == 0);
1891
1892     if (m_search_max)
1893         reduce += search_total / m_search_max;
1894     if (m_bw_max)
1895         reduce += (bw_total/m_bw_max);
1896     if (m_pdu_max)
1897     {
1898         if (pdu_total > m_pdu_max)
1899         {
1900             int nreduce = (m_pdu_max >= 60) ? 1 : 60/m_pdu_max;
1901             reduce = (reduce > nreduce) ? reduce : nreduce;
1902         }
1903     }
1904     m_http_version = 0;
1905
1906 #if 0
1907     /* uncomment to force a big reduce */
1908     m_timeout_mode = timeout_reduce;
1909     m_timeout_gdu = gdu;
1910     timeout(3);       // call us reduce seconds later
1911     return;
1912 #endif
1913     if (reduce)
1914     {
1915         yaz_log(YLOG_LOG, "%sdelay=%d bw=%d pdu=%d search=%d limit-bw=%d limit-pdu=%d limit-search=%d",
1916                 m_session_str, reduce, bw_total, pdu_total, search_total,
1917                 m_bw_max, m_pdu_max, m_search_max);
1918
1919         m_timeout_mode = timeout_reduce;
1920         m_timeout_gdu = gdu;
1921         timeout(reduce);       // call us reduce seconds later
1922     }
1923     else
1924         recv_GDU_normal(gdu);
1925 }
1926
1927 void Yaz_Proxy::recv_GDU_more(bool normal)
1928 {
1929     GDU *g;
1930     if (normal && m_timeout_mode == timeout_busy)
1931         m_timeout_mode = timeout_normal;
1932     while (m_timeout_mode == timeout_normal && (g = m_in_queue.dequeue()))
1933     {
1934         m_timeout_mode = timeout_busy;
1935         recv_GDU_reduce(g);
1936     }
1937 }
1938
1939 void Yaz_Proxy::recv_GDU_normal(GDU *gdu)
1940 {
1941     Z_GDU *apdu = 0;
1942     gdu->move_away_gdu(odr_decode(), &apdu);
1943     delete gdu;
1944
1945     if (apdu->which == Z_GDU_Z3950)
1946         handle_incoming_Z_PDU(apdu->u.z3950);
1947     else if (apdu->which == Z_GDU_HTTP_Request)
1948         handle_incoming_HTTP(apdu->u.HTTP_Request);
1949 }
1950
1951 void Yaz_Proxy::handle_max_record_retrieve(Z_APDU *apdu)
1952 {
1953     if (m_max_record_retrieve)
1954     {
1955         if (apdu->which == Z_APDU_presentRequest)
1956         {
1957             Z_PresentRequest *pr = apdu->u.presentRequest;
1958             if (pr->numberOfRecordsRequested &&
1959                 *pr->numberOfRecordsRequested > m_max_record_retrieve)
1960                 *pr->numberOfRecordsRequested = m_max_record_retrieve;
1961         }
1962     }
1963 }
1964
1965 void Yaz_Proxy::handle_charset_lang_negotiation(Z_APDU *apdu)
1966 {
1967     if (apdu->which == Z_APDU_initRequest)
1968     {
1969         if (m_initRequest_options &&
1970             !ODR_MASK_GET(m_initRequest_options, Z_Options_negotiationModel) &&
1971             (m_proxy_negotiation_charset || m_proxy_negotiation_lang))
1972         {
1973             // There is no negotiation proposal from
1974             // client's side. OK. The proxy negotiation
1975             // in use, only.
1976             Z_InitRequest *initRequest = apdu->u.initRequest;
1977             Z_OtherInformation **otherInfo;
1978             Z_OtherInformationUnit *oi;
1979             get_otherInfoAPDU(apdu, &otherInfo);
1980             oi = update_otherInformation(otherInfo, 1, NULL, 0, 0);
1981             if (oi)
1982             {
1983                 ODR_MASK_SET(initRequest->options,
1984                     Z_Options_negotiationModel);
1985                 oi->which = Z_OtherInfo_externallyDefinedInfo;
1986                 oi->information.externallyDefinedInfo =
1987                 yaz_set_proposal_charneg(odr_encode(),
1988                     (const char**)&m_proxy_negotiation_charset,
1989                     m_proxy_negotiation_charset ? 1:0,
1990                     (const char**)&m_proxy_negotiation_lang,
1991                     m_proxy_negotiation_lang ? 1:0,
1992                     1);
1993             }
1994         }
1995         else if (m_initRequest_options &&
1996                  ODR_MASK_GET(m_initRequest_options,
1997                               Z_Options_negotiationModel) &&
1998                  m_charset_converter->get_target_query_charset())
1999         {
2000             yaz_log(YLOG_LOG, "%sManaged charset negotiation: charset=%s",
2001                     m_session_str,
2002                     m_charset_converter->get_target_query_charset());
2003             Z_InitRequest *initRequest = apdu->u.initRequest;
2004             Z_CharSetandLanguageNegotiation *negotiation =
2005                 yaz_get_charneg_record (initRequest->otherInfo);
2006             if (negotiation &&
2007                 negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
2008             {
2009                 NMEM nmem = nmem_create();
2010                 char **charsets = 0;
2011                 int num_charsets = 0;
2012                 char **langs = 0;
2013                 int num_langs = 0;
2014                 int selected = 0;
2015                 yaz_get_proposal_charneg (nmem, negotiation,
2016                                           &charsets, &num_charsets,
2017                                           &langs, &num_langs, &selected);
2018                 int i;
2019                 for (i = 0; i<num_charsets; i++)
2020                     yaz_log(YLOG_LOG, "%scharset %s", m_session_str,
2021                             charsets[i]);
2022                 for (i = 0; i<num_langs; i++)
2023                     yaz_log(YLOG_LOG, "%slang %s", m_session_str,
2024                             langs[i]);
2025
2026                 const char *t_charset =
2027                     m_charset_converter->get_target_query_charset();
2028                 // sweep through charsets and pick the first supported
2029                 // conversion
2030                 for (i = 0; i<num_charsets; i++)
2031                 {
2032                     const char *c_charset = charsets[i];
2033                     if (!odr_set_charset(odr_decode(), t_charset, c_charset))
2034                         break;
2035                 }
2036                 if (i != num_charsets)
2037                 {
2038                     // got one .. set up ODR for reverse direction
2039                     const char *c_charset = charsets[i];
2040                     odr_set_charset(odr_encode(), c_charset, t_charset);
2041                     m_charset_converter->set_client_query_charset(c_charset);
2042                     m_charset_converter->set_client_charset_selected(selected);
2043                 }
2044                 nmem_destroy(nmem);
2045                 ODR_MASK_CLEAR(m_initRequest_options,
2046                                Z_Options_negotiationModel);
2047                 yaz_del_charneg_record(&initRequest->otherInfo);
2048             }
2049             else
2050             {
2051                 yaz_log(YLOG_WARN, "%sUnable to decode charset package",
2052                         m_session_str);
2053             }
2054         }
2055         else if (m_charset_converter->get_target_query_charset() &&
2056             m_proxy_negotiation_default_charset)
2057         {
2058             m_charset_converter->
2059                 set_client_query_charset(m_proxy_negotiation_default_charset);
2060         }
2061     }
2062     else if (apdu->which == Z_APDU_initResponse)
2063     {
2064         Z_InitResponse *initResponse = apdu->u.initResponse;
2065         Z_OtherInformation **otherInfo;
2066         get_otherInfoAPDU(apdu, &otherInfo);
2067         
2068         Z_CharSetandLanguageNegotiation *charneg = 0;
2069
2070         if (otherInfo && *otherInfo && 
2071             ODR_MASK_GET(initResponse->options, Z_Options_negotiationModel)
2072             && (charneg = yaz_get_charneg_record(*otherInfo)))
2073         {
2074             char *charset = 0;
2075             char *lang = 0;
2076             int selected = 0;
2077
2078             yaz_get_response_charneg(m_referenceId_mem, charneg,
2079                 &charset, &lang, &selected);
2080
2081             yaz_log(YLOG_LOG, "%sAccepted charset - '%s' and lang - '%s'",
2082                 m_session_str, (charset)?charset:"none", (lang)?lang:"none");
2083
2084             if (m_initRequest_options &&
2085                 ODR_MASK_GET(m_initRequest_options, Z_Options_negotiationModel))
2086             {
2087                 yaz_log(YLOG_LOG, "%sClient's negotiation record in use",
2088                     m_session_str);
2089             }
2090             else if (m_proxy_negotiation_charset || m_proxy_negotiation_lang)
2091             {
2092                 // negotiation-charset, negotiation-lang
2093                 // elements of config file in use.
2094
2095                 yaz_log(YLOG_LOG, "%sProxy's negotiation record in use",
2096                     m_session_str);
2097
2098                 // clear negotiation option.
2099                 ODR_MASK_CLEAR(initResponse->options, Z_Options_negotiationModel);
2100
2101                 // Delete negotiation (charneg-3) entry.
2102                 yaz_del_charneg_record(otherInfo);
2103             }
2104         }
2105         else
2106         {
2107             if (m_proxy_negotiation_charset || m_proxy_negotiation_lang)
2108             {
2109                 yaz_log(YLOG_LOG, "%sTarget did not honor negotiation",
2110                         m_session_str);
2111             }
2112             else if (m_charset_converter->get_client_query_charset())
2113             {
2114                 Z_OtherInformation **otherInfo;
2115                 Z_OtherInformationUnit *oi;
2116                 get_otherInfoAPDU(apdu, &otherInfo);
2117                 oi = update_otherInformation(otherInfo, 1, NULL, 0, 0);
2118                 if (oi)
2119                 {
2120                     ODR_MASK_SET(initResponse->options,
2121                                  Z_Options_negotiationModel);
2122                     if (m_initRequest_options)
2123                         ODR_MASK_SET(m_initRequest_options,
2124                                      Z_Options_negotiationModel);
2125                     
2126                     oi->which = Z_OtherInfo_externallyDefinedInfo;    
2127                     oi->information.externallyDefinedInfo =
2128                         yaz_set_response_charneg(
2129                             odr_encode(),
2130                             m_charset_converter->get_client_query_charset(),
2131                             0 /* no lang */,
2132                             m_charset_converter->get_client_charset_selected());
2133                 }
2134             }
2135         }
2136     }
2137 }
2138
2139 Z_Records *Yaz_Proxy::create_nonSurrogateDiagnostics(ODR odr,
2140                                                      int error,
2141                                                      const char *addinfo)
2142 {
2143     Z_Records *rec = (Z_Records *)
2144         odr_malloc (odr, sizeof(*rec));
2145     int *err = (int *)
2146         odr_malloc (odr, sizeof(*err));
2147     Z_DiagRec *drec = (Z_DiagRec *)
2148         odr_malloc (odr, sizeof(*drec));
2149     Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
2150         odr_malloc (odr, sizeof(*dr));
2151     *err = error;
2152     rec->which = Z_Records_NSD;
2153     rec->u.nonSurrogateDiagnostic = dr;
2154     dr->diagnosticSetId =
2155         yaz_oidval_to_z3950oid (odr, CLASS_DIAGSET, VAL_BIB1);
2156     dr->condition = err;
2157     dr->which = Z_DefaultDiagFormat_v2Addinfo;
2158     dr->u.v2Addinfo = odr_strdup (odr, addinfo ? addinfo : "");
2159     return rec;
2160 }
2161
2162 Z_APDU *Yaz_Proxy::handle_query_transformation(Z_APDU *apdu)
2163 {
2164     if (apdu->which == Z_APDU_searchRequest &&
2165         apdu->u.searchRequest->query &&
2166         apdu->u.searchRequest->query->which == Z_Query_type_104 &&
2167         apdu->u.searchRequest->query->u.type_104->which == Z_External_CQL)
2168     {
2169         Z_RPNQuery *rpnquery = 0;
2170         Z_SearchRequest *sr = apdu->u.searchRequest;
2171         char *addinfo = 0;
2172
2173         yaz_log(YLOG_LOG, "%sCQL: %s", m_session_str,
2174                 sr->query->u.type_104->u.cql);
2175
2176         int r = m_cql2rpn.query_transform(sr->query->u.type_104->u.cql,
2177                                           &rpnquery, odr_encode(),
2178                                           &addinfo);
2179         if (r == -3)
2180             yaz_log(YLOG_LOG, "%sNo CQL to RPN table", m_session_str);
2181         else if (r)
2182         {
2183             yaz_log(YLOG_LOG, "%sCQL Conversion error %d", m_session_str, r);
2184             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2185
2186             new_apdu->u.searchResponse->referenceId = sr->referenceId;
2187             new_apdu->u.searchResponse->records =
2188                 create_nonSurrogateDiagnostics(odr_encode(),
2189                                                yaz_diag_srw_to_bib1(r),
2190                                                addinfo);
2191             *new_apdu->u.searchResponse->searchStatus = 0;
2192
2193             send_to_client(new_apdu);
2194
2195             return 0;
2196         }
2197         else
2198         {
2199             sr->query->which = Z_Query_type_1;
2200             sr->query->u.type_1 = rpnquery;
2201         }
2202         return apdu;
2203     }
2204     return apdu;
2205 }
2206
2207 Z_APDU *Yaz_Proxy::handle_target_charset_conversion(Z_APDU *apdu)
2208 {
2209     if (apdu->which == Z_APDU_searchRequest &&
2210         apdu->u.searchRequest->query)
2211     {
2212         if (apdu->u.searchRequest->query->which == Z_Query_type_1
2213             || apdu->u.searchRequest->query->which == Z_Query_type_101)
2214         {
2215             if (m_http_version)
2216                 m_charset_converter->set_client_query_charset("UTF-8");
2217             Z_RPNQuery *rpnquery = apdu->u.searchRequest->query->u.type_1;
2218             m_charset_converter->convert_type_1(rpnquery, odr_encode());
2219         }
2220     }
2221     return apdu;
2222 }
2223
2224
2225 Z_APDU *Yaz_Proxy::handle_query_validation(Z_APDU *apdu)
2226 {
2227     if (apdu->which == Z_APDU_searchRequest)
2228     {
2229         Z_SearchRequest *sr = apdu->u.searchRequest;
2230         int err = 0;
2231         char *addinfo = 0;
2232
2233         Yaz_ProxyConfig *cfg = check_reconfigure();
2234         if (cfg)
2235             err = cfg->check_query(odr_encode(), m_default_target,
2236                                    sr->query, &addinfo);
2237         if (err)
2238         {
2239             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2240
2241             new_apdu->u.searchResponse->referenceId = sr->referenceId;
2242             new_apdu->u.searchResponse->records =
2243                 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
2244             *new_apdu->u.searchResponse->searchStatus = 0;
2245
2246             send_to_client(new_apdu);
2247
2248             return 0;
2249         }
2250     }
2251     return apdu;
2252 }
2253
2254 int Yaz_Proxy::handle_authentication(Z_APDU *apdu)
2255 {
2256     if (apdu->which != Z_APDU_initRequest)
2257         return 1;  // pass if no init request
2258     Z_InitRequest *req = apdu->u.initRequest;
2259
2260     Yaz_ProxyConfig *cfg = check_reconfigure();
2261     if (!cfg)
2262         return 1;  // pass if no config
2263
2264     int ret;
2265     if (req->idAuthentication == 0)
2266     {
2267         ret = cfg->client_authentication(m_default_target, 0, 0, 0,
2268                                          m_peername);
2269     }
2270     else if (req->idAuthentication->which == Z_IdAuthentication_idPass)
2271     {
2272         ret = cfg->client_authentication(
2273             m_default_target,
2274             req->idAuthentication->u.idPass->userId,
2275             req->idAuthentication->u.idPass->groupId,
2276             req->idAuthentication->u.idPass->password,
2277             m_peername);
2278     }
2279     else if (req->idAuthentication->which == Z_IdAuthentication_open)
2280     {
2281         char user[64], pass[64];
2282         *user = '\0';
2283         *pass = '\0';
2284         sscanf(req->idAuthentication->u.open, "%63[^/]/%63s", user, pass);
2285         ret = cfg->client_authentication(m_default_target, user, 0, pass,
2286                                          m_peername);
2287     }
2288     else
2289         ret = cfg->client_authentication(m_default_target, 0, 0, 0,
2290                                          m_peername);
2291     return ret;
2292 }
2293
2294 Z_APDU *Yaz_Proxy::handle_syntax_validation(Z_APDU *apdu)
2295 {
2296     m_marcxml_mode = none;
2297     if (apdu->which == Z_APDU_searchRequest)
2298     {
2299         Z_SearchRequest *sr = apdu->u.searchRequest;
2300         int err = 0;
2301         char *addinfo = 0;
2302         Yaz_ProxyConfig *cfg = check_reconfigure();
2303
2304         Z_RecordComposition rc_temp, *rc = 0;
2305         if (sr->smallSetElementSetNames)
2306         {
2307             rc_temp.which = Z_RecordComp_simple;
2308             rc_temp.u.simple = sr->smallSetElementSetNames;
2309             rc = &rc_temp;
2310         }
2311
2312         if (sr->preferredRecordSyntax)
2313         {
2314             struct oident *ent;
2315             ent = oid_getentbyoid(sr->preferredRecordSyntax);
2316             m_frontend_type = ent->value;
2317         }
2318         else
2319             m_frontend_type = VAL_NONE;
2320
2321         char *stylesheet_name = 0;
2322         if (cfg)
2323             err = cfg->check_syntax(odr_encode(),
2324                                     m_default_target,
2325                                     sr->preferredRecordSyntax, rc,
2326                                     &addinfo, &stylesheet_name, &m_schema,
2327                                     &m_backend_type, &m_backend_charset,
2328                                     &m_usemarcon_ini_stage1,
2329                                     &m_usemarcon_ini_stage2);
2330         if (stylesheet_name)
2331         {
2332             m_parent->low_socket_close();
2333
2334 #if HAVE_XSLT
2335             if (m_stylesheet_xsp)
2336                 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
2337             m_stylesheet_xsp = xsltParseStylesheetFile((const xmlChar*)
2338                                                        stylesheet_name);
2339 #endif
2340             m_stylesheet_offset = 0;
2341             xfree(stylesheet_name);
2342
2343             m_parent->low_socket_open();
2344         }
2345         if (err == -1)
2346         {
2347             sr->smallSetElementSetNames = 0;
2348             sr->mediumSetElementSetNames = 0;
2349             m_marcxml_mode = marcxml;
2350             if (m_backend_type)
2351             {
2352
2353                 sr->preferredRecordSyntax =
2354                     yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN,
2355                                         m_backend_type);
2356             }
2357             else
2358                 sr->preferredRecordSyntax =
2359                     yaz_oidval_to_z3950oid(odr_encode(), CLASS_RECSYN,
2360                                            VAL_USMARC);
2361         }
2362         else if (err)
2363         {
2364             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2365
2366             new_apdu->u.searchResponse->referenceId = sr->referenceId;
2367             new_apdu->u.searchResponse->records =
2368                 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
2369             *new_apdu->u.searchResponse->searchStatus = 0;
2370
2371             send_to_client(new_apdu);
2372
2373             return 0;
2374         }
2375         else if (m_backend_type)
2376         {
2377             sr->preferredRecordSyntax =
2378                 yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN, m_backend_type);
2379         }
2380     }
2381     else if (apdu->which == Z_APDU_presentRequest)
2382     {
2383         Z_PresentRequest *pr = apdu->u.presentRequest;
2384         int err = 0;
2385         char *addinfo = 0;
2386         Yaz_ProxyConfig *cfg = check_reconfigure();
2387
2388         if (pr->preferredRecordSyntax)
2389         {
2390             struct oident *ent;
2391             ent = oid_getentbyoid(pr->preferredRecordSyntax);
2392             m_frontend_type = ent->value;
2393         }
2394         else
2395             m_frontend_type = VAL_NONE;
2396
2397         char *stylesheet_name = 0;
2398         if (cfg)
2399             err = cfg->check_syntax(odr_encode(), m_default_target,
2400                                     pr->preferredRecordSyntax,
2401                                     pr->recordComposition,
2402                                     &addinfo, &stylesheet_name, &m_schema,
2403                                     &m_backend_type, &m_backend_charset,
2404                                     &m_usemarcon_ini_stage1,
2405                                     &m_usemarcon_ini_stage2
2406                                     );
2407         if (stylesheet_name)
2408         {
2409             m_parent->low_socket_close();
2410
2411 #if HAVE_XSLT
2412             if (m_stylesheet_xsp)
2413                 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
2414             m_stylesheet_xsp = xsltParseStylesheetFile((const xmlChar*)
2415                                                        stylesheet_name);
2416 #endif
2417             m_stylesheet_offset = 0;
2418             xfree(stylesheet_name);
2419
2420             m_parent->low_socket_open();
2421         }
2422         if (err == -1)
2423         {
2424             pr->recordComposition = 0;
2425             m_marcxml_mode = marcxml;
2426             if (m_backend_type)
2427             {
2428
2429                 pr->preferredRecordSyntax =
2430                     yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN,
2431                                         m_backend_type);
2432             }
2433             else
2434                 pr->preferredRecordSyntax =
2435                     yaz_oidval_to_z3950oid(odr_encode(), CLASS_RECSYN,
2436                                            VAL_USMARC);
2437         }
2438         else if (err)
2439         {
2440             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
2441
2442             new_apdu->u.presentResponse->referenceId = pr->referenceId;
2443             new_apdu->u.presentResponse->records =
2444                 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
2445             *new_apdu->u.presentResponse->presentStatus =
2446                 Z_PresentStatus_failure;
2447
2448             send_to_client(new_apdu);
2449
2450             return 0;
2451         }
2452         else if (m_backend_type)
2453         {
2454             pr->preferredRecordSyntax =
2455                 yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN, m_backend_type);
2456         }
2457     }
2458     return apdu;
2459 }
2460
2461 Z_ElementSetNames *Yaz_Proxy::mk_esn_from_schema(ODR o, const char *schema)
2462 {
2463     if (!schema)
2464         return 0;
2465     Z_ElementSetNames *esn = (Z_ElementSetNames *)
2466         odr_malloc(o, sizeof(Z_ElementSetNames));
2467     esn->which = Z_ElementSetNames_generic;
2468     esn->u.generic = odr_strdup(o, schema);
2469     return esn;
2470 }
2471
2472 void Yaz_Proxy::srw_get_client(const char *db, const char **backend_db)
2473 {
2474     const char *t = 0;
2475     Yaz_ProxyConfig *cfg = check_reconfigure();
2476     if (cfg)
2477         t = cfg->get_explain_name(db, backend_db);
2478
2479     if (m_client && m_default_target && t && strcmp(m_default_target, t))
2480     {
2481         releaseClient();
2482     }
2483
2484     if (t)
2485     {
2486         xfree(m_default_target);
2487         m_default_target = xstrdup(t);
2488     }
2489 }
2490
2491 int Yaz_Proxy::file_access(Z_HTTP_Request *hreq)
2492 {
2493     struct stat sbuf;
2494     if (strcmp(hreq->method, "GET"))
2495         return 0;
2496     if (hreq->path[0] != '/')
2497         return 0;
2498     const char *cp = hreq->path;
2499     while (*cp)
2500     {
2501         if (*cp == '/' && strchr("/.", cp[1]))
2502         {
2503             yaz_log(YLOG_LOG, "%sRejecting path %s", m_session_str,
2504                     hreq->path);
2505             return 0;
2506         }
2507         cp++;
2508     }
2509
2510     Yaz_ProxyConfig *cfg = check_reconfigure();
2511
2512     if (!cfg->get_file_access_info(hreq->path+1))
2513         return 0;
2514
2515     const char *fname = hreq->path+1;
2516     if (stat(fname, &sbuf))
2517     {
2518         yaz_log(YLOG_LOG|YLOG_ERRNO, "%sstat failed for %s", m_session_str,
2519                 fname);
2520         return 0;
2521     }
2522     if ((sbuf.st_mode & S_IFMT) != S_IFREG)
2523     {
2524         yaz_log(YLOG_LOG, "%sNot a regular file %s", m_session_str, fname);
2525         return 0;
2526     }
2527     if (sbuf.st_size > (off_t) 1000000)
2528     {
2529         yaz_log(YLOG_WARN, "%sFile %s too large for transfer", m_session_str,
2530                 fname);
2531         return 0;
2532     }
2533
2534     ODR o = odr_encode();
2535
2536     const char *ctype = cfg->check_mime_type(fname);
2537     Z_GDU *gdu = z_get_HTTP_Response(o, 200);
2538     Z_HTTP_Response *hres = gdu->u.HTTP_Response;
2539     if (m_http_version)
2540         hres->version = odr_strdup(o, m_http_version);
2541     z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
2542     if (m_http_keepalive)
2543         z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
2544     else
2545         timeout(0);
2546
2547     hres->content_len = sbuf.st_size;
2548     hres->content_buf = (char*) odr_malloc(o, hres->content_len);
2549     FILE *f = fopen(fname, "rb");
2550     if (f)
2551     {
2552         fread(hres->content_buf, 1, hres->content_len, f);
2553         fclose(f);
2554     }
2555     else
2556     {
2557         return 0;
2558     }
2559     if (m_log_mask & PROXY_LOG_REQ_CLIENT)
2560     {
2561         yaz_log (YLOG_LOG, "%sSending file %s to client", m_session_str,
2562                  fname);
2563     }
2564     int len;
2565     send_GDU(gdu, &len);
2566     recv_GDU_more(true);
2567     return 1;
2568 }
2569
2570 void Yaz_Proxy::handle_incoming_HTTP(Z_HTTP_Request *hreq)
2571 {
2572     if (m_s2z_odr_init)
2573     {
2574         odr_destroy(m_s2z_odr_init);
2575         m_s2z_odr_init = 0;
2576     }
2577     if (m_s2z_odr_search)
2578     {
2579         odr_destroy(m_s2z_odr_search);
2580         m_s2z_odr_search = 0;
2581     }
2582
2583     m_http_keepalive = 0;
2584     m_http_version = 0;
2585     if (!strcmp(hreq->version, "1.0"))
2586     {
2587         const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
2588         if (v && !strcmp(v, "Keep-Alive"))
2589             m_http_keepalive = 1;
2590         else
2591             m_http_keepalive = 0;
2592         m_http_version = "1.0";
2593     }
2594     else
2595     {
2596         const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
2597         if (v && !strcmp(v, "close"))
2598             m_http_keepalive = 0;
2599         else
2600             m_http_keepalive = 1;
2601         m_http_version = "1.1";
2602     }
2603
2604     const char *a = z_HTTP_header_lookup(hreq->headers, "Authorization");
2605     char authorization_str[255];
2606     *authorization_str = '\0';
2607     if (a && strncasecmp(a, "Basic ", 6) == 0)
2608         base64_decode(a + 6, authorization_str, 254);
2609
2610     Z_SRW_PDU *srw_pdu = 0;
2611     Z_SOAP *soap_package = 0;
2612     char *charset = 0;
2613     Z_SRW_diagnostic *diagnostic = 0;
2614     int num_diagnostic = 0;
2615
2616     if (file_access(hreq))
2617     {
2618         return;
2619     }
2620     else if (yaz_srw_decode(hreq, &srw_pdu, &soap_package, odr_decode(),
2621                             &charset) == 0
2622              || yaz_sru_decode(hreq, &srw_pdu, &soap_package, odr_decode(),
2623                                &charset, &diagnostic, &num_diagnostic) == 0)
2624     {
2625         m_s2z_odr_init = odr_createmem(ODR_ENCODE);
2626         m_s2z_odr_search = odr_createmem(ODR_ENCODE);
2627         m_soap_ns = odr_strdup(m_s2z_odr_search, soap_package->ns);
2628         m_s2z_init_apdu = 0;
2629         m_s2z_search_apdu = 0;
2630         m_s2z_present_apdu = 0;
2631
2632         m_s2z_stylesheet = 0;
2633
2634         Z_IdAuthentication *auth = NULL;
2635         if (*authorization_str)
2636         {
2637             auth = (Z_IdAuthentication *) odr_malloc(m_s2z_odr_init, sizeof(Z_IdAuthentication));
2638             auth->which = Z_IdAuthentication_idPass;
2639             auth->u.idPass = (Z_IdPass *) odr_malloc(m_s2z_odr_init, sizeof(Z_IdPass));
2640             auth->u.idPass->groupId = NULL;
2641             char *p = strchr(authorization_str, ':');
2642             if (p)
2643             {
2644                 *p = '\0';
2645                 p++;
2646                 auth->u.idPass->password = odr_strdup(m_s2z_odr_init, p);
2647             }
2648             auth->u.idPass->userId = odr_strdup(m_s2z_odr_init, authorization_str);
2649         }
2650
2651         if (srw_pdu->which == Z_SRW_searchRetrieve_request)
2652         {
2653
2654             Z_SRW_searchRetrieveRequest *srw_req = srw_pdu->u.request;
2655
2656             const char *backend_db = srw_req->database;
2657             srw_get_client(srw_req->database, &backend_db);
2658
2659             m_s2z_database = odr_strdup(m_s2z_odr_init, srw_req->database);
2660             // recordXPath unsupported.
2661             if (srw_req->recordXPath)
2662             {
2663                 yaz_add_srw_diagnostic(odr_decode(),
2664                                        &diagnostic, &num_diagnostic,
2665                                        72, 0);
2666             }
2667             // sort unsupported
2668             if (srw_req->sort_type != Z_SRW_sort_type_none)
2669             {
2670                 yaz_add_srw_diagnostic(odr_decode(),
2671                                        &diagnostic, &num_diagnostic,
2672                                        80, 0);
2673             }
2674             // save stylesheet
2675             if (srw_req->stylesheet)
2676                 m_s2z_stylesheet =
2677                     odr_strdup(m_s2z_odr_init, srw_req->stylesheet);
2678
2679             // set packing for response records ..
2680             if (srw_req->recordPacking &&
2681                 !strcmp(srw_req->recordPacking, "xml"))
2682                 m_s2z_packing = Z_SRW_recordPacking_XML;
2683             else
2684                 m_s2z_packing = Z_SRW_recordPacking_string;
2685
2686             if (num_diagnostic)
2687             {
2688                 Z_SRW_PDU *srw_pdu =
2689                     yaz_srw_get(odr_encode(),
2690                                 Z_SRW_searchRetrieve_response);
2691                 Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
2692
2693                 srw_res->diagnostics = diagnostic;
2694                 srw_res->num_diagnostics = num_diagnostic;
2695                 send_srw_response(srw_pdu);
2696                 return;
2697             }
2698
2699             // prepare search PDU
2700             m_s2z_search_apdu = zget_APDU(m_s2z_odr_search,
2701                                           Z_APDU_searchRequest);
2702             Z_SearchRequest *z_searchRequest =
2703                 m_s2z_search_apdu->u.searchRequest;
2704
2705             z_searchRequest->num_databaseNames = 1;
2706             z_searchRequest->databaseNames = (char**)
2707                 odr_malloc(m_s2z_odr_search, sizeof(char *));
2708             z_searchRequest->databaseNames[0] = odr_strdup(m_s2z_odr_search,
2709                                                            backend_db);
2710
2711             // query transformation
2712             Z_Query *query = (Z_Query *)
2713                 odr_malloc(m_s2z_odr_search, sizeof(Z_Query));
2714             z_searchRequest->query = query;
2715
2716             if (srw_req->query_type == Z_SRW_query_type_cql)
2717             {
2718                 Z_External *ext = (Z_External *)
2719                     odr_malloc(m_s2z_odr_search, sizeof(*ext));
2720                 ext->direct_reference =
2721                     odr_getoidbystr(m_s2z_odr_search, "1.2.840.10003.16.2");
2722                 ext->indirect_reference = 0;
2723                 ext->descriptor = 0;
2724                 ext->which = Z_External_CQL;
2725                 ext->u.cql = srw_req->query.cql;
2726
2727                 query->which = Z_Query_type_104;
2728                 query->u.type_104 =  ext;
2729             }
2730             else if (srw_req->query_type == Z_SRW_query_type_pqf)
2731             {
2732                 Z_RPNQuery *RPNquery;
2733                 YAZ_PQF_Parser pqf_parser;
2734
2735                 pqf_parser = yaz_pqf_create ();
2736
2737                 RPNquery = yaz_pqf_parse (pqf_parser, m_s2z_odr_search,
2738                                           srw_req->query.pqf);
2739                 if (!RPNquery)
2740                 {
2741                     const char *pqf_msg;
2742                     size_t off;
2743                     int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2744                     int ioff = off;
2745                     yaz_log(YLOG_LOG, "%*s^\n", ioff+4, "");
2746                     yaz_log(YLOG_LOG, "Bad PQF: %s (code %d)\n", pqf_msg, code);
2747
2748                     send_to_srw_client_error(10, 0);
2749                     return;
2750                 }
2751                 query->which = Z_Query_type_1;
2752                 query->u.type_1 =  RPNquery;
2753
2754                 yaz_pqf_destroy (pqf_parser);
2755             }
2756             else
2757             {
2758                 send_to_srw_client_error(7, "query");
2759                 return;
2760             }
2761
2762             // present
2763             m_s2z_present_apdu = 0;
2764             int max = 0;
2765             if (srw_req->maximumRecords)
2766                 max = *srw_req->maximumRecords;
2767             int start = 1;
2768             if (srw_req->startRecord)
2769                 start = *srw_req->startRecord;
2770             if (max > 0)
2771             {
2772                 // Some backend, such as Voyager doesn't honor piggyback
2773                 // So we use present always (0 &&).
2774                 if (0 && start <= 1)  // Z39.50 piggyback
2775                 {
2776                     *z_searchRequest->smallSetUpperBound = max;
2777                     *z_searchRequest->mediumSetPresentNumber = max;
2778                     *z_searchRequest->largeSetLowerBound = 2000000000; // 2e9
2779
2780                     z_searchRequest->preferredRecordSyntax =
2781                         yaz_oidval_to_z3950oid(m_s2z_odr_search, CLASS_RECSYN,
2782                                                VAL_TEXT_XML);
2783                     if (srw_req->recordSchema)
2784                     {
2785                         z_searchRequest->smallSetElementSetNames =
2786                             z_searchRequest->mediumSetElementSetNames =
2787                             mk_esn_from_schema(m_s2z_odr_search,
2788                                                srw_req->recordSchema);
2789                     }
2790                 }
2791                 else   // Z39.50 present
2792                 {
2793                     m_s2z_present_apdu = zget_APDU(m_s2z_odr_search,
2794                                                    Z_APDU_presentRequest);
2795                     Z_PresentRequest *z_presentRequest =
2796                         m_s2z_present_apdu->u.presentRequest;
2797                     *z_presentRequest->resultSetStartPoint = start;
2798                     *z_presentRequest->numberOfRecordsRequested = max;
2799                     z_presentRequest->preferredRecordSyntax =
2800                         yaz_oidval_to_z3950oid(m_s2z_odr_search, CLASS_RECSYN,
2801                                                VAL_TEXT_XML);
2802                     if (srw_req->recordSchema)
2803                     {
2804                         z_presentRequest->recordComposition =
2805                             (Z_RecordComposition *)
2806                             odr_malloc(m_s2z_odr_search,
2807                                        sizeof(Z_RecordComposition));
2808                         z_presentRequest->recordComposition->which =
2809                             Z_RecordComp_simple;
2810                         z_presentRequest->recordComposition->u.simple =
2811                             mk_esn_from_schema(m_s2z_odr_search,
2812                                                srw_req->recordSchema);
2813                     }
2814                 }
2815             }
2816             if (!m_client)
2817             {
2818                 m_s2z_init_apdu = zget_APDU(m_s2z_odr_init,
2819                                             Z_APDU_initRequest);
2820
2821                 m_s2z_init_apdu->u.initRequest->idAuthentication = auth;
2822
2823                 // prevent m_initRequest_apdu memory from being grabbed
2824                 // in Yaz_Proxy::handle_incoming_Z_PDU
2825                 m_initRequest_apdu = m_s2z_init_apdu;
2826                 handle_incoming_Z_PDU(m_s2z_init_apdu);
2827                 return;
2828             }
2829             else
2830             {
2831                 handle_incoming_Z_PDU(m_s2z_search_apdu);
2832                 return;
2833             }
2834         }
2835         else if (srw_pdu->which == Z_SRW_explain_request)
2836         {
2837             Z_SRW_explainRequest *srw_req = srw_pdu->u.explain_request;
2838
2839             const char *backend_db = srw_req->database;
2840             srw_get_client(srw_req->database, &backend_db);
2841
2842             m_s2z_database = odr_strdup(m_s2z_odr_init, srw_req->database);
2843
2844             // save stylesheet
2845             if (srw_req->stylesheet)
2846                 m_s2z_stylesheet =
2847                     odr_strdup(m_s2z_odr_init, srw_req->stylesheet);
2848
2849             if (srw_req->recordPacking &&
2850                 !strcmp(srw_req->recordPacking, "xml"))
2851                 m_s2z_packing = Z_SRW_recordPacking_XML;
2852             else
2853                 m_s2z_packing = Z_SRW_recordPacking_string;
2854
2855             if (num_diagnostic)
2856             {
2857                 send_srw_explain_response(diagnostic, num_diagnostic);
2858                 return;
2859             }
2860
2861             if (!m_client)
2862             {
2863                 m_s2z_init_apdu = zget_APDU(m_s2z_odr_init,
2864                                             Z_APDU_initRequest);
2865
2866                 m_s2z_init_apdu->u.initRequest->idAuthentication = auth;
2867                 
2868                 // prevent m_initRequest_apdu memory from being grabbed
2869                 // in Yaz_Proxy::handle_incoming_Z_PDU
2870                 m_initRequest_apdu = m_s2z_init_apdu;
2871                 handle_incoming_Z_PDU(m_s2z_init_apdu);
2872             }
2873             else
2874                 send_srw_explain_response(0, 0);
2875             return;
2876         }
2877         else if (srw_pdu->which == Z_SRW_scan_request)
2878         {
2879             m_s2z_database = odr_strdup(m_s2z_odr_init,
2880                                         srw_pdu->u.scan_request->database);
2881
2882             yaz_add_srw_diagnostic(odr_decode(),
2883                                    &diagnostic, &num_diagnostic,
2884                                    4, "scan");
2885             Z_SRW_PDU *srw_pdu =
2886                 yaz_srw_get(odr_encode(),
2887                             Z_SRW_scan_response);
2888             Z_SRW_scanResponse *srw_res = srw_pdu->u.scan_response;
2889
2890             srw_res->diagnostics = diagnostic;
2891             srw_res->num_diagnostics = num_diagnostic;
2892             send_srw_response(srw_pdu);
2893             return;
2894         }
2895         else
2896         {
2897             m_s2z_database = 0;
2898
2899             send_to_srw_client_error(4, 0);
2900         }
2901     }
2902     send_http_response(400);
2903 }
2904
2905 void Yaz_Proxy::handle_init(Z_APDU *apdu)
2906 {
2907
2908     Z_OtherInformation **oi;
2909     get_otherInfoAPDU(apdu, &oi);
2910
2911     if (apdu->u.initRequest->implementationId)
2912         yaz_log(YLOG_LOG, "%simplementationId: %s",
2913                 m_session_str, apdu->u.initRequest->implementationId);
2914     if (apdu->u.initRequest->implementationName)
2915         yaz_log(YLOG_LOG, "%simplementationName: %s",
2916                 m_session_str, apdu->u.initRequest->implementationName);
2917     if (apdu->u.initRequest->implementationVersion)
2918         yaz_log(YLOG_LOG, "%simplementationVersion: %s",
2919                 m_session_str, apdu->u.initRequest->implementationVersion);
2920     if (m_initRequest_apdu == 0)
2921     {
2922         if (m_initRequest_mem)
2923             nmem_destroy(m_initRequest_mem);
2924
2925         m_initRequest_apdu = apdu;
2926         m_initRequest_mem = odr_extract_mem(odr_decode());
2927
2928         m_initRequest_preferredMessageSize = *apdu->u.initRequest->
2929             preferredMessageSize;
2930         *apdu->u.initRequest->preferredMessageSize = 1024*1024;
2931         m_initRequest_maximumRecordSize = *apdu->u.initRequest->
2932             maximumRecordSize;
2933         *apdu->u.initRequest->maximumRecordSize = 1024*1024;
2934
2935         Z_CharSetandLanguageNegotiation *charSetandLangRecord =
2936             yaz_get_charneg_record(*oi);
2937
2938         // Save proposal charsets and langs.
2939         if (ODR_MASK_GET(apdu->u.initRequest->options,
2940                          Z_Options_negotiationModel)
2941             && charSetandLangRecord)
2942         {
2943
2944             yaz_get_proposal_charneg(m_referenceId_mem,
2945                                      charSetandLangRecord,
2946                                      &m_initRequest_oi_negotiation_charsets,
2947                                      &m_initRequest_oi_negotiation_num_charsets,
2948                                      &m_initRequest_oi_negotiation_langs,
2949                                      &m_initRequest_oi_negotiation_num_langs,
2950                                      &m_initRequest_oi_negotiation_selected);
2951
2952             for (int i = 0; i<m_initRequest_oi_negotiation_num_charsets; i++)
2953             {
2954                 yaz_log(YLOG_LOG, "%scharacters set proposal: %s",
2955                         m_session_str,(m_initRequest_oi_negotiation_charsets[i])?
2956                         m_initRequest_oi_negotiation_charsets[i]:"none");
2957             }
2958             for (int i=0; i<m_initRequest_oi_negotiation_num_langs; i++)
2959             {
2960                 yaz_log(YLOG_LOG, "%slanguages proposal: %s",
2961                         m_session_str, (m_initRequest_oi_negotiation_langs[i])?
2962                         m_initRequest_oi_negotiation_langs[i]:"none");
2963             }
2964             yaz_log(YLOG_LOG, "%sselected proposal: %d (boolean)",
2965                     m_session_str, m_initRequest_oi_negotiation_selected);
2966         }
2967         // save init options for the response..
2968         m_initRequest_options = apdu->u.initRequest->options;
2969
2970         apdu->u.initRequest->options =
2971             (Odr_bitmask *)nmem_malloc(m_initRequest_mem,
2972                                        sizeof(Odr_bitmask));
2973         ODR_MASK_ZERO(apdu->u.initRequest->options);
2974         int i;
2975         for (i = 0; i<= 24; i++)
2976             ODR_MASK_SET(apdu->u.initRequest->options, i);
2977         // check negotiation option
2978         if (!ODR_MASK_GET(m_initRequest_options,
2979                           Z_Options_negotiationModel))
2980         {
2981             ODR_MASK_CLEAR(apdu->u.initRequest->options,
2982                            Z_Options_negotiationModel);
2983         }
2984         ODR_MASK_CLEAR(apdu->u.initRequest->options,
2985                        Z_Options_concurrentOperations);
2986         // make new version
2987         m_initRequest_version = apdu->u.initRequest->protocolVersion;
2988         apdu->u.initRequest->protocolVersion =
2989             (Odr_bitmask *)nmem_malloc(m_initRequest_mem,
2990                                        sizeof(Odr_bitmask));
2991         ODR_MASK_ZERO(apdu->u.initRequest->protocolVersion);
2992
2993         for (i = 0; i<= 8; i++)
2994             ODR_MASK_SET(apdu->u.initRequest->protocolVersion, i);
2995     }
2996     handle_charset_lang_negotiation(apdu);
2997     if (m_client->m_init_flag)
2998     {
2999         if (handle_init_response_for_invalid_session(apdu))
3000             return;
3001         if (m_client->m_initResponse)
3002         {
3003             Z_APDU *apdu2 = m_client->m_initResponse;
3004             apdu2->u.initResponse->otherInfo = 0;
3005             if (m_client->m_cookie && *m_client->m_cookie)
3006                 set_otherInformationString(apdu2, VAL_COOKIE, 1,
3007                                            m_client->m_cookie);
3008             apdu2->u.initResponse->referenceId =
3009                 apdu->u.initRequest->referenceId;
3010             apdu2->u.initResponse->options = m_client->m_initResponse_options;
3011             apdu2->u.initResponse->protocolVersion =
3012                 m_client->m_initResponse_version;
3013
3014             handle_charset_lang_negotiation(apdu2);
3015
3016             send_to_client(apdu2);
3017             m_timeout_mode = timeout_normal;
3018             return;
3019         }
3020     }
3021     m_client->m_init_flag = 1;
3022
3023 #if USE_AUTH_MSG
3024     Auth_Msg *m = new Auth_Msg;
3025     m->m_proxy = this;
3026     z_APDU(odr_encode(), &apdu, 0, "encode");
3027     char *apdu_buf = odr_getbuf(odr_encode(), &m->m_apdu_len, 0);
3028     m->m_apdu_buf = (char*) nmem_malloc(m->m_nmem, m->m_apdu_len);
3029     memcpy(m->m_apdu_buf, apdu_buf, m->m_apdu_len);
3030     odr_reset(odr_encode());
3031
3032     inc_ref();
3033     m_my_thread->put(m);
3034 #else
3035     int ret = handle_authentication(apdu);
3036     result_authentication(apdu, ret);
3037 #endif
3038 }
3039
3040 void Yaz_Proxy::handle_incoming_Z_PDU(Z_APDU *apdu)
3041 {
3042     Z_ReferenceId **refid = get_referenceIdP(apdu);
3043     nmem_reset(m_referenceId_mem);
3044     if (refid && *refid)
3045     {
3046         m_referenceId = (Z_ReferenceId *)
3047             nmem_malloc(m_referenceId_mem, sizeof(*m_referenceId));
3048         m_referenceId->len = m_referenceId->size = (*refid)->len;
3049         m_referenceId->buf = (unsigned char *)
3050             nmem_malloc(m_referenceId_mem, (*refid)->len);
3051         memcpy(m_referenceId->buf, (*refid)->buf, (*refid)->len);
3052     }
3053     else
3054         m_referenceId = 0;
3055
3056     if (!m_client && m_flag_invalid_session)
3057     {
3058         // Got request for a session that is invalid..
3059         m_apdu_invalid_session = apdu; // save package
3060         m_mem_invalid_session = odr_extract_mem(odr_decode());
3061         apdu = m_initRequest_apdu;     // but throw an init to the target
3062     }
3063
3064     if (apdu->which == Z_APDU_searchRequest)
3065         m_search_stat.add_bytes(1);
3066
3067     // Determine our client.
3068     Z_OtherInformation **oi;
3069     get_otherInfoAPDU(apdu, &oi);
3070     m_client = get_client(apdu, get_cookie(oi), get_proxy(oi));
3071     if (!m_client)
3072     {
3073         if (m_http_version)
3074         {   // HTTP. Send not found
3075             send_http_response(404);
3076             return;
3077         }
3078         else
3079         {
3080             // Z39.50 just shutdown
3081             timeout(0);
3082             return;
3083         }
3084     }
3085
3086     m_client->m_server = this;
3087
3088     if (apdu->which == Z_APDU_initRequest)
3089         handle_init(apdu);
3090     else
3091         handle_incoming_Z_PDU_2(apdu);
3092 }
3093
3094 void Yaz_Proxy::handle_incoming_Z_PDU_2(Z_APDU *apdu)
3095 {
3096     handle_max_record_retrieve(apdu);
3097
3098     if (apdu)
3099         apdu = handle_syntax_validation(apdu);
3100
3101     if (apdu)
3102         apdu = handle_query_transformation(apdu);
3103
3104     if (apdu)
3105         apdu = handle_target_charset_conversion(apdu);
3106
3107     if (apdu)
3108         apdu = handle_query_validation(apdu);
3109
3110     if (apdu)
3111         apdu = result_set_optimize(apdu);
3112
3113     if (!apdu)
3114     {
3115         m_client->timeout(m_target_idletime);  // mark it active even
3116         recv_GDU_more(true);
3117         // though we didn't use it
3118         return;
3119     }
3120
3121     // delete other info construct completely if 0 elements
3122     Z_OtherInformation **oi;
3123     get_otherInfoAPDU(apdu, &oi);
3124     if (oi && *oi && (*oi)->num_elements == 0)
3125         *oi = 0;
3126
3127     if (apdu->which == Z_APDU_presentRequest &&
3128         m_client->m_resultSetStartPoint == 0)
3129     {
3130         Z_PresentRequest *pr = apdu->u.presentRequest;
3131         m_client->m_resultSetStartPoint = *pr->resultSetStartPoint;
3132         m_client->m_cache.copy_presentRequest(apdu->u.presentRequest);
3133     } else {
3134         m_client->m_resultSetStartPoint = 0;
3135     }
3136     if (m_client->send_to_target(apdu) < 0)
3137     {
3138         m_client->shutdown();
3139     }
3140     else
3141         m_client->m_waiting = 1;
3142 }
3143
3144 void Yaz_Proxy::connectNotify()
3145 {
3146 }
3147
3148 void Yaz_Proxy::releaseClient()
3149 {
3150     xfree(m_proxyTarget);
3151     m_proxyTarget = 0;
3152     m_flag_invalid_session = 0;
3153     // only keep if keep_alive flag is set...
3154     if (m_client &&
3155         m_client->m_pdu_recv < m_keepalive_limit_pdu &&
3156         m_client->m_bytes_recv+m_client->m_bytes_sent < m_keepalive_limit_bw &&
3157         m_client->m_waiting == 0)
3158     {
3159         yaz_log(YLOG_LOG, "%sShutdown (client to proxy) keepalive %s",
3160                  m_session_str,
3161                  m_client->get_hostname());
3162         yaz_log(YLOG_LOG, "%sbw=%d pdu=%d limit-bw=%d limit-pdu=%d",
3163                 m_session_str, m_client->m_pdu_recv,
3164                 m_client->m_bytes_sent + m_client->m_bytes_recv,
3165                 m_keepalive_limit_bw, m_keepalive_limit_pdu);
3166         assert (m_client->m_waiting != 2);
3167         // Tell client (if any) that no server connection is there..
3168         m_client->m_server = 0;
3169         m_client = 0;
3170     }
3171     else if (m_client)
3172     {
3173         yaz_log (YLOG_LOG, "%sShutdown (client to proxy) close %s",
3174                  m_session_str,
3175                  m_client->get_hostname());
3176         assert (m_client->m_waiting != 2);
3177         delete m_client;
3178         m_client = 0;
3179     }
3180     else if (!m_parent)
3181     {
3182         yaz_log (YLOG_LOG, "%sshutdown (client to proxy) bad state",
3183                  m_session_str);
3184         assert (m_parent);
3185     }
3186     else
3187     {
3188         yaz_log (YLOG_LOG, "%sShutdown (client to proxy)",
3189                  m_session_str);
3190     }
3191     if (m_parent)
3192         m_parent->pre_init();
3193 }
3194
3195 bool Yaz_Proxy::dec_ref(bool main_ptr)
3196 {
3197     assert(m_ref_count > 0);
3198     if (main_ptr)
3199     {
3200         if (m_main_ptr_dec)
3201             return false;
3202         m_main_ptr_dec = true;
3203     }
3204
3205     m_http_keepalive = 0;
3206
3207     --m_ref_count;
3208     if (m_ref_count > 0)
3209         return false;
3210
3211     releaseClient();
3212
3213     delete this;
3214     return true;
3215 }
3216
3217 const char *Yaz_ProxyClient::get_session_str()
3218 {
3219     if (!m_server)
3220         return "0 ";
3221     return m_server->get_session_str();
3222 }
3223
3224 void Yaz_ProxyClient::shutdown()
3225 {
3226     yaz_log (YLOG_LOG, "%sShutdown (proxy to target) %s", get_session_str(),
3227              get_hostname());
3228
3229     if (m_server)
3230     {
3231         m_waiting = 1;      // ensure it's released from Proxy in releaseClient
3232         m_server->dec_ref(true);
3233     }
3234     else
3235         delete this;
3236 }
3237
3238 void Yaz_Proxy::failNotify()
3239 {
3240     inc_request_no();
3241     yaz_log (YLOG_LOG, "%sConnection closed by client",
3242              get_session_str());
3243     dec_ref(true);
3244 }
3245
3246 void Yaz_Proxy::send_response_fail_client(const char *addr)
3247 {
3248     if (m_http_version)
3249     {
3250         Z_SRW_diagnostic *diagnostic = 0;
3251         int num_diagnostic = 0;
3252         
3253         yaz_add_srw_diagnostic(odr_encode(),
3254                                &diagnostic, &num_diagnostic,
3255                                YAZ_SRW_SYSTEM_TEMPORARILY_UNAVAILABLE, addr);
3256         if (m_s2z_search_apdu)
3257             send_srw_search_response(diagnostic, num_diagnostic);
3258         else
3259             send_srw_explain_response(diagnostic, num_diagnostic);
3260     }            
3261 }
3262 void Yaz_ProxyClient::failNotify()
3263 {
3264     if (m_server)
3265         m_server->inc_request_no();
3266     yaz_log (YLOG_LOG, "%sConnection closed by target %s",
3267              get_session_str(), get_hostname());
3268
3269     if (m_server)
3270         m_server->send_response_fail_client(get_hostname());
3271     shutdown();
3272 }
3273
3274 void Yaz_ProxyClient::connectNotify()
3275 {
3276     const char *s = get_session_str();
3277     const char *h = get_hostname();
3278     yaz_log (YLOG_LOG, "%sConnection accepted by %s timeout=%d", s, h,
3279              m_target_idletime);
3280     timeout(m_target_idletime);
3281     if (!m_server)
3282         pre_init_client();
3283 }
3284
3285 IPDU_Observer *Yaz_ProxyClient::sessionNotify(IPDU_Observable
3286                                               *the_PDU_Observable, int fd)
3287 {
3288     return new Yaz_ProxyClient(the_PDU_Observable, 0);
3289 }
3290
3291 Yaz_ProxyClient::~Yaz_ProxyClient()
3292 {
3293     if (m_prev)
3294         *m_prev = m_next;
3295     if (m_next)
3296         m_next->m_prev = m_prev;
3297     m_waiting = 2;     // for debugging purposes only.
3298     odr_destroy(m_init_odr);
3299     odr_destroy(m_idAuthentication_odr);
3300     delete m_last_query;
3301     xfree (m_last_resultSetId);
3302     xfree (m_cookie);
3303 }
3304
3305 void Yaz_ProxyClient::pre_init_client()
3306 {
3307     Z_APDU *apdu = create_Z_PDU(Z_APDU_initRequest);
3308     Z_InitRequest *req = apdu->u.initRequest;
3309
3310     int i;
3311     for (i = 0; i<= 24; i++)
3312         ODR_MASK_SET(req->options, i);
3313     ODR_MASK_CLEAR(apdu->u.initRequest->options,
3314                    Z_Options_negotiationModel);
3315     ODR_MASK_CLEAR(apdu->u.initRequest->options,
3316                    Z_Options_concurrentOperations);
3317     for (i = 0; i<= 10; i++)
3318         ODR_MASK_SET(req->protocolVersion, i);
3319
3320     if (send_to_target(apdu) < 0)
3321     {
3322         delete this;
3323     }
3324     else
3325     {
3326         m_waiting = 1;
3327         m_init_flag = 1;
3328     }
3329 }
3330
3331 void Yaz_Proxy::pre_init()
3332 {
3333     int i;
3334     const char *name = 0;
3335     const char *zurl_in_use[MAX_ZURL_PLEX];
3336     int limit_bw, limit_pdu, limit_req, limit_search;
3337     int target_idletime, client_idletime;
3338     int max_clients;
3339     int keepalive_limit_bw, keepalive_limit_pdu;
3340     int pre_init;
3341     const char *cql2rpn = 0;
3342     const char *authentication = 0;
3343     const char *negotiation_charset = 0;
3344     const char *negotiation_lang = 0;
3345
3346     Yaz_ProxyConfig *cfg = check_reconfigure();
3347
3348     zurl_in_use[0] = 0;
3349
3350     if (m_log_mask & PROXY_LOG_APDU_CLIENT)
3351         set_APDU_yazlog(1);
3352     else
3353         set_APDU_yazlog(0);
3354
3355     for (i = 0; cfg && cfg->get_target_no(i, &name, zurl_in_use,
3356                                           &limit_bw, &limit_pdu, &limit_req,
3357                                           &limit_search,
3358                                           &target_idletime, &client_idletime,
3359                                           &max_clients,
3360                                           &keepalive_limit_bw,
3361                                           &keepalive_limit_pdu,
3362                                           &pre_init,
3363                                           &cql2rpn,
3364                                           &authentication,
3365                                           &negotiation_charset,
3366                                           &negotiation_lang,
3367                                           0,
3368                                           0) ; i++)
3369     {
3370         if (pre_init)
3371         {
3372             int j;
3373             for (j = 0; zurl_in_use[j]; j++)
3374             {
3375                 Yaz_ProxyClient *c;
3376                 int spare = 0;
3377                 int spare_waiting = 0;
3378                 int in_use = 0;
3379                 int other = 0;
3380                 for (c = m_clientPool; c; c = c->m_next)
3381                 {
3382                     if (!strcmp(zurl_in_use[j], c->get_hostname()))
3383                     {
3384                         if (c->m_cookie == 0)
3385                         {
3386                             if (c->m_server == 0)
3387                                 if (c->m_waiting)
3388                                     spare_waiting++;
3389                                 else
3390                                     spare++;
3391                             else
3392                                 in_use++;
3393                         }
3394                         else
3395                             other++;
3396                     }
3397                 }
3398                 yaz_log(YLOG_LOG, "%spre-init %s %s use=%d other=%d spare=%d "
3399                         "sparew=%d preinit=%d",m_session_str,
3400                         name, zurl_in_use[j], in_use, other,
3401                         spare, spare_waiting, pre_init);
3402                 if (spare + spare_waiting < pre_init)
3403                 {
3404                     c = new Yaz_ProxyClient(m_PDU_Observable->clone(), this);
3405                     c->m_next = m_clientPool;
3406                     if (c->m_next)
3407                         c->m_next->m_prev = &c->m_next;
3408                     m_clientPool = c;
3409                     c->m_prev = &m_clientPool;
3410
3411                     if (m_log_mask & PROXY_LOG_APDU_SERVER)
3412                         c->set_APDU_yazlog(1);
3413                     else
3414                         c->set_APDU_yazlog(0);
3415
3416                     if (c->client(zurl_in_use[j]))
3417                     {
3418                         timeout(60);
3419                         delete c;
3420                         return;
3421                     }
3422                     c->timeout(30);
3423                     c->m_waiting = 1;
3424                     c->m_target_idletime = target_idletime;
3425                     c->m_seqno = m_seqno++;
3426                 }
3427             }
3428         }
3429     }
3430 }
3431
3432 void Yaz_Proxy::timeoutNotify()
3433 {
3434     if (m_parent)
3435     {
3436         GDU *gdu;
3437         switch(m_timeout_mode)
3438         {
3439         case timeout_normal:
3440         case timeout_busy:
3441             inc_request_no();
3442             m_in_queue.clear();
3443             yaz_log (YLOG_LOG, "%sTimeout (client to proxy)", m_session_str);
3444             dec_ref(true);
3445             break;
3446         case timeout_reduce:
3447             timeout(m_client_idletime);
3448             m_timeout_mode = timeout_busy;
3449             gdu = m_timeout_gdu;
3450             m_timeout_gdu = 0;
3451             recv_GDU_normal(gdu);
3452             break;
3453         case timeout_xsl:
3454             assert(m_stylesheet_nprl);
3455             convert_xsl_delay();
3456             recv_GDU_more(true);
3457         }
3458     }
3459     else
3460     {
3461         timeout(600);
3462         pre_init();
3463     }
3464 }
3465
3466 void Yaz_Proxy::markInvalid()
3467 {
3468     m_client = 0;
3469     m_flag_invalid_session = 1;
3470 }
3471
3472 void Yaz_ProxyClient::timeoutNotify()
3473 {
3474     if (m_server)
3475         m_server->inc_request_no();
3476
3477     yaz_log (YLOG_LOG, "%sTimeout (proxy to target) %s", get_session_str(),
3478              get_hostname());
3479
3480     if (m_server)
3481         m_server->send_response_fail_client(get_hostname());
3482
3483     Yaz_Proxy *proxy_root = m_root;
3484
3485     shutdown();
3486
3487     proxy_root->pre_init();
3488 }
3489
3490 Yaz_ProxyClient::Yaz_ProxyClient(IPDU_Observable *the_PDU_Observable,
3491                                  Yaz_Proxy *parent) :
3492     Z_Assoc (the_PDU_Observable)
3493 {
3494     m_cookie = 0;
3495     m_next = 0;
3496     m_prev = 0;
3497     m_init_flag = 0;
3498     m_last_query = 0;
3499     m_last_resultSetId = 0;
3500     m_last_resultCount = 0;
3501     m_last_ok = 0;
3502     m_sr_transform = 0;
3503     m_waiting = 0;
3504     m_init_odr = odr_createmem (ODR_DECODE);
3505     m_initResponse = 0;
3506     m_initResponse_options = 0;
3507     m_initResponse_version = 0;
3508     m_initResponse_preferredMessageSize = 0;
3509     m_initResponse_maximumRecordSize = 0;
3510     m_resultSetStartPoint = 0;
3511     m_bytes_sent = m_bytes_recv = 0;
3512     m_pdu_recv = 0;
3513     m_server = 0;
3514     m_seqno = 0;
3515     m_target_idletime = 600;
3516     m_root = parent;
3517     m_idAuthentication_odr = odr_createmem(ODR_ENCODE);
3518     m_idAuthentication_ber_buf = 0;
3519     m_idAuthentication_ber_size = 0;
3520 }
3521
3522 const char *Yaz_Proxy::option(const char *name, const char *value)
3523 {
3524     if (!strcmp (name, "optimize")) {
3525         if (value) {
3526             xfree (m_optimize);
3527             m_optimize = xstrdup (value);
3528         }
3529         return m_optimize;
3530     }
3531     return 0;
3532 }
3533
3534 void Yaz_ProxyClient::recv_HTTP_response(Z_HTTP_Response *apdu, int len)
3535 {
3536
3537 }
3538
3539 void Yaz_ProxyClient::recv_GDU(Z_GDU *apdu, int len)
3540 {
3541     if (apdu->which == Z_GDU_Z3950)
3542         recv_Z_PDU(apdu->u.z3950, len);
3543     else if (apdu->which == Z_GDU_HTTP_Response)
3544         recv_HTTP_response(apdu->u.HTTP_Response, len);
3545     else
3546         shutdown();
3547 }
3548
3549 int Yaz_Proxy::handle_init_response_for_invalid_session(Z_APDU *apdu)
3550 {
3551     if (!m_flag_invalid_session)
3552         return 0;
3553     m_flag_invalid_session = 0;
3554     handle_incoming_Z_PDU(m_apdu_invalid_session);
3555     assert (m_mem_invalid_session);
3556     nmem_destroy(m_mem_invalid_session);
3557     m_mem_invalid_session = 0;
3558     return 1;
3559 }
3560
3561 void Yaz_ProxyClient::recv_Z_PDU(Z_APDU *apdu, int len)
3562 {
3563     m_bytes_recv += len;
3564
3565     m_pdu_recv++;
3566     m_waiting = 0;
3567     if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
3568         yaz_log (YLOG_LOG, "%sReceiving %s from %s %d bytes", get_session_str(),
3569                  apdu_name(apdu), get_hostname(), len);
3570     if (apdu->which == Z_APDU_initResponse)
3571     {
3572         if (!m_server)  // if this is a pre init session , check for more
3573             m_root->pre_init();
3574         NMEM nmem = odr_extract_mem (odr_decode());
3575         odr_reset (m_init_odr);
3576         nmem_transfer (m_init_odr->mem, nmem);
3577         m_initResponse = apdu;
3578         m_initResponse_options = apdu->u.initResponse->options;
3579         m_initResponse_version = apdu->u.initResponse->protocolVersion;
3580         m_initResponse_preferredMessageSize =
3581             *apdu->u.initResponse->preferredMessageSize;
3582         m_initResponse_maximumRecordSize =
3583             *apdu->u.initResponse->maximumRecordSize;
3584
3585         Z_InitResponse *ir = apdu->u.initResponse;
3586        
3587         // apply YAZ Proxy version
3588         char *imv0 = ir->implementationVersion;
3589         char *imv1 = (char*)
3590             odr_malloc(m_init_odr, 20 + (imv0 ? strlen(imv0) : 0));
3591         *imv1 = '\0';
3592         if (imv0)
3593             strcat(imv1, imv0);
3594         strcat(imv1, "/" VERSION);
3595         ir->implementationVersion = imv1;
3596         
3597         // apply YAZ Proxy implementation name
3598         char *im0 = ir->implementationName;
3599         char *im1 = (char*)
3600             odr_malloc(m_init_odr, 20 + (im0 ? strlen(im0) : 0));
3601         *im1 = '\0';
3602         if (im0)
3603         {
3604             strcat(im1, im0);
3605             strcat(im1, " ");
3606         }
3607         strcat(im1, "(YAZ Proxy)");
3608         ir->implementationName = im1;
3609
3610         nmem_destroy (nmem);
3611
3612         if (m_server && m_server->handle_init_response_for_invalid_session(apdu))
3613             return;
3614     }
3615     if (apdu->which == Z_APDU_searchResponse)
3616     {
3617         Z_SearchResponse *sr = apdu->u.searchResponse;
3618         m_last_resultCount = *sr->resultCount;
3619         int status = *sr->searchStatus;
3620         if (status && (!sr->records || sr->records->which == Z_Records_DBOSD))
3621         {
3622             m_last_ok = 1;
3623
3624             if (sr->records && sr->records->which == Z_Records_DBOSD)
3625             {
3626                 m_cache.add(odr_decode(),
3627                             sr->records->u.databaseOrSurDiagnostics, 1,
3628                             *sr->resultCount);
3629             }
3630         }
3631     }
3632     if (apdu->which == Z_APDU_presentResponse)
3633     {
3634         Z_PresentResponse *pr = apdu->u.presentResponse;
3635         if (m_sr_transform)
3636         {
3637             m_sr_transform = 0;
3638             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
3639             Z_SearchResponse *sr = new_apdu->u.searchResponse;
3640             sr->referenceId = pr->referenceId;
3641             *sr->resultCount = m_last_resultCount;
3642             sr->records = pr->records;
3643             sr->nextResultSetPosition = pr->nextResultSetPosition;
3644             sr->numberOfRecordsReturned = pr->numberOfRecordsReturned;
3645             apdu = new_apdu;
3646         }
3647         if (pr->records &&
3648             pr->records->which == Z_Records_DBOSD && m_resultSetStartPoint)
3649         {
3650             m_cache.add(odr_decode(),
3651                         pr->records->u.databaseOrSurDiagnostics,
3652                         m_resultSetStartPoint, -1);
3653             m_resultSetStartPoint = 0;
3654         }
3655     }
3656     if (m_cookie)
3657         set_otherInformationString (apdu, VAL_COOKIE, 1, m_cookie);
3658
3659     Yaz_Proxy *server = m_server; // save it. send_to_client may destroy us
3660
3661     if (server)
3662         server->send_to_client(apdu);
3663     if (apdu->which == Z_APDU_close)
3664         shutdown();
3665     else if (server)
3666         server->recv_GDU_more(true);
3667 }
3668
3669 void Yaz_Proxy::low_socket_close()
3670 {
3671 #if WIN32
3672 #else
3673     int i;
3674     for (i = 0; i<NO_SPARE_SOLARIS_FD; i++)
3675         if  (m_lo_fd[i] >= 0)
3676             ::close(m_lo_fd[i]);
3677 #endif
3678 }
3679
3680 void Yaz_Proxy::low_socket_open()
3681 {
3682 #if WIN32
3683 #else
3684     int i;
3685     for (i = 0; i<NO_SPARE_SOLARIS_FD; i++)
3686         m_lo_fd[i] = open("/dev/null", O_RDONLY);
3687 #endif
3688 }
3689
3690 int Yaz_Proxy::server(const char *addr)
3691 {
3692     int r = Z_Assoc::server(addr);
3693     if (!r)
3694     {
3695         yaz_log(YLOG_LOG, "%sStarted proxy "
3696 #ifdef VERSION
3697             VERSION
3698 #endif
3699             " on %s", m_session_str, addr);
3700         timeout(1);
3701     }
3702     return r;
3703 }
3704
3705 void Yaz_Proxy::base64_decode(const char *base64, char *buf, int buf_len)
3706 {
3707     const char *base64_chars =
3708         "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
3709     int len = strlen(base64);
3710     int buf_pos = 0;
3711     int index = 1;
3712
3713     for (int pos = 0; pos <= len; pos++)
3714     {
3715         if (base64[pos] == '=' || buf_pos + 1 >= buf_len)
3716             break;
3717
3718         const char *ch_ptr = strchr(base64_chars, base64[pos]);
3719         if (!ch_ptr)
3720             break;
3721         char ch = (char) (ch_ptr - base64_chars);
3722         switch (index)
3723         {
3724             case 1:
3725                 buf[buf_pos] = ch << 2;
3726                 break;
3727             case 2:
3728                 buf[buf_pos++] += (ch & 0x30) >> 4;
3729                 buf[buf_pos] = (ch & 0x0f) << 4;
3730                 break;
3731             case 3:
3732                 buf[buf_pos++] += (ch & 0x3c) >> 2;
3733                 buf[buf_pos] = (ch & 0x03) << 6;
3734                 break;
3735             case 4:
3736                 buf[buf_pos++] += ch;
3737         }
3738         if (index < 4)
3739             index++;
3740         else
3741             index = 1;
3742     }
3743     buf[buf_pos] = '\0';
3744 }
3745
3746 /*
3747  * Local variables:
3748  * c-basic-offset: 4
3749  * indent-tabs-mode: nil
3750  * End:
3751  * vim: shiftwidth=4 tabstop=8 expandtab
3752  */
3753