]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/WatchMaildir.pm
watch: use signalfd for Maildir watching
[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 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                 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 {
217         my ($self) = @_;
218         require PublicInbox::DirIdle;
219         my $done = sub {
220                 delete $self->{done_timer};
221                 _done_for_now($self);
222         };
223         my $cb = sub {
224                 _try_path($self, $_[0]->fullname);
225                 $self->{done_timer} //= PublicInbox::DS::requeue($done);
226         };
227         my $di = PublicInbox::DirIdle->new($self->{mdir}, $cb);
228         PublicInbox::DS->SetPostLoopCallback(sub { !$self->{quit} });
229         PublicInbox::DS->EventLoop;
230         _done_for_now($self);
231 }
232
233 # returns the git config section name, e.g [imap "imaps://user@example.com"]
234 # without the mailbox, so we can share connections between different inboxes
235 sub imap_section ($) {
236         my ($uri) = @_;
237         $uri->scheme . '://' . $uri->authority;
238 }
239
240 sub cfg_intvl ($$) {
241         my ($cfg, $key) = @_;
242         defined(my $v = $cfg->{lc($key)}) or return;
243         $v =~ /\A[0-9]+\z/s and return $v + 0;
244         if (ref($v) eq 'ARRAY') {
245                 $v = join(', ', @$v);
246                 warn "W: $key has multiple values: $v\nW: $key ignored\n";
247         } else {
248                 warn "W: $key=$v is not an integer value in seconds\n";
249         }
250 }
251
252 # flesh out common IMAP-specific data structures
253 sub imap_common_init ($) {
254         my ($self) = @_;
255         my $cfg = $self->{config};
256         my $mic_args = {}; # scheme://authority => Mail:IMAPClient arg
257         for my $url (sort keys %{$self->{imap}}) {
258                 my $uri = PublicInbox::URIimap->new($url);
259                 my $sec = imap_section($uri);
260                 for my $k (qw(Starttls Debug Compress)) {
261                         my $key = lc("imap.$sec.$k");
262                         defined(my $orig = $cfg->{$key}) or next;
263                         my $v = PublicInbox::Config::_git_config_bool($orig);
264                         if (defined($v)) {
265                                 $mic_args->{$sec}->{$k} = $v;
266                         } else {
267                                 warn "W: $key=$orig is not boolean\n";
268                         }
269                 }
270                 my $to = cfg_intvl($cfg, "imap.$sec.Timeout");
271                 $mic_args->{$sec}->{Timeout} = $to if $to;
272                 $to = cfg_intvl($cfg, "imap.$sec.PollInterval");
273                 $self->{imap_opt}->{$sec}->{poll_intvl} = $to if $to;
274                 $to = cfg_intvl($cfg, "imap.$sec.IdleInterval");
275                 $self->{imap_opt}->{$sec}->{idle_intvl} = $to if $to;
276         }
277         $mic_args;
278 }
279
280 sub auth_anon_cb { '' }; # for Mail::IMAPClient::Authcallback
281
282 sub mic_for ($$$) { # mic = Mail::IMAPClient
283         my ($self, $uri, $mic_args) = @_;
284         my $url = $uri->as_string;
285         my $cred = {
286                 url => $url,
287                 protocol => $uri->scheme,
288                 host => $uri->host,
289                 username => $uri->user,
290                 password => $uri->password,
291         };
292         my $common = $mic_args->{imap_section($uri)} // {};
293         my $host = $cred->{host};
294         my $mic_arg = {
295                 Port => $uri->port,
296                 # IMAPClient mishandles `0', so we pass `127.0.0.1'
297                 Server => $host eq '0' ? '127.0.0.1' : $host,
298                 Ssl => $uri->scheme eq 'imaps',
299                 Keepalive => 1, # SO_KEEPALIVE
300                 %$common, # may set Starttls, Compress, Debug ....
301         };
302         my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or
303                 die "E: <$url> new: $@\n";
304
305         # default to using STARTTLS if it's available, but allow
306         # it to be disabled since I usually connect to localhost
307         if (!$mic_arg->{Ssl} && !defined($mic_arg->{Starttls}) &&
308                         $mic->has_capability('STARTTLS') &&
309                         $mic->can('starttls')) {
310                 $mic->starttls or die "E: <$url> STARTTLS: $@\n";
311         }
312
313         # do we even need credentials?
314         if (!defined($cred->{username}) &&
315                         $mic->has_capability('AUTH=ANONYMOUS')) {
316                 $cred = undef;
317         }
318         if ($cred) {
319                 Git::credential($cred, 'fill'); # may prompt user here
320                 $mic->User($mic_arg->{User} = $cred->{username});
321                 $mic->Password($mic_arg->{Password} = $cred->{password});
322         } else { # AUTH=ANONYMOUS
323                 $mic->Authmechanism($mic_arg->{Authmechanism} = 'ANONYMOUS');
324                 $mic->Authcallback($mic_arg->{Authcallback} = \&auth_anon_cb);
325         }
326         if ($mic->login && $mic->IsAuthenticated) {
327                 # success! keep IMAPClient->new arg in case we get disconnected
328                 $self->{mic_arg}->{imap_section($uri)} = $mic_arg;
329         } else {
330                 warn "E: <$url> LOGIN: $@\n";
331                 $mic = undef;
332         }
333         Git::credential($cred, $mic ? 'approve' : 'reject') if $cred;
334         $mic;
335 }
336
337 sub imap_start ($) {
338         my ($self) = @_;
339         eval { require PublicInbox::IMAPClient } or
340                 die "Mail::IMAPClient is required for IMAP:\n$@\n";
341         eval { require Git } or
342                 die "Git (Perl module) is required for IMAP:\n$@\n";
343         eval { require PublicInbox::IMAPTracker } or
344                 die "DBD::SQLite is required for IMAP\n:$@\n";
345
346         my $mic_args = imap_common_init($self);
347         # make sure we can connect and cache the credentials in memory
348         $self->{mic_arg} = {}; # schema://authority => IMAPClient->new args
349         my $mics = $self->{mics} = {}; # schema://authority => IMAPClient obj
350         for my $url (sort keys %{$self->{imap}}) {
351                 my $uri = PublicInbox::URIimap->new($url);
352                 $mics->{imap_section($uri)} //= mic_for($self, $uri, $mic_args);
353         }
354 }
355
356 sub imap_fetch_all ($$$) {
357         my ($self, $mic, $uri) = @_;
358         my $sec = imap_section($uri);
359         my $mbx = $uri->mailbox;
360         my $url = $uri->as_string;
361         $mic->Clear(1); # trim results history
362         $mic->examine($mbx) or return "E: EXAMINE $mbx ($sec) failed: $!";
363         my ($r_uidval, $r_uidnext);
364         for ($mic->Results) {
365                 /^\* OK \[UIDVALIDITY ([0-9]+)\].*/ and $r_uidval = $1;
366                 /^\* OK \[UIDNEXT ([0-9]+)\].*/ and $r_uidnext = $1;
367                 last if $r_uidval && $r_uidnext;
368         }
369         $r_uidval //= $mic->uidvalidity($mbx) //
370                 return "E: $url cannot get UIDVALIDITY";
371         $r_uidnext //= $mic->uidnext($mbx) //
372                 return "E: $url cannot get UIDNEXT";
373         my $itrk = PublicInbox::IMAPTracker->new;
374         my ($l_uidval, $l_uid) = $itrk->get_last($url);
375         $l_uidval //= $r_uidval; # first time
376         $l_uid //= 1;
377         if ($l_uidval != $r_uidval) {
378                 return "E: $url UIDVALIDITY mismatch\n".
379                         "E: local=$l_uidval != remote=$r_uidval";
380         }
381         my $r_uid = $r_uidnext - 1;
382         if ($l_uid != 1 && $l_uid > $r_uid) {
383                 return "E: $url local UID exceeds remote ($l_uid > $r_uid)\n".
384                         "E: $url strangely, UIDVALIDLITY matches ($l_uidval)\n";
385         }
386         return if $l_uid >= $r_uid; # nothing to do
387
388         $mic->Uid(1); # the default, we hope
389         my $req = $mic->imap4rev1 ? 'BODY.PEEK[]' : 'RFC822.PEEK';
390         my $key = $req;
391         $key =~ s/\.PEEK//;
392         my $inboxes = $self->{imap}->{$url};
393         warn "I: $url fetching $l_uid..$r_uid\n";
394         my $uid = -1;
395         my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
396         local $SIG{__WARN__} = sub {
397                 $warn_cb->("$url UID:$uid\n");
398                 $warn_cb->(@_);
399         };
400         my $err;
401         $itrk->{dbh}->begin_work;
402         for my $u ($l_uid..$r_uid) {
403                 $uid = $u;
404                 local $0 = "UID:$uid $mbx $sec";
405                 my $r = $mic->fetch_hash($uid, $req);
406                 unless ($r) { # network error?
407                         $err = "E: $url UID FETCH $uid error: $!\n";
408                         last;
409                 }
410
411                 # messages get deleted, so holes appear
412                 defined(my $raw = delete $r->{$uid}->{$key}) or next;
413
414                 # our target audience expects LF-only, save storage
415                 $raw =~ s/\r\n/\n/sg;
416
417                 if (ref($inboxes)) {
418                         for my $ibx (@$inboxes) {
419                                 my $eml = PublicInbox::Eml->new($raw);
420                                 my $x = import_eml($self, $ibx, $eml);
421                         }
422                 } elsif ($inboxes eq 'watchspam') {
423                         my $eml = PublicInbox::Eml->new($raw);
424                         my $arg = [ $self, $eml, "$uri UID:$uid" ];
425                         $self->{config}->each_inbox(\&remove_eml_i, $arg);
426                 } else {
427                         die "BUG: destination unknown $inboxes";
428                 }
429                 $itrk->update_last($url, $r_uidval, $uid);
430                 last if $self->{quit};
431         }
432         _done_for_now($self);
433         $itrk->{dbh}->commit;
434         $err;
435 }
436
437 sub imap_idle_once ($$$$) {
438         my ($self, $mic, $intvl, $url) = @_;
439         my $i = $intvl //= (29 * 60);
440         my $end = now() + $intvl;
441         warn "I: $url idling for ${intvl}s\n";
442         local $0 = "IDLE $0";
443         unless ($mic->idle) {
444                 return if $self->{quit};
445                 return "E: IDLE failed on $url: $!";
446         }
447         $self->{idle_mic} = $mic; # for ->quit
448         my @res;
449         until ($self->{quit} || grep(/^\* [0-9]+ EXISTS/, @res) || $i <= 0) {
450                 @res = $mic->idle_data($i);
451                 $i = $end - now();
452         }
453         delete $self->{idle_mic};
454         unless ($self->{quit}) {
455                 $mic->IsConnected or return "E: IDLE disconnected on $url";
456                 $mic->done or return "E: IDLE DONE failed on $url: $!";
457         }
458         undef;
459 }
460
461 # idles on a single URI
462 sub watch_imap_idle_1 ($$$) {
463         my ($self, $uri, $intvl) = @_;
464         my $sec = imap_section($uri);
465         my $mic_arg = $self->{mic_arg}->{$sec} or
466                         die "BUG: no Mail::IMAPClient->new arg for $sec";
467         my $mic;
468         local $0 = $uri->mailbox." $sec";
469         until ($self->{quit}) {
470                 $mic //= delete($self->{mics}->{$sec}) //
471                                 PublicInbox::IMAPClient->new(%$mic_arg);
472                 my $err = imap_fetch_all($self, $mic, $uri);
473                 $err //= imap_idle_once($self, $mic, $intvl, $uri->as_string);
474                 if ($err && !$self->{quit}) {
475                         warn $err, "\n";
476                         $mic = undef;
477                         sleep 60 unless $self->{quit};
478                 }
479         }
480 }
481
482 sub watch_atfork_child ($) {
483         my ($self) = @_;
484         PublicInbox::Sigfd::sig_setmask($self->{oldset});
485         %SIG = (%SIG, %{$self->{sig}});
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                                 watch_atfork_child($self);
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, $sig, $oldset) = @_;
569         $self->{oldset} = $oldset;
570         $self->{sig} = $sig;
571         if ($self->{mdre} && $self->{imap}) {
572                 defined(my $pid = fork) or die "fork: $!";
573                 if ($pid == 0) {
574                         watch_atfork_child($self);
575                         imap_start($self);
576                         goto &watch_imap;
577                 }
578                 $self->{-imap_pid} = $pid;
579         } elsif ($self->{imap}) {
580                 # not a child process, but no signalfd, yet:
581                 watch_atfork_child($self);
582                 imap_start($self);
583                 goto &watch_imap;
584         }
585         goto &watch_fs;
586 }
587
588 sub trigger_scan {
589         my ($self, $op) = @_;
590         push @{$self->{ops}}, $op;
591         PublicInbox::DS::requeue($self);
592 }
593
594 # called directly, and by PublicInbox::DS
595 sub event_step ($) {
596         my ($self) = @_;
597         return if $self->{quit};
598         my $op = shift @{$self->{ops}};
599
600         # continue existing scan
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 ($op && $op eq 'full') {
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         PublicInbox::DS::requeue($self) if keys %$opendirs;
632 }
633
634 sub scan {
635         my ($self, $op) = @_;
636         push @{$self->{ops}}, $op;
637         goto &event_step;
638 }
639
640 sub _importer_for {
641         my ($self, $ibx) = @_;
642         my $importers = $self->{importers};
643         my $im = $importers->{"$ibx"} ||= $ibx->importer(0);
644         if (scalar(keys(%$importers)) > 2) {
645                 delete $importers->{"$ibx"};
646                 _done_for_now($self);
647         }
648
649         $importers->{"$ibx"} = $im;
650 }
651
652 sub _spamcheck_cb {
653         my ($sc) = @_;
654         sub {
655                 my ($mime) = @_;
656                 my $tmp = '';
657                 if ($sc->spamcheck($mime, \$tmp)) {
658                         return PublicInbox::Eml->new(\$tmp);
659                 }
660                 warn $mime->header('Message-ID')." failed spam check\n";
661                 undef;
662         }
663 }
664
665 sub is_maildir {
666         $_[0] =~ s!\Amaildir:!! or return;
667         $_[0] =~ tr!/!/!s;
668         $_[0] =~ s!/\z!!;
669         $_[0];
670 }
671
672 sub is_watchspam {
673         my ($cur, $ws, $ibx) = @_;
674         if ($ws && !ref($ws) && $ws eq 'watchspam') {
675                 warn <<EOF;
676 E: $cur is a spam folder and cannot be used for `$ibx->{name}' input
677 EOF
678                 return 1;
679         }
680         undef;
681 }
682
683 sub imap_url {
684         my ($url) = @_;
685         require PublicInbox::URIimap;
686         my $uri = PublicInbox::URIimap->new($url);
687         $uri ? $uri->canonical->as_string : undef;
688 }
689
690 1;