1 # Copyright (C) 2016-2020 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 # http://wiki2.dovecot.org/MailboxFormat/Maildir
6 package PublicInbox::Watch;
10 use PublicInbox::InboxWritable qw(eml_from_path warn_ignore_cb);
11 use PublicInbox::Filter::Base qw(REJECT);
12 use PublicInbox::Spamcheck;
13 use PublicInbox::Sigfd;
14 use PublicInbox::DS qw(now);
15 use PublicInbox::MID qw(mids);
16 use PublicInbox::ContentHash qw(content_hash);
19 sub compile_watchheaders ($) {
22 if (my $whs = $ibx->{watchheader}) {
24 my ($k, $v) = split(/:/, $_, 2);
25 # XXX should this be case-insensitive?
26 # Or, mutt-style, case-sensitive iff
27 # a capital letter exists?
28 push @$watch_hdrs, [ $k, qr/\Q$v\E/ ];
31 if (my $list_ids = $ibx->{listid}) {
33 # RFC2919 section 6 stipulates
34 # "case insensitive equality"
35 my $re = qr/<[ \t]*\Q$_\E[ \t]*>/i;
36 push @$watch_hdrs, ['List-Id', $re ];
39 $ibx->{-watchheaders} = $watch_hdrs if scalar @$watch_hdrs;
43 my ($class, $config) = @_;
45 my (%imap, %nntp); # url => [inbox objects] or 'watchspam'
47 # "publicinboxwatch" is the documented namespace
48 # "publicinboxlearn" is legacy but may be supported
50 foreach my $pfx (qw(publicinboxwatch publicinboxlearn)) {
51 my $k = "$pfx.watchspam";
52 defined(my $dirs = $config->{$k}) or next;
53 $dirs = PublicInbox::Config::_array($dirs);
54 for my $dir (@$dirs) {
56 if (is_maildir($dir)) {
57 # skip "new", no MUA has seen it, yet.
58 $mdmap{"$dir/cur"} = 'watchspam';
59 } elsif ($url = imap_url($dir)) {
60 $imap{$url} = 'watchspam';
61 } elsif ($url = nntp_url($dir)) {
62 $nntp{$url} = 'watchspam';
64 warn "unsupported $k=$dir\n";
69 my $k = 'publicinboxwatch.spamcheck';
71 my $spamcheck = PublicInbox::Spamcheck::get($config, $k, $default);
72 $spamcheck = _spamcheck_cb($spamcheck) if $spamcheck;
74 $config->each_inbox(sub {
75 # need to make all inboxes writable for spam removal:
76 my $ibx = $_[0] = PublicInbox::InboxWritable->new($_[0]);
78 my $watches = $ibx->{watch} or return;
79 $watches = PublicInbox::Config::_array($watches);
80 for my $watch (@$watches) {
82 if (is_maildir($watch)) {
83 compile_watchheaders($ibx);
84 my ($new, $cur) = ("$watch/new", "$watch/cur");
85 my $cur_dst = $mdmap{$cur} //= [];
86 return if is_watchspam($cur, $cur_dst, $ibx);
87 push @{$mdmap{$new} //= []}, $ibx;
89 } elsif ($url = imap_url($watch)) {
90 return if is_watchspam($url, $imap{$url}, $ibx);
91 compile_watchheaders($ibx);
92 push @{$imap{$url} ||= []}, $ibx;
93 } elsif ($url = nntp_url($watch)) {
94 return if is_watchspam($url, $nntp{$url}, $ibx);
95 compile_watchheaders($ibx);
96 push @{$nntp{$url} ||= []}, $ibx;
98 warn "watch unsupported: $k=$watch\n";
104 if (scalar keys %mdmap) {
105 $mdre = join('|', map { quotemeta($_) } keys %mdmap);
106 $mdre = qr!\A($mdre)/!;
108 return unless $mdre || scalar(keys %imap) || scalar(keys %nntp);
111 max_batch => 10, # avoid hogging locks for too long
112 spamcheck => $spamcheck,
116 imap => scalar keys %imap ? \%imap : undef,
117 nntp => scalar keys %nntp? \%nntp : undef,
119 opendirs => {}, # dirname => dirhandle (in progress scans)
120 ops => [], # 'quit', 'full'
126 local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
127 for my $im (values %{$self->{importers}}) {
128 next if !$im; # $im may be undef during cleanup
130 warn "$im->{ibx}->{name} ->done: $@\n" if $@;
134 sub remove_eml_i { # each_inbox callback
135 my ($ibx, $arg) = @_;
136 my ($self, $eml, $loc) = @$arg;
138 my $im = _importer_for($self, $ibx);
139 $im->remove($eml, 'spam');
140 if (my $scrub = $ibx->filter($im)) {
141 my $scrubbed = $scrub->scrub($eml, 1);
142 if ($scrubbed && $scrubbed != REJECT) {
143 $im->remove($scrubbed, 'spam');
148 warn "error removing spam at: $loc from $ibx->{name}: $@\n";
149 _done_for_now($self);
154 my ($self, $path) = @_;
155 # path must be marked as (S)een
156 $path =~ /:2,[A-R]*S[T-Za-z]*\z/ or return;
157 my $eml = eml_from_path($path) or return;
158 local $SIG{__WARN__} = warn_ignore_cb();
159 $self->{config}->each_inbox(\&remove_eml_i, [ $self, $eml, $path ]);
162 sub import_eml ($$$) {
163 my ($self, $ibx, $eml) = @_;
165 # any header match means it's eligible for the inbox:
166 if (my $watch_hdrs = $ibx->{-watchheaders}) {
168 for my $wh (@$watch_hdrs) {
169 my @v = $eml->header_raw($wh->[0]);
170 $ok = grep(/$wh->[1]/, @v) and last;
175 my $im = _importer_for($self, $ibx);
176 if (my $scrub = $ibx->filter($im)) {
177 my $scrubbed = $scrub->scrub($eml) or return;
178 $scrubbed == REJECT and return;
181 $im->add($eml, $self->{spamcheck});
184 warn "$ibx->{name} add failed: $@\n";
185 _done_for_now($self);
190 my ($self, $path) = @_;
191 return unless PublicInbox::InboxWritable::is_maildir_path($path);
192 if ($path !~ $self->{mdre}) {
193 warn "unrecognized path: $path\n";
196 my $inboxes = $self->{mdmap}->{$1};
198 warn "unmappable dir: $1\n";
201 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
202 local $SIG{__WARN__} = sub {
203 my $pfx = ($_[0] // '') =~ /^([A-Z]: )/g ? $1 : '';
204 $warn_cb->($pfx, "path: $path\n", @_);
206 if (!ref($inboxes) && $inboxes eq 'watchspam') {
207 return _remove_spam($self, $path);
209 foreach my $ibx (@$inboxes) {
210 my $eml = eml_from_path($path) or next;
211 import_eml($self, $ibx, $eml);
217 return unless $self->{quit};
219 # don't have reliable wakeups, keep signalling
221 for (qw(idle_pids poll_pids)) {
222 my $pids = $self->{$_} or next;
224 $done = undef if kill('QUIT', $_);
233 %{$self->{opendirs}} = ();
234 _done_for_now($self);
236 if (my $idle_mic = $self->{idle_mic}) {
237 eval { $idle_mic->done };
239 warn "IDLE DONE error: $@\n";
240 eval { $idle_mic->disconnect };
241 warn "IDLE LOGOUT error: $@\n" if $@;
246 sub watch_fs_init ($) {
249 delete $self->{done_timer};
250 _done_for_now($self);
253 _try_path($self, $_[0]->fullname);
254 $self->{done_timer} //= PublicInbox::DS::requeue($done);
256 require PublicInbox::DirIdle;
257 # inotify_create + EPOLL_CTL_ADD
258 PublicInbox::DirIdle->new([keys %{$self->{mdmap}}], $cb);
261 # avoid exposing deprecated "snews" to users.
262 my %SCHEME_MAP = ('snews' => 'nntps');
266 my $scheme = $uri->scheme;
267 $SCHEME_MAP{$scheme} // $scheme;
270 # returns the git config section name, e.g [imap "imaps://user@example.com"]
271 # without the mailbox, so we can share connections between different inboxes
272 sub uri_section ($) {
274 uri_scheme($uri) . '://' . $uri->authority;
277 sub cfg_intvl ($$$) {
278 my ($cfg, $key, $url) = @_;
279 my $v = $cfg->urlmatch($key, $url) // return;
280 $v =~ /\A[0-9]+(?:\.[0-9]+)?\z/s and return $v + 0;
281 if (ref($v) eq 'ARRAY') {
282 $v = join(', ', @$v);
283 warn "W: $key has multiple values: $v\nW: $key ignored\n";
285 warn "W: $key=$v is not a numeric value in seconds\n";
290 my ($cfg, $key, $url) = @_;
291 my $orig = $cfg->urlmatch($key, $url) // return;
292 my $bool = $cfg->git_bool($orig);
293 warn "W: $key=$orig for $url is not boolean\n" unless defined($bool);
297 # flesh out common IMAP-specific data structures
298 sub imap_common_init ($) {
300 my $cfg = $self->{config};
301 my $mic_args = {}; # scheme://authority => Mail:IMAPClient arg
302 for my $url (sort keys %{$self->{imap}}) {
303 my $uri = PublicInbox::URIimap->new($url);
304 my $sec = uri_section($uri);
305 for my $k (qw(Starttls Debug Compress)) {
306 my $bool = cfg_bool($cfg, "imap.$k", $url) // next;
307 $mic_args->{$sec}->{$k} = $bool;
309 my $to = cfg_intvl($cfg, 'imap.timeout', $url);
310 $mic_args->{$sec}->{Timeout} = $to if $to;
311 for my $k (qw(pollInterval idleInterval)) {
312 $to = cfg_intvl($cfg, "imap.$k", $url) // next;
313 $self->{imap_opt}->{$sec}->{$k} = $to;
315 my $k = 'imap.fetchBatchSize';
316 my $bs = $cfg->urlmatch($k, $url) // next;
317 if ($bs =~ /\A([0-9]+)\z/) {
318 $self->{imap_opt}->{$sec}->{batch_size} = $bs;
320 warn "$k=$bs is not an integer\n";
326 sub auth_anon_cb { '' }; # for Mail::IMAPClient::Authcallback
328 sub mic_for ($$$) { # mic = Mail::IMAPClient
329 my ($self, $url, $mic_args) = @_;
330 my $uri = PublicInbox::URIimap->new($url);
331 require PublicInbox::GitCredential;
334 protocol => $uri->scheme,
336 username => $uri->user,
337 password => $uri->password,
338 }, 'PublicInbox::GitCredential';
339 my $common = $mic_args->{uri_section($uri)} // {};
340 # IMAPClient and Net::Netrc both mishandles `0', so we pass `127.0.0.1'
341 my $host = $cred->{host};
342 $host = '127.0.0.1' if $host eq '0';
346 Ssl => $uri->scheme eq 'imaps',
347 Keepalive => 1, # SO_KEEPALIVE
348 %$common, # may set Starttls, Compress, Debug ....
350 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or
351 die "E: <$url> new: $@\n";
353 # default to using STARTTLS if it's available, but allow
354 # it to be disabled since I usually connect to localhost
355 if (!$mic_arg->{Ssl} && !defined($mic_arg->{Starttls}) &&
356 $mic->has_capability('STARTTLS') &&
357 $mic->can('starttls')) {
358 $mic->starttls or die "E: <$url> STARTTLS: $@\n";
361 # do we even need credentials?
362 if (!defined($cred->{username}) &&
363 $mic->has_capability('AUTH=ANONYMOUS')) {
367 $cred->check_netrc unless defined $cred->{password};
368 $cred->fill; # may prompt user here
369 $mic->User($mic_arg->{User} = $cred->{username});
370 $mic->Password($mic_arg->{Password} = $cred->{password});
371 } else { # AUTH=ANONYMOUS
372 $mic->Authmechanism($mic_arg->{Authmechanism} = 'ANONYMOUS');
373 $mic->Authcallback($mic_arg->{Authcallback} = \&auth_anon_cb);
375 if ($mic->login && $mic->IsAuthenticated) {
376 # success! keep IMAPClient->new arg in case we get disconnected
377 $self->{mic_arg}->{uri_section($uri)} = $mic_arg;
379 warn "E: <$url> LOGIN: $@\n";
382 $cred->run($mic ? 'approve' : 'reject') if $cred;
386 sub imap_import_msg ($$$$$) {
387 my ($self, $url, $uid, $raw, $flags) = @_;
388 # our target audience expects LF-only, save storage
389 $$raw =~ s/\r\n/\n/sg;
391 my $inboxes = $self->{imap}->{$url};
393 for my $ibx (@$inboxes) {
394 my $eml = PublicInbox::Eml->new($$raw);
395 my $x = import_eml($self, $ibx, $eml);
397 } elsif ($inboxes eq 'watchspam') {
398 # we don't remove unseen messages
399 if ($flags =~ /\\Seen\b/) {
400 local $SIG{__WARN__} = warn_ignore_cb();
401 my $eml = PublicInbox::Eml->new($raw);
402 my $arg = [ $self, $eml, "$url UID:$uid" ];
403 $self->{config}->each_inbox(\&remove_eml_i, $arg);
406 die "BUG: destination unknown $inboxes";
410 sub imap_fetch_all ($$$) {
411 my ($self, $mic, $url) = @_;
412 my $uri = PublicInbox::URIimap->new($url);
413 my $sec = uri_section($uri);
414 my $mbx = $uri->mailbox;
415 $mic->Clear(1); # trim results history
416 $mic->examine($mbx) or return "E: EXAMINE $mbx ($sec) failed: $!";
417 my ($r_uidval, $r_uidnext);
418 for ($mic->Results) {
419 /^\* OK \[UIDVALIDITY ([0-9]+)\].*/ and $r_uidval = $1;
420 /^\* OK \[UIDNEXT ([0-9]+)\].*/ and $r_uidnext = $1;
421 last if $r_uidval && $r_uidnext;
423 $r_uidval //= $mic->uidvalidity($mbx) //
424 return "E: $url cannot get UIDVALIDITY";
425 $r_uidnext //= $mic->uidnext($mbx) //
426 return "E: $url cannot get UIDNEXT";
427 my $itrk = PublicInbox::IMAPTracker->new($url);
428 my ($l_uidval, $l_uid) = $itrk->get_last;
429 $l_uidval //= $r_uidval; # first time
431 if ($l_uidval != $r_uidval) {
432 return "E: $url UIDVALIDITY mismatch\n".
433 "E: local=$l_uidval != remote=$r_uidval";
435 my $r_uid = $r_uidnext - 1;
436 if ($l_uid != 1 && $l_uid > $r_uid) {
437 return "E: $url local UID exceeds remote ($l_uid > $r_uid)\n".
438 "E: $url strangely, UIDVALIDLITY matches ($l_uidval)\n";
440 return if $l_uid >= $r_uid; # nothing to do
442 warn "I: $url fetching UID $l_uid:$r_uid\n";
443 $mic->Uid(1); # the default, we hope
444 my $bs = $self->{imap_opt}->{$sec}->{batch_size} // 1;
445 my $req = $mic->imap4rev1 ? 'BODY.PEEK[]' : 'RFC822.PEEK';
447 # TODO: FLAGS may be useful for personal use
451 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
452 local $SIG{__WARN__} = sub {
453 my $pfx = ($_[0] // '') =~ /^([A-Z]: )/g ? $1 : '';
455 $warn_cb->("$pfx$url UID:$batch\n", @_);
459 # I wish "UID FETCH $START:*" could work, but:
460 # 1) servers do not need to return results in any order
461 # 2) Mail::IMAPClient doesn't offer a streaming API
462 $uids = $mic->search("UID $l_uid:*") or
463 return "E: $url UID SEARCH $l_uid:* error: $!";
464 return if scalar(@$uids) == 0;
466 # RFC 3501 doesn't seem to indicate order of UID SEARCH
467 # responses, so sort it ourselves. Order matters so
468 # IMAPTracker can store the newest UID.
469 @$uids = sort { $a <=> $b } @$uids;
471 # Did we actually get new messages?
472 return if $uids->[0] < $l_uid;
474 $l_uid = $uids->[-1] + 1; # for next search
476 my $n = $self->{max_batch};
478 while (scalar @$uids) {
480 _done_for_now($self);
481 $itrk->update_last($r_uidval, $last_uid);
482 $n = $self->{max_batch};
484 my @batch = splice(@$uids, 0, $bs);
485 $batch = join(',', @batch);
486 local $0 = "UID:$batch $mbx $sec";
487 my $r = $mic->fetch_hash($batch, $req, 'FLAGS');
488 unless ($r) { # network error?
489 $err = "E: $url UID FETCH $batch error: $!";
492 for my $uid (@batch) {
493 # messages get deleted, so holes appear
494 my $per_uid = delete $r->{$uid} // next;
495 my $raw = delete($per_uid->{$key}) // next;
496 my $fl = $per_uid->{FLAGS} // '';
497 imap_import_msg($self, $url, $uid, \$raw, $fl);
499 last if $self->{quit};
501 last if $self->{quit};
503 _done_for_now($self);
504 $itrk->update_last($r_uidval, $last_uid);
505 } until ($err || $self->{quit});
509 sub imap_idle_once ($$$$) {
510 my ($self, $mic, $intvl, $url) = @_;
511 my $i = $intvl //= (29 * 60);
512 my $end = now() + $intvl;
513 warn "I: $url idling for ${intvl}s\n";
514 local $0 = "IDLE $0";
515 unless ($mic->idle) {
516 return if $self->{quit};
517 return "E: IDLE failed on $url: $!";
519 $self->{idle_mic} = $mic; # for ->quit
521 until ($self->{quit} || !$mic->IsConnected ||
522 grep(/^\* [0-9]+ EXISTS/, @res) || $i <= 0) {
523 @res = $mic->idle_data($i);
526 delete $self->{idle_mic};
527 unless ($self->{quit}) {
528 $mic->IsConnected or return "E: IDLE disconnected on $url";
529 $mic->done or return "E: IDLE DONE failed on $url: $!";
534 # idles on a single URI
535 sub watch_imap_idle_1 ($$$) {
536 my ($self, $url, $intvl) = @_;
537 my $uri = PublicInbox::URIimap->new($url);
538 my $sec = uri_section($uri);
539 my $mic_arg = $self->{mic_arg}->{$sec} or
540 die "BUG: no Mail::IMAPClient->new arg for $sec";
542 local $0 = $uri->mailbox." $sec";
543 until ($self->{quit}) {
544 $mic //= PublicInbox::IMAPClient->new(%$mic_arg);
546 if ($mic && $mic->IsConnected) {
547 $err = imap_fetch_all($self, $mic, $url);
548 $err //= imap_idle_once($self, $mic, $intvl, $url);
550 $err = "not connected: $!";
552 if ($err && !$self->{quit}) {
555 sleep 60 unless $self->{quit};
560 sub watch_atfork_child ($) {
562 delete $self->{idle_pids};
563 delete $self->{poll_pids};
564 delete $self->{opendirs};
565 PublicInbox::DS->Reset;
566 %SIG = (%SIG, %{$self->{sig}}, CHLD => 'DEFAULT');
567 PublicInbox::Sigfd::sig_setmask($self->{oldset});
570 sub watch_atfork_parent ($) {
572 _done_for_now($self);
575 sub imap_idle_requeue ($) { # DS::add_timer callback
576 my ($self, $url_intvl) = @{$_[0]};
577 return if $self->{quit};
578 push @{$self->{idle_todo}}, $url_intvl;
582 sub imap_idle_reap { # PublicInbox::DS::dwaitpid callback
583 my ($self, $pid) = @_;
584 my $url_intvl = delete $self->{idle_pids}->{$pid} or
585 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
587 my ($url, $intvl) = @$url_intvl;
588 return if $self->{quit};
589 warn "W: PID=$pid on $url died: \$?=$?\n" if $?;
590 PublicInbox::DS::add_timer(60,
591 \&imap_idle_requeue, [ $self, $url_intvl ]);
594 sub imap_idle_fork ($$) {
595 my ($self, $url_intvl) = @_;
596 my ($url, $intvl) = @$url_intvl;
597 defined(my $pid = fork) or die "fork: $!";
599 watch_atfork_child($self);
600 watch_imap_idle_1($self, $url, $intvl);
603 $self->{idle_pids}->{$pid} = $url_intvl;
604 PublicInbox::DS::dwaitpid($pid, \&imap_idle_reap, $self);
609 return if $self->{quit};
610 my $idle_todo = $self->{idle_todo};
611 if ($idle_todo && @$idle_todo) {
612 watch_atfork_parent($self);
613 while (my $url_intvl = shift(@$idle_todo)) {
614 imap_idle_fork($self, $url_intvl);
617 goto(&fs_scan_step) if $self->{mdre};
620 sub watch_imap_fetch_all ($$) {
621 my ($self, $urls) = @_;
622 for my $url (@$urls) {
623 my $uri = PublicInbox::URIimap->new($url);
624 my $sec = uri_section($uri);
625 my $mic_arg = $self->{mic_arg}->{$sec} or
626 die "BUG: no Mail::IMAPClient->new arg for $sec";
627 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or next;
628 my $err = imap_fetch_all($self, $mic, $url);
629 last if $self->{quit};
630 warn $err, "\n" if $err;
634 sub watch_nntp_fetch_all ($$) {
635 my ($self, $urls) = @_;
636 for my $url (@$urls) {
637 my $uri = uri_new($url);
638 my $sec = uri_section($uri);
639 my $nn_arg = $self->{nn_arg}->{$sec} or
640 die "BUG: no Net::NNTP->new arg for $sec";
641 my $nntp_opt = $self->{nntp_opt}->{$sec};
642 my $nn = nn_new($nn_arg, $nntp_opt, $url);
644 warn "E: $url: \$!=$!\n";
647 last if $self->{quit};
648 if (my $postconn = $nntp_opt->{-postconn}) {
649 for my $m_arg (@$postconn) {
650 my ($method, @args) = @$m_arg;
651 $nn->$method(@args) and next;
652 warn "E: <$url> $method failed\n";
657 last if $self->{quit};
659 my $err = nntp_fetch_all($self, $nn, $url);
660 warn $err, "\n" if $err;
665 sub poll_fetch_fork ($) { # DS::add_timer callback
666 my ($self, $intvl, $urls) = @{$_[0]};
667 return if $self->{quit};
668 watch_atfork_parent($self);
669 defined(my $pid = fork) or die "fork: $!";
671 watch_atfork_child($self);
672 if ($urls->[0] =~ m!\Aimaps?://!i) {
673 watch_imap_fetch_all($self, $urls);
675 watch_nntp_fetch_all($self, $urls);
679 $self->{poll_pids}->{$pid} = [ $intvl, $urls ];
680 PublicInbox::DS::dwaitpid($pid, \&poll_fetch_reap, $self);
683 sub poll_fetch_reap { # PublicInbox::DS::dwaitpid callback
684 my ($self, $pid) = @_;
685 my $intvl_urls = delete $self->{poll_pids}->{$pid} or
686 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
687 return if $self->{quit};
688 my ($intvl, $urls) = @$intvl_urls;
690 warn "W: PID=$pid died: \$?=$?\n", map { "$_\n" } @$urls;
692 warn("I: will check $_ in ${intvl}s\n") for @$urls;
693 PublicInbox::DS::add_timer($intvl, \&poll_fetch_fork,
694 [$self, $intvl, $urls]);
697 sub watch_imap_init ($$) {
698 my ($self, $poll) = @_;
699 eval { require PublicInbox::IMAPClient } or
700 die "Mail::IMAPClient is required for IMAP:\n$@\n";
701 eval { require PublicInbox::IMAPTracker } or
702 die "DBD::SQLite is required for IMAP\n:$@\n";
704 my $mic_args = imap_common_init($self); # read args from config
706 # make sure we can connect and cache the credentials in memory
707 $self->{mic_arg} = {}; # schema://authority => IMAPClient->new args
708 my $mics = {}; # schema://authority => IMAPClient obj
709 for my $url (sort keys %{$self->{imap}}) {
710 my $uri = PublicInbox::URIimap->new($url);
711 $mics->{uri_section($uri)} //= mic_for($self, $url, $mic_args);
714 my $idle = []; # [ [ url1, intvl1 ], [url2, intvl2] ]
715 for my $url (keys %{$self->{imap}}) {
716 my $uri = PublicInbox::URIimap->new($url);
717 my $sec = uri_section($uri);
718 my $mic = $mics->{$sec};
719 my $intvl = $self->{imap_opt}->{$sec}->{pollInterval};
720 if ($mic->has_capability('IDLE') && !$intvl) {
721 $intvl = $self->{imap_opt}->{$sec}->{idleInterval};
722 push @$idle, [ $url, $intvl // () ];
724 push @{$poll->{$intvl || 120}}, $url;
728 $self->{idle_todo} = $idle;
729 PublicInbox::DS::requeue($self); # ->event_step to fork
733 # flesh out common NNTP-specific data structures
734 sub nntp_common_init ($) {
736 my $cfg = $self->{config};
737 my $nn_args = {}; # scheme://authority => Net::NNTP->new arg
738 for my $url (sort keys %{$self->{nntp}}) {
739 my $sec = uri_section(uri_new($url));
741 # Debug and Timeout are passed to Net::NNTP->new
742 my $v = cfg_bool($cfg, 'nntp.Debug', $url);
743 $nn_args->{$sec}->{Debug} = $v if defined $v;
744 my $to = cfg_intvl($cfg, 'nntp.Timeout', $url);
745 $nn_args->{$sec}->{Timeout} = $to if $to;
747 # Net::NNTP post-connect commands
748 for my $k (qw(starttls compress)) {
749 $v = cfg_bool($cfg, "nntp.$k", $url) // next;
750 $self->{nntp_opt}->{$sec}->{$k} = $v;
754 for my $k (qw(pollInterval)) {
755 $to = cfg_intvl($cfg, "nntp.$k", $url) // next;
756 $self->{nntp_opt}->{$sec}->{$k} = $to;
762 # Net::NNTP doesn't support CAPABILITIES, yet
763 sub try_starttls ($) {
765 return if $host =~ /\.onion\z/s;
766 return if $host =~ /\A127\.[0-9]+\.[0-9]+\.[0-9]+\z/s;
767 return if $host eq '::1';
772 my ($nn_arg, $nntp_opt, $url) = @_;
773 my $nn = Net::NNTP->new(%$nn_arg) or die "E: <$url> new: $!\n";
775 # default to using STARTTLS if it's available, but allow
776 # it to be disabled for localhost/VPN users
777 if (!$nn_arg->{SSL} && $nn->can('starttls')) {
778 if (!defined($nntp_opt->{starttls}) &&
779 try_starttls($nn_arg->{Host})) {
780 # soft fail by default
781 $nn->starttls or warn <<"";
782 W: <$url> STARTTLS tried and failed (not requested)
784 } elsif ($nntp_opt->{starttls}) {
785 # hard fail if explicitly configured
786 $nn->starttls or die <<"";
787 E: <$url> STARTTLS requested and failed
790 } elsif ($nntp_opt->{starttls}) {
791 $nn->can('starttls') or
792 die "E: <$url> Net::NNTP too old for STARTTLS\n";
793 $nn->starttls or die <<"";
794 E: <$url> STARTTLS requested and failed
800 sub nn_for ($$$) { # nn = Net::NNTP
801 my ($self, $url, $nn_args) = @_;
802 my $uri = uri_new($url);
803 my $sec = uri_section($uri);
804 my $nntp_opt = $self->{nntp_opt}->{$sec} //= {};
805 my $host = $uri->host;
806 # Net::NNTP and Net::Netrc both mishandle `0', so we pass `127.0.0.1'
807 $host = '127.0.0.1' if $host eq '0';
810 if (defined(my $ui = $uri->userinfo)) {
811 require PublicInbox::GitCredential;
814 protocol => uri_scheme($uri),
816 }, 'PublicInbox::GitCredential';
817 ($u, $p) = split(/:/, $ui, 2);
818 ($cred->{username}, $cred->{password}) = ($u, $p);
819 $cred->check_netrc unless defined $p;
821 my $common = $nn_args->{$sec} // {};
825 SSL => $uri->secure, # snews == nntps
826 %$common, # may Debug ....
828 my $nn = nn_new($nn_arg, $nntp_opt, $url);
831 $cred->fill; # may prompt user here
832 if ($nn->authinfo($u, $p)) {
833 push @{$nntp_opt->{-postconn}}, [ 'authinfo', $u, $p ];
835 warn "E: <$url> AUTHINFO $u XXXX failed\n";
840 if ($nntp_opt->{compress}) {
841 # https://rt.cpan.org/Ticket/Display.html?id=129967
842 if ($nn->can('compress')) {
844 push @{$nntp_opt->{-postconn}}, [ 'compress' ];
846 warn "W: <$url> COMPRESS failed\n";
849 delete $nntp_opt->{compress};
851 W: <$url> COMPRESS not supported by Net::NNTP
852 W: see https://rt.cpan.org/Ticket/Display.html?id=129967 for updates
857 $self->{nn_arg}->{$sec} = $nn_arg;
858 $cred->run($nn ? 'approve' : 'reject') if $cred;
862 sub nntp_fetch_all ($$$) {
863 my ($self, $nn, $url) = @_;
864 my $uri = uri_new($url);
865 my ($group, $num_a, $num_b) = $uri->group;
866 my $sec = uri_section($uri);
867 my ($nr, $beg, $end) = $nn->group($group);
868 unless (defined($nr)) {
869 chomp(my $msg = $nn->message);
870 return "E: GROUP $group <$sec> $msg";
873 # IMAPTracker is also used for tracking NNTP, UID == article number
874 # LIST.ACTIVE can get the equivalent of UIDVALIDITY, but that's
875 # expensive. So we assume newsgroups don't change:
876 my $itrk = PublicInbox::IMAPTracker->new($url);
877 my (undef, $l_art) = $itrk->get_last;
878 $l_art //= $beg; # initial import
880 # allow users to specify articles to refetch
881 # cf. https://tools.ietf.org/id/draft-gilman-news-url-01.txt
882 # nntp://example.com/inbox.foo/$num_a-$num_b
883 $l_art = $num_a if defined($num_a) && $num_a < $l_art;
884 $end = $num_b if defined($num_b) && $num_b < $end;
886 return if $l_art >= $end; # nothing to do
889 warn "I: $url fetching ARTICLE $beg..$end\n";
890 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
892 local $SIG{__WARN__} = sub {
893 my $pfx = ($_[0] // '') =~ /^([A-Z]: )/g ? $1 : '';
894 $warn_cb->("$pfx$url ", $art ? ("ARTICLE $art") : (), "\n", @_);
896 my $inboxes = $self->{nntp}->{$url};
898 my $n = $self->{max_batch};
900 last if $self->{quit};
903 _done_for_now($self);
904 $itrk->update_last(0, $last_art);
905 $n = $self->{max_batch};
907 my $raw = $nn->article($art);
908 unless (defined($raw)) {
909 my $msg = $nn->message;
910 if ($nn->code == 421) { # pseudo response from Net::Cmd
913 } else { # probably just a deleted message (spam)
918 s/\r\n/\n/ for @$raw;
919 $raw = join('', @$raw);
921 for my $ibx (@$inboxes) {
922 my $eml = PublicInbox::Eml->new($raw);
923 import_eml($self, $ibx, $eml);
925 } elsif ($inboxes eq 'watchspam') {
926 my $eml = PublicInbox::Eml->new(\$raw);
927 my $arg = [ $self, $eml, "$url ARTICLE $art" ];
928 $self->{config}->each_inbox(\&remove_eml_i, $arg);
930 die "BUG: destination unknown $inboxes";
934 _done_for_now($self);
935 $itrk->update_last(0, $last_art);
939 sub watch_nntp_init ($$) {
940 my ($self, $poll) = @_;
941 eval { require Net::NNTP } or
942 die "Net::NNTP is required for NNTP:\n$@\n";
943 eval { require PublicInbox::IMAPTracker } or
944 die "DBD::SQLite is required for NNTP\n:$@\n";
946 my $nn_args = nntp_common_init($self); # read args from config
948 # make sure we can connect and cache the credentials in memory
949 $self->{nn_arg} = {}; # schema://authority => Net::NNTP->new args
950 for my $url (sort keys %{$self->{nntp}}) {
951 nn_for($self, $url, $nn_args);
953 for my $url (keys %{$self->{nntp}}) {
954 my $uri = uri_new($url);
955 my $sec = uri_section($uri);
956 my $intvl = $self->{nntp_opt}->{$sec}->{pollInterval};
957 push @{$poll->{$intvl || 120}}, $url;
962 my ($self, $sig, $oldset) = @_;
963 $self->{oldset} = $oldset;
965 my $poll = {}; # intvl_seconds => [ url1, url2 ]
966 watch_imap_init($self, $poll) if $self->{imap};
967 watch_nntp_init($self, $poll) if $self->{nntp};
968 while (my ($intvl, $urls) = each %$poll) {
969 # poll all URLs for a given interval sequentially
970 PublicInbox::DS::add_timer(0, \&poll_fetch_fork,
971 [$self, $intvl, $urls]);
973 watch_fs_init($self) if $self->{mdre};
974 PublicInbox::DS->SetPostLoopCallback(sub { !$self->quit_done });
975 PublicInbox::DS->EventLoop;
976 _done_for_now($self);
980 my ($self, $op) = @_;
981 push @{$self->{ops}}, $op;
982 PublicInbox::DS::requeue($self);
987 return if $self->{quit};
988 my $op = shift @{$self->{ops}};
989 local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
991 # continue existing scan
992 my $opendirs = $self->{opendirs};
993 my @dirnames = keys %$opendirs;
994 foreach my $dir (@dirnames) {
995 my $dh = delete $opendirs->{$dir};
996 my $n = $self->{max_batch};
997 while (my $fn = readdir($dh)) {
998 _try_path($self, "$dir/$fn");
1001 $opendirs->{$dir} = $dh if $n < 0;
1003 if ($op && $op eq 'full') {
1004 foreach my $dir (keys %{$self->{mdmap}}) {
1005 next if $opendirs->{$dir}; # already in progress
1006 my $ok = opendir(my $dh, $dir);
1008 warn "failed to open $dir: $!\n";
1011 my $n = $self->{max_batch};
1012 while (my $fn = readdir($dh)) {
1013 _try_path($self, "$dir/$fn");
1016 $opendirs->{$dir} = $dh if $n < 0;
1019 _done_for_now($self);
1020 # do we have more work to do?
1021 PublicInbox::DS::requeue($self) if keys %$opendirs;
1025 my ($self, $op) = @_;
1026 push @{$self->{ops}}, $op;
1031 my ($self, $ibx) = @_;
1032 my $importers = $self->{importers};
1033 my $im = $importers->{"$ibx"} ||= $ibx->importer(0);
1034 if (scalar(keys(%$importers)) > 2) {
1035 delete $importers->{"$ibx"};
1036 _done_for_now($self);
1039 $importers->{"$ibx"} = $im;
1042 # XXX consider sharing with V2Writable, this only requires read-only access
1043 sub content_exists ($$) {
1044 my ($ibx, $eml) = @_;
1045 my $over = $ibx->over or return;
1046 my $mids = mids($eml);
1047 my $chash = content_hash($eml);
1049 for my $mid (@$mids) {
1050 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
1051 my $cmp = $ibx->smsg_eml($smsg) or return;
1052 return 1 if $chash eq content_hash($cmp);
1061 my ($mime, $ibx) = @_;
1062 return if content_exists($ibx, $mime);
1064 if ($sc->spamcheck($mime, \$tmp)) {
1065 return PublicInbox::Eml->new(\$tmp);
1067 warn $mime->header('Message-ID')." failed spam check\n";
1073 $_[0] =~ s!\Amaildir:!! or return;
1080 my ($cur, $ws, $ibx) = @_;
1081 if ($ws && !ref($ws) && $ws eq 'watchspam') {
1083 E: $cur is a spam folder and cannot be used for `$ibx->{name}' input
1093 # URI::snews exists, URI::nntps does not, so use URI::snews
1094 $url =~ s!\Anntps://!snews://!i;
1100 require PublicInbox::URIimap;
1101 my $uri = PublicInbox::URIimap->new($url);
1102 $uri ? $uri->canonical->as_string : undef;
1105 my %IS_NNTP = (news => 1, snews => 1, nntp => 1);
1109 my $uri = uri_new($url);
1110 return unless $uri && $IS_NNTP{$uri->scheme} && $uri->group;
1111 $url = $uri->canonical->as_string;
1112 # nntps is IANA registered, snews is deprecated
1113 $url =~ s!\Asnews://!nntps://!;