]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Watch.pm
watch: block signals before fork on non-signalfd/kevent systems
[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
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__} = warn_ignore_cb();
178         $self->{config}->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__} || sub { print STDERR @_ };
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 {
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->{config};
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                         my $x = import_eml($self, $ibx, $eml);
415                 }
416         } elsif ($inboxes eq 'watchspam') {
417                 # we don't remove unseen messages
418                 if ($flags =~ /\\Seen\b/) {
419                         local $SIG{__WARN__} = warn_ignore_cb();
420                         my $eml = PublicInbox::Eml->new($raw);
421                         my $arg = [ $self, $eml, "$url UID:$uid" ];
422                         $self->{config}->each_inbox(\&remove_eml_i, $arg);
423                 }
424         } else {
425                 die "BUG: destination unknown $inboxes";
426         }
427 }
428
429 sub imap_fetch_all ($$$) {
430         my ($self, $mic, $url) = @_;
431         my $uri = PublicInbox::URIimap->new($url);
432         my $sec = uri_section($uri);
433         my $mbx = $uri->mailbox;
434         $mic->Clear(1); # trim results history
435         $mic->examine($mbx) or return "E: EXAMINE $mbx ($sec) failed: $!";
436         my ($r_uidval, $r_uidnext);
437         for ($mic->Results) {
438                 /^\* OK \[UIDVALIDITY ([0-9]+)\].*/ and $r_uidval = $1;
439                 /^\* OK \[UIDNEXT ([0-9]+)\].*/ and $r_uidnext = $1;
440                 last if $r_uidval && $r_uidnext;
441         }
442         $r_uidval //= $mic->uidvalidity($mbx) //
443                 return "E: $url cannot get UIDVALIDITY";
444         $r_uidnext //= $mic->uidnext($mbx) //
445                 return "E: $url cannot get UIDNEXT";
446         my $itrk = PublicInbox::IMAPTracker->new($url);
447         my ($l_uidval, $l_uid) = $itrk->get_last;
448         $l_uidval //= $r_uidval; # first time
449         $l_uid //= 1;
450         if ($l_uidval != $r_uidval) {
451                 return "E: $url UIDVALIDITY mismatch\n".
452                         "E: local=$l_uidval != remote=$r_uidval";
453         }
454         my $r_uid = $r_uidnext - 1;
455         if ($l_uid != 1 && $l_uid > $r_uid) {
456                 return "E: $url local UID exceeds remote ($l_uid > $r_uid)\n".
457                         "E: $url strangely, UIDVALIDLITY matches ($l_uidval)\n";
458         }
459         return if $l_uid >= $r_uid; # nothing to do
460
461         warn "I: $url fetching UID $l_uid:$r_uid\n";
462         $mic->Uid(1); # the default, we hope
463         my $bs = $self->{imap_opt}->{$sec}->{batch_size} // 1;
464         my $req = $mic->imap4rev1 ? 'BODY.PEEK[]' : 'RFC822.PEEK';
465
466         # TODO: FLAGS may be useful for personal use
467         my $key = $req;
468         $key =~ s/\.PEEK//;
469         my ($uids, $batch);
470         my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
471         local $SIG{__WARN__} = sub {
472                 my $pfx = ($_[0] // '') =~ /^([A-Z]: )/g ? $1 : '';
473                 $batch //= '?';
474                 $warn_cb->("$pfx$url UID:$batch\n", @_);
475         };
476         my $err;
477         do {
478                 # I wish "UID FETCH $START:*" could work, but:
479                 # 1) servers do not need to return results in any order
480                 # 2) Mail::IMAPClient doesn't offer a streaming API
481                 $uids = $mic->search("UID $l_uid:*") or
482                         return "E: $url UID SEARCH $l_uid:* error: $!";
483                 return if scalar(@$uids) == 0;
484
485                 # RFC 3501 doesn't seem to indicate order of UID SEARCH
486                 # responses, so sort it ourselves.  Order matters so
487                 # IMAPTracker can store the newest UID.
488                 @$uids = sort { $a <=> $b } @$uids;
489
490                 # Did we actually get new messages?
491                 return if $uids->[0] < $l_uid;
492
493                 $l_uid = $uids->[-1] + 1; # for next search
494                 my $last_uid;
495                 my $n = $self->{max_batch};
496
497                 while (scalar @$uids) {
498                         if (--$n < 0) {
499                                 _done_for_now($self);
500                                 $itrk->update_last($r_uidval, $last_uid);
501                                 $n = $self->{max_batch};
502                         }
503                         my @batch = splice(@$uids, 0, $bs);
504                         $batch = join(',', @batch);
505                         local $0 = "UID:$batch $mbx $sec";
506                         my $r = $mic->fetch_hash($batch, $req, 'FLAGS');
507                         unless ($r) { # network error?
508                                 $err = "E: $url UID FETCH $batch error: $!";
509                                 last;
510                         }
511                         for my $uid (@batch) {
512                                 # messages get deleted, so holes appear
513                                 my $per_uid = delete $r->{$uid} // next;
514                                 my $raw = delete($per_uid->{$key}) // next;
515                                 my $fl = $per_uid->{FLAGS} // '';
516                                 imap_import_msg($self, $url, $uid, \$raw, $fl);
517                                 $last_uid = $uid;
518                                 last if $self->{quit};
519                         }
520                         last if $self->{quit};
521                 }
522                 _done_for_now($self);
523                 $itrk->update_last($r_uidval, $last_uid);
524         } until ($err || $self->{quit});
525         $err;
526 }
527
528 sub imap_idle_once ($$$$) {
529         my ($self, $mic, $intvl, $url) = @_;
530         my $i = $intvl //= (29 * 60);
531         my $end = now() + $intvl;
532         warn "I: $url idling for ${intvl}s\n";
533         local $0 = "IDLE $0";
534         unless ($mic->idle) {
535                 return if $self->{quit};
536                 return "E: IDLE failed on $url: $!";
537         }
538         $self->{idle_mic} = $mic; # for ->quit
539         my @res;
540         until ($self->{quit} || !$mic->IsConnected ||
541                         grep(/^\* [0-9]+ EXISTS/, @res) || $i <= 0) {
542                 @res = $mic->idle_data($i);
543                 $i = $end - now();
544         }
545         delete $self->{idle_mic};
546         unless ($self->{quit}) {
547                 $mic->IsConnected or return "E: IDLE disconnected on $url";
548                 $mic->done or return "E: IDLE DONE failed on $url: $!";
549         }
550         undef;
551 }
552
553 # idles on a single URI
554 sub watch_imap_idle_1 ($$$) {
555         my ($self, $url, $intvl) = @_;
556         my $uri = PublicInbox::URIimap->new($url);
557         my $sec = uri_section($uri);
558         my $mic_arg = $self->{mic_arg}->{$sec} or
559                         die "BUG: no Mail::IMAPClient->new arg for $sec";
560         my $mic;
561         local $0 = $uri->mailbox." $sec";
562         until ($self->{quit}) {
563                 $mic //= PublicInbox::IMAPClient->new(%$mic_arg);
564                 my $err;
565                 if ($mic && $mic->IsConnected) {
566                         $err = imap_fetch_all($self, $mic, $url);
567                         $err //= imap_idle_once($self, $mic, $intvl, $url);
568                 } else {
569                         $err = "not connected: $!";
570                 }
571                 if ($err && !$self->{quit}) {
572                         warn $err, "\n";
573                         $mic = undef;
574                         sleep 60 unless $self->{quit};
575                 }
576         }
577 }
578
579 sub watch_atfork_child ($) {
580         my ($self) = @_;
581         delete $self->{idle_pids};
582         delete $self->{poll_pids};
583         delete $self->{opendirs};
584         PublicInbox::DS->Reset;
585         %SIG = (%SIG, %{$self->{sig}}, CHLD => 'DEFAULT');
586         PublicInbox::Sigfd::sig_setmask($self->{oldset});
587 }
588
589 sub watch_atfork_parent ($) {
590         my ($self) = @_;
591         _done_for_now($self);
592         PublicInbox::Sigfd::block_signals();
593 }
594
595 sub imap_idle_requeue ($) { # DS::add_timer callback
596         my ($self, $url_intvl) = @{$_[0]};
597         return if $self->{quit};
598         push @{$self->{idle_todo}}, $url_intvl;
599         event_step($self);
600 }
601
602 sub imap_idle_reap { # PublicInbox::DS::dwaitpid callback
603         my ($self, $pid) = @_;
604         my $url_intvl = delete $self->{idle_pids}->{$pid} or
605                 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
606
607         my ($url, $intvl) = @$url_intvl;
608         return if $self->{quit};
609         warn "W: PID=$pid on $url died: \$?=$?\n" if $?;
610         PublicInbox::DS::add_timer(60,
611                                 \&imap_idle_requeue, [ $self, $url_intvl ]);
612 }
613
614 sub imap_idle_fork ($$) {
615         my ($self, $url_intvl) = @_;
616         my ($url, $intvl) = @$url_intvl;
617         defined(my $pid = fork) or die "fork: $!";
618         if ($pid == 0) {
619                 watch_atfork_child($self);
620                 watch_imap_idle_1($self, $url, $intvl);
621                 _exit(0);
622         }
623         $self->{idle_pids}->{$pid} = $url_intvl;
624         PublicInbox::DS::dwaitpid($pid, \&imap_idle_reap, $self);
625 }
626
627 sub event_step {
628         my ($self) = @_;
629         return if $self->{quit};
630         my $idle_todo = $self->{idle_todo};
631         if ($idle_todo && @$idle_todo) {
632                 my $oldset = watch_atfork_parent($self);
633                 eval {
634                         while (my $url_intvl = shift(@$idle_todo)) {
635                                 imap_idle_fork($self, $url_intvl);
636                         }
637                 };
638                 PublicInbox::Sigfd::sig_setmask($oldset);
639                 die $@ if $@;
640         }
641         goto(&fs_scan_step) if $self->{mdre};
642 }
643
644 sub watch_imap_fetch_all ($$) {
645         my ($self, $urls) = @_;
646         for my $url (@$urls) {
647                 my $uri = PublicInbox::URIimap->new($url);
648                 my $sec = uri_section($uri);
649                 my $mic_arg = $self->{mic_arg}->{$sec} or
650                         die "BUG: no Mail::IMAPClient->new arg for $sec";
651                 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or next;
652                 my $err = imap_fetch_all($self, $mic, $url);
653                 last if $self->{quit};
654                 warn $err, "\n" if $err;
655         }
656 }
657
658 sub watch_nntp_fetch_all ($$) {
659         my ($self, $urls) = @_;
660         for my $url (@$urls) {
661                 my $uri = uri_new($url);
662                 my $sec = uri_section($uri);
663                 my $nn_arg = $self->{nn_arg}->{$sec} or
664                         die "BUG: no Net::NNTP->new arg for $sec";
665                 my $nntp_opt = $self->{nntp_opt}->{$sec};
666                 my $nn = nn_new($nn_arg, $nntp_opt, $url);
667                 unless ($nn) {
668                         warn "E: $url: \$!=$!\n";
669                         next;
670                 }
671                 last if $self->{quit};
672                 if (my $postconn = $nntp_opt->{-postconn}) {
673                         for my $m_arg (@$postconn) {
674                                 my ($method, @args) = @$m_arg;
675                                 $nn->$method(@args) and next;
676                                 warn "E: <$url> $method failed\n";
677                                 $nn = undef;
678                                 last;
679                         }
680                 }
681                 last if $self->{quit};
682                 if ($nn) {
683                         my $err = nntp_fetch_all($self, $nn, $url);
684                         warn $err, "\n" if $err;
685                 }
686         }
687 }
688
689 sub poll_fetch_fork ($) { # DS::add_timer callback
690         my ($self, $intvl, $urls) = @{$_[0]};
691         return if $self->{quit};
692         my $oldset = watch_atfork_parent($self);
693         my $pid = fork;
694         if (defined($pid) && $pid == 0) {
695                 watch_atfork_child($self);
696                 if ($urls->[0] =~ m!\Aimaps?://!i) {
697                         watch_imap_fetch_all($self, $urls);
698                 } else {
699                         watch_nntp_fetch_all($self, $urls);
700                 }
701                 _exit(0);
702         }
703         PublicInbox::Sigfd::sig_setmask($oldset);
704         die "fork: $!"  unless defined $pid;
705         $self->{poll_pids}->{$pid} = [ $intvl, $urls ];
706         PublicInbox::DS::dwaitpid($pid, \&poll_fetch_reap, $self);
707 }
708
709 sub poll_fetch_reap { # PublicInbox::DS::dwaitpid callback
710         my ($self, $pid) = @_;
711         my $intvl_urls = delete $self->{poll_pids}->{$pid} or
712                 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
713         return if $self->{quit};
714         my ($intvl, $urls) = @$intvl_urls;
715         if ($?) {
716                 warn "W: PID=$pid died: \$?=$?\n", map { "$_\n" } @$urls;
717         }
718         warn("I: will check $_ in ${intvl}s\n") for @$urls;
719         PublicInbox::DS::add_timer($intvl, \&poll_fetch_fork,
720                                         [$self, $intvl, $urls]);
721 }
722
723 sub watch_imap_init ($$) {
724         my ($self, $poll) = @_;
725         eval { require PublicInbox::IMAPClient } or
726                 die "Mail::IMAPClient is required for IMAP:\n$@\n";
727         eval { require PublicInbox::IMAPTracker } or
728                 die "DBD::SQLite is required for IMAP\n:$@\n";
729
730         my $mic_args = imap_common_init($self); # read args from config
731
732         # make sure we can connect and cache the credentials in memory
733         $self->{mic_arg} = {}; # schema://authority => IMAPClient->new args
734         my $mics = {}; # schema://authority => IMAPClient obj
735         for my $url (sort keys %{$self->{imap}}) {
736                 my $uri = PublicInbox::URIimap->new($url);
737                 $mics->{uri_section($uri)} //= mic_for($self, $url, $mic_args);
738         }
739
740         my $idle = []; # [ [ url1, intvl1 ], [url2, intvl2] ]
741         for my $url (keys %{$self->{imap}}) {
742                 my $uri = PublicInbox::URIimap->new($url);
743                 my $sec = uri_section($uri);
744                 my $mic = $mics->{$sec};
745                 my $intvl = $self->{imap_opt}->{$sec}->{pollInterval};
746                 if ($mic->has_capability('IDLE') && !$intvl) {
747                         $intvl = $self->{imap_opt}->{$sec}->{idleInterval};
748                         push @$idle, [ $url, $intvl // () ];
749                 } else {
750                         push @{$poll->{$intvl || 120}}, $url;
751                 }
752         }
753         if (scalar @$idle) {
754                 $self->{idle_todo} = $idle;
755                 PublicInbox::DS::requeue($self); # ->event_step to fork
756         }
757 }
758
759 # flesh out common NNTP-specific data structures
760 sub nntp_common_init ($) {
761         my ($self) = @_;
762         my $cfg = $self->{config};
763         my $nn_args = {}; # scheme://authority => Net::NNTP->new arg
764         for my $url (sort keys %{$self->{nntp}}) {
765                 my $sec = uri_section(uri_new($url));
766
767                 # Debug and Timeout are passed to Net::NNTP->new
768                 my $v = cfg_bool($cfg, 'nntp.Debug', $url);
769                 $nn_args->{$sec}->{Debug} = $v if defined $v;
770                 my $to = cfg_intvl($cfg, 'nntp.Timeout', $url);
771                 $nn_args->{$sec}->{Timeout} = $to if $to;
772
773                 # Net::NNTP post-connect commands
774                 for my $k (qw(starttls compress)) {
775                         $v = cfg_bool($cfg, "nntp.$k", $url) // next;
776                         $self->{nntp_opt}->{$sec}->{$k} = $v;
777                 }
778
779                 # internal option
780                 for my $k (qw(pollInterval)) {
781                         $to = cfg_intvl($cfg, "nntp.$k", $url) // next;
782                         $self->{nntp_opt}->{$sec}->{$k} = $to;
783                 }
784         }
785         $nn_args;
786 }
787
788 # Net::NNTP doesn't support CAPABILITIES, yet
789 sub try_starttls ($) {
790         my ($host) = @_;
791         return if $host =~ /\.onion\z/s;
792         return if $host =~ /\A127\.[0-9]+\.[0-9]+\.[0-9]+\z/s;
793         return if $host eq '::1';
794         1;
795 }
796
797 sub nn_new ($$$) {
798         my ($nn_arg, $nntp_opt, $url) = @_;
799         my $nn = Net::NNTP->new(%$nn_arg) or die "E: <$url> new: $!\n";
800
801         # default to using STARTTLS if it's available, but allow
802         # it to be disabled for localhost/VPN users
803         if (!$nn_arg->{SSL} && $nn->can('starttls')) {
804                 if (!defined($nntp_opt->{starttls}) &&
805                                 try_starttls($nn_arg->{Host})) {
806                         # soft fail by default
807                         $nn->starttls or warn <<"";
808 W: <$url> STARTTLS tried and failed (not requested)
809
810                 } elsif ($nntp_opt->{starttls}) {
811                         # hard fail if explicitly configured
812                         $nn->starttls or die <<"";
813 E: <$url> STARTTLS requested and failed
814
815                 }
816         } elsif ($nntp_opt->{starttls}) {
817                 $nn->can('starttls') or
818                         die "E: <$url> Net::NNTP too old for STARTTLS\n";
819                 $nn->starttls or die <<"";
820 E: <$url> STARTTLS requested and failed
821
822         }
823         $nn;
824 }
825
826 sub nn_for ($$$) { # nn = Net::NNTP
827         my ($self, $url, $nn_args) = @_;
828         my $uri = uri_new($url);
829         my $sec = uri_section($uri);
830         my $nntp_opt = $self->{nntp_opt}->{$sec} //= {};
831         my $host = $uri->host;
832         # Net::NNTP and Net::Netrc both mishandle `0', so we pass `127.0.0.1'
833         $host = '127.0.0.1' if $host eq '0';
834         my $cred;
835         my ($u, $p);
836         if (defined(my $ui = $uri->userinfo)) {
837                 require PublicInbox::GitCredential;
838                 $cred = bless {
839                         url => $sec,
840                         protocol => uri_scheme($uri),
841                         host => $host,
842                 }, 'PublicInbox::GitCredential';
843                 ($u, $p) = split(/:/, $ui, 2);
844                 ($cred->{username}, $cred->{password}) = ($u, $p);
845                 $cred->check_netrc unless defined $p;
846         }
847         my $common = $nn_args->{$sec} // {};
848         my $nn_arg = {
849                 Port => $uri->port,
850                 Host => $host,
851                 SSL => $uri->secure, # snews == nntps
852                 %$common, # may Debug ....
853         };
854         my $nn = nn_new($nn_arg, $nntp_opt, $url);
855
856         if ($cred) {
857                 $cred->fill; # may prompt user here
858                 if ($nn->authinfo($u, $p)) {
859                         push @{$nntp_opt->{-postconn}}, [ 'authinfo', $u, $p ];
860                 } else {
861                         warn "E: <$url> AUTHINFO $u XXXX failed\n";
862                         $nn = undef;
863                 }
864         }
865
866         if ($nntp_opt->{compress}) {
867                 # https://rt.cpan.org/Ticket/Display.html?id=129967
868                 if ($nn->can('compress')) {
869                         if ($nn->compress) {
870                                 push @{$nntp_opt->{-postconn}}, [ 'compress' ];
871                         } else {
872                                 warn "W: <$url> COMPRESS failed\n";
873                         }
874                 } else {
875                         delete $nntp_opt->{compress};
876                         warn <<"";
877 W: <$url> COMPRESS not supported by Net::NNTP
878 W: see https://rt.cpan.org/Ticket/Display.html?id=129967 for updates
879
880                 }
881         }
882
883         $self->{nn_arg}->{$sec} = $nn_arg;
884         $cred->run($nn ? 'approve' : 'reject') if $cred;
885         $nn;
886 }
887
888 sub nntp_fetch_all ($$$) {
889         my ($self, $nn, $url) = @_;
890         my $uri = uri_new($url);
891         my ($group, $num_a, $num_b) = $uri->group;
892         my $sec = uri_section($uri);
893         my ($nr, $beg, $end) = $nn->group($group);
894         unless (defined($nr)) {
895                 chomp(my $msg = $nn->message);
896                 return "E: GROUP $group <$sec> $msg";
897         }
898
899         # IMAPTracker is also used for tracking NNTP, UID == article number
900         # LIST.ACTIVE can get the equivalent of UIDVALIDITY, but that's
901         # expensive.  So we assume newsgroups don't change:
902         my $itrk = PublicInbox::IMAPTracker->new($url);
903         my (undef, $l_art) = $itrk->get_last;
904         $l_art //= $beg; # initial import
905
906         # allow users to specify articles to refetch
907         # cf. https://tools.ietf.org/id/draft-gilman-news-url-01.txt
908         # nntp://example.com/inbox.foo/$num_a-$num_b
909         $l_art = $num_a if defined($num_a) && $num_a < $l_art;
910         $end = $num_b if defined($num_b) && $num_b < $end;
911
912         return if $l_art >= $end; # nothing to do
913         $beg = $l_art + 1;
914
915         warn "I: $url fetching ARTICLE $beg..$end\n";
916         my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
917         my ($err, $art);
918         local $SIG{__WARN__} = sub {
919                 my $pfx = ($_[0] // '') =~ /^([A-Z]: )/g ? $1 : '';
920                 $warn_cb->("$pfx$url ", $art ? ("ARTICLE $art") : (), "\n", @_);
921         };
922         my $inboxes = $self->{nntp}->{$url};
923         my $last_art;
924         my $n = $self->{max_batch};
925         for ($beg..$end) {
926                 last if $self->{quit};
927                 $art = $_;
928                 if (--$n < 0) {
929                         _done_for_now($self);
930                         $itrk->update_last(0, $last_art);
931                         $n = $self->{max_batch};
932                 }
933                 my $raw = $nn->article($art);
934                 unless (defined($raw)) {
935                         my $msg = $nn->message;
936                         if ($nn->code == 421) { # pseudo response from Net::Cmd
937                                 $err = "E: $msg";
938                                 last;
939                         } else { # probably just a deleted message (spam)
940                                 warn "W: $msg";
941                                 next;
942                         }
943                 }
944                 s/\r\n/\n/ for @$raw;
945                 $raw = join('', @$raw);
946                 if (ref($inboxes)) {
947                         for my $ibx (@$inboxes) {
948                                 my $eml = PublicInbox::Eml->new($raw);
949                                 import_eml($self, $ibx, $eml);
950                         }
951                 } elsif ($inboxes eq 'watchspam') {
952                         my $eml = PublicInbox::Eml->new(\$raw);
953                         my $arg = [ $self, $eml, "$url ARTICLE $art" ];
954                         $self->{config}->each_inbox(\&remove_eml_i, $arg);
955                 } else {
956                         die "BUG: destination unknown $inboxes";
957                 }
958                 $last_art = $art;
959         }
960         _done_for_now($self);
961         $itrk->update_last(0, $last_art);
962         $err;
963 }
964
965 sub watch_nntp_init ($$) {
966         my ($self, $poll) = @_;
967         eval { require Net::NNTP } or
968                 die "Net::NNTP is required for NNTP:\n$@\n";
969         eval { require PublicInbox::IMAPTracker } or
970                 die "DBD::SQLite is required for NNTP\n:$@\n";
971
972         my $nn_args = nntp_common_init($self); # read args from config
973
974         # make sure we can connect and cache the credentials in memory
975         $self->{nn_arg} = {}; # schema://authority => Net::NNTP->new args
976         for my $url (sort keys %{$self->{nntp}}) {
977                 nn_for($self, $url, $nn_args);
978         }
979         for my $url (keys %{$self->{nntp}}) {
980                 my $uri = uri_new($url);
981                 my $sec = uri_section($uri);
982                 my $intvl = $self->{nntp_opt}->{$sec}->{pollInterval};
983                 push @{$poll->{$intvl || 120}}, $url;
984         }
985 }
986
987 sub watch {
988         my ($self, $sig, $oldset) = @_;
989         $self->{oldset} = $oldset;
990         $self->{sig} = $sig;
991         my $poll = {}; # intvl_seconds => [ url1, url2 ]
992         watch_imap_init($self, $poll) if $self->{imap};
993         watch_nntp_init($self, $poll) if $self->{nntp};
994         while (my ($intvl, $urls) = each %$poll) {
995                 # poll all URLs for a given interval sequentially
996                 PublicInbox::DS::add_timer(0, \&poll_fetch_fork,
997                                                 [$self, $intvl, $urls]);
998         }
999         watch_fs_init($self) if $self->{mdre};
1000         PublicInbox::DS->SetPostLoopCallback(sub { !$self->quit_done });
1001         PublicInbox::DS->EventLoop;
1002         _done_for_now($self);
1003 }
1004
1005 sub trigger_scan {
1006         my ($self, $op) = @_;
1007         push @{$self->{ops}}, $op;
1008         PublicInbox::DS::requeue($self);
1009 }
1010
1011 sub fs_scan_step {
1012         my ($self) = @_;
1013         return if $self->{quit};
1014         my $op = shift @{$self->{ops}};
1015         local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
1016
1017         # continue existing scan
1018         my $opendirs = $self->{opendirs};
1019         my @dirnames = keys %$opendirs;
1020         foreach my $dir (@dirnames) {
1021                 my $dh = delete $opendirs->{$dir};
1022                 my $n = $self->{max_batch};
1023                 while (my $fn = readdir($dh)) {
1024                         _try_path($self, "$dir/$fn");
1025                         last if --$n < 0;
1026                 }
1027                 $opendirs->{$dir} = $dh if $n < 0;
1028         }
1029         if ($op && $op eq 'full') {
1030                 foreach my $dir (keys %{$self->{mdmap}}) {
1031                         next if $opendirs->{$dir}; # already in progress
1032                         my $ok = opendir(my $dh, $dir);
1033                         unless ($ok) {
1034                                 warn "failed to open $dir: $!\n";
1035                                 next;
1036                         }
1037                         my $n = $self->{max_batch};
1038                         while (my $fn = readdir($dh)) {
1039                                 _try_path($self, "$dir/$fn");
1040                                 last if --$n < 0;
1041                         }
1042                         $opendirs->{$dir} = $dh if $n < 0;
1043                 }
1044         }
1045         _done_for_now($self);
1046         # do we have more work to do?
1047         PublicInbox::DS::requeue($self) if keys %$opendirs;
1048 }
1049
1050 sub scan {
1051         my ($self, $op) = @_;
1052         push @{$self->{ops}}, $op;
1053         goto &fs_scan_step;
1054 }
1055
1056 sub _importer_for {
1057         my ($self, $ibx) = @_;
1058         my $importers = $self->{importers};
1059         my $im = $importers->{"$ibx"} ||= $ibx->importer(0);
1060         if (scalar(keys(%$importers)) > 2) {
1061                 delete $importers->{"$ibx"};
1062                 _done_for_now($self);
1063         }
1064
1065         $importers->{"$ibx"} = $im;
1066 }
1067
1068 # XXX consider sharing with V2Writable, this only requires read-only access
1069 sub content_exists ($$) {
1070         my ($ibx, $eml) = @_;
1071         my $over = $ibx->over or return;
1072         my $mids = mids($eml);
1073         my $chash = content_hash($eml);
1074         my ($id, $prev);
1075         for my $mid (@$mids) {
1076                 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
1077                         my $cmp = $ibx->smsg_eml($smsg) or return;
1078                         return 1 if $chash eq content_hash($cmp);
1079                 }
1080         }
1081         undef;
1082 }
1083
1084 sub _spamcheck_cb {
1085         my ($sc) = @_;
1086         sub {
1087                 my ($mime, $ibx) = @_;
1088                 return if content_exists($ibx, $mime);
1089                 my $tmp = '';
1090                 if ($sc->spamcheck($mime, \$tmp)) {
1091                         return PublicInbox::Eml->new(\$tmp);
1092                 }
1093                 warn $mime->header('Message-ID')." failed spam check\n";
1094                 undef;
1095         }
1096 }
1097
1098 sub is_maildir {
1099         $_[0] =~ s!\Amaildir:!! or return;
1100         $_[0] =~ tr!/!/!s;
1101         $_[0] =~ s!/\z!!;
1102         $_[0];
1103 }
1104
1105 sub is_watchspam {
1106         my ($cur, $ws, $ibx) = @_;
1107         if ($ws && !ref($ws) && $ws eq 'watchspam') {
1108                 warn <<EOF;
1109 E: $cur is a spam folder and cannot be used for `$ibx->{name}' input
1110 EOF
1111                 return 1;
1112         }
1113         undef;
1114 }
1115
1116 sub uri_new {
1117         my ($url) = @_;
1118
1119         # URI::snews exists, URI::nntps does not, so use URI::snews
1120         $url =~ s!\Anntps://!snews://!i;
1121         URI->new($url);
1122 }
1123
1124 sub imap_url {
1125         my ($url) = @_;
1126         require PublicInbox::URIimap;
1127         my $uri = PublicInbox::URIimap->new($url);
1128         $uri ? $uri->canonical->as_string : undef;
1129 }
1130
1131 my %IS_NNTP = (news => 1, snews => 1, nntp => 1);
1132 sub nntp_url {
1133         my ($url) = @_;
1134         require URI;
1135         my $uri = uri_new($url);
1136         return unless $uri && $IS_NNTP{$uri->scheme} && $uri->group;
1137         $url = $uri->canonical->as_string;
1138         # nntps is IANA registered, snews is deprecated
1139         $url =~ s!\Asnews://!nntps://!;
1140         $url;
1141 }
1142
1143 1;