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 ($url = imap_url($dir)) {
64 $imap{$url} = '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 ($url = imap_url($watch)) {
96 return if is_watchspam($url, $imap{$url}, $ibx);
97 compile_watchheaders($ibx);
98 my $n = push @{$imap{$url} ||= []}, $ibx;
99 push @imap, $url if $n == 1;
100 } elsif ($url = nntp_url($watch)) {
101 return if is_watchspam($url, $nntp{$url}, $ibx);
102 compile_watchheaders($ibx);
103 my $n = push @{$nntp{$url} ||= []}, $ibx;
104 push @nntp, $url if $n == 1;
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, $url, $uid, $raw, $flags) = @_;
292 # our target audience expects LF-only, save storage
293 $$raw =~ s/\r\n/\n/sg;
295 my $inboxes = $self->{imap}->{$url};
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, "$url UID:$uid");
308 die "BUG: destination unknown $inboxes";
312 sub imap_fetch_all ($$$) {
313 my ($self, $mic, $url) = @_;
314 my $uri = PublicInbox::URIimap->new($url);
315 my $sec = uri_section($uri);
316 my $mbx = $uri->mailbox;
317 $mic->Clear(1); # trim results history
318 $mic->examine($mbx) or return "E: EXAMINE $mbx ($sec) failed: $!";
319 my ($r_uidval, $r_uidnext);
320 for ($mic->Results) {
321 /^\* OK \[UIDVALIDITY ([0-9]+)\].*/ and $r_uidval = $1;
322 /^\* OK \[UIDNEXT ([0-9]+)\].*/ and $r_uidnext = $1;
323 last if $r_uidval && $r_uidnext;
325 $r_uidval //= $mic->uidvalidity($mbx) //
326 return "E: $url cannot get UIDVALIDITY";
327 $r_uidnext //= $mic->uidnext($mbx) //
328 return "E: $url cannot get UIDNEXT";
329 my $itrk = PublicInbox::IMAPTracker->new($url);
330 my ($l_uidval, $l_uid) = $itrk->get_last;
331 $l_uidval //= $r_uidval; # first time
333 if ($l_uidval != $r_uidval) {
334 return "E: $url UIDVALIDITY mismatch\n".
335 "E: local=$l_uidval != remote=$r_uidval";
337 my $r_uid = $r_uidnext - 1;
338 if ($l_uid != 1 && $l_uid > $r_uid) {
339 return "E: $url local UID exceeds remote ($l_uid > $r_uid)\n".
340 "E: $url strangely, UIDVALIDLITY matches ($l_uidval)\n";
342 return if $l_uid >= $r_uid; # nothing to do
344 warn "I: $url fetching UID $l_uid:$r_uid\n";
345 $mic->Uid(1); # the default, we hope
346 my $bs = $self->{imap_opt}->{$sec}->{batch_size} // 1;
347 my $req = $mic->imap4rev1 ? 'BODY.PEEK[]' : 'RFC822.PEEK';
349 # TODO: FLAGS may be useful for personal use
353 my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
354 local $SIG{__WARN__} = sub {
355 my $pfx = ($_[0] // '') =~ /^([A-Z]: )/g ? $1 : '';
357 $warn_cb->("$pfx$url UID:$batch\n", @_);
361 # I wish "UID FETCH $START:*" could work, but:
362 # 1) servers do not need to return results in any order
363 # 2) Mail::IMAPClient doesn't offer a streaming API
364 $uids = $mic->search("UID $l_uid:*") or
365 return "E: $url UID SEARCH $l_uid:* error: $!";
366 return if scalar(@$uids) == 0;
368 # RFC 3501 doesn't seem to indicate order of UID SEARCH
369 # responses, so sort it ourselves. Order matters so
370 # IMAPTracker can store the newest UID.
371 @$uids = sort { $a <=> $b } @$uids;
373 # Did we actually get new messages?
374 return if $uids->[0] < $l_uid;
376 $l_uid = $uids->[-1] + 1; # for next search
378 my $n = $self->{max_batch};
380 while (scalar @$uids) {
382 _done_for_now($self);
383 $itrk->update_last($r_uidval, $last_uid);
384 $n = $self->{max_batch};
386 my @batch = splice(@$uids, 0, $bs);
387 $batch = join(',', @batch);
388 local $0 = "UID:$batch $mbx $sec";
389 my $r = $mic->fetch_hash($batch, $req, 'FLAGS');
390 unless ($r) { # network error?
391 $err = "E: $url UID FETCH $batch error: $!";
394 for my $uid (@batch) {
395 # messages get deleted, so holes appear
396 my $per_uid = delete $r->{$uid} // next;
397 my $raw = delete($per_uid->{$key}) // next;
398 my $fl = $per_uid->{FLAGS} // '';
399 imap_import_msg($self, $url, $uid, \$raw, $fl);
401 last if $self->{quit};
403 last if $self->{quit};
405 _done_for_now($self);
406 $itrk->update_last($r_uidval, $last_uid);
407 } until ($err || $self->{quit});
411 sub imap_idle_once ($$$$) {
412 my ($self, $mic, $intvl, $url) = @_;
413 my $i = $intvl //= (29 * 60);
414 my $end = now() + $intvl;
415 warn "I: $url idling for ${intvl}s\n";
416 local $0 = "IDLE $0";
417 unless ($mic->idle) {
418 return if $self->{quit};
419 return "E: IDLE failed on $url: $!";
421 $self->{idle_mic} = $mic; # for ->quit
423 until ($self->{quit} || !$mic->IsConnected ||
424 grep(/^\* [0-9]+ EXISTS/, @res) || $i <= 0) {
425 @res = $mic->idle_data($i);
428 delete $self->{idle_mic};
429 unless ($self->{quit}) {
430 $mic->IsConnected or return "E: IDLE disconnected on $url";
431 $mic->done or return "E: IDLE DONE failed on $url: $!";
436 # idles on a single URI
437 sub watch_imap_idle_1 ($$$) {
438 my ($self, $url, $intvl) = @_;
439 my $uri = PublicInbox::URIimap->new($url);
440 my $sec = uri_section($uri);
441 my $mic_arg = $self->{mic_arg}->{$sec} or
442 die "BUG: no Mail::IMAPClient->new arg for $sec";
444 local $0 = $uri->mailbox." $sec";
445 until ($self->{quit}) {
446 $mic //= PublicInbox::IMAPClient->new(%$mic_arg);
448 if ($mic && $mic->IsConnected) {
449 $err = imap_fetch_all($self, $mic, $url);
450 $err //= imap_idle_once($self, $mic, $intvl, $url);
452 $err = "E: not connected: $!";
454 if ($err && !$self->{quit}) {
457 sleep 60 unless $self->{quit};
462 sub watch_atfork_child ($) {
464 delete $self->{idle_pids};
465 delete $self->{poll_pids};
466 delete $self->{opendirs};
467 PublicInbox::DS->Reset;
468 %SIG = (%SIG, %{$self->{sig}}, CHLD => 'DEFAULT');
469 PublicInbox::DS::sig_setmask($self->{oldset});
472 sub watch_atfork_parent ($) {
474 _done_for_now($self);
475 PublicInbox::DS::block_signals();
478 sub imap_idle_requeue { # DS::add_timer callback
479 my ($self, $url_intvl) = @_;
480 return if $self->{quit};
481 push @{$self->{idle_todo}}, $url_intvl;
485 sub imap_idle_reap { # PublicInbox::DS::dwaitpid callback
486 my ($self, $pid) = @_;
487 my $url_intvl = delete $self->{idle_pids}->{$pid} or
488 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
490 my ($url, $intvl) = @$url_intvl;
491 return if $self->{quit};
492 warn "W: PID=$pid on $url died: \$?=$?\n" if $?;
493 add_timer(60, \&imap_idle_requeue, $self, $url_intvl);
496 sub reap { # callback for EOFpipe
497 my ($pid, $cb, $self) = @{$_[0]};
498 my $ret = waitpid($pid, 0);
500 $cb->($self, $pid); # poll_fetch_reap || imap_idle_reap
502 warn "W: waitpid($pid) => ", $ret // "($!)", "\n";
506 sub imap_idle_fork ($$) {
507 my ($self, $url_intvl) = @_;
508 my ($url, $intvl) = @$url_intvl;
509 pipe(my ($r, $w)) or die "pipe: $!";
510 my $seed = rand(0xffffffff);
511 my $pid = fork // die "fork: $!";
514 eval { Net::SSLeay::randomize() };
516 watch_atfork_child($self);
517 watch_imap_idle_1($self, $url, $intvl);
521 $self->{idle_pids}->{$pid} = $url_intvl;
522 PublicInbox::EOFpipe->new($r, \&reap, [$pid, \&imap_idle_reap, $self]);
527 return if $self->{quit};
528 my $idle_todo = $self->{idle_todo};
529 if ($idle_todo && @$idle_todo) {
530 my $oldset = watch_atfork_parent($self);
532 while (my $url_intvl = shift(@$idle_todo)) {
533 imap_idle_fork($self, $url_intvl);
536 PublicInbox::DS::sig_setmask($oldset);
539 fs_scan_step($self) if $self->{mdre};
542 sub watch_imap_fetch_all ($$) {
543 my ($self, $urls) = @_;
544 for my $url (@$urls) {
545 my $uri = PublicInbox::URIimap->new($url);
546 my $sec = uri_section($uri);
547 my $mic_arg = $self->{mic_arg}->{$sec} or
548 die "BUG: no Mail::IMAPClient->new arg for $sec";
549 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or next;
550 my $err = imap_fetch_all($self, $mic, $url);
551 last if $self->{quit};
552 warn $err, "\n" if $err;
556 sub watch_nntp_fetch_all ($$) {
557 my ($self, $urls) = @_;
558 for my $url (@$urls) {
559 my $uri = uri_new($url);
560 my $sec = uri_section($uri);
561 my $nn_arg = $self->{nn_arg}->{$sec} or
562 die "BUG: no Net::NNTP->new arg for $sec";
563 my $nntp_opt = $self->{nntp_opt}->{$sec};
564 my $nn = nn_new($nn_arg, $nntp_opt, $url);
566 warn "E: $url: \$!=$!\n";
569 last if $self->{quit};
570 if (my $postconn = $nntp_opt->{-postconn}) {
571 for my $m_arg (@$postconn) {
572 my ($method, @args) = @$m_arg;
573 $nn->$method(@args) and next;
574 warn "E: <$url> $method failed\n";
579 last if $self->{quit};
581 my $err = nntp_fetch_all($self, $nn, $url);
582 warn $err, "\n" if $err;
587 sub poll_fetch_fork { # DS::add_timer callback
588 my ($self, $intvl, $urls) = @_;
589 return if $self->{quit};
590 pipe(my ($r, $w)) or die "pipe: $!";
591 my $oldset = watch_atfork_parent($self);
592 my $seed = rand(0xffffffff);
594 if (defined($pid) && $pid == 0) {
596 eval { Net::SSLeay::randomize() };
598 watch_atfork_child($self);
599 if ($urls->[0] =~ m!\Aimaps?://!i) {
600 watch_imap_fetch_all($self, $urls);
602 watch_nntp_fetch_all($self, $urls);
607 PublicInbox::DS::sig_setmask($oldset);
608 die "fork: $!" unless defined $pid;
609 $self->{poll_pids}->{$pid} = [ $intvl, $urls ];
610 PublicInbox::EOFpipe->new($r, \&reap, [$pid, \&poll_fetch_reap, $self]);
613 sub poll_fetch_reap {
614 my ($self, $pid) = @_;
615 my $intvl_urls = delete $self->{poll_pids}->{$pid} or
616 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
617 return if $self->{quit};
618 my ($intvl, $urls) = @$intvl_urls;
620 warn "W: PID=$pid died: \$?=$?\n", map { "$_\n" } @$urls;
622 warn("I: will check $_ in ${intvl}s\n") for @$urls;
623 add_timer($intvl, \&poll_fetch_fork, $self, $intvl, $urls);
626 sub watch_imap_init ($$) {
627 my ($self, $poll) = @_;
628 my $mics = imap_common_init($self); # read args from config
629 my $idle = []; # [ [ url1, intvl1 ], [url2, intvl2] ]
630 for my $url (keys %{$self->{imap}}) {
631 my $uri = PublicInbox::URIimap->new($url);
632 my $sec = uri_section($uri);
633 my $mic = $mics->{$sec};
634 my $intvl = $self->{imap_opt}->{$sec}->{pollInterval};
635 if ($mic->has_capability('IDLE') && !$intvl) {
636 $intvl = $self->{imap_opt}->{$sec}->{idleInterval};
637 push @$idle, [ $url, $intvl // () ];
639 push @{$poll->{$intvl || 120}}, $url;
643 $self->{idle_todo} = $idle;
644 PublicInbox::DS::requeue($self); # ->event_step to fork
648 # flesh out common NNTP-specific data structures
649 sub nntp_common_init ($) {
651 my $cfg = $self->{pi_cfg};
652 my $nn_args = {}; # scheme://authority => Net::NNTP->new arg
653 for my $url (@{$self->{nntp_order}}) {
654 my $sec = uri_section(uri_new($url));
656 # Debug and Timeout are passed to Net::NNTP->new
657 my $v = cfg_bool($cfg, 'nntp.Debug', $url);
658 $nn_args->{$sec}->{Debug} = $v if defined $v;
659 my $to = cfg_intvl($cfg, 'nntp.Timeout', $url);
660 $nn_args->{$sec}->{Timeout} = $to if $to;
662 # Net::NNTP post-connect commands
663 for my $k (qw(starttls compress)) {
664 $v = cfg_bool($cfg, "nntp.$k", $url) // next;
665 $self->{nntp_opt}->{$sec}->{$k} = $v;
669 for my $k (qw(pollInterval)) {
670 $to = cfg_intvl($cfg, "nntp.$k", $url) // next;
671 $self->{nntp_opt}->{$sec}->{$k} = $to;
677 sub nntp_fetch_all ($$$) {
678 my ($self, $nn, $url) = @_;
679 my $uri = uri_new($url);
680 my ($group, $num_a, $num_b) = $uri->group;
681 my $sec = uri_section($uri);
682 my ($nr, $beg, $end) = $nn->group($group);
683 unless (defined($nr)) {
684 chomp(my $msg = $nn->message);
685 return "E: GROUP $group <$sec> $msg";
688 # IMAPTracker is also used for tracking NNTP, UID == article number
689 # LIST.ACTIVE can get the equivalent of UIDVALIDITY, but that's
690 # expensive. So we assume newsgroups don't change:
691 my $itrk = PublicInbox::IMAPTracker->new($url);
692 my (undef, $l_art) = $itrk->get_last;
693 $l_art //= $beg; # initial import
695 # allow users to specify articles to refetch
696 # cf. https://tools.ietf.org/id/draft-gilman-news-url-01.txt
697 # nntp://example.com/inbox.foo/$num_a-$num_b
698 $l_art = $num_a if defined($num_a) && $num_a < $l_art;
699 $end = $num_b if defined($num_b) && $num_b < $end;
701 return if $l_art >= $end; # nothing to do
704 warn "I: $url fetching ARTICLE $beg..$end\n";
705 my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
707 local $SIG{__WARN__} = sub {
708 my $pfx = ($_[0] // '') =~ /^([A-Z]: )/g ? $1 : '';
709 $warn_cb->("$pfx$url ", $art ? ("ARTICLE $art") : (), "\n", @_);
711 my $inboxes = $self->{nntp}->{$url};
713 my $n = $self->{max_batch};
715 last if $self->{quit};
718 _done_for_now($self);
719 $itrk->update_last(0, $last_art);
720 $n = $self->{max_batch};
722 my $raw = $nn->article($art);
723 unless (defined($raw)) {
724 my $msg = $nn->message;
725 if ($nn->code == 421) { # pseudo response from Net::Cmd
728 } else { # probably just a deleted message (spam)
733 s/\r\n/\n/ for @$raw;
734 $raw = join('', @$raw);
736 for my $ibx (@$inboxes) {
737 my $eml = PublicInbox::Eml->new($raw);
738 import_eml($self, $ibx, $eml);
740 } elsif ($inboxes eq 'watchspam') {
741 my $eml = PublicInbox::Eml->new(\$raw);
742 $self->{pi_cfg}->each_inbox(\&remove_eml_i,
743 $self, $eml, "$url ARTICLE $art");
745 die "BUG: destination unknown $inboxes";
749 _done_for_now($self);
750 $itrk->update_last(0, $last_art);
754 sub watch_nntp_init ($$) {
755 my ($self, $poll) = @_;
756 eval { require Net::NNTP } or
757 die "Net::NNTP is required for NNTP:\n$@\n";
758 eval { require PublicInbox::IMAPTracker } or
759 die "DBD::SQLite is required for NNTP\n:$@\n";
761 my $nn_args = nntp_common_init($self); # read args from config
763 # make sure we can connect and cache the credentials in memory
764 $self->{nn_arg} = {}; # schema://authority => Net::NNTP->new args
765 for my $url (@{$self->{nntp_order}}) {
766 nn_for($self, $url, $nn_args);
768 for my $url (@{$self->{nntp_order}}) {
769 my $uri = uri_new($url);
770 my $sec = uri_section($uri);
771 my $intvl = $self->{nntp_opt}->{$sec}->{pollInterval};
772 push @{$poll->{$intvl || 120}}, $url;
776 sub watch { # main entry point
777 my ($self, $sig, $oldset) = @_;
778 $self->{oldset} = $oldset;
780 my $poll = {}; # intvl_seconds => [ url1, url2 ]
781 watch_imap_init($self, $poll) if $self->{imap};
782 watch_nntp_init($self, $poll) if $self->{nntp};
783 while (my ($intvl, $urls) = each %$poll) {
784 # poll all URLs for a given interval sequentially
785 add_timer(0, \&poll_fetch_fork, $self, $intvl, $urls);
787 watch_fs_init($self) if $self->{mdre};
788 PublicInbox::DS->SetPostLoopCallback(sub { !$self->quit_done });
789 PublicInbox::DS->EventLoop; # calls ->event_step
790 _done_for_now($self);
794 my ($self, $op) = @_;
795 push @{$self->{ops}}, $op;
796 PublicInbox::DS::requeue($self);
801 return if $self->{quit};
802 my $op = shift @{$self->{ops}};
803 local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
805 # continue existing scan
806 my $opendirs = $self->{opendirs};
807 my @dirnames = keys %$opendirs;
808 foreach my $dir (@dirnames) {
809 my $dh = delete $opendirs->{$dir};
810 my $n = $self->{max_batch};
811 while (my $fn = readdir($dh)) {
812 _try_path($self, "$dir/$fn");
815 $opendirs->{$dir} = $dh if $n < 0;
817 if ($op && $op eq 'full') {
818 foreach my $dir (keys %{$self->{mdmap}}) {
819 next if $opendirs->{$dir}; # already in progress
820 my $ok = opendir(my $dh, $dir);
822 warn "failed to open $dir: $!\n";
825 my $n = $self->{max_batch};
826 while (my $fn = readdir($dh)) {
827 _try_path($self, "$dir/$fn");
830 $opendirs->{$dir} = $dh if $n < 0;
833 _done_for_now($self);
834 # do we have more work to do?
835 PublicInbox::DS::requeue($self) if keys %$opendirs;
839 my ($self, $op) = @_;
840 push @{$self->{ops}}, $op;
845 my ($self, $ibx) = @_;
846 my $importers = $self->{importers};
847 my $im = $importers->{"$ibx"} ||= $ibx->importer(0);
848 if (scalar(keys(%$importers)) > 2) {
849 delete $importers->{"$ibx"};
850 _done_for_now($self);
853 $importers->{"$ibx"} = $im;
856 # XXX consider sharing with V2Writable, this only requires read-only access
857 sub content_exists ($$) {
858 my ($ibx, $eml) = @_;
859 my $over = $ibx->over or return;
860 my $mids = mids($eml);
861 my $chash = content_hash($eml);
863 for my $mid (@$mids) {
864 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
865 my $cmp = $ibx->smsg_eml($smsg) or return;
866 return 1 if $chash eq content_hash($cmp);
874 sub { # this gets called by (V2Writable||Import)->add
875 my ($mime, $ibx) = @_;
876 return if content_exists($ibx, $mime);
878 if ($sc->spamcheck($mime, \$tmp)) {
879 return PublicInbox::Eml->new(\$tmp);
881 warn $mime->header('Message-ID')." failed spam check\n";
887 $_[0] =~ s!\Amaildir:!! or return;
894 my ($cur, $ws, $ibx) = @_;
895 if ($ws && !ref($ws) && $ws eq 'watchspam') {
897 E: $cur is a spam folder and cannot be used for `$ibx->{name}' input