forked from madroach/minimalist
-
Notifications
You must be signed in to change notification settings - Fork 0
/
minimalist.pl
executable file
·2160 lines (1844 loc) · 64.9 KB
/
minimalist.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 -Tw
#
# Minimalist - Minimalistic Mailing List Manager.
# Copyright (c) 1999-2005 Vladimir Litovka <[email protected]>
# Copyright (c) 2012 Christopher Zimmermann <[email protected]>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
# THE POSSIBILITY OF SUCH DAMAGE.
use v5.10;
no if $] >= 5.018, warnings => "experimental::smartmatch";
use strict;
use integer;
use Fcntl ':flock'; # LOCK_* constants
use Carp;
use Net::Config qw(%NetConfig);
use Net::SMTP;
require File::Spec;
require Digest::MD5;
require MIME::QuotedPrint;
require MIME::Base64;
require Sys::Hostname;
require POSIX;
$ENV{SMTPHOST} = '127.0.0.1';
delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
$ENV{'PATH'} = '/bin:/usr/bin';
my $version = '3.1';
my $config = "/etc/minimalist.conf";
#####################################################
# Prototypes
#
sub send_message ($$$;$);
sub verify ($$);
sub logCommand ($$);
sub subscribe ($$;$);
sub unsubscribe ($$;$);
sub chgSettings ($$$$;@);
sub genAdminReport ($$$);
sub archive ($$$);
sub arch_pipe ($$);
sub read_config ($$);
sub load_config ($);
sub load_language ();
sub read_info ($$);
sub genAuth ($$$$;@);
sub getAuth ($);
# Lists' status bits
my $OPEN = 0;
my $RO = 1;
my $CLOSED = 2;
my $MANDATORY = 4;
#####################################################
# Various regular expressions
#
# for matching rounding spaces
my $spaces = '^\s*(.*?)\s*$';
# for parsing two forms of mailing addresses:
#
# 1st form: Vladimir Litovka <[email protected]>
# 2nd form: [email protected] (Vladimir Litovka)
my $addr = qr/[[:graph:]]+@[[:graph:]]+/;
my $first = qr/((.*?)\s*<($addr)>)(.*)/; # $2 - gecos, $3 - address, $4 - rest
my $second = qr/(($addr)\s*\((.*?)\))(.*)/; # $2 - address, $3 - gecos, $4 - rest
#####################################################
# Default values
#
my $domain = Sys::Hostname::hostname();
my %global_conf = (
domain => $domain,
admin => "postmaster\@$domain",
adminpwd => undef,
listpwd => undef,
archive => 'no',
archpgm => 'BUILTIN',
arcsize => 0,
auth_scheme => 'password',
auth_valid => 24,
background => 'no',
blocked_robots => 'CurrentlyWeAreBlockingNoRobot-Do__NOT__leaveThisBlank', # -VTV-
cc_on_subscribe => 'no', # -VTV-
charset => 'us-ascii',
copy_sender => 'yes',
delay => 0,
directory => '/var/db/minimalist',
errors_to => 'drop',
translationpath => 'translations',
language => 'en',
list_gecos => '',
listdir => 'lists',
listinfo => 'yes',
logfile => undef,
logmessages => 'no',
maxrcpts => 20,
maxsize => 0, # Maximum allowed size for message (incl. headers)
maxusers => 0,
me => "minimalist\@$domain",
mesender => "minimalist\@$domain", # For substitute in X-Sender header
modify_msgid => 'no',
modify_subject => 'yes',
outgoing_from => '',
remove_resent => 'no',
reply_to_list => 'no',
security => 'careful',
sendmail => undef,
status => $OPEN,
strip_rrq => 'no',
to_recipient => 'no',
xtrahdr => ''
);
undef $domain;
#####################################################
# Other global variables
#
my $smtp;
END { $smtp->quit() if(defined $smtp) }
my $password = 0;
my $maketext;
my %msgtxt;
# HASH of known lists - key is lowercase listname, value list directory.
my %lists;
my @blacklist;
my @trusted;
########################################################
# >>>>>>>>>>>>>>>>>>> CONFIGURING <<<<<<<<<<<<<<<<<<<< #
########################################################
srand; # Seed random number generator while /dev/urandom is accessible
my %conf = read_config($config, 'global');
@global_conf{keys %conf} = values %conf;
%conf = %global_conf;
if (defined $conf{logfile}) {
open LOG, '>>', "$conf{logfile}" or warn "Can't open $conf{logfile}: $!" }
else {
open LOG, '>', File::Spec->devnull or warn "Can't open null device: $!" }
unless(-t STDERR) {
open STDOUT, ">&LOG" or warn "Can't redirect STDOUT: $!";
open STDERR, ">&LOG" or warn "Can't redirect STDERR: $!";
select LOG;
}
load_language();
push @{$NetConfig{smtp_hosts}}, 'localhost' unless($#{$NetConfig{smtp_hosts}} >= 0);
unless (defined $smtp || defined $conf{sendmail}) {
$smtp = Net::SMTP->new()
or warn "SMTP connect failed. SMTP connection specified in local chrooted config?";
$conf{sendmail} = undef;
}
#########################################################
# >>>>>>>>>>>>>>>>>>>>>>> MAKETEXT <<<<<<<<<<<<<<<<<<<< #
#########################################################
chdir $conf{directory} or die "Cannot chdir to $conf{directory}.";
# Convenience wrapper
sub mt (@) { $maketext->maketext(@_) }
$maketext = Translation::en->new() || die "Language?";
################################################################
# >>>>>>>>>>>>>>> CHROOT AND DROP PRIVILEGES <<<<<<<<<<<<<<<<< #
################################################################
-d $conf{directory} or die "$conf{directory} is not a directory.";
# $< and $( are real [ug]id, $> and $) are effective [ug]id
if ($> == 0 && $< != 0) {
my $uid;
my $gid = getgrnam('nogroup');
defined $gid or $gid = getgrnam('nobody');
defined $gid or die "Could not get gid of nogroup.";
if (defined $conf{user}) {
$uid = getpwnam($conf{user});
defined $uid or die "Could not get uid of $conf{user}.";
}
else { $uid = $< }
# drop group privileges
$) = "$gid $gid";
die "Error while dropping group privileges: $!" unless($) eq "$gid $gid");
POSIX::setgid($gid) or die "setgid failed: $!";;
# chroot
chroot $conf{directory} or die "Could not chroot to $conf{directory}: $!";
chdir '/' or die "Cannot chdir to / in chroot ($conf{directory}).";
$conf{directory} = '/';
# drop user privileges
POSIX::setuid($uid) or die "setuid failed: $!";
# This may be too paranoid, but check
# that privileges are really dropped permanently
POSIX::setuid(0);
POSIX::setgid(0);
my $groups = qr/^$gid( $gid)?$/;
if ($< == 0 || $> == 0 || $( !~ $groups || $) !~ $groups) {
die "Could not drop privileges permanently." }
}
@INC = ('.');
####################################################################
# >>>>>>>>>>>>>>>>>>>>>> PREPARE HASH OF LISTS <<<<<<<<<<<<<<<<<<< #
####################################################################
opendir(LISTDIR, $conf{listdir}) || die "Cannot open $conf{listdir}!";
while ($_ = readdir LISTDIR) {
warn "$_ list is found twice - maybe in differing case?" if (exists $lists{lc $_});
$lists{lc $1} = $1 if(/^([^\.].*)$/ && -d "$conf{listdir}/$_");
}
closedir LISTDIR;
####################################################################
# >>>>>>>>>>>>>>>>>>>>>>>> CHECK CONFIGURATION <<<<<<<<<<<<<<<<<<< #
####################################################################
if (defined $ARGV[0] && $ARGV[0] eq '-') {
my $msg;
my %lconf = %conf;
print "\nMinimalist v$version, pleased to meet you.\n".
"Using \"$config\" as main configuration file\n\n";
print "================= Global configuration ================\n".
"Directory: $lconf{directory}\n".
"User: $lconf{user}\n".
"Administrative password: ".(defined $lconf{adminpwd} ? "ok\n" : "not defined\n").
"Logging: $lconf{logfile}\n".
"Language: $lconf{language}\n".
"Log info about messages: $lconf{logmessages}\n".
"Background execution: $lconf{background}\n".
"Authentication request valid at least $lconf{auth_valid} hours\n".
"Blocked robots:";
if ($lconf{blocked_robots} !~ /__NOT__/) {
foreach (split(/\|/, $lconf{blocked_robots})) {
print "\n\t$_"; }
}
else { print " no one"; }
if ( @blacklist ) {
print "\nGlobal access list is:\n";
foreach (@blacklist) {
if ( $_ =~ s/^!(.*)//g ) { print "\t - ".$1." allowed\n" }
else { print "\t - ".$_." disallowed\n" }
};
};
print "\n\n";
while ( $ARGV[0] ) {
@trusted = ();
if ($ARGV[0] ne '-') {
$ARGV[0] =~ /^([[:graph:]]+)$/;
my $list = $1;
if (exists $lists{lc $list}) {
$list = $lists{lc $list};
}
else {
print " * There isn't such list \U$list\E\n\n";
shift; next;
}
my %nconf = read_config("$conf{listdir}/$list/config", 'list');
%lconf = %conf;
@lconf{keys %nconf} = values %nconf;
undef %nconf;
print "================= \U$list\E ================\n";
print "Administrators: ";
if ( @trusted ) {
print "\n";
foreach (@trusted) { print "\t . ".$_."\n"; }
}
else { print "not defined\n"; }
print "Administrative password: ".(! $conf{listpwd} ? "empty" :
$conf{listpwd} =~ /^_.*_$/ ? "not defined" : "Ok")."\n";
}
print
"Domain: $lconf{domain}\n".
"Security: $lconf{security}\n".
"Archiving: $lconf{archive}\n".
($lconf{archive} ne 'no' ? " * Archiver: $lconf{archpgm}\n" . ($lconf{arcsize} != 0 ? " * Maximum message size: $lconf{arcsize} bytes\n" : "") : "")
.
"Status:";
if ($lconf{status}) {
print " read-only" if ($lconf{status} & $RO);
print " closed" if ($lconf{status} & $CLOSED);
print " mandatory" if ($lconf{status} & $MANDATORY);
}
else { print " open"; }
print "\nCopy to sender: $lconf{copy_sender}\n".
"Reply-To list: $lconf{reply_to_list}\n".
"List GECOS: ".($lconf{list_gecos} ? $lconf{list_gecos} : "empty")."\n".
"Subject tag: ".($lconf{subject_tag} ? $lconf{subject_tag} : "empty")."\n".
"Substitute From: ".($lconf{outgoing_from} ? $lconf{outgoing_from} : "none")."\n".
"Admin: $lconf{admin}\n".
"Errors from MTA: ".($lconf{errors_to} eq 'drop' ? "drop" :
($lconf{errors_to} eq 'verp' ? "generate VERP" : "return to $lconf{errors_to}"))."\n".
"Modify subject: $lconf{modify_subject}\n".
"Modify Message-ID: $lconf{modify_msgid}\n".
"Notify on subscribe/unsubscribe event: $lconf{cc_on_subscribe}\n".
"Maximal users per list: ".($lconf{maxusers} ? $lconf{maxusers} : "unlimited")."\n".
"Maximal recipients per message: ".($lconf{maxrcpts} ? $lconf{maxrcpts} : "unlimited")."\n".
"Delay between deliveries: ".($lconf{delay} ? $lconf{delay} : "none")."\n".
"Maximal size of message: ".($lconf{maxsize} ? "$lconf{maxsize} bytes" : "unlimited")."\n".
"Strip 'Return Receipt' requests: $lconf{strip_rrq}\n".
"List information: ".($lconf{listinfo} eq 'no' ? "no" : "yes".
($lconf{listinfo} ne 'yes' ? ", archive at: $lconf{listinfo}" : ""))."\n".
"Charset: $lconf{charset}\n".
"Language: $lconf{language}\n".
"Fill To: with recipient's address: $lconf{to_recipient}\n".
"Extra Header(s):".($lconf{xtrahdr} ? "\n\n$lconf{xtrahdr}" : " none")."\n\n";
# Various checks
$msg .= " * $lconf{directory} doesn't exist!\n" if (! -d $lconf{directory});
$msg .= " * Invalid 'log messages' value '$lconf{logmessages}'\n" if ($lconf{logmessages} !~ /^yes$|^no$/i);
$msg .= " * Invalid 'background' value '$lconf{background}'\n" if ($lconf{background} !~ /^yes$|^no$/i);
$msg .= " * Invalid security level '$lconf{security}'\n" if ($lconf{security} !~ /^none$|^careful$|^paranoid$/i);
$msg .= " * Invalid 'copy to sender' value '$lconf{copy_sender}'\n" if ($lconf{copy_sender} !~ /^yes$|^no$/i);
$msg .= " * Invalid 'modify subject' value '$lconf{modify_subject}'\n" if ($lconf{modify_subject} !~ /^yes$|^no$|^more$/i);
$msg .= " * Invalid 'modify message-id' value '$lconf{modify_msgid}'\n" if ($lconf{modify_msgid} !~ /^yes$|^no$/i);
$msg .= " * Invalid 'cc on subscribe' value '$lconf{cc_on_subscribe}'\n" if ($lconf{cc_on_subscribe} !~ /^yes$|^no$/i);
$msg .= " * Invalid 'reply-to list' value '$lconf{reply_to_list}'\n" if ($lconf{reply_to_list} !~ /^yes$|^no$|\@/i);
$msg .= " * Invalid 'from' value '$lconf{outgoing_from}'\n" if ($lconf{outgoing_from} !~ /\@|^$/i);
$msg .= " * Invalid authentication request validity time: $lconf{auth_valid}\n" if ($lconf{auth_valid} !~ /^[0-9]+$/);
$msg .= " * Invalid archiving strategy '$lconf{archive}'\n" if ($lconf{archive} !~ /^no$|^daily$|^monthly$|^yearly$|^pipe$/i);
$msg .= " * Invalid 'strip rrq' value '$lconf{strip_rrq}'\n" if ($lconf{strip_rrq} !~ /^yes$|^no$/i);
$msg .= " * Invalid 'remove resent' value '$lconf{remove_resent}'\n" if ($lconf{remove_resent} !~ /^yes$|^no$/i);
my $translation = "$lconf{translationpath}/$lconf{language}";
$msg .= " * Invalid 'to recipient' value '$lconf{to_recipient}'\n" if ($lconf{to_recipient} !~ /^yes$|^no$/i);
$msg .= " * Translation file $translation not available'\n" unless (-f $translation || $lconf{language} eq "en");
if ($lconf{archive} eq 'pipe') {
(my $arpg, ) = split(/\s+/, $lconf{archpgm}, 2);
$msg .= " * $arpg doesn't exists!\n" unless (-x $arpg);
}
goto CfgCheckEnd if ($msg);
shift;
}
CfgCheckEnd:
print "\t=== FAILURE ===\n\nErrors are:\n".$msg."\n" if ($msg);
exit;
}
####################################################################
# >>>>>>>>>>>>>>>>>>>>>>>>> START HERE <<<<<<<<<<<<<<<<<<<<<<<<<<< #
####################################################################
{
# Clean old authentication requests
cleanAuth();
my ($message, $header, $body);
while (<STDIN>) {
s/\r//g; # Remove Windooze's \r, it is safe to do this
$message .= $_;
}
($header, $body) = split(/\n\n/, $message, 2); $header .= "\n";
undef $message; # Clear memory, it isn't used anymore
my $list = my $from;
my $sender = my $xsender = my $orig_subj = my $subject = '';
# Check SysV-style "From ". Stupid workaround for messages from robots, but
# with human-like From: header. In most cases "From " is the only way to
# find out envelope sender of message.
if ($header =~ /^From (.*)\n/i) {
exit 0 if ($1 =~ /(MAILER-DAEMON|postmaster)@/i); }
# Extract $list from command line or Delivered-To:
if ($ARGV[0]) { $list = $ARGV[0] }
elsif ($header =~ /(^|\n)delivered-to: (.*)\n/i) {
$list = $2; $list =~ s/@.*//; }
else {
die "no list specified on commond line and ".
"could not find \"delivered-to:\" header." }
undef $list if($list eq "minimalist");
# Extract From:
if ($header =~ /(^|\n)from:\s+(.*\n([ \t]+.*\n)*)/i) {
$from = $2; $from =~ s/$spaces/$1/ogs;
$from =~ s/\n//g; $from =~ s/\s{2,}/ /g; }
else {
die "Could not find \"from:\" header." }
# Sender and X-Sender are interesting only when generated by robots
# (Minimalist, MTA, etc), which (I think :) don't produce multiline headers.
if ($header =~ /(^|\n)sender: (.*)\n/i) { $sender = $2; }
if ($header =~ /(^|\n)x-sender: (.*)\n/i) { $xsender = $2; }
# If there is Reply-To, use this address for replying
my $mailto;
if ($header =~ /(^|\n)reply-to:\s+(.*\n([ \t]+.*\n)*)/i) {
$mailto = $2; $mailto =~ s/$spaces/$1/gs }
else {
$mailto = $from }
# Preparing From:
if ($from =~ s/$first/$3/og) { ;}
elsif ($from =~ s/$second/$2/og) { ;}
$from =~ s/\s+//gs; $from = lc($from);
exit 0 if (($xsender eq $conf{mesender}) || ($from eq $conf{mesender})); # LOOP detected
exit 0 if (($from =~ /(MAILER-DAEMON|postmaster)@/i) || # -VTV-
($sender =~ /(MAILER-DAEMON|postmaster)@/i) ||
($xsender =~ /(MAILER-DAEMON|postmaster)@/i)); # ignore messages from MAILER-DAEMON
exit 0 if ( $header =~ /^($conf{blocked_robots}):/); # disable loops from robots -VTV-
foreach (@blacklist) { # Parse access control list
if ( $_ =~ s/^!(.*)//g ) {
last if ( $from =~ /$1$/i || $sender =~ /$1$/i || $xsender =~ /$1$/i) }
else {
exit if ( $from =~ /$_$/i || $sender =~ /$_$/i || $xsender =~ /$_$/i) }
};
my $qfrom = quotemeta($from); # For use among with 'grep' function
# Look for user's supplied password
# in header (in form: '{pwd: blah-blah}' )
while ($header =~ s/\{pwd:[ \t]*(\w+)\}//i) {
$password = $1; }
# in body, as very first '*password: blah-blah'
if (!$password && $body =~ s/^\*password:[ \t]+(\w+)\n+//i) {
$password = $1; }
# Get (multiline) subject
if ($header =~ /(^|\n)subject:[ \t]+(.*\n([ \t]+.*\n)*)/i) {
$subject = $2;
$subject .= substr($^X,0,0); # taint $subject
$orig_subj = $subject =~ s/$spaces/$1/gs; }
$body =~ s/\n*$/\n/g;
$body =~ s/\n\.\n/\n \.\n/g; # Single '.' treated as end of message
#########################################################################
########################## Message to list ##############################
#########################################################################
if ($list) {
my $msg;
my @hdrcpt;
my @members;
my @rcpts;
my @readonly;
my @recip;
my @recipients;
my @rw;
my @writeany;
my @dontcopyme;
# normalize to exact directory name.
if (exists $lists{lc $list}) {
$list = $lists{lc $list};
}
else {
$msg = <<_EOF_ ;
ERROR:
Minimalist was called with the '$list' argument, but there is no such list.
SOLUTION:
Check your 'aliases' file - there is a possible typo.
_EOF_
send_message('Subject: Possible error in system settings', $msg, $conf{admin});
exit;
}
##################################
# Go to background, through fork #
##################################
if ($conf{background} eq 'yes') {
$msg = <<_EOF_ ;
ERROR:
Minimalist can not fork due to the following reason:
_EOF_
my $forks = 0;
FORK: {
if (++$forks > 4) {
$msg .= "\n Can't fork for more than 5 times\n\n";
send_message('Subject: Can not fork', $msg, $conf{admin});
exit;
}
my $pid;
if ($pid = fork) {
# OK, parent here, exiting
exit 0;
}
elsif (defined $pid) {
# OK, child here. Detach and do
close STDIN;
close STDOUT;
close STDERR;
}
elsif ($! =~ /No more process/i) {
# EAGAIN, supposedly recoverable fork error, but no more than 5 times
sleep 5;
redo FORK;
}
else {
# weird fork error, exiting
$msg .= "\n $!\n\n";
send_message('Subject: Can not fork', $msg, $conf{admin});
exit;
}
} # Label FORK
} # if ($conf{background})
load_config($list);
# Remove or exit per List-ID
exit 0 if ($header =~ s/(^|\n)list-id:\s+(.*)\n/$1/i && $2 =~ /$list.$conf{domain}/i);
if ($conf{modify_subject} ne 'no') {
my $tag = $conf{subject_tag} // $list;
$orig_subj = $subject;
if ($conf{modify_subject} eq 'more') { # Remove leading "Re: "
$subject =~ s/^.*:\s+(\[\Q$tag\E\])/$1/ig }
else { # change anything before [...] to Re:
$subject =~ s/^(.*:\s+)+(\[\Q$tag\E\])/Re: $2/ig; }
# Modify subject if not already done
if ($subject !~ /^(.*:\s+)?\[\Q$tag\E\] /i) {
$subject = "[$tag] ".$subject; }
}
open LIST, "$conf{listdir}/$list/list" and do {
while (my $ent = <LIST>) {
if ( $ent =~ /^(?!#)([[:graph:]]+@[[:graph:]]+)$/ ) {
$ent = lc($1);
# Get and remove per-user settings from e-mail
my $userSet;
($ent, $userSet) = split (/>/, $ent);
# Check for '+' (write access) or '-' (read only access)
if (defined $userSet && $userSet =~ /-/) { push (@readonly, $ent); }
elsif (defined $userSet && $userSet =~ /\+/) { push (@writeany, $ent); }
# Check for 'd' (dont copy me)
if (defined $userSet && $userSet =~ /d/) { push (@dontcopyme, $ent); }
# If user's maxsize
my $usrMaxSize = 0;
if (defined $userSet && $userSet =~ /#ms([0-9]+)/) { $usrMaxSize = $1; }
# If suspended (!) or maxsize exceeded, do not put in @members
if (defined $userSet && $userSet =~ /!/ || ($usrMaxSize && length($body) > $usrMaxSize)) {
push (@rw, $ent); }
else {
push (@members, $ent); }
}
}
close LIST;
};
# If sender isn't admin, prepare list of allowed writers
if (($conf{security} ne 'none') && ! verify($from, $password)) {
push (@rw, @members);
open LIST, "$conf{listdir}/$list/list-writers" and do {
while (my $ent = <LIST>) {
if ( $ent && $ent !~ /^#/ ) {
chomp($ent); $ent = lc($ent);
# Get and remove per-user settings from e-mail
my $userSet;
($ent, $userSet) = split (/>/, $ent);
# Check for '+' (write access) or '-' (read only access)
if (defined $userSet && $userSet =~ /-/) { push (@readonly, $ent); }
elsif (defined $userSet && $userSet =~ /\+/) { push (@writeany, $ent); }
# Check for 'd' (dont copy me)
if (defined $userSet && $userSet =~ /d/) { push (@dontcopyme, $ent); }
push (@rw, $ent); }
}
close LIST;
}
}
# If sender isn't admin and not in list of allowed writers
if (($conf{security} ne 'none') && ! verify($from, $password) && !grep(/^$qfrom$/i, @rw)) {
my $body =
mt('ERROR:'). "\n\t".
mt('You([_1]) are not subscribed to this list([_2]).', $from, $list).
"\n\n".
mt('SOLUTION:'). "\n\t".
mt("Send a message to [_1] with a subject of 'help' (no quotes) for information about howto subscribe.",
"$conf{me}").
"\n\n".
mt('Your message follows:').
'==========================================================================='.
$body.
'===========================================================================';
send_message("Subject: $subject", $body, $mailto)
}
# If list or sender in read-only mode and sender isn't admin and not
# in allowed writers
elsif (($conf{status} & $RO || grep(/^$qfrom$/i, @readonly)) && !verify($from, $password) && !grep(/^$qfrom$/i, @writeany)) {
my $body =
mt('ERROR:'). "\n\t".
mt('You([_1]) are not allowed to write to this list.', $from). "\n\n".
mt('Your message follows:').
'==========================================================================='.
$body.
'===========================================================================';
send_message("Subject: $subject", $body, $mailto)
}
elsif ($conf{maxsize} && (length($header) + length($body) > $conf{maxsize})) {
my $body =
mt('ERROR:'). "\n\t".
mt('Message size is larger than maximum allowed ([_1] bytes).',
$conf{maxsize}).
"\n\n".
mt('SOLUTION:'). "\n\t".
mt('Either send a smaller message or split your message into multiple smaller ones.').
"\n\n".
mt('Your message header follows:').
'==========================================================================='.
$header.
'===========================================================================';
send_message("Subject: $subject", $body, $mailto)
}
else { # Ok, all checks done.
logCommand($from, "L=\"$list\" T=\"$orig_subj\" S=".(length($header) + length($body))) if ($conf{logmessages} ne 'no');
$conf{archive} = 'no' if ($conf{arcsize} && length ($body) > $conf{arcsize});
if ($conf{archive} eq 'pipe') { arch_pipe($header, $body); }
elsif ($conf{archive} ne 'no') { archive($list, $header, $body); }
# Extract and remove all recipients of message. This information will be
# used later, when sending message to members except those who already
# received this message directly.
my $rc;
if ($header =~ s/(^|\n)to:\s+(.*\n([ \t]+.*\n)*)/$1/i) { $rc = $2 }
if ($header =~ s/(^|\n)cc:\s+(.*\n([ \t]+.*\n)*)/$1/i) { $rc .= ",".$2 }
if ($rc) {
foreach $rc (split /,/, $rc) {
if ($rc =~ s/$first/$4/) { push (@recip, $1) }
elsif ($rc =~ s/$second/$4/) { push (@recip, $1) }
else { $rc =~ s/$spaces/$1/; push (@recip, $rc); }
}
}
my $to_gecos;
# Search for user's supplied GECOS
foreach my $trcpt (@recip) {
$trcpt =~ s/$spaces/$1/gs;
next if (! $trcpt); # In case "To: e@mail, \n" - don't push spaces, which are between ',' and '\n'
push(@hdrcpt, $trcpt);
my $tmp_to_gecos = undef;
if ( $trcpt =~ s/$first/$3/g ) { ($tmp_to_gecos = $2) =~ s/$spaces/$1/gs; }
elsif ( $trcpt =~ s/$second/$2/g ) { ($tmp_to_gecos = $3) =~ s/$spaces/$1/gs; }
push(@rcpts, $trcpt = lc($trcpt));
$to_gecos = $tmp_to_gecos if ($tmp_to_gecos && $trcpt =~ /$list\@$conf{domain}/i);
}
# If there was To: and Cc: headers, put them back in message's header
if (@hdrcpt && $conf{to_recipient} eq 'no') {
# If there is administrator's supplied GECOS, use it instead of user's supplied
if ($conf{list_gecos}) {
for (my $i=0; $i<@hdrcpt; $i++) {
if ($hdrcpt[$i] =~ /$list\@$conf{domain}/i) { # Yes, list's address
$hdrcpt[$i] =~ s/$second/$2/g if (! ($hdrcpt[$i] =~ s/$first/$3/g));
$hdrcpt[$i] = "$conf{list_gecos} <$hdrcpt[$i]>";
}
}
$to_gecos = $conf{list_gecos};
}
chomp $header;
$header .= "\nTo: $hdrcpt[0]\n";
if (@hdrcpt > 1) {
$header .= "Cc: $hdrcpt[1]";
for (my $i=2; $i<@hdrcpt; $i++) {
$header .= ",\n\t$hdrcpt[$i]";
}
$header .= "\n";
}
}
# Remove conflicting headers
$header =~ s/(^|\n)x-list-server:\s+.*\n([ \t]+.*\n)*/$1/ig;
$header =~ s/(^|\n)precedence:\s+.*\n/$1/ig;
if ($conf{remove_resent} eq 'yes') {
$header =~ s/(^|\n)(resent-.*\n([ \t]+.*\n)*)*/$1/ig;
}
if ($conf{strip_rrq} eq 'yes') { # Return Receipt requests
$header =~ s/return-receipt-to:\s+.*\n//ig;
$header =~ s/disposition-notification-to:\s+.*\n//ig;
$header =~ s/x-confirm-reading-to:\s+.*\n//ig;
}
if ($conf{modify_msgid} eq 'yes') { # Change Message-ID in outgoing message
$header =~ s/message-id:\s+(.*)\n//i;
my $old_msgid = $1; $old_msgid =~ s/$first/$3/g;
my $msgid = "MMLID_".int(rand(100000));
$header .= "Message-ID: <$msgid-$old_msgid>\n";
}
chomp ($header);
$header .= "\nPrecedence: list\n"; # For vacation and similar programs
# Remove original From_ line unconditionally
$header =~ s/^From .*\n//;
# Remove original Reply-To unconditionally, set configured one if it is
$header =~ s/(^|\n)reply-to:\s+.*\n([ \t]+.*\n)*/$1/ig;
if ($conf{reply_to_list} eq 'yes') { $header .= "Reply-To: $to_gecos <$list\@$conf{domain}>\n"; }
elsif ($conf{reply_to_list} ne 'no') { $header .= "Reply-To: $conf{reply_to_list}\n"; }
if ($conf{modify_subject} ne 'no') {
$header =~ s/(^|\n)subject:\s+.*\n([ \t]+.*\n)*/$1/ig;
$header .= "Subject: $subject\n";
}
if ($conf{outgoing_from} ne '') {
$header =~ s/(^|\n)from:\s+.*\n([ \t]+.*\n)*/$1/ig;
$header .= "From: $conf{outgoing_from}\n";
}
if ($conf{listinfo} ne 'no') {
# --- Preserve List-Archive if it's there
my $listarchive;
if ($header =~ s/(^|\n)List-Archive:\s+(.*\n([ \t]+.*\n)*)/$1/i) { $listarchive = $2; }
# --- Remove List-* headers
$header =~ s/(^|\n)(List-.*\n([ \t]+.*\n)*)*/$1/ig;
$header .= "List-Help: <mailto:$conf{me}?subject=help>\n";
$header .= "List-Subscribe: <mailto:$conf{me}?subject=subscribe%20$list>\n";
$header .= "List-Unsubscribe: <mailto:$conf{me}?subject=unsubscribe%20$list>\n";
$header .= "List-Post: <mailto:$list\@$conf{domain}>\n";
$header .= "List-Owner: <mailto:$list-owner\@$conf{domain}>\n";
if ($conf{listinfo} ne 'yes') {
$header .= "List-Archive: $conf{listinfo}\n"; }
elsif ($listarchive) {
$header .= "List-Archive: $listarchive\n"; }
}
$header .= "List-ID: <$list.$conf{domain}>\n";
$header .= "X-List-Server: Minimalist v$version <http://www.mml.org.ua/>\n";
$header .= "X-BeenThere: $list\@$conf{domain}\n"; # This header deprecated due to RFC2919 (List-ID)
if ($conf{xtrahdr}) {
$conf{xtrahdr} =~ s/\\a/$conf{admin}/ig;
$conf{xtrahdr} =~ s/\\d/$conf{domain}/ig;
$conf{xtrahdr} =~ s/\\l/$list/ig;
$conf{xtrahdr} =~ s/\\o/$list-owner\@$conf{domain}/ig;
$conf{xtrahdr} =~ s/\\n/\n/ig;
$conf{xtrahdr} =~ s/\\t/\t/ig;
$conf{xtrahdr} =~ s/\\s/ /ig;
chomp $conf{xtrahdr};
$header .= "$conf{xtrahdr}\n";
}
# Convert plain/text messages to multipart/mixed or
# append footer to existing MIME structure
#
if (my $footer = read_info($list, 'footer')) {
$header =~ /(^|\n)Content-Type:\s+(.*\n(\s+.*\n)*)/i;
my $ctyped = $2;
# Check if there is Content-Type and it isn't multipart/*
if (!$ctyped || $ctyped !~ /^multipart\/(mixed|related)/i) {
$ctyped =~ /charset="?(.*?)"?[;\s]/i;
my $msgcharset = lc($1);
$header =~ /(^|\n)Content-Transfer-Encoding:\s+(.*)\n/i;
my $encoding = lc($1)
if ($header =~ /(^|\n)Content-Transfer-Encoding:[ \t]+(.*\n([ \t]+.*\n)*)/i);
# If message is 7/8bit text/plain with same charset without preset headers in
# footer, then simply add footer to the end of message
if ($ctyped =~ /^text\/plain/i &&
$encoding =~ /[78]bit|quoted-printable/i &&
($conf{charset} eq $msgcharset || $conf{charset} eq 'us-ascii') &&
$footer !~ /^\*hdr:[ \t]+/i)
{
given ($encoding) {
when (/[78]bit/) {
$body .= "\n\n$footer" }
when (/quoted-printable/) {
$body .= MIME::QuotedPrint::encode_qp("\n\n$footer") }
default {
die "Unknown encoding \"$encoding\"" }
}
}
else {
# Move Content-* fields to MIME entity
my @ctypeh;
while ($header =~ s/(^|\n)(Content-[\w\-]+:[ \t]+(.*\n([ \t]+.*\n)*))/$1/i) {
push (@ctypeh, $2)
}
my $boundary = "MML_".time()."_$$\@".int(rand(10000)).".$conf{domain}";
$header .= "MIME-Version: 1.0\n" if ($header !~ /(^|\n)MIME-Version:/);
$header .= "Content-Type: multipart/mixed;\n\tboundary=\"$boundary\"\n";
if ($footer !~ s/^\*hdr:[ \t]+// && $conf{charset}) {
$footer = "Content-Type: text/plain; charset=$conf{charset}\n".
"Content-Disposition: inline\n".
"Content-Transfer-Encoding: 8bit\n\n".$footer;
}
# Make body
$body = "\nThis is a multi-part message in MIME format.\n".
"\n--$boundary\n".
join ('', @ctypeh).
"\n$body".
"\n--$boundary\n".
$footer.
"\n--$boundary--\n";
}
}
else { # Have multipart message
$ctyped =~ /boundary="?(.*?)"?[;\s]/i;
my @boundary;
my $level = 1; $boundary[0] = $boundary[1] = $1; my $pos = 0;
THROUGH_LEVELS:
while ($level) {
my $hdrpos = index ($body, "--$boundary[$level]", $pos) + length($boundary[$level]) + 3;
my $hdrend = index ($body, "\n\n", $hdrpos);
my $entity_hdr = substr ($body, $hdrpos, $hdrend - $hdrpos)."\n";
$entity_hdr =~ /(^|\n)Content-Type:[ \t]+(.*\n([ \t]+.*\n)*)/i;
$ctyped = $2;
if ($ctyped =~ /boundary="?(.*?)"?[;\s]/i) {
$level++; $boundary[$level] = $1; $pos = $hdrend + 2;
next;
}
else {
my $process_level = $level;
while ($process_level == $level) {
# Looking for nearest boundary
$pos = index ($body, "\n--", $hdrend);
# If nothing found, then if it's last entity, add footer
# to end of body, else return error
if ($pos == -1) {
if ($level == 1) { $pos = length ($body); }
last THROUGH_LEVELS;
}
$hdrend = index ($body, "\n", $pos+3);
my $bound = substr ($body, $pos+3, $hdrend-$pos-3);
my $difflevel;
# End of current level?
if ($bound eq $boundary[$level]."--") { $difflevel = 1; }
# End of previous level?
elsif ($bound eq $boundary[$level-1]."--") { $difflevel = 2; }
else { $difflevel = 0; }
if ($difflevel) {
$pos += 1; $level -= $difflevel;
if ($level > 0) {
$pos += length ("--".$boundary[$level]."--"); }
}
# Next part of current level
elsif ($bound eq "$boundary[$level]") {
$pos += length ("$boundary[$level]") + 1;
}
# Next part of previous level
elsif ($bound eq "$boundary[$level-1]") {
$pos++; $level--;
}
# else seems to be boundary error, but do nothing
}
}
} # while THROUGH_LEVELS
if ($pos != -1) {
# If end of last level not found, workaround this
if ($pos == length($body) && $body !~ /\n$/) {
$body .= "\n"; $pos++; }
# Modify last boundary - it will not be last
substr($body, $pos, length($body)-$pos) = "--$boundary[1]\n";
# Prepare footer and append it with really last boundary
if ($footer !~ s/^\*hdr:[ \t]+// && $conf{charset}) {
$footer = "Content-Type: text/plain; charset=$conf{charset}; name=\"footer\"\n".
"Content-Transfer-Encoding: 8bit\n\n".$footer;
}
$body .= $footer."\n--$boundary[1]--\n";
}
# else { print "Non-recoverable error while processing input file\n"; }
}
}
if ($conf{copy_sender} eq 'no') { push (@rcpts, $from) } # @rcpts will be _excluded_
# Sort by domains
my @t;
@members = sort @t = Invert ('@', '!', @members);
@rcpts = sort @t = Invert ('@', '!', @rcpts);
@dontcopyme = sort @t = Invert ('@', '!', @dontcopyme);
for (my $r = my $m = 0; $m < @members; ) {
if ($r >= @rcpts || $members[$m] lt $rcpts[$r]) {
my $qmember = quotemeta($members[$m]);
if (!grep(/^$qmember$/i, @dontcopyme)) {
push (@recipients, $members[$m++]); }
else {
my ($dom, $us) = split ('!', $members[$m]);
if ($us.'@'.$dom ne $from) {
push (@recipients, $members[$m++]); }
else {
$m++;
}
}
}
elsif ($members[$m] eq $rcpts[$r]) { $r++; $m++; }
elsif ($members[$m] gt $rcpts[$r]) { $r++ };
}
@recipients = Invert ('!', '@', @recipients);
#########################################################
# Send message to recipients ($conf{maxrcpts} per message)
warn "Empty recipient" if(grep($_ eq '', @recipients));
my $maxrcpts =
($conf{errors_to} eq 'verp' || $conf{to_recipient} eq 'yes')
? 1 : $conf{maxrcpts};
while (@recipients) {
my @bcc = splice(@recipients, 0, $maxrcpts);
my $hdr = $header;
my $verp_bcc = $bcc[0]; $verp_bcc =~ s/\@/=/g;
$hdr .= "To: $bcc[0]\n" if ($conf{to_recipient} eq 'yes');
my $envelope_sender;
given ($conf{errors_to}) {
when('drop') { $envelope_sender = "$conf{me}"; }
when('admin') { $envelope_sender = "$conf{admin}"; }
when('verp') { $envelope_sender = "$list-owner-$verp_bcc\@$conf{domain}"; }
when($_ ne 'sender') { $envelope_sender = $conf{errors_to} }
default { $envelope_sender = ""; }
}