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