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