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