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::DS qw(now add_timer);
16 use PublicInbox::MID qw(mids);
17 use PublicInbox::ContentHash qw(content_hash);
18 use PublicInbox::EOFpipe;
19 use POSIX qw(_exit WNOHANG);
21 sub compile_watchheaders ($) {
24 if (my $whs = $ibx->{watchheader}) {
26 my ($k, $v) = split(/:/, $_, 2);
27 # XXX should this be case-insensitive?
28 # Or, mutt-style, case-sensitive iff
29 # a capital letter exists?
30 push @$watch_hdrs, [ $k, qr/\Q$v\E/ ];
33 if (my $list_ids = $ibx->{listid}) {
35 # RFC2919 section 6 stipulates
36 # "case insensitive equality"
37 my $re = qr/<[ \t]*\Q$_\E[ \t]*>/i;
38 push @$watch_hdrs, ['List-Id', $re ];
41 $ibx->{-watchheaders} = $watch_hdrs if scalar @$watch_hdrs;
45 my ($class, $cfg) = @_;
47 my (%imap, %nntp); # url => [inbox objects] or 'watchspam'
50 # "publicinboxwatch" is the documented namespace
51 # "publicinboxlearn" is legacy but may be supported
53 foreach my $pfx (qw(publicinboxwatch publicinboxlearn)) {
54 my $k = "$pfx.watchspam";
55 my $dirs = $cfg->get_all($k) // next;
56 for my $dir (@$dirs) {
58 if (is_maildir($dir)) {
59 # skip "new", no MUA has seen it, yet.
60 $mdmap{"$dir/cur"} = 'watchspam';
61 } elsif ($uri = imap_uri($dir)) {
62 $imap{$$uri} = 'watchspam';
64 } elsif ($uri = nntp_uri($dir)) {
65 $nntp{$$uri} = 'watchspam';
68 warn "unsupported $k=$dir\n";
73 my $k = 'publicinboxwatch.spamcheck';
75 my $spamcheck = PublicInbox::Spamcheck::get($cfg, $k, $default);
76 $spamcheck = _spamcheck_cb($spamcheck) if $spamcheck;
78 $cfg->each_inbox(sub {
79 # need to make all inboxes writable for spam removal:
80 my $ibx = $_[0] = PublicInbox::InboxWritable->new($_[0]);
82 my $watches = $ibx->{watch} or return;
83 $watches = PublicInbox::Config::_array($watches);
84 for my $watch (@$watches) {
86 if (is_maildir($watch)) {
87 compile_watchheaders($ibx);
88 my ($new, $cur) = ("$watch/new", "$watch/cur");
89 my $cur_dst = $mdmap{$cur} //= [];
90 return if is_watchspam($cur, $cur_dst, $ibx);
91 push @{$mdmap{$new} //= []}, $ibx;
93 } elsif ($uri = imap_uri($watch)) {
94 my $cur_dst = $imap{$$uri} //= [];
95 return if is_watchspam($uri, $cur_dst, $ibx);
96 compile_watchheaders($ibx);
97 push(@imap, $uri) if 1 == push(@$cur_dst, $ibx);
98 } elsif ($uri = nntp_uri($watch)) {
99 my $cur_dst = $nntp{$$uri} //= [];
100 return if is_watchspam($uri, $cur_dst, $ibx);
101 compile_watchheaders($ibx);
102 push(@nntp, $uri) if 1 == push(@$cur_dst, $ibx);
104 warn "watch unsupported: $k=$watch\n";
110 if (scalar keys %mdmap) {
111 $mdre = join('|', map { quotemeta($_) } keys %mdmap);
112 $mdre = qr!\A($mdre)/!;
114 return unless $mdre || scalar(keys %imap) || scalar(keys %nntp);
117 max_batch => 10, # avoid hogging locks for too long
118 spamcheck => $spamcheck,
122 imap => scalar keys %imap ? \%imap : undef,
123 nntp => scalar keys %nntp? \%nntp : undef,
124 imap_order => scalar(@imap) ? \@imap : undef,
125 nntp_order => scalar(@nntp) ? \@nntp: undef,
127 opendirs => {}, # dirname => dirhandle (in progress scans)
128 ops => [], # 'quit', 'full'
134 local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
135 for my $im (values %{$self->{importers}}) {
136 next if !$im; # $im may be undef during cleanup
138 warn "$im->{ibx}->{name} ->done: $@\n" if $@;
142 sub remove_eml_i { # each_inbox callback
143 my ($ibx, $self, $eml, $loc) = @_;
146 # try to avoid taking a lock or unnecessary spawning
147 my $im = $self->{importers}->{"$ibx"};
149 if ((!$im || !$im->active) && $ibx->over) {
150 if (content_exists($ibx, $eml)) {
152 } elsif (my $scrub = $ibx->filter($im)) {
153 $scrubbed = $scrub->scrub($eml, 1);
154 if ($scrubbed && $scrubbed != REJECT &&
155 !content_exists($ibx, $scrubbed)) {
163 $im //= _importer_for($self, $ibx); # may spawn fast-import
164 $im->remove($eml, 'spam');
166 my $scrub = $ibx->filter($im);
167 $scrub ? $scrub->scrub($eml, 1) : undef;
169 if ($scrubbed && $scrubbed != REJECT) {
170 $im->remove($scrubbed, 'spam');
174 warn "error removing spam at: $loc from $ibx->{name}: $@\n";
175 _done_for_now($self);
180 my ($self, $path) = @_;
181 # path must be marked as (S)een
182 $path =~ /:2,[A-R]*S[T-Za-z]*\z/ or return;
183 my $eml = eml_from_path($path) or return;
184 local $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
185 $self->{pi_cfg}->each_inbox(\&remove_eml_i, $self, $eml, $path);
188 sub import_eml ($$$) {
189 my ($self, $ibx, $eml) = @_;
191 # any header match means it's eligible for the inbox:
192 if (my $watch_hdrs = $ibx->{-watchheaders}) {
194 for my $wh (@$watch_hdrs) {
195 my @v = $eml->header_raw($wh->[0]);
196 $ok = grep(/$wh->[1]/, @v) and last;
201 my $im = _importer_for($self, $ibx);
202 if (my $scrub = $ibx->filter($im)) {
203 my $scrubbed = $scrub->scrub($eml) or return;
204 $scrubbed == REJECT and return;
207 $im->add($eml, $self->{spamcheck});
210 warn "$ibx->{name} add failed: $@\n";
211 _done_for_now($self);
216 my ($self, $path) = @_;
217 my $fl = PublicInbox::MdirReader::maildir_path_flags($path) // return;
218 return if $fl =~ /[DT]/; # no Drafts or Trash
219 if ($path !~ $self->{mdre}) {
220 warn "unrecognized path: $path\n";
223 my $inboxes = $self->{mdmap}->{$1};
225 warn "unmappable dir: $1\n";
228 my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
229 local $SIG{__WARN__} = sub {
230 my $pfx = ($_[0] // '') =~ /^([A-Z]: )/g ? $1 : '';
231 $warn_cb->($pfx, "path: $path\n", @_);
233 if (!ref($inboxes) && $inboxes eq 'watchspam') {
234 return _remove_spam($self, $path);
236 foreach my $ibx (@$inboxes) {
237 my $eml = eml_from_path($path) or next;
238 import_eml($self, $ibx, $eml);
244 return unless $self->{quit};
246 # don't have reliable wakeups, keep signalling
248 for (qw(idle_pids poll_pids)) {
249 my $pids = $self->{$_} or next;
251 $done = undef if kill('QUIT', $_);
260 %{$self->{opendirs}} = ();
261 _done_for_now($self);
263 if (my $idle_mic = $self->{idle_mic}) {
264 eval { $idle_mic->done };
266 warn "IDLE DONE error: $@\n";
267 eval { $idle_mic->disconnect };
268 warn "IDLE LOGOUT error: $@\n" if $@;
273 sub watch_fs_init ($) {
276 delete $self->{done_timer};
277 _done_for_now($self);
279 my $cb = sub { # called by PublicInbox::DirIdle::event_step
280 _try_path($self, $_[0]->fullname);
281 $self->{done_timer} //= PublicInbox::DS::requeue($done);
283 require PublicInbox::DirIdle;
284 # inotify_create + EPOLL_CTL_ADD
285 my $dir_idle = PublicInbox::DirIdle->new($cb);
286 $dir_idle->add_watches([keys %{$self->{mdmap}}]);
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 return if $self->{quit};
334 unless ($mic->idle) {
335 return if $self->{quit};
336 return "E: IDLE failed on $uri: $!";
338 $self->{idle_mic} = $mic; # for ->quit
340 until ($self->{quit} || !$mic->IsConnected ||
341 grep(/^\* [0-9]+ EXISTS/, @res) || $i <= 0) {
342 @res = $mic->idle_data($i);
345 delete $self->{idle_mic};
346 unless ($self->{quit}) {
347 $mic->IsConnected or return "E: IDLE disconnected on $uri";
348 $mic->done or return "E: IDLE DONE failed on $uri: $!";
353 # idles on a single URI
354 sub watch_imap_idle_1 ($$$) {
355 my ($self, $uri, $intvl) = @_;
356 my $sec = uri_section($uri);
357 my $mic_arg = $self->{net_arg}->{$sec} or
358 die "BUG: no Mail::IMAPClient->new arg for $sec";
360 local $0 = $uri->mailbox." $sec";
361 until ($self->{quit}) {
362 $mic //= PublicInbox::NetReader::mic_new(
363 $self, $mic_arg, $sec, $uri);
365 if ($mic && $mic->IsConnected) {
366 local $self->{mics_cached}->{$sec} = $mic;
367 my $m = imap_fetch_all($self, $uri);
368 $m == $mic or die "BUG: wrong mic";
369 $mic->IsConnected and
370 $err = imap_idle_once($self, $mic, $intvl, $uri)
372 $err = "E: not connected: $!";
374 if ($err && !$self->{quit}) {
377 sleep 60 unless $self->{quit};
382 sub watch_atfork_child ($) {
384 delete $self->{idle_pids};
385 delete $self->{poll_pids};
386 delete $self->{opendirs};
387 PublicInbox::DS->Reset;
388 my $sig = delete $self->{sig};
389 $sig->{CHLD} = 'DEFAULT';
390 @SIG{keys %$sig} = values %$sig;
391 PublicInbox::DS::sig_setmask($self->{oldset});
394 sub watch_atfork_parent ($) { _done_for_now($_[0]) }
396 sub imap_idle_requeue { # DS::add_timer callback
397 my ($self, $uri_intvl) = @_;
398 return if $self->{quit};
399 push @{$self->{idle_todo}}, $uri_intvl;
403 sub imap_idle_reap { # PublicInbox::DS::dwaitpid callback
404 my ($self, $pid) = @_;
405 my $uri_intvl = delete $self->{idle_pids}->{$pid} or
406 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
408 my ($uri, $intvl) = @$uri_intvl;
409 return if $self->{quit};
410 warn "W: PID=$pid on $uri died: \$?=$?\n" if $?;
411 add_timer(60, \&imap_idle_requeue, $self, $uri_intvl);
414 sub reap { # callback for EOFpipe
415 my ($pid, $cb, $self) = @{$_[0]};
416 my $ret = waitpid($pid, 0);
418 $cb->($self, $pid); # poll_fetch_reap || imap_idle_reap
420 warn "W: waitpid($pid) => ", $ret // "($!)", "\n";
424 sub imap_idle_fork ($$) {
425 my ($self, $uri_intvl) = @_;
426 my ($uri, $intvl) = @$uri_intvl;
427 pipe(my ($r, $w)) or die "pipe: $!";
428 my $seed = rand(0xffffffff);
429 my $pid = fork // die "fork: $!";
432 eval { Net::SSLeay::randomize() };
434 watch_atfork_child($self);
435 watch_imap_idle_1($self, $uri, $intvl);
439 $self->{idle_pids}->{$pid} = $uri_intvl;
440 PublicInbox::EOFpipe->new($r, \&reap, [$pid, \&imap_idle_reap, $self]);
445 return if $self->{quit};
446 my $idle_todo = $self->{idle_todo};
447 if ($idle_todo && @$idle_todo) {
448 watch_atfork_parent($self);
450 while (my $uri_intvl = shift(@$idle_todo)) {
451 imap_idle_fork($self, $uri_intvl);
456 fs_scan_step($self) if $self->{mdre};
459 sub watch_imap_fetch_all ($$) {
460 my ($self, $uris) = @_;
461 for my $uri (@$uris) {
462 imap_fetch_all($self, $uri);
463 last if $self->{quit};
467 sub watch_nntp_fetch_all ($$) {
468 my ($self, $uris) = @_;
469 $self->{incremental} = 1;
470 $self->{on_commit} = [ \&_done_for_now, $self ];
471 my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
472 local $self->{cur_uid};
474 local $SIG{__WARN__} = sub {
475 my $pfx = ($_[0] // '') =~ /^([A-Z]: |# )/g ? $1 : '';
476 my $art = $self->{cur_uid};
477 $warn_cb->("$pfx$uri", $art ? ("ARTICLE $art") : (), "\n", @_);
480 PublicInbox::NetReader::nntp_each($self, $uri, \&net_cb, $self,
481 $self->{nntp}->{$$uri});
482 last if $self->{quit};
486 sub poll_fetch_fork { # DS::add_timer callback
487 my ($self, $intvl, $uris) = @_;
488 return if $self->{quit};
489 pipe(my ($r, $w)) or die "pipe: $!";
490 watch_atfork_parent($self);
491 my $seed = rand(0xffffffff);
493 if (defined($pid) && $pid == 0) {
495 eval { Net::SSLeay::randomize() };
497 watch_atfork_child($self);
498 if ($uris->[0]->scheme =~ m!\Aimaps?!i) {
499 watch_imap_fetch_all($self, $uris);
501 watch_nntp_fetch_all($self, $uris);
506 die "fork: $!" unless defined $pid;
507 $self->{poll_pids}->{$pid} = [ $intvl, $uris ];
508 PublicInbox::EOFpipe->new($r, \&reap, [$pid, \&poll_fetch_reap, $self]);
511 sub poll_fetch_reap {
512 my ($self, $pid) = @_;
513 my $intvl_uris = delete $self->{poll_pids}->{$pid} or
514 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
515 return if $self->{quit};
516 my ($intvl, $uris) = @$intvl_uris;
518 warn "W: PID=$pid died: \$?=$?\n", map { "$_\n" } @$uris;
520 warn("I: will check $_ in ${intvl}s\n") for @$uris;
521 add_timer($intvl, \&poll_fetch_fork, $self, $intvl, $uris);
524 sub watch_imap_init ($$) {
525 my ($self, $poll) = @_;
526 my $mics = PublicInbox::NetReader::imap_common_init($self);
527 my $idle = []; # [ [ uri1, intvl1 ], [uri2, intvl2] ]
528 for my $uri (@{$self->{imap_order}}) {
529 my $sec = uri_section($uri);
530 my $mic = $mics->{$sec};
531 my $intvl = $self->{cfg_opt}->{$sec}->{pollInterval};
532 if ($mic->has_capability('IDLE') && !$intvl) {
533 $intvl = $self->{cfg_opt}->{$sec}->{idleInterval};
534 push @$idle, [ $uri, $intvl // () ];
536 push @{$poll->{$intvl || 120}}, $uri;
540 $self->{idle_todo} = $idle;
541 PublicInbox::DS::requeue($self); # ->event_step to fork
545 sub watch_nntp_init ($$) {
546 my ($self, $poll) = @_;
547 PublicInbox::NetReader::nntp_common_init($self);
548 for my $uri (@{$self->{nntp_order}}) {
549 my $sec = uri_section($uri);
550 my $intvl = $self->{cfg_opt}->{$sec}->{pollInterval};
551 push @{$poll->{$intvl || 120}}, $uri;
555 sub watch { # main entry point
556 my ($self, $sig, $oldset) = @_;
557 $self->{oldset} = $oldset;
559 my $poll = {}; # intvl_seconds => [ uri1, uri2 ]
560 watch_imap_init($self, $poll) if $self->{imap};
561 watch_nntp_init($self, $poll) if $self->{nntp};
562 while (my ($intvl, $uris) = each %$poll) {
563 # poll all URIs for a given interval sequentially
564 add_timer(0, \&poll_fetch_fork, $self, $intvl, $uris);
566 watch_fs_init($self) if $self->{mdre};
567 PublicInbox::DS->SetPostLoopCallback(sub { !$self->quit_done });
568 PublicInbox::DS::event_loop($sig, $oldset); # calls ->event_step
569 _done_for_now($self);
573 my ($self, $op) = @_;
574 push @{$self->{ops}}, $op;
575 PublicInbox::DS::requeue($self);
580 return if $self->{quit};
581 my $op = shift @{$self->{ops}};
582 local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
584 # continue existing scan
585 my $opendirs = $self->{opendirs};
586 my @dirnames = keys %$opendirs;
587 foreach my $dir (@dirnames) {
588 my $dh = delete $opendirs->{$dir};
589 my $n = $self->{max_batch};
590 while (my $fn = readdir($dh)) {
591 _try_path($self, "$dir/$fn");
594 $opendirs->{$dir} = $dh if $n < 0;
596 if ($op && $op eq 'full') {
597 foreach my $dir (keys %{$self->{mdmap}}) {
598 next if $opendirs->{$dir}; # already in progress
599 my $ok = opendir(my $dh, $dir);
601 warn "failed to open $dir: $!\n";
604 my $n = $self->{max_batch};
605 while (my $fn = readdir($dh)) {
606 _try_path($self, "$dir/$fn");
609 $opendirs->{$dir} = $dh if $n < 0;
612 _done_for_now($self);
613 # do we have more work to do?
614 PublicInbox::DS::requeue($self) if keys %$opendirs;
618 my ($self, $op) = @_;
619 push @{$self->{ops}}, $op;
624 my ($self, $ibx) = @_;
625 my $importers = $self->{importers};
626 my $im = $importers->{"$ibx"} ||= $ibx->importer(0);
627 if (scalar(keys(%$importers)) > 2) {
628 delete $importers->{"$ibx"};
629 _done_for_now($self);
632 $importers->{"$ibx"} = $im;
635 # XXX consider sharing with V2Writable, this only requires read-only access
636 sub content_exists ($$) {
637 my ($ibx, $eml) = @_;
638 my $over = $ibx->over or return;
639 my $mids = mids($eml);
640 my $chash = content_hash($eml);
642 for my $mid (@$mids) {
643 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
644 my $cmp = $ibx->smsg_eml($smsg) or return;
645 return 1 if $chash eq content_hash($cmp);
653 sub { # this gets called by (V2Writable||Import)->add
654 my ($mime, $ibx) = @_;
655 return if content_exists($ibx, $mime);
657 if ($sc->spamcheck($mime, \$tmp)) {
658 return PublicInbox::Eml->new(\$tmp);
660 warn $mime->header('Message-ID')." failed spam check\n";
666 $_[0] =~ s!\Amaildir:!! or return;
673 my ($cur, $ws, $ibx) = @_;
674 if ($ws && !ref($ws) && $ws eq 'watchspam') {
676 E: $cur is a spam folder and cannot be used for `$ibx->{name}' input
683 sub folder_select { 'select' } # for PublicInbox::NetReader