1 # Copyright (C) 2016 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # ref: https://cr.yp.to/proto/maildir.html
5 # http://wiki2.dovecot.org/MailboxFormat/Maildir
6 package PublicInbox::WatchMaildir;
10 use Email::MIME::ContentType;
11 $Email::MIME::ContentType::STRICT_PARAMS = 0; # user input is imperfect
13 use PublicInbox::Import;
15 use PublicInbox::Spawn qw(spawn);
19 my ($class, $config) = @_;
20 my (%mdmap, @mdir, $spamc, $spamdir);
22 # "publicinboxwatch" is the documented namespace
23 # "publicinboxlearn" is legacy but may be supported
25 foreach my $pfx (qw(publicinboxwatch publicinboxlearn)) {
26 my $k = "$pfx.watchspam";
27 if (my $dir = $config->{$k}) {
28 if ($dir =~ s/\Amaildir://) {
30 # skip "new", no MUA has seen it, yet.
34 $mdmap{$cur} = 'watchspam';
36 warn "unsupported $k=$dir\n";
41 my $k = 'publicinboxwatch.spamcheck';
42 my $spamcheck = $config->{$k};
44 if ($spamcheck eq 'spamc') {
45 $spamcheck = 'PublicInbox::Spamcheck::Spamc';
47 if ($spamcheck =~ /::/) {
48 eval "require $spamcheck";
49 $spamcheck = _spamcheck_cb($spamcheck->new);
51 warn "unsupported $k=$spamcheck\n";
55 foreach $k (keys %$config) {
56 $k =~ /\Apublicinbox\.([^\.]+)\.watch\z/ or next;
58 my $watch = $config->{$k};
59 if ($watch =~ s/\Amaildir://) {
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/ ];
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;
73 warn "watch unsupported: $k=$watch\n";
78 my $mdre = join('|', map { quotemeta($_) } @mdir);
79 $mdre = qr!\A($mdre)/!;
81 spamcheck => $spamcheck,
88 opendirs => {}, # dirname => dirhandle (in progress scans)
94 my $opendirs = $self->{opendirs};
96 # spamdir scanning means every importer remains open
97 my $spamdir = $self->{spamdir};
98 return if defined($spamdir) && $opendirs->{$spamdir};
100 foreach my $im (values %{$self->{importers}}) {
101 # not done if we're scanning
102 next if $opendirs->{$im->{git}->{git_dir}};
108 my ($self, $scan_re, $paths) = @_;
110 my $path = $_->{path};
111 if ($path =~ $scan_re) {
114 _try_path($self, $path);
117 _done_for_now($self);
121 my ($self, $path) = @_;
122 # path must be marked as (S)een
123 $path =~ /:2,[A-R]*S[T-Za-z]*\z/ or return;
124 my $mime = _path_to_mime($path) or return;
126 $self->{config}->each_inbox(sub {
129 my $im = _importer_for($self, $ibx);
131 if (my $scrub = _scrubber_for($ibx)) {
132 my $scrubbed = $scrub->scrub($mime) or return;
133 $scrubbed == 100 and return;
134 $im->remove($scrubbed);
138 warn "error removing spam at: ", $path,
139 " from ", $ibx->{name}, ': ', $@, "\n";
144 # used to hash the relevant portions of a message when there are conflicts
148 my $dig = Digest::SHA->new('SHA-1');
149 $dig->add($mime->header_obj->header_raw('Subject'));
150 $dig->add($mime->body_raw);
156 # probably a bad idea, but we inject a Message-Id if
157 # one is missing, here..
158 my $mid = $mime->header_obj->header_raw('Message-Id');
159 if (!defined $mid || $mid =~ /\A\s*\z/) {
160 $mid = '<' . _hash_mime2($mime) . '@generated>';
161 $mime->header_set('Message-Id', $mid);
166 my ($self, $path) = @_;
167 my @p = split(m!/+!, $path);
168 return if $p[-1] !~ /\A[a-zA-Z0-9][\w:,=\.]+\z/;
169 if ($p[-1] =~ /:2,([A-Z]+)\z/i) {
171 return if $flags =~ /[DT]/; # no [D]rafts or [T]rashed mail
173 return unless -f $path;
174 if ($path !~ $self->{mdre}) {
175 warn "unrecognized path: $path\n";
178 my $inbox = $self->{mdmap}->{$1};
180 warn "unmappable dir: $1\n";
183 if (!ref($inbox) && $inbox eq 'watchspam') {
184 return _remove_spam($self, $path);
186 my $im = _importer_for($self, $inbox);
187 my $mime = _path_to_mime($path) or return;
188 $mime->header_set($_) foreach @PublicInbox::MDA::BAD_HEADERS;
189 my $wm = $inbox->{-watchheader};
191 my $v = $mime->header_obj->header_raw($wm->[0]);
192 return unless ($v && $v =~ $wm->[1]);
194 if (my $scrub = _scrubber_for($inbox)) {
195 my $ret = $scrub->scrub($mime) or return;
196 $ret == 100 and return;
201 $im->add($mime, $self->{spamcheck});
204 sub quit { $_[0]->{quit} = 1 }
208 my $scan = File::Temp->newdir("public-inbox-watch.$$.scan.XXXXXX",
210 my $scandir = $self->{scandir} = $scan->dirname;
211 my $re = qr!\A$scandir/!;
212 my $cb = sub { _try_fsn_paths($self, $re, \@_) };
214 # lazy load here, we may support watching via IMAP IDLE
216 require Filesys::Notify::Simple;
217 my $fsn = Filesys::Notify::Simple->new([@{$self->{mdir}}, $scandir]);
218 $fsn->wait($cb) until ($self->{quit});
222 my ($self, $base) = @_;
223 my $dir = $self->{scandir} or die "not watch-ing, yet\n";
224 open my $fh, '>', "$dir/$base" or die "open $dir/$base failed: $!\n";
225 close $fh or die "close $dir/$base failed: $!\n";
229 my ($self, $path) = @_;
231 my $opendirs = $self->{opendirs};
232 my @dirnames = keys %$opendirs;
233 foreach my $dir (@dirnames) {
234 my $dh = delete $opendirs->{$dir};
236 while (my $fn = readdir($dh)) {
237 _try_path($self, "$dir/$fn");
240 $opendirs->{$dir} = $dh if $n < 0;
242 if ($path =~ /full\z/) {
243 foreach my $dir (@{$self->{mdir}}) {
244 next if $opendirs->{$dir}; # already in progress
245 my $ok = opendir(my $dh, $dir);
247 warn "failed to open $dir: $!\n";
251 while (my $fn = readdir($dh)) {
252 _try_path($self, "$dir/$fn");
255 $opendirs->{$dir} = $dh if $n < 0;
258 if (keys %$opendirs) { # do we have more work to do?
259 trigger_scan($self, 'cont');
261 _done_for_now($self);
267 if (open my $fh, '<', $path) {
271 return PublicInbox::MIME->new(\$str);
272 } elsif ($!{ENOENT}) {
275 warn "failed to open $path: $!\n";
281 my ($self, $inbox) = @_;
282 my $im = $inbox->{-import} ||= eval {
283 my $git = $inbox->git;
284 my $name = $inbox->{name};
285 my $addr = $inbox->{-primary_address};
286 PublicInbox::Import->new($git, $name, $addr, $inbox);
289 my $importers = $self->{importers};
290 if (scalar(keys(%$importers)) > 2) {
291 delete $importers->{"$im"};
292 _done_for_now($self);
295 $importers->{"$im"} = $im;
300 my $f = $inbox->{filter};
301 if ($f && $f =~ /::/) {
302 my @args = (-inbox => $inbox);
303 # basic line splitting, only
304 # Perhaps we can have proper quote splitting one day...
305 ($f, @args) = split(/\s+/, $f) if $f =~ /\s+/;
311 # e.g: PublicInbox::Filter::Vger->new(@args)
312 return $f->new(@args);
323 if ($sc->spamcheck($mime, \$tmp)) {
324 return PublicInbox::MIME->new(\$tmp);
326 warn $mime->header('Message-ID')." failed spam check\n";