1 # Copyright (C) 2016-2020 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 PublicInbox::InboxWritable;
11 use File::Temp 0.19 (); # 0.19 for ->newdir
12 use PublicInbox::Filter::Base qw(REJECT);
13 use PublicInbox::Spamcheck;
14 use PublicInbox::DS qw(now);
15 use POSIX qw(_exit WNOHANG);
16 *mime_from_path = \&PublicInbox::InboxWritable::mime_from_path;
18 sub compile_watchheaders ($) {
21 if (my $whs = $ibx->{watchheader}) {
23 my ($k, $v) = split(/:/, $_, 2);
24 # XXX should this be case-insensitive?
25 # Or, mutt-style, case-sensitive iff
26 # a capital letter exists?
27 push @$watch_hdrs, [ $k, qr/\Q$v\E/ ];
30 if (my $list_ids = $ibx->{listid}) {
32 # RFC2919 section 6 stipulates
33 # "case insensitive equality"
34 my $re = qr/<[ \t]*\Q$_\E[ \t]*>/i;
35 push @$watch_hdrs, ['List-Id', $re ];
38 $ibx->{-watchheaders} = $watch_hdrs if scalar @$watch_hdrs;
42 my ($class, $config) = @_;
43 my (%mdmap, @mdir, $spamc);
44 my %uniq; # directory => count
45 my %imap; # url => [inbox objects] or 'watchspam'
47 # "publicinboxwatch" is the documented namespace
48 # "publicinboxlearn" is legacy but may be supported
50 foreach my $pfx (qw(publicinboxwatch publicinboxlearn)) {
51 my $k = "$pfx.watchspam";
52 defined(my $dirs = $config->{$k}) or next;
53 $dirs = [ $dirs ] if !ref($dirs);
54 for my $dir (@$dirs) {
55 if (is_maildir($dir)) {
56 # skip "new", no MUA has seen it, yet.
60 $mdmap{$cur} = 'watchspam';
61 } elsif (my $url = imap_url($dir)) {
62 $imap{$url} = 'watchspam';
64 warn "unsupported $k=$dir\n";
69 my $k = 'publicinboxwatch.spamcheck';
71 my $spamcheck = PublicInbox::Spamcheck::get($config, $k, $default);
72 $spamcheck = _spamcheck_cb($spamcheck) if $spamcheck;
74 $config->each_inbox(sub {
75 # need to make all inboxes writable for spam removal:
76 my $ibx = $_[0] = PublicInbox::InboxWritable->new($_[0]);
78 my $watch = $ibx->{watch} or return;
79 if (is_maildir($watch)) {
80 compile_watchheaders($ibx);
81 my ($new, $cur) = ("$watch/new", "$watch/cur");
82 return if is_watchspam($cur, $mdmap{$cur}, $ibx);
83 push @mdir, $new unless $uniq{$new}++;
84 push @mdir, $cur unless $uniq{$cur}++;
85 push @{$mdmap{$new} ||= []}, $ibx;
86 push @{$mdmap{$cur} ||= []}, $ibx;
87 } elsif (my $url = imap_url($watch)) {
88 return if is_watchspam($url, $imap{$url}, $ibx);
89 compile_watchheaders($ibx);
90 push @{$imap{$url} ||= []}, $ibx;
92 warn "watch unsupported: $k=$watch\n";
95 return unless scalar(@mdir) || scalar(keys %imap);
99 $mdre = join('|', map { quotemeta($_) } @mdir);
100 $mdre = qr!\A($mdre)/!;
103 spamcheck => $spamcheck,
108 imap => scalar keys %imap ? \%imap : undef,
110 opendirs => {}, # dirname => dirhandle (in progress scans)
116 my $importers = $self->{importers};
117 foreach my $im (values %$importers) {
122 sub remove_eml_i { # each_inbox callback
123 my ($ibx, $arg) = @_;
124 my ($self, $eml, $loc) = @$arg;
126 my $im = _importer_for($self, $ibx);
127 $im->remove($eml, 'spam');
128 if (my $scrub = $ibx->filter($im)) {
129 my $scrubbed = $scrub->scrub($eml, 1);
131 $scrubbed == REJECT() and return;
132 $im->remove($scrubbed, 'spam');
135 warn "error removing spam at: $loc from $ibx->{name}: $@\n" if $@;
139 my ($self, $path) = @_;
140 # path must be marked as (S)een
141 $path =~ /:2,[A-R]*S[T-Za-z]*\z/ or return;
142 my $eml = mime_from_path($path) or return;
143 $self->{config}->each_inbox(\&remove_eml_i, [ $self, $eml, $path ]);
146 sub import_eml ($$$) {
147 my ($self, $ibx, $eml) = @_;
148 my $im = _importer_for($self, $ibx);
150 # any header match means it's eligible for the inbox:
151 if (my $watch_hdrs = $ibx->{-watchheaders}) {
153 my $hdr = $eml->header_obj;
154 for my $wh (@$watch_hdrs) {
155 my @v = $hdr->header_raw($wh->[0]);
156 $ok = grep(/$wh->[1]/, @v) and last;
161 if (my $scrub = $ibx->filter($im)) {
162 my $ret = $scrub->scrub($eml) or return;
163 $ret == REJECT() and return;
166 $im->add($eml, $self->{spamcheck});
170 my ($self, $path) = @_;
171 return unless PublicInbox::InboxWritable::is_maildir_path($path);
172 if ($path !~ $self->{mdre}) {
173 warn "unrecognized path: $path\n";
176 my $inboxes = $self->{mdmap}->{$1};
178 warn "unmappable dir: $1\n";
181 if (!ref($inboxes) && $inboxes eq 'watchspam') {
182 return _remove_spam($self, $path);
185 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
186 local $SIG{__WARN__} = sub {
187 $warn_cb->("path: $path\n");
190 foreach my $ibx (@$inboxes) {
191 my $eml = mime_from_path($path) or next;
192 import_eml($self, $ibx, $eml);
198 trigger_scan($self, 'quit') or $self->{quit} = 1;
199 if (my $imap_pid = $self->{-imap_pid}) {
200 kill('QUIT', $imap_pid);
202 if (my $idle_pids = $self->{idle_pids}) {
203 kill('QUIT', $_) for (keys %$idle_pids);
205 if (my $idle_mic = $self->{idle_mic}) {
206 eval { $idle_mic->done };
207 warn "IDLE DONE error: $@\n" if $@;
208 eval { $idle_mic->disconnect };
209 warn "IDLE LOGOUT error: $@\n" if $@;
215 require PublicInbox::DirIdle;
216 my $scan = File::Temp->newdir("public-inbox-watch.$$.scan.XXXXXX",
218 my $scandir = $self->{scandir} = $scan->dirname;
219 my $scan_re = qr!\A$scandir/!;
221 delete $self->{done_timer};
222 _done_for_now($self);
225 my $path = $_[0]->fullname;
226 if ($path =~ $scan_re) {
229 _try_path($self, $path);
231 $self->{done_timer} //= PublicInbox::DS::requeue($done);
233 my $di = PublicInbox::DirIdle->new([@{$self->{mdir}}, $scandir], $cb);
234 PublicInbox::DS->SetPostLoopCallback(sub { !$self->{quit} });
235 PublicInbox::DS->EventLoop;
236 _done_for_now($self);
239 # returns the git config section name, e.g [imap "imaps://user@example.com"]
240 # without the mailbox, so we can share connections between different inboxes
241 sub imap_section ($) {
243 $uri->scheme . '://' . $uri->authority;
247 my ($cfg, $key) = @_;
248 defined(my $v = $cfg->{lc($key)}) or return;
249 $v =~ /\A[0-9]+\z/s and return $v + 0;
250 if (ref($v) eq 'ARRAY') {
251 $v = join(', ', @$v);
252 warn "W: $key has multiple values: $v\nW: $key ignored\n";
254 warn "W: $key=$v is not an integer value in seconds\n";
258 # flesh out common IMAP-specific data structures
259 sub imap_common_init ($) {
261 my $cfg = $self->{config};
262 my $mic_args = {}; # scheme://authority => Mail:IMAPClient arg
263 for my $url (sort keys %{$self->{imap}}) {
264 my $uri = PublicInbox::URIimap->new($url);
265 my $sec = imap_section($uri);
266 for my $k (qw(Starttls Debug Compress)) {
267 my $key = lc("imap.$sec.$k");
268 defined(my $orig = $cfg->{$key}) or next;
269 my $v = PublicInbox::Config::_git_config_bool($orig);
271 $mic_args->{$sec}->{$k} = $v;
273 warn "W: $key=$orig is not boolean\n";
276 my $to = cfg_intvl($cfg, "imap.$sec.Timeout");
277 $mic_args->{$sec}->{Timeout} = $to if $to;
278 $to = cfg_intvl($cfg, "imap.$sec.PollInterval");
279 $self->{imap_opt}->{$sec}->{poll_intvl} = $to if $to;
280 $to = cfg_intvl($cfg, "imap.$sec.IdleInterval");
281 $self->{imap_opt}->{$sec}->{idle_intvl} = $to if $to;
286 sub auth_anon_cb { '' }; # for Mail::IMAPClient::Authcallback
288 sub mic_for ($$$) { # mic = Mail::IMAPClient
289 my ($self, $uri, $mic_args) = @_;
290 my $url = $uri->as_string;
293 protocol => $uri->scheme,
295 username => $uri->user,
296 password => $uri->password,
298 my $common = $mic_args->{imap_section($uri)} // {};
299 my $host = $cred->{host};
302 # IMAPClient mishandles `0', so we pass `127.0.0.1'
303 Server => $host eq '0' ? '127.0.0.1' : $host,
304 Ssl => $uri->scheme eq 'imaps',
305 Keepalive => 1, # SO_KEEPALIVE
306 %$common, # may set Starttls, Compress, Debug ....
308 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or
309 die "E: <$url> new: $@\n";
311 # default to using STARTTLS if it's available, but allow
312 # it to be disabled since I usually connect to localhost
313 if (!$mic_arg->{Ssl} && !defined($mic_arg->{Starttls}) &&
314 $mic->has_capability('STARTTLS') &&
315 $mic->can('starttls')) {
316 $mic->starttls or die "E: <$url> STARTTLS: $@\n";
319 # do we even need credentials?
320 if (!defined($cred->{username}) &&
321 $mic->has_capability('AUTH=ANONYMOUS')) {
325 Git::credential($cred, 'fill'); # may prompt user here
326 $mic->User($mic_arg->{User} = $cred->{username});
327 $mic->Password($mic_arg->{Password} = $cred->{password});
328 } else { # AUTH=ANONYMOUS
329 $mic->Authmechanism($mic_arg->{Authmechanism} = 'ANONYMOUS');
330 $mic->Authcallback($mic_arg->{Authcallback} = \&auth_anon_cb);
332 if ($mic->login && $mic->IsAuthenticated) {
333 # success! keep IMAPClient->new arg in case we get disconnected
334 $self->{mic_arg}->{imap_section($uri)} = $mic_arg;
336 warn "E: <$url> LOGIN: $@\n";
339 Git::credential($cred, $mic ? 'approve' : 'reject') if $cred;
345 eval { require PublicInbox::IMAPClient } or
346 die "Mail::IMAPClient is required for IMAP:\n$@\n";
347 eval { require Git } or
348 die "Git (Perl module) is required for IMAP:\n$@\n";
349 eval { require PublicInbox::IMAPTracker } or
350 die "DBD::SQLite is required for IMAP\n:$@\n";
352 my $mic_args = imap_common_init($self);
353 # make sure we can connect and cache the credentials in memory
354 $self->{mic_arg} = {}; # schema://authority => IMAPClient->new args
355 my $mics = $self->{mics} = {}; # schema://authority => IMAPClient obj
356 for my $url (sort keys %{$self->{imap}}) {
357 my $uri = PublicInbox::URIimap->new($url);
358 $mics->{imap_section($uri)} //= mic_for($self, $uri, $mic_args);
362 sub imap_fetch_all ($$$) {
363 my ($self, $mic, $uri) = @_;
364 my $sec = imap_section($uri);
365 my $mbx = $uri->mailbox;
366 my $url = $uri->as_string;
367 $mic->Clear(1); # trim results history
368 $mic->examine($mbx) or return "E: EXAMINE $mbx ($sec) failed: $!";
369 my ($r_uidval, $r_uidnext);
370 for ($mic->Results) {
371 /^\* OK \[UIDVALIDITY ([0-9]+)\].*/ and $r_uidval = $1;
372 /^\* OK \[UIDNEXT ([0-9]+)\].*/ and $r_uidnext = $1;
373 last if $r_uidval && $r_uidnext;
375 $r_uidval //= $mic->uidvalidity($mbx) //
376 return "E: $url cannot get UIDVALIDITY";
377 $r_uidnext //= $mic->uidnext($mbx) //
378 return "E: $url cannot get UIDNEXT";
379 my $itrk = PublicInbox::IMAPTracker->new;
380 my ($l_uidval, $l_uid) = $itrk->get_last($url);
381 $l_uidval //= $r_uidval; # first time
383 if ($l_uidval != $r_uidval) {
384 return "E: $url UIDVALIDITY mismatch\n".
385 "E: local=$l_uidval != remote=$r_uidval";
387 my $r_uid = $r_uidnext - 1;
388 if ($l_uid != 1 && $l_uid > $r_uid) {
389 return "E: $url local UID exceeds remote ($l_uid > $r_uid)\n".
390 "E: $url strangely, UIDVALIDLITY matches ($l_uidval)\n";
392 return if $l_uid >= $r_uid; # nothing to do
394 $mic->Uid(1); # the default, we hope
395 my $req = $mic->imap4rev1 ? 'BODY.PEEK[]' : 'RFC822.PEEK';
398 my $inboxes = $self->{imap}->{$url};
399 warn "I: $url fetching $l_uid..$r_uid\n";
401 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
402 local $SIG{__WARN__} = sub {
403 $warn_cb->("$url UID:$uid\n");
407 $itrk->{dbh}->begin_work;
408 for my $u ($l_uid..$r_uid) {
410 local $0 = "UID:$uid $mbx $sec";
411 my $r = $mic->fetch_hash($uid, $req);
412 unless ($r) { # network error?
413 $err = "E: $url UID FETCH $uid error: $!\n";
417 # messages get deleted, so holes appear
418 defined(my $raw = delete $r->{$uid}->{$key}) or next;
420 # our target audience expects LF-only, save storage
421 $raw =~ s/\r\n/\n/sg;
424 for my $ibx (@$inboxes) {
425 my $eml = PublicInbox::Eml->new($raw);
426 my $x = import_eml($self, $ibx, $eml);
428 } elsif ($inboxes eq 'watchspam') {
429 my $eml = PublicInbox::Eml->new($raw);
430 my $arg = [ $self, $eml, "$uri UID:$uid" ];
431 $self->{config}->each_inbox(\&remove_eml_i, $arg);
433 die "BUG: destination unknown $inboxes";
435 $itrk->update_last($url, $r_uidval, $uid);
436 last if $self->{quit};
438 _done_for_now($self);
439 $itrk->{dbh}->commit;
443 sub imap_idle_once ($$$$) {
444 my ($self, $mic, $intvl, $url) = @_;
445 my $i = $intvl //= (29 * 60);
446 my $end = now() + $intvl;
447 warn "I: $url idling for ${intvl}s\n";
448 local $0 = "IDLE $0";
449 unless ($mic->idle) {
450 return if $self->{quit};
451 return "E: IDLE failed on $url: $!";
453 $self->{idle_mic} = $mic; # for ->quit
455 until ($self->{quit} || grep(/^\* [0-9]+ EXISTS/, @res) || $i <= 0) {
456 @res = $mic->idle_data($i);
459 delete $self->{idle_mic};
460 unless ($self->{quit}) {
461 $mic->IsConnected or return "E: IDLE disconnected on $url";
462 $mic->done or return "E: IDLE DONE failed on $url: $!";
467 # idles on a single URI
468 sub watch_imap_idle_1 ($$$) {
469 my ($self, $uri, $intvl) = @_;
470 my $sec = imap_section($uri);
471 my $mic_arg = $self->{mic_arg}->{$sec} or
472 die "BUG: no Mail::IMAPClient->new arg for $sec";
474 local $0 = $uri->mailbox." $sec";
475 until ($self->{quit}) {
476 $mic //= delete($self->{mics}->{$sec}) //
477 PublicInbox::IMAPClient->new(%$mic_arg);
478 my $err = imap_fetch_all($self, $mic, $uri);
479 $err //= imap_idle_once($self, $mic, $intvl, $uri->as_string);
480 if ($err && !$self->{quit}) {
483 sleep 60 unless $self->{quit};
488 sub watch_imap_idle_all ($$) {
489 my ($self, $idle) = @_; # $idle = [[ uri1, intvl1 ], [ uri2, intvl2 ]]
490 $self->{mics} = {}; # going to be forking, so disconnect
491 my $idle_pids = $self->{idle_pids} = {};
492 until ($self->{quit}) {
493 while (my $uri_intvl = shift @$idle) {
494 my ($uri, $intvl) = @$uri_intvl;
495 defined(my $pid = fork) or die "fork: $!";
497 delete $self->{idle_pids};
498 watch_imap_idle_1($self, $uri, $intvl);
501 $idle_pids->{$pid} = $uri_intvl;
503 my $pid = waitpid(-1, 0) or next;
505 warn "W: no idling children: $!";
509 warn "W: nothing to respawn, quitting IDLE\n";
513 if (my $uri_intvl = delete $idle_pids->{$pid}) {
514 my ($uri, $intvl) = @$uri_intvl;
515 my $url = $uri->as_string;
516 if ($? || !$self->{quit}) {
517 warn "W: PID=$pid on $url died: \$?=$?\n";
519 push @$idle, $uri_intvl;
521 warn "W: PID=$pid (unknown) reaped: \$?=$?\n";
526 kill('QUIT', $_) for (keys %$idle_pids);
527 while (scalar keys %$idle_pids) {
528 if (my $pid = waitpid(-1, WNOHANG)) {
530 warn "E: no children? $! (PIDs: ",
531 join(', ', keys %$idle_pids),")\n";
534 delete $idle_pids->{$pid};
536 } else { # signals aren't that reliable w/o signalfd/kevent
538 kill('QUIT', $_) for (keys %$idle_pids);
545 my $idle = []; # [ [ uri1, intvl1 ], [uri2, intvl2] ];
546 my $poll = {}; # intvl_seconds => [ uri1, uri2 ]
547 for my $url (keys %{$self->{imap}}) {
548 my $uri = PublicInbox::URIimap->new($url);
549 my $sec = imap_section($uri);
550 my $mic = $self->{mics}->{$sec};
551 my $intvl = $self->{imap_opt}->{$sec}->{poll_intvl};
552 if ($mic->has_capability('IDLE') && !$intvl) {
553 $intvl = $self->{imap_opt}->{$sec}->{idle_intvl};
554 push @$idle, [ $uri, $intvl // () ];
556 push @{$poll->{$intvl || 120}}, $uri;
559 my $nr_poll = scalar keys %$poll;
560 if (scalar @$idle && !$nr_poll) { # multiple idlers, need fork
561 watch_imap_idle_all($self, $idle);
568 if ($self->{mdre} && $self->{imap}) {
569 defined(my $pid = fork) or die "fork: $!";
574 $self->{-imap_pid} = $pid;
575 } elsif ($self->{imap}) {
583 my ($self, $base) = @_;
584 my $dir = $self->{scandir} or return;
585 open my $fh, '>', "$dir/$base" or die "open $dir/$base failed: $!\n";
586 close $fh or die "close $dir/$base failed: $!\n";
590 my ($self, $path) = @_;
591 if ($path =~ /quit\z/) {
592 %{$self->{opendirs}} = ();
593 _done_for_now($self);
594 delete $self->{scandir};
598 # else: $path =~ /(cont|full)\z/
599 return if $self->{quit};
601 my $opendirs = $self->{opendirs};
602 my @dirnames = keys %$opendirs;
603 foreach my $dir (@dirnames) {
604 my $dh = delete $opendirs->{$dir};
606 while (my $fn = readdir($dh)) {
607 _try_path($self, "$dir/$fn");
610 $opendirs->{$dir} = $dh if $n < 0;
612 if ($path =~ /full\z/) {
613 foreach my $dir (@{$self->{mdir}}) {
614 next if $opendirs->{$dir}; # already in progress
615 my $ok = opendir(my $dh, $dir);
617 warn "failed to open $dir: $!\n";
621 while (my $fn = readdir($dh)) {
622 _try_path($self, "$dir/$fn");
625 $opendirs->{$dir} = $dh if $n < 0;
628 _done_for_now($self);
629 # do we have more work to do?
630 trigger_scan($self, 'cont') if keys %$opendirs;
634 my ($self, $ibx) = @_;
635 my $importers = $self->{importers};
636 my $im = $importers->{"$ibx"} ||= $ibx->importer(0);
637 if (scalar(keys(%$importers)) > 2) {
638 delete $importers->{"$ibx"};
639 _done_for_now($self);
642 $importers->{"$ibx"} = $im;
650 if ($sc->spamcheck($mime, \$tmp)) {
651 return PublicInbox::Eml->new(\$tmp);
653 warn $mime->header('Message-ID')." failed spam check\n";
659 $_[0] =~ s!\Amaildir:!! or return;
666 my ($cur, $ws, $ibx) = @_;
667 if ($ws && !ref($ws) && $ws eq 'watchspam') {
669 E: $cur is a spam folder and cannot be used for `$ibx->{name}' input
678 require PublicInbox::URIimap;
679 my $uri = PublicInbox::URIimap->new($url);
680 $uri ? $uri->canonical->as_string : undef;