]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Watch.pm
dd24593599a0b72f785d8f6caa05ea238699d3bd
[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 net_cb { # NetReader::(nntp|imap)_each callback
313         my ($uri, $art, $kw, $eml, $self, $inboxes) = @_;
314         local $self->{cur_uid} = $art; # IMAP UID or NNTP article
315         if (ref($inboxes)) {
316                 my @ibx = @$inboxes;
317                 my $last = pop @ibx;
318                 for my $ibx (@ibx) {
319                         my $tmp = PublicInbox::Eml->new(\($eml->as_string));
320                         import_eml($self, $ibx, $tmp);
321                 }
322                 import_eml($self, $last, $eml);
323         } elsif ($inboxes eq 'watchspam') {
324                 $self->{pi_cfg}->each_inbox(\&remove_eml_i,
325                                 $self, $eml, "$uri #$art");
326         } else {
327                 die "BUG: destination unknown $inboxes";
328         }
329 }
330
331 sub imap_fetch_all ($$) {
332         my ($self, $uri) = @_;
333         my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
334         $self->{incremental} = 1;
335         $self->{on_commit} = [ \&_done_for_now, $self ];
336         local $self->{cur_uid};
337         local $SIG{__WARN__} = sub {
338                 my $pfx = ($_[0] // '') =~ /^([A-Z]: |# )/g ? $1 : '';
339                 my $uid = $self->{cur_uid};
340                 $warn_cb->("$pfx$uri", $uid ? ("UID:$uid") : (), "\n", @_);
341         };
342         PublicInbox::NetReader::imap_each($self, $uri, \&net_cb, $self,
343                                         $self->{imap}->{$$uri});
344 }
345
346 sub imap_idle_once ($$$$) {
347         my ($self, $mic, $intvl, $uri) = @_;
348         my $i = $intvl //= (29 * 60);
349         my $end = now() + $intvl;
350         warn "I: $uri idling for ${intvl}s\n";
351         local $0 = "IDLE $0";
352         unless ($mic->idle) {
353                 return if $self->{quit};
354                 return "E: IDLE failed on $uri: $!";
355         }
356         $self->{idle_mic} = $mic; # for ->quit
357         my @res;
358         until ($self->{quit} || !$mic->IsConnected ||
359                         grep(/^\* [0-9]+ EXISTS/, @res) || $i <= 0) {
360                 @res = $mic->idle_data($i);
361                 $i = $end - now();
362         }
363         delete $self->{idle_mic};
364         unless ($self->{quit}) {
365                 $mic->IsConnected or return "E: IDLE disconnected on $uri";
366                 $mic->done or return "E: IDLE DONE failed on $uri: $!";
367         }
368         undef;
369 }
370
371 # idles on a single URI
372 sub watch_imap_idle_1 ($$$) {
373         my ($self, $uri, $intvl) = @_;
374         my $sec = uri_section($uri);
375         my $mic_arg = $self->{mic_arg}->{$sec} or
376                         die "BUG: no Mail::IMAPClient->new arg for $sec";
377         my $mic;
378         local $0 = $uri->mailbox." $sec";
379         until ($self->{quit}) {
380                 $mic //= PublicInbox::IMAPClient->new(%$mic_arg);
381                 my $err;
382                 if ($mic && $mic->IsConnected) {
383                         local $self->{mics_cached}->{$sec} = $mic;
384                         my $m = imap_fetch_all($self, $uri);
385                         $m == $mic or die "BUG: wrong mic";
386                         $mic->IsConnected and
387                                 $err = imap_idle_once($self, $mic, $intvl, $uri)
388                 } else {
389                         $err = "E: not connected: $!";
390                 }
391                 if ($err && !$self->{quit}) {
392                         warn $err, "\n";
393                         $mic = undef;
394                         sleep 60 unless $self->{quit};
395                 }
396         }
397 }
398
399 sub watch_atfork_child ($) {
400         my ($self) = @_;
401         delete $self->{idle_pids};
402         delete $self->{poll_pids};
403         delete $self->{opendirs};
404         PublicInbox::DS->Reset;
405         %SIG = (%SIG, %{$self->{sig}}, CHLD => 'DEFAULT');
406         PublicInbox::DS::sig_setmask($self->{oldset});
407 }
408
409 sub watch_atfork_parent ($) {
410         my ($self) = @_;
411         _done_for_now($self);
412         PublicInbox::DS::block_signals();
413 }
414
415 sub imap_idle_requeue { # DS::add_timer callback
416         my ($self, $uri_intvl) = @_;
417         return if $self->{quit};
418         push @{$self->{idle_todo}}, $uri_intvl;
419         event_step($self);
420 }
421
422 sub imap_idle_reap { # PublicInbox::DS::dwaitpid callback
423         my ($self, $pid) = @_;
424         my $uri_intvl = delete $self->{idle_pids}->{$pid} or
425                 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
426
427         my ($uri, $intvl) = @$uri_intvl;
428         return if $self->{quit};
429         warn "W: PID=$pid on $uri died: \$?=$?\n" if $?;
430         add_timer(60, \&imap_idle_requeue, $self, $uri_intvl);
431 }
432
433 sub reap { # callback for EOFpipe
434         my ($pid, $cb, $self) = @{$_[0]};
435         my $ret = waitpid($pid, 0);
436         if ($ret == $pid) {
437                 $cb->($self, $pid); # poll_fetch_reap || imap_idle_reap
438         } else {
439                 warn "W: waitpid($pid) => ", $ret // "($!)", "\n";
440         }
441 }
442
443 sub imap_idle_fork ($$) {
444         my ($self, $uri_intvl) = @_;
445         my ($uri, $intvl) = @$uri_intvl;
446         pipe(my ($r, $w)) or die "pipe: $!";
447         my $seed = rand(0xffffffff);
448         my $pid = fork // die "fork: $!";
449         if ($pid == 0) {
450                 srand($seed);
451                 eval { Net::SSLeay::randomize() };
452                 close $r;
453                 watch_atfork_child($self);
454                 watch_imap_idle_1($self, $uri, $intvl);
455                 close $w;
456                 _exit(0);
457         }
458         $self->{idle_pids}->{$pid} = $uri_intvl;
459         PublicInbox::EOFpipe->new($r, \&reap, [$pid, \&imap_idle_reap, $self]);
460 }
461
462 sub event_step {
463         my ($self) = @_;
464         return if $self->{quit};
465         my $idle_todo = $self->{idle_todo};
466         if ($idle_todo && @$idle_todo) {
467                 my $oldset = watch_atfork_parent($self);
468                 eval {
469                         while (my $uri_intvl = shift(@$idle_todo)) {
470                                 imap_idle_fork($self, $uri_intvl);
471                         }
472                 };
473                 PublicInbox::DS::sig_setmask($oldset);
474                 die $@ if $@;
475         }
476         fs_scan_step($self) if $self->{mdre};
477 }
478
479 sub watch_imap_fetch_all ($$) {
480         my ($self, $uris) = @_;
481         for my $uri (@$uris) {
482                 imap_fetch_all($self, $uri);
483                 last if $self->{quit};
484         }
485 }
486
487 sub watch_nntp_fetch_all ($$) {
488         my ($self, $uris) = @_;
489         $self->{incremental} = 1;
490         $self->{on_commit} = [ \&_done_for_now, $self ];
491         my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
492         local $self->{cur_uid};
493         my $uri = '';
494         local $SIG{__WARN__} = sub {
495                 my $pfx = ($_[0] // '') =~ /^([A-Z]: |# )/g ? $1 : '';
496                 my $art = $self->{cur_uid};
497                 $warn_cb->("$pfx$uri", $art ? ("ARTICLE $art") : (), "\n", @_);
498         };
499         for $uri (@$uris) {
500                 PublicInbox::NetReader::nntp_each($self, $uri, \&net_cb, $self,
501                                         $self->{nntp}->{$$uri});
502                 last if $self->{quit};
503         }
504 }
505
506 sub poll_fetch_fork { # DS::add_timer callback
507         my ($self, $intvl, $uris) = @_;
508         return if $self->{quit};
509         pipe(my ($r, $w)) or die "pipe: $!";
510         my $oldset = watch_atfork_parent($self);
511         my $seed = rand(0xffffffff);
512         my $pid = fork;
513         if (defined($pid) && $pid == 0) {
514                 srand($seed);
515                 eval { Net::SSLeay::randomize() };
516                 close $r;
517                 watch_atfork_child($self);
518                 if ($uris->[0]->scheme =~ m!\Aimaps?!i) {
519                         watch_imap_fetch_all($self, $uris);
520                 } else {
521                         watch_nntp_fetch_all($self, $uris);
522                 }
523                 close $w;
524                 _exit(0);
525         }
526         PublicInbox::DS::sig_setmask($oldset);
527         die "fork: $!"  unless defined $pid;
528         $self->{poll_pids}->{$pid} = [ $intvl, $uris ];
529         PublicInbox::EOFpipe->new($r, \&reap, [$pid, \&poll_fetch_reap, $self]);
530 }
531
532 sub poll_fetch_reap {
533         my ($self, $pid) = @_;
534         my $intvl_uris = delete $self->{poll_pids}->{$pid} or
535                 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
536         return if $self->{quit};
537         my ($intvl, $uris) = @$intvl_uris;
538         if ($?) {
539                 warn "W: PID=$pid died: \$?=$?\n", map { "$_\n" } @$uris;
540         }
541         warn("I: will check $_ in ${intvl}s\n") for @$uris;
542         add_timer($intvl, \&poll_fetch_fork, $self, $intvl, $uris);
543 }
544
545 sub watch_imap_init ($$) {
546         my ($self, $poll) = @_;
547         my $mics = PublicInbox::NetReader::imap_common_init($self);
548         my $idle = []; # [ [ uri1, intvl1 ], [uri2, intvl2] ]
549         for my $uri (@{$self->{imap_order}}) {
550                 my $sec = uri_section($uri);
551                 my $mic = $mics->{$sec};
552                 my $intvl = $self->{imap_opt}->{$sec}->{pollInterval};
553                 if ($mic->has_capability('IDLE') && !$intvl) {
554                         $intvl = $self->{imap_opt}->{$sec}->{idleInterval};
555                         push @$idle, [ $uri, $intvl // () ];
556                 } else {
557                         push @{$poll->{$intvl || 120}}, $uri;
558                 }
559         }
560         if (scalar @$idle) {
561                 $self->{idle_todo} = $idle;
562                 PublicInbox::DS::requeue($self); # ->event_step to fork
563         }
564 }
565
566 sub watch_nntp_init ($$) {
567         my ($self, $poll) = @_;
568         PublicInbox::NetReader::nntp_common_init($self);
569         for my $uri (@{$self->{nntp_order}}) {
570                 my $sec = uri_section($uri);
571                 my $intvl = $self->{nntp_opt}->{$sec}->{pollInterval};
572                 push @{$poll->{$intvl || 120}}, $uri;
573         }
574 }
575
576 sub watch { # main entry point
577         my ($self, $sig, $oldset) = @_;
578         $self->{oldset} = $oldset;
579         $self->{sig} = $sig;
580         my $poll = {}; # intvl_seconds => [ uri1, uri2 ]
581         watch_imap_init($self, $poll) if $self->{imap};
582         watch_nntp_init($self, $poll) if $self->{nntp};
583         while (my ($intvl, $uris) = each %$poll) {
584                 # poll all URIs for a given interval sequentially
585                 add_timer(0, \&poll_fetch_fork, $self, $intvl, $uris);
586         }
587         watch_fs_init($self) if $self->{mdre};
588         PublicInbox::DS->SetPostLoopCallback(sub { !$self->quit_done });
589         PublicInbox::DS->EventLoop; # calls ->event_step
590         _done_for_now($self);
591 }
592
593 sub trigger_scan {
594         my ($self, $op) = @_;
595         push @{$self->{ops}}, $op;
596         PublicInbox::DS::requeue($self);
597 }
598
599 sub fs_scan_step {
600         my ($self) = @_;
601         return if $self->{quit};
602         my $op = shift @{$self->{ops}};
603         local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
604
605         # continue existing scan
606         my $opendirs = $self->{opendirs};
607         my @dirnames = keys %$opendirs;
608         foreach my $dir (@dirnames) {
609                 my $dh = delete $opendirs->{$dir};
610                 my $n = $self->{max_batch};
611                 while (my $fn = readdir($dh)) {
612                         _try_path($self, "$dir/$fn");
613                         last if --$n < 0;
614                 }
615                 $opendirs->{$dir} = $dh if $n < 0;
616         }
617         if ($op && $op eq 'full') {
618                 foreach my $dir (keys %{$self->{mdmap}}) {
619                         next if $opendirs->{$dir}; # already in progress
620                         my $ok = opendir(my $dh, $dir);
621                         unless ($ok) {
622                                 warn "failed to open $dir: $!\n";
623                                 next;
624                         }
625                         my $n = $self->{max_batch};
626                         while (my $fn = readdir($dh)) {
627                                 _try_path($self, "$dir/$fn");
628                                 last if --$n < 0;
629                         }
630                         $opendirs->{$dir} = $dh if $n < 0;
631                 }
632         }
633         _done_for_now($self);
634         # do we have more work to do?
635         PublicInbox::DS::requeue($self) if keys %$opendirs;
636 }
637
638 sub scan {
639         my ($self, $op) = @_;
640         push @{$self->{ops}}, $op;
641         fs_scan_step($self);
642 }
643
644 sub _importer_for {
645         my ($self, $ibx) = @_;
646         my $importers = $self->{importers};
647         my $im = $importers->{"$ibx"} ||= $ibx->importer(0);
648         if (scalar(keys(%$importers)) > 2) {
649                 delete $importers->{"$ibx"};
650                 _done_for_now($self);
651         }
652
653         $importers->{"$ibx"} = $im;
654 }
655
656 # XXX consider sharing with V2Writable, this only requires read-only access
657 sub content_exists ($$) {
658         my ($ibx, $eml) = @_;
659         my $over = $ibx->over or return;
660         my $mids = mids($eml);
661         my $chash = content_hash($eml);
662         my ($id, $prev);
663         for my $mid (@$mids) {
664                 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
665                         my $cmp = $ibx->smsg_eml($smsg) or return;
666                         return 1 if $chash eq content_hash($cmp);
667                 }
668         }
669         undef;
670 }
671
672 sub _spamcheck_cb {
673         my ($sc) = @_;
674         sub { # this gets called by (V2Writable||Import)->add
675                 my ($mime, $ibx) = @_;
676                 return if content_exists($ibx, $mime);
677                 my $tmp = '';
678                 if ($sc->spamcheck($mime, \$tmp)) {
679                         return PublicInbox::Eml->new(\$tmp);
680                 }
681                 warn $mime->header('Message-ID')." failed spam check\n";
682                 undef;
683         }
684 }
685
686 sub is_maildir {
687         $_[0] =~ s!\Amaildir:!! or return;
688         $_[0] =~ tr!/!/!s;
689         $_[0] =~ s!/\z!!;
690         $_[0];
691 }
692
693 sub is_watchspam {
694         my ($cur, $ws, $ibx) = @_;
695         if ($ws && !ref($ws) && $ws eq 'watchspam') {
696                 warn <<EOF;
697 E: $cur is a spam folder and cannot be used for `$ibx->{name}' input
698 EOF
699                 return 1;
700         }
701         undef;
702 }
703
704 1;