]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Watch.pm
a4302162db765f763a825a68ca69f4507606c89f
[public-inbox.git] / lib / PublicInbox / Watch.pm
1 # Copyright (C) 2016-2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 #
4 # ref: https://cr.yp.to/proto/maildir.html
5 #       httsp://wiki2.dovecot.org/MailboxFormat/Maildir
6 package PublicInbox::Watch;
7 use strict;
8 use v5.10.1;
9 use PublicInbox::Eml;
10 use PublicInbox::InboxWritable qw(eml_from_path);
11 use PublicInbox::MdirReader;
12 use PublicInbox::Filter::Base qw(REJECT);
13 use PublicInbox::Spamcheck;
14 use PublicInbox::Sigfd;
15 use PublicInbox::DS qw(now add_timer);
16 use PublicInbox::MID qw(mids);
17 use PublicInbox::ContentHash qw(content_hash);
18 use PublicInbox::EOFpipe;
19 use POSIX qw(_exit WNOHANG);
20
21 sub compile_watchheaders ($) {
22         my ($ibx) = @_;
23         my $watch_hdrs = [];
24         if (my $whs = $ibx->{watchheader}) {
25                 for (@$whs) {
26                         my ($k, $v) = split(/:/, $_, 2);
27                         # XXX should this be case-insensitive?
28                         # Or, mutt-style, case-sensitive iff
29                         # a capital letter exists?
30                         push @$watch_hdrs, [ $k, qr/\Q$v\E/ ];
31                 }
32         }
33         if (my $list_ids = $ibx->{listid}) {
34                 for (@$list_ids) {
35                         # RFC2919 section 6 stipulates
36                         # "case insensitive equality"
37                         my $re = qr/<[ \t]*\Q$_\E[ \t]*>/i;
38                         push @$watch_hdrs, ['List-Id', $re ];
39                 }
40         }
41         $ibx->{-watchheaders} = $watch_hdrs if scalar @$watch_hdrs;
42 }
43
44 sub new {
45         my ($class, $cfg) = @_;
46         my (%mdmap, $spamc);
47         my (%imap, %nntp); # url => [inbox objects] or 'watchspam'
48
49         # "publicinboxwatch" is the documented namespace
50         # "publicinboxlearn" is legacy but may be supported
51         # indefinitely...
52         foreach my $pfx (qw(publicinboxwatch publicinboxlearn)) {
53                 my $k = "$pfx.watchspam";
54                 defined(my $dirs = $cfg->{$k}) or next;
55                 $dirs = PublicInbox::Config::_array($dirs);
56                 for my $dir (@$dirs) {
57                         my $url;
58                         if (is_maildir($dir)) {
59                                 # skip "new", no MUA has seen it, yet.
60                                 $mdmap{"$dir/cur"} = 'watchspam';
61                         } elsif ($url = imap_url($dir)) {
62                                 $imap{$url} = 'watchspam';
63                         } elsif ($url = nntp_url($dir)) {
64                                 $nntp{$url} = 'watchspam';
65                         } else {
66                                 warn "unsupported $k=$dir\n";
67                         }
68                 }
69         }
70
71         my $k = 'publicinboxwatch.spamcheck';
72         my $default = undef;
73         my $spamcheck = PublicInbox::Spamcheck::get($cfg, $k, $default);
74         $spamcheck = _spamcheck_cb($spamcheck) if $spamcheck;
75
76         $cfg->each_inbox(sub {
77                 # need to make all inboxes writable for spam removal:
78                 my $ibx = $_[0] = PublicInbox::InboxWritable->new($_[0]);
79
80                 my $watches = $ibx->{watch} or return;
81                 $watches = PublicInbox::Config::_array($watches);
82                 for my $watch (@$watches) {
83                         my $url;
84                         if (is_maildir($watch)) {
85                                 compile_watchheaders($ibx);
86                                 my ($new, $cur) = ("$watch/new", "$watch/cur");
87                                 my $cur_dst = $mdmap{$cur} //= [];
88                                 return if is_watchspam($cur, $cur_dst, $ibx);
89                                 push @{$mdmap{$new} //= []}, $ibx;
90                                 push @$cur_dst, $ibx;
91                         } elsif ($url = imap_url($watch)) {
92                                 return if is_watchspam($url, $imap{$url}, $ibx);
93                                 compile_watchheaders($ibx);
94                                 push @{$imap{$url} ||= []}, $ibx;
95                         } elsif ($url = nntp_url($watch)) {
96                                 return if is_watchspam($url, $nntp{$url}, $ibx);
97                                 compile_watchheaders($ibx);
98                                 push @{$nntp{$url} ||= []}, $ibx;
99                         } else {
100                                 warn "watch unsupported: $k=$watch\n";
101                         }
102                 }
103         });
104
105         my $mdre;
106         if (scalar keys %mdmap) {
107                 $mdre = join('|', map { quotemeta($_) } keys %mdmap);
108                 $mdre = qr!\A($mdre)/!;
109         }
110         return unless $mdre || scalar(keys %imap) || scalar(keys %nntp);
111
112         bless {
113                 max_batch => 10, # avoid hogging locks for too long
114                 spamcheck => $spamcheck,
115                 mdmap => \%mdmap,
116                 mdre => $mdre,
117                 pi_cfg => $cfg,
118                 imap => scalar keys %imap ? \%imap : undef,
119                 nntp => scalar keys %nntp? \%nntp : undef,
120                 importers => {},
121                 opendirs => {}, # dirname => dirhandle (in progress scans)
122                 ops => [], # 'quit', 'full'
123         }, $class;
124 }
125
126 sub _done_for_now {
127         my ($self) = @_;
128         local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
129         for my $im (values %{$self->{importers}}) {
130                 next if !$im; # $im may be undef during cleanup
131                 eval { $im->done };
132                 warn "$im->{ibx}->{name} ->done: $@\n" if $@;
133         }
134 }
135
136 sub remove_eml_i { # each_inbox callback
137         my ($ibx, $self, $eml, $loc) = @_;
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__} = PublicInbox::Eml::warn_ignore_cb();
179         $self->{pi_cfg}->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         my $fl = PublicInbox::MdirReader::maildir_path_flags($path) // return;
212         return if $fl =~ /[DT]/; # no Drafts or Trash
213         if ($path !~ $self->{mdre}) {
214                 warn "unrecognized path: $path\n";
215                 return;
216         }
217         my $inboxes = $self->{mdmap}->{$1};
218         unless ($inboxes) {
219                 warn "unmappable dir: $1\n";
220                 return;
221         }
222         my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
223         local $SIG{__WARN__} = sub {
224                 my $pfx = ($_[0] // '') =~ /^([A-Z]: )/g ? $1 : '';
225                 $warn_cb->($pfx, "path: $path\n", @_);
226         };
227         if (!ref($inboxes) && $inboxes eq 'watchspam') {
228                 return _remove_spam($self, $path);
229         }
230         foreach my $ibx (@$inboxes) {
231                 my $eml = eml_from_path($path) or next;
232                 import_eml($self, $ibx, $eml);
233         }
234 }
235
236 sub quit_done ($) {
237         my ($self) = @_;
238         return unless $self->{quit};
239
240         # don't have reliable wakeups, keep signalling
241         my $done = 1;
242         for (qw(idle_pids poll_pids)) {
243                 my $pids = $self->{$_} or next;
244                 for (keys %$pids) {
245                         $done = undef if kill('QUIT', $_);
246                 }
247         }
248         $done;
249 }
250
251 sub quit {
252         my ($self) = @_;
253         $self->{quit} = 1;
254         %{$self->{opendirs}} = ();
255         _done_for_now($self);
256         quit_done($self);
257         if (my $idle_mic = $self->{idle_mic}) {
258                 eval { $idle_mic->done };
259                 if ($@) {
260                         warn "IDLE DONE error: $@\n";
261                         eval { $idle_mic->disconnect };
262                         warn "IDLE LOGOUT error: $@\n" if $@;
263                 }
264         }
265 }
266
267 sub watch_fs_init ($) {
268         my ($self) = @_;
269         my $done = sub {
270                 delete $self->{done_timer};
271                 _done_for_now($self);
272         };
273         my $cb = sub { # called by PublicInbox::DirIdle::event_step
274                 _try_path($self, $_[0]->fullname);
275                 $self->{done_timer} //= PublicInbox::DS::requeue($done);
276         };
277         require PublicInbox::DirIdle;
278         # inotify_create + EPOLL_CTL_ADD
279         PublicInbox::DirIdle->new([keys %{$self->{mdmap}}], $cb);
280 }
281
282 # avoid exposing deprecated "snews" to users.
283 my %SCHEME_MAP = ('snews' => 'nntps');
284
285 sub uri_scheme ($) {
286         my ($uri) = @_;
287         my $scheme = $uri->scheme;
288         $SCHEME_MAP{$scheme} // $scheme;
289 }
290
291 # returns the git config section name, e.g [imap "imaps://user@example.com"]
292 # without the mailbox, so we can share connections between different inboxes
293 sub uri_section ($) {
294         my ($uri) = @_;
295         uri_scheme($uri) . '://' . $uri->authority;
296 }
297
298 sub cfg_intvl ($$$) {
299         my ($cfg, $key, $url) = @_;
300         my $v = $cfg->urlmatch($key, $url) // return;
301         $v =~ /\A[0-9]+(?:\.[0-9]+)?\z/s and return $v + 0;
302         if (ref($v) eq 'ARRAY') {
303                 $v = join(', ', @$v);
304                 warn "W: $key has multiple values: $v\nW: $key ignored\n";
305         } else {
306                 warn "W: $key=$v is not a numeric value in seconds\n";
307         }
308 }
309
310 sub cfg_bool ($$$) {
311         my ($cfg, $key, $url) = @_;
312         my $orig = $cfg->urlmatch($key, $url) // return;
313         my $bool = $cfg->git_bool($orig);
314         warn "W: $key=$orig for $url is not boolean\n" unless defined($bool);
315         $bool;
316 }
317
318 # flesh out common IMAP-specific data structures
319 sub imap_common_init ($) {
320         my ($self) = @_;
321         my $cfg = $self->{pi_cfg};
322         my $mic_args = {}; # scheme://authority => Mail:IMAPClient arg
323         for my $url (sort keys %{$self->{imap}}) {
324                 my $uri = PublicInbox::URIimap->new($url);
325                 my $sec = uri_section($uri);
326                 for my $k (qw(Starttls Debug Compress)) {
327                         my $bool = cfg_bool($cfg, "imap.$k", $url) // next;
328                         $mic_args->{$sec}->{$k} = $bool;
329                 }
330                 my $to = cfg_intvl($cfg, 'imap.timeout', $url);
331                 $mic_args->{$sec}->{Timeout} = $to if $to;
332                 for my $k (qw(pollInterval idleInterval)) {
333                         $to = cfg_intvl($cfg, "imap.$k", $url) // next;
334                         $self->{imap_opt}->{$sec}->{$k} = $to;
335                 }
336                 my $k = 'imap.fetchBatchSize';
337                 my $bs = $cfg->urlmatch($k, $url) // next;
338                 if ($bs =~ /\A([0-9]+)\z/) {
339                         $self->{imap_opt}->{$sec}->{batch_size} = $bs;
340                 } else {
341                         warn "$k=$bs is not an integer\n";
342                 }
343         }
344         $mic_args;
345 }
346
347 sub auth_anon_cb { '' }; # for Mail::IMAPClient::Authcallback
348
349 sub mic_for ($$$) { # mic = Mail::IMAPClient
350         my ($self, $url, $mic_args) = @_;
351         my $uri = PublicInbox::URIimap->new($url);
352         require PublicInbox::GitCredential;
353         my $cred = bless {
354                 url => $url,
355                 protocol => $uri->scheme,
356                 host => $uri->host,
357                 username => $uri->user,
358                 password => $uri->password,
359         }, 'PublicInbox::GitCredential';
360         my $common = $mic_args->{uri_section($uri)} // {};
361         # IMAPClient and Net::Netrc both mishandles `0', so we pass `127.0.0.1'
362         my $host = $cred->{host};
363         $host = '127.0.0.1' if $host eq '0';
364         my $mic_arg = {
365                 Port => $uri->port,
366                 Server => $host,
367                 Ssl => $uri->scheme eq 'imaps',
368                 Keepalive => 1, # SO_KEEPALIVE
369                 %$common, # may set Starttls, Compress, Debug ....
370         };
371         my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or
372                 die "E: <$url> new: $@\n";
373
374         # default to using STARTTLS if it's available, but allow
375         # it to be disabled since I usually connect to localhost
376         if (!$mic_arg->{Ssl} && !defined($mic_arg->{Starttls}) &&
377                         $mic->has_capability('STARTTLS') &&
378                         $mic->can('starttls')) {
379                 $mic->starttls or die "E: <$url> STARTTLS: $@\n";
380         }
381
382         # do we even need credentials?
383         if (!defined($cred->{username}) &&
384                         $mic->has_capability('AUTH=ANONYMOUS')) {
385                 $cred = undef;
386         }
387         if ($cred) {
388                 $cred->check_netrc unless defined $cred->{password};
389                 $cred->fill; # may prompt user here
390                 $mic->User($mic_arg->{User} = $cred->{username});
391                 $mic->Password($mic_arg->{Password} = $cred->{password});
392         } else { # AUTH=ANONYMOUS
393                 $mic->Authmechanism($mic_arg->{Authmechanism} = 'ANONYMOUS');
394                 $mic->Authcallback($mic_arg->{Authcallback} = \&auth_anon_cb);
395         }
396         if ($mic->login && $mic->IsAuthenticated) {
397                 # success! keep IMAPClient->new arg in case we get disconnected
398                 $self->{mic_arg}->{uri_section($uri)} = $mic_arg;
399         } else {
400                 warn "E: <$url> LOGIN: $@\n";
401                 $mic = undef;
402         }
403         $cred->run($mic ? 'approve' : 'reject') if $cred;
404         $mic;
405 }
406
407 sub imap_import_msg ($$$$$) {
408         my ($self, $url, $uid, $raw, $flags) = @_;
409         # our target audience expects LF-only, save storage
410         $$raw =~ s/\r\n/\n/sg;
411
412         my $inboxes = $self->{imap}->{$url};
413         if (ref($inboxes)) {
414                 for my $ibx (@$inboxes) {
415                         my $eml = PublicInbox::Eml->new($$raw);
416                         import_eml($self, $ibx, $eml);
417                 }
418         } elsif ($inboxes eq 'watchspam') {
419                 return if $flags !~ /\\Seen\b/; # don't remove unseen messages
420                 local $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
421                 my $eml = PublicInbox::Eml->new($raw);
422                 $self->{pi_cfg}->each_inbox(\&remove_eml_i,
423                                                 $self, $eml, "$url UID:$uid");
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__} || \&CORE::warn;
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 = "E: 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::DS::sig_setmask($self->{oldset});
587 }
588
589 sub watch_atfork_parent ($) {
590         my ($self) = @_;
591         _done_for_now($self);
592         PublicInbox::DS::block_signals();
593 }
594
595 sub imap_idle_requeue { # DS::add_timer callback
596         my ($self, $url_intvl) = @_;
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         add_timer(60, \&imap_idle_requeue, $self, $url_intvl);
611 }
612
613 sub reap { # callback for EOFpipe
614         my ($pid, $cb, $self) = @{$_[0]};
615         my $ret = waitpid($pid, 0);
616         if ($ret == $pid) {
617                 $cb->($self, $pid); # poll_fetch_reap || imap_idle_reap
618         } else {
619                 warn "W: waitpid($pid) => ", $ret // "($!)", "\n";
620         }
621 }
622
623 sub imap_idle_fork ($$) {
624         my ($self, $url_intvl) = @_;
625         my ($url, $intvl) = @$url_intvl;
626         pipe(my ($r, $w)) or die "pipe: $!";
627         my $seed = rand(0xffffffff);
628         my $pid = fork // die "fork: $!";
629         if ($pid == 0) {
630                 srand($seed);
631                 eval { Net::SSLeay::randomize() };
632                 close $r;
633                 watch_atfork_child($self);
634                 watch_imap_idle_1($self, $url, $intvl);
635                 close $w;
636                 _exit(0);
637         }
638         $self->{idle_pids}->{$pid} = $url_intvl;
639         PublicInbox::EOFpipe->new($r, \&reap, [$pid, \&imap_idle_reap, $self]);
640 }
641
642 sub event_step {
643         my ($self) = @_;
644         return if $self->{quit};
645         my $idle_todo = $self->{idle_todo};
646         if ($idle_todo && @$idle_todo) {
647                 my $oldset = watch_atfork_parent($self);
648                 eval {
649                         while (my $url_intvl = shift(@$idle_todo)) {
650                                 imap_idle_fork($self, $url_intvl);
651                         }
652                 };
653                 PublicInbox::DS::sig_setmask($oldset);
654                 die $@ if $@;
655         }
656         fs_scan_step($self) if $self->{mdre};
657 }
658
659 sub watch_imap_fetch_all ($$) {
660         my ($self, $urls) = @_;
661         for my $url (@$urls) {
662                 my $uri = PublicInbox::URIimap->new($url);
663                 my $sec = uri_section($uri);
664                 my $mic_arg = $self->{mic_arg}->{$sec} or
665                         die "BUG: no Mail::IMAPClient->new arg for $sec";
666                 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or next;
667                 my $err = imap_fetch_all($self, $mic, $url);
668                 last if $self->{quit};
669                 warn $err, "\n" if $err;
670         }
671 }
672
673 sub watch_nntp_fetch_all ($$) {
674         my ($self, $urls) = @_;
675         for my $url (@$urls) {
676                 my $uri = uri_new($url);
677                 my $sec = uri_section($uri);
678                 my $nn_arg = $self->{nn_arg}->{$sec} or
679                         die "BUG: no Net::NNTP->new arg for $sec";
680                 my $nntp_opt = $self->{nntp_opt}->{$sec};
681                 my $nn = nn_new($nn_arg, $nntp_opt, $url);
682                 unless ($nn) {
683                         warn "E: $url: \$!=$!\n";
684                         next;
685                 }
686                 last if $self->{quit};
687                 if (my $postconn = $nntp_opt->{-postconn}) {
688                         for my $m_arg (@$postconn) {
689                                 my ($method, @args) = @$m_arg;
690                                 $nn->$method(@args) and next;
691                                 warn "E: <$url> $method failed\n";
692                                 $nn = undef;
693                                 last;
694                         }
695                 }
696                 last if $self->{quit};
697                 if ($nn) {
698                         my $err = nntp_fetch_all($self, $nn, $url);
699                         warn $err, "\n" if $err;
700                 }
701         }
702 }
703
704 sub poll_fetch_fork { # DS::add_timer callback
705         my ($self, $intvl, $urls) = @_;
706         return if $self->{quit};
707         pipe(my ($r, $w)) or die "pipe: $!";
708         my $oldset = watch_atfork_parent($self);
709         my $seed = rand(0xffffffff);
710         my $pid = fork;
711         if (defined($pid) && $pid == 0) {
712                 srand($seed);
713                 eval { Net::SSLeay::randomize() };
714                 close $r;
715                 watch_atfork_child($self);
716                 if ($urls->[0] =~ m!\Aimaps?://!i) {
717                         watch_imap_fetch_all($self, $urls);
718                 } else {
719                         watch_nntp_fetch_all($self, $urls);
720                 }
721                 close $w;
722                 _exit(0);
723         }
724         PublicInbox::DS::sig_setmask($oldset);
725         die "fork: $!"  unless defined $pid;
726         $self->{poll_pids}->{$pid} = [ $intvl, $urls ];
727         PublicInbox::EOFpipe->new($r, \&reap, [$pid, \&poll_fetch_reap, $self]);
728 }
729
730 sub poll_fetch_reap {
731         my ($self, $pid) = @_;
732         my $intvl_urls = delete $self->{poll_pids}->{$pid} or
733                 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
734         return if $self->{quit};
735         my ($intvl, $urls) = @$intvl_urls;
736         if ($?) {
737                 warn "W: PID=$pid died: \$?=$?\n", map { "$_\n" } @$urls;
738         }
739         warn("I: will check $_ in ${intvl}s\n") for @$urls;
740         add_timer($intvl, \&poll_fetch_fork, $self, $intvl, $urls);
741 }
742
743 sub watch_imap_init ($$) {
744         my ($self, $poll) = @_;
745         eval { require PublicInbox::IMAPClient } or
746                 die "Mail::IMAPClient is required for IMAP:\n$@\n";
747         eval { require PublicInbox::IMAPTracker } or
748                 die "DBD::SQLite is required for IMAP\n:$@\n";
749
750         my $mic_args = imap_common_init($self); # read args from config
751
752         # make sure we can connect and cache the credentials in memory
753         $self->{mic_arg} = {}; # schema://authority => IMAPClient->new args
754         my $mics = {}; # schema://authority => IMAPClient obj
755         for my $url (sort keys %{$self->{imap}}) {
756                 my $uri = PublicInbox::URIimap->new($url);
757                 $mics->{uri_section($uri)} //= mic_for($self, $url, $mic_args);
758         }
759
760         my $idle = []; # [ [ url1, intvl1 ], [url2, intvl2] ]
761         for my $url (keys %{$self->{imap}}) {
762                 my $uri = PublicInbox::URIimap->new($url);
763                 my $sec = uri_section($uri);
764                 my $mic = $mics->{$sec};
765                 my $intvl = $self->{imap_opt}->{$sec}->{pollInterval};
766                 if ($mic->has_capability('IDLE') && !$intvl) {
767                         $intvl = $self->{imap_opt}->{$sec}->{idleInterval};
768                         push @$idle, [ $url, $intvl // () ];
769                 } else {
770                         push @{$poll->{$intvl || 120}}, $url;
771                 }
772         }
773         if (scalar @$idle) {
774                 $self->{idle_todo} = $idle;
775                 PublicInbox::DS::requeue($self); # ->event_step to fork
776         }
777 }
778
779 # flesh out common NNTP-specific data structures
780 sub nntp_common_init ($) {
781         my ($self) = @_;
782         my $cfg = $self->{pi_cfg};
783         my $nn_args = {}; # scheme://authority => Net::NNTP->new arg
784         for my $url (sort keys %{$self->{nntp}}) {
785                 my $sec = uri_section(uri_new($url));
786
787                 # Debug and Timeout are passed to Net::NNTP->new
788                 my $v = cfg_bool($cfg, 'nntp.Debug', $url);
789                 $nn_args->{$sec}->{Debug} = $v if defined $v;
790                 my $to = cfg_intvl($cfg, 'nntp.Timeout', $url);
791                 $nn_args->{$sec}->{Timeout} = $to if $to;
792
793                 # Net::NNTP post-connect commands
794                 for my $k (qw(starttls compress)) {
795                         $v = cfg_bool($cfg, "nntp.$k", $url) // next;
796                         $self->{nntp_opt}->{$sec}->{$k} = $v;
797                 }
798
799                 # internal option
800                 for my $k (qw(pollInterval)) {
801                         $to = cfg_intvl($cfg, "nntp.$k", $url) // next;
802                         $self->{nntp_opt}->{$sec}->{$k} = $to;
803                 }
804         }
805         $nn_args;
806 }
807
808 # Net::NNTP doesn't support CAPABILITIES, yet
809 sub try_starttls ($) {
810         my ($host) = @_;
811         return if $host =~ /\.onion\z/s;
812         return if $host =~ /\A127\.[0-9]+\.[0-9]+\.[0-9]+\z/s;
813         return if $host eq '::1';
814         1;
815 }
816
817 sub nn_new ($$$) {
818         my ($nn_arg, $nntp_opt, $url) = @_;
819         my $nn = Net::NNTP->new(%$nn_arg) or die "E: <$url> new: $!\n";
820
821         # default to using STARTTLS if it's available, but allow
822         # it to be disabled for localhost/VPN users
823         if (!$nn_arg->{SSL} && $nn->can('starttls')) {
824                 if (!defined($nntp_opt->{starttls}) &&
825                                 try_starttls($nn_arg->{Host})) {
826                         # soft fail by default
827                         $nn->starttls or warn <<"";
828 W: <$url> STARTTLS tried and failed (not requested)
829
830                 } elsif ($nntp_opt->{starttls}) {
831                         # hard fail if explicitly configured
832                         $nn->starttls or die <<"";
833 E: <$url> STARTTLS requested and failed
834
835                 }
836         } elsif ($nntp_opt->{starttls}) {
837                 $nn->can('starttls') or
838                         die "E: <$url> Net::NNTP too old for STARTTLS\n";
839                 $nn->starttls or die <<"";
840 E: <$url> STARTTLS requested and failed
841
842         }
843         $nn;
844 }
845
846 sub nn_for ($$$) { # nn = Net::NNTP
847         my ($self, $url, $nn_args) = @_;
848         my $uri = uri_new($url);
849         my $sec = uri_section($uri);
850         my $nntp_opt = $self->{nntp_opt}->{$sec} //= {};
851         my $host = $uri->host;
852         # Net::NNTP and Net::Netrc both mishandle `0', so we pass `127.0.0.1'
853         $host = '127.0.0.1' if $host eq '0';
854         my $cred;
855         my ($u, $p);
856         if (defined(my $ui = $uri->userinfo)) {
857                 require PublicInbox::GitCredential;
858                 $cred = bless {
859                         url => $sec,
860                         protocol => uri_scheme($uri),
861                         host => $host,
862                 }, 'PublicInbox::GitCredential';
863                 ($u, $p) = split(/:/, $ui, 2);
864                 ($cred->{username}, $cred->{password}) = ($u, $p);
865                 $cred->check_netrc unless defined $p;
866         }
867         my $common = $nn_args->{$sec} // {};
868         my $nn_arg = {
869                 Port => $uri->port,
870                 Host => $host,
871                 SSL => $uri->secure, # snews == nntps
872                 %$common, # may Debug ....
873         };
874         my $nn = nn_new($nn_arg, $nntp_opt, $url);
875
876         if ($cred) {
877                 $cred->fill; # may prompt user here
878                 if ($nn->authinfo($u, $p)) {
879                         push @{$nntp_opt->{-postconn}}, [ 'authinfo', $u, $p ];
880                 } else {
881                         warn "E: <$url> AUTHINFO $u XXXX failed\n";
882                         $nn = undef;
883                 }
884         }
885
886         if ($nntp_opt->{compress}) {
887                 # https://rt.cpan.org/Ticket/Display.html?id=129967
888                 if ($nn->can('compress')) {
889                         if ($nn->compress) {
890                                 push @{$nntp_opt->{-postconn}}, [ 'compress' ];
891                         } else {
892                                 warn "W: <$url> COMPRESS failed\n";
893                         }
894                 } else {
895                         delete $nntp_opt->{compress};
896                         warn <<"";
897 W: <$url> COMPRESS not supported by Net::NNTP
898 W: see https://rt.cpan.org/Ticket/Display.html?id=129967 for updates
899
900                 }
901         }
902
903         $self->{nn_arg}->{$sec} = $nn_arg;
904         $cred->run($nn ? 'approve' : 'reject') if $cred;
905         $nn;
906 }
907
908 sub nntp_fetch_all ($$$) {
909         my ($self, $nn, $url) = @_;
910         my $uri = uri_new($url);
911         my ($group, $num_a, $num_b) = $uri->group;
912         my $sec = uri_section($uri);
913         my ($nr, $beg, $end) = $nn->group($group);
914         unless (defined($nr)) {
915                 chomp(my $msg = $nn->message);
916                 return "E: GROUP $group <$sec> $msg";
917         }
918
919         # IMAPTracker is also used for tracking NNTP, UID == article number
920         # LIST.ACTIVE can get the equivalent of UIDVALIDITY, but that's
921         # expensive.  So we assume newsgroups don't change:
922         my $itrk = PublicInbox::IMAPTracker->new($url);
923         my (undef, $l_art) = $itrk->get_last;
924         $l_art //= $beg; # initial import
925
926         # allow users to specify articles to refetch
927         # cf. https://tools.ietf.org/id/draft-gilman-news-url-01.txt
928         # nntp://example.com/inbox.foo/$num_a-$num_b
929         $l_art = $num_a if defined($num_a) && $num_a < $l_art;
930         $end = $num_b if defined($num_b) && $num_b < $end;
931
932         return if $l_art >= $end; # nothing to do
933         $beg = $l_art + 1;
934
935         warn "I: $url fetching ARTICLE $beg..$end\n";
936         my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
937         my ($err, $art);
938         local $SIG{__WARN__} = sub {
939                 my $pfx = ($_[0] // '') =~ /^([A-Z]: )/g ? $1 : '';
940                 $warn_cb->("$pfx$url ", $art ? ("ARTICLE $art") : (), "\n", @_);
941         };
942         my $inboxes = $self->{nntp}->{$url};
943         my $last_art;
944         my $n = $self->{max_batch};
945         for ($beg..$end) {
946                 last if $self->{quit};
947                 $art = $_;
948                 if (--$n < 0) {
949                         _done_for_now($self);
950                         $itrk->update_last(0, $last_art);
951                         $n = $self->{max_batch};
952                 }
953                 my $raw = $nn->article($art);
954                 unless (defined($raw)) {
955                         my $msg = $nn->message;
956                         if ($nn->code == 421) { # pseudo response from Net::Cmd
957                                 $err = "E: $msg";
958                                 last;
959                         } else { # probably just a deleted message (spam)
960                                 warn "W: $msg";
961                                 next;
962                         }
963                 }
964                 s/\r\n/\n/ for @$raw;
965                 $raw = join('', @$raw);
966                 if (ref($inboxes)) {
967                         for my $ibx (@$inboxes) {
968                                 my $eml = PublicInbox::Eml->new($raw);
969                                 import_eml($self, $ibx, $eml);
970                         }
971                 } elsif ($inboxes eq 'watchspam') {
972                         my $eml = PublicInbox::Eml->new(\$raw);
973                         $self->{pi_cfg}->each_inbox(\&remove_eml_i,
974                                         $self, $eml, "$url ARTICLE $art");
975                 } else {
976                         die "BUG: destination unknown $inboxes";
977                 }
978                 $last_art = $art;
979         }
980         _done_for_now($self);
981         $itrk->update_last(0, $last_art);
982         $err;
983 }
984
985 sub watch_nntp_init ($$) {
986         my ($self, $poll) = @_;
987         eval { require Net::NNTP } or
988                 die "Net::NNTP is required for NNTP:\n$@\n";
989         eval { require PublicInbox::IMAPTracker } or
990                 die "DBD::SQLite is required for NNTP\n:$@\n";
991
992         my $nn_args = nntp_common_init($self); # read args from config
993
994         # make sure we can connect and cache the credentials in memory
995         $self->{nn_arg} = {}; # schema://authority => Net::NNTP->new args
996         for my $url (sort keys %{$self->{nntp}}) {
997                 nn_for($self, $url, $nn_args);
998         }
999         for my $url (keys %{$self->{nntp}}) {
1000                 my $uri = uri_new($url);
1001                 my $sec = uri_section($uri);
1002                 my $intvl = $self->{nntp_opt}->{$sec}->{pollInterval};
1003                 push @{$poll->{$intvl || 120}}, $url;
1004         }
1005 }
1006
1007 sub watch { # main entry point
1008         my ($self, $sig, $oldset) = @_;
1009         $self->{oldset} = $oldset;
1010         $self->{sig} = $sig;
1011         my $poll = {}; # intvl_seconds => [ url1, url2 ]
1012         watch_imap_init($self, $poll) if $self->{imap};
1013         watch_nntp_init($self, $poll) if $self->{nntp};
1014         while (my ($intvl, $urls) = each %$poll) {
1015                 # poll all URLs for a given interval sequentially
1016                 add_timer(0, \&poll_fetch_fork, $self, $intvl, $urls);
1017         }
1018         watch_fs_init($self) if $self->{mdre};
1019         PublicInbox::DS->SetPostLoopCallback(sub { !$self->quit_done });
1020         PublicInbox::DS->EventLoop; # calls ->event_step
1021         _done_for_now($self);
1022 }
1023
1024 sub trigger_scan {
1025         my ($self, $op) = @_;
1026         push @{$self->{ops}}, $op;
1027         PublicInbox::DS::requeue($self);
1028 }
1029
1030 sub fs_scan_step {
1031         my ($self) = @_;
1032         return if $self->{quit};
1033         my $op = shift @{$self->{ops}};
1034         local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
1035
1036         # continue existing scan
1037         my $opendirs = $self->{opendirs};
1038         my @dirnames = keys %$opendirs;
1039         foreach my $dir (@dirnames) {
1040                 my $dh = delete $opendirs->{$dir};
1041                 my $n = $self->{max_batch};
1042                 while (my $fn = readdir($dh)) {
1043                         _try_path($self, "$dir/$fn");
1044                         last if --$n < 0;
1045                 }
1046                 $opendirs->{$dir} = $dh if $n < 0;
1047         }
1048         if ($op && $op eq 'full') {
1049                 foreach my $dir (keys %{$self->{mdmap}}) {
1050                         next if $opendirs->{$dir}; # already in progress
1051                         my $ok = opendir(my $dh, $dir);
1052                         unless ($ok) {
1053                                 warn "failed to open $dir: $!\n";
1054                                 next;
1055                         }
1056                         my $n = $self->{max_batch};
1057                         while (my $fn = readdir($dh)) {
1058                                 _try_path($self, "$dir/$fn");
1059                                 last if --$n < 0;
1060                         }
1061                         $opendirs->{$dir} = $dh if $n < 0;
1062                 }
1063         }
1064         _done_for_now($self);
1065         # do we have more work to do?
1066         PublicInbox::DS::requeue($self) if keys %$opendirs;
1067 }
1068
1069 sub scan {
1070         my ($self, $op) = @_;
1071         push @{$self->{ops}}, $op;
1072         fs_scan_step($self);
1073 }
1074
1075 sub _importer_for {
1076         my ($self, $ibx) = @_;
1077         my $importers = $self->{importers};
1078         my $im = $importers->{"$ibx"} ||= $ibx->importer(0);
1079         if (scalar(keys(%$importers)) > 2) {
1080                 delete $importers->{"$ibx"};
1081                 _done_for_now($self);
1082         }
1083
1084         $importers->{"$ibx"} = $im;
1085 }
1086
1087 # XXX consider sharing with V2Writable, this only requires read-only access
1088 sub content_exists ($$) {
1089         my ($ibx, $eml) = @_;
1090         my $over = $ibx->over or return;
1091         my $mids = mids($eml);
1092         my $chash = content_hash($eml);
1093         my ($id, $prev);
1094         for my $mid (@$mids) {
1095                 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
1096                         my $cmp = $ibx->smsg_eml($smsg) or return;
1097                         return 1 if $chash eq content_hash($cmp);
1098                 }
1099         }
1100         undef;
1101 }
1102
1103 sub _spamcheck_cb {
1104         my ($sc) = @_;
1105         sub { # this gets called by (V2Writable||Import)->add
1106                 my ($mime, $ibx) = @_;
1107                 return if content_exists($ibx, $mime);
1108                 my $tmp = '';
1109                 if ($sc->spamcheck($mime, \$tmp)) {
1110                         return PublicInbox::Eml->new(\$tmp);
1111                 }
1112                 warn $mime->header('Message-ID')." failed spam check\n";
1113                 undef;
1114         }
1115 }
1116
1117 sub is_maildir {
1118         $_[0] =~ s!\Amaildir:!! or return;
1119         $_[0] =~ tr!/!/!s;
1120         $_[0] =~ s!/\z!!;
1121         $_[0];
1122 }
1123
1124 sub is_watchspam {
1125         my ($cur, $ws, $ibx) = @_;
1126         if ($ws && !ref($ws) && $ws eq 'watchspam') {
1127                 warn <<EOF;
1128 E: $cur is a spam folder and cannot be used for `$ibx->{name}' input
1129 EOF
1130                 return 1;
1131         }
1132         undef;
1133 }
1134
1135 sub uri_new {
1136         my ($url) = @_;
1137
1138         # URI::snews exists, URI::nntps does not, so use URI::snews
1139         $url =~ s!\Anntps://!snews://!i;
1140         URI->new($url);
1141 }
1142
1143 sub imap_url {
1144         my ($url) = @_;
1145         require PublicInbox::URIimap;
1146         my $uri = PublicInbox::URIimap->new($url);
1147         $uri ? $uri->canonical->as_string : undef;
1148 }
1149
1150 my %IS_NNTP = (news => 1, snews => 1, nntp => 1);
1151 sub nntp_url {
1152         my ($url) = @_;
1153         require URI;
1154         my $uri = uri_new($url);
1155         return unless $uri && $IS_NNTP{$uri->scheme} && $uri->group;
1156         $url = $uri->canonical->as_string;
1157         # nntps is IANA registered, snews is deprecated
1158         $url =~ s!\Asnews://!nntps://!;
1159         $url;
1160 }
1161
1162 1;