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;
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);
18 *mime_from_path = \&PublicInbox::InboxWritable::mime_from_path;
20 sub compile_watchheaders ($) {
23 if (my $whs = $ibx->{watchheader}) {
25 my ($k, $v) = split(/:/, $_, 2);
26 # XXX should this be case-insensitive?
27 # Or, mutt-style, case-sensitive iff
28 # a capital letter exists?
29 push @$watch_hdrs, [ $k, qr/\Q$v\E/ ];
32 if (my $list_ids = $ibx->{listid}) {
34 # RFC2919 section 6 stipulates
35 # "case insensitive equality"
36 my $re = qr/<[ \t]*\Q$_\E[ \t]*>/i;
37 push @$watch_hdrs, ['List-Id', $re ];
40 $ibx->{-watchheaders} = $watch_hdrs if scalar @$watch_hdrs;
44 my ($class, $config) = @_;
46 my (%imap, %nntp); # url => [inbox objects] or 'watchspam'
48 # "publicinboxwatch" is the documented namespace
49 # "publicinboxlearn" is legacy but may be supported
51 foreach my $pfx (qw(publicinboxwatch publicinboxlearn)) {
52 my $k = "$pfx.watchspam";
53 defined(my $dirs = $config->{$k}) or next;
54 $dirs = PublicInbox::Config::_array($dirs);
55 for my $dir (@$dirs) {
57 if (is_maildir($dir)) {
58 # skip "new", no MUA has seen it, yet.
59 $mdmap{"$dir/cur"} = 'watchspam';
60 } elsif ($url = imap_url($dir)) {
61 $imap{$url} = 'watchspam';
62 } elsif ($url = nntp_url($dir)) {
63 $nntp{$url} = 'watchspam';
65 warn "unsupported $k=$dir\n";
70 my $k = 'publicinboxwatch.spamcheck';
72 my $spamcheck = PublicInbox::Spamcheck::get($config, $k, $default);
73 $spamcheck = _spamcheck_cb($spamcheck) if $spamcheck;
75 $config->each_inbox(sub {
76 # need to make all inboxes writable for spam removal:
77 my $ibx = $_[0] = PublicInbox::InboxWritable->new($_[0]);
79 my $watches = $ibx->{watch} or return;
80 $watches = PublicInbox::Config::_array($watches);
81 for my $watch (@$watches) {
83 if (is_maildir($watch)) {
84 compile_watchheaders($ibx);
85 my ($new, $cur) = ("$watch/new", "$watch/cur");
86 my $cur_dst = $mdmap{$cur} //= [];
87 return if is_watchspam($cur, $cur_dst, $ibx);
88 push @{$mdmap{$new} //= []}, $ibx;
90 } elsif ($url = imap_url($watch)) {
91 return if is_watchspam($url, $imap{$url}, $ibx);
92 compile_watchheaders($ibx);
93 push @{$imap{$url} ||= []}, $ibx;
94 } elsif ($url = nntp_url($watch)) {
95 return if is_watchspam($url, $nntp{$url}, $ibx);
96 compile_watchheaders($ibx);
97 push @{$nntp{$url} ||= []}, $ibx;
99 warn "watch unsupported: $k=$watch\n";
105 if (scalar keys %mdmap) {
106 $mdre = join('|', map { quotemeta($_) } keys %mdmap);
107 $mdre = qr!\A($mdre)/!;
109 return unless $mdre || scalar(keys %imap) || scalar(keys %nntp);
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 (values %{$self->{importers}}) {
128 $_->done if $_; # $_ may be undef during cleanup
132 sub remove_eml_i { # each_inbox callback
133 my ($ibx, $arg) = @_;
134 my ($self, $eml, $loc) = @$arg;
136 my $im = _importer_for($self, $ibx);
137 $im->remove($eml, 'spam');
138 if (my $scrub = $ibx->filter($im)) {
139 my $scrubbed = $scrub->scrub($eml, 1);
141 $scrubbed == REJECT() and return;
142 $im->remove($scrubbed, 'spam');
145 warn "error removing spam at: $loc from $ibx->{name}: $@\n" if $@;
149 my ($self, $path) = @_;
150 # path must be marked as (S)een
151 $path =~ /:2,[A-R]*S[T-Za-z]*\z/ or return;
152 my $eml = mime_from_path($path) or return;
153 $self->{config}->each_inbox(\&remove_eml_i, [ $self, $eml, $path ]);
156 sub import_eml ($$$) {
157 my ($self, $ibx, $eml) = @_;
158 my $im = _importer_for($self, $ibx);
160 # any header match means it's eligible for the inbox:
161 if (my $watch_hdrs = $ibx->{-watchheaders}) {
163 my $hdr = $eml->header_obj;
164 for my $wh (@$watch_hdrs) {
165 my @v = $hdr->header_raw($wh->[0]);
166 $ok = grep(/$wh->[1]/, @v) and last;
171 if (my $scrub = $ibx->filter($im)) {
172 my $ret = $scrub->scrub($eml) or return;
173 $ret == REJECT() and return;
176 $im->add($eml, $self->{spamcheck});
180 my ($self, $path) = @_;
181 return unless PublicInbox::InboxWritable::is_maildir_path($path);
182 if ($path !~ $self->{mdre}) {
183 warn "unrecognized path: $path\n";
186 my $inboxes = $self->{mdmap}->{$1};
188 warn "unmappable dir: $1\n";
191 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
192 local $SIG{__WARN__} = sub {
193 $warn_cb->("path: $path\n");
196 if (!ref($inboxes) && $inboxes eq 'watchspam') {
197 return _remove_spam($self, $path);
199 foreach my $ibx (@$inboxes) {
200 my $eml = mime_from_path($path) or next;
201 import_eml($self, $ibx, $eml);
207 return unless $self->{quit};
209 # don't have reliable wakeups, keep signalling
211 for (qw(idle_pids poll_pids)) {
212 my $pids = $self->{$_} or next;
214 $done = undef if kill('QUIT', $_);
223 %{$self->{opendirs}} = ();
224 _done_for_now($self);
226 if (my $idle_mic = $self->{idle_mic}) {
227 eval { $idle_mic->done };
229 warn "IDLE DONE error: $@\n";
230 eval { $idle_mic->disconnect };
231 warn "IDLE LOGOUT error: $@\n" if $@;
236 sub watch_fs_init ($) {
239 delete $self->{done_timer};
240 _done_for_now($self);
243 _try_path($self, $_[0]->fullname);
244 $self->{done_timer} //= PublicInbox::DS::requeue($done);
246 require PublicInbox::DirIdle;
247 # inotify_create + EPOLL_CTL_ADD
248 PublicInbox::DirIdle->new([keys %{$self->{mdmap}}], $cb);
251 # avoid exposing deprecated "snews" to users.
252 my %SCHEME_MAP = ('snews' => 'nntps');
256 my $scheme = $uri->scheme;
257 $SCHEME_MAP{$scheme} // $scheme;
260 # returns the git config section name, e.g [imap "imaps://user@example.com"]
261 # without the mailbox, so we can share connections between different inboxes
262 sub uri_section ($) {
264 uri_scheme($uri) . '://' . $uri->authority;
267 sub cfg_intvl ($$$) {
268 my ($cfg, $key, $url) = @_;
269 my $v = $cfg->urlmatch($key, $url) // return;
270 $v =~ /\A[0-9]+(?:\.[0-9]+)?\z/s and return $v + 0;
271 if (ref($v) eq 'ARRAY') {
272 $v = join(', ', @$v);
273 warn "W: $key has multiple values: $v\nW: $key ignored\n";
275 warn "W: $key=$v is not a numeric value in seconds\n";
280 my ($cfg, $key, $url) = @_;
281 my $orig = $cfg->urlmatch($key, $url) // return;
282 my $bool = PublicInbox::Config::_git_config_bool($orig);
283 warn "W: $key=$orig for $url is not boolean\n" unless defined($bool);
287 # flesh out common IMAP-specific data structures
288 sub imap_common_init ($) {
290 my $cfg = $self->{config};
291 my $mic_args = {}; # scheme://authority => Mail:IMAPClient arg
292 for my $url (sort keys %{$self->{imap}}) {
293 my $uri = PublicInbox::URIimap->new($url);
294 my $sec = uri_section($uri);
295 for my $k (qw(Starttls Debug Compress)) {
296 my $bool = cfg_bool($cfg, "imap.$k", $url) // next;
297 $mic_args->{$sec}->{$k} = $bool;
299 my $to = cfg_intvl($cfg, 'imap.timeout', $url);
300 $mic_args->{$sec}->{Timeout} = $to if $to;
301 for my $k (qw(pollInterval idleInterval)) {
302 $to = cfg_intvl($cfg, "imap.$k", $url) // next;
303 $self->{imap_opt}->{$sec}->{$k} = $to;
305 my $k = 'imap.fetchBatchSize';
306 my $bs = $cfg->urlmatch($k, $url) // next;
307 if ($bs =~ /\A([0-9]+)\z/) {
308 $self->{imap_opt}->{$sec}->{batch_size} = $bs;
310 warn "$k=$bs is not an integer\n";
316 sub auth_anon_cb { '' }; # for Mail::IMAPClient::Authcallback
318 sub mic_for ($$$) { # mic = Mail::IMAPClient
319 my ($self, $url, $mic_args) = @_;
320 my $uri = PublicInbox::URIimap->new($url);
321 require PublicInbox::GitCredential;
324 protocol => $uri->scheme,
326 username => $uri->user,
327 password => $uri->password,
328 }, 'PublicInbox::GitCredential';
329 my $common = $mic_args->{uri_section($uri)} // {};
330 # IMAPClient and Net::Netrc both mishandles `0', so we pass `127.0.0.1'
331 my $host = $cred->{host};
332 $host = '127.0.0.1' if $host eq '0';
336 Ssl => $uri->scheme eq 'imaps',
337 Keepalive => 1, # SO_KEEPALIVE
338 %$common, # may set Starttls, Compress, Debug ....
340 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or
341 die "E: <$url> new: $@\n";
343 # default to using STARTTLS if it's available, but allow
344 # it to be disabled since I usually connect to localhost
345 if (!$mic_arg->{Ssl} && !defined($mic_arg->{Starttls}) &&
346 $mic->has_capability('STARTTLS') &&
347 $mic->can('starttls')) {
348 $mic->starttls or die "E: <$url> STARTTLS: $@\n";
351 # do we even need credentials?
352 if (!defined($cred->{username}) &&
353 $mic->has_capability('AUTH=ANONYMOUS')) {
357 $cred->check_netrc unless defined $cred->{password};
358 $cred->fill; # may prompt user here
359 $mic->User($mic_arg->{User} = $cred->{username});
360 $mic->Password($mic_arg->{Password} = $cred->{password});
361 } else { # AUTH=ANONYMOUS
362 $mic->Authmechanism($mic_arg->{Authmechanism} = 'ANONYMOUS');
363 $mic->Authcallback($mic_arg->{Authcallback} = \&auth_anon_cb);
365 if ($mic->login && $mic->IsAuthenticated) {
366 # success! keep IMAPClient->new arg in case we get disconnected
367 $self->{mic_arg}->{uri_section($uri)} = $mic_arg;
369 warn "E: <$url> LOGIN: $@\n";
372 $cred->run($mic ? 'approve' : 'reject') if $cred;
376 sub imap_import_msg ($$$$) {
377 my ($self, $url, $uid, $raw) = @_;
378 # our target audience expects LF-only, save storage
379 $$raw =~ s/\r\n/\n/sg;
381 my $inboxes = $self->{imap}->{$url};
383 for my $ibx (@$inboxes) {
384 my $eml = PublicInbox::Eml->new($$raw);
385 my $x = import_eml($self, $ibx, $eml);
387 } elsif ($inboxes eq 'watchspam') {
388 my $eml = PublicInbox::Eml->new($raw);
389 my $arg = [ $self, $eml, "$url UID:$uid" ];
390 $self->{config}->each_inbox(\&remove_eml_i, $arg);
392 die "BUG: destination unknown $inboxes";
396 sub imap_fetch_all ($$$) {
397 my ($self, $mic, $url) = @_;
398 my $uri = PublicInbox::URIimap->new($url);
399 my $sec = uri_section($uri);
400 my $mbx = $uri->mailbox;
401 $mic->Clear(1); # trim results history
402 $mic->examine($mbx) or return "E: EXAMINE $mbx ($sec) failed: $!";
403 my ($r_uidval, $r_uidnext);
404 for ($mic->Results) {
405 /^\* OK \[UIDVALIDITY ([0-9]+)\].*/ and $r_uidval = $1;
406 /^\* OK \[UIDNEXT ([0-9]+)\].*/ and $r_uidnext = $1;
407 last if $r_uidval && $r_uidnext;
409 $r_uidval //= $mic->uidvalidity($mbx) //
410 return "E: $url cannot get UIDVALIDITY";
411 $r_uidnext //= $mic->uidnext($mbx) //
412 return "E: $url cannot get UIDNEXT";
413 my $itrk = PublicInbox::IMAPTracker->new($url);
414 my ($l_uidval, $l_uid) = $itrk->get_last;
415 $l_uidval //= $r_uidval; # first time
417 if ($l_uidval != $r_uidval) {
418 return "E: $url UIDVALIDITY mismatch\n".
419 "E: local=$l_uidval != remote=$r_uidval";
421 my $r_uid = $r_uidnext - 1;
422 if ($l_uid != 1 && $l_uid > $r_uid) {
423 return "E: $url local UID exceeds remote ($l_uid > $r_uid)\n".
424 "E: $url strangely, UIDVALIDLITY matches ($l_uidval)\n";
426 return if $l_uid >= $r_uid; # nothing to do
428 warn "I: $url fetching UID $l_uid:$r_uid\n";
429 $mic->Uid(1); # the default, we hope
430 my $bs = $self->{imap_opt}->{$sec}->{batch_size} // 1;
431 my $req = $mic->imap4rev1 ? 'BODY.PEEK[]' : 'RFC822.PEEK';
433 # TODO: FLAGS may be useful for personal use
437 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
438 local $SIG{__WARN__} = sub {
440 $warn_cb->("$url UID:$batch\n");
445 # I wish "UID FETCH $START:*" could work, but:
446 # 1) servers do not need to return results in any order
447 # 2) Mail::IMAPClient doesn't offer a streaming API
448 $uids = $mic->search("UID $l_uid:*") or
449 return "E: $url UID SEARCH $l_uid:* error: $!";
450 return if scalar(@$uids) == 0;
452 # RFC 3501 doesn't seem to indicate order of UID SEARCH
453 # responses, so sort it ourselves. Order matters so
454 # IMAPTracker can store the newest UID.
455 @$uids = sort { $a <=> $b } @$uids;
457 # Did we actually get new messages?
458 return if $uids->[0] < $l_uid;
460 $l_uid = $uids->[-1] + 1; # for next search
463 while (scalar @$uids) {
464 my @batch = splice(@$uids, 0, $bs);
465 $batch = join(',', @batch);
466 local $0 = "UID:$batch $mbx $sec";
467 my $r = $mic->fetch_hash($batch, $req);
468 unless ($r) { # network error?
469 $err = "E: $url UID FETCH $batch error: $!";
472 for my $uid (@batch) {
473 # messages get deleted, so holes appear
474 my $per_uid = delete $r->{$uid} // next;
475 my $raw = delete($per_uid->{$key}) // next;
476 imap_import_msg($self, $url, $uid, \$raw);
478 last if $self->{quit};
480 last if $self->{quit};
482 _done_for_now($self);
483 $itrk->update_last($r_uidval, $last_uid) if defined $last_uid;
484 } until ($err || $self->{quit});
488 sub imap_idle_once ($$$$) {
489 my ($self, $mic, $intvl, $url) = @_;
490 my $i = $intvl //= (29 * 60);
491 my $end = now() + $intvl;
492 warn "I: $url idling for ${intvl}s\n";
493 local $0 = "IDLE $0";
494 unless ($mic->idle) {
495 return if $self->{quit};
496 return "E: IDLE failed on $url: $!";
498 $self->{idle_mic} = $mic; # for ->quit
500 until ($self->{quit} || !$mic->IsConnected ||
501 grep(/^\* [0-9]+ EXISTS/, @res) || $i <= 0) {
502 @res = $mic->idle_data($i);
505 delete $self->{idle_mic};
506 unless ($self->{quit}) {
507 $mic->IsConnected or return "E: IDLE disconnected on $url";
508 $mic->done or return "E: IDLE DONE failed on $url: $!";
513 # idles on a single URI
514 sub watch_imap_idle_1 ($$$) {
515 my ($self, $url, $intvl) = @_;
516 my $uri = PublicInbox::URIimap->new($url);
517 my $sec = uri_section($uri);
518 my $mic_arg = $self->{mic_arg}->{$sec} or
519 die "BUG: no Mail::IMAPClient->new arg for $sec";
521 local $0 = $uri->mailbox." $sec";
522 until ($self->{quit}) {
523 $mic //= PublicInbox::IMAPClient->new(%$mic_arg);
525 if ($mic && $mic->IsConnected) {
526 $err = imap_fetch_all($self, $mic, $url);
527 $err //= imap_idle_once($self, $mic, $intvl, $url);
529 $err = "not connected: $!";
531 if ($err && !$self->{quit}) {
534 sleep 60 unless $self->{quit};
539 sub watch_atfork_child ($) {
541 delete $self->{idle_pids};
542 delete $self->{poll_pids};
543 delete $self->{opendirs};
544 PublicInbox::DS->Reset;
545 %SIG = (%SIG, %{$self->{sig}}, CHLD => 'DEFAULT');
546 PublicInbox::Sigfd::sig_setmask($self->{oldset});
549 sub watch_atfork_parent ($) {
551 _done_for_now($self);
554 sub imap_idle_requeue ($) { # DS::add_timer callback
555 my ($self, $url_intvl) = @{$_[0]};
556 return if $self->{quit};
557 push @{$self->{idle_todo}}, $url_intvl;
561 sub imap_idle_reap { # PublicInbox::DS::dwaitpid callback
562 my ($self, $pid) = @_;
563 my $url_intvl = delete $self->{idle_pids}->{$pid} or
564 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
566 my ($url, $intvl) = @$url_intvl;
567 return if $self->{quit};
568 warn "W: PID=$pid on $url died: \$?=$?\n" if $?;
569 PublicInbox::DS::add_timer(60,
570 \&imap_idle_requeue, [ $self, $url_intvl ]);
573 sub imap_idle_fork ($$) {
574 my ($self, $url_intvl) = @_;
575 my ($url, $intvl) = @$url_intvl;
576 defined(my $pid = fork) or die "fork: $!";
578 watch_atfork_child($self);
579 watch_imap_idle_1($self, $url, $intvl);
582 $self->{idle_pids}->{$pid} = $url_intvl;
583 PublicInbox::DS::dwaitpid($pid, \&imap_idle_reap, $self);
588 return if $self->{quit};
589 my $idle_todo = $self->{idle_todo};
590 if ($idle_todo && @$idle_todo) {
591 watch_atfork_parent($self);
592 while (my $url_intvl = shift(@$idle_todo)) {
593 imap_idle_fork($self, $url_intvl);
596 goto(&fs_scan_step) if $self->{mdre};
599 sub watch_imap_fetch_all ($$) {
600 my ($self, $urls) = @_;
601 for my $url (@$urls) {
602 my $uri = PublicInbox::URIimap->new($url);
603 my $sec = uri_section($uri);
604 my $mic_arg = $self->{mic_arg}->{$sec} or
605 die "BUG: no Mail::IMAPClient->new arg for $sec";
606 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or next;
607 my $err = imap_fetch_all($self, $mic, $url);
608 last if $self->{quit};
609 warn $err, "\n" if $err;
613 sub watch_nntp_fetch_all ($$) {
614 my ($self, $urls) = @_;
615 for my $url (@$urls) {
616 my $uri = uri_new($url);
617 my $sec = uri_section($uri);
618 my $nn_arg = $self->{nn_arg}->{$sec} or
619 die "BUG: no Net::NNTP->new arg for $sec";
620 my $nntp_opt = $self->{nntp_opt}->{$sec};
621 my $nn = nn_new($nn_arg, $nntp_opt, $url);
623 warn "E: $url: \$!=$!\n";
626 last if $self->{quit};
627 if (my $postconn = $nntp_opt->{-postconn}) {
628 for my $m_arg (@$postconn) {
629 my ($method, @args) = @$m_arg;
630 $nn->$method(@args) and next;
631 warn "E: <$url> $method failed\n";
636 last if $self->{quit};
638 my $err = nntp_fetch_all($self, $nn, $url);
639 warn $err, "\n" if $err;
644 sub poll_fetch_fork ($) { # DS::add_timer callback
645 my ($self, $intvl, $urls) = @{$_[0]};
646 return if $self->{quit};
647 watch_atfork_parent($self);
648 defined(my $pid = fork) or die "fork: $!";
650 watch_atfork_child($self);
651 if ($urls->[0] =~ m!\Aimaps?://!i) {
652 watch_imap_fetch_all($self, $urls);
654 watch_nntp_fetch_all($self, $urls);
658 $self->{poll_pids}->{$pid} = [ $intvl, $urls ];
659 PublicInbox::DS::dwaitpid($pid, \&poll_fetch_reap, $self);
662 sub poll_fetch_reap { # PublicInbox::DS::dwaitpid callback
663 my ($self, $pid) = @_;
664 my $intvl_urls = delete $self->{poll_pids}->{$pid} or
665 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
666 return if $self->{quit};
667 my ($intvl, $urls) = @$intvl_urls;
669 warn "W: PID=$pid died: \$?=$?\n", map { "$_\n" } @$urls;
671 warn("I: will check $_ in ${intvl}s\n") for @$urls;
672 PublicInbox::DS::add_timer($intvl, \&poll_fetch_fork,
673 [$self, $intvl, $urls]);
676 sub watch_imap_init ($$) {
677 my ($self, $poll) = @_;
678 eval { require PublicInbox::IMAPClient } or
679 die "Mail::IMAPClient is required for IMAP:\n$@\n";
680 eval { require PublicInbox::IMAPTracker } or
681 die "DBD::SQLite is required for IMAP\n:$@\n";
683 my $mic_args = imap_common_init($self); # read args from config
685 # make sure we can connect and cache the credentials in memory
686 $self->{mic_arg} = {}; # schema://authority => IMAPClient->new args
687 my $mics = {}; # schema://authority => IMAPClient obj
688 for my $url (sort keys %{$self->{imap}}) {
689 my $uri = PublicInbox::URIimap->new($url);
690 $mics->{uri_section($uri)} //= mic_for($self, $url, $mic_args);
693 my $idle = []; # [ [ url1, intvl1 ], [url2, intvl2] ]
694 for my $url (keys %{$self->{imap}}) {
695 my $uri = PublicInbox::URIimap->new($url);
696 my $sec = uri_section($uri);
697 my $mic = $mics->{$sec};
698 my $intvl = $self->{imap_opt}->{$sec}->{pollInterval};
699 if ($mic->has_capability('IDLE') && !$intvl) {
700 $intvl = $self->{imap_opt}->{$sec}->{idleInterval};
701 push @$idle, [ $url, $intvl // () ];
703 push @{$poll->{$intvl || 120}}, $url;
707 $self->{idle_todo} = $idle;
708 PublicInbox::DS::requeue($self); # ->event_step to fork
712 # flesh out common NNTP-specific data structures
713 sub nntp_common_init ($) {
715 my $cfg = $self->{config};
716 my $nn_args = {}; # scheme://authority => Net::NNTP->new arg
717 for my $url (sort keys %{$self->{nntp}}) {
718 my $sec = uri_section(uri_new($url));
720 # Debug and Timeout are passed to Net::NNTP->new
721 my $v = cfg_bool($cfg, 'nntp.Debug', $url);
722 $nn_args->{$sec}->{Debug} = $v if defined $v;
723 my $to = cfg_intvl($cfg, 'nntp.Timeout', $url);
724 $nn_args->{$sec}->{Timeout} = $to if $to;
726 # Net::NNTP post-connect commands
727 for my $k (qw(starttls compress)) {
728 $v = cfg_bool($cfg, "nntp.$k", $url) // next;
729 $self->{nntp_opt}->{$sec}->{$k} = $v;
733 for my $k (qw(pollInterval)) {
734 $to = cfg_intvl($cfg, "nntp.$k", $url) // next;
735 $self->{nntp_opt}->{$sec}->{$k} = $to;
741 # Net::NNTP doesn't support CAPABILITIES, yet
742 sub try_starttls ($) {
744 return if $host =~ /\.onion\z/s;
745 return if $host =~ /\A127\.[0-9]+\.[0-9]+\.[0-9]+\z/s;
746 return if $host eq '::1';
751 my ($nn_arg, $nntp_opt, $url) = @_;
752 my $nn = Net::NNTP->new(%$nn_arg) or die "E: <$url> new: $!\n";
754 # default to using STARTTLS if it's available, but allow
755 # it to be disabled for localhost/VPN users
756 if (!$nn_arg->{SSL} && $nn->can('starttls')) {
757 if (!defined($nntp_opt->{starttls}) &&
758 try_starttls($nn_arg->{Host})) {
759 # soft fail by default
760 $nn->starttls or warn <<"";
761 W: <$url> STARTTLS tried and failed (not requested)
763 } elsif ($nntp_opt->{starttls}) {
764 # hard fail if explicitly configured
765 $nn->starttls or die <<"";
766 E: <$url> STARTTLS requested and failed
769 } elsif ($nntp_opt->{starttls}) {
770 $nn->can('starttls') or
771 die "E: <$url> Net::NNTP too old for STARTTLS\n";
772 $nn->starttls or die <<"";
773 E: <$url> STARTTLS requested and failed
779 sub nn_for ($$$) { # nn = Net::NNTP
780 my ($self, $url, $nn_args) = @_;
781 my $uri = uri_new($url);
782 my $sec = uri_section($uri);
783 my $nntp_opt = $self->{nntp_opt}->{$sec} //= {};
784 my $host = $uri->host;
785 # Net::NNTP and Net::Netrc both mishandle `0', so we pass `127.0.0.1'
786 $host = '127.0.0.1' if $host eq '0';
789 if (defined(my $ui = $uri->userinfo)) {
790 require PublicInbox::GitCredential;
793 protocol => uri_scheme($uri),
795 }, 'PublicInbox::GitCredential';
796 ($u, $p) = split(/:/, $ui, 2);
797 ($cred->{username}, $cred->{password}) = ($u, $p);
798 $cred->check_netrc unless defined $p;
800 my $common = $nn_args->{$sec} // {};
804 SSL => $uri->secure, # snews == nntps
805 %$common, # may Debug ....
807 my $nn = nn_new($nn_arg, $nntp_opt, $url);
810 $cred->fill; # may prompt user here
811 if ($nn->authinfo($u, $p)) {
812 push @{$nntp_opt->{-postconn}}, [ 'authinfo', $u, $p ];
814 warn "E: <$url> AUTHINFO $u XXXX failed\n";
819 if ($nntp_opt->{compress}) {
820 # https://rt.cpan.org/Ticket/Display.html?id=129967
821 if ($nn->can('compress')) {
823 push @{$nntp_opt->{-postconn}}, [ 'compress' ];
825 warn "W: <$url> COMPRESS failed\n";
828 delete $nntp_opt->{compress};
830 W: <$url> COMPRESS not supported by Net::NNTP
831 W: see https://rt.cpan.org/Ticket/Display.html?id=129967 for updates
836 $self->{nn_arg}->{$sec} = $nn_arg;
837 $cred->run($nn ? 'approve' : 'reject') if $cred;
841 sub nntp_fetch_all ($$$) {
842 my ($self, $nn, $url) = @_;
843 my $uri = uri_new($url);
844 my ($group, $num_a, $num_b) = $uri->group;
845 my $sec = uri_section($uri);
846 my ($nr, $beg, $end) = $nn->group($group);
847 unless (defined($nr)) {
848 chomp(my $msg = $nn->message);
849 return "E: GROUP $group <$sec> $msg";
852 # IMAPTracker is also used for tracking NNTP, UID == article number
853 # LIST.ACTIVE can get the equivalent of UIDVALIDITY, but that's
854 # expensive. So we assume newsgroups don't change:
855 my $itrk = PublicInbox::IMAPTracker->new($url);
856 my (undef, $l_art) = $itrk->get_last;
857 $l_art //= $beg; # initial import
859 # allow users to specify articles to refetch
860 # cf. https://tools.ietf.org/id/draft-gilman-news-url-01.txt
861 # nntp://example.com/inbox.foo/$num_a-$num_b
862 $l_art = $num_a if defined($num_a) && $num_a < $l_art;
863 $end = $num_b if defined($num_b) && $num_b < $end;
865 return if $l_art >= $end; # nothing to do
868 warn "I: $url fetching ARTICLE $beg..$end\n";
869 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
871 local $SIG{__WARN__} = sub {
872 $warn_cb->("$url ", $art ? ("ARTICLE $art") : (), "\n", @_);
874 my $inboxes = $self->{nntp}->{$url};
877 last if $self->{quit};
879 my $raw = $nn->article($art);
880 unless (defined($raw)) {
881 my $msg = $nn->message;
882 if ($nn->code == 421) { # pseudo response from Net::Cmd
885 } else { # probably just a deleted message (spam)
890 s/\r\n/\n/ for @$raw;
891 $raw = join('', @$raw);
893 for my $ibx (@$inboxes) {
894 my $eml = PublicInbox::Eml->new($raw);
895 import_eml($self, $ibx, $eml);
897 } elsif ($inboxes eq 'watchspam') {
898 my $eml = PublicInbox::Eml->new(\$raw);
899 my $arg = [ $self, $eml, "$url ARTICLE $art" ];
900 $self->{config}->each_inbox(\&remove_eml_i, $arg);
902 die "BUG: destination unknown $inboxes";
906 $itrk->update_last(0, $last_art) if defined $last_art;
907 _done_for_now($self);
911 sub watch_nntp_init ($$) {
912 my ($self, $poll) = @_;
913 eval { require Net::NNTP } or
914 die "Net::NNTP is required for NNTP:\n$@\n";
915 eval { require PublicInbox::IMAPTracker } or
916 die "DBD::SQLite is required for NNTP\n:$@\n";
918 my $nn_args = nntp_common_init($self); # read args from config
920 # make sure we can connect and cache the credentials in memory
921 $self->{nn_arg} = {}; # schema://authority => Net::NNTP->new args
922 for my $url (sort keys %{$self->{nntp}}) {
923 nn_for($self, $url, $nn_args);
925 for my $url (keys %{$self->{nntp}}) {
926 my $uri = uri_new($url);
927 my $sec = uri_section($uri);
928 my $intvl = $self->{nntp_opt}->{$sec}->{pollInterval};
929 push @{$poll->{$intvl || 120}}, $url;
934 my ($self, $sig, $oldset) = @_;
935 $self->{oldset} = $oldset;
937 my $poll = {}; # intvl_seconds => [ url1, url2 ]
938 watch_imap_init($self, $poll) if $self->{imap};
939 watch_nntp_init($self, $poll) if $self->{nntp};
940 while (my ($intvl, $urls) = each %$poll) {
941 # poll all URLs for a given interval sequentially
942 PublicInbox::DS::add_timer(0, \&poll_fetch_fork,
943 [$self, $intvl, $urls]);
945 watch_fs_init($self) if $self->{mdre};
946 PublicInbox::DS->SetPostLoopCallback(sub { !$self->quit_done });
947 PublicInbox::DS->EventLoop;
948 _done_for_now($self);
952 my ($self, $op) = @_;
953 push @{$self->{ops}}, $op;
954 PublicInbox::DS::requeue($self);
959 return if $self->{quit};
960 my $op = shift @{$self->{ops}};
961 local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
963 # continue existing scan
965 my $opendirs = $self->{opendirs};
966 my @dirnames = keys %$opendirs;
967 foreach my $dir (@dirnames) {
968 my $dh = delete $opendirs->{$dir};
970 while (my $fn = readdir($dh)) {
971 _try_path($self, "$dir/$fn");
974 $opendirs->{$dir} = $dh if $n < 0;
976 if ($op && $op eq 'full') {
977 foreach my $dir (keys %{$self->{mdmap}}) {
978 next if $opendirs->{$dir}; # already in progress
979 my $ok = opendir(my $dh, $dir);
981 warn "failed to open $dir: $!\n";
985 while (my $fn = readdir($dh)) {
986 _try_path($self, "$dir/$fn");
989 $opendirs->{$dir} = $dh if $n < 0;
992 _done_for_now($self);
993 # do we have more work to do?
994 PublicInbox::DS::requeue($self) if keys %$opendirs;
998 my ($self, $op) = @_;
999 push @{$self->{ops}}, $op;
1004 my ($self, $ibx) = @_;
1005 my $importers = $self->{importers};
1006 my $im = $importers->{"$ibx"} ||= $ibx->importer(0);
1007 if (scalar(keys(%$importers)) > 2) {
1008 delete $importers->{"$ibx"};
1009 _done_for_now($self);
1012 $importers->{"$ibx"} = $im;
1015 # XXX consider sharing with V2Writable, this only requires read-only access
1016 sub content_exists ($$) {
1017 my ($ibx, $eml) = @_;
1018 my $over = $ibx->over or return;
1019 my $mids = mids($eml);
1020 my $chash = content_hash($eml);
1022 for my $mid (@$mids) {
1023 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
1024 my $cmp = $ibx->smsg_eml($smsg) or return;
1025 return 1 if $chash eq content_hash($cmp);
1034 my ($mime, $ibx) = @_;
1035 return if content_exists($ibx, $mime);
1037 if ($sc->spamcheck($mime, \$tmp)) {
1038 return PublicInbox::Eml->new(\$tmp);
1040 warn $mime->header('Message-ID')." failed spam check\n";
1046 $_[0] =~ s!\Amaildir:!! or return;
1053 my ($cur, $ws, $ibx) = @_;
1054 if ($ws && !ref($ws) && $ws eq 'watchspam') {
1056 E: $cur is a spam folder and cannot be used for `$ibx->{name}' input
1066 # URI::snews exists, URI::nntps does not, so use URI::snews
1067 $url =~ s!\Anntps://!snews://!i;
1073 require PublicInbox::URIimap;
1074 my $uri = PublicInbox::URIimap->new($url);
1075 $uri ? $uri->canonical->as_string : undef;
1078 my %IS_NNTP = (news => 1, snews => 1, nntp => 1);
1082 my $uri = uri_new($url);
1083 return unless $uri && $IS_NNTP{$uri->scheme} && $uri->group;
1084 $url = $uri->canonical->as_string;
1085 # nntps is IANA registered, snews is deprecated
1086 $url =~ s!\Asnews://!nntps://!;