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