]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/WatchMaildir.pm
watch: check for duplicates in ->over before spamcheck
[public-inbox.git] / lib / PublicInbox / WatchMaildir.pm
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>
3 #
4 # ref: https://cr.yp.to/proto/maildir.html
5 #       http://wiki2.dovecot.org/MailboxFormat/Maildir
6 package PublicInbox::WatchMaildir;
7 use strict;
8 use warnings;
9 use PublicInbox::Eml;
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);
17 use POSIX qw(_exit);
18 *mime_from_path = \&PublicInbox::InboxWritable::mime_from_path;
19
20 sub compile_watchheaders ($) {
21         my ($ibx) = @_;
22         my $watch_hdrs = [];
23         if (my $whs = $ibx->{watchheader}) {
24                 for (@$whs) {
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/ ];
30                 }
31         }
32         if (my $list_ids = $ibx->{listid}) {
33                 for (@$list_ids) {
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 ];
38                 }
39         }
40         $ibx->{-watchheaders} = $watch_hdrs if scalar @$watch_hdrs;
41 }
42
43 sub new {
44         my ($class, $config) = @_;
45         my (%mdmap, $spamc);
46         my (%imap, %nntp); # url => [inbox objects] or 'watchspam'
47
48         # "publicinboxwatch" is the documented namespace
49         # "publicinboxlearn" is legacy but may be supported
50         # indefinitely...
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) {
56                         my $url;
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';
64                         } else {
65                                 warn "unsupported $k=$dir\n";
66                         }
67                 }
68         }
69
70         my $k = 'publicinboxwatch.spamcheck';
71         my $default = undef;
72         my $spamcheck = PublicInbox::Spamcheck::get($config, $k, $default);
73         $spamcheck = _spamcheck_cb($spamcheck) if $spamcheck;
74
75         $config->each_inbox(sub {
76                 # need to make all inboxes writable for spam removal:
77                 my $ibx = $_[0] = PublicInbox::InboxWritable->new($_[0]);
78
79                 my $watches = $ibx->{watch} or return;
80                 $watches = PublicInbox::Config::_array($watches);
81                 for my $watch (@$watches) {
82                         my $url;
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;
89                                 push @$cur_dst, $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;
98                         } else {
99                                 warn "watch unsupported: $k=$watch\n";
100                         }
101                 }
102         });
103
104         my $mdre;
105         if (scalar keys %mdmap) {
106                 $mdre = join('|', map { quotemeta($_) } keys %mdmap);
107                 $mdre = qr!\A($mdre)/!;
108         }
109         return unless $mdre || scalar(keys %imap) || scalar(keys %nntp);
110
111         bless {
112                 spamcheck => $spamcheck,
113                 mdmap => \%mdmap,
114                 mdre => $mdre,
115                 config => $config,
116                 imap => scalar keys %imap ? \%imap : undef,
117                 nntp => scalar keys %nntp? \%nntp : undef,
118                 importers => {},
119                 opendirs => {}, # dirname => dirhandle (in progress scans)
120                 ops => [], # 'quit', 'full'
121         }, $class;
122 }
123
124 sub _done_for_now {
125         my ($self) = @_;
126         my $importers = $self->{importers};
127         foreach my $im (values %$importers) {
128                 $im->done;
129         }
130 }
131
132 sub remove_eml_i { # each_inbox callback
133         my ($ibx, $arg) = @_;
134         my ($self, $eml, $loc) = @$arg;
135         eval {
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);
140                         $scrubbed or return;
141                         $scrubbed == REJECT() and return;
142                         $im->remove($scrubbed, 'spam');
143                 }
144         };
145         warn "error removing spam at: $loc from $ibx->{name}: $@\n" if $@;
146 }
147
148 sub _remove_spam {
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 ]);
154 }
155
156 sub import_eml ($$$) {
157         my ($self, $ibx, $eml) = @_;
158         my $im = _importer_for($self, $ibx);
159
160         # any header match means it's eligible for the inbox:
161         if (my $watch_hdrs = $ibx->{-watchheaders}) {
162                 my $ok;
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;
167                 }
168                 return unless $ok;
169         }
170
171         if (my $scrub = $ibx->filter($im)) {
172                 my $ret = $scrub->scrub($eml) or return;
173                 $ret == REJECT() and return;
174                 $eml = $ret;
175         }
176         $im->add($eml, $self->{spamcheck});
177 }
178
179 sub _try_path {
180         my ($self, $path) = @_;
181         return unless PublicInbox::InboxWritable::is_maildir_path($path);
182         if ($path !~ $self->{mdre}) {
183                 warn "unrecognized path: $path\n";
184                 return;
185         }
186         my $inboxes = $self->{mdmap}->{$1};
187         unless ($inboxes) {
188                 warn "unmappable dir: $1\n";
189                 return;
190         }
191         if (!ref($inboxes) && $inboxes eq 'watchspam') {
192                 return _remove_spam($self, $path);
193         }
194
195         my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
196         local $SIG{__WARN__} = sub {
197                 $warn_cb->("path: $path\n");
198                 $warn_cb->(@_);
199         };
200         foreach my $ibx (@$inboxes) {
201                 my $eml = mime_from_path($path) or next;
202                 import_eml($self, $ibx, $eml);
203         }
204 }
205
206 sub quit {
207         my ($self) = @_;
208         $self->{quit} = 1;
209         %{$self->{opendirs}} = ();
210         _done_for_now($self);
211         if (my $imap_pid = $self->{-imap_pid}) {
212                 kill('QUIT', $imap_pid);
213         }
214         for (qw(idle_pids poll_pids)) {
215                 my $pids = $self->{$_} or next;
216                 kill('QUIT', $_) for (keys %$pids);
217         }
218         if (my $idle_mic = $self->{idle_mic}) {
219                 eval { $idle_mic->done };
220                 if ($@) {
221                         warn "IDLE DONE error: $@\n";
222                         eval { $idle_mic->disconnect };
223                         warn "IDLE LOGOUT error: $@\n" if $@;
224                 }
225         }
226 }
227
228 sub watch_fs_init ($) {
229         my ($self) = @_;
230         my $done = sub {
231                 delete $self->{done_timer};
232                 _done_for_now($self);
233         };
234         my $cb = sub {
235                 _try_path($self, $_[0]->fullname);
236                 $self->{done_timer} //= PublicInbox::DS::requeue($done);
237         };
238         require PublicInbox::DirIdle;
239         # inotify_create + EPOLL_CTL_ADD
240         PublicInbox::DirIdle->new([keys %{$self->{mdmap}}], $cb);
241 }
242
243 # avoid exposing deprecated "snews" to users.
244 my %SCHEME_MAP = ('snews' => 'nntps');
245
246 sub uri_scheme ($) {
247         my ($uri) = @_;
248         my $scheme = $uri->scheme;
249         $SCHEME_MAP{$scheme} // $scheme;
250 }
251
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 ($) {
255         my ($uri) = @_;
256         uri_scheme($uri) . '://' . $uri->authority;
257 }
258
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";
266         } else {
267                 warn "W: $key=$v is not a numeric value in seconds\n";
268         }
269 }
270
271 sub cfg_bool ($$$) {
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);
276         $bool;
277 }
278
279 # flesh out common IMAP-specific data structures
280 sub imap_common_init ($) {
281         my ($self) = @_;
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;
290                 }
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;
296                 }
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;
301                 } else {
302                         warn "$k=$bs is not an integer\n";
303                 }
304         }
305         $mic_args;
306 }
307
308 sub auth_anon_cb { '' }; # for Mail::IMAPClient::Authcallback
309
310 sub mic_for ($$$) { # mic = Mail::IMAPClient
311         my ($self, $url, $mic_args) = @_;
312         my $uri = PublicInbox::URIimap->new($url);
313         require PublicInbox::GitCredential;
314         my $cred = bless {
315                 url => $url,
316                 protocol => $uri->scheme,
317                 host => $uri->host,
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';
325         my $mic_arg = {
326                 Port => $uri->port,
327                 Server => $host,
328                 Ssl => $uri->scheme eq 'imaps',
329                 Keepalive => 1, # SO_KEEPALIVE
330                 %$common, # may set Starttls, Compress, Debug ....
331         };
332         my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or
333                 die "E: <$url> new: $@\n";
334
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";
341         }
342
343         # do we even need credentials?
344         if (!defined($cred->{username}) &&
345                         $mic->has_capability('AUTH=ANONYMOUS')) {
346                 $cred = undef;
347         }
348         if ($cred) {
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);
356         }
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;
360         } else {
361                 warn "E: <$url> LOGIN: $@\n";
362                 $mic = undef;
363         }
364         $cred->run($mic ? 'approve' : 'reject') if $cred;
365         $mic;
366 }
367
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;
372
373         my $inboxes = $self->{imap}->{$url};
374         if (ref($inboxes)) {
375                 for my $ibx (@$inboxes) {
376                         my $eml = PublicInbox::Eml->new($$raw);
377                         my $x = import_eml($self, $ibx, $eml);
378                 }
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);
383         } else {
384                 die "BUG: destination unknown $inboxes";
385         }
386 }
387
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;
400         }
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
408         $l_uid //= 1;
409         if ($l_uidval != $r_uidval) {
410                 return "E: $url UIDVALIDITY mismatch\n".
411                         "E: local=$l_uidval != remote=$r_uidval";
412         }
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";
417         }
418         return if $l_uid >= $r_uid; # nothing to do
419
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';
424
425         # TODO: FLAGS may be useful for personal use
426         my $key = $req;
427         $key =~ s/\.PEEK//;
428         my ($uids, $batch);
429         my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
430         local $SIG{__WARN__} = sub {
431                 $batch //= '?';
432                 $warn_cb->("$url UID:$batch\n");
433                 $warn_cb->(@_);
434         };
435         my $err;
436         do {
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;
443
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;
448
449                 # Did we actually get new messages?
450                 return if $uids->[0] < $l_uid;
451
452                 $l_uid = $uids->[-1] + 1; # for next search
453                 my $last_uid;
454
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: $!";
462                                 last;
463                         }
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);
469                                 $last_uid = $uid;
470                                 last if $self->{quit};
471                         }
472                         last if $self->{quit};
473                 }
474                 _done_for_now($self);
475                 $itrk->update_last($r_uidval, $last_uid) if defined $last_uid;
476         } until ($err || $self->{quit});
477         $err;
478 }
479
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: $!";
489         }
490         $self->{idle_mic} = $mic; # for ->quit
491         my @res;
492         until ($self->{quit} || grep(/^\* [0-9]+ EXISTS/, @res) || $i <= 0) {
493                 @res = $mic->idle_data($i);
494                 $i = $end - now();
495         }
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: $!";
500         }
501         undef;
502 }
503
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";
511         my $mic;
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}) {
518                         warn $err, "\n";
519                         $mic = undef;
520                         sleep 60 unless $self->{quit};
521                 }
522         }
523 }
524
525 sub watch_atfork_child ($) {
526         my ($self) = @_;
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}});
533 }
534
535 sub watch_atfork_parent ($) {
536         my ($self) = @_;
537         _done_for_now($self);
538 }
539
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";
544
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
550 }
551
552 sub imap_idle_fork ($$) {
553         my ($self, $url_intvl) = @_;
554         my ($url, $intvl) = @$url_intvl;
555         defined(my $pid = fork) or die "fork: $!";
556         if ($pid == 0) {
557                 watch_atfork_child($self);
558                 watch_imap_idle_1($self, $url, $intvl);
559                 _exit(0);
560         }
561         $self->{idle_pids}->{$pid} = $url_intvl;
562         PublicInbox::DS::dwaitpid($pid, \&imap_idle_reap, $self);
563 }
564
565 sub event_step {
566         my ($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);
573                 }
574         }
575         goto(&fs_scan_step) if $self->{mdre};
576 }
577
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;
589         }
590 }
591
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);
601                 unless ($nn) {
602                         warn "E: $url: \$!=$!\n";
603                         next;
604                 }
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";
611                                 $nn = undef;
612                                 last;
613                         }
614                 }
615                 last if $self->{quit};
616                 if ($nn) {
617                         my $err = nntp_fetch_all($self, $nn, $url);
618                         warn $err, "\n" if $err;
619                 }
620         }
621 }
622
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: $!";
628         if ($pid == 0) {
629                 watch_atfork_child($self);
630                 if ($urls->[0] =~ m!\Aimaps?://!i) {
631                         watch_imap_fetch_all($self, $urls);
632                 } else {
633                         watch_nntp_fetch_all($self, $urls);
634                 }
635                 _exit(0);
636         }
637         $self->{poll_pids}->{$pid} = [ $intvl, $urls ];
638         PublicInbox::DS::dwaitpid($pid, \&poll_fetch_reap, $self);
639 }
640
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;
647         if ($?) {
648                 warn "W: PID=$pid died: \$?=$?\n", map { "$_\n" } @$urls;
649         }
650         warn("I: will check $_ in ${intvl}s\n") for @$urls;
651         PublicInbox::DS::add_timer($intvl, \&poll_fetch_fork,
652                                         [$self, $intvl, $urls]);
653 }
654
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";
661
662         my $mic_args = imap_common_init($self); # read args from config
663
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);
670         }
671
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 // () ];
681                 } else {
682                         push @{$poll->{$intvl || 120}}, $url;
683                 }
684         }
685         if (scalar @$idle) {
686                 $self->{idle_todo} = $idle;
687                 PublicInbox::DS::requeue($self); # ->event_step to fork
688         }
689 }
690
691 # flesh out common NNTP-specific data structures
692 sub nntp_common_init ($) {
693         my ($self) = @_;
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));
698
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;
704
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;
709                 }
710
711                 # internal option
712                 for my $k (qw(pollInterval)) {
713                         $to = cfg_intvl($cfg, "nntp.$k", $url) // next;
714                         $self->{nntp_opt}->{$sec}->{$k} = $to;
715                 }
716         }
717         $nn_args;
718 }
719
720 # Net::NNTP doesn't support CAPABILITIES, yet
721 sub try_starttls ($) {
722         my ($host) = @_;
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';
726         1;
727 }
728
729 sub nn_new ($$$) {
730         my ($nn_arg, $nntp_opt, $url) = @_;
731         my $nn = Net::NNTP->new(%$nn_arg) or die "E: <$url> new: $!\n";
732
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)
741
742                 } elsif ($nntp_opt->{starttls}) {
743                         # hard fail if explicitly configured
744                         $nn->starttls or die <<"";
745 E: <$url> STARTTLS requested and failed
746
747                 }
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
753
754         }
755         $nn;
756 }
757
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';
766         my $cred;
767         my ($u, $p);
768         if (defined(my $ui = $uri->userinfo)) {
769                 require PublicInbox::GitCredential;
770                 $cred = bless {
771                         url => $sec,
772                         protocol => uri_scheme($uri),
773                         host => $host,
774                 }, 'PublicInbox::GitCredential';
775                 ($u, $p) = split(/:/, $ui, 2);
776                 ($cred->{username}, $cred->{password}) = ($u, $p);
777                 $cred->check_netrc unless defined $p;
778         }
779         my $common = $nn_args->{$sec} // {};
780         my $nn_arg = {
781                 Port => $uri->port,
782                 Host => $host,
783                 SSL => $uri->secure, # snews == nntps
784                 %$common, # may Debug ....
785         };
786         my $nn = nn_new($nn_arg, $nntp_opt, $url);
787
788         if ($cred) {
789                 $cred->fill; # may prompt user here
790                 if ($nn->authinfo($u, $p)) {
791                         push @{$nntp_opt->{-postconn}}, [ 'authinfo', $u, $p ];
792                 } else {
793                         warn "E: <$url> AUTHINFO $u XXXX failed\n";
794                         $nn = undef;
795                 }
796         }
797
798         if ($nntp_opt->{compress}) {
799                 # https://rt.cpan.org/Ticket/Display.html?id=129967
800                 if ($nn->can('compress')) {
801                         if ($nn->compress) {
802                                 push @{$nntp_opt->{-postconn}}, [ 'compress' ];
803                         } else {
804                                 warn "W: <$url> COMPRESS failed\n";
805                         }
806                 } else {
807                         delete $nntp_opt->{compress};
808                         warn <<"";
809 W: <$url> COMPRESS not supported by Net::NNTP
810 W: see https://rt.cpan.org/Ticket/Display.html?id=129967 for updates
811
812                 }
813         }
814
815         $self->{nn_arg}->{$sec} = $nn_arg;
816         $cred->run($nn ? 'approve' : 'reject') if $cred;
817         $nn;
818 }
819
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";
829         }
830
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
837
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;
843
844         return if $l_art >= $end; # nothing to do
845         $beg = $l_art + 1;
846
847         warn "I: $url fetching ARTICLE $beg..$end\n";
848         my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
849         my ($err, $art);
850         local $SIG{__WARN__} = sub {
851                 $warn_cb->("$url ", $art ? ("ARTICLE $art") : (), "\n", @_);
852         };
853         my $inboxes = $self->{nntp}->{$url};
854         my $last_art;
855         for ($beg..$end) {
856                 last if $self->{quit};
857                 $art = $_;
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
862                                 $err = "E: $msg";
863                                 last;
864                         } else { # probably just a deleted message (spam)
865                                 warn "W: $msg";
866                                 next;
867                         }
868                 }
869                 s/\r\n/\n/ for @$raw;
870                 $raw = join('', @$raw);
871                 if (ref($inboxes)) {
872                         for my $ibx (@$inboxes) {
873                                 my $eml = PublicInbox::Eml->new($raw);
874                                 import_eml($self, $ibx, $eml);
875                         }
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);
880                 } else {
881                         die "BUG: destination unknown $inboxes";
882                 }
883                 $last_art = $art;
884         }
885         $itrk->update_last(0, $last_art) if defined $last_art;
886         _done_for_now($self);
887         $err;
888 }
889
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";
896
897         my $nn_args = nntp_common_init($self); # read args from config
898
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);
903         }
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;
909         }
910 }
911
912 sub watch {
913         my ($self, $sig, $oldset) = @_;
914         $self->{oldset} = $oldset;
915         $self->{sig} = $sig;
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]);
923         }
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);
928 }
929
930 sub trigger_scan {
931         my ($self, $op) = @_;
932         push @{$self->{ops}}, $op;
933         PublicInbox::DS::requeue($self);
934 }
935
936 sub fs_scan_step {
937         my ($self) = @_;
938         return if $self->{quit};
939         my $op = shift @{$self->{ops}};
940
941         # continue existing scan
942         my $max = 10;
943         my $opendirs = $self->{opendirs};
944         my @dirnames = keys %$opendirs;
945         foreach my $dir (@dirnames) {
946                 my $dh = delete $opendirs->{$dir};
947                 my $n = $max;
948                 while (my $fn = readdir($dh)) {
949                         _try_path($self, "$dir/$fn");
950                         last if --$n < 0;
951                 }
952                 $opendirs->{$dir} = $dh if $n < 0;
953         }
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);
958                         unless ($ok) {
959                                 warn "failed to open $dir: $!\n";
960                                 next;
961                         }
962                         my $n = $max;
963                         while (my $fn = readdir($dh)) {
964                                 _try_path($self, "$dir/$fn");
965                                 last if --$n < 0;
966                         }
967                         $opendirs->{$dir} = $dh if $n < 0;
968                 }
969         }
970         _done_for_now($self);
971         # do we have more work to do?
972         PublicInbox::DS::requeue($self) if keys %$opendirs;
973 }
974
975 sub scan {
976         my ($self, $op) = @_;
977         push @{$self->{ops}}, $op;
978         goto &fs_scan_step;
979 }
980
981 sub _importer_for {
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);
988         }
989
990         $importers->{"$ibx"} = $im;
991 }
992
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);
999         my ($id, $prev);
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);
1004                 }
1005         }
1006         undef;
1007 }
1008
1009 sub _spamcheck_cb {
1010         my ($sc) = @_;
1011         sub {
1012                 my ($mime, $ibx) = @_;
1013                 return if content_exists($ibx, $mime);
1014                 my $tmp = '';
1015                 if ($sc->spamcheck($mime, \$tmp)) {
1016                         return PublicInbox::Eml->new(\$tmp);
1017                 }
1018                 warn $mime->header('Message-ID')." failed spam check\n";
1019                 undef;
1020         }
1021 }
1022
1023 sub is_maildir {
1024         $_[0] =~ s!\Amaildir:!! or return;
1025         $_[0] =~ tr!/!/!s;
1026         $_[0] =~ s!/\z!!;
1027         $_[0];
1028 }
1029
1030 sub is_watchspam {
1031         my ($cur, $ws, $ibx) = @_;
1032         if ($ws && !ref($ws) && $ws eq 'watchspam') {
1033                 warn <<EOF;
1034 E: $cur is a spam folder and cannot be used for `$ibx->{name}' input
1035 EOF
1036                 return 1;
1037         }
1038         undef;
1039 }
1040
1041 sub uri_new {
1042         my ($url) = @_;
1043
1044         # URI::snews exists, URI::nntps does not, so use URI::snews
1045         $url =~ s!\Anntps://!snews://!i;
1046         URI->new($url);
1047 }
1048
1049 sub imap_url {
1050         my ($url) = @_;
1051         require PublicInbox::URIimap;
1052         my $uri = PublicInbox::URIimap->new($url);
1053         $uri ? $uri->canonical->as_string : undef;
1054 }
1055
1056 my %IS_NNTP = (news => 1, snews => 1, nntp => 1);
1057 sub nntp_url {
1058         my ($url) = @_;
1059         require URI;
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://!;
1065         $url;
1066 }
1067
1068 1;