]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/WatchMaildir.pm
f81a917c5ab74070425a309c3ae3f25a93981fd4
[public-inbox.git] / lib / PublicInbox / WatchMaildir.pm
1 # Copyright (C) 2016 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 #
4 # ref: https://cr.yp.to/proto/maildir.html
5 #       http://wiki2.dovecot.org/MailboxFormat/Maildir
6 package PublicInbox::WatchMaildir;
7 use strict;
8 use warnings;
9 use PublicInbox::MIME;
10 use Email::MIME::ContentType;
11 $Email::MIME::ContentType::STRICT_PARAMS = 0; # user input is imperfect
12 use PublicInbox::Git;
13 use PublicInbox::Import;
14 use PublicInbox::MDA;
15 use PublicInbox::Spawn qw(spawn);
16
17 sub new {
18         my ($class, $config) = @_;
19         my (%mdmap, @mdir, $spamc);
20
21         # "publicinboxwatch" is the documented namespace
22         # "publicinboxlearn" is legacy but may be supported
23         # indefinitely...
24         foreach my $pfx (qw(publicinboxwatch publicinboxlearn)) {
25                 my $k = "$pfx.watchspam";
26                 if (my $spamdir = $config->{$k}) {
27                         if ($spamdir =~ s/\Amaildir://) {
28                                 $spamdir =~ s!/+\z!!;
29                                 # skip "new", no MUA has seen it, yet.
30                                 my $cur = "$spamdir/cur";
31                                 push @mdir, $cur;
32                                 $mdmap{$cur} = 'watchspam';
33                         } else {
34                                 warn "unsupported $k=$spamdir\n";
35                         }
36                 }
37         }
38
39         my $k = 'publicinboxwatch.spamcheck';
40         my $spamcheck = $config->{$k};
41         if ($spamcheck) {
42                 if ($spamcheck eq 'spamc') {
43                         $spamcheck = 'PublicInbox::Spamcheck::Spamc';
44                 }
45                 if ($spamcheck =~ /::/) {
46                         eval "require $spamcheck";
47                         $spamcheck = _spamcheck_cb($spamcheck->new);
48                 } else {
49                         warn "unsupported $k=$spamcheck\n";
50                         $spamcheck = undef;
51                 }
52         }
53         foreach $k (keys %$config) {
54                 $k =~ /\Apublicinbox\.([^\.]+)\.watch\z/ or next;
55                 my $name = $1;
56                 my $watch = $config->{$k};
57                 if ($watch =~ s/\Amaildir://) {
58                         $watch =~ s!/+\z!!;
59                         my $inbox = $config->lookup_name($name);
60                         if (my $wm = $inbox->{watchheader}) {
61                                 my ($k, $v) = split(/:/, $wm, 2);
62                                 $inbox->{-watchheader} = [ $k, qr/\Q$v\E/ ];
63                         }
64                         my $new = "$watch/new";
65                         my $cur = "$watch/cur";
66                         push @mdir, $new, $cur;
67                         die "$new already in use\n" if $mdmap{$new};
68                         die "$cur already in use\n" if $mdmap{$cur};
69                         $mdmap{$new} = $mdmap{$cur} = $inbox;
70                 } else {
71                         warn "watch unsupported: $k=$watch\n";
72                 }
73         }
74         return unless @mdir;
75
76         my $mdre = join('|', map { quotemeta($_) } @mdir);
77         $mdre = qr!\A($mdre)/!;
78         bless {
79                 spamcheck => $spamcheck,
80                 mdmap => \%mdmap,
81                 mdir => \@mdir,
82                 mdre => $mdre,
83                 config => $config,
84                 importers => {},
85         }, $class;
86 }
87
88 sub _done_for_now {
89         $_->done foreach values %{$_[0]->{importers}};
90 }
91
92 sub _try_fsn_paths {
93         my ($self, $paths) = @_;
94         _try_path($self, $_->{path}) foreach @$paths;
95         _done_for_now($self);
96 }
97
98 sub _remove_spam {
99         my ($self, $path) = @_;
100         # path must be marked as (S)een
101         $path =~ /:2,[A-R]*S[T-Za-z]*\z/ or return;
102         my $mime = _path_to_mime($path) or return;
103         _force_mid($mime);
104         $self->{config}->each_inbox(sub {
105                 my ($ibx) = @_;
106                 eval {
107                         my $im = _importer_for($self, $ibx);
108                         $im->remove($mime);
109                         if (my $scrub = _scrubber_for($ibx)) {
110                                 my $scrubbed = $scrub->scrub($mime) or return;
111                                 $scrubbed == 100 and return;
112                                 $im->remove($scrubbed);
113                         }
114                 };
115                 if ($@) {
116                         warn "error removing spam at: ", $path,
117                                 " from ", $ibx->{name}, ': ', $@, "\n";
118                 }
119         })
120 }
121
122 # used to hash the relevant portions of a message when there are conflicts
123 sub _hash_mime2 {
124         my ($mime) = @_;
125         require Digest::SHA;
126         my $dig = Digest::SHA->new('SHA-1');
127         $dig->add($mime->header_obj->header_raw('Subject'));
128         $dig->add($mime->body_raw);
129         $dig->hexdigest;
130 }
131
132 sub _force_mid {
133         my ($mime) = @_;
134         # probably a bad idea, but we inject a Message-Id if
135         # one is missing, here..
136         my $mid = $mime->header_obj->header_raw('Message-Id');
137         if (!defined $mid || $mid =~ /\A\s*\z/) {
138                 $mid = '<' . _hash_mime2($mime) . '@generated>';
139                 $mime->header_set('Message-Id', $mid);
140         }
141 }
142
143 sub _try_path {
144         my ($self, $path) = @_;
145         my @p = split(m!/+!, $path);
146         return if $p[-1] !~ /\A[a-zA-Z0-9][\w:,=\.]+\z/;
147         if ($p[-1] =~ /:2,([A-Z]+)\z/i) {
148                 my $flags = $1;
149                 return if $flags =~ /[DT]/; # no [D]rafts or [T]rashed mail
150         }
151         return unless -f $path;
152         if ($path !~ $self->{mdre}) {
153                 warn "unrecognized path: $path\n";
154                 return;
155         }
156         my $inbox = $self->{mdmap}->{$1};
157         unless ($inbox) {
158                 warn "unmappable dir: $1\n";
159                 return;
160         }
161         if (!ref($inbox) && $inbox eq 'watchspam') {
162                 return _remove_spam($self, $path);
163         }
164         my $im = _importer_for($self, $inbox);
165         my $mime = _path_to_mime($path) or return;
166         $mime->header_set($_) foreach @PublicInbox::MDA::BAD_HEADERS;
167         my $wm = $inbox->{-watchheader};
168         if ($wm) {
169                 my $v = $mime->header_obj->header_raw($wm->[0]);
170                 return unless ($v && $v =~ $wm->[1]);
171         }
172         if (my $scrub = _scrubber_for($inbox)) {
173                 my $ret = $scrub->scrub($mime) or return;
174                 $ret == 100 and return;
175                 $mime = $ret;
176         }
177
178         _force_mid($mime);
179         $im->add($mime, $self->{spamcheck});
180 }
181
182 sub quit { $_[0]->{quit} = 1 }
183
184 sub watch {
185         my ($self) = @_;
186         my $cb = sub { _try_fsn_paths($self, \@_) };
187         my $mdir = $self->{mdir};
188
189         # lazy load here, we may support watching via IMAP IDLE
190         # in the future...
191         require Filesys::Notify::Simple;
192         my $watcher = Filesys::Notify::Simple->new($mdir);
193         $watcher->wait($cb) until ($self->{quit});
194 }
195
196 sub scan {
197         my ($self) = @_;
198         my $mdir = $self->{mdir};
199         foreach my $dir (@$mdir) {
200                 my $ok = opendir(my $dh, $dir);
201                 unless ($ok) {
202                         warn "failed to open $dir: $!\n";
203                         next;
204                 }
205                 while (my $fn = readdir($dh)) {
206                         _try_path($self, "$dir/$fn");
207                 }
208                 closedir $dh;
209         }
210         _done_for_now($self);
211 }
212
213 sub _path_to_mime {
214         my ($path) = @_;
215         if (open my $fh, '<', $path) {
216                 local $/;
217                 my $str = <$fh>;
218                 $str or return;
219                 return PublicInbox::MIME->new(\$str);
220         } elsif ($!{ENOENT}) {
221                 return;
222         } else {
223                 warn "failed to open $path: $!\n";
224                 return;
225         }
226 }
227
228 sub _importer_for {
229         my ($self, $inbox) = @_;
230         my $im = $inbox->{-import} ||= eval {
231                 my $git = $inbox->git;
232                 my $name = $inbox->{name};
233                 my $addr = $inbox->{-primary_address};
234                 PublicInbox::Import->new($git, $name, $addr, $inbox);
235         };
236
237         my $importers = $self->{importers};
238         if (scalar(keys(%$importers)) > 2) {
239                 delete $importers->{"$im"};
240                 _done_for_now($self);
241         }
242
243         $importers->{"$im"} = $im;
244 }
245
246 sub _scrubber_for {
247         my ($inbox) = @_;
248         my $f = $inbox->{filter};
249         if ($f && $f =~ /::/) {
250                 my @args = (-inbox => $inbox);
251                 # basic line splitting, only
252                 # Perhaps we can have proper quote splitting one day...
253                 ($f, @args) = split(/\s+/, $f) if $f =~ /\s+/;
254
255                 eval "require $f";
256                 if ($@) {
257                         warn $@;
258                 } else {
259                         # e.g: PublicInbox::Filter::Vger->new(@args)
260                         return $f->new(@args);
261                 }
262         }
263         undef;
264 }
265
266 sub _spamcheck_cb {
267         my ($sc) = @_;
268         sub {
269                 my ($mime) = @_;
270                 my $tmp = '';
271                 if ($sc->spamcheck($mime, \$tmp)) {
272                         return PublicInbox::MIME->new(\$tmp);
273                 }
274                 warn $mime->header('Message-ID')." failed spam check\n";
275                 undef;
276         }
277 }
278
279 1;