diff options
Diffstat (limited to 'config/squid-reverse/squid.inc')
-rw-r--r-- | config/squid-reverse/squid.inc | 1003 |
1 files changed, 649 insertions, 354 deletions
diff --git a/config/squid-reverse/squid.inc b/config/squid-reverse/squid.inc index 151f710c..941395f6 100644 --- a/config/squid-reverse/squid.inc +++ b/config/squid-reverse/squid.inc @@ -4,7 +4,8 @@ squid.inc Copyright (C) 2006-2009 Scott Ullrich Copyright (C) 2006 Fernando Lemos - Copyright (C) 2008 Martin Fuchs + Copyright (C) 2012 Martin Fuchs + Copyright (C) 2012 Marcello Coutinho All rights reserved. Redistribution and use in source and binary forms, with or without @@ -38,14 +39,32 @@ require_once('service-utils.inc'); if(!function_exists("filter_configure")) require_once("filter.inc"); - -define('SQUID_CONFBASE', '/usr/local/etc/squid'); + +$pf_version=substr(trim(file_get_contents("/etc/version")),0,3); +if ($pf_version > 2.0) + define('SQUID_LOCALBASE', '/usr/pbi/squid-' . php_uname("m")); +else + define('SQUID_LOCALBASE','/usr/local'); + +define('SQUID_CONFBASE', SQUID_LOCALBASE .'/etc/squid'); +define('SQUID_CONFFILE', SQUID_CONFBASE . '/squid.conf'); define('SQUID_BASE', '/var/squid/'); define('SQUID_ACLDIR', '/var/squid/acl'); define('SQUID_PASSWD', '/var/etc/squid.passwd'); +define('SQUID_LIB','/var/squid/lib'); +define('SQUID_SSL_DB','/var/squid/lib/ssl_db'); $valid_acls = array(); +$uname=posix_uname(); +if ($uname['machine']=='amd64') + ini_set('memory_limit', '250M'); + + function sq_text_area_decode($text){ + return preg_replace('/\r\n/', "\n",base64_decode($text)); +} + + function squid_get_real_interface_address($iface) { global $config; @@ -77,6 +96,11 @@ function squid_chown_recursive($dir, $user, $group) { /* setup cache */ function squid_dash_z() { global $config; + + //Do nothing if there is no cache config + if (!is_array($config['installedpackages']['squidcache']['config'])) + return; + $settings = $config['installedpackages']['squidcache']['config'][0]; // If the cache system is null, there is no need to initialize the (irrelevant) cache dir. @@ -94,12 +118,12 @@ function squid_dash_z() { if(!is_dir($cachedir.'/00/')) { log_error("Creating squid cache subdirs in $cachedir"); - mwexec("/usr/local/sbin/squid -k shutdown"); + mwexec(SQUID_LOCALBASE. "/sbin/squid -k shutdown -f " . SQUID_CONFFILE); sleep(5); - mwexec("/usr/local/sbin/squid -k kill"); + mwexec(SQUID_LOCALBASE. "/sbin/squid -k kill -f " . SQUID_CONFFILE); // Double check permissions here, should be safe to recurse cache dir if it's small here. mwexec("/usr/sbin/chown -R proxy:proxy $cachedir"); - mwexec("/usr/local/sbin/squid -z"); + mwexec(SQUID_LOCALBASE. "/sbin/squid -z -f " . SQUID_CONFFILE); } if(file_exists("/var/squid/cache/swap.state")) { @@ -120,11 +144,17 @@ function squid_is_valid_acl($acl) { function squid_install_command() { global $config; global $g; + update_status("Checking if there is configuration to migrate... One moment please..."); /* migrate existing csv config fields */ - $settingsauth = $config['installedpackages']['squidauth']['config'][0]; - $settingscache = $config['installedpackages']['squidcache']['config'][0]; - $settingsnac = $config['installedpackages']['squidnac']['config'][0]; - + if (is_array($config['installedpackages']['squidauth']['config'])) + $settingsauth = $config['installedpackages']['squidauth']['config'][0]; + if (is_array($config['installedpackages']['squidcache']['config'])) + $settingscache = $config['installedpackages']['squidcache']['config'][0]; + if (is_array($config['installedpackages']['squidnac']['config'])) + $settingsnac = $config['installedpackages']['squidnac']['config'][0]; + if (is_array($config['installedpackages']['squid']['config'])) + $settingsgen = $config['installedpackages']['squid']['config'][0]; + /* Set storage system */ if ($g['platform'] == "nanobsd") { $config['installedpackages']['squidcache']['config'][0]['harddisk_cache_system'] = 'null'; @@ -153,7 +183,6 @@ function squid_install_command() { $config['installedpackages']['squidnac']['config'][0]['allowed_subnets'] = $settingsnac['allowed_subnets']; } } - if(! empty($settingsnac['banned_hosts'])) { if(strstr($settingsnac['banned_hosts'], ",")) { $settingsnac['banned_hosts'] = base64_encode(implode("\n", explode(",", $settingsnac['banned_hosts']))); @@ -195,7 +224,49 @@ function squid_install_command() { $config['installedpackages']['squidnac']['config'][0]['blacklist'] = $settingsnac['blacklist']; } } - + + /*Migrate reverse settings*/ + if (is_array($config['installedpackages']['squidreverse'])){ + $old_reverse_settings=$config['installedpackages']['squidreverse']['config'][0]; + + //Settings + if (!is_array($config['installedpackages']['squidreversegeneral'])){ + $config['installedpackages']['squidreversegeneral']['config'][0]=$old_reverse_settings; + unset ($config['installedpackages']['squidreversegeneral']['config'][0]['reverse_cache_peer']); + unset ($config['installedpackages']['squidreversegeneral']['config'][0]['reverse_uri']); + unset ($config['installedpackages']['squidreversegeneral']['config'][0]['reverse_acl']); + } + + //PEERS + if (!is_array($config['installedpackages']['squidreversepeer'])){ + foreach (explode("\n",sq_text_area_decode($old_reverse_settings['reverse_cache_peer'])) as $cache_peers) + foreach (explode(";",$cache_peers) as $cache_peer) + $config['installedpackages']['squidreversepeer']['config'][]=array('description'=>'migrated', + 'enable'=> 'on', + 'name'=> $cache_peer[0], + 'port'=> $cache_peer[1], + 'protocol' => $cache_peer[2]); + } + + //MAPPINGS + if (!is_array($config['installedpackages']['squidreverseuri'])){ + foreach (explode("\n",sq_text_area_decode($old_reverse_settings['reverse_acl'])) as $acls){ + foreach (explode(";",$acls) as $acl) + array_push(${'peer_'.$acl[0]},$acl[1]); + } + foreach (explode("\n",sq_text_area_decode($old_reverse_settings['reverse_uri'])) as $uris) + foreach (explode(";",$uris) as $uri){ + $peer_list=(is_array(${'peer_'.$uri[0]})?implode(",",${'peer_'.$uri[0]}):""); + $config['installedpackages']['squidreverseuri']['config'][]=array('description'=>'migrated', + 'enable'=> 'on', + 'name'=> $uri[0], + 'uri'=> $uri[1], + 'vhost' => $uri[2], + 'peers'=>$peer_list); + } + } + } + update_status("Writing configuration... One moment please..."); write_config(); @@ -204,18 +275,23 @@ function squid_install_command() { update_status("Creating squid cache pools... One moment please..."); squid_dash_z(); /* make sure pinger is executable */ - if(file_exists("/usr/local/libexec/squid/pinger")) - exec("/bin/chmod a+x /usr/local/libexec/squid/pinger"); + if(file_exists(SQUID_LOCALBASE. "/libexec/squid/pinger")) + exec("/bin/chmod a+x ". SQUID_LOCALBASE. "/libexec/squid/pinger"); if(file_exists("/usr/local/etc/rc.d/squid")) exec("/bin/rm /usr/local/etc/rc.d/squid"); squid_write_rcfile(); - exec("chmod a+rx /usr/local/libexec/squid/dnsserver"); if(file_exists("/usr/local/pkg/swapstate_check.php")) exec("/bin/chmod a+x /usr/local/pkg/swapstate_check.php"); + write_rcfile(array( + "file" => "sqp_monitor.sh", + "start" => "/usr/local/pkg/sqpmon.sh &", + "stop" => "ps awux | grep \"sqpmon\" | grep -v \"grep\" | grep -v \"php\" | awk '{ print $2 }' | xargs kill")); foreach (array( SQUID_CONFBASE, SQUID_ACLDIR, - SQUID_BASE ) as $dir) { + SQUID_BASE, + SQUID_LIB, + SQUID_SSL_DB ) as $dir) { make_dirs($dir); squid_chown_recursive($dir, 'proxy', 'proxy'); } @@ -223,7 +299,7 @@ function squid_install_command() { /* kill any running proxy alarm scripts */ update_status("Checking for running processes... One moment please..."); log_error("Stopping any running proxy monitors"); - mwexec("ps awux | grep \"proxy_monitor\" | grep -v \"grep\" | grep -v \"php\" | awk '{ print $2 }' | xargs kill"); + mwexec("/usr/local/etc/rc.d/sqp_monitor.sh stop"); sleep(1); if (!file_exists(SQUID_CONFBASE . '/mime.conf') && file_exists(SQUID_CONFBASE . '/mime.conf.default')) @@ -235,16 +311,16 @@ function squid_install_command() { if (!is_service_running('squid')) { update_status("Starting... One moment please..."); log_error("Starting Squid"); - mwexec_bg("/usr/local/sbin/squid -D"); + mwexec_bg(SQUID_LOCALBASE. "/sbin/squid -f " . SQUID_CONFFILE); } else { update_status("Reloading Squid for configuration sync... One moment please..."); log_error("Reloading Squid for configuration sync"); - mwexec("/usr/local/sbin/squid -k reconfigure"); + mwexec(SQUID_LOCALBASE. "/sbin/squid -k reconfigure -f " . SQUID_CONFFILE); } /* restart proxy alarm scripts */ log_error("Starting a proxy monitor script"); - mwexec_bg("/usr/local/etc/rc.d/proxy_monitor.sh"); + mwexec_bg("/usr/local/etc/rc.d/sqp_monitor.sh start"); update_status("Reconfiguring filter... One moment please..."); filter_configure(); @@ -254,7 +330,10 @@ function squid_deinstall_command() { global $config, $g; $plswait_txt = "This operation may take quite some time, please be patient. Do not press stop or attempt to navigate away from this page during this process."; squid_install_cron(false); - $settings = &$config['installedpackages']['squidcache']['config'][0]; + if (is_array($config['installedpackages']['squidcache'])) + $settings = $config['installedpackages']['squidcache']['config'][0]; + else + $settings = array(); $cachedir =($settings['harddisk_cache_location'] ? $settings['harddisk_cache_location'] : '/var/squid/cache'); $logdir = ($settings['log_dir'] ? $settings['log_dir'] : '/var/squid/logs'); update_status("Removing swap.state ... One moment please..."); @@ -262,8 +341,8 @@ function squid_deinstall_command() { mwexec('rm -rf $cachedir/swap.state'); mwexec('rm -rf $logdir'); update_status("Finishing package cleanup."); - mwexec('rm -f /usr/local/etc/rc.d/proxy_monitor.sh'); - mwexec("ps awux | grep \"proxy_monitor\" | grep -v \"grep\" | grep -v \"php\" | awk '{ print $2 }' | xargs kill"); + mwexec("/usr/local/etc/rc.d/sqp_monitor.sh stop"); + mwexec('rm -f /usr/local/etc/rc.d/sqp_monitor.sh'); mwexec("ps awux | grep \"squid\" | grep -v \"grep\" | awk '{ print $2 }' | xargs kill"); mwexec("ps awux | grep \"dnsserver\" | grep -v \"grep\" | awk '{ print $2 }' | xargs kill"); mwexec("ps awux | grep \"unlinkd\" | grep -v \"grep\" | awk '{ print $2 }' | xargs kill"); @@ -273,9 +352,12 @@ function squid_deinstall_command() { function squid_before_form_general($pkg) { $values = get_dir(SQUID_CONFBASE . '/errors/'); - // Get rid of '..' and '.' + // Get rid of '..' and '.' and ... array_shift($values); array_shift($values); + array_shift($values); + array_shift($values); + $name = array(); foreach ($values as $value) $names[] = implode(" ", explode("_", $value)); @@ -294,7 +376,10 @@ function squid_before_form_general($pkg) { function squid_validate_general($post, $input_errors) { global $config; - $settings = $config['installedpackages']['squid']['config'][0]; + if (is_array($config['installedpackages']['squid'])) + $settings = $config['installedpackages']['squid']['config'][0]; + else + $settings = array(); $port = ($settings['proxy_port'] ? $settings['proxy_port'] : 3128); $port = $post['proxy_port'] ? $post['proxy_port'] : $port; @@ -313,7 +398,7 @@ function squid_validate_general($post, $input_errors) { $log_rotate = trim($post['log_rotate']); if (!empty($log_rotate) && (!is_numeric($log_rotate) or ($log_rotate < 1))) - $input_errors[] = 'You must enter a valid number of days \'Log rotate\' field'; + $input_errors[] = 'You must enter a valid number of days in the \'Log rotate\' field'; $webgui_port = $config['system']['webgui']['port']; if(($config['system']['webgui']['port'] == "") && ($config['system']['webgui']['protocol'] == "http")) { @@ -347,12 +432,13 @@ function squid_validate_general($post, $input_errors) { foreach ($altdns as $dnssrv) { if (!is_ipaddr($dnssrv)) $input_errors[] = 'You must enter a valid IP address in the \'Alternate DNS servers\' field'; + break; }} } function squid_validate_upstream($post, $input_errors) { - if ($post['proxy_forwarding'] == 'on') { - $addr = trim($post['proxy_addr']); + if ($post['enabled'] == 'on') { + $addr = trim($post['proxyaddr']); if (empty($addr)) $input_errors[] = 'The field \'Hostname\' is required'; else { @@ -360,7 +446,7 @@ function squid_validate_upstream($post, $input_errors) { $input_errors[] = 'You must enter a valid IP address or host name in the \'Proxy hostname\' field'; } - foreach (array('proxy_port' => 'TCP port', 'icp_port' => 'ICP port') as $field => $name) { + foreach (array('proxyport' => 'TCP port', 'icpport' => 'ICP port') as $field => $name) { $port = trim($post[$field]); if (empty($port)) $input_errors[] = "The field '$name' is required"; @@ -420,10 +506,18 @@ function squid_validate_nac($post, $input_errors) { } foreach (array( 'unrestricted_hosts', 'banned_hosts') as $hosts) { - foreach (explode("\n", $post[$hosts]) as $host) { - $host = trim($host); - if (!empty($host) && !is_ipaddr($host)) - $input_errors[] = "The host '$host' is not a valid IP address"; + + if (preg_match_all("@([0-9.]+)(/[0-9.]+|)@",$_POST[$hosts],$matches)){ + for ($x=0;$x < count($matches[1]);$x++){ + if ($matches[2][$x] == ""){ + if (!is_ipaddr($matches[1][$x])) + $input_errors[] = "'{$matches[1][$x]}' is not a valid IP address"; + } + else{ + if (!is_subnet($matches[0][$x])) + $input_errors[] = "The subnet '{$matches[0][$x]}' is not a valid CIDR range"; + } + } } } @@ -476,26 +570,34 @@ function squid_validate_traffic($post, $input_errors) { if (!empty($post['quick_abort_pct'])) { $value = trim($post['quick_abort_pct']); if (!is_numeric($value) || ($value > 100)) - $input_errors[] = "The field 'Finish when remaining %' must contain a percentaged value"; + $input_errors[] = "The field 'Finish when remaining %' must contain a percentage"; } } function squid_validate_reverse($post, $input_errors) { - $fqdn = trim($post['reverse_external_fqdn']); - if (!empty($fqdn) && !is_domain($fqdn)) - $input_errors[] = 'The field \'external FQDN\' must contain a valid domain name'; + if(!empty($post['reverse_ip'])) { + $reverse_ip = explode(";", ($post['reverse_ip'])); + foreach ($reverse_ip as $reip) { + if (!is_ipaddr($reip)) + $input_errors[] = 'You must enter a valid IP address in the \'User-defined reverse-proxy IPs\' field'; + break; + }} + + $fqdn = trim($post['reverse_external_fqdn']); + if (!empty($fqdn) && !is_domain($fqdn)) + $input_errors[] = 'The field \'external FQDN\' must contain a valid domain name'; - $port = trim($post['reverse_http_port']); - if (!empty($port) && !is_port($port)) - $input_errors[] = 'The field \'reverse HTTP port\' must contain a valid port number'; + $port = trim($post['reverse_http_port']); + if (!empty($port) && !is_port($port)) + $input_errors[] = 'The field \'reverse HTTP port\' must contain a valid port number'; - $port = trim($post['reverse_https_port']); - if (!empty($port) && !is_port($port)) - $input_errors[] = 'The field \'reverse HTTPS port\' must contain a valid port number'; + $port = trim($post['reverse_https_port']); + if (!empty($port) && !is_port($port)) + $input_errors[] = 'The field \'reverse HTTPS port\' must contain a valid port number'; - if ($post['reverse_ssl_cert'] == 'none') - $input_errors[] = 'A valid certificate for the external interface must be selected'; + if ($post['reverse_ssl_cert'] == 'none') + $input_errors[] = 'A valid certificate for the external interface must be selected'; if (($post['reverse_https'] != 'on') && ($post['reverse_owa'] == 'on')) { $input_errors[] = "You have to enable reverse HTTPS before enabling OWA support."; @@ -506,9 +608,9 @@ function squid_validate_reverse($post, $input_errors) { $input_errors[] = 'A valid certificate for the external interface must be selected'; */ - $rowa = trim($post['reverse_owa_ip']); - if (!empty($rowa) && !is_ipaddr($rowa)) - $input_errors[] = 'The field \'OWA frontend IP address\' must contain a valid IP address'; + $rowa = trim($post['reverse_owa_ip']); + if (!empty($rowa) && !is_ipaddr($rowa)) + $input_errors[] = 'The field \'OWA frontend IP address\' must contain a valid IP address'; $contents = $post['reverse_cache_peer']; @@ -588,24 +690,28 @@ function squid_install_cron($should_install) { if(!$config['cron']['item']) return; - $settings = $config['installedpackages']['squidcache']['config'][0]; + + if (is_array($config['installedpackages']['squidcache'])) + $settings = $config['installedpackages']['squidcache']['config'][0]; + else + $settings = array(); + $x=0; $rotate_job_id=-1; $swapstate_job_id=-1; foreach($config['cron']['item'] as $item) { if(strstr($item['task_name'], "squid_rotate_logs")) { - - $rotate_job_id = $x; - } elseif(strstr($item['task_name'], "squid_check_swapstate")) { - $swapstate_job_id = $x; + $rotate_job_id = $x; + } elseif(strstr($item['task_name'], "squid_check_swapstate")) { + $swapstate_job_id = $x; } $x++; } $need_write = false; switch($should_install) { case true: - $cachedir =($settings['harddisk_cache_location'] ? $settings['harddisk_cache_location'] : '/var/squid/cache'); - if($rotate_job_id < 0) { + $cachedir =($settings['harddisk_cache_location'] ? $settings['harddisk_cache_location'] : '/var/squid/cache'); + if($rotate_job_id < 0) { $cron_item = array(); $cron_item['task_name'] = "squid_rotate_logs"; $cron_item['minute'] = "0"; @@ -614,11 +720,12 @@ function squid_install_cron($should_install) { $cron_item['month'] = "*"; $cron_item['wday'] = "*"; $cron_item['who'] = "root"; - $cron_item['command'] = "/bin/rm {$cachedir}/swap.state; /usr/local/sbin/squid -k rotate"; + $cron_item['command'] = "/bin/rm {$cachedir}/swap.state; ". SQUID_LOCALBASE."/sbin/squid -k rotate -f " . SQUID_CONFFILE; + /* Add this cron_item as a new entry at the end of the item array. */ $config['cron']['item'][] = $cron_item; $need_write = true; - } - if($swapstate_job_id < 0) { + } + if($swapstate_job_id < 0) { $cron_item = array(); $cron_item['task_name'] = "squid_check_swapstate"; $cron_item['minute'] = "*/15"; @@ -628,37 +735,40 @@ function squid_install_cron($should_install) { $cron_item['wday'] = "*"; $cron_item['who'] = "root"; $cron_item['command'] = "/usr/local/pkg/swapstate_check.php"; + /* Add this cron_item as a new entry at the end of the item array. */ $config['cron']['item'][] = $cron_item; $need_write = true; - } - if ($need_write) { - $config['cron']['item'][] = $cron_item; + } + if ($need_write) { parse_config(true); write_config("Adding Squid Cron Jobs"); } - break; + break; case false: - if($rotate_job_id >= 0) { - unset($config['cron']['item'][$rotate_job_id]); - $need_write = true; - } - if($swapstate_job_id >= 0) { - unset($config['cron']['item'][$swapstate_job_id]); - $need_write = true; - } - if ($need_write) { - parse_config(true); - write_config("Removing Squid Cron Jobs"); - } - break; + if($rotate_job_id >= 0) { + unset($config['cron']['item'][$rotate_job_id]); + $need_write = true; + } + if($swapstate_job_id >= 0) { + unset($config['cron']['item'][$swapstate_job_id]); + $need_write = true; + } + if ($need_write) { + parse_config(true); + write_config("Removing Squid Cron Jobs"); + } + break; } configure_cron(); - } +} function squid_resync_general() { global $g, $config, $valid_acls; - $settings = $config['installedpackages']['squid']['config'][0]; + if (is_array($config['installedpackages']['squid'])) + $settings = $config['installedpackages']['squid']['config'][0]; + else + $settings=array(); $conf = "# This file is automatically generated by pfSense\n"; $conf .= "# Do not edit manually !\n"; @@ -672,35 +782,38 @@ function squid_resync_general() { } } if (($settings['transparent_proxy'] == 'on')) { - $conf .= "http_port 127.0.0.1:" . $settings['proxy_port'] . " transparent\n"; + $conf .= "http_port 127.0.0.1:" . $settings['proxy_port'] . " intercept\n"; } - $icp_port = ($settings['icp_port'] ? $settings['icp_port'] : 0); - + $icp_port = ($settings['icp_port'] ? $settings['icp_port'] : 7); + $dns_v4_first= ($settings['dns_v4_first'] == "on" ? "on" : "off" ); $pidfile = "{$g['varrun_path']}/squid.pid"; - $language = ($settings['error_language'] ? $settings['error_language'] : 'English'); - $errordir = SQUID_CONFBASE . '/errors/' . $language; + $language = ($settings['error_language'] ? $settings['error_language'] : 'en'); $icondir = SQUID_CONFBASE . '/icons'; $hostname = ($settings['visible_hostname'] ? $settings['visible_hostname'] : 'localhost'); $email = ($settings['admin_email'] ? $settings['admin_email'] : 'admin@localhost'); $logdir = ($settings['log_dir'] ? $settings['log_dir'] : '/var/squid/logs'); - + if (! is_dir($logdir)){ + make_dirs($logdir); + squid_chown_recursive($logdir, 'proxy', 'proxy'); + } $logdir_cache = $logdir . '/cache.log'; $logdir_access = ($settings['log_enabled'] == 'on' ? $logdir . '/access.log' : '/dev/null'); $conf .= <<<EOD -icp_port $icp_port - -pid_filename $pidfile +icp_port {$icp_port} +dns_v4_first {$dns_v4_first} +pid_filename {$pidfile} cache_effective_user proxy cache_effective_group proxy -error_directory $errordir -icon_directory $icondir -visible_hostname $hostname -cache_mgr $email -access_log $logdir_access -cache_log $logdir_cache +error_default_language {$language} +icon_directory {$icondir} +visible_hostname {$hostname} +cache_mgr {$email} +access_log {$logdir_access} +cache_log {$logdir_cache} cache_store_log none +sslcrtd_children 0 EOD; @@ -721,6 +834,7 @@ EOD; foreach ($real_ifaces as $iface) { list($ip, $mask) = $iface; $ip = long2ip(ip2long($ip) & ip2long($mask)); + $mask = 32-log((ip2long($mask) ^ ip2long('255.255.255.255'))+1,2); $src .= " $ip/$mask"; } $conf .= "# Allow local network(s) on interface(s)\n"; @@ -748,52 +862,118 @@ EOD; function squid_resync_cache() { global $config, $g; - - $settings = $config['installedpackages']['squidcache']['config'][0]; - + if (is_array($config['installedpackages']['squidcache'])) + $settings = $config['installedpackages']['squidcache']['config'][0]; + else + $settings = array(); + //apply cache settings $cachedir =($settings['harddisk_cache_location'] ? $settings['harddisk_cache_location'] : '/var/squid/cache'); $disk_cache_size = ($settings['harddisk_cache_size'] ? $settings['harddisk_cache_size'] : 100); $level1 = ($settings['level1_subdirs'] ? $settings['level1_subdirs'] : 16); $memory_cache_size = ($settings['memory_cache_size'] ? $settings['memory_cache_size'] : 8); - $max_objsize = ($settings['maximum_object_size'] ? $settings['maximum_object_size'] : 10); + $max_objsize = ($settings['maximum_object_size'] ? $settings['maximum_object_size']." KB" : "10 KB"); $min_objsize = ($settings['minimum_object_size'] ? $settings['minimum_object_size'] : 0); $max_objsize_in_mem = ($settings['maximum_objsize_in_mem'] ? $settings['maximum_objsize_in_mem'] : 32); $cache_policy = ($settings['cache_replacement_policy'] ? $settings['cache_replacement_policy'] : 'heap LFUDA'); $memory_policy = ($settings['memory_replacement_policy'] ? $settings['memory_replacement_policy'] : 'heap GDSF'); $offline_mode = ($settings['enable_offline'] == 'on' ? 'on' : 'off'); - + $conf = ''; if (!isset($settings['harddisk_cache_system'])) { - if ($g['platform'] == "nanobsd") { + if ($g['platform'] == "nanobsd" || !is_array ($config['installedpackages']['squidcache']['config'])) $disk_cache_system = 'null'; - } else { + else $disk_cache_system = 'ufs'; } - } else { + else{ $disk_cache_system = $settings['harddisk_cache_system']; - } + } + #'null' storage type dropped. In-memory cache is always present. Remove all cache_dir options to prevent on-disk caching. + if ($disk_cache_system != "null") { + $disk_cache_opts = "cache_dir {$disk_cache_system} {$cachedir} {$disk_cache_size} {$level1} 256"; + } +//check dynamic content +if(empty($settings['cache_dynamic_content'])){ + $conf.='acl dynamic urlpath_regex cgi-bin \?'."\n"; + $conf.="cache deny dynamic\n"; +} +else{ + if(preg_match('/youtube/',$settings['refresh_patterns'])){ + $conf.=<<<EOC +# Break HTTP standard for flash videos. Keep them in cache even if asked not to. +refresh_pattern -i \.flv$ 10080 90% 999999 ignore-no-cache override-expire ignore-private - if ($disk_cache_system == "null") { - $disk_cache_opts = "{$disk_cache_system} /tmp"; - } else { - $disk_cache_opts = "{$disk_cache_system} {$cachedir} {$disk_cache_size} {$level1} 256"; +# Let the clients favorite video site through with full caching +acl youtube dstdomain .youtube.com +cache allow youtube + +EOC; } + if(preg_match('/windows/',$settings['refresh_patterns'])){ + $conf.=<<<EOC - $conf = <<<EOD -cache_mem $memory_cache_size MB -maximum_object_size_in_memory $max_objsize_in_mem KB -memory_replacement_policy $memory_policy -cache_replacement_policy $cache_policy -cache_dir $disk_cache_opts -minimum_object_size $min_objsize KB -maximum_object_size $max_objsize KB -offline_mode $offline_mode +# Windows Update refresh_pattern +range_offset_limit -1 +refresh_pattern -i microsoft.com/.*\.(cab|exe|ms[i|u|f]|asf|wm[v|a]|dat|zip) 4320 80% 43200 reload-into-ims +refresh_pattern -i windowsupdate.com/.*\.(cab|exe|ms[i|u|f]|asf|wm[v|a]|dat|zip) 4320 80% 43200 reload-into-ims +refresh_pattern -i my.windowsupdate.website.com/.*\.(cab|exe|ms[i|u|f]|asf|wm[v|a]|dat|zip) 4320 80% 43200 reload-into-ims + +EOC; + } + +if(preg_match('/symantec/',$settings['refresh_patterns'])){ + $conf.=<<<EOC + +# Symantec refresh_pattern +range_offset_limit -1 +refresh_pattern liveupdate.symantecliveupdate.com/.*\.(cab|exe|dll|msi) 10080 100% 43200 reload-into-ims +refresh_pattern symantecliveupdate.com/.*\.(cab|exe|dll|msi) 10080 100% 43200 reload-into-ims +EOC; + } +if(preg_match('/avast/',$settings['refresh_patterns'])){ + $conf.=<<<EOC + +# Avast refresh_pattern +range_offset_limit -1 +refresh_pattern avast.com/.*\.(vpu|cab|stamp|exe) 10080 100% 43200 reload-into-ims + +EOC; + } +if(preg_match('/avira/',$settings['refresh_patterns'])){ + $conf.=<<<EOC + +# Avira refresh_pattern +range_offset_limit -1 +refresh_pattern personal.avira-update.com/.*\.(cab|exe|dll|msi|gz) 10080 100% 43200 reload-into-ims + +EOC; + } + $refresh_conf=<<<EOC + +# Add any of your own refresh_pattern entries above these. +refresh_pattern ^ftp: 1440 20% 10080 +refresh_pattern ^gopher: 1440 0% 1440 +refresh_pattern -i (/cgi-bin/|\?) 0 0% 0 +refresh_pattern . 0 20% 4320 +EOC; + +} + + $conf .= <<<EOD +cache_mem $memory_cache_size MB +maximum_object_size_in_memory {$max_objsize_in_mem} KB +memory_replacement_policy {$memory_policy} +cache_replacement_policy {$cache_policy} +$disk_cache_opts +minimum_object_size {$min_objsize} KB +maximum_object_size {$max_objsize} +offline_mode {$offline_mode} EOD; if (!empty($settings['cache_swap_low'])) $conf .= "cache_swap_low {$settings['cache_swap_low']}\n"; if (!empty($settings['cache_swap_high'])) $conf .= "cache_swap_high {$settings['cache_swap_high']}\n"; - $donotcache = base64_decode($settings['donotcache']); + $donotcache = sq_text_area_decode($settings['donotcache']); if (!empty($donotcache)) { file_put_contents(SQUID_ACLDIR . '/donotcache.acl', $donotcache); $conf .= 'acl donotcache dstdomain "' . SQUID_ACLDIR . "/donotcache.acl\"\n"; @@ -802,28 +982,39 @@ EOD; elseif (file_exists(SQUID_ACLDIR . '/donotcache.acl')) { unlink(SQUID_ACLDIR . '/donotcache.acl'); } - - return $conf; + return $conf.$refresh_conf; } function squid_resync_upstream() { global $config; - $settings = $config['installedpackages']['squidupstream']['config'][0]; - - $conf = ''; - if ($settings['proxy_forwarding'] == 'on') { - $conf .= "cache_peer {$settings['proxy_addr']} parent {$settings['proxy_port']} "; - if ($settings['icp_port'] == '7') - $conf .= "{$settings['icp_port']} no-query"; - else - $conf .= "{$settings['icp_port']}"; - - if (!empty($settings['username'])) - $conf .= " login={$settings['username']}"; - if (!empty($settings['password'])) - $conf .= ":{$settings['password']}"; - } - + $conf = "\n#Remote proxies\n"; + if (is_array($config['installedpackages']['squidremote']['config'])) + foreach ($config['installedpackages']['squidremote']['config'] as $settings){ + if ($settings['enable'] == 'on') { + $conf .= "cache_peer {$settings['proxyaddr']} {$settings['hierarchy']} {$settings['proxyport']} "; + if ($settings['icpport'] == '7') + $conf .= "{$settings['icpport']} {$settings['icpoptions']} {$settings['peermethod']} {$settings['allowmiss']} "; + else + $conf .= "{$settings['icpport']} "; + #auth settings + if (!empty($settings['username']) && !empty($settings['password'])){ + $conf .= " login={$settings['username']}:{$settings['password']}"; + } + else{ + $conf .= "{$settings['authoption']} "; + } + #other options settings + if (!empty($settings['weight'])) + $conf .= "weight={$settings['weight']} "; + if (!empty($settings['basetime'])) + $conf .= "basetime={$settings['basetime']} "; + if (!empty($settings['ttl'])) + $conf .= "ttl={$settings['ttl']} "; + if (!empty($settings['nodelay'])) + $conf .= "no-delay"; + } + $conf .= "\n"; + } return $conf; } @@ -842,8 +1033,11 @@ function squid_resync_redirector() { function squid_resync_nac() { global $config, $valid_acls; - $port = ($settings['proxy_port'] ? $settings['proxy_port'] : 3128); - $settings = $config['installedpackages']['squidnac']['config'][0]; + $port = ($settings['proxy_port'] ? $settings['proxy_port'] : 3128); + if (is_array($config['installedpackages']['squidnac'])) + $settings = $config['installedpackages']['squidnac']['config'][0]; + else + $settings = array(); $webgui_port = $config['system']['webgui']['port']; $addtl_ports = $settings['addtl_ports']; $addtl_sslports = $settings['addtl_sslports']; @@ -851,27 +1045,27 @@ function squid_resync_nac() { $conf = <<<EOD # Setup some default acls -acl all src 0.0.0.0/0.0.0.0 -acl localhost src 127.0.0.1/255.255.255.255 +acl allsrc src all +acl localhost src 127.0.0.1/32 acl safeports port 21 70 80 210 280 443 488 563 591 631 777 901 $webgui_port $port 1025-65535 $addtl_ports acl sslports port 443 563 $webgui_port $addtl_sslports acl manager proto cache_object acl purge method PURGE acl connect method CONNECT -acl dynamic urlpath_regex cgi-bin \? + EOD; - $allowed_subnets = explode("\n", base64_decode($settings['allowed_subnets'])); - $allowed = ""; - foreach ($allowed_subnets as $subnet) { - if(!empty($subnet)) { - $subnet = trim($subnet); - $allowed .= "$subnet "; - } - } - if (!empty($allowed)) { - $conf .= "acl allowed_subnets src $allowed\n"; + $allowed_subnets = preg_replace("/\s+/"," ",sq_text_area_decode($settings['allowed_subnets'])); + #$allowed = ""; + #foreach ($allowed_subnets as $subnet) { + # if(!empty($subnet)) { + # $subnet = trim($subnet); + # $allowed .= "$subnet "; + # } + #} + if (!empty($allowed_subnets)) { + $conf .= "acl allowed_subnets src $allowed_subnets\n"; $valid_acls[] = 'allowed_subnets'; } @@ -881,7 +1075,7 @@ EOD; 'blacklist' => 'dstdom_regex -i', ); foreach ($options as $option => $directive) { - $contents = base64_decode($settings[$option]); + $contents = sq_text_area_decode($settings[$option]); if (!empty($contents)) { file_put_contents(SQUID_ACLDIR . "/$option.acl", $contents); $conf .= "acl $option $directive \"" . SQUID_ACLDIR . "/$option.acl\"\n"; @@ -893,23 +1087,21 @@ EOD; } $conf .= <<<EOD -cache deny dynamic http_access allow manager localhost EOD; - if(!empty($settings['ext_cachemanager'])) { - $extmgr = explode(";", ($settings['ext_cachemanager'])); - $count = 1; - $conf .= "\n# Allow external cache managers\n"; -// $conf .= "acl ext_manager src ".$settings['ext_cachemanager']."\n"; - foreach ($extmgr as $mgr) { - $conf .= "acl ext_manager_".$count." src "; - $conf .= $mgr." "; - $conf .= "\n"; - $conf .= "http_access allow manager ext_manager_".$count."\n"; - $count += 1; - }} + if (is_array($config['installedpackages']['squidcache'])){ + $settings_ch = $config['installedpackages']['squidcache']['config'][0]; + if(!empty($settings_ch['ext_cachemanager'])) { + $extmgr = explode(";", ($settings_ch['ext_cachemanager'])); + $conf .= "\n# Allow external cache managers\n"; + foreach ($extmgr as $mgr) { + $conf .= "acl ext_manager src {$mgr}\n"; + } + $conf .= "http_access allow manager ext_manager\n"; + } + } $conf .= <<<EOD @@ -929,20 +1121,29 @@ EOD; function squid_resync_traffic() { global $config, $valid_acls; + if(!is_array($valid_acls)) return; - $settings = $config['installedpackages']['squidtraffic']['config'][0]; + if (is_array($config['installedpackages']['squidtraffic'])) + $settings = $config['installedpackages']['squidtraffic']['config'][0]; + else + $settings = array(); + $conf = ''; - - if (!empty($settings['quick_abort_min']) || ($settings['quick_abort_min']) == "0") $conf .= "quick_abort_min {$settings['quick_abort_min']} KB\n"; - if (!empty($settings['quick_abort_max']) || ($settings['quick_abort_max']) == "0") $conf .= "quick_abort_max {$settings['quick_abort_max']} KB\n"; - if (!empty($settings['quick_abort_pct'])) $conf .= "quick_abort_pct {$settings['quick_abort_pct']}\n"; + if (!empty($settings['quick_abort_min']) || ($settings['quick_abort_min']) == "0") + $conf .= "quick_abort_min {$settings['quick_abort_min']} KB\n"; + if (!empty($settings['quick_abort_max']) || ($settings['quick_abort_max']) == "0") + $conf .= "quick_abort_max {$settings['quick_abort_max']} KB\n"; + if (!empty($settings['quick_abort_pct'])) + $conf .= "quick_abort_pct {$settings['quick_abort_pct']}\n"; $up_limit = ($settings['max_upload_size'] ? $settings['max_upload_size'] : 0); $down_limit = ($settings['max_download_size'] ? $settings['max_download_size'] : 0); $conf .= "request_body_max_size $up_limit KB\n"; - $conf .= 'reply_body_max_size ' . ($down_limit * 1024) . " deny all\n"; + if ($down_limit != 0) + $conf .= 'reply_body_max_size ' . $down_limit . " KB allsrc \n"; + // Only apply throttling past 10MB // XXX: Should this really be hardcoded? $threshold = 10 * 1024 * 1024; @@ -996,10 +1197,10 @@ EOD; $conf .= "# Throttle extensions matched in the url\n"; $conf .= "acl throttle_exts urlpath_regex -i \"" . SQUID_ACLDIR . "/throttle_exts.acl\"\n"; $conf .= "delay_access 1 allow throttle_exts\n"; - $conf .= "delay_access 1 deny all\n"; + $conf .= "delay_access 1 deny allsrc\n"; } else - $conf .= "delay_access 1 allow all\n"; + $conf .= "delay_access 1 allow allsrc\n"; return $conf; } @@ -1014,144 +1215,35 @@ function squid_get_server_certs() { return $cert_arr; } -function squid_resync_reverse() { - global $config, $valid_acls; - if(!is_array($valid_acls)) - return; - $settings = $config['installedpackages']['squidreverse']['config'][0]; - $conf = ''; - - $conf .= "# Reverse Proxy settings\n"; - - if(isset($settings["reverse_ssl_cert"]) && $settings["reverse_ssl_cert"] != "none") { - $svr_cert = lookup_cert($settings["reverse_ssl_cert"]); - if ($svr_cert != false) { - if(base64_decode($svr_cert['crt'])) { - file_put_contents(SQUID_CONFBASE . "/{$settings["reverse_ssl_cert"]}.crt",base64_decode($svr_cert['crt'])); - $reverse_crt = SQUID_CONFBASE . "/{$settings["reverse_ssl_cert"]}.crt"; - } - if(base64_decode($svr_cert['prv'])) { - file_put_contents(SQUID_CONFBASE . "/{$settings["reverse_ssl_cert"]}.key",base64_decode($svr_cert['prv'])); - $reverse_key = SQUID_CONFBASE . "/{$settings["reverse_ssl_cert"]}.key"; - }}} - - if (!empty($settings['reverse_int_ca'])) file_put_contents(SQUID_CONFBASE . "/{$settings["reverse_ssl_cert"]}.crt","\n" . base64_decode($settings['reverse_int_ca']),FILE_APPEND | LOCK_EX); - - $ifaces = ($settings['reverse_interface'] ? $settings['reverse_interface'] : 'wan'); - $real_ifaces = array(); - foreach (explode(",", $ifaces) as $i => $iface) { - $real_ifaces[] = squid_get_real_interface_address($iface); - if($real_ifaces[$i][0]) { - //HTTP - if (!empty($settings['reverse_http']) && empty($settings['reverse_http_port']) && empty($settings['reverse_http_defsite'])) $conf .= "http_port {$real_ifaces[$i][0]}:80 accel defaultsite={$settings['reverse_external_fqdn']} vhost\n"; - if (!empty($settings['reverse_http']) && (!empty($settings['reverse_http_port'])) && empty($settings['reverse_http_defsite'])) $conf .= "http_port {$real_ifaces[$i][0]}:{$settings['reverse_http_port']} accel defaultsite={$settings['reverse_external_fqdn']} vhost\n"; - if (!empty($settings['reverse_http']) && empty($settings['reverse_http_port']) && (!empty($settings['reverse_http_defsite']))) $conf .= "http_port {$real_ifaces[$i][0]}:80 accel defaultsite={$settings['reverse_http_defsite']} vhost\n"; - if (!empty($settings['reverse_http']) && (!empty($settings['reverse_http_port'])) && (!empty($settings['reverse_http_defsite']))) $conf .= "http_port {$real_ifaces[$i][0]}:{$settings['reverse_http_port']} accel defaultsite={$settings['reverse_http_defsite']} vhost\n"; - //HTTPS - if (!empty($settings['reverse_https']) && empty($settings['reverse_https_port']) && empty($settings['reverse_https_defsite'])) $conf .= "https_port {$real_ifaces[$i][0]}:443 cert={$reverse_crt} key={$reverse_key} defaultsite={$settings['reverse_external_fqdn']}\n"; - if (!empty($settings['reverse_https']) && (!empty($settings['reverse_https_port'])) && empty($settings['reverse_https_defsite'])) $conf .= "https_port {$real_ifaces[$i][0]}:{$settings['reverse_https_port']} cert={$reverse_crt} key={$reverse_key} defaultsite={$settings['reverse_external_fqdn']} vhost\n"; - if (!empty($settings['reverse_https']) && empty($settings['reverse_https_port']) && (!empty($settings['reverse_https_defsite']))) $conf .= "https_port {$real_ifaces[$i][0]}:443 cert={$reverse_crt} key={$reverse_key} defaultsite={$settings['reverse_https_defsite']} vhost\n"; - if (!empty($settings['reverse_https']) && (!empty($settings['reverse_https_port'])) && (!empty($settings['reverse_https_defsite']))) $conf .= "https_port {$real_ifaces[$i][0]}:{$settings['reverse_https_port']} cert={$reverse_crt} key={$reverse_key} defaultsite={$settings['reverse_https_defsite']} vhost\n"; - } - } - //PEERS - if (($settings['reverse_owa'] == 'on') && (!empty($settings['reverse_owa_ip']))) $conf .= "cache_peer {$settings['reverse_owa_ip']} parent 443 0 proxy-only no-query originserver login=PASS ssl sslflags=DONT_VERIFY_PEER front-end-https=auto name=OWA_HOST_pfs\n"; - - $contents = base64_decode($settings['reverse_cache_peer']); - if(!empty($contents)) { - $defs = explode("\r\n", ($contents)); - foreach ($defs as $def) { - $cfg = explode(";",($def)); - if (($cfg[0]) != '' && ($cfg[1]) != '' && ($cfg[2]) != ''){ - $conf .= "cache_peer {$cfg[1]} parent {$cfg[2]} 0 proxy-only no-query originserver "; - if($cfg[3] == 'HTTPS') - $conf .= "login=PASS ssl sslflags=DONT_VERIFY_PEER front-end-https=auto "; - $conf .= "name={$cfg[0]}\n"; - }}} - - //ACLs - if (($settings['reverse_owa'] == 'on') && (!empty($settings['reverse_owa_ip']))) { - $conf .= "acl OWA_URI_pfs url_regex -i ^https://{$settings['reverse_external_fqdn']}/owa.*$\n"; - $conf .= "acl OWA_URI_pfs url_regex -i ^https://{$settings['reverse_external_fqdn']}/exchange.*$\n"; - $conf .= "acl OWA_URI_pfs url_regex -i ^https://{$settings['reverse_external_fqdn']}/public.*$\n"; - $conf .= "acl OWA_URI_pfs url_regex -i ^https://{$settings['reverse_external_fqdn']}/exchwebexchweb.*$\n"; - } - if (($settings['reverse_owa'] == 'on') && (!empty($settings['reverse_owa_ip'])) && ($settings['reverse_owa_activesync'] == 'on')) { - $conf .= "acl OWA_URI_pfs url_regex -i ^https://{$settings['reverse_external_fqdn']}/Microsoft-Server-ActiveSync.*$\n"; - } - if (($settings['reverse_owa'] == 'on') && (!empty($settings['reverse_owa_ip'])) && ($settings['reverse_owa_rpchttp'] == 'on')) { - $conf .= "acl OWA_URI_pfs url_regex -i ^https://{$settings['reverse_external_fqdn']}/rpc/rpcproxy.dll.*$\n"; - $conf .= "extension_methods RPC_IN_DATA RPC_OUT_DATA\n"; - } - - $contents = base64_decode($settings['revrse_uri']); - if(!empty($contents)) { - $defs = explode("\r\n", ($contents)); - foreach ($defs as $def) { - $cfg = explode(";",($def)); - if (($cfg[0]) != '' && ($cfg[1]) != ''){ - if($cfg[2] != '') - $conf .= "acl {$cfg[0]} url_regex -i {$cfg[2]}/{$cfg[1]}.*$\n"; - if($cfg[2] == '') - $conf .= "acl {$cfg[0]} url_regex -i {$settings['reverse_external_fqdn']}/{$cfg[1]}.*$\n"; - }}} - - - //ACCESS - if (($settings['reverse_owa'] == 'on') && (!empty($settings['reverse_owa_ip']))) { - $conf .= "cache_peer_access OWA_HOST_pfs allow OWA_URI_pfs\n"; - $conf .= "cache_peer_access OWA_HOST_pfs deny all\n"; - $conf .= "never_direct allow OWA_URI_pfs\n"; - $conf .= "http_access allow OWA_URI_pfs\n"; - } - - $contents = base64_decode($settings['reverse_acl']); - if(!empty($contents)) { - $defs = explode("\r\n", ($contents)); - foreach ($defs as $def) { - $cfg = explode(";",($def)); - if (($cfg[0]) != '' && ($cfg[1]) != ''){ - $conf .= "cache_peer_access {$cfg[0]} allow {$cfg[1]}\n"; - }} - foreach ($defs as $def) { - $cfg = explode(";",($def)); - if (($cfg[0]) != '' && ($cfg[1]) != ''){ - $conf .= "cache_peer_access {$cfg[0]} deny all\n"; - }} - foreach ($defs as $def) { - $cfg = explode(";",($def)); - if (($cfg[0]) != '' && ($cfg[1]) != ''){ - $conf .= "never direct allow {$cfg[1]}\n"; - }} - foreach ($defs as $def) { - $cfg = explode(";",($def)); - if (($cfg[0]) != '' && ($cfg[1]) != ''){ - $conf .= "http_access allow {$cfg[1]}\n"; - }} - } - - $conf .= "\n"; - - if (!empty($settings['deny_info_tcp_reset'])) $conf .= "deny_info TCP_RESET all\n"; - return $conf; -} +#squid reverse +include('/usr/local/pkg/squid_reverse.inc'); function squid_resync_auth() { global $config, $valid_acls; - $settings = $config['installedpackages']['squidauth']['config'][0]; - $settingsnac = $config['installedpackages']['squidnac']['config'][0]; - $settingsconfig = $config['installedpackages']['squid']['config'][0]; + if (is_array($config['installedpackages']['squidauth']['config'])) + $settings = $config['installedpackages']['squidauth']['config'][0]; + else + $settings = array(); + + if (is_array($config['installedpackages']['squidnac']['config'])) + $settingsnac = $config['installedpackages']['squidnac']['config'][0]; + else + $settingsnac = array(); + + if (is_array($config['installedpackages']['squid']['config'])) + $settingsconfig = $config['installedpackages']['squid']['config'][0]; + else + $settingsconfig = array(); + $conf = ''; - // Custom Options - if(!empty($config['installedpackages']['squid']['config'][0]['custom_options'])) { - $custopts = explode(";", ($config['installedpackages']['squid']['config'][0]['custom_options'])); - $conf .= "# Custom options\n"; - foreach ($custopts as $custopt) { - $conf .= $custopt."\n"; - } - } + // Package integration + if(!empty($settingsconfig['custom_options'])) + $conf.="# Package Integration\n".preg_replace('/;/',"\n",$settingsconfig['custom_options'])."\n\n"; + + // Custom User Options + $conf .= "# Custom options\n".sq_text_area_decode($settingsconfig['custom_options_squid3'])."\n\n"; // Deny the banned guys before allowing the good guys if(! empty($settingsnac['banned_hosts'])) { @@ -1167,9 +1259,9 @@ function squid_resync_auth() { } } - // Unrestricted hosts take precendence over blacklist + // Unrestricted hosts take precedence over blacklist if(! empty($settingsnac['unrestricted_hosts'])) { - if (squid_is_valid_acl('unrestricted_hosts')) { + if (squid_is_valid_acl('unrestricted_hosts') && $settings['unrestricted_auth']!= "on") { $conf .= "# These hosts do not have any restrictions\n"; $conf .= "http_access allow unrestricted_hosts\n"; } @@ -1181,7 +1273,7 @@ function squid_resync_auth() { } } - // Whitelist and blacklist also take precendence over other allow rules + // Whitelist and blacklist also take precedence over other allow rules if(! empty($settingsnac['whitelist'])) { if (squid_is_valid_acl('whitelist')) { $conf .= "# Always allow access to whitelist domains\n"; @@ -1222,19 +1314,19 @@ function squid_resync_auth() { $prompt = ($settings['auth_prompt'] ? $settings['auth_prompt'] : 'Please enter your credentials to access the proxy'); switch ($auth_method) { case 'local': - $conf .= 'auth_param basic program /usr/local/libexec/squid/ncsa_auth ' . SQUID_PASSWD . "\n"; + $conf .= 'auth_param basic program '.SQUID_LOCALBASE.'/libexec/squid/ncsa_auth ' . SQUID_PASSWD . "\n"; break; case 'ldap': $port = (isset($settings['auth_server_port']) ? ":{$settings['auth_server_port']}" : ''); $password = (isset($settings['ldap_pass']) ? "-w {$settings['ldap_pass']}" : ''); - $conf .= "auth_param basic program /usr/local/libexec/squid/squid_ldap_auth -v {$settings['ldap_version']} -b {$settings['ldap_basedomain']} -D {$settings['ldap_user']} $password -f \"{$settings['ldap_filter']}\" -u {$settings['ldap_userattribute']} -P {$settings['auth_server']}$port\n"; + $conf .= "auth_param basic program " . SQUID_LOCALBASE . "/libexec/squid/squid_ldap_auth -v {$settings['ldap_version']} -b {$settings['ldap_basedomain']} -D {$settings['ldap_user']} $password -f \"{$settings['ldap_filter']}\" -u {$settings['ldap_userattribute']} -P {$settings['auth_server']}$port\n"; break; case 'radius': $port = (isset($settings['auth_server_port']) ? "-p {$settings['auth_server_port']}" : ''); - $conf .= "auth_param basic program /usr/local/libexec/squid/squid_radius_auth -w {$settings['radius_secret']} -h {$settings['auth_server']} $port\n"; + $conf .= "auth_param basic program ". SQUID_LOCALBASE . "/libexec/squid/squid_radius_auth -w {$settings['radius_secret']} -h {$settings['auth_server']} $port\n"; break; case 'msnt': - $conf .= "auth_param basic program /usr/local/libexec/squid/msnt_auth\n"; + $conf .= "auth_param basic program ". SQUID_LOCALBASE . "/libexec/squid/msnt_auth\n"; squid_resync_msnt(); break; } @@ -1268,7 +1360,7 @@ EOD; } $conf .= "# Default block all to be sure\n"; - $conf .= "http_access deny all\n"; + $conf .= "http_access deny allsrc\n"; return $conf; } @@ -1290,7 +1382,10 @@ function squid_resync_users() { function squid_resync_msnt() { global $config; - $settings = $config['installedpackages']['squidauth']['config'][0]; + if (is_array($config['installedpackages']['squidauth'])) + $settings = $config['installedpackages']['squidauth']['config'][0]; + else + $settings = array(); $pdcserver = $settings['auth_server']; $bdcserver = str_replace(',',' ',$settings['msnt_secondary']); $ntdomain = $settings['auth_ntdomain']; @@ -1302,7 +1397,29 @@ function squid_resync_msnt() { function squid_resync() { global $config; + + # detect boot process + if (is_array($_POST)){ + if (preg_match("/\w+/",$_POST['__csrf_magic'])) + unset($boot_process); + else + $boot_process="on"; + } + + if (is_process_running('squid') && isset($boot_process)) + return; + conf_mount_rw(); + foreach (array( SQUID_CONFBASE, + SQUID_ACLDIR, + SQUID_BASE, + SQUID_LIB, + SQUID_SSL_DB ) as $dir) { + make_dirs($dir); + chown($dir, 'proxy'); + chgrp($dir, 'proxy'); + squid_chown_recursive($dir, 'proxy', 'proxy'); + } $conf = squid_resync_general() . "\n"; $conf .= squid_resync_cache() . "\n"; $conf .= squid_resync_redirector() . "\n"; @@ -1313,44 +1430,56 @@ function squid_resync() { $conf .= squid_resync_auth(); squid_resync_users(); squid_write_rcfile(); - - /* make sure pinger is executable */ - if(file_exists("/usr/local/libexec/squid/pinger")) - exec("chmod a+x /usr/local/libexec/squid/pinger"); - - foreach (array( SQUID_CONFBASE, - SQUID_ACLDIR, - SQUID_BASE ) as $dir) { - make_dirs($dir); - squid_chown_recursive($dir, 'proxy', 'proxy'); - } - + + if(!isset($boot_process)) + squid_sync_on_changes(); + + #write config file file_put_contents(SQUID_CONFBASE . '/squid.conf', $conf); - - $log_dir = $config['installedpackages']['squid']['config'][0]['log_dir'].'/'; - - if(!is_dir($log_dir)) { - log_error("Creating squid log dir $log_dir"); - make_dirs($log_dir); - squid_chown_recursive($log_dir, 'proxy', 'proxy'); - } - - squid_dash_z(); - - if (!is_service_running('squid')) { - log_error("Starting Squid"); - mwexec("/usr/local/sbin/squid -D"); - } else { - log_error("Reloading Squid for configuration sync"); - mwexec("/usr/local/sbin/squid -k reconfigure"); - } - - // Sleep for a couple seconds to give squid a chance to fire up fully. - for ($i=0; $i < 10; $i++) { - if (!is_service_running('squid')) - sleep(1); + + /* make sure pinger is executable */ + if(file_exists(SQUID_LOCALBASE . "/libexec/squid/pinger")) + exec("chmod a+x " . SQUID_LOCALBASE . "/libexec/squid/pinger"); + + $log_dir=""; + #check if squid is enabled + if (is_array($config['installedpackages']['squid']['config'])){ + if ($config['installedpackages']['squid']['config'][0]['active_interface']!= "") + $log_dir = $config['installedpackages']['squid']['config'][0]['log_dir'].'/'; + } + #check if squidreverse is enabled + else if (is_array($config['installedpackages']['squidreversegeneral']['config'])){ + if ($config['installedpackages']['squidreversegeneral']['config'][0]['reverse_interface'] != "") + $log_dir="/var/squid/logs/"; + } + #do not start squid if there is no log dir + if ($log_dir != ""){ + if(!is_dir($log_dir)) { + log_error("Creating squid log dir $log_dir"); + make_dirs($log_dir); + squid_chown_recursive($log_dir, 'proxy', 'proxy'); + } + + squid_dash_z(); + + if (!is_service_running('squid')) { + log_error("Starting Squid"); + mwexec(SQUID_LOCALBASE . "/sbin/squid -f " . SQUID_CONFFILE); + } + else { + if (!isset($boot_process)){ + log_error("Reloading Squid for configuration sync"); + mwexec(SQUID_LOCALBASE . "/sbin/squid -k reconfigure -f " . SQUID_CONFFILE); + } + } + + // Sleep for a couple seconds to give squid a chance to fire up fully. + for ($i=0; $i < 10; $i++) { + if (!is_service_running('squid')) + sleep(1); + } + filter_configure(); } - filter_configure(); conf_mount_ro(); } @@ -1493,7 +1622,42 @@ function squid_generate_rules($type) { global $config; $squid_conf = $config['installedpackages']['squid']['config'][0]; - + + //check captive portal option + $cp_file='/etc/inc/captiveportal.inc'; + $pfsense_version=preg_replace("/\s/","",file_get_contents("/etc/version")); + $port = ($settings['proxy_port'] ? $settings['proxy_port'] : 3128); + $cp_inc = file($cp_file); + $new_cp_inc=""; + $found_rule=0; + foreach ($cp_inc as $line){ + $new_line=$line; + //remove applied squid patch + if (preg_match('/} set 1 skipto 65314/',$line)){ + $found_rule++; + $new_line =""; + } + //add squid patch option based on current config + if (preg_match('/set 1 pass ip from any to/',$line) && $squid_conf['patch_cp']){ + $found_rule++; + $new_line = "\t".'$cprules .= "add {$rulenum} set 1 skipto 65314 ip from any to {$ips} '.$port.' in\n";'."\n"; + $new_line .= $line; + } + if (preg_match('/set 1 pass ip from {/',$line) && $squid_conf['patch_cp']){ + $found_rule++; + $new_line = "\t".'$cprules .= "add {$rulenum} set 1 skipto 65314 ip from {$ips} '.$port.' to any out\n";'."\n"; + $new_line .= $line; + } + $new_cp_inc .= $new_line; + } + if (!file_exists('/root/'.$pfsense_version.'.captiveportal.inc.backup')) { + copy ($cp_file,'/root/'.$pfsense_version.'.captiveportal.inc.backup'); + } + if($found_rule > 0){ + file_put_contents($cp_file,$new_cp_inc, LOCK_EX); + } + + //normal squid rule check if (($squid_conf['transparent_proxy'] != 'on') || ($squid_conf['allow_interface'] != 'on')) { return; } @@ -1617,16 +1781,21 @@ function squid_generate_rules($type) { } function squid_write_rcfile() { + /* Declare a variable for the SQUID_CONFFILE constant. */ + /* Then the variable can be referenced easily in the Heredoc text that generates the rc file. */ + $squid_conffile_var = SQUID_CONFFILE; + $squid_local_base = SQUID_LOCALBASE; $rc = array(); $rc['file'] = 'squid.sh'; $rc['start'] = <<<EOD -if [ -z "`ps auxw | grep "[s]quid -D"|awk '{print $2}'`" ];then - /usr/local/sbin/squid -D +if [ -z "`ps auxw | grep "[s]quid "|awk '{print $2}'`" ];then + {$squid_local_base}/sbin/squid -f {$squid_conffile_var} fi EOD; + $rc['stop'] = <<<EOD -/usr/local/sbin/squid -k shutdown +{$squid_local_base}/sbin/squid -k shutdown -f {$squid_conffile_var} # Just to be sure... sleep 5 killall -9 squid 2>/dev/null @@ -1634,14 +1803,140 @@ killall pinger 2>/dev/null EOD; $rc['restart'] = <<<EOD -if [ -z "`ps auxw | grep "[s]quid -D"|awk '{print $2}'`" ];then - /usr/local/sbin/squid -D +if [ -z "`ps auxw | grep "[s]quid "|awk '{print $2}'`" ];then + {$squid_local_base}/sbin/squid -f {$squid_conffile_var} else - /usr/local/sbin/squid -k reconfigure + {$squid_local_base}/sbin/squid -k reconfigure -f {$squid_conffile_var} fi EOD; conf_mount_rw(); write_rcfile($rc); + conf_mount_ro(); } + +/* Uses XMLRPC to synchronize the changes to a remote node */ +function squid_sync_on_changes() { + global $config, $g; + + log_error("[squid] xmlrpc sync is starting."); + $synconchanges = $config['installedpackages']['squidsync']['config'][0]['synconchanges']; + if(!$synconchanges) + return; + foreach ($config['installedpackages']['squidsync']['config'] as $rs ){ + foreach($rs['row'] as $sh){ + $sync_to_ip = $sh['ipaddress']; + $password = $sh['password']; + if($sh['username']) + $username = $sh['username']; + else + $username = 'admin'; + if($password && $sync_to_ip) + squid_do_xmlrpc_sync($sync_to_ip, $username, $password); + } + } + log_error("[squid] xmlrpc sync is ending."); +} +/* Do the actual XMLRPC sync */ +function squid_do_xmlrpc_sync($sync_to_ip, $username, $password) { + global $config, $g; + + if(!$username) + return; + + if(!$password) + return; + + if(!$sync_to_ip) + return; + + $xmlrpc_sync_neighbor = $sync_to_ip; + if($config['system']['webgui']['protocol'] != "") { + $synchronizetoip = $config['system']['webgui']['protocol']; + $synchronizetoip .= "://"; + } + $port = $config['system']['webgui']['port']; + /* if port is empty lets rely on the protocol selection */ + if($port == "") { + if($config['system']['webgui']['protocol'] == "http") + $port = "80"; + else + $port = "443"; + } + $synchronizetoip .= $sync_to_ip; + + /* xml will hold the sections to sync */ + $xml = array(); + $xml['squid'] = $config['installedpackages']['squid']; + $xml['squidupstream'] = $config['installedpackages']['squidupstream']; + $xml['squidcache'] = $config['installedpackages']['squidcache']; + $xml['squidnac'] = $config['installedpackages']['squidnac']; + $xml['squidtraffic'] = $config['installedpackages']['squidtraffic']; + $xml['squidreversegeneral'] = $config['installedpackages']['squidreversegeneral']; + $xml['squidreversepeer'] = $config['installedpackages']['squidreversepeer']; + $xml['squidreverseuri'] = $config['installedpackages']['squidreverseuri']; + $xml['squidauth'] = $config['installedpackages']['squidauth']; + $xml['squidusers'] = $config['installedpackages']['squidusers']; + /* assemble xmlrpc payload */ + $params = array( + XML_RPC_encode($password), + XML_RPC_encode($xml) + ); + + /* set a few variables needed for sync code borrowed from filter.inc */ + $url = $synchronizetoip; + log_error("Beginning squid XMLRPC sync to {$url}:{$port}."); + $method = 'pfsense.merge_installedpackages_section_xmlrpc'; + $msg = new XML_RPC_Message($method, $params); + $cli = new XML_RPC_Client('/xmlrpc.php', $url, $port); + $cli->setCredentials($username, $password); + if($g['debug']) + $cli->setDebug(1); + /* send our XMLRPC message and timeout after 250 seconds */ + $resp = $cli->send($msg, "250"); + if(!$resp) { + $error = "A communications error occurred while attempting squid XMLRPC sync with {$url}:{$port}."; + log_error($error); + file_notice("sync_settings", $error, "squid Settings Sync", ""); + } elseif($resp->faultCode()) { + $cli->setDebug(1); + $resp = $cli->send($msg, "250"); + $error = "An error code was received while attempting squid XMLRPC sync with {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString(); + log_error($error); + file_notice("sync_settings", $error, "squid Settings Sync", ""); + } else { + log_error("squid XMLRPC sync successfully completed with {$url}:{$port}."); + } + + /* tell squid to reload our settings on the destination sync host. */ + $method = 'pfsense.exec_php'; + $execcmd = "require_once('/usr/local/pkg/squid.inc');\n"; + $execcmd .= "squid_resync();"; + /* assemble xmlrpc payload */ + $params = array( + XML_RPC_encode($password), + XML_RPC_encode($execcmd) + ); + + log_error("squid XMLRPC reload data {$url}:{$port}."); + $msg = new XML_RPC_Message($method, $params); + $cli = new XML_RPC_Client('/xmlrpc.php', $url, $port); + $cli->setCredentials($username, $password); + $resp = $cli->send($msg, "250"); + if(!$resp) { + $error = "A communications error occurred while attempting squid XMLRPC sync with {$url}:{$port} (pfsense.exec_php)."; + log_error($error); + file_notice("sync_settings", $error, "squid Settings Sync", ""); + } elseif($resp->faultCode()) { + $cli->setDebug(1); + $resp = $cli->send($msg, "250"); + $error = "An error code was received while attempting squid XMLRPC sync with {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString(); + log_error($error); + file_notice("sync_settings", $error, "squid Settings Sync", ""); + } else { + log_error("squid XMLRPC reload data success with {$url}:{$port} (pfsense.exec_php)."); + } + +} + ?> |