1 # Copyright (C) 2016-2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # ref: https://cr.yp.to/proto/maildir.html
5 # http://wiki2.dovecot.org/MailboxFormat/Maildir
6 package PublicInbox::WatchMaildir;
10 use PublicInbox::InboxWritable;
11 use PublicInbox::Filter::Base qw(REJECT);
12 use PublicInbox::Spamcheck;
13 use PublicInbox::Sigfd;
14 use PublicInbox::DS qw(now);
15 use PublicInbox::MID qw(mids);
16 use PublicInbox::ContentHash qw(content_hash);
18 *mime_from_path = \&PublicInbox::InboxWritable::mime_from_path;
20 sub compile_watchheaders ($) {
23 if (my $whs = $ibx->{watchheader}) {
25 my ($k, $v) = split(/:/, $_, 2);
26 # XXX should this be case-insensitive?
27 # Or, mutt-style, case-sensitive iff
28 # a capital letter exists?
29 push @$watch_hdrs, [ $k, qr/\Q$v\E/ ];
32 if (my $list_ids = $ibx->{listid}) {
34 # RFC2919 section 6 stipulates
35 # "case insensitive equality"
36 my $re = qr/<[ \t]*\Q$_\E[ \t]*>/i;
37 push @$watch_hdrs, ['List-Id', $re ];
40 $ibx->{-watchheaders} = $watch_hdrs if scalar @$watch_hdrs;
44 my ($class, $config) = @_;
46 my (%imap, %nntp); # url => [inbox objects] or 'watchspam'
48 # "publicinboxwatch" is the documented namespace
49 # "publicinboxlearn" is legacy but may be supported
51 foreach my $pfx (qw(publicinboxwatch publicinboxlearn)) {
52 my $k = "$pfx.watchspam";
53 defined(my $dirs = $config->{$k}) or next;
54 $dirs = PublicInbox::Config::_array($dirs);
55 for my $dir (@$dirs) {
57 if (is_maildir($dir)) {
58 # skip "new", no MUA has seen it, yet.
59 $mdmap{"$dir/cur"} = 'watchspam';
60 } elsif ($url = imap_url($dir)) {
61 $imap{$url} = 'watchspam';
62 } elsif ($url = nntp_url($dir)) {
63 $nntp{$url} = 'watchspam';
65 warn "unsupported $k=$dir\n";
70 my $k = 'publicinboxwatch.spamcheck';
72 my $spamcheck = PublicInbox::Spamcheck::get($config, $k, $default);
73 $spamcheck = _spamcheck_cb($spamcheck) if $spamcheck;
75 $config->each_inbox(sub {
76 # need to make all inboxes writable for spam removal:
77 my $ibx = $_[0] = PublicInbox::InboxWritable->new($_[0]);
79 my $watches = $ibx->{watch} or return;
80 $watches = PublicInbox::Config::_array($watches);
81 for my $watch (@$watches) {
83 if (is_maildir($watch)) {
84 compile_watchheaders($ibx);
85 my ($new, $cur) = ("$watch/new", "$watch/cur");
86 my $cur_dst = $mdmap{$cur} //= [];
87 return if is_watchspam($cur, $cur_dst, $ibx);
88 push @{$mdmap{$new} //= []}, $ibx;
90 } elsif ($url = imap_url($watch)) {
91 return if is_watchspam($url, $imap{$url}, $ibx);
92 compile_watchheaders($ibx);
93 push @{$imap{$url} ||= []}, $ibx;
94 } elsif ($url = nntp_url($watch)) {
95 return if is_watchspam($url, $nntp{$url}, $ibx);
96 compile_watchheaders($ibx);
97 push @{$nntp{$url} ||= []}, $ibx;
99 warn "watch unsupported: $k=$watch\n";
105 if (scalar keys %mdmap) {
106 $mdre = join('|', map { quotemeta($_) } keys %mdmap);
107 $mdre = qr!\A($mdre)/!;
109 return unless $mdre || scalar(keys %imap) || scalar(keys %nntp);
112 spamcheck => $spamcheck,
116 imap => scalar keys %imap ? \%imap : undef,
117 nntp => scalar keys %nntp? \%nntp : undef,
119 opendirs => {}, # dirname => dirhandle (in progress scans)
120 ops => [], # 'quit', 'full'
126 local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
127 for (values %{$self->{importers}}) {
128 $_->done if $_; # $_ may be undef during cleanup
132 sub remove_eml_i { # each_inbox callback
133 my ($ibx, $arg) = @_;
134 my ($self, $eml, $loc) = @$arg;
136 my $im = _importer_for($self, $ibx);
137 $im->remove($eml, 'spam');
138 if (my $scrub = $ibx->filter($im)) {
139 my $scrubbed = $scrub->scrub($eml, 1);
141 $scrubbed == REJECT() and return;
142 $im->remove($scrubbed, 'spam');
145 warn "error removing spam at: $loc from $ibx->{name}: $@\n" if $@;
149 my ($self, $path) = @_;
150 # path must be marked as (S)een
151 $path =~ /:2,[A-R]*S[T-Za-z]*\z/ or return;
152 my $eml = mime_from_path($path) or return;
153 $self->{config}->each_inbox(\&remove_eml_i, [ $self, $eml, $path ]);
156 sub import_eml ($$$) {
157 my ($self, $ibx, $eml) = @_;
158 my $im = _importer_for($self, $ibx);
160 # any header match means it's eligible for the inbox:
161 if (my $watch_hdrs = $ibx->{-watchheaders}) {
163 my $hdr = $eml->header_obj;
164 for my $wh (@$watch_hdrs) {
165 my @v = $hdr->header_raw($wh->[0]);
166 $ok = grep(/$wh->[1]/, @v) and last;
171 if (my $scrub = $ibx->filter($im)) {
172 my $ret = $scrub->scrub($eml) or return;
173 $ret == REJECT() and return;
176 $im->add($eml, $self->{spamcheck});
180 my ($self, $path) = @_;
181 return unless PublicInbox::InboxWritable::is_maildir_path($path);
182 if ($path !~ $self->{mdre}) {
183 warn "unrecognized path: $path\n";
186 my $inboxes = $self->{mdmap}->{$1};
188 warn "unmappable dir: $1\n";
191 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
192 local $SIG{__WARN__} = sub {
193 $warn_cb->("path: $path\n");
196 if (!ref($inboxes) && $inboxes eq 'watchspam') {
197 return _remove_spam($self, $path);
199 foreach my $ibx (@$inboxes) {
200 my $eml = mime_from_path($path) or next;
201 import_eml($self, $ibx, $eml);
207 return unless $self->{quit};
209 # don't have reliable wakeups, keep signalling
211 for (qw(idle_pids poll_pids)) {
212 my $pids = $self->{$_} or next;
214 $done = undef if kill('QUIT', $_);
223 %{$self->{opendirs}} = ();
224 _done_for_now($self);
226 if (my $idle_mic = $self->{idle_mic}) {
227 eval { $idle_mic->done };
229 warn "IDLE DONE error: $@\n";
230 eval { $idle_mic->disconnect };
231 warn "IDLE LOGOUT error: $@\n" if $@;
236 sub watch_fs_init ($) {
239 delete $self->{done_timer};
240 _done_for_now($self);
243 _try_path($self, $_[0]->fullname);
244 $self->{done_timer} //= PublicInbox::DS::requeue($done);
246 require PublicInbox::DirIdle;
247 # inotify_create + EPOLL_CTL_ADD
248 PublicInbox::DirIdle->new([keys %{$self->{mdmap}}], $cb);
251 # avoid exposing deprecated "snews" to users.
252 my %SCHEME_MAP = ('snews' => 'nntps');
256 my $scheme = $uri->scheme;
257 $SCHEME_MAP{$scheme} // $scheme;
260 # returns the git config section name, e.g [imap "imaps://user@example.com"]
261 # without the mailbox, so we can share connections between different inboxes
262 sub uri_section ($) {
264 uri_scheme($uri) . '://' . $uri->authority;
267 sub cfg_intvl ($$$) {
268 my ($cfg, $key, $url) = @_;
269 my $v = $cfg->urlmatch($key, $url) // return;
270 $v =~ /\A[0-9]+(?:\.[0-9]+)?\z/s and return $v + 0;
271 if (ref($v) eq 'ARRAY') {
272 $v = join(', ', @$v);
273 warn "W: $key has multiple values: $v\nW: $key ignored\n";
275 warn "W: $key=$v is not a numeric value in seconds\n";
280 my ($cfg, $key, $url) = @_;
281 my $orig = $cfg->urlmatch($key, $url) // return;
282 my $bool = PublicInbox::Config::_git_config_bool($orig);
283 warn "W: $key=$orig for $url is not boolean\n" unless defined($bool);
287 # flesh out common IMAP-specific data structures
288 sub imap_common_init ($) {
290 my $cfg = $self->{config};
291 my $mic_args = {}; # scheme://authority => Mail:IMAPClient arg
292 for my $url (sort keys %{$self->{imap}}) {
293 my $uri = PublicInbox::URIimap->new($url);
294 my $sec = uri_section($uri);
295 for my $k (qw(Starttls Debug Compress)) {
296 my $bool = cfg_bool($cfg, "imap.$k", $url) // next;
297 $mic_args->{$sec}->{$k} = $bool;
299 my $to = cfg_intvl($cfg, 'imap.timeout', $url);
300 $mic_args->{$sec}->{Timeout} = $to if $to;
301 for my $k (qw(pollInterval idleInterval)) {
302 $to = cfg_intvl($cfg, "imap.$k", $url) // next;
303 $self->{imap_opt}->{$sec}->{$k} = $to;
305 my $k = 'imap.fetchBatchSize';
306 my $bs = $cfg->urlmatch($k, $url) // next;
307 if ($bs =~ /\A([0-9]+)\z/) {
308 $self->{imap_opt}->{$sec}->{batch_size} = $bs;
310 warn "$k=$bs is not an integer\n";
316 sub auth_anon_cb { '' }; # for Mail::IMAPClient::Authcallback
318 sub mic_for ($$$) { # mic = Mail::IMAPClient
319 my ($self, $url, $mic_args) = @_;
320 my $uri = PublicInbox::URIimap->new($url);
321 require PublicInbox::GitCredential;
324 protocol => $uri->scheme,
326 username => $uri->user,
327 password => $uri->password,
328 }, 'PublicInbox::GitCredential';
329 my $common = $mic_args->{uri_section($uri)} // {};
330 # IMAPClient and Net::Netrc both mishandles `0', so we pass `127.0.0.1'
331 my $host = $cred->{host};
332 $host = '127.0.0.1' if $host eq '0';
336 Ssl => $uri->scheme eq 'imaps',
337 Keepalive => 1, # SO_KEEPALIVE
338 %$common, # may set Starttls, Compress, Debug ....
340 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or
341 die "E: <$url> new: $@\n";
343 # default to using STARTTLS if it's available, but allow
344 # it to be disabled since I usually connect to localhost
345 if (!$mic_arg->{Ssl} && !defined($mic_arg->{Starttls}) &&
346 $mic->has_capability('STARTTLS') &&
347 $mic->can('starttls')) {
348 $mic->starttls or die "E: <$url> STARTTLS: $@\n";
351 # do we even need credentials?
352 if (!defined($cred->{username}) &&
353 $mic->has_capability('AUTH=ANONYMOUS')) {
357 $cred->check_netrc unless defined $cred->{password};
358 $cred->fill; # may prompt user here
359 $mic->User($mic_arg->{User} = $cred->{username});
360 $mic->Password($mic_arg->{Password} = $cred->{password});
361 } else { # AUTH=ANONYMOUS
362 $mic->Authmechanism($mic_arg->{Authmechanism} = 'ANONYMOUS');
363 $mic->Authcallback($mic_arg->{Authcallback} = \&auth_anon_cb);
365 if ($mic->login && $mic->IsAuthenticated) {
366 # success! keep IMAPClient->new arg in case we get disconnected
367 $self->{mic_arg}->{uri_section($uri)} = $mic_arg;
369 warn "E: <$url> LOGIN: $@\n";
372 $cred->run($mic ? 'approve' : 'reject') if $cred;
376 sub imap_import_msg ($$$$) {
377 my ($self, $url, $uid, $raw) = @_;
378 # our target audience expects LF-only, save storage
379 $$raw =~ s/\r\n/\n/sg;
381 my $inboxes = $self->{imap}->{$url};
383 for my $ibx (@$inboxes) {
384 my $eml = PublicInbox::Eml->new($$raw);
385 my $x = import_eml($self, $ibx, $eml);
387 } elsif ($inboxes eq 'watchspam') {
388 my $eml = PublicInbox::Eml->new($raw);
389 my $arg = [ $self, $eml, "$url UID:$uid" ];
390 $self->{config}->each_inbox(\&remove_eml_i, $arg);
392 die "BUG: destination unknown $inboxes";
396 sub imap_fetch_all ($$$) {
397 my ($self, $mic, $url) = @_;
398 my $uri = PublicInbox::URIimap->new($url);
399 my $sec = uri_section($uri);
400 my $mbx = $uri->mailbox;
401 $mic->Clear(1); # trim results history
402 $mic->examine($mbx) or return "E: EXAMINE $mbx ($sec) failed: $!";
403 my ($r_uidval, $r_uidnext);
404 for ($mic->Results) {
405 /^\* OK \[UIDVALIDITY ([0-9]+)\].*/ and $r_uidval = $1;
406 /^\* OK \[UIDNEXT ([0-9]+)\].*/ and $r_uidnext = $1;
407 last if $r_uidval && $r_uidnext;
409 $r_uidval //= $mic->uidvalidity($mbx) //
410 return "E: $url cannot get UIDVALIDITY";
411 $r_uidnext //= $mic->uidnext($mbx) //
412 return "E: $url cannot get UIDNEXT";
413 my $itrk = PublicInbox::IMAPTracker->new($url);
414 my ($l_uidval, $l_uid) = $itrk->get_last;
415 $l_uidval //= $r_uidval; # first time
417 if ($l_uidval != $r_uidval) {
418 return "E: $url UIDVALIDITY mismatch\n".
419 "E: local=$l_uidval != remote=$r_uidval";
421 my $r_uid = $r_uidnext - 1;
422 if ($l_uid != 1 && $l_uid > $r_uid) {
423 return "E: $url local UID exceeds remote ($l_uid > $r_uid)\n".
424 "E: $url strangely, UIDVALIDLITY matches ($l_uidval)\n";
426 return if $l_uid >= $r_uid; # nothing to do
428 warn "I: $url fetching UID $l_uid:$r_uid\n";
429 $mic->Uid(1); # the default, we hope
430 my $bs = $self->{imap_opt}->{$sec}->{batch_size} // 1;
431 my $req = $mic->imap4rev1 ? 'BODY.PEEK[]' : 'RFC822.PEEK';
433 # TODO: FLAGS may be useful for personal use
437 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
438 local $SIG{__WARN__} = sub {
440 $warn_cb->("$url UID:$batch\n");
445 # I wish "UID FETCH $START:*" could work, but:
446 # 1) servers do not need to return results in any order
447 # 2) Mail::IMAPClient doesn't offer a streaming API
448 $uids = $mic->search("UID $l_uid:*") or
449 return "E: $url UID SEARCH $l_uid:* error: $!";
450 return if scalar(@$uids) == 0;
452 # RFC 3501 doesn't seem to indicate order of UID SEARCH
453 # responses, so sort it ourselves. Order matters so
454 # IMAPTracker can store the newest UID.
455 @$uids = sort { $a <=> $b } @$uids;
457 # Did we actually get new messages?
458 return if $uids->[0] < $l_uid;
460 $l_uid = $uids->[-1] + 1; # for next search
463 while (scalar @$uids) {
464 my @batch = splice(@$uids, 0, $bs);
465 $batch = join(',', @batch);
466 local $0 = "UID:$batch $mbx $sec";
467 my $r = $mic->fetch_hash($batch, $req);
468 unless ($r) { # network error?
469 $err = "E: $url UID FETCH $batch error: $!";
472 for my $uid (@batch) {
473 # messages get deleted, so holes appear
474 my $per_uid = delete $r->{$uid} // next;
475 my $raw = delete($per_uid->{$key}) // next;
476 imap_import_msg($self, $url, $uid, \$raw);
478 last if $self->{quit};
480 last if $self->{quit};
482 _done_for_now($self);
483 $itrk->update_last($r_uidval, $last_uid) if defined $last_uid;
484 } until ($err || $self->{quit});
488 sub imap_idle_once ($$$$) {
489 my ($self, $mic, $intvl, $url) = @_;
490 my $i = $intvl //= (29 * 60);
491 my $end = now() + $intvl;
492 warn "I: $url idling for ${intvl}s\n";
493 local $0 = "IDLE $0";
494 unless ($mic->idle) {
495 return if $self->{quit};
496 return "E: IDLE failed on $url: $!";
498 $self->{idle_mic} = $mic; # for ->quit
500 until ($self->{quit} || grep(/^\* [0-9]+ EXISTS/, @res) || $i <= 0) {
501 @res = $mic->idle_data($i);
504 delete $self->{idle_mic};
505 unless ($self->{quit}) {
506 $mic->IsConnected or return "E: IDLE disconnected on $url";
507 $mic->done or return "E: IDLE DONE failed on $url: $!";
512 # idles on a single URI
513 sub watch_imap_idle_1 ($$$) {
514 my ($self, $url, $intvl) = @_;
515 my $uri = PublicInbox::URIimap->new($url);
516 my $sec = uri_section($uri);
517 my $mic_arg = $self->{mic_arg}->{$sec} or
518 die "BUG: no Mail::IMAPClient->new arg for $sec";
520 local $0 = $uri->mailbox." $sec";
521 until ($self->{quit}) {
522 $mic //= PublicInbox::IMAPClient->new(%$mic_arg);
523 my $err = imap_fetch_all($self, $mic, $url);
524 $err //= imap_idle_once($self, $mic, $intvl, $url);
525 if ($err && !$self->{quit}) {
528 sleep 60 unless $self->{quit};
533 sub watch_atfork_child ($) {
535 delete $self->{idle_pids};
536 delete $self->{poll_pids};
537 delete $self->{opendirs};
538 PublicInbox::DS->Reset;
539 %SIG = (%SIG, %{$self->{sig}}, CHLD => 'DEFAULT');
540 PublicInbox::Sigfd::sig_setmask($self->{oldset});
543 sub watch_atfork_parent ($) {
545 _done_for_now($self);
548 sub imap_idle_reap { # PublicInbox::DS::dwaitpid callback
549 my ($self, $pid) = @_;
550 my $url_intvl = delete $self->{idle_pids}->{$pid} or
551 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
553 my ($url, $intvl) = @$url_intvl;
554 return if $self->{quit};
555 warn "W: PID=$pid on $url died: \$?=$?\n" if $?;
556 push @{$self->{idle_todo}}, $url_intvl;
557 PubicInbox::DS::requeue($self); # call ->event_step to respawn
560 sub imap_idle_fork ($$) {
561 my ($self, $url_intvl) = @_;
562 my ($url, $intvl) = @$url_intvl;
563 defined(my $pid = fork) or die "fork: $!";
565 watch_atfork_child($self);
566 watch_imap_idle_1($self, $url, $intvl);
569 $self->{idle_pids}->{$pid} = $url_intvl;
570 PublicInbox::DS::dwaitpid($pid, \&imap_idle_reap, $self);
575 return if $self->{quit};
576 my $idle_todo = $self->{idle_todo};
577 if ($idle_todo && @$idle_todo) {
578 watch_atfork_parent($self);
579 while (my $url_intvl = shift(@$idle_todo)) {
580 imap_idle_fork($self, $url_intvl);
583 goto(&fs_scan_step) if $self->{mdre};
586 sub watch_imap_fetch_all ($$) {
587 my ($self, $urls) = @_;
588 for my $url (@$urls) {
589 my $uri = PublicInbox::URIimap->new($url);
590 my $sec = uri_section($uri);
591 my $mic_arg = $self->{mic_arg}->{$sec} or
592 die "BUG: no Mail::IMAPClient->new arg for $sec";
593 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or next;
594 my $err = imap_fetch_all($self, $mic, $url);
595 last if $self->{quit};
596 warn $err, "\n" if $err;
600 sub watch_nntp_fetch_all ($$) {
601 my ($self, $urls) = @_;
602 for my $url (@$urls) {
603 my $uri = uri_new($url);
604 my $sec = uri_section($uri);
605 my $nn_arg = $self->{nn_arg}->{$sec} or
606 die "BUG: no Net::NNTP->new arg for $sec";
607 my $nntp_opt = $self->{nntp_opt}->{$sec};
608 my $nn = nn_new($nn_arg, $nntp_opt, $url);
610 warn "E: $url: \$!=$!\n";
613 last if $self->{quit};
614 if (my $postconn = $nntp_opt->{-postconn}) {
615 for my $m_arg (@$postconn) {
616 my ($method, @args) = @$m_arg;
617 $nn->$method(@args) and next;
618 warn "E: <$url> $method failed\n";
623 last if $self->{quit};
625 my $err = nntp_fetch_all($self, $nn, $url);
626 warn $err, "\n" if $err;
631 sub poll_fetch_fork ($) { # DS::add_timer callback
632 my ($self, $intvl, $urls) = @{$_[0]};
633 return if $self->{quit};
634 watch_atfork_parent($self);
635 defined(my $pid = fork) or die "fork: $!";
637 watch_atfork_child($self);
638 if ($urls->[0] =~ m!\Aimaps?://!i) {
639 watch_imap_fetch_all($self, $urls);
641 watch_nntp_fetch_all($self, $urls);
645 $self->{poll_pids}->{$pid} = [ $intvl, $urls ];
646 PublicInbox::DS::dwaitpid($pid, \&poll_fetch_reap, $self);
649 sub poll_fetch_reap { # PublicInbox::DS::dwaitpid callback
650 my ($self, $pid) = @_;
651 my $intvl_urls = delete $self->{poll_pids}->{$pid} or
652 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
653 return if $self->{quit};
654 my ($intvl, $urls) = @$intvl_urls;
656 warn "W: PID=$pid died: \$?=$?\n", map { "$_\n" } @$urls;
658 warn("I: will check $_ in ${intvl}s\n") for @$urls;
659 PublicInbox::DS::add_timer($intvl, \&poll_fetch_fork,
660 [$self, $intvl, $urls]);
663 sub watch_imap_init ($$) {
664 my ($self, $poll) = @_;
665 eval { require PublicInbox::IMAPClient } or
666 die "Mail::IMAPClient is required for IMAP:\n$@\n";
667 eval { require PublicInbox::IMAPTracker } or
668 die "DBD::SQLite is required for IMAP\n:$@\n";
670 my $mic_args = imap_common_init($self); # read args from config
672 # make sure we can connect and cache the credentials in memory
673 $self->{mic_arg} = {}; # schema://authority => IMAPClient->new args
674 my $mics = {}; # schema://authority => IMAPClient obj
675 for my $url (sort keys %{$self->{imap}}) {
676 my $uri = PublicInbox::URIimap->new($url);
677 $mics->{uri_section($uri)} //= mic_for($self, $url, $mic_args);
680 my $idle = []; # [ [ url1, intvl1 ], [url2, intvl2] ]
681 for my $url (keys %{$self->{imap}}) {
682 my $uri = PublicInbox::URIimap->new($url);
683 my $sec = uri_section($uri);
684 my $mic = $mics->{$sec};
685 my $intvl = $self->{imap_opt}->{$sec}->{pollInterval};
686 if ($mic->has_capability('IDLE') && !$intvl) {
687 $intvl = $self->{imap_opt}->{$sec}->{idleInterval};
688 push @$idle, [ $url, $intvl // () ];
690 push @{$poll->{$intvl || 120}}, $url;
694 $self->{idle_todo} = $idle;
695 PublicInbox::DS::requeue($self); # ->event_step to fork
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} //= {};
771 my $host = $uri->host;
772 # Net::NNTP and Net::Netrc both mishandle `0', so we pass `127.0.0.1'
773 $host = '127.0.0.1' if $host eq '0';
776 if (defined(my $ui = $uri->userinfo)) {
777 require PublicInbox::GitCredential;
780 protocol => uri_scheme($uri),
782 }, 'PublicInbox::GitCredential';
783 ($u, $p) = split(/:/, $ui, 2);
784 ($cred->{username}, $cred->{password}) = ($u, $p);
785 $cred->check_netrc unless defined $p;
787 my $common = $nn_args->{$sec} // {};
791 SSL => $uri->secure, # snews == nntps
792 %$common, # may Debug ....
794 my $nn = nn_new($nn_arg, $nntp_opt, $url);
797 $cred->fill; # may prompt user here
798 if ($nn->authinfo($u, $p)) {
799 push @{$nntp_opt->{-postconn}}, [ 'authinfo', $u, $p ];
801 warn "E: <$url> AUTHINFO $u XXXX failed\n";
806 if ($nntp_opt->{compress}) {
807 # https://rt.cpan.org/Ticket/Display.html?id=129967
808 if ($nn->can('compress')) {
810 push @{$nntp_opt->{-postconn}}, [ 'compress' ];
812 warn "W: <$url> COMPRESS failed\n";
815 delete $nntp_opt->{compress};
817 W: <$url> COMPRESS not supported by Net::NNTP
818 W: see https://rt.cpan.org/Ticket/Display.html?id=129967 for updates
823 $self->{nn_arg}->{$sec} = $nn_arg;
824 $cred->run($nn ? 'approve' : 'reject') if $cred;
828 sub nntp_fetch_all ($$$) {
829 my ($self, $nn, $url) = @_;
830 my $uri = uri_new($url);
831 my ($group, $num_a, $num_b) = $uri->group;
832 my $sec = uri_section($uri);
833 my ($nr, $beg, $end) = $nn->group($group);
834 unless (defined($nr)) {
835 chomp(my $msg = $nn->message);
836 return "E: GROUP $group <$sec> $msg";
839 # IMAPTracker is also used for tracking NNTP, UID == article number
840 # LIST.ACTIVE can get the equivalent of UIDVALIDITY, but that's
841 # expensive. So we assume newsgroups don't change:
842 my $itrk = PublicInbox::IMAPTracker->new($url);
843 my (undef, $l_art) = $itrk->get_last;
844 $l_art //= $beg; # initial import
846 # allow users to specify articles to refetch
847 # cf. https://tools.ietf.org/id/draft-gilman-news-url-01.txt
848 # nntp://example.com/inbox.foo/$num_a-$num_b
849 $l_art = $num_a if defined($num_a) && $num_a < $l_art;
850 $end = $num_b if defined($num_b) && $num_b < $end;
852 return if $l_art >= $end; # nothing to do
855 warn "I: $url fetching ARTICLE $beg..$end\n";
856 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
858 local $SIG{__WARN__} = sub {
859 $warn_cb->("$url ", $art ? ("ARTICLE $art") : (), "\n", @_);
861 my $inboxes = $self->{nntp}->{$url};
864 last if $self->{quit};
866 my $raw = $nn->article($art);
867 unless (defined($raw)) {
868 my $msg = $nn->message;
869 if ($nn->code == 421) { # pseudo response from Net::Cmd
872 } else { # probably just a deleted message (spam)
877 s/\r\n/\n/ for @$raw;
878 $raw = join('', @$raw);
880 for my $ibx (@$inboxes) {
881 my $eml = PublicInbox::Eml->new($raw);
882 import_eml($self, $ibx, $eml);
884 } elsif ($inboxes eq 'watchspam') {
885 my $eml = PublicInbox::Eml->new(\$raw);
886 my $arg = [ $self, $eml, "$url ARTICLE $art" ];
887 $self->{config}->each_inbox(\&remove_eml_i, $arg);
889 die "BUG: destination unknown $inboxes";
893 $itrk->update_last(0, $last_art) if defined $last_art;
894 _done_for_now($self);
898 sub watch_nntp_init ($$) {
899 my ($self, $poll) = @_;
900 eval { require Net::NNTP } or
901 die "Net::NNTP is required for NNTP:\n$@\n";
902 eval { require PublicInbox::IMAPTracker } or
903 die "DBD::SQLite is required for NNTP\n:$@\n";
905 my $nn_args = nntp_common_init($self); # read args from config
907 # make sure we can connect and cache the credentials in memory
908 $self->{nn_arg} = {}; # schema://authority => Net::NNTP->new args
909 for my $url (sort keys %{$self->{nntp}}) {
910 nn_for($self, $url, $nn_args);
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;
921 my ($self, $sig, $oldset) = @_;
922 $self->{oldset} = $oldset;
924 my $poll = {}; # intvl_seconds => [ url1, url2 ]
925 watch_imap_init($self, $poll) if $self->{imap};
926 watch_nntp_init($self, $poll) if $self->{nntp};
927 while (my ($intvl, $urls) = each %$poll) {
928 # poll all URLs for a given interval sequentially
929 PublicInbox::DS::add_timer(0, \&poll_fetch_fork,
930 [$self, $intvl, $urls]);
932 watch_fs_init($self) if $self->{mdre};
933 PublicInbox::DS->SetPostLoopCallback(sub { !$self->quit_done });
934 PublicInbox::DS->EventLoop;
935 _done_for_now($self);
939 my ($self, $op) = @_;
940 push @{$self->{ops}}, $op;
941 PublicInbox::DS::requeue($self);
946 return if $self->{quit};
947 my $op = shift @{$self->{ops}};
948 local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
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;
1002 # XXX consider sharing with V2Writable, this only requires read-only access
1003 sub content_exists ($$) {
1004 my ($ibx, $eml) = @_;
1005 my $over = $ibx->over or return;
1006 my $mids = mids($eml);
1007 my $chash = content_hash($eml);
1009 for my $mid (@$mids) {
1010 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
1011 my $cmp = $ibx->smsg_eml($smsg) or return;
1012 return 1 if $chash eq content_hash($cmp);
1021 my ($mime, $ibx) = @_;
1022 return if content_exists($ibx, $mime);
1024 if ($sc->spamcheck($mime, \$tmp)) {
1025 return PublicInbox::Eml->new(\$tmp);
1027 warn $mime->header('Message-ID')." failed spam check\n";
1033 $_[0] =~ s!\Amaildir:!! or return;
1040 my ($cur, $ws, $ibx) = @_;
1041 if ($ws && !ref($ws) && $ws eq 'watchspam') {
1043 E: $cur is a spam folder and cannot be used for `$ibx->{name}' input
1053 # URI::snews exists, URI::nntps does not, so use URI::snews
1054 $url =~ s!\Anntps://!snews://!i;
1060 require PublicInbox::URIimap;
1061 my $uri = PublicInbox::URIimap->new($url);
1062 $uri ? $uri->canonical->as_string : undef;
1065 my %IS_NNTP = (news => 1, snews => 1, nntp => 1);
1069 my $uri = uri_new($url);
1070 return unless $uri && $IS_NNTP{$uri->scheme} && $uri->group;
1071 $url = $uri->canonical->as_string;
1072 # nntps is IANA registered, snews is deprecated
1073 $url =~ s!\Asnews://!nntps://!;