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