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