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