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