]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/WatchMaildir.pm
watch: show path for warnings from spam messages
[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         my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
192         local $SIG{__WARN__} = sub {
193                 $warn_cb->("path: $path\n");
194                 $warn_cb->(@_);
195         };
196         if (!ref($inboxes) && $inboxes eq 'watchspam') {
197                 return _remove_spam($self, $path);
198         }
199         foreach my $ibx (@$inboxes) {
200                 my $eml = mime_from_path($path) or next;
201                 import_eml($self, $ibx, $eml);
202         }
203 }
204
205 sub quit {
206         my ($self) = @_;
207         $self->{quit} = 1;
208         %{$self->{opendirs}} = ();
209         _done_for_now($self);
210         if (my $imap_pid = $self->{-imap_pid}) {
211                 kill('QUIT', $imap_pid);
212         }
213         for (qw(idle_pids poll_pids)) {
214                 my $pids = $self->{$_} or next;
215                 kill('QUIT', $_) for (keys %$pids);
216         }
217         if (my $idle_mic = $self->{idle_mic}) {
218                 eval { $idle_mic->done };
219                 if ($@) {
220                         warn "IDLE DONE error: $@\n";
221                         eval { $idle_mic->disconnect };
222                         warn "IDLE LOGOUT error: $@\n" if $@;
223                 }
224         }
225 }
226
227 sub watch_fs_init ($) {
228         my ($self) = @_;
229         my $done = sub {
230                 delete $self->{done_timer};
231                 _done_for_now($self);
232         };
233         my $cb = sub {
234                 _try_path($self, $_[0]->fullname);
235                 $self->{done_timer} //= PublicInbox::DS::requeue($done);
236         };
237         require PublicInbox::DirIdle;
238         # inotify_create + EPOLL_CTL_ADD
239         PublicInbox::DirIdle->new([keys %{$self->{mdmap}}], $cb);
240 }
241
242 # avoid exposing deprecated "snews" to users.
243 my %SCHEME_MAP = ('snews' => 'nntps');
244
245 sub uri_scheme ($) {
246         my ($uri) = @_;
247         my $scheme = $uri->scheme;
248         $SCHEME_MAP{$scheme} // $scheme;
249 }
250
251 # returns the git config section name, e.g [imap "imaps://user@example.com"]
252 # without the mailbox, so we can share connections between different inboxes
253 sub uri_section ($) {
254         my ($uri) = @_;
255         uri_scheme($uri) . '://' . $uri->authority;
256 }
257
258 sub cfg_intvl ($$$) {
259         my ($cfg, $key, $url) = @_;
260         my $v = $cfg->urlmatch($key, $url) // return;
261         $v =~ /\A[0-9]+(?:\.[0-9]+)?\z/s and return $v + 0;
262         if (ref($v) eq 'ARRAY') {
263                 $v = join(', ', @$v);
264                 warn "W: $key has multiple values: $v\nW: $key ignored\n";
265         } else {
266                 warn "W: $key=$v is not a numeric value in seconds\n";
267         }
268 }
269
270 sub cfg_bool ($$$) {
271         my ($cfg, $key, $url) = @_;
272         my $orig = $cfg->urlmatch($key, $url) // return;
273         my $bool = PublicInbox::Config::_git_config_bool($orig);
274         warn "W: $key=$orig for $url is not boolean\n" unless defined($bool);
275         $bool;
276 }
277
278 # flesh out common IMAP-specific data structures
279 sub imap_common_init ($) {
280         my ($self) = @_;
281         my $cfg = $self->{config};
282         my $mic_args = {}; # scheme://authority => Mail:IMAPClient arg
283         for my $url (sort keys %{$self->{imap}}) {
284                 my $uri = PublicInbox::URIimap->new($url);
285                 my $sec = uri_section($uri);
286                 for my $k (qw(Starttls Debug Compress)) {
287                         my $bool = cfg_bool($cfg, "imap.$k", $url) // next;
288                         $mic_args->{$sec}->{$k} = $bool;
289                 }
290                 my $to = cfg_intvl($cfg, 'imap.timeout', $url);
291                 $mic_args->{$sec}->{Timeout} = $to if $to;
292                 for my $k (qw(pollInterval idleInterval)) {
293                         $to = cfg_intvl($cfg, "imap.$k", $url) // next;
294                         $self->{imap_opt}->{$sec}->{$k} = $to;
295                 }
296                 my $k = 'imap.fetchBatchSize';
297                 my $bs = $cfg->urlmatch($k, $url) // next;
298                 if ($bs =~ /\A([0-9]+)\z/) {
299                         $self->{imap_opt}->{$sec}->{batch_size} = $bs;
300                 } else {
301                         warn "$k=$bs is not an integer\n";
302                 }
303         }
304         $mic_args;
305 }
306
307 sub auth_anon_cb { '' }; # for Mail::IMAPClient::Authcallback
308
309 sub mic_for ($$$) { # mic = Mail::IMAPClient
310         my ($self, $url, $mic_args) = @_;
311         my $uri = PublicInbox::URIimap->new($url);
312         require PublicInbox::GitCredential;
313         my $cred = bless {
314                 url => $url,
315                 protocol => $uri->scheme,
316                 host => $uri->host,
317                 username => $uri->user,
318                 password => $uri->password,
319         }, 'PublicInbox::GitCredential';
320         my $common = $mic_args->{uri_section($uri)} // {};
321         # IMAPClient and Net::Netrc both mishandles `0', so we pass `127.0.0.1'
322         my $host = $cred->{host};
323         $host = '127.0.0.1' if $host eq '0';
324         my $mic_arg = {
325                 Port => $uri->port,
326                 Server => $host,
327                 Ssl => $uri->scheme eq 'imaps',
328                 Keepalive => 1, # SO_KEEPALIVE
329                 %$common, # may set Starttls, Compress, Debug ....
330         };
331         my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or
332                 die "E: <$url> new: $@\n";
333
334         # default to using STARTTLS if it's available, but allow
335         # it to be disabled since I usually connect to localhost
336         if (!$mic_arg->{Ssl} && !defined($mic_arg->{Starttls}) &&
337                         $mic->has_capability('STARTTLS') &&
338                         $mic->can('starttls')) {
339                 $mic->starttls or die "E: <$url> STARTTLS: $@\n";
340         }
341
342         # do we even need credentials?
343         if (!defined($cred->{username}) &&
344                         $mic->has_capability('AUTH=ANONYMOUS')) {
345                 $cred = undef;
346         }
347         if ($cred) {
348                 $cred->check_netrc unless defined $cred->{password};
349                 $cred->fill; # may prompt user here
350                 $mic->User($mic_arg->{User} = $cred->{username});
351                 $mic->Password($mic_arg->{Password} = $cred->{password});
352         } else { # AUTH=ANONYMOUS
353                 $mic->Authmechanism($mic_arg->{Authmechanism} = 'ANONYMOUS');
354                 $mic->Authcallback($mic_arg->{Authcallback} = \&auth_anon_cb);
355         }
356         if ($mic->login && $mic->IsAuthenticated) {
357                 # success! keep IMAPClient->new arg in case we get disconnected
358                 $self->{mic_arg}->{uri_section($uri)} = $mic_arg;
359         } else {
360                 warn "E: <$url> LOGIN: $@\n";
361                 $mic = undef;
362         }
363         $cred->run($mic ? 'approve' : 'reject') if $cred;
364         $mic;
365 }
366
367 sub imap_import_msg ($$$$) {
368         my ($self, $url, $uid, $raw) = @_;
369         # our target audience expects LF-only, save storage
370         $$raw =~ s/\r\n/\n/sg;
371
372         my $inboxes = $self->{imap}->{$url};
373         if (ref($inboxes)) {
374                 for my $ibx (@$inboxes) {
375                         my $eml = PublicInbox::Eml->new($$raw);
376                         my $x = import_eml($self, $ibx, $eml);
377                 }
378         } elsif ($inboxes eq 'watchspam') {
379                 my $eml = PublicInbox::Eml->new($raw);
380                 my $arg = [ $self, $eml, "$url UID:$uid" ];
381                 $self->{config}->each_inbox(\&remove_eml_i, $arg);
382         } else {
383                 die "BUG: destination unknown $inboxes";
384         }
385 }
386
387 sub imap_fetch_all ($$$) {
388         my ($self, $mic, $url) = @_;
389         my $uri = PublicInbox::URIimap->new($url);
390         my $sec = uri_section($uri);
391         my $mbx = $uri->mailbox;
392         $mic->Clear(1); # trim results history
393         $mic->examine($mbx) or return "E: EXAMINE $mbx ($sec) failed: $!";
394         my ($r_uidval, $r_uidnext);
395         for ($mic->Results) {
396                 /^\* OK \[UIDVALIDITY ([0-9]+)\].*/ and $r_uidval = $1;
397                 /^\* OK \[UIDNEXT ([0-9]+)\].*/ and $r_uidnext = $1;
398                 last if $r_uidval && $r_uidnext;
399         }
400         $r_uidval //= $mic->uidvalidity($mbx) //
401                 return "E: $url cannot get UIDVALIDITY";
402         $r_uidnext //= $mic->uidnext($mbx) //
403                 return "E: $url cannot get UIDNEXT";
404         my $itrk = PublicInbox::IMAPTracker->new($url);
405         my ($l_uidval, $l_uid) = $itrk->get_last;
406         $l_uidval //= $r_uidval; # first time
407         $l_uid //= 1;
408         if ($l_uidval != $r_uidval) {
409                 return "E: $url UIDVALIDITY mismatch\n".
410                         "E: local=$l_uidval != remote=$r_uidval";
411         }
412         my $r_uid = $r_uidnext - 1;
413         if ($l_uid != 1 && $l_uid > $r_uid) {
414                 return "E: $url local UID exceeds remote ($l_uid > $r_uid)\n".
415                         "E: $url strangely, UIDVALIDLITY matches ($l_uidval)\n";
416         }
417         return if $l_uid >= $r_uid; # nothing to do
418
419         warn "I: $url fetching UID $l_uid:$r_uid\n";
420         $mic->Uid(1); # the default, we hope
421         my $bs = $self->{imap_opt}->{$sec}->{batch_size} // 1;
422         my $req = $mic->imap4rev1 ? 'BODY.PEEK[]' : 'RFC822.PEEK';
423
424         # TODO: FLAGS may be useful for personal use
425         my $key = $req;
426         $key =~ s/\.PEEK//;
427         my ($uids, $batch);
428         my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
429         local $SIG{__WARN__} = sub {
430                 $batch //= '?';
431                 $warn_cb->("$url UID:$batch\n");
432                 $warn_cb->(@_);
433         };
434         my $err;
435         do {
436                 # I wish "UID FETCH $START:*" could work, but:
437                 # 1) servers do not need to return results in any order
438                 # 2) Mail::IMAPClient doesn't offer a streaming API
439                 $uids = $mic->search("UID $l_uid:*") or
440                         return "E: $url UID SEARCH $l_uid:* error: $!";
441                 return if scalar(@$uids) == 0;
442
443                 # RFC 3501 doesn't seem to indicate order of UID SEARCH
444                 # responses, so sort it ourselves.  Order matters so
445                 # IMAPTracker can store the newest UID.
446                 @$uids = sort { $a <=> $b } @$uids;
447
448                 # Did we actually get new messages?
449                 return if $uids->[0] < $l_uid;
450
451                 $l_uid = $uids->[-1] + 1; # for next search
452                 my $last_uid;
453
454                 while (scalar @$uids) {
455                         my @batch = splice(@$uids, 0, $bs);
456                         $batch = join(',', @batch);
457                         local $0 = "UID:$batch $mbx $sec";
458                         my $r = $mic->fetch_hash($batch, $req);
459                         unless ($r) { # network error?
460                                 $err = "E: $url UID FETCH $batch error: $!";
461                                 last;
462                         }
463                         for my $uid (@batch) {
464                                 # messages get deleted, so holes appear
465                                 my $per_uid = delete $r->{$uid} // next;
466                                 my $raw = delete($per_uid->{$key}) // next;
467                                 imap_import_msg($self, $url, $uid, \$raw);
468                                 $last_uid = $uid;
469                                 last if $self->{quit};
470                         }
471                         last if $self->{quit};
472                 }
473                 _done_for_now($self);
474                 $itrk->update_last($r_uidval, $last_uid) if defined $last_uid;
475         } until ($err || $self->{quit});
476         $err;
477 }
478
479 sub imap_idle_once ($$$$) {
480         my ($self, $mic, $intvl, $url) = @_;
481         my $i = $intvl //= (29 * 60);
482         my $end = now() + $intvl;
483         warn "I: $url idling for ${intvl}s\n";
484         local $0 = "IDLE $0";
485         unless ($mic->idle) {
486                 return if $self->{quit};
487                 return "E: IDLE failed on $url: $!";
488         }
489         $self->{idle_mic} = $mic; # for ->quit
490         my @res;
491         until ($self->{quit} || grep(/^\* [0-9]+ EXISTS/, @res) || $i <= 0) {
492                 @res = $mic->idle_data($i);
493                 $i = $end - now();
494         }
495         delete $self->{idle_mic};
496         unless ($self->{quit}) {
497                 $mic->IsConnected or return "E: IDLE disconnected on $url";
498                 $mic->done or return "E: IDLE DONE failed on $url: $!";
499         }
500         undef;
501 }
502
503 # idles on a single URI
504 sub watch_imap_idle_1 ($$$) {
505         my ($self, $url, $intvl) = @_;
506         my $uri = PublicInbox::URIimap->new($url);
507         my $sec = uri_section($uri);
508         my $mic_arg = $self->{mic_arg}->{$sec} or
509                         die "BUG: no Mail::IMAPClient->new arg for $sec";
510         my $mic;
511         local $0 = $uri->mailbox." $sec";
512         until ($self->{quit}) {
513                 $mic //= PublicInbox::IMAPClient->new(%$mic_arg);
514                 my $err = imap_fetch_all($self, $mic, $url);
515                 $err //= imap_idle_once($self, $mic, $intvl, $url);
516                 if ($err && !$self->{quit}) {
517                         warn $err, "\n";
518                         $mic = undef;
519                         sleep 60 unless $self->{quit};
520                 }
521         }
522 }
523
524 sub watch_atfork_child ($) {
525         my ($self) = @_;
526         delete $self->{idle_pids};
527         delete $self->{poll_pids};
528         delete $self->{opendirs};
529         PublicInbox::DS->Reset;
530         PublicInbox::Sigfd::sig_setmask($self->{oldset});
531         %SIG = (%SIG, %{$self->{sig}});
532 }
533
534 sub watch_atfork_parent ($) {
535         my ($self) = @_;
536         _done_for_now($self);
537 }
538
539 sub imap_idle_reap { # PublicInbox::DS::dwaitpid callback
540         my ($self, $pid) = @_;
541         my $url_intvl = delete $self->{idle_pids}->{$pid} or
542                 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
543
544         my ($url, $intvl) = @$url_intvl;
545         return if $self->{quit};
546         warn "W: PID=$pid on $url died: \$?=$?\n" if $?;
547         push @{$self->{idle_todo}}, $url_intvl;
548         PubicInbox::DS::requeue($self); # call ->event_step to respawn
549 }
550
551 sub imap_idle_fork ($$) {
552         my ($self, $url_intvl) = @_;
553         my ($url, $intvl) = @$url_intvl;
554         defined(my $pid = fork) or die "fork: $!";
555         if ($pid == 0) {
556                 watch_atfork_child($self);
557                 watch_imap_idle_1($self, $url, $intvl);
558                 _exit(0);
559         }
560         $self->{idle_pids}->{$pid} = $url_intvl;
561         PublicInbox::DS::dwaitpid($pid, \&imap_idle_reap, $self);
562 }
563
564 sub event_step {
565         my ($self) = @_;
566         return if $self->{quit};
567         my $idle_todo = $self->{idle_todo};
568         if ($idle_todo && @$idle_todo) {
569                 watch_atfork_parent($self);
570                 while (my $url_intvl = shift(@$idle_todo)) {
571                         imap_idle_fork($self, $url_intvl);
572                 }
573         }
574         goto(&fs_scan_step) if $self->{mdre};
575 }
576
577 sub watch_imap_fetch_all ($$) {
578         my ($self, $urls) = @_;
579         for my $url (@$urls) {
580                 my $uri = PublicInbox::URIimap->new($url);
581                 my $sec = uri_section($uri);
582                 my $mic_arg = $self->{mic_arg}->{$sec} or
583                         die "BUG: no Mail::IMAPClient->new arg for $sec";
584                 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or next;
585                 my $err = imap_fetch_all($self, $mic, $url);
586                 last if $self->{quit};
587                 warn $err, "\n" if $err;
588         }
589 }
590
591 sub watch_nntp_fetch_all ($$) {
592         my ($self, $urls) = @_;
593         for my $url (@$urls) {
594                 my $uri = uri_new($url);
595                 my $sec = uri_section($uri);
596                 my $nn_arg = $self->{nn_arg}->{$sec} or
597                         die "BUG: no Net::NNTP->new arg for $sec";
598                 my $nntp_opt = $self->{nntp_opt}->{$sec};
599                 my $nn = nn_new($nn_arg, $nntp_opt, $url);
600                 unless ($nn) {
601                         warn "E: $url: \$!=$!\n";
602                         next;
603                 }
604                 last if $self->{quit};
605                 if (my $postconn = $nntp_opt->{-postconn}) {
606                         for my $m_arg (@$postconn) {
607                                 my ($method, @args) = @$m_arg;
608                                 $nn->$method(@args) and next;
609                                 warn "E: <$url> $method failed\n";
610                                 $nn = undef;
611                                 last;
612                         }
613                 }
614                 last if $self->{quit};
615                 if ($nn) {
616                         my $err = nntp_fetch_all($self, $nn, $url);
617                         warn $err, "\n" if $err;
618                 }
619         }
620 }
621
622 sub poll_fetch_fork ($) { # DS::add_timer callback
623         my ($self, $intvl, $urls) = @{$_[0]};
624         return if $self->{quit};
625         watch_atfork_parent($self);
626         defined(my $pid = fork) or die "fork: $!";
627         if ($pid == 0) {
628                 watch_atfork_child($self);
629                 if ($urls->[0] =~ m!\Aimaps?://!i) {
630                         watch_imap_fetch_all($self, $urls);
631                 } else {
632                         watch_nntp_fetch_all($self, $urls);
633                 }
634                 _exit(0);
635         }
636         $self->{poll_pids}->{$pid} = [ $intvl, $urls ];
637         PublicInbox::DS::dwaitpid($pid, \&poll_fetch_reap, $self);
638 }
639
640 sub poll_fetch_reap { # PublicInbox::DS::dwaitpid callback
641         my ($self, $pid) = @_;
642         my $intvl_urls = delete $self->{poll_pids}->{$pid} or
643                 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
644         return if $self->{quit};
645         my ($intvl, $urls) = @$intvl_urls;
646         if ($?) {
647                 warn "W: PID=$pid died: \$?=$?\n", map { "$_\n" } @$urls;
648         }
649         warn("I: will check $_ in ${intvl}s\n") for @$urls;
650         PublicInbox::DS::add_timer($intvl, \&poll_fetch_fork,
651                                         [$self, $intvl, $urls]);
652 }
653
654 sub watch_imap_init ($$) {
655         my ($self, $poll) = @_;
656         eval { require PublicInbox::IMAPClient } or
657                 die "Mail::IMAPClient is required for IMAP:\n$@\n";
658         eval { require PublicInbox::IMAPTracker } or
659                 die "DBD::SQLite is required for IMAP\n:$@\n";
660
661         my $mic_args = imap_common_init($self); # read args from config
662
663         # make sure we can connect and cache the credentials in memory
664         $self->{mic_arg} = {}; # schema://authority => IMAPClient->new args
665         my $mics = {}; # schema://authority => IMAPClient obj
666         for my $url (sort keys %{$self->{imap}}) {
667                 my $uri = PublicInbox::URIimap->new($url);
668                 $mics->{uri_section($uri)} //= mic_for($self, $url, $mic_args);
669         }
670
671         my $idle = []; # [ [ url1, intvl1 ], [url2, intvl2] ]
672         for my $url (keys %{$self->{imap}}) {
673                 my $uri = PublicInbox::URIimap->new($url);
674                 my $sec = uri_section($uri);
675                 my $mic = $mics->{$sec};
676                 my $intvl = $self->{imap_opt}->{$sec}->{pollInterval};
677                 if ($mic->has_capability('IDLE') && !$intvl) {
678                         $intvl = $self->{imap_opt}->{$sec}->{idleInterval};
679                         push @$idle, [ $url, $intvl // () ];
680                 } else {
681                         push @{$poll->{$intvl || 120}}, $url;
682                 }
683         }
684         if (scalar @$idle) {
685                 $self->{idle_todo} = $idle;
686                 PublicInbox::DS::requeue($self); # ->event_step to fork
687         }
688 }
689
690 # flesh out common NNTP-specific data structures
691 sub nntp_common_init ($) {
692         my ($self) = @_;
693         my $cfg = $self->{config};
694         my $nn_args = {}; # scheme://authority => Net::NNTP->new arg
695         for my $url (sort keys %{$self->{nntp}}) {
696                 my $sec = uri_section(uri_new($url));
697
698                 # Debug and Timeout are passed to Net::NNTP->new
699                 my $v = cfg_bool($cfg, 'nntp.Debug', $url);
700                 $nn_args->{$sec}->{Debug} = $v if defined $v;
701                 my $to = cfg_intvl($cfg, 'nntp.Timeout', $url);
702                 $nn_args->{$sec}->{Timeout} = $to if $to;
703
704                 # Net::NNTP post-connect commands
705                 for my $k (qw(starttls compress)) {
706                         $v = cfg_bool($cfg, "nntp.$k", $url) // next;
707                         $self->{nntp_opt}->{$sec}->{$k} = $v;
708                 }
709
710                 # internal option
711                 for my $k (qw(pollInterval)) {
712                         $to = cfg_intvl($cfg, "nntp.$k", $url) // next;
713                         $self->{nntp_opt}->{$sec}->{$k} = $to;
714                 }
715         }
716         $nn_args;
717 }
718
719 # Net::NNTP doesn't support CAPABILITIES, yet
720 sub try_starttls ($) {
721         my ($host) = @_;
722         return if $host =~ /\.onion\z/s;
723         return if $host =~ /\A127\.[0-9]+\.[0-9]+\.[0-9]+\z/s;
724         return if $host eq '::1';
725         1;
726 }
727
728 sub nn_new ($$$) {
729         my ($nn_arg, $nntp_opt, $url) = @_;
730         my $nn = Net::NNTP->new(%$nn_arg) or die "E: <$url> new: $!\n";
731
732         # default to using STARTTLS if it's available, but allow
733         # it to be disabled for localhost/VPN users
734         if (!$nn_arg->{SSL} && $nn->can('starttls')) {
735                 if (!defined($nntp_opt->{starttls}) &&
736                                 try_starttls($nn_arg->{Host})) {
737                         # soft fail by default
738                         $nn->starttls or warn <<"";
739 W: <$url> STARTTLS tried and failed (not requested)
740
741                 } elsif ($nntp_opt->{starttls}) {
742                         # hard fail if explicitly configured
743                         $nn->starttls or die <<"";
744 E: <$url> STARTTLS requested and failed
745
746                 }
747         } elsif ($nntp_opt->{starttls}) {
748                 $nn->can('starttls') or
749                         die "E: <$url> Net::NNTP too old for STARTTLS\n";
750                 $nn->starttls or die <<"";
751 E: <$url> STARTTLS requested and failed
752
753         }
754         $nn;
755 }
756
757 sub nn_for ($$$) { # nn = Net::NNTP
758         my ($self, $url, $nn_args) = @_;
759         my $uri = uri_new($url);
760         my $sec = uri_section($uri);
761         my $nntp_opt = $self->{nntp_opt}->{$sec} //= {};
762         my $host = $uri->host;
763         # Net::NNTP and Net::Netrc both mishandle `0', so we pass `127.0.0.1'
764         $host = '127.0.0.1' if $host eq '0';
765         my $cred;
766         my ($u, $p);
767         if (defined(my $ui = $uri->userinfo)) {
768                 require PublicInbox::GitCredential;
769                 $cred = bless {
770                         url => $sec,
771                         protocol => uri_scheme($uri),
772                         host => $host,
773                 }, 'PublicInbox::GitCredential';
774                 ($u, $p) = split(/:/, $ui, 2);
775                 ($cred->{username}, $cred->{password}) = ($u, $p);
776                 $cred->check_netrc unless defined $p;
777         }
778         my $common = $nn_args->{$sec} // {};
779         my $nn_arg = {
780                 Port => $uri->port,
781                 Host => $host,
782                 SSL => $uri->secure, # snews == nntps
783                 %$common, # may Debug ....
784         };
785         my $nn = nn_new($nn_arg, $nntp_opt, $url);
786
787         if ($cred) {
788                 $cred->fill; # may prompt user here
789                 if ($nn->authinfo($u, $p)) {
790                         push @{$nntp_opt->{-postconn}}, [ 'authinfo', $u, $p ];
791                 } else {
792                         warn "E: <$url> AUTHINFO $u XXXX failed\n";
793                         $nn = undef;
794                 }
795         }
796
797         if ($nntp_opt->{compress}) {
798                 # https://rt.cpan.org/Ticket/Display.html?id=129967
799                 if ($nn->can('compress')) {
800                         if ($nn->compress) {
801                                 push @{$nntp_opt->{-postconn}}, [ 'compress' ];
802                         } else {
803                                 warn "W: <$url> COMPRESS failed\n";
804                         }
805                 } else {
806                         delete $nntp_opt->{compress};
807                         warn <<"";
808 W: <$url> COMPRESS not supported by Net::NNTP
809 W: see https://rt.cpan.org/Ticket/Display.html?id=129967 for updates
810
811                 }
812         }
813
814         $self->{nn_arg}->{$sec} = $nn_arg;
815         $cred->run($nn ? 'approve' : 'reject') if $cred;
816         $nn;
817 }
818
819 sub nntp_fetch_all ($$$) {
820         my ($self, $nn, $url) = @_;
821         my $uri = uri_new($url);
822         my ($group, $num_a, $num_b) = $uri->group;
823         my $sec = uri_section($uri);
824         my ($nr, $beg, $end) = $nn->group($group);
825         unless (defined($nr)) {
826                 chomp(my $msg = $nn->message);
827                 return "E: GROUP $group <$sec> $msg";
828         }
829
830         # IMAPTracker is also used for tracking NNTP, UID == article number
831         # LIST.ACTIVE can get the equivalent of UIDVALIDITY, but that's
832         # expensive.  So we assume newsgroups don't change:
833         my $itrk = PublicInbox::IMAPTracker->new($url);
834         my (undef, $l_art) = $itrk->get_last;
835         $l_art //= $beg; # initial import
836
837         # allow users to specify articles to refetch
838         # cf. https://tools.ietf.org/id/draft-gilman-news-url-01.txt
839         # nntp://example.com/inbox.foo/$num_a-$num_b
840         $l_art = $num_a if defined($num_a) && $num_a < $l_art;
841         $end = $num_b if defined($num_b) && $num_b < $end;
842
843         return if $l_art >= $end; # nothing to do
844         $beg = $l_art + 1;
845
846         warn "I: $url fetching ARTICLE $beg..$end\n";
847         my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
848         my ($err, $art);
849         local $SIG{__WARN__} = sub {
850                 $warn_cb->("$url ", $art ? ("ARTICLE $art") : (), "\n", @_);
851         };
852         my $inboxes = $self->{nntp}->{$url};
853         my $last_art;
854         for ($beg..$end) {
855                 last if $self->{quit};
856                 $art = $_;
857                 my $raw = $nn->article($art);
858                 unless (defined($raw)) {
859                         my $msg = $nn->message;
860                         if ($nn->code == 421) { # pseudo response from Net::Cmd
861                                 $err = "E: $msg";
862                                 last;
863                         } else { # probably just a deleted message (spam)
864                                 warn "W: $msg";
865                                 next;
866                         }
867                 }
868                 s/\r\n/\n/ for @$raw;
869                 $raw = join('', @$raw);
870                 if (ref($inboxes)) {
871                         for my $ibx (@$inboxes) {
872                                 my $eml = PublicInbox::Eml->new($raw);
873                                 import_eml($self, $ibx, $eml);
874                         }
875                 } elsif ($inboxes eq 'watchspam') {
876                         my $eml = PublicInbox::Eml->new(\$raw);
877                         my $arg = [ $self, $eml, "$url ARTICLE $art" ];
878                         $self->{config}->each_inbox(\&remove_eml_i, $arg);
879                 } else {
880                         die "BUG: destination unknown $inboxes";
881                 }
882                 $last_art = $art;
883         }
884         $itrk->update_last(0, $last_art) if defined $last_art;
885         _done_for_now($self);
886         $err;
887 }
888
889 sub watch_nntp_init ($$) {
890         my ($self, $poll) = @_;
891         eval { require Net::NNTP } or
892                 die "Net::NNTP is required for NNTP:\n$@\n";
893         eval { require PublicInbox::IMAPTracker } or
894                 die "DBD::SQLite is required for NNTP\n:$@\n";
895
896         my $nn_args = nntp_common_init($self); # read args from config
897
898         # make sure we can connect and cache the credentials in memory
899         $self->{nn_arg} = {}; # schema://authority => Net::NNTP->new args
900         for my $url (sort keys %{$self->{nntp}}) {
901                 nn_for($self, $url, $nn_args);
902         }
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}}, $url;
908         }
909 }
910
911 sub watch {
912         my ($self, $sig, $oldset) = @_;
913         $self->{oldset} = $oldset;
914         $self->{sig} = $sig;
915         my $poll = {}; # intvl_seconds => [ url1, url2 ]
916         watch_imap_init($self, $poll) if $self->{imap};
917         watch_nntp_init($self, $poll) if $self->{nntp};
918         while (my ($intvl, $urls) = each %$poll) {
919                 # poll all URLs for a given interval sequentially
920                 PublicInbox::DS::add_timer(0, \&poll_fetch_fork,
921                                                 [$self, $intvl, $urls]);
922         }
923         watch_fs_init($self) if $self->{mdre};
924         PublicInbox::DS->SetPostLoopCallback(sub {});
925         PublicInbox::DS->EventLoop until $self->{quit};
926         _done_for_now($self);
927 }
928
929 sub trigger_scan {
930         my ($self, $op) = @_;
931         push @{$self->{ops}}, $op;
932         PublicInbox::DS::requeue($self);
933 }
934
935 sub fs_scan_step {
936         my ($self) = @_;
937         return if $self->{quit};
938         my $op = shift @{$self->{ops}};
939
940         # continue existing scan
941         my $max = 10;
942         my $opendirs = $self->{opendirs};
943         my @dirnames = keys %$opendirs;
944         foreach my $dir (@dirnames) {
945                 my $dh = delete $opendirs->{$dir};
946                 my $n = $max;
947                 while (my $fn = readdir($dh)) {
948                         _try_path($self, "$dir/$fn");
949                         last if --$n < 0;
950                 }
951                 $opendirs->{$dir} = $dh if $n < 0;
952         }
953         if ($op && $op eq 'full') {
954                 foreach my $dir (keys %{$self->{mdmap}}) {
955                         next if $opendirs->{$dir}; # already in progress
956                         my $ok = opendir(my $dh, $dir);
957                         unless ($ok) {
958                                 warn "failed to open $dir: $!\n";
959                                 next;
960                         }
961                         my $n = $max;
962                         while (my $fn = readdir($dh)) {
963                                 _try_path($self, "$dir/$fn");
964                                 last if --$n < 0;
965                         }
966                         $opendirs->{$dir} = $dh if $n < 0;
967                 }
968         }
969         _done_for_now($self);
970         # do we have more work to do?
971         PublicInbox::DS::requeue($self) if keys %$opendirs;
972 }
973
974 sub scan {
975         my ($self, $op) = @_;
976         push @{$self->{ops}}, $op;
977         goto &fs_scan_step;
978 }
979
980 sub _importer_for {
981         my ($self, $ibx) = @_;
982         my $importers = $self->{importers};
983         my $im = $importers->{"$ibx"} ||= $ibx->importer(0);
984         if (scalar(keys(%$importers)) > 2) {
985                 delete $importers->{"$ibx"};
986                 _done_for_now($self);
987         }
988
989         $importers->{"$ibx"} = $im;
990 }
991
992 # XXX consider sharing with V2Writable, this only requires read-only access
993 sub content_exists ($$) {
994         my ($ibx, $eml) = @_;
995         my $over = $ibx->over or return;
996         my $mids = mids($eml);
997         my $chash = content_hash($eml);
998         my ($id, $prev);
999         for my $mid (@$mids) {
1000                 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
1001                         my $cmp = $ibx->smsg_eml($smsg) or return;
1002                         return 1 if $chash eq content_hash($cmp);
1003                 }
1004         }
1005         undef;
1006 }
1007
1008 sub _spamcheck_cb {
1009         my ($sc) = @_;
1010         sub {
1011                 my ($mime, $ibx) = @_;
1012                 return if content_exists($ibx, $mime);
1013                 my $tmp = '';
1014                 if ($sc->spamcheck($mime, \$tmp)) {
1015                         return PublicInbox::Eml->new(\$tmp);
1016                 }
1017                 warn $mime->header('Message-ID')." failed spam check\n";
1018                 undef;
1019         }
1020 }
1021
1022 sub is_maildir {
1023         $_[0] =~ s!\Amaildir:!! or return;
1024         $_[0] =~ tr!/!/!s;
1025         $_[0] =~ s!/\z!!;
1026         $_[0];
1027 }
1028
1029 sub is_watchspam {
1030         my ($cur, $ws, $ibx) = @_;
1031         if ($ws && !ref($ws) && $ws eq 'watchspam') {
1032                 warn <<EOF;
1033 E: $cur is a spam folder and cannot be used for `$ibx->{name}' input
1034 EOF
1035                 return 1;
1036         }
1037         undef;
1038 }
1039
1040 sub uri_new {
1041         my ($url) = @_;
1042
1043         # URI::snews exists, URI::nntps does not, so use URI::snews
1044         $url =~ s!\Anntps://!snews://!i;
1045         URI->new($url);
1046 }
1047
1048 sub imap_url {
1049         my ($url) = @_;
1050         require PublicInbox::URIimap;
1051         my $uri = PublicInbox::URIimap->new($url);
1052         $uri ? $uri->canonical->as_string : undef;
1053 }
1054
1055 my %IS_NNTP = (news => 1, snews => 1, nntp => 1);
1056 sub nntp_url {
1057         my ($url) = @_;
1058         require URI;
1059         my $uri = uri_new($url);
1060         return unless $uri && $IS_NNTP{$uri->scheme} && $uri->group;
1061         $url = $uri->canonical->as_string;
1062         # nntps is IANA registered, snews is deprecated
1063         $url =~ s!\Asnews://!nntps://!;
1064         $url;
1065 }
1066
1067 1;