1 # Copyright (C) 2016-2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # ref: https://cr.yp.to/proto/maildir.html
5 # http://wiki2.dovecot.org/MailboxFormat/Maildir
6 package PublicInbox::WatchMaildir;
10 use PublicInbox::InboxWritable qw(eml_from_path);
11 use PublicInbox::Filter::Base qw(REJECT);
12 use PublicInbox::Spamcheck;
13 use PublicInbox::Sigfd;
14 use PublicInbox::DS qw(now);
15 use PublicInbox::MID qw(mids);
16 use PublicInbox::ContentHash qw(content_hash);
19 sub compile_watchheaders ($) {
22 if (my $whs = $ibx->{watchheader}) {
24 my ($k, $v) = split(/:/, $_, 2);
25 # XXX should this be case-insensitive?
26 # Or, mutt-style, case-sensitive iff
27 # a capital letter exists?
28 push @$watch_hdrs, [ $k, qr/\Q$v\E/ ];
31 if (my $list_ids = $ibx->{listid}) {
33 # RFC2919 section 6 stipulates
34 # "case insensitive equality"
35 my $re = qr/<[ \t]*\Q$_\E[ \t]*>/i;
36 push @$watch_hdrs, ['List-Id', $re ];
39 $ibx->{-watchheaders} = $watch_hdrs if scalar @$watch_hdrs;
43 my ($class, $config) = @_;
45 my (%imap, %nntp); # url => [inbox objects] or 'watchspam'
47 # "publicinboxwatch" is the documented namespace
48 # "publicinboxlearn" is legacy but may be supported
50 foreach my $pfx (qw(publicinboxwatch publicinboxlearn)) {
51 my $k = "$pfx.watchspam";
52 defined(my $dirs = $config->{$k}) or next;
53 $dirs = PublicInbox::Config::_array($dirs);
54 for my $dir (@$dirs) {
56 if (is_maildir($dir)) {
57 # skip "new", no MUA has seen it, yet.
58 $mdmap{"$dir/cur"} = 'watchspam';
59 } elsif ($url = imap_url($dir)) {
60 $imap{$url} = 'watchspam';
61 } elsif ($url = nntp_url($dir)) {
62 $nntp{$url} = 'watchspam';
64 warn "unsupported $k=$dir\n";
69 my $k = 'publicinboxwatch.spamcheck';
71 my $spamcheck = PublicInbox::Spamcheck::get($config, $k, $default);
72 $spamcheck = _spamcheck_cb($spamcheck) if $spamcheck;
74 $config->each_inbox(sub {
75 # need to make all inboxes writable for spam removal:
76 my $ibx = $_[0] = PublicInbox::InboxWritable->new($_[0]);
78 my $watches = $ibx->{watch} or return;
79 $watches = PublicInbox::Config::_array($watches);
80 for my $watch (@$watches) {
82 if (is_maildir($watch)) {
83 compile_watchheaders($ibx);
84 my ($new, $cur) = ("$watch/new", "$watch/cur");
85 my $cur_dst = $mdmap{$cur} //= [];
86 return if is_watchspam($cur, $cur_dst, $ibx);
87 push @{$mdmap{$new} //= []}, $ibx;
89 } elsif ($url = imap_url($watch)) {
90 return if is_watchspam($url, $imap{$url}, $ibx);
91 compile_watchheaders($ibx);
92 push @{$imap{$url} ||= []}, $ibx;
93 } elsif ($url = nntp_url($watch)) {
94 return if is_watchspam($url, $nntp{$url}, $ibx);
95 compile_watchheaders($ibx);
96 push @{$nntp{$url} ||= []}, $ibx;
98 warn "watch unsupported: $k=$watch\n";
104 if (scalar keys %mdmap) {
105 $mdre = join('|', map { quotemeta($_) } keys %mdmap);
106 $mdre = qr!\A($mdre)/!;
108 return unless $mdre || scalar(keys %imap) || scalar(keys %nntp);
111 spamcheck => $spamcheck,
115 imap => scalar keys %imap ? \%imap : undef,
116 nntp => scalar keys %nntp? \%nntp : undef,
118 opendirs => {}, # dirname => dirhandle (in progress scans)
119 ops => [], # 'quit', 'full'
125 local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
126 for my $im (values %{$self->{importers}}) {
127 next if !$im; # $im may be undef during cleanup
129 warn "$im->{ibx}->{name} ->done: $@\n" if $@;
133 sub remove_eml_i { # each_inbox callback
134 my ($ibx, $arg) = @_;
135 my ($self, $eml, $loc) = @$arg;
137 my $im = _importer_for($self, $ibx);
138 $im->remove($eml, 'spam');
139 if (my $scrub = $ibx->filter($im)) {
140 my $scrubbed = $scrub->scrub($eml, 1);
141 if ($scrubbed && $scrubbed != REJECT) {
142 $im->remove($scrubbed, 'spam');
147 warn "error removing spam at: $loc from $ibx->{name}: $@\n";
148 _done_for_now($self);
153 my ($self, $path) = @_;
154 # path must be marked as (S)een
155 $path =~ /:2,[A-R]*S[T-Za-z]*\z/ or return;
156 my $eml = eml_from_path($path) or return;
157 $self->{config}->each_inbox(\&remove_eml_i, [ $self, $eml, $path ]);
160 sub import_eml ($$$) {
161 my ($self, $ibx, $eml) = @_;
163 # any header match means it's eligible for the inbox:
164 if (my $watch_hdrs = $ibx->{-watchheaders}) {
166 for my $wh (@$watch_hdrs) {
167 my @v = $eml->header_raw($wh->[0]);
168 $ok = grep(/$wh->[1]/, @v) and last;
173 my $im = _importer_for($self, $ibx);
174 if (my $scrub = $ibx->filter($im)) {
175 my $scrubbed = $scrub->scrub($eml) or return;
176 $scrubbed == REJECT and return;
179 $im->add($eml, $self->{spamcheck});
182 warn "$ibx->{name} add failed: $@\n";
183 _done_for_now($self);
188 my ($self, $path) = @_;
189 return unless PublicInbox::InboxWritable::is_maildir_path($path);
190 if ($path !~ $self->{mdre}) {
191 warn "unrecognized path: $path\n";
194 my $inboxes = $self->{mdmap}->{$1};
196 warn "unmappable dir: $1\n";
199 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
200 local $SIG{__WARN__} = sub {
201 $warn_cb->("path: $path\n");
204 if (!ref($inboxes) && $inboxes eq 'watchspam') {
205 return _remove_spam($self, $path);
207 foreach my $ibx (@$inboxes) {
208 my $eml = eml_from_path($path) or next;
209 import_eml($self, $ibx, $eml);
215 return unless $self->{quit};
217 # don't have reliable wakeups, keep signalling
219 for (qw(idle_pids poll_pids)) {
220 my $pids = $self->{$_} or next;
222 $done = undef if kill('QUIT', $_);
231 %{$self->{opendirs}} = ();
232 _done_for_now($self);
234 if (my $idle_mic = $self->{idle_mic}) {
235 eval { $idle_mic->done };
237 warn "IDLE DONE error: $@\n";
238 eval { $idle_mic->disconnect };
239 warn "IDLE LOGOUT error: $@\n" if $@;
244 sub watch_fs_init ($) {
247 delete $self->{done_timer};
248 _done_for_now($self);
251 _try_path($self, $_[0]->fullname);
252 $self->{done_timer} //= PublicInbox::DS::requeue($done);
254 require PublicInbox::DirIdle;
255 # inotify_create + EPOLL_CTL_ADD
256 PublicInbox::DirIdle->new([keys %{$self->{mdmap}}], $cb);
259 # avoid exposing deprecated "snews" to users.
260 my %SCHEME_MAP = ('snews' => 'nntps');
264 my $scheme = $uri->scheme;
265 $SCHEME_MAP{$scheme} // $scheme;
268 # returns the git config section name, e.g [imap "imaps://user@example.com"]
269 # without the mailbox, so we can share connections between different inboxes
270 sub uri_section ($) {
272 uri_scheme($uri) . '://' . $uri->authority;
275 sub cfg_intvl ($$$) {
276 my ($cfg, $key, $url) = @_;
277 my $v = $cfg->urlmatch($key, $url) // return;
278 $v =~ /\A[0-9]+(?:\.[0-9]+)?\z/s and return $v + 0;
279 if (ref($v) eq 'ARRAY') {
280 $v = join(', ', @$v);
281 warn "W: $key has multiple values: $v\nW: $key ignored\n";
283 warn "W: $key=$v is not a numeric value in seconds\n";
288 my ($cfg, $key, $url) = @_;
289 my $orig = $cfg->urlmatch($key, $url) // return;
290 my $bool = PublicInbox::Config::_git_config_bool($orig);
291 warn "W: $key=$orig for $url is not boolean\n" unless defined($bool);
295 # flesh out common IMAP-specific data structures
296 sub imap_common_init ($) {
298 my $cfg = $self->{config};
299 my $mic_args = {}; # scheme://authority => Mail:IMAPClient arg
300 for my $url (sort keys %{$self->{imap}}) {
301 my $uri = PublicInbox::URIimap->new($url);
302 my $sec = uri_section($uri);
303 for my $k (qw(Starttls Debug Compress)) {
304 my $bool = cfg_bool($cfg, "imap.$k", $url) // next;
305 $mic_args->{$sec}->{$k} = $bool;
307 my $to = cfg_intvl($cfg, 'imap.timeout', $url);
308 $mic_args->{$sec}->{Timeout} = $to if $to;
309 for my $k (qw(pollInterval idleInterval)) {
310 $to = cfg_intvl($cfg, "imap.$k", $url) // next;
311 $self->{imap_opt}->{$sec}->{$k} = $to;
313 my $k = 'imap.fetchBatchSize';
314 my $bs = $cfg->urlmatch($k, $url) // next;
315 if ($bs =~ /\A([0-9]+)\z/) {
316 $self->{imap_opt}->{$sec}->{batch_size} = $bs;
318 warn "$k=$bs is not an integer\n";
324 sub auth_anon_cb { '' }; # for Mail::IMAPClient::Authcallback
326 sub mic_for ($$$) { # mic = Mail::IMAPClient
327 my ($self, $url, $mic_args) = @_;
328 my $uri = PublicInbox::URIimap->new($url);
329 require PublicInbox::GitCredential;
332 protocol => $uri->scheme,
334 username => $uri->user,
335 password => $uri->password,
336 }, 'PublicInbox::GitCredential';
337 my $common = $mic_args->{uri_section($uri)} // {};
338 # IMAPClient and Net::Netrc both mishandles `0', so we pass `127.0.0.1'
339 my $host = $cred->{host};
340 $host = '127.0.0.1' if $host eq '0';
344 Ssl => $uri->scheme eq 'imaps',
345 Keepalive => 1, # SO_KEEPALIVE
346 %$common, # may set Starttls, Compress, Debug ....
348 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or
349 die "E: <$url> new: $@\n";
351 # default to using STARTTLS if it's available, but allow
352 # it to be disabled since I usually connect to localhost
353 if (!$mic_arg->{Ssl} && !defined($mic_arg->{Starttls}) &&
354 $mic->has_capability('STARTTLS') &&
355 $mic->can('starttls')) {
356 $mic->starttls or die "E: <$url> STARTTLS: $@\n";
359 # do we even need credentials?
360 if (!defined($cred->{username}) &&
361 $mic->has_capability('AUTH=ANONYMOUS')) {
365 $cred->check_netrc unless defined $cred->{password};
366 $cred->fill; # may prompt user here
367 $mic->User($mic_arg->{User} = $cred->{username});
368 $mic->Password($mic_arg->{Password} = $cred->{password});
369 } else { # AUTH=ANONYMOUS
370 $mic->Authmechanism($mic_arg->{Authmechanism} = 'ANONYMOUS');
371 $mic->Authcallback($mic_arg->{Authcallback} = \&auth_anon_cb);
373 if ($mic->login && $mic->IsAuthenticated) {
374 # success! keep IMAPClient->new arg in case we get disconnected
375 $self->{mic_arg}->{uri_section($uri)} = $mic_arg;
377 warn "E: <$url> LOGIN: $@\n";
380 $cred->run($mic ? 'approve' : 'reject') if $cred;
384 sub imap_import_msg ($$$$) {
385 my ($self, $url, $uid, $raw) = @_;
386 # our target audience expects LF-only, save storage
387 $$raw =~ s/\r\n/\n/sg;
389 my $inboxes = $self->{imap}->{$url};
391 for my $ibx (@$inboxes) {
392 my $eml = PublicInbox::Eml->new($$raw);
393 my $x = import_eml($self, $ibx, $eml);
395 } elsif ($inboxes eq 'watchspam') {
396 my $eml = PublicInbox::Eml->new($raw);
397 my $arg = [ $self, $eml, "$url UID:$uid" ];
398 $self->{config}->each_inbox(\&remove_eml_i, $arg);
400 die "BUG: destination unknown $inboxes";
404 sub imap_fetch_all ($$$) {
405 my ($self, $mic, $url) = @_;
406 my $uri = PublicInbox::URIimap->new($url);
407 my $sec = uri_section($uri);
408 my $mbx = $uri->mailbox;
409 $mic->Clear(1); # trim results history
410 $mic->examine($mbx) or return "E: EXAMINE $mbx ($sec) failed: $!";
411 my ($r_uidval, $r_uidnext);
412 for ($mic->Results) {
413 /^\* OK \[UIDVALIDITY ([0-9]+)\].*/ and $r_uidval = $1;
414 /^\* OK \[UIDNEXT ([0-9]+)\].*/ and $r_uidnext = $1;
415 last if $r_uidval && $r_uidnext;
417 $r_uidval //= $mic->uidvalidity($mbx) //
418 return "E: $url cannot get UIDVALIDITY";
419 $r_uidnext //= $mic->uidnext($mbx) //
420 return "E: $url cannot get UIDNEXT";
421 my $itrk = PublicInbox::IMAPTracker->new($url);
422 my ($l_uidval, $l_uid) = $itrk->get_last;
423 $l_uidval //= $r_uidval; # first time
425 if ($l_uidval != $r_uidval) {
426 return "E: $url UIDVALIDITY mismatch\n".
427 "E: local=$l_uidval != remote=$r_uidval";
429 my $r_uid = $r_uidnext - 1;
430 if ($l_uid != 1 && $l_uid > $r_uid) {
431 return "E: $url local UID exceeds remote ($l_uid > $r_uid)\n".
432 "E: $url strangely, UIDVALIDLITY matches ($l_uidval)\n";
434 return if $l_uid >= $r_uid; # nothing to do
436 warn "I: $url fetching UID $l_uid:$r_uid\n";
437 $mic->Uid(1); # the default, we hope
438 my $bs = $self->{imap_opt}->{$sec}->{batch_size} // 1;
439 my $req = $mic->imap4rev1 ? 'BODY.PEEK[]' : 'RFC822.PEEK';
441 # TODO: FLAGS may be useful for personal use
445 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
446 local $SIG{__WARN__} = sub {
448 $warn_cb->("$url UID:$batch\n");
453 # I wish "UID FETCH $START:*" could work, but:
454 # 1) servers do not need to return results in any order
455 # 2) Mail::IMAPClient doesn't offer a streaming API
456 $uids = $mic->search("UID $l_uid:*") or
457 return "E: $url UID SEARCH $l_uid:* error: $!";
458 return if scalar(@$uids) == 0;
460 # RFC 3501 doesn't seem to indicate order of UID SEARCH
461 # responses, so sort it ourselves. Order matters so
462 # IMAPTracker can store the newest UID.
463 @$uids = sort { $a <=> $b } @$uids;
465 # Did we actually get new messages?
466 return if $uids->[0] < $l_uid;
468 $l_uid = $uids->[-1] + 1; # for next search
471 while (scalar @$uids) {
472 my @batch = splice(@$uids, 0, $bs);
473 $batch = join(',', @batch);
474 local $0 = "UID:$batch $mbx $sec";
475 my $r = $mic->fetch_hash($batch, $req);
476 unless ($r) { # network error?
477 $err = "E: $url UID FETCH $batch error: $!";
480 for my $uid (@batch) {
481 # messages get deleted, so holes appear
482 my $per_uid = delete $r->{$uid} // next;
483 my $raw = delete($per_uid->{$key}) // next;
484 imap_import_msg($self, $url, $uid, \$raw);
486 last if $self->{quit};
488 last if $self->{quit};
490 _done_for_now($self);
491 $itrk->update_last($r_uidval, $last_uid) if defined $last_uid;
492 } until ($err || $self->{quit});
496 sub imap_idle_once ($$$$) {
497 my ($self, $mic, $intvl, $url) = @_;
498 my $i = $intvl //= (29 * 60);
499 my $end = now() + $intvl;
500 warn "I: $url idling for ${intvl}s\n";
501 local $0 = "IDLE $0";
502 unless ($mic->idle) {
503 return if $self->{quit};
504 return "E: IDLE failed on $url: $!";
506 $self->{idle_mic} = $mic; # for ->quit
508 until ($self->{quit} || !$mic->IsConnected ||
509 grep(/^\* [0-9]+ EXISTS/, @res) || $i <= 0) {
510 @res = $mic->idle_data($i);
513 delete $self->{idle_mic};
514 unless ($self->{quit}) {
515 $mic->IsConnected or return "E: IDLE disconnected on $url";
516 $mic->done or return "E: IDLE DONE failed on $url: $!";
521 # idles on a single URI
522 sub watch_imap_idle_1 ($$$) {
523 my ($self, $url, $intvl) = @_;
524 my $uri = PublicInbox::URIimap->new($url);
525 my $sec = uri_section($uri);
526 my $mic_arg = $self->{mic_arg}->{$sec} or
527 die "BUG: no Mail::IMAPClient->new arg for $sec";
529 local $0 = $uri->mailbox." $sec";
530 until ($self->{quit}) {
531 $mic //= PublicInbox::IMAPClient->new(%$mic_arg);
533 if ($mic && $mic->IsConnected) {
534 $err = imap_fetch_all($self, $mic, $url);
535 $err //= imap_idle_once($self, $mic, $intvl, $url);
537 $err = "not connected: $!";
539 if ($err && !$self->{quit}) {
542 sleep 60 unless $self->{quit};
547 sub watch_atfork_child ($) {
549 delete $self->{idle_pids};
550 delete $self->{poll_pids};
551 delete $self->{opendirs};
552 PublicInbox::DS->Reset;
553 %SIG = (%SIG, %{$self->{sig}}, CHLD => 'DEFAULT');
554 PublicInbox::Sigfd::sig_setmask($self->{oldset});
557 sub watch_atfork_parent ($) {
559 _done_for_now($self);
562 sub imap_idle_requeue ($) { # DS::add_timer callback
563 my ($self, $url_intvl) = @{$_[0]};
564 return if $self->{quit};
565 push @{$self->{idle_todo}}, $url_intvl;
569 sub imap_idle_reap { # PublicInbox::DS::dwaitpid callback
570 my ($self, $pid) = @_;
571 my $url_intvl = delete $self->{idle_pids}->{$pid} or
572 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
574 my ($url, $intvl) = @$url_intvl;
575 return if $self->{quit};
576 warn "W: PID=$pid on $url died: \$?=$?\n" if $?;
577 PublicInbox::DS::add_timer(60,
578 \&imap_idle_requeue, [ $self, $url_intvl ]);
581 sub imap_idle_fork ($$) {
582 my ($self, $url_intvl) = @_;
583 my ($url, $intvl) = @$url_intvl;
584 defined(my $pid = fork) or die "fork: $!";
586 watch_atfork_child($self);
587 watch_imap_idle_1($self, $url, $intvl);
590 $self->{idle_pids}->{$pid} = $url_intvl;
591 PublicInbox::DS::dwaitpid($pid, \&imap_idle_reap, $self);
596 return if $self->{quit};
597 my $idle_todo = $self->{idle_todo};
598 if ($idle_todo && @$idle_todo) {
599 watch_atfork_parent($self);
600 while (my $url_intvl = shift(@$idle_todo)) {
601 imap_idle_fork($self, $url_intvl);
604 goto(&fs_scan_step) if $self->{mdre};
607 sub watch_imap_fetch_all ($$) {
608 my ($self, $urls) = @_;
609 for my $url (@$urls) {
610 my $uri = PublicInbox::URIimap->new($url);
611 my $sec = uri_section($uri);
612 my $mic_arg = $self->{mic_arg}->{$sec} or
613 die "BUG: no Mail::IMAPClient->new arg for $sec";
614 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or next;
615 my $err = imap_fetch_all($self, $mic, $url);
616 last if $self->{quit};
617 warn $err, "\n" if $err;
621 sub watch_nntp_fetch_all ($$) {
622 my ($self, $urls) = @_;
623 for my $url (@$urls) {
624 my $uri = uri_new($url);
625 my $sec = uri_section($uri);
626 my $nn_arg = $self->{nn_arg}->{$sec} or
627 die "BUG: no Net::NNTP->new arg for $sec";
628 my $nntp_opt = $self->{nntp_opt}->{$sec};
629 my $nn = nn_new($nn_arg, $nntp_opt, $url);
631 warn "E: $url: \$!=$!\n";
634 last if $self->{quit};
635 if (my $postconn = $nntp_opt->{-postconn}) {
636 for my $m_arg (@$postconn) {
637 my ($method, @args) = @$m_arg;
638 $nn->$method(@args) and next;
639 warn "E: <$url> $method failed\n";
644 last if $self->{quit};
646 my $err = nntp_fetch_all($self, $nn, $url);
647 warn $err, "\n" if $err;
652 sub poll_fetch_fork ($) { # DS::add_timer callback
653 my ($self, $intvl, $urls) = @{$_[0]};
654 return if $self->{quit};
655 watch_atfork_parent($self);
656 defined(my $pid = fork) or die "fork: $!";
658 watch_atfork_child($self);
659 if ($urls->[0] =~ m!\Aimaps?://!i) {
660 watch_imap_fetch_all($self, $urls);
662 watch_nntp_fetch_all($self, $urls);
666 $self->{poll_pids}->{$pid} = [ $intvl, $urls ];
667 PublicInbox::DS::dwaitpid($pid, \&poll_fetch_reap, $self);
670 sub poll_fetch_reap { # PublicInbox::DS::dwaitpid callback
671 my ($self, $pid) = @_;
672 my $intvl_urls = delete $self->{poll_pids}->{$pid} or
673 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
674 return if $self->{quit};
675 my ($intvl, $urls) = @$intvl_urls;
677 warn "W: PID=$pid died: \$?=$?\n", map { "$_\n" } @$urls;
679 warn("I: will check $_ in ${intvl}s\n") for @$urls;
680 PublicInbox::DS::add_timer($intvl, \&poll_fetch_fork,
681 [$self, $intvl, $urls]);
684 sub watch_imap_init ($$) {
685 my ($self, $poll) = @_;
686 eval { require PublicInbox::IMAPClient } or
687 die "Mail::IMAPClient is required for IMAP:\n$@\n";
688 eval { require PublicInbox::IMAPTracker } or
689 die "DBD::SQLite is required for IMAP\n:$@\n";
691 my $mic_args = imap_common_init($self); # read args from config
693 # make sure we can connect and cache the credentials in memory
694 $self->{mic_arg} = {}; # schema://authority => IMAPClient->new args
695 my $mics = {}; # schema://authority => IMAPClient obj
696 for my $url (sort keys %{$self->{imap}}) {
697 my $uri = PublicInbox::URIimap->new($url);
698 $mics->{uri_section($uri)} //= mic_for($self, $url, $mic_args);
701 my $idle = []; # [ [ url1, intvl1 ], [url2, intvl2] ]
702 for my $url (keys %{$self->{imap}}) {
703 my $uri = PublicInbox::URIimap->new($url);
704 my $sec = uri_section($uri);
705 my $mic = $mics->{$sec};
706 my $intvl = $self->{imap_opt}->{$sec}->{pollInterval};
707 if ($mic->has_capability('IDLE') && !$intvl) {
708 $intvl = $self->{imap_opt}->{$sec}->{idleInterval};
709 push @$idle, [ $url, $intvl // () ];
711 push @{$poll->{$intvl || 120}}, $url;
715 $self->{idle_todo} = $idle;
716 PublicInbox::DS::requeue($self); # ->event_step to fork
720 # flesh out common NNTP-specific data structures
721 sub nntp_common_init ($) {
723 my $cfg = $self->{config};
724 my $nn_args = {}; # scheme://authority => Net::NNTP->new arg
725 for my $url (sort keys %{$self->{nntp}}) {
726 my $sec = uri_section(uri_new($url));
728 # Debug and Timeout are passed to Net::NNTP->new
729 my $v = cfg_bool($cfg, 'nntp.Debug', $url);
730 $nn_args->{$sec}->{Debug} = $v if defined $v;
731 my $to = cfg_intvl($cfg, 'nntp.Timeout', $url);
732 $nn_args->{$sec}->{Timeout} = $to if $to;
734 # Net::NNTP post-connect commands
735 for my $k (qw(starttls compress)) {
736 $v = cfg_bool($cfg, "nntp.$k", $url) // next;
737 $self->{nntp_opt}->{$sec}->{$k} = $v;
741 for my $k (qw(pollInterval)) {
742 $to = cfg_intvl($cfg, "nntp.$k", $url) // next;
743 $self->{nntp_opt}->{$sec}->{$k} = $to;
749 # Net::NNTP doesn't support CAPABILITIES, yet
750 sub try_starttls ($) {
752 return if $host =~ /\.onion\z/s;
753 return if $host =~ /\A127\.[0-9]+\.[0-9]+\.[0-9]+\z/s;
754 return if $host eq '::1';
759 my ($nn_arg, $nntp_opt, $url) = @_;
760 my $nn = Net::NNTP->new(%$nn_arg) or die "E: <$url> new: $!\n";
762 # default to using STARTTLS if it's available, but allow
763 # it to be disabled for localhost/VPN users
764 if (!$nn_arg->{SSL} && $nn->can('starttls')) {
765 if (!defined($nntp_opt->{starttls}) &&
766 try_starttls($nn_arg->{Host})) {
767 # soft fail by default
768 $nn->starttls or warn <<"";
769 W: <$url> STARTTLS tried and failed (not requested)
771 } elsif ($nntp_opt->{starttls}) {
772 # hard fail if explicitly configured
773 $nn->starttls or die <<"";
774 E: <$url> STARTTLS requested and failed
777 } elsif ($nntp_opt->{starttls}) {
778 $nn->can('starttls') or
779 die "E: <$url> Net::NNTP too old for STARTTLS\n";
780 $nn->starttls or die <<"";
781 E: <$url> STARTTLS requested and failed
787 sub nn_for ($$$) { # nn = Net::NNTP
788 my ($self, $url, $nn_args) = @_;
789 my $uri = uri_new($url);
790 my $sec = uri_section($uri);
791 my $nntp_opt = $self->{nntp_opt}->{$sec} //= {};
792 my $host = $uri->host;
793 # Net::NNTP and Net::Netrc both mishandle `0', so we pass `127.0.0.1'
794 $host = '127.0.0.1' if $host eq '0';
797 if (defined(my $ui = $uri->userinfo)) {
798 require PublicInbox::GitCredential;
801 protocol => uri_scheme($uri),
803 }, 'PublicInbox::GitCredential';
804 ($u, $p) = split(/:/, $ui, 2);
805 ($cred->{username}, $cred->{password}) = ($u, $p);
806 $cred->check_netrc unless defined $p;
808 my $common = $nn_args->{$sec} // {};
812 SSL => $uri->secure, # snews == nntps
813 %$common, # may Debug ....
815 my $nn = nn_new($nn_arg, $nntp_opt, $url);
818 $cred->fill; # may prompt user here
819 if ($nn->authinfo($u, $p)) {
820 push @{$nntp_opt->{-postconn}}, [ 'authinfo', $u, $p ];
822 warn "E: <$url> AUTHINFO $u XXXX failed\n";
827 if ($nntp_opt->{compress}) {
828 # https://rt.cpan.org/Ticket/Display.html?id=129967
829 if ($nn->can('compress')) {
831 push @{$nntp_opt->{-postconn}}, [ 'compress' ];
833 warn "W: <$url> COMPRESS failed\n";
836 delete $nntp_opt->{compress};
838 W: <$url> COMPRESS not supported by Net::NNTP
839 W: see https://rt.cpan.org/Ticket/Display.html?id=129967 for updates
844 $self->{nn_arg}->{$sec} = $nn_arg;
845 $cred->run($nn ? 'approve' : 'reject') if $cred;
849 sub nntp_fetch_all ($$$) {
850 my ($self, $nn, $url) = @_;
851 my $uri = uri_new($url);
852 my ($group, $num_a, $num_b) = $uri->group;
853 my $sec = uri_section($uri);
854 my ($nr, $beg, $end) = $nn->group($group);
855 unless (defined($nr)) {
856 chomp(my $msg = $nn->message);
857 return "E: GROUP $group <$sec> $msg";
860 # IMAPTracker is also used for tracking NNTP, UID == article number
861 # LIST.ACTIVE can get the equivalent of UIDVALIDITY, but that's
862 # expensive. So we assume newsgroups don't change:
863 my $itrk = PublicInbox::IMAPTracker->new($url);
864 my (undef, $l_art) = $itrk->get_last;
865 $l_art //= $beg; # initial import
867 # allow users to specify articles to refetch
868 # cf. https://tools.ietf.org/id/draft-gilman-news-url-01.txt
869 # nntp://example.com/inbox.foo/$num_a-$num_b
870 $l_art = $num_a if defined($num_a) && $num_a < $l_art;
871 $end = $num_b if defined($num_b) && $num_b < $end;
873 return if $l_art >= $end; # nothing to do
876 warn "I: $url fetching ARTICLE $beg..$end\n";
877 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
879 local $SIG{__WARN__} = sub {
880 $warn_cb->("$url ", $art ? ("ARTICLE $art") : (), "\n", @_);
882 my $inboxes = $self->{nntp}->{$url};
885 last if $self->{quit};
887 my $raw = $nn->article($art);
888 unless (defined($raw)) {
889 my $msg = $nn->message;
890 if ($nn->code == 421) { # pseudo response from Net::Cmd
893 } else { # probably just a deleted message (spam)
898 s/\r\n/\n/ for @$raw;
899 $raw = join('', @$raw);
901 for my $ibx (@$inboxes) {
902 my $eml = PublicInbox::Eml->new($raw);
903 import_eml($self, $ibx, $eml);
905 } elsif ($inboxes eq 'watchspam') {
906 my $eml = PublicInbox::Eml->new(\$raw);
907 my $arg = [ $self, $eml, "$url ARTICLE $art" ];
908 $self->{config}->each_inbox(\&remove_eml_i, $arg);
910 die "BUG: destination unknown $inboxes";
914 $itrk->update_last(0, $last_art) if defined $last_art;
915 _done_for_now($self);
919 sub watch_nntp_init ($$) {
920 my ($self, $poll) = @_;
921 eval { require Net::NNTP } or
922 die "Net::NNTP is required for NNTP:\n$@\n";
923 eval { require PublicInbox::IMAPTracker } or
924 die "DBD::SQLite is required for NNTP\n:$@\n";
926 my $nn_args = nntp_common_init($self); # read args from config
928 # make sure we can connect and cache the credentials in memory
929 $self->{nn_arg} = {}; # schema://authority => Net::NNTP->new args
930 for my $url (sort keys %{$self->{nntp}}) {
931 nn_for($self, $url, $nn_args);
933 for my $url (keys %{$self->{nntp}}) {
934 my $uri = uri_new($url);
935 my $sec = uri_section($uri);
936 my $intvl = $self->{nntp_opt}->{$sec}->{pollInterval};
937 push @{$poll->{$intvl || 120}}, $url;
942 my ($self, $sig, $oldset) = @_;
943 $self->{oldset} = $oldset;
945 my $poll = {}; # intvl_seconds => [ url1, url2 ]
946 watch_imap_init($self, $poll) if $self->{imap};
947 watch_nntp_init($self, $poll) if $self->{nntp};
948 while (my ($intvl, $urls) = each %$poll) {
949 # poll all URLs for a given interval sequentially
950 PublicInbox::DS::add_timer(0, \&poll_fetch_fork,
951 [$self, $intvl, $urls]);
953 watch_fs_init($self) if $self->{mdre};
954 PublicInbox::DS->SetPostLoopCallback(sub { !$self->quit_done });
955 PublicInbox::DS->EventLoop;
956 _done_for_now($self);
960 my ($self, $op) = @_;
961 push @{$self->{ops}}, $op;
962 PublicInbox::DS::requeue($self);
967 return if $self->{quit};
968 my $op = shift @{$self->{ops}};
969 local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
971 # continue existing scan
973 my $opendirs = $self->{opendirs};
974 my @dirnames = keys %$opendirs;
975 foreach my $dir (@dirnames) {
976 my $dh = delete $opendirs->{$dir};
978 while (my $fn = readdir($dh)) {
979 _try_path($self, "$dir/$fn");
982 $opendirs->{$dir} = $dh if $n < 0;
984 if ($op && $op eq 'full') {
985 foreach my $dir (keys %{$self->{mdmap}}) {
986 next if $opendirs->{$dir}; # already in progress
987 my $ok = opendir(my $dh, $dir);
989 warn "failed to open $dir: $!\n";
993 while (my $fn = readdir($dh)) {
994 _try_path($self, "$dir/$fn");
997 $opendirs->{$dir} = $dh if $n < 0;
1000 _done_for_now($self);
1001 # do we have more work to do?
1002 PublicInbox::DS::requeue($self) if keys %$opendirs;
1006 my ($self, $op) = @_;
1007 push @{$self->{ops}}, $op;
1012 my ($self, $ibx) = @_;
1013 my $importers = $self->{importers};
1014 my $im = $importers->{"$ibx"} ||= $ibx->importer(0);
1015 if (scalar(keys(%$importers)) > 2) {
1016 delete $importers->{"$ibx"};
1017 _done_for_now($self);
1020 $importers->{"$ibx"} = $im;
1023 # XXX consider sharing with V2Writable, this only requires read-only access
1024 sub content_exists ($$) {
1025 my ($ibx, $eml) = @_;
1026 my $over = $ibx->over or return;
1027 my $mids = mids($eml);
1028 my $chash = content_hash($eml);
1030 for my $mid (@$mids) {
1031 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
1032 my $cmp = $ibx->smsg_eml($smsg) or return;
1033 return 1 if $chash eq content_hash($cmp);
1042 my ($mime, $ibx) = @_;
1043 return if content_exists($ibx, $mime);
1045 if ($sc->spamcheck($mime, \$tmp)) {
1046 return PublicInbox::Eml->new(\$tmp);
1048 warn $mime->header('Message-ID')." failed spam check\n";
1054 $_[0] =~ s!\Amaildir:!! or return;
1061 my ($cur, $ws, $ibx) = @_;
1062 if ($ws && !ref($ws) && $ws eq 'watchspam') {
1064 E: $cur is a spam folder and cannot be used for `$ibx->{name}' input
1074 # URI::snews exists, URI::nntps does not, so use URI::snews
1075 $url =~ s!\Anntps://!snews://!i;
1081 require PublicInbox::URIimap;
1082 my $uri = PublicInbox::URIimap->new($url);
1083 $uri ? $uri->canonical->as_string : undef;
1086 my %IS_NNTP = (news => 1, snews => 1, nntp => 1);
1090 my $uri = uri_new($url);
1091 return unless $uri && $IS_NNTP{$uri->scheme} && $uri->group;
1092 $url = $uri->canonical->as_string;
1093 # nntps is IANA registered, snews is deprecated
1094 $url =~ s!\Asnews://!nntps://!;