]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/WatchMaildir.pm
watchmaildir: allow arguments for filters
[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
17 sub new {
18         my ($class, $config) = @_;
19         my (%mdmap, @mdir, $spamc);
20
21         # "publicinboxwatch" is the documented namespace
22         # "publicinboxlearn" is legacy but may be supported
23         # indefinitely...
24         foreach my $pfx (qw(publicinboxwatch publicinboxlearn)) {
25                 my $k = "$pfx.watchspam";
26                 if (my $spamdir = $config->{$k}) {
27                         if ($spamdir =~ s/\Amaildir://) {
28                                 $spamdir =~ s!/+\z!!;
29                                 # skip "new", no MUA has seen it, yet.
30                                 my $cur = "$spamdir/cur";
31                                 push @mdir, $cur;
32                                 $mdmap{$cur} = 'watchspam';
33                         } else {
34                                 warn "unsupported $k=$spamdir\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                 mdmap => \%mdmap,
81                 mdir => \@mdir,
82                 mdre => $mdre,
83                 config => $config,
84                 importers => {},
85         }, $class;
86 }
87
88 sub _done_for_now {
89         $_->done foreach values %{$_[0]->{importers}};
90 }
91
92 sub _try_fsn_paths {
93         my ($self, $paths) = @_;
94         _try_path($self, $_->{path}) foreach @$paths;
95         _done_for_now($self);
96 }
97
98 sub _remove_spam {
99         my ($self, $path) = @_;
100         $path =~ /:2,[A-R]*S[T-Z]*\z/i or return;
101         my $mime = _path_to_mime($path) or return;
102         _force_mid($mime);
103         $self->{config}->each_inbox(sub {
104                 my ($ibx) = @_;
105                 eval {
106                         my $im = _importer_for($self, $ibx);
107                         $im->remove($mime);
108                         if (my $scrub = _scrubber_for($ibx)) {
109                                 my $scrubbed = $scrub->scrub($mime) or return;
110                                 $im->remove($scrubbed);
111                         }
112                 };
113                 warn "error removing spam at $path from $ibx->{name}\n" if $@;
114         })
115 }
116
117 # used to hash the relevant portions of a message when there are conflicts
118 sub _hash_mime2 {
119         my ($mime) = @_;
120         require Digest::SHA;
121         my $dig = Digest::SHA->new('SHA-1');
122         $dig->add($mime->header_obj->header_raw('Subject'));
123         $dig->add($mime->body_raw);
124         $dig->hexdigest;
125 }
126
127 sub _force_mid {
128         my ($mime) = @_;
129         # probably a bad idea, but we inject a Message-Id if
130         # one is missing, here..
131         my $mid = $mime->header_obj->header_raw('Message-Id');
132         if (!defined $mid || $mid =~ /\A\s*\z/) {
133                 $mid = '<' . _hash_mime2($mime) . '@generated>';
134                 $mime->header_set('Message-Id', $mid);
135         }
136 }
137
138 sub _try_path {
139         my ($self, $path) = @_;
140         my @p = split(m!/+!, $path);
141         return if $p[-1] !~ /\A[a-zA-Z0-9][\w:,=\.]+\z/;
142         if ($p[-1] =~ /:2,([A-Z]+)\z/i) {
143                 my $flags = $1;
144                 return if $flags =~ /[DT]/; # no [D]rafts or [T]rashed mail
145         }
146         return unless -f $path;
147         if ($path !~ $self->{mdre}) {
148                 warn "unrecognized path: $path\n";
149                 return;
150         }
151         my $inbox = $self->{mdmap}->{$1};
152         unless ($inbox) {
153                 warn "unmappable dir: $1\n";
154                 return;
155         }
156         if (!ref($inbox) && $inbox eq 'watchspam') {
157                 return _remove_spam($self, $path);
158         }
159         my $im = _importer_for($self, $inbox);
160         my $mime = _path_to_mime($path) or return;
161         $mime->header_set($_) foreach @PublicInbox::MDA::BAD_HEADERS;
162         my $wm = $inbox->{-watchheader};
163         if ($wm) {
164                 my $v = $mime->header_obj->header_raw($wm->[0]);
165                 return unless ($v && $v =~ $wm->[1]);
166         }
167         if (my $scrub = _scrubber_for($inbox)) {
168                 $mime = $scrub->scrub($mime) or return;
169         }
170
171         _force_mid($mime);
172         $im->add($mime, $self->{spamcheck});
173 }
174
175 sub watch {
176         my ($self) = @_;
177         my $cb = sub { _try_fsn_paths($self, \@_) };
178         my $mdir = $self->{mdir};
179
180         # lazy load here, we may support watching via IMAP IDLE
181         # in the future...
182         require Filesys::Notify::Simple;
183         my $watcher = Filesys::Notify::Simple->new($mdir);
184         $watcher->wait($cb) while (1);
185 }
186
187 sub scan {
188         my ($self) = @_;
189         my $mdir = $self->{mdir};
190         foreach my $dir (@$mdir) {
191                 my $ok = opendir(my $dh, $dir);
192                 unless ($ok) {
193                         warn "failed to open $dir: $!\n";
194                         next;
195                 }
196                 while (my $fn = readdir($dh)) {
197                         _try_path($self, "$dir/$fn");
198                 }
199                 closedir $dh;
200         }
201         _done_for_now($self);
202 }
203
204 sub _path_to_mime {
205         my ($path) = @_;
206         if (open my $fh, '<', $path) {
207                 local $/;
208                 my $str = <$fh>;
209                 $str or return;
210                 return PublicInbox::MIME->new(\$str);
211         } elsif ($!{ENOENT}) {
212                 return;
213         } else {
214                 warn "failed to open $path: $!\n";
215                 return;
216         }
217 }
218
219 sub _importer_for {
220         my ($self, $inbox) = @_;
221         my $im = $inbox->{-import} ||= eval {
222                 my $git = $inbox->git;
223                 my $name = $inbox->{name};
224                 my $addr = $inbox->{-primary_address};
225                 PublicInbox::Import->new($git, $name, $addr, $inbox);
226         };
227
228         my $importers = $self->{importers};
229         if (scalar(keys(%$importers)) > 2) {
230                 delete $importers->{"$im"};
231                 _done_for_now($self);
232         }
233
234         $importers->{"$im"} = $im;
235 }
236
237 sub _scrubber_for {
238         my ($inbox) = @_;
239         my $f = $inbox->{filter};
240         if ($f && $f =~ /::/) {
241                 my @args;
242                 # basic line splitting, only
243                 # Perhaps we can have proper quote splitting one day...
244                 ($f, @args) = split(/\s+/, $f) if $f =~ /\s+/;
245
246                 eval "require $f";
247                 if ($@) {
248                         warn $@;
249                 } else {
250                         # e.g: PublicInbox::Filter::Vger->new(@args)
251                         return $f->new(@args);
252                 }
253         }
254         undef;
255 }
256
257 sub _spamcheck_cb {
258         my ($sc) = @_;
259         sub {
260                 my ($mime) = @_;
261                 my $tmp = '';
262                 if ($sc->spamcheck($mime, \$tmp)) {
263                         return PublicInbox::MIME->new(\$tmp);
264                 }
265                 warn $mime->header('Message-ID')." failed spam check\n";
266                 undef;
267         }
268 }
269
270 1;