]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/WatchMaildir.pm
watch: use our own "git credential" wrapper
[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         my $host = $cred->{host};
321         my $mic_arg = {
322                 Port => $uri->port,
323                 # IMAPClient mishandles `0', so we pass `127.0.0.1'
324                 Server => $host eq '0' ? '127.0.0.1' : $host,
325                 Ssl => $uri->scheme eq 'imaps',
326                 Keepalive => 1, # SO_KEEPALIVE
327                 %$common, # may set Starttls, Compress, Debug ....
328         };
329         my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or
330                 die "E: <$url> new: $@\n";
331
332         # default to using STARTTLS if it's available, but allow
333         # it to be disabled since I usually connect to localhost
334         if (!$mic_arg->{Ssl} && !defined($mic_arg->{Starttls}) &&
335                         $mic->has_capability('STARTTLS') &&
336                         $mic->can('starttls')) {
337                 $mic->starttls or die "E: <$url> STARTTLS: $@\n";
338         }
339
340         # do we even need credentials?
341         if (!defined($cred->{username}) &&
342                         $mic->has_capability('AUTH=ANONYMOUS')) {
343                 $cred = undef;
344         }
345         if ($cred) {
346                 $cred->fill; # may prompt user here
347                 $mic->User($mic_arg->{User} = $cred->{username});
348                 $mic->Password($mic_arg->{Password} = $cred->{password});
349         } else { # AUTH=ANONYMOUS
350                 $mic->Authmechanism($mic_arg->{Authmechanism} = 'ANONYMOUS');
351                 $mic->Authcallback($mic_arg->{Authcallback} = \&auth_anon_cb);
352         }
353         if ($mic->login && $mic->IsAuthenticated) {
354                 # success! keep IMAPClient->new arg in case we get disconnected
355                 $self->{mic_arg}->{uri_section($uri)} = $mic_arg;
356         } else {
357                 warn "E: <$url> LOGIN: $@\n";
358                 $mic = undef;
359         }
360         $cred->run($mic ? 'approve' : 'reject') if $cred;
361         $mic;
362 }
363
364 sub imap_import_msg ($$$$) {
365         my ($self, $url, $uid, $raw) = @_;
366         # our target audience expects LF-only, save storage
367         $$raw =~ s/\r\n/\n/sg;
368
369         my $inboxes = $self->{imap}->{$url};
370         if (ref($inboxes)) {
371                 for my $ibx (@$inboxes) {
372                         my $eml = PublicInbox::Eml->new($$raw);
373                         my $x = import_eml($self, $ibx, $eml);
374                 }
375         } elsif ($inboxes eq 'watchspam') {
376                 my $eml = PublicInbox::Eml->new($raw);
377                 my $arg = [ $self, $eml, "$url UID:$uid" ];
378                 $self->{config}->each_inbox(\&remove_eml_i, $arg);
379         } else {
380                 die "BUG: destination unknown $inboxes";
381         }
382 }
383
384 sub imap_fetch_all ($$$) {
385         my ($self, $mic, $url) = @_;
386         my $uri = PublicInbox::URIimap->new($url);
387         my $sec = uri_section($uri);
388         my $mbx = $uri->mailbox;
389         $mic->Clear(1); # trim results history
390         $mic->examine($mbx) or return "E: EXAMINE $mbx ($sec) failed: $!";
391         my ($r_uidval, $r_uidnext);
392         for ($mic->Results) {
393                 /^\* OK \[UIDVALIDITY ([0-9]+)\].*/ and $r_uidval = $1;
394                 /^\* OK \[UIDNEXT ([0-9]+)\].*/ and $r_uidnext = $1;
395                 last if $r_uidval && $r_uidnext;
396         }
397         $r_uidval //= $mic->uidvalidity($mbx) //
398                 return "E: $url cannot get UIDVALIDITY";
399         $r_uidnext //= $mic->uidnext($mbx) //
400                 return "E: $url cannot get UIDNEXT";
401         my $itrk = PublicInbox::IMAPTracker->new($url);
402         my ($l_uidval, $l_uid) = $itrk->get_last;
403         $l_uidval //= $r_uidval; # first time
404         $l_uid //= 1;
405         if ($l_uidval != $r_uidval) {
406                 return "E: $url UIDVALIDITY mismatch\n".
407                         "E: local=$l_uidval != remote=$r_uidval";
408         }
409         my $r_uid = $r_uidnext - 1;
410         if ($l_uid != 1 && $l_uid > $r_uid) {
411                 return "E: $url local UID exceeds remote ($l_uid > $r_uid)\n".
412                         "E: $url strangely, UIDVALIDLITY matches ($l_uidval)\n";
413         }
414         return if $l_uid >= $r_uid; # nothing to do
415
416         warn "I: $url fetching UID $l_uid:$r_uid\n";
417         $mic->Uid(1); # the default, we hope
418         my $bs = $self->{imap_opt}->{$sec}->{batch_size} // 1;
419         my $req = $mic->imap4rev1 ? 'BODY.PEEK[]' : 'RFC822.PEEK';
420
421         # TODO: FLAGS may be useful for personal use
422         my $key = $req;
423         $key =~ s/\.PEEK//;
424         my ($uids, $batch);
425         my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
426         local $SIG{__WARN__} = sub {
427                 $batch //= '?';
428                 $warn_cb->("$url UID:$batch\n");
429                 $warn_cb->(@_);
430         };
431         my $err;
432         do {
433                 # I wish "UID FETCH $START:*" could work, but:
434                 # 1) servers do not need to return results in any order
435                 # 2) Mail::IMAPClient doesn't offer a streaming API
436                 $uids = $mic->search("UID $l_uid:*") or
437                         return "E: $url UID SEARCH $l_uid:* error: $!";
438                 return if scalar(@$uids) == 0;
439
440                 # RFC 3501 doesn't seem to indicate order of UID SEARCH
441                 # responses, so sort it ourselves.  Order matters so
442                 # IMAPTracker can store the newest UID.
443                 @$uids = sort { $a <=> $b } @$uids;
444
445                 # Did we actually get new messages?
446                 return if $uids->[0] < $l_uid;
447
448                 $l_uid = $uids->[-1] + 1; # for next search
449                 my $last_uid;
450
451                 while (scalar @$uids) {
452                         my @batch = splice(@$uids, 0, $bs);
453                         $batch = join(',', @batch);
454                         local $0 = "UID:$batch $mbx $sec";
455                         my $r = $mic->fetch_hash($batch, $req);
456                         unless ($r) { # network error?
457                                 $err = "E: $url UID FETCH $batch error: $!";
458                                 last;
459                         }
460                         for my $uid (@batch) {
461                                 # messages get deleted, so holes appear
462                                 my $per_uid = delete $r->{$uid} // next;
463                                 my $raw = delete($per_uid->{$key}) // next;
464                                 imap_import_msg($self, $url, $uid, \$raw);
465                                 $last_uid = $uid;
466                                 last if $self->{quit};
467                         }
468                         last if $self->{quit};
469                 }
470                 _done_for_now($self);
471                 $itrk->update_last($r_uidval, $last_uid) if defined $last_uid;
472         } until ($err || $self->{quit});
473         $err;
474 }
475
476 sub imap_idle_once ($$$$) {
477         my ($self, $mic, $intvl, $url) = @_;
478         my $i = $intvl //= (29 * 60);
479         my $end = now() + $intvl;
480         warn "I: $url idling for ${intvl}s\n";
481         local $0 = "IDLE $0";
482         unless ($mic->idle) {
483                 return if $self->{quit};
484                 return "E: IDLE failed on $url: $!";
485         }
486         $self->{idle_mic} = $mic; # for ->quit
487         my @res;
488         until ($self->{quit} || grep(/^\* [0-9]+ EXISTS/, @res) || $i <= 0) {
489                 @res = $mic->idle_data($i);
490                 $i = $end - now();
491         }
492         delete $self->{idle_mic};
493         unless ($self->{quit}) {
494                 $mic->IsConnected or return "E: IDLE disconnected on $url";
495                 $mic->done or return "E: IDLE DONE failed on $url: $!";
496         }
497         undef;
498 }
499
500 # idles on a single URI
501 sub watch_imap_idle_1 ($$$) {
502         my ($self, $url, $intvl) = @_;
503         my $uri = PublicInbox::URIimap->new($url);
504         my $sec = uri_section($uri);
505         my $mic_arg = $self->{mic_arg}->{$sec} or
506                         die "BUG: no Mail::IMAPClient->new arg for $sec";
507         my $mic;
508         local $0 = $uri->mailbox." $sec";
509         until ($self->{quit}) {
510                 $mic //= delete($self->{mics}->{$sec}) //
511                                 PublicInbox::IMAPClient->new(%$mic_arg);
512                 my $err = imap_fetch_all($self, $mic, $url);
513                 $err //= imap_idle_once($self, $mic, $intvl, $url);
514                 if ($err && !$self->{quit}) {
515                         warn $err, "\n";
516                         $mic = undef;
517                         sleep 60 unless $self->{quit};
518                 }
519         }
520 }
521
522 sub watch_atfork_child ($) {
523         my ($self) = @_;
524         delete $self->{idle_pids};
525         delete $self->{poll_pids};
526         delete $self->{opendirs};
527         PublicInbox::DS->Reset;
528         PublicInbox::Sigfd::sig_setmask($self->{oldset});
529         %SIG = (%SIG, %{$self->{sig}});
530 }
531
532 sub watch_atfork_parent ($) {
533         my ($self) = @_;
534         _done_for_now($self);
535         $self->{mics} = {}; # going to be forking, so disconnect
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) = @_;
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 = $self->{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         my $poll = {}; # intvl_seconds => [ url1, url2 ]
672         for my $url (keys %{$self->{imap}}) {
673                 my $uri = PublicInbox::URIimap->new($url);
674                 my $sec = uri_section($uri);
675                 my $mic = $mics->{$sec};
676                 my $intvl = $self->{imap_opt}->{$sec}->{pollInterval};
677                 if ($mic->has_capability('IDLE') && !$intvl) {
678                         $intvl = $self->{imap_opt}->{$sec}->{idleInterval};
679                         push @$idle, [ $url, $intvl // () ];
680                 } else {
681                         push @{$poll->{$intvl || 120}}, $url;
682                 }
683         }
684         if (scalar @$idle) {
685                 $self->{idle_pids} = {};
686                 $self->{idle_todo} = $idle;
687                 PublicInbox::DS::requeue($self); # ->event_step to fork
688         }
689         return unless scalar keys %$poll;
690         $self->{poll_pids} //= {};
691
692         # poll all URLs for a given interval sequentially
693         while (my ($intvl, $urls) = each %$poll) {
694                 PublicInbox::DS::add_timer(0, \&poll_fetch_fork,
695                                                 [$self, $intvl, $urls]);
696         }
697 }
698
699 # flesh out common NNTP-specific data structures
700 sub nntp_common_init ($) {
701         my ($self) = @_;
702         my $cfg = $self->{config};
703         my $nn_args = {}; # scheme://authority => Net::NNTP->new arg
704         for my $url (sort keys %{$self->{nntp}}) {
705                 my $sec = uri_section(uri_new($url));
706
707                 # Debug and Timeout are passed to Net::NNTP->new
708                 my $v = cfg_bool($cfg, 'nntp.Debug', $url);
709                 $nn_args->{$sec}->{Debug} = $v if defined $v;
710                 my $to = cfg_intvl($cfg, 'nntp.Timeout', $url);
711                 $nn_args->{$sec}->{Timeout} = $to if $to;
712
713                 # Net::NNTP post-connect commands
714                 for my $k (qw(starttls compress)) {
715                         $v = cfg_bool($cfg, "nntp.$k", $url) // next;
716                         $self->{nntp_opt}->{$sec}->{$k} = $v;
717                 }
718
719                 # internal option
720                 for my $k (qw(pollInterval)) {
721                         $to = cfg_intvl($cfg, "nntp.$k", $url) // next;
722                         $self->{nntp_opt}->{$sec}->{$k} = $to;
723                 }
724         }
725         $nn_args;
726 }
727
728 # Net::NNTP doesn't support CAPABILITIES, yet
729 sub try_starttls ($) {
730         my ($host) = @_;
731         return if $host =~ /\.onion\z/s;
732         return if $host =~ /\A127\.[0-9]+\.[0-9]+\.[0-9]+\z/s;
733         return if $host eq '::1';
734         1;
735 }
736
737 sub nn_new ($$$) {
738         my ($nn_arg, $nntp_opt, $url) = @_;
739         my $nn = Net::NNTP->new(%$nn_arg) or die "E: <$url> new: $!\n";
740
741         # default to using STARTTLS if it's available, but allow
742         # it to be disabled for localhost/VPN users
743         if (!$nn_arg->{SSL} && $nn->can('starttls')) {
744                 if (!defined($nntp_opt->{starttls}) &&
745                                 try_starttls($nn_arg->{Host})) {
746                         # soft fail by default
747                         $nn->starttls or warn <<"";
748 W: <$url> STARTTLS tried and failed (not requested)
749
750                 } elsif ($nntp_opt->{starttls}) {
751                         # hard fail if explicitly configured
752                         $nn->starttls or die <<"";
753 E: <$url> STARTTLS requested and failed
754
755                 }
756         } elsif ($nntp_opt->{starttls}) {
757                 $nn->can('starttls') or
758                         die "E: <$url> Net::NNTP too old for STARTTLS\n";
759                 $nn->starttls or die <<"";
760 E: <$url> STARTTLS requested and failed
761
762         }
763         $nn;
764 }
765
766 sub nn_for ($$$) { # nn = Net::NNTP
767         my ($self, $url, $nn_args) = @_;
768         my $uri = uri_new($url);
769         my $sec = uri_section($uri);
770         my $nntp_opt = $self->{nntp_opt}->{$sec} //= {};
771         my $cred;
772         my ($u, $p);
773         if (defined(my $ui = $uri->userinfo)) {
774                 require PublicInbox::GitCredential;
775                 $cred = bless {
776                         url => $sec,
777                         protocol => uri_scheme($uri),
778                         host => $uri->host,
779                 }, 'PublicInbox::GitCredential';
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                 $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         $cred->run($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 PublicInbox::IMAPTracker } or
900                 die "DBD::SQLite is required for NNTP\n:$@\n";
901
902         my $nn_args = nntp_common_init($self); # read args from config
903
904         # make sure we can connect and cache the credentials in memory
905         $self->{nn_arg} = {}; # schema://authority => Net::NNTP->new args
906         for my $url (sort keys %{$self->{nntp}}) {
907                 nn_for($self, $url, $nn_args);
908         }
909         my $poll = {}; # intvl_seconds => [ url1, url2 ]
910         for my $url (keys %{$self->{nntp}}) {
911                 my $uri = uri_new($url);
912                 my $sec = uri_section($uri);
913                 my $intvl = $self->{nntp_opt}->{$sec}->{pollInterval};
914                 push @{$poll->{$intvl || 120}}, $url;
915         }
916         $self->{poll_pids} //= {};
917
918         # poll all URLs for a given interval sequentially
919         while (my ($intvl, $urls) = each %$poll) {
920                 PublicInbox::DS::add_timer(0, \&poll_fetch_fork,
921                                                 [$self, $intvl, $urls]);
922         }
923 }
924
925 sub watch {
926         my ($self, $sig, $oldset) = @_;
927         $self->{oldset} = $oldset;
928         $self->{sig} = $sig;
929         watch_imap_init($self) if $self->{imap};
930         watch_nntp_init($self) if $self->{nntp};
931         watch_fs_init($self) if $self->{mdre};
932         PublicInbox::DS->SetPostLoopCallback(sub {});
933         PublicInbox::DS->EventLoop until $self->{quit};
934         _done_for_now($self);
935 }
936
937 sub trigger_scan {
938         my ($self, $op) = @_;
939         push @{$self->{ops}}, $op;
940         PublicInbox::DS::requeue($self);
941 }
942
943 sub fs_scan_step {
944         my ($self) = @_;
945         return if $self->{quit};
946         my $op = shift @{$self->{ops}};
947
948         # continue existing scan
949         my $max = 10;
950         my $opendirs = $self->{opendirs};
951         my @dirnames = keys %$opendirs;
952         foreach my $dir (@dirnames) {
953                 my $dh = delete $opendirs->{$dir};
954                 my $n = $max;
955                 while (my $fn = readdir($dh)) {
956                         _try_path($self, "$dir/$fn");
957                         last if --$n < 0;
958                 }
959                 $opendirs->{$dir} = $dh if $n < 0;
960         }
961         if ($op && $op eq 'full') {
962                 foreach my $dir (keys %{$self->{mdmap}}) {
963                         next if $opendirs->{$dir}; # already in progress
964                         my $ok = opendir(my $dh, $dir);
965                         unless ($ok) {
966                                 warn "failed to open $dir: $!\n";
967                                 next;
968                         }
969                         my $n = $max;
970                         while (my $fn = readdir($dh)) {
971                                 _try_path($self, "$dir/$fn");
972                                 last if --$n < 0;
973                         }
974                         $opendirs->{$dir} = $dh if $n < 0;
975                 }
976         }
977         _done_for_now($self);
978         # do we have more work to do?
979         PublicInbox::DS::requeue($self) if keys %$opendirs;
980 }
981
982 sub scan {
983         my ($self, $op) = @_;
984         push @{$self->{ops}}, $op;
985         goto &fs_scan_step;
986 }
987
988 sub _importer_for {
989         my ($self, $ibx) = @_;
990         my $importers = $self->{importers};
991         my $im = $importers->{"$ibx"} ||= $ibx->importer(0);
992         if (scalar(keys(%$importers)) > 2) {
993                 delete $importers->{"$ibx"};
994                 _done_for_now($self);
995         }
996
997         $importers->{"$ibx"} = $im;
998 }
999
1000 sub _spamcheck_cb {
1001         my ($sc) = @_;
1002         sub {
1003                 my ($mime) = @_;
1004                 my $tmp = '';
1005                 if ($sc->spamcheck($mime, \$tmp)) {
1006                         return PublicInbox::Eml->new(\$tmp);
1007                 }
1008                 warn $mime->header('Message-ID')." failed spam check\n";
1009                 undef;
1010         }
1011 }
1012
1013 sub is_maildir {
1014         $_[0] =~ s!\Amaildir:!! or return;
1015         $_[0] =~ tr!/!/!s;
1016         $_[0] =~ s!/\z!!;
1017         $_[0];
1018 }
1019
1020 sub is_watchspam {
1021         my ($cur, $ws, $ibx) = @_;
1022         if ($ws && !ref($ws) && $ws eq 'watchspam') {
1023                 warn <<EOF;
1024 E: $cur is a spam folder and cannot be used for `$ibx->{name}' input
1025 EOF
1026                 return 1;
1027         }
1028         undef;
1029 }
1030
1031 sub uri_new {
1032         my ($url) = @_;
1033
1034         # URI::snews exists, URI::nntps does not, so use URI::snews
1035         $url =~ s!\Anntps://!snews://!i;
1036         URI->new($url);
1037 }
1038
1039 sub imap_url {
1040         my ($url) = @_;
1041         require PublicInbox::URIimap;
1042         my $uri = PublicInbox::URIimap->new($url);
1043         $uri ? $uri->canonical->as_string : undef;
1044 }
1045
1046 my %IS_NNTP = (news => 1, snews => 1, nntp => 1);
1047 sub nntp_url {
1048         my ($url) = @_;
1049         require URI;
1050         my $uri = uri_new($url);
1051         return unless $uri && $IS_NNTP{$uri->scheme} && $uri->group;
1052         $url = $uri->canonical->as_string;
1053         # nntps is IANA registered, snews is deprecated
1054         $url =~ s!\Asnews://!nntps://!;
1055         $url;
1056 }
1057
1058 1;