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