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