1 # Copyright (C) 2016-2021 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 # https://wiki2.dovecot.org/MailboxFormat/Maildir
6 package PublicInbox::Watch;
10 use PublicInbox::InboxWritable qw(eml_from_path);
11 use PublicInbox::MdirReader;
12 use PublicInbox::NetReader;
13 use PublicInbox::Filter::Base qw(REJECT);
14 use PublicInbox::Spamcheck;
15 use PublicInbox::Sigfd;
16 use PublicInbox::DS qw(now add_timer);
17 use PublicInbox::MID qw(mids);
18 use PublicInbox::ContentHash qw(content_hash);
19 use PublicInbox::EOFpipe;
20 use POSIX qw(_exit WNOHANG);
22 sub compile_watchheaders ($) {
25 if (my $whs = $ibx->{watchheader}) {
27 my ($k, $v) = split(/:/, $_, 2);
28 # XXX should this be case-insensitive?
29 # Or, mutt-style, case-sensitive iff
30 # a capital letter exists?
31 push @$watch_hdrs, [ $k, qr/\Q$v\E/ ];
34 if (my $list_ids = $ibx->{listid}) {
36 # RFC2919 section 6 stipulates
37 # "case insensitive equality"
38 my $re = qr/<[ \t]*\Q$_\E[ \t]*>/i;
39 push @$watch_hdrs, ['List-Id', $re ];
42 $ibx->{-watchheaders} = $watch_hdrs if scalar @$watch_hdrs;
46 my ($class, $cfg) = @_;
48 my (%imap, %nntp); # url => [inbox objects] or 'watchspam'
51 # "publicinboxwatch" is the documented namespace
52 # "publicinboxlearn" is legacy but may be supported
54 foreach my $pfx (qw(publicinboxwatch publicinboxlearn)) {
55 my $k = "$pfx.watchspam";
56 my $dirs = $cfg->get_all($k) // next;
57 for my $dir (@$dirs) {
59 if (is_maildir($dir)) {
60 # skip "new", no MUA has seen it, yet.
61 $mdmap{"$dir/cur"} = 'watchspam';
62 } elsif ($uri = imap_uri($dir)) {
63 $imap{$$uri} = 'watchspam';
65 } elsif ($uri = nntp_uri($dir)) {
66 $nntp{$$uri} = 'watchspam';
69 warn "unsupported $k=$dir\n";
74 my $k = 'publicinboxwatch.spamcheck';
76 my $spamcheck = PublicInbox::Spamcheck::get($cfg, $k, $default);
77 $spamcheck = _spamcheck_cb($spamcheck) if $spamcheck;
79 $cfg->each_inbox(sub {
80 # need to make all inboxes writable for spam removal:
81 my $ibx = $_[0] = PublicInbox::InboxWritable->new($_[0]);
83 my $watches = $ibx->{watch} or return;
84 $watches = PublicInbox::Config::_array($watches);
85 for my $watch (@$watches) {
87 if (is_maildir($watch)) {
88 compile_watchheaders($ibx);
89 my ($new, $cur) = ("$watch/new", "$watch/cur");
90 my $cur_dst = $mdmap{$cur} //= [];
91 return if is_watchspam($cur, $cur_dst, $ibx);
92 push @{$mdmap{$new} //= []}, $ibx;
94 } elsif ($uri = imap_uri($watch)) {
95 my $cur_dst = $imap{$$uri} //= [];
96 return if is_watchspam($uri, $cur_dst, $ibx);
97 compile_watchheaders($ibx);
98 push(@imap, $uri) if 1 == push(@$cur_dst, $ibx);
99 } elsif ($uri = nntp_uri($watch)) {
100 my $cur_dst = $nntp{$$uri} //= [];
101 return if is_watchspam($uri, $cur_dst, $ibx);
102 compile_watchheaders($ibx);
103 push(@nntp, $uri) if 1 == push(@$cur_dst, $ibx);
105 warn "watch unsupported: $k=$watch\n";
111 if (scalar keys %mdmap) {
112 $mdre = join('|', map { quotemeta($_) } keys %mdmap);
113 $mdre = qr!\A($mdre)/!;
115 return unless $mdre || scalar(keys %imap) || scalar(keys %nntp);
118 max_batch => 10, # avoid hogging locks for too long
119 spamcheck => $spamcheck,
123 imap => scalar keys %imap ? \%imap : undef,
124 nntp => scalar keys %nntp? \%nntp : undef,
125 imap_order => scalar(@imap) ? \@imap : undef,
126 nntp_order => scalar(@nntp) ? \@nntp: undef,
128 opendirs => {}, # dirname => dirhandle (in progress scans)
129 ops => [], # 'quit', 'full'
135 local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
136 for my $im (values %{$self->{importers}}) {
137 next if !$im; # $im may be undef during cleanup
139 warn "$im->{ibx}->{name} ->done: $@\n" if $@;
143 sub remove_eml_i { # each_inbox callback
144 my ($ibx, $self, $eml, $loc) = @_;
147 # try to avoid taking a lock or unnecessary spawning
148 my $im = $self->{importers}->{"$ibx"};
150 if ((!$im || !$im->active) && $ibx->over) {
151 if (content_exists($ibx, $eml)) {
153 } elsif (my $scrub = $ibx->filter($im)) {
154 $scrubbed = $scrub->scrub($eml, 1);
155 if ($scrubbed && $scrubbed != REJECT &&
156 !content_exists($ibx, $scrubbed)) {
164 $im //= _importer_for($self, $ibx); # may spawn fast-import
165 $im->remove($eml, 'spam');
167 my $scrub = $ibx->filter($im);
168 $scrub ? $scrub->scrub($eml, 1) : undef;
170 if ($scrubbed && $scrubbed != REJECT) {
171 $im->remove($scrubbed, 'spam');
175 warn "error removing spam at: $loc from $ibx->{name}: $@\n";
176 _done_for_now($self);
181 my ($self, $path) = @_;
182 # path must be marked as (S)een
183 $path =~ /:2,[A-R]*S[T-Za-z]*\z/ or return;
184 my $eml = eml_from_path($path) or return;
185 local $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
186 $self->{pi_cfg}->each_inbox(\&remove_eml_i, $self, $eml, $path);
189 sub import_eml ($$$) {
190 my ($self, $ibx, $eml) = @_;
192 # any header match means it's eligible for the inbox:
193 if (my $watch_hdrs = $ibx->{-watchheaders}) {
195 for my $wh (@$watch_hdrs) {
196 my @v = $eml->header_raw($wh->[0]);
197 $ok = grep(/$wh->[1]/, @v) and last;
202 my $im = _importer_for($self, $ibx);
203 if (my $scrub = $ibx->filter($im)) {
204 my $scrubbed = $scrub->scrub($eml) or return;
205 $scrubbed == REJECT and return;
208 $im->add($eml, $self->{spamcheck});
211 warn "$ibx->{name} add failed: $@\n";
212 _done_for_now($self);
217 my ($self, $path) = @_;
218 my $fl = PublicInbox::MdirReader::maildir_path_flags($path) // return;
219 return if $fl =~ /[DT]/; # no Drafts or Trash
220 if ($path !~ $self->{mdre}) {
221 warn "unrecognized path: $path\n";
224 my $inboxes = $self->{mdmap}->{$1};
226 warn "unmappable dir: $1\n";
229 my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
230 local $SIG{__WARN__} = sub {
231 my $pfx = ($_[0] // '') =~ /^([A-Z]: )/g ? $1 : '';
232 $warn_cb->($pfx, "path: $path\n", @_);
234 if (!ref($inboxes) && $inboxes eq 'watchspam') {
235 return _remove_spam($self, $path);
237 foreach my $ibx (@$inboxes) {
238 my $eml = eml_from_path($path) or next;
239 import_eml($self, $ibx, $eml);
245 return unless $self->{quit};
247 # don't have reliable wakeups, keep signalling
249 for (qw(idle_pids poll_pids)) {
250 my $pids = $self->{$_} or next;
252 $done = undef if kill('QUIT', $_);
261 %{$self->{opendirs}} = ();
262 _done_for_now($self);
264 if (my $idle_mic = $self->{idle_mic}) {
265 eval { $idle_mic->done };
267 warn "IDLE DONE error: $@\n";
268 eval { $idle_mic->disconnect };
269 warn "IDLE LOGOUT error: $@\n" if $@;
274 sub watch_fs_init ($) {
277 delete $self->{done_timer};
278 _done_for_now($self);
280 my $cb = sub { # called by PublicInbox::DirIdle::event_step
281 _try_path($self, $_[0]->fullname);
282 $self->{done_timer} //= PublicInbox::DS::requeue($done);
284 require PublicInbox::DirIdle;
285 # inotify_create + EPOLL_CTL_ADD
286 PublicInbox::DirIdle->new([keys %{$self->{mdmap}}], $cb);
289 sub net_cb { # NetReader::(nntp|imap)_each callback
290 my ($uri, $art, $kw, $eml, $self, $inboxes) = @_;
291 return if grep(/\Adraft\z/, @$kw);
292 local $self->{cur_uid} = $art; # IMAP UID or NNTP article
297 my $tmp = PublicInbox::Eml->new(\($eml->as_string));
298 import_eml($self, $ibx, $tmp);
300 import_eml($self, $last, $eml);
301 } elsif ($inboxes eq 'watchspam') {
302 if ($uri->scheme =~ /\Aimaps?\z/ && !grep(/\Aseen\z/, @$kw)) {
305 $self->{pi_cfg}->each_inbox(\&remove_eml_i,
306 $self, $eml, "$uri #$art");
308 die "BUG: destination unknown $inboxes";
312 sub imap_fetch_all ($$) {
313 my ($self, $uri) = @_;
314 my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
315 $self->{incremental} = 1;
316 $self->{on_commit} = [ \&_done_for_now, $self ];
317 local $self->{cur_uid};
318 local $SIG{__WARN__} = sub {
319 my $pfx = ($_[0] // '') =~ /^([A-Z]: |# )/g ? $1 : '';
320 my $uid = $self->{cur_uid};
321 $warn_cb->("$pfx$uri", $uid ? ("UID:$uid") : (), "\n", @_);
323 PublicInbox::NetReader::imap_each($self, $uri, \&net_cb, $self,
324 $self->{imap}->{$$uri});
327 sub imap_idle_once ($$$$) {
328 my ($self, $mic, $intvl, $uri) = @_;
329 my $i = $intvl //= (29 * 60);
330 my $end = now() + $intvl;
331 warn "I: $uri idling for ${intvl}s\n";
332 local $0 = "IDLE $0";
333 unless ($mic->idle) {
334 return if $self->{quit};
335 return "E: IDLE failed on $uri: $!";
337 $self->{idle_mic} = $mic; # for ->quit
339 until ($self->{quit} || !$mic->IsConnected ||
340 grep(/^\* [0-9]+ EXISTS/, @res) || $i <= 0) {
341 @res = $mic->idle_data($i);
344 delete $self->{idle_mic};
345 unless ($self->{quit}) {
346 $mic->IsConnected or return "E: IDLE disconnected on $uri";
347 $mic->done or return "E: IDLE DONE failed on $uri: $!";
352 # idles on a single URI
353 sub watch_imap_idle_1 ($$$) {
354 my ($self, $uri, $intvl) = @_;
355 my $sec = uri_section($uri);
356 my $mic_arg = $self->{net_arg}->{$sec} or
357 die "BUG: no Mail::IMAPClient->new arg for $sec";
359 local $0 = $uri->mailbox." $sec";
360 until ($self->{quit}) {
361 $mic //= PublicInbox::NetReader::mic_new(
362 $self, $mic_arg, $sec, $uri);
364 if ($mic && $mic->IsConnected) {
365 local $self->{mics_cached}->{$sec} = $mic;
366 my $m = imap_fetch_all($self, $uri);
367 $m == $mic or die "BUG: wrong mic";
368 $mic->IsConnected and
369 $err = imap_idle_once($self, $mic, $intvl, $uri)
371 $err = "E: not connected: $!";
373 if ($err && !$self->{quit}) {
376 sleep 60 unless $self->{quit};
381 sub watch_atfork_child ($) {
383 delete $self->{idle_pids};
384 delete $self->{poll_pids};
385 delete $self->{opendirs};
386 PublicInbox::DS->Reset;
387 my $sig = delete $self->{sig};
388 $sig->{CHLD} = 'DEFAULT';
389 @SIG{keys %$sig} = values %$sig;
390 PublicInbox::DS::sig_setmask($self->{oldset});
393 sub watch_atfork_parent ($) {
395 _done_for_now($self);
396 PublicInbox::DS::block_signals();
399 sub imap_idle_requeue { # DS::add_timer callback
400 my ($self, $uri_intvl) = @_;
401 return if $self->{quit};
402 push @{$self->{idle_todo}}, $uri_intvl;
406 sub imap_idle_reap { # PublicInbox::DS::dwaitpid callback
407 my ($self, $pid) = @_;
408 my $uri_intvl = delete $self->{idle_pids}->{$pid} or
409 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
411 my ($uri, $intvl) = @$uri_intvl;
412 return if $self->{quit};
413 warn "W: PID=$pid on $uri died: \$?=$?\n" if $?;
414 add_timer(60, \&imap_idle_requeue, $self, $uri_intvl);
417 sub reap { # callback for EOFpipe
418 my ($pid, $cb, $self) = @{$_[0]};
419 my $ret = waitpid($pid, 0);
421 $cb->($self, $pid); # poll_fetch_reap || imap_idle_reap
423 warn "W: waitpid($pid) => ", $ret // "($!)", "\n";
427 sub imap_idle_fork ($$) {
428 my ($self, $uri_intvl) = @_;
429 my ($uri, $intvl) = @$uri_intvl;
430 pipe(my ($r, $w)) or die "pipe: $!";
431 my $seed = rand(0xffffffff);
432 my $pid = fork // die "fork: $!";
435 eval { Net::SSLeay::randomize() };
437 watch_atfork_child($self);
438 watch_imap_idle_1($self, $uri, $intvl);
442 $self->{idle_pids}->{$pid} = $uri_intvl;
443 PublicInbox::EOFpipe->new($r, \&reap, [$pid, \&imap_idle_reap, $self]);
448 return if $self->{quit};
449 my $idle_todo = $self->{idle_todo};
450 if ($idle_todo && @$idle_todo) {
451 my $oldset = watch_atfork_parent($self);
453 while (my $uri_intvl = shift(@$idle_todo)) {
454 imap_idle_fork($self, $uri_intvl);
457 PublicInbox::DS::sig_setmask($oldset);
460 fs_scan_step($self) if $self->{mdre};
463 sub watch_imap_fetch_all ($$) {
464 my ($self, $uris) = @_;
465 for my $uri (@$uris) {
466 imap_fetch_all($self, $uri);
467 last if $self->{quit};
471 sub watch_nntp_fetch_all ($$) {
472 my ($self, $uris) = @_;
473 $self->{incremental} = 1;
474 $self->{on_commit} = [ \&_done_for_now, $self ];
475 my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
476 local $self->{cur_uid};
478 local $SIG{__WARN__} = sub {
479 my $pfx = ($_[0] // '') =~ /^([A-Z]: |# )/g ? $1 : '';
480 my $art = $self->{cur_uid};
481 $warn_cb->("$pfx$uri", $art ? ("ARTICLE $art") : (), "\n", @_);
484 PublicInbox::NetReader::nntp_each($self, $uri, \&net_cb, $self,
485 $self->{nntp}->{$$uri});
486 last if $self->{quit};
490 sub poll_fetch_fork { # DS::add_timer callback
491 my ($self, $intvl, $uris) = @_;
492 return if $self->{quit};
493 pipe(my ($r, $w)) or die "pipe: $!";
494 my $oldset = watch_atfork_parent($self);
495 my $seed = rand(0xffffffff);
497 if (defined($pid) && $pid == 0) {
499 eval { Net::SSLeay::randomize() };
501 watch_atfork_child($self);
502 if ($uris->[0]->scheme =~ m!\Aimaps?!i) {
503 watch_imap_fetch_all($self, $uris);
505 watch_nntp_fetch_all($self, $uris);
510 PublicInbox::DS::sig_setmask($oldset);
511 die "fork: $!" unless defined $pid;
512 $self->{poll_pids}->{$pid} = [ $intvl, $uris ];
513 PublicInbox::EOFpipe->new($r, \&reap, [$pid, \&poll_fetch_reap, $self]);
516 sub poll_fetch_reap {
517 my ($self, $pid) = @_;
518 my $intvl_uris = delete $self->{poll_pids}->{$pid} or
519 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
520 return if $self->{quit};
521 my ($intvl, $uris) = @$intvl_uris;
523 warn "W: PID=$pid died: \$?=$?\n", map { "$_\n" } @$uris;
525 warn("I: will check $_ in ${intvl}s\n") for @$uris;
526 add_timer($intvl, \&poll_fetch_fork, $self, $intvl, $uris);
529 sub watch_imap_init ($$) {
530 my ($self, $poll) = @_;
531 my $mics = PublicInbox::NetReader::imap_common_init($self);
532 my $idle = []; # [ [ uri1, intvl1 ], [uri2, intvl2] ]
533 for my $uri (@{$self->{imap_order}}) {
534 my $sec = uri_section($uri);
535 my $mic = $mics->{$sec};
536 my $intvl = $self->{cfg_opt}->{$sec}->{pollInterval};
537 if ($mic->has_capability('IDLE') && !$intvl) {
538 $intvl = $self->{cfg_opt}->{$sec}->{idleInterval};
539 push @$idle, [ $uri, $intvl // () ];
541 push @{$poll->{$intvl || 120}}, $uri;
545 $self->{idle_todo} = $idle;
546 PublicInbox::DS::requeue($self); # ->event_step to fork
550 sub watch_nntp_init ($$) {
551 my ($self, $poll) = @_;
552 PublicInbox::NetReader::nntp_common_init($self);
553 for my $uri (@{$self->{nntp_order}}) {
554 my $sec = uri_section($uri);
555 my $intvl = $self->{cfg_opt}->{$sec}->{pollInterval};
556 push @{$poll->{$intvl || 120}}, $uri;
560 sub watch { # main entry point
561 my ($self, $sig, $oldset) = @_;
562 $self->{oldset} = $oldset;
564 my $poll = {}; # intvl_seconds => [ uri1, uri2 ]
565 watch_imap_init($self, $poll) if $self->{imap};
566 watch_nntp_init($self, $poll) if $self->{nntp};
567 while (my ($intvl, $uris) = each %$poll) {
568 # poll all URIs for a given interval sequentially
569 add_timer(0, \&poll_fetch_fork, $self, $intvl, $uris);
571 watch_fs_init($self) if $self->{mdre};
572 PublicInbox::DS->SetPostLoopCallback(sub { !$self->quit_done });
573 PublicInbox::DS->EventLoop; # calls ->event_step
574 _done_for_now($self);
578 my ($self, $op) = @_;
579 push @{$self->{ops}}, $op;
580 PublicInbox::DS::requeue($self);
585 return if $self->{quit};
586 my $op = shift @{$self->{ops}};
587 local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
589 # continue existing scan
590 my $opendirs = $self->{opendirs};
591 my @dirnames = keys %$opendirs;
592 foreach my $dir (@dirnames) {
593 my $dh = delete $opendirs->{$dir};
594 my $n = $self->{max_batch};
595 while (my $fn = readdir($dh)) {
596 _try_path($self, "$dir/$fn");
599 $opendirs->{$dir} = $dh if $n < 0;
601 if ($op && $op eq 'full') {
602 foreach my $dir (keys %{$self->{mdmap}}) {
603 next if $opendirs->{$dir}; # already in progress
604 my $ok = opendir(my $dh, $dir);
606 warn "failed to open $dir: $!\n";
609 my $n = $self->{max_batch};
610 while (my $fn = readdir($dh)) {
611 _try_path($self, "$dir/$fn");
614 $opendirs->{$dir} = $dh if $n < 0;
617 _done_for_now($self);
618 # do we have more work to do?
619 PublicInbox::DS::requeue($self) if keys %$opendirs;
623 my ($self, $op) = @_;
624 push @{$self->{ops}}, $op;
629 my ($self, $ibx) = @_;
630 my $importers = $self->{importers};
631 my $im = $importers->{"$ibx"} ||= $ibx->importer(0);
632 if (scalar(keys(%$importers)) > 2) {
633 delete $importers->{"$ibx"};
634 _done_for_now($self);
637 $importers->{"$ibx"} = $im;
640 # XXX consider sharing with V2Writable, this only requires read-only access
641 sub content_exists ($$) {
642 my ($ibx, $eml) = @_;
643 my $over = $ibx->over or return;
644 my $mids = mids($eml);
645 my $chash = content_hash($eml);
647 for my $mid (@$mids) {
648 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
649 my $cmp = $ibx->smsg_eml($smsg) or return;
650 return 1 if $chash eq content_hash($cmp);
658 sub { # this gets called by (V2Writable||Import)->add
659 my ($mime, $ibx) = @_;
660 return if content_exists($ibx, $mime);
662 if ($sc->spamcheck($mime, \$tmp)) {
663 return PublicInbox::Eml->new(\$tmp);
665 warn $mime->header('Message-ID')." failed spam check\n";
671 $_[0] =~ s!\Amaildir:!! or return;
678 my ($cur, $ws, $ibx) = @_;
679 if ($ws && !ref($ws) && $ws eq 'watchspam') {
681 E: $cur is a spam folder and cannot be used for `$ibx->{name}' input
688 sub folder_select { 'select' } # for PublicInbox::NetReader