]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/WatchMaildir.pm
use PublicInbox::MIME consistently
[public-inbox.git] / lib / PublicInbox / WatchMaildir.pm
1 # Copyright (C) 2016-2018 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 PublicInbox::Git;
11 use PublicInbox::Import;
12 use PublicInbox::MDA;
13 use PublicInbox::Spawn qw(spawn);
14 use File::Temp qw//;
15
16 sub new {
17         my ($class, $config) = @_;
18         my (%mdmap, @mdir, $spamc, $spamdir);
19
20         # "publicinboxwatch" is the documented namespace
21         # "publicinboxlearn" is legacy but may be supported
22         # indefinitely...
23         foreach my $pfx (qw(publicinboxwatch publicinboxlearn)) {
24                 my $k = "$pfx.watchspam";
25                 if (my $dir = $config->{$k}) {
26                         if ($dir =~ s/\Amaildir://) {
27                                 $dir =~ s!/+\z!!;
28                                 # skip "new", no MUA has seen it, yet.
29                                 my $cur = "$dir/cur";
30                                 $spamdir = $cur;
31                                 push @mdir, $cur;
32                                 $mdmap{$cur} = 'watchspam';
33                         } else {
34                                 warn "unsupported $k=$dir\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                 spamdir => $spamdir,
81                 mdmap => \%mdmap,
82                 mdir => \@mdir,
83                 mdre => $mdre,
84                 config => $config,
85                 importers => {},
86                 opendirs => {}, # dirname => dirhandle (in progress scans)
87         }, $class;
88 }
89
90 sub _done_for_now {
91         my ($self) = @_;
92         my $importers = $self->{importers};
93         foreach my $im (values %$importers) {
94                 $im->done if $im->{nchg};
95         }
96
97         my $opendirs = $self->{opendirs};
98
99         # spamdir scanning means every importer remains open
100         my $spamdir = $self->{spamdir};
101         return if defined($spamdir) && $opendirs->{$spamdir};
102
103         foreach my $im (values %$importers) {
104                 # not done if we're scanning
105                 next if $opendirs->{$im->{git}->{git_dir}};
106                 $im->done;
107         }
108 }
109
110 sub _try_fsn_paths {
111         my ($self, $scan_re, $paths) = @_;
112         foreach (@$paths) {
113                 my $path = $_->{path};
114                 if ($path =~ $scan_re) {
115                         scan($self, $path);
116                 } else {
117                         _try_path($self, $path);
118                 }
119         }
120         _done_for_now($self);
121 }
122
123 sub _remove_spam {
124         my ($self, $path) = @_;
125         # path must be marked as (S)een
126         $path =~ /:2,[A-R]*S[T-Za-z]*\z/ or return;
127         my $mime = _path_to_mime($path) or return;
128         _force_mid($mime);
129         $self->{config}->each_inbox(sub {
130                 my ($ibx) = @_;
131                 eval {
132                         my $im = _importer_for($self, $ibx);
133                         $im->remove($mime, 'spam');
134                         if (my $scrub = _scrubber_for($ibx)) {
135                                 my $scrubbed = $scrub->scrub($mime) or return;
136                                 $scrubbed == 100 and return;
137                                 $im->remove($scrubbed, 'spam');
138                         }
139                 };
140                 if ($@) {
141                         warn "error removing spam at: ", $path,
142                                 " from ", $ibx->{name}, ': ', $@, "\n";
143                 }
144         })
145 }
146
147 # used to hash the relevant portions of a message when there are conflicts
148 sub _hash_mime2 {
149         my ($mime) = @_;
150         require Digest::SHA;
151         my $dig = Digest::SHA->new('SHA-1');
152         $dig->add($mime->header_obj->header_raw('Subject'));
153         $dig->add($mime->body_raw);
154         $dig->hexdigest;
155 }
156
157 sub _force_mid {
158         my ($mime) = @_;
159         # probably a bad idea, but we inject a Message-Id if
160         # one is missing, here..
161         my $mid = $mime->header_obj->header_raw('Message-Id');
162         if (!defined $mid || $mid =~ /\A\s*\z/) {
163                 $mid = '<' . _hash_mime2($mime) . '@generated>';
164                 $mime->header_set('Message-Id', $mid);
165         }
166 }
167
168 sub _try_path {
169         my ($self, $path) = @_;
170         my @p = split(m!/+!, $path);
171         return if $p[-1] !~ /\A[a-zA-Z0-9][\-\w:,=\.]+\z/;
172         if ($p[-1] =~ /:2,([A-Z]+)\z/i) {
173                 my $flags = $1;
174                 return if $flags =~ /[DT]/; # no [D]rafts or [T]rashed mail
175         }
176         return unless -f $path;
177         if ($path !~ $self->{mdre}) {
178                 warn "unrecognized path: $path\n";
179                 return;
180         }
181         my $inbox = $self->{mdmap}->{$1};
182         unless ($inbox) {
183                 warn "unmappable dir: $1\n";
184                 return;
185         }
186         if (!ref($inbox) && $inbox eq 'watchspam') {
187                 return _remove_spam($self, $path);
188         }
189         my $im = _importer_for($self, $inbox);
190         my $mime = _path_to_mime($path) or return;
191         $mime->header_set($_) foreach @PublicInbox::MDA::BAD_HEADERS;
192         my $wm = $inbox->{-watchheader};
193         if ($wm) {
194                 my $v = $mime->header_obj->header_raw($wm->[0]);
195                 return unless ($v && $v =~ $wm->[1]);
196         }
197         if (my $scrub = _scrubber_for($inbox)) {
198                 my $ret = $scrub->scrub($mime) or return;
199                 $ret == 100 and return;
200                 $mime = $ret;
201         }
202
203         _force_mid($mime);
204         $im->add($mime, $self->{spamcheck});
205 }
206
207 sub quit { trigger_scan($_[0], 'quit') }
208
209 sub watch {
210         my ($self) = @_;
211         my $scan = File::Temp->newdir("public-inbox-watch.$$.scan.XXXXXX",
212                                         TMPDIR => 1);
213         my $scandir = $self->{scandir} = $scan->dirname;
214         my $re = qr!\A$scandir/!;
215         my $cb = sub { _try_fsn_paths($self, $re, \@_) };
216
217         # lazy load here, we may support watching via IMAP IDLE
218         # in the future...
219         require Filesys::Notify::Simple;
220         my $fsn = Filesys::Notify::Simple->new([@{$self->{mdir}}, $scandir]);
221         $fsn->wait($cb) until $self->{quit};
222 }
223
224 sub trigger_scan {
225         my ($self, $base) = @_;
226         my $dir = $self->{scandir} or return;
227         open my $fh, '>', "$dir/$base" or die "open $dir/$base failed: $!\n";
228         close $fh or die "close $dir/$base failed: $!\n";
229 }
230
231 sub scan {
232         my ($self, $path) = @_;
233         if ($path =~ /quit\z/) {
234                 %{$self->{opendirs}} = ();
235                 _done_for_now($self);
236                 delete $self->{scandir};
237                 $self->{quit} = 1;
238                 return;
239         }
240         # else: $path =~ /(cont|full)\z/
241         return if $self->{quit};
242         my $max = 10;
243         my $opendirs = $self->{opendirs};
244         my @dirnames = keys %$opendirs;
245         foreach my $dir (@dirnames) {
246                 my $dh = delete $opendirs->{$dir};
247                 my $n = $max;
248                 while (my $fn = readdir($dh)) {
249                         _try_path($self, "$dir/$fn");
250                         last if --$n < 0;
251                 }
252                 $opendirs->{$dir} = $dh if $n < 0;
253         }
254         if ($path =~ /full\z/) {
255                 foreach my $dir (@{$self->{mdir}}) {
256                         next if $opendirs->{$dir}; # already in progress
257                         my $ok = opendir(my $dh, $dir);
258                         unless ($ok) {
259                                 warn "failed to open $dir: $!\n";
260                                 next;
261                         }
262                         my $n = $max;
263                         while (my $fn = readdir($dh)) {
264                                 _try_path($self, "$dir/$fn");
265                                 last if --$n < 0;
266                         }
267                         $opendirs->{$dir} = $dh if $n < 0;
268                 }
269         }
270         _done_for_now($self);
271         # do we have more work to do?
272         trigger_scan($self, 'cont') if keys %$opendirs;
273 }
274
275 sub _path_to_mime {
276         my ($path) = @_;
277         if (open my $fh, '<', $path) {
278                 local $/;
279                 my $str = <$fh>;
280                 $str or return;
281                 return PublicInbox::MIME->new(\$str);
282         } elsif ($!{ENOENT}) {
283                 return;
284         } else {
285                 warn "failed to open $path: $!\n";
286                 return;
287         }
288 }
289
290 sub _importer_for {
291         my ($self, $inbox) = @_;
292         my $im = $inbox->{-import} ||= eval {
293                 my $git = $inbox->git;
294                 my $name = $inbox->{name};
295                 my $addr = $inbox->{-primary_address};
296                 PublicInbox::Import->new($git, $name, $addr, $inbox);
297         };
298
299         my $importers = $self->{importers};
300         if (scalar(keys(%$importers)) > 2) {
301                 delete $importers->{"$im"};
302                 _done_for_now($self);
303         }
304
305         $importers->{"$im"} = $im;
306 }
307
308 sub _scrubber_for {
309         my ($inbox) = @_;
310         my $f = $inbox->{filter};
311         if ($f && $f =~ /::/) {
312                 my @args = (-inbox => $inbox);
313                 # basic line splitting, only
314                 # Perhaps we can have proper quote splitting one day...
315                 ($f, @args) = split(/\s+/, $f) if $f =~ /\s+/;
316
317                 eval "require $f";
318                 if ($@) {
319                         warn $@;
320                 } else {
321                         # e.g: PublicInbox::Filter::Vger->new(@args)
322                         return $f->new(@args);
323                 }
324         }
325         undef;
326 }
327
328 sub _spamcheck_cb {
329         my ($sc) = @_;
330         sub {
331                 my ($mime) = @_;
332                 my $tmp = '';
333                 if ($sc->spamcheck($mime, \$tmp)) {
334                         return PublicInbox::MIME->new(\$tmp);
335                 }
336                 warn $mime->header('Message-ID')." failed spam check\n";
337                 undef;
338         }
339 }
340
341 1;