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 my $importers = $self->{importers};
127 foreach my $im (values %$importers) {
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);
208 %{$self->{opendirs}} = ();
209 _done_for_now($self);
210 if (my $imap_pid = $self->{-imap_pid}) {
211 kill('QUIT', $imap_pid);
213 for (qw(idle_pids poll_pids)) {
214 my $pids = $self->{$_} or next;
215 kill('QUIT', $_) for (keys %$pids);
217 if (my $idle_mic = $self->{idle_mic}) {
218 eval { $idle_mic->done };
220 warn "IDLE DONE error: $@\n";
221 eval { $idle_mic->disconnect };
222 warn "IDLE LOGOUT error: $@\n" if $@;
227 sub watch_fs_init ($) {
230 delete $self->{done_timer};
231 _done_for_now($self);
234 _try_path($self, $_[0]->fullname);
235 $self->{done_timer} //= PublicInbox::DS::requeue($done);
237 require PublicInbox::DirIdle;
238 # inotify_create + EPOLL_CTL_ADD
239 PublicInbox::DirIdle->new([keys %{$self->{mdmap}}], $cb);
242 # avoid exposing deprecated "snews" to users.
243 my %SCHEME_MAP = ('snews' => 'nntps');
247 my $scheme = $uri->scheme;
248 $SCHEME_MAP{$scheme} // $scheme;
251 # returns the git config section name, e.g [imap "imaps://user@example.com"]
252 # without the mailbox, so we can share connections between different inboxes
253 sub uri_section ($) {
255 uri_scheme($uri) . '://' . $uri->authority;
258 sub cfg_intvl ($$$) {
259 my ($cfg, $key, $url) = @_;
260 my $v = $cfg->urlmatch($key, $url) // return;
261 $v =~ /\A[0-9]+(?:\.[0-9]+)?\z/s and return $v + 0;
262 if (ref($v) eq 'ARRAY') {
263 $v = join(', ', @$v);
264 warn "W: $key has multiple values: $v\nW: $key ignored\n";
266 warn "W: $key=$v is not a numeric value in seconds\n";
271 my ($cfg, $key, $url) = @_;
272 my $orig = $cfg->urlmatch($key, $url) // return;
273 my $bool = PublicInbox::Config::_git_config_bool($orig);
274 warn "W: $key=$orig for $url is not boolean\n" unless defined($bool);
278 # flesh out common IMAP-specific data structures
279 sub imap_common_init ($) {
281 my $cfg = $self->{config};
282 my $mic_args = {}; # scheme://authority => Mail:IMAPClient arg
283 for my $url (sort keys %{$self->{imap}}) {
284 my $uri = PublicInbox::URIimap->new($url);
285 my $sec = uri_section($uri);
286 for my $k (qw(Starttls Debug Compress)) {
287 my $bool = cfg_bool($cfg, "imap.$k", $url) // next;
288 $mic_args->{$sec}->{$k} = $bool;
290 my $to = cfg_intvl($cfg, 'imap.timeout', $url);
291 $mic_args->{$sec}->{Timeout} = $to if $to;
292 for my $k (qw(pollInterval idleInterval)) {
293 $to = cfg_intvl($cfg, "imap.$k", $url) // next;
294 $self->{imap_opt}->{$sec}->{$k} = $to;
296 my $k = 'imap.fetchBatchSize';
297 my $bs = $cfg->urlmatch($k, $url) // next;
298 if ($bs =~ /\A([0-9]+)\z/) {
299 $self->{imap_opt}->{$sec}->{batch_size} = $bs;
301 warn "$k=$bs is not an integer\n";
307 sub auth_anon_cb { '' }; # for Mail::IMAPClient::Authcallback
309 sub mic_for ($$$) { # mic = Mail::IMAPClient
310 my ($self, $url, $mic_args) = @_;
311 my $uri = PublicInbox::URIimap->new($url);
312 require PublicInbox::GitCredential;
315 protocol => $uri->scheme,
317 username => $uri->user,
318 password => $uri->password,
319 }, 'PublicInbox::GitCredential';
320 my $common = $mic_args->{uri_section($uri)} // {};
321 # IMAPClient and Net::Netrc both mishandles `0', so we pass `127.0.0.1'
322 my $host = $cred->{host};
323 $host = '127.0.0.1' if $host eq '0';
327 Ssl => $uri->scheme eq 'imaps',
328 Keepalive => 1, # SO_KEEPALIVE
329 %$common, # may set Starttls, Compress, Debug ....
331 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or
332 die "E: <$url> new: $@\n";
334 # default to using STARTTLS if it's available, but allow
335 # it to be disabled since I usually connect to localhost
336 if (!$mic_arg->{Ssl} && !defined($mic_arg->{Starttls}) &&
337 $mic->has_capability('STARTTLS') &&
338 $mic->can('starttls')) {
339 $mic->starttls or die "E: <$url> STARTTLS: $@\n";
342 # do we even need credentials?
343 if (!defined($cred->{username}) &&
344 $mic->has_capability('AUTH=ANONYMOUS')) {
348 $cred->check_netrc unless defined $cred->{password};
349 $cred->fill; # may prompt user here
350 $mic->User($mic_arg->{User} = $cred->{username});
351 $mic->Password($mic_arg->{Password} = $cred->{password});
352 } else { # AUTH=ANONYMOUS
353 $mic->Authmechanism($mic_arg->{Authmechanism} = 'ANONYMOUS');
354 $mic->Authcallback($mic_arg->{Authcallback} = \&auth_anon_cb);
356 if ($mic->login && $mic->IsAuthenticated) {
357 # success! keep IMAPClient->new arg in case we get disconnected
358 $self->{mic_arg}->{uri_section($uri)} = $mic_arg;
360 warn "E: <$url> LOGIN: $@\n";
363 $cred->run($mic ? 'approve' : 'reject') if $cred;
367 sub imap_import_msg ($$$$) {
368 my ($self, $url, $uid, $raw) = @_;
369 # our target audience expects LF-only, save storage
370 $$raw =~ s/\r\n/\n/sg;
372 my $inboxes = $self->{imap}->{$url};
374 for my $ibx (@$inboxes) {
375 my $eml = PublicInbox::Eml->new($$raw);
376 my $x = import_eml($self, $ibx, $eml);
378 } elsif ($inboxes eq 'watchspam') {
379 my $eml = PublicInbox::Eml->new($raw);
380 my $arg = [ $self, $eml, "$url UID:$uid" ];
381 $self->{config}->each_inbox(\&remove_eml_i, $arg);
383 die "BUG: destination unknown $inboxes";
387 sub imap_fetch_all ($$$) {
388 my ($self, $mic, $url) = @_;
389 my $uri = PublicInbox::URIimap->new($url);
390 my $sec = uri_section($uri);
391 my $mbx = $uri->mailbox;
392 $mic->Clear(1); # trim results history
393 $mic->examine($mbx) or return "E: EXAMINE $mbx ($sec) failed: $!";
394 my ($r_uidval, $r_uidnext);
395 for ($mic->Results) {
396 /^\* OK \[UIDVALIDITY ([0-9]+)\].*/ and $r_uidval = $1;
397 /^\* OK \[UIDNEXT ([0-9]+)\].*/ and $r_uidnext = $1;
398 last if $r_uidval && $r_uidnext;
400 $r_uidval //= $mic->uidvalidity($mbx) //
401 return "E: $url cannot get UIDVALIDITY";
402 $r_uidnext //= $mic->uidnext($mbx) //
403 return "E: $url cannot get UIDNEXT";
404 my $itrk = PublicInbox::IMAPTracker->new($url);
405 my ($l_uidval, $l_uid) = $itrk->get_last;
406 $l_uidval //= $r_uidval; # first time
408 if ($l_uidval != $r_uidval) {
409 return "E: $url UIDVALIDITY mismatch\n".
410 "E: local=$l_uidval != remote=$r_uidval";
412 my $r_uid = $r_uidnext - 1;
413 if ($l_uid != 1 && $l_uid > $r_uid) {
414 return "E: $url local UID exceeds remote ($l_uid > $r_uid)\n".
415 "E: $url strangely, UIDVALIDLITY matches ($l_uidval)\n";
417 return if $l_uid >= $r_uid; # nothing to do
419 warn "I: $url fetching UID $l_uid:$r_uid\n";
420 $mic->Uid(1); # the default, we hope
421 my $bs = $self->{imap_opt}->{$sec}->{batch_size} // 1;
422 my $req = $mic->imap4rev1 ? 'BODY.PEEK[]' : 'RFC822.PEEK';
424 # TODO: FLAGS may be useful for personal use
428 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
429 local $SIG{__WARN__} = sub {
431 $warn_cb->("$url UID:$batch\n");
436 # I wish "UID FETCH $START:*" could work, but:
437 # 1) servers do not need to return results in any order
438 # 2) Mail::IMAPClient doesn't offer a streaming API
439 $uids = $mic->search("UID $l_uid:*") or
440 return "E: $url UID SEARCH $l_uid:* error: $!";
441 return if scalar(@$uids) == 0;
443 # RFC 3501 doesn't seem to indicate order of UID SEARCH
444 # responses, so sort it ourselves. Order matters so
445 # IMAPTracker can store the newest UID.
446 @$uids = sort { $a <=> $b } @$uids;
448 # Did we actually get new messages?
449 return if $uids->[0] < $l_uid;
451 $l_uid = $uids->[-1] + 1; # for next search
454 while (scalar @$uids) {
455 my @batch = splice(@$uids, 0, $bs);
456 $batch = join(',', @batch);
457 local $0 = "UID:$batch $mbx $sec";
458 my $r = $mic->fetch_hash($batch, $req);
459 unless ($r) { # network error?
460 $err = "E: $url UID FETCH $batch error: $!";
463 for my $uid (@batch) {
464 # messages get deleted, so holes appear
465 my $per_uid = delete $r->{$uid} // next;
466 my $raw = delete($per_uid->{$key}) // next;
467 imap_import_msg($self, $url, $uid, \$raw);
469 last if $self->{quit};
471 last if $self->{quit};
473 _done_for_now($self);
474 $itrk->update_last($r_uidval, $last_uid) if defined $last_uid;
475 } until ($err || $self->{quit});
479 sub imap_idle_once ($$$$) {
480 my ($self, $mic, $intvl, $url) = @_;
481 my $i = $intvl //= (29 * 60);
482 my $end = now() + $intvl;
483 warn "I: $url idling for ${intvl}s\n";
484 local $0 = "IDLE $0";
485 unless ($mic->idle) {
486 return if $self->{quit};
487 return "E: IDLE failed on $url: $!";
489 $self->{idle_mic} = $mic; # for ->quit
491 until ($self->{quit} || grep(/^\* [0-9]+ EXISTS/, @res) || $i <= 0) {
492 @res = $mic->idle_data($i);
495 delete $self->{idle_mic};
496 unless ($self->{quit}) {
497 $mic->IsConnected or return "E: IDLE disconnected on $url";
498 $mic->done or return "E: IDLE DONE failed on $url: $!";
503 # idles on a single URI
504 sub watch_imap_idle_1 ($$$) {
505 my ($self, $url, $intvl) = @_;
506 my $uri = PublicInbox::URIimap->new($url);
507 my $sec = uri_section($uri);
508 my $mic_arg = $self->{mic_arg}->{$sec} or
509 die "BUG: no Mail::IMAPClient->new arg for $sec";
511 local $0 = $uri->mailbox." $sec";
512 until ($self->{quit}) {
513 $mic //= 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);
539 sub imap_idle_reap { # PublicInbox::DS::dwaitpid callback
540 my ($self, $pid) = @_;
541 my $url_intvl = delete $self->{idle_pids}->{$pid} or
542 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
544 my ($url, $intvl) = @$url_intvl;
545 return if $self->{quit};
546 warn "W: PID=$pid on $url died: \$?=$?\n" if $?;
547 push @{$self->{idle_todo}}, $url_intvl;
548 PubicInbox::DS::requeue($self); # call ->event_step to respawn
551 sub imap_idle_fork ($$) {
552 my ($self, $url_intvl) = @_;
553 my ($url, $intvl) = @$url_intvl;
554 defined(my $pid = fork) or die "fork: $!";
556 watch_atfork_child($self);
557 watch_imap_idle_1($self, $url, $intvl);
560 $self->{idle_pids}->{$pid} = $url_intvl;
561 PublicInbox::DS::dwaitpid($pid, \&imap_idle_reap, $self);
566 return if $self->{quit};
567 my $idle_todo = $self->{idle_todo};
568 if ($idle_todo && @$idle_todo) {
569 watch_atfork_parent($self);
570 while (my $url_intvl = shift(@$idle_todo)) {
571 imap_idle_fork($self, $url_intvl);
574 goto(&fs_scan_step) if $self->{mdre};
577 sub watch_imap_fetch_all ($$) {
578 my ($self, $urls) = @_;
579 for my $url (@$urls) {
580 my $uri = PublicInbox::URIimap->new($url);
581 my $sec = uri_section($uri);
582 my $mic_arg = $self->{mic_arg}->{$sec} or
583 die "BUG: no Mail::IMAPClient->new arg for $sec";
584 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or next;
585 my $err = imap_fetch_all($self, $mic, $url);
586 last if $self->{quit};
587 warn $err, "\n" if $err;
591 sub watch_nntp_fetch_all ($$) {
592 my ($self, $urls) = @_;
593 for my $url (@$urls) {
594 my $uri = uri_new($url);
595 my $sec = uri_section($uri);
596 my $nn_arg = $self->{nn_arg}->{$sec} or
597 die "BUG: no Net::NNTP->new arg for $sec";
598 my $nntp_opt = $self->{nntp_opt}->{$sec};
599 my $nn = nn_new($nn_arg, $nntp_opt, $url);
601 warn "E: $url: \$!=$!\n";
604 last if $self->{quit};
605 if (my $postconn = $nntp_opt->{-postconn}) {
606 for my $m_arg (@$postconn) {
607 my ($method, @args) = @$m_arg;
608 $nn->$method(@args) and next;
609 warn "E: <$url> $method failed\n";
614 last if $self->{quit};
616 my $err = nntp_fetch_all($self, $nn, $url);
617 warn $err, "\n" if $err;
622 sub poll_fetch_fork ($) { # DS::add_timer callback
623 my ($self, $intvl, $urls) = @{$_[0]};
624 return if $self->{quit};
625 watch_atfork_parent($self);
626 defined(my $pid = fork) or die "fork: $!";
628 watch_atfork_child($self);
629 if ($urls->[0] =~ m!\Aimaps?://!i) {
630 watch_imap_fetch_all($self, $urls);
632 watch_nntp_fetch_all($self, $urls);
636 $self->{poll_pids}->{$pid} = [ $intvl, $urls ];
637 PublicInbox::DS::dwaitpid($pid, \&poll_fetch_reap, $self);
640 sub poll_fetch_reap { # PublicInbox::DS::dwaitpid callback
641 my ($self, $pid) = @_;
642 my $intvl_urls = delete $self->{poll_pids}->{$pid} or
643 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
644 return if $self->{quit};
645 my ($intvl, $urls) = @$intvl_urls;
647 warn "W: PID=$pid died: \$?=$?\n", map { "$_\n" } @$urls;
649 warn("I: will check $_ in ${intvl}s\n") for @$urls;
650 PublicInbox::DS::add_timer($intvl, \&poll_fetch_fork,
651 [$self, $intvl, $urls]);
654 sub watch_imap_init ($$) {
655 my ($self, $poll) = @_;
656 eval { require PublicInbox::IMAPClient } or
657 die "Mail::IMAPClient 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 = {}; # 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 for my $url (keys %{$self->{imap}}) {
673 my $uri = PublicInbox::URIimap->new($url);
674 my $sec = uri_section($uri);
675 my $mic = $mics->{$sec};
676 my $intvl = $self->{imap_opt}->{$sec}->{pollInterval};
677 if ($mic->has_capability('IDLE') && !$intvl) {
678 $intvl = $self->{imap_opt}->{$sec}->{idleInterval};
679 push @$idle, [ $url, $intvl // () ];
681 push @{$poll->{$intvl || 120}}, $url;
685 $self->{idle_todo} = $idle;
686 PublicInbox::DS::requeue($self); # ->event_step to fork
690 # flesh out common NNTP-specific data structures
691 sub nntp_common_init ($) {
693 my $cfg = $self->{config};
694 my $nn_args = {}; # scheme://authority => Net::NNTP->new arg
695 for my $url (sort keys %{$self->{nntp}}) {
696 my $sec = uri_section(uri_new($url));
698 # Debug and Timeout are passed to Net::NNTP->new
699 my $v = cfg_bool($cfg, 'nntp.Debug', $url);
700 $nn_args->{$sec}->{Debug} = $v if defined $v;
701 my $to = cfg_intvl($cfg, 'nntp.Timeout', $url);
702 $nn_args->{$sec}->{Timeout} = $to if $to;
704 # Net::NNTP post-connect commands
705 for my $k (qw(starttls compress)) {
706 $v = cfg_bool($cfg, "nntp.$k", $url) // next;
707 $self->{nntp_opt}->{$sec}->{$k} = $v;
711 for my $k (qw(pollInterval)) {
712 $to = cfg_intvl($cfg, "nntp.$k", $url) // next;
713 $self->{nntp_opt}->{$sec}->{$k} = $to;
719 # Net::NNTP doesn't support CAPABILITIES, yet
720 sub try_starttls ($) {
722 return if $host =~ /\.onion\z/s;
723 return if $host =~ /\A127\.[0-9]+\.[0-9]+\.[0-9]+\z/s;
724 return if $host eq '::1';
729 my ($nn_arg, $nntp_opt, $url) = @_;
730 my $nn = Net::NNTP->new(%$nn_arg) or die "E: <$url> new: $!\n";
732 # default to using STARTTLS if it's available, but allow
733 # it to be disabled for localhost/VPN users
734 if (!$nn_arg->{SSL} && $nn->can('starttls')) {
735 if (!defined($nntp_opt->{starttls}) &&
736 try_starttls($nn_arg->{Host})) {
737 # soft fail by default
738 $nn->starttls or warn <<"";
739 W: <$url> STARTTLS tried and failed (not requested)
741 } elsif ($nntp_opt->{starttls}) {
742 # hard fail if explicitly configured
743 $nn->starttls or die <<"";
744 E: <$url> STARTTLS requested and failed
747 } elsif ($nntp_opt->{starttls}) {
748 $nn->can('starttls') or
749 die "E: <$url> Net::NNTP too old for STARTTLS\n";
750 $nn->starttls or die <<"";
751 E: <$url> STARTTLS requested and failed
757 sub nn_for ($$$) { # nn = Net::NNTP
758 my ($self, $url, $nn_args) = @_;
759 my $uri = uri_new($url);
760 my $sec = uri_section($uri);
761 my $nntp_opt = $self->{nntp_opt}->{$sec} //= {};
762 my $host = $uri->host;
763 # Net::NNTP and Net::Netrc both mishandle `0', so we pass `127.0.0.1'
764 $host = '127.0.0.1' if $host eq '0';
767 if (defined(my $ui = $uri->userinfo)) {
768 require PublicInbox::GitCredential;
771 protocol => uri_scheme($uri),
773 }, 'PublicInbox::GitCredential';
774 ($u, $p) = split(/:/, $ui, 2);
775 ($cred->{username}, $cred->{password}) = ($u, $p);
776 $cred->check_netrc unless defined $p;
778 my $common = $nn_args->{$sec} // {};
782 SSL => $uri->secure, # snews == nntps
783 %$common, # may Debug ....
785 my $nn = nn_new($nn_arg, $nntp_opt, $url);
788 $cred->fill; # may prompt user here
789 if ($nn->authinfo($u, $p)) {
790 push @{$nntp_opt->{-postconn}}, [ 'authinfo', $u, $p ];
792 warn "E: <$url> AUTHINFO $u XXXX failed\n";
797 if ($nntp_opt->{compress}) {
798 # https://rt.cpan.org/Ticket/Display.html?id=129967
799 if ($nn->can('compress')) {
801 push @{$nntp_opt->{-postconn}}, [ 'compress' ];
803 warn "W: <$url> COMPRESS failed\n";
806 delete $nntp_opt->{compress};
808 W: <$url> COMPRESS not supported by Net::NNTP
809 W: see https://rt.cpan.org/Ticket/Display.html?id=129967 for updates
814 $self->{nn_arg}->{$sec} = $nn_arg;
815 $cred->run($nn ? 'approve' : 'reject') if $cred;
819 sub nntp_fetch_all ($$$) {
820 my ($self, $nn, $url) = @_;
821 my $uri = uri_new($url);
822 my ($group, $num_a, $num_b) = $uri->group;
823 my $sec = uri_section($uri);
824 my ($nr, $beg, $end) = $nn->group($group);
825 unless (defined($nr)) {
826 chomp(my $msg = $nn->message);
827 return "E: GROUP $group <$sec> $msg";
830 # IMAPTracker is also used for tracking NNTP, UID == article number
831 # LIST.ACTIVE can get the equivalent of UIDVALIDITY, but that's
832 # expensive. So we assume newsgroups don't change:
833 my $itrk = PublicInbox::IMAPTracker->new($url);
834 my (undef, $l_art) = $itrk->get_last;
835 $l_art //= $beg; # initial import
837 # allow users to specify articles to refetch
838 # cf. https://tools.ietf.org/id/draft-gilman-news-url-01.txt
839 # nntp://example.com/inbox.foo/$num_a-$num_b
840 $l_art = $num_a if defined($num_a) && $num_a < $l_art;
841 $end = $num_b if defined($num_b) && $num_b < $end;
843 return if $l_art >= $end; # nothing to do
846 warn "I: $url fetching ARTICLE $beg..$end\n";
847 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
849 local $SIG{__WARN__} = sub {
850 $warn_cb->("$url ", $art ? ("ARTICLE $art") : (), "\n", @_);
852 my $inboxes = $self->{nntp}->{$url};
855 last if $self->{quit};
857 my $raw = $nn->article($art);
858 unless (defined($raw)) {
859 my $msg = $nn->message;
860 if ($nn->code == 421) { # pseudo response from Net::Cmd
863 } else { # probably just a deleted message (spam)
868 s/\r\n/\n/ for @$raw;
869 $raw = join('', @$raw);
871 for my $ibx (@$inboxes) {
872 my $eml = PublicInbox::Eml->new($raw);
873 import_eml($self, $ibx, $eml);
875 } elsif ($inboxes eq 'watchspam') {
876 my $eml = PublicInbox::Eml->new(\$raw);
877 my $arg = [ $self, $eml, "$url ARTICLE $art" ];
878 $self->{config}->each_inbox(\&remove_eml_i, $arg);
880 die "BUG: destination unknown $inboxes";
884 $itrk->update_last(0, $last_art) if defined $last_art;
885 _done_for_now($self);
889 sub watch_nntp_init ($$) {
890 my ($self, $poll) = @_;
891 eval { require Net::NNTP } or
892 die "Net::NNTP is required for NNTP:\n$@\n";
893 eval { require PublicInbox::IMAPTracker } or
894 die "DBD::SQLite is required for NNTP\n:$@\n";
896 my $nn_args = nntp_common_init($self); # read args from config
898 # make sure we can connect and cache the credentials in memory
899 $self->{nn_arg} = {}; # schema://authority => Net::NNTP->new args
900 for my $url (sort keys %{$self->{nntp}}) {
901 nn_for($self, $url, $nn_args);
903 for my $url (keys %{$self->{nntp}}) {
904 my $uri = uri_new($url);
905 my $sec = uri_section($uri);
906 my $intvl = $self->{nntp_opt}->{$sec}->{pollInterval};
907 push @{$poll->{$intvl || 120}}, $url;
912 my ($self, $sig, $oldset) = @_;
913 $self->{oldset} = $oldset;
915 my $poll = {}; # intvl_seconds => [ url1, url2 ]
916 watch_imap_init($self, $poll) if $self->{imap};
917 watch_nntp_init($self, $poll) if $self->{nntp};
918 while (my ($intvl, $urls) = each %$poll) {
919 # poll all URLs for a given interval sequentially
920 PublicInbox::DS::add_timer(0, \&poll_fetch_fork,
921 [$self, $intvl, $urls]);
923 watch_fs_init($self) if $self->{mdre};
924 PublicInbox::DS->SetPostLoopCallback(sub {});
925 PublicInbox::DS->EventLoop until $self->{quit};
926 _done_for_now($self);
930 my ($self, $op) = @_;
931 push @{$self->{ops}}, $op;
932 PublicInbox::DS::requeue($self);
937 return if $self->{quit};
938 my $op = shift @{$self->{ops}};
940 # continue existing scan
942 my $opendirs = $self->{opendirs};
943 my @dirnames = keys %$opendirs;
944 foreach my $dir (@dirnames) {
945 my $dh = delete $opendirs->{$dir};
947 while (my $fn = readdir($dh)) {
948 _try_path($self, "$dir/$fn");
951 $opendirs->{$dir} = $dh if $n < 0;
953 if ($op && $op eq 'full') {
954 foreach my $dir (keys %{$self->{mdmap}}) {
955 next if $opendirs->{$dir}; # already in progress
956 my $ok = opendir(my $dh, $dir);
958 warn "failed to open $dir: $!\n";
962 while (my $fn = readdir($dh)) {
963 _try_path($self, "$dir/$fn");
966 $opendirs->{$dir} = $dh if $n < 0;
969 _done_for_now($self);
970 # do we have more work to do?
971 PublicInbox::DS::requeue($self) if keys %$opendirs;
975 my ($self, $op) = @_;
976 push @{$self->{ops}}, $op;
981 my ($self, $ibx) = @_;
982 my $importers = $self->{importers};
983 my $im = $importers->{"$ibx"} ||= $ibx->importer(0);
984 if (scalar(keys(%$importers)) > 2) {
985 delete $importers->{"$ibx"};
986 _done_for_now($self);
989 $importers->{"$ibx"} = $im;
992 # XXX consider sharing with V2Writable, this only requires read-only access
993 sub content_exists ($$) {
994 my ($ibx, $eml) = @_;
995 my $over = $ibx->over or return;
996 my $mids = mids($eml);
997 my $chash = content_hash($eml);
999 for my $mid (@$mids) {
1000 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
1001 my $cmp = $ibx->smsg_eml($smsg) or return;
1002 return 1 if $chash eq content_hash($cmp);
1011 my ($mime, $ibx) = @_;
1012 return if content_exists($ibx, $mime);
1014 if ($sc->spamcheck($mime, \$tmp)) {
1015 return PublicInbox::Eml->new(\$tmp);
1017 warn $mime->header('Message-ID')." failed spam check\n";
1023 $_[0] =~ s!\Amaildir:!! or return;
1030 my ($cur, $ws, $ibx) = @_;
1031 if ($ws && !ref($ws) && $ws eq 'watchspam') {
1033 E: $cur is a spam folder and cannot be used for `$ibx->{name}' input
1043 # URI::snews exists, URI::nntps does not, so use URI::snews
1044 $url =~ s!\Anntps://!snews://!i;
1050 require PublicInbox::URIimap;
1051 my $uri = PublicInbox::URIimap->new($url);
1052 $uri ? $uri->canonical->as_string : undef;
1055 my %IS_NNTP = (news => 1, snews => 1, nntp => 1);
1059 my $uri = uri_new($url);
1060 return unless $uri && $IS_NNTP{$uri->scheme} && $uri->group;
1061 $url = $uri->canonical->as_string;
1062 # nntps is IANA registered, snews is deprecated
1063 $url =~ s!\Asnews://!nntps://!;