]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/WatchMaildir.pm
treewide: run update-copyrights from gnulib for 2019
[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 *maildir_path_load = *PublicInbox::InboxWritable::maildir_path_load;
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 $wh = $ibx->{watchheader}) {
63                                 my ($k, $v) = split(/:/, $wh, 2);
64                                 push @$watch_hdrs, [ $k, qr/\Q$v\E/ ];
65                         }
66                         if (my $list_ids = $ibx->{listid}) {
67                                 for (@$list_ids) {
68                                         my $re = qr/<[ \t]*\Q$_\E[ \t]*>/;
69                                         push @$watch_hdrs, ['List-Id', $re ];
70                                 }
71                         }
72                         if (scalar @$watch_hdrs) {
73                                 $ibx->{-watchheaders} = $watch_hdrs;
74                         }
75                         my $new = "$watch/new";
76                         my $cur = "$watch/cur";
77                         push @mdir, $new unless $uniq{$new}++;
78                         push @mdir, $cur unless $uniq{$cur}++;
79
80                         push @{$mdmap{$new} ||= []}, $ibx;
81                         push @{$mdmap{$cur} ||= []}, $ibx;
82                 } else {
83                         warn "watch unsupported: $k=$watch\n";
84                 }
85         });
86         return unless @mdir;
87
88         my $mdre = join('|', map { quotemeta($_) } @mdir);
89         $mdre = qr!\A($mdre)/!;
90         bless {
91                 spamcheck => $spamcheck,
92                 mdmap => \%mdmap,
93                 mdir => \@mdir,
94                 mdre => $mdre,
95                 config => $config,
96                 importers => {},
97                 opendirs => {}, # dirname => dirhandle (in progress scans)
98         }, $class;
99 }
100
101 sub _done_for_now {
102         my ($self) = @_;
103         my $importers = $self->{importers};
104         foreach my $im (values %$importers) {
105                 $im->done;
106         }
107 }
108
109 sub _try_fsn_paths {
110         my ($self, $scan_re, $paths) = @_;
111         foreach (@$paths) {
112                 my $path = $_->{path};
113                 if ($path =~ $scan_re) {
114                         scan($self, $path);
115                 } else {
116                         _try_path($self, $path);
117                 }
118         }
119         _done_for_now($self);
120 }
121
122 sub _remove_spam {
123         my ($self, $path) = @_;
124         # path must be marked as (S)een
125         $path =~ /:2,[A-R]*S[T-Za-z]*\z/ or return;
126         my $mime = maildir_path_load($path) or return;
127         $self->{config}->each_inbox(sub {
128                 my ($ibx) = @_;
129                 eval {
130                         my $im = _importer_for($self, $ibx);
131                         $im->remove($mime, 'spam');
132                         if (my $scrub = $ibx->filter($im)) {
133                                 my $scrubbed = $scrub->scrub($mime, 1);
134                                 $scrubbed or return;
135                                 $scrubbed == REJECT() and return;
136                                 $im->remove($scrubbed, 'spam');
137                         }
138                 };
139                 if ($@) {
140                         warn "error removing spam at: ", $path,
141                                 " from ", $ibx->{name}, ': ', $@, "\n";
142                 }
143         })
144 }
145
146 sub _try_path {
147         my ($self, $path) = @_;
148         return unless PublicInbox::InboxWritable::is_maildir_path($path);
149         if ($path !~ $self->{mdre}) {
150                 warn "unrecognized path: $path\n";
151                 return;
152         }
153         my $inboxes = $self->{mdmap}->{$1};
154         unless ($inboxes) {
155                 warn "unmappable dir: $1\n";
156                 return;
157         }
158         if (!ref($inboxes) && $inboxes eq 'watchspam') {
159                 return _remove_spam($self, $path);
160         }
161
162         my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
163         local $SIG{__WARN__} = sub {
164                 $warn_cb->("path: $path\n");
165                 $warn_cb->(@_);
166         };
167         foreach my $ibx (@$inboxes) {
168                 my $mime = maildir_path_load($path) or next;
169                 my $im = _importer_for($self, $ibx);
170
171                 # any header match means it's eligible for the inbox:
172                 if (my $watch_hdrs = $ibx->{-watchheaders}) {
173                         my $ok;
174                         my $hdr = $mime->header_obj;
175                         for my $wh (@$watch_hdrs) {
176                                 my $v = $hdr->header_raw($wh->[0]);
177                                 next unless defined($v) && $v =~ $wh->[1];
178                                 $ok = 1;
179                                 last;
180                         }
181                         next unless $ok;
182                 }
183
184                 if (my $scrub = $ibx->filter($im)) {
185                         my $ret = $scrub->scrub($mime) or next;
186                         $ret == REJECT() and next;
187                         $mime = $ret;
188                 }
189                 $im->add($mime, $self->{spamcheck});
190         }
191 }
192
193 sub quit { trigger_scan($_[0], 'quit') }
194
195 sub watch {
196         my ($self) = @_;
197         my $scan = File::Temp->newdir("public-inbox-watch.$$.scan.XXXXXX",
198                                         TMPDIR => 1);
199         my $scandir = $self->{scandir} = $scan->dirname;
200         my $re = qr!\A$scandir/!;
201         my $cb = sub { _try_fsn_paths($self, $re, \@_) };
202
203         # lazy load here, we may support watching via IMAP IDLE
204         # in the future...
205         eval { require Filesys::Notify::Simple } or
206                 die "Filesys::Notify::Simple is currently required for $0\n";
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 _importer_for {
263         my ($self, $ibx) = @_;
264         my $importers = $self->{importers};
265         my $im = $importers->{"$ibx"} ||= $ibx->importer(0);
266         if (scalar(keys(%$importers)) > 2) {
267                 delete $importers->{"$ibx"};
268                 _done_for_now($self);
269         }
270
271         $importers->{"$ibx"} = $im;
272 }
273
274 sub _spamcheck_cb {
275         my ($sc) = @_;
276         sub {
277                 my ($mime) = @_;
278                 my $tmp = '';
279                 if ($sc->spamcheck($mime, \$tmp)) {
280                         return PublicInbox::MIME->new(\$tmp);
281                 }
282                 warn $mime->header('Message-ID')." failed spam check\n";
283                 undef;
284         }
285 }
286
287 sub is_maildir {
288         $_[0] =~ s!\Amaildir:!! or return;
289         $_[0] =~ tr!/!/!s;
290         $_[0] =~ s!/\z!!;
291         $_[0];
292 }
293
294 1;