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