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