]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/WatchMaildir.pm
e923178066fcac20f7e4e5a6c331354ee7d5a7da
[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 *maildir_path_load = *PublicInbox::InboxWritable::maildir_path_load;
17
18 sub new {
19         my ($class, $config) = @_;
20         my (%mdmap, @mdir, $spamc);
21         my %uniq;
22
23         # "publicinboxwatch" is the documented namespace
24         # "publicinboxlearn" is legacy but may be supported
25         # indefinitely...
26         foreach my $pfx (qw(publicinboxwatch publicinboxlearn)) {
27                 my $k = "$pfx.watchspam";
28                 defined(my $dirs = $config->{$k}) or next;
29                 $dirs = [ $dirs ] if !ref($dirs);
30                 for my $dir (@$dirs) {
31                         if (is_maildir($dir)) {
32                                 # skip "new", no MUA has seen it, yet.
33                                 my $cur = "$dir/cur";
34                                 my $old = $mdmap{$cur};
35                                 if (ref($old)) {
36                                         foreach my $ibx (@$old) {
37                                                 warn <<"";
38 "$cur already watched for `$ibx->{name}'
39
40                                         }
41                                         die;
42                                 }
43                                 push @mdir, $cur;
44                                 $uniq{$cur}++;
45                                 $mdmap{$cur} = 'watchspam';
46                         } else {
47                                 warn "unsupported $k=$dir\n";
48                         }
49                 }
50         }
51
52         my $k = 'publicinboxwatch.spamcheck';
53         my $default = undef;
54         my $spamcheck = PublicInbox::Spamcheck::get($config, $k, $default);
55         $spamcheck = _spamcheck_cb($spamcheck) if $spamcheck;
56
57         $config->each_inbox(sub {
58                 # need to make all inboxes writable for spam removal:
59                 my $ibx = $_[0] = PublicInbox::InboxWritable->new($_[0]);
60
61                 my $watch = $ibx->{watch} or return;
62                 if (is_maildir($watch)) {
63                         my $watch_hdrs = [];
64                         if (my $wh = $ibx->{watchheader}) {
65                                 my ($k, $v) = split(/:/, $wh, 2);
66                                 push @$watch_hdrs, [ $k, qr/\Q$v\E/ ];
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 = maildir_path_load($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 = maildir_path_load($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         require Filesys::Notify::Simple;
208         my $fsn = Filesys::Notify::Simple->new([@{$self->{mdir}}, $scandir]);
209         $fsn->wait($cb) until $self->{quit};
210 }
211
212 sub trigger_scan {
213         my ($self, $base) = @_;
214         my $dir = $self->{scandir} or return;
215         open my $fh, '>', "$dir/$base" or die "open $dir/$base failed: $!\n";
216         close $fh or die "close $dir/$base failed: $!\n";
217 }
218
219 sub scan {
220         my ($self, $path) = @_;
221         if ($path =~ /quit\z/) {
222                 %{$self->{opendirs}} = ();
223                 _done_for_now($self);
224                 delete $self->{scandir};
225                 $self->{quit} = 1;
226                 return;
227         }
228         # else: $path =~ /(cont|full)\z/
229         return if $self->{quit};
230         my $max = 10;
231         my $opendirs = $self->{opendirs};
232         my @dirnames = keys %$opendirs;
233         foreach my $dir (@dirnames) {
234                 my $dh = delete $opendirs->{$dir};
235                 my $n = $max;
236                 while (my $fn = readdir($dh)) {
237                         _try_path($self, "$dir/$fn");
238                         last if --$n < 0;
239                 }
240                 $opendirs->{$dir} = $dh if $n < 0;
241         }
242         if ($path =~ /full\z/) {
243                 foreach my $dir (@{$self->{mdir}}) {
244                         next if $opendirs->{$dir}; # already in progress
245                         my $ok = opendir(my $dh, $dir);
246                         unless ($ok) {
247                                 warn "failed to open $dir: $!\n";
248                                 next;
249                         }
250                         my $n = $max;
251                         while (my $fn = readdir($dh)) {
252                                 _try_path($self, "$dir/$fn");
253                                 last if --$n < 0;
254                         }
255                         $opendirs->{$dir} = $dh if $n < 0;
256                 }
257         }
258         _done_for_now($self);
259         # do we have more work to do?
260         trigger_scan($self, 'cont') if keys %$opendirs;
261 }
262
263 sub _importer_for {
264         my ($self, $ibx) = @_;
265         my $importers = $self->{importers};
266         my $im = $importers->{"$ibx"} ||= $ibx->importer(0);
267         if (scalar(keys(%$importers)) > 2) {
268                 delete $importers->{"$ibx"};
269                 _done_for_now($self);
270         }
271
272         $importers->{"$ibx"} = $im;
273 }
274
275 sub _spamcheck_cb {
276         my ($sc) = @_;
277         sub {
278                 my ($mime) = @_;
279                 my $tmp = '';
280                 if ($sc->spamcheck($mime, \$tmp)) {
281                         return PublicInbox::MIME->new(\$tmp);
282                 }
283                 warn $mime->header('Message-ID')." failed spam check\n";
284                 undef;
285         }
286 }
287
288 sub is_maildir {
289         $_[0] =~ s!\Amaildir:!! or return;
290         $_[0] =~ tr!/!/!s;
291         $_[0] =~ s!/\z!!;
292         $_[0];
293 }
294
295 1;