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 (my $uri = imap_uri($dir)) {
64 $imap{$$uri} = 'watchspam';
66 } elsif ($url = nntp_url($dir)) {
67 $nntp{$url} = '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 (my $uri = imap_uri($watch)) {
97 return if is_watchspam($url, $imap{$url}, $ibx);
98 compile_watchheaders($ibx);
99 my $n = push @{$imap{$url} ||= []}, $ibx;
100 push @imap, $uri if $n == 1;
101 } elsif ($url = nntp_url($watch)) {
102 return if is_watchspam($url, $nntp{$url}, $ibx);
103 compile_watchheaders($ibx);
104 my $n = push @{$nntp{$url} ||= []}, $ibx;
105 push @nntp, $url if $n == 1;
107 warn "watch unsupported: $k=$watch\n";
113 if (scalar keys %mdmap) {
114 $mdre = join('|', map { quotemeta($_) } keys %mdmap);
115 $mdre = qr!\A($mdre)/!;
117 return unless $mdre || scalar(keys %imap) || scalar(keys %nntp);
120 max_batch => 10, # avoid hogging locks for too long
121 spamcheck => $spamcheck,
125 imap => scalar keys %imap ? \%imap : undef,
126 nntp => scalar keys %nntp? \%nntp : undef,
127 imap_order => scalar(@imap) ? \@imap : undef,
128 nntp_order => scalar(@nntp) ? \@nntp: undef,
130 opendirs => {}, # dirname => dirhandle (in progress scans)
131 ops => [], # 'quit', 'full'
137 local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
138 for my $im (values %{$self->{importers}}) {
139 next if !$im; # $im may be undef during cleanup
141 warn "$im->{ibx}->{name} ->done: $@\n" if $@;
145 sub remove_eml_i { # each_inbox callback
146 my ($ibx, $self, $eml, $loc) = @_;
149 # try to avoid taking a lock or unnecessary spawning
150 my $im = $self->{importers}->{"$ibx"};
152 if ((!$im || !$im->active) && $ibx->over) {
153 if (content_exists($ibx, $eml)) {
155 } elsif (my $scrub = $ibx->filter($im)) {
156 $scrubbed = $scrub->scrub($eml, 1);
157 if ($scrubbed && $scrubbed != REJECT &&
158 !content_exists($ibx, $scrubbed)) {
166 $im //= _importer_for($self, $ibx); # may spawn fast-import
167 $im->remove($eml, 'spam');
169 my $scrub = $ibx->filter($im);
170 $scrub ? $scrub->scrub($eml, 1) : undef;
172 if ($scrubbed && $scrubbed != REJECT) {
173 $im->remove($scrubbed, 'spam');
177 warn "error removing spam at: $loc from $ibx->{name}: $@\n";
178 _done_for_now($self);
183 my ($self, $path) = @_;
184 # path must be marked as (S)een
185 $path =~ /:2,[A-R]*S[T-Za-z]*\z/ or return;
186 my $eml = eml_from_path($path) or return;
187 local $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
188 $self->{pi_cfg}->each_inbox(\&remove_eml_i, $self, $eml, $path);
191 sub import_eml ($$$) {
192 my ($self, $ibx, $eml) = @_;
194 # any header match means it's eligible for the inbox:
195 if (my $watch_hdrs = $ibx->{-watchheaders}) {
197 for my $wh (@$watch_hdrs) {
198 my @v = $eml->header_raw($wh->[0]);
199 $ok = grep(/$wh->[1]/, @v) and last;
204 my $im = _importer_for($self, $ibx);
205 if (my $scrub = $ibx->filter($im)) {
206 my $scrubbed = $scrub->scrub($eml) or return;
207 $scrubbed == REJECT and return;
210 $im->add($eml, $self->{spamcheck});
213 warn "$ibx->{name} add failed: $@\n";
214 _done_for_now($self);
219 my ($self, $path) = @_;
220 my $fl = PublicInbox::MdirReader::maildir_path_flags($path) // return;
221 return if $fl =~ /[DT]/; # no Drafts or Trash
222 if ($path !~ $self->{mdre}) {
223 warn "unrecognized path: $path\n";
226 my $inboxes = $self->{mdmap}->{$1};
228 warn "unmappable dir: $1\n";
231 my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
232 local $SIG{__WARN__} = sub {
233 my $pfx = ($_[0] // '') =~ /^([A-Z]: )/g ? $1 : '';
234 $warn_cb->($pfx, "path: $path\n", @_);
236 if (!ref($inboxes) && $inboxes eq 'watchspam') {
237 return _remove_spam($self, $path);
239 foreach my $ibx (@$inboxes) {
240 my $eml = eml_from_path($path) or next;
241 import_eml($self, $ibx, $eml);
247 return unless $self->{quit};
249 # don't have reliable wakeups, keep signalling
251 for (qw(idle_pids poll_pids)) {
252 my $pids = $self->{$_} or next;
254 $done = undef if kill('QUIT', $_);
263 %{$self->{opendirs}} = ();
264 _done_for_now($self);
266 if (my $idle_mic = $self->{idle_mic}) {
267 eval { $idle_mic->done };
269 warn "IDLE DONE error: $@\n";
270 eval { $idle_mic->disconnect };
271 warn "IDLE LOGOUT error: $@\n" if $@;
276 sub watch_fs_init ($) {
279 delete $self->{done_timer};
280 _done_for_now($self);
282 my $cb = sub { # called by PublicInbox::DirIdle::event_step
283 _try_path($self, $_[0]->fullname);
284 $self->{done_timer} //= PublicInbox::DS::requeue($done);
286 require PublicInbox::DirIdle;
287 # inotify_create + EPOLL_CTL_ADD
288 PublicInbox::DirIdle->new([keys %{$self->{mdmap}}], $cb);
291 sub imap_import_msg ($$$$$) {
292 my ($self, $url, $uid, $raw, $flags) = @_;
293 # our target audience expects LF-only, save storage
294 $$raw =~ s/\r\n/\n/sg;
296 my $inboxes = $self->{imap}->{$url};
298 for my $ibx (@$inboxes) {
299 my $eml = PublicInbox::Eml->new($$raw);
300 import_eml($self, $ibx, $eml);
302 } elsif ($inboxes eq 'watchspam') {
303 return if $flags !~ /\\Seen\b/; # don't remove unseen messages
304 local $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
305 my $eml = PublicInbox::Eml->new($raw);
306 $self->{pi_cfg}->each_inbox(\&remove_eml_i,
307 $self, $eml, "$url UID:$uid");
309 die "BUG: destination unknown $inboxes";
313 sub imap_fetch_all ($$$) {
314 my ($self, $mic, $url) = @_;
315 my $uri = PublicInbox::URIimap->new($url);
316 my $sec = uri_section($uri);
317 my $mbx = $uri->mailbox;
318 $mic->Clear(1); # trim results history
319 $mic->examine($mbx) or return "E: EXAMINE $mbx ($sec) failed: $!";
320 my ($r_uidval, $r_uidnext);
321 for ($mic->Results) {
322 /^\* OK \[UIDVALIDITY ([0-9]+)\].*/ and $r_uidval = $1;
323 /^\* OK \[UIDNEXT ([0-9]+)\].*/ and $r_uidnext = $1;
324 last if $r_uidval && $r_uidnext;
326 $r_uidval //= $mic->uidvalidity($mbx) //
327 return "E: $url cannot get UIDVALIDITY";
328 $r_uidnext //= $mic->uidnext($mbx) //
329 return "E: $url cannot get UIDNEXT";
330 my $itrk = PublicInbox::IMAPTracker->new($url);
331 my ($l_uidval, $l_uid) = $itrk->get_last;
332 $l_uidval //= $r_uidval; # first time
334 if ($l_uidval != $r_uidval) {
335 return "E: $url UIDVALIDITY mismatch\n".
336 "E: local=$l_uidval != remote=$r_uidval";
338 my $r_uid = $r_uidnext - 1;
339 if ($l_uid != 1 && $l_uid > $r_uid) {
340 return "E: $url local UID exceeds remote ($l_uid > $r_uid)\n".
341 "E: $url strangely, UIDVALIDLITY matches ($l_uidval)\n";
343 return if $l_uid >= $r_uid; # nothing to do
345 warn "I: $url fetching UID $l_uid:$r_uid\n";
346 $mic->Uid(1); # the default, we hope
347 my $bs = $self->{imap_opt}->{$sec}->{batch_size} // 1;
348 my $req = $mic->imap4rev1 ? 'BODY.PEEK[]' : 'RFC822.PEEK';
350 # TODO: FLAGS may be useful for personal use
354 my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
355 local $SIG{__WARN__} = sub {
356 my $pfx = ($_[0] // '') =~ /^([A-Z]: )/g ? $1 : '';
358 $warn_cb->("$pfx$url UID:$batch\n", @_);
362 # I wish "UID FETCH $START:*" could work, but:
363 # 1) servers do not need to return results in any order
364 # 2) Mail::IMAPClient doesn't offer a streaming API
365 $uids = $mic->search("UID $l_uid:*") or
366 return "E: $url UID SEARCH $l_uid:* error: $!";
367 return if scalar(@$uids) == 0;
369 # RFC 3501 doesn't seem to indicate order of UID SEARCH
370 # responses, so sort it ourselves. Order matters so
371 # IMAPTracker can store the newest UID.
372 @$uids = sort { $a <=> $b } @$uids;
374 # Did we actually get new messages?
375 return if $uids->[0] < $l_uid;
377 $l_uid = $uids->[-1] + 1; # for next search
379 my $n = $self->{max_batch};
381 while (scalar @$uids) {
383 _done_for_now($self);
384 $itrk->update_last($r_uidval, $last_uid);
385 $n = $self->{max_batch};
387 my @batch = splice(@$uids, 0, $bs);
388 $batch = join(',', @batch);
389 local $0 = "UID:$batch $mbx $sec";
390 my $r = $mic->fetch_hash($batch, $req, 'FLAGS');
391 unless ($r) { # network error?
392 $err = "E: $url UID FETCH $batch error: $!";
395 for my $uid (@batch) {
396 # messages get deleted, so holes appear
397 my $per_uid = delete $r->{$uid} // next;
398 my $raw = delete($per_uid->{$key}) // next;
399 my $fl = $per_uid->{FLAGS} // '';
400 imap_import_msg($self, $url, $uid, \$raw, $fl);
402 last if $self->{quit};
404 last if $self->{quit};
406 _done_for_now($self);
407 $itrk->update_last($r_uidval, $last_uid);
408 } until ($err || $self->{quit});
412 sub imap_idle_once ($$$$) {
413 my ($self, $mic, $intvl, $url) = @_;
414 my $i = $intvl //= (29 * 60);
415 my $end = now() + $intvl;
416 warn "I: $url idling for ${intvl}s\n";
417 local $0 = "IDLE $0";
418 unless ($mic->idle) {
419 return if $self->{quit};
420 return "E: IDLE failed on $url: $!";
422 $self->{idle_mic} = $mic; # for ->quit
424 until ($self->{quit} || !$mic->IsConnected ||
425 grep(/^\* [0-9]+ EXISTS/, @res) || $i <= 0) {
426 @res = $mic->idle_data($i);
429 delete $self->{idle_mic};
430 unless ($self->{quit}) {
431 $mic->IsConnected or return "E: IDLE disconnected on $url";
432 $mic->done or return "E: IDLE DONE failed on $url: $!";
437 # idles on a single URI
438 sub watch_imap_idle_1 ($$$) {
439 my ($self, $url, $intvl) = @_;
440 my $uri = PublicInbox::URIimap->new($url);
441 my $sec = uri_section($uri);
442 my $mic_arg = $self->{mic_arg}->{$sec} or
443 die "BUG: no Mail::IMAPClient->new arg for $sec";
445 local $0 = $uri->mailbox." $sec";
446 until ($self->{quit}) {
447 $mic //= PublicInbox::IMAPClient->new(%$mic_arg);
449 if ($mic && $mic->IsConnected) {
450 $err = imap_fetch_all($self, $mic, $url);
451 $err //= imap_idle_once($self, $mic, $intvl, $url);
453 $err = "E: not connected: $!";
455 if ($err && !$self->{quit}) {
458 sleep 60 unless $self->{quit};
463 sub watch_atfork_child ($) {
465 delete $self->{idle_pids};
466 delete $self->{poll_pids};
467 delete $self->{opendirs};
468 PublicInbox::DS->Reset;
469 %SIG = (%SIG, %{$self->{sig}}, CHLD => 'DEFAULT');
470 PublicInbox::DS::sig_setmask($self->{oldset});
473 sub watch_atfork_parent ($) {
475 _done_for_now($self);
476 PublicInbox::DS::block_signals();
479 sub imap_idle_requeue { # DS::add_timer callback
480 my ($self, $url_intvl) = @_;
481 return if $self->{quit};
482 push @{$self->{idle_todo}}, $url_intvl;
486 sub imap_idle_reap { # PublicInbox::DS::dwaitpid callback
487 my ($self, $pid) = @_;
488 my $url_intvl = delete $self->{idle_pids}->{$pid} or
489 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
491 my ($url, $intvl) = @$url_intvl;
492 return if $self->{quit};
493 warn "W: PID=$pid on $url died: \$?=$?\n" if $?;
494 add_timer(60, \&imap_idle_requeue, $self, $url_intvl);
497 sub reap { # callback for EOFpipe
498 my ($pid, $cb, $self) = @{$_[0]};
499 my $ret = waitpid($pid, 0);
501 $cb->($self, $pid); # poll_fetch_reap || imap_idle_reap
503 warn "W: waitpid($pid) => ", $ret // "($!)", "\n";
507 sub imap_idle_fork ($$) {
508 my ($self, $url_intvl) = @_;
509 my ($url, $intvl) = @$url_intvl;
510 pipe(my ($r, $w)) or die "pipe: $!";
511 my $seed = rand(0xffffffff);
512 my $pid = fork // die "fork: $!";
515 eval { Net::SSLeay::randomize() };
517 watch_atfork_child($self);
518 watch_imap_idle_1($self, $url, $intvl);
522 $self->{idle_pids}->{$pid} = $url_intvl;
523 PublicInbox::EOFpipe->new($r, \&reap, [$pid, \&imap_idle_reap, $self]);
528 return if $self->{quit};
529 my $idle_todo = $self->{idle_todo};
530 if ($idle_todo && @$idle_todo) {
531 my $oldset = watch_atfork_parent($self);
533 while (my $url_intvl = shift(@$idle_todo)) {
534 imap_idle_fork($self, $url_intvl);
537 PublicInbox::DS::sig_setmask($oldset);
540 fs_scan_step($self) if $self->{mdre};
543 sub watch_imap_fetch_all ($$) {
544 my ($self, $urls) = @_;
545 for my $url (@$urls) {
546 my $uri = PublicInbox::URIimap->new($url);
547 my $sec = uri_section($uri);
548 my $mic_arg = $self->{mic_arg}->{$sec} or
549 die "BUG: no Mail::IMAPClient->new arg for $sec";
550 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or next;
551 my $err = imap_fetch_all($self, $mic, $url);
552 last if $self->{quit};
553 warn $err, "\n" if $err;
557 sub watch_nntp_fetch_all ($$) {
558 my ($self, $urls) = @_;
559 for my $url (@$urls) {
560 my $uri = uri_new($url);
561 my $sec = uri_section($uri);
562 my $nn_arg = $self->{nn_arg}->{$sec} or
563 die "BUG: no Net::NNTP->new arg for $sec";
564 my $nntp_opt = $self->{nntp_opt}->{$sec};
565 my $nn = nn_new($nn_arg, $nntp_opt, $url);
567 warn "E: $url: \$!=$!\n";
570 last if $self->{quit};
571 if (my $postconn = $nntp_opt->{-postconn}) {
572 for my $m_arg (@$postconn) {
573 my ($method, @args) = @$m_arg;
574 $nn->$method(@args) and next;
575 warn "E: <$url> $method failed\n";
580 last if $self->{quit};
582 my $err = nntp_fetch_all($self, $nn, $url);
583 warn $err, "\n" if $err;
588 sub poll_fetch_fork { # DS::add_timer callback
589 my ($self, $intvl, $urls) = @_;
590 return if $self->{quit};
591 pipe(my ($r, $w)) or die "pipe: $!";
592 my $oldset = watch_atfork_parent($self);
593 my $seed = rand(0xffffffff);
595 if (defined($pid) && $pid == 0) {
597 eval { Net::SSLeay::randomize() };
599 watch_atfork_child($self);
600 if ($urls->[0] =~ m!\Aimaps?://!i) {
601 watch_imap_fetch_all($self, $urls);
603 watch_nntp_fetch_all($self, $urls);
608 PublicInbox::DS::sig_setmask($oldset);
609 die "fork: $!" unless defined $pid;
610 $self->{poll_pids}->{$pid} = [ $intvl, $urls ];
611 PublicInbox::EOFpipe->new($r, \&reap, [$pid, \&poll_fetch_reap, $self]);
614 sub poll_fetch_reap {
615 my ($self, $pid) = @_;
616 my $intvl_urls = delete $self->{poll_pids}->{$pid} or
617 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
618 return if $self->{quit};
619 my ($intvl, $urls) = @$intvl_urls;
621 warn "W: PID=$pid died: \$?=$?\n", map { "$_\n" } @$urls;
623 warn("I: will check $_ in ${intvl}s\n") for @$urls;
624 add_timer($intvl, \&poll_fetch_fork, $self, $intvl, $urls);
627 sub watch_imap_init ($$) {
628 my ($self, $poll) = @_;
629 my $mics = imap_common_init($self); # read args from config
630 my $idle = []; # [ [ url1, intvl1 ], [url2, intvl2] ]
631 for my $url (keys %{$self->{imap}}) {
632 my $uri = PublicInbox::URIimap->new($url);
633 my $sec = uri_section($uri);
634 my $mic = $mics->{$sec};
635 my $intvl = $self->{imap_opt}->{$sec}->{pollInterval};
636 if ($mic->has_capability('IDLE') && !$intvl) {
637 $intvl = $self->{imap_opt}->{$sec}->{idleInterval};
638 push @$idle, [ $url, $intvl // () ];
640 push @{$poll->{$intvl || 120}}, $url;
644 $self->{idle_todo} = $idle;
645 PublicInbox::DS::requeue($self); # ->event_step to fork
649 # flesh out common NNTP-specific data structures
650 sub nntp_common_init ($) {
652 my $cfg = $self->{pi_cfg};
653 my $nn_args = {}; # scheme://authority => Net::NNTP->new arg
654 for my $url (@{$self->{nntp_order}}) {
655 my $sec = uri_section(uri_new($url));
657 # Debug and Timeout are passed to Net::NNTP->new
658 my $v = cfg_bool($cfg, 'nntp.Debug', $url);
659 $nn_args->{$sec}->{Debug} = $v if defined $v;
660 my $to = cfg_intvl($cfg, 'nntp.Timeout', $url);
661 $nn_args->{$sec}->{Timeout} = $to if $to;
663 # Net::NNTP post-connect commands
664 for my $k (qw(starttls compress)) {
665 $v = cfg_bool($cfg, "nntp.$k", $url) // next;
666 $self->{nntp_opt}->{$sec}->{$k} = $v;
670 for my $k (qw(pollInterval)) {
671 $to = cfg_intvl($cfg, "nntp.$k", $url) // next;
672 $self->{nntp_opt}->{$sec}->{$k} = $to;
678 sub nntp_fetch_all ($$$) {
679 my ($self, $nn, $url) = @_;
680 my $uri = uri_new($url);
681 my ($group, $num_a, $num_b) = $uri->group;
682 my $sec = uri_section($uri);
683 my ($nr, $beg, $end) = $nn->group($group);
684 unless (defined($nr)) {
685 chomp(my $msg = $nn->message);
686 return "E: GROUP $group <$sec> $msg";
689 # IMAPTracker is also used for tracking NNTP, UID == article number
690 # LIST.ACTIVE can get the equivalent of UIDVALIDITY, but that's
691 # expensive. So we assume newsgroups don't change:
692 my $itrk = PublicInbox::IMAPTracker->new($url);
693 my (undef, $l_art) = $itrk->get_last;
694 $l_art //= $beg; # initial import
696 # allow users to specify articles to refetch
697 # cf. https://tools.ietf.org/id/draft-gilman-news-url-01.txt
698 # nntp://example.com/inbox.foo/$num_a-$num_b
699 $l_art = $num_a if defined($num_a) && $num_a < $l_art;
700 $end = $num_b if defined($num_b) && $num_b < $end;
702 return if $l_art >= $end; # nothing to do
705 warn "I: $url fetching ARTICLE $beg..$end\n";
706 my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
708 local $SIG{__WARN__} = sub {
709 my $pfx = ($_[0] // '') =~ /^([A-Z]: )/g ? $1 : '';
710 $warn_cb->("$pfx$url ", $art ? ("ARTICLE $art") : (), "\n", @_);
712 my $inboxes = $self->{nntp}->{$url};
714 my $n = $self->{max_batch};
716 last if $self->{quit};
719 _done_for_now($self);
720 $itrk->update_last(0, $last_art);
721 $n = $self->{max_batch};
723 my $raw = $nn->article($art);
724 unless (defined($raw)) {
725 my $msg = $nn->message;
726 if ($nn->code == 421) { # pseudo response from Net::Cmd
729 } else { # probably just a deleted message (spam)
734 s/\r\n/\n/ for @$raw;
735 $raw = join('', @$raw);
737 for my $ibx (@$inboxes) {
738 my $eml = PublicInbox::Eml->new($raw);
739 import_eml($self, $ibx, $eml);
741 } elsif ($inboxes eq 'watchspam') {
742 my $eml = PublicInbox::Eml->new(\$raw);
743 $self->{pi_cfg}->each_inbox(\&remove_eml_i,
744 $self, $eml, "$url ARTICLE $art");
746 die "BUG: destination unknown $inboxes";
750 _done_for_now($self);
751 $itrk->update_last(0, $last_art);
755 sub watch_nntp_init ($$) {
756 my ($self, $poll) = @_;
757 eval { require Net::NNTP } or
758 die "Net::NNTP is required for NNTP:\n$@\n";
759 eval { require PublicInbox::IMAPTracker } or
760 die "DBD::SQLite is required for NNTP\n:$@\n";
762 my $nn_args = nntp_common_init($self); # read args from config
764 # make sure we can connect and cache the credentials in memory
765 $self->{nn_arg} = {}; # schema://authority => Net::NNTP->new args
766 for my $url (@{$self->{nntp_order}}) {
767 nn_for($self, $url, $nn_args);
769 for my $url (@{$self->{nntp_order}}) {
770 my $uri = uri_new($url);
771 my $sec = uri_section($uri);
772 my $intvl = $self->{nntp_opt}->{$sec}->{pollInterval};
773 push @{$poll->{$intvl || 120}}, $url;
777 sub watch { # main entry point
778 my ($self, $sig, $oldset) = @_;
779 $self->{oldset} = $oldset;
781 my $poll = {}; # intvl_seconds => [ url1, url2 ]
782 watch_imap_init($self, $poll) if $self->{imap};
783 watch_nntp_init($self, $poll) if $self->{nntp};
784 while (my ($intvl, $urls) = each %$poll) {
785 # poll all URLs for a given interval sequentially
786 add_timer(0, \&poll_fetch_fork, $self, $intvl, $urls);
788 watch_fs_init($self) if $self->{mdre};
789 PublicInbox::DS->SetPostLoopCallback(sub { !$self->quit_done });
790 PublicInbox::DS->EventLoop; # calls ->event_step
791 _done_for_now($self);
795 my ($self, $op) = @_;
796 push @{$self->{ops}}, $op;
797 PublicInbox::DS::requeue($self);
802 return if $self->{quit};
803 my $op = shift @{$self->{ops}};
804 local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
806 # continue existing scan
807 my $opendirs = $self->{opendirs};
808 my @dirnames = keys %$opendirs;
809 foreach my $dir (@dirnames) {
810 my $dh = delete $opendirs->{$dir};
811 my $n = $self->{max_batch};
812 while (my $fn = readdir($dh)) {
813 _try_path($self, "$dir/$fn");
816 $opendirs->{$dir} = $dh if $n < 0;
818 if ($op && $op eq 'full') {
819 foreach my $dir (keys %{$self->{mdmap}}) {
820 next if $opendirs->{$dir}; # already in progress
821 my $ok = opendir(my $dh, $dir);
823 warn "failed to open $dir: $!\n";
826 my $n = $self->{max_batch};
827 while (my $fn = readdir($dh)) {
828 _try_path($self, "$dir/$fn");
831 $opendirs->{$dir} = $dh if $n < 0;
834 _done_for_now($self);
835 # do we have more work to do?
836 PublicInbox::DS::requeue($self) if keys %$opendirs;
840 my ($self, $op) = @_;
841 push @{$self->{ops}}, $op;
846 my ($self, $ibx) = @_;
847 my $importers = $self->{importers};
848 my $im = $importers->{"$ibx"} ||= $ibx->importer(0);
849 if (scalar(keys(%$importers)) > 2) {
850 delete $importers->{"$ibx"};
851 _done_for_now($self);
854 $importers->{"$ibx"} = $im;
857 # XXX consider sharing with V2Writable, this only requires read-only access
858 sub content_exists ($$) {
859 my ($ibx, $eml) = @_;
860 my $over = $ibx->over or return;
861 my $mids = mids($eml);
862 my $chash = content_hash($eml);
864 for my $mid (@$mids) {
865 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
866 my $cmp = $ibx->smsg_eml($smsg) or return;
867 return 1 if $chash eq content_hash($cmp);
875 sub { # this gets called by (V2Writable||Import)->add
876 my ($mime, $ibx) = @_;
877 return if content_exists($ibx, $mime);
879 if ($sc->spamcheck($mime, \$tmp)) {
880 return PublicInbox::Eml->new(\$tmp);
882 warn $mime->header('Message-ID')." failed spam check\n";
888 $_[0] =~ s!\Amaildir:!! or return;
895 my ($cur, $ws, $ibx) = @_;
896 if ($ws && !ref($ws) && $ws eq 'watchspam') {
898 E: $cur is a spam folder and cannot be used for `$ibx->{name}' input