]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Watch.pm
c6bebce32edb3ea3a919065d4cf0a8f72dbc2341
[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 #       https://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::DS qw(now add_timer);
16 use PublicInbox::MID qw(mids);
17 use PublicInbox::ContentHash qw(content_hash);
18 use PublicInbox::EOFpipe;
19 use POSIX qw(_exit WNOHANG);
20
21 sub compile_watchheaders ($) {
22         my ($ibx) = @_;
23         my $watch_hdrs = [];
24         if (my $whs = $ibx->{watchheader}) {
25                 for (@$whs) {
26                         my ($k, $v) = split(/:/, $_, 2);
27                         # XXX should this be case-insensitive?
28                         # Or, mutt-style, case-sensitive iff
29                         # a capital letter exists?
30                         push @$watch_hdrs, [ $k, qr/\Q$v\E/ ];
31                 }
32         }
33         if (my $list_ids = $ibx->{listid}) {
34                 for (@$list_ids) {
35                         # RFC2919 section 6 stipulates
36                         # "case insensitive equality"
37                         my $re = qr/<[ \t]*\Q$_\E[ \t]*>/i;
38                         push @$watch_hdrs, ['List-Id', $re ];
39                 }
40         }
41         $ibx->{-watchheaders} = $watch_hdrs if scalar @$watch_hdrs;
42 }
43
44 sub new {
45         my ($class, $cfg) = @_;
46         my (%mdmap, $spamc);
47         my (%imap, %nntp); # url => [inbox objects] or 'watchspam'
48         my (@imap, @nntp);
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                 my $dirs = $cfg->get_all($k) // next;
56                 for my $dir (@$dirs) {
57                         my $uri;
58                         if (is_maildir($dir)) {
59                                 # skip "new", no MUA has seen it, yet.
60                                 $mdmap{"$dir/cur"} = 'watchspam';
61                         } elsif ($uri = imap_uri($dir)) {
62                                 $imap{$$uri} = 'watchspam';
63                                 push @imap, $uri;
64                         } elsif ($uri = nntp_uri($dir)) {
65                                 $nntp{$$uri} = 'watchspam';
66                                 push @nntp, $uri;
67                         } else {
68                                 warn "unsupported $k=$dir\n";
69                         }
70                 }
71         }
72
73         my $k = 'publicinboxwatch.spamcheck';
74         my $default = undef;
75         my $spamcheck = PublicInbox::Spamcheck::get($cfg, $k, $default);
76         $spamcheck = _spamcheck_cb($spamcheck) if $spamcheck;
77
78         $cfg->each_inbox(sub {
79                 # need to make all inboxes writable for spam removal:
80                 my $ibx = $_[0] = PublicInbox::InboxWritable->new($_[0]);
81
82                 my $watches = $ibx->{watch} or return;
83                 $watches = PublicInbox::Config::_array($watches);
84                 for my $watch (@$watches) {
85                         my $uri;
86                         if (is_maildir($watch)) {
87                                 compile_watchheaders($ibx);
88                                 my ($new, $cur) = ("$watch/new", "$watch/cur");
89                                 my $cur_dst = $mdmap{$cur} //= [];
90                                 return if is_watchspam($cur, $cur_dst, $ibx);
91                                 push @{$mdmap{$new} //= []}, $ibx;
92                                 push @$cur_dst, $ibx;
93                         } elsif ($uri = imap_uri($watch)) {
94                                 my $cur_dst = $imap{$$uri} //= [];
95                                 return if is_watchspam($uri, $cur_dst, $ibx);
96                                 compile_watchheaders($ibx);
97                                 push(@imap, $uri) if 1 == push(@$cur_dst, $ibx);
98                         } elsif ($uri = nntp_uri($watch)) {
99                                 my $cur_dst = $nntp{$$uri} //= [];
100                                 return if is_watchspam($uri, $cur_dst, $ibx);
101                                 compile_watchheaders($ibx);
102                                 push(@nntp, $uri) if 1 == push(@$cur_dst, $ibx);
103                         } else {
104                                 warn "watch unsupported: $k=$watch\n";
105                         }
106                 }
107         });
108
109         my $mdre;
110         if (scalar keys %mdmap) {
111                 $mdre = join('|', map { quotemeta($_) } keys %mdmap);
112                 $mdre = qr!\A($mdre)/!;
113         }
114         return unless $mdre || scalar(keys %imap) || scalar(keys %nntp);
115
116         bless {
117                 max_batch => 10, # avoid hogging locks for too long
118                 spamcheck => $spamcheck,
119                 mdmap => \%mdmap,
120                 mdre => $mdre,
121                 pi_cfg => $cfg,
122                 imap => scalar keys %imap ? \%imap : undef,
123                 nntp => scalar keys %nntp? \%nntp : undef,
124                 imap_order => scalar(@imap) ? \@imap : undef,
125                 nntp_order => scalar(@nntp) ? \@nntp: undef,
126                 importers => {},
127                 opendirs => {}, # dirname => dirhandle (in progress scans)
128                 ops => [], # 'quit', 'full'
129         }, $class;
130 }
131
132 sub _done_for_now {
133         my ($self) = @_;
134         local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
135         for my $im (values %{$self->{importers}}) {
136                 next if !$im; # $im may be undef during cleanup
137                 eval { $im->done };
138                 warn "$im->{ibx}->{name} ->done: $@\n" if $@;
139         }
140 }
141
142 sub remove_eml_i { # each_inbox callback
143         my ($ibx, $self, $eml, $loc) = @_;
144
145         eval {
146                 # try to avoid taking a lock or unnecessary spawning
147                 my $im = $self->{importers}->{"$ibx"};
148                 my $scrubbed;
149                 if ((!$im || !$im->active) && $ibx->over) {
150                         if (content_exists($ibx, $eml)) {
151                                 # continue
152                         } elsif (my $scrub = $ibx->filter($im)) {
153                                 $scrubbed = $scrub->scrub($eml, 1);
154                                 if ($scrubbed && $scrubbed != REJECT &&
155                                           !content_exists($ibx, $scrubbed)) {
156                                         return;
157                                 }
158                         } else {
159                                 return;
160                         }
161                 }
162
163                 $im //= _importer_for($self, $ibx); # may spawn fast-import
164                 $im->remove($eml, 'spam');
165                 $scrubbed //= do {
166                         my $scrub = $ibx->filter($im);
167                         $scrub ? $scrub->scrub($eml, 1) : undef;
168                 };
169                 if ($scrubbed && $scrubbed != REJECT) {
170                         $im->remove($scrubbed, 'spam');
171                 }
172         };
173         if ($@) {
174                 warn "error removing spam at: $loc from $ibx->{name}: $@\n";
175                 _done_for_now($self);
176         }
177 }
178
179 sub _remove_spam {
180         my ($self, $path) = @_;
181         # path must be marked as (S)een
182         $path =~ /:2,[A-R]*S[T-Za-z]*\z/ or return;
183         my $eml = eml_from_path($path) or return;
184         local $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
185         $self->{pi_cfg}->each_inbox(\&remove_eml_i, $self, $eml, $path);
186 }
187
188 sub import_eml ($$$) {
189         my ($self, $ibx, $eml) = @_;
190
191         # any header match means it's eligible for the inbox:
192         if (my $watch_hdrs = $ibx->{-watchheaders}) {
193                 my $ok;
194                 for my $wh (@$watch_hdrs) {
195                         my @v = $eml->header_raw($wh->[0]);
196                         $ok = grep(/$wh->[1]/, @v) and last;
197                 }
198                 return unless $ok;
199         }
200         eval {
201                 my $im = _importer_for($self, $ibx);
202                 if (my $scrub = $ibx->filter($im)) {
203                         my $scrubbed = $scrub->scrub($eml) or return;
204                         $scrubbed == REJECT and return;
205                         $eml = $scrubbed;
206                 }
207                 $im->add($eml, $self->{spamcheck});
208         };
209         if ($@) {
210                 warn "$ibx->{name} add failed: $@\n";
211                 _done_for_now($self);
212         }
213 }
214
215 sub _try_path {
216         my ($self, $path) = @_;
217         my $fl = PublicInbox::MdirReader::maildir_path_flags($path) // return;
218         return if $fl =~ /[DT]/; # no Drafts or Trash
219         if ($path !~ $self->{mdre}) {
220                 warn "unrecognized path: $path\n";
221                 return;
222         }
223         my $inboxes = $self->{mdmap}->{$1};
224         unless ($inboxes) {
225                 warn "unmappable dir: $1\n";
226                 return;
227         }
228         my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
229         local $SIG{__WARN__} = sub {
230                 my $pfx = ($_[0] // '') =~ /^([A-Z]: )/g ? $1 : '';
231                 $warn_cb->($pfx, "path: $path\n", @_);
232         };
233         if (!ref($inboxes) && $inboxes eq 'watchspam') {
234                 return _remove_spam($self, $path);
235         }
236         foreach my $ibx (@$inboxes) {
237                 my $eml = eml_from_path($path) or next;
238                 import_eml($self, $ibx, $eml);
239         }
240 }
241
242 sub quit_done ($) {
243         my ($self) = @_;
244         return unless $self->{quit};
245
246         # don't have reliable wakeups, keep signalling
247         my $done = 1;
248         for (qw(idle_pids poll_pids)) {
249                 my $pids = $self->{$_} or next;
250                 for (keys %$pids) {
251                         $done = undef if kill('QUIT', $_);
252                 }
253         }
254         $done;
255 }
256
257 sub quit {
258         my ($self) = @_;
259         $self->{quit} = 1;
260         %{$self->{opendirs}} = ();
261         _done_for_now($self);
262         quit_done($self);
263         if (my $idle_mic = $self->{idle_mic}) {
264                 eval { $idle_mic->done };
265                 if ($@) {
266                         warn "IDLE DONE error: $@\n";
267                         eval { $idle_mic->disconnect };
268                         warn "IDLE LOGOUT error: $@\n" if $@;
269                 }
270         }
271 }
272
273 sub watch_fs_init ($) {
274         my ($self) = @_;
275         my $done = sub {
276                 delete $self->{done_timer};
277                 _done_for_now($self);
278         };
279         my $cb = sub { # called by PublicInbox::DirIdle::event_step
280                 _try_path($self, $_[0]->fullname);
281                 $self->{done_timer} //= PublicInbox::DS::requeue($done);
282         };
283         require PublicInbox::DirIdle;
284         # inotify_create + EPOLL_CTL_ADD
285         PublicInbox::DirIdle->new([keys %{$self->{mdmap}}], $cb);
286 }
287
288 sub net_cb { # NetReader::(nntp|imap)_each callback
289         my ($uri, $art, $kw, $eml, $self, $inboxes) = @_;
290         return if grep(/\Adraft\z/, @$kw);
291         local $self->{cur_uid} = $art; # IMAP UID or NNTP article
292         if (ref($inboxes)) {
293                 my @ibx = @$inboxes;
294                 my $last = pop @ibx;
295                 for my $ibx (@ibx) {
296                         my $tmp = PublicInbox::Eml->new(\($eml->as_string));
297                         import_eml($self, $ibx, $tmp);
298                 }
299                 import_eml($self, $last, $eml);
300         } elsif ($inboxes eq 'watchspam') {
301                 if ($uri->scheme =~ /\Aimaps?\z/ && !grep(/\Aseen\z/, @$kw)) {
302                         return;
303                 }
304                 $self->{pi_cfg}->each_inbox(\&remove_eml_i,
305                                 $self, $eml, "$uri #$art");
306         } else {
307                 die "BUG: destination unknown $inboxes";
308         }
309 }
310
311 sub imap_fetch_all ($$) {
312         my ($self, $uri) = @_;
313         my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
314         $self->{incremental} = 1;
315         $self->{on_commit} = [ \&_done_for_now, $self ];
316         local $self->{cur_uid};
317         local $SIG{__WARN__} = sub {
318                 my $pfx = ($_[0] // '') =~ /^([A-Z]: |# )/g ? $1 : '';
319                 my $uid = $self->{cur_uid};
320                 $warn_cb->("$pfx$uri", $uid ? ("UID:$uid") : (), "\n", @_);
321         };
322         PublicInbox::NetReader::imap_each($self, $uri, \&net_cb, $self,
323                                         $self->{imap}->{$$uri});
324 }
325
326 sub imap_idle_once ($$$$) {
327         my ($self, $mic, $intvl, $uri) = @_;
328         my $i = $intvl //= (29 * 60);
329         my $end = now() + $intvl;
330         warn "I: $uri idling for ${intvl}s\n";
331         local $0 = "IDLE $0";
332         unless ($mic->idle) {
333                 return if $self->{quit};
334                 return "E: IDLE failed on $uri: $!";
335         }
336         $self->{idle_mic} = $mic; # for ->quit
337         my @res;
338         until ($self->{quit} || !$mic->IsConnected ||
339                         grep(/^\* [0-9]+ EXISTS/, @res) || $i <= 0) {
340                 @res = $mic->idle_data($i);
341                 $i = $end - now();
342         }
343         delete $self->{idle_mic};
344         unless ($self->{quit}) {
345                 $mic->IsConnected or return "E: IDLE disconnected on $uri";
346                 $mic->done or return "E: IDLE DONE failed on $uri: $!";
347         }
348         undef;
349 }
350
351 # idles on a single URI
352 sub watch_imap_idle_1 ($$$) {
353         my ($self, $uri, $intvl) = @_;
354         my $sec = uri_section($uri);
355         my $mic_arg = $self->{net_arg}->{$sec} or
356                         die "BUG: no Mail::IMAPClient->new arg for $sec";
357         my $mic;
358         local $0 = $uri->mailbox." $sec";
359         until ($self->{quit}) {
360                 $mic //= PublicInbox::NetReader::mic_new(
361                                         $self, $mic_arg, $sec, $uri);
362                 my $err;
363                 if ($mic && $mic->IsConnected) {
364                         local $self->{mics_cached}->{$sec} = $mic;
365                         my $m = imap_fetch_all($self, $uri);
366                         $m == $mic or die "BUG: wrong mic";
367                         $mic->IsConnected and
368                                 $err = imap_idle_once($self, $mic, $intvl, $uri)
369                 } else {
370                         $err = "E: not connected: $!";
371                 }
372                 if ($err && !$self->{quit}) {
373                         warn $err, "\n";
374                         $mic = undef;
375                         sleep 60 unless $self->{quit};
376                 }
377         }
378 }
379
380 sub watch_atfork_child ($) {
381         my ($self) = @_;
382         delete $self->{idle_pids};
383         delete $self->{poll_pids};
384         delete $self->{opendirs};
385         PublicInbox::DS->Reset;
386         my $sig = delete $self->{sig};
387         $sig->{CHLD} = 'DEFAULT';
388         @SIG{keys %$sig} = values %$sig;
389         PublicInbox::DS::sig_setmask($self->{oldset});
390 }
391
392 sub watch_atfork_parent ($) {
393         my ($self) = @_;
394         _done_for_now($self);
395         PublicInbox::DS::block_signals();
396 }
397
398 sub imap_idle_requeue { # DS::add_timer callback
399         my ($self, $uri_intvl) = @_;
400         return if $self->{quit};
401         push @{$self->{idle_todo}}, $uri_intvl;
402         event_step($self);
403 }
404
405 sub imap_idle_reap { # PublicInbox::DS::dwaitpid callback
406         my ($self, $pid) = @_;
407         my $uri_intvl = delete $self->{idle_pids}->{$pid} or
408                 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
409
410         my ($uri, $intvl) = @$uri_intvl;
411         return if $self->{quit};
412         warn "W: PID=$pid on $uri died: \$?=$?\n" if $?;
413         add_timer(60, \&imap_idle_requeue, $self, $uri_intvl);
414 }
415
416 sub reap { # callback for EOFpipe
417         my ($pid, $cb, $self) = @{$_[0]};
418         my $ret = waitpid($pid, 0);
419         if ($ret == $pid) {
420                 $cb->($self, $pid); # poll_fetch_reap || imap_idle_reap
421         } else {
422                 warn "W: waitpid($pid) => ", $ret // "($!)", "\n";
423         }
424 }
425
426 sub imap_idle_fork ($$) {
427         my ($self, $uri_intvl) = @_;
428         my ($uri, $intvl) = @$uri_intvl;
429         pipe(my ($r, $w)) or die "pipe: $!";
430         my $seed = rand(0xffffffff);
431         my $pid = fork // die "fork: $!";
432         if ($pid == 0) {
433                 srand($seed);
434                 eval { Net::SSLeay::randomize() };
435                 close $r;
436                 watch_atfork_child($self);
437                 watch_imap_idle_1($self, $uri, $intvl);
438                 close $w;
439                 _exit(0);
440         }
441         $self->{idle_pids}->{$pid} = $uri_intvl;
442         PublicInbox::EOFpipe->new($r, \&reap, [$pid, \&imap_idle_reap, $self]);
443 }
444
445 sub event_step {
446         my ($self) = @_;
447         return if $self->{quit};
448         my $idle_todo = $self->{idle_todo};
449         if ($idle_todo && @$idle_todo) {
450                 my $oldset = watch_atfork_parent($self);
451                 eval {
452                         while (my $uri_intvl = shift(@$idle_todo)) {
453                                 imap_idle_fork($self, $uri_intvl);
454                         }
455                 };
456                 PublicInbox::DS::sig_setmask($oldset);
457                 die $@ if $@;
458         }
459         fs_scan_step($self) if $self->{mdre};
460 }
461
462 sub watch_imap_fetch_all ($$) {
463         my ($self, $uris) = @_;
464         for my $uri (@$uris) {
465                 imap_fetch_all($self, $uri);
466                 last if $self->{quit};
467         }
468 }
469
470 sub watch_nntp_fetch_all ($$) {
471         my ($self, $uris) = @_;
472         $self->{incremental} = 1;
473         $self->{on_commit} = [ \&_done_for_now, $self ];
474         my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
475         local $self->{cur_uid};
476         my $uri = '';
477         local $SIG{__WARN__} = sub {
478                 my $pfx = ($_[0] // '') =~ /^([A-Z]: |# )/g ? $1 : '';
479                 my $art = $self->{cur_uid};
480                 $warn_cb->("$pfx$uri", $art ? ("ARTICLE $art") : (), "\n", @_);
481         };
482         for $uri (@$uris) {
483                 PublicInbox::NetReader::nntp_each($self, $uri, \&net_cb, $self,
484                                         $self->{nntp}->{$$uri});
485                 last if $self->{quit};
486         }
487 }
488
489 sub poll_fetch_fork { # DS::add_timer callback
490         my ($self, $intvl, $uris) = @_;
491         return if $self->{quit};
492         pipe(my ($r, $w)) or die "pipe: $!";
493         my $oldset = watch_atfork_parent($self);
494         my $seed = rand(0xffffffff);
495         my $pid = fork;
496         if (defined($pid) && $pid == 0) {
497                 srand($seed);
498                 eval { Net::SSLeay::randomize() };
499                 close $r;
500                 watch_atfork_child($self);
501                 if ($uris->[0]->scheme =~ m!\Aimaps?!i) {
502                         watch_imap_fetch_all($self, $uris);
503                 } else {
504                         watch_nntp_fetch_all($self, $uris);
505                 }
506                 close $w;
507                 _exit(0);
508         }
509         PublicInbox::DS::sig_setmask($oldset);
510         die "fork: $!"  unless defined $pid;
511         $self->{poll_pids}->{$pid} = [ $intvl, $uris ];
512         PublicInbox::EOFpipe->new($r, \&reap, [$pid, \&poll_fetch_reap, $self]);
513 }
514
515 sub poll_fetch_reap {
516         my ($self, $pid) = @_;
517         my $intvl_uris = delete $self->{poll_pids}->{$pid} or
518                 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
519         return if $self->{quit};
520         my ($intvl, $uris) = @$intvl_uris;
521         if ($?) {
522                 warn "W: PID=$pid died: \$?=$?\n", map { "$_\n" } @$uris;
523         }
524         warn("I: will check $_ in ${intvl}s\n") for @$uris;
525         add_timer($intvl, \&poll_fetch_fork, $self, $intvl, $uris);
526 }
527
528 sub watch_imap_init ($$) {
529         my ($self, $poll) = @_;
530         my $mics = PublicInbox::NetReader::imap_common_init($self);
531         my $idle = []; # [ [ uri1, intvl1 ], [uri2, intvl2] ]
532         for my $uri (@{$self->{imap_order}}) {
533                 my $sec = uri_section($uri);
534                 my $mic = $mics->{$sec};
535                 my $intvl = $self->{cfg_opt}->{$sec}->{pollInterval};
536                 if ($mic->has_capability('IDLE') && !$intvl) {
537                         $intvl = $self->{cfg_opt}->{$sec}->{idleInterval};
538                         push @$idle, [ $uri, $intvl // () ];
539                 } else {
540                         push @{$poll->{$intvl || 120}}, $uri;
541                 }
542         }
543         if (scalar @$idle) {
544                 $self->{idle_todo} = $idle;
545                 PublicInbox::DS::requeue($self); # ->event_step to fork
546         }
547 }
548
549 sub watch_nntp_init ($$) {
550         my ($self, $poll) = @_;
551         PublicInbox::NetReader::nntp_common_init($self);
552         for my $uri (@{$self->{nntp_order}}) {
553                 my $sec = uri_section($uri);
554                 my $intvl = $self->{cfg_opt}->{$sec}->{pollInterval};
555                 push @{$poll->{$intvl || 120}}, $uri;
556         }
557 }
558
559 sub watch { # main entry point
560         my ($self, $sig, $oldset) = @_;
561         $self->{oldset} = $oldset;
562         $self->{sig} = $sig;
563         my $poll = {}; # intvl_seconds => [ uri1, uri2 ]
564         watch_imap_init($self, $poll) if $self->{imap};
565         watch_nntp_init($self, $poll) if $self->{nntp};
566         while (my ($intvl, $uris) = each %$poll) {
567                 # poll all URIs for a given interval sequentially
568                 add_timer(0, \&poll_fetch_fork, $self, $intvl, $uris);
569         }
570         watch_fs_init($self) if $self->{mdre};
571         PublicInbox::DS->SetPostLoopCallback(sub { !$self->quit_done });
572         PublicInbox::DS::event_loop($sig, $oldset); # calls ->event_step
573         _done_for_now($self);
574 }
575
576 sub trigger_scan {
577         my ($self, $op) = @_;
578         push @{$self->{ops}}, $op;
579         PublicInbox::DS::requeue($self);
580 }
581
582 sub fs_scan_step {
583         my ($self) = @_;
584         return if $self->{quit};
585         my $op = shift @{$self->{ops}};
586         local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
587
588         # continue existing scan
589         my $opendirs = $self->{opendirs};
590         my @dirnames = keys %$opendirs;
591         foreach my $dir (@dirnames) {
592                 my $dh = delete $opendirs->{$dir};
593                 my $n = $self->{max_batch};
594                 while (my $fn = readdir($dh)) {
595                         _try_path($self, "$dir/$fn");
596                         last if --$n < 0;
597                 }
598                 $opendirs->{$dir} = $dh if $n < 0;
599         }
600         if ($op && $op eq 'full') {
601                 foreach my $dir (keys %{$self->{mdmap}}) {
602                         next if $opendirs->{$dir}; # already in progress
603                         my $ok = opendir(my $dh, $dir);
604                         unless ($ok) {
605                                 warn "failed to open $dir: $!\n";
606                                 next;
607                         }
608                         my $n = $self->{max_batch};
609                         while (my $fn = readdir($dh)) {
610                                 _try_path($self, "$dir/$fn");
611                                 last if --$n < 0;
612                         }
613                         $opendirs->{$dir} = $dh if $n < 0;
614                 }
615         }
616         _done_for_now($self);
617         # do we have more work to do?
618         PublicInbox::DS::requeue($self) if keys %$opendirs;
619 }
620
621 sub scan {
622         my ($self, $op) = @_;
623         push @{$self->{ops}}, $op;
624         fs_scan_step($self);
625 }
626
627 sub _importer_for {
628         my ($self, $ibx) = @_;
629         my $importers = $self->{importers};
630         my $im = $importers->{"$ibx"} ||= $ibx->importer(0);
631         if (scalar(keys(%$importers)) > 2) {
632                 delete $importers->{"$ibx"};
633                 _done_for_now($self);
634         }
635
636         $importers->{"$ibx"} = $im;
637 }
638
639 # XXX consider sharing with V2Writable, this only requires read-only access
640 sub content_exists ($$) {
641         my ($ibx, $eml) = @_;
642         my $over = $ibx->over or return;
643         my $mids = mids($eml);
644         my $chash = content_hash($eml);
645         my ($id, $prev);
646         for my $mid (@$mids) {
647                 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
648                         my $cmp = $ibx->smsg_eml($smsg) or return;
649                         return 1 if $chash eq content_hash($cmp);
650                 }
651         }
652         undef;
653 }
654
655 sub _spamcheck_cb {
656         my ($sc) = @_;
657         sub { # this gets called by (V2Writable||Import)->add
658                 my ($mime, $ibx) = @_;
659                 return if content_exists($ibx, $mime);
660                 my $tmp = '';
661                 if ($sc->spamcheck($mime, \$tmp)) {
662                         return PublicInbox::Eml->new(\$tmp);
663                 }
664                 warn $mime->header('Message-ID')." failed spam check\n";
665                 undef;
666         }
667 }
668
669 sub is_maildir {
670         $_[0] =~ s!\Amaildir:!! or return;
671         $_[0] =~ tr!/!/!s;
672         $_[0] =~ s!/\z!!;
673         $_[0];
674 }
675
676 sub is_watchspam {
677         my ($cur, $ws, $ibx) = @_;
678         if ($ws && !ref($ws) && $ws eq 'watchspam') {
679                 warn <<EOF;
680 E: $cur is a spam folder and cannot be used for `$ibx->{name}' input
681 EOF
682                 return 1;
683         }
684         undef;
685 }
686
687 sub folder_select { 'select' } # for PublicInbox::NetReader
688
689 1;