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'
50 # "publicinboxwatch" is the documented namespace
51 # "publicinboxlearn" is legacy but may be supported
53 foreach my $pfx (qw(publicinboxwatch publicinboxlearn)) {
54 my $k = "$pfx.watchspam";
55 defined(my $dirs = $cfg->{$k}) or next;
56 $dirs = PublicInbox::Config::_array($dirs);
57 for my $dir (@$dirs) {
59 if (is_maildir($dir)) {
60 # skip "new", no MUA has seen it, yet.
61 $mdmap{"$dir/cur"} = 'watchspam';
62 } elsif ($url = imap_url($dir)) {
63 $imap{$url} = 'watchspam';
64 } elsif ($url = nntp_url($dir)) {
65 $nntp{$url} = '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 ($url = imap_url($watch)) {
93 return if is_watchspam($url, $imap{$url}, $ibx);
94 compile_watchheaders($ibx);
95 push @{$imap{$url} ||= []}, $ibx;
96 } elsif ($url = nntp_url($watch)) {
97 return if is_watchspam($url, $nntp{$url}, $ibx);
98 compile_watchheaders($ibx);
99 push @{$nntp{$url} ||= []}, $ibx;
101 warn "watch unsupported: $k=$watch\n";
107 if (scalar keys %mdmap) {
108 $mdre = join('|', map { quotemeta($_) } keys %mdmap);
109 $mdre = qr!\A($mdre)/!;
111 return unless $mdre || scalar(keys %imap) || scalar(keys %nntp);
114 max_batch => 10, # avoid hogging locks for too long
115 spamcheck => $spamcheck,
119 imap => scalar keys %imap ? \%imap : undef,
120 nntp => scalar keys %nntp? \%nntp : undef,
122 opendirs => {}, # dirname => dirhandle (in progress scans)
123 ops => [], # 'quit', 'full'
129 local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
130 for my $im (values %{$self->{importers}}) {
131 next if !$im; # $im may be undef during cleanup
133 warn "$im->{ibx}->{name} ->done: $@\n" if $@;
137 sub remove_eml_i { # each_inbox callback
138 my ($ibx, $self, $eml, $loc) = @_;
141 # try to avoid taking a lock or unnecessary spawning
142 my $im = $self->{importers}->{"$ibx"};
144 if ((!$im || !$im->active) && $ibx->over) {
145 if (content_exists($ibx, $eml)) {
147 } elsif (my $scrub = $ibx->filter($im)) {
148 $scrubbed = $scrub->scrub($eml, 1);
149 if ($scrubbed && $scrubbed != REJECT &&
150 !content_exists($ibx, $scrubbed)) {
158 $im //= _importer_for($self, $ibx); # may spawn fast-import
159 $im->remove($eml, 'spam');
161 my $scrub = $ibx->filter($im);
162 $scrub ? $scrub->scrub($eml, 1) : undef;
164 if ($scrubbed && $scrubbed != REJECT) {
165 $im->remove($scrubbed, 'spam');
169 warn "error removing spam at: $loc from $ibx->{name}: $@\n";
170 _done_for_now($self);
175 my ($self, $path) = @_;
176 # path must be marked as (S)een
177 $path =~ /:2,[A-R]*S[T-Za-z]*\z/ or return;
178 my $eml = eml_from_path($path) or return;
179 local $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
180 $self->{pi_cfg}->each_inbox(\&remove_eml_i, $self, $eml, $path);
183 sub import_eml ($$$) {
184 my ($self, $ibx, $eml) = @_;
186 # any header match means it's eligible for the inbox:
187 if (my $watch_hdrs = $ibx->{-watchheaders}) {
189 for my $wh (@$watch_hdrs) {
190 my @v = $eml->header_raw($wh->[0]);
191 $ok = grep(/$wh->[1]/, @v) and last;
196 my $im = _importer_for($self, $ibx);
197 if (my $scrub = $ibx->filter($im)) {
198 my $scrubbed = $scrub->scrub($eml) or return;
199 $scrubbed == REJECT and return;
202 $im->add($eml, $self->{spamcheck});
205 warn "$ibx->{name} add failed: $@\n";
206 _done_for_now($self);
211 my ($self, $path) = @_;
212 my $fl = PublicInbox::MdirReader::maildir_path_flags($path) // return;
213 return if $fl =~ /[DT]/; # no Drafts or Trash
214 if ($path !~ $self->{mdre}) {
215 warn "unrecognized path: $path\n";
218 my $inboxes = $self->{mdmap}->{$1};
220 warn "unmappable dir: $1\n";
223 my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
224 local $SIG{__WARN__} = sub {
225 my $pfx = ($_[0] // '') =~ /^([A-Z]: )/g ? $1 : '';
226 $warn_cb->($pfx, "path: $path\n", @_);
228 if (!ref($inboxes) && $inboxes eq 'watchspam') {
229 return _remove_spam($self, $path);
231 foreach my $ibx (@$inboxes) {
232 my $eml = eml_from_path($path) or next;
233 import_eml($self, $ibx, $eml);
239 return unless $self->{quit};
241 # don't have reliable wakeups, keep signalling
243 for (qw(idle_pids poll_pids)) {
244 my $pids = $self->{$_} or next;
246 $done = undef if kill('QUIT', $_);
255 %{$self->{opendirs}} = ();
256 _done_for_now($self);
258 if (my $idle_mic = $self->{idle_mic}) {
259 eval { $idle_mic->done };
261 warn "IDLE DONE error: $@\n";
262 eval { $idle_mic->disconnect };
263 warn "IDLE LOGOUT error: $@\n" if $@;
268 sub watch_fs_init ($) {
271 delete $self->{done_timer};
272 _done_for_now($self);
274 my $cb = sub { # called by PublicInbox::DirIdle::event_step
275 _try_path($self, $_[0]->fullname);
276 $self->{done_timer} //= PublicInbox::DS::requeue($done);
278 require PublicInbox::DirIdle;
279 # inotify_create + EPOLL_CTL_ADD
280 PublicInbox::DirIdle->new([keys %{$self->{mdmap}}], $cb);
283 sub cfg_intvl ($$$) {
284 my ($cfg, $key, $url) = @_;
285 my $v = $cfg->urlmatch($key, $url) // return;
286 $v =~ /\A[0-9]+(?:\.[0-9]+)?\z/s and return $v + 0;
287 if (ref($v) eq 'ARRAY') {
288 $v = join(', ', @$v);
289 warn "W: $key has multiple values: $v\nW: $key ignored\n";
291 warn "W: $key=$v is not a numeric value in seconds\n";
296 my ($cfg, $key, $url) = @_;
297 my $orig = $cfg->urlmatch($key, $url) // return;
298 my $bool = $cfg->git_bool($orig);
299 warn "W: $key=$orig for $url is not boolean\n" unless defined($bool);
303 # flesh out common IMAP-specific data structures
304 sub imap_common_init ($) {
306 my $cfg = $self->{pi_cfg};
307 my $mic_args = {}; # scheme://authority => Mail:IMAPClient arg
308 for my $url (sort keys %{$self->{imap}}) {
309 my $uri = PublicInbox::URIimap->new($url);
310 my $sec = uri_section($uri);
311 for my $k (qw(Starttls Debug Compress)) {
312 my $bool = cfg_bool($cfg, "imap.$k", $url) // next;
313 $mic_args->{$sec}->{$k} = $bool;
315 my $to = cfg_intvl($cfg, 'imap.timeout', $url);
316 $mic_args->{$sec}->{Timeout} = $to if $to;
317 for my $k (qw(pollInterval idleInterval)) {
318 $to = cfg_intvl($cfg, "imap.$k", $url) // next;
319 $self->{imap_opt}->{$sec}->{$k} = $to;
321 my $k = 'imap.fetchBatchSize';
322 my $bs = $cfg->urlmatch($k, $url) // next;
323 if ($bs =~ /\A([0-9]+)\z/) {
324 $self->{imap_opt}->{$sec}->{batch_size} = $bs;
326 warn "$k=$bs is not an integer\n";
332 sub imap_import_msg ($$$$$) {
333 my ($self, $url, $uid, $raw, $flags) = @_;
334 # our target audience expects LF-only, save storage
335 $$raw =~ s/\r\n/\n/sg;
337 my $inboxes = $self->{imap}->{$url};
339 for my $ibx (@$inboxes) {
340 my $eml = PublicInbox::Eml->new($$raw);
341 import_eml($self, $ibx, $eml);
343 } elsif ($inboxes eq 'watchspam') {
344 return if $flags !~ /\\Seen\b/; # don't remove unseen messages
345 local $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
346 my $eml = PublicInbox::Eml->new($raw);
347 $self->{pi_cfg}->each_inbox(\&remove_eml_i,
348 $self, $eml, "$url UID:$uid");
350 die "BUG: destination unknown $inboxes";
354 sub imap_fetch_all ($$$) {
355 my ($self, $mic, $url) = @_;
356 my $uri = PublicInbox::URIimap->new($url);
357 my $sec = uri_section($uri);
358 my $mbx = $uri->mailbox;
359 $mic->Clear(1); # trim results history
360 $mic->examine($mbx) or return "E: EXAMINE $mbx ($sec) failed: $!";
361 my ($r_uidval, $r_uidnext);
362 for ($mic->Results) {
363 /^\* OK \[UIDVALIDITY ([0-9]+)\].*/ and $r_uidval = $1;
364 /^\* OK \[UIDNEXT ([0-9]+)\].*/ and $r_uidnext = $1;
365 last if $r_uidval && $r_uidnext;
367 $r_uidval //= $mic->uidvalidity($mbx) //
368 return "E: $url cannot get UIDVALIDITY";
369 $r_uidnext //= $mic->uidnext($mbx) //
370 return "E: $url cannot get UIDNEXT";
371 my $itrk = PublicInbox::IMAPTracker->new($url);
372 my ($l_uidval, $l_uid) = $itrk->get_last;
373 $l_uidval //= $r_uidval; # first time
375 if ($l_uidval != $r_uidval) {
376 return "E: $url UIDVALIDITY mismatch\n".
377 "E: local=$l_uidval != remote=$r_uidval";
379 my $r_uid = $r_uidnext - 1;
380 if ($l_uid != 1 && $l_uid > $r_uid) {
381 return "E: $url local UID exceeds remote ($l_uid > $r_uid)\n".
382 "E: $url strangely, UIDVALIDLITY matches ($l_uidval)\n";
384 return if $l_uid >= $r_uid; # nothing to do
386 warn "I: $url fetching UID $l_uid:$r_uid\n";
387 $mic->Uid(1); # the default, we hope
388 my $bs = $self->{imap_opt}->{$sec}->{batch_size} // 1;
389 my $req = $mic->imap4rev1 ? 'BODY.PEEK[]' : 'RFC822.PEEK';
391 # TODO: FLAGS may be useful for personal use
395 my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
396 local $SIG{__WARN__} = sub {
397 my $pfx = ($_[0] // '') =~ /^([A-Z]: )/g ? $1 : '';
399 $warn_cb->("$pfx$url UID:$batch\n", @_);
403 # I wish "UID FETCH $START:*" could work, but:
404 # 1) servers do not need to return results in any order
405 # 2) Mail::IMAPClient doesn't offer a streaming API
406 $uids = $mic->search("UID $l_uid:*") or
407 return "E: $url UID SEARCH $l_uid:* error: $!";
408 return if scalar(@$uids) == 0;
410 # RFC 3501 doesn't seem to indicate order of UID SEARCH
411 # responses, so sort it ourselves. Order matters so
412 # IMAPTracker can store the newest UID.
413 @$uids = sort { $a <=> $b } @$uids;
415 # Did we actually get new messages?
416 return if $uids->[0] < $l_uid;
418 $l_uid = $uids->[-1] + 1; # for next search
420 my $n = $self->{max_batch};
422 while (scalar @$uids) {
424 _done_for_now($self);
425 $itrk->update_last($r_uidval, $last_uid);
426 $n = $self->{max_batch};
428 my @batch = splice(@$uids, 0, $bs);
429 $batch = join(',', @batch);
430 local $0 = "UID:$batch $mbx $sec";
431 my $r = $mic->fetch_hash($batch, $req, 'FLAGS');
432 unless ($r) { # network error?
433 $err = "E: $url UID FETCH $batch error: $!";
436 for my $uid (@batch) {
437 # messages get deleted, so holes appear
438 my $per_uid = delete $r->{$uid} // next;
439 my $raw = delete($per_uid->{$key}) // next;
440 my $fl = $per_uid->{FLAGS} // '';
441 imap_import_msg($self, $url, $uid, \$raw, $fl);
443 last if $self->{quit};
445 last if $self->{quit};
447 _done_for_now($self);
448 $itrk->update_last($r_uidval, $last_uid);
449 } until ($err || $self->{quit});
453 sub imap_idle_once ($$$$) {
454 my ($self, $mic, $intvl, $url) = @_;
455 my $i = $intvl //= (29 * 60);
456 my $end = now() + $intvl;
457 warn "I: $url idling for ${intvl}s\n";
458 local $0 = "IDLE $0";
459 unless ($mic->idle) {
460 return if $self->{quit};
461 return "E: IDLE failed on $url: $!";
463 $self->{idle_mic} = $mic; # for ->quit
465 until ($self->{quit} || !$mic->IsConnected ||
466 grep(/^\* [0-9]+ EXISTS/, @res) || $i <= 0) {
467 @res = $mic->idle_data($i);
470 delete $self->{idle_mic};
471 unless ($self->{quit}) {
472 $mic->IsConnected or return "E: IDLE disconnected on $url";
473 $mic->done or return "E: IDLE DONE failed on $url: $!";
478 # idles on a single URI
479 sub watch_imap_idle_1 ($$$) {
480 my ($self, $url, $intvl) = @_;
481 my $uri = PublicInbox::URIimap->new($url);
482 my $sec = uri_section($uri);
483 my $mic_arg = $self->{mic_arg}->{$sec} or
484 die "BUG: no Mail::IMAPClient->new arg for $sec";
486 local $0 = $uri->mailbox." $sec";
487 until ($self->{quit}) {
488 $mic //= PublicInbox::IMAPClient->new(%$mic_arg);
490 if ($mic && $mic->IsConnected) {
491 $err = imap_fetch_all($self, $mic, $url);
492 $err //= imap_idle_once($self, $mic, $intvl, $url);
494 $err = "E: not connected: $!";
496 if ($err && !$self->{quit}) {
499 sleep 60 unless $self->{quit};
504 sub watch_atfork_child ($) {
506 delete $self->{idle_pids};
507 delete $self->{poll_pids};
508 delete $self->{opendirs};
509 PublicInbox::DS->Reset;
510 %SIG = (%SIG, %{$self->{sig}}, CHLD => 'DEFAULT');
511 PublicInbox::DS::sig_setmask($self->{oldset});
514 sub watch_atfork_parent ($) {
516 _done_for_now($self);
517 PublicInbox::DS::block_signals();
520 sub imap_idle_requeue { # DS::add_timer callback
521 my ($self, $url_intvl) = @_;
522 return if $self->{quit};
523 push @{$self->{idle_todo}}, $url_intvl;
527 sub imap_idle_reap { # PublicInbox::DS::dwaitpid callback
528 my ($self, $pid) = @_;
529 my $url_intvl = delete $self->{idle_pids}->{$pid} or
530 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
532 my ($url, $intvl) = @$url_intvl;
533 return if $self->{quit};
534 warn "W: PID=$pid on $url died: \$?=$?\n" if $?;
535 add_timer(60, \&imap_idle_requeue, $self, $url_intvl);
538 sub reap { # callback for EOFpipe
539 my ($pid, $cb, $self) = @{$_[0]};
540 my $ret = waitpid($pid, 0);
542 $cb->($self, $pid); # poll_fetch_reap || imap_idle_reap
544 warn "W: waitpid($pid) => ", $ret // "($!)", "\n";
548 sub imap_idle_fork ($$) {
549 my ($self, $url_intvl) = @_;
550 my ($url, $intvl) = @$url_intvl;
551 pipe(my ($r, $w)) or die "pipe: $!";
552 my $seed = rand(0xffffffff);
553 my $pid = fork // die "fork: $!";
556 eval { Net::SSLeay::randomize() };
558 watch_atfork_child($self);
559 watch_imap_idle_1($self, $url, $intvl);
563 $self->{idle_pids}->{$pid} = $url_intvl;
564 PublicInbox::EOFpipe->new($r, \&reap, [$pid, \&imap_idle_reap, $self]);
569 return if $self->{quit};
570 my $idle_todo = $self->{idle_todo};
571 if ($idle_todo && @$idle_todo) {
572 my $oldset = watch_atfork_parent($self);
574 while (my $url_intvl = shift(@$idle_todo)) {
575 imap_idle_fork($self, $url_intvl);
578 PublicInbox::DS::sig_setmask($oldset);
581 fs_scan_step($self) if $self->{mdre};
584 sub watch_imap_fetch_all ($$) {
585 my ($self, $urls) = @_;
586 for my $url (@$urls) {
587 my $uri = PublicInbox::URIimap->new($url);
588 my $sec = uri_section($uri);
589 my $mic_arg = $self->{mic_arg}->{$sec} or
590 die "BUG: no Mail::IMAPClient->new arg for $sec";
591 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or next;
592 my $err = imap_fetch_all($self, $mic, $url);
593 last if $self->{quit};
594 warn $err, "\n" if $err;
598 sub watch_nntp_fetch_all ($$) {
599 my ($self, $urls) = @_;
600 for my $url (@$urls) {
601 my $uri = uri_new($url);
602 my $sec = uri_section($uri);
603 my $nn_arg = $self->{nn_arg}->{$sec} or
604 die "BUG: no Net::NNTP->new arg for $sec";
605 my $nntp_opt = $self->{nntp_opt}->{$sec};
606 my $nn = nn_new($nn_arg, $nntp_opt, $url);
608 warn "E: $url: \$!=$!\n";
611 last if $self->{quit};
612 if (my $postconn = $nntp_opt->{-postconn}) {
613 for my $m_arg (@$postconn) {
614 my ($method, @args) = @$m_arg;
615 $nn->$method(@args) and next;
616 warn "E: <$url> $method failed\n";
621 last if $self->{quit};
623 my $err = nntp_fetch_all($self, $nn, $url);
624 warn $err, "\n" if $err;
629 sub poll_fetch_fork { # DS::add_timer callback
630 my ($self, $intvl, $urls) = @_;
631 return if $self->{quit};
632 pipe(my ($r, $w)) or die "pipe: $!";
633 my $oldset = watch_atfork_parent($self);
634 my $seed = rand(0xffffffff);
636 if (defined($pid) && $pid == 0) {
638 eval { Net::SSLeay::randomize() };
640 watch_atfork_child($self);
641 if ($urls->[0] =~ m!\Aimaps?://!i) {
642 watch_imap_fetch_all($self, $urls);
644 watch_nntp_fetch_all($self, $urls);
649 PublicInbox::DS::sig_setmask($oldset);
650 die "fork: $!" unless defined $pid;
651 $self->{poll_pids}->{$pid} = [ $intvl, $urls ];
652 PublicInbox::EOFpipe->new($r, \&reap, [$pid, \&poll_fetch_reap, $self]);
655 sub poll_fetch_reap {
656 my ($self, $pid) = @_;
657 my $intvl_urls = delete $self->{poll_pids}->{$pid} or
658 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
659 return if $self->{quit};
660 my ($intvl, $urls) = @$intvl_urls;
662 warn "W: PID=$pid died: \$?=$?\n", map { "$_\n" } @$urls;
664 warn("I: will check $_ in ${intvl}s\n") for @$urls;
665 add_timer($intvl, \&poll_fetch_fork, $self, $intvl, $urls);
668 sub watch_imap_init ($$) {
669 my ($self, $poll) = @_;
670 eval { require PublicInbox::IMAPClient } or
671 die "Mail::IMAPClient is required for IMAP:\n$@\n";
672 eval { require PublicInbox::IMAPTracker } or
673 die "DBD::SQLite is required for IMAP\n:$@\n";
675 my $mic_args = imap_common_init($self); # read args from config
677 # make sure we can connect and cache the credentials in memory
678 $self->{mic_arg} = {}; # schema://authority => IMAPClient->new args
679 my $mics = {}; # schema://authority => IMAPClient obj
680 for my $url (sort keys %{$self->{imap}}) {
681 my $uri = PublicInbox::URIimap->new($url);
682 $mics->{uri_section($uri)} //= mic_for($self, $url, $mic_args);
685 my $idle = []; # [ [ url1, intvl1 ], [url2, intvl2] ]
686 for my $url (keys %{$self->{imap}}) {
687 my $uri = PublicInbox::URIimap->new($url);
688 my $sec = uri_section($uri);
689 my $mic = $mics->{$sec};
690 my $intvl = $self->{imap_opt}->{$sec}->{pollInterval};
691 if ($mic->has_capability('IDLE') && !$intvl) {
692 $intvl = $self->{imap_opt}->{$sec}->{idleInterval};
693 push @$idle, [ $url, $intvl // () ];
695 push @{$poll->{$intvl || 120}}, $url;
699 $self->{idle_todo} = $idle;
700 PublicInbox::DS::requeue($self); # ->event_step to fork
704 # flesh out common NNTP-specific data structures
705 sub nntp_common_init ($) {
707 my $cfg = $self->{pi_cfg};
708 my $nn_args = {}; # scheme://authority => Net::NNTP->new arg
709 for my $url (sort keys %{$self->{nntp}}) {
710 my $sec = uri_section(uri_new($url));
712 # Debug and Timeout are passed to Net::NNTP->new
713 my $v = cfg_bool($cfg, 'nntp.Debug', $url);
714 $nn_args->{$sec}->{Debug} = $v if defined $v;
715 my $to = cfg_intvl($cfg, 'nntp.Timeout', $url);
716 $nn_args->{$sec}->{Timeout} = $to if $to;
718 # Net::NNTP post-connect commands
719 for my $k (qw(starttls compress)) {
720 $v = cfg_bool($cfg, "nntp.$k", $url) // next;
721 $self->{nntp_opt}->{$sec}->{$k} = $v;
725 for my $k (qw(pollInterval)) {
726 $to = cfg_intvl($cfg, "nntp.$k", $url) // next;
727 $self->{nntp_opt}->{$sec}->{$k} = $to;
733 sub nntp_fetch_all ($$$) {
734 my ($self, $nn, $url) = @_;
735 my $uri = uri_new($url);
736 my ($group, $num_a, $num_b) = $uri->group;
737 my $sec = uri_section($uri);
738 my ($nr, $beg, $end) = $nn->group($group);
739 unless (defined($nr)) {
740 chomp(my $msg = $nn->message);
741 return "E: GROUP $group <$sec> $msg";
744 # IMAPTracker is also used for tracking NNTP, UID == article number
745 # LIST.ACTIVE can get the equivalent of UIDVALIDITY, but that's
746 # expensive. So we assume newsgroups don't change:
747 my $itrk = PublicInbox::IMAPTracker->new($url);
748 my (undef, $l_art) = $itrk->get_last;
749 $l_art //= $beg; # initial import
751 # allow users to specify articles to refetch
752 # cf. https://tools.ietf.org/id/draft-gilman-news-url-01.txt
753 # nntp://example.com/inbox.foo/$num_a-$num_b
754 $l_art = $num_a if defined($num_a) && $num_a < $l_art;
755 $end = $num_b if defined($num_b) && $num_b < $end;
757 return if $l_art >= $end; # nothing to do
760 warn "I: $url fetching ARTICLE $beg..$end\n";
761 my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
763 local $SIG{__WARN__} = sub {
764 my $pfx = ($_[0] // '') =~ /^([A-Z]: )/g ? $1 : '';
765 $warn_cb->("$pfx$url ", $art ? ("ARTICLE $art") : (), "\n", @_);
767 my $inboxes = $self->{nntp}->{$url};
769 my $n = $self->{max_batch};
771 last if $self->{quit};
774 _done_for_now($self);
775 $itrk->update_last(0, $last_art);
776 $n = $self->{max_batch};
778 my $raw = $nn->article($art);
779 unless (defined($raw)) {
780 my $msg = $nn->message;
781 if ($nn->code == 421) { # pseudo response from Net::Cmd
784 } else { # probably just a deleted message (spam)
789 s/\r\n/\n/ for @$raw;
790 $raw = join('', @$raw);
792 for my $ibx (@$inboxes) {
793 my $eml = PublicInbox::Eml->new($raw);
794 import_eml($self, $ibx, $eml);
796 } elsif ($inboxes eq 'watchspam') {
797 my $eml = PublicInbox::Eml->new(\$raw);
798 $self->{pi_cfg}->each_inbox(\&remove_eml_i,
799 $self, $eml, "$url ARTICLE $art");
801 die "BUG: destination unknown $inboxes";
805 _done_for_now($self);
806 $itrk->update_last(0, $last_art);
810 sub watch_nntp_init ($$) {
811 my ($self, $poll) = @_;
812 eval { require Net::NNTP } or
813 die "Net::NNTP is required for NNTP:\n$@\n";
814 eval { require PublicInbox::IMAPTracker } or
815 die "DBD::SQLite is required for NNTP\n:$@\n";
817 my $nn_args = nntp_common_init($self); # read args from config
819 # make sure we can connect and cache the credentials in memory
820 $self->{nn_arg} = {}; # schema://authority => Net::NNTP->new args
821 for my $url (sort keys %{$self->{nntp}}) {
822 nn_for($self, $url, $nn_args);
824 for my $url (keys %{$self->{nntp}}) {
825 my $uri = uri_new($url);
826 my $sec = uri_section($uri);
827 my $intvl = $self->{nntp_opt}->{$sec}->{pollInterval};
828 push @{$poll->{$intvl || 120}}, $url;
832 sub watch { # main entry point
833 my ($self, $sig, $oldset) = @_;
834 $self->{oldset} = $oldset;
836 my $poll = {}; # intvl_seconds => [ url1, url2 ]
837 watch_imap_init($self, $poll) if $self->{imap};
838 watch_nntp_init($self, $poll) if $self->{nntp};
839 while (my ($intvl, $urls) = each %$poll) {
840 # poll all URLs for a given interval sequentially
841 add_timer(0, \&poll_fetch_fork, $self, $intvl, $urls);
843 watch_fs_init($self) if $self->{mdre};
844 PublicInbox::DS->SetPostLoopCallback(sub { !$self->quit_done });
845 PublicInbox::DS->EventLoop; # calls ->event_step
846 _done_for_now($self);
850 my ($self, $op) = @_;
851 push @{$self->{ops}}, $op;
852 PublicInbox::DS::requeue($self);
857 return if $self->{quit};
858 my $op = shift @{$self->{ops}};
859 local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
861 # continue existing scan
862 my $opendirs = $self->{opendirs};
863 my @dirnames = keys %$opendirs;
864 foreach my $dir (@dirnames) {
865 my $dh = delete $opendirs->{$dir};
866 my $n = $self->{max_batch};
867 while (my $fn = readdir($dh)) {
868 _try_path($self, "$dir/$fn");
871 $opendirs->{$dir} = $dh if $n < 0;
873 if ($op && $op eq 'full') {
874 foreach my $dir (keys %{$self->{mdmap}}) {
875 next if $opendirs->{$dir}; # already in progress
876 my $ok = opendir(my $dh, $dir);
878 warn "failed to open $dir: $!\n";
881 my $n = $self->{max_batch};
882 while (my $fn = readdir($dh)) {
883 _try_path($self, "$dir/$fn");
886 $opendirs->{$dir} = $dh if $n < 0;
889 _done_for_now($self);
890 # do we have more work to do?
891 PublicInbox::DS::requeue($self) if keys %$opendirs;
895 my ($self, $op) = @_;
896 push @{$self->{ops}}, $op;
901 my ($self, $ibx) = @_;
902 my $importers = $self->{importers};
903 my $im = $importers->{"$ibx"} ||= $ibx->importer(0);
904 if (scalar(keys(%$importers)) > 2) {
905 delete $importers->{"$ibx"};
906 _done_for_now($self);
909 $importers->{"$ibx"} = $im;
912 # XXX consider sharing with V2Writable, this only requires read-only access
913 sub content_exists ($$) {
914 my ($ibx, $eml) = @_;
915 my $over = $ibx->over or return;
916 my $mids = mids($eml);
917 my $chash = content_hash($eml);
919 for my $mid (@$mids) {
920 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
921 my $cmp = $ibx->smsg_eml($smsg) or return;
922 return 1 if $chash eq content_hash($cmp);
930 sub { # this gets called by (V2Writable||Import)->add
931 my ($mime, $ibx) = @_;
932 return if content_exists($ibx, $mime);
934 if ($sc->spamcheck($mime, \$tmp)) {
935 return PublicInbox::Eml->new(\$tmp);
937 warn $mime->header('Message-ID')." failed spam check\n";
943 $_[0] =~ s!\Amaildir:!! or return;
950 my ($cur, $ws, $ibx) = @_;
951 if ($ws && !ref($ws) && $ws eq 'watchspam') {
953 E: $cur is a spam folder and cannot be used for `$ibx->{name}' input