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::WatchMaildir;
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 spamcheck => $spamcheck,
115 imap => scalar keys %imap ? \%imap : undef,
116 nntp => scalar keys %nntp? \%nntp : undef,
118 opendirs => {}, # dirname => dirhandle (in progress scans)
119 ops => [], # 'quit', 'full'
125 local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
126 for my $im (values %{$self->{importers}}) {
127 next if !$im; # $im may be undef during cleanup
129 warn "$im->{ibx}->{name} ->done: $@\n" if $@;
133 sub remove_eml_i { # each_inbox callback
134 my ($ibx, $arg) = @_;
135 my ($self, $eml, $loc) = @$arg;
137 my $im = _importer_for($self, $ibx);
138 $im->remove($eml, 'spam');
139 if (my $scrub = $ibx->filter($im)) {
140 my $scrubbed = $scrub->scrub($eml, 1);
141 if ($scrubbed && $scrubbed != REJECT) {
142 $im->remove($scrubbed, 'spam');
147 warn "error removing spam at: $loc from $ibx->{name}: $@\n";
148 _done_for_now($self);
153 my ($self, $path) = @_;
154 # path must be marked as (S)een
155 $path =~ /:2,[A-R]*S[T-Za-z]*\z/ or return;
156 my $eml = eml_from_path($path) or return;
157 local $SIG{__WARN__} = warn_ignore_cb();
158 $self->{config}->each_inbox(\&remove_eml_i, [ $self, $eml, $path ]);
161 sub import_eml ($$$) {
162 my ($self, $ibx, $eml) = @_;
164 # any header match means it's eligible for the inbox:
165 if (my $watch_hdrs = $ibx->{-watchheaders}) {
167 for my $wh (@$watch_hdrs) {
168 my @v = $eml->header_raw($wh->[0]);
169 $ok = grep(/$wh->[1]/, @v) and last;
174 my $im = _importer_for($self, $ibx);
175 if (my $scrub = $ibx->filter($im)) {
176 my $scrubbed = $scrub->scrub($eml) or return;
177 $scrubbed == REJECT and return;
180 $im->add($eml, $self->{spamcheck});
183 warn "$ibx->{name} add failed: $@\n";
184 _done_for_now($self);
189 my ($self, $path) = @_;
190 return unless PublicInbox::InboxWritable::is_maildir_path($path);
191 if ($path !~ $self->{mdre}) {
192 warn "unrecognized path: $path\n";
195 my $inboxes = $self->{mdmap}->{$1};
197 warn "unmappable dir: $1\n";
200 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
201 local $SIG{__WARN__} = sub {
202 my $pfx = ($_[0] // '') =~ /^([A-Z]: )/g ? $1 : '';
203 $warn_cb->($pfx, "path: $path\n", @_);
205 if (!ref($inboxes) && $inboxes eq 'watchspam') {
206 return _remove_spam($self, $path);
208 foreach my $ibx (@$inboxes) {
209 my $eml = eml_from_path($path) or next;
210 import_eml($self, $ibx, $eml);
216 return unless $self->{quit};
218 # don't have reliable wakeups, keep signalling
220 for (qw(idle_pids poll_pids)) {
221 my $pids = $self->{$_} or next;
223 $done = undef if kill('QUIT', $_);
232 %{$self->{opendirs}} = ();
233 _done_for_now($self);
235 if (my $idle_mic = $self->{idle_mic}) {
236 eval { $idle_mic->done };
238 warn "IDLE DONE error: $@\n";
239 eval { $idle_mic->disconnect };
240 warn "IDLE LOGOUT error: $@\n" if $@;
245 sub watch_fs_init ($) {
248 delete $self->{done_timer};
249 _done_for_now($self);
252 _try_path($self, $_[0]->fullname);
253 $self->{done_timer} //= PublicInbox::DS::requeue($done);
255 require PublicInbox::DirIdle;
256 # inotify_create + EPOLL_CTL_ADD
257 PublicInbox::DirIdle->new([keys %{$self->{mdmap}}], $cb);
260 # avoid exposing deprecated "snews" to users.
261 my %SCHEME_MAP = ('snews' => 'nntps');
265 my $scheme = $uri->scheme;
266 $SCHEME_MAP{$scheme} // $scheme;
269 # returns the git config section name, e.g [imap "imaps://user@example.com"]
270 # without the mailbox, so we can share connections between different inboxes
271 sub uri_section ($) {
273 uri_scheme($uri) . '://' . $uri->authority;
276 sub cfg_intvl ($$$) {
277 my ($cfg, $key, $url) = @_;
278 my $v = $cfg->urlmatch($key, $url) // return;
279 $v =~ /\A[0-9]+(?:\.[0-9]+)?\z/s and return $v + 0;
280 if (ref($v) eq 'ARRAY') {
281 $v = join(', ', @$v);
282 warn "W: $key has multiple values: $v\nW: $key ignored\n";
284 warn "W: $key=$v is not a numeric value in seconds\n";
289 my ($cfg, $key, $url) = @_;
290 my $orig = $cfg->urlmatch($key, $url) // return;
291 my $bool = $cfg->git_bool($orig);
292 warn "W: $key=$orig for $url is not boolean\n" unless defined($bool);
296 # flesh out common IMAP-specific data structures
297 sub imap_common_init ($) {
299 my $cfg = $self->{config};
300 my $mic_args = {}; # scheme://authority => Mail:IMAPClient arg
301 for my $url (sort keys %{$self->{imap}}) {
302 my $uri = PublicInbox::URIimap->new($url);
303 my $sec = uri_section($uri);
304 for my $k (qw(Starttls Debug Compress)) {
305 my $bool = cfg_bool($cfg, "imap.$k", $url) // next;
306 $mic_args->{$sec}->{$k} = $bool;
308 my $to = cfg_intvl($cfg, 'imap.timeout', $url);
309 $mic_args->{$sec}->{Timeout} = $to if $to;
310 for my $k (qw(pollInterval idleInterval)) {
311 $to = cfg_intvl($cfg, "imap.$k", $url) // next;
312 $self->{imap_opt}->{$sec}->{$k} = $to;
314 my $k = 'imap.fetchBatchSize';
315 my $bs = $cfg->urlmatch($k, $url) // next;
316 if ($bs =~ /\A([0-9]+)\z/) {
317 $self->{imap_opt}->{$sec}->{batch_size} = $bs;
319 warn "$k=$bs is not an integer\n";
325 sub auth_anon_cb { '' }; # for Mail::IMAPClient::Authcallback
327 sub mic_for ($$$) { # mic = Mail::IMAPClient
328 my ($self, $url, $mic_args) = @_;
329 my $uri = PublicInbox::URIimap->new($url);
330 require PublicInbox::GitCredential;
333 protocol => $uri->scheme,
335 username => $uri->user,
336 password => $uri->password,
337 }, 'PublicInbox::GitCredential';
338 my $common = $mic_args->{uri_section($uri)} // {};
339 # IMAPClient and Net::Netrc both mishandles `0', so we pass `127.0.0.1'
340 my $host = $cred->{host};
341 $host = '127.0.0.1' if $host eq '0';
345 Ssl => $uri->scheme eq 'imaps',
346 Keepalive => 1, # SO_KEEPALIVE
347 %$common, # may set Starttls, Compress, Debug ....
349 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or
350 die "E: <$url> new: $@\n";
352 # default to using STARTTLS if it's available, but allow
353 # it to be disabled since I usually connect to localhost
354 if (!$mic_arg->{Ssl} && !defined($mic_arg->{Starttls}) &&
355 $mic->has_capability('STARTTLS') &&
356 $mic->can('starttls')) {
357 $mic->starttls or die "E: <$url> STARTTLS: $@\n";
360 # do we even need credentials?
361 if (!defined($cred->{username}) &&
362 $mic->has_capability('AUTH=ANONYMOUS')) {
366 $cred->check_netrc unless defined $cred->{password};
367 $cred->fill; # may prompt user here
368 $mic->User($mic_arg->{User} = $cred->{username});
369 $mic->Password($mic_arg->{Password} = $cred->{password});
370 } else { # AUTH=ANONYMOUS
371 $mic->Authmechanism($mic_arg->{Authmechanism} = 'ANONYMOUS');
372 $mic->Authcallback($mic_arg->{Authcallback} = \&auth_anon_cb);
374 if ($mic->login && $mic->IsAuthenticated) {
375 # success! keep IMAPClient->new arg in case we get disconnected
376 $self->{mic_arg}->{uri_section($uri)} = $mic_arg;
378 warn "E: <$url> LOGIN: $@\n";
381 $cred->run($mic ? 'approve' : 'reject') if $cred;
385 sub imap_import_msg ($$$$$) {
386 my ($self, $url, $uid, $raw, $flags) = @_;
387 # our target audience expects LF-only, save storage
388 $$raw =~ s/\r\n/\n/sg;
390 my $inboxes = $self->{imap}->{$url};
392 for my $ibx (@$inboxes) {
393 my $eml = PublicInbox::Eml->new($$raw);
394 my $x = import_eml($self, $ibx, $eml);
396 } elsif ($inboxes eq 'watchspam') {
397 # we don't remove unseen messages
398 if ($flags =~ /\\Seen\b/) {
399 local $SIG{__WARN__} = warn_ignore_cb();
400 my $eml = PublicInbox::Eml->new($raw);
401 my $arg = [ $self, $eml, "$url UID:$uid" ];
402 $self->{config}->each_inbox(\&remove_eml_i, $arg);
405 die "BUG: destination unknown $inboxes";
409 sub imap_fetch_all ($$$) {
410 my ($self, $mic, $url) = @_;
411 my $uri = PublicInbox::URIimap->new($url);
412 my $sec = uri_section($uri);
413 my $mbx = $uri->mailbox;
414 $mic->Clear(1); # trim results history
415 $mic->examine($mbx) or return "E: EXAMINE $mbx ($sec) failed: $!";
416 my ($r_uidval, $r_uidnext);
417 for ($mic->Results) {
418 /^\* OK \[UIDVALIDITY ([0-9]+)\].*/ and $r_uidval = $1;
419 /^\* OK \[UIDNEXT ([0-9]+)\].*/ and $r_uidnext = $1;
420 last if $r_uidval && $r_uidnext;
422 $r_uidval //= $mic->uidvalidity($mbx) //
423 return "E: $url cannot get UIDVALIDITY";
424 $r_uidnext //= $mic->uidnext($mbx) //
425 return "E: $url cannot get UIDNEXT";
426 my $itrk = PublicInbox::IMAPTracker->new($url);
427 my ($l_uidval, $l_uid) = $itrk->get_last;
428 $l_uidval //= $r_uidval; # first time
430 if ($l_uidval != $r_uidval) {
431 return "E: $url UIDVALIDITY mismatch\n".
432 "E: local=$l_uidval != remote=$r_uidval";
434 my $r_uid = $r_uidnext - 1;
435 if ($l_uid != 1 && $l_uid > $r_uid) {
436 return "E: $url local UID exceeds remote ($l_uid > $r_uid)\n".
437 "E: $url strangely, UIDVALIDLITY matches ($l_uidval)\n";
439 return if $l_uid >= $r_uid; # nothing to do
441 warn "I: $url fetching UID $l_uid:$r_uid\n";
442 $mic->Uid(1); # the default, we hope
443 my $bs = $self->{imap_opt}->{$sec}->{batch_size} // 1;
444 my $req = $mic->imap4rev1 ? 'BODY.PEEK[]' : 'RFC822.PEEK';
446 # TODO: FLAGS may be useful for personal use
450 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
451 local $SIG{__WARN__} = sub {
452 my $pfx = ($_[0] // '') =~ /^([A-Z]: )/g ? $1 : '';
454 $warn_cb->("$pfx$url UID:$batch\n", @_);
458 # I wish "UID FETCH $START:*" could work, but:
459 # 1) servers do not need to return results in any order
460 # 2) Mail::IMAPClient doesn't offer a streaming API
461 $uids = $mic->search("UID $l_uid:*") or
462 return "E: $url UID SEARCH $l_uid:* error: $!";
463 return if scalar(@$uids) == 0;
465 # RFC 3501 doesn't seem to indicate order of UID SEARCH
466 # responses, so sort it ourselves. Order matters so
467 # IMAPTracker can store the newest UID.
468 @$uids = sort { $a <=> $b } @$uids;
470 # Did we actually get new messages?
471 return if $uids->[0] < $l_uid;
473 $l_uid = $uids->[-1] + 1; # for next search
476 while (scalar @$uids) {
477 my @batch = splice(@$uids, 0, $bs);
478 $batch = join(',', @batch);
479 local $0 = "UID:$batch $mbx $sec";
480 my $r = $mic->fetch_hash($batch, $req, 'FLAGS');
481 unless ($r) { # network error?
482 $err = "E: $url UID FETCH $batch error: $!";
485 for my $uid (@batch) {
486 # messages get deleted, so holes appear
487 my $per_uid = delete $r->{$uid} // next;
488 my $raw = delete($per_uid->{$key}) // next;
489 my $fl = $per_uid->{FLAGS} // '';
490 imap_import_msg($self, $url, $uid, \$raw, $fl);
492 last if $self->{quit};
494 last if $self->{quit};
496 _done_for_now($self);
497 $itrk->update_last($r_uidval, $last_uid) if defined $last_uid;
498 } until ($err || $self->{quit});
502 sub imap_idle_once ($$$$) {
503 my ($self, $mic, $intvl, $url) = @_;
504 my $i = $intvl //= (29 * 60);
505 my $end = now() + $intvl;
506 warn "I: $url idling for ${intvl}s\n";
507 local $0 = "IDLE $0";
508 unless ($mic->idle) {
509 return if $self->{quit};
510 return "E: IDLE failed on $url: $!";
512 $self->{idle_mic} = $mic; # for ->quit
514 until ($self->{quit} || !$mic->IsConnected ||
515 grep(/^\* [0-9]+ EXISTS/, @res) || $i <= 0) {
516 @res = $mic->idle_data($i);
519 delete $self->{idle_mic};
520 unless ($self->{quit}) {
521 $mic->IsConnected or return "E: IDLE disconnected on $url";
522 $mic->done or return "E: IDLE DONE failed on $url: $!";
527 # idles on a single URI
528 sub watch_imap_idle_1 ($$$) {
529 my ($self, $url, $intvl) = @_;
530 my $uri = PublicInbox::URIimap->new($url);
531 my $sec = uri_section($uri);
532 my $mic_arg = $self->{mic_arg}->{$sec} or
533 die "BUG: no Mail::IMAPClient->new arg for $sec";
535 local $0 = $uri->mailbox." $sec";
536 until ($self->{quit}) {
537 $mic //= PublicInbox::IMAPClient->new(%$mic_arg);
539 if ($mic && $mic->IsConnected) {
540 $err = imap_fetch_all($self, $mic, $url);
541 $err //= imap_idle_once($self, $mic, $intvl, $url);
543 $err = "not connected: $!";
545 if ($err && !$self->{quit}) {
548 sleep 60 unless $self->{quit};
553 sub watch_atfork_child ($) {
555 delete $self->{idle_pids};
556 delete $self->{poll_pids};
557 delete $self->{opendirs};
558 PublicInbox::DS->Reset;
559 %SIG = (%SIG, %{$self->{sig}}, CHLD => 'DEFAULT');
560 PublicInbox::Sigfd::sig_setmask($self->{oldset});
563 sub watch_atfork_parent ($) {
565 _done_for_now($self);
568 sub imap_idle_requeue ($) { # DS::add_timer callback
569 my ($self, $url_intvl) = @{$_[0]};
570 return if $self->{quit};
571 push @{$self->{idle_todo}}, $url_intvl;
575 sub imap_idle_reap { # PublicInbox::DS::dwaitpid callback
576 my ($self, $pid) = @_;
577 my $url_intvl = delete $self->{idle_pids}->{$pid} or
578 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
580 my ($url, $intvl) = @$url_intvl;
581 return if $self->{quit};
582 warn "W: PID=$pid on $url died: \$?=$?\n" if $?;
583 PublicInbox::DS::add_timer(60,
584 \&imap_idle_requeue, [ $self, $url_intvl ]);
587 sub imap_idle_fork ($$) {
588 my ($self, $url_intvl) = @_;
589 my ($url, $intvl) = @$url_intvl;
590 defined(my $pid = fork) or die "fork: $!";
592 watch_atfork_child($self);
593 watch_imap_idle_1($self, $url, $intvl);
596 $self->{idle_pids}->{$pid} = $url_intvl;
597 PublicInbox::DS::dwaitpid($pid, \&imap_idle_reap, $self);
602 return if $self->{quit};
603 my $idle_todo = $self->{idle_todo};
604 if ($idle_todo && @$idle_todo) {
605 watch_atfork_parent($self);
606 while (my $url_intvl = shift(@$idle_todo)) {
607 imap_idle_fork($self, $url_intvl);
610 goto(&fs_scan_step) if $self->{mdre};
613 sub watch_imap_fetch_all ($$) {
614 my ($self, $urls) = @_;
615 for my $url (@$urls) {
616 my $uri = PublicInbox::URIimap->new($url);
617 my $sec = uri_section($uri);
618 my $mic_arg = $self->{mic_arg}->{$sec} or
619 die "BUG: no Mail::IMAPClient->new arg for $sec";
620 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or next;
621 my $err = imap_fetch_all($self, $mic, $url);
622 last if $self->{quit};
623 warn $err, "\n" if $err;
627 sub watch_nntp_fetch_all ($$) {
628 my ($self, $urls) = @_;
629 for my $url (@$urls) {
630 my $uri = uri_new($url);
631 my $sec = uri_section($uri);
632 my $nn_arg = $self->{nn_arg}->{$sec} or
633 die "BUG: no Net::NNTP->new arg for $sec";
634 my $nntp_opt = $self->{nntp_opt}->{$sec};
635 my $nn = nn_new($nn_arg, $nntp_opt, $url);
637 warn "E: $url: \$!=$!\n";
640 last if $self->{quit};
641 if (my $postconn = $nntp_opt->{-postconn}) {
642 for my $m_arg (@$postconn) {
643 my ($method, @args) = @$m_arg;
644 $nn->$method(@args) and next;
645 warn "E: <$url> $method failed\n";
650 last if $self->{quit};
652 my $err = nntp_fetch_all($self, $nn, $url);
653 warn $err, "\n" if $err;
658 sub poll_fetch_fork ($) { # DS::add_timer callback
659 my ($self, $intvl, $urls) = @{$_[0]};
660 return if $self->{quit};
661 watch_atfork_parent($self);
662 defined(my $pid = fork) or die "fork: $!";
664 watch_atfork_child($self);
665 if ($urls->[0] =~ m!\Aimaps?://!i) {
666 watch_imap_fetch_all($self, $urls);
668 watch_nntp_fetch_all($self, $urls);
672 $self->{poll_pids}->{$pid} = [ $intvl, $urls ];
673 PublicInbox::DS::dwaitpid($pid, \&poll_fetch_reap, $self);
676 sub poll_fetch_reap { # PublicInbox::DS::dwaitpid callback
677 my ($self, $pid) = @_;
678 my $intvl_urls = delete $self->{poll_pids}->{$pid} or
679 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
680 return if $self->{quit};
681 my ($intvl, $urls) = @$intvl_urls;
683 warn "W: PID=$pid died: \$?=$?\n", map { "$_\n" } @$urls;
685 warn("I: will check $_ in ${intvl}s\n") for @$urls;
686 PublicInbox::DS::add_timer($intvl, \&poll_fetch_fork,
687 [$self, $intvl, $urls]);
690 sub watch_imap_init ($$) {
691 my ($self, $poll) = @_;
692 eval { require PublicInbox::IMAPClient } or
693 die "Mail::IMAPClient is required for IMAP:\n$@\n";
694 eval { require PublicInbox::IMAPTracker } or
695 die "DBD::SQLite is required for IMAP\n:$@\n";
697 my $mic_args = imap_common_init($self); # read args from config
699 # make sure we can connect and cache the credentials in memory
700 $self->{mic_arg} = {}; # schema://authority => IMAPClient->new args
701 my $mics = {}; # schema://authority => IMAPClient obj
702 for my $url (sort keys %{$self->{imap}}) {
703 my $uri = PublicInbox::URIimap->new($url);
704 $mics->{uri_section($uri)} //= mic_for($self, $url, $mic_args);
707 my $idle = []; # [ [ url1, intvl1 ], [url2, intvl2] ]
708 for my $url (keys %{$self->{imap}}) {
709 my $uri = PublicInbox::URIimap->new($url);
710 my $sec = uri_section($uri);
711 my $mic = $mics->{$sec};
712 my $intvl = $self->{imap_opt}->{$sec}->{pollInterval};
713 if ($mic->has_capability('IDLE') && !$intvl) {
714 $intvl = $self->{imap_opt}->{$sec}->{idleInterval};
715 push @$idle, [ $url, $intvl // () ];
717 push @{$poll->{$intvl || 120}}, $url;
721 $self->{idle_todo} = $idle;
722 PublicInbox::DS::requeue($self); # ->event_step to fork
726 # flesh out common NNTP-specific data structures
727 sub nntp_common_init ($) {
729 my $cfg = $self->{config};
730 my $nn_args = {}; # scheme://authority => Net::NNTP->new arg
731 for my $url (sort keys %{$self->{nntp}}) {
732 my $sec = uri_section(uri_new($url));
734 # Debug and Timeout are passed to Net::NNTP->new
735 my $v = cfg_bool($cfg, 'nntp.Debug', $url);
736 $nn_args->{$sec}->{Debug} = $v if defined $v;
737 my $to = cfg_intvl($cfg, 'nntp.Timeout', $url);
738 $nn_args->{$sec}->{Timeout} = $to if $to;
740 # Net::NNTP post-connect commands
741 for my $k (qw(starttls compress)) {
742 $v = cfg_bool($cfg, "nntp.$k", $url) // next;
743 $self->{nntp_opt}->{$sec}->{$k} = $v;
747 for my $k (qw(pollInterval)) {
748 $to = cfg_intvl($cfg, "nntp.$k", $url) // next;
749 $self->{nntp_opt}->{$sec}->{$k} = $to;
755 # Net::NNTP doesn't support CAPABILITIES, yet
756 sub try_starttls ($) {
758 return if $host =~ /\.onion\z/s;
759 return if $host =~ /\A127\.[0-9]+\.[0-9]+\.[0-9]+\z/s;
760 return if $host eq '::1';
765 my ($nn_arg, $nntp_opt, $url) = @_;
766 my $nn = Net::NNTP->new(%$nn_arg) or die "E: <$url> new: $!\n";
768 # default to using STARTTLS if it's available, but allow
769 # it to be disabled for localhost/VPN users
770 if (!$nn_arg->{SSL} && $nn->can('starttls')) {
771 if (!defined($nntp_opt->{starttls}) &&
772 try_starttls($nn_arg->{Host})) {
773 # soft fail by default
774 $nn->starttls or warn <<"";
775 W: <$url> STARTTLS tried and failed (not requested)
777 } elsif ($nntp_opt->{starttls}) {
778 # hard fail if explicitly configured
779 $nn->starttls or die <<"";
780 E: <$url> STARTTLS requested and failed
783 } elsif ($nntp_opt->{starttls}) {
784 $nn->can('starttls') or
785 die "E: <$url> Net::NNTP too old for STARTTLS\n";
786 $nn->starttls or die <<"";
787 E: <$url> STARTTLS requested and failed
793 sub nn_for ($$$) { # nn = Net::NNTP
794 my ($self, $url, $nn_args) = @_;
795 my $uri = uri_new($url);
796 my $sec = uri_section($uri);
797 my $nntp_opt = $self->{nntp_opt}->{$sec} //= {};
798 my $host = $uri->host;
799 # Net::NNTP and Net::Netrc both mishandle `0', so we pass `127.0.0.1'
800 $host = '127.0.0.1' if $host eq '0';
803 if (defined(my $ui = $uri->userinfo)) {
804 require PublicInbox::GitCredential;
807 protocol => uri_scheme($uri),
809 }, 'PublicInbox::GitCredential';
810 ($u, $p) = split(/:/, $ui, 2);
811 ($cred->{username}, $cred->{password}) = ($u, $p);
812 $cred->check_netrc unless defined $p;
814 my $common = $nn_args->{$sec} // {};
818 SSL => $uri->secure, # snews == nntps
819 %$common, # may Debug ....
821 my $nn = nn_new($nn_arg, $nntp_opt, $url);
824 $cred->fill; # may prompt user here
825 if ($nn->authinfo($u, $p)) {
826 push @{$nntp_opt->{-postconn}}, [ 'authinfo', $u, $p ];
828 warn "E: <$url> AUTHINFO $u XXXX failed\n";
833 if ($nntp_opt->{compress}) {
834 # https://rt.cpan.org/Ticket/Display.html?id=129967
835 if ($nn->can('compress')) {
837 push @{$nntp_opt->{-postconn}}, [ 'compress' ];
839 warn "W: <$url> COMPRESS failed\n";
842 delete $nntp_opt->{compress};
844 W: <$url> COMPRESS not supported by Net::NNTP
845 W: see https://rt.cpan.org/Ticket/Display.html?id=129967 for updates
850 $self->{nn_arg}->{$sec} = $nn_arg;
851 $cred->run($nn ? 'approve' : 'reject') if $cred;
855 sub nntp_fetch_all ($$$) {
856 my ($self, $nn, $url) = @_;
857 my $uri = uri_new($url);
858 my ($group, $num_a, $num_b) = $uri->group;
859 my $sec = uri_section($uri);
860 my ($nr, $beg, $end) = $nn->group($group);
861 unless (defined($nr)) {
862 chomp(my $msg = $nn->message);
863 return "E: GROUP $group <$sec> $msg";
866 # IMAPTracker is also used for tracking NNTP, UID == article number
867 # LIST.ACTIVE can get the equivalent of UIDVALIDITY, but that's
868 # expensive. So we assume newsgroups don't change:
869 my $itrk = PublicInbox::IMAPTracker->new($url);
870 my (undef, $l_art) = $itrk->get_last;
871 $l_art //= $beg; # initial import
873 # allow users to specify articles to refetch
874 # cf. https://tools.ietf.org/id/draft-gilman-news-url-01.txt
875 # nntp://example.com/inbox.foo/$num_a-$num_b
876 $l_art = $num_a if defined($num_a) && $num_a < $l_art;
877 $end = $num_b if defined($num_b) && $num_b < $end;
879 return if $l_art >= $end; # nothing to do
882 warn "I: $url fetching ARTICLE $beg..$end\n";
883 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
885 local $SIG{__WARN__} = sub {
886 my $pfx = ($_[0] // '') =~ /^([A-Z]: )/g ? $1 : '';
887 $warn_cb->("$pfx$url ", $art ? ("ARTICLE $art") : (), "\n", @_);
889 my $inboxes = $self->{nntp}->{$url};
892 last if $self->{quit};
894 my $raw = $nn->article($art);
895 unless (defined($raw)) {
896 my $msg = $nn->message;
897 if ($nn->code == 421) { # pseudo response from Net::Cmd
900 } else { # probably just a deleted message (spam)
905 s/\r\n/\n/ for @$raw;
906 $raw = join('', @$raw);
908 for my $ibx (@$inboxes) {
909 my $eml = PublicInbox::Eml->new($raw);
910 import_eml($self, $ibx, $eml);
912 } elsif ($inboxes eq 'watchspam') {
913 my $eml = PublicInbox::Eml->new(\$raw);
914 my $arg = [ $self, $eml, "$url ARTICLE $art" ];
915 $self->{config}->each_inbox(\&remove_eml_i, $arg);
917 die "BUG: destination unknown $inboxes";
921 $itrk->update_last(0, $last_art) if defined $last_art;
922 _done_for_now($self);
926 sub watch_nntp_init ($$) {
927 my ($self, $poll) = @_;
928 eval { require Net::NNTP } or
929 die "Net::NNTP is required for NNTP:\n$@\n";
930 eval { require PublicInbox::IMAPTracker } or
931 die "DBD::SQLite is required for NNTP\n:$@\n";
933 my $nn_args = nntp_common_init($self); # read args from config
935 # make sure we can connect and cache the credentials in memory
936 $self->{nn_arg} = {}; # schema://authority => Net::NNTP->new args
937 for my $url (sort keys %{$self->{nntp}}) {
938 nn_for($self, $url, $nn_args);
940 for my $url (keys %{$self->{nntp}}) {
941 my $uri = uri_new($url);
942 my $sec = uri_section($uri);
943 my $intvl = $self->{nntp_opt}->{$sec}->{pollInterval};
944 push @{$poll->{$intvl || 120}}, $url;
949 my ($self, $sig, $oldset) = @_;
950 $self->{oldset} = $oldset;
952 my $poll = {}; # intvl_seconds => [ url1, url2 ]
953 watch_imap_init($self, $poll) if $self->{imap};
954 watch_nntp_init($self, $poll) if $self->{nntp};
955 while (my ($intvl, $urls) = each %$poll) {
956 # poll all URLs for a given interval sequentially
957 PublicInbox::DS::add_timer(0, \&poll_fetch_fork,
958 [$self, $intvl, $urls]);
960 watch_fs_init($self) if $self->{mdre};
961 PublicInbox::DS->SetPostLoopCallback(sub { !$self->quit_done });
962 PublicInbox::DS->EventLoop;
963 _done_for_now($self);
967 my ($self, $op) = @_;
968 push @{$self->{ops}}, $op;
969 PublicInbox::DS::requeue($self);
974 return if $self->{quit};
975 my $op = shift @{$self->{ops}};
976 local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
978 # continue existing scan
980 my $opendirs = $self->{opendirs};
981 my @dirnames = keys %$opendirs;
982 foreach my $dir (@dirnames) {
983 my $dh = delete $opendirs->{$dir};
985 while (my $fn = readdir($dh)) {
986 _try_path($self, "$dir/$fn");
989 $opendirs->{$dir} = $dh if $n < 0;
991 if ($op && $op eq 'full') {
992 foreach my $dir (keys %{$self->{mdmap}}) {
993 next if $opendirs->{$dir}; # already in progress
994 my $ok = opendir(my $dh, $dir);
996 warn "failed to open $dir: $!\n";
1000 while (my $fn = readdir($dh)) {
1001 _try_path($self, "$dir/$fn");
1004 $opendirs->{$dir} = $dh if $n < 0;
1007 _done_for_now($self);
1008 # do we have more work to do?
1009 PublicInbox::DS::requeue($self) if keys %$opendirs;
1013 my ($self, $op) = @_;
1014 push @{$self->{ops}}, $op;
1019 my ($self, $ibx) = @_;
1020 my $importers = $self->{importers};
1021 my $im = $importers->{"$ibx"} ||= $ibx->importer(0);
1022 if (scalar(keys(%$importers)) > 2) {
1023 delete $importers->{"$ibx"};
1024 _done_for_now($self);
1027 $importers->{"$ibx"} = $im;
1030 # XXX consider sharing with V2Writable, this only requires read-only access
1031 sub content_exists ($$) {
1032 my ($ibx, $eml) = @_;
1033 my $over = $ibx->over or return;
1034 my $mids = mids($eml);
1035 my $chash = content_hash($eml);
1037 for my $mid (@$mids) {
1038 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
1039 my $cmp = $ibx->smsg_eml($smsg) or return;
1040 return 1 if $chash eq content_hash($cmp);
1049 my ($mime, $ibx) = @_;
1050 return if content_exists($ibx, $mime);
1052 if ($sc->spamcheck($mime, \$tmp)) {
1053 return PublicInbox::Eml->new(\$tmp);
1055 warn $mime->header('Message-ID')." failed spam check\n";
1061 $_[0] =~ s!\Amaildir:!! or return;
1068 my ($cur, $ws, $ibx) = @_;
1069 if ($ws && !ref($ws) && $ws eq 'watchspam') {
1071 E: $cur is a spam folder and cannot be used for `$ibx->{name}' input
1081 # URI::snews exists, URI::nntps does not, so use URI::snews
1082 $url =~ s!\Anntps://!snews://!i;
1088 require PublicInbox::URIimap;
1089 my $uri = PublicInbox::URIimap->new($url);
1090 $uri ? $uri->canonical->as_string : undef;
1093 my %IS_NNTP = (news => 1, snews => 1, nntp => 1);
1097 my $uri = uri_new($url);
1098 return unless $uri && $IS_NNTP{$uri->scheme} && $uri->group;
1099 $url = $uri->canonical->as_string;
1100 # nntps is IANA registered, snews is deprecated
1101 $url =~ s!\Asnews://!nntps://!;