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