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