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