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