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