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