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