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