]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/WatchMaildir.pm
watchmaildir: support multiple watchheader values
[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                                         push @$watch_hdrs, [ $k, qr/\Q$v\E/ ];
66                                 }
67                         }
68                         if (my $list_ids = $ibx->{listid}) {
69                                 for (@$list_ids) {
70                                         my $re = qr/<[ \t]*\Q$_\E[ \t]*>/;
71                                         push @$watch_hdrs, ['List-Id', $re ];
72                                 }
73                         }
74                         if (scalar @$watch_hdrs) {
75                                 $ibx->{-watchheaders} = $watch_hdrs;
76                         }
77                         my $new = "$watch/new";
78                         my $cur = "$watch/cur";
79                         push @mdir, $new unless $uniq{$new}++;
80                         push @mdir, $cur unless $uniq{$cur}++;
81
82                         push @{$mdmap{$new} ||= []}, $ibx;
83                         push @{$mdmap{$cur} ||= []}, $ibx;
84                 } else {
85                         warn "watch unsupported: $k=$watch\n";
86                 }
87         });
88         return unless @mdir;
89
90         my $mdre = join('|', map { quotemeta($_) } @mdir);
91         $mdre = qr!\A($mdre)/!;
92         bless {
93                 spamcheck => $spamcheck,
94                 mdmap => \%mdmap,
95                 mdir => \@mdir,
96                 mdre => $mdre,
97                 config => $config,
98                 importers => {},
99                 opendirs => {}, # dirname => dirhandle (in progress scans)
100         }, $class;
101 }
102
103 sub _done_for_now {
104         my ($self) = @_;
105         my $importers = $self->{importers};
106         foreach my $im (values %$importers) {
107                 $im->done;
108         }
109 }
110
111 sub _try_fsn_paths {
112         my ($self, $scan_re, $paths) = @_;
113         foreach (@$paths) {
114                 my $path = $_->{path};
115                 if ($path =~ $scan_re) {
116                         scan($self, $path);
117                 } else {
118                         _try_path($self, $path);
119                 }
120         }
121         _done_for_now($self);
122 }
123
124 sub _remove_spam {
125         my ($self, $path) = @_;
126         # path must be marked as (S)een
127         $path =~ /:2,[A-R]*S[T-Za-z]*\z/ or return;
128         my $mime = mime_from_path($path) or return;
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 = $ibx->filter($im)) {
135                                 my $scrubbed = $scrub->scrub($mime, 1);
136                                 $scrubbed or return;
137                                 $scrubbed == REJECT() and return;
138                                 $im->remove($scrubbed, 'spam');
139                         }
140                 };
141                 if ($@) {
142                         warn "error removing spam at: ", $path,
143                                 " from ", $ibx->{name}, ': ', $@, "\n";
144                 }
145         })
146 }
147
148 sub _try_path {
149         my ($self, $path) = @_;
150         return unless PublicInbox::InboxWritable::is_maildir_path($path);
151         if ($path !~ $self->{mdre}) {
152                 warn "unrecognized path: $path\n";
153                 return;
154         }
155         my $inboxes = $self->{mdmap}->{$1};
156         unless ($inboxes) {
157                 warn "unmappable dir: $1\n";
158                 return;
159         }
160         if (!ref($inboxes) && $inboxes eq 'watchspam') {
161                 return _remove_spam($self, $path);
162         }
163
164         my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
165         local $SIG{__WARN__} = sub {
166                 $warn_cb->("path: $path\n");
167                 $warn_cb->(@_);
168         };
169         foreach my $ibx (@$inboxes) {
170                 my $mime = mime_from_path($path) or next;
171                 my $im = _importer_for($self, $ibx);
172
173                 # any header match means it's eligible for the inbox:
174                 if (my $watch_hdrs = $ibx->{-watchheaders}) {
175                         my $ok;
176                         my $hdr = $mime->header_obj;
177                         for my $wh (@$watch_hdrs) {
178                                 my $v = $hdr->header_raw($wh->[0]);
179                                 next unless defined($v) && $v =~ $wh->[1];
180                                 $ok = 1;
181                                 last;
182                         }
183                         next unless $ok;
184                 }
185
186                 if (my $scrub = $ibx->filter($im)) {
187                         my $ret = $scrub->scrub($mime) or next;
188                         $ret == REJECT() and next;
189                         $mime = $ret;
190                 }
191                 $im->add($mime, $self->{spamcheck});
192         }
193 }
194
195 sub quit { trigger_scan($_[0], 'quit') }
196
197 sub watch {
198         my ($self) = @_;
199         my $scan = File::Temp->newdir("public-inbox-watch.$$.scan.XXXXXX",
200                                         TMPDIR => 1);
201         my $scandir = $self->{scandir} = $scan->dirname;
202         my $re = qr!\A$scandir/!;
203         my $cb = sub { _try_fsn_paths($self, $re, \@_) };
204
205         # lazy load here, we may support watching via IMAP IDLE
206         # in the future...
207         eval { require Filesys::Notify::Simple } or
208                 die "Filesys::Notify::Simple is currently required for $0\n";
209         my $fsn = Filesys::Notify::Simple->new([@{$self->{mdir}}, $scandir]);
210         $fsn->wait($cb) until $self->{quit};
211 }
212
213 sub trigger_scan {
214         my ($self, $base) = @_;
215         my $dir = $self->{scandir} or return;
216         open my $fh, '>', "$dir/$base" or die "open $dir/$base failed: $!\n";
217         close $fh or die "close $dir/$base failed: $!\n";
218 }
219
220 sub scan {
221         my ($self, $path) = @_;
222         if ($path =~ /quit\z/) {
223                 %{$self->{opendirs}} = ();
224                 _done_for_now($self);
225                 delete $self->{scandir};
226                 $self->{quit} = 1;
227                 return;
228         }
229         # else: $path =~ /(cont|full)\z/
230         return if $self->{quit};
231         my $max = 10;
232         my $opendirs = $self->{opendirs};
233         my @dirnames = keys %$opendirs;
234         foreach my $dir (@dirnames) {
235                 my $dh = delete $opendirs->{$dir};
236                 my $n = $max;
237                 while (my $fn = readdir($dh)) {
238                         _try_path($self, "$dir/$fn");
239                         last if --$n < 0;
240                 }
241                 $opendirs->{$dir} = $dh if $n < 0;
242         }
243         if ($path =~ /full\z/) {
244                 foreach my $dir (@{$self->{mdir}}) {
245                         next if $opendirs->{$dir}; # already in progress
246                         my $ok = opendir(my $dh, $dir);
247                         unless ($ok) {
248                                 warn "failed to open $dir: $!\n";
249                                 next;
250                         }
251                         my $n = $max;
252                         while (my $fn = readdir($dh)) {
253                                 _try_path($self, "$dir/$fn");
254                                 last if --$n < 0;
255                         }
256                         $opendirs->{$dir} = $dh if $n < 0;
257                 }
258         }
259         _done_for_now($self);
260         # do we have more work to do?
261         trigger_scan($self, 'cont') if keys %$opendirs;
262 }
263
264 sub _importer_for {
265         my ($self, $ibx) = @_;
266         my $importers = $self->{importers};
267         my $im = $importers->{"$ibx"} ||= $ibx->importer(0);
268         if (scalar(keys(%$importers)) > 2) {
269                 delete $importers->{"$ibx"};
270                 _done_for_now($self);
271         }
272
273         $importers->{"$ibx"} = $im;
274 }
275
276 sub _spamcheck_cb {
277         my ($sc) = @_;
278         sub {
279                 my ($mime) = @_;
280                 my $tmp = '';
281                 if ($sc->spamcheck($mime, \$tmp)) {
282                         return PublicInbox::MIME->new(\$tmp);
283                 }
284                 warn $mime->header('Message-ID')." failed spam check\n";
285                 undef;
286         }
287 }
288
289 sub is_maildir {
290         $_[0] =~ s!\Amaildir:!! or return;
291         $_[0] =~ tr!/!/!s;
292         $_[0] =~ s!/\z!!;
293         $_[0];
294 }
295
296 1;