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::Watch;
10 use PublicInbox::InboxWritable qw(eml_from_path warn_ignore_cb);
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 max_batch => 10, # avoid hogging locks for too long
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 my $im (values %{$self->{importers}}) {
128 next if !$im; # $im may be undef during cleanup
130 warn "$im->{ibx}->{name} ->done: $@\n" if $@;
134 sub remove_eml_i { # each_inbox callback
135 my ($ibx, $arg) = @_;
136 my ($self, $eml, $loc) = @$arg;
139 # try to avoid taking a lock or unnecessary spawning
140 my $im = $self->{importers}->{"$ibx"};
142 if ((!$im || !$im->active) && $ibx->over) {
143 if (content_exists($ibx, $eml)) {
145 } elsif (my $scrub = $ibx->filter($im)) {
146 $scrubbed = $scrub->scrub($eml, 1);
147 if ($scrubbed && $scrubbed != REJECT &&
148 !content_exists($ibx, $scrubbed)) {
156 $im //= _importer_for($self, $ibx); # may spawn fast-import
157 $im->remove($eml, 'spam');
159 my $scrub = $ibx->filter($im);
160 $scrub ? $scrub->scrub($eml, 1) : undef;
162 if ($scrubbed && $scrubbed != REJECT) {
163 $im->remove($scrubbed, 'spam');
167 warn "error removing spam at: $loc from $ibx->{name}: $@\n";
168 _done_for_now($self);
173 my ($self, $path) = @_;
174 # path must be marked as (S)een
175 $path =~ /:2,[A-R]*S[T-Za-z]*\z/ or return;
176 my $eml = eml_from_path($path) or return;
177 local $SIG{__WARN__} = warn_ignore_cb();
178 $self->{config}->each_inbox(\&remove_eml_i, [ $self, $eml, $path ]);
181 sub import_eml ($$$) {
182 my ($self, $ibx, $eml) = @_;
184 # any header match means it's eligible for the inbox:
185 if (my $watch_hdrs = $ibx->{-watchheaders}) {
187 for my $wh (@$watch_hdrs) {
188 my @v = $eml->header_raw($wh->[0]);
189 $ok = grep(/$wh->[1]/, @v) and last;
194 my $im = _importer_for($self, $ibx);
195 if (my $scrub = $ibx->filter($im)) {
196 my $scrubbed = $scrub->scrub($eml) or return;
197 $scrubbed == REJECT and return;
200 $im->add($eml, $self->{spamcheck});
203 warn "$ibx->{name} add failed: $@\n";
204 _done_for_now($self);
209 my ($self, $path) = @_;
210 return unless PublicInbox::InboxWritable::is_maildir_path($path);
211 if ($path !~ $self->{mdre}) {
212 warn "unrecognized path: $path\n";
215 my $inboxes = $self->{mdmap}->{$1};
217 warn "unmappable dir: $1\n";
220 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
221 local $SIG{__WARN__} = sub {
222 my $pfx = ($_[0] // '') =~ /^([A-Z]: )/g ? $1 : '';
223 $warn_cb->($pfx, "path: $path\n", @_);
225 if (!ref($inboxes) && $inboxes eq 'watchspam') {
226 return _remove_spam($self, $path);
228 foreach my $ibx (@$inboxes) {
229 my $eml = eml_from_path($path) or next;
230 import_eml($self, $ibx, $eml);
236 return unless $self->{quit};
238 # don't have reliable wakeups, keep signalling
240 for (qw(idle_pids poll_pids)) {
241 my $pids = $self->{$_} or next;
243 $done = undef if kill('QUIT', $_);
252 %{$self->{opendirs}} = ();
253 _done_for_now($self);
255 if (my $idle_mic = $self->{idle_mic}) {
256 eval { $idle_mic->done };
258 warn "IDLE DONE error: $@\n";
259 eval { $idle_mic->disconnect };
260 warn "IDLE LOGOUT error: $@\n" if $@;
265 sub watch_fs_init ($) {
268 delete $self->{done_timer};
269 _done_for_now($self);
272 _try_path($self, $_[0]->fullname);
273 $self->{done_timer} //= PublicInbox::DS::requeue($done);
275 require PublicInbox::DirIdle;
276 # inotify_create + EPOLL_CTL_ADD
277 PublicInbox::DirIdle->new([keys %{$self->{mdmap}}], $cb);
280 # avoid exposing deprecated "snews" to users.
281 my %SCHEME_MAP = ('snews' => 'nntps');
285 my $scheme = $uri->scheme;
286 $SCHEME_MAP{$scheme} // $scheme;
289 # returns the git config section name, e.g [imap "imaps://user@example.com"]
290 # without the mailbox, so we can share connections between different inboxes
291 sub uri_section ($) {
293 uri_scheme($uri) . '://' . $uri->authority;
296 sub cfg_intvl ($$$) {
297 my ($cfg, $key, $url) = @_;
298 my $v = $cfg->urlmatch($key, $url) // return;
299 $v =~ /\A[0-9]+(?:\.[0-9]+)?\z/s and return $v + 0;
300 if (ref($v) eq 'ARRAY') {
301 $v = join(', ', @$v);
302 warn "W: $key has multiple values: $v\nW: $key ignored\n";
304 warn "W: $key=$v is not a numeric value in seconds\n";
309 my ($cfg, $key, $url) = @_;
310 my $orig = $cfg->urlmatch($key, $url) // return;
311 my $bool = $cfg->git_bool($orig);
312 warn "W: $key=$orig for $url is not boolean\n" unless defined($bool);
316 # flesh out common IMAP-specific data structures
317 sub imap_common_init ($) {
319 my $cfg = $self->{config};
320 my $mic_args = {}; # scheme://authority => Mail:IMAPClient arg
321 for my $url (sort keys %{$self->{imap}}) {
322 my $uri = PublicInbox::URIimap->new($url);
323 my $sec = uri_section($uri);
324 for my $k (qw(Starttls Debug Compress)) {
325 my $bool = cfg_bool($cfg, "imap.$k", $url) // next;
326 $mic_args->{$sec}->{$k} = $bool;
328 my $to = cfg_intvl($cfg, 'imap.timeout', $url);
329 $mic_args->{$sec}->{Timeout} = $to if $to;
330 for my $k (qw(pollInterval idleInterval)) {
331 $to = cfg_intvl($cfg, "imap.$k", $url) // next;
332 $self->{imap_opt}->{$sec}->{$k} = $to;
334 my $k = 'imap.fetchBatchSize';
335 my $bs = $cfg->urlmatch($k, $url) // next;
336 if ($bs =~ /\A([0-9]+)\z/) {
337 $self->{imap_opt}->{$sec}->{batch_size} = $bs;
339 warn "$k=$bs is not an integer\n";
345 sub auth_anon_cb { '' }; # for Mail::IMAPClient::Authcallback
347 sub mic_for ($$$) { # mic = Mail::IMAPClient
348 my ($self, $url, $mic_args) = @_;
349 my $uri = PublicInbox::URIimap->new($url);
350 require PublicInbox::GitCredential;
353 protocol => $uri->scheme,
355 username => $uri->user,
356 password => $uri->password,
357 }, 'PublicInbox::GitCredential';
358 my $common = $mic_args->{uri_section($uri)} // {};
359 # IMAPClient and Net::Netrc both mishandles `0', so we pass `127.0.0.1'
360 my $host = $cred->{host};
361 $host = '127.0.0.1' if $host eq '0';
365 Ssl => $uri->scheme eq 'imaps',
366 Keepalive => 1, # SO_KEEPALIVE
367 %$common, # may set Starttls, Compress, Debug ....
369 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or
370 die "E: <$url> new: $@\n";
372 # default to using STARTTLS if it's available, but allow
373 # it to be disabled since I usually connect to localhost
374 if (!$mic_arg->{Ssl} && !defined($mic_arg->{Starttls}) &&
375 $mic->has_capability('STARTTLS') &&
376 $mic->can('starttls')) {
377 $mic->starttls or die "E: <$url> STARTTLS: $@\n";
380 # do we even need credentials?
381 if (!defined($cred->{username}) &&
382 $mic->has_capability('AUTH=ANONYMOUS')) {
386 $cred->check_netrc unless defined $cred->{password};
387 $cred->fill; # may prompt user here
388 $mic->User($mic_arg->{User} = $cred->{username});
389 $mic->Password($mic_arg->{Password} = $cred->{password});
390 } else { # AUTH=ANONYMOUS
391 $mic->Authmechanism($mic_arg->{Authmechanism} = 'ANONYMOUS');
392 $mic->Authcallback($mic_arg->{Authcallback} = \&auth_anon_cb);
394 if ($mic->login && $mic->IsAuthenticated) {
395 # success! keep IMAPClient->new arg in case we get disconnected
396 $self->{mic_arg}->{uri_section($uri)} = $mic_arg;
398 warn "E: <$url> LOGIN: $@\n";
401 $cred->run($mic ? 'approve' : 'reject') if $cred;
405 sub imap_import_msg ($$$$$) {
406 my ($self, $url, $uid, $raw, $flags) = @_;
407 # our target audience expects LF-only, save storage
408 $$raw =~ s/\r\n/\n/sg;
410 my $inboxes = $self->{imap}->{$url};
412 for my $ibx (@$inboxes) {
413 my $eml = PublicInbox::Eml->new($$raw);
414 my $x = import_eml($self, $ibx, $eml);
416 } elsif ($inboxes eq 'watchspam') {
417 # we don't remove unseen messages
418 if ($flags =~ /\\Seen\b/) {
419 local $SIG{__WARN__} = warn_ignore_cb();
420 my $eml = PublicInbox::Eml->new($raw);
421 my $arg = [ $self, $eml, "$url UID:$uid" ];
422 $self->{config}->each_inbox(\&remove_eml_i, $arg);
425 die "BUG: destination unknown $inboxes";
429 sub imap_fetch_all ($$$) {
430 my ($self, $mic, $url) = @_;
431 my $uri = PublicInbox::URIimap->new($url);
432 my $sec = uri_section($uri);
433 my $mbx = $uri->mailbox;
434 $mic->Clear(1); # trim results history
435 $mic->examine($mbx) or return "E: EXAMINE $mbx ($sec) failed: $!";
436 my ($r_uidval, $r_uidnext);
437 for ($mic->Results) {
438 /^\* OK \[UIDVALIDITY ([0-9]+)\].*/ and $r_uidval = $1;
439 /^\* OK \[UIDNEXT ([0-9]+)\].*/ and $r_uidnext = $1;
440 last if $r_uidval && $r_uidnext;
442 $r_uidval //= $mic->uidvalidity($mbx) //
443 return "E: $url cannot get UIDVALIDITY";
444 $r_uidnext //= $mic->uidnext($mbx) //
445 return "E: $url cannot get UIDNEXT";
446 my $itrk = PublicInbox::IMAPTracker->new($url);
447 my ($l_uidval, $l_uid) = $itrk->get_last;
448 $l_uidval //= $r_uidval; # first time
450 if ($l_uidval != $r_uidval) {
451 return "E: $url UIDVALIDITY mismatch\n".
452 "E: local=$l_uidval != remote=$r_uidval";
454 my $r_uid = $r_uidnext - 1;
455 if ($l_uid != 1 && $l_uid > $r_uid) {
456 return "E: $url local UID exceeds remote ($l_uid > $r_uid)\n".
457 "E: $url strangely, UIDVALIDLITY matches ($l_uidval)\n";
459 return if $l_uid >= $r_uid; # nothing to do
461 warn "I: $url fetching UID $l_uid:$r_uid\n";
462 $mic->Uid(1); # the default, we hope
463 my $bs = $self->{imap_opt}->{$sec}->{batch_size} // 1;
464 my $req = $mic->imap4rev1 ? 'BODY.PEEK[]' : 'RFC822.PEEK';
466 # TODO: FLAGS may be useful for personal use
470 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
471 local $SIG{__WARN__} = sub {
472 my $pfx = ($_[0] // '') =~ /^([A-Z]: )/g ? $1 : '';
474 $warn_cb->("$pfx$url UID:$batch\n", @_);
478 # I wish "UID FETCH $START:*" could work, but:
479 # 1) servers do not need to return results in any order
480 # 2) Mail::IMAPClient doesn't offer a streaming API
481 $uids = $mic->search("UID $l_uid:*") or
482 return "E: $url UID SEARCH $l_uid:* error: $!";
483 return if scalar(@$uids) == 0;
485 # RFC 3501 doesn't seem to indicate order of UID SEARCH
486 # responses, so sort it ourselves. Order matters so
487 # IMAPTracker can store the newest UID.
488 @$uids = sort { $a <=> $b } @$uids;
490 # Did we actually get new messages?
491 return if $uids->[0] < $l_uid;
493 $l_uid = $uids->[-1] + 1; # for next search
495 my $n = $self->{max_batch};
497 while (scalar @$uids) {
499 _done_for_now($self);
500 $itrk->update_last($r_uidval, $last_uid);
501 $n = $self->{max_batch};
503 my @batch = splice(@$uids, 0, $bs);
504 $batch = join(',', @batch);
505 local $0 = "UID:$batch $mbx $sec";
506 my $r = $mic->fetch_hash($batch, $req, 'FLAGS');
507 unless ($r) { # network error?
508 $err = "E: $url UID FETCH $batch error: $!";
511 for my $uid (@batch) {
512 # messages get deleted, so holes appear
513 my $per_uid = delete $r->{$uid} // next;
514 my $raw = delete($per_uid->{$key}) // next;
515 my $fl = $per_uid->{FLAGS} // '';
516 imap_import_msg($self, $url, $uid, \$raw, $fl);
518 last if $self->{quit};
520 last if $self->{quit};
522 _done_for_now($self);
523 $itrk->update_last($r_uidval, $last_uid);
524 } until ($err || $self->{quit});
528 sub imap_idle_once ($$$$) {
529 my ($self, $mic, $intvl, $url) = @_;
530 my $i = $intvl //= (29 * 60);
531 my $end = now() + $intvl;
532 warn "I: $url idling for ${intvl}s\n";
533 local $0 = "IDLE $0";
534 unless ($mic->idle) {
535 return if $self->{quit};
536 return "E: IDLE failed on $url: $!";
538 $self->{idle_mic} = $mic; # for ->quit
540 until ($self->{quit} || !$mic->IsConnected ||
541 grep(/^\* [0-9]+ EXISTS/, @res) || $i <= 0) {
542 @res = $mic->idle_data($i);
545 delete $self->{idle_mic};
546 unless ($self->{quit}) {
547 $mic->IsConnected or return "E: IDLE disconnected on $url";
548 $mic->done or return "E: IDLE DONE failed on $url: $!";
553 # idles on a single URI
554 sub watch_imap_idle_1 ($$$) {
555 my ($self, $url, $intvl) = @_;
556 my $uri = PublicInbox::URIimap->new($url);
557 my $sec = uri_section($uri);
558 my $mic_arg = $self->{mic_arg}->{$sec} or
559 die "BUG: no Mail::IMAPClient->new arg for $sec";
561 local $0 = $uri->mailbox." $sec";
562 until ($self->{quit}) {
563 $mic //= PublicInbox::IMAPClient->new(%$mic_arg);
565 if ($mic && $mic->IsConnected) {
566 $err = imap_fetch_all($self, $mic, $url);
567 $err //= imap_idle_once($self, $mic, $intvl, $url);
569 $err = "not connected: $!";
571 if ($err && !$self->{quit}) {
574 sleep 60 unless $self->{quit};
579 sub watch_atfork_child ($) {
581 delete $self->{idle_pids};
582 delete $self->{poll_pids};
583 delete $self->{opendirs};
584 PublicInbox::DS->Reset;
585 %SIG = (%SIG, %{$self->{sig}}, CHLD => 'DEFAULT');
586 PublicInbox::Sigfd::sig_setmask($self->{oldset});
589 sub watch_atfork_parent ($) {
591 _done_for_now($self);
594 sub imap_idle_requeue ($) { # DS::add_timer callback
595 my ($self, $url_intvl) = @{$_[0]};
596 return if $self->{quit};
597 push @{$self->{idle_todo}}, $url_intvl;
601 sub imap_idle_reap { # PublicInbox::DS::dwaitpid callback
602 my ($self, $pid) = @_;
603 my $url_intvl = delete $self->{idle_pids}->{$pid} or
604 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
606 my ($url, $intvl) = @$url_intvl;
607 return if $self->{quit};
608 warn "W: PID=$pid on $url died: \$?=$?\n" if $?;
609 PublicInbox::DS::add_timer(60,
610 \&imap_idle_requeue, [ $self, $url_intvl ]);
613 sub imap_idle_fork ($$) {
614 my ($self, $url_intvl) = @_;
615 my ($url, $intvl) = @$url_intvl;
616 defined(my $pid = fork) or die "fork: $!";
618 watch_atfork_child($self);
619 watch_imap_idle_1($self, $url, $intvl);
622 $self->{idle_pids}->{$pid} = $url_intvl;
623 PublicInbox::DS::dwaitpid($pid, \&imap_idle_reap, $self);
628 return if $self->{quit};
629 my $idle_todo = $self->{idle_todo};
630 if ($idle_todo && @$idle_todo) {
631 watch_atfork_parent($self);
632 while (my $url_intvl = shift(@$idle_todo)) {
633 imap_idle_fork($self, $url_intvl);
636 goto(&fs_scan_step) if $self->{mdre};
639 sub watch_imap_fetch_all ($$) {
640 my ($self, $urls) = @_;
641 for my $url (@$urls) {
642 my $uri = PublicInbox::URIimap->new($url);
643 my $sec = uri_section($uri);
644 my $mic_arg = $self->{mic_arg}->{$sec} or
645 die "BUG: no Mail::IMAPClient->new arg for $sec";
646 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or next;
647 my $err = imap_fetch_all($self, $mic, $url);
648 last if $self->{quit};
649 warn $err, "\n" if $err;
653 sub watch_nntp_fetch_all ($$) {
654 my ($self, $urls) = @_;
655 for my $url (@$urls) {
656 my $uri = uri_new($url);
657 my $sec = uri_section($uri);
658 my $nn_arg = $self->{nn_arg}->{$sec} or
659 die "BUG: no Net::NNTP->new arg for $sec";
660 my $nntp_opt = $self->{nntp_opt}->{$sec};
661 my $nn = nn_new($nn_arg, $nntp_opt, $url);
663 warn "E: $url: \$!=$!\n";
666 last if $self->{quit};
667 if (my $postconn = $nntp_opt->{-postconn}) {
668 for my $m_arg (@$postconn) {
669 my ($method, @args) = @$m_arg;
670 $nn->$method(@args) and next;
671 warn "E: <$url> $method failed\n";
676 last if $self->{quit};
678 my $err = nntp_fetch_all($self, $nn, $url);
679 warn $err, "\n" if $err;
684 sub poll_fetch_fork ($) { # DS::add_timer callback
685 my ($self, $intvl, $urls) = @{$_[0]};
686 return if $self->{quit};
687 watch_atfork_parent($self);
688 defined(my $pid = fork) or die "fork: $!";
690 watch_atfork_child($self);
691 if ($urls->[0] =~ m!\Aimaps?://!i) {
692 watch_imap_fetch_all($self, $urls);
694 watch_nntp_fetch_all($self, $urls);
698 $self->{poll_pids}->{$pid} = [ $intvl, $urls ];
699 PublicInbox::DS::dwaitpid($pid, \&poll_fetch_reap, $self);
702 sub poll_fetch_reap { # PublicInbox::DS::dwaitpid callback
703 my ($self, $pid) = @_;
704 my $intvl_urls = delete $self->{poll_pids}->{$pid} or
705 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
706 return if $self->{quit};
707 my ($intvl, $urls) = @$intvl_urls;
709 warn "W: PID=$pid died: \$?=$?\n", map { "$_\n" } @$urls;
711 warn("I: will check $_ in ${intvl}s\n") for @$urls;
712 PublicInbox::DS::add_timer($intvl, \&poll_fetch_fork,
713 [$self, $intvl, $urls]);
716 sub watch_imap_init ($$) {
717 my ($self, $poll) = @_;
718 eval { require PublicInbox::IMAPClient } or
719 die "Mail::IMAPClient is required for IMAP:\n$@\n";
720 eval { require PublicInbox::IMAPTracker } or
721 die "DBD::SQLite is required for IMAP\n:$@\n";
723 my $mic_args = imap_common_init($self); # read args from config
725 # make sure we can connect and cache the credentials in memory
726 $self->{mic_arg} = {}; # schema://authority => IMAPClient->new args
727 my $mics = {}; # schema://authority => IMAPClient obj
728 for my $url (sort keys %{$self->{imap}}) {
729 my $uri = PublicInbox::URIimap->new($url);
730 $mics->{uri_section($uri)} //= mic_for($self, $url, $mic_args);
733 my $idle = []; # [ [ url1, intvl1 ], [url2, intvl2] ]
734 for my $url (keys %{$self->{imap}}) {
735 my $uri = PublicInbox::URIimap->new($url);
736 my $sec = uri_section($uri);
737 my $mic = $mics->{$sec};
738 my $intvl = $self->{imap_opt}->{$sec}->{pollInterval};
739 if ($mic->has_capability('IDLE') && !$intvl) {
740 $intvl = $self->{imap_opt}->{$sec}->{idleInterval};
741 push @$idle, [ $url, $intvl // () ];
743 push @{$poll->{$intvl || 120}}, $url;
747 $self->{idle_todo} = $idle;
748 PublicInbox::DS::requeue($self); # ->event_step to fork
752 # flesh out common NNTP-specific data structures
753 sub nntp_common_init ($) {
755 my $cfg = $self->{config};
756 my $nn_args = {}; # scheme://authority => Net::NNTP->new arg
757 for my $url (sort keys %{$self->{nntp}}) {
758 my $sec = uri_section(uri_new($url));
760 # Debug and Timeout are passed to Net::NNTP->new
761 my $v = cfg_bool($cfg, 'nntp.Debug', $url);
762 $nn_args->{$sec}->{Debug} = $v if defined $v;
763 my $to = cfg_intvl($cfg, 'nntp.Timeout', $url);
764 $nn_args->{$sec}->{Timeout} = $to if $to;
766 # Net::NNTP post-connect commands
767 for my $k (qw(starttls compress)) {
768 $v = cfg_bool($cfg, "nntp.$k", $url) // next;
769 $self->{nntp_opt}->{$sec}->{$k} = $v;
773 for my $k (qw(pollInterval)) {
774 $to = cfg_intvl($cfg, "nntp.$k", $url) // next;
775 $self->{nntp_opt}->{$sec}->{$k} = $to;
781 # Net::NNTP doesn't support CAPABILITIES, yet
782 sub try_starttls ($) {
784 return if $host =~ /\.onion\z/s;
785 return if $host =~ /\A127\.[0-9]+\.[0-9]+\.[0-9]+\z/s;
786 return if $host eq '::1';
791 my ($nn_arg, $nntp_opt, $url) = @_;
792 my $nn = Net::NNTP->new(%$nn_arg) or die "E: <$url> new: $!\n";
794 # default to using STARTTLS if it's available, but allow
795 # it to be disabled for localhost/VPN users
796 if (!$nn_arg->{SSL} && $nn->can('starttls')) {
797 if (!defined($nntp_opt->{starttls}) &&
798 try_starttls($nn_arg->{Host})) {
799 # soft fail by default
800 $nn->starttls or warn <<"";
801 W: <$url> STARTTLS tried and failed (not requested)
803 } elsif ($nntp_opt->{starttls}) {
804 # hard fail if explicitly configured
805 $nn->starttls or die <<"";
806 E: <$url> STARTTLS requested and failed
809 } elsif ($nntp_opt->{starttls}) {
810 $nn->can('starttls') or
811 die "E: <$url> Net::NNTP too old for STARTTLS\n";
812 $nn->starttls or die <<"";
813 E: <$url> STARTTLS requested and failed
819 sub nn_for ($$$) { # nn = Net::NNTP
820 my ($self, $url, $nn_args) = @_;
821 my $uri = uri_new($url);
822 my $sec = uri_section($uri);
823 my $nntp_opt = $self->{nntp_opt}->{$sec} //= {};
824 my $host = $uri->host;
825 # Net::NNTP and Net::Netrc both mishandle `0', so we pass `127.0.0.1'
826 $host = '127.0.0.1' if $host eq '0';
829 if (defined(my $ui = $uri->userinfo)) {
830 require PublicInbox::GitCredential;
833 protocol => uri_scheme($uri),
835 }, 'PublicInbox::GitCredential';
836 ($u, $p) = split(/:/, $ui, 2);
837 ($cred->{username}, $cred->{password}) = ($u, $p);
838 $cred->check_netrc unless defined $p;
840 my $common = $nn_args->{$sec} // {};
844 SSL => $uri->secure, # snews == nntps
845 %$common, # may Debug ....
847 my $nn = nn_new($nn_arg, $nntp_opt, $url);
850 $cred->fill; # may prompt user here
851 if ($nn->authinfo($u, $p)) {
852 push @{$nntp_opt->{-postconn}}, [ 'authinfo', $u, $p ];
854 warn "E: <$url> AUTHINFO $u XXXX failed\n";
859 if ($nntp_opt->{compress}) {
860 # https://rt.cpan.org/Ticket/Display.html?id=129967
861 if ($nn->can('compress')) {
863 push @{$nntp_opt->{-postconn}}, [ 'compress' ];
865 warn "W: <$url> COMPRESS failed\n";
868 delete $nntp_opt->{compress};
870 W: <$url> COMPRESS not supported by Net::NNTP
871 W: see https://rt.cpan.org/Ticket/Display.html?id=129967 for updates
876 $self->{nn_arg}->{$sec} = $nn_arg;
877 $cred->run($nn ? 'approve' : 'reject') if $cred;
881 sub nntp_fetch_all ($$$) {
882 my ($self, $nn, $url) = @_;
883 my $uri = uri_new($url);
884 my ($group, $num_a, $num_b) = $uri->group;
885 my $sec = uri_section($uri);
886 my ($nr, $beg, $end) = $nn->group($group);
887 unless (defined($nr)) {
888 chomp(my $msg = $nn->message);
889 return "E: GROUP $group <$sec> $msg";
892 # IMAPTracker is also used for tracking NNTP, UID == article number
893 # LIST.ACTIVE can get the equivalent of UIDVALIDITY, but that's
894 # expensive. So we assume newsgroups don't change:
895 my $itrk = PublicInbox::IMAPTracker->new($url);
896 my (undef, $l_art) = $itrk->get_last;
897 $l_art //= $beg; # initial import
899 # allow users to specify articles to refetch
900 # cf. https://tools.ietf.org/id/draft-gilman-news-url-01.txt
901 # nntp://example.com/inbox.foo/$num_a-$num_b
902 $l_art = $num_a if defined($num_a) && $num_a < $l_art;
903 $end = $num_b if defined($num_b) && $num_b < $end;
905 return if $l_art >= $end; # nothing to do
908 warn "I: $url fetching ARTICLE $beg..$end\n";
909 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
911 local $SIG{__WARN__} = sub {
912 my $pfx = ($_[0] // '') =~ /^([A-Z]: )/g ? $1 : '';
913 $warn_cb->("$pfx$url ", $art ? ("ARTICLE $art") : (), "\n", @_);
915 my $inboxes = $self->{nntp}->{$url};
917 my $n = $self->{max_batch};
919 last if $self->{quit};
922 _done_for_now($self);
923 $itrk->update_last(0, $last_art);
924 $n = $self->{max_batch};
926 my $raw = $nn->article($art);
927 unless (defined($raw)) {
928 my $msg = $nn->message;
929 if ($nn->code == 421) { # pseudo response from Net::Cmd
932 } else { # probably just a deleted message (spam)
937 s/\r\n/\n/ for @$raw;
938 $raw = join('', @$raw);
940 for my $ibx (@$inboxes) {
941 my $eml = PublicInbox::Eml->new($raw);
942 import_eml($self, $ibx, $eml);
944 } elsif ($inboxes eq 'watchspam') {
945 my $eml = PublicInbox::Eml->new(\$raw);
946 my $arg = [ $self, $eml, "$url ARTICLE $art" ];
947 $self->{config}->each_inbox(\&remove_eml_i, $arg);
949 die "BUG: destination unknown $inboxes";
953 _done_for_now($self);
954 $itrk->update_last(0, $last_art);
958 sub watch_nntp_init ($$) {
959 my ($self, $poll) = @_;
960 eval { require Net::NNTP } or
961 die "Net::NNTP is required for NNTP:\n$@\n";
962 eval { require PublicInbox::IMAPTracker } or
963 die "DBD::SQLite is required for NNTP\n:$@\n";
965 my $nn_args = nntp_common_init($self); # read args from config
967 # make sure we can connect and cache the credentials in memory
968 $self->{nn_arg} = {}; # schema://authority => Net::NNTP->new args
969 for my $url (sort keys %{$self->{nntp}}) {
970 nn_for($self, $url, $nn_args);
972 for my $url (keys %{$self->{nntp}}) {
973 my $uri = uri_new($url);
974 my $sec = uri_section($uri);
975 my $intvl = $self->{nntp_opt}->{$sec}->{pollInterval};
976 push @{$poll->{$intvl || 120}}, $url;
981 my ($self, $sig, $oldset) = @_;
982 $self->{oldset} = $oldset;
984 my $poll = {}; # intvl_seconds => [ url1, url2 ]
985 watch_imap_init($self, $poll) if $self->{imap};
986 watch_nntp_init($self, $poll) if $self->{nntp};
987 while (my ($intvl, $urls) = each %$poll) {
988 # poll all URLs for a given interval sequentially
989 PublicInbox::DS::add_timer(0, \&poll_fetch_fork,
990 [$self, $intvl, $urls]);
992 watch_fs_init($self) if $self->{mdre};
993 PublicInbox::DS->SetPostLoopCallback(sub { !$self->quit_done });
994 PublicInbox::DS->EventLoop;
995 _done_for_now($self);
999 my ($self, $op) = @_;
1000 push @{$self->{ops}}, $op;
1001 PublicInbox::DS::requeue($self);
1006 return if $self->{quit};
1007 my $op = shift @{$self->{ops}};
1008 local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
1010 # continue existing scan
1011 my $opendirs = $self->{opendirs};
1012 my @dirnames = keys %$opendirs;
1013 foreach my $dir (@dirnames) {
1014 my $dh = delete $opendirs->{$dir};
1015 my $n = $self->{max_batch};
1016 while (my $fn = readdir($dh)) {
1017 _try_path($self, "$dir/$fn");
1020 $opendirs->{$dir} = $dh if $n < 0;
1022 if ($op && $op eq 'full') {
1023 foreach my $dir (keys %{$self->{mdmap}}) {
1024 next if $opendirs->{$dir}; # already in progress
1025 my $ok = opendir(my $dh, $dir);
1027 warn "failed to open $dir: $!\n";
1030 my $n = $self->{max_batch};
1031 while (my $fn = readdir($dh)) {
1032 _try_path($self, "$dir/$fn");
1035 $opendirs->{$dir} = $dh if $n < 0;
1038 _done_for_now($self);
1039 # do we have more work to do?
1040 PublicInbox::DS::requeue($self) if keys %$opendirs;
1044 my ($self, $op) = @_;
1045 push @{$self->{ops}}, $op;
1050 my ($self, $ibx) = @_;
1051 my $importers = $self->{importers};
1052 my $im = $importers->{"$ibx"} ||= $ibx->importer(0);
1053 if (scalar(keys(%$importers)) > 2) {
1054 delete $importers->{"$ibx"};
1055 _done_for_now($self);
1058 $importers->{"$ibx"} = $im;
1061 # XXX consider sharing with V2Writable, this only requires read-only access
1062 sub content_exists ($$) {
1063 my ($ibx, $eml) = @_;
1064 my $over = $ibx->over or return;
1065 my $mids = mids($eml);
1066 my $chash = content_hash($eml);
1068 for my $mid (@$mids) {
1069 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
1070 my $cmp = $ibx->smsg_eml($smsg) or return;
1071 return 1 if $chash eq content_hash($cmp);
1080 my ($mime, $ibx) = @_;
1081 return if content_exists($ibx, $mime);
1083 if ($sc->spamcheck($mime, \$tmp)) {
1084 return PublicInbox::Eml->new(\$tmp);
1086 warn $mime->header('Message-ID')." failed spam check\n";
1092 $_[0] =~ s!\Amaildir:!! or return;
1099 my ($cur, $ws, $ibx) = @_;
1100 if ($ws && !ref($ws) && $ws eq 'watchspam') {
1102 E: $cur is a spam folder and cannot be used for `$ibx->{name}' input
1112 # URI::snews exists, URI::nntps does not, so use URI::snews
1113 $url =~ s!\Anntps://!snews://!i;
1119 require PublicInbox::URIimap;
1120 my $uri = PublicInbox::URIimap->new($url);
1121 $uri ? $uri->canonical->as_string : undef;
1124 my %IS_NNTP = (news => 1, snews => 1, nntp => 1);
1128 my $uri = uri_new($url);
1129 return unless $uri && $IS_NNTP{$uri->scheme} && $uri->group;
1130 $url = $uri->canonical->as_string;
1131 # nntps is IANA registered, snews is deprecated
1132 $url =~ s!\Asnews://!nntps://!;