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