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