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