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);
16 *mime_from_path = \&PublicInbox::InboxWritable::mime_from_path;
18 sub compile_watchheaders ($) {
21 if (my $whs = $ibx->{watchheader}) {
23 my ($k, $v) = split(/:/, $_, 2);
24 # XXX should this be case-insensitive?
25 # Or, mutt-style, case-sensitive iff
26 # a capital letter exists?
27 push @$watch_hdrs, [ $k, qr/\Q$v\E/ ];
30 if (my $list_ids = $ibx->{listid}) {
32 # RFC2919 section 6 stipulates
33 # "case insensitive equality"
34 my $re = qr/<[ \t]*\Q$_\E[ \t]*>/i;
35 push @$watch_hdrs, ['List-Id', $re ];
38 $ibx->{-watchheaders} = $watch_hdrs if scalar @$watch_hdrs;
42 my ($class, $config) = @_;
44 my (%imap, %nntp); # url => [inbox objects] or 'watchspam'
46 # "publicinboxwatch" is the documented namespace
47 # "publicinboxlearn" is legacy but may be supported
49 foreach my $pfx (qw(publicinboxwatch publicinboxlearn)) {
50 my $k = "$pfx.watchspam";
51 defined(my $dirs = $config->{$k}) or next;
52 $dirs = PublicInbox::Config::_array($dirs);
53 for my $dir (@$dirs) {
55 if (is_maildir($dir)) {
56 # skip "new", no MUA has seen it, yet.
57 $mdmap{"$dir/cur"} = 'watchspam';
58 } elsif ($url = imap_url($dir)) {
59 $imap{$url} = 'watchspam';
60 } elsif ($url = nntp_url($dir)) {
61 $nntp{$url} = 'watchspam';
63 warn "unsupported $k=$dir\n";
68 my $k = 'publicinboxwatch.spamcheck';
70 my $spamcheck = PublicInbox::Spamcheck::get($config, $k, $default);
71 $spamcheck = _spamcheck_cb($spamcheck) if $spamcheck;
73 $config->each_inbox(sub {
74 # need to make all inboxes writable for spam removal:
75 my $ibx = $_[0] = PublicInbox::InboxWritable->new($_[0]);
77 my $watches = $ibx->{watch} or return;
78 $watches = PublicInbox::Config::_array($watches);
79 for my $watch (@$watches) {
81 if (is_maildir($watch)) {
82 compile_watchheaders($ibx);
83 my ($new, $cur) = ("$watch/new", "$watch/cur");
84 my $cur_dst = $mdmap{$cur} //= [];
85 return if is_watchspam($cur, $cur_dst, $ibx);
86 push @{$mdmap{$new} //= []}, $ibx;
88 } elsif ($url = imap_url($watch)) {
89 return if is_watchspam($url, $imap{$url}, $ibx);
90 compile_watchheaders($ibx);
91 push @{$imap{$url} ||= []}, $ibx;
92 } elsif ($url = nntp_url($watch)) {
93 return if is_watchspam($url, $nntp{$url}, $ibx);
94 compile_watchheaders($ibx);
95 push @{$nntp{$url} ||= []}, $ibx;
97 warn "watch unsupported: $k=$watch\n";
103 if (scalar keys %mdmap) {
104 $mdre = join('|', map { quotemeta($_) } keys %mdmap);
105 $mdre = qr!\A($mdre)/!;
107 return unless $mdre || scalar(keys %imap) || scalar(keys %nntp);
110 spamcheck => $spamcheck,
114 imap => scalar keys %imap ? \%imap : undef,
115 nntp => scalar keys %nntp? \%nntp : undef,
117 opendirs => {}, # dirname => dirhandle (in progress scans)
118 ops => [], # 'quit', 'full'
124 my $importers = $self->{importers};
125 foreach my $im (values %$importers) {
130 sub remove_eml_i { # each_inbox callback
131 my ($ibx, $arg) = @_;
132 my ($self, $eml, $loc) = @$arg;
134 my $im = _importer_for($self, $ibx);
135 $im->remove($eml, 'spam');
136 if (my $scrub = $ibx->filter($im)) {
137 my $scrubbed = $scrub->scrub($eml, 1);
139 $scrubbed == REJECT() and return;
140 $im->remove($scrubbed, 'spam');
143 warn "error removing spam at: $loc from $ibx->{name}: $@\n" if $@;
147 my ($self, $path) = @_;
148 # path must be marked as (S)een
149 $path =~ /:2,[A-R]*S[T-Za-z]*\z/ or return;
150 my $eml = mime_from_path($path) or return;
151 $self->{config}->each_inbox(\&remove_eml_i, [ $self, $eml, $path ]);
154 sub import_eml ($$$) {
155 my ($self, $ibx, $eml) = @_;
156 my $im = _importer_for($self, $ibx);
158 # any header match means it's eligible for the inbox:
159 if (my $watch_hdrs = $ibx->{-watchheaders}) {
161 my $hdr = $eml->header_obj;
162 for my $wh (@$watch_hdrs) {
163 my @v = $hdr->header_raw($wh->[0]);
164 $ok = grep(/$wh->[1]/, @v) and last;
169 if (my $scrub = $ibx->filter($im)) {
170 my $ret = $scrub->scrub($eml) or return;
171 $ret == REJECT() and return;
174 $im->add($eml, $self->{spamcheck});
178 my ($self, $path) = @_;
179 return unless PublicInbox::InboxWritable::is_maildir_path($path);
180 if ($path !~ $self->{mdre}) {
181 warn "unrecognized path: $path\n";
184 my $inboxes = $self->{mdmap}->{$1};
186 warn "unmappable dir: $1\n";
189 if (!ref($inboxes) && $inboxes eq 'watchspam') {
190 return _remove_spam($self, $path);
193 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
194 local $SIG{__WARN__} = sub {
195 $warn_cb->("path: $path\n");
198 foreach my $ibx (@$inboxes) {
199 my $eml = mime_from_path($path) or next;
200 import_eml($self, $ibx, $eml);
207 %{$self->{opendirs}} = ();
208 _done_for_now($self);
209 if (my $imap_pid = $self->{-imap_pid}) {
210 kill('QUIT', $imap_pid);
212 for (qw(idle_pids poll_pids)) {
213 my $pids = $self->{$_} or next;
214 kill('QUIT', $_) for (keys %$pids);
216 if (my $idle_mic = $self->{idle_mic}) {
217 eval { $idle_mic->done };
219 warn "IDLE DONE error: $@\n";
220 eval { $idle_mic->disconnect };
221 warn "IDLE LOGOUT error: $@\n" if $@;
226 sub watch_fs_init ($) {
229 delete $self->{done_timer};
230 _done_for_now($self);
233 _try_path($self, $_[0]->fullname);
234 $self->{done_timer} //= PublicInbox::DS::requeue($done);
236 require PublicInbox::DirIdle;
237 # inotify_create + EPOLL_CTL_ADD
238 PublicInbox::DirIdle->new([keys %{$self->{mdmap}}], $cb);
241 # avoid exposing deprecated "snews" to users.
242 my %SCHEME_MAP = ('snews' => 'nntps');
246 my $scheme = $uri->scheme;
247 $SCHEME_MAP{$scheme} // $scheme;
250 # returns the git config section name, e.g [imap "imaps://user@example.com"]
251 # without the mailbox, so we can share connections between different inboxes
252 sub uri_section ($) {
254 uri_scheme($uri) . '://' . $uri->authority;
257 sub cfg_intvl ($$$) {
258 my ($cfg, $key, $url) = @_;
259 my $v = $cfg->urlmatch($key, $url) // return;
260 $v =~ /\A[0-9]+(?:\.[0-9]+)?\z/s and return $v + 0;
261 if (ref($v) eq 'ARRAY') {
262 $v = join(', ', @$v);
263 warn "W: $key has multiple values: $v\nW: $key ignored\n";
265 warn "W: $key=$v is not a numeric value in seconds\n";
270 my ($cfg, $key, $url) = @_;
271 my $orig = $cfg->urlmatch($key, $url) // return;
272 my $bool = PublicInbox::Config::_git_config_bool($orig);
273 warn "W: $key=$orig for $url is not boolean\n" unless defined($bool);
277 # flesh out common IMAP-specific data structures
278 sub imap_common_init ($) {
280 my $cfg = $self->{config};
281 my $mic_args = {}; # scheme://authority => Mail:IMAPClient arg
282 for my $url (sort keys %{$self->{imap}}) {
283 my $uri = PublicInbox::URIimap->new($url);
284 my $sec = uri_section($uri);
285 for my $k (qw(Starttls Debug Compress)) {
286 my $bool = cfg_bool($cfg, "imap.$k", $url) // next;
287 $mic_args->{$sec}->{$k} = $bool;
289 my $to = cfg_intvl($cfg, 'imap.timeout', $url);
290 $mic_args->{$sec}->{Timeout} = $to if $to;
291 for my $k (qw(pollInterval idleInterval)) {
292 $to = cfg_intvl($cfg, "imap.$k", $url) // next;
293 $self->{imap_opt}->{$sec}->{$k} = $to;
295 my $k = 'imap.fetchBatchSize';
296 my $bs = $cfg->urlmatch($k, $url) // next;
297 if ($bs =~ /\A([0-9]+)\z/) {
298 $self->{imap_opt}->{$sec}->{batch_size} = $bs;
300 warn "$k=$bs is not an integer\n";
306 sub auth_anon_cb { '' }; # for Mail::IMAPClient::Authcallback
308 sub mic_for ($$$) { # mic = Mail::IMAPClient
309 my ($self, $url, $mic_args) = @_;
310 my $uri = PublicInbox::URIimap->new($url);
311 require PublicInbox::GitCredential;
314 protocol => $uri->scheme,
316 username => $uri->user,
317 password => $uri->password,
318 }, 'PublicInbox::GitCredential';
319 my $common = $mic_args->{uri_section($uri)} // {};
320 my $host = $cred->{host};
323 # IMAPClient mishandles `0', so we pass `127.0.0.1'
324 Server => $host eq '0' ? '127.0.0.1' : $host,
325 Ssl => $uri->scheme eq 'imaps',
326 Keepalive => 1, # SO_KEEPALIVE
327 %$common, # may set Starttls, Compress, Debug ....
329 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or
330 die "E: <$url> new: $@\n";
332 # default to using STARTTLS if it's available, but allow
333 # it to be disabled since I usually connect to localhost
334 if (!$mic_arg->{Ssl} && !defined($mic_arg->{Starttls}) &&
335 $mic->has_capability('STARTTLS') &&
336 $mic->can('starttls')) {
337 $mic->starttls or die "E: <$url> STARTTLS: $@\n";
340 # do we even need credentials?
341 if (!defined($cred->{username}) &&
342 $mic->has_capability('AUTH=ANONYMOUS')) {
346 $cred->fill; # may prompt user here
347 $mic->User($mic_arg->{User} = $cred->{username});
348 $mic->Password($mic_arg->{Password} = $cred->{password});
349 } else { # AUTH=ANONYMOUS
350 $mic->Authmechanism($mic_arg->{Authmechanism} = 'ANONYMOUS');
351 $mic->Authcallback($mic_arg->{Authcallback} = \&auth_anon_cb);
353 if ($mic->login && $mic->IsAuthenticated) {
354 # success! keep IMAPClient->new arg in case we get disconnected
355 $self->{mic_arg}->{uri_section($uri)} = $mic_arg;
357 warn "E: <$url> LOGIN: $@\n";
360 $cred->run($mic ? 'approve' : 'reject') if $cred;
364 sub imap_import_msg ($$$$) {
365 my ($self, $url, $uid, $raw) = @_;
366 # our target audience expects LF-only, save storage
367 $$raw =~ s/\r\n/\n/sg;
369 my $inboxes = $self->{imap}->{$url};
371 for my $ibx (@$inboxes) {
372 my $eml = PublicInbox::Eml->new($$raw);
373 my $x = import_eml($self, $ibx, $eml);
375 } elsif ($inboxes eq 'watchspam') {
376 my $eml = PublicInbox::Eml->new($raw);
377 my $arg = [ $self, $eml, "$url UID:$uid" ];
378 $self->{config}->each_inbox(\&remove_eml_i, $arg);
380 die "BUG: destination unknown $inboxes";
384 sub imap_fetch_all ($$$) {
385 my ($self, $mic, $url) = @_;
386 my $uri = PublicInbox::URIimap->new($url);
387 my $sec = uri_section($uri);
388 my $mbx = $uri->mailbox;
389 $mic->Clear(1); # trim results history
390 $mic->examine($mbx) or return "E: EXAMINE $mbx ($sec) failed: $!";
391 my ($r_uidval, $r_uidnext);
392 for ($mic->Results) {
393 /^\* OK \[UIDVALIDITY ([0-9]+)\].*/ and $r_uidval = $1;
394 /^\* OK \[UIDNEXT ([0-9]+)\].*/ and $r_uidnext = $1;
395 last if $r_uidval && $r_uidnext;
397 $r_uidval //= $mic->uidvalidity($mbx) //
398 return "E: $url cannot get UIDVALIDITY";
399 $r_uidnext //= $mic->uidnext($mbx) //
400 return "E: $url cannot get UIDNEXT";
401 my $itrk = PublicInbox::IMAPTracker->new($url);
402 my ($l_uidval, $l_uid) = $itrk->get_last;
403 $l_uidval //= $r_uidval; # first time
405 if ($l_uidval != $r_uidval) {
406 return "E: $url UIDVALIDITY mismatch\n".
407 "E: local=$l_uidval != remote=$r_uidval";
409 my $r_uid = $r_uidnext - 1;
410 if ($l_uid != 1 && $l_uid > $r_uid) {
411 return "E: $url local UID exceeds remote ($l_uid > $r_uid)\n".
412 "E: $url strangely, UIDVALIDLITY matches ($l_uidval)\n";
414 return if $l_uid >= $r_uid; # nothing to do
416 warn "I: $url fetching UID $l_uid:$r_uid\n";
417 $mic->Uid(1); # the default, we hope
418 my $bs = $self->{imap_opt}->{$sec}->{batch_size} // 1;
419 my $req = $mic->imap4rev1 ? 'BODY.PEEK[]' : 'RFC822.PEEK';
421 # TODO: FLAGS may be useful for personal use
425 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
426 local $SIG{__WARN__} = sub {
428 $warn_cb->("$url UID:$batch\n");
433 # I wish "UID FETCH $START:*" could work, but:
434 # 1) servers do not need to return results in any order
435 # 2) Mail::IMAPClient doesn't offer a streaming API
436 $uids = $mic->search("UID $l_uid:*") or
437 return "E: $url UID SEARCH $l_uid:* error: $!";
438 return if scalar(@$uids) == 0;
440 # RFC 3501 doesn't seem to indicate order of UID SEARCH
441 # responses, so sort it ourselves. Order matters so
442 # IMAPTracker can store the newest UID.
443 @$uids = sort { $a <=> $b } @$uids;
445 # Did we actually get new messages?
446 return if $uids->[0] < $l_uid;
448 $l_uid = $uids->[-1] + 1; # for next search
451 while (scalar @$uids) {
452 my @batch = splice(@$uids, 0, $bs);
453 $batch = join(',', @batch);
454 local $0 = "UID:$batch $mbx $sec";
455 my $r = $mic->fetch_hash($batch, $req);
456 unless ($r) { # network error?
457 $err = "E: $url UID FETCH $batch error: $!";
460 for my $uid (@batch) {
461 # messages get deleted, so holes appear
462 my $per_uid = delete $r->{$uid} // next;
463 my $raw = delete($per_uid->{$key}) // next;
464 imap_import_msg($self, $url, $uid, \$raw);
466 last if $self->{quit};
468 last if $self->{quit};
470 _done_for_now($self);
471 $itrk->update_last($r_uidval, $last_uid) if defined $last_uid;
472 } until ($err || $self->{quit});
476 sub imap_idle_once ($$$$) {
477 my ($self, $mic, $intvl, $url) = @_;
478 my $i = $intvl //= (29 * 60);
479 my $end = now() + $intvl;
480 warn "I: $url idling for ${intvl}s\n";
481 local $0 = "IDLE $0";
482 unless ($mic->idle) {
483 return if $self->{quit};
484 return "E: IDLE failed on $url: $!";
486 $self->{idle_mic} = $mic; # for ->quit
488 until ($self->{quit} || grep(/^\* [0-9]+ EXISTS/, @res) || $i <= 0) {
489 @res = $mic->idle_data($i);
492 delete $self->{idle_mic};
493 unless ($self->{quit}) {
494 $mic->IsConnected or return "E: IDLE disconnected on $url";
495 $mic->done or return "E: IDLE DONE failed on $url: $!";
500 # idles on a single URI
501 sub watch_imap_idle_1 ($$$) {
502 my ($self, $url, $intvl) = @_;
503 my $uri = PublicInbox::URIimap->new($url);
504 my $sec = uri_section($uri);
505 my $mic_arg = $self->{mic_arg}->{$sec} or
506 die "BUG: no Mail::IMAPClient->new arg for $sec";
508 local $0 = $uri->mailbox." $sec";
509 until ($self->{quit}) {
510 $mic //= delete($self->{mics}->{$sec}) //
511 PublicInbox::IMAPClient->new(%$mic_arg);
512 my $err = imap_fetch_all($self, $mic, $url);
513 $err //= imap_idle_once($self, $mic, $intvl, $url);
514 if ($err && !$self->{quit}) {
517 sleep 60 unless $self->{quit};
522 sub watch_atfork_child ($) {
524 delete $self->{idle_pids};
525 delete $self->{poll_pids};
526 delete $self->{opendirs};
527 PublicInbox::DS->Reset;
528 PublicInbox::Sigfd::sig_setmask($self->{oldset});
529 %SIG = (%SIG, %{$self->{sig}});
532 sub watch_atfork_parent ($) {
534 _done_for_now($self);
535 $self->{mics} = {}; # going to be forking, so disconnect
538 sub imap_idle_reap { # PublicInbox::DS::dwaitpid callback
539 my ($self, $pid) = @_;
540 my $url_intvl = delete $self->{idle_pids}->{$pid} or
541 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
543 my ($url, $intvl) = @$url_intvl;
544 return if $self->{quit};
545 warn "W: PID=$pid on $url died: \$?=$?\n" if $?;
546 push @{$self->{idle_todo}}, $url_intvl;
547 PubicInbox::DS::requeue($self); # call ->event_step to respawn
550 sub imap_idle_fork ($$) {
551 my ($self, $url_intvl) = @_;
552 my ($url, $intvl) = @$url_intvl;
553 defined(my $pid = fork) or die "fork: $!";
555 watch_atfork_child($self);
556 watch_imap_idle_1($self, $url, $intvl);
559 $self->{idle_pids}->{$pid} = $url_intvl;
560 PublicInbox::DS::dwaitpid($pid, \&imap_idle_reap, $self);
565 return if $self->{quit};
566 my $idle_todo = $self->{idle_todo};
567 if ($idle_todo && @$idle_todo) {
568 watch_atfork_parent($self);
569 while (my $url_intvl = shift(@$idle_todo)) {
570 imap_idle_fork($self, $url_intvl);
573 goto(&fs_scan_step) if $self->{mdre};
576 sub watch_imap_fetch_all ($$) {
577 my ($self, $urls) = @_;
578 for my $url (@$urls) {
579 my $uri = PublicInbox::URIimap->new($url);
580 my $sec = uri_section($uri);
581 my $mic_arg = $self->{mic_arg}->{$sec} or
582 die "BUG: no Mail::IMAPClient->new arg for $sec";
583 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or next;
584 my $err = imap_fetch_all($self, $mic, $url);
585 last if $self->{quit};
586 warn $err, "\n" if $err;
590 sub watch_nntp_fetch_all ($$) {
591 my ($self, $urls) = @_;
592 for my $url (@$urls) {
593 my $uri = uri_new($url);
594 my $sec = uri_section($uri);
595 my $nn_arg = $self->{nn_arg}->{$sec} or
596 die "BUG: no Net::NNTP->new arg for $sec";
597 my $nntp_opt = $self->{nntp_opt}->{$sec};
598 my $nn = nn_new($nn_arg, $nntp_opt, $url);
600 warn "E: $url: \$!=$!\n";
603 last if $self->{quit};
604 if (my $postconn = $nntp_opt->{-postconn}) {
605 for my $m_arg (@$postconn) {
606 my ($method, @args) = @$m_arg;
607 $nn->$method(@args) and next;
608 warn "E: <$url> $method failed\n";
613 last if $self->{quit};
615 my $err = nntp_fetch_all($self, $nn, $url);
616 warn $err, "\n" if $err;
621 sub poll_fetch_fork ($) { # DS::add_timer callback
622 my ($self, $intvl, $urls) = @{$_[0]};
623 return if $self->{quit};
624 watch_atfork_parent($self);
625 defined(my $pid = fork) or die "fork: $!";
627 watch_atfork_child($self);
628 if ($urls->[0] =~ m!\Aimaps?://!i) {
629 watch_imap_fetch_all($self, $urls);
631 watch_nntp_fetch_all($self, $urls);
635 $self->{poll_pids}->{$pid} = [ $intvl, $urls ];
636 PublicInbox::DS::dwaitpid($pid, \&poll_fetch_reap, $self);
639 sub poll_fetch_reap { # PublicInbox::DS::dwaitpid callback
640 my ($self, $pid) = @_;
641 my $intvl_urls = delete $self->{poll_pids}->{$pid} or
642 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
643 return if $self->{quit};
644 my ($intvl, $urls) = @$intvl_urls;
646 warn "W: PID=$pid died: \$?=$?\n", map { "$_\n" } @$urls;
648 warn("I: will check $_ in ${intvl}s\n") for @$urls;
649 PublicInbox::DS::add_timer($intvl, \&poll_fetch_fork,
650 [$self, $intvl, $urls]);
653 sub watch_imap_init ($) {
655 eval { require PublicInbox::IMAPClient } or
656 die "Mail::IMAPClient is required for IMAP:\n$@\n";
657 eval { require PublicInbox::IMAPTracker } or
658 die "DBD::SQLite is required for IMAP\n:$@\n";
660 my $mic_args = imap_common_init($self); # read args from config
662 # make sure we can connect and cache the credentials in memory
663 $self->{mic_arg} = {}; # schema://authority => IMAPClient->new args
664 my $mics = $self->{mics} = {}; # schema://authority => IMAPClient obj
665 for my $url (sort keys %{$self->{imap}}) {
666 my $uri = PublicInbox::URIimap->new($url);
667 $mics->{uri_section($uri)} //= mic_for($self, $url, $mic_args);
670 my $idle = []; # [ [ url1, intvl1 ], [url2, intvl2] ]
671 my $poll = {}; # intvl_seconds => [ url1, url2 ]
672 for my $url (keys %{$self->{imap}}) {
673 my $uri = PublicInbox::URIimap->new($url);
674 my $sec = uri_section($uri);
675 my $mic = $mics->{$sec};
676 my $intvl = $self->{imap_opt}->{$sec}->{pollInterval};
677 if ($mic->has_capability('IDLE') && !$intvl) {
678 $intvl = $self->{imap_opt}->{$sec}->{idleInterval};
679 push @$idle, [ $url, $intvl // () ];
681 push @{$poll->{$intvl || 120}}, $url;
685 $self->{idle_pids} = {};
686 $self->{idle_todo} = $idle;
687 PublicInbox::DS::requeue($self); # ->event_step to fork
689 return unless scalar keys %$poll;
690 $self->{poll_pids} //= {};
692 # poll all URLs for a given interval sequentially
693 while (my ($intvl, $urls) = each %$poll) {
694 PublicInbox::DS::add_timer(0, \&poll_fetch_fork,
695 [$self, $intvl, $urls]);
699 # flesh out common NNTP-specific data structures
700 sub nntp_common_init ($) {
702 my $cfg = $self->{config};
703 my $nn_args = {}; # scheme://authority => Net::NNTP->new arg
704 for my $url (sort keys %{$self->{nntp}}) {
705 my $sec = uri_section(uri_new($url));
707 # Debug and Timeout are passed to Net::NNTP->new
708 my $v = cfg_bool($cfg, 'nntp.Debug', $url);
709 $nn_args->{$sec}->{Debug} = $v if defined $v;
710 my $to = cfg_intvl($cfg, 'nntp.Timeout', $url);
711 $nn_args->{$sec}->{Timeout} = $to if $to;
713 # Net::NNTP post-connect commands
714 for my $k (qw(starttls compress)) {
715 $v = cfg_bool($cfg, "nntp.$k", $url) // next;
716 $self->{nntp_opt}->{$sec}->{$k} = $v;
720 for my $k (qw(pollInterval)) {
721 $to = cfg_intvl($cfg, "nntp.$k", $url) // next;
722 $self->{nntp_opt}->{$sec}->{$k} = $to;
728 # Net::NNTP doesn't support CAPABILITIES, yet
729 sub try_starttls ($) {
731 return if $host =~ /\.onion\z/s;
732 return if $host =~ /\A127\.[0-9]+\.[0-9]+\.[0-9]+\z/s;
733 return if $host eq '::1';
738 my ($nn_arg, $nntp_opt, $url) = @_;
739 my $nn = Net::NNTP->new(%$nn_arg) or die "E: <$url> new: $!\n";
741 # default to using STARTTLS if it's available, but allow
742 # it to be disabled for localhost/VPN users
743 if (!$nn_arg->{SSL} && $nn->can('starttls')) {
744 if (!defined($nntp_opt->{starttls}) &&
745 try_starttls($nn_arg->{Host})) {
746 # soft fail by default
747 $nn->starttls or warn <<"";
748 W: <$url> STARTTLS tried and failed (not requested)
750 } elsif ($nntp_opt->{starttls}) {
751 # hard fail if explicitly configured
752 $nn->starttls or die <<"";
753 E: <$url> STARTTLS requested and failed
756 } elsif ($nntp_opt->{starttls}) {
757 $nn->can('starttls') or
758 die "E: <$url> Net::NNTP too old for STARTTLS\n";
759 $nn->starttls or die <<"";
760 E: <$url> STARTTLS requested and failed
766 sub nn_for ($$$) { # nn = Net::NNTP
767 my ($self, $url, $nn_args) = @_;
768 my $uri = uri_new($url);
769 my $sec = uri_section($uri);
770 my $nntp_opt = $self->{nntp_opt}->{$sec} //= {};
773 if (defined(my $ui = $uri->userinfo)) {
774 require PublicInbox::GitCredential;
777 protocol => uri_scheme($uri),
779 }, 'PublicInbox::GitCredential';
780 ($u, $p) = split(/:/, $ui, 2);
781 ($cred->{username}, $cred->{password}) = ($u, $p);
783 my $common = $nn_args->{$sec} // {};
786 # Net::NNTP mishandles `0', so we pass `127.0.0.1'
787 Host => $uri->host eq '0' ? '127.0.0.1' : $uri->host,
788 SSL => $uri->secure, # snews == nntps
789 %$common, # may Debug ....
791 my $nn = nn_new($nn_arg, $nntp_opt, $url);
794 $cred->fill; # may prompt user here
795 if ($nn->authinfo($u, $p)) {
796 push @{$nntp_opt->{-postconn}}, [ 'authinfo', $u, $p ];
798 warn "E: <$url> AUTHINFO $u XXXX failed\n";
803 if ($nntp_opt->{compress}) {
804 # https://rt.cpan.org/Ticket/Display.html?id=129967
805 if ($nn->can('compress')) {
807 push @{$nntp_opt->{-postconn}}, [ 'compress' ];
809 warn "W: <$url> COMPRESS failed\n";
812 delete $nntp_opt->{compress};
814 W: <$url> COMPRESS not supported by Net::NNTP
815 W: see https://rt.cpan.org/Ticket/Display.html?id=129967 for updates
820 $self->{nn_arg}->{$sec} = $nn_arg;
821 $cred->run($nn ? 'approve' : 'reject') if $cred;
825 sub nntp_fetch_all ($$$) {
826 my ($self, $nn, $url) = @_;
827 my $uri = uri_new($url);
828 my ($group, $num_a, $num_b) = $uri->group;
829 my $sec = uri_section($uri);
830 my ($nr, $beg, $end) = $nn->group($group);
831 unless (defined($nr)) {
832 chomp(my $msg = $nn->message);
833 return "E: GROUP $group <$sec> $msg";
836 # IMAPTracker is also used for tracking NNTP, UID == article number
837 # LIST.ACTIVE can get the equivalent of UIDVALIDITY, but that's
838 # expensive. So we assume newsgroups don't change:
839 my $itrk = PublicInbox::IMAPTracker->new($url);
840 my (undef, $l_art) = $itrk->get_last;
841 $l_art //= $beg; # initial import
843 # allow users to specify articles to refetch
844 # cf. https://tools.ietf.org/id/draft-gilman-news-url-01.txt
845 # nntp://example.com/inbox.foo/$num_a-$num_b
846 $l_art = $num_a if defined($num_a) && $num_a < $l_art;
847 $end = $num_b if defined($num_b) && $num_b < $end;
849 return if $l_art >= $end; # nothing to do
852 warn "I: $url fetching ARTICLE $beg..$end\n";
853 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
855 local $SIG{__WARN__} = sub {
856 $warn_cb->("$url ", $art ? ("ARTICLE $art") : (), "\n", @_);
858 my $inboxes = $self->{nntp}->{$url};
861 last if $self->{quit};
863 my $raw = $nn->article($art);
864 unless (defined($raw)) {
865 my $msg = $nn->message;
866 if ($nn->code == 421) { # pseudo response from Net::Cmd
869 } else { # probably just a deleted message (spam)
874 s/\r\n/\n/ for @$raw;
875 $raw = join('', @$raw);
877 for my $ibx (@$inboxes) {
878 my $eml = PublicInbox::Eml->new($raw);
879 import_eml($self, $ibx, $eml);
881 } elsif ($inboxes eq 'watchspam') {
882 my $eml = PublicInbox::Eml->new(\$raw);
883 my $arg = [ $self, $eml, "$url ARTICLE $art" ];
884 $self->{config}->each_inbox(\&remove_eml_i, $arg);
886 die "BUG: destination unknown $inboxes";
890 $itrk->update_last(0, $last_art) if defined $last_art;
891 _done_for_now($self);
895 sub watch_nntp_init ($) {
897 eval { require Net::NNTP } or
898 die "Net::NNTP is required for NNTP:\n$@\n";
899 eval { require PublicInbox::IMAPTracker } or
900 die "DBD::SQLite is required for NNTP\n:$@\n";
902 my $nn_args = nntp_common_init($self); # read args from config
904 # make sure we can connect and cache the credentials in memory
905 $self->{nn_arg} = {}; # schema://authority => Net::NNTP->new args
906 for my $url (sort keys %{$self->{nntp}}) {
907 nn_for($self, $url, $nn_args);
909 my $poll = {}; # intvl_seconds => [ url1, url2 ]
910 for my $url (keys %{$self->{nntp}}) {
911 my $uri = uri_new($url);
912 my $sec = uri_section($uri);
913 my $intvl = $self->{nntp_opt}->{$sec}->{pollInterval};
914 push @{$poll->{$intvl || 120}}, $url;
916 $self->{poll_pids} //= {};
918 # poll all URLs for a given interval sequentially
919 while (my ($intvl, $urls) = each %$poll) {
920 PublicInbox::DS::add_timer(0, \&poll_fetch_fork,
921 [$self, $intvl, $urls]);
926 my ($self, $sig, $oldset) = @_;
927 $self->{oldset} = $oldset;
929 watch_imap_init($self) if $self->{imap};
930 watch_nntp_init($self) if $self->{nntp};
931 watch_fs_init($self) if $self->{mdre};
932 PublicInbox::DS->SetPostLoopCallback(sub {});
933 PublicInbox::DS->EventLoop until $self->{quit};
934 _done_for_now($self);
938 my ($self, $op) = @_;
939 push @{$self->{ops}}, $op;
940 PublicInbox::DS::requeue($self);
945 return if $self->{quit};
946 my $op = shift @{$self->{ops}};
948 # continue existing scan
950 my $opendirs = $self->{opendirs};
951 my @dirnames = keys %$opendirs;
952 foreach my $dir (@dirnames) {
953 my $dh = delete $opendirs->{$dir};
955 while (my $fn = readdir($dh)) {
956 _try_path($self, "$dir/$fn");
959 $opendirs->{$dir} = $dh if $n < 0;
961 if ($op && $op eq 'full') {
962 foreach my $dir (keys %{$self->{mdmap}}) {
963 next if $opendirs->{$dir}; # already in progress
964 my $ok = opendir(my $dh, $dir);
966 warn "failed to open $dir: $!\n";
970 while (my $fn = readdir($dh)) {
971 _try_path($self, "$dir/$fn");
974 $opendirs->{$dir} = $dh if $n < 0;
977 _done_for_now($self);
978 # do we have more work to do?
979 PublicInbox::DS::requeue($self) if keys %$opendirs;
983 my ($self, $op) = @_;
984 push @{$self->{ops}}, $op;
989 my ($self, $ibx) = @_;
990 my $importers = $self->{importers};
991 my $im = $importers->{"$ibx"} ||= $ibx->importer(0);
992 if (scalar(keys(%$importers)) > 2) {
993 delete $importers->{"$ibx"};
994 _done_for_now($self);
997 $importers->{"$ibx"} = $im;
1005 if ($sc->spamcheck($mime, \$tmp)) {
1006 return PublicInbox::Eml->new(\$tmp);
1008 warn $mime->header('Message-ID')." failed spam check\n";
1014 $_[0] =~ s!\Amaildir:!! or return;
1021 my ($cur, $ws, $ibx) = @_;
1022 if ($ws && !ref($ws) && $ws eq 'watchspam') {
1024 E: $cur is a spam folder and cannot be used for `$ibx->{name}' input
1034 # URI::snews exists, URI::nntps does not, so use URI::snews
1035 $url =~ s!\Anntps://!snews://!i;
1041 require PublicInbox::URIimap;
1042 my $uri = PublicInbox::URIimap->new($url);
1043 $uri ? $uri->canonical->as_string : undef;
1046 my %IS_NNTP = (news => 1, snews => 1, nntp => 1);
1050 my $uri = uri_new($url);
1051 return unless $uri && $IS_NNTP{$uri->scheme} && $uri->group;
1052 $url = $uri->canonical->as_string;
1053 # nntps is IANA registered, snews is deprecated
1054 $url =~ s!\Asnews://!nntps://!;