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 # IMAPClient and Net::Netrc both mishandles `0', so we pass `127.0.0.1'
321 my $host = $cred->{host};
322 $host = '127.0.0.1' if $host eq '0';
326 Ssl => $uri->scheme eq 'imaps',
327 Keepalive => 1, # SO_KEEPALIVE
328 %$common, # may set Starttls, Compress, Debug ....
330 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or
331 die "E: <$url> new: $@\n";
333 # default to using STARTTLS if it's available, but allow
334 # it to be disabled since I usually connect to localhost
335 if (!$mic_arg->{Ssl} && !defined($mic_arg->{Starttls}) &&
336 $mic->has_capability('STARTTLS') &&
337 $mic->can('starttls')) {
338 $mic->starttls or die "E: <$url> STARTTLS: $@\n";
341 # do we even need credentials?
342 if (!defined($cred->{username}) &&
343 $mic->has_capability('AUTH=ANONYMOUS')) {
347 $cred->check_netrc unless defined $cred->{password};
348 $cred->fill; # may prompt user here
349 $mic->User($mic_arg->{User} = $cred->{username});
350 $mic->Password($mic_arg->{Password} = $cred->{password});
351 } else { # AUTH=ANONYMOUS
352 $mic->Authmechanism($mic_arg->{Authmechanism} = 'ANONYMOUS');
353 $mic->Authcallback($mic_arg->{Authcallback} = \&auth_anon_cb);
355 if ($mic->login && $mic->IsAuthenticated) {
356 # success! keep IMAPClient->new arg in case we get disconnected
357 $self->{mic_arg}->{uri_section($uri)} = $mic_arg;
359 warn "E: <$url> LOGIN: $@\n";
362 $cred->run($mic ? 'approve' : 'reject') if $cred;
366 sub imap_import_msg ($$$$) {
367 my ($self, $url, $uid, $raw) = @_;
368 # our target audience expects LF-only, save storage
369 $$raw =~ s/\r\n/\n/sg;
371 my $inboxes = $self->{imap}->{$url};
373 for my $ibx (@$inboxes) {
374 my $eml = PublicInbox::Eml->new($$raw);
375 my $x = import_eml($self, $ibx, $eml);
377 } elsif ($inboxes eq 'watchspam') {
378 my $eml = PublicInbox::Eml->new($raw);
379 my $arg = [ $self, $eml, "$url UID:$uid" ];
380 $self->{config}->each_inbox(\&remove_eml_i, $arg);
382 die "BUG: destination unknown $inboxes";
386 sub imap_fetch_all ($$$) {
387 my ($self, $mic, $url) = @_;
388 my $uri = PublicInbox::URIimap->new($url);
389 my $sec = uri_section($uri);
390 my $mbx = $uri->mailbox;
391 $mic->Clear(1); # trim results history
392 $mic->examine($mbx) or return "E: EXAMINE $mbx ($sec) failed: $!";
393 my ($r_uidval, $r_uidnext);
394 for ($mic->Results) {
395 /^\* OK \[UIDVALIDITY ([0-9]+)\].*/ and $r_uidval = $1;
396 /^\* OK \[UIDNEXT ([0-9]+)\].*/ and $r_uidnext = $1;
397 last if $r_uidval && $r_uidnext;
399 $r_uidval //= $mic->uidvalidity($mbx) //
400 return "E: $url cannot get UIDVALIDITY";
401 $r_uidnext //= $mic->uidnext($mbx) //
402 return "E: $url cannot get UIDNEXT";
403 my $itrk = PublicInbox::IMAPTracker->new($url);
404 my ($l_uidval, $l_uid) = $itrk->get_last;
405 $l_uidval //= $r_uidval; # first time
407 if ($l_uidval != $r_uidval) {
408 return "E: $url UIDVALIDITY mismatch\n".
409 "E: local=$l_uidval != remote=$r_uidval";
411 my $r_uid = $r_uidnext - 1;
412 if ($l_uid != 1 && $l_uid > $r_uid) {
413 return "E: $url local UID exceeds remote ($l_uid > $r_uid)\n".
414 "E: $url strangely, UIDVALIDLITY matches ($l_uidval)\n";
416 return if $l_uid >= $r_uid; # nothing to do
418 warn "I: $url fetching UID $l_uid:$r_uid\n";
419 $mic->Uid(1); # the default, we hope
420 my $bs = $self->{imap_opt}->{$sec}->{batch_size} // 1;
421 my $req = $mic->imap4rev1 ? 'BODY.PEEK[]' : 'RFC822.PEEK';
423 # TODO: FLAGS may be useful for personal use
427 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
428 local $SIG{__WARN__} = sub {
430 $warn_cb->("$url UID:$batch\n");
435 # I wish "UID FETCH $START:*" could work, but:
436 # 1) servers do not need to return results in any order
437 # 2) Mail::IMAPClient doesn't offer a streaming API
438 $uids = $mic->search("UID $l_uid:*") or
439 return "E: $url UID SEARCH $l_uid:* error: $!";
440 return if scalar(@$uids) == 0;
442 # RFC 3501 doesn't seem to indicate order of UID SEARCH
443 # responses, so sort it ourselves. Order matters so
444 # IMAPTracker can store the newest UID.
445 @$uids = sort { $a <=> $b } @$uids;
447 # Did we actually get new messages?
448 return if $uids->[0] < $l_uid;
450 $l_uid = $uids->[-1] + 1; # for next search
453 while (scalar @$uids) {
454 my @batch = splice(@$uids, 0, $bs);
455 $batch = join(',', @batch);
456 local $0 = "UID:$batch $mbx $sec";
457 my $r = $mic->fetch_hash($batch, $req);
458 unless ($r) { # network error?
459 $err = "E: $url UID FETCH $batch error: $!";
462 for my $uid (@batch) {
463 # messages get deleted, so holes appear
464 my $per_uid = delete $r->{$uid} // next;
465 my $raw = delete($per_uid->{$key}) // next;
466 imap_import_msg($self, $url, $uid, \$raw);
468 last if $self->{quit};
470 last if $self->{quit};
472 _done_for_now($self);
473 $itrk->update_last($r_uidval, $last_uid) if defined $last_uid;
474 } until ($err || $self->{quit});
478 sub imap_idle_once ($$$$) {
479 my ($self, $mic, $intvl, $url) = @_;
480 my $i = $intvl //= (29 * 60);
481 my $end = now() + $intvl;
482 warn "I: $url idling for ${intvl}s\n";
483 local $0 = "IDLE $0";
484 unless ($mic->idle) {
485 return if $self->{quit};
486 return "E: IDLE failed on $url: $!";
488 $self->{idle_mic} = $mic; # for ->quit
490 until ($self->{quit} || grep(/^\* [0-9]+ EXISTS/, @res) || $i <= 0) {
491 @res = $mic->idle_data($i);
494 delete $self->{idle_mic};
495 unless ($self->{quit}) {
496 $mic->IsConnected or return "E: IDLE disconnected on $url";
497 $mic->done or return "E: IDLE DONE failed on $url: $!";
502 # idles on a single URI
503 sub watch_imap_idle_1 ($$$) {
504 my ($self, $url, $intvl) = @_;
505 my $uri = PublicInbox::URIimap->new($url);
506 my $sec = uri_section($uri);
507 my $mic_arg = $self->{mic_arg}->{$sec} or
508 die "BUG: no Mail::IMAPClient->new arg for $sec";
510 local $0 = $uri->mailbox." $sec";
511 until ($self->{quit}) {
512 $mic //= delete($self->{mics}->{$sec}) //
513 PublicInbox::IMAPClient->new(%$mic_arg);
514 my $err = imap_fetch_all($self, $mic, $url);
515 $err //= imap_idle_once($self, $mic, $intvl, $url);
516 if ($err && !$self->{quit}) {
519 sleep 60 unless $self->{quit};
524 sub watch_atfork_child ($) {
526 delete $self->{idle_pids};
527 delete $self->{poll_pids};
528 delete $self->{opendirs};
529 PublicInbox::DS->Reset;
530 PublicInbox::Sigfd::sig_setmask($self->{oldset});
531 %SIG = (%SIG, %{$self->{sig}});
534 sub watch_atfork_parent ($) {
536 _done_for_now($self);
537 $self->{mics} = {}; # going to be forking, so disconnect
540 sub imap_idle_reap { # PublicInbox::DS::dwaitpid callback
541 my ($self, $pid) = @_;
542 my $url_intvl = delete $self->{idle_pids}->{$pid} or
543 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
545 my ($url, $intvl) = @$url_intvl;
546 return if $self->{quit};
547 warn "W: PID=$pid on $url died: \$?=$?\n" if $?;
548 push @{$self->{idle_todo}}, $url_intvl;
549 PubicInbox::DS::requeue($self); # call ->event_step to respawn
552 sub imap_idle_fork ($$) {
553 my ($self, $url_intvl) = @_;
554 my ($url, $intvl) = @$url_intvl;
555 defined(my $pid = fork) or die "fork: $!";
557 watch_atfork_child($self);
558 watch_imap_idle_1($self, $url, $intvl);
561 $self->{idle_pids}->{$pid} = $url_intvl;
562 PublicInbox::DS::dwaitpid($pid, \&imap_idle_reap, $self);
567 return if $self->{quit};
568 my $idle_todo = $self->{idle_todo};
569 if ($idle_todo && @$idle_todo) {
570 watch_atfork_parent($self);
571 while (my $url_intvl = shift(@$idle_todo)) {
572 imap_idle_fork($self, $url_intvl);
575 goto(&fs_scan_step) if $self->{mdre};
578 sub watch_imap_fetch_all ($$) {
579 my ($self, $urls) = @_;
580 for my $url (@$urls) {
581 my $uri = PublicInbox::URIimap->new($url);
582 my $sec = uri_section($uri);
583 my $mic_arg = $self->{mic_arg}->{$sec} or
584 die "BUG: no Mail::IMAPClient->new arg for $sec";
585 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or next;
586 my $err = imap_fetch_all($self, $mic, $url);
587 last if $self->{quit};
588 warn $err, "\n" if $err;
592 sub watch_nntp_fetch_all ($$) {
593 my ($self, $urls) = @_;
594 for my $url (@$urls) {
595 my $uri = uri_new($url);
596 my $sec = uri_section($uri);
597 my $nn_arg = $self->{nn_arg}->{$sec} or
598 die "BUG: no Net::NNTP->new arg for $sec";
599 my $nntp_opt = $self->{nntp_opt}->{$sec};
600 my $nn = nn_new($nn_arg, $nntp_opt, $url);
602 warn "E: $url: \$!=$!\n";
605 last if $self->{quit};
606 if (my $postconn = $nntp_opt->{-postconn}) {
607 for my $m_arg (@$postconn) {
608 my ($method, @args) = @$m_arg;
609 $nn->$method(@args) and next;
610 warn "E: <$url> $method failed\n";
615 last if $self->{quit};
617 my $err = nntp_fetch_all($self, $nn, $url);
618 warn $err, "\n" if $err;
623 sub poll_fetch_fork ($) { # DS::add_timer callback
624 my ($self, $intvl, $urls) = @{$_[0]};
625 return if $self->{quit};
626 watch_atfork_parent($self);
627 defined(my $pid = fork) or die "fork: $!";
629 watch_atfork_child($self);
630 if ($urls->[0] =~ m!\Aimaps?://!i) {
631 watch_imap_fetch_all($self, $urls);
633 watch_nntp_fetch_all($self, $urls);
637 $self->{poll_pids}->{$pid} = [ $intvl, $urls ];
638 PublicInbox::DS::dwaitpid($pid, \&poll_fetch_reap, $self);
641 sub poll_fetch_reap { # PublicInbox::DS::dwaitpid callback
642 my ($self, $pid) = @_;
643 my $intvl_urls = delete $self->{poll_pids}->{$pid} or
644 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
645 return if $self->{quit};
646 my ($intvl, $urls) = @$intvl_urls;
648 warn "W: PID=$pid died: \$?=$?\n", map { "$_\n" } @$urls;
650 warn("I: will check $_ in ${intvl}s\n") for @$urls;
651 PublicInbox::DS::add_timer($intvl, \&poll_fetch_fork,
652 [$self, $intvl, $urls]);
655 sub watch_imap_init ($) {
657 eval { require PublicInbox::IMAPClient } or
658 die "Mail::IMAPClient is required for IMAP:\n$@\n";
659 eval { require PublicInbox::IMAPTracker } or
660 die "DBD::SQLite is required for IMAP\n:$@\n";
662 my $mic_args = imap_common_init($self); # read args from config
664 # make sure we can connect and cache the credentials in memory
665 $self->{mic_arg} = {}; # schema://authority => IMAPClient->new args
666 my $mics = $self->{mics} = {}; # schema://authority => IMAPClient obj
667 for my $url (sort keys %{$self->{imap}}) {
668 my $uri = PublicInbox::URIimap->new($url);
669 $mics->{uri_section($uri)} //= mic_for($self, $url, $mic_args);
672 my $idle = []; # [ [ url1, intvl1 ], [url2, intvl2] ]
673 my $poll = {}; # intvl_seconds => [ url1, url2 ]
674 for my $url (keys %{$self->{imap}}) {
675 my $uri = PublicInbox::URIimap->new($url);
676 my $sec = uri_section($uri);
677 my $mic = $mics->{$sec};
678 my $intvl = $self->{imap_opt}->{$sec}->{pollInterval};
679 if ($mic->has_capability('IDLE') && !$intvl) {
680 $intvl = $self->{imap_opt}->{$sec}->{idleInterval};
681 push @$idle, [ $url, $intvl // () ];
683 push @{$poll->{$intvl || 120}}, $url;
687 $self->{idle_pids} = {};
688 $self->{idle_todo} = $idle;
689 PublicInbox::DS::requeue($self); # ->event_step to fork
691 return unless scalar keys %$poll;
692 $self->{poll_pids} //= {};
694 # poll all URLs for a given interval sequentially
695 while (my ($intvl, $urls) = each %$poll) {
696 PublicInbox::DS::add_timer(0, \&poll_fetch_fork,
697 [$self, $intvl, $urls]);
701 # flesh out common NNTP-specific data structures
702 sub nntp_common_init ($) {
704 my $cfg = $self->{config};
705 my $nn_args = {}; # scheme://authority => Net::NNTP->new arg
706 for my $url (sort keys %{$self->{nntp}}) {
707 my $sec = uri_section(uri_new($url));
709 # Debug and Timeout are passed to Net::NNTP->new
710 my $v = cfg_bool($cfg, 'nntp.Debug', $url);
711 $nn_args->{$sec}->{Debug} = $v if defined $v;
712 my $to = cfg_intvl($cfg, 'nntp.Timeout', $url);
713 $nn_args->{$sec}->{Timeout} = $to if $to;
715 # Net::NNTP post-connect commands
716 for my $k (qw(starttls compress)) {
717 $v = cfg_bool($cfg, "nntp.$k", $url) // next;
718 $self->{nntp_opt}->{$sec}->{$k} = $v;
722 for my $k (qw(pollInterval)) {
723 $to = cfg_intvl($cfg, "nntp.$k", $url) // next;
724 $self->{nntp_opt}->{$sec}->{$k} = $to;
730 # Net::NNTP doesn't support CAPABILITIES, yet
731 sub try_starttls ($) {
733 return if $host =~ /\.onion\z/s;
734 return if $host =~ /\A127\.[0-9]+\.[0-9]+\.[0-9]+\z/s;
735 return if $host eq '::1';
740 my ($nn_arg, $nntp_opt, $url) = @_;
741 my $nn = Net::NNTP->new(%$nn_arg) or die "E: <$url> new: $!\n";
743 # default to using STARTTLS if it's available, but allow
744 # it to be disabled for localhost/VPN users
745 if (!$nn_arg->{SSL} && $nn->can('starttls')) {
746 if (!defined($nntp_opt->{starttls}) &&
747 try_starttls($nn_arg->{Host})) {
748 # soft fail by default
749 $nn->starttls or warn <<"";
750 W: <$url> STARTTLS tried and failed (not requested)
752 } elsif ($nntp_opt->{starttls}) {
753 # hard fail if explicitly configured
754 $nn->starttls or die <<"";
755 E: <$url> STARTTLS requested and failed
758 } elsif ($nntp_opt->{starttls}) {
759 $nn->can('starttls') or
760 die "E: <$url> Net::NNTP too old for STARTTLS\n";
761 $nn->starttls or die <<"";
762 E: <$url> STARTTLS requested and failed
768 sub nn_for ($$$) { # nn = Net::NNTP
769 my ($self, $url, $nn_args) = @_;
770 my $uri = uri_new($url);
771 my $sec = uri_section($uri);
772 my $nntp_opt = $self->{nntp_opt}->{$sec} //= {};
773 my $host = $uri->host;
774 # Net::NNTP and Net::Netrc both mishandle `0', so we pass `127.0.0.1'
775 $host = '127.0.0.1' if $host eq '0';
778 if (defined(my $ui = $uri->userinfo)) {
779 require PublicInbox::GitCredential;
782 protocol => uri_scheme($uri),
784 }, 'PublicInbox::GitCredential';
785 ($u, $p) = split(/:/, $ui, 2);
786 ($cred->{username}, $cred->{password}) = ($u, $p);
787 $cred->check_netrc unless defined $p;
789 my $common = $nn_args->{$sec} // {};
793 SSL => $uri->secure, # snews == nntps
794 %$common, # may Debug ....
796 my $nn = nn_new($nn_arg, $nntp_opt, $url);
799 $cred->fill; # may prompt user here
800 if ($nn->authinfo($u, $p)) {
801 push @{$nntp_opt->{-postconn}}, [ 'authinfo', $u, $p ];
803 warn "E: <$url> AUTHINFO $u XXXX failed\n";
808 if ($nntp_opt->{compress}) {
809 # https://rt.cpan.org/Ticket/Display.html?id=129967
810 if ($nn->can('compress')) {
812 push @{$nntp_opt->{-postconn}}, [ 'compress' ];
814 warn "W: <$url> COMPRESS failed\n";
817 delete $nntp_opt->{compress};
819 W: <$url> COMPRESS not supported by Net::NNTP
820 W: see https://rt.cpan.org/Ticket/Display.html?id=129967 for updates
825 $self->{nn_arg}->{$sec} = $nn_arg;
826 $cred->run($nn ? 'approve' : 'reject') if $cred;
830 sub nntp_fetch_all ($$$) {
831 my ($self, $nn, $url) = @_;
832 my $uri = uri_new($url);
833 my ($group, $num_a, $num_b) = $uri->group;
834 my $sec = uri_section($uri);
835 my ($nr, $beg, $end) = $nn->group($group);
836 unless (defined($nr)) {
837 chomp(my $msg = $nn->message);
838 return "E: GROUP $group <$sec> $msg";
841 # IMAPTracker is also used for tracking NNTP, UID == article number
842 # LIST.ACTIVE can get the equivalent of UIDVALIDITY, but that's
843 # expensive. So we assume newsgroups don't change:
844 my $itrk = PublicInbox::IMAPTracker->new($url);
845 my (undef, $l_art) = $itrk->get_last;
846 $l_art //= $beg; # initial import
848 # allow users to specify articles to refetch
849 # cf. https://tools.ietf.org/id/draft-gilman-news-url-01.txt
850 # nntp://example.com/inbox.foo/$num_a-$num_b
851 $l_art = $num_a if defined($num_a) && $num_a < $l_art;
852 $end = $num_b if defined($num_b) && $num_b < $end;
854 return if $l_art >= $end; # nothing to do
857 warn "I: $url fetching ARTICLE $beg..$end\n";
858 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
860 local $SIG{__WARN__} = sub {
861 $warn_cb->("$url ", $art ? ("ARTICLE $art") : (), "\n", @_);
863 my $inboxes = $self->{nntp}->{$url};
866 last if $self->{quit};
868 my $raw = $nn->article($art);
869 unless (defined($raw)) {
870 my $msg = $nn->message;
871 if ($nn->code == 421) { # pseudo response from Net::Cmd
874 } else { # probably just a deleted message (spam)
879 s/\r\n/\n/ for @$raw;
880 $raw = join('', @$raw);
882 for my $ibx (@$inboxes) {
883 my $eml = PublicInbox::Eml->new($raw);
884 import_eml($self, $ibx, $eml);
886 } elsif ($inboxes eq 'watchspam') {
887 my $eml = PublicInbox::Eml->new(\$raw);
888 my $arg = [ $self, $eml, "$url ARTICLE $art" ];
889 $self->{config}->each_inbox(\&remove_eml_i, $arg);
891 die "BUG: destination unknown $inboxes";
895 $itrk->update_last(0, $last_art) if defined $last_art;
896 _done_for_now($self);
900 sub watch_nntp_init ($) {
902 eval { require Net::NNTP } or
903 die "Net::NNTP is required for NNTP:\n$@\n";
904 eval { require PublicInbox::IMAPTracker } or
905 die "DBD::SQLite is required for NNTP\n:$@\n";
907 my $nn_args = nntp_common_init($self); # read args from config
909 # make sure we can connect and cache the credentials in memory
910 $self->{nn_arg} = {}; # schema://authority => Net::NNTP->new args
911 for my $url (sort keys %{$self->{nntp}}) {
912 nn_for($self, $url, $nn_args);
914 my $poll = {}; # intvl_seconds => [ url1, url2 ]
915 for my $url (keys %{$self->{nntp}}) {
916 my $uri = uri_new($url);
917 my $sec = uri_section($uri);
918 my $intvl = $self->{nntp_opt}->{$sec}->{pollInterval};
919 push @{$poll->{$intvl || 120}}, $url;
921 $self->{poll_pids} //= {};
923 # poll all URLs for a given interval sequentially
924 while (my ($intvl, $urls) = each %$poll) {
925 PublicInbox::DS::add_timer(0, \&poll_fetch_fork,
926 [$self, $intvl, $urls]);
931 my ($self, $sig, $oldset) = @_;
932 $self->{oldset} = $oldset;
934 watch_imap_init($self) if $self->{imap};
935 watch_nntp_init($self) if $self->{nntp};
936 watch_fs_init($self) if $self->{mdre};
937 PublicInbox::DS->SetPostLoopCallback(sub {});
938 PublicInbox::DS->EventLoop until $self->{quit};
939 _done_for_now($self);
943 my ($self, $op) = @_;
944 push @{$self->{ops}}, $op;
945 PublicInbox::DS::requeue($self);
950 return if $self->{quit};
951 my $op = shift @{$self->{ops}};
953 # continue existing scan
955 my $opendirs = $self->{opendirs};
956 my @dirnames = keys %$opendirs;
957 foreach my $dir (@dirnames) {
958 my $dh = delete $opendirs->{$dir};
960 while (my $fn = readdir($dh)) {
961 _try_path($self, "$dir/$fn");
964 $opendirs->{$dir} = $dh if $n < 0;
966 if ($op && $op eq 'full') {
967 foreach my $dir (keys %{$self->{mdmap}}) {
968 next if $opendirs->{$dir}; # already in progress
969 my $ok = opendir(my $dh, $dir);
971 warn "failed to open $dir: $!\n";
975 while (my $fn = readdir($dh)) {
976 _try_path($self, "$dir/$fn");
979 $opendirs->{$dir} = $dh if $n < 0;
982 _done_for_now($self);
983 # do we have more work to do?
984 PublicInbox::DS::requeue($self) if keys %$opendirs;
988 my ($self, $op) = @_;
989 push @{$self->{ops}}, $op;
994 my ($self, $ibx) = @_;
995 my $importers = $self->{importers};
996 my $im = $importers->{"$ibx"} ||= $ibx->importer(0);
997 if (scalar(keys(%$importers)) > 2) {
998 delete $importers->{"$ibx"};
999 _done_for_now($self);
1002 $importers->{"$ibx"} = $im;
1010 if ($sc->spamcheck($mime, \$tmp)) {
1011 return PublicInbox::Eml->new(\$tmp);
1013 warn $mime->header('Message-ID')." failed spam check\n";
1019 $_[0] =~ s!\Amaildir:!! or return;
1026 my ($cur, $ws, $ibx) = @_;
1027 if ($ws && !ref($ws) && $ws eq 'watchspam') {
1029 E: $cur is a spam folder and cannot be used for `$ibx->{name}' input
1039 # URI::snews exists, URI::nntps does not, so use URI::snews
1040 $url =~ s!\Anntps://!snews://!i;
1046 require PublicInbox::URIimap;
1047 my $uri = PublicInbox::URIimap->new($url);
1048 $uri ? $uri->canonical->as_string : undef;
1051 my %IS_NNTP = (news => 1, snews => 1, nntp => 1);
1055 my $uri = uri_new($url);
1056 return unless $uri && $IS_NNTP{$uri->scheme} && $uri->group;
1057 $url = $uri->canonical->as_string;
1058 # nntps is IANA registered, snews is deprecated
1059 $url =~ s!\Asnews://!nntps://!;