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 # httsp://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 defined(my $dirs = $cfg->{$k}) or next;
57 $dirs = PublicInbox::Config::_array($dirs);
58 for my $dir (@$dirs) {
60 if (is_maildir($dir)) {
61 # skip "new", no MUA has seen it, yet.
62 $mdmap{"$dir/cur"} = 'watchspam';
63 } elsif ($uri = imap_uri($dir)) {
64 $imap{$$uri} = 'watchspam';
66 } elsif ($uri = nntp_uri($dir)) {
67 $nntp{$$uri} = 'watchspam';
70 warn "unsupported $k=$dir\n";
75 my $k = 'publicinboxwatch.spamcheck';
77 my $spamcheck = PublicInbox::Spamcheck::get($cfg, $k, $default);
78 $spamcheck = _spamcheck_cb($spamcheck) if $spamcheck;
80 $cfg->each_inbox(sub {
81 # need to make all inboxes writable for spam removal:
82 my $ibx = $_[0] = PublicInbox::InboxWritable->new($_[0]);
84 my $watches = $ibx->{watch} or return;
85 $watches = PublicInbox::Config::_array($watches);
86 for my $watch (@$watches) {
88 if (is_maildir($watch)) {
89 compile_watchheaders($ibx);
90 my ($new, $cur) = ("$watch/new", "$watch/cur");
91 my $cur_dst = $mdmap{$cur} //= [];
92 return if is_watchspam($cur, $cur_dst, $ibx);
93 push @{$mdmap{$new} //= []}, $ibx;
95 } elsif ($uri = imap_uri($watch)) {
96 my $cur_dst = $imap{$$uri} //= [];
97 return if is_watchspam($uri, $cur_dst, $ibx);
98 compile_watchheaders($ibx);
99 push(@imap, $uri) if 1 == push(@$cur_dst, $ibx);
100 } elsif ($uri = nntp_uri($watch)) {
101 my $cur_dst = $nntp{$$uri} //= [];
102 return if is_watchspam($uri, $cur_dst, $ibx);
103 compile_watchheaders($ibx);
104 push(@nntp, $uri) if 1 == push(@$cur_dst, $ibx);
106 warn "watch unsupported: $k=$watch\n";
112 if (scalar keys %mdmap) {
113 $mdre = join('|', map { quotemeta($_) } keys %mdmap);
114 $mdre = qr!\A($mdre)/!;
116 return unless $mdre || scalar(keys %imap) || scalar(keys %nntp);
119 max_batch => 10, # avoid hogging locks for too long
120 spamcheck => $spamcheck,
124 imap => scalar keys %imap ? \%imap : undef,
125 nntp => scalar keys %nntp? \%nntp : undef,
126 imap_order => scalar(@imap) ? \@imap : undef,
127 nntp_order => scalar(@nntp) ? \@nntp: undef,
129 opendirs => {}, # dirname => dirhandle (in progress scans)
130 ops => [], # 'quit', 'full'
136 local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
137 for my $im (values %{$self->{importers}}) {
138 next if !$im; # $im may be undef during cleanup
140 warn "$im->{ibx}->{name} ->done: $@\n" if $@;
144 sub remove_eml_i { # each_inbox callback
145 my ($ibx, $self, $eml, $loc) = @_;
148 # try to avoid taking a lock or unnecessary spawning
149 my $im = $self->{importers}->{"$ibx"};
151 if ((!$im || !$im->active) && $ibx->over) {
152 if (content_exists($ibx, $eml)) {
154 } elsif (my $scrub = $ibx->filter($im)) {
155 $scrubbed = $scrub->scrub($eml, 1);
156 if ($scrubbed && $scrubbed != REJECT &&
157 !content_exists($ibx, $scrubbed)) {
165 $im //= _importer_for($self, $ibx); # may spawn fast-import
166 $im->remove($eml, 'spam');
168 my $scrub = $ibx->filter($im);
169 $scrub ? $scrub->scrub($eml, 1) : undef;
171 if ($scrubbed && $scrubbed != REJECT) {
172 $im->remove($scrubbed, 'spam');
176 warn "error removing spam at: $loc from $ibx->{name}: $@\n";
177 _done_for_now($self);
182 my ($self, $path) = @_;
183 # path must be marked as (S)een
184 $path =~ /:2,[A-R]*S[T-Za-z]*\z/ or return;
185 my $eml = eml_from_path($path) or return;
186 local $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
187 $self->{pi_cfg}->each_inbox(\&remove_eml_i, $self, $eml, $path);
190 sub import_eml ($$$) {
191 my ($self, $ibx, $eml) = @_;
193 # any header match means it's eligible for the inbox:
194 if (my $watch_hdrs = $ibx->{-watchheaders}) {
196 for my $wh (@$watch_hdrs) {
197 my @v = $eml->header_raw($wh->[0]);
198 $ok = grep(/$wh->[1]/, @v) and last;
203 my $im = _importer_for($self, $ibx);
204 if (my $scrub = $ibx->filter($im)) {
205 my $scrubbed = $scrub->scrub($eml) or return;
206 $scrubbed == REJECT and return;
209 $im->add($eml, $self->{spamcheck});
212 warn "$ibx->{name} add failed: $@\n";
213 _done_for_now($self);
218 my ($self, $path) = @_;
219 my $fl = PublicInbox::MdirReader::maildir_path_flags($path) // return;
220 return if $fl =~ /[DT]/; # no Drafts or Trash
221 if ($path !~ $self->{mdre}) {
222 warn "unrecognized path: $path\n";
225 my $inboxes = $self->{mdmap}->{$1};
227 warn "unmappable dir: $1\n";
230 my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
231 local $SIG{__WARN__} = sub {
232 my $pfx = ($_[0] // '') =~ /^([A-Z]: )/g ? $1 : '';
233 $warn_cb->($pfx, "path: $path\n", @_);
235 if (!ref($inboxes) && $inboxes eq 'watchspam') {
236 return _remove_spam($self, $path);
238 foreach my $ibx (@$inboxes) {
239 my $eml = eml_from_path($path) or next;
240 import_eml($self, $ibx, $eml);
246 return unless $self->{quit};
248 # don't have reliable wakeups, keep signalling
250 for (qw(idle_pids poll_pids)) {
251 my $pids = $self->{$_} or next;
253 $done = undef if kill('QUIT', $_);
262 %{$self->{opendirs}} = ();
263 _done_for_now($self);
265 if (my $idle_mic = $self->{idle_mic}) {
266 eval { $idle_mic->done };
268 warn "IDLE DONE error: $@\n";
269 eval { $idle_mic->disconnect };
270 warn "IDLE LOGOUT error: $@\n" if $@;
275 sub watch_fs_init ($) {
278 delete $self->{done_timer};
279 _done_for_now($self);
281 my $cb = sub { # called by PublicInbox::DirIdle::event_step
282 _try_path($self, $_[0]->fullname);
283 $self->{done_timer} //= PublicInbox::DS::requeue($done);
285 require PublicInbox::DirIdle;
286 # inotify_create + EPOLL_CTL_ADD
287 PublicInbox::DirIdle->new([keys %{$self->{mdmap}}], $cb);
290 sub imap_import_msg ($$$$$) {
291 my ($self, $uri, $uid, $raw, $flags) = @_;
292 # our target audience expects LF-only, save storage
293 $$raw =~ s/\r\n/\n/sg;
295 my $inboxes = $self->{imap}->{$$uri};
297 for my $ibx (@$inboxes) {
298 my $eml = PublicInbox::Eml->new($$raw);
299 import_eml($self, $ibx, $eml);
301 } elsif ($inboxes eq 'watchspam') {
302 return if $flags !~ /\\Seen\b/; # don't remove unseen messages
303 local $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
304 my $eml = PublicInbox::Eml->new($raw);
305 $self->{pi_cfg}->each_inbox(\&remove_eml_i,
306 $self, $eml, "$uri UID:$uid");
308 die "BUG: destination unknown $inboxes";
312 sub imap_fetch_all ($$$) {
313 my ($self, $mic, $uri) = @_;
314 my $sec = uri_section($uri);
315 my $mbx = $uri->mailbox;
316 $mic->Clear(1); # trim results history
317 $mic->examine($mbx) or return "E: EXAMINE $mbx ($sec) failed: $!";
318 my ($r_uidval, $r_uidnext);
319 for ($mic->Results) {
320 /^\* OK \[UIDVALIDITY ([0-9]+)\].*/ and $r_uidval = $1;
321 /^\* OK \[UIDNEXT ([0-9]+)\].*/ and $r_uidnext = $1;
322 last if $r_uidval && $r_uidnext;
324 $r_uidval //= $mic->uidvalidity($mbx) //
325 return "E: $uri cannot get UIDVALIDITY";
326 $r_uidnext //= $mic->uidnext($mbx) //
327 return "E: $uri cannot get UIDNEXT";
328 my $itrk = PublicInbox::IMAPTracker->new($$uri);
329 my ($l_uidval, $l_uid) = $itrk->get_last;
330 $l_uidval //= $r_uidval; # first time
332 if ($l_uidval != $r_uidval) {
333 return "E: $uri UIDVALIDITY mismatch\n".
334 "E: local=$l_uidval != remote=$r_uidval";
336 my $r_uid = $r_uidnext - 1;
337 if ($l_uid != 1 && $l_uid > $r_uid) {
338 return "E: $uri local UID exceeds remote ($l_uid > $r_uid)\n".
339 "E: $uri strangely, UIDVALIDLITY matches ($l_uidval)\n";
341 return if $l_uid >= $r_uid; # nothing to do
343 warn "I: $uri fetching UID $l_uid:$r_uid\n";
344 $mic->Uid(1); # the default, we hope
345 my $bs = $self->{imap_opt}->{$sec}->{batch_size} // 1;
346 my $req = $mic->imap4rev1 ? 'BODY.PEEK[]' : 'RFC822.PEEK';
348 # TODO: FLAGS may be useful for personal use
352 my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
353 local $SIG{__WARN__} = sub {
354 my $pfx = ($_[0] // '') =~ /^([A-Z]: )/g ? $1 : '';
356 $warn_cb->("$pfx$uri UID:$batch\n", @_);
360 # I wish "UID FETCH $START:*" could work, but:
361 # 1) servers do not need to return results in any order
362 # 2) Mail::IMAPClient doesn't offer a streaming API
363 $uids = $mic->search("UID $l_uid:*") or
364 return "E: $uri UID SEARCH $l_uid:* error: $!";
365 return if scalar(@$uids) == 0;
367 # RFC 3501 doesn't seem to indicate order of UID SEARCH
368 # responses, so sort it ourselves. Order matters so
369 # IMAPTracker can store the newest UID.
370 @$uids = sort { $a <=> $b } @$uids;
372 # Did we actually get new messages?
373 return if $uids->[0] < $l_uid;
375 $l_uid = $uids->[-1] + 1; # for next search
377 my $n = $self->{max_batch};
379 while (scalar @$uids) {
381 _done_for_now($self);
382 $itrk->update_last($r_uidval, $last_uid);
383 $n = $self->{max_batch};
385 my @batch = splice(@$uids, 0, $bs);
386 $batch = join(',', @batch);
387 local $0 = "UID:$batch $mbx $sec";
388 my $r = $mic->fetch_hash($batch, $req, 'FLAGS');
389 unless ($r) { # network error?
390 $err = "E: $uri UID FETCH $batch error: $!";
393 for my $uid (@batch) {
394 # messages get deleted, so holes appear
395 my $per_uid = delete $r->{$uid} // next;
396 my $raw = delete($per_uid->{$key}) // next;
397 my $fl = $per_uid->{FLAGS} // '';
398 imap_import_msg($self, $uri, $uid, \$raw, $fl);
400 last if $self->{quit};
402 last if $self->{quit};
404 _done_for_now($self);
405 $itrk->update_last($r_uidval, $last_uid);
406 } until ($err || $self->{quit});
410 sub imap_idle_once ($$$$) {
411 my ($self, $mic, $intvl, $uri) = @_;
412 my $i = $intvl //= (29 * 60);
413 my $end = now() + $intvl;
414 warn "I: $uri idling for ${intvl}s\n";
415 local $0 = "IDLE $0";
416 unless ($mic->idle) {
417 return if $self->{quit};
418 return "E: IDLE failed on $uri: $!";
420 $self->{idle_mic} = $mic; # for ->quit
422 until ($self->{quit} || !$mic->IsConnected ||
423 grep(/^\* [0-9]+ EXISTS/, @res) || $i <= 0) {
424 @res = $mic->idle_data($i);
427 delete $self->{idle_mic};
428 unless ($self->{quit}) {
429 $mic->IsConnected or return "E: IDLE disconnected on $uri";
430 $mic->done or return "E: IDLE DONE failed on $uri: $!";
435 # idles on a single URI
436 sub watch_imap_idle_1 ($$$) {
437 my ($self, $uri, $intvl) = @_;
438 my $sec = uri_section($uri);
439 my $mic_arg = $self->{mic_arg}->{$sec} or
440 die "BUG: no Mail::IMAPClient->new arg for $sec";
442 local $0 = $uri->mailbox." $sec";
443 until ($self->{quit}) {
444 $mic //= PublicInbox::IMAPClient->new(%$mic_arg);
446 if ($mic && $mic->IsConnected) {
447 $err = imap_fetch_all($self, $mic, $uri);
448 $err //= imap_idle_once($self, $mic, $intvl, $uri);
450 $err = "E: not connected: $!";
452 if ($err && !$self->{quit}) {
455 sleep 60 unless $self->{quit};
460 sub watch_atfork_child ($) {
462 delete $self->{idle_pids};
463 delete $self->{poll_pids};
464 delete $self->{opendirs};
465 PublicInbox::DS->Reset;
466 %SIG = (%SIG, %{$self->{sig}}, CHLD => 'DEFAULT');
467 PublicInbox::DS::sig_setmask($self->{oldset});
470 sub watch_atfork_parent ($) {
472 _done_for_now($self);
473 PublicInbox::DS::block_signals();
476 sub imap_idle_requeue { # DS::add_timer callback
477 my ($self, $uri_intvl) = @_;
478 return if $self->{quit};
479 push @{$self->{idle_todo}}, $uri_intvl;
483 sub imap_idle_reap { # PublicInbox::DS::dwaitpid callback
484 my ($self, $pid) = @_;
485 my $uri_intvl = delete $self->{idle_pids}->{$pid} or
486 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
488 my ($uri, $intvl) = @$uri_intvl;
489 return if $self->{quit};
490 warn "W: PID=$pid on $uri died: \$?=$?\n" if $?;
491 add_timer(60, \&imap_idle_requeue, $self, $uri_intvl);
494 sub reap { # callback for EOFpipe
495 my ($pid, $cb, $self) = @{$_[0]};
496 my $ret = waitpid($pid, 0);
498 $cb->($self, $pid); # poll_fetch_reap || imap_idle_reap
500 warn "W: waitpid($pid) => ", $ret // "($!)", "\n";
504 sub imap_idle_fork ($$) {
505 my ($self, $uri_intvl) = @_;
506 my ($uri, $intvl) = @$uri_intvl;
507 pipe(my ($r, $w)) or die "pipe: $!";
508 my $seed = rand(0xffffffff);
509 my $pid = fork // die "fork: $!";
512 eval { Net::SSLeay::randomize() };
514 watch_atfork_child($self);
515 watch_imap_idle_1($self, $uri, $intvl);
519 $self->{idle_pids}->{$pid} = $uri_intvl;
520 PublicInbox::EOFpipe->new($r, \&reap, [$pid, \&imap_idle_reap, $self]);
525 return if $self->{quit};
526 my $idle_todo = $self->{idle_todo};
527 if ($idle_todo && @$idle_todo) {
528 my $oldset = watch_atfork_parent($self);
530 while (my $uri_intvl = shift(@$idle_todo)) {
531 imap_idle_fork($self, $uri_intvl);
534 PublicInbox::DS::sig_setmask($oldset);
537 fs_scan_step($self) if $self->{mdre};
540 sub watch_imap_fetch_all ($$) {
541 my ($self, $uris) = @_;
542 for my $uri (@$uris) {
543 my $sec = uri_section($uri);
544 my $mic_arg = $self->{mic_arg}->{$sec} or
545 die "BUG: no Mail::IMAPClient->new arg for $sec";
546 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or next;
547 my $err = imap_fetch_all($self, $mic, $uri);
548 last if $self->{quit};
549 warn $err, "\n" if $err;
553 sub watch_nntp_fetch_all ($$) {
554 my ($self, $uris) = @_;
555 for my $uri (@$uris) {
556 my $sec = uri_section($uri);
557 my $nn_arg = $self->{nn_arg}->{$sec} or
558 die "BUG: no Net::NNTP->new arg for $sec";
559 my $nntp_opt = $self->{nntp_opt}->{$sec};
560 my $nn = nn_new($nn_arg, $nntp_opt, $uri);
562 warn "E: $uri: \$!=$!\n";
565 last if $self->{quit};
566 if (my $postconn = $nntp_opt->{-postconn}) {
567 for my $m_arg (@$postconn) {
568 my ($method, @args) = @$m_arg;
569 $nn->$method(@args) and next;
570 warn "E: <$uri> $method failed\n";
575 last if $self->{quit};
577 my $err = nntp_fetch_all($self, $nn, $uri);
578 warn $err, "\n" if $err;
583 sub poll_fetch_fork { # DS::add_timer callback
584 my ($self, $intvl, $uris) = @_;
585 return if $self->{quit};
586 pipe(my ($r, $w)) or die "pipe: $!";
587 my $oldset = watch_atfork_parent($self);
588 my $seed = rand(0xffffffff);
590 if (defined($pid) && $pid == 0) {
592 eval { Net::SSLeay::randomize() };
594 watch_atfork_child($self);
595 if ($uris->[0]->scheme =~ m!\Aimaps?!i) {
596 watch_imap_fetch_all($self, $uris);
598 watch_nntp_fetch_all($self, $uris);
603 PublicInbox::DS::sig_setmask($oldset);
604 die "fork: $!" unless defined $pid;
605 $self->{poll_pids}->{$pid} = [ $intvl, $uris ];
606 PublicInbox::EOFpipe->new($r, \&reap, [$pid, \&poll_fetch_reap, $self]);
609 sub poll_fetch_reap {
610 my ($self, $pid) = @_;
611 my $intvl_uris = delete $self->{poll_pids}->{$pid} or
612 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
613 return if $self->{quit};
614 my ($intvl, $uris) = @$intvl_uris;
616 warn "W: PID=$pid died: \$?=$?\n", map { "$_\n" } @$uris;
618 warn("I: will check $_ in ${intvl}s\n") for @$uris;
619 add_timer($intvl, \&poll_fetch_fork, $self, $intvl, $uris);
622 sub watch_imap_init ($$) {
623 my ($self, $poll) = @_;
624 my $mics = imap_common_init($self); # read args from config
625 my $idle = []; # [ [ uri1, intvl1 ], [uri2, intvl2] ]
626 for my $uri (@{$self->{imap_order}}) {
627 my $sec = uri_section($uri);
628 my $mic = $mics->{$sec};
629 my $intvl = $self->{imap_opt}->{$sec}->{pollInterval};
630 if ($mic->has_capability('IDLE') && !$intvl) {
631 $intvl = $self->{imap_opt}->{$sec}->{idleInterval};
632 push @$idle, [ $uri, $intvl // () ];
634 push @{$poll->{$intvl || 120}}, $uri;
638 $self->{idle_todo} = $idle;
639 PublicInbox::DS::requeue($self); # ->event_step to fork
643 sub nntp_fetch_all ($$$) {
644 my ($self, $nn, $uri) = @_;
645 my ($group, $num_a, $num_b) = $uri->group;
646 my $sec = uri_section($uri);
647 my ($nr, $beg, $end) = $nn->group($group);
648 unless (defined($nr)) {
649 chomp(my $msg = $nn->message);
650 return "E: GROUP $group <$sec> $msg";
653 # IMAPTracker is also used for tracking NNTP, UID == article number
654 # LIST.ACTIVE can get the equivalent of UIDVALIDITY, but that's
655 # expensive. So we assume newsgroups don't change:
656 my $itrk = PublicInbox::IMAPTracker->new($$uri);
657 my (undef, $l_art) = $itrk->get_last;
658 $l_art //= $beg; # initial import
660 # allow users to specify articles to refetch
661 # cf. https://tools.ietf.org/id/draft-gilman-news-url-01.txt
662 # nntp://example.com/inbox.foo/$num_a-$num_b
663 $l_art = $num_a if defined($num_a) && $num_a < $l_art;
664 $end = $num_b if defined($num_b) && $num_b < $end;
666 return if $l_art >= $end; # nothing to do
669 warn "I: $uri fetching ARTICLE $beg..$end\n";
670 my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
672 local $SIG{__WARN__} = sub {
673 my $pfx = ($_[0] // '') =~ /^([A-Z]: )/g ? $1 : '';
674 $warn_cb->("$pfx$uri ", $art ? ("ARTICLE $art") : (), "\n", @_);
676 my $inboxes = $self->{nntp}->{$$uri};
678 my $n = $self->{max_batch};
680 last if $self->{quit};
683 _done_for_now($self);
684 $itrk->update_last(0, $last_art);
685 $n = $self->{max_batch};
687 my $raw = $nn->article($art);
688 unless (defined($raw)) {
689 my $msg = $nn->message;
690 if ($nn->code == 421) { # pseudo response from Net::Cmd
693 } else { # probably just a deleted message (spam)
698 s/\r\n/\n/ for @$raw;
699 $raw = join('', @$raw);
701 for my $ibx (@$inboxes) {
702 my $eml = PublicInbox::Eml->new($raw);
703 import_eml($self, $ibx, $eml);
705 } elsif ($inboxes eq 'watchspam') {
706 my $eml = PublicInbox::Eml->new(\$raw);
707 $self->{pi_cfg}->each_inbox(\&remove_eml_i,
708 $self, $eml, "$uri ARTICLE $art");
710 die "BUG: destination unknown $inboxes";
714 _done_for_now($self);
715 $itrk->update_last(0, $last_art);
719 sub watch_nntp_init ($$) {
720 my ($self, $poll) = @_;
721 nntp_common_init($self); # read args from config
722 for my $uri (@{$self->{nntp_order}}) {
723 my $sec = uri_section($uri);
724 my $intvl = $self->{nntp_opt}->{$sec}->{pollInterval};
725 push @{$poll->{$intvl || 120}}, $uri;
729 sub watch { # main entry point
730 my ($self, $sig, $oldset) = @_;
731 $self->{oldset} = $oldset;
733 my $poll = {}; # intvl_seconds => [ uri1, uri2 ]
734 watch_imap_init($self, $poll) if $self->{imap};
735 watch_nntp_init($self, $poll) if $self->{nntp};
736 while (my ($intvl, $uris) = each %$poll) {
737 # poll all URIs for a given interval sequentially
738 add_timer(0, \&poll_fetch_fork, $self, $intvl, $uris);
740 watch_fs_init($self) if $self->{mdre};
741 PublicInbox::DS->SetPostLoopCallback(sub { !$self->quit_done });
742 PublicInbox::DS->EventLoop; # calls ->event_step
743 _done_for_now($self);
747 my ($self, $op) = @_;
748 push @{$self->{ops}}, $op;
749 PublicInbox::DS::requeue($self);
754 return if $self->{quit};
755 my $op = shift @{$self->{ops}};
756 local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
758 # continue existing scan
759 my $opendirs = $self->{opendirs};
760 my @dirnames = keys %$opendirs;
761 foreach my $dir (@dirnames) {
762 my $dh = delete $opendirs->{$dir};
763 my $n = $self->{max_batch};
764 while (my $fn = readdir($dh)) {
765 _try_path($self, "$dir/$fn");
768 $opendirs->{$dir} = $dh if $n < 0;
770 if ($op && $op eq 'full') {
771 foreach my $dir (keys %{$self->{mdmap}}) {
772 next if $opendirs->{$dir}; # already in progress
773 my $ok = opendir(my $dh, $dir);
775 warn "failed to open $dir: $!\n";
778 my $n = $self->{max_batch};
779 while (my $fn = readdir($dh)) {
780 _try_path($self, "$dir/$fn");
783 $opendirs->{$dir} = $dh if $n < 0;
786 _done_for_now($self);
787 # do we have more work to do?
788 PublicInbox::DS::requeue($self) if keys %$opendirs;
792 my ($self, $op) = @_;
793 push @{$self->{ops}}, $op;
798 my ($self, $ibx) = @_;
799 my $importers = $self->{importers};
800 my $im = $importers->{"$ibx"} ||= $ibx->importer(0);
801 if (scalar(keys(%$importers)) > 2) {
802 delete $importers->{"$ibx"};
803 _done_for_now($self);
806 $importers->{"$ibx"} = $im;
809 # XXX consider sharing with V2Writable, this only requires read-only access
810 sub content_exists ($$) {
811 my ($ibx, $eml) = @_;
812 my $over = $ibx->over or return;
813 my $mids = mids($eml);
814 my $chash = content_hash($eml);
816 for my $mid (@$mids) {
817 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
818 my $cmp = $ibx->smsg_eml($smsg) or return;
819 return 1 if $chash eq content_hash($cmp);
827 sub { # this gets called by (V2Writable||Import)->add
828 my ($mime, $ibx) = @_;
829 return if content_exists($ibx, $mime);
831 if ($sc->spamcheck($mime, \$tmp)) {
832 return PublicInbox::Eml->new(\$tmp);
834 warn $mime->header('Message-ID')." failed spam check\n";
840 $_[0] =~ s!\Amaildir:!! or return;
847 my ($cur, $ws, $ibx) = @_;
848 if ($ws && !ref($ws) && $ws eq 'watchspam') {
850 E: $cur is a spam folder and cannot be used for `$ibx->{name}' input