-
Notifications
You must be signed in to change notification settings - Fork 73
/
sa-update.raw
executable file
·2305 lines (1902 loc) · 76.1 KB
/
sa-update.raw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/perl -w -T
# <@LICENSE>
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to you under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# </@LICENSE>
use strict;
use warnings;
use re 'taint';
my $VERSION = 'svnunknown';
if ('$Id$' =~ ':') {
# Subversion keyword "$Id$" has been successfully expanded.
# Doesn't happen with automated launchpad builds:
# https://bugs.launchpad.net/launchpad/+bug/780916
$VERSION = &Mail::SpamAssassin::Version . ' / svn' . (split(/\s+/, '$Id$'))[2];
}
my $PREFIX = '@@PREFIX@@'; # substituted at 'make' time
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 <[email protected]>
# 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://issues.apache.org/SpamAssassin/show_bug.cgi?id=5854
if ( defined $opt{'checkonly'}) {
$GPG_ENABLED=0;
dbg("gpg: Disabling gpg requirement due to checkonly flag.");
}
dbg("generic: sa-update version $VERSION");
dbg("generic: using update directory: $opt{'updatedir'}");
# doesn't really display useful things for this script, but we do want
# a module/version listing, etc. sa-update may be used for older versions
# of SA that don't include this function, so eval around it.
eval { $SA->debug_diagnostics(); 1; };
$SA->finish();
# untaint the command-line args; since the root user supplied these, and
# we're not a setuid script, we trust them
foreach my $optkey (keys %opt) {
next if ref $opt{$optkey};
untaint_var(\$opt{$optkey});
}
##############################################################################
# Deal with gpg-related options
if (@{$opt{'gpgkey'}}) {
$GPG_ENABLED = 1;
foreach my $key (@{$opt{'gpgkey'}}) {
unless (is_valid_gpg_key_id($key)) {
dbg("gpg: invalid gpgkey parameter $key");
next;
}
$key = uc $key;
dbg("gpg: adding key id $key");
$valid_GPG{$key} = 1;
}
}
if (defined $opt{'gpgkeyfile'}) {
$GPG_ENABLED = 1;
open(GPG, $opt{'gpgkeyfile'})
or die "cannot open $opt{'gpgkeyfile'} for reading: $!\n";
dbg("gpg: reading in gpgfile ".$opt{'gpgkeyfile'});
while(my $key = <GPG>) {
chomp $key;
$key =~ s/#.*$//; # remove comments
$key =~ s/^\s+//; # remove leading whitespace
$key =~ s/\s+$//; # remove tailing whitespace
next if $key eq ''; # skip empty lines
unless (is_valid_gpg_key_id($key)) {
dbg("gpg: invalid key id $key");
next;
}
$key = uc $key;
dbg("gpg: adding key id $key");
$valid_GPG{$key} = 1;
}
close(GPG) or die "cannot close $opt{'gpgkeyfile'}: $!";
}
# At this point, we need to know where GPG is ...
my $GPGPath;
if ($GPG_ENABLED || $opt{'import'}) {
# find GPG in the PATH
# bug 4958: for *NIX it's "gpg", in Windows it's "gpg.exe"
$GPGPath = 'gpg' . $Config{_exe};
dbg("gpg: Searching for '$GPGPath'");
if ($GPGPath = Mail::SpamAssassin::Util::find_executable_in_env_path($GPGPath)) {
dbg("gpg: found $GPGPath");
# bug 5030: if GPGPath has a space, put it in quotes
if ($GPGPath =~ / /) {
$GPGPath =~ s/"/\\"/g;
$GPGPath = qq/"$GPGPath"/;
dbg("gpg: path changed to $GPGPath");
}
}
else {
die "error: gpg required but not found! It is not recommended, but you can use \"sa-update\" with the --no-gpg to skip the verification. \n";
}
# GPG was found, and we've been asked to import a key only
if ( $opt{'import'} ) {
my $ex = import_gpg_key($opt{'import'});
exit $ex;
}
# does the sa-update keyring exist? if not, import it
if(!-f File::Spec->catfile($opt{'gpghomedir'}, "trustdb.gpg")) {
import_default_keyring();
# attempt to continue even if this fails, anyway
}
# specify which keys are trusted
dbg("gpg: release trusted key id list: ".join(" ", keys %valid_GPG));
# convert fingerprint gpg ids to keyids
foreach (keys %valid_GPG) {
my $id = substr $_, -8;
$valid_GPG{$id} = 1;
}
}
##############################################################################
# Deal with channel-related options
if (defined $opt{'channel'} && scalar @{$opt{'channel'}} > 0) {
@channels = @{$opt{'channel'}};
}
if (defined $opt{'channelfile'}) {
open(CHAN, $opt{'channelfile'})
or die "cannot open $opt{'channelfile'} for reading: $!\n";
dbg("channel: reading in channelfile ".$opt{'channelfile'});
@channels = ();
while(my $chan = <CHAN>) {
chomp $chan;
$chan =~ s/#.*$//; # remove comments
$chan =~ s/^\s+//; # remove leading whitespace
$chan =~ s/\s+$//; # remove tailing whitespace
next if $chan eq ''; # skip empty lines
$chan = lc $chan;
dbg("channel: adding $chan");
push(@channels, $chan);
}
close(CHAN) or die "cannot close $opt{'channelfile'}: $!";
}
# untaint the channel listing
for(my $ind = 0; $ind < @channels; $ind++) {
local($1); # bug 5061: prevent random taint flagging of $1
if ($channels[$ind] =~ /^([a-zA-Z0-9._-]+)$/) {
untaint_var(\$channels[$ind]);
}
else {
dbg("channel: skipping invalid channel: $channels[$ind]");
splice @channels, $ind, 1;
$ind--; # the next element takes the place of the deleted one
}
}
my ($res, $ua);
if ($opt{'install'}) {
if (scalar @channels > 1) {
die "fatal: --install cannot be used with multiple --channel switches.\n";
}
} else {
$res = Net::DNS::Resolver->new();
$res->force_v4(1) if $have_inet4 &&
$opt{'force_pf'} && $opt{'force_pf'} eq 'inet';
}
# Generate a temporary file to put channel content in for later use ...
my ($content_file, $tfh) = secure_tmpfile();
$tfh
or die "fatal: could not create temporary channel content file: $!\n";
close $tfh
or die "cannot close temporary channel content file $content_file: $!";
undef $tfh;
my $lint_failures = 0;
my $channel_failures = 0;
my $channel_successes = 0;
# Use a temporary directory for all update channels
my $UPDTmp;
# we only need to lint the site pre files once
my $site_pre_linted = 0;
# Go ahead and loop through all of the channels
foreach my $channel (@channels) {
dbg("channel: attempting channel $channel");
my %preserve_files;
# Convert the channel to a nice-for-filesystem version
my $nicechannel = $channel;
$nicechannel =~ tr/A-Za-z0-9-/_/cs;
my $UPDDir = File::Spec->catfile($opt{'updatedir'}, $nicechannel);
my $CFFile = "$UPDDir.cf";
my $PREFile = "$UPDDir.pre";
if (-d $UPDDir) {
dbg("channel: using existing directory $UPDDir");
} else {
# create the dir, if it doesn't exist
dbg("channel: creating directory $UPDDir");
mkpath([$UPDDir], 0, 0777)
or die "channel: cannot create channel directory $UPDDir: $!\n";
}
dbg("channel: channel cf file $CFFile");
dbg("channel: channel pre file $PREFile");
my $instfile;
if ($opt{'install'}) {
$instfile = $opt{'install'};
dbg("channel: installing from file $instfile");
}
my($mirby, $mirby_force_reload, $mirby_file_is_ok);
my $mirby_path = File::Spec->catfile($UPDDir, "MIRRORED.BY");
# try to read metadata from channel.cf file
my $currentV = -1;
if (!open(CF, $CFFile)) {
dbg("channel: error opening file %s: %s",
$CFFile, $!) unless $! == ENOENT;
} else {
while(<CF>) {
local($1,$2);
last unless /^# UPDATE\s+([A-Za-z]+)\s+(\S+)/;
my($type, $value) = (lc $1,$2);
dbg("channel: metadata $type = $value, from file $CFFile");
if ($type eq 'version') {
$value =~ /^(\d+)/;
$currentV = $1;
}
}
close(CF) or die "cannot close $CFFile: $!";
}
# obtain a version number which should be installed
my $newV;
if ($instfile) {
# the /.*/ ensures we use the 3-digit string nearest to the end of string,
# otherwise we might pick up something from the middle of the directory path
local($1);
if ($instfile !~ /(?:.*\D|^)(\d{3,})/) {
# this is a requirement
die "channel: $channel: --install file $instfile does not contain a 3-digit version number!\n";
}
$newV = $1;
if ( defined $opt{'checkonly'} ) {
dbg("channel: $channel: --install and --checkonly, claiming update available");
$channel_successes++;
next;
}
} else { # not an install file, get the latest version number from network
# Setup the channel version DNS query
my $DNSQ = "$RevSAVersion.$channel";
my $dnsV = join(' ', do_dns_query($DNSQ));
local($1);
if (defined $dnsV && $dnsV =~ /^(\d+)/) {
$newV = untaint_var($1) if (!defined $newV || $1 > $newV);
dbg("dns: $DNSQ => $dnsV, parsed as $1");
}
# Not getting a response isn't a failure, there may just not be any updates
# for this SA version yet.
if (!defined $newV) {
my @mirs = do_dns_query("mirrors.$channel");
if (defined shift @mirs) {
dbg("channel: no updates available, skipping channel");
} else {
channel_failed("channel '$channel': no 'mirrors.$channel' record found");
}
next;
}
# If this channel hasn't been installed before, or it's out of date,
# keep going. Otherwise, skip it.
if ($currentV >= $newV) {
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;
utime($now, $now, $mirby_path)
or warn "error: error setting creation time of $mirby_path: $!\n";
last;
}
}
if ($mirby_force_reload) { # not refreshed?
warn "error: unable to refresh mirrors file for channel $channel, ".
"using old file\n";
}
}
if (!$mirby_file_is_ok) {
warn "error: no mirror data available for channel $channel\n";
channel_failed("channel '$channel': MIRRORED.BY file contents were missing");
next;
} elsif ($mirby) {
# file contents already in memory, no need to read it from a file
} elsif (!open(MIRBY, $mirby_path)) {
warn "error: error opening mirrors file $mirby_path: $!\n";
channel_failed("channel '$channel': error opening mirrors file $mirby_path: $!");
next;
} else {
dbg("channel: reading MIRRORED.BY file %s", $mirby_path);
{ local $/ = undef; $mirby = <MIRBY> }
close(MIRBY) or die "cannot close $mirby_path: $!";
$preserve_files{$mirby_path} = 1;
}
# Parse the list of mirrors
dbg("channel: parsing MIRRORED.BY file for channel %s", $channel);
my %mirrors;
my @mirrors = split(/^/, $mirby);
while(my $mirror = shift @mirrors) {
chomp $mirror;
if ( defined $opt{'forcemirror'} ) {
$mirror = $opt{'forcemirror'};
$mirrors{$mirror}->{"weight"} = 1;
dbg("channel: found mirror $mirror (forced)");
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;
}
if (-s $path_asc) {
$GPG = read_content($path_asc, 0); # ascii
$preserve_files{$path_asc} = 1;
}
}
}
unless ($content && (($GPG_ENABLED && $GPG) || (!$GPG_ENABLED && ($SHA512 || $SHA256)))) {
if ($instfile) {
channel_failed("channel '$channel': missing checksum files $instfile\{,.sha512,.sha256\}");
} else {
channel_failed("channel '$channel': could not find working mirror");
}
next;
}
if ( $SHA512 ) {
# Validate the SHA512 signature
{ local($1);
$SHA512 =~ /^([a-fA-F0-9]{128})\b/;
$SHA512 = defined $1 ? lc($1) : 'INVALID';
}
my $digest = sha512_hex($content);
dbg("sha512: verification wanted: $SHA512");
dbg("sha512: verification result: $digest");
unless ($digest eq $SHA512) {
channel_failed("channel '$channel': SHA512 verification failed");
next;
}
}
if ( $SHA256 ) {
# Validate the SHA256 signature
{ local($1);
$SHA256 =~ /^([a-fA-F0-9]{64})\b/;
$SHA256 = defined $1 ? lc($1) : 'INVALID';
}
my $digest = sha256_hex($content);
dbg("sha256: verification wanted: $SHA256");
dbg("sha256: verification result: $digest");
unless ($digest eq $SHA256) {
channel_failed("channel '$channel': SHA256 verification failed");
next;
}
}
# Write the content out to a temp file for GPG/Archive::Tar interaction
dbg("channel: populating temp content file %s", $content_file);
open(TMP, ">$content_file")
or die "fatal: cannot create content temp file $content_file: $!\n";
binmode TMP
or die "fatal: cannot set binmode on content temp file $content_file: $!\n";
print TMP $content
or die "fatal: cannot write to content temp file $content_file: $!\n";
close TMP
or die "fatal: cannot close content temp file $content_file: $!\n";
# to sign : gpg -bas file
# to verify: gpg --verify --batch --no-tty --status-fd=1 -q --logger-fd=1 file.asc file
# look for : [GNUPG:] GOODSIG 6C55397824F434CE updates.spamassassin.org [...]
# [GNUPG:] VALIDSIG 0C2B1D7175B852C64B3CDC716C55397824F434CE [...]
# [GNUPG:] NO_PUBKEY 6C55397824F434CE
if ($GPG) {
dbg("gpg: populating temp signature file");
my $sig_file;
($sig_file, $tfh) = secure_tmpfile();
$tfh
or die "fatal: couldn't create temp file for GPG signature: $!\n";
binmode $tfh
or die "fatal: cannot set binmode on temp file for GPG signature: $!\n";
print $tfh $GPG
or die "fatal: cannot write temp file for GPG signature: $!\n";
close $tfh
or die "fatal: cannot close temp file for GPG signature: $!\n";
undef $tfh;
dbg("gpg: calling gpg");
my $gpghome = interpolate_gpghomedir();
# TODO: we could also use "--keyserver pgp.mit.edu" or similar,
# to autodownload missing keys...
my $CMD = "$GPGPath $gpghome --verify --batch ".
"--no-tty --status-fd=1 -q --logger-fd=1";
unless (open(CMD, "$CMD $sig_file $content_file|")) {
unlink $sig_file or warn "error: cannot unlink $sig_file: $!\n";
die "fatal: couldn't execute $GPGPath: $!\n";
}
# Determine the fate of the signature
my $signer = '';
my $missingkeys = '';
while(my $GNUPG = <CMD>) {
chop $GNUPG;
dbg ("gpg: $GNUPG");
if ($GNUPG =~ /^gpg: fatal:/) {
warn $GNUPG."\n"; # report bad news
}
local($1);
if ($GNUPG =~ /^\Q[GNUPG:]\E NO_PUBKEY \S+(\S{8})$/) {
$missingkeys .= $1." ";
}
next unless ($GNUPG =~ /^\Q[GNUPG:]\E (?:VALID|GOOD)SIG (\S{8,40})/);
my $key = $1;
# we want either a keyid (8) or a fingerprint (40)
if (length $key > 8 && length $key < 40) {
substr($key, 8) = '';
}
# use the longest match we can find
$signer = $key if length $key > length $signer;
}
my $errno = 0; close CMD or $errno = $!;
proc_status_ok($?,$errno)
or warn("gpg: process '$GPGPath' finished: ".
exit_status_str($?,$errno)."\n");
unlink $sig_file or warn "cannot unlink $sig_file: $!\n";
if ($signer) {
my $keyid = substr $signer, -8;
dbg("gpg: found signature made by key $signer");
if (exists $valid_GPG{$signer}) {
dbg("gpg: key id $signer is release trusted");
}
elsif (exists $valid_GPG{$keyid}) {
dbg("gpg: key id $keyid is release trusted");
}
else {
dbg("gpg: key id $keyid is not release trusted");
$signer = undef;
}
}
unless ($signer) {
warn "error: GPG validation failed!\n";
if ($missingkeys) {
warn <<ENDOFVALIDATIONERR;