Mail-SpamAssassin
view release on metacpan or search on metacpan
sa-update.raw view on Meta::CPAN
my $DEF_RULES_DIR = '@@DEF_RULES_DIR@@'; # substituted at 'make' time
my $LOCAL_RULES_DIR = '@@LOCAL_RULES_DIR@@'; # substituted at 'make' time
my $LOCAL_STATE_DIR = '@@LOCAL_STATE_DIR@@'; # substituted at 'make' time
use lib '@@INSTALLSITELIB@@'; # substituted at 'make' time
# We want to do a small amount of macro processing during channel installs,
# based on the values as passed in via 'make'
my %MACRO_VALUES = (
'VERSION' => '@@VERSION@@',
'CONTACT_ADDRESS' => '@@CONTACT_ADDRESS@@',
'PREFIX' => '@@PREFIX@@',
'DEF_RULES_DIR' => '@@DEF_RULES_DIR@@',
'LOCAL_RULES_DIR' => '@@LOCAL_RULES_DIR@@',
'LOCAL_STATE_DIR' => '@@LOCAL_STATE_DIR@@',
'INSTALLSITELIB' => '@@INSTALLSITELIB@@',
);
# Standard perl modules
use Errno qw(ENOENT EACCES);
use IO::File qw(O_RDONLY O_WRONLY O_RDWR O_CREAT O_EXCL);
use File::Spec;
use File::Path;
use Getopt::Long;
use Pod::Usage;
use Config;
use POSIX qw(locale_h setsid sigprocmask _exit);
POSIX::setlocale(LC_TIME,'C');
BEGIN { # see comments in "spamassassin.raw" for doco
my @bin = File::Spec->splitpath($0);
my $bin = ($bin[0] ? File::Spec->catpath(@bin[0..1], '') : $bin[1])
|| File::Spec->curdir;
if (-e $bin.'/lib/Mail/SpamAssassin.pm'
|| !-e '@@INSTALLSITELIB@@/Mail/SpamAssassin.pm' )
{
my $searchrelative;
$searchrelative = 1; # disabled during "make install": REMOVEFORINST
if ($searchrelative && $bin eq '../' && -e '../blib/lib/Mail/SpamAssassin.pm')
{
unshift ( @INC, '../blib/lib' );
} else {
foreach ( qw(lib ../lib/site_perl
../lib/spamassassin ../share/spamassassin/lib))
{
my $dir = File::Spec->catdir( $bin, split ( '/', $_ ) );
if ( -f File::Spec->catfile( $dir, "Mail", "SpamAssassin.pm" ) )
{ unshift ( @INC, $dir ); last; }
}
}
}
}
# These are the non-standard required modules
use Net::DNS;
use Archive::Tar 1.23;
use IO::Zlib 1.04;
use Mail::SpamAssassin::Logger qw(:DEFAULT info log_message);
our ($have_lwp, $io_socket_module_name, $have_inet4, $use_inet4, $have_inet6, $use_inet6, $have_sha256, $have_sha512);
BEGIN {
# Deal with optional modules
eval { require Digest::SHA; Digest::SHA->import(qw(sha256_hex sha512_hex)); 1 } and do { $have_sha256=1; $have_sha512=1 }
or die "Unable to verify file hashes! You must install a modern version of Digest::SHA.";
$have_lwp = eval {
require LWP::UserAgent;
require LWP::Protocol::https;
};
if (eval { require IO::Socket::IP }) { # handles IPv6 and IPv4
$io_socket_module_name = 'IO::Socket::IP';
} elsif (eval { require IO::Socket::INET6 }) { # handles IPv6 and IPv4
$io_socket_module_name = 'IO::Socket::INET6';
} elsif (eval { require IO::Socket::INET }) { # IPv4 only
$io_socket_module_name = 'IO::Socket::INET';
}
$have_inet4 = # can we create a PF_INET socket?
defined $io_socket_module_name && eval {
my $sock =
$io_socket_module_name->new(LocalAddr => '0.0.0.0', Proto => 'tcp');
$sock->close or die "error closing socket: $!" if $sock;
$sock ? 1 : undef;
};
$have_inet6 = # can we create a PF_INET6 socket?
defined $io_socket_module_name &&
$io_socket_module_name ne 'IO::Socket::INET' &&
eval {
my $sock =
$io_socket_module_name->new(LocalAddr => '::', Proto => 'tcp');
$sock->close or die "error closing socket: $!" if $sock;
$sock ? 1 : undef;
};
}
# These should already be available
use Mail::SpamAssassin;
use Mail::SpamAssassin::Util qw(untaint_var untaint_file_path
proc_status_ok exit_status_str am_running_on_windows
secure_tmpfile secure_tmpdir);
# Make the main dbg() accessible in our package w/o an extra function
*dbg=\&Mail::SpamAssassin::dbg;
sub dbg;
$| = 1; # autoflushing STDOUT makes verbose output consistent with warnings
# Clean up PATH appropriately
Mail::SpamAssassin::Util::clean_path_in_taint_mode();
##############################################################################
# Default list of GPG keys allowed to sign update releases
#
# pub 4096R/5244EC45 2005-12-20
# Key fingerprint = 5E54 1DC9 59CB 8BAC 7C78 DFDC 4056 A61A 5244 EC45
# uid updates.spamassassin.org Signing Key <release@spamassassin.org>
# sub 4096R/24F434CE 2005-12-20
#
# note for gpg newbs: these are "long" gpg keyids. It's common to also
# use the last 8 hex digits as a shorter keyid string.
#
my %valid_GPG = (
'0C2B1D7175B852C64B3CDC716C55397824F434CE' => 1,
'5E541DC959CB8BAC7C78DFDC4056A61A5244EC45' => 1,
);
# Default list of channels to update against
#
my @channels = ( 'updates.spamassassin.org' );
my $IGNORE_MIRBY_OLDER_THAN = (24 * 60 * 60 * 7); # 1 week
##############################################################################
my %opt;
@{$opt{'gpgkey'}} = ();
@{$opt{'channel'}} = ();
my $GPG_ENABLED = 1;
$opt{'gpghomedir'} = File::Spec->catfile($LOCAL_RULES_DIR, 'sa-update-keys');
Getopt::Long::Configure(
qw(bundling no_getopt_compat no_auto_abbrev no_ignore_case));
GetOptions(
'debug|D:s' => \$opt{'debug'},
'version|V' => \$opt{'version'},
'help|h|?' => \$opt{'help'},
'verbose|v+' => \$opt{'verbose'},
'checkonly' => \$opt{'checkonly'},
'allowplugins' => \$opt{'allowplugins'},
'reallyallowplugins' => \$opt{'reallyallowplugins'},
'refreshmirrors' => \$opt{'refreshmirrors'},
'forcemirror=s' => \$opt{'forcemirror'},
'httputil=s' => \$opt{'httputil'},
'score-multiplier=s' => \$opt{'score-multiplier'},
'score-limit=s' => \$opt{'score-limit'},
# allow multiple of these on the commandline
'gpgkey=s' => $opt{'gpgkey'},
'gpghomedir=s' => \$opt{'gpghomedir'},
'channel=s' => $opt{'channel'},
'install=s' => \$opt{'install'},
'import=s' => \$opt{'import'},
'gpgkeyfile=s' => \$opt{'gpgkeyfile'},
'channelfile=s' => \$opt{'channelfile'},
'updatedir=s' => \$opt{'updatedir'},
'gpg!' => \$GPG_ENABLED,
'4' => sub { $opt{'force_pf'} = 'inet' },
'6' => sub { $opt{'force_pf'} = 'inet6' },
# backward compatibility
'usegpg' => \$GPG_ENABLED,
) or print_usage_and_exit();
if ( defined $opt{'help'} ) {
print_usage_and_exit("For more information read the sa-update man page.\n", 0);
}
if ( defined $opt{'version'} ) {
print_version();
exit(0);
}
if ( $opt{'allowplugins'} && !$opt{'reallyallowplugins'} ) {
warn "Security warning: dangerous option --allowplugins used:\n".
"- there should never be need to use this option, see man sa-update(1)\n".
"- specify --reallyallowplugins to allow activating plugins\n";
exit 2;
}
$use_inet4 = $have_inet4 && ( !$opt{'force_pf'} || $opt{'force_pf'} eq 'inet' );
$use_inet6 = $have_inet6 && ( !$opt{'force_pf'} || $opt{'force_pf'} eq 'inet6' );
if ( $opt{'force_pf'} && $opt{'force_pf'} eq 'inet' && !$have_inet4 ) {
warn "Option -4 specified but support for the ".
"INET protocol family is not available.\n";
}
if ( $opt{'force_pf'} && $opt{'force_pf'} eq 'inet6' && !$have_inet6 ) {
warn "Option -6 specified but support for the ".
"INET6 protocol family is not available.\n";
}
if ( defined $opt{'httputil'} && $opt{'httputil'} !~ /^(curl|wget|fetch|lwp)$/ ) {
warn "Invalid parameter for --httputil, curl|wget|fetch|lwp wanted\n";
}
if ( defined $opt{'score-multiplier'} && $opt{'score-multiplier'} !~ /^\d+(?:\.\d+)?$/ ) {
die "Invalid parameter for --score-multiplier, integer or float expected.\n";
}
if ( defined $opt{'score-limit'} && $opt{'score-limit'} !~ /^\d+(?:\.\d+)?$/ ) {
die "Invalid parameter for --score-limit, integer or float expected.\n";
}
# Figure out what version of SpamAssassin we're using, and also figure out the
# reverse of it for the DNS query. Handle x.yyyzzz as well as x.yz.
my $SAVersion = $Mail::SpamAssassin::VERSION;
if ($SAVersion =~ /^(\d+)\.(\d{3})(\d{3})$/) {
$SAVersion = join(".", $1+0, $2+0, $3+0);
}
elsif ($SAVersion =~ /^(\d)\.(\d)(\d)$/) {
$SAVersion = "$1.$2.$3";
}
else {
die "fatal: SpamAssassin version number '$SAVersion' is in an unknown format!\n";
}
my $RevSAVersion = join(".", reverse split(/\./, $SAVersion));
# set debug areas, if any specified (only useful for command-line tools)
$opt{'debug'} ||= 'all' if (defined $opt{'debug'});
# Find the default site rule directory, also setup debugging and other M::SA bits
my $SA = Mail::SpamAssassin->new({
debug => $opt{'debug'},
local_tests_only => 1,
dont_copy_prefs => 1,
PREFIX => $PREFIX,
DEF_RULES_DIR => $DEF_RULES_DIR,
LOCAL_RULES_DIR => $LOCAL_RULES_DIR,
LOCAL_STATE_DIR => $LOCAL_STATE_DIR,
});
if (defined $opt{'updatedir'}) {
$opt{'updatedir'} = untaint_file_path($opt{'updatedir'});
}
else {
$opt{'updatedir'} = $SA->sed_path('__local_state_dir__/__version__');
}
# check only disabled gpg
# https://bz.apache.org/SpamAssassin/show_bug.cgi?id=5854
if ( defined $opt{'checkonly'}) {
$GPG_ENABLED=0;
dbg("gpg: Disabling gpg requirement due to checkonly flag.");
}
sa-update.raw view on Meta::CPAN
dbg("channel: current version is $currentV, new version is $newV, ".
"skipping channel");
next;
}
print "Update available for channel $channel: $currentV -> $newV\n" if $opt{'verbose'};
# If we are only checking for update availability, exit now
if ( defined $opt{'checkonly'} ) {
dbg("channel: $channel: update available, not downloading ".
"in checkonly mode");
$channel_successes++;
next;
}
}
# we need a directory we control that we can use to avoid loading any rules
# when we lint the site pre files, we might as well use the channel temp dir
dbg("channel: preparing temp directory for new channel");
if (!$UPDTmp) {
$UPDTmp = secure_tmpdir();
dbg("channel: created tmp directory $UPDTmp");
}
else {
dbg("channel: using existing tmp directory $UPDTmp");
if (!clean_update_dir($UPDTmp)) {
die "channel: attempt to clean update temp dir failed, aborting";
}
}
# lint the site pre files (that will be used when lint checking the channel)
# before downloading the channel update
unless ($site_pre_linted) {
dbg("generic: lint checking site pre files once before attempting channel updates");
unless (lint_check_dir(File::Spec->catfile($UPDTmp, "doesnotexist"))) {
dbg("generic: lint of site pre files failed, cannot continue");
print "Lint of site pre files failed, cannot continue\n" if $opt{'verbose'};
$lint_failures++;
last;
}
dbg("generic: lint check of site pre files succeeded, continuing with channel updates");
$site_pre_linted = 1;
}
my $content;
my $SHA512;
my $SHA256;
my $GPG;
if ($instfile) {
dbg("channel: using --install files $instfile\{,.asc,.sha512,.sha256\}");
$content = read_install_file($instfile);
if ( -f "$instfile.sha512" ) { $SHA512 = read_install_file($instfile.".sha512"); }
if ( -f "$instfile.sha256" ) { $SHA256 = read_install_file($instfile.".sha256"); }
$GPG = read_install_file($instfile.".asc") if $GPG_ENABLED;
} else { # not an install file, obtain fresh rules from network
dbg("channel: protocol family available: %s%s",
join(',', $have_inet4 ? 'inet' : (),
$have_inet6 ? 'inet6' : ()),
$opt{'force_pf'} ? '; force '.$opt{'force_pf'} : '' );
# test if the MIRRORED.BY file for this channel exists,
# is nonempty, and is reasonably fresh
my(@mirr_stat_list) = stat($mirby_path);
if (!@mirr_stat_list) {
if ($! == ENOENT) {
dbg("channel: no mirror file %s, will fetch it", $mirby_path);
} else {
# protection error, misconfiguration, file system error, ...
warn "error: error accessing mirrors file $mirby_path: $!\n";
channel_failed("channel '$channel': error accessing mirrors file $mirby_path: $!");
next;
}
} elsif (-z _) {
dbg("channel: file %s is empty, refreshing mirrors file", $mirby_path);
$mirby_force_reload = 1;
} elsif ($opt{'refreshmirrors'}) {
dbg("channel: --refreshmirrors used, forcing mirrors file refresh ".
"on channel $channel");
$mirby_force_reload = 1;
} elsif (time - $mirr_stat_list[9] > $IGNORE_MIRBY_OLDER_THAN) {
dbg("channel: file %s is too old, refreshing mirrors file", $mirby_path);
$mirby_file_is_ok = 1; # mirrors file seems fine, but is old
$mirby_force_reload = 1;
} else {
# mirror file $mirby_path exists, is nonempty, and is reasonably fresh
$mirby_file_is_ok = 1;
}
if (!$mirby_file_is_ok || $mirby_force_reload) {
# fetch a fresh list of mirrors
dbg("channel: DNS lookup on mirrors.$channel");
my @mirrors = do_dns_query("mirrors.$channel");
unless (@mirrors) {
warn "error: no mirror data available for channel $channel\n";
channel_failed("channel '$channel': MIRRORED.BY file URL was not in DNS");
next;
}
# make sure requests spread randomly
Mail::SpamAssassin::Util::fisher_yates_shuffle(\@mirrors);
foreach my $mirror (@mirrors) {
my ($result_fname, $http_ok) =
http_get($mirror, $UPDDir, $mirby_path, $mirby_force_reload);
if (!$http_ok) {
dbg("channel: no mirror data available for channel %s from %s",
$channel, $mirror);
next;
}
$mirby = read_content($result_fname, 0);
if ($mirby) {
dbg("channel: MIRRORED.BY file for channel %s retrieved", $channel);
$mirby_file_is_ok = 1;
$mirby_force_reload = 0;
$preserve_files{$mirby_path} = 1;
# set file creation time to now, otherwise we'll keep refreshing
# (N.B.: curl preserves time of a downloaded file)
my $now = time;
sa-update.raw view on Meta::CPAN
last;
}
$mirror =~ s/#.*$//; # remove comments
$mirror =~ s/^\s+//; # remove leading whitespace
$mirror =~ s/\s+$//; # remove tailing whitespace
next if $mirror eq ''; # skip empty lines
# We only support HTTP (and HTTPS) right now
if ($mirror !~ m{^https?://}i) {
dbg("channel: skipping non-HTTP mirror: $mirror");
next;
}
dbg("channel: found mirror $mirror");
my @data;
($mirror,@data) = split(/\s+/, $mirror);
$mirror =~ s{/+\z}{}; # http://example.com/updates/ -> .../updates
$mirrors{$mirror}->{weight} = 1;
foreach (@data) {
my($k,$v) = split(/=/, $_, 2);
$mirrors{$mirror}->{$k} = $v;
}
}
unless (%mirrors) {
warn "error: no mirrors available for channel $channel\n";
channel_failed("channel '$channel': no mirrors available");
next;
}
# Now that we've laid the foundation, go grab the appropriate files
#
my $path_content = File::Spec->catfile($UPDDir, "$newV.tar.gz");
my $path_sha512 = File::Spec->catfile($UPDDir, "$newV.tar.gz.sha512");
my $path_sha256 = File::Spec->catfile($UPDDir, "$newV.tar.gz.sha256");
my $path_asc = File::Spec->catfile($UPDDir, "$newV.tar.gz.asc");
# Loop through all available mirrors, choose from them randomly
# if any get fails, choose another mirror to retry _all_ files again
# sleep few seconds on retries
my $download_ok = 0;
while (my $mirror = choose_mirror(\%mirrors)) {
my ($result_fname, $http_ok);
# Grab the data hash for this mirror, then remove it from the list
my $mirror_info = $mirrors{$mirror};
delete $mirrors{$mirror};
# Make sure we start without files from existing tries
unlink($path_content);
unlink($path_sha512);
unlink($path_sha256);
unlink($path_asc);
my $sleep_sec = 2;
if (!check_mirror_af($mirror)) {
my @my_af;
push(@my_af, "IPv4") if $use_inet4;
push(@my_af, "IPv6") if $use_inet6;
push(@my_af, "no IP service") if !@my_af;
dbg("reject mirror %s: no common address family (%s), %s",
$mirror, join(" ", @my_af),
%mirrors ? "sleeping $sleep_sec sec and trying next" : 'no mirrors left');
sleep($sleep_sec) if %mirrors;
next;
}
dbg("channel: selected mirror $mirror");
# Actual archive file
($result_fname, $http_ok) = http_get("$mirror/$newV.tar.gz", $UPDDir);
if (!$http_ok || !-s $result_fname) {
dbg("channel: failed to get $newV.tar.gz from mirror $mirror, %s",
%mirrors ? "sleeping $sleep_sec sec and trying next" : 'no mirrors left');
sleep($sleep_sec) if %mirrors;
next;
}
# if GPG is enabled, the GPG detached signature of the archive file
if ($GPG_ENABLED) {
($result_fname, $http_ok) = http_get("$mirror/$newV.tar.gz.asc", $UPDDir);
if (!$http_ok || !-s $result_fname) {
dbg("channel: No GPG/asc file available from $mirror, %s",
%mirrors ? "sleeping $sleep_sec sec and trying next" : 'no mirrors left');
sleep($sleep_sec) if %mirrors;
next;
}
}
else {
# SHA512 of the archive file
($result_fname, $http_ok) = http_get("$mirror/$newV.tar.gz.sha512", $UPDDir);
if (!$http_ok || !-s $result_fname) {
# If not found, try SHA256 instead
($result_fname, $http_ok) = http_get("$mirror/$newV.tar.gz.sha256", $UPDDir);
if (!$http_ok || !-s $result_fname) {
dbg("channel: No sha512 or sha256 file available from $mirror, %s",
%mirrors ? "sleeping $sleep_sec sec and trying next" : 'no mirrors left');
sleep($sleep_sec) if %mirrors;
next;
}
}
}
$download_ok = 1;
last;
}
if ($download_ok) {
if (-s $path_content) {
$content = read_content($path_content, 1); # binary
$preserve_files{$path_content} = 1;
}
if (-s $path_sha512) {
$SHA512 = read_content($path_sha512, 0); # ascii
$preserve_files{$path_sha512} = 1;
}
if (-s $path_sha256) {
$SHA256 = read_content($path_sha256, 0); # ascii
$preserve_files{$path_sha256} = 1;
sa-update.raw view on Meta::CPAN
}
return @files;
failed:
return; # undef = failure
}
##############################################################################
# Do a generic DNS query
sub do_dns_query {
my($query, $rr_type) = @_;
$rr_type = 'TXT' if !defined $rr_type;
my $RR = $res->query($query, $rr_type);
my @result;
# NOTE: $rr->rdatastr returns the result encoded in a DNS zone file
# format, i.e. enclosed in double quotes if a result contains whitespace
# (or other funny characters), and may use \DDD encoding or \X quoting as
# per RFC 1035. Using $rr->txtdata instead avoids this unnecessary encoding
# step and a need for decoding by a caller, returning an unmodified string.
# Caveat: in case of multiple RDATA <character-string> fields contained
# in a resource record (TXT, SPF, HINFO), starting with Net::DNS 0.69
# the $rr->txtdata in a list context returns these strings as a list.
# The $rr->txtdata in a scalar context always returns a single string
# with <character-string> fields joined by a single space character as
# a separator. The $rr->txtdata in Net::DNS 0.68 and older returned
# such joined space-separated string even in a list context.
#
# From Net::DNS maintainers (Willem Toorop, NLnet Labs):
# I encourage you to use txtdata for getting the values of
# <version>.updates.spamassassin.org and mirrors.updates.spamassassin.org.
# As those records have only a single rdata field, txtdata would return
# the same value since Net::DNS 0.34.
#
if ($RR) {
foreach my $rr ($RR->answer) {
next if !$rr; # no answer records, only rcode
next if $rr->type ne $rr_type;
# scalar context!
my $text = $rr->UNIVERSAL::can('txtdata') ? $rr->txtdata : $rr->rdstring;
push(@result,$text) if defined $text && $text ne '';
}
printf("DNS %s query: %s -> %s\n", $rr_type, $query, join(", ",@result))
if $opt{'verbose'} && $opt{'verbose'} > 1;
}
else {
dbg("dns: query failed: $query => " . $res->errorstring);
printf("DNS %s query %s failed: %s\n", $rr_type, $query, $res->errorstring)
if $opt{'verbose'} && $opt{'verbose'} > 1;
}
return @result;
}
##############################################################################
sub init_lwp {
if ($have_inet6 &&
(!$opt{'force_pf'} || $opt{'force_pf'} eq 'inet6') &&
($io_socket_module_name eq 'IO::Socket::IP' ||
$io_socket_module_name eq 'IO::Socket::INET6') )
{
# LWP module has no support for IPv6. Use hotpatching,
# copying IO::Socket::IP or IO::Socket::INET6 to IO::Socket::INET.
# 'Borrowed' from Net::INET6Glue::INET_is_INET6 :
printf("http: (lwp) hotpatching IO::Socket::INET by module %s\n",
$io_socket_module_name) if $opt{'verbose'};
my $io_socket_module_hash_name = $io_socket_module_name . '::';
my $io_socket_module_path = $io_socket_module_name . '.pm';
$io_socket_module_path =~ s{::}{/}g;
$INC{'IO/Socket/INET.pm'} = $INC{$io_socket_module_path};
no strict 'refs';
no warnings 'redefine';
for ( keys %{$io_socket_module_hash_name} ) {
ref(my $v = $io_socket_module_hash_name->{$_}) and next;
*{ 'IO::Socket::INET::'.$_ } =
\&{ $io_socket_module_hash_name . $_ } if *{$v}{CODE};
}
}
my $ua = LWP::UserAgent->new();
$ua->agent("sa-update/$VERSION/$SAVersion");
$ua->timeout(60); # a good long timeout; 10 is too short for Coral!
$ua->env_proxy;
# if ($opt{'force_pf'}) {
# # No longer needed and can be harmful as we don't know which address family
# # will be picked by the IO::Socket::* module in case of multihomed servers.
# # The IO::Socket::IP should choose the right protocol family automatically.
# if ($have_inet4 && $opt{'force_pf'} eq 'inet') {
# $ua->local_address('0.0.0.0');
# } elsif ($have_inet6 && $opt{'force_pf'} eq 'inet6') {
# $ua->local_address('::');
# }
# }
return $ua;
}
# Do a GET request via HTTP for a certain URL
# Use the optional time_t value to do an IMS GET
sub http_get_lwp {
my($url, $ims, $dir) = @_;
$have_lwp or die "http_get_lwp: module LWP not available";
$ua = init_lwp() if !$ua;
my $response;
my $text;
# retry 3 times; this works better with Coral
foreach my $retries (1 .. 3) {
my $request = HTTP::Request->new("GET");
$request->url($url);
if (defined $ims) {
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) = gmtime($ims);
my $str = sprintf("%s, %02d %s %04d %02d:%02d:%02d GMT",
qw(Sun Mon Tue Wed Thu Fri Sat)[$wday], $mday,
qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)[$mon],
$year + 1900, $hour, $min, $sec);
$request->header('If-Modified-Since', $str);
dbg("http: IMS GET request, $url, $str");
}
else {
dbg("http: GET request, $url");
}
$response = $ua->request($request);
printf("http: (lwp) %sGET %s, %s\n",
defined $ims ? 'IMS ' : '', $url,
!$response ? '(no response)' : $response->status_line )
if $opt{'verbose'};
if ($response->is_success) {
return $response->content;
}
# could be a "304 not modified" or similar.
# TODO: should use a special return type for "not modified" here
# instead of overloading the failure return type
if ($ims && $response->status_line =~ /^3/) {
return;
}
if ($response->status_line =~ /^[45]/) {
# client error or server error, makes no sense retrying
return;
}
# include the text in the debug output; it's useful in some cases,
# e.g. proxies that require authentication, diagnosing fascist
sa-update.raw view on Meta::CPAN
if (!$have_lwp) {
die "http: module LWP not available, download failed";
}
} else {
$ext_prog = $opt{'httputil'};
$cmd = Mail::SpamAssassin::Util::find_executable_in_env_path($ext_prog);
if (!defined $cmd || $cmd eq '') {
die "http: $ext_prog utility not found, download failed";
}
}
} else {
foreach my $try_prog ('curl', 'wget', 'fetch') {
$cmd = Mail::SpamAssassin::Util::find_executable_in_env_path($try_prog);
if (defined $cmd && $cmd ne '') { $ext_prog = $try_prog; last }
}
}
if (defined $ext_prog && $ext_prog eq 'curl') {
push(@args, qw(-s -L -O --remote-time -g --max-redirs 2
--connect-timeout 30 --max-time 300
--fail -o), $out_fname_short);
push(@args, '-z', $out_fname_short) if $out_fname_exists && !$force_reload;
push(@args, '-A', "sa-update/$VERSION/$SAVersion");
} elsif (defined $ext_prog && $ext_prog eq 'wget') {
push(@args, qw(-q --max-redirect=2 --tries=3
--dns-timeout=20 --connect-timeout=30 --read-timeout=300));
push(@args, defined $suggested_out_fname ? ('-O', $out_fname_short)
: $force_reload ? () : ('-N') );
push(@args, '-U', "sa-update/$VERSION/$SAVersion");
} elsif (defined $ext_prog && $ext_prog eq 'fetch') {
push(@args, qw(-q -n -a -w 20 -m -o), $out_fname_short);
push(@args, '-m') if $out_fname_exists && !$force_reload;
push(@args, "--user-agent=sa-update/$VERSION/$SAVersion");
} elsif ($have_lwp) {
dbg("http: no external tool for download, fallback to using LWP") if !$opt{'httputil'};
my $ims;
if ($out_fname_exists && !$force_reload) {
my @out_fname_stat = stat($out_fname);
my $size = $out_fname_stat[7];
$ims = $out_fname_stat[9] if $size; # only if nonempty
}
my $out_fh = IO::File->new;
$out_fh->open($out_fname,'>',0640)
or die "Cannot create a file $out_fname: $!";
binmode($out_fh) or die "Can't set binmode on $out_fname: $!";
$content = http_get_lwp($url, $ims, $dir);
if (!defined $content) {
dbg("http: (lwp) no content downloaded from %s", $url);
} else {
$out_fh->print($content) or die "Error writing to $out_fname: $!";
}
$out_fh->close or die "Error closing file $out_fname: $!";
return ($out_fname, 1);
} else {
die "http: no downloading tool available";
}
# only reached if invoking an external program is needed (not lwp)
if ($opt{'force_pf'}) {
if ($opt{'force_pf'} eq 'inet') { push(@args, '-4') }
elsif ($opt{'force_pf'} eq 'inet6') { push(@args, '-6') }
}
push(@args, '--', untaint_var($url));
dbg("http: %s", join(' ',$cmd,@args));
# avoid a system() call, use fork/exec to make sure we avoid invoking a shell
my $pid;
eval {
# use eval, the fork() sometimes signals an error
# instead of returning a failure status
$pid = fork(); 1;
} or do { $@ = "errno=$!" if $@ eq ''; chomp $@; die "http fork: $@" };
defined $pid or die "spawning $cmd failed: $!";
if (!$pid) { # child
chdir($dir) or die "Can't chdir to $dir: $!";
$cmd = untaint_file_path($cmd);
exec {$cmd} ($cmd,@args);
die "failed to exec $cmd: $!";
}
# parent
waitpid($pid,0);
my $child_stat = $?;
dbg("http: process [%s], exit status: %s",
$pid, exit_status_str($child_stat,0));
if (!$opt{'verbose'}) {
# silent
} elsif ($child_stat == 0) {
printf("http: (%s) GET %s, success\n", $ext_prog, $url);
} else {
printf("http: (%s) GET %s, FAILED, status: %s\n",
$ext_prog, $url, exit_status_str($child_stat,0));
}
return ($out_fname, $child_stat == 0);
}
# Read the content of a (downloaded) file. The subroutine expects a file name
# and a boolean value. The boolean value indicates whether the file should be
# opened in "text" mode or in "binary" mode. Pass 0 for text mode, 1 for binary
# mode. Returns the content of the file as a string.
sub read_content {
my ($file_name, $binary_mode) = @_;
my $file = IO::File->new;
if (!$file->open($file_name, '<')) {
dbg("read_content: Cannot open file $file_name: $!");
return undef; ## no critic (ProhibitExplicitReturnUndef)
}
if ($binary_mode) {
binmode $file;
}
my($number_of_bytes,$buffer);
my $content = '';
while (($number_of_bytes = $file->read($buffer, 16384)) > 0) {
$content .= $buffer;
}
if (!defined $number_of_bytes) {
dbg("read_content: Error reading from file $file_name: $!");
sa-update.raw view on Meta::CPAN
$file->close;
return $content;
}
##############################################################################
# choose a random integer between 0 and the total weight of all mirrors
# loop through the mirrors from largest to smallest weight
# if random number is < largest weight, use it
# otherwise, random number -= largest, remove mirror from list, try again
# eventually, there'll just be 1 mirror left in $mirrors[0] and it'll be used
#
sub choose_mirror {
my($mirror_list) = @_;
# Sort the mirror list by reverse weight (largest first)
my @mirrors = sort { $mirror_list->{$b}->{weight} <=> $mirror_list->{$a}->{weight} } keys %{$mirror_list};
return unless @mirrors;
if (keys %{$mirror_list} > 1) {
# Figure out the total weight
my $weight_total = 0;
foreach (@mirrors) {
$weight_total += $mirror_list->{$_}->{weight};
}
# Pick a random int
my $value = int(rand($weight_total));
# loop until we find the right mirror, or there's only 1 left
while (@mirrors > 1) {
if ($value < $mirror_list->{$mirrors[0]}->{weight}) {
last;
}
$value -= $mirror_list->{$mirrors[0]}->{weight};
shift @mirrors;
}
}
return $mirrors[0];
}
##############################################################################
sub check_mirror_af {
my ($mirror) = @_;
# RFC 3986: scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
$mirror =~ s{^([a-z][a-z0-9.+-]*)://}{}si; # strip scheme like http://
my $scheme = lc($1);
# No DNS check needed for proxied connections (caveat: no_proxy is not checked)
my $http_proxy = (defined $ENV{"http_proxy"} && $ENV{"http_proxy"} =~ /\S/) ||
(defined $ENV{"HTTP_PROXY"} && $ENV{"HTTP_PROXY"} =~ /\S/);
my $https_proxy = (defined $ENV{"https_proxy"} && $ENV{"https_proxy"} =~ /\S/) ||
(defined $ENV{"HTTPS_PROXY"} && $ENV{"HTTPS_PROXY"} =~ /\S/);
return 1 if $scheme eq "http" && $http_proxy;
return 1 if $scheme eq "https" && $https_proxy;
# No DNS check needed for IPv4 or IPv6 address literal
return 1 if $use_inet4 && $mirror =~ m{^\d+\.\d+\.\d+\.\d+(?:[:/]|$)};
return 1 if $use_inet6 && $mirror =~ m{^\[};
$mirror =~ s{[:/].*}{}s; # strip all starting from :port or /path
return 1 if $use_inet4 && do_dns_query($mirror, "A");
return 1 if $use_inet6 && do_dns_query($mirror, "AAAA");
return 0;
}
##############################################################################
sub print_version {
printf("sa-update version %s\n running on Perl version %s\n", $VERSION,
join(".", map( 0+($_||0), ( $] =~ /(\d)\.(\d{3})(\d{3})?/ ))));
}
##############################################################################
sub print_usage_and_exit {
my ( $message, $exitval ) = @_;
$exitval ||= 64;
if ($exitval == 0) {
print_version();
print("\n");
}
pod2usage(
-verbose => 0,
-message => $message,
-exitval => $exitval,
);
}
##############################################################################
sub usage {
my ( $verbose, $message ) = @_;
print "sa-update version $VERSION\n";
pod2usage( -verbose => $verbose, -message => $message, -exitval => 64 );
}
##############################################################################
sub interpolate_gpghomedir {
my $gpghome = '';
if ($opt{'gpghomedir'}) {
$gpghome = $opt{'gpghomedir'};
if (am_running_on_windows()) {
# windows is single-quote-phobic; bug 4958 cmt 7
$gpghome =~ s/\"/\\\"/gs;
$gpghome = "--homedir=\"$gpghome\"";
} else {
$gpghome =~ s/\'/\\\'/gs;
$gpghome = "--homedir='$gpghome'";
}
}
return $gpghome;
}
##############################################################################
sub check_gpghomedir {
unless (-d $opt{gpghomedir}) {
dbg("gpg: creating gpg home dir ".$opt{gpghomedir});
# use 0700 to avoid "unsafe permissions" warning
mkpath([$opt{gpghomedir}], 0, 0700)
sa-update.raw view on Meta::CPAN
LOCAL_STATE_DIR => $LOCAL_STATE_DIR,
});
# need to kluge disabling bayes since it may try to expire the DB, and
# without the proper config it's not going to be good.
$spamtest->{conf}->{use_bayes} = 0;
my $res = $spamtest->lint_rules();
$spamtest->finish();
return $res == 0;
}
##############################################################################
=head1 NAME
sa-update - automate SpamAssassin rule updates
=head1 SYNOPSIS
B<sa-update> [options]
Options:
--channel channel Retrieve updates from this channel
Use multiple times for multiple channels
--channelfile file Retrieve updates from the channels in the file
--checkonly Check for update availability, do not install
--install file Install updates directly from this file. Signature
verification will use "file.asc", or "file.sha512"
or "file.sha256".
--allowplugins Allow updates to load plugin code (DANGEROUS)
--gpgkey key Trust the key id to sign releases
Use multiple times for multiple keys
--gpgkeyfile file Trust the key ids in the file to sign releases
--gpghomedir path Store the GPG keyring in this directory
--gpg and --nogpg Use (or do not use) GPG to verify updates
(--gpg is assumed by use of the above
--gpgkey and --gpgkeyfile options)
--import file Import GPG key(s) from file into sa-update's
keyring. Use multiple times for multiple files
--updatedir path Directory to place updates, defaults to the
SpamAssassin site rules directory
(default: @@LOCAL_STATE_DIR@@/@@VERSION@@)
--refreshmirrors Force the MIRRORED.BY file to be updated
--forcemirror url Use a specific mirror instead of downloading from
official mirrors
--httputil util Force used download tool. By default first found
from these is used: curl, wget, fetch, lwp
--score-multiplier x.x Adjust all scores from update channel, multiply
with given value (integer or float).
--score-limit x.x Adjust all scores from update channel, limit
to given value (integer or float). Limiting
is done after possible multiply operation.
-D, --debug [area=n,...] Print debugging messages
-v, --verbose Be verbose, like print updated channel names;
For more verbosity specify multiple times
-V, --version Print version
-h, --help Print usage message
-4 Force using the inet protocol (IPv4), not inet6
-6 Force using the inet6 protocol (IPv6), not inet
=head1 DESCRIPTION
sa-update automates the process of downloading and installing new rules and
configuration, based on channels. The default channel is
I<updates.spamassassin.org>, which has updated rules since the previous
release.
NOTE: channel names are domain names, but DO NOT typically have any DNS
records other than (maybe) NS records. There is a tree of records below that
name which denote the SpamAssassin version and resolve that name to the
version number of the latest rules, e.g. to find the latest update
version number for SpamAssassin v4.0.0:
$ host -t txt 0.0.4.updates.spamassassin.org
0.0.4.updates.spamassassin.org is an alias for 3.3.3.updates.spamassassin.org.
3.3.3.updates.spamassassin.org descriptive text "1907730"
That also illuminates the fact that the current ruleset is supposed to be
backward-compatible to v3.3.3.
Update archives are verified using GPG signatures by default. If GPG is
disabled (not recommended), file integrity is checked with SHA512 or SHA256
checksums.
Note that C<sa-update> will not restart C<spamd> or otherwise cause
a scanner to reload the now-updated ruleset automatically. Instead,
C<sa-update> is typically used in something like the following manner:
sa-update && /etc/init.d/spamassassin reload
This works because C<sa-update> only returns an exit status of C<0> if
it has successfully downloaded and installed an updated ruleset.
The program sa-update uses the underlying operating system umask for the
updated rule files it installs. You may wish to run sa-update from a script
that sets the umask prior to calling sa-update. For example:
#!/bin/sh
umask 022
sa-update
=head1 OPTIONS
=over 4
=item B<--channel>
sa-update can update multiple channels at the same time. By default, it will
only access "updates.spamassassin.org", but more channels can be specified via
this option. If there are multiple additional channels, use the option
multiple times, once per channel. i.e.:
sa-update --channel foo.example.com --channel bar.example.com
=item B<--channelfile>
Similar to the B<--channel> option, except specify the additional channels in a
file instead of on the commandline. This is useful when there are a
lot of additional channels.
( run in 1.245 second using v1.01-cache-2.11-cpan-5837b0d9d2c )