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