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