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