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 { $warn_cb->("path: $path\n", @_) };
202 if (!ref($inboxes) && $inboxes eq 'watchspam') {
203 return _remove_spam($self, $path);
205 foreach my $ibx (@$inboxes) {
206 my $eml = eml_from_path($path) or next;
207 import_eml($self, $ibx, $eml);
213 return unless $self->{quit};
215 # don't have reliable wakeups, keep signalling
217 for (qw(idle_pids poll_pids)) {
218 my $pids = $self->{$_} or next;
220 $done = undef if kill('QUIT', $_);
229 %{$self->{opendirs}} = ();
230 _done_for_now($self);
232 if (my $idle_mic = $self->{idle_mic}) {
233 eval { $idle_mic->done };
235 warn "IDLE DONE error: $@\n";
236 eval { $idle_mic->disconnect };
237 warn "IDLE LOGOUT error: $@\n" if $@;
242 sub watch_fs_init ($) {
245 delete $self->{done_timer};
246 _done_for_now($self);
249 _try_path($self, $_[0]->fullname);
250 $self->{done_timer} //= PublicInbox::DS::requeue($done);
252 require PublicInbox::DirIdle;
253 # inotify_create + EPOLL_CTL_ADD
254 PublicInbox::DirIdle->new([keys %{$self->{mdmap}}], $cb);
257 # avoid exposing deprecated "snews" to users.
258 my %SCHEME_MAP = ('snews' => 'nntps');
262 my $scheme = $uri->scheme;
263 $SCHEME_MAP{$scheme} // $scheme;
266 # returns the git config section name, e.g [imap "imaps://user@example.com"]
267 # without the mailbox, so we can share connections between different inboxes
268 sub uri_section ($) {
270 uri_scheme($uri) . '://' . $uri->authority;
273 sub cfg_intvl ($$$) {
274 my ($cfg, $key, $url) = @_;
275 my $v = $cfg->urlmatch($key, $url) // return;
276 $v =~ /\A[0-9]+(?:\.[0-9]+)?\z/s and return $v + 0;
277 if (ref($v) eq 'ARRAY') {
278 $v = join(', ', @$v);
279 warn "W: $key has multiple values: $v\nW: $key ignored\n";
281 warn "W: $key=$v is not a numeric value in seconds\n";
286 my ($cfg, $key, $url) = @_;
287 my $orig = $cfg->urlmatch($key, $url) // return;
288 my $bool = $cfg->git_bool($orig);
289 warn "W: $key=$orig for $url is not boolean\n" unless defined($bool);
293 # flesh out common IMAP-specific data structures
294 sub imap_common_init ($) {
296 my $cfg = $self->{config};
297 my $mic_args = {}; # scheme://authority => Mail:IMAPClient arg
298 for my $url (sort keys %{$self->{imap}}) {
299 my $uri = PublicInbox::URIimap->new($url);
300 my $sec = uri_section($uri);
301 for my $k (qw(Starttls Debug Compress)) {
302 my $bool = cfg_bool($cfg, "imap.$k", $url) // next;
303 $mic_args->{$sec}->{$k} = $bool;
305 my $to = cfg_intvl($cfg, 'imap.timeout', $url);
306 $mic_args->{$sec}->{Timeout} = $to if $to;
307 for my $k (qw(pollInterval idleInterval)) {
308 $to = cfg_intvl($cfg, "imap.$k", $url) // next;
309 $self->{imap_opt}->{$sec}->{$k} = $to;
311 my $k = 'imap.fetchBatchSize';
312 my $bs = $cfg->urlmatch($k, $url) // next;
313 if ($bs =~ /\A([0-9]+)\z/) {
314 $self->{imap_opt}->{$sec}->{batch_size} = $bs;
316 warn "$k=$bs is not an integer\n";
322 sub auth_anon_cb { '' }; # for Mail::IMAPClient::Authcallback
324 sub mic_for ($$$) { # mic = Mail::IMAPClient
325 my ($self, $url, $mic_args) = @_;
326 my $uri = PublicInbox::URIimap->new($url);
327 require PublicInbox::GitCredential;
330 protocol => $uri->scheme,
332 username => $uri->user,
333 password => $uri->password,
334 }, 'PublicInbox::GitCredential';
335 my $common = $mic_args->{uri_section($uri)} // {};
336 # IMAPClient and Net::Netrc both mishandles `0', so we pass `127.0.0.1'
337 my $host = $cred->{host};
338 $host = '127.0.0.1' if $host eq '0';
342 Ssl => $uri->scheme eq 'imaps',
343 Keepalive => 1, # SO_KEEPALIVE
344 %$common, # may set Starttls, Compress, Debug ....
346 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or
347 die "E: <$url> new: $@\n";
349 # default to using STARTTLS if it's available, but allow
350 # it to be disabled since I usually connect to localhost
351 if (!$mic_arg->{Ssl} && !defined($mic_arg->{Starttls}) &&
352 $mic->has_capability('STARTTLS') &&
353 $mic->can('starttls')) {
354 $mic->starttls or die "E: <$url> STARTTLS: $@\n";
357 # do we even need credentials?
358 if (!defined($cred->{username}) &&
359 $mic->has_capability('AUTH=ANONYMOUS')) {
363 $cred->check_netrc unless defined $cred->{password};
364 $cred->fill; # may prompt user here
365 $mic->User($mic_arg->{User} = $cred->{username});
366 $mic->Password($mic_arg->{Password} = $cred->{password});
367 } else { # AUTH=ANONYMOUS
368 $mic->Authmechanism($mic_arg->{Authmechanism} = 'ANONYMOUS');
369 $mic->Authcallback($mic_arg->{Authcallback} = \&auth_anon_cb);
371 if ($mic->login && $mic->IsAuthenticated) {
372 # success! keep IMAPClient->new arg in case we get disconnected
373 $self->{mic_arg}->{uri_section($uri)} = $mic_arg;
375 warn "E: <$url> LOGIN: $@\n";
378 $cred->run($mic ? 'approve' : 'reject') if $cred;
382 sub imap_import_msg ($$$$) {
383 my ($self, $url, $uid, $raw) = @_;
384 # our target audience expects LF-only, save storage
385 $$raw =~ s/\r\n/\n/sg;
387 my $inboxes = $self->{imap}->{$url};
389 for my $ibx (@$inboxes) {
390 my $eml = PublicInbox::Eml->new($$raw);
391 my $x = import_eml($self, $ibx, $eml);
393 } elsif ($inboxes eq 'watchspam') {
394 local $SIG{__WARN__} = warn_ignore_cb();
395 my $eml = PublicInbox::Eml->new($raw);
396 my $arg = [ $self, $eml, "$url UID:$uid" ];
397 $self->{config}->each_inbox(\&remove_eml_i, $arg);
399 die "BUG: destination unknown $inboxes";
403 sub imap_fetch_all ($$$) {
404 my ($self, $mic, $url) = @_;
405 my $uri = PublicInbox::URIimap->new($url);
406 my $sec = uri_section($uri);
407 my $mbx = $uri->mailbox;
408 $mic->Clear(1); # trim results history
409 $mic->examine($mbx) or return "E: EXAMINE $mbx ($sec) failed: $!";
410 my ($r_uidval, $r_uidnext);
411 for ($mic->Results) {
412 /^\* OK \[UIDVALIDITY ([0-9]+)\].*/ and $r_uidval = $1;
413 /^\* OK \[UIDNEXT ([0-9]+)\].*/ and $r_uidnext = $1;
414 last if $r_uidval && $r_uidnext;
416 $r_uidval //= $mic->uidvalidity($mbx) //
417 return "E: $url cannot get UIDVALIDITY";
418 $r_uidnext //= $mic->uidnext($mbx) //
419 return "E: $url cannot get UIDNEXT";
420 my $itrk = PublicInbox::IMAPTracker->new($url);
421 my ($l_uidval, $l_uid) = $itrk->get_last;
422 $l_uidval //= $r_uidval; # first time
424 if ($l_uidval != $r_uidval) {
425 return "E: $url UIDVALIDITY mismatch\n".
426 "E: local=$l_uidval != remote=$r_uidval";
428 my $r_uid = $r_uidnext - 1;
429 if ($l_uid != 1 && $l_uid > $r_uid) {
430 return "E: $url local UID exceeds remote ($l_uid > $r_uid)\n".
431 "E: $url strangely, UIDVALIDLITY matches ($l_uidval)\n";
433 return if $l_uid >= $r_uid; # nothing to do
435 warn "I: $url fetching UID $l_uid:$r_uid\n";
436 $mic->Uid(1); # the default, we hope
437 my $bs = $self->{imap_opt}->{$sec}->{batch_size} // 1;
438 my $req = $mic->imap4rev1 ? 'BODY.PEEK[]' : 'RFC822.PEEK';
440 # TODO: FLAGS may be useful for personal use
444 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
445 local $SIG{__WARN__} = sub {
447 $warn_cb->("$url UID:$batch\n", @_);
451 # I wish "UID FETCH $START:*" could work, but:
452 # 1) servers do not need to return results in any order
453 # 2) Mail::IMAPClient doesn't offer a streaming API
454 $uids = $mic->search("UID $l_uid:*") or
455 return "E: $url UID SEARCH $l_uid:* error: $!";
456 return if scalar(@$uids) == 0;
458 # RFC 3501 doesn't seem to indicate order of UID SEARCH
459 # responses, so sort it ourselves. Order matters so
460 # IMAPTracker can store the newest UID.
461 @$uids = sort { $a <=> $b } @$uids;
463 # Did we actually get new messages?
464 return if $uids->[0] < $l_uid;
466 $l_uid = $uids->[-1] + 1; # for next search
469 while (scalar @$uids) {
470 my @batch = splice(@$uids, 0, $bs);
471 $batch = join(',', @batch);
472 local $0 = "UID:$batch $mbx $sec";
473 my $r = $mic->fetch_hash($batch, $req);
474 unless ($r) { # network error?
475 $err = "E: $url UID FETCH $batch error: $!";
478 for my $uid (@batch) {
479 # messages get deleted, so holes appear
480 my $per_uid = delete $r->{$uid} // next;
481 my $raw = delete($per_uid->{$key}) // next;
482 imap_import_msg($self, $url, $uid, \$raw);
484 last if $self->{quit};
486 last if $self->{quit};
488 _done_for_now($self);
489 $itrk->update_last($r_uidval, $last_uid) if defined $last_uid;
490 } until ($err || $self->{quit});
494 sub imap_idle_once ($$$$) {
495 my ($self, $mic, $intvl, $url) = @_;
496 my $i = $intvl //= (29 * 60);
497 my $end = now() + $intvl;
498 warn "I: $url idling for ${intvl}s\n";
499 local $0 = "IDLE $0";
500 unless ($mic->idle) {
501 return if $self->{quit};
502 return "E: IDLE failed on $url: $!";
504 $self->{idle_mic} = $mic; # for ->quit
506 until ($self->{quit} || !$mic->IsConnected ||
507 grep(/^\* [0-9]+ EXISTS/, @res) || $i <= 0) {
508 @res = $mic->idle_data($i);
511 delete $self->{idle_mic};
512 unless ($self->{quit}) {
513 $mic->IsConnected or return "E: IDLE disconnected on $url";
514 $mic->done or return "E: IDLE DONE failed on $url: $!";
519 # idles on a single URI
520 sub watch_imap_idle_1 ($$$) {
521 my ($self, $url, $intvl) = @_;
522 my $uri = PublicInbox::URIimap->new($url);
523 my $sec = uri_section($uri);
524 my $mic_arg = $self->{mic_arg}->{$sec} or
525 die "BUG: no Mail::IMAPClient->new arg for $sec";
527 local $0 = $uri->mailbox." $sec";
528 until ($self->{quit}) {
529 $mic //= PublicInbox::IMAPClient->new(%$mic_arg);
531 if ($mic && $mic->IsConnected) {
532 $err = imap_fetch_all($self, $mic, $url);
533 $err //= imap_idle_once($self, $mic, $intvl, $url);
535 $err = "not connected: $!";
537 if ($err && !$self->{quit}) {
540 sleep 60 unless $self->{quit};
545 sub watch_atfork_child ($) {
547 delete $self->{idle_pids};
548 delete $self->{poll_pids};
549 delete $self->{opendirs};
550 PublicInbox::DS->Reset;
551 %SIG = (%SIG, %{$self->{sig}}, CHLD => 'DEFAULT');
552 PublicInbox::Sigfd::sig_setmask($self->{oldset});
555 sub watch_atfork_parent ($) {
557 _done_for_now($self);
560 sub imap_idle_requeue ($) { # DS::add_timer callback
561 my ($self, $url_intvl) = @{$_[0]};
562 return if $self->{quit};
563 push @{$self->{idle_todo}}, $url_intvl;
567 sub imap_idle_reap { # PublicInbox::DS::dwaitpid callback
568 my ($self, $pid) = @_;
569 my $url_intvl = delete $self->{idle_pids}->{$pid} or
570 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
572 my ($url, $intvl) = @$url_intvl;
573 return if $self->{quit};
574 warn "W: PID=$pid on $url died: \$?=$?\n" if $?;
575 PublicInbox::DS::add_timer(60,
576 \&imap_idle_requeue, [ $self, $url_intvl ]);
579 sub imap_idle_fork ($$) {
580 my ($self, $url_intvl) = @_;
581 my ($url, $intvl) = @$url_intvl;
582 defined(my $pid = fork) or die "fork: $!";
584 watch_atfork_child($self);
585 watch_imap_idle_1($self, $url, $intvl);
588 $self->{idle_pids}->{$pid} = $url_intvl;
589 PublicInbox::DS::dwaitpid($pid, \&imap_idle_reap, $self);
594 return if $self->{quit};
595 my $idle_todo = $self->{idle_todo};
596 if ($idle_todo && @$idle_todo) {
597 watch_atfork_parent($self);
598 while (my $url_intvl = shift(@$idle_todo)) {
599 imap_idle_fork($self, $url_intvl);
602 goto(&fs_scan_step) if $self->{mdre};
605 sub watch_imap_fetch_all ($$) {
606 my ($self, $urls) = @_;
607 for my $url (@$urls) {
608 my $uri = PublicInbox::URIimap->new($url);
609 my $sec = uri_section($uri);
610 my $mic_arg = $self->{mic_arg}->{$sec} or
611 die "BUG: no Mail::IMAPClient->new arg for $sec";
612 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or next;
613 my $err = imap_fetch_all($self, $mic, $url);
614 last if $self->{quit};
615 warn $err, "\n" if $err;
619 sub watch_nntp_fetch_all ($$) {
620 my ($self, $urls) = @_;
621 for my $url (@$urls) {
622 my $uri = uri_new($url);
623 my $sec = uri_section($uri);
624 my $nn_arg = $self->{nn_arg}->{$sec} or
625 die "BUG: no Net::NNTP->new arg for $sec";
626 my $nntp_opt = $self->{nntp_opt}->{$sec};
627 my $nn = nn_new($nn_arg, $nntp_opt, $url);
629 warn "E: $url: \$!=$!\n";
632 last if $self->{quit};
633 if (my $postconn = $nntp_opt->{-postconn}) {
634 for my $m_arg (@$postconn) {
635 my ($method, @args) = @$m_arg;
636 $nn->$method(@args) and next;
637 warn "E: <$url> $method failed\n";
642 last if $self->{quit};
644 my $err = nntp_fetch_all($self, $nn, $url);
645 warn $err, "\n" if $err;
650 sub poll_fetch_fork ($) { # DS::add_timer callback
651 my ($self, $intvl, $urls) = @{$_[0]};
652 return if $self->{quit};
653 watch_atfork_parent($self);
654 defined(my $pid = fork) or die "fork: $!";
656 watch_atfork_child($self);
657 if ($urls->[0] =~ m!\Aimaps?://!i) {
658 watch_imap_fetch_all($self, $urls);
660 watch_nntp_fetch_all($self, $urls);
664 $self->{poll_pids}->{$pid} = [ $intvl, $urls ];
665 PublicInbox::DS::dwaitpid($pid, \&poll_fetch_reap, $self);
668 sub poll_fetch_reap { # PublicInbox::DS::dwaitpid callback
669 my ($self, $pid) = @_;
670 my $intvl_urls = delete $self->{poll_pids}->{$pid} or
671 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
672 return if $self->{quit};
673 my ($intvl, $urls) = @$intvl_urls;
675 warn "W: PID=$pid died: \$?=$?\n", map { "$_\n" } @$urls;
677 warn("I: will check $_ in ${intvl}s\n") for @$urls;
678 PublicInbox::DS::add_timer($intvl, \&poll_fetch_fork,
679 [$self, $intvl, $urls]);
682 sub watch_imap_init ($$) {
683 my ($self, $poll) = @_;
684 eval { require PublicInbox::IMAPClient } or
685 die "Mail::IMAPClient is required for IMAP:\n$@\n";
686 eval { require PublicInbox::IMAPTracker } or
687 die "DBD::SQLite is required for IMAP\n:$@\n";
689 my $mic_args = imap_common_init($self); # read args from config
691 # make sure we can connect and cache the credentials in memory
692 $self->{mic_arg} = {}; # schema://authority => IMAPClient->new args
693 my $mics = {}; # schema://authority => IMAPClient obj
694 for my $url (sort keys %{$self->{imap}}) {
695 my $uri = PublicInbox::URIimap->new($url);
696 $mics->{uri_section($uri)} //= mic_for($self, $url, $mic_args);
699 my $idle = []; # [ [ url1, intvl1 ], [url2, intvl2] ]
700 for my $url (keys %{$self->{imap}}) {
701 my $uri = PublicInbox::URIimap->new($url);
702 my $sec = uri_section($uri);
703 my $mic = $mics->{$sec};
704 my $intvl = $self->{imap_opt}->{$sec}->{pollInterval};
705 if ($mic->has_capability('IDLE') && !$intvl) {
706 $intvl = $self->{imap_opt}->{$sec}->{idleInterval};
707 push @$idle, [ $url, $intvl // () ];
709 push @{$poll->{$intvl || 120}}, $url;
713 $self->{idle_todo} = $idle;
714 PublicInbox::DS::requeue($self); # ->event_step to fork
718 # flesh out common NNTP-specific data structures
719 sub nntp_common_init ($) {
721 my $cfg = $self->{config};
722 my $nn_args = {}; # scheme://authority => Net::NNTP->new arg
723 for my $url (sort keys %{$self->{nntp}}) {
724 my $sec = uri_section(uri_new($url));
726 # Debug and Timeout are passed to Net::NNTP->new
727 my $v = cfg_bool($cfg, 'nntp.Debug', $url);
728 $nn_args->{$sec}->{Debug} = $v if defined $v;
729 my $to = cfg_intvl($cfg, 'nntp.Timeout', $url);
730 $nn_args->{$sec}->{Timeout} = $to if $to;
732 # Net::NNTP post-connect commands
733 for my $k (qw(starttls compress)) {
734 $v = cfg_bool($cfg, "nntp.$k", $url) // next;
735 $self->{nntp_opt}->{$sec}->{$k} = $v;
739 for my $k (qw(pollInterval)) {
740 $to = cfg_intvl($cfg, "nntp.$k", $url) // next;
741 $self->{nntp_opt}->{$sec}->{$k} = $to;
747 # Net::NNTP doesn't support CAPABILITIES, yet
748 sub try_starttls ($) {
750 return if $host =~ /\.onion\z/s;
751 return if $host =~ /\A127\.[0-9]+\.[0-9]+\.[0-9]+\z/s;
752 return if $host eq '::1';
757 my ($nn_arg, $nntp_opt, $url) = @_;
758 my $nn = Net::NNTP->new(%$nn_arg) or die "E: <$url> new: $!\n";
760 # default to using STARTTLS if it's available, but allow
761 # it to be disabled for localhost/VPN users
762 if (!$nn_arg->{SSL} && $nn->can('starttls')) {
763 if (!defined($nntp_opt->{starttls}) &&
764 try_starttls($nn_arg->{Host})) {
765 # soft fail by default
766 $nn->starttls or warn <<"";
767 W: <$url> STARTTLS tried and failed (not requested)
769 } elsif ($nntp_opt->{starttls}) {
770 # hard fail if explicitly configured
771 $nn->starttls or die <<"";
772 E: <$url> STARTTLS requested and failed
775 } elsif ($nntp_opt->{starttls}) {
776 $nn->can('starttls') or
777 die "E: <$url> Net::NNTP too old for STARTTLS\n";
778 $nn->starttls or die <<"";
779 E: <$url> STARTTLS requested and failed
785 sub nn_for ($$$) { # nn = Net::NNTP
786 my ($self, $url, $nn_args) = @_;
787 my $uri = uri_new($url);
788 my $sec = uri_section($uri);
789 my $nntp_opt = $self->{nntp_opt}->{$sec} //= {};
790 my $host = $uri->host;
791 # Net::NNTP and Net::Netrc both mishandle `0', so we pass `127.0.0.1'
792 $host = '127.0.0.1' if $host eq '0';
795 if (defined(my $ui = $uri->userinfo)) {
796 require PublicInbox::GitCredential;
799 protocol => uri_scheme($uri),
801 }, 'PublicInbox::GitCredential';
802 ($u, $p) = split(/:/, $ui, 2);
803 ($cred->{username}, $cred->{password}) = ($u, $p);
804 $cred->check_netrc unless defined $p;
806 my $common = $nn_args->{$sec} // {};
810 SSL => $uri->secure, # snews == nntps
811 %$common, # may Debug ....
813 my $nn = nn_new($nn_arg, $nntp_opt, $url);
816 $cred->fill; # may prompt user here
817 if ($nn->authinfo($u, $p)) {
818 push @{$nntp_opt->{-postconn}}, [ 'authinfo', $u, $p ];
820 warn "E: <$url> AUTHINFO $u XXXX failed\n";
825 if ($nntp_opt->{compress}) {
826 # https://rt.cpan.org/Ticket/Display.html?id=129967
827 if ($nn->can('compress')) {
829 push @{$nntp_opt->{-postconn}}, [ 'compress' ];
831 warn "W: <$url> COMPRESS failed\n";
834 delete $nntp_opt->{compress};
836 W: <$url> COMPRESS not supported by Net::NNTP
837 W: see https://rt.cpan.org/Ticket/Display.html?id=129967 for updates
842 $self->{nn_arg}->{$sec} = $nn_arg;
843 $cred->run($nn ? 'approve' : 'reject') if $cred;
847 sub nntp_fetch_all ($$$) {
848 my ($self, $nn, $url) = @_;
849 my $uri = uri_new($url);
850 my ($group, $num_a, $num_b) = $uri->group;
851 my $sec = uri_section($uri);
852 my ($nr, $beg, $end) = $nn->group($group);
853 unless (defined($nr)) {
854 chomp(my $msg = $nn->message);
855 return "E: GROUP $group <$sec> $msg";
858 # IMAPTracker is also used for tracking NNTP, UID == article number
859 # LIST.ACTIVE can get the equivalent of UIDVALIDITY, but that's
860 # expensive. So we assume newsgroups don't change:
861 my $itrk = PublicInbox::IMAPTracker->new($url);
862 my (undef, $l_art) = $itrk->get_last;
863 $l_art //= $beg; # initial import
865 # allow users to specify articles to refetch
866 # cf. https://tools.ietf.org/id/draft-gilman-news-url-01.txt
867 # nntp://example.com/inbox.foo/$num_a-$num_b
868 $l_art = $num_a if defined($num_a) && $num_a < $l_art;
869 $end = $num_b if defined($num_b) && $num_b < $end;
871 return if $l_art >= $end; # nothing to do
874 warn "I: $url fetching ARTICLE $beg..$end\n";
875 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
877 local $SIG{__WARN__} = sub {
878 $warn_cb->("$url ", $art ? ("ARTICLE $art") : (), "\n", @_);
880 my $inboxes = $self->{nntp}->{$url};
883 last if $self->{quit};
885 my $raw = $nn->article($art);
886 unless (defined($raw)) {
887 my $msg = $nn->message;
888 if ($nn->code == 421) { # pseudo response from Net::Cmd
891 } else { # probably just a deleted message (spam)
896 s/\r\n/\n/ for @$raw;
897 $raw = join('', @$raw);
899 for my $ibx (@$inboxes) {
900 my $eml = PublicInbox::Eml->new($raw);
901 import_eml($self, $ibx, $eml);
903 } elsif ($inboxes eq 'watchspam') {
904 my $eml = PublicInbox::Eml->new(\$raw);
905 my $arg = [ $self, $eml, "$url ARTICLE $art" ];
906 $self->{config}->each_inbox(\&remove_eml_i, $arg);
908 die "BUG: destination unknown $inboxes";
912 $itrk->update_last(0, $last_art) if defined $last_art;
913 _done_for_now($self);
917 sub watch_nntp_init ($$) {
918 my ($self, $poll) = @_;
919 eval { require Net::NNTP } or
920 die "Net::NNTP is required for NNTP:\n$@\n";
921 eval { require PublicInbox::IMAPTracker } or
922 die "DBD::SQLite is required for NNTP\n:$@\n";
924 my $nn_args = nntp_common_init($self); # read args from config
926 # make sure we can connect and cache the credentials in memory
927 $self->{nn_arg} = {}; # schema://authority => Net::NNTP->new args
928 for my $url (sort keys %{$self->{nntp}}) {
929 nn_for($self, $url, $nn_args);
931 for my $url (keys %{$self->{nntp}}) {
932 my $uri = uri_new($url);
933 my $sec = uri_section($uri);
934 my $intvl = $self->{nntp_opt}->{$sec}->{pollInterval};
935 push @{$poll->{$intvl || 120}}, $url;
940 my ($self, $sig, $oldset) = @_;
941 $self->{oldset} = $oldset;
943 my $poll = {}; # intvl_seconds => [ url1, url2 ]
944 watch_imap_init($self, $poll) if $self->{imap};
945 watch_nntp_init($self, $poll) if $self->{nntp};
946 while (my ($intvl, $urls) = each %$poll) {
947 # poll all URLs for a given interval sequentially
948 PublicInbox::DS::add_timer(0, \&poll_fetch_fork,
949 [$self, $intvl, $urls]);
951 watch_fs_init($self) if $self->{mdre};
952 PublicInbox::DS->SetPostLoopCallback(sub { !$self->quit_done });
953 PublicInbox::DS->EventLoop;
954 _done_for_now($self);
958 my ($self, $op) = @_;
959 push @{$self->{ops}}, $op;
960 PublicInbox::DS::requeue($self);
965 return if $self->{quit};
966 my $op = shift @{$self->{ops}};
967 local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
969 # continue existing scan
971 my $opendirs = $self->{opendirs};
972 my @dirnames = keys %$opendirs;
973 foreach my $dir (@dirnames) {
974 my $dh = delete $opendirs->{$dir};
976 while (my $fn = readdir($dh)) {
977 _try_path($self, "$dir/$fn");
980 $opendirs->{$dir} = $dh if $n < 0;
982 if ($op && $op eq 'full') {
983 foreach my $dir (keys %{$self->{mdmap}}) {
984 next if $opendirs->{$dir}; # already in progress
985 my $ok = opendir(my $dh, $dir);
987 warn "failed to open $dir: $!\n";
991 while (my $fn = readdir($dh)) {
992 _try_path($self, "$dir/$fn");
995 $opendirs->{$dir} = $dh if $n < 0;
998 _done_for_now($self);
999 # do we have more work to do?
1000 PublicInbox::DS::requeue($self) if keys %$opendirs;
1004 my ($self, $op) = @_;
1005 push @{$self->{ops}}, $op;
1010 my ($self, $ibx) = @_;
1011 my $importers = $self->{importers};
1012 my $im = $importers->{"$ibx"} ||= $ibx->importer(0);
1013 if (scalar(keys(%$importers)) > 2) {
1014 delete $importers->{"$ibx"};
1015 _done_for_now($self);
1018 $importers->{"$ibx"} = $im;
1021 # XXX consider sharing with V2Writable, this only requires read-only access
1022 sub content_exists ($$) {
1023 my ($ibx, $eml) = @_;
1024 my $over = $ibx->over or return;
1025 my $mids = mids($eml);
1026 my $chash = content_hash($eml);
1028 for my $mid (@$mids) {
1029 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
1030 my $cmp = $ibx->smsg_eml($smsg) or return;
1031 return 1 if $chash eq content_hash($cmp);
1040 my ($mime, $ibx) = @_;
1041 return if content_exists($ibx, $mime);
1043 if ($sc->spamcheck($mime, \$tmp)) {
1044 return PublicInbox::Eml->new(\$tmp);
1046 warn $mime->header('Message-ID')." failed spam check\n";
1052 $_[0] =~ s!\Amaildir:!! or return;
1059 my ($cur, $ws, $ibx) = @_;
1060 if ($ws && !ref($ws) && $ws eq 'watchspam') {
1062 E: $cur is a spam folder and cannot be used for `$ibx->{name}' input
1072 # URI::snews exists, URI::nntps does not, so use URI::snews
1073 $url =~ s!\Anntps://!snews://!i;
1079 require PublicInbox::URIimap;
1080 my $uri = PublicInbox::URIimap->new($url);
1081 $uri ? $uri->canonical->as_string : undef;
1084 my %IS_NNTP = (news => 1, snews => 1, nntp => 1);
1088 my $uri = uri_new($url);
1089 return unless $uri && $IS_NNTP{$uri->scheme} && $uri->group;
1090 $url = $uri->canonical->as_string;
1091 # nntps is IANA registered, snews is deprecated
1092 $url =~ s!\Asnews://!nntps://!;