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