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