]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/WatchMaildir.pm
watch: support IMAP polling
[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         for (qw(idle_pids poll_pids)) {
206                 my $pids = $self->{$_} or next;
207                 kill('QUIT', $_) for (keys %$pids);
208         }
209         if (my $idle_mic = $self->{idle_mic}) {
210                 eval { $idle_mic->done };
211                 warn "IDLE DONE error: $@\n" if $@;
212                 eval { $idle_mic->disconnect };
213                 warn "IDLE LOGOUT error: $@\n" if $@;
214         }
215 }
216
217 sub watch_fs_init ($) {
218         my ($self) = @_;
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         require PublicInbox::DirIdle;
228         PublicInbox::DirIdle->new($self->{mdir}, $cb); # EPOLL_CTL_ADD
229 }
230
231 # returns the git config section name, e.g [imap "imaps://user@example.com"]
232 # without the mailbox, so we can share connections between different inboxes
233 sub imap_section ($) {
234         my ($uri) = @_;
235         $uri->scheme . '://' . $uri->authority;
236 }
237
238 sub cfg_intvl ($$) {
239         my ($cfg, $key) = @_;
240         defined(my $v = $cfg->{lc($key)}) or return;
241         $v =~ /\A[0-9]+(?:\.[0-9]+)?\z/s and return $v + 0;
242         if (ref($v) eq 'ARRAY') {
243                 $v = join(', ', @$v);
244                 warn "W: $key has multiple values: $v\nW: $key ignored\n";
245         } else {
246                 warn "W: $key=$v is not a numeric value in seconds\n";
247         }
248 }
249
250 # flesh out common IMAP-specific data structures
251 sub imap_common_init ($) {
252         my ($self) = @_;
253         my $cfg = $self->{config};
254         my $mic_args = {}; # scheme://authority => Mail:IMAPClient arg
255         for my $url (sort keys %{$self->{imap}}) {
256                 my $uri = PublicInbox::URIimap->new($url);
257                 my $sec = imap_section($uri);
258                 for my $k (qw(Starttls Debug Compress)) {
259                         my $key = lc("imap.$sec.$k");
260                         defined(my $orig = $cfg->{$key}) or next;
261                         my $v = PublicInbox::Config::_git_config_bool($orig);
262                         if (defined($v)) {
263                                 $mic_args->{$sec}->{$k} = $v;
264                         } else {
265                                 warn "W: $key=$orig is not boolean\n";
266                         }
267                 }
268                 my $to = cfg_intvl($cfg, "imap.$sec.Timeout");
269                 $mic_args->{$sec}->{Timeout} = $to if $to;
270                 $to = cfg_intvl($cfg, "imap.$sec.PollInterval");
271                 $self->{imap_opt}->{$sec}->{poll_intvl} = $to if $to;
272                 $to = cfg_intvl($cfg, "imap.$sec.IdleInterval");
273                 $self->{imap_opt}->{$sec}->{idle_intvl} = $to if $to;
274         }
275         $mic_args;
276 }
277
278 sub auth_anon_cb { '' }; # for Mail::IMAPClient::Authcallback
279
280 sub mic_for ($$$) { # mic = Mail::IMAPClient
281         my ($self, $uri, $mic_args) = @_;
282         my $url = $uri->as_string;
283         my $cred = {
284                 url => $url,
285                 protocol => $uri->scheme,
286                 host => $uri->host,
287                 username => $uri->user,
288                 password => $uri->password,
289         };
290         my $common = $mic_args->{imap_section($uri)} // {};
291         my $host = $cred->{host};
292         my $mic_arg = {
293                 Port => $uri->port,
294                 # IMAPClient mishandles `0', so we pass `127.0.0.1'
295                 Server => $host eq '0' ? '127.0.0.1' : $host,
296                 Ssl => $uri->scheme eq 'imaps',
297                 Keepalive => 1, # SO_KEEPALIVE
298                 %$common, # may set Starttls, Compress, Debug ....
299         };
300         my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or
301                 die "E: <$url> new: $@\n";
302
303         # default to using STARTTLS if it's available, but allow
304         # it to be disabled since I usually connect to localhost
305         if (!$mic_arg->{Ssl} && !defined($mic_arg->{Starttls}) &&
306                         $mic->has_capability('STARTTLS') &&
307                         $mic->can('starttls')) {
308                 $mic->starttls or die "E: <$url> STARTTLS: $@\n";
309         }
310
311         # do we even need credentials?
312         if (!defined($cred->{username}) &&
313                         $mic->has_capability('AUTH=ANONYMOUS')) {
314                 $cred = undef;
315         }
316         if ($cred) {
317                 Git::credential($cred, 'fill'); # may prompt user here
318                 $mic->User($mic_arg->{User} = $cred->{username});
319                 $mic->Password($mic_arg->{Password} = $cred->{password});
320         } else { # AUTH=ANONYMOUS
321                 $mic->Authmechanism($mic_arg->{Authmechanism} = 'ANONYMOUS');
322                 $mic->Authcallback($mic_arg->{Authcallback} = \&auth_anon_cb);
323         }
324         if ($mic->login && $mic->IsAuthenticated) {
325                 # success! keep IMAPClient->new arg in case we get disconnected
326                 $self->{mic_arg}->{imap_section($uri)} = $mic_arg;
327         } else {
328                 warn "E: <$url> LOGIN: $@\n";
329                 $mic = undef;
330         }
331         Git::credential($cred, $mic ? 'approve' : 'reject') if $cred;
332         $mic;
333 }
334
335 sub imap_fetch_all ($$$) {
336         my ($self, $mic, $uri) = @_;
337         my $sec = imap_section($uri);
338         my $mbx = $uri->mailbox;
339         my $url = $uri->as_string;
340         $mic->Clear(1); # trim results history
341         $mic->examine($mbx) or return "E: EXAMINE $mbx ($sec) failed: $!";
342         my ($r_uidval, $r_uidnext);
343         for ($mic->Results) {
344                 /^\* OK \[UIDVALIDITY ([0-9]+)\].*/ and $r_uidval = $1;
345                 /^\* OK \[UIDNEXT ([0-9]+)\].*/ and $r_uidnext = $1;
346                 last if $r_uidval && $r_uidnext;
347         }
348         $r_uidval //= $mic->uidvalidity($mbx) //
349                 return "E: $url cannot get UIDVALIDITY";
350         $r_uidnext //= $mic->uidnext($mbx) //
351                 return "E: $url cannot get UIDNEXT";
352         my $itrk = PublicInbox::IMAPTracker->new;
353         my ($l_uidval, $l_uid) = $itrk->get_last($url);
354         $l_uidval //= $r_uidval; # first time
355         $l_uid //= 1;
356         if ($l_uidval != $r_uidval) {
357                 return "E: $url UIDVALIDITY mismatch\n".
358                         "E: local=$l_uidval != remote=$r_uidval";
359         }
360         my $r_uid = $r_uidnext - 1;
361         if ($l_uid != 1 && $l_uid > $r_uid) {
362                 return "E: $url local UID exceeds remote ($l_uid > $r_uid)\n".
363                         "E: $url strangely, UIDVALIDLITY matches ($l_uidval)\n";
364         }
365         return if $l_uid >= $r_uid; # nothing to do
366
367         $mic->Uid(1); # the default, we hope
368         my $req = $mic->imap4rev1 ? 'BODY.PEEK[]' : 'RFC822.PEEK';
369         my $key = $req;
370         $key =~ s/\.PEEK//;
371         my $inboxes = $self->{imap}->{$url};
372         warn "I: $url fetching $l_uid..$r_uid\n";
373         my $uid = -1;
374         my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
375         local $SIG{__WARN__} = sub {
376                 $warn_cb->("$url UID:$uid\n");
377                 $warn_cb->(@_);
378         };
379         my $err;
380         $itrk->{dbh}->begin_work;
381         for my $u ($l_uid..$r_uid) {
382                 $uid = $u;
383                 local $0 = "UID:$uid $mbx $sec";
384                 my $r = $mic->fetch_hash($uid, $req);
385                 unless ($r) { # network error?
386                         $err = "E: $url UID FETCH $uid error: $!\n";
387                         last;
388                 }
389
390                 # messages get deleted, so holes appear
391                 defined(my $raw = delete $r->{$uid}->{$key}) or next;
392
393                 # our target audience expects LF-only, save storage
394                 $raw =~ s/\r\n/\n/sg;
395
396                 if (ref($inboxes)) {
397                         for my $ibx (@$inboxes) {
398                                 my $eml = PublicInbox::Eml->new($raw);
399                                 my $x = import_eml($self, $ibx, $eml);
400                         }
401                 } elsif ($inboxes eq 'watchspam') {
402                         my $eml = PublicInbox::Eml->new($raw);
403                         my $arg = [ $self, $eml, "$uri UID:$uid" ];
404                         $self->{config}->each_inbox(\&remove_eml_i, $arg);
405                 } else {
406                         die "BUG: destination unknown $inboxes";
407                 }
408                 $itrk->update_last($url, $r_uidval, $uid);
409                 last if $self->{quit};
410         }
411         _done_for_now($self);
412         $itrk->{dbh}->commit;
413         $err;
414 }
415
416 sub imap_idle_once ($$$$) {
417         my ($self, $mic, $intvl, $url) = @_;
418         my $i = $intvl //= (29 * 60);
419         my $end = now() + $intvl;
420         warn "I: $url idling for ${intvl}s\n";
421         local $0 = "IDLE $0";
422         unless ($mic->idle) {
423                 return if $self->{quit};
424                 return "E: IDLE failed on $url: $!";
425         }
426         $self->{idle_mic} = $mic; # for ->quit
427         my @res;
428         until ($self->{quit} || grep(/^\* [0-9]+ EXISTS/, @res) || $i <= 0) {
429                 @res = $mic->idle_data($i);
430                 $i = $end - now();
431         }
432         delete $self->{idle_mic};
433         unless ($self->{quit}) {
434                 $mic->IsConnected or return "E: IDLE disconnected on $url";
435                 $mic->done or return "E: IDLE DONE failed on $url: $!";
436         }
437         undef;
438 }
439
440 # idles on a single URI
441 sub watch_imap_idle_1 ($$$) {
442         my ($self, $uri, $intvl) = @_;
443         my $sec = imap_section($uri);
444         my $mic_arg = $self->{mic_arg}->{$sec} or
445                         die "BUG: no Mail::IMAPClient->new arg for $sec";
446         my $mic;
447         local $0 = $uri->mailbox." $sec";
448         until ($self->{quit}) {
449                 $mic //= delete($self->{mics}->{$sec}) //
450                                 PublicInbox::IMAPClient->new(%$mic_arg);
451                 my $err = imap_fetch_all($self, $mic, $uri);
452                 $err //= imap_idle_once($self, $mic, $intvl, $uri->as_string);
453                 if ($err && !$self->{quit}) {
454                         warn $err, "\n";
455                         $mic = undef;
456                         sleep 60 unless $self->{quit};
457                 }
458         }
459 }
460
461 sub watch_atfork_child ($) {
462         my ($self) = @_;
463         delete $self->{idle_pids};
464         delete $self->{poll_pids};
465         PublicInbox::DS->Reset;
466         PublicInbox::Sigfd::sig_setmask($self->{oldset});
467         %SIG = (%SIG, %{$self->{sig}});
468 }
469
470 sub imap_idle_reap { # PublicInbox::DS::dwaitpid callback
471         my ($self, $pid) = @_;
472         my $uri_intvl = delete $self->{idle_pids}->{$pid} or
473                 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
474
475         my ($uri, $intvl) = @$uri_intvl;
476         my $url = $uri->as_string;
477         return if $self->{quit};
478         warn "W: PID=$pid on $url died: \$?=$?\n" if $?;
479         push @{$self->{idle_todo}}, $uri_intvl;
480         PubicInbox::DS::requeue($self); # call ->event_step to respawn
481 }
482
483 sub imap_idle_fork ($$) {
484         my ($self, $uri_intvl) = @_;
485         my ($uri, $intvl) = @$uri_intvl;
486         defined(my $pid = fork) or die "fork: $!";
487         if ($pid == 0) {
488                 watch_atfork_child($self);
489                 watch_imap_idle_1($self, $uri, $intvl);
490                 _exit(0);
491         }
492         $self->{idle_pids}->{$pid} = $uri_intvl;
493         PublicInbox::DS::dwaitpid($pid, \&imap_idle_reap, $self);
494 }
495
496 sub event_step {
497         my ($self) = @_;
498         return if $self->{quit};
499         my $idle_todo = $self->{idle_todo};
500         if ($idle_todo && @$idle_todo) {
501                 $self->{mics} = {}; # going to be forking, so disconnect
502                 while (my $uri_intvl = shift(@$idle_todo)) {
503                         imap_idle_fork($self, $uri_intvl);
504                 }
505         }
506         goto(&fs_scan_step) if $self->{mdre};
507 }
508
509 sub watch_imap_fetch_all ($$) {
510         my ($self, $uris) = @_;
511         for my $uri (@$uris) {
512                 my $sec = imap_section($uri);
513                 my $mic_arg = $self->{mic_arg}->{$sec} or
514                         die "BUG: no Mail::IMAPClient->new arg for $sec";
515                 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or next;
516                 my $err = imap_fetch_all($self, $mic, $uri);
517                 last if $self->{quit};
518                 warn $err, "\n" if $err;
519         }
520 }
521
522 sub imap_fetch_fork ($$$) {
523         my ($self, $intvl, $uris) = @_;
524         return if $self->{quit};
525         $self->{mics} = {}; # going to be forking, so disconnect
526         defined(my $pid = fork) or die "fork: $!";
527         if ($pid == 0) {
528                 watch_atfork_child($self);
529                 watch_imap_fetch_all($self, $uris);
530                 _exit(0);
531         }
532         $self->{poll_pids}->{$pid} = [ $intvl, $uris ];
533         PublicInbox::DS::dwaitpid($pid, \&imap_fetch_reap, $self);
534 }
535
536 sub imap_fetch_cb ($$$) {
537         my ($self, $intvl, $uris) = @_;
538         sub { imap_fetch_fork($self, $intvl, $uris) };
539 }
540
541 sub imap_fetch_reap { # PublicInbox::DS::dwaitpid callback
542         my ($self, $pid) = @_;
543         my $intvl_uris = delete $self->{poll_pids}->{$pid} or
544                 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
545         return if $self->{quit};
546         my ($intvl, $uris) = @$intvl_uris;
547         if ($?) {
548                 warn "W: PID=$pid died: \$?=$?\n",
549                         map { $_->as_string."\n" } @$uris;
550         }
551         warn('I: will check ', $_->as_string, " in ${intvl}s\n") for @$uris;
552         PublicInbox::DS::add_timer($intvl, imap_fetch_cb($self, $intvl, $uris));
553 }
554
555 sub watch_imap_init ($) {
556         my ($self) = @_;
557         eval { require PublicInbox::IMAPClient } or
558                 die "Mail::IMAPClient is required for IMAP:\n$@\n";
559         eval { require Git } or
560                 die "Git (Perl module) is required for IMAP:\n$@\n";
561         eval { require PublicInbox::IMAPTracker } or
562                 die "DBD::SQLite is required for IMAP\n:$@\n";
563
564         my $mic_args = imap_common_init($self); # read args from config
565
566         # make sure we can connect and cache the credentials in memory
567         $self->{mic_arg} = {}; # schema://authority => IMAPClient->new args
568         my $mics = $self->{mics} = {}; # schema://authority => IMAPClient obj
569         for my $url (sort keys %{$self->{imap}}) {
570                 my $uri = PublicInbox::URIimap->new($url);
571                 $mics->{imap_section($uri)} //= mic_for($self, $uri, $mic_args);
572         }
573
574         my $idle = []; # [ [ uri1, intvl1 ], [uri2, intvl2] ]
575         my $poll = {}; # intvl_seconds => [ uri1, uri2 ]
576         for my $url (keys %{$self->{imap}}) {
577                 my $uri = PublicInbox::URIimap->new($url);
578                 my $sec = imap_section($uri);
579                 my $mic = $mics->{$sec};
580                 my $intvl = $self->{imap_opt}->{$sec}->{poll_intvl};
581                 if ($mic->has_capability('IDLE') && !$intvl) {
582                         $intvl = $self->{imap_opt}->{$sec}->{idle_intvl};
583                         push @$idle, [ $uri, $intvl // () ];
584                 } else {
585                         push @{$poll->{$intvl || 120}}, $uri;
586                 }
587         }
588         if (scalar @$idle) {
589                 $self->{idle_pids} = {};
590                 $self->{idle_todo} = $idle;
591                 PublicInbox::DS::requeue($self); # ->event_step to fork
592         }
593         return unless scalar keys %$poll;
594         $self->{poll_pids} = {};
595
596         # poll all URIs for a given interval sequentially
597         while (my ($intvl, $uris) = each %$poll) {
598                 PublicInbox::DS::requeue(imap_fetch_cb($self, $intvl, $uris));
599         }
600 }
601
602 sub watch {
603         my ($self, $sig, $oldset) = @_;
604         $self->{oldset} = $oldset;
605         $self->{sig} = $sig;
606         watch_imap_init($self) if $self->{imap};
607         watch_fs_init($self) if $self->{mdre};
608         PublicInbox::DS->SetPostLoopCallback(sub {});
609         PublicInbox::DS->EventLoop until $self->{quit};
610         _done_for_now($self);
611 }
612
613 sub trigger_scan {
614         my ($self, $op) = @_;
615         push @{$self->{ops}}, $op;
616         PublicInbox::DS::requeue($self);
617 }
618
619 sub fs_scan_step {
620         my ($self) = @_;
621         return if $self->{quit};
622         my $op = shift @{$self->{ops}};
623
624         # continue existing scan
625         my $max = 10;
626         my $opendirs = $self->{opendirs};
627         my @dirnames = keys %$opendirs;
628         foreach my $dir (@dirnames) {
629                 my $dh = delete $opendirs->{$dir};
630                 my $n = $max;
631                 while (my $fn = readdir($dh)) {
632                         _try_path($self, "$dir/$fn");
633                         last if --$n < 0;
634                 }
635                 $opendirs->{$dir} = $dh if $n < 0;
636         }
637         if ($op && $op eq 'full') {
638                 foreach my $dir (@{$self->{mdir}}) {
639                         next if $opendirs->{$dir}; # already in progress
640                         my $ok = opendir(my $dh, $dir);
641                         unless ($ok) {
642                                 warn "failed to open $dir: $!\n";
643                                 next;
644                         }
645                         my $n = $max;
646                         while (my $fn = readdir($dh)) {
647                                 _try_path($self, "$dir/$fn");
648                                 last if --$n < 0;
649                         }
650                         $opendirs->{$dir} = $dh if $n < 0;
651                 }
652         }
653         _done_for_now($self);
654         # do we have more work to do?
655         PublicInbox::DS::requeue($self) if keys %$opendirs;
656 }
657
658 sub scan {
659         my ($self, $op) = @_;
660         push @{$self->{ops}}, $op;
661         goto &fs_scan_step;
662 }
663
664 sub _importer_for {
665         my ($self, $ibx) = @_;
666         my $importers = $self->{importers};
667         my $im = $importers->{"$ibx"} ||= $ibx->importer(0);
668         if (scalar(keys(%$importers)) > 2) {
669                 delete $importers->{"$ibx"};
670                 _done_for_now($self);
671         }
672
673         $importers->{"$ibx"} = $im;
674 }
675
676 sub _spamcheck_cb {
677         my ($sc) = @_;
678         sub {
679                 my ($mime) = @_;
680                 my $tmp = '';
681                 if ($sc->spamcheck($mime, \$tmp)) {
682                         return PublicInbox::Eml->new(\$tmp);
683                 }
684                 warn $mime->header('Message-ID')." failed spam check\n";
685                 undef;
686         }
687 }
688
689 sub is_maildir {
690         $_[0] =~ s!\Amaildir:!! or return;
691         $_[0] =~ tr!/!/!s;
692         $_[0] =~ s!/\z!!;
693         $_[0];
694 }
695
696 sub is_watchspam {
697         my ($cur, $ws, $ibx) = @_;
698         if ($ws && !ref($ws) && $ws eq 'watchspam') {
699                 warn <<EOF;
700 E: $cur is a spam folder and cannot be used for `$ibx->{name}' input
701 EOF
702                 return 1;
703         }
704         undef;
705 }
706
707 sub imap_url {
708         my ($url) = @_;
709         require PublicInbox::URIimap;
710         my $uri = PublicInbox::URIimap->new($url);
711         $uri ? $uri->canonical->as_string : undef;
712 }
713
714 1;