]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/WatchMaildir.pm
watch: commit changes to fast-import sooner
[public-inbox.git] / lib / PublicInbox / WatchMaildir.pm
1 # Copyright (C) 2016 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 Email::MIME::ContentType;
11 $Email::MIME::ContentType::STRICT_PARAMS = 0; # user input is imperfect
12 use PublicInbox::Git;
13 use PublicInbox::Import;
14 use PublicInbox::MDA;
15 use PublicInbox::Spawn qw(spawn);
16 use File::Temp qw//;
17
18 sub new {
19         my ($class, $config) = @_;
20         my (%mdmap, @mdir, $spamc, $spamdir);
21
22         # "publicinboxwatch" is the documented namespace
23         # "publicinboxlearn" is legacy but may be supported
24         # indefinitely...
25         foreach my $pfx (qw(publicinboxwatch publicinboxlearn)) {
26                 my $k = "$pfx.watchspam";
27                 if (my $dir = $config->{$k}) {
28                         if ($dir =~ s/\Amaildir://) {
29                                 $dir =~ s!/+\z!!;
30                                 # skip "new", no MUA has seen it, yet.
31                                 my $cur = "$dir/cur";
32                                 $spamdir = $cur;
33                                 push @mdir, $cur;
34                                 $mdmap{$cur} = 'watchspam';
35                         } else {
36                                 warn "unsupported $k=$dir\n";
37                         }
38                 }
39         }
40
41         my $k = 'publicinboxwatch.spamcheck';
42         my $spamcheck = $config->{$k};
43         if ($spamcheck) {
44                 if ($spamcheck eq 'spamc') {
45                         $spamcheck = 'PublicInbox::Spamcheck::Spamc';
46                 }
47                 if ($spamcheck =~ /::/) {
48                         eval "require $spamcheck";
49                         $spamcheck = _spamcheck_cb($spamcheck->new);
50                 } else {
51                         warn "unsupported $k=$spamcheck\n";
52                         $spamcheck = undef;
53                 }
54         }
55         foreach $k (keys %$config) {
56                 $k =~ /\Apublicinbox\.([^\.]+)\.watch\z/ or next;
57                 my $name = $1;
58                 my $watch = $config->{$k};
59                 if ($watch =~ s/\Amaildir://) {
60                         $watch =~ s!/+\z!!;
61                         my $inbox = $config->lookup_name($name);
62                         if (my $wm = $inbox->{watchheader}) {
63                                 my ($k, $v) = split(/:/, $wm, 2);
64                                 $inbox->{-watchheader} = [ $k, qr/\Q$v\E/ ];
65                         }
66                         my $new = "$watch/new";
67                         my $cur = "$watch/cur";
68                         push @mdir, $new, $cur;
69                         die "$new already in use\n" if $mdmap{$new};
70                         die "$cur already in use\n" if $mdmap{$cur};
71                         $mdmap{$new} = $mdmap{$cur} = $inbox;
72                 } else {
73                         warn "watch unsupported: $k=$watch\n";
74                 }
75         }
76         return unless @mdir;
77
78         my $mdre = join('|', map { quotemeta($_) } @mdir);
79         $mdre = qr!\A($mdre)/!;
80         bless {
81                 spamcheck => $spamcheck,
82                 spamdir => $spamdir,
83                 mdmap => \%mdmap,
84                 mdir => \@mdir,
85                 mdre => $mdre,
86                 config => $config,
87                 importers => {},
88                 opendirs => {}, # dirname => dirhandle (in progress scans)
89         }, $class;
90 }
91
92 sub _done_for_now {
93         my ($self) = @_;
94         my $importers = $self->{importers};
95         foreach my $im (values %$importers) {
96                 $im->done if $im->{nchg};
97         }
98
99         my $opendirs = $self->{opendirs};
100
101         # spamdir scanning means every importer remains open
102         my $spamdir = $self->{spamdir};
103         return if defined($spamdir) && $opendirs->{$spamdir};
104
105         foreach my $im (values %$importers) {
106                 # not done if we're scanning
107                 next if $opendirs->{$im->{git}->{git_dir}};
108                 $im->done;
109         }
110 }
111
112 sub _try_fsn_paths {
113         my ($self, $scan_re, $paths) = @_;
114         foreach (@$paths) {
115                 my $path = $_->{path};
116                 if ($path =~ $scan_re) {
117                         scan($self, $path);
118                 } else {
119                         _try_path($self, $path);
120                 }
121         }
122         _done_for_now($self);
123 }
124
125 sub _remove_spam {
126         my ($self, $path) = @_;
127         # path must be marked as (S)een
128         $path =~ /:2,[A-R]*S[T-Za-z]*\z/ or return;
129         my $mime = _path_to_mime($path) or return;
130         _force_mid($mime);
131         $self->{config}->each_inbox(sub {
132                 my ($ibx) = @_;
133                 eval {
134                         my $im = _importer_for($self, $ibx);
135                         $im->remove($mime);
136                         if (my $scrub = _scrubber_for($ibx)) {
137                                 my $scrubbed = $scrub->scrub($mime) or return;
138                                 $scrubbed == 100 and return;
139                                 $im->remove($scrubbed);
140                         }
141                 };
142                 if ($@) {
143                         warn "error removing spam at: ", $path,
144                                 " from ", $ibx->{name}, ': ', $@, "\n";
145                 }
146         })
147 }
148
149 # used to hash the relevant portions of a message when there are conflicts
150 sub _hash_mime2 {
151         my ($mime) = @_;
152         require Digest::SHA;
153         my $dig = Digest::SHA->new('SHA-1');
154         $dig->add($mime->header_obj->header_raw('Subject'));
155         $dig->add($mime->body_raw);
156         $dig->hexdigest;
157 }
158
159 sub _force_mid {
160         my ($mime) = @_;
161         # probably a bad idea, but we inject a Message-Id if
162         # one is missing, here..
163         my $mid = $mime->header_obj->header_raw('Message-Id');
164         if (!defined $mid || $mid =~ /\A\s*\z/) {
165                 $mid = '<' . _hash_mime2($mime) . '@generated>';
166                 $mime->header_set('Message-Id', $mid);
167         }
168 }
169
170 sub _try_path {
171         my ($self, $path) = @_;
172         my @p = split(m!/+!, $path);
173         return if $p[-1] !~ /\A[a-zA-Z0-9][\w:,=\.]+\z/;
174         if ($p[-1] =~ /:2,([A-Z]+)\z/i) {
175                 my $flags = $1;
176                 return if $flags =~ /[DT]/; # no [D]rafts or [T]rashed mail
177         }
178         return unless -f $path;
179         if ($path !~ $self->{mdre}) {
180                 warn "unrecognized path: $path\n";
181                 return;
182         }
183         my $inbox = $self->{mdmap}->{$1};
184         unless ($inbox) {
185                 warn "unmappable dir: $1\n";
186                 return;
187         }
188         if (!ref($inbox) && $inbox eq 'watchspam') {
189                 return _remove_spam($self, $path);
190         }
191         my $im = _importer_for($self, $inbox);
192         my $mime = _path_to_mime($path) or return;
193         $mime->header_set($_) foreach @PublicInbox::MDA::BAD_HEADERS;
194         my $wm = $inbox->{-watchheader};
195         if ($wm) {
196                 my $v = $mime->header_obj->header_raw($wm->[0]);
197                 return unless ($v && $v =~ $wm->[1]);
198         }
199         if (my $scrub = _scrubber_for($inbox)) {
200                 my $ret = $scrub->scrub($mime) or return;
201                 $ret == 100 and return;
202                 $mime = $ret;
203         }
204
205         _force_mid($mime);
206         $im->add($mime, $self->{spamcheck});
207 }
208
209 sub quit { trigger_scan($_[0], 'quit') }
210
211 sub watch {
212         my ($self) = @_;
213         my $scan = File::Temp->newdir("public-inbox-watch.$$.scan.XXXXXX",
214                                         TMPDIR => 1);
215         my $scandir = $self->{scandir} = $scan->dirname;
216         my $re = qr!\A$scandir/!;
217         my $cb = sub { _try_fsn_paths($self, $re, \@_) };
218
219         # lazy load here, we may support watching via IMAP IDLE
220         # in the future...
221         require Filesys::Notify::Simple;
222         my $fsn = Filesys::Notify::Simple->new([@{$self->{mdir}}, $scandir]);
223         $fsn->wait($cb) until $self->{quit};
224 }
225
226 sub trigger_scan {
227         my ($self, $base) = @_;
228         my $dir = $self->{scandir} or die "not watch-ing, yet\n";
229         open my $fh, '>', "$dir/$base" or die "open $dir/$base failed: $!\n";
230         close $fh or die "close $dir/$base failed: $!\n";
231 }
232
233 sub scan {
234         my ($self, $path) = @_;
235         if ($path =~ /quit\z/) {
236                 %{$self->{opendirs}} = ();
237                 _done_for_now($self);
238                 $self->{quit} = 1;
239                 return;
240         }
241         # else: $path =~ /(cont|full)\z/
242         return if $self->{quit};
243         my $max = 10;
244         my $opendirs = $self->{opendirs};
245         my @dirnames = keys %$opendirs;
246         foreach my $dir (@dirnames) {
247                 my $dh = delete $opendirs->{$dir};
248                 my $n = $max;
249                 while (my $fn = readdir($dh)) {
250                         _try_path($self, "$dir/$fn");
251                         last if --$n < 0;
252                 }
253                 $opendirs->{$dir} = $dh if $n < 0;
254         }
255         if ($path =~ /full\z/) {
256                 foreach my $dir (@{$self->{mdir}}) {
257                         next if $opendirs->{$dir}; # already in progress
258                         my $ok = opendir(my $dh, $dir);
259                         unless ($ok) {
260                                 warn "failed to open $dir: $!\n";
261                                 next;
262                         }
263                         my $n = $max;
264                         while (my $fn = readdir($dh)) {
265                                 _try_path($self, "$dir/$fn");
266                                 last if --$n < 0;
267                         }
268                         $opendirs->{$dir} = $dh if $n < 0;
269                 }
270         }
271         _done_for_now($self);
272         # do we have more work to do?
273         trigger_scan($self, 'cont') if keys %$opendirs;
274 }
275
276 sub _path_to_mime {
277         my ($path) = @_;
278         if (open my $fh, '<', $path) {
279                 local $/;
280                 my $str = <$fh>;
281                 $str or return;
282                 return PublicInbox::MIME->new(\$str);
283         } elsif ($!{ENOENT}) {
284                 return;
285         } else {
286                 warn "failed to open $path: $!\n";
287                 return;
288         }
289 }
290
291 sub _importer_for {
292         my ($self, $inbox) = @_;
293         my $im = $inbox->{-import} ||= eval {
294                 my $git = $inbox->git;
295                 my $name = $inbox->{name};
296                 my $addr = $inbox->{-primary_address};
297                 PublicInbox::Import->new($git, $name, $addr, $inbox);
298         };
299
300         my $importers = $self->{importers};
301         if (scalar(keys(%$importers)) > 2) {
302                 delete $importers->{"$im"};
303                 _done_for_now($self);
304         }
305
306         $importers->{"$im"} = $im;
307 }
308
309 sub _scrubber_for {
310         my ($inbox) = @_;
311         my $f = $inbox->{filter};
312         if ($f && $f =~ /::/) {
313                 my @args = (-inbox => $inbox);
314                 # basic line splitting, only
315                 # Perhaps we can have proper quote splitting one day...
316                 ($f, @args) = split(/\s+/, $f) if $f =~ /\s+/;
317
318                 eval "require $f";
319                 if ($@) {
320                         warn $@;
321                 } else {
322                         # e.g: PublicInbox::Filter::Vger->new(@args)
323                         return $f->new(@args);
324                 }
325         }
326         undef;
327 }
328
329 sub _spamcheck_cb {
330         my ($sc) = @_;
331         sub {
332                 my ($mime) = @_;
333                 my $tmp = '';
334                 if ($sc->spamcheck($mime, \$tmp)) {
335                         return PublicInbox::MIME->new(\$tmp);
336                 }
337                 warn $mime->header('Message-ID')." failed spam check\n";
338                 undef;
339         }
340 }
341
342 1;