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