Windows version of yazproxy
[yazproxy-moved-to-github.git] / src / yaz-proxy.cpp
1 /* $Id: yaz-proxy.cpp,v 1.47 2006-03-30 14:16:34 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 #undef USE_AUTH_MSG
63 #define USE_AUTH_MSG 0
64
65 #if USE_AUTH_MSG
66 #error x
67 class YAZ_EXPORT Auth_Msg : public IMsg_Thread {
68 public:
69     int m_ret;
70     IMsg_Thread *handle();
71     void result();
72     Yaz_Proxy *m_proxy;
73     NMEM m_nmem;
74     char *m_apdu_buf;
75     int m_apdu_len;
76     Auth_Msg();
77     virtual ~Auth_Msg();
78 };
79
80 Auth_Msg::Auth_Msg()
81 {
82     m_nmem = nmem_create();
83 }
84
85 Auth_Msg::~Auth_Msg()
86 {
87     nmem_destroy(m_nmem);
88 }
89
90 IMsg_Thread *Auth_Msg::handle()
91 {
92     ODR decode = odr_createmem(ODR_DECODE);
93     Z_APDU *apdu;
94
95     odr_setbuf(decode, m_apdu_buf, m_apdu_len, 0);
96     int r = z_APDU(decode, &apdu, 0, 0);
97     if (!r)
98     {
99         yaz_log(YLOG_WARN, "decode failed in Auth_Msg::handle");
100     }
101     else
102     {
103         m_ret = m_proxy->handle_authentication(apdu);
104     }
105     odr_destroy(decode);
106     return this;
107 }
108
109 void Auth_Msg::result()
110 {
111     if (m_proxy->dec_ref(false))
112     {
113         yaz_log(YLOG_LOG, "Auth_Msg::proxy deleted meanwhile");
114     }
115     else
116     {
117         odr_setbuf(m_proxy->odr_decode(), m_apdu_buf, m_apdu_len, 0);
118         Z_APDU *apdu = 0;
119         int r = z_APDU(m_proxy->odr_decode(), &apdu, 0, 0);
120         if (!r)
121             yaz_log(YLOG_LOG, "Auth_Msg::result z_APDU failed");
122         m_proxy->result_authentication(apdu, m_ret);
123     }
124     delete this;
125 }
126
127 #endif
128
129 void Yaz_Proxy::result_authentication(Z_APDU *apdu, int ret)
130 {
131     if (apdu == 0 || ret == 0)
132     {
133         Z_APDU *apdu_reject = zget_APDU(odr_encode(), Z_APDU_initResponse);
134         *apdu_reject->u.initResponse->result = 0;
135         send_to_client(apdu_reject);
136         dec_ref(false);
137     }
138     else
139     {
140         if (apdu->which == Z_APDU_initRequest)
141         {
142             Yaz_ProxyConfig *cfg = check_reconfigure();
143             if (cfg)
144                 cfg->target_authentication(m_default_target, odr_encode(), 
145                                            apdu->u.initRequest);
146         }
147         handle_incoming_Z_PDU_2(apdu);
148     }
149 }
150
151 static const char *apdu_name(Z_APDU *apdu)
152 {
153     switch (apdu->which)
154     {
155     case Z_APDU_initRequest:
156         return "initRequest";
157     case Z_APDU_initResponse:
158         return "initResponse";
159     case Z_APDU_searchRequest:
160         return "searchRequest";
161     case Z_APDU_searchResponse:
162         return "searchResponse";
163     case Z_APDU_presentRequest:
164         return "presentRequest";
165     case Z_APDU_presentResponse:
166         return "presentResponse";
167     case Z_APDU_deleteResultSetRequest:
168         return "deleteResultSetRequest";
169     case Z_APDU_deleteResultSetResponse:
170         return "deleteResultSetResponse";
171     case Z_APDU_scanRequest:
172         return "scanRequest";
173     case Z_APDU_scanResponse:
174         return "scanResponse";
175     case Z_APDU_sortRequest:
176         return "sortRequest";
177     case Z_APDU_sortResponse:
178         return "sortResponse";
179     case Z_APDU_extendedServicesRequest:
180         return "extendedServicesRequest";
181     case Z_APDU_extendedServicesResponse:
182         return "extendedServicesResponse";
183     case Z_APDU_close:
184         return "close";
185     }
186     return "other";
187 }
188
189 static const char *gdu_name(Z_GDU *gdu)
190 {
191     switch(gdu->which)
192     {
193     case Z_GDU_Z3950:
194         return apdu_name(gdu->u.z3950);
195     case Z_GDU_HTTP_Request:
196         return "HTTP Request";
197     case Z_GDU_HTTP_Response:
198         return "HTTP Response";
199     }
200     return "Unknown request/response";
201 }
202
203 Yaz_Proxy::Yaz_Proxy(IPDU_Observable *the_PDU_Observable,
204                      ISocketObservable *the_socket_observable,
205                      Yaz_Proxy *parent)
206     :
207     Z_Assoc(the_PDU_Observable), m_bw_stat(60), m_pdu_stat(60)
208 {
209     m_PDU_Observable = the_PDU_Observable;
210     m_socket_observable = the_socket_observable;
211     m_client = 0;
212     m_parent = parent;
213     m_clientPool = 0;
214     m_seqno = 1;
215     m_keepalive_limit_bw = 500000;
216     m_keepalive_limit_pdu = 1000;
217     m_proxyTarget = 0;
218     m_default_target = 0;
219     m_proxy_negotiation_charset = 0;
220     m_proxy_negotiation_lang = 0;
221     m_proxy_negotiation_default_charset = 0;
222     m_charset_converter = new Yaz_CharsetConverter;
223     m_max_clients = 150;
224     m_log_mask = 0;
225     m_seed = time(0);
226     m_client_idletime = 600;
227     m_target_idletime = 600;
228     m_optimize = xstrdup ("1");
229     strcpy(m_session_str, "0 ");
230     m_session_no = 0;
231     m_bytes_sent = 0;
232     m_bytes_recv = 0;
233     m_bw_max = 0;
234     m_pdu_max = 0;
235     m_search_max = 0;
236     m_connect_max = 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 }
297
298 void Yaz_Proxy::inc_ref()
299 {
300     m_ref_count++;
301 }
302
303 Yaz_Proxy::~Yaz_Proxy()
304 {
305     yaz_log(YLOG_LOG, "%sClosed %d/%d sent/recv bytes total", m_session_str,
306             m_bytes_sent, m_bytes_recv);
307     nmem_destroy(m_initRequest_mem);
308     nmem_destroy(m_mem_invalid_session);
309     nmem_destroy(m_referenceId_mem);
310
311     xfree(m_proxyTarget);
312     xfree(m_default_target);
313     xfree(m_proxy_negotiation_charset);
314     xfree(m_proxy_negotiation_lang);
315     xfree(m_proxy_negotiation_default_charset);
316     delete m_charset_converter;
317     xfree(m_optimize);
318
319 #if HAVE_XSLT
320     if (m_stylesheet_xsp)
321         xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
322 #endif
323     xfree (m_time_tv);
324
325     xfree (m_peername);
326     xfree (m_schema);
327     xfree (m_backend_type);
328     xfree (m_backend_charset);
329     xfree (m_usemarcon_ini_stage1);
330     xfree (m_usemarcon_ini_stage2);
331     delete m_usemarcon;
332     if (m_s2z_odr_init)
333         odr_destroy(m_s2z_odr_init);
334     if (m_s2z_odr_search)
335         odr_destroy(m_s2z_odr_search);
336     if (!m_parent)
337         low_socket_close();
338     if (!m_parent)
339         delete m_my_thread;
340     delete m_config;
341 }
342
343 void Yaz_Proxy::set_debug_mode(int mode)
344 {
345     m_debug_mode = mode;
346 }
347
348 int Yaz_Proxy::set_config(const char *config)
349 {
350     delete m_config;
351     m_config = new Yaz_ProxyConfig();
352     xfree(m_config_fname);
353     m_config_fname = xstrdup(config);
354     int r = m_config->read_xml(config);
355     if (!r)
356         m_config->get_generic_info(&m_log_mask, &m_max_clients,
357                                    &m_connect_max);
358     return r;
359 }
360
361 void Yaz_Proxy::set_default_target(const char *target)
362 {
363     xfree (m_default_target);
364     m_default_target = 0;
365     if (target)
366         m_default_target = (char *) xstrdup (target);
367 }
368
369 void Yaz_Proxy::set_proxy_negotiation (const char *charset, const char *lang,
370                                        const char *default_charset)
371 {
372     yaz_log(YLOG_LOG, "%sSet the proxy negotiation: charset to '%s', "
373         "default charset to '%s', language to '%s'", m_session_str, 
374         charset?charset:"none",
375         default_charset?default_charset:"none",
376         lang?lang:"none");
377     xfree (m_proxy_negotiation_charset);
378     xfree (m_proxy_negotiation_lang);
379     m_proxy_negotiation_charset = m_proxy_negotiation_lang = 0;
380     if (charset)
381         m_proxy_negotiation_charset = (char *) xstrdup (charset);
382     if (lang)
383         m_proxy_negotiation_lang = (char *) xstrdup (lang);
384     if (default_charset)
385         m_proxy_negotiation_default_charset =
386             (char *) xstrdup (default_charset);
387 }
388
389 Yaz_ProxyConfig *Yaz_Proxy::check_reconfigure()
390 {
391     if (m_parent)
392         return m_parent->check_reconfigure();
393
394     Yaz_ProxyConfig *cfg = m_config;
395     if (m_reconfig_flag)
396     {
397         yaz_log(YLOG_LOG, "reconfigure");
398         yaz_log_reopen();
399         if (m_config_fname && cfg)
400         {
401             yaz_log(YLOG_LOG, "reconfigure config %s", m_config_fname);
402             int r = cfg->read_xml(m_config_fname);
403             if (r)
404                 yaz_log(YLOG_WARN, "reconfigure failed");
405             else
406             {
407                 m_log_mask = 0;
408                 cfg->get_generic_info(&m_log_mask, &m_max_clients,
409                                       &m_connect_max);
410             }
411         }
412         else
413             yaz_log(YLOG_LOG, "reconfigure");
414         m_reconfig_flag = 0;
415     }
416     return cfg;
417 }
418
419 IPDU_Observer *Yaz_Proxy::sessionNotify(IPDU_Observable
420                                         *the_PDU_Observable, int fd)
421 {
422     check_reconfigure();
423
424     char session_str[200];
425     sprintf(session_str, "%ld:%d ", (long) time(0), m_session_no);
426     m_session_no++;
427
428     const char *peername = the_PDU_Observable->getpeername();
429     yaz_log (YLOG_LOG, "%sNew session %s", session_str, peername);
430
431     m_connect.cleanup(false);
432     m_connect.add_connect(peername);
433
434     int connect_total = m_connect.get_total(peername);
435     int connect_max = m_connect_max;
436     if (connect_max && connect_total > connect_max)
437     {
438         yaz_log(YLOG_LOG, "%sconnect not accepted total=%d max=%d",
439                 session_str, connect_total, connect_max);
440         return 0;
441     }
442     yaz_log(YLOG_LOG, "%sconnect accepted total=%d", session_str,
443             connect_total);
444     
445     Yaz_Proxy *new_proxy = new Yaz_Proxy(the_PDU_Observable,
446                                          m_socket_observable, this);
447     new_proxy->m_config = 0;
448     new_proxy->m_config_fname = 0;
449     new_proxy->timeout(m_client_idletime);
450     new_proxy->m_target_idletime = m_target_idletime;
451     new_proxy->set_default_target(m_default_target);
452     new_proxy->m_max_clients = m_max_clients;
453     new_proxy->m_log_mask = m_log_mask;
454     new_proxy->set_APDU_log(get_APDU_log());
455     if (m_log_mask & PROXY_LOG_APDU_CLIENT)
456         new_proxy->set_APDU_yazlog(1);
457     else
458         new_proxy->set_APDU_yazlog(0);
459     strcpy(new_proxy->m_session_str, session_str);
460     new_proxy->m_peername = xstrdup(peername);
461     new_proxy->set_proxy_negotiation(m_proxy_negotiation_charset,
462         m_proxy_negotiation_lang, m_proxy_negotiation_default_charset);
463     // create thread object the first time we get an incoming connection
464     if (!m_my_thread)
465         m_my_thread = new Msg_Thread(m_socket_observable, 1);
466     new_proxy->m_my_thread = m_my_thread;
467     return new_proxy;
468 }
469
470 char *Yaz_Proxy::get_cookie(Z_OtherInformation **otherInfo)
471 {
472     int oid[OID_SIZE];
473     Z_OtherInformationUnit *oi;
474     struct oident ent;
475     ent.proto = PROTO_Z3950;
476     ent.oclass = CLASS_USERINFO;
477     ent.value = (oid_value) VAL_COOKIE;
478     assert (oid_ent_to_oid (&ent, oid));
479
480     if (oid_ent_to_oid (&ent, oid) &&
481         (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
482         oi->which == Z_OtherInfo_characterInfo)
483         return oi->information.characterInfo;
484     return 0;
485 }
486 char *Yaz_Proxy::get_proxy(Z_OtherInformation **otherInfo)
487 {
488     int oid[OID_SIZE];
489     Z_OtherInformationUnit *oi;
490     struct oident ent;
491     ent.proto = PROTO_Z3950;
492     ent.oclass = CLASS_USERINFO;
493     ent.value = (oid_value) VAL_PROXY;
494     if (oid_ent_to_oid (&ent, oid) &&
495         (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
496         oi->which == Z_OtherInfo_characterInfo)
497         return oi->information.characterInfo;
498     return 0;
499 }
500 const char *Yaz_Proxy::load_balance(const char **url)
501 {
502     int zurl_in_use[MAX_ZURL_PLEX];
503     int zurl_in_spare[MAX_ZURL_PLEX];
504     Yaz_ProxyClient *c;
505     int i;
506
507     for (i = 0; i<MAX_ZURL_PLEX; i++)
508     {
509         zurl_in_use[i] = 0;
510         zurl_in_spare[i] = 0;
511     }
512     for (c = m_parent->m_clientPool; c; c = c->m_next)
513     {
514         for (i = 0; url[i]; i++)
515             if (!strcmp(url[i], c->get_hostname()))
516             {
517                 zurl_in_use[i]++;
518                 if (c->m_cookie == 0 && c->m_server == 0 && c->m_waiting == 0)
519                     zurl_in_spare[i]++;
520             }
521     }
522     int min_use = 100000;
523     int spare_for_min = 0;
524     int max_spare = 0;
525     const char *ret_min = 0;
526     const char *ret_spare = 0;
527     for (i = 0; url[i]; i++)
528     {
529         yaz_log(YLOG_DEBUG, "%szurl=%s use=%d spare=%d",
530                 m_session_str, url[i], zurl_in_use[i], zurl_in_spare[i]);
531         if (min_use > zurl_in_use[i])
532         {
533             ret_min = url[i];
534             min_use = zurl_in_use[i];
535             spare_for_min = zurl_in_spare[i];
536         }
537         if (max_spare < zurl_in_spare[i])
538         {
539             ret_spare = url[i];
540             max_spare = zurl_in_spare[i];
541         }
542     }
543     return ret_min;
544 }
545
546 Yaz_ProxyClient *Yaz_Proxy::get_client(Z_APDU *apdu, const char *cookie,
547                                        const char *proxy_host)
548 {
549     assert (m_parent);
550     Yaz_Proxy *parent = m_parent;
551     Yaz_ProxyClient *c = m_client;
552
553     if (!m_proxyTarget)
554     {
555         const char *url[MAX_ZURL_PLEX];
556         Yaz_ProxyConfig *cfg = check_reconfigure();
557         if (proxy_host)
558         {
559             if (parent && parent->m_debug_mode)
560             {
561                 // only to be enabled for debugging...
562                 if (!strcmp(proxy_host, "stop"))
563                     exit(0);
564             }
565             xfree(m_default_target);
566             m_default_target = xstrdup(proxy_host);
567         }
568         proxy_host = m_default_target;
569         int client_idletime = -1;
570         const char *cql2rpn_fname = 0;
571         const char *negotiation_charset = 0;
572         const char *negotiation_lang = 0;
573         const char *query_charset = 0;
574         const char *default_client_query_charset = 0;
575         url[0] = m_default_target;
576         url[1] = 0;
577         if (cfg)
578         {
579             int pre_init = 0;
580             cfg->get_target_info(proxy_host, url, &m_bw_max,
581                                  &m_pdu_max, &m_max_record_retrieve,
582                                  &m_search_max,
583                                  &m_target_idletime, &client_idletime,
584                                  &parent->m_max_clients,
585                                  &m_keepalive_limit_bw,
586                                  &m_keepalive_limit_pdu,
587                                  &pre_init,
588                                  &cql2rpn_fname,
589                                  &negotiation_charset,
590                                  &negotiation_lang,
591                                  &query_charset,
592                                  &default_client_query_charset);
593         }
594         if (client_idletime != -1)
595         {
596             m_client_idletime = client_idletime;
597             timeout(m_client_idletime);
598         }
599         if (cql2rpn_fname)
600             m_cql2rpn.set_pqf_file(cql2rpn_fname);
601         if (negotiation_charset || negotiation_lang || default_client_query_charset)
602         {
603             set_proxy_negotiation(negotiation_charset,
604                 negotiation_lang, default_client_query_charset);
605         }
606         m_charset_converter->set_target_query_charset(query_charset);
607         if (!url[0])
608         {
609             yaz_log(YLOG_LOG, "%sNo default target", m_session_str);
610             return 0;
611         }
612         // we don't handle multiplexing for cookie session, so we just
613         // pick the first one in this case (anonymous users will be able
614         // to use any backend)
615         if (cookie && *cookie)
616             m_proxyTarget = (char*) xstrdup(url[0]);
617         else
618             m_proxyTarget = (char*) xstrdup(load_balance(url));
619     }
620     if (cookie && *cookie)
621     {   // search in sessions with a cookie
622         for (c = parent->m_clientPool; c; c = c->m_next)
623         {
624             assert (c->m_prev);
625             assert (*c->m_prev == c);
626             if (c->m_cookie && !strcmp(cookie,c->m_cookie) &&
627                 !strcmp(m_proxyTarget, c->get_hostname()))
628             {
629                 // Found it in cache
630                 // The following handles "cancel"
631                 // If connection is busy (waiting for PDU) and
632                 // we have an initRequest we can safely do re-open
633                 if (c->m_waiting && apdu->which == Z_APDU_initRequest)
634                 {
635                     yaz_log (YLOG_LOG, "%s REOPEN target=%s", m_session_str,
636                              c->get_hostname());
637                     c->close();
638                     c->m_init_flag = 0;
639
640                     c->m_last_ok = 0;
641                     c->m_cache.clear();
642                     c->m_last_resultCount = 0;
643                     c->m_sr_transform = 0;
644                     c->m_waiting = 0;
645                     c->m_resultSetStartPoint = 0;
646                     c->m_target_idletime = m_target_idletime;
647                     if (c->client(m_proxyTarget))
648                     {
649                         delete c;
650                         return 0;
651                     }
652                     c->timeout(30);
653                 }
654                 c->m_seqno = parent->m_seqno;
655                 if (c->m_server && c->m_server != this)
656                     c->m_server->m_client = 0;
657                 c->m_server = this;
658                 (parent->m_seqno)++;
659                 yaz_log (YLOG_DEBUG, "get_client 1 %p %p", this, c);
660                 return c;
661             }
662         }
663     }
664     else if (!c && apdu->which == Z_APDU_initRequest )
665     {
666         // anonymous sessions without cookie.
667         // if authentication is set it is NOT anonymous se we can't share them.
668         // If charset and lang negotiation is use it is NOT anonymous session too.
669         for (c = parent->m_clientPool; c; c = c->m_next)
670         {
671             assert(c->m_prev);
672             assert(*c->m_prev == c);
673             if (c->m_server == 0 && c->m_cookie == 0 &&  c->m_waiting == 0 
674                 && c->compare_idAuthentication(apdu)
675                 && c->compare_charset(apdu)
676                 && !strcmp(m_proxyTarget, c->get_hostname()))
677             {
678                 // found it in cache
679                 yaz_log (YLOG_LOG, "%sREUSE %d %s",
680                          m_session_str, parent->m_seqno, c->get_hostname());
681                 
682                 c->m_seqno = parent->m_seqno;
683                 assert(c->m_server == 0);
684                 c->m_server = this;
685
686                 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
687                     c->set_APDU_yazlog(1);
688                 else
689                     c->set_APDU_yazlog(0);
690
691                 (parent->m_seqno)++;
692
693                 parent->pre_init();
694
695                 return c;
696             }
697         }
698     }
699     if (!m_client)
700     {
701         if (apdu->which != Z_APDU_initRequest)
702         {
703             yaz_log (YLOG_LOG, "%sno init request as first PDU", m_session_str);
704             return 0;
705         }
706         // go through list of clients - and find the lowest/oldest one.
707         Yaz_ProxyClient *c_min = 0;
708         int min_seq = -1;
709         int no_of_clients = 0;
710         if (parent->m_clientPool)
711             yaz_log (YLOG_DEBUG, "Existing sessions");
712         for (c = parent->m_clientPool; c; c = c->m_next)
713         {
714             yaz_log (YLOG_DEBUG, " Session %-3d wait=%d %s cookie=%s", c->m_seqno,
715                                c->m_waiting, c->get_hostname(),
716                                c->m_cookie ? c->m_cookie : "");
717             no_of_clients++;
718             if (min_seq < 0 || c->m_seqno < min_seq)
719             {
720                 min_seq = c->m_seqno;
721                 c_min = c;
722             }
723         }
724         if (no_of_clients >= parent->m_max_clients)
725         {
726             c = c_min;
727             if (c->m_waiting || strcmp(m_proxyTarget, c->get_hostname()))
728             {
729                 yaz_log (YLOG_LOG, "%sMAXCLIENTS %d Destroy %d",
730                          m_session_str, parent->m_max_clients, c->m_seqno);
731                 if (c->m_server && c->m_server != this)
732                     delete c->m_server;   // PROBLEM: m_ref_count!
733                 c->m_server = 0;
734             }
735             else
736             {
737                 yaz_log (YLOG_LOG, "%sMAXCLIENTS %d Reuse %d %d %s",
738                          m_session_str, parent->m_max_clients,
739                          c->m_seqno, parent->m_seqno, c->get_hostname());
740                 xfree (c->m_cookie);
741                 c->m_cookie = 0;
742                 if (cookie)
743                     c->m_cookie = xstrdup(cookie);
744                 c->m_seqno = parent->m_seqno;
745                 if (c->m_server && c->m_server != this)
746                 {
747                     c->m_server->m_client = 0;
748                     delete c->m_server;   // PROBLEM: m_ref_count!
749                 }
750                 (parent->m_seqno)++;
751                 c->m_target_idletime = m_target_idletime;
752                 c->timeout(m_target_idletime);
753
754                 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
755                     c->set_APDU_yazlog(1);
756                 else
757                     c->set_APDU_yazlog(0);
758
759                 return c;
760             }
761         }
762         else
763         {
764             yaz_log (YLOG_LOG, "%sNEW %d %s",
765                      m_session_str, parent->m_seqno, m_proxyTarget);
766             c = new Yaz_ProxyClient(m_PDU_Observable->clone(), parent);
767             c->m_next = parent->m_clientPool;
768             if (c->m_next)
769                 c->m_next->m_prev = &c->m_next;
770             parent->m_clientPool = c;
771             c->m_prev = &parent->m_clientPool;
772         }
773
774         xfree (c->m_cookie);
775         c->m_cookie = 0;
776         if (cookie)
777             c->m_cookie = xstrdup(cookie);
778
779         c->m_seqno = parent->m_seqno;
780         c->m_init_flag = 0;
781         c->m_last_resultCount = 0;
782         c->m_last_ok = 0;
783         c->m_cache.clear();
784         c->m_sr_transform = 0;
785         c->m_waiting = 0;
786         c->m_resultSetStartPoint = 0;
787         (parent->m_seqno)++;
788         if (c->client(m_proxyTarget))
789         {
790             delete c;
791             return 0;
792         }
793         c->m_target_idletime = m_target_idletime;
794         c->timeout(30);
795
796         if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
797             c->set_APDU_yazlog(1);
798         else
799             c->set_APDU_yazlog(0);
800
801         c->set_idAuthentication(apdu);
802     }
803     yaz_log (YLOG_DEBUG, "get_client 3 %p %p", this, c);
804     return c;
805 }
806
807 void Yaz_Proxy::display_diagrecs(Z_DiagRec **pp, int num)
808 {
809     int i;
810     for (i = 0; i<num; i++)
811     {
812         oident *ent;
813         Z_DefaultDiagFormat *r;
814         Z_DiagRec *p = pp[i];
815         if (p->which != Z_DiagRec_defaultFormat)
816         {
817             yaz_log(YLOG_LOG, "%sError no diagnostics", m_session_str);
818             return;
819         }
820         else
821             r = p->u.defaultFormat;
822         if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
823             ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
824             yaz_log(YLOG_LOG, "%sError unknown diagnostic set", m_session_str);
825         switch (r->which)
826         {
827         case Z_DefaultDiagFormat_v2Addinfo:
828             yaz_log(YLOG_LOG, "%sError %d %s:%s",
829                     m_session_str,
830                     *r->condition, diagbib1_str(*r->condition),
831                     r->u.v2Addinfo);
832             break;
833         case Z_DefaultDiagFormat_v3Addinfo:
834             yaz_log(YLOG_LOG, "%sError %d %s:%s",
835                     m_session_str,
836                     *r->condition, diagbib1_str(*r->condition),
837                     r->u.v3Addinfo);
838             break;
839         }
840     }
841 }
842
843 int Yaz_Proxy::convert_xsl(Z_NamePlusRecordList *p, Z_APDU *apdu)
844 {
845     if (!m_stylesheet_xsp || p->num_records <= 0)
846     {
847         return 0;  /* no XSLT to be done ... */
848     }
849
850     m_stylesheet_offset = 0;
851     m_stylesheet_nprl = p;
852     m_stylesheet_apdu = apdu;
853     m_timeout_mode = timeout_xsl;
854
855     timeout(0);
856     return 1;
857 }
858
859 void Yaz_Proxy::convert_xsl_delay()
860 {
861 #if HAVE_XSLT
862     Z_NamePlusRecord *npr = m_stylesheet_nprl->records[m_stylesheet_offset];
863     if (npr->which == Z_NamePlusRecord_databaseRecord)
864     {
865         Z_External *r = npr->u.databaseRecord;
866         if (r->which == Z_External_octet)
867         {
868 #if 0
869             fwrite((char*) r->u.octet_aligned->buf, 1, r->u.octet_aligned->len, stdout);
870 #endif
871             xmlDocPtr res, doc = xmlParseMemory(
872                 (char*) r->u.octet_aligned->buf,
873                 r->u.octet_aligned->len);
874
875
876             yaz_log(YLOG_LOG, "%sXSLT convert %d",
877                     m_session_str, m_stylesheet_offset);
878             res = xsltApplyStylesheet((xsltStylesheetPtr) m_stylesheet_xsp,
879                                       doc, 0);
880
881             if (res)
882             {
883                 xmlChar *out_buf;
884                 int out_len;
885                 xmlDocDumpFormatMemory (res, &out_buf, &out_len, 1);
886
887                 m_stylesheet_nprl->records[m_stylesheet_offset]->
888                     u.databaseRecord =
889                     z_ext_record(odr_encode(), VAL_TEXT_XML,
890                                  (char*) out_buf, out_len);
891                 xmlFree(out_buf);
892                 xmlFreeDoc(res);
893             }
894
895             xmlFreeDoc(doc);
896         }
897     }
898 #endif
899     m_stylesheet_offset++;
900     if (m_stylesheet_offset == m_stylesheet_nprl->num_records)
901     {
902         m_timeout_mode = timeout_normal;
903         m_stylesheet_nprl = 0;
904 #if HAVE_XSLT
905         if (m_stylesheet_xsp)
906             xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
907 #endif
908         m_stylesheet_xsp = 0;
909         timeout(m_client_idletime);
910         send_PDU_convert(m_stylesheet_apdu);
911     }
912     else
913         timeout(0);
914 }
915
916 void Yaz_Proxy::convert_to_frontend_type(Z_NamePlusRecordList *p)
917 {
918     if (m_frontend_type != VAL_NONE)
919     {
920         int i;
921         for (i = 0; i < p->num_records; i++)
922         {
923             Z_NamePlusRecord *npr = p->records[i];
924             if (npr->which == Z_NamePlusRecord_databaseRecord)
925             {
926                 Z_External *r = npr->u.databaseRecord;
927                 if (r->which == Z_External_octet)
928                 {
929 #if HAVE_USEMARCON
930                     if (m_usemarcon_ini_stage1 && *m_usemarcon_ini_stage1)
931                     {
932                         if (!m_usemarcon->m_stage1)
933                         {
934                             m_usemarcon->m_stage1 = new CDetails();
935                         }
936                         m_usemarcon->m_stage1->SetIniFileName(m_usemarcon_ini_stage1);
937                         m_usemarcon->m_stage1->SetMarcRecord((char*) r->u.octet_aligned->buf, r->u.octet_aligned->len);
938                         int res = m_usemarcon->m_stage1->Start();
939                         if (res == 0)
940                         {
941                             char *converted;
942                             int convlen;
943                             m_usemarcon->m_stage1->GetMarcRecord(converted, convlen);
944                             if (m_usemarcon_ini_stage2 && *m_usemarcon_ini_stage2)
945                             {
946                                 if (!m_usemarcon->m_stage2)
947                                 {
948                                     m_usemarcon->m_stage2 = new CDetails();
949                                 }
950                                 m_usemarcon->m_stage2->SetIniFileName(m_usemarcon_ini_stage2);
951                                 m_usemarcon->m_stage2->SetMarcRecord(converted, convlen);
952                                 res = m_usemarcon->m_stage2->Start();
953                                 if (res == 0)
954                                 {
955                                     free(converted);
956                                     m_usemarcon->m_stage2->GetMarcRecord(converted, convlen);
957                                 }
958                                 else
959                                 {
960                                     yaz_log(YLOG_LOG, "%sUSEMARCON stage 2 error %d", m_session_str, res);
961                                 }
962                             }
963                             npr->u.databaseRecord =
964                                 z_ext_record(odr_encode(),
965                                              m_frontend_type,
966                                              converted,
967                                              strlen(converted));
968                             free(converted);
969                         }
970                         else
971                         {
972                             yaz_log(YLOG_LOG, "%sUSEMARCON stage 1 error %d", m_session_str, res);
973                         }
974                         continue;
975                     }
976 #endif
977 /* HAVE_USEMARCON */
978                     npr->u.databaseRecord =
979                         z_ext_record(odr_encode(),
980                                      m_frontend_type,
981                                      (char*) r->u.octet_aligned->buf,
982                                      r->u.octet_aligned->len);
983                 }
984             }
985         }
986     }
987 }
988
989 void Yaz_Proxy::convert_records_charset(Z_NamePlusRecordList *p,
990                                         const char *backend_charset)
991 {
992     yaz_log(YLOG_LOG, "%sconvert_to_marc", m_session_str);
993     int sel =   m_charset_converter->get_client_charset_selected();
994     const char *client_record_charset =
995         m_charset_converter->get_client_query_charset();
996     if (sel && backend_charset && client_record_charset &&
997         strcmp(backend_charset, client_record_charset))
998     {
999         int i;
1000         yaz_iconv_t cd = yaz_iconv_open(client_record_charset,
1001                                         backend_charset);
1002         yaz_marc_t mt = yaz_marc_create();
1003         yaz_marc_xml(mt, YAZ_MARC_ISO2709);
1004         yaz_marc_iconv(mt, cd);
1005         for (i = 0; i < p->num_records; i++)
1006         {
1007             Z_NamePlusRecord *npr = p->records[i];
1008             if (npr->which == Z_NamePlusRecord_databaseRecord)
1009             {
1010                 Z_External *r = npr->u.databaseRecord;
1011                 oident *ent = oid_getentbyoid(r->direct_reference);
1012                 if (!ent || ent->value == VAL_NONE)
1013                     continue;
1014
1015                 if (ent->value == VAL_SUTRS)
1016                 {
1017                     WRBUF w = wrbuf_alloc();
1018
1019                     wrbuf_iconv_write(w, cd,  (char*) r->u.octet_aligned->buf,
1020                                       r->u.octet_aligned->len);
1021                     npr->u.databaseRecord =
1022                         z_ext_record(odr_encode(), ent->value, wrbuf_buf(w),
1023                                      wrbuf_len(w));
1024                     wrbuf_free(w, 1);
1025                 }
1026                 else if (ent->value == VAL_TEXT_XML)
1027                 {
1028                     ;
1029                 }
1030                 else if (r->which == Z_External_octet)
1031                 {
1032                     int rlen;
1033                     char *result;
1034                     if (yaz_marc_decode_buf(mt,
1035                                             (char*) r->u.octet_aligned->buf,
1036                                             r->u.octet_aligned->len,
1037                                             &result, &rlen))
1038                     {
1039                         npr->u.databaseRecord =
1040                             z_ext_record(odr_encode(), ent->value, result, rlen);
1041                         yaz_log(YLOG_LOG, "%sRecoding MARC record",
1042                                 m_session_str);
1043                     }
1044                 }
1045             }
1046         }
1047         if (cd)
1048             yaz_iconv_close(cd);
1049         yaz_marc_destroy(mt);
1050     }
1051     else
1052     {
1053         yaz_log(YLOG_LOG, "%sSkipping marc convert", m_session_str);
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 = 0;
1863
1864     int bw_total = m_bw_stat.get_total();
1865     int pdu_total = m_pdu_stat.get_total();
1866
1867     assert(m_timeout_mode == timeout_busy);
1868     assert(m_timeout_gdu == 0);
1869
1870     if (m_bw_max)
1871     {
1872         if (bw_total > m_bw_max)
1873         {
1874             reduce = (bw_total/m_bw_max);
1875         }
1876     }
1877     if (m_pdu_max)
1878     {
1879         if (pdu_total > m_pdu_max)
1880         {
1881             int nreduce = (m_pdu_max >= 60) ? 1 : 60/m_pdu_max;
1882             reduce = (reduce > nreduce) ? reduce : nreduce;
1883         }
1884     }
1885     m_http_version = 0;
1886
1887 #if 0
1888     /* uncomment to force a big reduce */
1889     m_timeout_mode = timeout_reduce;
1890     m_timeout_gdu = gdu;
1891     timeout(3);       // call us reduce seconds later
1892     return;
1893 #endif
1894     if (reduce)
1895     {
1896         yaz_log(YLOG_LOG, "%sdelay=%d bw=%d pdu=%d limit-bw=%d limit-pdu=%d",
1897                 m_session_str, reduce, bw_total, pdu_total,
1898                 m_bw_max, m_pdu_max);
1899
1900         m_timeout_mode = timeout_reduce;
1901         m_timeout_gdu = gdu;
1902         timeout(reduce);       // call us reduce seconds later
1903     }
1904     else
1905         recv_GDU_normal(gdu);
1906 }
1907
1908 void Yaz_Proxy::recv_GDU_more(bool normal)
1909 {
1910     GDU *g;
1911     if (normal && m_timeout_mode == timeout_busy)
1912         m_timeout_mode = timeout_normal;
1913     while (m_timeout_mode == timeout_normal && (g = m_in_queue.dequeue()))
1914     {
1915         m_timeout_mode = timeout_busy;
1916         recv_GDU_reduce(g);
1917     }
1918 }
1919
1920 void Yaz_Proxy::recv_GDU_normal(GDU *gdu)
1921 {
1922     Z_GDU *apdu = 0;
1923     gdu->move_away_gdu(odr_decode(), &apdu);
1924     delete gdu;
1925
1926     if (apdu->which == Z_GDU_Z3950)
1927         handle_incoming_Z_PDU(apdu->u.z3950);
1928     else if (apdu->which == Z_GDU_HTTP_Request)
1929         handle_incoming_HTTP(apdu->u.HTTP_Request);
1930 }
1931
1932 void Yaz_Proxy::handle_max_record_retrieve(Z_APDU *apdu)
1933 {
1934     if (m_max_record_retrieve)
1935     {
1936         if (apdu->which == Z_APDU_presentRequest)
1937         {
1938             Z_PresentRequest *pr = apdu->u.presentRequest;
1939             if (pr->numberOfRecordsRequested &&
1940                 *pr->numberOfRecordsRequested > m_max_record_retrieve)
1941                 *pr->numberOfRecordsRequested = m_max_record_retrieve;
1942         }
1943     }
1944 }
1945
1946 void Yaz_Proxy::handle_charset_lang_negotiation(Z_APDU *apdu)
1947 {
1948     if (apdu->which == Z_APDU_initRequest)
1949     {
1950         if (m_initRequest_options &&
1951             !ODR_MASK_GET(m_initRequest_options, Z_Options_negotiationModel) &&
1952             (m_proxy_negotiation_charset || m_proxy_negotiation_lang))
1953         {
1954             // There is no negotiation proposal from
1955             // client's side. OK. The proxy negotiation
1956             // in use, only.
1957             Z_InitRequest *initRequest = apdu->u.initRequest;
1958             Z_OtherInformation **otherInfo;
1959             Z_OtherInformationUnit *oi;
1960             get_otherInfoAPDU(apdu, &otherInfo);
1961             oi = update_otherInformation(otherInfo, 1, NULL, 0, 0);
1962             if (oi)
1963             {
1964                 ODR_MASK_SET(initRequest->options,
1965                     Z_Options_negotiationModel);
1966                 oi->which = Z_OtherInfo_externallyDefinedInfo;
1967                 oi->information.externallyDefinedInfo =
1968                 yaz_set_proposal_charneg(odr_encode(),
1969                     (const char**)&m_proxy_negotiation_charset,
1970                     m_proxy_negotiation_charset ? 1:0,
1971                     (const char**)&m_proxy_negotiation_lang,
1972                     m_proxy_negotiation_lang ? 1:0,
1973                     1);
1974             }
1975         }
1976         else if (m_initRequest_options &&
1977                  ODR_MASK_GET(m_initRequest_options,
1978                               Z_Options_negotiationModel) &&
1979                  m_charset_converter->get_target_query_charset())
1980         {
1981             yaz_log(YLOG_LOG, "%sManaged charset negotiation: charset=%s",
1982                     m_session_str,
1983                     m_charset_converter->get_target_query_charset());
1984             Z_InitRequest *initRequest = apdu->u.initRequest;
1985             Z_CharSetandLanguageNegotiation *negotiation =
1986                 yaz_get_charneg_record (initRequest->otherInfo);
1987             if (negotiation &&
1988                 negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
1989             {
1990                 NMEM nmem = nmem_create();
1991                 char **charsets = 0;
1992                 int num_charsets = 0;
1993                 char **langs = 0;
1994                 int num_langs = 0;
1995                 int selected = 0;
1996                 yaz_get_proposal_charneg (nmem, negotiation,
1997                                           &charsets, &num_charsets,
1998                                           &langs, &num_langs, &selected);
1999                 int i;
2000                 for (i = 0; i<num_charsets; i++)
2001                     yaz_log(YLOG_LOG, "%scharset %s", m_session_str,
2002                             charsets[i]);
2003                 for (i = 0; i<num_langs; i++)
2004                     yaz_log(YLOG_LOG, "%slang %s", m_session_str,
2005                             langs[i]);
2006
2007                 const char *t_charset =
2008                     m_charset_converter->get_target_query_charset();
2009                 // sweep through charsets and pick the first supported
2010                 // conversion
2011                 for (i = 0; i<num_charsets; i++)
2012                 {
2013                     const char *c_charset = charsets[i];
2014                     if (!odr_set_charset(odr_decode(), t_charset, c_charset))
2015                         break;
2016                 }
2017                 if (i != num_charsets)
2018                 {
2019                     // got one .. set up ODR for reverse direction
2020                     const char *c_charset = charsets[i];
2021                     odr_set_charset(odr_encode(), c_charset, t_charset);
2022                     m_charset_converter->set_client_query_charset(c_charset);
2023                     m_charset_converter->set_client_charset_selected(selected);
2024                 }
2025                 nmem_destroy(nmem);
2026                 ODR_MASK_CLEAR(m_initRequest_options,
2027                                Z_Options_negotiationModel);
2028                 yaz_del_charneg_record(&initRequest->otherInfo);
2029             }
2030             else
2031             {
2032                 yaz_log(YLOG_WARN, "%sUnable to decode charset package",
2033                         m_session_str);
2034             }
2035         }
2036         else if (m_charset_converter->get_target_query_charset() &&
2037             m_proxy_negotiation_default_charset)
2038         {
2039             m_charset_converter->
2040                 set_client_query_charset(m_proxy_negotiation_default_charset);
2041         }
2042     }
2043     else if (apdu->which == Z_APDU_initResponse)
2044     {
2045         Z_InitResponse *initResponse = apdu->u.initResponse;
2046         Z_OtherInformation **otherInfo;
2047         get_otherInfoAPDU(apdu, &otherInfo);
2048         
2049         Z_CharSetandLanguageNegotiation *charneg = 0;
2050
2051         if (otherInfo && *otherInfo && 
2052             ODR_MASK_GET(initResponse->options, Z_Options_negotiationModel)
2053             && (charneg = yaz_get_charneg_record(*otherInfo)))
2054         {
2055             char *charset = 0;
2056             char *lang = 0;
2057             int selected = 0;
2058
2059             yaz_get_response_charneg(m_referenceId_mem, charneg,
2060                 &charset, &lang, &selected);
2061
2062             yaz_log(YLOG_LOG, "%sAccepted charset - '%s' and lang - '%s'",
2063                 m_session_str, (charset)?charset:"none", (lang)?lang:"none");
2064
2065             if (m_initRequest_options &&
2066                 ODR_MASK_GET(m_initRequest_options, Z_Options_negotiationModel))
2067             {
2068                 yaz_log(YLOG_LOG, "%sClient's negotiation record in use",
2069                     m_session_str);
2070             }
2071             else if (m_proxy_negotiation_charset || m_proxy_negotiation_lang)
2072             {
2073                 // negotiation-charset, negotiation-lang
2074                 // elements of config file in use.
2075
2076                 yaz_log(YLOG_LOG, "%sProxy's negotiation record in use",
2077                     m_session_str);
2078
2079                 // clear negotiation option.
2080                 ODR_MASK_CLEAR(initResponse->options, Z_Options_negotiationModel);
2081
2082                 // Delete negotiation (charneg-3) entry.
2083                 yaz_del_charneg_record(otherInfo);
2084             }
2085         }
2086         else
2087         {
2088             if (m_proxy_negotiation_charset || m_proxy_negotiation_lang)
2089             {
2090                 yaz_log(YLOG_LOG, "%sTarget did not honor negotiation",
2091                         m_session_str);
2092             }
2093             else if (m_charset_converter->get_client_query_charset())
2094             {
2095                 Z_OtherInformation **otherInfo;
2096                 Z_OtherInformationUnit *oi;
2097                 get_otherInfoAPDU(apdu, &otherInfo);
2098                 oi = update_otherInformation(otherInfo, 1, NULL, 0, 0);
2099                 if (oi)
2100                 {
2101                     ODR_MASK_SET(initResponse->options,
2102                                  Z_Options_negotiationModel);
2103                     if (m_initRequest_options)
2104                         ODR_MASK_SET(m_initRequest_options,
2105                                      Z_Options_negotiationModel);
2106                     
2107                     oi->which = Z_OtherInfo_externallyDefinedInfo;    
2108                     oi->information.externallyDefinedInfo =
2109                         yaz_set_response_charneg(
2110                             odr_encode(),
2111                             m_charset_converter->get_client_query_charset(),
2112                             0 /* no lang */,
2113                             m_charset_converter->get_client_charset_selected());
2114                 }
2115             }
2116         }
2117     }
2118 }
2119
2120 Z_Records *Yaz_Proxy::create_nonSurrogateDiagnostics(ODR odr,
2121                                                      int error,
2122                                                      const char *addinfo)
2123 {
2124     Z_Records *rec = (Z_Records *)
2125         odr_malloc (odr, sizeof(*rec));
2126     int *err = (int *)
2127         odr_malloc (odr, sizeof(*err));
2128     Z_DiagRec *drec = (Z_DiagRec *)
2129         odr_malloc (odr, sizeof(*drec));
2130     Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
2131         odr_malloc (odr, sizeof(*dr));
2132     *err = error;
2133     rec->which = Z_Records_NSD;
2134     rec->u.nonSurrogateDiagnostic = dr;
2135     dr->diagnosticSetId =
2136         yaz_oidval_to_z3950oid (odr, CLASS_DIAGSET, VAL_BIB1);
2137     dr->condition = err;
2138     dr->which = Z_DefaultDiagFormat_v2Addinfo;
2139     dr->u.v2Addinfo = odr_strdup (odr, addinfo ? addinfo : "");
2140     return rec;
2141 }
2142
2143 Z_APDU *Yaz_Proxy::handle_query_transformation(Z_APDU *apdu)
2144 {
2145     if (apdu->which == Z_APDU_searchRequest &&
2146         apdu->u.searchRequest->query &&
2147         apdu->u.searchRequest->query->which == Z_Query_type_104 &&
2148         apdu->u.searchRequest->query->u.type_104->which == Z_External_CQL)
2149     {
2150         Z_RPNQuery *rpnquery = 0;
2151         Z_SearchRequest *sr = apdu->u.searchRequest;
2152         char *addinfo = 0;
2153
2154         yaz_log(YLOG_LOG, "%sCQL: %s", m_session_str,
2155                 sr->query->u.type_104->u.cql);
2156
2157         int r = m_cql2rpn.query_transform(sr->query->u.type_104->u.cql,
2158                                           &rpnquery, odr_encode(),
2159                                           &addinfo);
2160         if (r == -3)
2161             yaz_log(YLOG_LOG, "%sNo CQL to RPN table", m_session_str);
2162         else if (r)
2163         {
2164             yaz_log(YLOG_LOG, "%sCQL Conversion error %d", m_session_str, r);
2165             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2166
2167             new_apdu->u.searchResponse->referenceId = sr->referenceId;
2168             new_apdu->u.searchResponse->records =
2169                 create_nonSurrogateDiagnostics(odr_encode(),
2170                                                yaz_diag_srw_to_bib1(r),
2171                                                addinfo);
2172             *new_apdu->u.searchResponse->searchStatus = 0;
2173
2174             send_to_client(new_apdu);
2175
2176             return 0;
2177         }
2178         else
2179         {
2180             sr->query->which = Z_Query_type_1;
2181             sr->query->u.type_1 = rpnquery;
2182         }
2183         return apdu;
2184     }
2185     return apdu;
2186 }
2187
2188 Z_APDU *Yaz_Proxy::handle_target_charset_conversion(Z_APDU *apdu)
2189 {
2190     if (apdu->which == Z_APDU_searchRequest &&
2191         apdu->u.searchRequest->query)
2192     {
2193         if (apdu->u.searchRequest->query->which == Z_Query_type_1
2194             || apdu->u.searchRequest->query->which == Z_Query_type_101)
2195         {
2196             if (m_http_version)
2197                 m_charset_converter->set_client_query_charset("UTF-8");
2198             Z_RPNQuery *rpnquery = apdu->u.searchRequest->query->u.type_1;
2199             m_charset_converter->convert_type_1(rpnquery, odr_encode());
2200         }
2201     }
2202     return apdu;
2203 }
2204
2205
2206 Z_APDU *Yaz_Proxy::handle_query_validation(Z_APDU *apdu)
2207 {
2208     if (apdu->which == Z_APDU_searchRequest)
2209     {
2210         Z_SearchRequest *sr = apdu->u.searchRequest;
2211         int err = 0;
2212         char *addinfo = 0;
2213
2214         Yaz_ProxyConfig *cfg = check_reconfigure();
2215         if (cfg)
2216             err = cfg->check_query(odr_encode(), m_default_target,
2217                                    sr->query, &addinfo);
2218         if (err)
2219         {
2220             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2221
2222             new_apdu->u.searchResponse->referenceId = sr->referenceId;
2223             new_apdu->u.searchResponse->records =
2224                 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
2225             *new_apdu->u.searchResponse->searchStatus = 0;
2226
2227             send_to_client(new_apdu);
2228
2229             return 0;
2230         }
2231     }
2232     return apdu;
2233 }
2234
2235 int Yaz_Proxy::handle_authentication(Z_APDU *apdu)
2236 {
2237     if (apdu->which != Z_APDU_initRequest)
2238         return 1;  // pass if no init request
2239     Z_InitRequest *req = apdu->u.initRequest;
2240
2241     Yaz_ProxyConfig *cfg = check_reconfigure();
2242     if (!cfg)
2243         return 1;  // pass if no config
2244
2245     int ret;
2246     if (req->idAuthentication == 0)
2247     {
2248         ret = cfg->client_authentication(m_default_target, 0, 0, 0,
2249                                          m_peername);
2250     }
2251     else if (req->idAuthentication->which == Z_IdAuthentication_idPass)
2252     {
2253         ret = cfg->client_authentication(
2254             m_default_target,
2255             req->idAuthentication->u.idPass->userId,
2256             req->idAuthentication->u.idPass->groupId,
2257             req->idAuthentication->u.idPass->password,
2258             m_peername);
2259     }
2260     else if (req->idAuthentication->which == Z_IdAuthentication_open)
2261     {
2262         char user[64], pass[64];
2263         *user = '\0';
2264         *pass = '\0';
2265         sscanf(req->idAuthentication->u.open, "%63[^/]/%63s", user, pass);
2266         ret = cfg->client_authentication(m_default_target, user, 0, pass,
2267                                          m_peername);
2268     }
2269     else
2270         ret = cfg->client_authentication(m_default_target, 0, 0, 0,
2271                                          m_peername);
2272     return ret;
2273 }
2274
2275 Z_APDU *Yaz_Proxy::handle_syntax_validation(Z_APDU *apdu)
2276 {
2277     m_marcxml_mode = none;
2278     if (apdu->which == Z_APDU_searchRequest)
2279     {
2280         Z_SearchRequest *sr = apdu->u.searchRequest;
2281         int err = 0;
2282         char *addinfo = 0;
2283         Yaz_ProxyConfig *cfg = check_reconfigure();
2284
2285         Z_RecordComposition rc_temp, *rc = 0;
2286         if (sr->smallSetElementSetNames)
2287         {
2288             rc_temp.which = Z_RecordComp_simple;
2289             rc_temp.u.simple = sr->smallSetElementSetNames;
2290             rc = &rc_temp;
2291         }
2292
2293         if (sr->preferredRecordSyntax)
2294         {
2295             struct oident *ent;
2296             ent = oid_getentbyoid(sr->preferredRecordSyntax);
2297             m_frontend_type = ent->value;
2298         }
2299         else
2300             m_frontend_type = VAL_NONE;
2301
2302         char *stylesheet_name = 0;
2303         if (cfg)
2304             err = cfg->check_syntax(odr_encode(),
2305                                     m_default_target,
2306                                     sr->preferredRecordSyntax, rc,
2307                                     &addinfo, &stylesheet_name, &m_schema,
2308                                     &m_backend_type, &m_backend_charset,
2309                                     &m_usemarcon_ini_stage1,
2310                                     &m_usemarcon_ini_stage2);
2311         if (stylesheet_name)
2312         {
2313             m_parent->low_socket_close();
2314
2315 #if HAVE_XSLT
2316             if (m_stylesheet_xsp)
2317                 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
2318             m_stylesheet_xsp = xsltParseStylesheetFile((const xmlChar*)
2319                                                        stylesheet_name);
2320 #endif
2321             m_stylesheet_offset = 0;
2322             xfree(stylesheet_name);
2323
2324             m_parent->low_socket_open();
2325         }
2326         if (err == -1)
2327         {
2328             sr->smallSetElementSetNames = 0;
2329             sr->mediumSetElementSetNames = 0;
2330             m_marcxml_mode = marcxml;
2331             if (m_backend_type)
2332             {
2333
2334                 sr->preferredRecordSyntax =
2335                     yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN,
2336                                         m_backend_type);
2337             }
2338             else
2339                 sr->preferredRecordSyntax =
2340                     yaz_oidval_to_z3950oid(odr_encode(), CLASS_RECSYN,
2341                                            VAL_USMARC);
2342         }
2343         else if (err)
2344         {
2345             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2346
2347             new_apdu->u.searchResponse->referenceId = sr->referenceId;
2348             new_apdu->u.searchResponse->records =
2349                 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
2350             *new_apdu->u.searchResponse->searchStatus = 0;
2351
2352             send_to_client(new_apdu);
2353
2354             return 0;
2355         }
2356         else if (m_backend_type)
2357         {
2358             sr->preferredRecordSyntax =
2359                 yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN, m_backend_type);
2360         }
2361     }
2362     else if (apdu->which == Z_APDU_presentRequest)
2363     {
2364         Z_PresentRequest *pr = apdu->u.presentRequest;
2365         int err = 0;
2366         char *addinfo = 0;
2367         Yaz_ProxyConfig *cfg = check_reconfigure();
2368
2369         if (pr->preferredRecordSyntax)
2370         {
2371             struct oident *ent;
2372             ent = oid_getentbyoid(pr->preferredRecordSyntax);
2373             m_frontend_type = ent->value;
2374         }
2375         else
2376             m_frontend_type = VAL_NONE;
2377
2378         char *stylesheet_name = 0;
2379         if (cfg)
2380             err = cfg->check_syntax(odr_encode(), m_default_target,
2381                                     pr->preferredRecordSyntax,
2382                                     pr->recordComposition,
2383                                     &addinfo, &stylesheet_name, &m_schema,
2384                                     &m_backend_type, &m_backend_charset,
2385                                     &m_usemarcon_ini_stage1,
2386                                     &m_usemarcon_ini_stage2
2387                                     );
2388         if (stylesheet_name)
2389         {
2390             m_parent->low_socket_close();
2391
2392 #if HAVE_XSLT
2393             if (m_stylesheet_xsp)
2394                 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
2395             m_stylesheet_xsp = xsltParseStylesheetFile((const xmlChar*)
2396                                                        stylesheet_name);
2397 #endif
2398             m_stylesheet_offset = 0;
2399             xfree(stylesheet_name);
2400
2401             m_parent->low_socket_open();
2402         }
2403         if (err == -1)
2404         {
2405             pr->recordComposition = 0;
2406             m_marcxml_mode = marcxml;
2407             if (m_backend_type)
2408             {
2409
2410                 pr->preferredRecordSyntax =
2411                     yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN,
2412                                         m_backend_type);
2413             }
2414             else
2415                 pr->preferredRecordSyntax =
2416                     yaz_oidval_to_z3950oid(odr_encode(), CLASS_RECSYN,
2417                                            VAL_USMARC);
2418         }
2419         else if (err)
2420         {
2421             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
2422
2423             new_apdu->u.presentResponse->referenceId = pr->referenceId;
2424             new_apdu->u.presentResponse->records =
2425                 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
2426             *new_apdu->u.presentResponse->presentStatus =
2427                 Z_PresentStatus_failure;
2428
2429             send_to_client(new_apdu);
2430
2431             return 0;
2432         }
2433         else if (m_backend_type)
2434         {
2435             pr->preferredRecordSyntax =
2436                 yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN, m_backend_type);
2437         }
2438     }
2439     return apdu;
2440 }
2441
2442 Z_ElementSetNames *Yaz_Proxy::mk_esn_from_schema(ODR o, const char *schema)
2443 {
2444     if (!schema)
2445         return 0;
2446     Z_ElementSetNames *esn = (Z_ElementSetNames *)
2447         odr_malloc(o, sizeof(Z_ElementSetNames));
2448     esn->which = Z_ElementSetNames_generic;
2449     esn->u.generic = odr_strdup(o, schema);
2450     return esn;
2451 }
2452
2453 void Yaz_Proxy::srw_get_client(const char *db, const char **backend_db)
2454 {
2455     const char *t = 0;
2456     Yaz_ProxyConfig *cfg = check_reconfigure();
2457     if (cfg)
2458         t = cfg->get_explain_name(db, backend_db);
2459
2460     if (m_client && m_default_target && t && strcmp(m_default_target, t))
2461     {
2462         releaseClient();
2463     }
2464
2465     if (t)
2466     {
2467         xfree(m_default_target);
2468         m_default_target = xstrdup(t);
2469     }
2470 }
2471
2472 int Yaz_Proxy::file_access(Z_HTTP_Request *hreq)
2473 {
2474     struct stat sbuf;
2475     if (strcmp(hreq->method, "GET"))
2476         return 0;
2477     if (hreq->path[0] != '/')
2478     {
2479         yaz_log(YLOG_WARN, "Bad path: %s", hreq->path);
2480         return 0;
2481     }
2482     const char *cp = hreq->path;
2483     while (*cp)
2484     {
2485         if (*cp == '/' && strchr("/.", cp[1]))
2486         {
2487             yaz_log(YLOG_WARN, "Bad path: %s", hreq->path);
2488             return 0;
2489         }
2490         cp++;
2491     }
2492     const char *fname = hreq->path+1;
2493     if (stat(fname, &sbuf))
2494     {
2495         yaz_log(YLOG_WARN|YLOG_ERRNO, "%s: stat failed", fname);
2496         return 0;
2497     }
2498     if ((sbuf.st_mode & S_IFMT) != S_IFREG)
2499     {
2500         yaz_log(YLOG_WARN, "%s: not a regular file", fname);
2501         return 0;
2502     }
2503     if (sbuf.st_size > (off_t) 1000000)
2504     {
2505         yaz_log(YLOG_WARN, "%s: too large for transfer", fname);
2506         return 0;
2507     }
2508
2509     ODR o = odr_encode();
2510     Yaz_ProxyConfig *cfg = check_reconfigure();
2511     const char *ctype = cfg->check_mime_type(fname);
2512     Z_GDU *gdu = z_get_HTTP_Response(o, 200);
2513     Z_HTTP_Response *hres = gdu->u.HTTP_Response;
2514     if (m_http_version)
2515         hres->version = odr_strdup(o, m_http_version);
2516     z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
2517     if (m_http_keepalive)
2518         z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
2519     else
2520         timeout(0);
2521
2522     hres->content_len = sbuf.st_size;
2523     hres->content_buf = (char*) odr_malloc(o, hres->content_len);
2524     FILE *f = fopen(fname, "rb");
2525     if (f)
2526     {
2527         fread(hres->content_buf, 1, hres->content_len, f);
2528         fclose(f);
2529     }
2530     else
2531     {
2532         return 0;
2533     }
2534     if (m_log_mask & PROXY_LOG_REQ_CLIENT)
2535     {
2536         yaz_log (YLOG_LOG, "%sSending file %s to client", m_session_str,
2537                  fname);
2538     }
2539     int len;
2540     send_GDU(gdu, &len);
2541     recv_GDU_more(true);
2542     return 1;
2543 }
2544
2545 void Yaz_Proxy::handle_incoming_HTTP(Z_HTTP_Request *hreq)
2546 {
2547     if (m_s2z_odr_init)
2548     {
2549         odr_destroy(m_s2z_odr_init);
2550         m_s2z_odr_init = 0;
2551     }
2552     if (m_s2z_odr_search)
2553     {
2554         odr_destroy(m_s2z_odr_search);
2555         m_s2z_odr_search = 0;
2556     }
2557
2558     m_http_keepalive = 0;
2559     m_http_version = 0;
2560     if (!strcmp(hreq->version, "1.0"))
2561     {
2562         const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
2563         if (v && !strcmp(v, "Keep-Alive"))
2564             m_http_keepalive = 1;
2565         else
2566             m_http_keepalive = 0;
2567         m_http_version = "1.0";
2568     }
2569     else
2570     {
2571         const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
2572         if (v && !strcmp(v, "close"))
2573             m_http_keepalive = 0;
2574         else
2575             m_http_keepalive = 1;
2576         m_http_version = "1.1";
2577     }
2578
2579     const char *a = z_HTTP_header_lookup(hreq->headers, "Authorization");
2580     char authorization_str[255];
2581     *authorization_str = '\0';
2582     if (a && strncasecmp(a, "Basic ", 6) == 0)
2583         base64_decode(a + 6, authorization_str, 254);
2584
2585     Z_SRW_PDU *srw_pdu = 0;
2586     Z_SOAP *soap_package = 0;
2587     char *charset = 0;
2588     Z_SRW_diagnostic *diagnostic = 0;
2589     int num_diagnostic = 0;
2590
2591     if (file_access(hreq))
2592     {
2593         return;
2594     }
2595     else if (yaz_srw_decode(hreq, &srw_pdu, &soap_package, odr_decode(),
2596                             &charset) == 0
2597              || yaz_sru_decode(hreq, &srw_pdu, &soap_package, odr_decode(),
2598                                &charset, &diagnostic, &num_diagnostic) == 0)
2599     {
2600         m_s2z_odr_init = odr_createmem(ODR_ENCODE);
2601         m_s2z_odr_search = odr_createmem(ODR_ENCODE);
2602         m_soap_ns = odr_strdup(m_s2z_odr_search, soap_package->ns);
2603         m_s2z_init_apdu = 0;
2604         m_s2z_search_apdu = 0;
2605         m_s2z_present_apdu = 0;
2606
2607         m_s2z_stylesheet = 0;
2608
2609         Z_IdAuthentication *auth = NULL;
2610         if (*authorization_str)
2611         {
2612             auth = (Z_IdAuthentication *) odr_malloc(m_s2z_odr_init, sizeof(Z_IdAuthentication));
2613             auth->which = Z_IdAuthentication_idPass;
2614             auth->u.idPass = (Z_IdPass *) odr_malloc(m_s2z_odr_init, sizeof(Z_IdPass));
2615             auth->u.idPass->groupId = NULL;
2616             char *p = strchr(authorization_str, ':');
2617             if (p)
2618             {
2619                 *p = '\0';
2620                 p++;
2621                 auth->u.idPass->password = odr_strdup(m_s2z_odr_init, p);
2622             }
2623             auth->u.idPass->userId = odr_strdup(m_s2z_odr_init, authorization_str);
2624         }
2625
2626         if (srw_pdu->which == Z_SRW_searchRetrieve_request)
2627         {
2628             Z_SRW_searchRetrieveRequest *srw_req = srw_pdu->u.request;
2629
2630             const char *backend_db = srw_req->database;
2631             srw_get_client(srw_req->database, &backend_db);
2632
2633             m_s2z_database = odr_strdup(m_s2z_odr_init, srw_req->database);
2634             // recordXPath unsupported.
2635             if (srw_req->recordXPath)
2636             {
2637                 yaz_add_srw_diagnostic(odr_decode(),
2638                                        &diagnostic, &num_diagnostic,
2639                                        72, 0);
2640             }
2641             // sort unsupported
2642             if (srw_req->sort_type != Z_SRW_sort_type_none)
2643             {
2644                 yaz_add_srw_diagnostic(odr_decode(),
2645                                        &diagnostic, &num_diagnostic,
2646                                        80, 0);
2647             }
2648             // save stylesheet
2649             if (srw_req->stylesheet)
2650                 m_s2z_stylesheet =
2651                     odr_strdup(m_s2z_odr_init, srw_req->stylesheet);
2652
2653             // set packing for response records ..
2654             if (srw_req->recordPacking &&
2655                 !strcmp(srw_req->recordPacking, "xml"))
2656                 m_s2z_packing = Z_SRW_recordPacking_XML;
2657             else
2658                 m_s2z_packing = Z_SRW_recordPacking_string;
2659
2660             if (num_diagnostic)
2661             {
2662                 Z_SRW_PDU *srw_pdu =
2663                     yaz_srw_get(odr_encode(),
2664                                 Z_SRW_searchRetrieve_response);
2665                 Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
2666
2667                 srw_res->diagnostics = diagnostic;
2668                 srw_res->num_diagnostics = num_diagnostic;
2669                 send_srw_response(srw_pdu);
2670                 return;
2671             }
2672
2673             // prepare search PDU
2674             m_s2z_search_apdu = zget_APDU(m_s2z_odr_search,
2675                                           Z_APDU_searchRequest);
2676             Z_SearchRequest *z_searchRequest =
2677                 m_s2z_search_apdu->u.searchRequest;
2678
2679             z_searchRequest->num_databaseNames = 1;
2680             z_searchRequest->databaseNames = (char**)
2681                 odr_malloc(m_s2z_odr_search, sizeof(char *));
2682             z_searchRequest->databaseNames[0] = odr_strdup(m_s2z_odr_search,
2683                                                            backend_db);
2684
2685             // query transformation
2686             Z_Query *query = (Z_Query *)
2687                 odr_malloc(m_s2z_odr_search, sizeof(Z_Query));
2688             z_searchRequest->query = query;
2689
2690             if (srw_req->query_type == Z_SRW_query_type_cql)
2691             {
2692                 Z_External *ext = (Z_External *)
2693                     odr_malloc(m_s2z_odr_search, sizeof(*ext));
2694                 ext->direct_reference =
2695                     odr_getoidbystr(m_s2z_odr_search, "1.2.840.10003.16.2");
2696                 ext->indirect_reference = 0;
2697                 ext->descriptor = 0;
2698                 ext->which = Z_External_CQL;
2699                 ext->u.cql = srw_req->query.cql;
2700
2701                 query->which = Z_Query_type_104;
2702                 query->u.type_104 =  ext;
2703             }
2704             else if (srw_req->query_type == Z_SRW_query_type_pqf)
2705             {
2706                 Z_RPNQuery *RPNquery;
2707                 YAZ_PQF_Parser pqf_parser;
2708
2709                 pqf_parser = yaz_pqf_create ();
2710
2711                 RPNquery = yaz_pqf_parse (pqf_parser, m_s2z_odr_search,
2712                                           srw_req->query.pqf);
2713                 if (!RPNquery)
2714                 {
2715                     const char *pqf_msg;
2716                     size_t off;
2717                     int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2718                     int ioff = off;
2719                     yaz_log(YLOG_LOG, "%*s^\n", ioff+4, "");
2720                     yaz_log(YLOG_LOG, "Bad PQF: %s (code %d)\n", pqf_msg, code);
2721
2722                     send_to_srw_client_error(10, 0);
2723                     return;
2724                 }
2725                 query->which = Z_Query_type_1;
2726                 query->u.type_1 =  RPNquery;
2727
2728                 yaz_pqf_destroy (pqf_parser);
2729             }
2730             else
2731             {
2732                 send_to_srw_client_error(7, "query");
2733                 return;
2734             }
2735
2736             // present
2737             m_s2z_present_apdu = 0;
2738             int max = 0;
2739             if (srw_req->maximumRecords)
2740                 max = *srw_req->maximumRecords;
2741             int start = 1;
2742             if (srw_req->startRecord)
2743                 start = *srw_req->startRecord;
2744             if (max > 0)
2745             {
2746                 // Some backend, such as Voyager doesn't honor piggyback
2747                 // So we use present always (0 &&).
2748                 if (0 && start <= 1)  // Z39.50 piggyback
2749                 {
2750                     *z_searchRequest->smallSetUpperBound = max;
2751                     *z_searchRequest->mediumSetPresentNumber = max;
2752                     *z_searchRequest->largeSetLowerBound = 2000000000; // 2e9
2753
2754                     z_searchRequest->preferredRecordSyntax =
2755                         yaz_oidval_to_z3950oid(m_s2z_odr_search, CLASS_RECSYN,
2756                                                VAL_TEXT_XML);
2757                     if (srw_req->recordSchema)
2758                     {
2759                         z_searchRequest->smallSetElementSetNames =
2760                             z_searchRequest->mediumSetElementSetNames =
2761                             mk_esn_from_schema(m_s2z_odr_search,
2762                                                srw_req->recordSchema);
2763                     }
2764                 }
2765                 else   // Z39.50 present
2766                 {
2767                     m_s2z_present_apdu = zget_APDU(m_s2z_odr_search,
2768                                                    Z_APDU_presentRequest);
2769                     Z_PresentRequest *z_presentRequest =
2770                         m_s2z_present_apdu->u.presentRequest;
2771                     *z_presentRequest->resultSetStartPoint = start;
2772                     *z_presentRequest->numberOfRecordsRequested = max;
2773                     z_presentRequest->preferredRecordSyntax =
2774                         yaz_oidval_to_z3950oid(m_s2z_odr_search, CLASS_RECSYN,
2775                                                VAL_TEXT_XML);
2776                     if (srw_req->recordSchema)
2777                     {
2778                         z_presentRequest->recordComposition =
2779                             (Z_RecordComposition *)
2780                             odr_malloc(m_s2z_odr_search,
2781                                        sizeof(Z_RecordComposition));
2782                         z_presentRequest->recordComposition->which =
2783                             Z_RecordComp_simple;
2784                         z_presentRequest->recordComposition->u.simple =
2785                             mk_esn_from_schema(m_s2z_odr_search,
2786                                                srw_req->recordSchema);
2787                     }
2788                 }
2789             }
2790             if (!m_client)
2791             {
2792                 m_s2z_init_apdu = zget_APDU(m_s2z_odr_init,
2793                                             Z_APDU_initRequest);
2794
2795                 m_s2z_init_apdu->u.initRequest->idAuthentication = auth;
2796
2797                 // prevent m_initRequest_apdu memory from being grabbed
2798                 // in Yaz_Proxy::handle_incoming_Z_PDU
2799                 m_initRequest_apdu = m_s2z_init_apdu;
2800                 handle_incoming_Z_PDU(m_s2z_init_apdu);
2801                 return;
2802             }
2803             else
2804             {
2805                 handle_incoming_Z_PDU(m_s2z_search_apdu);
2806                 return;
2807             }
2808         }
2809         else if (srw_pdu->which == Z_SRW_explain_request)
2810         {
2811             Z_SRW_explainRequest *srw_req = srw_pdu->u.explain_request;
2812
2813             const char *backend_db = srw_req->database;
2814             srw_get_client(srw_req->database, &backend_db);
2815
2816             m_s2z_database = odr_strdup(m_s2z_odr_init, srw_req->database);
2817
2818             // save stylesheet
2819             if (srw_req->stylesheet)
2820                 m_s2z_stylesheet =
2821                     odr_strdup(m_s2z_odr_init, srw_req->stylesheet);
2822
2823             if (srw_req->recordPacking &&
2824                 !strcmp(srw_req->recordPacking, "xml"))
2825                 m_s2z_packing = Z_SRW_recordPacking_XML;
2826             else
2827                 m_s2z_packing = Z_SRW_recordPacking_string;
2828
2829             if (num_diagnostic)
2830             {
2831                 send_srw_explain_response(diagnostic, num_diagnostic);
2832                 return;
2833             }
2834
2835             if (!m_client)
2836             {
2837                 m_s2z_init_apdu = zget_APDU(m_s2z_odr_init,
2838                                             Z_APDU_initRequest);
2839
2840                 m_s2z_init_apdu->u.initRequest->idAuthentication = auth;
2841                 
2842                 // prevent m_initRequest_apdu memory from being grabbed
2843                 // in Yaz_Proxy::handle_incoming_Z_PDU
2844                 m_initRequest_apdu = m_s2z_init_apdu;
2845                 handle_incoming_Z_PDU(m_s2z_init_apdu);
2846             }
2847             else
2848                 send_srw_explain_response(0, 0);
2849             return;
2850         }
2851         else if (srw_pdu->which == Z_SRW_scan_request)
2852         {
2853             m_s2z_database = odr_strdup(m_s2z_odr_init,
2854                                         srw_pdu->u.scan_request->database);
2855
2856             yaz_add_srw_diagnostic(odr_decode(),
2857                                    &diagnostic, &num_diagnostic,
2858                                    4, "scan");
2859             Z_SRW_PDU *srw_pdu =
2860                 yaz_srw_get(odr_encode(),
2861                             Z_SRW_scan_response);
2862             Z_SRW_scanResponse *srw_res = srw_pdu->u.scan_response;
2863
2864             srw_res->diagnostics = diagnostic;
2865             srw_res->num_diagnostics = num_diagnostic;
2866             send_srw_response(srw_pdu);
2867             return;
2868         }
2869         else
2870         {
2871             m_s2z_database = 0;
2872
2873             send_to_srw_client_error(4, 0);
2874         }
2875     }
2876     send_http_response(400);
2877 }
2878
2879 void Yaz_Proxy::handle_init(Z_APDU *apdu)
2880 {
2881
2882     Z_OtherInformation **oi;
2883     get_otherInfoAPDU(apdu, &oi);
2884
2885     if (apdu->u.initRequest->implementationId)
2886         yaz_log(YLOG_LOG, "%simplementationId: %s",
2887                 m_session_str, apdu->u.initRequest->implementationId);
2888     if (apdu->u.initRequest->implementationName)
2889         yaz_log(YLOG_LOG, "%simplementationName: %s",
2890                 m_session_str, apdu->u.initRequest->implementationName);
2891     if (apdu->u.initRequest->implementationVersion)
2892         yaz_log(YLOG_LOG, "%simplementationVersion: %s",
2893                 m_session_str, apdu->u.initRequest->implementationVersion);
2894     if (m_initRequest_apdu == 0)
2895     {
2896         if (m_initRequest_mem)
2897             nmem_destroy(m_initRequest_mem);
2898
2899         m_initRequest_apdu = apdu;
2900         m_initRequest_mem = odr_extract_mem(odr_decode());
2901
2902         m_initRequest_preferredMessageSize = *apdu->u.initRequest->
2903             preferredMessageSize;
2904         *apdu->u.initRequest->preferredMessageSize = 1024*1024;
2905         m_initRequest_maximumRecordSize = *apdu->u.initRequest->
2906             maximumRecordSize;
2907         *apdu->u.initRequest->maximumRecordSize = 1024*1024;
2908
2909         Z_CharSetandLanguageNegotiation *charSetandLangRecord =
2910             yaz_get_charneg_record(*oi);
2911
2912         // Save proposal charsets and langs.
2913         if (ODR_MASK_GET(apdu->u.initRequest->options,
2914                          Z_Options_negotiationModel)
2915             && charSetandLangRecord)
2916         {
2917
2918             yaz_get_proposal_charneg(m_referenceId_mem,
2919                                      charSetandLangRecord,
2920                                      &m_initRequest_oi_negotiation_charsets,
2921                                      &m_initRequest_oi_negotiation_num_charsets,
2922                                      &m_initRequest_oi_negotiation_langs,
2923                                      &m_initRequest_oi_negotiation_num_langs,
2924                                      &m_initRequest_oi_negotiation_selected);
2925
2926             for (int i = 0; i<m_initRequest_oi_negotiation_num_charsets; i++)
2927             {
2928                 yaz_log(YLOG_LOG, "%scharacters set proposal: %s",
2929                         m_session_str,(m_initRequest_oi_negotiation_charsets[i])?
2930                         m_initRequest_oi_negotiation_charsets[i]:"none");
2931             }
2932             for (int i=0; i<m_initRequest_oi_negotiation_num_langs; i++)
2933             {
2934                 yaz_log(YLOG_LOG, "%slanguages proposal: %s",
2935                         m_session_str, (m_initRequest_oi_negotiation_langs[i])?
2936                         m_initRequest_oi_negotiation_langs[i]:"none");
2937             }
2938             yaz_log(YLOG_LOG, "%sselected proposal: %d (boolean)",
2939                     m_session_str, m_initRequest_oi_negotiation_selected);
2940         }
2941         // save init options for the response..
2942         m_initRequest_options = apdu->u.initRequest->options;
2943
2944         apdu->u.initRequest->options =
2945             (Odr_bitmask *)nmem_malloc(m_initRequest_mem,
2946                                        sizeof(Odr_bitmask));
2947         ODR_MASK_ZERO(apdu->u.initRequest->options);
2948         int i;
2949         for (i = 0; i<= 24; i++)
2950             ODR_MASK_SET(apdu->u.initRequest->options, i);
2951         // check negotiation option
2952         if (!ODR_MASK_GET(m_initRequest_options,
2953                           Z_Options_negotiationModel))
2954         {
2955             ODR_MASK_CLEAR(apdu->u.initRequest->options,
2956                            Z_Options_negotiationModel);
2957         }
2958         ODR_MASK_CLEAR(apdu->u.initRequest->options,
2959                        Z_Options_concurrentOperations);
2960         // make new version
2961         m_initRequest_version = apdu->u.initRequest->protocolVersion;
2962         apdu->u.initRequest->protocolVersion =
2963             (Odr_bitmask *)nmem_malloc(m_initRequest_mem,
2964                                        sizeof(Odr_bitmask));
2965         ODR_MASK_ZERO(apdu->u.initRequest->protocolVersion);
2966
2967         for (i = 0; i<= 8; i++)
2968             ODR_MASK_SET(apdu->u.initRequest->protocolVersion, i);
2969     }
2970     handle_charset_lang_negotiation(apdu);
2971     if (m_client->m_init_flag)
2972     {
2973         if (handle_init_response_for_invalid_session(apdu))
2974             return;
2975         if (m_client->m_initResponse)
2976         {
2977             Z_APDU *apdu2 = m_client->m_initResponse;
2978             apdu2->u.initResponse->otherInfo = 0;
2979             if (m_client->m_cookie && *m_client->m_cookie)
2980                 set_otherInformationString(apdu2, VAL_COOKIE, 1,
2981                                            m_client->m_cookie);
2982             apdu2->u.initResponse->referenceId =
2983                 apdu->u.initRequest->referenceId;
2984             apdu2->u.initResponse->options = m_client->m_initResponse_options;
2985             apdu2->u.initResponse->protocolVersion =
2986                 m_client->m_initResponse_version;
2987
2988             handle_charset_lang_negotiation(apdu2);
2989
2990             send_to_client(apdu2);
2991             m_timeout_mode = timeout_normal;
2992             return;
2993         }
2994     }
2995     m_client->m_init_flag = 1;
2996
2997 #if USE_AUTH_MSG
2998     Auth_Msg *m = new Auth_Msg;
2999     m->m_proxy = this;
3000     z_APDU(odr_encode(), &apdu, 0, "encode");
3001     char *apdu_buf = odr_getbuf(odr_encode(), &m->m_apdu_len, 0);
3002     m->m_apdu_buf = (char*) nmem_malloc(m->m_nmem, m->m_apdu_len);
3003     memcpy(m->m_apdu_buf, apdu_buf, m->m_apdu_len);
3004     odr_reset(odr_encode());
3005
3006     inc_ref();
3007     m_my_thread->put(m);
3008 #else
3009     int ret = handle_authentication(apdu);
3010     result_authentication(apdu, ret);
3011 #endif
3012 }
3013
3014 void Yaz_Proxy::handle_incoming_Z_PDU(Z_APDU *apdu)
3015 {
3016     Z_ReferenceId **refid = get_referenceIdP(apdu);
3017     nmem_reset(m_referenceId_mem);
3018     if (refid && *refid)
3019     {
3020         m_referenceId = (Z_ReferenceId *)
3021             nmem_malloc(m_referenceId_mem, sizeof(*m_referenceId));
3022         m_referenceId->len = m_referenceId->size = (*refid)->len;
3023         m_referenceId->buf = (unsigned char *)
3024             nmem_malloc(m_referenceId_mem, (*refid)->len);
3025         memcpy(m_referenceId->buf, (*refid)->buf, (*refid)->len);
3026     }
3027     else
3028         m_referenceId = 0;
3029
3030     if (!m_client && m_flag_invalid_session)
3031     {
3032         // Got request for a session that is invalid..
3033         m_apdu_invalid_session = apdu; // save package
3034         m_mem_invalid_session = odr_extract_mem(odr_decode());
3035         apdu = m_initRequest_apdu;     // but throw an init to the target
3036     }
3037
3038     // Determine our client.
3039     Z_OtherInformation **oi;
3040     get_otherInfoAPDU(apdu, &oi);
3041     m_client = get_client(apdu, get_cookie(oi), get_proxy(oi));
3042     if (!m_client)
3043     {
3044         if (m_http_version)
3045         {   // HTTP. Send not found
3046             send_http_response(404);
3047             return;
3048         }
3049         else
3050         {
3051             // Z39.50 just shutdown
3052             delete this;
3053             return;
3054         }
3055     }
3056
3057     m_client->m_server = this;
3058
3059     if (apdu->which == Z_APDU_initRequest)
3060         handle_init(apdu);
3061     else
3062         handle_incoming_Z_PDU_2(apdu);
3063 }
3064
3065 void Yaz_Proxy::handle_incoming_Z_PDU_2(Z_APDU *apdu)
3066 {
3067     handle_max_record_retrieve(apdu);
3068
3069     if (apdu)
3070         apdu = handle_syntax_validation(apdu);
3071
3072     if (apdu)
3073         apdu = handle_query_transformation(apdu);
3074
3075     if (apdu)
3076         apdu = handle_target_charset_conversion(apdu);
3077
3078     if (apdu)
3079         apdu = handle_query_validation(apdu);
3080
3081     if (apdu)
3082         apdu = result_set_optimize(apdu);
3083
3084     if (!apdu)
3085     {
3086         m_client->timeout(m_target_idletime);  // mark it active even
3087         recv_GDU_more(true);
3088         // though we didn't use it
3089         return;
3090     }
3091
3092     // delete other info construct completely if 0 elements
3093     Z_OtherInformation **oi;
3094     get_otherInfoAPDU(apdu, &oi);
3095     if (oi && *oi && (*oi)->num_elements == 0)
3096         *oi = 0;
3097
3098     if (apdu->which == Z_APDU_presentRequest &&
3099         m_client->m_resultSetStartPoint == 0)
3100     {
3101         Z_PresentRequest *pr = apdu->u.presentRequest;
3102         m_client->m_resultSetStartPoint = *pr->resultSetStartPoint;
3103         m_client->m_cache.copy_presentRequest(apdu->u.presentRequest);
3104     } else {
3105         m_client->m_resultSetStartPoint = 0;
3106     }
3107     if (m_client->send_to_target(apdu) < 0)
3108     {
3109         m_client->shutdown();
3110     }
3111     else
3112         m_client->m_waiting = 1;
3113 }
3114
3115 void Yaz_Proxy::connectNotify()
3116 {
3117 }
3118
3119 void Yaz_Proxy::releaseClient()
3120 {
3121     xfree(m_proxyTarget);
3122     m_proxyTarget = 0;
3123     m_flag_invalid_session = 0;
3124     // only keep if keep_alive flag is set...
3125     if (m_client &&
3126         m_client->m_pdu_recv < m_keepalive_limit_pdu &&
3127         m_client->m_bytes_recv+m_client->m_bytes_sent < m_keepalive_limit_bw &&
3128         m_client->m_waiting == 0)
3129     {
3130         yaz_log(YLOG_LOG, "%sShutdown (client to proxy) keepalive %s",
3131                  m_session_str,
3132                  m_client->get_hostname());
3133         yaz_log(YLOG_LOG, "%sbw=%d pdu=%d limit-bw=%d limit-pdu=%d",
3134                 m_session_str, m_client->m_pdu_recv,
3135                 m_client->m_bytes_sent + m_client->m_bytes_recv,
3136                 m_keepalive_limit_bw, m_keepalive_limit_pdu);
3137         assert (m_client->m_waiting != 2);
3138         // Tell client (if any) that no server connection is there..
3139         m_client->m_server = 0;
3140         m_client = 0;
3141     }
3142     else if (m_client)
3143     {
3144         yaz_log (YLOG_LOG, "%sShutdown (client to proxy) close %s",
3145                  m_session_str,
3146                  m_client->get_hostname());
3147         assert (m_client->m_waiting != 2);
3148         delete m_client;
3149         m_client = 0;
3150     }
3151     else if (!m_parent)
3152     {
3153         yaz_log (YLOG_LOG, "%sshutdown (client to proxy) bad state",
3154                  m_session_str);
3155         assert (m_parent);
3156     }
3157     else
3158     {
3159         yaz_log (YLOG_LOG, "%sShutdown (client to proxy)",
3160                  m_session_str);
3161     }
3162     if (m_parent)
3163         m_parent->pre_init();
3164 }
3165
3166 bool Yaz_Proxy::dec_ref(bool main_ptr)
3167 {
3168     assert(m_ref_count > 0);
3169     if (main_ptr)
3170     {
3171         if (m_main_ptr_dec)
3172             return false;
3173         m_main_ptr_dec = true;
3174     }
3175
3176     m_http_keepalive = 0;
3177
3178     --m_ref_count;
3179     if (m_ref_count > 0)
3180         return false;
3181
3182     releaseClient();
3183
3184     delete this;
3185     return true;
3186 }
3187
3188 const char *Yaz_ProxyClient::get_session_str()
3189 {
3190     if (!m_server)
3191         return "0 ";
3192     return m_server->get_session_str();
3193 }
3194
3195 void Yaz_ProxyClient::shutdown()
3196 {
3197     yaz_log (YLOG_LOG, "%sShutdown (proxy to target) %s", get_session_str(),
3198              get_hostname());
3199
3200     if (m_server)
3201     {
3202         m_waiting = 1;      // ensure it's released from Proxy in releaseClient
3203         m_server->dec_ref(true);
3204     }
3205     else
3206         delete this;
3207 }
3208
3209 void Yaz_Proxy::failNotify()
3210 {
3211     inc_request_no();
3212     yaz_log (YLOG_LOG, "%sConnection closed by client",
3213              get_session_str());
3214     dec_ref(true);
3215 }
3216
3217 void Yaz_Proxy::send_response_fail_client(const char *addr)
3218 {
3219     if (m_http_version)
3220     {
3221         Z_SRW_diagnostic *diagnostic = 0;
3222         int num_diagnostic = 0;
3223         
3224         yaz_add_srw_diagnostic(odr_encode(),
3225                                &diagnostic, &num_diagnostic,
3226                                YAZ_SRW_SYSTEM_TEMPORARILY_UNAVAILABLE, addr);
3227         if (m_s2z_search_apdu)
3228             send_srw_search_response(diagnostic, num_diagnostic);
3229         else
3230             send_srw_explain_response(diagnostic, num_diagnostic);
3231     }            
3232 }
3233 void Yaz_ProxyClient::failNotify()
3234 {
3235     if (m_server)
3236         m_server->inc_request_no();
3237     yaz_log (YLOG_LOG, "%sConnection closed by target %s",
3238              get_session_str(), get_hostname());
3239
3240     if (m_server)
3241         m_server->send_response_fail_client(get_hostname());
3242     shutdown();
3243 }
3244
3245 void Yaz_ProxyClient::connectNotify()
3246 {
3247     const char *s = get_session_str();
3248     const char *h = get_hostname();
3249     yaz_log (YLOG_LOG, "%sConnection accepted by %s timeout=%d", s, h,
3250              m_target_idletime);
3251     timeout(m_target_idletime);
3252     if (!m_server)
3253         pre_init_client();
3254 }
3255
3256 IPDU_Observer *Yaz_ProxyClient::sessionNotify(IPDU_Observable
3257                                               *the_PDU_Observable, int fd)
3258 {
3259     return new Yaz_ProxyClient(the_PDU_Observable, 0);
3260 }
3261
3262 Yaz_ProxyClient::~Yaz_ProxyClient()
3263 {
3264     if (m_prev)
3265         *m_prev = m_next;
3266     if (m_next)
3267         m_next->m_prev = m_prev;
3268     m_waiting = 2;     // for debugging purposes only.
3269     odr_destroy(m_init_odr);
3270     odr_destroy(m_idAuthentication_odr);
3271     delete m_last_query;
3272     xfree (m_last_resultSetId);
3273     xfree (m_cookie);
3274 }
3275
3276 void Yaz_ProxyClient::pre_init_client()
3277 {
3278     Z_APDU *apdu = create_Z_PDU(Z_APDU_initRequest);
3279     Z_InitRequest *req = apdu->u.initRequest;
3280
3281     int i;
3282     for (i = 0; i<= 24; i++)
3283         ODR_MASK_SET(req->options, i);
3284     ODR_MASK_CLEAR(apdu->u.initRequest->options,
3285                    Z_Options_negotiationModel);
3286     ODR_MASK_CLEAR(apdu->u.initRequest->options,
3287                    Z_Options_concurrentOperations);
3288     for (i = 0; i<= 10; i++)
3289         ODR_MASK_SET(req->protocolVersion, i);
3290
3291     if (send_to_target(apdu) < 0)
3292     {
3293         delete this;
3294     }
3295     else
3296     {
3297         m_waiting = 1;
3298         m_init_flag = 1;
3299     }
3300 }
3301
3302 void Yaz_Proxy::pre_init()
3303 {
3304     int i;
3305     const char *name = 0;
3306     const char *zurl_in_use[MAX_ZURL_PLEX];
3307     int limit_bw, limit_pdu, limit_req, limit_search;
3308     int target_idletime, client_idletime;
3309     int max_clients;
3310     int keepalive_limit_bw, keepalive_limit_pdu;
3311     int pre_init;
3312     const char *cql2rpn = 0;
3313     const char *authentication = 0;
3314     const char *negotiation_charset = 0;
3315     const char *negotiation_lang = 0;
3316
3317     Yaz_ProxyConfig *cfg = check_reconfigure();
3318
3319     zurl_in_use[0] = 0;
3320
3321     if (m_log_mask & PROXY_LOG_APDU_CLIENT)
3322         set_APDU_yazlog(1);
3323     else
3324         set_APDU_yazlog(0);
3325
3326     for (i = 0; cfg && cfg->get_target_no(i, &name, zurl_in_use,
3327                                           &limit_bw, &limit_pdu, &limit_req,
3328                                           &limit_search,
3329                                           &target_idletime, &client_idletime,
3330                                           &max_clients,
3331                                           &keepalive_limit_bw,
3332                                           &keepalive_limit_pdu,
3333                                           &pre_init,
3334                                           &cql2rpn,
3335                                           &authentication,
3336                                           &negotiation_charset,
3337                                           &negotiation_lang,
3338                                           0,
3339                                           0) ; i++)
3340     {
3341         if (pre_init)
3342         {
3343             int j;
3344             for (j = 0; zurl_in_use[j]; j++)
3345             {
3346                 Yaz_ProxyClient *c;
3347                 int spare = 0;
3348                 int spare_waiting = 0;
3349                 int in_use = 0;
3350                 int other = 0;
3351                 for (c = m_clientPool; c; c = c->m_next)
3352                 {
3353                     if (!strcmp(zurl_in_use[j], c->get_hostname()))
3354                     {
3355                         if (c->m_cookie == 0)
3356                         {
3357                             if (c->m_server == 0)
3358                                 if (c->m_waiting)
3359                                     spare_waiting++;
3360                                 else
3361                                     spare++;
3362                             else
3363                                 in_use++;
3364                         }
3365                         else
3366                             other++;
3367                     }
3368                 }
3369                 yaz_log(YLOG_LOG, "%spre-init %s %s use=%d other=%d spare=%d "
3370                         "sparew=%d preinit=%d",m_session_str,
3371                         name, zurl_in_use[j], in_use, other,
3372                         spare, spare_waiting, pre_init);
3373                 if (spare + spare_waiting < pre_init)
3374                 {
3375                     c = new Yaz_ProxyClient(m_PDU_Observable->clone(), this);
3376                     c->m_next = m_clientPool;
3377                     if (c->m_next)
3378                         c->m_next->m_prev = &c->m_next;
3379                     m_clientPool = c;
3380                     c->m_prev = &m_clientPool;
3381
3382                     if (m_log_mask & PROXY_LOG_APDU_SERVER)
3383                         c->set_APDU_yazlog(1);
3384                     else
3385                         c->set_APDU_yazlog(0);
3386
3387                     if (c->client(zurl_in_use[j]))
3388                     {
3389                         timeout(60);
3390                         delete c;
3391                         return;
3392                     }
3393                     c->timeout(30);
3394                     c->m_waiting = 1;
3395                     c->m_target_idletime = target_idletime;
3396                     c->m_seqno = m_seqno++;
3397                 }
3398             }
3399         }
3400     }
3401 }
3402
3403 void Yaz_Proxy::timeoutNotify()
3404 {
3405     if (m_parent)
3406     {
3407         GDU *gdu;
3408         switch(m_timeout_mode)
3409         {
3410         case timeout_normal:
3411         case timeout_busy:
3412             inc_request_no();
3413             m_in_queue.clear();
3414             yaz_log (YLOG_LOG, "%sTimeout (client to proxy)", m_session_str);
3415             dec_ref(true);
3416             break;
3417         case timeout_reduce:
3418             timeout(m_client_idletime);
3419             m_timeout_mode = timeout_busy;
3420             gdu = m_timeout_gdu;
3421             m_timeout_gdu = 0;
3422             recv_GDU_normal(gdu);
3423             break;
3424         case timeout_xsl:
3425             assert(m_stylesheet_nprl);
3426             convert_xsl_delay();
3427             recv_GDU_more(true);
3428         }
3429     }
3430     else
3431     {
3432         timeout(600);
3433         pre_init();
3434     }
3435 }
3436
3437 void Yaz_Proxy::markInvalid()
3438 {
3439     m_client = 0;
3440     m_flag_invalid_session = 1;
3441 }
3442
3443 void Yaz_ProxyClient::timeoutNotify()
3444 {
3445     if (m_server)
3446         m_server->inc_request_no();
3447
3448     yaz_log (YLOG_LOG, "%sTimeout (proxy to target) %s", get_session_str(),
3449              get_hostname());
3450
3451     if (m_server)
3452         m_server->send_response_fail_client(get_hostname());
3453     shutdown();
3454
3455     m_root->pre_init();
3456 }
3457
3458 Yaz_ProxyClient::Yaz_ProxyClient(IPDU_Observable *the_PDU_Observable,
3459                                  Yaz_Proxy *parent) :
3460     Z_Assoc (the_PDU_Observable)
3461 {
3462     m_cookie = 0;
3463     m_next = 0;
3464     m_prev = 0;
3465     m_init_flag = 0;
3466     m_last_query = 0;
3467     m_last_resultSetId = 0;
3468     m_last_resultCount = 0;
3469     m_last_ok = 0;
3470     m_sr_transform = 0;
3471     m_waiting = 0;
3472     m_init_odr = odr_createmem (ODR_DECODE);
3473     m_initResponse = 0;
3474     m_initResponse_options = 0;
3475     m_initResponse_version = 0;
3476     m_initResponse_preferredMessageSize = 0;
3477     m_initResponse_maximumRecordSize = 0;
3478     m_resultSetStartPoint = 0;
3479     m_bytes_sent = m_bytes_recv = 0;
3480     m_pdu_recv = 0;
3481     m_server = 0;
3482     m_seqno = 0;
3483     m_target_idletime = 600;
3484     m_root = parent;
3485     m_idAuthentication_odr = odr_createmem(ODR_ENCODE);
3486     m_idAuthentication_ber_buf = 0;
3487     m_idAuthentication_ber_size = 0;
3488 }
3489
3490 const char *Yaz_Proxy::option(const char *name, const char *value)
3491 {
3492     if (!strcmp (name, "optimize")) {
3493         if (value) {
3494             xfree (m_optimize);
3495             m_optimize = xstrdup (value);
3496         }
3497         return m_optimize;
3498     }
3499     return 0;
3500 }
3501
3502 void Yaz_ProxyClient::recv_HTTP_response(Z_HTTP_Response *apdu, int len)
3503 {
3504
3505 }
3506
3507 void Yaz_ProxyClient::recv_GDU(Z_GDU *apdu, int len)
3508 {
3509     if (apdu->which == Z_GDU_Z3950)
3510         recv_Z_PDU(apdu->u.z3950, len);
3511     else if (apdu->which == Z_GDU_HTTP_Response)
3512         recv_HTTP_response(apdu->u.HTTP_Response, len);
3513     else
3514         shutdown();
3515 }
3516
3517 int Yaz_Proxy::handle_init_response_for_invalid_session(Z_APDU *apdu)
3518 {
3519     if (!m_flag_invalid_session)
3520         return 0;
3521     m_flag_invalid_session = 0;
3522     handle_incoming_Z_PDU(m_apdu_invalid_session);
3523     assert (m_mem_invalid_session);
3524     nmem_destroy(m_mem_invalid_session);
3525     m_mem_invalid_session = 0;
3526     return 1;
3527 }
3528
3529 void Yaz_ProxyClient::recv_Z_PDU(Z_APDU *apdu, int len)
3530 {
3531     m_bytes_recv += len;
3532
3533     m_pdu_recv++;
3534     m_waiting = 0;
3535     if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
3536         yaz_log (YLOG_LOG, "%sReceiving %s from %s %d bytes", get_session_str(),
3537                  apdu_name(apdu), get_hostname(), len);
3538     if (apdu->which == Z_APDU_initResponse)
3539     {
3540         if (!m_server)  // if this is a pre init session , check for more
3541             m_root->pre_init();
3542         NMEM nmem = odr_extract_mem (odr_decode());
3543         odr_reset (m_init_odr);
3544         nmem_transfer (m_init_odr->mem, nmem);
3545         m_initResponse = apdu;
3546         m_initResponse_options = apdu->u.initResponse->options;
3547         m_initResponse_version = apdu->u.initResponse->protocolVersion;
3548         m_initResponse_preferredMessageSize =
3549             *apdu->u.initResponse->preferredMessageSize;
3550         m_initResponse_maximumRecordSize =
3551             *apdu->u.initResponse->maximumRecordSize;
3552
3553         Z_InitResponse *ir = apdu->u.initResponse;
3554         char *im0 = ir->implementationName;
3555
3556         char *im1 = (char*)
3557             odr_malloc(m_init_odr, 20 + (im0 ? strlen(im0) : 0));
3558         *im1 = '\0';
3559         if (im0)
3560         {
3561             strcat(im1, im0);
3562             strcat(im1, " ");
3563         }
3564         strcat(im1, "(YAZ Proxy)");
3565         ir->implementationName = im1;
3566
3567         nmem_destroy (nmem);
3568
3569         if (m_server && m_server->handle_init_response_for_invalid_session(apdu))
3570             return;
3571     }
3572     if (apdu->which == Z_APDU_searchResponse)
3573     {
3574         Z_SearchResponse *sr = apdu->u.searchResponse;
3575         m_last_resultCount = *sr->resultCount;
3576         int status = *sr->searchStatus;
3577         if (status && (!sr->records || sr->records->which == Z_Records_DBOSD))
3578         {
3579             m_last_ok = 1;
3580
3581             if (sr->records && sr->records->which == Z_Records_DBOSD)
3582             {
3583                 m_cache.add(odr_decode(),
3584                             sr->records->u.databaseOrSurDiagnostics, 1,
3585                             *sr->resultCount);
3586             }
3587         }
3588     }
3589     if (apdu->which == Z_APDU_presentResponse)
3590     {
3591         Z_PresentResponse *pr = apdu->u.presentResponse;
3592         if (m_sr_transform)
3593         {
3594             m_sr_transform = 0;
3595             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
3596             Z_SearchResponse *sr = new_apdu->u.searchResponse;
3597             sr->referenceId = pr->referenceId;
3598             *sr->resultCount = m_last_resultCount;
3599             sr->records = pr->records;
3600             sr->nextResultSetPosition = pr->nextResultSetPosition;
3601             sr->numberOfRecordsReturned = pr->numberOfRecordsReturned;
3602             apdu = new_apdu;
3603         }
3604         if (pr->records &&
3605             pr->records->which == Z_Records_DBOSD && m_resultSetStartPoint)
3606         {
3607             m_cache.add(odr_decode(),
3608                         pr->records->u.databaseOrSurDiagnostics,
3609                         m_resultSetStartPoint, -1);
3610             m_resultSetStartPoint = 0;
3611         }
3612     }
3613     if (m_cookie)
3614         set_otherInformationString (apdu, VAL_COOKIE, 1, m_cookie);
3615
3616     Yaz_Proxy *server = m_server; // save it. send_to_client may destroy us
3617
3618     if (server)
3619         server->send_to_client(apdu);
3620     if (apdu->which == Z_APDU_close)
3621         shutdown();
3622     else if (server)
3623         server->recv_GDU_more(true);
3624 }
3625
3626 void Yaz_Proxy::low_socket_close()
3627 {
3628 #if WIN32
3629 #else
3630     int i;
3631     for (i = 0; i<NO_SPARE_SOLARIS_FD; i++)
3632         if  (m_lo_fd[i] >= 0)
3633             ::close(m_lo_fd[i]);
3634 #endif
3635 }
3636
3637 void Yaz_Proxy::low_socket_open()
3638 {
3639 #if WIN32
3640 #else
3641     int i;
3642     for (i = 0; i<NO_SPARE_SOLARIS_FD; i++)
3643         m_lo_fd[i] = open("/dev/null", O_RDONLY);
3644 #endif
3645 }
3646
3647 int Yaz_Proxy::server(const char *addr)
3648 {
3649     int r = Z_Assoc::server(addr);
3650     if (!r)
3651     {
3652         yaz_log(YLOG_LOG, "%sStarted proxy "
3653 #ifdef VERSION
3654             VERSION
3655 #endif
3656             " on %s", m_session_str, addr);
3657         timeout(1);
3658     }
3659     return r;
3660 }
3661
3662 void Yaz_Proxy::base64_decode(const char *base64, char *buf, int buf_len)
3663 {
3664     const char *base64_chars =
3665         "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
3666     int len = strlen(base64);
3667     int buf_pos = 0;
3668     int index = 1;
3669
3670     for (int pos = 0; pos <= len; pos++)
3671     {
3672         if (base64[pos] == '=' || buf_pos + 1 >= buf_len)
3673             break;
3674
3675         const char *ch_ptr = strchr(base64_chars, base64[pos]);
3676         if (!ch_ptr)
3677             break;
3678         char ch = (char) (ch_ptr - base64_chars);
3679         switch (index)
3680         {
3681             case 1:
3682                 buf[buf_pos] = ch << 2;
3683                 break;
3684             case 2:
3685                 buf[buf_pos++] += (ch & 0x30) >> 4;
3686                 buf[buf_pos] = (ch & 0x0f) << 4;
3687                 break;
3688             case 3:
3689                 buf[buf_pos++] += (ch & 0x3c) >> 2;
3690                 buf[buf_pos] = (ch & 0x03) << 6;
3691                 break;
3692             case 4:
3693                 buf[buf_pos++] += ch;
3694         }
3695         if (index < 4)
3696             index++;
3697         else
3698             index = 1;
3699     }
3700     buf[buf_pos] = '\0';
3701 }
3702
3703 /*
3704  * Local variables:
3705  * c-basic-offset: 4
3706  * indent-tabs-mode: nil
3707  * End:
3708  * vim: shiftwidth=4 tabstop=8 expandtab
3709  */
3710