-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdbmail-postfix-policyd
executable file
·962 lines (793 loc) · 31.3 KB
/
dbmail-postfix-policyd
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
#!/usr/bin/perl -w
# dbmail-postfix-policyd: a Postfix policy server for DBmail
# Copyright 2005,2011 (c) Jesse Norell
# Copyright 2005,2011 (c) Kentec Communications, Inc.
# adapted from postgrey, Copyright 2004 (c) ETH Zurich
# released under the GNU General Public License
# see the documentation with 'perldoc dbmail-postfix-policyd'
# and check https://github.com/jnorell/dbmail-postfix-policyd for more
package dbmail_postfix_policyd;
use strict;
use Pod::Usage;
use Getopt::Long 2.25 qw(:config posix_default no_ignore_case);
use Net::Server::Multiplex;
use Config::IniFiles;
use Sys::Hostname;
use Sys::Syslog;
use DBI;
use vars qw(@ISA);
@ISA = qw(Net::Server::Multiplex);
my $VERSION = "0.01";
my $hostname = hostname;
my $quota_recurse_depth = 0;
# strips comments/whitespace from ini file values
sub ini_cleanup($)
{
my $str = shift;
$str =~ s/\s+#.*//;
$str =~ s/^\s+//;
$str =~ s/\s+$//;
return $str;
}
sub read_dbmail_conf($$)
{
my ($self, $fatal) = @_;
my (%ini, $val);
if ((! defined $self->{dbmail_postfix_policyd}{dbmail_conf}) or
(! -r $self->{dbmail_postfix_policyd}{dbmail_conf}) ) {
return $fatal;
}
$self->log(4, "tieing config file: ".$self->{dbmail_postfix_policyd}{dbmail_conf});
tie %ini, 'Config::IniFiles', ( -file => $self->{dbmail_postfix_policyd}{dbmail_conf} )
or $fatal and die "ERROR: $self->{dbmail_postfix_policyd}{dbmail_conf}: $!\n";
if (defined $ini{DBMAIL}{driver}) {
$val = ini_cleanup($ini{DBMAIL}{driver});
$self->log(4, "read {DBMAIL}{driver}: $val");
$self->{dbmail_postfix_policyd}{dbdriver} = $val;
}
if (defined $ini{DBMAIL}{host}) {
$val = ini_cleanup($ini{DBMAIL}{host});
$self->log(4, "read {DBMAIL}{host}: $val");
$self->{dbmail_postfix_policyd}{dbhost} = $val;
}
if (defined $ini{DBMAIL}{sqlport}) {
$val = ini_cleanup($ini{DBMAIL}{sqlport});
$self->log(4, "read {DBMAIL}{sqlport}: $val");
$self->{dbmail_postfix_policyd}{dbsqlport} = $val;
}
if (defined $ini{DBMAIL}{sqlsocket}) {
$val = ini_cleanup($ini{DBMAIL}{sqlsocket});
$self->log(4, "read {DBMAIL}{sqlsocket}: $val");
$self->{dbmail_postfix_policyd}{dbsqlsocket} = $val;
}
if (defined $ini{DBMAIL}{user}) {
$val = ini_cleanup($ini{DBMAIL}{user});
$self->log(4, "read {DBMAIL}{user}: $val");
$self->{dbmail_postfix_policyd}{dbuser} = $val;
}
if (defined $ini{DBMAIL}{pass}) {
$val = ini_cleanup($ini{DBMAIL}{pass});
$self->log(4, "read {DBMAIL}{pass}: (not displayed)");
$self->{dbmail_postfix_policyd}{dbpass} = $val;
}
if (defined $ini{DBMAIL}{db}) {
$val = ini_cleanup($ini{DBMAIL}{db});
$self->log(4, "read {DBMAIL}{db}: $val");
$self->{dbmail_postfix_policyd}{dbdb} = $val;
}
if (defined $ini{DBMAIL}{table_prefix}) {
$val = ini_cleanup($ini{DBMAIL}{table_prefix});
$self->log(4, "read {DBMAIL}{table_prefix}: $val");
$self->{dbmail_postfix_policyd}{table_prefix} = $val;
}
return 0;
}
# db_reconnect closes any open db connection, reconnects to the server,
# then sets up sql statements depending on dbmail version, etc.
# Note this does not prepare the statements (sql), just saves the query
sub db_reconnect($)
{
my ($self) = @_;
my ($dbd_type, $data_source);
my $d=$self->{dbmail_postfix_policyd};
# if database connection is open, close it
if ($d->{dbh}->{Active}) {
my ($alias_sth, $quota_sth, $quota_by_userid_sth);
# finish active statement handlers
local $d->{dbh}->{RaiseError} = 0;
for (grep { defined } @{$self->{dbmail_postfix_policyd}{dbh}->{ChildHandles}}) {
$_->{Active} && $_->finish();
}
$d->{dbh}->{RaiseError} = 1;
$self->log(4, "db_reconnect: Database is Active, disconnecting");
$d->{dbh}->disconnect();
}
# open database connection and save the handle in $self->{server}
if ($d->{dbtype} =~ m/^pgsql$/i) {
$dbd_type='Pg';
} elsif ($d->{dbtype} =~ m/^mysql$/i) {
$dbd_type='mysql';
} elsif ($d->{dbtype} =~ m/^sqlite$/i) {
$dbd_type='SQLite';
} else {
die "db_reconnect: unknown dbtype ($d->{dbtype})!\n";
}
$data_source="dbi:$dbd_type:dbname=$d->{dbdb}";
if ($dbd_type =~ m/mysql/ && defined $d->{dbhost} && $d->{dbhost} =~ m/^localhost$/) {
$data_source .= ";host=$d->{dbhost}";
if (defined $d->{dbsqlsocket}) {
$data_source .= ";mysql_socket=$d->{dbsqlsocket}";
}
} elsif (defined $d->{dbsqlsocket}) {
if ($dbd_type =~ m/mysql/) {
$data_source .= ";mysql_socket=$d->{dbsqlsocket}";
} else {
$data_source .= ";host=$d->{dbsqlsocket}";
}
} elsif (defined $d->{dbhost}) {
$data_source .= ";host=$d->{dbhost}";
if (defined $d->{dbsqlport}) {
$data_source .= ";port=$d->{dbsqlport}";
}
}
$self->log(4, "db_reconnect: Connecting to $data_source as $d->{dbuser}");
$d->{dbh} = DBI->connect($data_source, $d->{dbuser}, $d->{dbpass},
{ RaiseError => 1, AutoCommit => 1 } ) || die "db_reconnect: Error connecting to database: $DBI::errstr\n";
if ($dbd_type =~ m/mysql/) {
$self->log(4, "db_reconnect: Setting mysql_auto_reconnect");
$d->{dbh}->{mysql_auto_reconnect} = 1;
}
# alias statement is currently the same for all dbmail versions:
$d->{alias_stmt} = "SELECT deliver_to from $d->{table_prefix}aliases where lower(alias) = ?";
if ($d->{dbmail_version} == 1) {
$d->{quota_stmt} = "SELECT maxmail_size, SUM(messagesize) AS curmail_size "
. "FROM $d->{table_prefix}users, $d->{table_prefix}mailboxes "
. "join $d->{table_prefix}messages on "
. " $d->{table_prefix}messages.mailbox_idnr = $d->{table_prefix}mailboxes.mailbox_idnr "
. "where user_idnr = ? "
. "and owner_idnr = user_idnr "
. "and status < 2 "
. "group by user_idnr, maxmail_size ";
$d->{quota_by_userid_stmt} = "";
} elsif ($d->{dbmail_version} == 2) {
$d->{quota_stmt} = "SELECT maxmail_size, curmail_size from $d->{table_prefix}users "
. " where user_idnr = ?";
$d->{quota_by_userid_stmt} = "SELECT maxmail_size, curmail_size from $d->{table_prefix}users "
. " where lower(userid) = ?";
}
return 0;
}
# main routine: based on attributes specified as argument, return policy decision
sub smtpd_access_policy($$)
{
my ($self, $attr) = @_;
# Quota Check requires these:
defined $attr->{recipient} or return 'DUNNO';
defined $attr->{size} or return 'DUNNO';
my $recipient = lc($attr->{recipient});
my $size = $attr->{size};
# Quota Check
dbmail_quota_check($self, $recipient, $size) &&
return "552 Message too large, recipient $recipient would exceed size limits at this time.";
return 'DUNNO';
}
# Quota Check
# We recursively expand aliases, so a single recipient can check against multiple quotas.
# If any of them is under quota, we must allow the message (return 0).
# If any recipients are forwarded externally or execute a command, allow the message.
# Return true (1) only if all recipients would exceed quota.
sub dbmail_quota_check($$$)
{
my ($self, $recipient, $size) = @_;
my $d=$self->{dbmail_postfix_policyd};
unless ($recipient) { return 0; }
unless (($size =~ /^(\d+)$/) and ($size > 0)) { return 0; }
$quota_recurse_depth = 0;
unless ($d->{dbh}->{Active}) {
$self->log(4, "dbmail_quota_check: Database NOT Active, reconnecting");
&db_reconnect($self);
}
# The v1 and v2 checks have a lot of overlap, but the logic is cleaner if kept separate
if ($d->{dbmail_version} == 1) {
return &dbmail_v1_quota_check($self, $recipient, $size);
} elsif ($d->{dbmail_version} == 2) {
return &dbmail_v2_quota_check($self, $recipient, $size);
}
return 0;
}
# Quota Check for DBMail version 1.2 schema
# Return true (1) only if all recipients would exceed quota.
# (see comments at top of dbmail_quota_check())
sub dbmail_v1_quota_check($$$)
{
my ($self, $recipient, $size) = @_;
my $dbh = $self->{dbmail_postfix_policyd}{dbh};
my ($alias_sth, $quota_sth, $quota_by_userid_sth);
my $alias_stmt = $self->{dbmail_postfix_policyd}{alias_stmt};
my $quota_stmt = $self->{dbmail_postfix_policyd}{quota_stmt};
my $quota_by_userid_stmt = $self->{dbmail_postfix_policyd}{quota_by_userid_stmt};
my ($query, @row, $numrows, $max, $cur);
my ($deliver_to, @user_idnrs, @recurse);
unless ($recipient = lc($recipient)) { return 0; }
unless (($size =~ /^(\d+)$/) and ($size > 0)) { return 0; }
$self->log(4, "dbmail_v1_quota_check: checking $recipient (recurse_depth $quota_recurse_depth)");
# what's a sane max depth here?
if ($quota_recurse_depth++ > 12) {
$self->log(2, "recipient $recipient hit max quota_recurse_depth - possible alias loop");
return 0;
}
local $dbh->{RaiseError} = 0;
unless( $alias_sth = $dbh->prepare_cached($alias_stmt,{},1) ) {
$self->log(2, "dbmail_v1_quota_check: prepare_cached(alias_sth): $dbh->errstr");
return 0;
}
unless( $alias_sth->execute($recipient) ) {
$self->log(2, "dbmail_v1_quota_check: alias_sth: $alias_sth->errstr");
return 0;
}
$dbh->{RaiseError} = 1;
for ($numrows=0; @row = $alias_sth->fetchrow_array; $numrows++ ) {
$deliver_to = $row[0];
# commands start with ! or |
if ($deliver_to =~ /^(\!|\|)$/) {
$self->log(4, "dbmail_v1_quota_check: alias expands to command, accepting");
return 0;
}
# all-numeric is a userid
if ($deliver_to =~ /^(\d+)$/) {
$self->log(4, "dbmail_v1_quota_check: found user_idnr $deliver_to");
push @user_idnrs, $deliver_to;
} else {
$self->log(4, "dbmail_v1_quota_check: found $deliver_to");
push @recurse, $deliver_to;
}
}
# recursive lookups of mail forwards
foreach my $recip (@recurse) {
&dbmail_v1_quota_check($self, $recip, $size) || return 0;
}
# at this point, dbmail 1.2 should have all user_idnr's in @user_idnrs,
# we won't recurse past this point.
$quota_recurse_depth--;
# didn't find a matching alias: a showstopper for dbmail 1.x
if ($numrows == 0) {
# should we add an "authoritive" mode, where we reject here?
$self->log(4, "dbmail_v1_quota_check: alias not found, accepting");
return 0;
}
# at this point, all user's ids are in @user_idnrs,
# we can definitively check their quota
foreach my $user_idnr (@user_idnrs) {
local $dbh->{RaiseError} = 0;
unless( $quota_sth = $dbh->prepare_cached($quota_stmt,{},1) ) {
$self->log(2, "dbmail_v1_quota_check: prepare_cached(quota_sth): $dbh->errstr");
return 0;
}
unless( $quota_sth->execute($user_idnr) ) {
$self->log(2, "dbmail_v1_quota_check: quota_sth: $quota_sth->errstr");
return 0;
}
$dbh->{RaiseError} = 1;
for ($numrows=0; ($max, $cur) = $quota_sth->fetchrow_array; $numrows++ ){
if ($max == 0) {
$self->log(4, "dbmail_v1_quota_check: user_idnr $user_idnr has no quota, accepting");
return 0;
}
if ($cur + $size <= $max) {
$self->log(4, "dbmail_v1_quota_check: user_idnr $user_idnr still under quota [$max], accepting");
return 0;
}
}
unless ($numrows) {
# should we add an "authoritive" mode, where we reject here?
$self->log(4, "dbmail_v1_quota_check: user_idnr $user_idnr not found, accepting");
return 0;
}
}
$self->log(4, "dbmail_v1_quota_check: $recipient: $size bytes would exceed quota");
return 1;
}
# Quota Check for DBMail version 2.x schema
# Return true (1) only if all recipients would exceed quota.
# (see comments at top of dbmail_quota_check())
sub dbmail_v2_quota_check($$$)
{
my ($self, $recipient, $size) = @_;
my $dbh = $self->{dbmail_postfix_policyd}{dbh};
my ($alias_sth, $quota_sth, $quota_by_userid_sth);
my $alias_stmt = $self->{dbmail_postfix_policyd}{alias_stmt};
my $quota_stmt = $self->{dbmail_postfix_policyd}{quota_stmt};
my $quota_by_userid_stmt = $self->{dbmail_postfix_policyd}{quota_by_userid_stmt};
my ($query, @row, $numrows, $max, $cur);
my ($deliver_to, @user_idnrs, @recurse);
unless ($recipient = lc($recipient)) { return 0; }
unless (($size =~ /^(\d+)$/) and ($size > 0)) { return 0; }
$self->log(4, "dbmail_v2_quota_check: checking $recipient (recurse_depth $quota_recurse_depth)");
# what's a sane max depth here?
if ($quota_recurse_depth++ > 12) {
$self->log(2, "recipient $recipient hit max quota_recurse_depth - possible alias loop");
return 0;
}
local $dbh->{RaiseError} = 0;
unless( $alias_sth = $dbh->prepare_cached($alias_stmt,{},1) ) {
$self->log(2, "dbmail_v2_quota_check: prepare_cached(alias_sth): $dbh->errstr");
return 0;
}
unless( $alias_sth->execute($recipient) ) {
$self->log(2, "dbmail_v2_quota_check: alias_sth: $alias_sth->errstr");
return 0;
}
$dbh->{RaiseError} = 1;
for ($numrows=0; @row = $alias_sth->fetchrow_array; $numrows++ ) {
$deliver_to = $row[0];
# commands start with ! or |
if ($deliver_to =~ /^(\!|\|)$/) {
$self->log(4, "dbmail_v2_quota_check: alias expands to command, accepting");
return 0;
}
# all-numeric is a userid
if ($deliver_to =~ /^(\d+)$/) {
$self->log(4, "dbmail_v2_quota_check: found user_idnr $deliver_to");
push @user_idnrs, $deliver_to;
} else {
$self->log(4, "dbmail_v2_quota_check: found $deliver_to");
push @recurse, $deliver_to;
}
}
# recursive lookups of mail forwards
foreach my $recip (@recurse) {
&dbmail_v2_quota_check($self, $recip, $size) || return 0;
}
if ($numrows == 0) {
$self->log(4, "dbmail_v2_quota_check: alias not found, checking for matching userid");
local $dbh->{RaiseError} = 0;
unless( $quota_by_userid_sth = $dbh->prepare_cached($quota_by_userid_stmt,{},1) ) {
$self->log(2, "dbmail_v2_quota_check: prepare_cached(quota_by_userid_sth): $dbh->errstr");
return 0;
}
unless( $quota_by_userid_sth->execute($recipient) ) {
$self->log(2, "dbmail_v2_quota_check: quota_by_userid_sth: $quota_by_userid_sth->errstr");
return 0;
}
$dbh->{RaiseError} = 1;
for ($numrows=0; ($max, $cur) = $quota_by_userid_sth->fetchrow_array; $numrows++ ) {
if ($max == 0) {
$self->log(4, "dbmail_v2_quota_check: userid $recipient has no quota, accepting");
return 0;
}
if ($cur + $size <= $max) {
$self->log(4, "dbmail_v2_quota_check: userid $recipient still under quota [$max], accepting");
return 0;
}
}
# dbmail 2 must have found a userid now, or will yet process @user_idnrs,
# else we try catchall addrs
unless (($numrows > 0) || ($#user_idnrs >= 0)) {
my ($user, $dom) = split(/@/, $recipient);
# if $user or $dom is empty, we're checking a catchall addr
unless (length($user)>0 and length($dom)>0) {
$self->log(4, "dbmail_v2_quota_check: $recipient was a catchall lookup, accepting");
return 0;
}
$self->log(4, "dbmail_v2_quota_check: userid not found, begin checking for catchall addrs");
my @catchalls = ("$user\@", "\@$dom");
$_ = $dom;
while (m/\./) {
$_ =~ s/^[^\.]*\.//;
push (@catchalls, '@.'.$_);
}
foreach my $addr (@catchalls) {
$self->log(4, "dbmail_v2_quota_check: checking for catchall $addr");
local $dbh->{RaiseError} = 0;
unless( $alias_sth->execute($addr) ) {
$self->log(2, "dbmail_v2_quota_check: alias_sth: $alias_sth->errstr");
return 0;
}
$dbh->{RaiseError} = 1;
for ($numrows=0; @row = $alias_sth->fetchrow_array; $numrows++ ) {
$deliver_to = $row[0];
if (length($deliver_to) > 0) {
$self->log(4, "dbmail_v2_quota_check: found catchall $addr");
# we check for catchalls in specific order, first match is determinative
return &dbmail_v2_quota_check($self, $addr, $size);
}
}
}
# should we add an "authoritive" mode, where we reject here?
$self->log(4, "dbmail_v2_quota_check: no catchall addrs found, accepting");
return 0;
}
}
# at this point, all user's ids are in @user_idnrs,
# we won't recurse past this point
$quota_recurse_depth--;
# and we can definitively check their quota
foreach my $user_idnr (@user_idnrs) {
local $dbh->{RaiseError} = 0;
unless( $quota_sth = $dbh->prepare_cached($quota_stmt,{},1) ) {
$self->log(2, "dbmail_v2_quota_check: prepare_cached(quota_sth): $dbh->errstr");
return 0;
}
unless( $quota_sth->execute($user_idnr) ) {
$self->log(2, "dbmail_v2_quota_check: quota_sth: $quota_sth->errstr");
return 0;
}
$dbh->{RaiseError} = 1;
for ($numrows=0; ($max, $cur) = $quota_sth->fetchrow_array; $numrows++ ){
if ($max == 0) {
$self->log(4, "dbmail_v2_quota_check: user_idnr $user_idnr has no quota, accepting");
return 0;
}
if ($cur + $size <= $max) {
$self->log(4, "dbmail_v2_quota_check: user_idnr $user_idnr still under quota [$max], accepting");
return 0;
}
}
unless ($numrows) {
# should we add an "authoritive" mode, where we reject here?
$self->log(4, "dbmail_v2_quota_check: user_idnr $user_idnr not found, accepting");
return 0;
}
}
$self->log(4, "dbmail_v2_quota_check: $recipient: $size bytes would exceed quota");
return 1;
}
sub main()
{
# save arguments for Net:Server HUP restart
my @ARGV_saved = @ARGV;
# do not output any localized texts!
$ENV{LC_ALL}='C';
# parse options
my %opt = ();
GetOptions(\%opt, 'help|h', 'man', 'version', 'noaction|no-action|n',
'verbose|v', 'daemonize|d', 'unix|u=s', 'inet|i=s', 'user=s',
'group=s', 'pidfile=s', 'dbtype=s', 'dbhost=s', 'dbsqlport=s',
'dbsqlsocket=s', 'dbuser=s', 'dbpass=s', 'dbdb=s',
'dbmail-conf|f=s', 'dbmail-version|V=s', 'table_prefix=s',
) or exit(1);
if($opt{help}) { pod2usage(1) }
if($opt{man}) { pod2usage(-exitstatus => 0, -verbose => 2) }
if($opt{version}) { print "dbmail-postfix-policyd $VERSION\n"; exit(0) }
if($opt{noaction}) { die "ERROR: don't know how to \"no-action\".\n" }
defined $opt{unix} or defined $opt{inet} or
$opt{inet} = "60002";
# bind only localhost if no host is specified
if(defined $opt{inet} and $opt{inet}=~/^\d+$/) {
$opt{inet} = "localhost:$opt{inet}";
}
defined $opt{dbtype} and $opt{dbtype} !~ m/^((my|pg)sql|sqlite)$/i and
die "ERROR: unsupported dbtype (use mysql, pgsql, or sqlite)\n";
# note: more option checks are done in post_configure_hook(),
# so we can use logging
# create Net::Server object and run it
my $server = bless {
server => {
commandline => [ $0, @ARGV_saved ],
opt => { %opt },
port => [ $opt{inet} ? $opt{inet} : $opt{unix}."|unix" ],
proto => $opt{inet} ? 'tcp' : 'unix',
user => $opt{user} || 'dbmail',
group => $opt{group} || 'dbmail',
setsid => $opt{daemonize} ? 1 : undef,
pid_file => $opt{daemonize} ? $opt{pidfile} : undef,
log_level => $opt{verbose} ? 4 : 2,
log_file => $opt{daemonize} ? 'Sys::Syslog' : undef,
syslog_logsock => $^O eq 'solaris' ? 'inet' : 'unix',
syslog_facility => 'mail',
syslog_ident => 'dbmail-postfix-policyd',
},
dbmail_postfix_policyd => {
dbmail_conf => $opt{'dbmail-conf'} ? $opt{'dbmail-conf'} : '/etc/dbmail/dbmail.conf',
dbmail_version => $opt{'dbmail-version'} ? $opt{'dbmail-version'} : 2,
dbtype => $opt{dbtype} ? $opt{dbtype} : undef,
dbhost => $opt{dbhost} ? $opt{dbhost} : undef,
dbsqlport => $opt{dbsqlport} ? $opt{dbsqlport} : undef,
dbsqlsocket => $opt{dbsqlsocket} ? $opt{dbsqlsocket} : undef,
dbuser => $opt{dbuser} ? $opt{dbuser} : undef,
dbpass => $opt{dbpass} ? $opt{dbpass} : undef,
dbdb => $opt{dbdb} ? $opt{dbdb} : undef,
table_prefix => $opt{table_prefix} ? $opt{table_prefix} : undef,
dbh => undef,
},
}, 'dbmail_postfix_policyd';
if (defined $opt{'dbmail-conf'}) {
$server->read_dbmail_conf(1) and
die "ERROR: error reading $server->{dbmail_postfix_policyd}{dbmail_conf}\n";
}
elsif (defined $opt{dbhost} and defined $opt{dbuser}
and defined $opt{dbpass} and defined $opt{dbdb}) {
$server->read_dbmail_conf(0);
$server->{dbmail_postfix_policyd}{dbmail_conf} = undef;
}
else {
$server->read_dbmail_conf(1) and
die "ERROR: error reading $server->{dbmail_postfix_policyd}{dbmail_conf}\n";
}
unless (defined $server->{dbmail_postfix_policyd}{dbtype}) {
if (defined $server->{dbmail_postfix_policyd}{dbdriver}) {
$_ = $server->{dbmail_postfix_policyd}{dbdriver};
if ((/^postgresql$/) or (/^pgsql$/)) {
$server->{dbmail_postfix_policyd}{dbtype} = 'pgsql';
}
if ((/^mysql$/) or (/^sqlite$/)) {
$server->{dbmail_postfix_policyd}{dbtype} = $_;
}
} else {
die "ERROR: dbtype required (mysql or pgsql)\n";
}
}
if (defined $opt{dbhost}) {
$server->{dbmail_postfix_policyd}{dbhost} = $opt{dbhost};
}
if (defined $opt{dbsqlport}) {
$server->{dbmail_postfix_policyd}{dbsqlport} = $opt{dbsqlport};
}
if (defined $opt{dbsqlsocket}) {
$server->{dbmail_postfix_policyd}{dbsqlsocket} = $opt{dbsqlsocket};
}
if (defined $opt{dbuser}) {
$server->{dbmail_postfix_policyd}{dbuser} = $opt{dbuser};
}
if (defined $opt{dbpass}) {
$server->{dbmail_postfix_policyd}{dbpass} = $opt{dbpass};
}
if (defined $opt{dbdb}) {
$server->{dbmail_postfix_policyd}{dbdb} = $opt{dbdb};
}
# TODO: need to handle dbmail_version 3 and check for libzdb settings
unless (( $server->{dbmail_postfix_policyd}{dbmail_version} == 2
and
( defined $server->{dbmail_postfix_policyd}{dbsqlsocket}
or
( defined $server->{dbmail_postfix_policyd}{dbhost}
and
defined $server->{dbmail_postfix_policyd}{dbsqlport}
)
)
and
( defined $server->{dbmail_postfix_policyd}{dbuser}
and
defined $server->{dbmail_postfix_policyd}{dbpass}
and
defined $server->{dbmail_postfix_policyd}{dbdb}
)
)
or
( $server->{dbmail_postfix_policyd}{dbmail_version} == 1
and
( defined $server->{dbmail_postfix_policyd}{dbhost}
and
defined $server->{dbmail_postfix_policyd}{dbuser}
and
defined $server->{dbmail_postfix_policyd}{dbpass}
and
defined $server->{dbmail_postfix_policyd}{dbdb}
)
)
)
{
die "ERROR: You must either provide a dbmail.conf \n"
. "or specify all db parameters on the command line.\n";
}
if (defined $opt{table_prefix}) {
$server->{dbmail_postfix_policyd}{table_prefix} = $opt{table_prefix};
} elsif (! defined $server->{dbmail_postfix_policyd}{table_prefix}) {
if ($server->{dbmail_postfix_policyd}{dbmail_version} > 1) {
$server->{dbmail_postfix_policyd}{table_prefix} = 'dbmail_';
}
else {
$server->{dbmail_postfix_policyd}{table_prefix} = '';
}
}
$server->run;
}
##### Net::Server::Multiplex methods:
# reload dbmail.conf on HUP
sub sig_hup {
my $self = shift;
$self->log(2, "HUP received: reloading dbmail.conf...");
if ($self->{dbmail_postfix_policyd}{dbh}->{Active}) {
for (grep { defined } @{$self->{dbmail_postfix_policyd}{dbh}->{ChildHandles}}) {
$_->{Active} && $_->finish();
}
$self->{dbmail_postfix_policyd}{dbh}->disconnect();
}
# note this allows some settings to be changed via dbmail.conf
# that were set via cli options, which could break things
# right now that's a feature, not a bug.
$self->read_dbmail_conf();
pre_loop_hook($self)
}
sub pre_loop_hook()
{
my ($self) = @_;
# write files with mode 600
umask 0077;
# unix socket permissions should be 666
if($self->{server}{proto} eq 'unix') {
my $unix_path = $self->{server}{port}[0];
$unix_path =~ s/\|unix$//;
chmod 0666, $unix_path;
}
# be sure to put in syslog any warnings / fatal errors
if($self->{server}{log_file} eq 'Sys::Syslog') {
$SIG{__WARN__} = sub { Sys::Syslog::syslog('warning', '%s', "warning: $_[0]") };
$SIG{__DIE__} = sub { Sys::Syslog::syslog('crit', '%s', "fatal: $_[0]"); die @_; };
}
&db_reconnect($self);
}
sub mux_input()
{
my ($self, $mux, $fh, $in_ref) = @_;
defined $self->{dbmail_postfix_policyd} or $self->{dbmail_postfix_policyd} = {};
my $attr = $self->{dbmail_postfix_policyd};
# consume entire lines
while ($$in_ref =~ s/^([^\r\n]*)\r?\n//) {
next unless defined $1;
my $in = $1;
if($in =~ /([^=]+)=(.*)/) {
# read attributes
$attr->{substr($1, 0, 512)} = substr($2, 0, 512);
}
elsif($in eq '') {
defined $attr->{request} or $attr->{request}='';
if($attr->{request} ne 'smtpd_access_policy') {
$self->{net_server}->log(2, "unrecognized request type: '$attr->{request}'");
}
else {
# decide
my $action = $self->{net_server}->smtpd_access_policy($attr);
# debug
if($self->{net_server}{server}{log_level}>=4) {
my $a = 'request: ';
$a .= join(' ', map {"$_=$attr->{$_}"} (sort keys %$attr));
$a .= " action=$action";
$self->{net_server}->log(4, $a);
}
# give answer
print $fh "action=$action\n\n";
}
$self->{dbmail_postfix_policyd} = {};
}
else {
$self->{net_server}->log(2, "ignoring garbage: <".substr($in, 0, 100).">");
}
}
}
main;
__END__
=head1 NAME
dbmail-postfix-policyd - Postfix Policy Server for DBmail
=head1 SYNOPSIS
B<dbmail-postfix-policyd> [I<options>...]
-h, --help display this help and exit
--version output version information and exit
-v, --verbose increase verbosity level
-u, --unix=PATH listen on unix socket PATH
-i, --inet=[HOST:]PORT listen on PORT (default: 60002), localhost if HOST is not specified
-d, --daemonize run in the background
--pidfile=PATH put daemon pid into this file
--user=USER run as USER (default: dbmail)
--group=GROUP run as group GROUP (default: dbmail)
-f, --dbmail-conf=PATH location of dbmail.conf file
(default: /etc/dbmail/dbmail.conf)
-V, --dbmail-version=VER dbmail version in use (default: 2)
--table_prefix=PREFIX dbmail table prefix
(default: '' for dbmail-version = 1
'dbmail_' for dbmail-version > 1 )
--dbtype=TYPE database type, mysql, pgsql, or sqlite (default: read from dbmail.conf)
--dbhost=HOST database host (default: read from dbmail.conf)
--sqlport=PORT database port (default: read from dbmail.conf)
--sqlsocket=PATH database socket (default: read from dbmail.conf)
--dbuser=USER database username (default: read from dbmail.conf)
--dbpass=PASS database password (default: read from dbmail.conf)
--dbdb=DB database name (default: read from dbmail.conf)
Note the database parameters are read from dbmail.conf and can be
overwritten with command-line options. dbmail.conf is not needed
if you supply all options on the command-line, but don't do that
for security reasons if you have other users on your machine.
=head1 DESCRIPTION
dbmail-postfix-policyd is a Postfix policy server for use with DBmail.
Currenly only a Quota Check is performed, though other dbmail-specific
checks could be added in the future.
=head2 Quota Check
=over 4
When a request for delivery of a mail is received by Postfix via SMTP,
recipient address is first checked for existance in dbmail's aliases and/or
users table (varies by dbmail version), and matching aliases expanded. If
all possible delivery recipients would go over quota by receiving the message,
it is rejected. (Typically there is only one delivery recipient, going to
the user's INBOX.) This helps keep your local mail queue clear of many of the
undeliverable over-quota bounces dbmail generates.
=back
=head1 INSTALLATION
=over 4
=item *
Create a C<dbmail> user and /etc/dbmail/dbmail.conf config file
(both probably exist, if you're already running dbmail).
=item *
Write an init script to start dbmail-postfix-policyd at boot and start it.
Like this for example:
dbmail-postfix-policyd -d
or:
dbmail-postfix-policyd --inet=60002 -d -f=/etc/dbmail.conf -V=1 --dbtype=mysql
=item *
Configure postfix to use the policy service with something like this in
/etc/postfix/main.cf:
smtpd_recipient_restrictions =
...
reject_unauth_destination
check_policy_service inet:127.0.0.1:60002
smtpd_end_of_data_restrictions =
check_policy_service inet:127.0.0.1:60002
If your postfix setup uses an after-queue content filter
(eg. for spam or virus scanning), add a
C<-o smtpd_end_of_data_restrictions =>
to the after-filter smtp server.
=back
=head1 SEE ALSO
See L<https://github.com/jnorell/dbmail-postfix-policyd> for
the latest version of dbmail-postfix-policyd, Installation
help and any other project goodies.
See L<http://www.dbmail.org/> for more information on
dbmail.
See L<http://www.postfix.org/SMTPD_POLICY_README.html>
for a description of how Postfix policy servers work,
and L<http://www.postfix.org/FILTER_README.html> for
information on setting up Postfix after-queue content
fiters.
=head1 TODO
=over 4
=item -
Handle errors/restarts, maybe create a watcher script or
test performance running as a service right from master.cf.
=item -
Capability to prompt for database password.
=item -
Stress-test everything, watch for query performance, etc.
=item -
SQLite/Oracle/Other Support
=item -
Sieve Support (per-folder quotas, forwarding, etc.) ?
=item -
Add option to customize returned message.
=item -
Scrap everything and re-write a policy server based on dbmail-lmtpd ?
=back
=head1 COPYRIGHT
=over 4
=item
Copyright (c) 2005,2011 by Jesse Norell. All rights reserved.
=item
Copyright (c) 2005,2011 by Kentec Communications, Inc. All rights reserved.
=item
Portions Copyright (c) 2004-2007 by ETH Zurich. All rights reserved.
=back
=head1 LICENSE
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, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
=head1 AUTHOR
=over 4
=item
Initial DBMail quota support: S<Jesse Norell E<lt>jesse@kci.netE<gt>>
=item
Code based on postgrey, Copyright 2004 (c) ETH Zurich.
=back
=head1 HISTORY
=over 4
=item -
2011-04-08 jn Completed initial version
=item -
2005-02-14 jn Initial work begun
=back
=cut