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
246 my $live = grep { kill('QUIT', $_) } keys %{$self->{pids}};
247 add_timer(0.01, \&quit_done, $self) if $live;
254 %{$self->{opendirs}} = ();
255 _done_for_now($self);
257 if (my $idle_mic = $self->{idle_mic}) {
258 eval { $idle_mic->done };
260 warn "IDLE DONE error: $@\n";
261 eval { $idle_mic->disconnect };
262 warn "IDLE LOGOUT error: $@\n" if $@;
267 sub watch_fs_init ($) {
270 delete $self->{done_timer};
271 _done_for_now($self);
273 my $cb = sub { # called by PublicInbox::DirIdle::event_step
274 _try_path($self, $_[0]->fullname);
275 $self->{done_timer} //= PublicInbox::DS::requeue($done);
277 require PublicInbox::DirIdle;
278 # inotify_create + EPOLL_CTL_ADD
279 my $dir_idle = PublicInbox::DirIdle->new($cb);
280 $dir_idle->add_watches([keys %{$self->{mdmap}}]);
283 sub net_cb { # NetReader::(nntp|imap)_each callback
284 my ($uri, $art, $kw, $eml, $self, $inboxes) = @_;
285 return if grep(/\Adraft\z/, @$kw);
286 local $self->{cur_uid} = $art; # IMAP UID or NNTP article
291 my $tmp = PublicInbox::Eml->new(\($eml->as_string));
292 import_eml($self, $ibx, $tmp);
294 import_eml($self, $last, $eml);
295 } elsif ($inboxes eq 'watchspam') {
296 if ($uri->scheme =~ /\Aimaps?\z/ && !grep(/\Aseen\z/, @$kw)) {
299 $self->{pi_cfg}->each_inbox(\&remove_eml_i,
300 $self, $eml, "$uri #$art");
302 die "BUG: destination unknown $inboxes";
306 sub imap_fetch_all ($$) {
307 my ($self, $uri) = @_;
308 my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
309 $self->{incremental} = 1;
310 $self->{on_commit} = [ \&_done_for_now, $self ];
311 local $self->{cur_uid};
312 local $SIG{__WARN__} = sub {
313 my $pfx = ($_[0] // '') =~ /^([A-Z]: |# )/g ? $1 : '';
314 my $uid = $self->{cur_uid};
315 $warn_cb->("$pfx$uri", $uid ? ("UID:$uid") : (), "\n", @_);
317 PublicInbox::NetReader::imap_each($self, $uri, \&net_cb, $self,
318 $self->{imap}->{$$uri});
321 sub imap_idle_once ($$$$) {
322 my ($self, $mic, $intvl, $uri) = @_;
323 my $i = $intvl //= (29 * 60);
324 my $end = now() + $intvl;
325 warn "# $uri idling for ${intvl}s\n";
326 local $0 = "IDLE $0";
327 return if $self->{quit};
328 unless ($mic->idle) {
329 return if $self->{quit};
330 return "E: IDLE failed on $uri: $!";
332 $self->{idle_mic} = $mic; # for ->quit
334 until ($self->{quit} || !$mic->IsConnected ||
335 grep(/^\* [0-9]+ EXISTS/, @res) || $i <= 0) {
336 @res = $mic->idle_data($i);
339 delete $self->{idle_mic};
340 unless ($self->{quit}) {
341 $mic->IsConnected or return "E: IDLE disconnected on $uri";
342 $mic->done or return "E: IDLE DONE failed on $uri: $!";
347 # idles on a single URI
348 sub watch_imap_idle_1 ($$$) {
349 my ($self, $uri, $intvl) = @_;
350 my $sec = uri_section($uri);
351 my $mic_arg = $self->{net_arg}->{$sec} or
352 die "BUG: no Mail::IMAPClient->new arg for $sec";
354 local $0 = $uri->mailbox." $sec";
355 until ($self->{quit}) {
356 $mic //= PublicInbox::NetReader::mic_new(
357 $self, $mic_arg, $sec, $uri);
359 if ($mic && $mic->IsConnected) {
360 local $self->{mics_cached}->{$sec} = $mic;
361 my $m = imap_fetch_all($self, $uri);
362 $m == $mic or die "BUG: wrong mic";
363 $mic->IsConnected and
364 $err = imap_idle_once($self, $mic, $intvl, $uri)
366 $err = "E: not connected: $!";
368 if ($err && !$self->{quit}) {
371 sleep 60 unless $self->{quit};
376 sub watch_atfork_child ($) {
378 delete $self->{pids};
379 delete $self->{opendirs};
380 PublicInbox::DS->Reset;
381 my $sig = delete $self->{sig};
382 $sig->{CHLD} = 'DEFAULT';
383 @SIG{keys %$sig} = values %$sig;
384 PublicInbox::DS::sig_setmask($self->{oldset});
387 sub watch_atfork_parent ($) { _done_for_now($_[0]) }
389 sub imap_idle_requeue { # DS::add_timer callback
390 my ($self, $uri, $intvl) = @_;
391 return if $self->{quit};
392 push @{$self->{idle_todo}}, $uri, $intvl;
396 sub imap_idle_reap { # awaitpid callback
397 my ($pid, $self, $uri, $intvl) = @_;
398 delete $self->{pids}->{$pid};
399 return if $self->{quit};
400 warn "W: PID=$pid on $uri died: \$?=$?\n" if $?;
401 add_timer(60, \&imap_idle_requeue, $self, $uri, $intvl);
405 my ($self, $uri, $intvl) = @_;
406 return if $self->{quit};
407 my $seed = rand(0xffffffff);
408 my $pid = fork // die "fork: $!";
411 eval { Net::SSLeay::randomize() };
412 watch_atfork_child($self);
413 watch_imap_idle_1($self, $uri, $intvl);
416 $self->{pids}->{$pid} = undef;
417 awaitpid($pid, \&imap_idle_reap, $self, $uri, $intvl);
422 return if $self->{quit};
423 my $idle_todo = $self->{idle_todo};
424 if ($idle_todo && @$idle_todo) {
425 watch_atfork_parent($self);
427 while (my ($uri, $intvl) = splice(@$idle_todo, 0, 2)) {
428 imap_idle_fork($self, $uri, $intvl);
433 fs_scan_step($self) if $self->{mdre};
436 sub watch_imap_fetch_all ($$) {
437 my ($self, $uris) = @_;
438 for my $uri (@$uris) {
439 imap_fetch_all($self, $uri);
440 last if $self->{quit};
444 sub watch_nntp_fetch_all ($$) {
445 my ($self, $uris) = @_;
446 $self->{incremental} = 1;
447 $self->{on_commit} = [ \&_done_for_now, $self ];
448 my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
449 local $self->{cur_uid};
451 local $SIG{__WARN__} = sub {
452 my $pfx = ($_[0] // '') =~ /^([A-Z]: |# )/g ? $1 : '';
453 my $art = $self->{cur_uid};
454 $warn_cb->("$pfx$uri", $art ? ("ARTICLE $art") : (), "\n", @_);
457 PublicInbox::NetReader::nntp_each($self, $uri, \&net_cb, $self,
458 $self->{nntp}->{$$uri});
459 last if $self->{quit};
463 sub poll_fetch_fork { # DS::add_timer callback
464 my ($self, $intvl, $uris) = @_;
465 return if $self->{quit};
466 watch_atfork_parent($self);
468 my @imap = grep { # push() always returns > 0
469 $_->scheme =~ m!\Aimaps?!i ? 1 : (push(@nntp, $_) < 0)
471 my $seed = rand(0xffffffff);
472 my $pid = fork // die "fork: $!";
475 eval { Net::SSLeay::randomize() };
476 watch_atfork_child($self);
477 watch_imap_fetch_all($self, \@imap) if @imap;
478 watch_nntp_fetch_all($self, \@nntp) if @nntp;
481 $self->{pids}->{$pid} = undef;
482 awaitpid($pid, \&poll_fetch_reap, $self, $intvl, $uris);
485 sub poll_fetch_reap { # awaitpid callback
486 my ($pid, $self, $intvl, $uris) = @_;
487 delete $self->{pids}->{$pid};
488 return if $self->{quit};
490 warn "W: PID=$pid died: \$?=$?\n", map { "$_\n" } @$uris;
492 warn("# will check $_ in ${intvl}s\n") for @$uris;
493 add_timer($intvl, \&poll_fetch_fork, $self, $intvl, $uris);
496 sub watch_imap_init ($$) {
497 my ($self, $poll) = @_;
498 my $mics = PublicInbox::NetReader::imap_common_init($self);
499 my $idle = []; # [ uri1, intvl1, uri2, intvl2 ]
500 for my $uri (@{$self->{imap_order}}) {
501 my $sec = uri_section($uri);
502 my $mic = $mics->{$sec};
503 my $intvl = $self->{cfg_opt}->{$sec}->{pollInterval};
504 if ($mic->has_capability('IDLE') && !$intvl) {
505 $intvl = $self->{cfg_opt}->{$sec}->{idleInterval};
506 push @$idle, $uri, $intvl;
508 push @{$poll->{$intvl || 120}}, $uri;
512 $self->{idle_todo} = $idle;
513 PublicInbox::DS::requeue($self); # ->event_step to fork
517 sub watch_nntp_init ($$) {
518 my ($self, $poll) = @_;
519 PublicInbox::NetReader::nntp_common_init($self);
520 for my $uri (@{$self->{nntp_order}}) {
521 my $sec = uri_section($uri);
522 my $intvl = $self->{cfg_opt}->{$sec}->{pollInterval};
523 push @{$poll->{$intvl || 120}}, $uri;
527 sub watch { # main entry point
528 my ($self, $sig, $oldset) = @_;
529 $self->{oldset} = $oldset;
531 my $poll = {}; # intvl_seconds => [ uri1, uri2 ]
532 watch_imap_init($self, $poll) if $self->{imap};
533 watch_nntp_init($self, $poll) if $self->{nntp};
534 while (my ($intvl, $uris) = each %$poll) {
535 # poll all URIs for a given interval sequentially
536 add_timer(0, \&poll_fetch_fork, $self, $intvl, $uris);
538 watch_fs_init($self) if $self->{mdre};
539 PublicInbox::DS->SetPostLoopCallback(sub { !$self->quit_done });
540 PublicInbox::DS::event_loop($sig, $oldset); # calls ->event_step
541 _done_for_now($self);
545 my ($self, $op) = @_;
546 push @{$self->{ops}}, $op;
547 PublicInbox::DS::requeue($self);
552 return if $self->{quit};
553 my $op = shift @{$self->{ops}};
554 local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
556 # continue existing scan
557 my $opendirs = $self->{opendirs};
558 my @dirnames = keys %$opendirs;
559 foreach my $dir (@dirnames) {
560 my $dh = delete $opendirs->{$dir};
561 my $n = $self->{max_batch};
562 while (my $fn = readdir($dh)) {
563 _try_path($self, "$dir/$fn");
566 $opendirs->{$dir} = $dh if $n < 0;
568 if ($op && $op eq 'full') {
569 foreach my $dir (keys %{$self->{mdmap}}) {
570 next if $opendirs->{$dir}; # already in progress
571 my $ok = opendir(my $dh, $dir);
573 warn "failed to open $dir: $!\n";
576 my $n = $self->{max_batch};
577 while (my $fn = readdir($dh)) {
578 _try_path($self, "$dir/$fn");
581 $opendirs->{$dir} = $dh if $n < 0;
584 _done_for_now($self);
585 # do we have more work to do?
586 PublicInbox::DS::requeue($self) if keys %$opendirs;
590 my ($self, $op) = @_;
591 push @{$self->{ops}}, $op;
596 my ($self, $ibx) = @_;
597 my $importers = $self->{importers};
598 my $im = $importers->{"$ibx"} ||= $ibx->importer(0);
599 if (scalar(keys(%$importers)) > 2) {
600 delete $importers->{"$ibx"};
601 _done_for_now($self);
604 $importers->{"$ibx"} = $im;
607 # XXX consider sharing with V2Writable, this only requires read-only access
608 sub content_exists ($$) {
609 my ($ibx, $eml) = @_;
610 my $over = $ibx->over or return;
611 my $mids = mids($eml);
612 my $chash = content_hash($eml);
614 for my $mid (@$mids) {
615 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
616 my $cmp = $ibx->smsg_eml($smsg) or return;
617 return 1 if $chash eq content_hash($cmp);
625 sub { # this gets called by (V2Writable||Import)->add
626 my ($mime, $ibx) = @_;
627 return if content_exists($ibx, $mime);
629 if ($sc->spamcheck($mime, \$tmp)) {
630 return PublicInbox::Eml->new(\$tmp);
632 warn $mime->header('Message-ID')." failed spam check\n";
638 $_[0] =~ s!\Amaildir:!! or return;
645 my ($cur, $ws, $ibx) = @_;
646 if ($ws && !ref($ws) && $ws eq 'watchspam') {
648 E: $cur is a spam folder and cannot be used for `$ibx->{name}' input
655 sub folder_select { 'select' } # for PublicInbox::NetReader