]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Watch.pm
lei <import|convert>: support NNTP sources
[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 $uri;
60                         if (is_maildir($dir)) {
61                                 # skip "new", no MUA has seen it, yet.
62                                 $mdmap{"$dir/cur"} = 'watchspam';
63                         } elsif ($uri = imap_uri($dir)) {
64                                 $imap{$$uri} = 'watchspam';
65                                 push @imap, $uri;
66                         } elsif ($uri = nntp_uri($dir)) {
67                                 $nntp{$$uri} = 'watchspam';
68                                 push @nntp, $uri;
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 $uri;
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 ($uri = imap_uri($watch)) {
96                                 my $cur_dst = $imap{$$uri} //= [];
97                                 return if is_watchspam($uri, $cur_dst, $ibx);
98                                 compile_watchheaders($ibx);
99                                 push(@imap, $uri) if 1 == push(@$cur_dst, $ibx);
100                         } elsif ($uri = nntp_uri($watch)) {
101                                 my $cur_dst = $nntp{$$uri} //= [];
102                                 return if is_watchspam($uri, $cur_dst, $ibx);
103                                 compile_watchheaders($ibx);
104                                 push(@nntp, $uri) if 1 == push(@$cur_dst, $ibx);
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, $uri, $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}->{$$uri};
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, "$uri UID:$uid");
307         } else {
308                 die "BUG: destination unknown $inboxes";
309         }
310 }
311
312 sub imap_fetch_all ($$$) {
313         my ($self, $mic, $uri) = @_;
314         my $sec = uri_section($uri);
315         my $mbx = $uri->mailbox;
316         $mic->Clear(1); # trim results history
317         $mic->examine($mbx) or return "E: EXAMINE $mbx ($sec) failed: $!";
318         my ($r_uidval, $r_uidnext);
319         for ($mic->Results) {
320                 /^\* OK \[UIDVALIDITY ([0-9]+)\].*/ and $r_uidval = $1;
321                 /^\* OK \[UIDNEXT ([0-9]+)\].*/ and $r_uidnext = $1;
322                 last if $r_uidval && $r_uidnext;
323         }
324         $r_uidval //= $mic->uidvalidity($mbx) //
325                 return "E: $uri cannot get UIDVALIDITY";
326         $r_uidnext //= $mic->uidnext($mbx) //
327                 return "E: $uri cannot get UIDNEXT";
328         my $itrk = PublicInbox::IMAPTracker->new($$uri);
329         my ($l_uidval, $l_uid) = $itrk->get_last;
330         $l_uidval //= $r_uidval; # first time
331         $l_uid //= 1;
332         if ($l_uidval != $r_uidval) {
333                 return "E: $uri UIDVALIDITY mismatch\n".
334                         "E: local=$l_uidval != remote=$r_uidval";
335         }
336         my $r_uid = $r_uidnext - 1;
337         if ($l_uid != 1 && $l_uid > $r_uid) {
338                 return "E: $uri local UID exceeds remote ($l_uid > $r_uid)\n".
339                         "E: $uri strangely, UIDVALIDLITY matches ($l_uidval)\n";
340         }
341         return if $l_uid >= $r_uid; # nothing to do
342
343         warn "I: $uri fetching UID $l_uid:$r_uid\n";
344         $mic->Uid(1); # the default, we hope
345         my $bs = $self->{imap_opt}->{$sec}->{batch_size} // 1;
346         my $req = $mic->imap4rev1 ? 'BODY.PEEK[]' : 'RFC822.PEEK';
347
348         # TODO: FLAGS may be useful for personal use
349         my $key = $req;
350         $key =~ s/\.PEEK//;
351         my ($uids, $batch);
352         my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
353         local $SIG{__WARN__} = sub {
354                 my $pfx = ($_[0] // '') =~ /^([A-Z]: )/g ? $1 : '';
355                 $batch //= '?';
356                 $warn_cb->("$pfx$uri UID:$batch\n", @_);
357         };
358         my $err;
359         do {
360                 # I wish "UID FETCH $START:*" could work, but:
361                 # 1) servers do not need to return results in any order
362                 # 2) Mail::IMAPClient doesn't offer a streaming API
363                 $uids = $mic->search("UID $l_uid:*") or
364                         return "E: $uri UID SEARCH $l_uid:* error: $!";
365                 return if scalar(@$uids) == 0;
366
367                 # RFC 3501 doesn't seem to indicate order of UID SEARCH
368                 # responses, so sort it ourselves.  Order matters so
369                 # IMAPTracker can store the newest UID.
370                 @$uids = sort { $a <=> $b } @$uids;
371
372                 # Did we actually get new messages?
373                 return if $uids->[0] < $l_uid;
374
375                 $l_uid = $uids->[-1] + 1; # for next search
376                 my $last_uid;
377                 my $n = $self->{max_batch};
378
379                 while (scalar @$uids) {
380                         if (--$n < 0) {
381                                 _done_for_now($self);
382                                 $itrk->update_last($r_uidval, $last_uid);
383                                 $n = $self->{max_batch};
384                         }
385                         my @batch = splice(@$uids, 0, $bs);
386                         $batch = join(',', @batch);
387                         local $0 = "UID:$batch $mbx $sec";
388                         my $r = $mic->fetch_hash($batch, $req, 'FLAGS');
389                         unless ($r) { # network error?
390                                 $err = "E: $uri UID FETCH $batch error: $!";
391                                 last;
392                         }
393                         for my $uid (@batch) {
394                                 # messages get deleted, so holes appear
395                                 my $per_uid = delete $r->{$uid} // next;
396                                 my $raw = delete($per_uid->{$key}) // next;
397                                 my $fl = $per_uid->{FLAGS} // '';
398                                 imap_import_msg($self, $uri, $uid, \$raw, $fl);
399                                 $last_uid = $uid;
400                                 last if $self->{quit};
401                         }
402                         last if $self->{quit};
403                 }
404                 _done_for_now($self);
405                 $itrk->update_last($r_uidval, $last_uid);
406         } until ($err || $self->{quit});
407         $err;
408 }
409
410 sub imap_idle_once ($$$$) {
411         my ($self, $mic, $intvl, $uri) = @_;
412         my $i = $intvl //= (29 * 60);
413         my $end = now() + $intvl;
414         warn "I: $uri idling for ${intvl}s\n";
415         local $0 = "IDLE $0";
416         unless ($mic->idle) {
417                 return if $self->{quit};
418                 return "E: IDLE failed on $uri: $!";
419         }
420         $self->{idle_mic} = $mic; # for ->quit
421         my @res;
422         until ($self->{quit} || !$mic->IsConnected ||
423                         grep(/^\* [0-9]+ EXISTS/, @res) || $i <= 0) {
424                 @res = $mic->idle_data($i);
425                 $i = $end - now();
426         }
427         delete $self->{idle_mic};
428         unless ($self->{quit}) {
429                 $mic->IsConnected or return "E: IDLE disconnected on $uri";
430                 $mic->done or return "E: IDLE DONE failed on $uri: $!";
431         }
432         undef;
433 }
434
435 # idles on a single URI
436 sub watch_imap_idle_1 ($$$) {
437         my ($self, $uri, $intvl) = @_;
438         my $sec = uri_section($uri);
439         my $mic_arg = $self->{mic_arg}->{$sec} or
440                         die "BUG: no Mail::IMAPClient->new arg for $sec";
441         my $mic;
442         local $0 = $uri->mailbox." $sec";
443         until ($self->{quit}) {
444                 $mic //= PublicInbox::IMAPClient->new(%$mic_arg);
445                 my $err;
446                 if ($mic && $mic->IsConnected) {
447                         $err = imap_fetch_all($self, $mic, $uri);
448                         $err //= imap_idle_once($self, $mic, $intvl, $uri);
449                 } else {
450                         $err = "E: not connected: $!";
451                 }
452                 if ($err && !$self->{quit}) {
453                         warn $err, "\n";
454                         $mic = undef;
455                         sleep 60 unless $self->{quit};
456                 }
457         }
458 }
459
460 sub watch_atfork_child ($) {
461         my ($self) = @_;
462         delete $self->{idle_pids};
463         delete $self->{poll_pids};
464         delete $self->{opendirs};
465         PublicInbox::DS->Reset;
466         %SIG = (%SIG, %{$self->{sig}}, CHLD => 'DEFAULT');
467         PublicInbox::DS::sig_setmask($self->{oldset});
468 }
469
470 sub watch_atfork_parent ($) {
471         my ($self) = @_;
472         _done_for_now($self);
473         PublicInbox::DS::block_signals();
474 }
475
476 sub imap_idle_requeue { # DS::add_timer callback
477         my ($self, $uri_intvl) = @_;
478         return if $self->{quit};
479         push @{$self->{idle_todo}}, $uri_intvl;
480         event_step($self);
481 }
482
483 sub imap_idle_reap { # PublicInbox::DS::dwaitpid callback
484         my ($self, $pid) = @_;
485         my $uri_intvl = delete $self->{idle_pids}->{$pid} or
486                 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
487
488         my ($uri, $intvl) = @$uri_intvl;
489         return if $self->{quit};
490         warn "W: PID=$pid on $uri died: \$?=$?\n" if $?;
491         add_timer(60, \&imap_idle_requeue, $self, $uri_intvl);
492 }
493
494 sub reap { # callback for EOFpipe
495         my ($pid, $cb, $self) = @{$_[0]};
496         my $ret = waitpid($pid, 0);
497         if ($ret == $pid) {
498                 $cb->($self, $pid); # poll_fetch_reap || imap_idle_reap
499         } else {
500                 warn "W: waitpid($pid) => ", $ret // "($!)", "\n";
501         }
502 }
503
504 sub imap_idle_fork ($$) {
505         my ($self, $uri_intvl) = @_;
506         my ($uri, $intvl) = @$uri_intvl;
507         pipe(my ($r, $w)) or die "pipe: $!";
508         my $seed = rand(0xffffffff);
509         my $pid = fork // die "fork: $!";
510         if ($pid == 0) {
511                 srand($seed);
512                 eval { Net::SSLeay::randomize() };
513                 close $r;
514                 watch_atfork_child($self);
515                 watch_imap_idle_1($self, $uri, $intvl);
516                 close $w;
517                 _exit(0);
518         }
519         $self->{idle_pids}->{$pid} = $uri_intvl;
520         PublicInbox::EOFpipe->new($r, \&reap, [$pid, \&imap_idle_reap, $self]);
521 }
522
523 sub event_step {
524         my ($self) = @_;
525         return if $self->{quit};
526         my $idle_todo = $self->{idle_todo};
527         if ($idle_todo && @$idle_todo) {
528                 my $oldset = watch_atfork_parent($self);
529                 eval {
530                         while (my $uri_intvl = shift(@$idle_todo)) {
531                                 imap_idle_fork($self, $uri_intvl);
532                         }
533                 };
534                 PublicInbox::DS::sig_setmask($oldset);
535                 die $@ if $@;
536         }
537         fs_scan_step($self) if $self->{mdre};
538 }
539
540 sub watch_imap_fetch_all ($$) {
541         my ($self, $uris) = @_;
542         for my $uri (@$uris) {
543                 my $sec = uri_section($uri);
544                 my $mic_arg = $self->{mic_arg}->{$sec} or
545                         die "BUG: no Mail::IMAPClient->new arg for $sec";
546                 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or next;
547                 my $err = imap_fetch_all($self, $mic, $uri);
548                 last if $self->{quit};
549                 warn $err, "\n" if $err;
550         }
551 }
552
553 sub watch_nntp_fetch_all ($$) {
554         my ($self, $uris) = @_;
555         for my $uri (@$uris) {
556                 my $sec = uri_section($uri);
557                 my $nn_arg = $self->{nn_arg}->{$sec} or
558                         die "BUG: no Net::NNTP->new arg for $sec";
559                 my $nntp_opt = $self->{nntp_opt}->{$sec};
560                 my $nn = nn_new($nn_arg, $nntp_opt, $uri);
561                 unless ($nn) {
562                         warn "E: $uri: \$!=$!\n";
563                         next;
564                 }
565                 last if $self->{quit};
566                 if (my $postconn = $nntp_opt->{-postconn}) {
567                         for my $m_arg (@$postconn) {
568                                 my ($method, @args) = @$m_arg;
569                                 $nn->$method(@args) and next;
570                                 warn "E: <$uri> $method failed\n";
571                                 $nn = undef;
572                                 last;
573                         }
574                 }
575                 last if $self->{quit};
576                 if ($nn) {
577                         my $err = nntp_fetch_all($self, $nn, $uri);
578                         warn $err, "\n" if $err;
579                 }
580         }
581 }
582
583 sub poll_fetch_fork { # DS::add_timer callback
584         my ($self, $intvl, $uris) = @_;
585         return if $self->{quit};
586         pipe(my ($r, $w)) or die "pipe: $!";
587         my $oldset = watch_atfork_parent($self);
588         my $seed = rand(0xffffffff);
589         my $pid = fork;
590         if (defined($pid) && $pid == 0) {
591                 srand($seed);
592                 eval { Net::SSLeay::randomize() };
593                 close $r;
594                 watch_atfork_child($self);
595                 if ($uris->[0]->scheme =~ m!\Aimaps?!i) {
596                         watch_imap_fetch_all($self, $uris);
597                 } else {
598                         watch_nntp_fetch_all($self, $uris);
599                 }
600                 close $w;
601                 _exit(0);
602         }
603         PublicInbox::DS::sig_setmask($oldset);
604         die "fork: $!"  unless defined $pid;
605         $self->{poll_pids}->{$pid} = [ $intvl, $uris ];
606         PublicInbox::EOFpipe->new($r, \&reap, [$pid, \&poll_fetch_reap, $self]);
607 }
608
609 sub poll_fetch_reap {
610         my ($self, $pid) = @_;
611         my $intvl_uris = delete $self->{poll_pids}->{$pid} or
612                 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
613         return if $self->{quit};
614         my ($intvl, $uris) = @$intvl_uris;
615         if ($?) {
616                 warn "W: PID=$pid died: \$?=$?\n", map { "$_\n" } @$uris;
617         }
618         warn("I: will check $_ in ${intvl}s\n") for @$uris;
619         add_timer($intvl, \&poll_fetch_fork, $self, $intvl, $uris);
620 }
621
622 sub watch_imap_init ($$) {
623         my ($self, $poll) = @_;
624         my $mics = imap_common_init($self); # read args from config
625         my $idle = []; # [ [ uri1, intvl1 ], [uri2, intvl2] ]
626         for my $uri (@{$self->{imap_order}}) {
627                 my $sec = uri_section($uri);
628                 my $mic = $mics->{$sec};
629                 my $intvl = $self->{imap_opt}->{$sec}->{pollInterval};
630                 if ($mic->has_capability('IDLE') && !$intvl) {
631                         $intvl = $self->{imap_opt}->{$sec}->{idleInterval};
632                         push @$idle, [ $uri, $intvl // () ];
633                 } else {
634                         push @{$poll->{$intvl || 120}}, $uri;
635                 }
636         }
637         if (scalar @$idle) {
638                 $self->{idle_todo} = $idle;
639                 PublicInbox::DS::requeue($self); # ->event_step to fork
640         }
641 }
642
643 sub nntp_fetch_all ($$$) {
644         my ($self, $nn, $uri) = @_;
645         my ($group, $num_a, $num_b) = $uri->group;
646         my $sec = uri_section($uri);
647         my ($nr, $beg, $end) = $nn->group($group);
648         unless (defined($nr)) {
649                 chomp(my $msg = $nn->message);
650                 return "E: GROUP $group <$sec> $msg";
651         }
652
653         # IMAPTracker is also used for tracking NNTP, UID == article number
654         # LIST.ACTIVE can get the equivalent of UIDVALIDITY, but that's
655         # expensive.  So we assume newsgroups don't change:
656         my $itrk = PublicInbox::IMAPTracker->new($$uri);
657         my (undef, $l_art) = $itrk->get_last;
658         $l_art //= $beg; # initial import
659
660         # allow users to specify articles to refetch
661         # cf. https://tools.ietf.org/id/draft-gilman-news-url-01.txt
662         # nntp://example.com/inbox.foo/$num_a-$num_b
663         $l_art = $num_a if defined($num_a) && $num_a < $l_art;
664         $end = $num_b if defined($num_b) && $num_b < $end;
665
666         return if $l_art >= $end; # nothing to do
667         $beg = $l_art + 1;
668
669         warn "I: $uri fetching ARTICLE $beg..$end\n";
670         my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
671         my ($err, $art);
672         local $SIG{__WARN__} = sub {
673                 my $pfx = ($_[0] // '') =~ /^([A-Z]: )/g ? $1 : '';
674                 $warn_cb->("$pfx$uri ", $art ? ("ARTICLE $art") : (), "\n", @_);
675         };
676         my $inboxes = $self->{nntp}->{$$uri};
677         my $last_art;
678         my $n = $self->{max_batch};
679         for ($beg..$end) {
680                 last if $self->{quit};
681                 $art = $_;
682                 if (--$n < 0) {
683                         _done_for_now($self);
684                         $itrk->update_last(0, $last_art);
685                         $n = $self->{max_batch};
686                 }
687                 my $raw = $nn->article($art);
688                 unless (defined($raw)) {
689                         my $msg = $nn->message;
690                         if ($nn->code == 421) { # pseudo response from Net::Cmd
691                                 $err = "E: $msg";
692                                 last;
693                         } else { # probably just a deleted message (spam)
694                                 warn "W: $msg";
695                                 next;
696                         }
697                 }
698                 s/\r\n/\n/ for @$raw;
699                 $raw = join('', @$raw);
700                 if (ref($inboxes)) {
701                         for my $ibx (@$inboxes) {
702                                 my $eml = PublicInbox::Eml->new($raw);
703                                 import_eml($self, $ibx, $eml);
704                         }
705                 } elsif ($inboxes eq 'watchspam') {
706                         my $eml = PublicInbox::Eml->new(\$raw);
707                         $self->{pi_cfg}->each_inbox(\&remove_eml_i,
708                                         $self, $eml, "$uri ARTICLE $art");
709                 } else {
710                         die "BUG: destination unknown $inboxes";
711                 }
712                 $last_art = $art;
713         }
714         _done_for_now($self);
715         $itrk->update_last(0, $last_art);
716         $err;
717 }
718
719 sub watch_nntp_init ($$) {
720         my ($self, $poll) = @_;
721         nntp_common_init($self); # read args from config
722         for my $uri (@{$self->{nntp_order}}) {
723                 my $sec = uri_section($uri);
724                 my $intvl = $self->{nntp_opt}->{$sec}->{pollInterval};
725                 push @{$poll->{$intvl || 120}}, $uri;
726         }
727 }
728
729 sub watch { # main entry point
730         my ($self, $sig, $oldset) = @_;
731         $self->{oldset} = $oldset;
732         $self->{sig} = $sig;
733         my $poll = {}; # intvl_seconds => [ uri1, uri2 ]
734         watch_imap_init($self, $poll) if $self->{imap};
735         watch_nntp_init($self, $poll) if $self->{nntp};
736         while (my ($intvl, $uris) = each %$poll) {
737                 # poll all URIs for a given interval sequentially
738                 add_timer(0, \&poll_fetch_fork, $self, $intvl, $uris);
739         }
740         watch_fs_init($self) if $self->{mdre};
741         PublicInbox::DS->SetPostLoopCallback(sub { !$self->quit_done });
742         PublicInbox::DS->EventLoop; # calls ->event_step
743         _done_for_now($self);
744 }
745
746 sub trigger_scan {
747         my ($self, $op) = @_;
748         push @{$self->{ops}}, $op;
749         PublicInbox::DS::requeue($self);
750 }
751
752 sub fs_scan_step {
753         my ($self) = @_;
754         return if $self->{quit};
755         my $op = shift @{$self->{ops}};
756         local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
757
758         # continue existing scan
759         my $opendirs = $self->{opendirs};
760         my @dirnames = keys %$opendirs;
761         foreach my $dir (@dirnames) {
762                 my $dh = delete $opendirs->{$dir};
763                 my $n = $self->{max_batch};
764                 while (my $fn = readdir($dh)) {
765                         _try_path($self, "$dir/$fn");
766                         last if --$n < 0;
767                 }
768                 $opendirs->{$dir} = $dh if $n < 0;
769         }
770         if ($op && $op eq 'full') {
771                 foreach my $dir (keys %{$self->{mdmap}}) {
772                         next if $opendirs->{$dir}; # already in progress
773                         my $ok = opendir(my $dh, $dir);
774                         unless ($ok) {
775                                 warn "failed to open $dir: $!\n";
776                                 next;
777                         }
778                         my $n = $self->{max_batch};
779                         while (my $fn = readdir($dh)) {
780                                 _try_path($self, "$dir/$fn");
781                                 last if --$n < 0;
782                         }
783                         $opendirs->{$dir} = $dh if $n < 0;
784                 }
785         }
786         _done_for_now($self);
787         # do we have more work to do?
788         PublicInbox::DS::requeue($self) if keys %$opendirs;
789 }
790
791 sub scan {
792         my ($self, $op) = @_;
793         push @{$self->{ops}}, $op;
794         fs_scan_step($self);
795 }
796
797 sub _importer_for {
798         my ($self, $ibx) = @_;
799         my $importers = $self->{importers};
800         my $im = $importers->{"$ibx"} ||= $ibx->importer(0);
801         if (scalar(keys(%$importers)) > 2) {
802                 delete $importers->{"$ibx"};
803                 _done_for_now($self);
804         }
805
806         $importers->{"$ibx"} = $im;
807 }
808
809 # XXX consider sharing with V2Writable, this only requires read-only access
810 sub content_exists ($$) {
811         my ($ibx, $eml) = @_;
812         my $over = $ibx->over or return;
813         my $mids = mids($eml);
814         my $chash = content_hash($eml);
815         my ($id, $prev);
816         for my $mid (@$mids) {
817                 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
818                         my $cmp = $ibx->smsg_eml($smsg) or return;
819                         return 1 if $chash eq content_hash($cmp);
820                 }
821         }
822         undef;
823 }
824
825 sub _spamcheck_cb {
826         my ($sc) = @_;
827         sub { # this gets called by (V2Writable||Import)->add
828                 my ($mime, $ibx) = @_;
829                 return if content_exists($ibx, $mime);
830                 my $tmp = '';
831                 if ($sc->spamcheck($mime, \$tmp)) {
832                         return PublicInbox::Eml->new(\$tmp);
833                 }
834                 warn $mime->header('Message-ID')." failed spam check\n";
835                 undef;
836         }
837 }
838
839 sub is_maildir {
840         $_[0] =~ s!\Amaildir:!! or return;
841         $_[0] =~ tr!/!/!s;
842         $_[0] =~ s!/\z!!;
843         $_[0];
844 }
845
846 sub is_watchspam {
847         my ($cur, $ws, $ibx) = @_;
848         if ($ws && !ref($ws) && $ws eq 'watchspam') {
849                 warn <<EOF;
850 E: $cur is a spam folder and cannot be used for `$ibx->{name}' input
851 EOF
852                 return 1;
853         }
854         undef;
855 }
856
857 1;