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);
313 protocol => $uri->scheme,
315 username => $uri->user,
316 password => $uri->password,
318 my $common = $mic_args->{uri_section($uri)} // {};
319 my $host = $cred->{host};
322 # IMAPClient mishandles `0', so we pass `127.0.0.1'
323 Server => $host eq '0' ? '127.0.0.1' : $host,
324 Ssl => $uri->scheme eq 'imaps',
325 Keepalive => 1, # SO_KEEPALIVE
326 %$common, # may set Starttls, Compress, Debug ....
328 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or
329 die "E: <$url> new: $@\n";
331 # default to using STARTTLS if it's available, but allow
332 # it to be disabled since I usually connect to localhost
333 if (!$mic_arg->{Ssl} && !defined($mic_arg->{Starttls}) &&
334 $mic->has_capability('STARTTLS') &&
335 $mic->can('starttls')) {
336 $mic->starttls or die "E: <$url> STARTTLS: $@\n";
339 # do we even need credentials?
340 if (!defined($cred->{username}) &&
341 $mic->has_capability('AUTH=ANONYMOUS')) {
345 Git::credential($cred, 'fill'); # may prompt user here
346 $mic->User($mic_arg->{User} = $cred->{username});
347 $mic->Password($mic_arg->{Password} = $cred->{password});
348 } else { # AUTH=ANONYMOUS
349 $mic->Authmechanism($mic_arg->{Authmechanism} = 'ANONYMOUS');
350 $mic->Authcallback($mic_arg->{Authcallback} = \&auth_anon_cb);
352 if ($mic->login && $mic->IsAuthenticated) {
353 # success! keep IMAPClient->new arg in case we get disconnected
354 $self->{mic_arg}->{uri_section($uri)} = $mic_arg;
356 warn "E: <$url> LOGIN: $@\n";
359 Git::credential($cred, $mic ? 'approve' : 'reject') if $cred;
363 sub imap_import_msg ($$$$) {
364 my ($self, $url, $uid, $raw) = @_;
365 # our target audience expects LF-only, save storage
366 $$raw =~ s/\r\n/\n/sg;
368 my $inboxes = $self->{imap}->{$url};
370 for my $ibx (@$inboxes) {
371 my $eml = PublicInbox::Eml->new($$raw);
372 my $x = import_eml($self, $ibx, $eml);
374 } elsif ($inboxes eq 'watchspam') {
375 my $eml = PublicInbox::Eml->new($raw);
376 my $arg = [ $self, $eml, "$url UID:$uid" ];
377 $self->{config}->each_inbox(\&remove_eml_i, $arg);
379 die "BUG: destination unknown $inboxes";
383 sub imap_fetch_all ($$$) {
384 my ($self, $mic, $url) = @_;
385 my $uri = PublicInbox::URIimap->new($url);
386 my $sec = uri_section($uri);
387 my $mbx = $uri->mailbox;
388 $mic->Clear(1); # trim results history
389 $mic->examine($mbx) or return "E: EXAMINE $mbx ($sec) failed: $!";
390 my ($r_uidval, $r_uidnext);
391 for ($mic->Results) {
392 /^\* OK \[UIDVALIDITY ([0-9]+)\].*/ and $r_uidval = $1;
393 /^\* OK \[UIDNEXT ([0-9]+)\].*/ and $r_uidnext = $1;
394 last if $r_uidval && $r_uidnext;
396 $r_uidval //= $mic->uidvalidity($mbx) //
397 return "E: $url cannot get UIDVALIDITY";
398 $r_uidnext //= $mic->uidnext($mbx) //
399 return "E: $url cannot get UIDNEXT";
400 my $itrk = PublicInbox::IMAPTracker->new($url);
401 my ($l_uidval, $l_uid) = $itrk->get_last;
402 $l_uidval //= $r_uidval; # first time
404 if ($l_uidval != $r_uidval) {
405 return "E: $url UIDVALIDITY mismatch\n".
406 "E: local=$l_uidval != remote=$r_uidval";
408 my $r_uid = $r_uidnext - 1;
409 if ($l_uid != 1 && $l_uid > $r_uid) {
410 return "E: $url local UID exceeds remote ($l_uid > $r_uid)\n".
411 "E: $url strangely, UIDVALIDLITY matches ($l_uidval)\n";
413 return if $l_uid >= $r_uid; # nothing to do
415 warn "I: $url fetching UID $l_uid:$r_uid\n";
416 $mic->Uid(1); # the default, we hope
417 my $bs = $self->{imap_opt}->{$sec}->{batch_size} // 1;
418 my $req = $mic->imap4rev1 ? 'BODY.PEEK[]' : 'RFC822.PEEK';
420 # TODO: FLAGS may be useful for personal use
424 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
425 local $SIG{__WARN__} = sub {
427 $warn_cb->("$url UID:$batch\n");
432 # I wish "UID FETCH $START:*" could work, but:
433 # 1) servers do not need to return results in any order
434 # 2) Mail::IMAPClient doesn't offer a streaming API
435 $uids = $mic->search("UID $l_uid:*") or
436 return "E: $url UID SEARCH $l_uid:* error: $!";
437 return if scalar(@$uids) == 0;
439 # RFC 3501 doesn't seem to indicate order of UID SEARCH
440 # responses, so sort it ourselves. Order matters so
441 # IMAPTracker can store the newest UID.
442 @$uids = sort { $a <=> $b } @$uids;
444 # Did we actually get new messages?
445 return if $uids->[0] < $l_uid;
447 $l_uid = $uids->[-1] + 1; # for next search
450 while (scalar @$uids) {
451 my @batch = splice(@$uids, 0, $bs);
452 $batch = join(',', @batch);
453 local $0 = "UID:$batch $mbx $sec";
454 my $r = $mic->fetch_hash($batch, $req);
455 unless ($r) { # network error?
456 $err = "E: $url UID FETCH $batch error: $!";
459 for my $uid (@batch) {
460 # messages get deleted, so holes appear
461 my $per_uid = delete $r->{$uid} // next;
462 my $raw = delete($per_uid->{$key}) // next;
463 imap_import_msg($self, $url, $uid, \$raw);
465 last if $self->{quit};
467 last if $self->{quit};
469 _done_for_now($self);
470 $itrk->update_last($r_uidval, $last_uid) if defined $last_uid;
471 } until ($err || $self->{quit});
475 sub imap_idle_once ($$$$) {
476 my ($self, $mic, $intvl, $url) = @_;
477 my $i = $intvl //= (29 * 60);
478 my $end = now() + $intvl;
479 warn "I: $url idling for ${intvl}s\n";
480 local $0 = "IDLE $0";
481 unless ($mic->idle) {
482 return if $self->{quit};
483 return "E: IDLE failed on $url: $!";
485 $self->{idle_mic} = $mic; # for ->quit
487 until ($self->{quit} || grep(/^\* [0-9]+ EXISTS/, @res) || $i <= 0) {
488 @res = $mic->idle_data($i);
491 delete $self->{idle_mic};
492 unless ($self->{quit}) {
493 $mic->IsConnected or return "E: IDLE disconnected on $url";
494 $mic->done or return "E: IDLE DONE failed on $url: $!";
499 # idles on a single URI
500 sub watch_imap_idle_1 ($$$) {
501 my ($self, $url, $intvl) = @_;
502 my $uri = PublicInbox::URIimap->new($url);
503 my $sec = uri_section($uri);
504 my $mic_arg = $self->{mic_arg}->{$sec} or
505 die "BUG: no Mail::IMAPClient->new arg for $sec";
507 local $0 = $uri->mailbox." $sec";
508 until ($self->{quit}) {
509 $mic //= delete($self->{mics}->{$sec}) //
510 PublicInbox::IMAPClient->new(%$mic_arg);
511 my $err = imap_fetch_all($self, $mic, $url);
512 $err //= imap_idle_once($self, $mic, $intvl, $url);
513 if ($err && !$self->{quit}) {
516 sleep 60 unless $self->{quit};
521 sub watch_atfork_child ($) {
523 delete $self->{idle_pids};
524 delete $self->{poll_pids};
525 delete $self->{opendirs};
526 PublicInbox::DS->Reset;
527 PublicInbox::Sigfd::sig_setmask($self->{oldset});
528 %SIG = (%SIG, %{$self->{sig}});
531 sub watch_atfork_parent ($) {
533 _done_for_now($self);
534 $self->{mics} = {}; # going to be forking, so disconnect
537 sub imap_idle_reap { # PublicInbox::DS::dwaitpid callback
538 my ($self, $pid) = @_;
539 my $url_intvl = delete $self->{idle_pids}->{$pid} or
540 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
542 my ($url, $intvl) = @$url_intvl;
543 return if $self->{quit};
544 warn "W: PID=$pid on $url died: \$?=$?\n" if $?;
545 push @{$self->{idle_todo}}, $url_intvl;
546 PubicInbox::DS::requeue($self); # call ->event_step to respawn
549 sub imap_idle_fork ($$) {
550 my ($self, $url_intvl) = @_;
551 my ($url, $intvl) = @$url_intvl;
552 defined(my $pid = fork) or die "fork: $!";
554 watch_atfork_child($self);
555 watch_imap_idle_1($self, $url, $intvl);
558 $self->{idle_pids}->{$pid} = $url_intvl;
559 PublicInbox::DS::dwaitpid($pid, \&imap_idle_reap, $self);
564 return if $self->{quit};
565 my $idle_todo = $self->{idle_todo};
566 if ($idle_todo && @$idle_todo) {
567 watch_atfork_parent($self);
568 while (my $url_intvl = shift(@$idle_todo)) {
569 imap_idle_fork($self, $url_intvl);
572 goto(&fs_scan_step) if $self->{mdre};
575 sub watch_imap_fetch_all ($$) {
576 my ($self, $urls) = @_;
577 for my $url (@$urls) {
578 my $uri = PublicInbox::URIimap->new($url);
579 my $sec = uri_section($uri);
580 my $mic_arg = $self->{mic_arg}->{$sec} or
581 die "BUG: no Mail::IMAPClient->new arg for $sec";
582 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or next;
583 my $err = imap_fetch_all($self, $mic, $url);
584 last if $self->{quit};
585 warn $err, "\n" if $err;
589 sub watch_nntp_fetch_all ($$) {
590 my ($self, $urls) = @_;
591 for my $url (@$urls) {
592 my $uri = uri_new($url);
593 my $sec = uri_section($uri);
594 my $nn_arg = $self->{nn_arg}->{$sec} or
595 die "BUG: no Net::NNTP->new arg for $sec";
596 my $nntp_opt = $self->{nntp_opt}->{$sec};
597 my $nn = nn_new($nn_arg, $nntp_opt, $url);
599 warn "E: $url: \$!=$!\n";
602 last if $self->{quit};
603 if (my $postconn = $nntp_opt->{-postconn}) {
604 for my $m_arg (@$postconn) {
605 my ($method, @args) = @$m_arg;
606 $nn->$method(@args) and next;
607 warn "E: <$url> $method failed\n";
612 last if $self->{quit};
614 my $err = nntp_fetch_all($self, $nn, $url);
615 warn $err, "\n" if $err;
620 sub poll_fetch_fork ($) { # DS::add_timer callback
621 my ($self, $intvl, $urls) = @{$_[0]};
622 return if $self->{quit};
623 watch_atfork_parent($self);
624 defined(my $pid = fork) or die "fork: $!";
626 watch_atfork_child($self);
627 if ($urls->[0] =~ m!\Aimaps?://!i) {
628 watch_imap_fetch_all($self, $urls);
630 watch_nntp_fetch_all($self, $urls);
634 $self->{poll_pids}->{$pid} = [ $intvl, $urls ];
635 PublicInbox::DS::dwaitpid($pid, \&poll_fetch_reap, $self);
638 sub poll_fetch_reap { # PublicInbox::DS::dwaitpid callback
639 my ($self, $pid) = @_;
640 my $intvl_urls = delete $self->{poll_pids}->{$pid} or
641 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
642 return if $self->{quit};
643 my ($intvl, $urls) = @$intvl_urls;
645 warn "W: PID=$pid died: \$?=$?\n", map { "$_\n" } @$urls;
647 warn("I: will check $_ in ${intvl}s\n") for @$urls;
648 PublicInbox::DS::add_timer($intvl, \&poll_fetch_fork,
649 [$self, $intvl, $urls]);
652 sub watch_imap_init ($) {
654 eval { require PublicInbox::IMAPClient } or
655 die "Mail::IMAPClient is required for IMAP:\n$@\n";
656 eval { require Git } or
657 die "Git (Perl module) is required for IMAP:\n$@\n";
658 eval { require PublicInbox::IMAPTracker } or
659 die "DBD::SQLite is required for IMAP\n:$@\n";
661 my $mic_args = imap_common_init($self); # read args from config
663 # make sure we can connect and cache the credentials in memory
664 $self->{mic_arg} = {}; # schema://authority => IMAPClient->new args
665 my $mics = $self->{mics} = {}; # schema://authority => IMAPClient obj
666 for my $url (sort keys %{$self->{imap}}) {
667 my $uri = PublicInbox::URIimap->new($url);
668 $mics->{uri_section($uri)} //= mic_for($self, $url, $mic_args);
671 my $idle = []; # [ [ url1, intvl1 ], [url2, intvl2] ]
672 my $poll = {}; # intvl_seconds => [ url1, url2 ]
673 for my $url (keys %{$self->{imap}}) {
674 my $uri = PublicInbox::URIimap->new($url);
675 my $sec = uri_section($uri);
676 my $mic = $mics->{$sec};
677 my $intvl = $self->{imap_opt}->{$sec}->{pollInterval};
678 if ($mic->has_capability('IDLE') && !$intvl) {
679 $intvl = $self->{imap_opt}->{$sec}->{idleInterval};
680 push @$idle, [ $url, $intvl // () ];
682 push @{$poll->{$intvl || 120}}, $url;
686 $self->{idle_pids} = {};
687 $self->{idle_todo} = $idle;
688 PublicInbox::DS::requeue($self); # ->event_step to fork
690 return unless scalar keys %$poll;
691 $self->{poll_pids} //= {};
693 # poll all URLs for a given interval sequentially
694 while (my ($intvl, $urls) = each %$poll) {
695 PublicInbox::DS::add_timer(0, \&poll_fetch_fork,
696 [$self, $intvl, $urls]);
700 # flesh out common NNTP-specific data structures
701 sub nntp_common_init ($) {
703 my $cfg = $self->{config};
704 my $nn_args = {}; # scheme://authority => Net::NNTP->new arg
705 for my $url (sort keys %{$self->{nntp}}) {
706 my $sec = uri_section(uri_new($url));
708 # Debug and Timeout are passed to Net::NNTP->new
709 my $v = cfg_bool($cfg, 'nntp.Debug', $url);
710 $nn_args->{$sec}->{Debug} = $v if defined $v;
711 my $to = cfg_intvl($cfg, 'nntp.Timeout', $url);
712 $nn_args->{$sec}->{Timeout} = $to if $to;
714 # Net::NNTP post-connect commands
715 for my $k (qw(starttls compress)) {
716 $v = cfg_bool($cfg, "nntp.$k", $url) // next;
717 $self->{nntp_opt}->{$sec}->{$k} = $v;
721 for my $k (qw(pollInterval)) {
722 $to = cfg_intvl($cfg, "nntp.$k", $url) // next;
723 $self->{nntp_opt}->{$sec}->{$k} = $to;
729 # Net::NNTP doesn't support CAPABILITIES, yet
730 sub try_starttls ($) {
732 return if $host =~ /\.onion\z/s;
733 return if $host =~ /\A127\.[0-9]+\.[0-9]+\.[0-9]+\z/s;
734 return if $host eq '::1';
739 my ($nn_arg, $nntp_opt, $url) = @_;
740 my $nn = Net::NNTP->new(%$nn_arg) or die "E: <$url> new: $!\n";
742 # default to using STARTTLS if it's available, but allow
743 # it to be disabled for localhost/VPN users
744 if (!$nn_arg->{SSL} && $nn->can('starttls')) {
745 if (!defined($nntp_opt->{starttls}) &&
746 try_starttls($nn_arg->{Host})) {
747 # soft fail by default
748 $nn->starttls or warn <<"";
749 W: <$url> STARTTLS tried and failed (not requested)
751 } elsif ($nntp_opt->{starttls}) {
752 # hard fail if explicitly configured
753 $nn->starttls or die <<"";
754 E: <$url> STARTTLS requested and failed
757 } elsif ($nntp_opt->{starttls}) {
758 $nn->can('starttls') or
759 die "E: <$url> Net::NNTP too old for STARTTLS\n";
760 $nn->starttls or die <<"";
761 E: <$url> STARTTLS requested and failed
767 sub nn_for ($$$) { # nn = Net::NNTP
768 my ($self, $url, $nn_args) = @_;
769 my $uri = uri_new($url);
770 my $sec = uri_section($uri);
771 my $nntp_opt = $self->{nntp_opt}->{$sec} //= {};
774 if (defined(my $ui = $uri->userinfo)) {
777 protocol => uri_scheme($uri),
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 Git::credential($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 Git::credential($cred, $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 Git } or
900 die "Git (Perl module) is required for NNTP:\n$@\n";
901 eval { require PublicInbox::IMAPTracker } or
902 die "DBD::SQLite is required for NNTP\n:$@\n";
904 my $nn_args = nntp_common_init($self); # read args from config
906 # make sure we can connect and cache the credentials in memory
907 $self->{nn_arg} = {}; # schema://authority => Net::NNTP->new args
908 for my $url (sort keys %{$self->{nntp}}) {
909 nn_for($self, $url, $nn_args);
911 my $poll = {}; # intvl_seconds => [ url1, url2 ]
912 for my $url (keys %{$self->{nntp}}) {
913 my $uri = uri_new($url);
914 my $sec = uri_section($uri);
915 my $intvl = $self->{nntp_opt}->{$sec}->{pollInterval};
916 push @{$poll->{$intvl || 120}}, $url;
918 $self->{poll_pids} //= {};
920 # poll all URLs for a given interval sequentially
921 while (my ($intvl, $urls) = each %$poll) {
922 PublicInbox::DS::add_timer(0, \&poll_fetch_fork,
923 [$self, $intvl, $urls]);
928 my ($self, $sig, $oldset) = @_;
929 $self->{oldset} = $oldset;
931 watch_imap_init($self) if $self->{imap};
932 watch_nntp_init($self) if $self->{nntp};
933 watch_fs_init($self) if $self->{mdre};
934 PublicInbox::DS->SetPostLoopCallback(sub {});
935 PublicInbox::DS->EventLoop until $self->{quit};
936 _done_for_now($self);
940 my ($self, $op) = @_;
941 push @{$self->{ops}}, $op;
942 PublicInbox::DS::requeue($self);
947 return if $self->{quit};
948 my $op = shift @{$self->{ops}};
950 # continue existing scan
952 my $opendirs = $self->{opendirs};
953 my @dirnames = keys %$opendirs;
954 foreach my $dir (@dirnames) {
955 my $dh = delete $opendirs->{$dir};
957 while (my $fn = readdir($dh)) {
958 _try_path($self, "$dir/$fn");
961 $opendirs->{$dir} = $dh if $n < 0;
963 if ($op && $op eq 'full') {
964 foreach my $dir (keys %{$self->{mdmap}}) {
965 next if $opendirs->{$dir}; # already in progress
966 my $ok = opendir(my $dh, $dir);
968 warn "failed to open $dir: $!\n";
972 while (my $fn = readdir($dh)) {
973 _try_path($self, "$dir/$fn");
976 $opendirs->{$dir} = $dh if $n < 0;
979 _done_for_now($self);
980 # do we have more work to do?
981 PublicInbox::DS::requeue($self) if keys %$opendirs;
985 my ($self, $op) = @_;
986 push @{$self->{ops}}, $op;
991 my ($self, $ibx) = @_;
992 my $importers = $self->{importers};
993 my $im = $importers->{"$ibx"} ||= $ibx->importer(0);
994 if (scalar(keys(%$importers)) > 2) {
995 delete $importers->{"$ibx"};
996 _done_for_now($self);
999 $importers->{"$ibx"} = $im;
1007 if ($sc->spamcheck($mime, \$tmp)) {
1008 return PublicInbox::Eml->new(\$tmp);
1010 warn $mime->header('Message-ID')." failed spam check\n";
1016 $_[0] =~ s!\Amaildir:!! or return;
1023 my ($cur, $ws, $ibx) = @_;
1024 if ($ws && !ref($ws) && $ws eq 'watchspam') {
1026 E: $cur is a spam folder and cannot be used for `$ibx->{name}' input
1036 # URI::snews exists, URI::nntps does not, so use URI::snews
1037 $url =~ s!\Anntps://!snews://!i;
1043 require PublicInbox::URIimap;
1044 my $uri = PublicInbox::URIimap->new($url);
1045 $uri ? $uri->canonical->as_string : undef;
1048 my %IS_NNTP = (news => 1, snews => 1, nntp => 1);
1052 my $uri = uri_new($url);
1053 return unless $uri && $IS_NNTP{$uri->scheme} && $uri->group;
1054 $url = $uri->canonical->as_string;
1055 # nntps is IANA registered, snews is deprecated
1056 $url =~ s!\Asnews://!nntps://!;