]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/WatchMaildir.pm
watchmaildir: match List-ID case-insensitively
[public-inbox.git] / lib / PublicInbox / WatchMaildir.pm
1 # Copyright (C) 2016-2020 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::InboxWritable;
11 use File::Temp 0.19 (); # 0.19 for ->newdir
12 use PublicInbox::Filter::Base qw(REJECT);
13 use PublicInbox::Spamcheck;
14 *mime_from_path = \&PublicInbox::InboxWritable::mime_from_path;
15
16 sub new {
17         my ($class, $config) = @_;
18         my (%mdmap, @mdir, $spamc);
19         my %uniq;
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                 defined(my $dirs = $config->{$k}) or next;
27                 $dirs = [ $dirs ] if !ref($dirs);
28                 for my $dir (@$dirs) {
29                         if (is_maildir($dir)) {
30                                 # skip "new", no MUA has seen it, yet.
31                                 my $cur = "$dir/cur";
32                                 my $old = $mdmap{$cur};
33                                 if (ref($old)) {
34                                         foreach my $ibx (@$old) {
35                                                 warn <<"";
36 "$cur already watched for `$ibx->{name}'
37
38                                         }
39                                         die;
40                                 }
41                                 push @mdir, $cur;
42                                 $uniq{$cur}++;
43                                 $mdmap{$cur} = 'watchspam';
44                         } else {
45                                 warn "unsupported $k=$dir\n";
46                         }
47                 }
48         }
49
50         my $k = 'publicinboxwatch.spamcheck';
51         my $default = undef;
52         my $spamcheck = PublicInbox::Spamcheck::get($config, $k, $default);
53         $spamcheck = _spamcheck_cb($spamcheck) if $spamcheck;
54
55         $config->each_inbox(sub {
56                 # need to make all inboxes writable for spam removal:
57                 my $ibx = $_[0] = PublicInbox::InboxWritable->new($_[0]);
58
59                 my $watch = $ibx->{watch} or return;
60                 if (is_maildir($watch)) {
61                         my $watch_hdrs = [];
62                         if (my $whs = $ibx->{watchheader}) {
63                                 for (@$whs) {
64                                         my ($k, $v) = split(/:/, $_, 2);
65                                         # XXX should this be case-insensitive?
66                                         # Or, mutt-style, case-sensitive iff
67                                         # a capital letter exists?
68                                         push @$watch_hdrs, [ $k, qr/\Q$v\E/ ];
69                                 }
70                         }
71                         if (my $list_ids = $ibx->{listid}) {
72                                 for (@$list_ids) {
73                                         # RFC2919 section 6 stipulates
74                                         # "case insensitive equality"
75                                         my $re = qr/<[ \t]*\Q$_\E[ \t]*>/i;
76                                         push @$watch_hdrs, ['List-Id', $re ];
77                                 }
78                         }
79                         if (scalar @$watch_hdrs) {
80                                 $ibx->{-watchheaders} = $watch_hdrs;
81                         }
82                         my $new = "$watch/new";
83                         my $cur = "$watch/cur";
84                         push @mdir, $new unless $uniq{$new}++;
85                         push @mdir, $cur unless $uniq{$cur}++;
86
87                         push @{$mdmap{$new} ||= []}, $ibx;
88                         push @{$mdmap{$cur} ||= []}, $ibx;
89                 } else {
90                         warn "watch unsupported: $k=$watch\n";
91                 }
92         });
93         return unless @mdir;
94
95         my $mdre = join('|', map { quotemeta($_) } @mdir);
96         $mdre = qr!\A($mdre)/!;
97         bless {
98                 spamcheck => $spamcheck,
99                 mdmap => \%mdmap,
100                 mdir => \@mdir,
101                 mdre => $mdre,
102                 config => $config,
103                 importers => {},
104                 opendirs => {}, # dirname => dirhandle (in progress scans)
105         }, $class;
106 }
107
108 sub _done_for_now {
109         my ($self) = @_;
110         my $importers = $self->{importers};
111         foreach my $im (values %$importers) {
112                 $im->done;
113         }
114 }
115
116 sub _try_fsn_paths {
117         my ($self, $scan_re, $paths) = @_;
118         foreach (@$paths) {
119                 my $path = $_->{path};
120                 if ($path =~ $scan_re) {
121                         scan($self, $path);
122                 } else {
123                         _try_path($self, $path);
124                 }
125         }
126         _done_for_now($self);
127 }
128
129 sub _remove_spam {
130         my ($self, $path) = @_;
131         # path must be marked as (S)een
132         $path =~ /:2,[A-R]*S[T-Za-z]*\z/ or return;
133         my $mime = mime_from_path($path) or return;
134         $self->{config}->each_inbox(sub {
135                 my ($ibx) = @_;
136                 eval {
137                         my $im = _importer_for($self, $ibx);
138                         $im->remove($mime, 'spam');
139                         if (my $scrub = $ibx->filter($im)) {
140                                 my $scrubbed = $scrub->scrub($mime, 1);
141                                 $scrubbed or return;
142                                 $scrubbed == REJECT() and return;
143                                 $im->remove($scrubbed, 'spam');
144                         }
145                 };
146                 if ($@) {
147                         warn "error removing spam at: ", $path,
148                                 " from ", $ibx->{name}, ': ', $@, "\n";
149                 }
150         })
151 }
152
153 sub _try_path {
154         my ($self, $path) = @_;
155         return unless PublicInbox::InboxWritable::is_maildir_path($path);
156         if ($path !~ $self->{mdre}) {
157                 warn "unrecognized path: $path\n";
158                 return;
159         }
160         my $inboxes = $self->{mdmap}->{$1};
161         unless ($inboxes) {
162                 warn "unmappable dir: $1\n";
163                 return;
164         }
165         if (!ref($inboxes) && $inboxes eq 'watchspam') {
166                 return _remove_spam($self, $path);
167         }
168
169         my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
170         local $SIG{__WARN__} = sub {
171                 $warn_cb->("path: $path\n");
172                 $warn_cb->(@_);
173         };
174         foreach my $ibx (@$inboxes) {
175                 my $mime = mime_from_path($path) or next;
176                 my $im = _importer_for($self, $ibx);
177
178                 # any header match means it's eligible for the inbox:
179                 if (my $watch_hdrs = $ibx->{-watchheaders}) {
180                         my $ok;
181                         my $hdr = $mime->header_obj;
182                         for my $wh (@$watch_hdrs) {
183                                 my @v = $hdr->header_raw($wh->[0]);
184                                 $ok = grep(/$wh->[1]/, @v) and last;
185                         }
186                         next unless $ok;
187                 }
188
189                 if (my $scrub = $ibx->filter($im)) {
190                         my $ret = $scrub->scrub($mime) or next;
191                         $ret == REJECT() and next;
192                         $mime = $ret;
193                 }
194                 $im->add($mime, $self->{spamcheck});
195         }
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         eval { require Filesys::Notify::Simple } or
211                 die "Filesys::Notify::Simple is currently required for $0\n";
212         my $fsn = Filesys::Notify::Simple->new([@{$self->{mdir}}, $scandir]);
213         $fsn->wait($cb) until $self->{quit};
214 }
215
216 sub trigger_scan {
217         my ($self, $base) = @_;
218         my $dir = $self->{scandir} or return;
219         open my $fh, '>', "$dir/$base" or die "open $dir/$base failed: $!\n";
220         close $fh or die "close $dir/$base failed: $!\n";
221 }
222
223 sub scan {
224         my ($self, $path) = @_;
225         if ($path =~ /quit\z/) {
226                 %{$self->{opendirs}} = ();
227                 _done_for_now($self);
228                 delete $self->{scandir};
229                 $self->{quit} = 1;
230                 return;
231         }
232         # else: $path =~ /(cont|full)\z/
233         return if $self->{quit};
234         my $max = 10;
235         my $opendirs = $self->{opendirs};
236         my @dirnames = keys %$opendirs;
237         foreach my $dir (@dirnames) {
238                 my $dh = delete $opendirs->{$dir};
239                 my $n = $max;
240                 while (my $fn = readdir($dh)) {
241                         _try_path($self, "$dir/$fn");
242                         last if --$n < 0;
243                 }
244                 $opendirs->{$dir} = $dh if $n < 0;
245         }
246         if ($path =~ /full\z/) {
247                 foreach my $dir (@{$self->{mdir}}) {
248                         next if $opendirs->{$dir}; # already in progress
249                         my $ok = opendir(my $dh, $dir);
250                         unless ($ok) {
251                                 warn "failed to open $dir: $!\n";
252                                 next;
253                         }
254                         my $n = $max;
255                         while (my $fn = readdir($dh)) {
256                                 _try_path($self, "$dir/$fn");
257                                 last if --$n < 0;
258                         }
259                         $opendirs->{$dir} = $dh if $n < 0;
260                 }
261         }
262         _done_for_now($self);
263         # do we have more work to do?
264         trigger_scan($self, 'cont') if keys %$opendirs;
265 }
266
267 sub _importer_for {
268         my ($self, $ibx) = @_;
269         my $importers = $self->{importers};
270         my $im = $importers->{"$ibx"} ||= $ibx->importer(0);
271         if (scalar(keys(%$importers)) > 2) {
272                 delete $importers->{"$ibx"};
273                 _done_for_now($self);
274         }
275
276         $importers->{"$ibx"} = $im;
277 }
278
279 sub _spamcheck_cb {
280         my ($sc) = @_;
281         sub {
282                 my ($mime) = @_;
283                 my $tmp = '';
284                 if ($sc->spamcheck($mime, \$tmp)) {
285                         return PublicInbox::MIME->new(\$tmp);
286                 }
287                 warn $mime->header('Message-ID')." failed spam check\n";
288                 undef;
289         }
290 }
291
292 sub is_maildir {
293         $_[0] =~ s!\Amaildir:!! or return;
294         $_[0] =~ tr!/!/!s;
295         $_[0] =~ s!/\z!!;
296         $_[0];
297 }
298
299 1;