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