]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/WatchMaildir.pm
watch: don't burn CPU on IDLE failures
[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} || !$mic->IsConnected ||
501                         grep(/^\* [0-9]+ EXISTS/, @res) || $i <= 0) {
502                 @res = $mic->idle_data($i);
503                 $i = $end - now();
504         }
505         delete $self->{idle_mic};
506         unless ($self->{quit}) {
507                 $mic->IsConnected or return "E: IDLE disconnected on $url";
508                 $mic->done or return "E: IDLE DONE failed on $url: $!";
509         }
510         undef;
511 }
512
513 # idles on a single URI
514 sub watch_imap_idle_1 ($$$) {
515         my ($self, $url, $intvl) = @_;
516         my $uri = PublicInbox::URIimap->new($url);
517         my $sec = uri_section($uri);
518         my $mic_arg = $self->{mic_arg}->{$sec} or
519                         die "BUG: no Mail::IMAPClient->new arg for $sec";
520         my $mic;
521         local $0 = $uri->mailbox." $sec";
522         until ($self->{quit}) {
523                 $mic //= PublicInbox::IMAPClient->new(%$mic_arg);
524                 my $err;
525                 if ($mic && $mic->IsConnected) {
526                         $err = imap_fetch_all($self, $mic, $url);
527                         $err //= imap_idle_once($self, $mic, $intvl, $url);
528                 } else {
529                         $err = "not connected: $!";
530                 }
531                 if ($err && !$self->{quit}) {
532                         warn $err, "\n";
533                         $mic = undef;
534                         sleep 60 unless $self->{quit};
535                 }
536         }
537 }
538
539 sub watch_atfork_child ($) {
540         my ($self) = @_;
541         delete $self->{idle_pids};
542         delete $self->{poll_pids};
543         delete $self->{opendirs};
544         PublicInbox::DS->Reset;
545         %SIG = (%SIG, %{$self->{sig}}, CHLD => 'DEFAULT');
546         PublicInbox::Sigfd::sig_setmask($self->{oldset});
547 }
548
549 sub watch_atfork_parent ($) {
550         my ($self) = @_;
551         _done_for_now($self);
552 }
553
554 sub imap_idle_requeue ($) { # DS::add_timer callback
555         my ($self, $url_intvl) = @{$_[0]};
556         return if $self->{quit};
557         push @{$self->{idle_todo}}, $url_intvl;
558         event_step($self);
559 }
560
561 sub imap_idle_reap { # PublicInbox::DS::dwaitpid callback
562         my ($self, $pid) = @_;
563         my $url_intvl = delete $self->{idle_pids}->{$pid} or
564                 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
565
566         my ($url, $intvl) = @$url_intvl;
567         return if $self->{quit};
568         warn "W: PID=$pid on $url died: \$?=$?\n" if $?;
569         PublicInbox::DS::add_timer(60,
570                                 \&imap_idle_requeue, [ $self, $url_intvl ]);
571 }
572
573 sub imap_idle_fork ($$) {
574         my ($self, $url_intvl) = @_;
575         my ($url, $intvl) = @$url_intvl;
576         defined(my $pid = fork) or die "fork: $!";
577         if ($pid == 0) {
578                 watch_atfork_child($self);
579                 watch_imap_idle_1($self, $url, $intvl);
580                 _exit(0);
581         }
582         $self->{idle_pids}->{$pid} = $url_intvl;
583         PublicInbox::DS::dwaitpid($pid, \&imap_idle_reap, $self);
584 }
585
586 sub event_step {
587         my ($self) = @_;
588         return if $self->{quit};
589         my $idle_todo = $self->{idle_todo};
590         if ($idle_todo && @$idle_todo) {
591                 watch_atfork_parent($self);
592                 while (my $url_intvl = shift(@$idle_todo)) {
593                         imap_idle_fork($self, $url_intvl);
594                 }
595         }
596         goto(&fs_scan_step) if $self->{mdre};
597 }
598
599 sub watch_imap_fetch_all ($$) {
600         my ($self, $urls) = @_;
601         for my $url (@$urls) {
602                 my $uri = PublicInbox::URIimap->new($url);
603                 my $sec = uri_section($uri);
604                 my $mic_arg = $self->{mic_arg}->{$sec} or
605                         die "BUG: no Mail::IMAPClient->new arg for $sec";
606                 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or next;
607                 my $err = imap_fetch_all($self, $mic, $url);
608                 last if $self->{quit};
609                 warn $err, "\n" if $err;
610         }
611 }
612
613 sub watch_nntp_fetch_all ($$) {
614         my ($self, $urls) = @_;
615         for my $url (@$urls) {
616                 my $uri = uri_new($url);
617                 my $sec = uri_section($uri);
618                 my $nn_arg = $self->{nn_arg}->{$sec} or
619                         die "BUG: no Net::NNTP->new arg for $sec";
620                 my $nntp_opt = $self->{nntp_opt}->{$sec};
621                 my $nn = nn_new($nn_arg, $nntp_opt, $url);
622                 unless ($nn) {
623                         warn "E: $url: \$!=$!\n";
624                         next;
625                 }
626                 last if $self->{quit};
627                 if (my $postconn = $nntp_opt->{-postconn}) {
628                         for my $m_arg (@$postconn) {
629                                 my ($method, @args) = @$m_arg;
630                                 $nn->$method(@args) and next;
631                                 warn "E: <$url> $method failed\n";
632                                 $nn = undef;
633                                 last;
634                         }
635                 }
636                 last if $self->{quit};
637                 if ($nn) {
638                         my $err = nntp_fetch_all($self, $nn, $url);
639                         warn $err, "\n" if $err;
640                 }
641         }
642 }
643
644 sub poll_fetch_fork ($) { # DS::add_timer callback
645         my ($self, $intvl, $urls) = @{$_[0]};
646         return if $self->{quit};
647         watch_atfork_parent($self);
648         defined(my $pid = fork) or die "fork: $!";
649         if ($pid == 0) {
650                 watch_atfork_child($self);
651                 if ($urls->[0] =~ m!\Aimaps?://!i) {
652                         watch_imap_fetch_all($self, $urls);
653                 } else {
654                         watch_nntp_fetch_all($self, $urls);
655                 }
656                 _exit(0);
657         }
658         $self->{poll_pids}->{$pid} = [ $intvl, $urls ];
659         PublicInbox::DS::dwaitpid($pid, \&poll_fetch_reap, $self);
660 }
661
662 sub poll_fetch_reap { # PublicInbox::DS::dwaitpid callback
663         my ($self, $pid) = @_;
664         my $intvl_urls = delete $self->{poll_pids}->{$pid} or
665                 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
666         return if $self->{quit};
667         my ($intvl, $urls) = @$intvl_urls;
668         if ($?) {
669                 warn "W: PID=$pid died: \$?=$?\n", map { "$_\n" } @$urls;
670         }
671         warn("I: will check $_ in ${intvl}s\n") for @$urls;
672         PublicInbox::DS::add_timer($intvl, \&poll_fetch_fork,
673                                         [$self, $intvl, $urls]);
674 }
675
676 sub watch_imap_init ($$) {
677         my ($self, $poll) = @_;
678         eval { require PublicInbox::IMAPClient } or
679                 die "Mail::IMAPClient is required for IMAP:\n$@\n";
680         eval { require PublicInbox::IMAPTracker } or
681                 die "DBD::SQLite is required for IMAP\n:$@\n";
682
683         my $mic_args = imap_common_init($self); # read args from config
684
685         # make sure we can connect and cache the credentials in memory
686         $self->{mic_arg} = {}; # schema://authority => IMAPClient->new args
687         my $mics = {}; # schema://authority => IMAPClient obj
688         for my $url (sort keys %{$self->{imap}}) {
689                 my $uri = PublicInbox::URIimap->new($url);
690                 $mics->{uri_section($uri)} //= mic_for($self, $url, $mic_args);
691         }
692
693         my $idle = []; # [ [ url1, intvl1 ], [url2, intvl2] ]
694         for my $url (keys %{$self->{imap}}) {
695                 my $uri = PublicInbox::URIimap->new($url);
696                 my $sec = uri_section($uri);
697                 my $mic = $mics->{$sec};
698                 my $intvl = $self->{imap_opt}->{$sec}->{pollInterval};
699                 if ($mic->has_capability('IDLE') && !$intvl) {
700                         $intvl = $self->{imap_opt}->{$sec}->{idleInterval};
701                         push @$idle, [ $url, $intvl // () ];
702                 } else {
703                         push @{$poll->{$intvl || 120}}, $url;
704                 }
705         }
706         if (scalar @$idle) {
707                 $self->{idle_todo} = $idle;
708                 PublicInbox::DS::requeue($self); # ->event_step to fork
709         }
710 }
711
712 # flesh out common NNTP-specific data structures
713 sub nntp_common_init ($) {
714         my ($self) = @_;
715         my $cfg = $self->{config};
716         my $nn_args = {}; # scheme://authority => Net::NNTP->new arg
717         for my $url (sort keys %{$self->{nntp}}) {
718                 my $sec = uri_section(uri_new($url));
719
720                 # Debug and Timeout are passed to Net::NNTP->new
721                 my $v = cfg_bool($cfg, 'nntp.Debug', $url);
722                 $nn_args->{$sec}->{Debug} = $v if defined $v;
723                 my $to = cfg_intvl($cfg, 'nntp.Timeout', $url);
724                 $nn_args->{$sec}->{Timeout} = $to if $to;
725
726                 # Net::NNTP post-connect commands
727                 for my $k (qw(starttls compress)) {
728                         $v = cfg_bool($cfg, "nntp.$k", $url) // next;
729                         $self->{nntp_opt}->{$sec}->{$k} = $v;
730                 }
731
732                 # internal option
733                 for my $k (qw(pollInterval)) {
734                         $to = cfg_intvl($cfg, "nntp.$k", $url) // next;
735                         $self->{nntp_opt}->{$sec}->{$k} = $to;
736                 }
737         }
738         $nn_args;
739 }
740
741 # Net::NNTP doesn't support CAPABILITIES, yet
742 sub try_starttls ($) {
743         my ($host) = @_;
744         return if $host =~ /\.onion\z/s;
745         return if $host =~ /\A127\.[0-9]+\.[0-9]+\.[0-9]+\z/s;
746         return if $host eq '::1';
747         1;
748 }
749
750 sub nn_new ($$$) {
751         my ($nn_arg, $nntp_opt, $url) = @_;
752         my $nn = Net::NNTP->new(%$nn_arg) or die "E: <$url> new: $!\n";
753
754         # default to using STARTTLS if it's available, but allow
755         # it to be disabled for localhost/VPN users
756         if (!$nn_arg->{SSL} && $nn->can('starttls')) {
757                 if (!defined($nntp_opt->{starttls}) &&
758                                 try_starttls($nn_arg->{Host})) {
759                         # soft fail by default
760                         $nn->starttls or warn <<"";
761 W: <$url> STARTTLS tried and failed (not requested)
762
763                 } elsif ($nntp_opt->{starttls}) {
764                         # hard fail if explicitly configured
765                         $nn->starttls or die <<"";
766 E: <$url> STARTTLS requested and failed
767
768                 }
769         } elsif ($nntp_opt->{starttls}) {
770                 $nn->can('starttls') or
771                         die "E: <$url> Net::NNTP too old for STARTTLS\n";
772                 $nn->starttls or die <<"";
773 E: <$url> STARTTLS requested and failed
774
775         }
776         $nn;
777 }
778
779 sub nn_for ($$$) { # nn = Net::NNTP
780         my ($self, $url, $nn_args) = @_;
781         my $uri = uri_new($url);
782         my $sec = uri_section($uri);
783         my $nntp_opt = $self->{nntp_opt}->{$sec} //= {};
784         my $host = $uri->host;
785         # Net::NNTP and Net::Netrc both mishandle `0', so we pass `127.0.0.1'
786         $host = '127.0.0.1' if $host eq '0';
787         my $cred;
788         my ($u, $p);
789         if (defined(my $ui = $uri->userinfo)) {
790                 require PublicInbox::GitCredential;
791                 $cred = bless {
792                         url => $sec,
793                         protocol => uri_scheme($uri),
794                         host => $host,
795                 }, 'PublicInbox::GitCredential';
796                 ($u, $p) = split(/:/, $ui, 2);
797                 ($cred->{username}, $cred->{password}) = ($u, $p);
798                 $cred->check_netrc unless defined $p;
799         }
800         my $common = $nn_args->{$sec} // {};
801         my $nn_arg = {
802                 Port => $uri->port,
803                 Host => $host,
804                 SSL => $uri->secure, # snews == nntps
805                 %$common, # may Debug ....
806         };
807         my $nn = nn_new($nn_arg, $nntp_opt, $url);
808
809         if ($cred) {
810                 $cred->fill; # may prompt user here
811                 if ($nn->authinfo($u, $p)) {
812                         push @{$nntp_opt->{-postconn}}, [ 'authinfo', $u, $p ];
813                 } else {
814                         warn "E: <$url> AUTHINFO $u XXXX failed\n";
815                         $nn = undef;
816                 }
817         }
818
819         if ($nntp_opt->{compress}) {
820                 # https://rt.cpan.org/Ticket/Display.html?id=129967
821                 if ($nn->can('compress')) {
822                         if ($nn->compress) {
823                                 push @{$nntp_opt->{-postconn}}, [ 'compress' ];
824                         } else {
825                                 warn "W: <$url> COMPRESS failed\n";
826                         }
827                 } else {
828                         delete $nntp_opt->{compress};
829                         warn <<"";
830 W: <$url> COMPRESS not supported by Net::NNTP
831 W: see https://rt.cpan.org/Ticket/Display.html?id=129967 for updates
832
833                 }
834         }
835
836         $self->{nn_arg}->{$sec} = $nn_arg;
837         $cred->run($nn ? 'approve' : 'reject') if $cred;
838         $nn;
839 }
840
841 sub nntp_fetch_all ($$$) {
842         my ($self, $nn, $url) = @_;
843         my $uri = uri_new($url);
844         my ($group, $num_a, $num_b) = $uri->group;
845         my $sec = uri_section($uri);
846         my ($nr, $beg, $end) = $nn->group($group);
847         unless (defined($nr)) {
848                 chomp(my $msg = $nn->message);
849                 return "E: GROUP $group <$sec> $msg";
850         }
851
852         # IMAPTracker is also used for tracking NNTP, UID == article number
853         # LIST.ACTIVE can get the equivalent of UIDVALIDITY, but that's
854         # expensive.  So we assume newsgroups don't change:
855         my $itrk = PublicInbox::IMAPTracker->new($url);
856         my (undef, $l_art) = $itrk->get_last;
857         $l_art //= $beg; # initial import
858
859         # allow users to specify articles to refetch
860         # cf. https://tools.ietf.org/id/draft-gilman-news-url-01.txt
861         # nntp://example.com/inbox.foo/$num_a-$num_b
862         $l_art = $num_a if defined($num_a) && $num_a < $l_art;
863         $end = $num_b if defined($num_b) && $num_b < $end;
864
865         return if $l_art >= $end; # nothing to do
866         $beg = $l_art + 1;
867
868         warn "I: $url fetching ARTICLE $beg..$end\n";
869         my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
870         my ($err, $art);
871         local $SIG{__WARN__} = sub {
872                 $warn_cb->("$url ", $art ? ("ARTICLE $art") : (), "\n", @_);
873         };
874         my $inboxes = $self->{nntp}->{$url};
875         my $last_art;
876         for ($beg..$end) {
877                 last if $self->{quit};
878                 $art = $_;
879                 my $raw = $nn->article($art);
880                 unless (defined($raw)) {
881                         my $msg = $nn->message;
882                         if ($nn->code == 421) { # pseudo response from Net::Cmd
883                                 $err = "E: $msg";
884                                 last;
885                         } else { # probably just a deleted message (spam)
886                                 warn "W: $msg";
887                                 next;
888                         }
889                 }
890                 s/\r\n/\n/ for @$raw;
891                 $raw = join('', @$raw);
892                 if (ref($inboxes)) {
893                         for my $ibx (@$inboxes) {
894                                 my $eml = PublicInbox::Eml->new($raw);
895                                 import_eml($self, $ibx, $eml);
896                         }
897                 } elsif ($inboxes eq 'watchspam') {
898                         my $eml = PublicInbox::Eml->new(\$raw);
899                         my $arg = [ $self, $eml, "$url ARTICLE $art" ];
900                         $self->{config}->each_inbox(\&remove_eml_i, $arg);
901                 } else {
902                         die "BUG: destination unknown $inboxes";
903                 }
904                 $last_art = $art;
905         }
906         $itrk->update_last(0, $last_art) if defined $last_art;
907         _done_for_now($self);
908         $err;
909 }
910
911 sub watch_nntp_init ($$) {
912         my ($self, $poll) = @_;
913         eval { require Net::NNTP } or
914                 die "Net::NNTP is required for NNTP:\n$@\n";
915         eval { require PublicInbox::IMAPTracker } or
916                 die "DBD::SQLite is required for NNTP\n:$@\n";
917
918         my $nn_args = nntp_common_init($self); # read args from config
919
920         # make sure we can connect and cache the credentials in memory
921         $self->{nn_arg} = {}; # schema://authority => Net::NNTP->new args
922         for my $url (sort keys %{$self->{nntp}}) {
923                 nn_for($self, $url, $nn_args);
924         }
925         for my $url (keys %{$self->{nntp}}) {
926                 my $uri = uri_new($url);
927                 my $sec = uri_section($uri);
928                 my $intvl = $self->{nntp_opt}->{$sec}->{pollInterval};
929                 push @{$poll->{$intvl || 120}}, $url;
930         }
931 }
932
933 sub watch {
934         my ($self, $sig, $oldset) = @_;
935         $self->{oldset} = $oldset;
936         $self->{sig} = $sig;
937         my $poll = {}; # intvl_seconds => [ url1, url2 ]
938         watch_imap_init($self, $poll) if $self->{imap};
939         watch_nntp_init($self, $poll) if $self->{nntp};
940         while (my ($intvl, $urls) = each %$poll) {
941                 # poll all URLs for a given interval sequentially
942                 PublicInbox::DS::add_timer(0, \&poll_fetch_fork,
943                                                 [$self, $intvl, $urls]);
944         }
945         watch_fs_init($self) if $self->{mdre};
946         PublicInbox::DS->SetPostLoopCallback(sub { !$self->quit_done });
947         PublicInbox::DS->EventLoop;
948         _done_for_now($self);
949 }
950
951 sub trigger_scan {
952         my ($self, $op) = @_;
953         push @{$self->{ops}}, $op;
954         PublicInbox::DS::requeue($self);
955 }
956
957 sub fs_scan_step {
958         my ($self) = @_;
959         return if $self->{quit};
960         my $op = shift @{$self->{ops}};
961         local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
962
963         # continue existing scan
964         my $max = 10;
965         my $opendirs = $self->{opendirs};
966         my @dirnames = keys %$opendirs;
967         foreach my $dir (@dirnames) {
968                 my $dh = delete $opendirs->{$dir};
969                 my $n = $max;
970                 while (my $fn = readdir($dh)) {
971                         _try_path($self, "$dir/$fn");
972                         last if --$n < 0;
973                 }
974                 $opendirs->{$dir} = $dh if $n < 0;
975         }
976         if ($op && $op eq 'full') {
977                 foreach my $dir (keys %{$self->{mdmap}}) {
978                         next if $opendirs->{$dir}; # already in progress
979                         my $ok = opendir(my $dh, $dir);
980                         unless ($ok) {
981                                 warn "failed to open $dir: $!\n";
982                                 next;
983                         }
984                         my $n = $max;
985                         while (my $fn = readdir($dh)) {
986                                 _try_path($self, "$dir/$fn");
987                                 last if --$n < 0;
988                         }
989                         $opendirs->{$dir} = $dh if $n < 0;
990                 }
991         }
992         _done_for_now($self);
993         # do we have more work to do?
994         PublicInbox::DS::requeue($self) if keys %$opendirs;
995 }
996
997 sub scan {
998         my ($self, $op) = @_;
999         push @{$self->{ops}}, $op;
1000         goto &fs_scan_step;
1001 }
1002
1003 sub _importer_for {
1004         my ($self, $ibx) = @_;
1005         my $importers = $self->{importers};
1006         my $im = $importers->{"$ibx"} ||= $ibx->importer(0);
1007         if (scalar(keys(%$importers)) > 2) {
1008                 delete $importers->{"$ibx"};
1009                 _done_for_now($self);
1010         }
1011
1012         $importers->{"$ibx"} = $im;
1013 }
1014
1015 # XXX consider sharing with V2Writable, this only requires read-only access
1016 sub content_exists ($$) {
1017         my ($ibx, $eml) = @_;
1018         my $over = $ibx->over or return;
1019         my $mids = mids($eml);
1020         my $chash = content_hash($eml);
1021         my ($id, $prev);
1022         for my $mid (@$mids) {
1023                 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
1024                         my $cmp = $ibx->smsg_eml($smsg) or return;
1025                         return 1 if $chash eq content_hash($cmp);
1026                 }
1027         }
1028         undef;
1029 }
1030
1031 sub _spamcheck_cb {
1032         my ($sc) = @_;
1033         sub {
1034                 my ($mime, $ibx) = @_;
1035                 return if content_exists($ibx, $mime);
1036                 my $tmp = '';
1037                 if ($sc->spamcheck($mime, \$tmp)) {
1038                         return PublicInbox::Eml->new(\$tmp);
1039                 }
1040                 warn $mime->header('Message-ID')." failed spam check\n";
1041                 undef;
1042         }
1043 }
1044
1045 sub is_maildir {
1046         $_[0] =~ s!\Amaildir:!! or return;
1047         $_[0] =~ tr!/!/!s;
1048         $_[0] =~ s!/\z!!;
1049         $_[0];
1050 }
1051
1052 sub is_watchspam {
1053         my ($cur, $ws, $ibx) = @_;
1054         if ($ws && !ref($ws) && $ws eq 'watchspam') {
1055                 warn <<EOF;
1056 E: $cur is a spam folder and cannot be used for `$ibx->{name}' input
1057 EOF
1058                 return 1;
1059         }
1060         undef;
1061 }
1062
1063 sub uri_new {
1064         my ($url) = @_;
1065
1066         # URI::snews exists, URI::nntps does not, so use URI::snews
1067         $url =~ s!\Anntps://!snews://!i;
1068         URI->new($url);
1069 }
1070
1071 sub imap_url {
1072         my ($url) = @_;
1073         require PublicInbox::URIimap;
1074         my $uri = PublicInbox::URIimap->new($url);
1075         $uri ? $uri->canonical->as_string : undef;
1076 }
1077
1078 my %IS_NNTP = (news => 1, snews => 1, nntp => 1);
1079 sub nntp_url {
1080         my ($url) = @_;
1081         require URI;
1082         my $uri = uri_new($url);
1083         return unless $uri && $IS_NNTP{$uri->scheme} && $uri->group;
1084         $url = $uri->canonical->as_string;
1085         # nntps is IANA registered, snews is deprecated
1086         $url =~ s!\Asnews://!nntps://!;
1087         $url;
1088 }
1089
1090 1;