-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
spampd.pl
executable file
·2832 lines (2240 loc) · 109 KB
/
spampd.pl
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 -T
######################
# SpamPD - Spam Proxy Daemon
#
# v2.61 - 06-Aug-21
# v2.60 - 26-Jul-21
# v2.53 - 25-Feb-19
# v2.52 - 10-Nov-18
# v2.51 - 01-May-18
# v2.50 - 30-Apr-18
# v2.42 - 08-Dec-13
# v2.41 - 11-Aug-10
# v2.40 - 10-Jan-09
# v2.32 - 02-Feb-06
# v2.30 - 31-Oct-05
# v2.21 - 23-Oct-05
# v2.20 - 05-Oct-04
# v2.13 - 24-Nov-03
# v2.12 - 15-Nov-03
# v2.11 - 15-Jul-03
# v2.10 - 01-Jul-03
# v2.00 - 10-Jun-03
# v1.0.2 - 13-Apr-03
# v1.0.1 - 03-Feb-03
# v1.0.0 - May 2002
#
# spampd is Copyright (c) Maxim Paperno; All Rights Reserved.
#
# Written and maintained by Maxim Paperno ([email protected])
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see L<https://www.gnu.org/licenses/>.
#
# spampd v2 uses two Perl modules by Bennett Todd and Copyright (C) 2001 Morgan
# Stanley Dean Witter. These are also distributed under the GNU GPL (see
# module code for more details). Both modules have been slightly modified
# from the originals and are included in this file under new names.
#
# spampd v1 was based on code by Dave Carrigan named assassind. Trace amounts
# of his code or documentation may still remain. Thanks to him for the
# original inspiration and code. (see http://www.rudedog.org/assassind/)
#
######################
################################################################################
package SpamPD::Server;
# Originally known as MSDW::SMTP::Server
#
# This code is Copyright (C) 2001 Morgan Stanley Dean Witter, and
# is distributed according to the terms of the GNU Public License
# as found at <URL:http://www.fsf.org/copyleft/gpl.html>.
#
# Modified for use in SpamPD by Maxim Paperno (June, 2003)
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# Written by Bennett Todd <[email protected]>
# =item DESCRIPTION
#
# This server simply gathers the SMTP acquired information (envelope
# sender and recipient, and data) into unparsed memory buffers (or a
# file for the data), and returns control to the caller to explicitly
# acknowledge each command or request. Since acknowledgement or failure
# are driven explicitly from the caller, this module can be used to
# create a robust SMTP content scanning proxy, transparent or not as
# desired.
#
# =cut
use strict;
use warnings;
use IO::File ();
# =item new(socket => $socket);
#
# Changed by MP: This now emulates Net::SMTP::Server::Client for use with
# Net::Server which passes an already open socket.
# The $socket to listen on must be specified. If this call
# succeeds, it returns a server structure. If it fails it dies, so
# if you want anything other than an exit with an explanatory error
# message, wrap the constructor call in an eval block and pull the
# error out of $@ as usual. This is also the case for all other
# methods; they succeed or they die.
#
# =cut
sub new {
my ($this, $socket) = @_;
my $class = ref($this) || $this || die "Missing class";
die "Invalid $socket argument in ".__PACKAGE__."->new()" unless defined $socket;
return bless {
sock => $socket,
state => 'started',
proto => 'unknown',
helo => 'unknown.host',
}, $class;
}
# =item chat;
#
# The chat method carries the SMTP dialogue up to the point where any
# acknowledgement must be made. If chat returns true, then its return
# value is the previous SMTP command. If the return value begins with
# 'mail' (case insensitive), then the attribute 'from' has been filled
# in, and may be checked; if the return value begins with 'rcpt' then
# both from and to have been been filled in with scalars, and should
# be checked, then C<reply("(2|5)50 [OK|Error]")> should be called to accept
# or reject the given sender/recipient pair. If the return value is
# 'data', then the attributes from and to are populated; in this case,
# the 'to' attribute is a reference to an anonymous array containing
# all the recipients for this data. If the return value is '.', then
# the 'data' attribute (which may be pre-populated in the "new" or
# "accept" methods if desired) is a reference to a filehandle; if it's
# created automatically by this module it will point to an unlinked
# tmp file in /tmp. If chat returns false, the SMTP dialogue has been
# completed and the socket closed; this server is ready to exit or to
# accept again, as appropriate for the server style.
#
# The return value from chat is also remembered inside the server
# structure in the "state" attribute.
#
# =cut
sub chat {
my ($self) = @_;
local (*_);
if ($self->{state} !~ /^data/i) {
return 0 unless defined($_ = $self->_getline);
s/[\r\n]*$//;
$self->{state} = $_;
if (/^(l|h)?he?lo\s+/i) { # mp: find helo|ehlo|lhlo
# mp: determine protocol
if (s/^helo\s+//i) {
$self->{proto} = "smtp";
}
elsif (s/^ehlo\s+//i) {
$self->{proto} = "esmtp";
}
elsif (s/^lhlo\s+//i) {
$self->{proto} = "lmtp";
}
s/\s*$//;
s/\s+/ /g;
$self->{helo} = $_;
}
elsif (s/^rset\s*//i) {
delete $self->{to};
delete $self->{data};
delete $self->{recipients};
}
elsif (s/^mail\s+from:\s*//i) {
delete $self->{to};
delete $self->{data};
delete $self->{recipients};
s/\s*$//;
$self->{from} = $_;
}
elsif (s/^rcpt\s+to:\s*//i) {
s/\s*$//; s/\s+/ /g;
$self->{to} = $_;
push @{$self->{recipients}}, $_;
}
elsif (/^data/i) {
$self->{to} = $self->{recipients};
}
}
else {
if (defined($self->{data})) {
$self->{data}->seek(0, 0);
$self->{data}->truncate(0);
}
else {
$self->{data} = IO::File->new_tmpfile;
}
while (defined($_ = $self->_getline)) {
if ($_ eq ".\r\n") {
$self->{data}->seek(0, 0);
return $self->{state} = '.';
}
s/^\.\./\./;
$self->{data}->print($_) or die "Server error while saving data: $!\n";
}
return 0;
}
return $self->{state};
}
# =item reply([message]);
#
# Send a response back to the connected peer. Default message is a confirmation
# response: "250 ok."
#
# =cut
sub reply {
my ($self, @msg) = @_;
@msg = ("250 ok.") unless @msg;
chomp(@msg);
$self->{sock}->print("@msg\r\n") or
die "Server error while sending response '@msg' (state = $self->{state}): $!\n";
# $self->{debug}->print(@msg) if defined $self->{debug};
}
# utility functions
sub _getline {
my ($self) = @_;
local ($/) = "\r\n";
my $tmp = $self->{sock}->getline;
if (defined $self->{debug}) {
$self->{debug}->print($tmp) if ($tmp);
}
return $tmp;
}
1;
################################################################################
package SpamPD::Client;
# Originally known as MSDW::SMTP::Client
#
# This code is Copyright (C) 2001 Morgan Stanley Dean Witter, and
# is distributed according to the terms of the GNU Public License
# as found at <URL:http://www.fsf.org/copyleft/gpl.html>.
#
# Modified for use in SpamPD by Maxim Paperno (June, 2003)
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# Written by Bennett Todd <[email protected]>
# =head1 DESCRIPTION
#
# MSDW::SMTP::Client provides a very lean SMTP client implementation;
# the only protocol-specific knowledge it has is the structure of SMTP
# multiline responses. All specifics lie in the hands of the calling
# program; this makes it appropriate for a semi-transparent SMTP
# proxy, passing commands between a talker and a listener.
#
# =cut
use strict;
use warnings;
# =item new([interface => $interface, port => $port] | [unix_socket => $unix_socket] [, timeout = 300]);
#
# The interface and port, OR a UNIX socket to talk to must be specified. If
# this call succeeds, it returns a client structure with an open
# IO::Socket::IP or IO::Socket::UNIX in it, ready to talk to.
# If it fails it dies, so if you want anything other than an exit with an
# explanatory error message, wrap the constructor call in an eval block and pull
# the error out of $@ as usual. This is also the case for all other
# methods; they succeed or they die. The timeout parameter is passed
# on into the IO::Socket::IP/UNIX constructor.
#
# =cut
sub new {
my ($this, @opts) = @_;
my $class = ref($this) || $this;
my $self = bless {timeout => 300, @opts}, $class;
if ($self->{unix_socket}) {
require IO::Socket::UNIX;
$self->{sock} = IO::Socket::UNIX->new(
Peer => $self->{unix_socket},
Timeout => $self->{timeout},
Type => IO::Socket::UNIX->SOCK_STREAM,
);
}
else {
require IO::Socket::IP;
$self->{sock} = IO::Socket::IP->new(
PeerAddr => $self->{interface},
PeerPort => $self->{port},
Timeout => $self->{timeout},
Proto => 'tcp',
Type => IO::Socket::IP->SOCK_STREAM,
);
}
die "Client connection failure to ". ($self->{unix_socket} || $self->{interface}) .": $!\n" unless defined $self->{sock};
return $self;
}
# =item hear
#
# hear collects a complete SMTP response and returns it with trailing
# CRLF removed; for multi-line responses, intermediate CRLFs are left
# intact. Returns undef if EOF is seen before a complete reply is
# collected.
#
# =cut
sub hear {
my ($self) = @_;
my ($tmp, $reply);
return unless $tmp = $self->{sock}->getline;
while ($tmp =~ /^\d{3}-/) {
$reply .= $tmp;
return unless $tmp = $self->{sock}->getline;
}
$reply .= $tmp;
$reply =~ s/\r\n$//;
return $reply;
}
# =item say("command text")
#
# say sends an SMTP command, appending CRLF.
#
# =cut
sub say {
my ($self, @msg) = @_;
return unless @msg;
chomp(@msg);
$self->_print("@msg", "\r\n");
}
# =item yammer(FILEHANDLE)
#
# yammer takes a filehandle (which should be positioned at the
# beginning of the file, remember to $fh->seek(0,0) if you've just
# written it) and sends its contents as the contents of DATA. This
# should only be invoked after a $client->say("data") and a
# $client->hear to collect the reply to the data command. It will send
# the trailing "." as well. It will perform leading-dot-doubling in
# accordance with the SMTP protocol spec, where "leading dot" is
# defined in terms of CR-LF terminated lines --- i.e. the data should
# contain CR-LF data without the leading-dot-quoting. The filehandle
# will be left at EOF.
#
# =cut
sub yammer {
my ($self, $fh) = (@_);
local (*_);
local ($/) = "\r\n";
$self->{sock}->autoflush(0); # use fewer writes (thx to Sam Horrocks for the tip)
while (<$fh>) {
s/^\./../;
$self->_print($_);
}
$self->{sock}->autoflush(1); # restore unbuffered socket operation
$self->_print(".\r\n");
}
sub _print {
return unless @_ > 1;
shift()->{sock}->print(@_) or die "Client socket write error: $!\n";
}
1;
################################################################################
package SpamPD;
use strict;
use warnings;
BEGIN {
require Net::Server;
Net::Server->VERSION(0.89);
# use included modules
import SpamPD::Server;
import SpamPD::Client;
}
use Getopt::Long qw(GetOptions);
use Time::HiRes qw(time);
use Mail::SpamAssassin ();
our $VERSION = '2.611';
# ISA will change to a Net::Server "flavor" at runtime based on options.
our @ISA = qw(Net::Server);
use constant {
# Logging type constants: low byte for destination(s), high byte for logger type.
LOG_NONE => 0, LOG_SYSLOG => 0x01, LOG_FILE => 0x02, LOG_STDERR => 0x04, LOG_TYPE_MASK => 0xFF,
LOGGER_DEFAULT => 0, LOGGER_SA => 0x0100, LOGGER_L4P => 0x0200, LOGGER_TYPE_MASK => 0xFF00,
# Map Net::Server logging levels to SpamAssassin::Logger level names.
SA_LOG_LEVELS => {0 => 'error', 1 => 'warn', 2 => 'notice', 3 => 'info', 4 => 'dbg'},
};
################## RUN ######################
unless (caller) {
# Create, init, and go.
SpamPD->new()->init()->run();
exit 1; # shouldn't get here
}
################## SETUP ######################
# Create ourselves and set defaults for options.
sub new {
my $class = shift || die "Missing class.";
return bless {
server => {
host => '127.0.0.1', # listen on ip
port => 10025, # listen on port
min_servers => undef, # min num of servers to always have running (undef means use same value as max_servers, otherwise means run as PreFork)
min_spare_servers => 1, # min num of servers just sitting there (only used when running as PreFork)
max_spare_servers => 4, # max num of servers just sitting there (only used when running as PreFork)
max_servers => 5, # max number of child processes (servers) to spawn
max_requests => 20, # max requests handled by child b4 dying
pid_file => '/var/run/spampd.pid', # write pid to file
user => 'mail', # user to run as
group => 'mail', # group to run as
log_file => undef, # log destination (undef means log to use write_to_log_hook() with stderr fallback)
syslog_logsock => undef, # syslog socket (undef means for Sys::Syslog to decide)
syslog_ident => 'spampd', # syslog identity
syslog_facility => 'mail', # syslog facility
log_level => 2, # log level for Net::Server (in the range 0-4) (--debug option sets this to 4)
background => 1, # specifies whether to 'daemonize' and fork into background (--[no]detach option)
setsid => 0, # use POSIX::setsid() command to truly daemonize.
leave_children_open_on_hup => 1, # this lets any busy children finish processing before exiting, using old SA object
},
spampd => {
socket => undef, # listen on socket (saved for setting permissions after binding)
socket_mode => undef, # listening socket permissions (octal)
relayhost => '127.0.0.1', # relay to ip
relayport => 25, # relay to port
relaysocket => undef, # relay to socket
childtimeout => 6 * 60, # child process per-command timeout in seconds
satimeout => 285, # SA timeout in seconds (15s less than Postfix default for smtp_data_done_timeout)
tagall => 0, # mark-up all msgs with SA, not just spam
maxsize => 64, # max. msg size to scan with SA, in KB.
rh => 0, # log which rules were hit
dose => 0, # die-on-sa-errors flag
envelopeheaders => 0, # Set X-Envelope-To & X-Envelope-From headers in the mail before passing it to SA (--seh option)
setenvelopefrom => 0, # Set X-Envelope-From header only (--sef option)
sa_awl => 0, # SA auto-whitelist (deprecated)
logtype => LOG_SYSLOG, # logging destination and logger type (--logfile option)
sa_version => $Mail::SpamAssassin::VERSION, # may be used while processing messages
runtime_stats => undef, # variables hash for status tracking, can be used as values in user-provided template strings (defined in init())
# default child name template
child_name_templ => '%base_name: child #%child_count(%child_status) ' .
'[req %req_count/%req_max, time lst/avg/ttl %(req_time_last).3f/%(req_time_avg).3f/%(req_time_ttl).3f, ham/spm %req_ham/%req_spam] ' .
'[SA %sa_ver/%sa_rls_ver]',
},
# this hash is eventually passed to SpamAssassin->new() so it must use valid SA option names. This also becomes the SA object afterwards.
assassin => {
debug => 0, # debug flag, can be boolean or a list to pass to SA (--debug option)
local_tests_only => 0, # disable SA network tests (--local-only flag)
userstate_dir =>
'/var/spool/spamassassin/spampd', # home directory for SA files and plugins (--homedir option)
home_dir_for_helpers => '', # this will be set to the same as userstate_dir once options are parsed
username => '', # this will be set to the same user as we're running as once options are parsed
userprefs_filename => undef, # add this config file for SA "user_prefs" settings (--saconfig option)
dont_copy_prefs => 1, # tell SA not to copy user pref file into its working dir
}
}, $class;
}
# Set the actual Net::Server flavor type we'll run as.
sub set_server_type {
my $self = shift;
# Default behavior is to run as PreForkSimple unless min_servers is set and is != max_servers.
if ($self->{server}->{min_servers} && $self->{server}->{min_servers} != $self->{server}->{max_servers}) {
require Net::Server::PreFork;
@SpamPD::ISA = qw(Net::Server::PreFork);
}
else {
require Net::Server::PreForkSimple;
@SpamPD::ISA = qw(Net::Server::PreForkSimple);
}
}
################## INIT ######################
sub init {
my $self = shift;
my ($spd_p, $sa_p) = ($self->{spampd}, $self->{assassin});
# Clean up environment.
delete @ENV{qw(IFS CDPATH ENV BASH_ENV HOME)};
eval {
# Try to safely untaint the PATH instead of resetting it. Also prevents SA from duplicating this step when it starts.
require Mail::SpamAssassin::Util;
Mail::SpamAssassin::Util::clean_path_in_taint_mode();
} or do {
$ENV{'PATH'} = '/bin:/usr/bin:/sbin:/usr/sbin:/usr/local/bin:/usr/local/sbin';
};
# Untaint $0 and each member of @ARGV, and save untainted copies for HUPping. This saves the original
# command line, including any configuration files, which would be re-read upon a HUP. commandline() is in Net::Server.
$self->commandline([untaint_var($0), @{untaint_var(\@ARGV)}]);
# Set the logger type. SA v3.1.0 changed debug logging to be more granular and introduced Logger module which we can use.
$spd_p->{logtype} |= eval {
require Mail::SpamAssassin::Logger;
LOGGER_SA;
} or LOGGER_DEFAULT;
# We actually call Getopt::Long::GetOptions twice. First time is to check for presence of config file option(s).
# If we get any, then we parse the file(s) into @ARGV, in front of any existing @ARGV options (so command-line overrides).
$self->handle_initial_opts();
# save final ARGV for debug (handle_main_opts() will clear @ARGV)
my @startup_args = @ARGV;
# Now process all the actual options passed on @ARGV (including anything from config files).
# Options on the actual command line will override anything loaded from the file(s).
$self->handle_main_opts();
# Configure logging ASAP, unless just showing debug info.
$self->setup_logging() if !$spd_p->{show_dbg};
# Validate options.
my (@errs, @warns) = $self->validate_main_opts();
if (@errs) {
$self->err("CONFIG ERROR! ".$_."\n") for @errs;
$self->server_close(1) if $self->is_reloading();
$self->server_exit(1);
}
$self->wrn("CONFIG WARNING! ".$_."\n") for @warns;
# If debug output requested, do it now and exit.
$self->show_debug($spd_p->{show_dbg}, {$self->options_map()}, \@startup_args) && exit(0) if $spd_p->{show_dbg};
# Create and set up SpamAssassin object. This replaces our SpamPD->{assassin} property with the actual object instance.
$sa_p = Mail::SpamAssassin->new($sa_p);
$spd_p->{sa_awl} and eval {
require Mail::SpamAssassin::DBBasedAddrList;
# create a factory for the persistent address list
my $addrlistfactory = Mail::SpamAssassin::DBBasedAddrList->new();
$sa_p->set_persistent_address_list_factory($addrlistfactory);
};
$sa_p->compile_now(!!$sa_p->{userprefs_filename});
# Get the SA "rules update version" for logging and child process name (since v3.4.0).
# https://github.com/apache/spamassassin/blob/3.4/build/announcements/3.4.0.txt#L334
# https://github.com/apache/spamassassin/blob/3.4/lib/Mail/SpamAssassin/PerMsgStatus.pm#L1597
my $sa_rules_ver;
($spd_p->{sa_version} >= 3.0040) and eval {
$sa_rules_ver = Mail::SpamAssassin::PerMsgStatus->new($sa_p)->get_tag("RULESVERSION");
};
# Set up statistics hash. This is currently used for report formatting, eg. in child process name.
my $ns_type = (split(':', $self->net_server_type()))[-1];
$spd_p->{runtime_stats} = {
base_name => eval { ($0 =~ m/^.*?([\w-]+)(?:\.[\w-]+)*$/) ? $1 : "spampd"; },
spampd_ver => $self->VERSION(),
perl_ver => sprintf("%vd", $^V), # (split(/v/, $^V))[-1];
ns_ver => Net::Server->VERSION(),
ns_typ => $ns_type,
ns_typ_acr => do { (my $tmp = $ns_type) =~ s/[a-z]//g; $tmp },
sa_ver => Mail::SpamAssassin::Version(),
sa_rls_ver => $sa_rules_ver || "(unknown)",
child_count => 0, # total # of children launched
child_status => "D", # (C)onnected, or (D)isconnected
req_count => 0, # num of requests child has processed so far
req_max => $self->{server}->{max_requests}, # maximum child requests
req_time_last => 0, # [s] time to process the last message
req_time_ttl => 0, # [s] total processing time for this child
req_time_avg => 0, # [s] average processing time for this child (req_time_ttl / req_count)
req_ham => 0, # count of ham messages scored by child
req_spam => 0, # count of spam messages scored by child
};
my $template = ' v%spampd_ver [Perl %perl_ver, Net::Server::%ns_typ %ns_ver, SA %sa_ver, rules v%sa_rls_ver] ';
$self->inf(ref($self) . $self->format_stats_string($template) . ($self->is_reloading() ? "reloading": "starting") . " with: @startup_args \n");
# Redirect all errors to logger (must do this after SA is compiled, otherwise for some reason we get strange SA errors if anything actually dies).
# $SIG{__DIE__} = sub { return if $^S; chomp(my $m = $_[0]); $self->fatal($m); };
# clean up a bit
delete $spd_p->{config_files};
delete $spd_p->{logspec};
delete $spd_p->{show_dbg};
delete $spd_p->{sa_awl};
return $self;
}
sub initial_options_map {
my $self = shift;
my $spd_p = $self->{spampd};
my %options = (
'conf|config|cfg|conf-file|config-file|cfg-file=s@' => \$spd_p->{config_files},
);
# Also a good place to check for help/version/show option(s), but not if we're HUPping.
# These all cause an exit(0) (--show is processed later but still exits).
if (!$self->is_reloading()) {
my ($q2, $q3, $q4) = ("|??", "|???", "|????");
# https://github.com/mpaperno/spampd/issues/30#issuecomment-889110122
$q2 = $q3 = $q4 = "" if ($Getopt::Long::VERSION < 2.39);
%options = (
%options,
'show=s@' => \$spd_p->{show_dbg},
'help|h|?:s' => sub { $self->usage(0, 1, $_[1]); },
'hh'.$q2.':s' => sub { $self->usage(0, 2, $_[1]); },
'hhh'.$q3.':s' => sub { $self->usage(0, 3, $_[1]); },
'hhhh'.$q4.'|man:s' => sub { $self->usage(0, 4, $_[1]); },
'version|vers' => sub { $self->version(); },
);
}
return %options;
}
sub handle_initial_opts {
my $self = shift;
my %options = $_[0] || $self->initial_options_map();
my $spd_p = $self->{spampd};
# Configure Getopt::Long to pass through any unknown options.
Getopt::Long::Configure(qw(ignore_case no_permute no_auto_abbrev no_require_order pass_through));
# Check for config file option(s) only.
GetOptions(%options);
# Handle "--show <things>"
if ($spd_p->{show_dbg}) {
my $shw = \@{$spd_p->{show_dbg}};
trimmed(@$shw = split(/,/, join(',', @$shw))); # could be a CSV list
if (@$shw && grep(/^(def(aults?)?|all)$/i, @$shw)) {
# Handle "--show defaults" debugging request here (while we still know them).
@$shw = grep {$_ !~ /^def(aults?)?$/i} @$shw; # remove "defaults" from list
# show defaults and exit here if that's all the user wanted to see
$self->print_options({$self->options_map()}, 'default', (@$shw ? -1 : 0));
}
}
# Handle config files. Note that options on the actual command line will override anything loaded from the file(s).
if (defined($spd_p->{config_files})) {
# files could be passed as a list separated by ":"
trimmed(@{$spd_p->{config_files}} = split(/:/, join(':', @{$spd_p->{config_files}})));
$self->inf("Loading config from file(s): @{$spd_p->{config_files}} \n");
read_args_from_file(\@{$spd_p->{config_files}}, \@ARGV);
}
}
# Main command-line options mapping; this is for Getopt::Long::GetOptions and also to generate config dumps.
sub options_map {
my $self = $_[0];
my ($srv_p, $spd_p, $sa_p) = ($self->{server}, $self->{spampd}, $self->{assassin});
$spd_p->{logspec} = logtype2logfile($spd_p->{logtype}, $srv_p->{log_file}); # set a valid default for print_options()
# To support setting boolean options with "--opt", "--opt=1|0", as well as the "no-" prefix,
# we make them accept an optional integer and add the "no" variants manually. Because Getopt::Long doesn't support that :(
# Anything that isn't a direct reference to value (eg. a sub) will not be shown in "--show defaults|config" listings.
return (
# Net::Server
'host=s' => \$srv_p->{host},
'port=i' => \$srv_p->{port},
'min-servers|mns=i' => \$srv_p->{min_servers},
'min-spare|mnsp=i' => \$srv_p->{min_spare_servers},
'max-spare|mxsp=i' => \$srv_p->{max_spare_servers},
'max-servers|mxs=i' => \$srv_p->{max_servers},
'children|c=i' => sub { $srv_p->{max_servers} = $_[1]; },
'maxrequests|mr|r=i' => \$srv_p->{max_requests},
'pid|p=s' => \$srv_p->{pid_file},
'user|u=s' => \$srv_p->{user},
'group|g=s' => \$srv_p->{group},
'logsock|ls=s' => \$srv_p->{syslog_logsock},
'logident|li=s' => \$srv_p->{syslog_ident},
'logfacility|lf=s' => \$srv_p->{syslog_facility},
'detach:1' => \$srv_p->{background},
'no-detach|nodetach' => sub { $srv_p->{background} = 0; },
'setsid:1' => \$srv_p->{setsid},
'no-setsid|nosetsid' => sub { $srv_p->{setsid} = 0; },
# SpamPD
'socket=s' => \$spd_p->{socket},
'socket-perms=s' => \$spd_p->{socket_mode},
'relayhost=s' => \$spd_p->{relayhost},
'relayport=i' => \$spd_p->{relayport},
'relaysocket=s' => \$spd_p->{relaysocket},
'childtimeout=i' => \$spd_p->{childtimeout},
'satimeout=i' => \$spd_p->{satimeout},
'maxsize=i' => \$spd_p->{maxsize},
'logfile|o=s@' => \$spd_p->{logspec},
'tagall|a:1' => \$spd_p->{tagall},
'no-tagall|no-a' => sub { $spd_p->{tagall} = 0; },
'log-rules-hit|rh:1' => \$spd_p->{rh},
'no-log-rules-hit|no-rh' => sub { $spd_p->{rh} = 0; },
'dose:1' => \$spd_p->{dose},
'no-dose|nodose' => sub { $spd_p->{dose} = 0; },
'auto-whitelist|aw:1' => \$spd_p->{sa_awl},
'set-envelope-headers|seh:1' => \$spd_p->{envelopeheaders},
'no-set-envelope-headers|no-seh' => sub { $spd_p->{envelopeheaders} = 0; },
'set-envelope-from|sef:1' => \$spd_p->{setenvelopefrom},
'no-set-envelope-from|no-sef' => sub { $spd_p->{setenvelopefrom} = 0; },
'child-name-template|cnt:s' => \$spd_p->{child_name_templ},
# SA
'debug|d:s' => \$sa_p->{debug},
'saconfig=s' => \$sa_p->{userprefs_filename},
'homedir=s' => \$sa_p->{userstate_dir},
'local-only|l:1' => \$sa_p->{local_tests_only},
'no-local-only|no-l' => sub { $sa_p->{local_tests_only} = 0; },
# others
'dead-letters=s' => \&deprecated_opt,
'heloname=s' => \&deprecated_opt,
'stop-at-threshold' => \&deprecated_opt,
'add-sc-header|ash' => \&deprecated_opt,
'hostname=s' => \&deprecated_opt,
);
}
sub handle_main_opts {
my $self = shift;
my %options = $_[0] || $self->options_map();
my ($srv_p, $spd_p, $sa_p) = ($self->{server}, $self->{spampd}, $self->{assassin});
# Reconfigure GoL for stricter parsing and check for all other options on ARGV, including anything parsed from config file(s).
Getopt::Long::Configure(qw(ignore_case no_permute no_bundling auto_abbrev require_order no_pass_through));
GetOptions(%options) or ($self->is_reloading ? $self->fatal("Could not parse command line!\n") : $self->usage(1));
$self->set_server_type(); # decide who we are
# These paths are already untainted but do a more careful check JIC.
for ($spd_p->{socket}, $spd_p->{relaysocket}, $srv_p->{pid_file}, $sa_p->{userprefs_filename})
{ $_ = untaint_path($_); }
# set up logging specs based on options ($logspec is only an array if --logfile option(s) existed)
if (ref($spd_p->{logspec}) eq 'ARRAY') {
$spd_p->{logtype} &= ~LOG_TYPE_MASK; # reset the low byte containing LOG_<type> constant
($spd_p->{logtype}, $srv_p->{log_file}) = logfile2logtype($spd_p->{logspec}, $spd_p->{logtype});
}
# elsif (!$srv_p->{background}) {
# # set default logging to stderr if not daemonizing and user didn't specify.
# $spd_p->{logtype} = $spd_p->{logtype} & (~LOG_TYPE_MASK) | LOG_STDERR;
# }
# fixup listening socket/host/port if needed
if ($spd_p->{socket}) {
# Net::Server wants UNIX sockets passed via port option.
$srv_p->{port} = join('|', $spd_p->{socket}, 'unix');
}
elsif ($srv_p->{host}) {
# Set IP host/port if they're passed together. A port as part of the host option wins over port option.
my @tmp = split(/:(\d+)$/, $srv_p->{host}); # this split should handle IPv6 addresses also.
$srv_p->{host} = $tmp[0];
$srv_p->{port} = $tmp[1] if $tmp[1];
}
# Set misc. options based on other options.
$srv_p->{setsid}= 0 if !$srv_p->{background};
$sa_p->{home_dir_for_helpers} = $sa_p->{userstate_dir};
$sa_p->{username} = $srv_p->{user};
}
sub validate_main_opts {
my $self = shift;
my ($srv_p, $spd_p) = ($self->{server}, $self->{spampd});
my (@errs, @warns) = (@_ ? $_[0] : (), @_ > 1 ? $_[1] : ());
(@errs, @warns) = $self->validate_server_type_opts(@errs, @warns);
if ($self->{spampd}->{sa_awl} && $spd_p->{sa_version} >= 3)
{ push (@errs, "Option --auto-whitelist is deprecated with SpamAssassin v3.0+. Use SA configuration file instead."); }
# Validate that required modules for relay server exist (better now than later).
if ($spd_p->{relaysocket}) {
eval { require IO::Socket::UNIX; }
or push (@errs, "Error loading IO::Socket::UNIX module, required for --relaysocket option.\n\t$@");
}
else {
eval { require IO::Socket::IP; }
or push (@errs, "Error loading IO::Socket::IP module, required for --relayhost option.\n\t$@");
}
return (@errs, @warns);
}
sub validate_server_type_opts {
my $self = shift;
return $self->validate_prefork_opts(@_) if $self->isa(qw(Net::Server::PreFork)); # must check before Simple (PreFork inherits from it)
return $self->validate_preforksimple_opts(@_) if $self->isa(qw(Net::Server::PreForkSimple));
return @_;
}
sub validate_preforksimple_opts {
my ($self, @errs, @warns) = @_;
if ($self->{server}->{max_servers} < 1)
{ push (@errs, "Option '--max-servers' (or '--children') ($self->{server}->{max_servers}) must be greater than zero!"); }
return (@errs, @warns);
}
sub validate_prefork_opts {
my ($self, @errs, @warns) = @_;
my $prop = $self->{server};
# Even though Net::Server::PreFork validates all these options also,
# their error messages can be confusing and in some cases just wrong.
if ($prop->{min_servers} < 1) {
push (@errs, "Option '--min-servers' ($prop->{min_servers}) must be greater than zero!");
}
elsif ($prop->{max_servers} < 1) {
push (@errs, "Option '--max-servers' (or '--children') ($prop->{max_servers}) must be greater than zero!");
}
elsif ($prop->{max_servers} < $prop->{min_servers}) {
push (@errs, "Option '--max-servers' (or --children) ($prop->{max_servers}) must be >= '--min-servers' ($prop->{min_servers})!");
}
else {
if ($prop->{max_spare_servers} >= $prop->{max_servers})
{ push (@errs, "Option '--max-spare' ($prop->{max_spare_servers}) must be < '--max-servers' ($prop->{max_servers})."); }
if (my $ms = $prop->{min_spare_servers}) {
if ($ms > $prop->{min_servers})
{ push (@errs, "Option '--min-spare' ($ms) must be <= '--min-servers' ($prop->{min_servers})"); }
if ($ms > $prop->{max_spare_servers})
{ push (@errs, "Option '--min-spare' ($ms) must be <= '--max-spare' ($prop->{max_spare_servers})"); }
}
}
return (@errs, @warns);
}
sub setup_logging {
my $self = shift;
my ($srv_p, $ltype, $debug) = ($self->{server}, $self->{spampd}->{logtype}, \$self->{assassin}->{debug});
if ($ltype & LOG_SYSLOG) {
# Need to validate logsock option otherwise SA Logger barfs. In theory this check could be made more adaptive based on OS or something.
if ($srv_p->{syslog_logsock} && $srv_p->{syslog_logsock} !~ /^(native|eventlog|tcp|udp|inet|unix|stream|pipe|console)$/) {
$self->wrn("WARNING! Option '--logsock' parameter \"$srv_p->{syslog_logsock}\" not recognized, reverting to default.\n");
$srv_p->{syslog_logsock} = undef;
}
# set log socket default for HP-UX and SunOS (thanks to Kurt Andersen for the 'uname -s' fix)
# `uname` throws errors (and fails anyway) when HUPping, so we do not repeat it, but do "cache" any new default in our 'commandline'.
if (!($srv_p->{syslog_logsock} || $self->is_reloading())) {
eval { push(@{$srv_p->{commandline}}, "--logsock=" . ($srv_p->{syslog_logsock} = "inet")) if (`uname -s` =~ /HP\-UX|SunOS/); };
}
}
# Configure debugging
if ($$debug ne '0') {
$srv_p->{log_level} = 4; # set Net::Server log level to debug
# SA since v3.1.0 can do granular debug logging based "channels" which can be passed to us via --debug option parameters.
# --debug can also be specified w/out any parameters, in which case we enable the "all" channel.
if ($ltype & LOGGER_SA) { $$debug = 'all' if (!$$debug || $$debug eq '1'); }
else { $$debug = 1; } # In case of old SA version, just set the debug flag to true.
}
if ($ltype & LOGGER_SA) {
# Add SA logging facilities
Mail::SpamAssassin::Logger::add_facilities($$debug);
my $have_log = 0;
# Add syslog method?
if ($ltype & LOG_SYSLOG) {
$have_log = Mail::SpamAssassin::Logger::add(
method => 'syslog',
socket => $srv_p->{syslog_logsock},
facility => $srv_p->{syslog_facility},
ident => $srv_p->{syslog_ident}
);
}
# Add file method?
if (($ltype & LOG_FILE) && Mail::SpamAssassin::Logger::add(method => 'file', filename => $srv_p->{log_file})) {
$have_log = 1;
push(@{$srv_p->{chown_files}}, $srv_p->{log_file}); # make sure we own the file
}
# Stderr logger method is active by default, remove it unless we need it.
if (!($ltype & LOG_STDERR) && $have_log) {
Mail::SpamAssassin::Logger::remove('stderr');
}
$$debug = undef; # clear this otherwise SA will re-add the facilities in new()
$srv_p->{log_file} = undef; # disable Net::Server logging (use our write_to_log_hook() instead)
}
# using Net::Server default logging
elsif ($ltype & LOG_SYSLOG) {
$srv_p->{log_file} = 'Sys::Syslog';
}
elsif ($ltype & LOG_STDERR) {
$srv_p->{log_file} = undef; # tells Net::Server to log to stderr
}
# Redirect all warnings to logger
$SIG{__WARN__} = sub { $self->wrn($_[0]); };
}
################## SERVER METHODS ######################
sub process_message {
my ($self, $fh) = @_;
my $prop = $self->{spampd};
# output lists with a , delimeter by default
local ($") = ",";
# start a timer
my $start = time;
# use the assassin object created during startup
my $assassin = $self->{assassin};
# this gets info about the message temp file
my $size = ($fh->stat)[7] or die "Can't stat mail file: $!";
# Only process message under --maxsize KB
if ($size >= ($prop->{maxsize} * 1024)) {
$self->inf("skipped large message (" . $size / 1024 . "KB)");
return 1;
}
my (@msglines, $msgid, $sender, $recips, $tmp, $mail, $msg_resp);
my $inhdr = 1;
my $addedenvto = 0;
my $envfrom = !($prop->{envelopeheaders} || $prop->{setenvelopefrom});
my $envto = !$prop->{envelopeheaders};
$recips = "@{$self->{smtp_server}->{to}}";
if ("$self->{smtp_server}->{from}" =~ /(\<.*?\>)/) { $sender = $1; }
$recips ||= "(unknown)";
$sender ||= "(unknown)";
## read message into array of lines to feed to SA
# loop over message file content
$fh->seek(0, 0) or die "Can't rewind message file: $!";
while (<$fh>) {
if ($inhdr) {
# we look for and possibly set some headers before handing to SA
if (/^\r?\n$/) {
# outside of msg header after first blank line
$inhdr = 0;
if (!$envfrom) {
unshift(@msglines, "X-Envelope-From: $sender\r\n");
$self->dbg("Added X-Envelope-From") ;
}
if (!$envto) {
unshift(@msglines, "X-Envelope-To: $recips\r\n");
$addedenvto = 1; # we remove this header later
$self->dbg("Added X-Envelope-To");
}
}
else {
# still inside headers, check for some we're interested in
$envto = $envto || (/^(?:X-)?Envelope-To: /);
$envfrom = $envfrom || (/^(?:X-)?Envelope-From: /);
# find the Message-ID for logging (code is mostly from spamd)
if (/^Message-Id:\s+(.*?)\s*$/i) {
$msgid = $1;
while ($msgid =~ s/\([^\(\)]*\)//) { } # remove comments and
$msgid =~ s/^\s+|\s+$//g; # leading and trailing spaces
$msgid =~ s/\s+/ /g; # collapse whitespaces
$msgid =~ s/^.*?<(.*?)>.*$/$1/; # keep only the id itself
$msgid =~ s/[^\x21-\x7e]/?/g; # replace all weird chars
$msgid =~ s/[<>]/?/g; # plus all dangling angle brackets
$msgid =~ s/^(.+)$/<$1>/; # re-bracket the id (if not empty)
}
}
}
# add the line to our result array
push(@msglines, $_);
}
$msgid ||= "(unknown)";
$self->inf("processing message $msgid for " . $recips);
eval {
local $SIG{ALRM} = sub { die "Timed out!\n" };
# save previous timer and start new
my $previous_alarm = alarm($prop->{satimeout});
# Audit the message
if ($prop->{sa_version} >= 3) {
$mail = $assassin->parse(\@msglines, 0);
undef @msglines; #clear some memory-- this screws up SA < v3
}
elsif ($prop->{sa_version} >= 2.70) {
$mail = Mail::SpamAssassin::MsgParser->parse(\@msglines);
}
else {
$mail = Mail::SpamAssassin::NoMailAudit->new(data => \@msglines);
}
# Check spamminess (returns Mail::SpamAssassin:PerMsgStatus object)
my $status = $assassin->check($mail);
$self->dbg("Returned from checking by SpamAssassin");