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 if (!ref($inboxes) && $inboxes eq 'watchspam') {
192 return _remove_spam($self, $path);
195 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
196 local $SIG{__WARN__} = sub {
197 $warn_cb->("path: $path\n");
200 foreach my $ibx (@$inboxes) {
201 my $eml = mime_from_path($path) or next;
202 import_eml($self, $ibx, $eml);
209 %{$self->{opendirs}} = ();
210 _done_for_now($self);
211 if (my $imap_pid = $self->{-imap_pid}) {
212 kill('QUIT', $imap_pid);
214 for (qw(idle_pids poll_pids)) {
215 my $pids = $self->{$_} or next;
216 kill('QUIT', $_) for (keys %$pids);
218 if (my $idle_mic = $self->{idle_mic}) {
219 eval { $idle_mic->done };
221 warn "IDLE DONE error: $@\n";
222 eval { $idle_mic->disconnect };
223 warn "IDLE LOGOUT error: $@\n" if $@;
228 sub watch_fs_init ($) {
231 delete $self->{done_timer};
232 _done_for_now($self);
235 _try_path($self, $_[0]->fullname);
236 $self->{done_timer} //= PublicInbox::DS::requeue($done);
238 require PublicInbox::DirIdle;
239 # inotify_create + EPOLL_CTL_ADD
240 PublicInbox::DirIdle->new([keys %{$self->{mdmap}}], $cb);
243 # avoid exposing deprecated "snews" to users.
244 my %SCHEME_MAP = ('snews' => 'nntps');
248 my $scheme = $uri->scheme;
249 $SCHEME_MAP{$scheme} // $scheme;
252 # returns the git config section name, e.g [imap "imaps://user@example.com"]
253 # without the mailbox, so we can share connections between different inboxes
254 sub uri_section ($) {
256 uri_scheme($uri) . '://' . $uri->authority;
259 sub cfg_intvl ($$$) {
260 my ($cfg, $key, $url) = @_;
261 my $v = $cfg->urlmatch($key, $url) // return;
262 $v =~ /\A[0-9]+(?:\.[0-9]+)?\z/s and return $v + 0;
263 if (ref($v) eq 'ARRAY') {
264 $v = join(', ', @$v);
265 warn "W: $key has multiple values: $v\nW: $key ignored\n";
267 warn "W: $key=$v is not a numeric value in seconds\n";
272 my ($cfg, $key, $url) = @_;
273 my $orig = $cfg->urlmatch($key, $url) // return;
274 my $bool = PublicInbox::Config::_git_config_bool($orig);
275 warn "W: $key=$orig for $url is not boolean\n" unless defined($bool);
279 # flesh out common IMAP-specific data structures
280 sub imap_common_init ($) {
282 my $cfg = $self->{config};
283 my $mic_args = {}; # scheme://authority => Mail:IMAPClient arg
284 for my $url (sort keys %{$self->{imap}}) {
285 my $uri = PublicInbox::URIimap->new($url);
286 my $sec = uri_section($uri);
287 for my $k (qw(Starttls Debug Compress)) {
288 my $bool = cfg_bool($cfg, "imap.$k", $url) // next;
289 $mic_args->{$sec}->{$k} = $bool;
291 my $to = cfg_intvl($cfg, 'imap.timeout', $url);
292 $mic_args->{$sec}->{Timeout} = $to if $to;
293 for my $k (qw(pollInterval idleInterval)) {
294 $to = cfg_intvl($cfg, "imap.$k", $url) // next;
295 $self->{imap_opt}->{$sec}->{$k} = $to;
297 my $k = 'imap.fetchBatchSize';
298 my $bs = $cfg->urlmatch($k, $url) // next;
299 if ($bs =~ /\A([0-9]+)\z/) {
300 $self->{imap_opt}->{$sec}->{batch_size} = $bs;
302 warn "$k=$bs is not an integer\n";
308 sub auth_anon_cb { '' }; # for Mail::IMAPClient::Authcallback
310 sub mic_for ($$$) { # mic = Mail::IMAPClient
311 my ($self, $url, $mic_args) = @_;
312 my $uri = PublicInbox::URIimap->new($url);
313 require PublicInbox::GitCredential;
316 protocol => $uri->scheme,
318 username => $uri->user,
319 password => $uri->password,
320 }, 'PublicInbox::GitCredential';
321 my $common = $mic_args->{uri_section($uri)} // {};
322 # IMAPClient and Net::Netrc both mishandles `0', so we pass `127.0.0.1'
323 my $host = $cred->{host};
324 $host = '127.0.0.1' if $host eq '0';
328 Ssl => $uri->scheme eq 'imaps',
329 Keepalive => 1, # SO_KEEPALIVE
330 %$common, # may set Starttls, Compress, Debug ....
332 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or
333 die "E: <$url> new: $@\n";
335 # default to using STARTTLS if it's available, but allow
336 # it to be disabled since I usually connect to localhost
337 if (!$mic_arg->{Ssl} && !defined($mic_arg->{Starttls}) &&
338 $mic->has_capability('STARTTLS') &&
339 $mic->can('starttls')) {
340 $mic->starttls or die "E: <$url> STARTTLS: $@\n";
343 # do we even need credentials?
344 if (!defined($cred->{username}) &&
345 $mic->has_capability('AUTH=ANONYMOUS')) {
349 $cred->check_netrc unless defined $cred->{password};
350 $cred->fill; # may prompt user here
351 $mic->User($mic_arg->{User} = $cred->{username});
352 $mic->Password($mic_arg->{Password} = $cred->{password});
353 } else { # AUTH=ANONYMOUS
354 $mic->Authmechanism($mic_arg->{Authmechanism} = 'ANONYMOUS');
355 $mic->Authcallback($mic_arg->{Authcallback} = \&auth_anon_cb);
357 if ($mic->login && $mic->IsAuthenticated) {
358 # success! keep IMAPClient->new arg in case we get disconnected
359 $self->{mic_arg}->{uri_section($uri)} = $mic_arg;
361 warn "E: <$url> LOGIN: $@\n";
364 $cred->run($mic ? 'approve' : 'reject') if $cred;
368 sub imap_import_msg ($$$$) {
369 my ($self, $url, $uid, $raw) = @_;
370 # our target audience expects LF-only, save storage
371 $$raw =~ s/\r\n/\n/sg;
373 my $inboxes = $self->{imap}->{$url};
375 for my $ibx (@$inboxes) {
376 my $eml = PublicInbox::Eml->new($$raw);
377 my $x = import_eml($self, $ibx, $eml);
379 } elsif ($inboxes eq 'watchspam') {
380 my $eml = PublicInbox::Eml->new($raw);
381 my $arg = [ $self, $eml, "$url UID:$uid" ];
382 $self->{config}->each_inbox(\&remove_eml_i, $arg);
384 die "BUG: destination unknown $inboxes";
388 sub imap_fetch_all ($$$) {
389 my ($self, $mic, $url) = @_;
390 my $uri = PublicInbox::URIimap->new($url);
391 my $sec = uri_section($uri);
392 my $mbx = $uri->mailbox;
393 $mic->Clear(1); # trim results history
394 $mic->examine($mbx) or return "E: EXAMINE $mbx ($sec) failed: $!";
395 my ($r_uidval, $r_uidnext);
396 for ($mic->Results) {
397 /^\* OK \[UIDVALIDITY ([0-9]+)\].*/ and $r_uidval = $1;
398 /^\* OK \[UIDNEXT ([0-9]+)\].*/ and $r_uidnext = $1;
399 last if $r_uidval && $r_uidnext;
401 $r_uidval //= $mic->uidvalidity($mbx) //
402 return "E: $url cannot get UIDVALIDITY";
403 $r_uidnext //= $mic->uidnext($mbx) //
404 return "E: $url cannot get UIDNEXT";
405 my $itrk = PublicInbox::IMAPTracker->new($url);
406 my ($l_uidval, $l_uid) = $itrk->get_last;
407 $l_uidval //= $r_uidval; # first time
409 if ($l_uidval != $r_uidval) {
410 return "E: $url UIDVALIDITY mismatch\n".
411 "E: local=$l_uidval != remote=$r_uidval";
413 my $r_uid = $r_uidnext - 1;
414 if ($l_uid != 1 && $l_uid > $r_uid) {
415 return "E: $url local UID exceeds remote ($l_uid > $r_uid)\n".
416 "E: $url strangely, UIDVALIDLITY matches ($l_uidval)\n";
418 return if $l_uid >= $r_uid; # nothing to do
420 warn "I: $url fetching UID $l_uid:$r_uid\n";
421 $mic->Uid(1); # the default, we hope
422 my $bs = $self->{imap_opt}->{$sec}->{batch_size} // 1;
423 my $req = $mic->imap4rev1 ? 'BODY.PEEK[]' : 'RFC822.PEEK';
425 # TODO: FLAGS may be useful for personal use
429 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
430 local $SIG{__WARN__} = sub {
432 $warn_cb->("$url UID:$batch\n");
437 # I wish "UID FETCH $START:*" could work, but:
438 # 1) servers do not need to return results in any order
439 # 2) Mail::IMAPClient doesn't offer a streaming API
440 $uids = $mic->search("UID $l_uid:*") or
441 return "E: $url UID SEARCH $l_uid:* error: $!";
442 return if scalar(@$uids) == 0;
444 # RFC 3501 doesn't seem to indicate order of UID SEARCH
445 # responses, so sort it ourselves. Order matters so
446 # IMAPTracker can store the newest UID.
447 @$uids = sort { $a <=> $b } @$uids;
449 # Did we actually get new messages?
450 return if $uids->[0] < $l_uid;
452 $l_uid = $uids->[-1] + 1; # for next search
455 while (scalar @$uids) {
456 my @batch = splice(@$uids, 0, $bs);
457 $batch = join(',', @batch);
458 local $0 = "UID:$batch $mbx $sec";
459 my $r = $mic->fetch_hash($batch, $req);
460 unless ($r) { # network error?
461 $err = "E: $url UID FETCH $batch error: $!";
464 for my $uid (@batch) {
465 # messages get deleted, so holes appear
466 my $per_uid = delete $r->{$uid} // next;
467 my $raw = delete($per_uid->{$key}) // next;
468 imap_import_msg($self, $url, $uid, \$raw);
470 last if $self->{quit};
472 last if $self->{quit};
474 _done_for_now($self);
475 $itrk->update_last($r_uidval, $last_uid) if defined $last_uid;
476 } until ($err || $self->{quit});
480 sub imap_idle_once ($$$$) {
481 my ($self, $mic, $intvl, $url) = @_;
482 my $i = $intvl //= (29 * 60);
483 my $end = now() + $intvl;
484 warn "I: $url idling for ${intvl}s\n";
485 local $0 = "IDLE $0";
486 unless ($mic->idle) {
487 return if $self->{quit};
488 return "E: IDLE failed on $url: $!";
490 $self->{idle_mic} = $mic; # for ->quit
492 until ($self->{quit} || grep(/^\* [0-9]+ EXISTS/, @res) || $i <= 0) {
493 @res = $mic->idle_data($i);
496 delete $self->{idle_mic};
497 unless ($self->{quit}) {
498 $mic->IsConnected or return "E: IDLE disconnected on $url";
499 $mic->done or return "E: IDLE DONE failed on $url: $!";
504 # idles on a single URI
505 sub watch_imap_idle_1 ($$$) {
506 my ($self, $url, $intvl) = @_;
507 my $uri = PublicInbox::URIimap->new($url);
508 my $sec = uri_section($uri);
509 my $mic_arg = $self->{mic_arg}->{$sec} or
510 die "BUG: no Mail::IMAPClient->new arg for $sec";
512 local $0 = $uri->mailbox." $sec";
513 until ($self->{quit}) {
514 $mic //= PublicInbox::IMAPClient->new(%$mic_arg);
515 my $err = imap_fetch_all($self, $mic, $url);
516 $err //= imap_idle_once($self, $mic, $intvl, $url);
517 if ($err && !$self->{quit}) {
520 sleep 60 unless $self->{quit};
525 sub watch_atfork_child ($) {
527 delete $self->{idle_pids};
528 delete $self->{poll_pids};
529 delete $self->{opendirs};
530 PublicInbox::DS->Reset;
531 PublicInbox::Sigfd::sig_setmask($self->{oldset});
532 %SIG = (%SIG, %{$self->{sig}});
535 sub watch_atfork_parent ($) {
537 _done_for_now($self);
540 sub imap_idle_reap { # PublicInbox::DS::dwaitpid callback
541 my ($self, $pid) = @_;
542 my $url_intvl = delete $self->{idle_pids}->{$pid} or
543 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
545 my ($url, $intvl) = @$url_intvl;
546 return if $self->{quit};
547 warn "W: PID=$pid on $url died: \$?=$?\n" if $?;
548 push @{$self->{idle_todo}}, $url_intvl;
549 PubicInbox::DS::requeue($self); # call ->event_step to respawn
552 sub imap_idle_fork ($$) {
553 my ($self, $url_intvl) = @_;
554 my ($url, $intvl) = @$url_intvl;
555 defined(my $pid = fork) or die "fork: $!";
557 watch_atfork_child($self);
558 watch_imap_idle_1($self, $url, $intvl);
561 $self->{idle_pids}->{$pid} = $url_intvl;
562 PublicInbox::DS::dwaitpid($pid, \&imap_idle_reap, $self);
567 return if $self->{quit};
568 my $idle_todo = $self->{idle_todo};
569 if ($idle_todo && @$idle_todo) {
570 watch_atfork_parent($self);
571 while (my $url_intvl = shift(@$idle_todo)) {
572 imap_idle_fork($self, $url_intvl);
575 goto(&fs_scan_step) if $self->{mdre};
578 sub watch_imap_fetch_all ($$) {
579 my ($self, $urls) = @_;
580 for my $url (@$urls) {
581 my $uri = PublicInbox::URIimap->new($url);
582 my $sec = uri_section($uri);
583 my $mic_arg = $self->{mic_arg}->{$sec} or
584 die "BUG: no Mail::IMAPClient->new arg for $sec";
585 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or next;
586 my $err = imap_fetch_all($self, $mic, $url);
587 last if $self->{quit};
588 warn $err, "\n" if $err;
592 sub watch_nntp_fetch_all ($$) {
593 my ($self, $urls) = @_;
594 for my $url (@$urls) {
595 my $uri = uri_new($url);
596 my $sec = uri_section($uri);
597 my $nn_arg = $self->{nn_arg}->{$sec} or
598 die "BUG: no Net::NNTP->new arg for $sec";
599 my $nntp_opt = $self->{nntp_opt}->{$sec};
600 my $nn = nn_new($nn_arg, $nntp_opt, $url);
602 warn "E: $url: \$!=$!\n";
605 last if $self->{quit};
606 if (my $postconn = $nntp_opt->{-postconn}) {
607 for my $m_arg (@$postconn) {
608 my ($method, @args) = @$m_arg;
609 $nn->$method(@args) and next;
610 warn "E: <$url> $method failed\n";
615 last if $self->{quit};
617 my $err = nntp_fetch_all($self, $nn, $url);
618 warn $err, "\n" if $err;
623 sub poll_fetch_fork ($) { # DS::add_timer callback
624 my ($self, $intvl, $urls) = @{$_[0]};
625 return if $self->{quit};
626 watch_atfork_parent($self);
627 defined(my $pid = fork) or die "fork: $!";
629 watch_atfork_child($self);
630 if ($urls->[0] =~ m!\Aimaps?://!i) {
631 watch_imap_fetch_all($self, $urls);
633 watch_nntp_fetch_all($self, $urls);
637 $self->{poll_pids}->{$pid} = [ $intvl, $urls ];
638 PublicInbox::DS::dwaitpid($pid, \&poll_fetch_reap, $self);
641 sub poll_fetch_reap { # PublicInbox::DS::dwaitpid callback
642 my ($self, $pid) = @_;
643 my $intvl_urls = delete $self->{poll_pids}->{$pid} or
644 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
645 return if $self->{quit};
646 my ($intvl, $urls) = @$intvl_urls;
648 warn "W: PID=$pid died: \$?=$?\n", map { "$_\n" } @$urls;
650 warn("I: will check $_ in ${intvl}s\n") for @$urls;
651 PublicInbox::DS::add_timer($intvl, \&poll_fetch_fork,
652 [$self, $intvl, $urls]);
655 sub watch_imap_init ($$) {
656 my ($self, $poll) = @_;
657 eval { require PublicInbox::IMAPClient } or
658 die "Mail::IMAPClient is required for IMAP:\n$@\n";
659 eval { require PublicInbox::IMAPTracker } or
660 die "DBD::SQLite is required for IMAP\n:$@\n";
662 my $mic_args = imap_common_init($self); # read args from config
664 # make sure we can connect and cache the credentials in memory
665 $self->{mic_arg} = {}; # schema://authority => IMAPClient->new args
666 my $mics = {}; # schema://authority => IMAPClient obj
667 for my $url (sort keys %{$self->{imap}}) {
668 my $uri = PublicInbox::URIimap->new($url);
669 $mics->{uri_section($uri)} //= mic_for($self, $url, $mic_args);
672 my $idle = []; # [ [ url1, intvl1 ], [url2, intvl2] ]
673 for my $url (keys %{$self->{imap}}) {
674 my $uri = PublicInbox::URIimap->new($url);
675 my $sec = uri_section($uri);
676 my $mic = $mics->{$sec};
677 my $intvl = $self->{imap_opt}->{$sec}->{pollInterval};
678 if ($mic->has_capability('IDLE') && !$intvl) {
679 $intvl = $self->{imap_opt}->{$sec}->{idleInterval};
680 push @$idle, [ $url, $intvl // () ];
682 push @{$poll->{$intvl || 120}}, $url;
686 $self->{idle_todo} = $idle;
687 PublicInbox::DS::requeue($self); # ->event_step to fork
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, $url, $nn_args) = @_;
760 my $uri = uri_new($url);
761 my $sec = uri_section($uri);
762 my $nntp_opt = $self->{nntp_opt}->{$sec} //= {};
763 my $host = $uri->host;
764 # Net::NNTP and Net::Netrc both mishandle `0', so we pass `127.0.0.1'
765 $host = '127.0.0.1' if $host eq '0';
768 if (defined(my $ui = $uri->userinfo)) {
769 require PublicInbox::GitCredential;
772 protocol => uri_scheme($uri),
774 }, 'PublicInbox::GitCredential';
775 ($u, $p) = split(/:/, $ui, 2);
776 ($cred->{username}, $cred->{password}) = ($u, $p);
777 $cred->check_netrc unless defined $p;
779 my $common = $nn_args->{$sec} // {};
783 SSL => $uri->secure, # snews == nntps
784 %$common, # may Debug ....
786 my $nn = nn_new($nn_arg, $nntp_opt, $url);
789 $cred->fill; # may prompt user here
790 if ($nn->authinfo($u, $p)) {
791 push @{$nntp_opt->{-postconn}}, [ 'authinfo', $u, $p ];
793 warn "E: <$url> AUTHINFO $u XXXX failed\n";
798 if ($nntp_opt->{compress}) {
799 # https://rt.cpan.org/Ticket/Display.html?id=129967
800 if ($nn->can('compress')) {
802 push @{$nntp_opt->{-postconn}}, [ 'compress' ];
804 warn "W: <$url> COMPRESS failed\n";
807 delete $nntp_opt->{compress};
809 W: <$url> COMPRESS not supported by Net::NNTP
810 W: see https://rt.cpan.org/Ticket/Display.html?id=129967 for updates
815 $self->{nn_arg}->{$sec} = $nn_arg;
816 $cred->run($nn ? 'approve' : 'reject') if $cred;
820 sub nntp_fetch_all ($$$) {
821 my ($self, $nn, $url) = @_;
822 my $uri = uri_new($url);
823 my ($group, $num_a, $num_b) = $uri->group;
824 my $sec = uri_section($uri);
825 my ($nr, $beg, $end) = $nn->group($group);
826 unless (defined($nr)) {
827 chomp(my $msg = $nn->message);
828 return "E: GROUP $group <$sec> $msg";
831 # IMAPTracker is also used for tracking NNTP, UID == article number
832 # LIST.ACTIVE can get the equivalent of UIDVALIDITY, but that's
833 # expensive. So we assume newsgroups don't change:
834 my $itrk = PublicInbox::IMAPTracker->new($url);
835 my (undef, $l_art) = $itrk->get_last;
836 $l_art //= $beg; # initial import
838 # allow users to specify articles to refetch
839 # cf. https://tools.ietf.org/id/draft-gilman-news-url-01.txt
840 # nntp://example.com/inbox.foo/$num_a-$num_b
841 $l_art = $num_a if defined($num_a) && $num_a < $l_art;
842 $end = $num_b if defined($num_b) && $num_b < $end;
844 return if $l_art >= $end; # nothing to do
847 warn "I: $url fetching ARTICLE $beg..$end\n";
848 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
850 local $SIG{__WARN__} = sub {
851 $warn_cb->("$url ", $art ? ("ARTICLE $art") : (), "\n", @_);
853 my $inboxes = $self->{nntp}->{$url};
856 last if $self->{quit};
858 my $raw = $nn->article($art);
859 unless (defined($raw)) {
860 my $msg = $nn->message;
861 if ($nn->code == 421) { # pseudo response from Net::Cmd
864 } else { # probably just a deleted message (spam)
869 s/\r\n/\n/ for @$raw;
870 $raw = join('', @$raw);
872 for my $ibx (@$inboxes) {
873 my $eml = PublicInbox::Eml->new($raw);
874 import_eml($self, $ibx, $eml);
876 } elsif ($inboxes eq 'watchspam') {
877 my $eml = PublicInbox::Eml->new(\$raw);
878 my $arg = [ $self, $eml, "$url ARTICLE $art" ];
879 $self->{config}->each_inbox(\&remove_eml_i, $arg);
881 die "BUG: destination unknown $inboxes";
885 $itrk->update_last(0, $last_art) if defined $last_art;
886 _done_for_now($self);
890 sub watch_nntp_init ($$) {
891 my ($self, $poll) = @_;
892 eval { require Net::NNTP } or
893 die "Net::NNTP is required for NNTP:\n$@\n";
894 eval { require PublicInbox::IMAPTracker } or
895 die "DBD::SQLite is required for NNTP\n:$@\n";
897 my $nn_args = nntp_common_init($self); # read args from config
899 # make sure we can connect and cache the credentials in memory
900 $self->{nn_arg} = {}; # schema://authority => Net::NNTP->new args
901 for my $url (sort keys %{$self->{nntp}}) {
902 nn_for($self, $url, $nn_args);
904 for my $url (keys %{$self->{nntp}}) {
905 my $uri = uri_new($url);
906 my $sec = uri_section($uri);
907 my $intvl = $self->{nntp_opt}->{$sec}->{pollInterval};
908 push @{$poll->{$intvl || 120}}, $url;
913 my ($self, $sig, $oldset) = @_;
914 $self->{oldset} = $oldset;
916 my $poll = {}; # intvl_seconds => [ url1, url2 ]
917 watch_imap_init($self, $poll) if $self->{imap};
918 watch_nntp_init($self, $poll) if $self->{nntp};
919 while (my ($intvl, $urls) = each %$poll) {
920 # poll all URLs for a given interval sequentially
921 PublicInbox::DS::add_timer(0, \&poll_fetch_fork,
922 [$self, $intvl, $urls]);
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;
993 # XXX consider sharing with V2Writable, this only requires read-only access
994 sub content_exists ($$) {
995 my ($ibx, $eml) = @_;
996 my $over = $ibx->over or return;
997 my $mids = mids($eml);
998 my $chash = content_hash($eml);
1000 for my $mid (@$mids) {
1001 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
1002 my $cmp = $ibx->smsg_eml($smsg) or return;
1003 return 1 if $chash eq content_hash($cmp);
1012 my ($mime, $ibx) = @_;
1013 return if content_exists($ibx, $mime);
1015 if ($sc->spamcheck($mime, \$tmp)) {
1016 return PublicInbox::Eml->new(\$tmp);
1018 warn $mime->header('Message-ID')." failed spam check\n";
1024 $_[0] =~ s!\Amaildir:!! or return;
1031 my ($cur, $ws, $ibx) = @_;
1032 if ($ws && !ref($ws) && $ws eq 'watchspam') {
1034 E: $cur is a spam folder and cannot be used for `$ibx->{name}' input
1044 # URI::snews exists, URI::nntps does not, so use URI::snews
1045 $url =~ s!\Anntps://!snews://!i;
1051 require PublicInbox::URIimap;
1052 my $uri = PublicInbox::URIimap->new($url);
1053 $uri ? $uri->canonical->as_string : undef;
1056 my %IS_NNTP = (news => 1, snews => 1, nntp => 1);
1060 my $uri = uri_new($url);
1061 return unless $uri && $IS_NNTP{$uri->scheme} && $uri->group;
1062 $url = $uri->canonical->as_string;
1063 # nntps is IANA registered, snews is deprecated
1064 $url =~ s!\Asnews://!nntps://!;