]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/WatchMaildir.pm
mda, watch: wire up List-ID header support
[public-inbox.git] / lib / PublicInbox / WatchMaildir.pm
1 # Copyright (C) 2016-2019 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::Spawn qw(spawn);
11 use PublicInbox::InboxWritable;
12 use File::Temp qw//;
13 use PublicInbox::Filter::Base;
14 use PublicInbox::Spamcheck;
15 *REJECT = *PublicInbox::Filter::Base::REJECT;
16
17 sub new {
18         my ($class, $config) = @_;
19         my (%mdmap, @mdir, $spamc);
20         my %uniq;
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                 defined(my $dirs = $config->{$k}) or next;
28                 $dirs = [ $dirs ] if !ref($dirs);
29                 for my $dir (@$dirs) {
30                         if (is_maildir($dir)) {
31                                 # skip "new", no MUA has seen it, yet.
32                                 my $cur = "$dir/cur";
33                                 my $old = $mdmap{$cur};
34                                 if (ref($old)) {
35                                         foreach my $ibx (@$old) {
36                                                 warn <<"";
37 "$cur already watched for `$ibx->{name}'
38
39                                         }
40                                         die;
41                                 }
42                                 push @mdir, $cur;
43                                 $uniq{$cur}++;
44                                 $mdmap{$cur} = 'watchspam';
45                         } else {
46                                 warn "unsupported $k=$dir\n";
47                         }
48                 }
49         }
50
51         my $k = 'publicinboxwatch.spamcheck';
52         my $default = undef;
53         my $spamcheck = PublicInbox::Spamcheck::get($config, $k, $default);
54         $spamcheck = _spamcheck_cb($spamcheck) if $spamcheck;
55
56         $config->each_inbox(sub {
57                 # need to make all inboxes writable for spam removal:
58                 my $ibx = $_[0] = PublicInbox::InboxWritable->new($_[0]);
59
60                 my $watch = $ibx->{watch} or return;
61                 if (is_maildir($watch)) {
62                         my $watch_hdrs = [];
63                         if (my $wh = $ibx->{watchheader}) {
64                                 my ($k, $v) = split(/:/, $wh, 2);
65                                 push @$watch_hdrs, [ $k, qr/\Q$v\E/ ];
66                         }
67                         if (my $list_ids = $ibx->{listid}) {
68                                 for (@$list_ids) {
69                                         my $re = qr/<[ \t]*\Q$_\E[ \t]*>/;
70                                         push @$watch_hdrs, ['List-Id', $re ];
71                                 }
72                         }
73                         if (scalar @$watch_hdrs) {
74                                 $ibx->{-watchheaders} = $watch_hdrs;
75                         }
76                         my $new = "$watch/new";
77                         my $cur = "$watch/cur";
78                         push @mdir, $new unless $uniq{$new}++;
79                         push @mdir, $cur unless $uniq{$cur}++;
80
81                         push @{$mdmap{$new} ||= []}, $ibx;
82                         push @{$mdmap{$cur} ||= []}, $ibx;
83                 } else {
84                         warn "watch unsupported: $k=$watch\n";
85                 }
86         });
87         return unless @mdir;
88
89         my $mdre = join('|', map { quotemeta($_) } @mdir);
90         $mdre = qr!\A($mdre)/!;
91         bless {
92                 spamcheck => $spamcheck,
93                 mdmap => \%mdmap,
94                 mdir => \@mdir,
95                 mdre => $mdre,
96                 config => $config,
97                 importers => {},
98                 opendirs => {}, # dirname => dirhandle (in progress scans)
99         }, $class;
100 }
101
102 sub _done_for_now {
103         my ($self) = @_;
104         my $importers = $self->{importers};
105         foreach my $im (values %$importers) {
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         $self->{config}->each_inbox(sub {
129                 my ($ibx) = @_;
130                 eval {
131                         my $im = _importer_for($self, $ibx);
132                         $im->remove($mime, 'spam');
133                         if (my $scrub = $ibx->filter($im)) {
134                                 my $scrubbed = $scrub->scrub($mime, 1);
135                                 $scrubbed or return;
136                                 $scrubbed == REJECT() 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 sub _try_path {
148         my ($self, $path) = @_;
149         return unless PublicInbox::InboxWritable::is_maildir_path($path);
150         if ($path !~ $self->{mdre}) {
151                 warn "unrecognized path: $path\n";
152                 return;
153         }
154         my $inboxes = $self->{mdmap}->{$1};
155         unless ($inboxes) {
156                 warn "unmappable dir: $1\n";
157                 return;
158         }
159         if (!ref($inboxes) && $inboxes eq 'watchspam') {
160                 return _remove_spam($self, $path);
161         }
162
163         my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
164         local $SIG{__WARN__} = sub {
165                 $warn_cb->("path: $path\n");
166                 $warn_cb->(@_);
167         };
168         foreach my $ibx (@$inboxes) {
169                 my $mime = _path_to_mime($path) or next;
170                 my $im = _importer_for($self, $ibx);
171
172                 # any header match means it's eligible for the inbox:
173                 if (my $watch_hdrs = $ibx->{-watchheaders}) {
174                         my $ok;
175                         my $hdr = $mime->header_obj;
176                         for my $wh (@$watch_hdrs) {
177                                 my $v = $hdr->header_raw($wh->[0]);
178                                 next unless defined($v) && $v =~ $wh->[1];
179                                 $ok = 1;
180                                 last;
181                         }
182                         next unless $ok;
183                 }
184
185                 if (my $scrub = $ibx->filter($im)) {
186                         my $ret = $scrub->scrub($mime) or next;
187                         $ret == REJECT() and next;
188                         $mime = $ret;
189                 }
190                 $im->add($mime, $self->{spamcheck});
191         }
192 }
193
194 sub quit { trigger_scan($_[0], 'quit') }
195
196 sub watch {
197         my ($self) = @_;
198         my $scan = File::Temp->newdir("public-inbox-watch.$$.scan.XXXXXX",
199                                         TMPDIR => 1);
200         my $scandir = $self->{scandir} = $scan->dirname;
201         my $re = qr!\A$scandir/!;
202         my $cb = sub { _try_fsn_paths($self, $re, \@_) };
203
204         # lazy load here, we may support watching via IMAP IDLE
205         # in the future...
206         require Filesys::Notify::Simple;
207         my $fsn = Filesys::Notify::Simple->new([@{$self->{mdir}}, $scandir]);
208         $fsn->wait($cb) until $self->{quit};
209 }
210
211 sub trigger_scan {
212         my ($self, $base) = @_;
213         my $dir = $self->{scandir} or return;
214         open my $fh, '>', "$dir/$base" or die "open $dir/$base failed: $!\n";
215         close $fh or die "close $dir/$base failed: $!\n";
216 }
217
218 sub scan {
219         my ($self, $path) = @_;
220         if ($path =~ /quit\z/) {
221                 %{$self->{opendirs}} = ();
222                 _done_for_now($self);
223                 delete $self->{scandir};
224                 $self->{quit} = 1;
225                 return;
226         }
227         # else: $path =~ /(cont|full)\z/
228         return if $self->{quit};
229         my $max = 10;
230         my $opendirs = $self->{opendirs};
231         my @dirnames = keys %$opendirs;
232         foreach my $dir (@dirnames) {
233                 my $dh = delete $opendirs->{$dir};
234                 my $n = $max;
235                 while (my $fn = readdir($dh)) {
236                         _try_path($self, "$dir/$fn");
237                         last if --$n < 0;
238                 }
239                 $opendirs->{$dir} = $dh if $n < 0;
240         }
241         if ($path =~ /full\z/) {
242                 foreach my $dir (@{$self->{mdir}}) {
243                         next if $opendirs->{$dir}; # already in progress
244                         my $ok = opendir(my $dh, $dir);
245                         unless ($ok) {
246                                 warn "failed to open $dir: $!\n";
247                                 next;
248                         }
249                         my $n = $max;
250                         while (my $fn = readdir($dh)) {
251                                 _try_path($self, "$dir/$fn");
252                                 last if --$n < 0;
253                         }
254                         $opendirs->{$dir} = $dh if $n < 0;
255                 }
256         }
257         _done_for_now($self);
258         # do we have more work to do?
259         trigger_scan($self, 'cont') if keys %$opendirs;
260 }
261
262 sub _path_to_mime {
263         my ($path) = @_;
264         if (open my $fh, '<', $path) {
265                 local $/;
266                 my $str = <$fh>;
267                 $str or return;
268                 return PublicInbox::MIME->new(\$str);
269         } elsif ($!{ENOENT}) {
270                 return;
271         } else {
272                 warn "failed to open $path: $!\n";
273                 return;
274         }
275 }
276
277 sub _importer_for {
278         my ($self, $ibx) = @_;
279         my $importers = $self->{importers};
280         my $im = $importers->{"$ibx"} ||= $ibx->importer(0);
281         if (scalar(keys(%$importers)) > 2) {
282                 delete $importers->{"$ibx"};
283                 _done_for_now($self);
284         }
285
286         $importers->{"$ibx"} = $im;
287 }
288
289 sub _spamcheck_cb {
290         my ($sc) = @_;
291         sub {
292                 my ($mime) = @_;
293                 my $tmp = '';
294                 if ($sc->spamcheck($mime, \$tmp)) {
295                         return PublicInbox::MIME->new(\$tmp);
296                 }
297                 warn $mime->header('Message-ID')." failed spam check\n";
298                 undef;
299         }
300 }
301
302 sub is_maildir {
303         $_[0] =~ s!\Amaildir:!! or return;
304         $_[0] =~ tr!/!/!s;
305         $_[0] =~ s!/\z!!;
306         $_[0];
307 }
308
309 1;