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);
16 *mime_from_path = \&PublicInbox::InboxWritable::mime_from_path;
18 sub compile_watchheaders ($) {
21 if (my $whs = $ibx->{watchheader}) {
23 my ($k, $v) = split(/:/, $_, 2);
24 # XXX should this be case-insensitive?
25 # Or, mutt-style, case-sensitive iff
26 # a capital letter exists?
27 push @$watch_hdrs, [ $k, qr/\Q$v\E/ ];
30 if (my $list_ids = $ibx->{listid}) {
32 # RFC2919 section 6 stipulates
33 # "case insensitive equality"
34 my $re = qr/<[ \t]*\Q$_\E[ \t]*>/i;
35 push @$watch_hdrs, ['List-Id', $re ];
38 $ibx->{-watchheaders} = $watch_hdrs if scalar @$watch_hdrs;
42 my ($class, $config) = @_;
44 my (%imap, %nntp); # url => [inbox objects] or 'watchspam'
46 # "publicinboxwatch" is the documented namespace
47 # "publicinboxlearn" is legacy but may be supported
49 foreach my $pfx (qw(publicinboxwatch publicinboxlearn)) {
50 my $k = "$pfx.watchspam";
51 defined(my $dirs = $config->{$k}) or next;
52 $dirs = PublicInbox::Config::_array($dirs);
53 for my $dir (@$dirs) {
55 if (is_maildir($dir)) {
56 # skip "new", no MUA has seen it, yet.
57 $mdmap{"$dir/cur"} = 'watchspam';
58 } elsif ($url = imap_url($dir)) {
59 $imap{$url} = 'watchspam';
60 } elsif ($url = nntp_url($dir)) {
61 $nntp{$url} = 'watchspam';
63 warn "unsupported $k=$dir\n";
68 my $k = 'publicinboxwatch.spamcheck';
70 my $spamcheck = PublicInbox::Spamcheck::get($config, $k, $default);
71 $spamcheck = _spamcheck_cb($spamcheck) if $spamcheck;
73 $config->each_inbox(sub {
74 # need to make all inboxes writable for spam removal:
75 my $ibx = $_[0] = PublicInbox::InboxWritable->new($_[0]);
77 my $watches = $ibx->{watch} or return;
78 $watches = PublicInbox::Config::_array($watches);
79 for my $watch (@$watches) {
81 if (is_maildir($watch)) {
82 compile_watchheaders($ibx);
83 my ($new, $cur) = ("$watch/new", "$watch/cur");
84 my $cur_dst = $mdmap{$cur} //= [];
85 return if is_watchspam($cur, $cur_dst, $ibx);
86 push @{$mdmap{$new} //= []}, $ibx;
88 } elsif ($url = imap_url($watch)) {
89 return if is_watchspam($url, $imap{$url}, $ibx);
90 compile_watchheaders($ibx);
91 push @{$imap{$url} ||= []}, $ibx;
92 } elsif ($url = nntp_url($watch)) {
93 return if is_watchspam($url, $nntp{$url}, $ibx);
94 compile_watchheaders($ibx);
95 push @{$nntp{$url} ||= []}, $ibx;
97 warn "watch unsupported: $k=$watch\n";
103 if (scalar keys %mdmap) {
104 $mdre = join('|', map { quotemeta($_) } keys %mdmap);
105 $mdre = qr!\A($mdre)/!;
107 return unless $mdre || scalar(keys %imap) || scalar(keys %nntp);
110 spamcheck => $spamcheck,
114 imap => scalar keys %imap ? \%imap : undef,
115 nntp => scalar keys %nntp? \%nntp : undef,
117 opendirs => {}, # dirname => dirhandle (in progress scans)
118 ops => [], # 'quit', 'full'
124 my $importers = $self->{importers};
125 foreach my $im (values %$importers) {
130 sub remove_eml_i { # each_inbox callback
131 my ($ibx, $arg) = @_;
132 my ($self, $eml, $loc) = @$arg;
134 my $im = _importer_for($self, $ibx);
135 $im->remove($eml, 'spam');
136 if (my $scrub = $ibx->filter($im)) {
137 my $scrubbed = $scrub->scrub($eml, 1);
139 $scrubbed == REJECT() and return;
140 $im->remove($scrubbed, 'spam');
143 warn "error removing spam at: $loc from $ibx->{name}: $@\n" if $@;
147 my ($self, $path) = @_;
148 # path must be marked as (S)een
149 $path =~ /:2,[A-R]*S[T-Za-z]*\z/ or return;
150 my $eml = mime_from_path($path) or return;
151 $self->{config}->each_inbox(\&remove_eml_i, [ $self, $eml, $path ]);
154 sub import_eml ($$$) {
155 my ($self, $ibx, $eml) = @_;
156 my $im = _importer_for($self, $ibx);
158 # any header match means it's eligible for the inbox:
159 if (my $watch_hdrs = $ibx->{-watchheaders}) {
161 my $hdr = $eml->header_obj;
162 for my $wh (@$watch_hdrs) {
163 my @v = $hdr->header_raw($wh->[0]);
164 $ok = grep(/$wh->[1]/, @v) and last;
169 if (my $scrub = $ibx->filter($im)) {
170 my $ret = $scrub->scrub($eml) or return;
171 $ret == REJECT() and return;
174 $im->add($eml, $self->{spamcheck});
178 my ($self, $path) = @_;
179 return unless PublicInbox::InboxWritable::is_maildir_path($path);
180 if ($path !~ $self->{mdre}) {
181 warn "unrecognized path: $path\n";
184 my $inboxes = $self->{mdmap}->{$1};
186 warn "unmappable dir: $1\n";
189 if (!ref($inboxes) && $inboxes eq 'watchspam') {
190 return _remove_spam($self, $path);
193 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
194 local $SIG{__WARN__} = sub {
195 $warn_cb->("path: $path\n");
198 foreach my $ibx (@$inboxes) {
199 my $eml = mime_from_path($path) or next;
200 import_eml($self, $ibx, $eml);
207 %{$self->{opendirs}} = ();
208 _done_for_now($self);
209 if (my $imap_pid = $self->{-imap_pid}) {
210 kill('QUIT', $imap_pid);
212 for (qw(idle_pids poll_pids)) {
213 my $pids = $self->{$_} or next;
214 kill('QUIT', $_) for (keys %$pids);
216 if (my $idle_mic = $self->{idle_mic}) {
217 eval { $idle_mic->done };
219 warn "IDLE DONE error: $@\n";
220 eval { $idle_mic->disconnect };
221 warn "IDLE LOGOUT error: $@\n" if $@;
226 sub watch_fs_init ($) {
229 delete $self->{done_timer};
230 _done_for_now($self);
233 _try_path($self, $_[0]->fullname);
234 $self->{done_timer} //= PublicInbox::DS::requeue($done);
236 require PublicInbox::DirIdle;
237 # inotify_create + EPOLL_CTL_ADD
238 PublicInbox::DirIdle->new([keys %{$self->{mdmap}}], $cb);
241 # returns the git config section name, e.g [imap "imaps://user@example.com"]
242 # without the mailbox, so we can share connections between different inboxes
243 sub uri_section ($) {
245 $uri->scheme . '://' . $uri->authority;
248 sub cfg_intvl ($$$) {
249 my ($cfg, $key, $url) = @_;
250 my $v = $cfg->urlmatch($key, $url) // return;
251 $v =~ /\A[0-9]+(?:\.[0-9]+)?\z/s and return $v + 0;
252 if (ref($v) eq 'ARRAY') {
253 $v = join(', ', @$v);
254 warn "W: $key has multiple values: $v\nW: $key ignored\n";
256 warn "W: $key=$v is not a numeric value in seconds\n";
261 my ($cfg, $key, $url) = @_;
262 my $orig = $cfg->urlmatch($key, $url) // return;
263 my $bool = PublicInbox::Config::_git_config_bool($orig);
264 warn "W: $key=$orig for $url is not boolean\n" unless defined($bool);
268 # flesh out common IMAP-specific data structures
269 sub imap_common_init ($) {
271 my $cfg = $self->{config};
272 my $mic_args = {}; # scheme://authority => Mail:IMAPClient arg
273 for my $url (sort keys %{$self->{imap}}) {
274 my $uri = PublicInbox::URIimap->new($url);
275 my $sec = uri_section($uri);
276 for my $k (qw(Starttls Debug Compress)) {
277 my $bool = cfg_bool($cfg, "imap.$k", $url) // next;
278 $mic_args->{$sec}->{$k} = $bool;
280 my $to = cfg_intvl($cfg, 'imap.timeout', $url);
281 $mic_args->{$sec}->{Timeout} = $to if $to;
282 for my $k (qw(pollInterval idleInterval)) {
283 $to = cfg_intvl($cfg, "imap.$k", $url) // next;
284 $self->{imap_opt}->{$sec}->{$k} = $to;
286 my $k = 'imap.fetchBatchSize';
287 my $bs = $cfg->urlmatch($k, $url) // next;
288 if ($bs =~ /\A([0-9]+)\z/) {
289 $self->{imap_opt}->{$sec}->{batch_size} = $bs;
291 warn "$k=$bs is not an integer\n";
297 sub auth_anon_cb { '' }; # for Mail::IMAPClient::Authcallback
299 sub mic_for ($$$) { # mic = Mail::IMAPClient
300 my ($self, $uri, $mic_args) = @_;
301 my $url = $uri->as_string;
304 protocol => $uri->scheme,
306 username => $uri->user,
307 password => $uri->password,
309 my $common = $mic_args->{uri_section($uri)} // {};
310 my $host = $cred->{host};
313 # IMAPClient mishandles `0', so we pass `127.0.0.1'
314 Server => $host eq '0' ? '127.0.0.1' : $host,
315 Ssl => $uri->scheme eq 'imaps',
316 Keepalive => 1, # SO_KEEPALIVE
317 %$common, # may set Starttls, Compress, Debug ....
319 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or
320 die "E: <$url> new: $@\n";
322 # default to using STARTTLS if it's available, but allow
323 # it to be disabled since I usually connect to localhost
324 if (!$mic_arg->{Ssl} && !defined($mic_arg->{Starttls}) &&
325 $mic->has_capability('STARTTLS') &&
326 $mic->can('starttls')) {
327 $mic->starttls or die "E: <$url> STARTTLS: $@\n";
330 # do we even need credentials?
331 if (!defined($cred->{username}) &&
332 $mic->has_capability('AUTH=ANONYMOUS')) {
336 Git::credential($cred, 'fill'); # may prompt user here
337 $mic->User($mic_arg->{User} = $cred->{username});
338 $mic->Password($mic_arg->{Password} = $cred->{password});
339 } else { # AUTH=ANONYMOUS
340 $mic->Authmechanism($mic_arg->{Authmechanism} = 'ANONYMOUS');
341 $mic->Authcallback($mic_arg->{Authcallback} = \&auth_anon_cb);
343 if ($mic->login && $mic->IsAuthenticated) {
344 # success! keep IMAPClient->new arg in case we get disconnected
345 $self->{mic_arg}->{uri_section($uri)} = $mic_arg;
347 warn "E: <$url> LOGIN: $@\n";
350 Git::credential($cred, $mic ? 'approve' : 'reject') if $cred;
354 sub imap_import_msg ($$$$) {
355 my ($self, $url, $uid, $raw) = @_;
356 # our target audience expects LF-only, save storage
357 $$raw =~ s/\r\n/\n/sg;
359 my $inboxes = $self->{imap}->{$url};
361 for my $ibx (@$inboxes) {
362 my $eml = PublicInbox::Eml->new($$raw);
363 my $x = import_eml($self, $ibx, $eml);
365 } elsif ($inboxes eq 'watchspam') {
366 my $eml = PublicInbox::Eml->new($raw);
367 my $arg = [ $self, $eml, "$url UID:$uid" ];
368 $self->{config}->each_inbox(\&remove_eml_i, $arg);
370 die "BUG: destination unknown $inboxes";
374 sub imap_fetch_all ($$$) {
375 my ($self, $mic, $uri) = @_;
376 my $sec = uri_section($uri);
377 my $mbx = $uri->mailbox;
378 my $url = $uri->as_string;
379 $mic->Clear(1); # trim results history
380 $mic->examine($mbx) or return "E: EXAMINE $mbx ($sec) failed: $!";
381 my ($r_uidval, $r_uidnext);
382 for ($mic->Results) {
383 /^\* OK \[UIDVALIDITY ([0-9]+)\].*/ and $r_uidval = $1;
384 /^\* OK \[UIDNEXT ([0-9]+)\].*/ and $r_uidnext = $1;
385 last if $r_uidval && $r_uidnext;
387 $r_uidval //= $mic->uidvalidity($mbx) //
388 return "E: $url cannot get UIDVALIDITY";
389 $r_uidnext //= $mic->uidnext($mbx) //
390 return "E: $url cannot get UIDNEXT";
391 my $itrk = PublicInbox::IMAPTracker->new($url);
392 my ($l_uidval, $l_uid) = $itrk->get_last;
393 $l_uidval //= $r_uidval; # first time
395 if ($l_uidval != $r_uidval) {
396 return "E: $url UIDVALIDITY mismatch\n".
397 "E: local=$l_uidval != remote=$r_uidval";
399 my $r_uid = $r_uidnext - 1;
400 if ($l_uid != 1 && $l_uid > $r_uid) {
401 return "E: $url local UID exceeds remote ($l_uid > $r_uid)\n".
402 "E: $url strangely, UIDVALIDLITY matches ($l_uidval)\n";
404 return if $l_uid >= $r_uid; # nothing to do
406 warn "I: $url fetching UID $l_uid:$r_uid\n";
407 $mic->Uid(1); # the default, we hope
408 my $bs = $self->{imap_opt}->{$sec}->{batch_size} // 1;
409 my $req = $mic->imap4rev1 ? 'BODY.PEEK[]' : 'RFC822.PEEK';
411 # TODO: FLAGS may be useful for personal use
415 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
416 local $SIG{__WARN__} = sub {
418 $warn_cb->("$url UID:$batch\n");
423 # I wish "UID FETCH $START:*" could work, but:
424 # 1) servers do not need to return results in any order
425 # 2) Mail::IMAPClient doesn't offer a streaming API
426 $uids = $mic->search("UID $l_uid:*") or
427 return "E: $url UID SEARCH $l_uid:* error: $!";
428 return if scalar(@$uids) == 0;
430 # RFC 3501 doesn't seem to indicate order of UID SEARCH
431 # responses, so sort it ourselves. Order matters so
432 # IMAPTracker can store the newest UID.
433 @$uids = sort { $a <=> $b } @$uids;
435 # Did we actually get new messages?
436 return if $uids->[0] < $l_uid;
438 $l_uid = $uids->[-1] + 1; # for next search
441 while (scalar @$uids) {
442 my @batch = splice(@$uids, 0, $bs);
443 $batch = join(',', @batch);
444 local $0 = "UID:$batch $mbx $sec";
445 my $r = $mic->fetch_hash($batch, $req);
446 unless ($r) { # network error?
447 $err = "E: $url UID FETCH $batch error: $!";
450 for my $uid (@batch) {
451 # messages get deleted, so holes appear
452 my $per_uid = delete $r->{$uid} // next;
453 my $raw = delete($per_uid->{$key}) // next;
454 imap_import_msg($self, $url, $uid, \$raw);
456 last if $self->{quit};
458 last if $self->{quit};
460 _done_for_now($self);
461 $itrk->update_last($r_uidval, $last_uid) if defined $last_uid;
462 } until ($err || $self->{quit});
466 sub imap_idle_once ($$$$) {
467 my ($self, $mic, $intvl, $url) = @_;
468 my $i = $intvl //= (29 * 60);
469 my $end = now() + $intvl;
470 warn "I: $url idling for ${intvl}s\n";
471 local $0 = "IDLE $0";
472 unless ($mic->idle) {
473 return if $self->{quit};
474 return "E: IDLE failed on $url: $!";
476 $self->{idle_mic} = $mic; # for ->quit
478 until ($self->{quit} || grep(/^\* [0-9]+ EXISTS/, @res) || $i <= 0) {
479 @res = $mic->idle_data($i);
482 delete $self->{idle_mic};
483 unless ($self->{quit}) {
484 $mic->IsConnected or return "E: IDLE disconnected on $url";
485 $mic->done or return "E: IDLE DONE failed on $url: $!";
490 # idles on a single URI
491 sub watch_imap_idle_1 ($$$) {
492 my ($self, $uri, $intvl) = @_;
493 my $sec = uri_section($uri);
494 my $mic_arg = $self->{mic_arg}->{$sec} or
495 die "BUG: no Mail::IMAPClient->new arg for $sec";
497 local $0 = $uri->mailbox." $sec";
498 until ($self->{quit}) {
499 $mic //= delete($self->{mics}->{$sec}) //
500 PublicInbox::IMAPClient->new(%$mic_arg);
501 my $err = imap_fetch_all($self, $mic, $uri);
502 $err //= imap_idle_once($self, $mic, $intvl, $uri->as_string);
503 if ($err && !$self->{quit}) {
506 sleep 60 unless $self->{quit};
511 sub watch_atfork_child ($) {
513 delete $self->{idle_pids};
514 delete $self->{poll_pids};
515 delete $self->{opendirs};
516 PublicInbox::DS->Reset;
517 PublicInbox::Sigfd::sig_setmask($self->{oldset});
518 %SIG = (%SIG, %{$self->{sig}});
521 sub watch_atfork_parent ($) {
523 _done_for_now($self);
524 $self->{mics} = {}; # going to be forking, so disconnect
527 sub imap_idle_reap { # PublicInbox::DS::dwaitpid callback
528 my ($self, $pid) = @_;
529 my $uri_intvl = delete $self->{idle_pids}->{$pid} or
530 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
532 my ($uri, $intvl) = @$uri_intvl;
533 my $url = $uri->as_string;
534 return if $self->{quit};
535 warn "W: PID=$pid on $url died: \$?=$?\n" if $?;
536 push @{$self->{idle_todo}}, $uri_intvl;
537 PubicInbox::DS::requeue($self); # call ->event_step to respawn
540 sub imap_idle_fork ($$) {
541 my ($self, $uri_intvl) = @_;
542 my ($uri, $intvl) = @$uri_intvl;
543 defined(my $pid = fork) or die "fork: $!";
545 watch_atfork_child($self);
546 watch_imap_idle_1($self, $uri, $intvl);
549 $self->{idle_pids}->{$pid} = $uri_intvl;
550 PublicInbox::DS::dwaitpid($pid, \&imap_idle_reap, $self);
555 return if $self->{quit};
556 my $idle_todo = $self->{idle_todo};
557 if ($idle_todo && @$idle_todo) {
558 watch_atfork_parent($self);
559 while (my $uri_intvl = shift(@$idle_todo)) {
560 imap_idle_fork($self, $uri_intvl);
563 goto(&fs_scan_step) if $self->{mdre};
566 sub watch_imap_fetch_all ($$) {
567 my ($self, $uris) = @_;
568 for my $uri (@$uris) {
569 my $sec = uri_section($uri);
570 my $mic_arg = $self->{mic_arg}->{$sec} or
571 die "BUG: no Mail::IMAPClient->new arg for $sec";
572 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or next;
573 my $err = imap_fetch_all($self, $mic, $uri);
574 last if $self->{quit};
575 warn $err, "\n" if $err;
579 sub watch_nntp_fetch_all ($$) {
580 my ($self, $uris) = @_;
581 for my $uri (@$uris) {
582 my $sec = uri_section($uri);
583 my $nn_arg = $self->{nn_arg}->{$sec} or
584 die "BUG: no Net::NNTP->new arg for $sec";
585 my $nntp_opt = $self->{nntp_opt}->{$sec};
586 my $url = $uri->as_string;
587 my $nn = nn_new($nn_arg, $nntp_opt, $url);
589 warn "E: $url: \$!=$!\n";
592 last if $self->{quit};
593 if (my $postconn = $nntp_opt->{-postconn}) {
594 for my $m_arg (@$postconn) {
595 my ($method, @args) = @$m_arg;
596 $nn->$method(@args) and next;
597 warn "E: <$url> $method failed\n";
602 last if $self->{quit};
604 my $err = nntp_fetch_all($self, $nn, $uri);
605 warn $err, "\n" if $err;
610 sub poll_fetch_fork ($) { # DS::add_timer callback
611 my ($self, $intvl, $uris) = @{$_[0]};
612 return if $self->{quit};
613 watch_atfork_parent($self);
614 defined(my $pid = fork) or die "fork: $!";
616 watch_atfork_child($self);
617 if ($uris->[0]->scheme =~ /\Aimaps?\z/) {
618 watch_imap_fetch_all($self, $uris);
620 watch_nntp_fetch_all($self, $uris);
624 $self->{poll_pids}->{$pid} = [ $intvl, $uris ];
625 PublicInbox::DS::dwaitpid($pid, \&poll_fetch_reap, $self);
628 sub poll_fetch_reap { # PublicInbox::DS::dwaitpid callback
629 my ($self, $pid) = @_;
630 my $intvl_uris = delete $self->{poll_pids}->{$pid} or
631 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
632 return if $self->{quit};
633 my ($intvl, $uris) = @$intvl_uris;
635 warn "W: PID=$pid died: \$?=$?\n",
636 map { $_->as_string."\n" } @$uris;
638 warn('I: will check ', $_->as_string, " in ${intvl}s\n") for @$uris;
639 PublicInbox::DS::add_timer($intvl, \&poll_fetch_fork,
640 [$self, $intvl, $uris]);
643 sub watch_imap_init ($) {
645 eval { require PublicInbox::IMAPClient } or
646 die "Mail::IMAPClient is required for IMAP:\n$@\n";
647 eval { require Git } or
648 die "Git (Perl module) is required for IMAP:\n$@\n";
649 eval { require PublicInbox::IMAPTracker } or
650 die "DBD::SQLite is required for IMAP\n:$@\n";
652 my $mic_args = imap_common_init($self); # read args from config
654 # make sure we can connect and cache the credentials in memory
655 $self->{mic_arg} = {}; # schema://authority => IMAPClient->new args
656 my $mics = $self->{mics} = {}; # schema://authority => IMAPClient obj
657 for my $url (sort keys %{$self->{imap}}) {
658 my $uri = PublicInbox::URIimap->new($url);
659 $mics->{uri_section($uri)} //= mic_for($self, $uri, $mic_args);
662 my $idle = []; # [ [ uri1, intvl1 ], [uri2, intvl2] ]
663 my $poll = {}; # intvl_seconds => [ uri1, uri2 ]
664 for my $url (keys %{$self->{imap}}) {
665 my $uri = PublicInbox::URIimap->new($url);
666 my $sec = uri_section($uri);
667 my $mic = $mics->{$sec};
668 my $intvl = $self->{imap_opt}->{$sec}->{pollInterval};
669 if ($mic->has_capability('IDLE') && !$intvl) {
670 $intvl = $self->{imap_opt}->{$sec}->{idleInterval};
671 push @$idle, [ $uri, $intvl // () ];
673 push @{$poll->{$intvl || 120}}, $uri;
677 $self->{idle_pids} = {};
678 $self->{idle_todo} = $idle;
679 PublicInbox::DS::requeue($self); # ->event_step to fork
681 return unless scalar keys %$poll;
682 $self->{poll_pids} //= {};
684 # poll all URIs for a given interval sequentially
685 while (my ($intvl, $uris) = each %$poll) {
686 PublicInbox::DS::add_timer(0, \&poll_fetch_fork,
687 [$self, $intvl, $uris]);
691 # flesh out common NNTP-specific data structures
692 sub nntp_common_init ($) {
694 my $cfg = $self->{config};
695 my $nn_args = {}; # scheme://authority => Net::NNTP->new arg
696 for my $url (sort keys %{$self->{nntp}}) {
697 my $sec = uri_section(URI->new($url));
699 # Debug and Timeout are passed to Net::NNTP->new
700 my $v = cfg_bool($cfg, 'nntp.Debug', $url);
701 $nn_args->{$sec}->{Debug} = $v if defined $v;
702 my $to = cfg_intvl($cfg, 'nntp.Timeout', $url);
703 $nn_args->{$sec}->{Timeout} = $to if $to;
705 # Net::NNTP post-connect commands
706 for my $k (qw(starttls compress)) {
707 $v = cfg_bool($cfg, "nntp.$k", $url) // next;
708 $self->{nntp_opt}->{$sec}->{$k} = $v;
712 for my $k (qw(pollInterval)) {
713 $to = cfg_intvl($cfg, "nntp.$k", $url) // next;
714 $self->{nntp_opt}->{$sec}->{$k} = $to;
720 # Net::NNTP doesn't support CAPABILITIES, yet
721 sub try_starttls ($) {
723 return if $host =~ /\.onion\z/s;
724 return if $host =~ /\A127\.[0-9]+\.[0-9]+\.[0-9]+\z/s;
725 return if $host eq '::1';
730 my ($nn_arg, $nntp_opt, $url) = @_;
731 my $nn = Net::NNTP->new(%$nn_arg) or die "E: <$url> new: $!\n";
733 # default to using STARTTLS if it's available, but allow
734 # it to be disabled for localhost/VPN users
735 if (!$nn_arg->{SSL} && $nn->can('starttls')) {
736 if (!defined($nntp_opt->{starttls}) &&
737 try_starttls($nn_arg->{Host})) {
738 # soft fail by default
739 $nn->starttls or warn <<"";
740 W: <$url> STARTTLS tried and failed (not requested)
742 } elsif ($nntp_opt->{starttls}) {
743 # hard fail if explicitly configured
744 $nn->starttls or die <<"";
745 E: <$url> STARTTLS requested and failed
748 } elsif ($nntp_opt->{starttls}) {
749 $nn->can('starttls') or
750 die "E: <$url> Net::NNTP too old for STARTTLS\n";
751 $nn->starttls or die <<"";
752 E: <$url> STARTTLS requested and failed
758 sub nn_for ($$$) { # nn = Net::NNTP
759 my ($self, $uri, $nn_args) = @_;
760 my $url = $uri->as_string;
761 my $sec = uri_section($uri);
762 my $nntp_opt = $self->{nntp_opt}->{$sec} //= {};
765 if (defined(my $ui = $uri->userinfo)) {
768 protocol => $uri->scheme,
771 ($u, $p) = split(/:/, $ui, 2);
772 ($cred->{username}, $cred->{password}) = ($u, $p);
774 my $common = $nn_args->{$sec} // {};
777 # Net::NNTP mishandles `0', so we pass `127.0.0.1'
778 Host => $uri->host eq '0' ? '127.0.0.1' : $uri->host,
779 SSL => $uri->secure, # snews == nntps
780 %$common, # may Debug ....
782 my $nn = nn_new($nn_arg, $nntp_opt, $url);
785 Git::credential($cred, 'fill'); # may prompt user here
786 if ($nn->authinfo($u, $p)) {
787 push @{$nntp_opt->{-postconn}}, [ 'authinfo', $u, $p ];
789 warn "E: <$url> AUTHINFO $u XXXX failed\n";
794 if ($nntp_opt->{compress}) {
795 # https://rt.cpan.org/Ticket/Display.html?id=129967
796 if ($nn->can('compress')) {
798 push @{$nntp_opt->{-postconn}}, [ 'compress' ];
800 warn "W: <$url> COMPRESS failed\n";
803 delete $nntp_opt->{compress};
805 W: <$url> COMPRESS not supported by Net::NNTP
806 W: see https://rt.cpan.org/Ticket/Display.html?id=129967 for updates
811 $self->{nn_arg}->{$sec} = $nn_arg;
812 Git::credential($cred, $nn ? 'approve' : 'reject') if $cred;
816 sub nntp_fetch_all ($$$) {
817 my ($self, $nn, $uri) = @_;
818 my ($group, $num_a, $num_b) = $uri->group;
819 my $sec = uri_section($uri);
820 my $url = $uri->as_string;
821 my ($nr, $beg, $end) = $nn->group($group);
822 unless (defined($nr)) {
823 chomp(my $msg = $nn->message);
824 return "E: GROUP $group <$sec> $msg";
827 # IMAPTracker is also used for tracking NNTP, UID == article number
828 # LIST.ACTIVE can get the equivalent of UIDVALIDITY, but that's
829 # expensive. So we assume newsgroups don't change:
830 my $itrk = PublicInbox::IMAPTracker->new($url);
831 my (undef, $l_art) = $itrk->get_last;
832 $l_art //= $beg; # initial import
834 # allow users to specify articles to refetch
835 # cf. https://tools.ietf.org/id/draft-gilman-news-url-01.txt
836 # nntp://example.com/inbox.foo/$num_a-$num_b
837 $l_art = $num_a if defined($num_a) && $num_a < $l_art;
838 $end = $num_b if defined($num_b) && $num_b < $end;
840 return if $l_art >= $end; # nothing to do
843 warn "I: $url fetching ARTICLE $beg..$end\n";
844 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
846 local $SIG{__WARN__} = sub {
847 $warn_cb->("$url ", $art ? ("ARTICLE $art") : (), "\n", @_);
849 my $inboxes = $self->{nntp}->{$url};
852 last if $self->{quit};
854 my $raw = $nn->article($art);
855 unless (defined($raw)) {
856 my $msg = $nn->message;
857 if ($nn->code == 421) { # pseudo response from Net::Cmd
860 } else { # probably just a deleted message (spam)
865 s/\r\n/\n/ for @$raw;
866 $raw = join('', @$raw);
868 for my $ibx (@$inboxes) {
869 my $eml = PublicInbox::Eml->new($raw);
870 import_eml($self, $ibx, $eml);
872 } elsif ($inboxes eq 'watchspam') {
873 my $eml = PublicInbox::Eml->new(\$raw);
874 my $arg = [ $self, $eml, "$url ARTICLE $art" ];
875 $self->{config}->each_inbox(\&remove_eml_i, $arg);
877 die "BUG: destination unknown $inboxes";
881 $itrk->update_last(0, $last_art) if defined $last_art;
882 _done_for_now($self);
886 sub watch_nntp_init ($) {
888 eval { require Net::NNTP } or
889 die "Net::NNTP is required for NNTP:\n$@\n";
890 eval { require Git } or
891 die "Git (Perl module) is required for NNTP:\n$@\n";
892 eval { require PublicInbox::IMAPTracker } or
893 die "DBD::SQLite is required for NNTP\n:$@\n";
895 my $nn_args = nntp_common_init($self); # read args from config
897 # make sure we can connect and cache the credentials in memory
898 $self->{nn_arg} = {}; # schema://authority => Net::NNTP->new args
899 for my $url (sort keys %{$self->{nntp}}) {
900 nn_for($self, URI->new($url), $nn_args);
902 my $poll = {}; # intvl_seconds => [ uri1, uri2 ]
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}}, $uri;
909 $self->{poll_pids} //= {};
911 # poll all URIs for a given interval sequentially
912 while (my ($intvl, $uris) = each %$poll) {
913 PublicInbox::DS::add_timer(0, \&poll_fetch_fork,
914 [$self, $intvl, $uris]);
919 my ($self, $sig, $oldset) = @_;
920 $self->{oldset} = $oldset;
922 watch_imap_init($self) if $self->{imap};
923 watch_nntp_init($self) if $self->{nntp};
924 watch_fs_init($self) if $self->{mdre};
925 PublicInbox::DS->SetPostLoopCallback(sub {});
926 PublicInbox::DS->EventLoop until $self->{quit};
927 _done_for_now($self);
931 my ($self, $op) = @_;
932 push @{$self->{ops}}, $op;
933 PublicInbox::DS::requeue($self);
938 return if $self->{quit};
939 my $op = shift @{$self->{ops}};
941 # continue existing scan
943 my $opendirs = $self->{opendirs};
944 my @dirnames = keys %$opendirs;
945 foreach my $dir (@dirnames) {
946 my $dh = delete $opendirs->{$dir};
948 while (my $fn = readdir($dh)) {
949 _try_path($self, "$dir/$fn");
952 $opendirs->{$dir} = $dh if $n < 0;
954 if ($op && $op eq 'full') {
955 foreach my $dir (keys %{$self->{mdmap}}) {
956 next if $opendirs->{$dir}; # already in progress
957 my $ok = opendir(my $dh, $dir);
959 warn "failed to open $dir: $!\n";
963 while (my $fn = readdir($dh)) {
964 _try_path($self, "$dir/$fn");
967 $opendirs->{$dir} = $dh if $n < 0;
970 _done_for_now($self);
971 # do we have more work to do?
972 PublicInbox::DS::requeue($self) if keys %$opendirs;
976 my ($self, $op) = @_;
977 push @{$self->{ops}}, $op;
982 my ($self, $ibx) = @_;
983 my $importers = $self->{importers};
984 my $im = $importers->{"$ibx"} ||= $ibx->importer(0);
985 if (scalar(keys(%$importers)) > 2) {
986 delete $importers->{"$ibx"};
987 _done_for_now($self);
990 $importers->{"$ibx"} = $im;
998 if ($sc->spamcheck($mime, \$tmp)) {
999 return PublicInbox::Eml->new(\$tmp);
1001 warn $mime->header('Message-ID')." failed spam check\n";
1007 $_[0] =~ s!\Amaildir:!! or return;
1014 my ($cur, $ws, $ibx) = @_;
1015 if ($ws && !ref($ws) && $ws eq 'watchspam') {
1017 E: $cur is a spam folder and cannot be used for `$ibx->{name}' input
1026 require PublicInbox::URIimap;
1027 my $uri = PublicInbox::URIimap->new($url);
1028 $uri ? $uri->canonical->as_string : undef;
1031 my %IS_NNTP = (news => 1, snews => 1, nntp => 1);
1035 # URI::snews exists, URI::nntps does not, so use URI::snews
1036 $url =~ s!\Anntps://!snews://!i;
1037 my $uri = URI->new($url);
1038 return unless $uri && $IS_NNTP{$uri->scheme};
1039 $uri->group ? $uri->canonical->as_string : undef;