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);
17 use PublicInbox::EOFpipe;
18 use POSIX qw(_exit WNOHANG);
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 max_batch => 10, # avoid hogging locks for too long
113 spamcheck => $spamcheck,
117 imap => scalar keys %imap ? \%imap : undef,
118 nntp => scalar keys %nntp? \%nntp : undef,
120 opendirs => {}, # dirname => dirhandle (in progress scans)
121 ops => [], # 'quit', 'full'
127 local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
128 for my $im (values %{$self->{importers}}) {
129 next if !$im; # $im may be undef during cleanup
131 warn "$im->{ibx}->{name} ->done: $@\n" if $@;
135 sub remove_eml_i { # each_inbox callback
136 my ($ibx, $arg) = @_;
137 my ($self, $eml, $loc) = @$arg;
140 # try to avoid taking a lock or unnecessary spawning
141 my $im = $self->{importers}->{"$ibx"};
143 if ((!$im || !$im->active) && $ibx->over) {
144 if (content_exists($ibx, $eml)) {
146 } elsif (my $scrub = $ibx->filter($im)) {
147 $scrubbed = $scrub->scrub($eml, 1);
148 if ($scrubbed && $scrubbed != REJECT &&
149 !content_exists($ibx, $scrubbed)) {
157 $im //= _importer_for($self, $ibx); # may spawn fast-import
158 $im->remove($eml, 'spam');
160 my $scrub = $ibx->filter($im);
161 $scrub ? $scrub->scrub($eml, 1) : undef;
163 if ($scrubbed && $scrubbed != REJECT) {
164 $im->remove($scrubbed, 'spam');
168 warn "error removing spam at: $loc from $ibx->{name}: $@\n";
169 _done_for_now($self);
174 my ($self, $path) = @_;
175 # path must be marked as (S)een
176 $path =~ /:2,[A-R]*S[T-Za-z]*\z/ or return;
177 my $eml = eml_from_path($path) or return;
178 local $SIG{__WARN__} = warn_ignore_cb();
179 $self->{config}->each_inbox(\&remove_eml_i, [ $self, $eml, $path ]);
182 sub import_eml ($$$) {
183 my ($self, $ibx, $eml) = @_;
185 # any header match means it's eligible for the inbox:
186 if (my $watch_hdrs = $ibx->{-watchheaders}) {
188 for my $wh (@$watch_hdrs) {
189 my @v = $eml->header_raw($wh->[0]);
190 $ok = grep(/$wh->[1]/, @v) and last;
195 my $im = _importer_for($self, $ibx);
196 if (my $scrub = $ibx->filter($im)) {
197 my $scrubbed = $scrub->scrub($eml) or return;
198 $scrubbed == REJECT and return;
201 $im->add($eml, $self->{spamcheck});
204 warn "$ibx->{name} add failed: $@\n";
205 _done_for_now($self);
210 my ($self, $path) = @_;
211 return unless PublicInbox::InboxWritable::is_maildir_path($path);
212 if ($path !~ $self->{mdre}) {
213 warn "unrecognized path: $path\n";
216 my $inboxes = $self->{mdmap}->{$1};
218 warn "unmappable dir: $1\n";
221 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
222 local $SIG{__WARN__} = sub {
223 my $pfx = ($_[0] // '') =~ /^([A-Z]: )/g ? $1 : '';
224 $warn_cb->($pfx, "path: $path\n", @_);
226 if (!ref($inboxes) && $inboxes eq 'watchspam') {
227 return _remove_spam($self, $path);
229 foreach my $ibx (@$inboxes) {
230 my $eml = eml_from_path($path) or next;
231 import_eml($self, $ibx, $eml);
237 return unless $self->{quit};
239 # don't have reliable wakeups, keep signalling
241 for (qw(idle_pids poll_pids)) {
242 my $pids = $self->{$_} or next;
244 $done = undef if kill('QUIT', $_);
253 %{$self->{opendirs}} = ();
254 _done_for_now($self);
256 if (my $idle_mic = $self->{idle_mic}) {
257 eval { $idle_mic->done };
259 warn "IDLE DONE error: $@\n";
260 eval { $idle_mic->disconnect };
261 warn "IDLE LOGOUT error: $@\n" if $@;
266 sub watch_fs_init ($) {
269 delete $self->{done_timer};
270 _done_for_now($self);
272 my $cb = sub { # called by PublicInbox::DirIdle::event_step
273 _try_path($self, $_[0]->fullname);
274 $self->{done_timer} //= PublicInbox::DS::requeue($done);
276 require PublicInbox::DirIdle;
277 # inotify_create + EPOLL_CTL_ADD
278 PublicInbox::DirIdle->new([keys %{$self->{mdmap}}], $cb);
281 # avoid exposing deprecated "snews" to users.
282 my %SCHEME_MAP = ('snews' => 'nntps');
286 my $scheme = $uri->scheme;
287 $SCHEME_MAP{$scheme} // $scheme;
290 # returns the git config section name, e.g [imap "imaps://user@example.com"]
291 # without the mailbox, so we can share connections between different inboxes
292 sub uri_section ($) {
294 uri_scheme($uri) . '://' . $uri->authority;
297 sub cfg_intvl ($$$) {
298 my ($cfg, $key, $url) = @_;
299 my $v = $cfg->urlmatch($key, $url) // return;
300 $v =~ /\A[0-9]+(?:\.[0-9]+)?\z/s and return $v + 0;
301 if (ref($v) eq 'ARRAY') {
302 $v = join(', ', @$v);
303 warn "W: $key has multiple values: $v\nW: $key ignored\n";
305 warn "W: $key=$v is not a numeric value in seconds\n";
310 my ($cfg, $key, $url) = @_;
311 my $orig = $cfg->urlmatch($key, $url) // return;
312 my $bool = $cfg->git_bool($orig);
313 warn "W: $key=$orig for $url is not boolean\n" unless defined($bool);
317 # flesh out common IMAP-specific data structures
318 sub imap_common_init ($) {
320 my $cfg = $self->{config};
321 my $mic_args = {}; # scheme://authority => Mail:IMAPClient arg
322 for my $url (sort keys %{$self->{imap}}) {
323 my $uri = PublicInbox::URIimap->new($url);
324 my $sec = uri_section($uri);
325 for my $k (qw(Starttls Debug Compress)) {
326 my $bool = cfg_bool($cfg, "imap.$k", $url) // next;
327 $mic_args->{$sec}->{$k} = $bool;
329 my $to = cfg_intvl($cfg, 'imap.timeout', $url);
330 $mic_args->{$sec}->{Timeout} = $to if $to;
331 for my $k (qw(pollInterval idleInterval)) {
332 $to = cfg_intvl($cfg, "imap.$k", $url) // next;
333 $self->{imap_opt}->{$sec}->{$k} = $to;
335 my $k = 'imap.fetchBatchSize';
336 my $bs = $cfg->urlmatch($k, $url) // next;
337 if ($bs =~ /\A([0-9]+)\z/) {
338 $self->{imap_opt}->{$sec}->{batch_size} = $bs;
340 warn "$k=$bs is not an integer\n";
346 sub auth_anon_cb { '' }; # for Mail::IMAPClient::Authcallback
348 sub mic_for ($$$) { # mic = Mail::IMAPClient
349 my ($self, $url, $mic_args) = @_;
350 my $uri = PublicInbox::URIimap->new($url);
351 require PublicInbox::GitCredential;
354 protocol => $uri->scheme,
356 username => $uri->user,
357 password => $uri->password,
358 }, 'PublicInbox::GitCredential';
359 my $common = $mic_args->{uri_section($uri)} // {};
360 # IMAPClient and Net::Netrc both mishandles `0', so we pass `127.0.0.1'
361 my $host = $cred->{host};
362 $host = '127.0.0.1' if $host eq '0';
366 Ssl => $uri->scheme eq 'imaps',
367 Keepalive => 1, # SO_KEEPALIVE
368 %$common, # may set Starttls, Compress, Debug ....
370 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or
371 die "E: <$url> new: $@\n";
373 # default to using STARTTLS if it's available, but allow
374 # it to be disabled since I usually connect to localhost
375 if (!$mic_arg->{Ssl} && !defined($mic_arg->{Starttls}) &&
376 $mic->has_capability('STARTTLS') &&
377 $mic->can('starttls')) {
378 $mic->starttls or die "E: <$url> STARTTLS: $@\n";
381 # do we even need credentials?
382 if (!defined($cred->{username}) &&
383 $mic->has_capability('AUTH=ANONYMOUS')) {
387 $cred->check_netrc unless defined $cred->{password};
388 $cred->fill; # may prompt user here
389 $mic->User($mic_arg->{User} = $cred->{username});
390 $mic->Password($mic_arg->{Password} = $cred->{password});
391 } else { # AUTH=ANONYMOUS
392 $mic->Authmechanism($mic_arg->{Authmechanism} = 'ANONYMOUS');
393 $mic->Authcallback($mic_arg->{Authcallback} = \&auth_anon_cb);
395 if ($mic->login && $mic->IsAuthenticated) {
396 # success! keep IMAPClient->new arg in case we get disconnected
397 $self->{mic_arg}->{uri_section($uri)} = $mic_arg;
399 warn "E: <$url> LOGIN: $@\n";
402 $cred->run($mic ? 'approve' : 'reject') if $cred;
406 sub imap_import_msg ($$$$$) {
407 my ($self, $url, $uid, $raw, $flags) = @_;
408 # our target audience expects LF-only, save storage
409 $$raw =~ s/\r\n/\n/sg;
411 my $inboxes = $self->{imap}->{$url};
413 for my $ibx (@$inboxes) {
414 my $eml = PublicInbox::Eml->new($$raw);
415 import_eml($self, $ibx, $eml);
417 } elsif ($inboxes eq 'watchspam') {
418 # we don't remove unseen messages
419 if ($flags =~ /\\Seen\b/) {
420 local $SIG{__WARN__} = warn_ignore_cb();
421 my $eml = PublicInbox::Eml->new($raw);
422 my $arg = [ $self, $eml, "$url UID:$uid" ];
423 $self->{config}->each_inbox(\&remove_eml_i, $arg);
426 die "BUG: destination unknown $inboxes";
430 sub imap_fetch_all ($$$) {
431 my ($self, $mic, $url) = @_;
432 my $uri = PublicInbox::URIimap->new($url);
433 my $sec = uri_section($uri);
434 my $mbx = $uri->mailbox;
435 $mic->Clear(1); # trim results history
436 $mic->examine($mbx) or return "E: EXAMINE $mbx ($sec) failed: $!";
437 my ($r_uidval, $r_uidnext);
438 for ($mic->Results) {
439 /^\* OK \[UIDVALIDITY ([0-9]+)\].*/ and $r_uidval = $1;
440 /^\* OK \[UIDNEXT ([0-9]+)\].*/ and $r_uidnext = $1;
441 last if $r_uidval && $r_uidnext;
443 $r_uidval //= $mic->uidvalidity($mbx) //
444 return "E: $url cannot get UIDVALIDITY";
445 $r_uidnext //= $mic->uidnext($mbx) //
446 return "E: $url cannot get UIDNEXT";
447 my $itrk = PublicInbox::IMAPTracker->new($url);
448 my ($l_uidval, $l_uid) = $itrk->get_last;
449 $l_uidval //= $r_uidval; # first time
451 if ($l_uidval != $r_uidval) {
452 return "E: $url UIDVALIDITY mismatch\n".
453 "E: local=$l_uidval != remote=$r_uidval";
455 my $r_uid = $r_uidnext - 1;
456 if ($l_uid != 1 && $l_uid > $r_uid) {
457 return "E: $url local UID exceeds remote ($l_uid > $r_uid)\n".
458 "E: $url strangely, UIDVALIDLITY matches ($l_uidval)\n";
460 return if $l_uid >= $r_uid; # nothing to do
462 warn "I: $url fetching UID $l_uid:$r_uid\n";
463 $mic->Uid(1); # the default, we hope
464 my $bs = $self->{imap_opt}->{$sec}->{batch_size} // 1;
465 my $req = $mic->imap4rev1 ? 'BODY.PEEK[]' : 'RFC822.PEEK';
467 # TODO: FLAGS may be useful for personal use
471 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
472 local $SIG{__WARN__} = sub {
473 my $pfx = ($_[0] // '') =~ /^([A-Z]: )/g ? $1 : '';
475 $warn_cb->("$pfx$url UID:$batch\n", @_);
479 # I wish "UID FETCH $START:*" could work, but:
480 # 1) servers do not need to return results in any order
481 # 2) Mail::IMAPClient doesn't offer a streaming API
482 $uids = $mic->search("UID $l_uid:*") or
483 return "E: $url UID SEARCH $l_uid:* error: $!";
484 return if scalar(@$uids) == 0;
486 # RFC 3501 doesn't seem to indicate order of UID SEARCH
487 # responses, so sort it ourselves. Order matters so
488 # IMAPTracker can store the newest UID.
489 @$uids = sort { $a <=> $b } @$uids;
491 # Did we actually get new messages?
492 return if $uids->[0] < $l_uid;
494 $l_uid = $uids->[-1] + 1; # for next search
496 my $n = $self->{max_batch};
498 while (scalar @$uids) {
500 _done_for_now($self);
501 $itrk->update_last($r_uidval, $last_uid);
502 $n = $self->{max_batch};
504 my @batch = splice(@$uids, 0, $bs);
505 $batch = join(',', @batch);
506 local $0 = "UID:$batch $mbx $sec";
507 my $r = $mic->fetch_hash($batch, $req, 'FLAGS');
508 unless ($r) { # network error?
509 $err = "E: $url UID FETCH $batch error: $!";
512 for my $uid (@batch) {
513 # messages get deleted, so holes appear
514 my $per_uid = delete $r->{$uid} // next;
515 my $raw = delete($per_uid->{$key}) // next;
516 my $fl = $per_uid->{FLAGS} // '';
517 imap_import_msg($self, $url, $uid, \$raw, $fl);
519 last if $self->{quit};
521 last if $self->{quit};
523 _done_for_now($self);
524 $itrk->update_last($r_uidval, $last_uid);
525 } until ($err || $self->{quit});
529 sub imap_idle_once ($$$$) {
530 my ($self, $mic, $intvl, $url) = @_;
531 my $i = $intvl //= (29 * 60);
532 my $end = now() + $intvl;
533 warn "I: $url idling for ${intvl}s\n";
534 local $0 = "IDLE $0";
535 unless ($mic->idle) {
536 return if $self->{quit};
537 return "E: IDLE failed on $url: $!";
539 $self->{idle_mic} = $mic; # for ->quit
541 until ($self->{quit} || !$mic->IsConnected ||
542 grep(/^\* [0-9]+ EXISTS/, @res) || $i <= 0) {
543 @res = $mic->idle_data($i);
546 delete $self->{idle_mic};
547 unless ($self->{quit}) {
548 $mic->IsConnected or return "E: IDLE disconnected on $url";
549 $mic->done or return "E: IDLE DONE failed on $url: $!";
554 # idles on a single URI
555 sub watch_imap_idle_1 ($$$) {
556 my ($self, $url, $intvl) = @_;
557 my $uri = PublicInbox::URIimap->new($url);
558 my $sec = uri_section($uri);
559 my $mic_arg = $self->{mic_arg}->{$sec} or
560 die "BUG: no Mail::IMAPClient->new arg for $sec";
562 local $0 = $uri->mailbox." $sec";
563 until ($self->{quit}) {
564 $mic //= PublicInbox::IMAPClient->new(%$mic_arg);
566 if ($mic && $mic->IsConnected) {
567 $err = imap_fetch_all($self, $mic, $url);
568 $err //= imap_idle_once($self, $mic, $intvl, $url);
570 $err = "E: not connected: $!";
572 if ($err && !$self->{quit}) {
575 sleep 60 unless $self->{quit};
580 sub watch_atfork_child ($) {
582 delete $self->{idle_pids};
583 delete $self->{poll_pids};
584 delete $self->{opendirs};
585 PublicInbox::DS->Reset;
586 %SIG = (%SIG, %{$self->{sig}}, CHLD => 'DEFAULT');
587 PublicInbox::Sigfd::sig_setmask($self->{oldset});
590 sub watch_atfork_parent ($) {
592 _done_for_now($self);
593 PublicInbox::Sigfd::block_signals();
596 sub imap_idle_requeue ($) { # DS::add_timer callback
597 my ($self, $url_intvl) = @{$_[0]};
598 return if $self->{quit};
599 push @{$self->{idle_todo}}, $url_intvl;
603 sub imap_idle_reap { # PublicInbox::DS::dwaitpid callback
604 my ($self, $pid) = @_;
605 my $url_intvl = delete $self->{idle_pids}->{$pid} or
606 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
608 my ($url, $intvl) = @$url_intvl;
609 return if $self->{quit};
610 warn "W: PID=$pid on $url died: \$?=$?\n" if $?;
611 PublicInbox::DS::add_timer(60,
612 \&imap_idle_requeue, [ $self, $url_intvl ]);
615 sub reap { # callback for EOFpipe
616 my ($pid, $cb, $self) = @{$_[0]};
617 my $ret = waitpid($pid, 0);
619 $cb->($self, $pid); # poll_fetch_reap || imap_idle_reap
621 warn "W: waitpid($pid) => ", $ret // "($!)", "\n";
625 sub imap_idle_fork ($$) {
626 my ($self, $url_intvl) = @_;
627 my ($url, $intvl) = @$url_intvl;
628 pipe(my ($r, $w)) or die "pipe: $!";
629 defined(my $pid = fork) or die "fork: $!";
632 watch_atfork_child($self);
633 watch_imap_idle_1($self, $url, $intvl);
637 $self->{idle_pids}->{$pid} = $url_intvl;
638 PublicInbox::EOFpipe->new($r, \&reap, [$pid, \&imap_idle_reap, $self]);
643 return if $self->{quit};
644 my $idle_todo = $self->{idle_todo};
645 if ($idle_todo && @$idle_todo) {
646 my $oldset = watch_atfork_parent($self);
648 while (my $url_intvl = shift(@$idle_todo)) {
649 imap_idle_fork($self, $url_intvl);
652 PublicInbox::Sigfd::sig_setmask($oldset);
655 goto(&fs_scan_step) if $self->{mdre};
658 sub watch_imap_fetch_all ($$) {
659 my ($self, $urls) = @_;
660 for my $url (@$urls) {
661 my $uri = PublicInbox::URIimap->new($url);
662 my $sec = uri_section($uri);
663 my $mic_arg = $self->{mic_arg}->{$sec} or
664 die "BUG: no Mail::IMAPClient->new arg for $sec";
665 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or next;
666 my $err = imap_fetch_all($self, $mic, $url);
667 last if $self->{quit};
668 warn $err, "\n" if $err;
672 sub watch_nntp_fetch_all ($$) {
673 my ($self, $urls) = @_;
674 for my $url (@$urls) {
675 my $uri = uri_new($url);
676 my $sec = uri_section($uri);
677 my $nn_arg = $self->{nn_arg}->{$sec} or
678 die "BUG: no Net::NNTP->new arg for $sec";
679 my $nntp_opt = $self->{nntp_opt}->{$sec};
680 my $nn = nn_new($nn_arg, $nntp_opt, $url);
682 warn "E: $url: \$!=$!\n";
685 last if $self->{quit};
686 if (my $postconn = $nntp_opt->{-postconn}) {
687 for my $m_arg (@$postconn) {
688 my ($method, @args) = @$m_arg;
689 $nn->$method(@args) and next;
690 warn "E: <$url> $method failed\n";
695 last if $self->{quit};
697 my $err = nntp_fetch_all($self, $nn, $url);
698 warn $err, "\n" if $err;
703 sub poll_fetch_fork ($) { # DS::add_timer callback
704 my ($self, $intvl, $urls) = @{$_[0]};
705 return if $self->{quit};
706 pipe(my ($r, $w)) or die "pipe: $!";
707 my $oldset = watch_atfork_parent($self);
709 if (defined($pid) && $pid == 0) {
711 watch_atfork_child($self);
712 if ($urls->[0] =~ m!\Aimaps?://!i) {
713 watch_imap_fetch_all($self, $urls);
715 watch_nntp_fetch_all($self, $urls);
720 PublicInbox::Sigfd::sig_setmask($oldset);
721 die "fork: $!" unless defined $pid;
722 $self->{poll_pids}->{$pid} = [ $intvl, $urls ];
723 PublicInbox::EOFpipe->new($r, \&reap, [$pid, \&poll_fetch_reap, $self]);
726 sub poll_fetch_reap {
727 my ($self, $pid) = @_;
728 my $intvl_urls = delete $self->{poll_pids}->{$pid} or
729 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
730 return if $self->{quit};
731 my ($intvl, $urls) = @$intvl_urls;
733 warn "W: PID=$pid died: \$?=$?\n", map { "$_\n" } @$urls;
735 warn("I: will check $_ in ${intvl}s\n") for @$urls;
736 PublicInbox::DS::add_timer($intvl, \&poll_fetch_fork,
737 [$self, $intvl, $urls]);
740 sub watch_imap_init ($$) {
741 my ($self, $poll) = @_;
742 eval { require PublicInbox::IMAPClient } or
743 die "Mail::IMAPClient is required for IMAP:\n$@\n";
744 eval { require PublicInbox::IMAPTracker } or
745 die "DBD::SQLite is required for IMAP\n:$@\n";
747 my $mic_args = imap_common_init($self); # read args from config
749 # make sure we can connect and cache the credentials in memory
750 $self->{mic_arg} = {}; # schema://authority => IMAPClient->new args
751 my $mics = {}; # schema://authority => IMAPClient obj
752 for my $url (sort keys %{$self->{imap}}) {
753 my $uri = PublicInbox::URIimap->new($url);
754 $mics->{uri_section($uri)} //= mic_for($self, $url, $mic_args);
757 my $idle = []; # [ [ url1, intvl1 ], [url2, intvl2] ]
758 for my $url (keys %{$self->{imap}}) {
759 my $uri = PublicInbox::URIimap->new($url);
760 my $sec = uri_section($uri);
761 my $mic = $mics->{$sec};
762 my $intvl = $self->{imap_opt}->{$sec}->{pollInterval};
763 if ($mic->has_capability('IDLE') && !$intvl) {
764 $intvl = $self->{imap_opt}->{$sec}->{idleInterval};
765 push @$idle, [ $url, $intvl // () ];
767 push @{$poll->{$intvl || 120}}, $url;
771 $self->{idle_todo} = $idle;
772 PublicInbox::DS::requeue($self); # ->event_step to fork
776 # flesh out common NNTP-specific data structures
777 sub nntp_common_init ($) {
779 my $cfg = $self->{config};
780 my $nn_args = {}; # scheme://authority => Net::NNTP->new arg
781 for my $url (sort keys %{$self->{nntp}}) {
782 my $sec = uri_section(uri_new($url));
784 # Debug and Timeout are passed to Net::NNTP->new
785 my $v = cfg_bool($cfg, 'nntp.Debug', $url);
786 $nn_args->{$sec}->{Debug} = $v if defined $v;
787 my $to = cfg_intvl($cfg, 'nntp.Timeout', $url);
788 $nn_args->{$sec}->{Timeout} = $to if $to;
790 # Net::NNTP post-connect commands
791 for my $k (qw(starttls compress)) {
792 $v = cfg_bool($cfg, "nntp.$k", $url) // next;
793 $self->{nntp_opt}->{$sec}->{$k} = $v;
797 for my $k (qw(pollInterval)) {
798 $to = cfg_intvl($cfg, "nntp.$k", $url) // next;
799 $self->{nntp_opt}->{$sec}->{$k} = $to;
805 # Net::NNTP doesn't support CAPABILITIES, yet
806 sub try_starttls ($) {
808 return if $host =~ /\.onion\z/s;
809 return if $host =~ /\A127\.[0-9]+\.[0-9]+\.[0-9]+\z/s;
810 return if $host eq '::1';
815 my ($nn_arg, $nntp_opt, $url) = @_;
816 my $nn = Net::NNTP->new(%$nn_arg) or die "E: <$url> new: $!\n";
818 # default to using STARTTLS if it's available, but allow
819 # it to be disabled for localhost/VPN users
820 if (!$nn_arg->{SSL} && $nn->can('starttls')) {
821 if (!defined($nntp_opt->{starttls}) &&
822 try_starttls($nn_arg->{Host})) {
823 # soft fail by default
824 $nn->starttls or warn <<"";
825 W: <$url> STARTTLS tried and failed (not requested)
827 } elsif ($nntp_opt->{starttls}) {
828 # hard fail if explicitly configured
829 $nn->starttls or die <<"";
830 E: <$url> STARTTLS requested and failed
833 } elsif ($nntp_opt->{starttls}) {
834 $nn->can('starttls') or
835 die "E: <$url> Net::NNTP too old for STARTTLS\n";
836 $nn->starttls or die <<"";
837 E: <$url> STARTTLS requested and failed
843 sub nn_for ($$$) { # nn = Net::NNTP
844 my ($self, $url, $nn_args) = @_;
845 my $uri = uri_new($url);
846 my $sec = uri_section($uri);
847 my $nntp_opt = $self->{nntp_opt}->{$sec} //= {};
848 my $host = $uri->host;
849 # Net::NNTP and Net::Netrc both mishandle `0', so we pass `127.0.0.1'
850 $host = '127.0.0.1' if $host eq '0';
853 if (defined(my $ui = $uri->userinfo)) {
854 require PublicInbox::GitCredential;
857 protocol => uri_scheme($uri),
859 }, 'PublicInbox::GitCredential';
860 ($u, $p) = split(/:/, $ui, 2);
861 ($cred->{username}, $cred->{password}) = ($u, $p);
862 $cred->check_netrc unless defined $p;
864 my $common = $nn_args->{$sec} // {};
868 SSL => $uri->secure, # snews == nntps
869 %$common, # may Debug ....
871 my $nn = nn_new($nn_arg, $nntp_opt, $url);
874 $cred->fill; # may prompt user here
875 if ($nn->authinfo($u, $p)) {
876 push @{$nntp_opt->{-postconn}}, [ 'authinfo', $u, $p ];
878 warn "E: <$url> AUTHINFO $u XXXX failed\n";
883 if ($nntp_opt->{compress}) {
884 # https://rt.cpan.org/Ticket/Display.html?id=129967
885 if ($nn->can('compress')) {
887 push @{$nntp_opt->{-postconn}}, [ 'compress' ];
889 warn "W: <$url> COMPRESS failed\n";
892 delete $nntp_opt->{compress};
894 W: <$url> COMPRESS not supported by Net::NNTP
895 W: see https://rt.cpan.org/Ticket/Display.html?id=129967 for updates
900 $self->{nn_arg}->{$sec} = $nn_arg;
901 $cred->run($nn ? 'approve' : 'reject') if $cred;
905 sub nntp_fetch_all ($$$) {
906 my ($self, $nn, $url) = @_;
907 my $uri = uri_new($url);
908 my ($group, $num_a, $num_b) = $uri->group;
909 my $sec = uri_section($uri);
910 my ($nr, $beg, $end) = $nn->group($group);
911 unless (defined($nr)) {
912 chomp(my $msg = $nn->message);
913 return "E: GROUP $group <$sec> $msg";
916 # IMAPTracker is also used for tracking NNTP, UID == article number
917 # LIST.ACTIVE can get the equivalent of UIDVALIDITY, but that's
918 # expensive. So we assume newsgroups don't change:
919 my $itrk = PublicInbox::IMAPTracker->new($url);
920 my (undef, $l_art) = $itrk->get_last;
921 $l_art //= $beg; # initial import
923 # allow users to specify articles to refetch
924 # cf. https://tools.ietf.org/id/draft-gilman-news-url-01.txt
925 # nntp://example.com/inbox.foo/$num_a-$num_b
926 $l_art = $num_a if defined($num_a) && $num_a < $l_art;
927 $end = $num_b if defined($num_b) && $num_b < $end;
929 return if $l_art >= $end; # nothing to do
932 warn "I: $url fetching ARTICLE $beg..$end\n";
933 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
935 local $SIG{__WARN__} = sub {
936 my $pfx = ($_[0] // '') =~ /^([A-Z]: )/g ? $1 : '';
937 $warn_cb->("$pfx$url ", $art ? ("ARTICLE $art") : (), "\n", @_);
939 my $inboxes = $self->{nntp}->{$url};
941 my $n = $self->{max_batch};
943 last if $self->{quit};
946 _done_for_now($self);
947 $itrk->update_last(0, $last_art);
948 $n = $self->{max_batch};
950 my $raw = $nn->article($art);
951 unless (defined($raw)) {
952 my $msg = $nn->message;
953 if ($nn->code == 421) { # pseudo response from Net::Cmd
956 } else { # probably just a deleted message (spam)
961 s/\r\n/\n/ for @$raw;
962 $raw = join('', @$raw);
964 for my $ibx (@$inboxes) {
965 my $eml = PublicInbox::Eml->new($raw);
966 import_eml($self, $ibx, $eml);
968 } elsif ($inboxes eq 'watchspam') {
969 my $eml = PublicInbox::Eml->new(\$raw);
970 my $arg = [ $self, $eml, "$url ARTICLE $art" ];
971 $self->{config}->each_inbox(\&remove_eml_i, $arg);
973 die "BUG: destination unknown $inboxes";
977 _done_for_now($self);
978 $itrk->update_last(0, $last_art);
982 sub watch_nntp_init ($$) {
983 my ($self, $poll) = @_;
984 eval { require Net::NNTP } or
985 die "Net::NNTP is required for NNTP:\n$@\n";
986 eval { require PublicInbox::IMAPTracker } or
987 die "DBD::SQLite is required for NNTP\n:$@\n";
989 my $nn_args = nntp_common_init($self); # read args from config
991 # make sure we can connect and cache the credentials in memory
992 $self->{nn_arg} = {}; # schema://authority => Net::NNTP->new args
993 for my $url (sort keys %{$self->{nntp}}) {
994 nn_for($self, $url, $nn_args);
996 for my $url (keys %{$self->{nntp}}) {
997 my $uri = uri_new($url);
998 my $sec = uri_section($uri);
999 my $intvl = $self->{nntp_opt}->{$sec}->{pollInterval};
1000 push @{$poll->{$intvl || 120}}, $url;
1004 sub watch { # main entry point
1005 my ($self, $sig, $oldset) = @_;
1006 $self->{oldset} = $oldset;
1007 $self->{sig} = $sig;
1008 my $poll = {}; # intvl_seconds => [ url1, url2 ]
1009 watch_imap_init($self, $poll) if $self->{imap};
1010 watch_nntp_init($self, $poll) if $self->{nntp};
1011 while (my ($intvl, $urls) = each %$poll) {
1012 # poll all URLs for a given interval sequentially
1013 PublicInbox::DS::add_timer(0, \&poll_fetch_fork,
1014 [$self, $intvl, $urls]);
1016 watch_fs_init($self) if $self->{mdre};
1017 PublicInbox::DS->SetPostLoopCallback(sub { !$self->quit_done });
1018 PublicInbox::DS->EventLoop; # calls ->event_step
1019 _done_for_now($self);
1023 my ($self, $op) = @_;
1024 push @{$self->{ops}}, $op;
1025 PublicInbox::DS::requeue($self);
1030 return if $self->{quit};
1031 my $op = shift @{$self->{ops}};
1032 local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
1034 # continue existing scan
1035 my $opendirs = $self->{opendirs};
1036 my @dirnames = keys %$opendirs;
1037 foreach my $dir (@dirnames) {
1038 my $dh = delete $opendirs->{$dir};
1039 my $n = $self->{max_batch};
1040 while (my $fn = readdir($dh)) {
1041 _try_path($self, "$dir/$fn");
1044 $opendirs->{$dir} = $dh if $n < 0;
1046 if ($op && $op eq 'full') {
1047 foreach my $dir (keys %{$self->{mdmap}}) {
1048 next if $opendirs->{$dir}; # already in progress
1049 my $ok = opendir(my $dh, $dir);
1051 warn "failed to open $dir: $!\n";
1054 my $n = $self->{max_batch};
1055 while (my $fn = readdir($dh)) {
1056 _try_path($self, "$dir/$fn");
1059 $opendirs->{$dir} = $dh if $n < 0;
1062 _done_for_now($self);
1063 # do we have more work to do?
1064 PublicInbox::DS::requeue($self) if keys %$opendirs;
1068 my ($self, $op) = @_;
1069 push @{$self->{ops}}, $op;
1074 my ($self, $ibx) = @_;
1075 my $importers = $self->{importers};
1076 my $im = $importers->{"$ibx"} ||= $ibx->importer(0);
1077 if (scalar(keys(%$importers)) > 2) {
1078 delete $importers->{"$ibx"};
1079 _done_for_now($self);
1082 $importers->{"$ibx"} = $im;
1085 # XXX consider sharing with V2Writable, this only requires read-only access
1086 sub content_exists ($$) {
1087 my ($ibx, $eml) = @_;
1088 my $over = $ibx->over or return;
1089 my $mids = mids($eml);
1090 my $chash = content_hash($eml);
1092 for my $mid (@$mids) {
1093 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
1094 my $cmp = $ibx->smsg_eml($smsg) or return;
1095 return 1 if $chash eq content_hash($cmp);
1103 sub { # this gets called by (V2Writable||Import)->add
1104 my ($mime, $ibx) = @_;
1105 return if content_exists($ibx, $mime);
1107 if ($sc->spamcheck($mime, \$tmp)) {
1108 return PublicInbox::Eml->new(\$tmp);
1110 warn $mime->header('Message-ID')." failed spam check\n";
1116 $_[0] =~ s!\Amaildir:!! or return;
1123 my ($cur, $ws, $ibx) = @_;
1124 if ($ws && !ref($ws) && $ws eq 'watchspam') {
1126 E: $cur is a spam folder and cannot be used for `$ibx->{name}' input
1136 # URI::snews exists, URI::nntps does not, so use URI::snews
1137 $url =~ s!\Anntps://!snews://!i;
1143 require PublicInbox::URIimap;
1144 my $uri = PublicInbox::URIimap->new($url);
1145 $uri ? $uri->canonical->as_string : undef;
1148 my %IS_NNTP = (news => 1, snews => 1, nntp => 1);
1152 my $uri = uri_new($url);
1153 return unless $uri && $IS_NNTP{$uri->scheme} && $uri->group;
1154 $url = $uri->canonical->as_string;
1155 # nntps is IANA registered, snews is deprecated
1156 $url =~ s!\Asnews://!nntps://!;