]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/WatchMaildir.pm
watch: wire up IMAP IDLE reapers to DS
[public-inbox.git] / lib / PublicInbox / WatchMaildir.pm
1 # Copyright (C) 2016-2020 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 #       http://wiki2.dovecot.org/MailboxFormat/Maildir
6 package PublicInbox::WatchMaildir;
7 use strict;
8 use warnings;
9 use PublicInbox::Eml;
10 use PublicInbox::InboxWritable;
11 use PublicInbox::Filter::Base qw(REJECT);
12 use PublicInbox::Spamcheck;
13 use PublicInbox::Sigfd;
14 use PublicInbox::DS qw(now);
15 use POSIX qw(_exit);
16 *mime_from_path = \&PublicInbox::InboxWritable::mime_from_path;
17
18 sub compile_watchheaders ($) {
19         my ($ibx) = @_;
20         my $watch_hdrs = [];
21         if (my $whs = $ibx->{watchheader}) {
22                 for (@$whs) {
23                         my ($k, $v) = split(/:/, $_, 2);
24                         # XXX should this be case-insensitive?
25                         # Or, mutt-style, case-sensitive iff
26                         # a capital letter exists?
27                         push @$watch_hdrs, [ $k, qr/\Q$v\E/ ];
28                 }
29         }
30         if (my $list_ids = $ibx->{listid}) {
31                 for (@$list_ids) {
32                         # RFC2919 section 6 stipulates
33                         # "case insensitive equality"
34                         my $re = qr/<[ \t]*\Q$_\E[ \t]*>/i;
35                         push @$watch_hdrs, ['List-Id', $re ];
36                 }
37         }
38         $ibx->{-watchheaders} = $watch_hdrs if scalar @$watch_hdrs;
39 }
40
41 sub new {
42         my ($class, $config) = @_;
43         my (%mdmap, @mdir, $spamc);
44         my %uniq; # directory => count
45         my %imap; # url => [inbox objects] or 'watchspam'
46
47         # "publicinboxwatch" is the documented namespace
48         # "publicinboxlearn" is legacy but may be supported
49         # indefinitely...
50         foreach my $pfx (qw(publicinboxwatch publicinboxlearn)) {
51                 my $k = "$pfx.watchspam";
52                 defined(my $dirs = $config->{$k}) or next;
53                 $dirs = [ $dirs ] if !ref($dirs);
54                 for my $dir (@$dirs) {
55                         if (is_maildir($dir)) {
56                                 # skip "new", no MUA has seen it, yet.
57                                 my $cur = "$dir/cur";
58                                 push @mdir, $cur;
59                                 $uniq{$cur}++;
60                                 $mdmap{$cur} = 'watchspam';
61                         } elsif (my $url = imap_url($dir)) {
62                                 $imap{$url} = 'watchspam';
63                         } else {
64                                 warn "unsupported $k=$dir\n";
65                         }
66                 }
67         }
68
69         my $k = 'publicinboxwatch.spamcheck';
70         my $default = undef;
71         my $spamcheck = PublicInbox::Spamcheck::get($config, $k, $default);
72         $spamcheck = _spamcheck_cb($spamcheck) if $spamcheck;
73
74         $config->each_inbox(sub {
75                 # need to make all inboxes writable for spam removal:
76                 my $ibx = $_[0] = PublicInbox::InboxWritable->new($_[0]);
77
78                 my $watch = $ibx->{watch} or return;
79                 if (is_maildir($watch)) {
80                         compile_watchheaders($ibx);
81                         my ($new, $cur) = ("$watch/new", "$watch/cur");
82                         return if is_watchspam($cur, $mdmap{$cur}, $ibx);
83                         push @mdir, $new unless $uniq{$new}++;
84                         push @mdir, $cur unless $uniq{$cur}++;
85                         push @{$mdmap{$new} ||= []}, $ibx;
86                         push @{$mdmap{$cur} ||= []}, $ibx;
87                 } elsif (my $url = imap_url($watch)) {
88                         return if is_watchspam($url, $imap{$url}, $ibx);
89                         compile_watchheaders($ibx);
90                         push @{$imap{$url} ||= []}, $ibx;
91                 } else {
92                         warn "watch unsupported: $k=$watch\n";
93                 }
94         });
95         return unless scalar(@mdir) || scalar(keys %imap);
96
97         my $mdre;
98         if (@mdir) {
99                 $mdre = join('|', map { quotemeta($_) } @mdir);
100                 $mdre = qr!\A($mdre)/!;
101         }
102         bless {
103                 spamcheck => $spamcheck,
104                 mdmap => \%mdmap,
105                 mdir => \@mdir,
106                 mdre => $mdre,
107                 config => $config,
108                 imap => scalar keys %imap ? \%imap : undef,
109                 importers => {},
110                 opendirs => {}, # dirname => dirhandle (in progress scans)
111                 ops => [], # 'quit', 'full'
112         }, $class;
113 }
114
115 sub _done_for_now {
116         my ($self) = @_;
117         my $importers = $self->{importers};
118         foreach my $im (values %$importers) {
119                 $im->done;
120         }
121 }
122
123 sub remove_eml_i { # each_inbox callback
124         my ($ibx, $arg) = @_;
125         my ($self, $eml, $loc) = @$arg;
126         eval {
127                 my $im = _importer_for($self, $ibx);
128                 $im->remove($eml, 'spam');
129                 if (my $scrub = $ibx->filter($im)) {
130                         my $scrubbed = $scrub->scrub($eml, 1);
131                         $scrubbed or return;
132                         $scrubbed == REJECT() and return;
133                         $im->remove($scrubbed, 'spam');
134                 }
135         };
136         warn "error removing spam at: $loc from $ibx->{name}: $@\n" if $@;
137 }
138
139 sub _remove_spam {
140         my ($self, $path) = @_;
141         # path must be marked as (S)een
142         $path =~ /:2,[A-R]*S[T-Za-z]*\z/ or return;
143         my $eml = mime_from_path($path) or return;
144         $self->{config}->each_inbox(\&remove_eml_i, [ $self, $eml, $path ]);
145 }
146
147 sub import_eml ($$$) {
148         my ($self, $ibx, $eml) = @_;
149         my $im = _importer_for($self, $ibx);
150
151         # any header match means it's eligible for the inbox:
152         if (my $watch_hdrs = $ibx->{-watchheaders}) {
153                 my $ok;
154                 my $hdr = $eml->header_obj;
155                 for my $wh (@$watch_hdrs) {
156                         my @v = $hdr->header_raw($wh->[0]);
157                         $ok = grep(/$wh->[1]/, @v) and last;
158                 }
159                 return unless $ok;
160         }
161
162         if (my $scrub = $ibx->filter($im)) {
163                 my $ret = $scrub->scrub($eml) or return;
164                 $ret == REJECT() and return;
165                 $eml = $ret;
166         }
167         $im->add($eml, $self->{spamcheck});
168 }
169
170 sub _try_path {
171         my ($self, $path) = @_;
172         return unless PublicInbox::InboxWritable::is_maildir_path($path);
173         if ($path !~ $self->{mdre}) {
174                 warn "unrecognized path: $path\n";
175                 return;
176         }
177         my $inboxes = $self->{mdmap}->{$1};
178         unless ($inboxes) {
179                 warn "unmappable dir: $1\n";
180                 return;
181         }
182         if (!ref($inboxes) && $inboxes eq 'watchspam') {
183                 return _remove_spam($self, $path);
184         }
185
186         my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
187         local $SIG{__WARN__} = sub {
188                 $warn_cb->("path: $path\n");
189                 $warn_cb->(@_);
190         };
191         foreach my $ibx (@$inboxes) {
192                 my $eml = mime_from_path($path) or next;
193                 import_eml($self, $ibx, $eml);
194         }
195 }
196
197 sub quit {
198         my ($self) = @_;
199         $self->{quit} = 1;
200         %{$self->{opendirs}} = ();
201         _done_for_now($self);
202         if (my $imap_pid = $self->{-imap_pid}) {
203                 kill('QUIT', $imap_pid);
204         }
205         if (my $idle_pids = $self->{idle_pids}) {
206                 kill('QUIT', $_) for (keys %$idle_pids);
207         }
208         if (my $idle_mic = $self->{idle_mic}) {
209                 eval { $idle_mic->done };
210                 warn "IDLE DONE error: $@\n" if $@;
211                 eval { $idle_mic->disconnect };
212                 warn "IDLE LOGOUT error: $@\n" if $@;
213         }
214 }
215
216 sub watch_fs_init ($) {
217         my ($self) = @_;
218         my $done = sub {
219                 delete $self->{done_timer};
220                 _done_for_now($self);
221         };
222         my $cb = sub {
223                 _try_path($self, $_[0]->fullname);
224                 $self->{done_timer} //= PublicInbox::DS::requeue($done);
225         };
226         require PublicInbox::DirIdle;
227         PublicInbox::DirIdle->new($self->{mdir}, $cb); # EPOLL_CTL_ADD
228 }
229
230 # returns the git config section name, e.g [imap "imaps://user@example.com"]
231 # without the mailbox, so we can share connections between different inboxes
232 sub imap_section ($) {
233         my ($uri) = @_;
234         $uri->scheme . '://' . $uri->authority;
235 }
236
237 sub cfg_intvl ($$) {
238         my ($cfg, $key) = @_;
239         defined(my $v = $cfg->{lc($key)}) or return;
240         $v =~ /\A[0-9]+\z/s and return $v + 0;
241         if (ref($v) eq 'ARRAY') {
242                 $v = join(', ', @$v);
243                 warn "W: $key has multiple values: $v\nW: $key ignored\n";
244         } else {
245                 warn "W: $key=$v is not an integer value in seconds\n";
246         }
247 }
248
249 # flesh out common IMAP-specific data structures
250 sub imap_common_init ($) {
251         my ($self) = @_;
252         my $cfg = $self->{config};
253         my $mic_args = {}; # scheme://authority => Mail:IMAPClient arg
254         for my $url (sort keys %{$self->{imap}}) {
255                 my $uri = PublicInbox::URIimap->new($url);
256                 my $sec = imap_section($uri);
257                 for my $k (qw(Starttls Debug Compress)) {
258                         my $key = lc("imap.$sec.$k");
259                         defined(my $orig = $cfg->{$key}) or next;
260                         my $v = PublicInbox::Config::_git_config_bool($orig);
261                         if (defined($v)) {
262                                 $mic_args->{$sec}->{$k} = $v;
263                         } else {
264                                 warn "W: $key=$orig is not boolean\n";
265                         }
266                 }
267                 my $to = cfg_intvl($cfg, "imap.$sec.Timeout");
268                 $mic_args->{$sec}->{Timeout} = $to if $to;
269                 $to = cfg_intvl($cfg, "imap.$sec.PollInterval");
270                 $self->{imap_opt}->{$sec}->{poll_intvl} = $to if $to;
271                 $to = cfg_intvl($cfg, "imap.$sec.IdleInterval");
272                 $self->{imap_opt}->{$sec}->{idle_intvl} = $to if $to;
273         }
274         $mic_args;
275 }
276
277 sub auth_anon_cb { '' }; # for Mail::IMAPClient::Authcallback
278
279 sub mic_for ($$$) { # mic = Mail::IMAPClient
280         my ($self, $uri, $mic_args) = @_;
281         my $url = $uri->as_string;
282         my $cred = {
283                 url => $url,
284                 protocol => $uri->scheme,
285                 host => $uri->host,
286                 username => $uri->user,
287                 password => $uri->password,
288         };
289         my $common = $mic_args->{imap_section($uri)} // {};
290         my $host = $cred->{host};
291         my $mic_arg = {
292                 Port => $uri->port,
293                 # IMAPClient mishandles `0', so we pass `127.0.0.1'
294                 Server => $host eq '0' ? '127.0.0.1' : $host,
295                 Ssl => $uri->scheme eq 'imaps',
296                 Keepalive => 1, # SO_KEEPALIVE
297                 %$common, # may set Starttls, Compress, Debug ....
298         };
299         my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or
300                 die "E: <$url> new: $@\n";
301
302         # default to using STARTTLS if it's available, but allow
303         # it to be disabled since I usually connect to localhost
304         if (!$mic_arg->{Ssl} && !defined($mic_arg->{Starttls}) &&
305                         $mic->has_capability('STARTTLS') &&
306                         $mic->can('starttls')) {
307                 $mic->starttls or die "E: <$url> STARTTLS: $@\n";
308         }
309
310         # do we even need credentials?
311         if (!defined($cred->{username}) &&
312                         $mic->has_capability('AUTH=ANONYMOUS')) {
313                 $cred = undef;
314         }
315         if ($cred) {
316                 Git::credential($cred, 'fill'); # may prompt user here
317                 $mic->User($mic_arg->{User} = $cred->{username});
318                 $mic->Password($mic_arg->{Password} = $cred->{password});
319         } else { # AUTH=ANONYMOUS
320                 $mic->Authmechanism($mic_arg->{Authmechanism} = 'ANONYMOUS');
321                 $mic->Authcallback($mic_arg->{Authcallback} = \&auth_anon_cb);
322         }
323         if ($mic->login && $mic->IsAuthenticated) {
324                 # success! keep IMAPClient->new arg in case we get disconnected
325                 $self->{mic_arg}->{imap_section($uri)} = $mic_arg;
326         } else {
327                 warn "E: <$url> LOGIN: $@\n";
328                 $mic = undef;
329         }
330         Git::credential($cred, $mic ? 'approve' : 'reject') if $cred;
331         $mic;
332 }
333
334 sub imap_fetch_all ($$$) {
335         my ($self, $mic, $uri) = @_;
336         my $sec = imap_section($uri);
337         my $mbx = $uri->mailbox;
338         my $url = $uri->as_string;
339         $mic->Clear(1); # trim results history
340         $mic->examine($mbx) or return "E: EXAMINE $mbx ($sec) failed: $!";
341         my ($r_uidval, $r_uidnext);
342         for ($mic->Results) {
343                 /^\* OK \[UIDVALIDITY ([0-9]+)\].*/ and $r_uidval = $1;
344                 /^\* OK \[UIDNEXT ([0-9]+)\].*/ and $r_uidnext = $1;
345                 last if $r_uidval && $r_uidnext;
346         }
347         $r_uidval //= $mic->uidvalidity($mbx) //
348                 return "E: $url cannot get UIDVALIDITY";
349         $r_uidnext //= $mic->uidnext($mbx) //
350                 return "E: $url cannot get UIDNEXT";
351         my $itrk = PublicInbox::IMAPTracker->new;
352         my ($l_uidval, $l_uid) = $itrk->get_last($url);
353         $l_uidval //= $r_uidval; # first time
354         $l_uid //= 1;
355         if ($l_uidval != $r_uidval) {
356                 return "E: $url UIDVALIDITY mismatch\n".
357                         "E: local=$l_uidval != remote=$r_uidval";
358         }
359         my $r_uid = $r_uidnext - 1;
360         if ($l_uid != 1 && $l_uid > $r_uid) {
361                 return "E: $url local UID exceeds remote ($l_uid > $r_uid)\n".
362                         "E: $url strangely, UIDVALIDLITY matches ($l_uidval)\n";
363         }
364         return if $l_uid >= $r_uid; # nothing to do
365
366         $mic->Uid(1); # the default, we hope
367         my $req = $mic->imap4rev1 ? 'BODY.PEEK[]' : 'RFC822.PEEK';
368         my $key = $req;
369         $key =~ s/\.PEEK//;
370         my $inboxes = $self->{imap}->{$url};
371         warn "I: $url fetching $l_uid..$r_uid\n";
372         my $uid = -1;
373         my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
374         local $SIG{__WARN__} = sub {
375                 $warn_cb->("$url UID:$uid\n");
376                 $warn_cb->(@_);
377         };
378         my $err;
379         $itrk->{dbh}->begin_work;
380         for my $u ($l_uid..$r_uid) {
381                 $uid = $u;
382                 local $0 = "UID:$uid $mbx $sec";
383                 my $r = $mic->fetch_hash($uid, $req);
384                 unless ($r) { # network error?
385                         $err = "E: $url UID FETCH $uid error: $!\n";
386                         last;
387                 }
388
389                 # messages get deleted, so holes appear
390                 defined(my $raw = delete $r->{$uid}->{$key}) or next;
391
392                 # our target audience expects LF-only, save storage
393                 $raw =~ s/\r\n/\n/sg;
394
395                 if (ref($inboxes)) {
396                         for my $ibx (@$inboxes) {
397                                 my $eml = PublicInbox::Eml->new($raw);
398                                 my $x = import_eml($self, $ibx, $eml);
399                         }
400                 } elsif ($inboxes eq 'watchspam') {
401                         my $eml = PublicInbox::Eml->new($raw);
402                         my $arg = [ $self, $eml, "$uri UID:$uid" ];
403                         $self->{config}->each_inbox(\&remove_eml_i, $arg);
404                 } else {
405                         die "BUG: destination unknown $inboxes";
406                 }
407                 $itrk->update_last($url, $r_uidval, $uid);
408                 last if $self->{quit};
409         }
410         _done_for_now($self);
411         $itrk->{dbh}->commit;
412         $err;
413 }
414
415 sub imap_idle_once ($$$$) {
416         my ($self, $mic, $intvl, $url) = @_;
417         my $i = $intvl //= (29 * 60);
418         my $end = now() + $intvl;
419         warn "I: $url idling for ${intvl}s\n";
420         local $0 = "IDLE $0";
421         unless ($mic->idle) {
422                 return if $self->{quit};
423                 return "E: IDLE failed on $url: $!";
424         }
425         $self->{idle_mic} = $mic; # for ->quit
426         my @res;
427         until ($self->{quit} || grep(/^\* [0-9]+ EXISTS/, @res) || $i <= 0) {
428                 @res = $mic->idle_data($i);
429                 $i = $end - now();
430         }
431         delete $self->{idle_mic};
432         unless ($self->{quit}) {
433                 $mic->IsConnected or return "E: IDLE disconnected on $url";
434                 $mic->done or return "E: IDLE DONE failed on $url: $!";
435         }
436         undef;
437 }
438
439 # idles on a single URI
440 sub watch_imap_idle_1 ($$$) {
441         my ($self, $uri, $intvl) = @_;
442         my $sec = imap_section($uri);
443         my $mic_arg = $self->{mic_arg}->{$sec} or
444                         die "BUG: no Mail::IMAPClient->new arg for $sec";
445         my $mic;
446         local $0 = $uri->mailbox." $sec";
447         until ($self->{quit}) {
448                 $mic //= delete($self->{mics}->{$sec}) //
449                                 PublicInbox::IMAPClient->new(%$mic_arg);
450                 my $err = imap_fetch_all($self, $mic, $uri);
451                 $err //= imap_idle_once($self, $mic, $intvl, $uri->as_string);
452                 if ($err && !$self->{quit}) {
453                         warn $err, "\n";
454                         $mic = undef;
455                         sleep 60 unless $self->{quit};
456                 }
457         }
458 }
459
460 sub watch_atfork_child ($) {
461         my ($self) = @_;
462         delete $self->{idle_pids};
463         PublicInbox::DS->Reset;
464         PublicInbox::Sigfd::sig_setmask($self->{oldset});
465         %SIG = (%SIG, %{$self->{sig}});
466 }
467
468 sub imap_idle_reap { # PublicInbox::DS::dwaitpid callback
469         my ($self, $pid) = @_;
470         my $uri_intvl = delete $self->{idle_pids}->{$pid} or
471                 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
472
473         my ($uri, $intvl) = @$uri_intvl;
474         my $url = $uri->as_string;
475         return if $self->{quit};
476         warn "W: PID=$pid on $url died: \$?=$?\n" if $?;
477         push @{$self->{idle_todo}}, $uri_intvl;
478         PubicInbox::DS::requeue($self); # call ->event_step to respawn
479 }
480
481 sub imap_idle_fork ($$) {
482         my ($self, $uri_intvl) = @_;
483         my ($uri, $intvl) = @$uri_intvl;
484         defined(my $pid = fork) or die "fork: $!";
485         if ($pid == 0) {
486                 watch_atfork_child($self);
487                 watch_imap_idle_1($self, $uri, $intvl);
488                 _exit(0);
489         }
490         $self->{idle_pids}->{$pid} = $uri_intvl;
491         PublicInbox::DS::dwaitpid($pid, \&imap_idle_reap, $self);
492 }
493
494 sub event_step {
495         my ($self) = @_;
496         return if $self->{quit};
497         my $idle_todo = $self->{idle_todo};
498         if ($idle_todo && @$idle_todo) {
499                 $self->{mics} = {}; # going to be forking, so disconnect
500                 while (my $uri_intvl = shift(@$idle_todo)) {
501                         imap_idle_fork($self, $uri_intvl);
502                 }
503         }
504         goto(&fs_scan_step) if $self->{mdre};
505 }
506
507 sub watch_imap_init ($) {
508         my ($self) = @_;
509         eval { require PublicInbox::IMAPClient } or
510                 die "Mail::IMAPClient is required for IMAP:\n$@\n";
511         eval { require Git } or
512                 die "Git (Perl module) is required for IMAP:\n$@\n";
513         eval { require PublicInbox::IMAPTracker } or
514                 die "DBD::SQLite is required for IMAP\n:$@\n";
515
516         my $mic_args = imap_common_init($self); # read args from config
517
518         # make sure we can connect and cache the credentials in memory
519         $self->{mic_arg} = {}; # schema://authority => IMAPClient->new args
520         my $mics = $self->{mics} = {}; # schema://authority => IMAPClient obj
521         for my $url (sort keys %{$self->{imap}}) {
522                 my $uri = PublicInbox::URIimap->new($url);
523                 $mics->{imap_section($uri)} //= mic_for($self, $uri, $mic_args);
524         }
525
526         my $idle = []; # [ [ uri1, intvl1 ], [uri2, intvl2] ]
527         my $poll = {}; # intvl_seconds => [ uri1, uri2 ]
528         for my $url (keys %{$self->{imap}}) {
529                 my $uri = PublicInbox::URIimap->new($url);
530                 my $sec = imap_section($uri);
531                 my $mic = $mics->{$sec};
532                 my $intvl = $self->{imap_opt}->{$sec}->{poll_intvl};
533                 if ($mic->has_capability('IDLE') && !$intvl) {
534                         $intvl = $self->{imap_opt}->{$sec}->{idle_intvl};
535                         push @$idle, [ $uri, $intvl // () ];
536                 } else {
537                         push @{$poll->{$intvl || 120}}, $uri;
538                 }
539         }
540         if (scalar @$idle) {
541                 $self->{idle_pids} = {};
542                 $self->{idle_todo} = $idle;
543                 PublicInbox::DS::requeue($self); # ->event_step to fork
544         }
545         # TODO: polling
546 }
547
548 sub watch {
549         my ($self, $sig, $oldset) = @_;
550         $self->{oldset} = $oldset;
551         $self->{sig} = $sig;
552         watch_imap_init($self) if $self->{imap};
553         watch_fs_init($self) if $self->{mdre};
554         PublicInbox::DS->SetPostLoopCallback(sub {});
555         PublicInbox::DS->EventLoop until $self->{quit};
556         _done_for_now($self);
557 }
558
559 sub trigger_scan {
560         my ($self, $op) = @_;
561         push @{$self->{ops}}, $op;
562         PublicInbox::DS::requeue($self);
563 }
564
565 sub fs_scan_step {
566         my ($self) = @_;
567         return if $self->{quit};
568         my $op = shift @{$self->{ops}};
569
570         # continue existing scan
571         my $max = 10;
572         my $opendirs = $self->{opendirs};
573         my @dirnames = keys %$opendirs;
574         foreach my $dir (@dirnames) {
575                 my $dh = delete $opendirs->{$dir};
576                 my $n = $max;
577                 while (my $fn = readdir($dh)) {
578                         _try_path($self, "$dir/$fn");
579                         last if --$n < 0;
580                 }
581                 $opendirs->{$dir} = $dh if $n < 0;
582         }
583         if ($op && $op eq 'full') {
584                 foreach my $dir (@{$self->{mdir}}) {
585                         next if $opendirs->{$dir}; # already in progress
586                         my $ok = opendir(my $dh, $dir);
587                         unless ($ok) {
588                                 warn "failed to open $dir: $!\n";
589                                 next;
590                         }
591                         my $n = $max;
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         }
599         _done_for_now($self);
600         # do we have more work to do?
601         PublicInbox::DS::requeue($self) if keys %$opendirs;
602 }
603
604 sub scan {
605         my ($self, $op) = @_;
606         push @{$self->{ops}}, $op;
607         goto &fs_scan_step;
608 }
609
610 sub _importer_for {
611         my ($self, $ibx) = @_;
612         my $importers = $self->{importers};
613         my $im = $importers->{"$ibx"} ||= $ibx->importer(0);
614         if (scalar(keys(%$importers)) > 2) {
615                 delete $importers->{"$ibx"};
616                 _done_for_now($self);
617         }
618
619         $importers->{"$ibx"} = $im;
620 }
621
622 sub _spamcheck_cb {
623         my ($sc) = @_;
624         sub {
625                 my ($mime) = @_;
626                 my $tmp = '';
627                 if ($sc->spamcheck($mime, \$tmp)) {
628                         return PublicInbox::Eml->new(\$tmp);
629                 }
630                 warn $mime->header('Message-ID')." failed spam check\n";
631                 undef;
632         }
633 }
634
635 sub is_maildir {
636         $_[0] =~ s!\Amaildir:!! or return;
637         $_[0] =~ tr!/!/!s;
638         $_[0] =~ s!/\z!!;
639         $_[0];
640 }
641
642 sub is_watchspam {
643         my ($cur, $ws, $ibx) = @_;
644         if ($ws && !ref($ws) && $ws eq 'watchspam') {
645                 warn <<EOF;
646 E: $cur is a spam folder and cannot be used for `$ibx->{name}' input
647 EOF
648                 return 1;
649         }
650         undef;
651 }
652
653 sub imap_url {
654         my ($url) = @_;
655         require PublicInbox::URIimap;
656         my $uri = PublicInbox::URIimap->new($url);
657         $uri ? $uri->canonical->as_string : undef;
658 }
659
660 1;