]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Watch.pm
watch: connect to NNTP and IMAP in config order
[public-inbox.git] / lib / PublicInbox / Watch.pm
1 # Copyright (C) 2016-2021 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 #       httsp://wiki2.dovecot.org/MailboxFormat/Maildir
6 package PublicInbox::Watch;
7 use strict;
8 use v5.10.1;
9 use PublicInbox::Eml;
10 use PublicInbox::InboxWritable qw(eml_from_path);
11 use PublicInbox::MdirReader;
12 use PublicInbox::NetReader;
13 use PublicInbox::Filter::Base qw(REJECT);
14 use PublicInbox::Spamcheck;
15 use PublicInbox::Sigfd;
16 use PublicInbox::DS qw(now add_timer);
17 use PublicInbox::MID qw(mids);
18 use PublicInbox::ContentHash qw(content_hash);
19 use PublicInbox::EOFpipe;
20 use POSIX qw(_exit WNOHANG);
21
22 sub compile_watchheaders ($) {
23         my ($ibx) = @_;
24         my $watch_hdrs = [];
25         if (my $whs = $ibx->{watchheader}) {
26                 for (@$whs) {
27                         my ($k, $v) = split(/:/, $_, 2);
28                         # XXX should this be case-insensitive?
29                         # Or, mutt-style, case-sensitive iff
30                         # a capital letter exists?
31                         push @$watch_hdrs, [ $k, qr/\Q$v\E/ ];
32                 }
33         }
34         if (my $list_ids = $ibx->{listid}) {
35                 for (@$list_ids) {
36                         # RFC2919 section 6 stipulates
37                         # "case insensitive equality"
38                         my $re = qr/<[ \t]*\Q$_\E[ \t]*>/i;
39                         push @$watch_hdrs, ['List-Id', $re ];
40                 }
41         }
42         $ibx->{-watchheaders} = $watch_hdrs if scalar @$watch_hdrs;
43 }
44
45 sub new {
46         my ($class, $cfg) = @_;
47         my (%mdmap, $spamc);
48         my (%imap, %nntp); # url => [inbox objects] or 'watchspam'
49         my (@imap, @nntp);
50
51         # "publicinboxwatch" is the documented namespace
52         # "publicinboxlearn" is legacy but may be supported
53         # indefinitely...
54         foreach my $pfx (qw(publicinboxwatch publicinboxlearn)) {
55                 my $k = "$pfx.watchspam";
56                 defined(my $dirs = $cfg->{$k}) or next;
57                 $dirs = PublicInbox::Config::_array($dirs);
58                 for my $dir (@$dirs) {
59                         my $url;
60                         if (is_maildir($dir)) {
61                                 # skip "new", no MUA has seen it, yet.
62                                 $mdmap{"$dir/cur"} = 'watchspam';
63                         } elsif ($url = imap_url($dir)) {
64                                 $imap{$url} = 'watchspam';
65                                 push @imap, $url;
66                         } elsif ($url = nntp_url($dir)) {
67                                 $nntp{$url} = 'watchspam';
68                                 push @nntp, $url;
69                         } else {
70                                 warn "unsupported $k=$dir\n";
71                         }
72                 }
73         }
74
75         my $k = 'publicinboxwatch.spamcheck';
76         my $default = undef;
77         my $spamcheck = PublicInbox::Spamcheck::get($cfg, $k, $default);
78         $spamcheck = _spamcheck_cb($spamcheck) if $spamcheck;
79
80         $cfg->each_inbox(sub {
81                 # need to make all inboxes writable for spam removal:
82                 my $ibx = $_[0] = PublicInbox::InboxWritable->new($_[0]);
83
84                 my $watches = $ibx->{watch} or return;
85                 $watches = PublicInbox::Config::_array($watches);
86                 for my $watch (@$watches) {
87                         my $url;
88                         if (is_maildir($watch)) {
89                                 compile_watchheaders($ibx);
90                                 my ($new, $cur) = ("$watch/new", "$watch/cur");
91                                 my $cur_dst = $mdmap{$cur} //= [];
92                                 return if is_watchspam($cur, $cur_dst, $ibx);
93                                 push @{$mdmap{$new} //= []}, $ibx;
94                                 push @$cur_dst, $ibx;
95                         } elsif ($url = imap_url($watch)) {
96                                 return if is_watchspam($url, $imap{$url}, $ibx);
97                                 compile_watchheaders($ibx);
98                                 my $n = push @{$imap{$url} ||= []}, $ibx;
99                                 push @imap, $url if $n == 1;
100                         } elsif ($url = nntp_url($watch)) {
101                                 return if is_watchspam($url, $nntp{$url}, $ibx);
102                                 compile_watchheaders($ibx);
103                                 my $n = push @{$nntp{$url} ||= []}, $ibx;
104                                 push @nntp, $url if $n == 1;
105                         } else {
106                                 warn "watch unsupported: $k=$watch\n";
107                         }
108                 }
109         });
110
111         my $mdre;
112         if (scalar keys %mdmap) {
113                 $mdre = join('|', map { quotemeta($_) } keys %mdmap);
114                 $mdre = qr!\A($mdre)/!;
115         }
116         return unless $mdre || scalar(keys %imap) || scalar(keys %nntp);
117
118         bless {
119                 max_batch => 10, # avoid hogging locks for too long
120                 spamcheck => $spamcheck,
121                 mdmap => \%mdmap,
122                 mdre => $mdre,
123                 pi_cfg => $cfg,
124                 imap => scalar keys %imap ? \%imap : undef,
125                 nntp => scalar keys %nntp? \%nntp : undef,
126                 imap_order => scalar(@imap) ? \@imap : undef,
127                 nntp_order => scalar(@nntp) ? \@nntp: undef,
128                 importers => {},
129                 opendirs => {}, # dirname => dirhandle (in progress scans)
130                 ops => [], # 'quit', 'full'
131         }, $class;
132 }
133
134 sub _done_for_now {
135         my ($self) = @_;
136         local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
137         for my $im (values %{$self->{importers}}) {
138                 next if !$im; # $im may be undef during cleanup
139                 eval { $im->done };
140                 warn "$im->{ibx}->{name} ->done: $@\n" if $@;
141         }
142 }
143
144 sub remove_eml_i { # each_inbox callback
145         my ($ibx, $self, $eml, $loc) = @_;
146
147         eval {
148                 # try to avoid taking a lock or unnecessary spawning
149                 my $im = $self->{importers}->{"$ibx"};
150                 my $scrubbed;
151                 if ((!$im || !$im->active) && $ibx->over) {
152                         if (content_exists($ibx, $eml)) {
153                                 # continue
154                         } elsif (my $scrub = $ibx->filter($im)) {
155                                 $scrubbed = $scrub->scrub($eml, 1);
156                                 if ($scrubbed && $scrubbed != REJECT &&
157                                           !content_exists($ibx, $scrubbed)) {
158                                         return;
159                                 }
160                         } else {
161                                 return;
162                         }
163                 }
164
165                 $im //= _importer_for($self, $ibx); # may spawn fast-import
166                 $im->remove($eml, 'spam');
167                 $scrubbed //= do {
168                         my $scrub = $ibx->filter($im);
169                         $scrub ? $scrub->scrub($eml, 1) : undef;
170                 };
171                 if ($scrubbed && $scrubbed != REJECT) {
172                         $im->remove($scrubbed, 'spam');
173                 }
174         };
175         if ($@) {
176                 warn "error removing spam at: $loc from $ibx->{name}: $@\n";
177                 _done_for_now($self);
178         }
179 }
180
181 sub _remove_spam {
182         my ($self, $path) = @_;
183         # path must be marked as (S)een
184         $path =~ /:2,[A-R]*S[T-Za-z]*\z/ or return;
185         my $eml = eml_from_path($path) or return;
186         local $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
187         $self->{pi_cfg}->each_inbox(\&remove_eml_i, $self, $eml, $path);
188 }
189
190 sub import_eml ($$$) {
191         my ($self, $ibx, $eml) = @_;
192
193         # any header match means it's eligible for the inbox:
194         if (my $watch_hdrs = $ibx->{-watchheaders}) {
195                 my $ok;
196                 for my $wh (@$watch_hdrs) {
197                         my @v = $eml->header_raw($wh->[0]);
198                         $ok = grep(/$wh->[1]/, @v) and last;
199                 }
200                 return unless $ok;
201         }
202         eval {
203                 my $im = _importer_for($self, $ibx);
204                 if (my $scrub = $ibx->filter($im)) {
205                         my $scrubbed = $scrub->scrub($eml) or return;
206                         $scrubbed == REJECT and return;
207                         $eml = $scrubbed;
208                 }
209                 $im->add($eml, $self->{spamcheck});
210         };
211         if ($@) {
212                 warn "$ibx->{name} add failed: $@\n";
213                 _done_for_now($self);
214         }
215 }
216
217 sub _try_path {
218         my ($self, $path) = @_;
219         my $fl = PublicInbox::MdirReader::maildir_path_flags($path) // return;
220         return if $fl =~ /[DT]/; # no Drafts or Trash
221         if ($path !~ $self->{mdre}) {
222                 warn "unrecognized path: $path\n";
223                 return;
224         }
225         my $inboxes = $self->{mdmap}->{$1};
226         unless ($inboxes) {
227                 warn "unmappable dir: $1\n";
228                 return;
229         }
230         my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
231         local $SIG{__WARN__} = sub {
232                 my $pfx = ($_[0] // '') =~ /^([A-Z]: )/g ? $1 : '';
233                 $warn_cb->($pfx, "path: $path\n", @_);
234         };
235         if (!ref($inboxes) && $inboxes eq 'watchspam') {
236                 return _remove_spam($self, $path);
237         }
238         foreach my $ibx (@$inboxes) {
239                 my $eml = eml_from_path($path) or next;
240                 import_eml($self, $ibx, $eml);
241         }
242 }
243
244 sub quit_done ($) {
245         my ($self) = @_;
246         return unless $self->{quit};
247
248         # don't have reliable wakeups, keep signalling
249         my $done = 1;
250         for (qw(idle_pids poll_pids)) {
251                 my $pids = $self->{$_} or next;
252                 for (keys %$pids) {
253                         $done = undef if kill('QUIT', $_);
254                 }
255         }
256         $done;
257 }
258
259 sub quit {
260         my ($self) = @_;
261         $self->{quit} = 1;
262         %{$self->{opendirs}} = ();
263         _done_for_now($self);
264         quit_done($self);
265         if (my $idle_mic = $self->{idle_mic}) {
266                 eval { $idle_mic->done };
267                 if ($@) {
268                         warn "IDLE DONE error: $@\n";
269                         eval { $idle_mic->disconnect };
270                         warn "IDLE LOGOUT error: $@\n" if $@;
271                 }
272         }
273 }
274
275 sub watch_fs_init ($) {
276         my ($self) = @_;
277         my $done = sub {
278                 delete $self->{done_timer};
279                 _done_for_now($self);
280         };
281         my $cb = sub { # called by PublicInbox::DirIdle::event_step
282                 _try_path($self, $_[0]->fullname);
283                 $self->{done_timer} //= PublicInbox::DS::requeue($done);
284         };
285         require PublicInbox::DirIdle;
286         # inotify_create + EPOLL_CTL_ADD
287         PublicInbox::DirIdle->new([keys %{$self->{mdmap}}], $cb);
288 }
289
290 sub imap_import_msg ($$$$$) {
291         my ($self, $url, $uid, $raw, $flags) = @_;
292         # our target audience expects LF-only, save storage
293         $$raw =~ s/\r\n/\n/sg;
294
295         my $inboxes = $self->{imap}->{$url};
296         if (ref($inboxes)) {
297                 for my $ibx (@$inboxes) {
298                         my $eml = PublicInbox::Eml->new($$raw);
299                         import_eml($self, $ibx, $eml);
300                 }
301         } elsif ($inboxes eq 'watchspam') {
302                 return if $flags !~ /\\Seen\b/; # don't remove unseen messages
303                 local $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
304                 my $eml = PublicInbox::Eml->new($raw);
305                 $self->{pi_cfg}->each_inbox(\&remove_eml_i,
306                                                 $self, $eml, "$url UID:$uid");
307         } else {
308                 die "BUG: destination unknown $inboxes";
309         }
310 }
311
312 sub imap_fetch_all ($$$) {
313         my ($self, $mic, $url) = @_;
314         my $uri = PublicInbox::URIimap->new($url);
315         my $sec = uri_section($uri);
316         my $mbx = $uri->mailbox;
317         $mic->Clear(1); # trim results history
318         $mic->examine($mbx) or return "E: EXAMINE $mbx ($sec) failed: $!";
319         my ($r_uidval, $r_uidnext);
320         for ($mic->Results) {
321                 /^\* OK \[UIDVALIDITY ([0-9]+)\].*/ and $r_uidval = $1;
322                 /^\* OK \[UIDNEXT ([0-9]+)\].*/ and $r_uidnext = $1;
323                 last if $r_uidval && $r_uidnext;
324         }
325         $r_uidval //= $mic->uidvalidity($mbx) //
326                 return "E: $url cannot get UIDVALIDITY";
327         $r_uidnext //= $mic->uidnext($mbx) //
328                 return "E: $url cannot get UIDNEXT";
329         my $itrk = PublicInbox::IMAPTracker->new($url);
330         my ($l_uidval, $l_uid) = $itrk->get_last;
331         $l_uidval //= $r_uidval; # first time
332         $l_uid //= 1;
333         if ($l_uidval != $r_uidval) {
334                 return "E: $url UIDVALIDITY mismatch\n".
335                         "E: local=$l_uidval != remote=$r_uidval";
336         }
337         my $r_uid = $r_uidnext - 1;
338         if ($l_uid != 1 && $l_uid > $r_uid) {
339                 return "E: $url local UID exceeds remote ($l_uid > $r_uid)\n".
340                         "E: $url strangely, UIDVALIDLITY matches ($l_uidval)\n";
341         }
342         return if $l_uid >= $r_uid; # nothing to do
343
344         warn "I: $url fetching UID $l_uid:$r_uid\n";
345         $mic->Uid(1); # the default, we hope
346         my $bs = $self->{imap_opt}->{$sec}->{batch_size} // 1;
347         my $req = $mic->imap4rev1 ? 'BODY.PEEK[]' : 'RFC822.PEEK';
348
349         # TODO: FLAGS may be useful for personal use
350         my $key = $req;
351         $key =~ s/\.PEEK//;
352         my ($uids, $batch);
353         my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
354         local $SIG{__WARN__} = sub {
355                 my $pfx = ($_[0] // '') =~ /^([A-Z]: )/g ? $1 : '';
356                 $batch //= '?';
357                 $warn_cb->("$pfx$url UID:$batch\n", @_);
358         };
359         my $err;
360         do {
361                 # I wish "UID FETCH $START:*" could work, but:
362                 # 1) servers do not need to return results in any order
363                 # 2) Mail::IMAPClient doesn't offer a streaming API
364                 $uids = $mic->search("UID $l_uid:*") or
365                         return "E: $url UID SEARCH $l_uid:* error: $!";
366                 return if scalar(@$uids) == 0;
367
368                 # RFC 3501 doesn't seem to indicate order of UID SEARCH
369                 # responses, so sort it ourselves.  Order matters so
370                 # IMAPTracker can store the newest UID.
371                 @$uids = sort { $a <=> $b } @$uids;
372
373                 # Did we actually get new messages?
374                 return if $uids->[0] < $l_uid;
375
376                 $l_uid = $uids->[-1] + 1; # for next search
377                 my $last_uid;
378                 my $n = $self->{max_batch};
379
380                 while (scalar @$uids) {
381                         if (--$n < 0) {
382                                 _done_for_now($self);
383                                 $itrk->update_last($r_uidval, $last_uid);
384                                 $n = $self->{max_batch};
385                         }
386                         my @batch = splice(@$uids, 0, $bs);
387                         $batch = join(',', @batch);
388                         local $0 = "UID:$batch $mbx $sec";
389                         my $r = $mic->fetch_hash($batch, $req, 'FLAGS');
390                         unless ($r) { # network error?
391                                 $err = "E: $url UID FETCH $batch error: $!";
392                                 last;
393                         }
394                         for my $uid (@batch) {
395                                 # messages get deleted, so holes appear
396                                 my $per_uid = delete $r->{$uid} // next;
397                                 my $raw = delete($per_uid->{$key}) // next;
398                                 my $fl = $per_uid->{FLAGS} // '';
399                                 imap_import_msg($self, $url, $uid, \$raw, $fl);
400                                 $last_uid = $uid;
401                                 last if $self->{quit};
402                         }
403                         last if $self->{quit};
404                 }
405                 _done_for_now($self);
406                 $itrk->update_last($r_uidval, $last_uid);
407         } until ($err || $self->{quit});
408         $err;
409 }
410
411 sub imap_idle_once ($$$$) {
412         my ($self, $mic, $intvl, $url) = @_;
413         my $i = $intvl //= (29 * 60);
414         my $end = now() + $intvl;
415         warn "I: $url idling for ${intvl}s\n";
416         local $0 = "IDLE $0";
417         unless ($mic->idle) {
418                 return if $self->{quit};
419                 return "E: IDLE failed on $url: $!";
420         }
421         $self->{idle_mic} = $mic; # for ->quit
422         my @res;
423         until ($self->{quit} || !$mic->IsConnected ||
424                         grep(/^\* [0-9]+ EXISTS/, @res) || $i <= 0) {
425                 @res = $mic->idle_data($i);
426                 $i = $end - now();
427         }
428         delete $self->{idle_mic};
429         unless ($self->{quit}) {
430                 $mic->IsConnected or return "E: IDLE disconnected on $url";
431                 $mic->done or return "E: IDLE DONE failed on $url: $!";
432         }
433         undef;
434 }
435
436 # idles on a single URI
437 sub watch_imap_idle_1 ($$$) {
438         my ($self, $url, $intvl) = @_;
439         my $uri = PublicInbox::URIimap->new($url);
440         my $sec = uri_section($uri);
441         my $mic_arg = $self->{mic_arg}->{$sec} or
442                         die "BUG: no Mail::IMAPClient->new arg for $sec";
443         my $mic;
444         local $0 = $uri->mailbox." $sec";
445         until ($self->{quit}) {
446                 $mic //= PublicInbox::IMAPClient->new(%$mic_arg);
447                 my $err;
448                 if ($mic && $mic->IsConnected) {
449                         $err = imap_fetch_all($self, $mic, $url);
450                         $err //= imap_idle_once($self, $mic, $intvl, $url);
451                 } else {
452                         $err = "E: not connected: $!";
453                 }
454                 if ($err && !$self->{quit}) {
455                         warn $err, "\n";
456                         $mic = undef;
457                         sleep 60 unless $self->{quit};
458                 }
459         }
460 }
461
462 sub watch_atfork_child ($) {
463         my ($self) = @_;
464         delete $self->{idle_pids};
465         delete $self->{poll_pids};
466         delete $self->{opendirs};
467         PublicInbox::DS->Reset;
468         %SIG = (%SIG, %{$self->{sig}}, CHLD => 'DEFAULT');
469         PublicInbox::DS::sig_setmask($self->{oldset});
470 }
471
472 sub watch_atfork_parent ($) {
473         my ($self) = @_;
474         _done_for_now($self);
475         PublicInbox::DS::block_signals();
476 }
477
478 sub imap_idle_requeue { # DS::add_timer callback
479         my ($self, $url_intvl) = @_;
480         return if $self->{quit};
481         push @{$self->{idle_todo}}, $url_intvl;
482         event_step($self);
483 }
484
485 sub imap_idle_reap { # PublicInbox::DS::dwaitpid callback
486         my ($self, $pid) = @_;
487         my $url_intvl = delete $self->{idle_pids}->{$pid} or
488                 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
489
490         my ($url, $intvl) = @$url_intvl;
491         return if $self->{quit};
492         warn "W: PID=$pid on $url died: \$?=$?\n" if $?;
493         add_timer(60, \&imap_idle_requeue, $self, $url_intvl);
494 }
495
496 sub reap { # callback for EOFpipe
497         my ($pid, $cb, $self) = @{$_[0]};
498         my $ret = waitpid($pid, 0);
499         if ($ret == $pid) {
500                 $cb->($self, $pid); # poll_fetch_reap || imap_idle_reap
501         } else {
502                 warn "W: waitpid($pid) => ", $ret // "($!)", "\n";
503         }
504 }
505
506 sub imap_idle_fork ($$) {
507         my ($self, $url_intvl) = @_;
508         my ($url, $intvl) = @$url_intvl;
509         pipe(my ($r, $w)) or die "pipe: $!";
510         my $seed = rand(0xffffffff);
511         my $pid = fork // die "fork: $!";
512         if ($pid == 0) {
513                 srand($seed);
514                 eval { Net::SSLeay::randomize() };
515                 close $r;
516                 watch_atfork_child($self);
517                 watch_imap_idle_1($self, $url, $intvl);
518                 close $w;
519                 _exit(0);
520         }
521         $self->{idle_pids}->{$pid} = $url_intvl;
522         PublicInbox::EOFpipe->new($r, \&reap, [$pid, \&imap_idle_reap, $self]);
523 }
524
525 sub event_step {
526         my ($self) = @_;
527         return if $self->{quit};
528         my $idle_todo = $self->{idle_todo};
529         if ($idle_todo && @$idle_todo) {
530                 my $oldset = watch_atfork_parent($self);
531                 eval {
532                         while (my $url_intvl = shift(@$idle_todo)) {
533                                 imap_idle_fork($self, $url_intvl);
534                         }
535                 };
536                 PublicInbox::DS::sig_setmask($oldset);
537                 die $@ if $@;
538         }
539         fs_scan_step($self) if $self->{mdre};
540 }
541
542 sub watch_imap_fetch_all ($$) {
543         my ($self, $urls) = @_;
544         for my $url (@$urls) {
545                 my $uri = PublicInbox::URIimap->new($url);
546                 my $sec = uri_section($uri);
547                 my $mic_arg = $self->{mic_arg}->{$sec} or
548                         die "BUG: no Mail::IMAPClient->new arg for $sec";
549                 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or next;
550                 my $err = imap_fetch_all($self, $mic, $url);
551                 last if $self->{quit};
552                 warn $err, "\n" if $err;
553         }
554 }
555
556 sub watch_nntp_fetch_all ($$) {
557         my ($self, $urls) = @_;
558         for my $url (@$urls) {
559                 my $uri = uri_new($url);
560                 my $sec = uri_section($uri);
561                 my $nn_arg = $self->{nn_arg}->{$sec} or
562                         die "BUG: no Net::NNTP->new arg for $sec";
563                 my $nntp_opt = $self->{nntp_opt}->{$sec};
564                 my $nn = nn_new($nn_arg, $nntp_opt, $url);
565                 unless ($nn) {
566                         warn "E: $url: \$!=$!\n";
567                         next;
568                 }
569                 last if $self->{quit};
570                 if (my $postconn = $nntp_opt->{-postconn}) {
571                         for my $m_arg (@$postconn) {
572                                 my ($method, @args) = @$m_arg;
573                                 $nn->$method(@args) and next;
574                                 warn "E: <$url> $method failed\n";
575                                 $nn = undef;
576                                 last;
577                         }
578                 }
579                 last if $self->{quit};
580                 if ($nn) {
581                         my $err = nntp_fetch_all($self, $nn, $url);
582                         warn $err, "\n" if $err;
583                 }
584         }
585 }
586
587 sub poll_fetch_fork { # DS::add_timer callback
588         my ($self, $intvl, $urls) = @_;
589         return if $self->{quit};
590         pipe(my ($r, $w)) or die "pipe: $!";
591         my $oldset = watch_atfork_parent($self);
592         my $seed = rand(0xffffffff);
593         my $pid = fork;
594         if (defined($pid) && $pid == 0) {
595                 srand($seed);
596                 eval { Net::SSLeay::randomize() };
597                 close $r;
598                 watch_atfork_child($self);
599                 if ($urls->[0] =~ m!\Aimaps?://!i) {
600                         watch_imap_fetch_all($self, $urls);
601                 } else {
602                         watch_nntp_fetch_all($self, $urls);
603                 }
604                 close $w;
605                 _exit(0);
606         }
607         PublicInbox::DS::sig_setmask($oldset);
608         die "fork: $!"  unless defined $pid;
609         $self->{poll_pids}->{$pid} = [ $intvl, $urls ];
610         PublicInbox::EOFpipe->new($r, \&reap, [$pid, \&poll_fetch_reap, $self]);
611 }
612
613 sub poll_fetch_reap {
614         my ($self, $pid) = @_;
615         my $intvl_urls = delete $self->{poll_pids}->{$pid} or
616                 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
617         return if $self->{quit};
618         my ($intvl, $urls) = @$intvl_urls;
619         if ($?) {
620                 warn "W: PID=$pid died: \$?=$?\n", map { "$_\n" } @$urls;
621         }
622         warn("I: will check $_ in ${intvl}s\n") for @$urls;
623         add_timer($intvl, \&poll_fetch_fork, $self, $intvl, $urls);
624 }
625
626 sub watch_imap_init ($$) {
627         my ($self, $poll) = @_;
628         my $mics = imap_common_init($self); # read args from config
629         my $idle = []; # [ [ url1, intvl1 ], [url2, intvl2] ]
630         for my $url (keys %{$self->{imap}}) {
631                 my $uri = PublicInbox::URIimap->new($url);
632                 my $sec = uri_section($uri);
633                 my $mic = $mics->{$sec};
634                 my $intvl = $self->{imap_opt}->{$sec}->{pollInterval};
635                 if ($mic->has_capability('IDLE') && !$intvl) {
636                         $intvl = $self->{imap_opt}->{$sec}->{idleInterval};
637                         push @$idle, [ $url, $intvl // () ];
638                 } else {
639                         push @{$poll->{$intvl || 120}}, $url;
640                 }
641         }
642         if (scalar @$idle) {
643                 $self->{idle_todo} = $idle;
644                 PublicInbox::DS::requeue($self); # ->event_step to fork
645         }
646 }
647
648 # flesh out common NNTP-specific data structures
649 sub nntp_common_init ($) {
650         my ($self) = @_;
651         my $cfg = $self->{pi_cfg};
652         my $nn_args = {}; # scheme://authority => Net::NNTP->new arg
653         for my $url (@{$self->{nntp_order}}) {
654                 my $sec = uri_section(uri_new($url));
655
656                 # Debug and Timeout are passed to Net::NNTP->new
657                 my $v = cfg_bool($cfg, 'nntp.Debug', $url);
658                 $nn_args->{$sec}->{Debug} = $v if defined $v;
659                 my $to = cfg_intvl($cfg, 'nntp.Timeout', $url);
660                 $nn_args->{$sec}->{Timeout} = $to if $to;
661
662                 # Net::NNTP post-connect commands
663                 for my $k (qw(starttls compress)) {
664                         $v = cfg_bool($cfg, "nntp.$k", $url) // next;
665                         $self->{nntp_opt}->{$sec}->{$k} = $v;
666                 }
667
668                 # internal option
669                 for my $k (qw(pollInterval)) {
670                         $to = cfg_intvl($cfg, "nntp.$k", $url) // next;
671                         $self->{nntp_opt}->{$sec}->{$k} = $to;
672                 }
673         }
674         $nn_args;
675 }
676
677 sub nntp_fetch_all ($$$) {
678         my ($self, $nn, $url) = @_;
679         my $uri = uri_new($url);
680         my ($group, $num_a, $num_b) = $uri->group;
681         my $sec = uri_section($uri);
682         my ($nr, $beg, $end) = $nn->group($group);
683         unless (defined($nr)) {
684                 chomp(my $msg = $nn->message);
685                 return "E: GROUP $group <$sec> $msg";
686         }
687
688         # IMAPTracker is also used for tracking NNTP, UID == article number
689         # LIST.ACTIVE can get the equivalent of UIDVALIDITY, but that's
690         # expensive.  So we assume newsgroups don't change:
691         my $itrk = PublicInbox::IMAPTracker->new($url);
692         my (undef, $l_art) = $itrk->get_last;
693         $l_art //= $beg; # initial import
694
695         # allow users to specify articles to refetch
696         # cf. https://tools.ietf.org/id/draft-gilman-news-url-01.txt
697         # nntp://example.com/inbox.foo/$num_a-$num_b
698         $l_art = $num_a if defined($num_a) && $num_a < $l_art;
699         $end = $num_b if defined($num_b) && $num_b < $end;
700
701         return if $l_art >= $end; # nothing to do
702         $beg = $l_art + 1;
703
704         warn "I: $url fetching ARTICLE $beg..$end\n";
705         my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
706         my ($err, $art);
707         local $SIG{__WARN__} = sub {
708                 my $pfx = ($_[0] // '') =~ /^([A-Z]: )/g ? $1 : '';
709                 $warn_cb->("$pfx$url ", $art ? ("ARTICLE $art") : (), "\n", @_);
710         };
711         my $inboxes = $self->{nntp}->{$url};
712         my $last_art;
713         my $n = $self->{max_batch};
714         for ($beg..$end) {
715                 last if $self->{quit};
716                 $art = $_;
717                 if (--$n < 0) {
718                         _done_for_now($self);
719                         $itrk->update_last(0, $last_art);
720                         $n = $self->{max_batch};
721                 }
722                 my $raw = $nn->article($art);
723                 unless (defined($raw)) {
724                         my $msg = $nn->message;
725                         if ($nn->code == 421) { # pseudo response from Net::Cmd
726                                 $err = "E: $msg";
727                                 last;
728                         } else { # probably just a deleted message (spam)
729                                 warn "W: $msg";
730                                 next;
731                         }
732                 }
733                 s/\r\n/\n/ for @$raw;
734                 $raw = join('', @$raw);
735                 if (ref($inboxes)) {
736                         for my $ibx (@$inboxes) {
737                                 my $eml = PublicInbox::Eml->new($raw);
738                                 import_eml($self, $ibx, $eml);
739                         }
740                 } elsif ($inboxes eq 'watchspam') {
741                         my $eml = PublicInbox::Eml->new(\$raw);
742                         $self->{pi_cfg}->each_inbox(\&remove_eml_i,
743                                         $self, $eml, "$url ARTICLE $art");
744                 } else {
745                         die "BUG: destination unknown $inboxes";
746                 }
747                 $last_art = $art;
748         }
749         _done_for_now($self);
750         $itrk->update_last(0, $last_art);
751         $err;
752 }
753
754 sub watch_nntp_init ($$) {
755         my ($self, $poll) = @_;
756         eval { require Net::NNTP } or
757                 die "Net::NNTP is required for NNTP:\n$@\n";
758         eval { require PublicInbox::IMAPTracker } or
759                 die "DBD::SQLite is required for NNTP\n:$@\n";
760
761         my $nn_args = nntp_common_init($self); # read args from config
762
763         # make sure we can connect and cache the credentials in memory
764         $self->{nn_arg} = {}; # schema://authority => Net::NNTP->new args
765         for my $url (@{$self->{nntp_order}}) {
766                 nn_for($self, $url, $nn_args);
767         }
768         for my $url (@{$self->{nntp_order}}) {
769                 my $uri = uri_new($url);
770                 my $sec = uri_section($uri);
771                 my $intvl = $self->{nntp_opt}->{$sec}->{pollInterval};
772                 push @{$poll->{$intvl || 120}}, $url;
773         }
774 }
775
776 sub watch { # main entry point
777         my ($self, $sig, $oldset) = @_;
778         $self->{oldset} = $oldset;
779         $self->{sig} = $sig;
780         my $poll = {}; # intvl_seconds => [ url1, url2 ]
781         watch_imap_init($self, $poll) if $self->{imap};
782         watch_nntp_init($self, $poll) if $self->{nntp};
783         while (my ($intvl, $urls) = each %$poll) {
784                 # poll all URLs for a given interval sequentially
785                 add_timer(0, \&poll_fetch_fork, $self, $intvl, $urls);
786         }
787         watch_fs_init($self) if $self->{mdre};
788         PublicInbox::DS->SetPostLoopCallback(sub { !$self->quit_done });
789         PublicInbox::DS->EventLoop; # calls ->event_step
790         _done_for_now($self);
791 }
792
793 sub trigger_scan {
794         my ($self, $op) = @_;
795         push @{$self->{ops}}, $op;
796         PublicInbox::DS::requeue($self);
797 }
798
799 sub fs_scan_step {
800         my ($self) = @_;
801         return if $self->{quit};
802         my $op = shift @{$self->{ops}};
803         local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
804
805         # continue existing scan
806         my $opendirs = $self->{opendirs};
807         my @dirnames = keys %$opendirs;
808         foreach my $dir (@dirnames) {
809                 my $dh = delete $opendirs->{$dir};
810                 my $n = $self->{max_batch};
811                 while (my $fn = readdir($dh)) {
812                         _try_path($self, "$dir/$fn");
813                         last if --$n < 0;
814                 }
815                 $opendirs->{$dir} = $dh if $n < 0;
816         }
817         if ($op && $op eq 'full') {
818                 foreach my $dir (keys %{$self->{mdmap}}) {
819                         next if $opendirs->{$dir}; # already in progress
820                         my $ok = opendir(my $dh, $dir);
821                         unless ($ok) {
822                                 warn "failed to open $dir: $!\n";
823                                 next;
824                         }
825                         my $n = $self->{max_batch};
826                         while (my $fn = readdir($dh)) {
827                                 _try_path($self, "$dir/$fn");
828                                 last if --$n < 0;
829                         }
830                         $opendirs->{$dir} = $dh if $n < 0;
831                 }
832         }
833         _done_for_now($self);
834         # do we have more work to do?
835         PublicInbox::DS::requeue($self) if keys %$opendirs;
836 }
837
838 sub scan {
839         my ($self, $op) = @_;
840         push @{$self->{ops}}, $op;
841         fs_scan_step($self);
842 }
843
844 sub _importer_for {
845         my ($self, $ibx) = @_;
846         my $importers = $self->{importers};
847         my $im = $importers->{"$ibx"} ||= $ibx->importer(0);
848         if (scalar(keys(%$importers)) > 2) {
849                 delete $importers->{"$ibx"};
850                 _done_for_now($self);
851         }
852
853         $importers->{"$ibx"} = $im;
854 }
855
856 # XXX consider sharing with V2Writable, this only requires read-only access
857 sub content_exists ($$) {
858         my ($ibx, $eml) = @_;
859         my $over = $ibx->over or return;
860         my $mids = mids($eml);
861         my $chash = content_hash($eml);
862         my ($id, $prev);
863         for my $mid (@$mids) {
864                 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
865                         my $cmp = $ibx->smsg_eml($smsg) or return;
866                         return 1 if $chash eq content_hash($cmp);
867                 }
868         }
869         undef;
870 }
871
872 sub _spamcheck_cb {
873         my ($sc) = @_;
874         sub { # this gets called by (V2Writable||Import)->add
875                 my ($mime, $ibx) = @_;
876                 return if content_exists($ibx, $mime);
877                 my $tmp = '';
878                 if ($sc->spamcheck($mime, \$tmp)) {
879                         return PublicInbox::Eml->new(\$tmp);
880                 }
881                 warn $mime->header('Message-ID')." failed spam check\n";
882                 undef;
883         }
884 }
885
886 sub is_maildir {
887         $_[0] =~ s!\Amaildir:!! or return;
888         $_[0] =~ tr!/!/!s;
889         $_[0] =~ s!/\z!!;
890         $_[0];
891 }
892
893 sub is_watchspam {
894         my ($cur, $ws, $ibx) = @_;
895         if ($ws && !ref($ws) && $ws eq 'watchspam') {
896                 warn <<EOF;
897 E: $cur is a spam folder and cannot be used for `$ibx->{name}' input
898 EOF
899                 return 1;
900         }
901         undef;
902 }
903
904 1;