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