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