1 # Copyright (C) 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 awaitpid);
16 use PublicInbox::MID qw(mids);
17 use PublicInbox::ContentHash qw(content_hash);
18 use POSIX qw(_exit WNOHANG);
20 sub compile_watchheaders ($) {
23 if (my $whs = $ibx->{watchheader}) {
25 my ($k, $v) = split(/:/, $_, 2);
26 # XXX should this be case-insensitive?
27 # Or, mutt-style, case-sensitive iff
28 # a capital letter exists?
29 push @$watch_hdrs, [ $k, qr/\Q$v\E/ ];
32 if (my $list_ids = $ibx->{listid}) {
34 # RFC2919 section 6 stipulates
35 # "case insensitive equality"
36 my $re = qr/<[ \t]*\Q$_\E[ \t]*>/i;
37 push @$watch_hdrs, ['List-Id', $re ];
40 $ibx->{-watchheaders} = $watch_hdrs if scalar @$watch_hdrs;
44 my ($class, $cfg) = @_;
46 my (%imap, %nntp); # url => [inbox objects] or 'watchspam'
49 # "publicinboxwatch" is the documented namespace
50 # "publicinboxlearn" is legacy but may be supported
52 foreach my $pfx (qw(publicinboxwatch publicinboxlearn)) {
53 my $k = "$pfx.watchspam";
54 my $dirs = $cfg->get_all($k) // next;
55 for my $dir (@$dirs) {
57 if (is_maildir($dir)) {
58 # skip "new", no MUA has seen it, yet.
59 $mdmap{"$dir/cur"} = 'watchspam';
60 } elsif ($uri = imap_uri($dir)) {
61 $imap{$$uri} = 'watchspam';
63 } elsif ($uri = nntp_uri($dir)) {
64 $nntp{$$uri} = 'watchspam';
67 warn "unsupported $k=$dir\n";
72 my $k = 'publicinboxwatch.spamcheck';
74 my $spamcheck = PublicInbox::Spamcheck::get($cfg, $k, $default);
75 $spamcheck = _spamcheck_cb($spamcheck) if $spamcheck;
77 $cfg->each_inbox(sub {
78 # need to make all inboxes writable for spam removal:
79 my $ibx = $_[0] = PublicInbox::InboxWritable->new($_[0]);
81 my $watches = $ibx->{watch} or return;
82 $watches = PublicInbox::Config::_array($watches);
83 for my $watch (@$watches) {
85 if (is_maildir($watch)) {
86 compile_watchheaders($ibx);
87 my ($new, $cur) = ("$watch/new", "$watch/cur");
88 my $cur_dst = $mdmap{$cur} //= [];
89 return if is_watchspam($cur, $cur_dst, $ibx);
90 push @{$mdmap{$new} //= []}, $ibx;
92 } elsif ($uri = imap_uri($watch)) {
93 my $cur_dst = $imap{$$uri} //= [];
94 return if is_watchspam($uri, $cur_dst, $ibx);
95 compile_watchheaders($ibx);
96 push(@imap, $uri) if 1 == push(@$cur_dst, $ibx);
97 } elsif ($uri = nntp_uri($watch)) {
98 my $cur_dst = $nntp{$$uri} //= [];
99 return if is_watchspam($uri, $cur_dst, $ibx);
100 compile_watchheaders($ibx);
101 push(@nntp, $uri) if 1 == push(@$cur_dst, $ibx);
103 warn "watch unsupported: $k=$watch\n";
109 if (scalar keys %mdmap) {
110 $mdre = join('|', map { quotemeta($_) } keys %mdmap);
111 $mdre = qr!\A($mdre)/!;
113 return unless $mdre || scalar(keys %imap) || scalar(keys %nntp);
116 max_batch => 10, # avoid hogging locks for too long
117 spamcheck => $spamcheck,
121 imap => scalar keys %imap ? \%imap : undef,
122 nntp => scalar keys %nntp? \%nntp : undef,
123 imap_order => scalar(@imap) ? \@imap : undef,
124 nntp_order => scalar(@nntp) ? \@nntp: undef,
126 opendirs => {}, # dirname => dirhandle (in progress scans)
127 ops => [], # 'quit', 'full'
133 local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
134 for my $im (values %{$self->{importers}}) {
135 next if !$im; # $im may be undef during cleanup
137 warn "$im->{ibx}->{name} ->done: $@\n" if $@;
141 sub remove_eml_i { # each_inbox callback
142 my ($ibx, $self, $eml, $loc) = @_;
145 # try to avoid taking a lock or unnecessary spawning
146 my $im = $self->{importers}->{"$ibx"};
148 if ((!$im || !$im->active) && $ibx->over) {
149 if (content_exists($ibx, $eml)) {
151 } elsif (my $scrub = $ibx->filter($im)) {
152 $scrubbed = $scrub->scrub($eml, 1);
153 if ($scrubbed && $scrubbed != REJECT &&
154 !content_exists($ibx, $scrubbed)) {
162 $im //= _importer_for($self, $ibx); # may spawn fast-import
163 $im->remove($eml, 'spam');
165 my $scrub = $ibx->filter($im);
166 $scrub ? $scrub->scrub($eml, 1) : undef;
168 if ($scrubbed && $scrubbed != REJECT) {
169 $im->remove($scrubbed, 'spam');
173 warn "error removing spam at: $loc from $ibx->{name}: $@\n";
174 _done_for_now($self);
179 my ($self, $path) = @_;
180 # path must be marked as (S)een
181 $path =~ /:2,[A-R]*S[T-Za-z]*\z/ or return;
182 my $eml = eml_from_path($path) or return;
183 local $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
184 $self->{pi_cfg}->each_inbox(\&remove_eml_i, $self, $eml, $path);
187 sub import_eml ($$$) {
188 my ($self, $ibx, $eml) = @_;
190 # any header match means it's eligible for the inbox:
191 if (my $watch_hdrs = $ibx->{-watchheaders}) {
193 for my $wh (@$watch_hdrs) {
194 my @v = $eml->header_raw($wh->[0]);
195 $ok = grep(/$wh->[1]/, @v) and last;
200 my $im = _importer_for($self, $ibx);
201 if (my $scrub = $ibx->filter($im)) {
202 my $scrubbed = $scrub->scrub($eml) or return;
203 $scrubbed == REJECT and return;
206 $im->add($eml, $self->{spamcheck});
209 warn "$ibx->{name} add failed: $@\n";
210 _done_for_now($self);
215 my ($self, $path) = @_;
216 my $fl = PublicInbox::MdirReader::maildir_path_flags($path) // return;
217 return if $fl =~ /[DT]/; # no Drafts or Trash
218 if ($path !~ $self->{mdre}) {
219 warn "unrecognized path: $path\n";
222 my $inboxes = $self->{mdmap}->{$1};
224 warn "unmappable dir: $1\n";
227 my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
228 local $SIG{__WARN__} = sub {
229 my $pfx = ($_[0] // '') =~ /^([A-Z]: )/g ? $1 : '';
230 $warn_cb->($pfx, "path: $path\n", @_);
232 if (!ref($inboxes) && $inboxes eq 'watchspam') {
233 return _remove_spam($self, $path);
235 foreach my $ibx (@$inboxes) {
236 my $eml = eml_from_path($path) or next;
237 import_eml($self, $ibx, $eml);
243 return unless $self->{quit};
245 # don't have reliable wakeups, keep signalling
247 for (qw(idle_pids poll_pids)) {
248 my $pids = $self->{$_} or next;
249 $live += grep { kill('QUIT', $_) } keys %$pids;
251 add_timer(0.01, \&quit_done, $self) if $live;
258 %{$self->{opendirs}} = ();
259 _done_for_now($self);
261 if (my $idle_mic = $self->{idle_mic}) {
262 eval { $idle_mic->done };
264 warn "IDLE DONE error: $@\n";
265 eval { $idle_mic->disconnect };
266 warn "IDLE LOGOUT error: $@\n" if $@;
271 sub watch_fs_init ($) {
274 delete $self->{done_timer};
275 _done_for_now($self);
277 my $cb = sub { # called by PublicInbox::DirIdle::event_step
278 _try_path($self, $_[0]->fullname);
279 $self->{done_timer} //= PublicInbox::DS::requeue($done);
281 require PublicInbox::DirIdle;
282 # inotify_create + EPOLL_CTL_ADD
283 my $dir_idle = PublicInbox::DirIdle->new($cb);
284 $dir_idle->add_watches([keys %{$self->{mdmap}}]);
287 sub net_cb { # NetReader::(nntp|imap)_each callback
288 my ($uri, $art, $kw, $eml, $self, $inboxes) = @_;
289 return if grep(/\Adraft\z/, @$kw);
290 local $self->{cur_uid} = $art; # IMAP UID or NNTP article
295 my $tmp = PublicInbox::Eml->new(\($eml->as_string));
296 import_eml($self, $ibx, $tmp);
298 import_eml($self, $last, $eml);
299 } elsif ($inboxes eq 'watchspam') {
300 if ($uri->scheme =~ /\Aimaps?\z/ && !grep(/\Aseen\z/, @$kw)) {
303 $self->{pi_cfg}->each_inbox(\&remove_eml_i,
304 $self, $eml, "$uri #$art");
306 die "BUG: destination unknown $inboxes";
310 sub imap_fetch_all ($$) {
311 my ($self, $uri) = @_;
312 my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
313 $self->{incremental} = 1;
314 $self->{on_commit} = [ \&_done_for_now, $self ];
315 local $self->{cur_uid};
316 local $SIG{__WARN__} = sub {
317 my $pfx = ($_[0] // '') =~ /^([A-Z]: |# )/g ? $1 : '';
318 my $uid = $self->{cur_uid};
319 $warn_cb->("$pfx$uri", $uid ? ("UID:$uid") : (), "\n", @_);
321 PublicInbox::NetReader::imap_each($self, $uri, \&net_cb, $self,
322 $self->{imap}->{$$uri});
325 sub imap_idle_once ($$$$) {
326 my ($self, $mic, $intvl, $uri) = @_;
327 my $i = $intvl //= (29 * 60);
328 my $end = now() + $intvl;
329 warn "# $uri idling for ${intvl}s\n";
330 local $0 = "IDLE $0";
331 return if $self->{quit};
332 unless ($mic->idle) {
333 return if $self->{quit};
334 return "E: IDLE failed on $uri: $!";
336 $self->{idle_mic} = $mic; # for ->quit
338 until ($self->{quit} || !$mic->IsConnected ||
339 grep(/^\* [0-9]+ EXISTS/, @res) || $i <= 0) {
340 @res = $mic->idle_data($i);
343 delete $self->{idle_mic};
344 unless ($self->{quit}) {
345 $mic->IsConnected or return "E: IDLE disconnected on $uri";
346 $mic->done or return "E: IDLE DONE failed on $uri: $!";
351 # idles on a single URI
352 sub watch_imap_idle_1 ($$$) {
353 my ($self, $uri, $intvl) = @_;
354 my $sec = uri_section($uri);
355 my $mic_arg = $self->{net_arg}->{$sec} or
356 die "BUG: no Mail::IMAPClient->new arg for $sec";
358 local $0 = $uri->mailbox." $sec";
359 until ($self->{quit}) {
360 $mic //= PublicInbox::NetReader::mic_new(
361 $self, $mic_arg, $sec, $uri);
363 if ($mic && $mic->IsConnected) {
364 local $self->{mics_cached}->{$sec} = $mic;
365 my $m = imap_fetch_all($self, $uri);
366 $m == $mic or die "BUG: wrong mic";
367 $mic->IsConnected and
368 $err = imap_idle_once($self, $mic, $intvl, $uri)
370 $err = "E: not connected: $!";
372 if ($err && !$self->{quit}) {
375 sleep 60 unless $self->{quit};
380 sub watch_atfork_child ($) {
382 delete $self->{idle_pids};
383 delete $self->{poll_pids};
384 delete $self->{opendirs};
385 PublicInbox::DS->Reset;
386 my $sig = delete $self->{sig};
387 $sig->{CHLD} = 'DEFAULT';
388 @SIG{keys %$sig} = values %$sig;
389 PublicInbox::DS::sig_setmask($self->{oldset});
392 sub watch_atfork_parent ($) { _done_for_now($_[0]) }
394 sub imap_idle_requeue { # DS::add_timer callback
395 my ($self, $uri_intvl) = @_;
396 return if $self->{quit};
397 push @{$self->{idle_todo}}, $uri_intvl;
401 sub imap_idle_reap { # awaitpid callback
402 my ($pid, $self) = @_;
403 my $uri_intvl = delete $self->{idle_pids}->{$pid} or
404 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
406 my ($uri, $intvl) = @$uri_intvl;
407 return if $self->{quit};
408 warn "W: PID=$pid on $uri died: \$?=$?\n" if $?;
409 add_timer(60, \&imap_idle_requeue, $self, $uri_intvl);
412 sub imap_idle_fork ($$) {
413 my ($self, $uri_intvl) = @_;
414 return if $self->{quit};
415 my ($uri, $intvl) = @$uri_intvl;
416 my $seed = rand(0xffffffff);
417 my $pid = fork // die "fork: $!";
420 eval { Net::SSLeay::randomize() };
421 watch_atfork_child($self);
422 watch_imap_idle_1($self, $uri, $intvl);
425 $self->{idle_pids}->{$pid} = $uri_intvl;
426 awaitpid($pid, \&imap_idle_reap, $self);
431 return if $self->{quit};
432 my $idle_todo = $self->{idle_todo};
433 if ($idle_todo && @$idle_todo) {
434 watch_atfork_parent($self);
436 while (my $uri_intvl = shift(@$idle_todo)) {
437 imap_idle_fork($self, $uri_intvl);
442 fs_scan_step($self) if $self->{mdre};
445 sub watch_imap_fetch_all ($$) {
446 my ($self, $uris) = @_;
447 for my $uri (@$uris) {
448 imap_fetch_all($self, $uri);
449 last if $self->{quit};
453 sub watch_nntp_fetch_all ($$) {
454 my ($self, $uris) = @_;
455 $self->{incremental} = 1;
456 $self->{on_commit} = [ \&_done_for_now, $self ];
457 my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
458 local $self->{cur_uid};
460 local $SIG{__WARN__} = sub {
461 my $pfx = ($_[0] // '') =~ /^([A-Z]: |# )/g ? $1 : '';
462 my $art = $self->{cur_uid};
463 $warn_cb->("$pfx$uri", $art ? ("ARTICLE $art") : (), "\n", @_);
466 PublicInbox::NetReader::nntp_each($self, $uri, \&net_cb, $self,
467 $self->{nntp}->{$$uri});
468 last if $self->{quit};
472 sub poll_fetch_fork { # DS::add_timer callback
473 my ($self, $intvl, $uris) = @_;
474 return if $self->{quit};
475 watch_atfork_parent($self);
476 my $seed = rand(0xffffffff);
477 my $pid = fork // die "fork: $!";
480 eval { Net::SSLeay::randomize() };
481 watch_atfork_child($self);
482 if ($uris->[0]->scheme =~ m!\Aimaps?!i) {
483 watch_imap_fetch_all($self, $uris);
485 watch_nntp_fetch_all($self, $uris);
489 $self->{poll_pids}->{$pid} = [ $intvl, $uris ];
490 awaitpid($pid, \&poll_fetch_reap, $self);
493 sub poll_fetch_reap { # awaitpid callback
494 my ($pid, $self) = @_;
495 my $intvl_uris = delete $self->{poll_pids}->{$pid} or
496 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
497 return if $self->{quit};
498 my ($intvl, $uris) = @$intvl_uris;
500 warn "W: PID=$pid died: \$?=$?\n", map { "$_\n" } @$uris;
502 warn("# will check $_ in ${intvl}s\n") for @$uris;
503 add_timer($intvl, \&poll_fetch_fork, $self, $intvl, $uris);
506 sub watch_imap_init ($$) {
507 my ($self, $poll) = @_;
508 my $mics = PublicInbox::NetReader::imap_common_init($self);
509 my $idle = []; # [ [ uri1, intvl1 ], [uri2, intvl2] ]
510 for my $uri (@{$self->{imap_order}}) {
511 my $sec = uri_section($uri);
512 my $mic = $mics->{$sec};
513 my $intvl = $self->{cfg_opt}->{$sec}->{pollInterval};
514 if ($mic->has_capability('IDLE') && !$intvl) {
515 $intvl = $self->{cfg_opt}->{$sec}->{idleInterval};
516 push @$idle, [ $uri, $intvl // () ];
518 push @{$poll->{$intvl || 120}}, $uri;
522 $self->{idle_todo} = $idle;
523 PublicInbox::DS::requeue($self); # ->event_step to fork
527 sub watch_nntp_init ($$) {
528 my ($self, $poll) = @_;
529 PublicInbox::NetReader::nntp_common_init($self);
530 for my $uri (@{$self->{nntp_order}}) {
531 my $sec = uri_section($uri);
532 my $intvl = $self->{cfg_opt}->{$sec}->{pollInterval};
533 push @{$poll->{$intvl || 120}}, $uri;
537 sub watch { # main entry point
538 my ($self, $sig, $oldset) = @_;
539 $self->{oldset} = $oldset;
541 my $poll = {}; # intvl_seconds => [ uri1, uri2 ]
542 watch_imap_init($self, $poll) if $self->{imap};
543 watch_nntp_init($self, $poll) if $self->{nntp};
544 while (my ($intvl, $uris) = each %$poll) {
545 # poll all URIs for a given interval sequentially
546 add_timer(0, \&poll_fetch_fork, $self, $intvl, $uris);
548 watch_fs_init($self) if $self->{mdre};
549 PublicInbox::DS->SetPostLoopCallback(sub { !$self->quit_done });
550 PublicInbox::DS::event_loop($sig, $oldset); # calls ->event_step
551 _done_for_now($self);
555 my ($self, $op) = @_;
556 push @{$self->{ops}}, $op;
557 PublicInbox::DS::requeue($self);
562 return if $self->{quit};
563 my $op = shift @{$self->{ops}};
564 local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
566 # continue existing scan
567 my $opendirs = $self->{opendirs};
568 my @dirnames = keys %$opendirs;
569 foreach my $dir (@dirnames) {
570 my $dh = delete $opendirs->{$dir};
571 my $n = $self->{max_batch};
572 while (my $fn = readdir($dh)) {
573 _try_path($self, "$dir/$fn");
576 $opendirs->{$dir} = $dh if $n < 0;
578 if ($op && $op eq 'full') {
579 foreach my $dir (keys %{$self->{mdmap}}) {
580 next if $opendirs->{$dir}; # already in progress
581 my $ok = opendir(my $dh, $dir);
583 warn "failed to open $dir: $!\n";
586 my $n = $self->{max_batch};
587 while (my $fn = readdir($dh)) {
588 _try_path($self, "$dir/$fn");
591 $opendirs->{$dir} = $dh if $n < 0;
594 _done_for_now($self);
595 # do we have more work to do?
596 PublicInbox::DS::requeue($self) if keys %$opendirs;
600 my ($self, $op) = @_;
601 push @{$self->{ops}}, $op;
606 my ($self, $ibx) = @_;
607 my $importers = $self->{importers};
608 my $im = $importers->{"$ibx"} ||= $ibx->importer(0);
609 if (scalar(keys(%$importers)) > 2) {
610 delete $importers->{"$ibx"};
611 _done_for_now($self);
614 $importers->{"$ibx"} = $im;
617 # XXX consider sharing with V2Writable, this only requires read-only access
618 sub content_exists ($$) {
619 my ($ibx, $eml) = @_;
620 my $over = $ibx->over or return;
621 my $mids = mids($eml);
622 my $chash = content_hash($eml);
624 for my $mid (@$mids) {
625 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
626 my $cmp = $ibx->smsg_eml($smsg) or return;
627 return 1 if $chash eq content_hash($cmp);
635 sub { # this gets called by (V2Writable||Import)->add
636 my ($mime, $ibx) = @_;
637 return if content_exists($ibx, $mime);
639 if ($sc->spamcheck($mime, \$tmp)) {
640 return PublicInbox::Eml->new(\$tmp);
642 warn $mime->header('Message-ID')." failed spam check\n";
648 $_[0] =~ s!\Amaildir:!! or return;
655 my ($cur, $ws, $ibx) = @_;
656 if ($ws && !ref($ws) && $ws eq 'watchspam') {
658 E: $cur is a spam folder and cannot be used for `$ibx->{name}' input
665 sub folder_select { 'select' } # for PublicInbox::NetReader