]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/WatchMaildir.pm
watch: remove {mdir} array
[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, $spamc);
44         my %imap; # url => [inbox objects] or 'watchspam'
45
46         # "publicinboxwatch" is the documented namespace
47         # "publicinboxlearn" is legacy but may be supported
48         # indefinitely...
49         foreach my $pfx (qw(publicinboxwatch publicinboxlearn)) {
50                 my $k = "$pfx.watchspam";
51                 defined(my $dirs = $config->{$k}) or next;
52                 $dirs = PublicInbox::Config::_array($dirs);
53                 for my $dir (@$dirs) {
54                         if (is_maildir($dir)) {
55                                 # skip "new", no MUA has seen it, yet.
56                                 $mdmap{"$dir/cur"} = 'watchspam';
57                         } elsif (my $url = imap_url($dir)) {
58                                 $imap{$url} = 'watchspam';
59                         } else {
60                                 warn "unsupported $k=$dir\n";
61                         }
62                 }
63         }
64
65         my $k = 'publicinboxwatch.spamcheck';
66         my $default = undef;
67         my $spamcheck = PublicInbox::Spamcheck::get($config, $k, $default);
68         $spamcheck = _spamcheck_cb($spamcheck) if $spamcheck;
69
70         $config->each_inbox(sub {
71                 # need to make all inboxes writable for spam removal:
72                 my $ibx = $_[0] = PublicInbox::InboxWritable->new($_[0]);
73
74                 my $watches = $ibx->{watch} or return;
75                 $watches = PublicInbox::Config::_array($watches);
76                 for my $watch (@$watches) {
77                         if (is_maildir($watch)) {
78                                 compile_watchheaders($ibx);
79                                 my ($new, $cur) = ("$watch/new", "$watch/cur");
80                                 my $cur_dst = $mdmap{$cur} //= [];
81                                 return if is_watchspam($cur, $cur_dst, $ibx);
82                                 push @{$mdmap{$new} //= []}, $ibx;
83                                 push @$cur_dst, $ibx;
84                         } elsif (my $url = imap_url($watch)) {
85                                 return if is_watchspam($url, $imap{$url}, $ibx);
86                                 compile_watchheaders($ibx);
87                                 push @{$imap{$url} ||= []}, $ibx;
88                         } else {
89                                 warn "watch unsupported: $k=$watch\n";
90                         }
91                 }
92         });
93
94         my $mdre;
95         if (scalar keys %mdmap) {
96                 $mdre = join('|', map { quotemeta($_) } keys %mdmap);
97                 $mdre = qr!\A($mdre)/!;
98         }
99         return unless $mdre || scalar(keys %imap);
100         bless {
101                 spamcheck => $spamcheck,
102                 mdmap => \%mdmap,
103                 mdre => $mdre,
104                 config => $config,
105                 imap => scalar keys %imap ? \%imap : undef,
106                 importers => {},
107                 opendirs => {}, # dirname => dirhandle (in progress scans)
108                 ops => [], # 'quit', 'full'
109         }, $class;
110 }
111
112 sub _done_for_now {
113         my ($self) = @_;
114         my $importers = $self->{importers};
115         foreach my $im (values %$importers) {
116                 $im->done;
117         }
118 }
119
120 sub remove_eml_i { # each_inbox callback
121         my ($ibx, $arg) = @_;
122         my ($self, $eml, $loc) = @$arg;
123         eval {
124                 my $im = _importer_for($self, $ibx);
125                 $im->remove($eml, 'spam');
126                 if (my $scrub = $ibx->filter($im)) {
127                         my $scrubbed = $scrub->scrub($eml, 1);
128                         $scrubbed or return;
129                         $scrubbed == REJECT() and return;
130                         $im->remove($scrubbed, 'spam');
131                 }
132         };
133         warn "error removing spam at: $loc from $ibx->{name}: $@\n" if $@;
134 }
135
136 sub _remove_spam {
137         my ($self, $path) = @_;
138         # path must be marked as (S)een
139         $path =~ /:2,[A-R]*S[T-Za-z]*\z/ or return;
140         my $eml = mime_from_path($path) or return;
141         $self->{config}->each_inbox(\&remove_eml_i, [ $self, $eml, $path ]);
142 }
143
144 sub import_eml ($$$) {
145         my ($self, $ibx, $eml) = @_;
146         my $im = _importer_for($self, $ibx);
147
148         # any header match means it's eligible for the inbox:
149         if (my $watch_hdrs = $ibx->{-watchheaders}) {
150                 my $ok;
151                 my $hdr = $eml->header_obj;
152                 for my $wh (@$watch_hdrs) {
153                         my @v = $hdr->header_raw($wh->[0]);
154                         $ok = grep(/$wh->[1]/, @v) and last;
155                 }
156                 return unless $ok;
157         }
158
159         if (my $scrub = $ibx->filter($im)) {
160                 my $ret = $scrub->scrub($eml) or return;
161                 $ret == REJECT() and return;
162                 $eml = $ret;
163         }
164         $im->add($eml, $self->{spamcheck});
165 }
166
167 sub _try_path {
168         my ($self, $path) = @_;
169         return unless PublicInbox::InboxWritable::is_maildir_path($path);
170         if ($path !~ $self->{mdre}) {
171                 warn "unrecognized path: $path\n";
172                 return;
173         }
174         my $inboxes = $self->{mdmap}->{$1};
175         unless ($inboxes) {
176                 warn "unmappable dir: $1\n";
177                 return;
178         }
179         if (!ref($inboxes) && $inboxes eq 'watchspam') {
180                 return _remove_spam($self, $path);
181         }
182
183         my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
184         local $SIG{__WARN__} = sub {
185                 $warn_cb->("path: $path\n");
186                 $warn_cb->(@_);
187         };
188         foreach my $ibx (@$inboxes) {
189                 my $eml = mime_from_path($path) or next;
190                 import_eml($self, $ibx, $eml);
191         }
192 }
193
194 sub quit {
195         my ($self) = @_;
196         $self->{quit} = 1;
197         %{$self->{opendirs}} = ();
198         _done_for_now($self);
199         if (my $imap_pid = $self->{-imap_pid}) {
200                 kill('QUIT', $imap_pid);
201         }
202         for (qw(idle_pids poll_pids)) {
203                 my $pids = $self->{$_} or next;
204                 kill('QUIT', $_) for (keys %$pids);
205         }
206         if (my $idle_mic = $self->{idle_mic}) {
207                 eval { $idle_mic->done };
208                 if ($@) {
209                         warn "IDLE DONE error: $@\n";
210                         eval { $idle_mic->disconnect };
211                         warn "IDLE LOGOUT error: $@\n" if $@;
212                 }
213         }
214 }
215
216 sub watch_fs_init ($) {
217         my ($self) = @_;
218         my $done = sub {
219                 delete $self->{done_timer};
220                 _done_for_now($self);
221         };
222         my $cb = sub {
223                 _try_path($self, $_[0]->fullname);
224                 $self->{done_timer} //= PublicInbox::DS::requeue($done);
225         };
226         require PublicInbox::DirIdle;
227         # inotify_create + EPOLL_CTL_ADD
228         PublicInbox::DirIdle->new([keys %{$self->{mdmap}}], $cb);
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                 my $key = lc("imap.$sec.fetchBatchSize");
279                 my $bs = $cfg->{lc($key)} //
280                         $cfg->urlmatch('imap.fetchBatchSize', $url) // next;
281                 if ($bs =~ /\A([0-9]+)\z/) {
282                         $self->{imap_opt}->{$sec}->{batch_size} = $bs;
283                 } else {
284                         warn "W: $key=$bs is not an integer\n";
285                 }
286         }
287         $mic_args;
288 }
289
290 sub auth_anon_cb { '' }; # for Mail::IMAPClient::Authcallback
291
292 sub mic_for ($$$) { # mic = Mail::IMAPClient
293         my ($self, $uri, $mic_args) = @_;
294         my $url = $uri->as_string;
295         my $cred = {
296                 url => $url,
297                 protocol => $uri->scheme,
298                 host => $uri->host,
299                 username => $uri->user,
300                 password => $uri->password,
301         };
302         my $common = $mic_args->{imap_section($uri)} // {};
303         my $host = $cred->{host};
304         my $mic_arg = {
305                 Port => $uri->port,
306                 # IMAPClient mishandles `0', so we pass `127.0.0.1'
307                 Server => $host eq '0' ? '127.0.0.1' : $host,
308                 Ssl => $uri->scheme eq 'imaps',
309                 Keepalive => 1, # SO_KEEPALIVE
310                 %$common, # may set Starttls, Compress, Debug ....
311         };
312         my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or
313                 die "E: <$url> new: $@\n";
314
315         # default to using STARTTLS if it's available, but allow
316         # it to be disabled since I usually connect to localhost
317         if (!$mic_arg->{Ssl} && !defined($mic_arg->{Starttls}) &&
318                         $mic->has_capability('STARTTLS') &&
319                         $mic->can('starttls')) {
320                 $mic->starttls or die "E: <$url> STARTTLS: $@\n";
321         }
322
323         # do we even need credentials?
324         if (!defined($cred->{username}) &&
325                         $mic->has_capability('AUTH=ANONYMOUS')) {
326                 $cred = undef;
327         }
328         if ($cred) {
329                 Git::credential($cred, 'fill'); # may prompt user here
330                 $mic->User($mic_arg->{User} = $cred->{username});
331                 $mic->Password($mic_arg->{Password} = $cred->{password});
332         } else { # AUTH=ANONYMOUS
333                 $mic->Authmechanism($mic_arg->{Authmechanism} = 'ANONYMOUS');
334                 $mic->Authcallback($mic_arg->{Authcallback} = \&auth_anon_cb);
335         }
336         if ($mic->login && $mic->IsAuthenticated) {
337                 # success! keep IMAPClient->new arg in case we get disconnected
338                 $self->{mic_arg}->{imap_section($uri)} = $mic_arg;
339         } else {
340                 warn "E: <$url> LOGIN: $@\n";
341                 $mic = undef;
342         }
343         Git::credential($cred, $mic ? 'approve' : 'reject') if $cred;
344         $mic;
345 }
346
347 sub imap_import_msg ($$$$) {
348         my ($self, $url, $uid, $raw) = @_;
349         # our target audience expects LF-only, save storage
350         $$raw =~ s/\r\n/\n/sg;
351
352         my $inboxes = $self->{imap}->{$url};
353         if (ref($inboxes)) {
354                 for my $ibx (@$inboxes) {
355                         my $eml = PublicInbox::Eml->new($$raw);
356                         my $x = import_eml($self, $ibx, $eml);
357                 }
358         } elsif ($inboxes eq 'watchspam') {
359                 my $eml = PublicInbox::Eml->new($raw);
360                 my $arg = [ $self, $eml, "$url UID:$uid" ];
361                 $self->{config}->each_inbox(\&remove_eml_i, $arg);
362         } else {
363                 die "BUG: destination unknown $inboxes";
364         }
365 }
366
367 sub imap_fetch_all ($$$) {
368         my ($self, $mic, $uri) = @_;
369         my $sec = imap_section($uri);
370         my $mbx = $uri->mailbox;
371         my $url = $uri->as_string;
372         $mic->Clear(1); # trim results history
373         $mic->examine($mbx) or return "E: EXAMINE $mbx ($sec) failed: $!";
374         my ($r_uidval, $r_uidnext);
375         for ($mic->Results) {
376                 /^\* OK \[UIDVALIDITY ([0-9]+)\].*/ and $r_uidval = $1;
377                 /^\* OK \[UIDNEXT ([0-9]+)\].*/ and $r_uidnext = $1;
378                 last if $r_uidval && $r_uidnext;
379         }
380         $r_uidval //= $mic->uidvalidity($mbx) //
381                 return "E: $url cannot get UIDVALIDITY";
382         $r_uidnext //= $mic->uidnext($mbx) //
383                 return "E: $url cannot get UIDNEXT";
384         my $itrk = PublicInbox::IMAPTracker->new($url);
385         my ($l_uidval, $l_uid) = $itrk->get_last;
386         $l_uidval //= $r_uidval; # first time
387         $l_uid //= 1;
388         if ($l_uidval != $r_uidval) {
389                 return "E: $url UIDVALIDITY mismatch\n".
390                         "E: local=$l_uidval != remote=$r_uidval";
391         }
392         my $r_uid = $r_uidnext - 1;
393         if ($l_uid != 1 && $l_uid > $r_uid) {
394                 return "E: $url local UID exceeds remote ($l_uid > $r_uid)\n".
395                         "E: $url strangely, UIDVALIDLITY matches ($l_uidval)\n";
396         }
397         return if $l_uid >= $r_uid; # nothing to do
398
399         warn "I: $url fetching UID $l_uid:$r_uid\n";
400         $mic->Uid(1); # the default, we hope
401         my $bs = $self->{imap_opt}->{$sec}->{batch_size} // 1;
402         my $req = $mic->imap4rev1 ? 'BODY.PEEK[]' : 'RFC822.PEEK';
403
404         # TODO: FLAGS may be useful for personal use
405         my $key = $req;
406         $key =~ s/\.PEEK//;
407         my ($uids, $batch);
408         my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
409         local $SIG{__WARN__} = sub {
410                 $batch //= '?';
411                 $warn_cb->("$url UID:$batch\n");
412                 $warn_cb->(@_);
413         };
414         my $err;
415         do {
416                 # I wish "UID FETCH $START:*" could work, but:
417                 # 1) servers do not need to return results in any order
418                 # 2) Mail::IMAPClient doesn't offer a streaming API
419                 $uids = $mic->search("UID $l_uid:*") or
420                         return "E: $url UID SEARCH $l_uid:* error: $!";
421                 return if scalar(@$uids) == 0;
422
423                 # RFC 3501 doesn't seem to indicate order of UID SEARCH
424                 # responses, so sort it ourselves.  Order matters so
425                 # IMAPTracker can store the newest UID.
426                 @$uids = sort { $a <=> $b } @$uids;
427
428                 # Did we actually get new messages?
429                 return if $uids->[0] < $l_uid;
430
431                 $l_uid = $uids->[-1] + 1; # for next search
432                 my $last_uid;
433
434                 while (scalar @$uids) {
435                         my @batch = splice(@$uids, 0, $bs);
436                         $batch = join(',', @batch);
437                         local $0 = "UID:$batch $mbx $sec";
438                         my $r = $mic->fetch_hash($batch, $req);
439                         unless ($r) { # network error?
440                                 $err = "E: $url UID FETCH $batch error: $!";
441                                 last;
442                         }
443                         for my $uid (@batch) {
444                                 # messages get deleted, so holes appear
445                                 my $per_uid = delete $r->{$uid} // next;
446                                 my $raw = delete($per_uid->{$key}) // next;
447                                 imap_import_msg($self, $url, $uid, \$raw);
448                                 $last_uid = $uid;
449                                 last if $self->{quit};
450                         }
451                         last if $self->{quit};
452                 }
453                 _done_for_now($self);
454                 $itrk->update_last($r_uidval, $last_uid) if defined $last_uid;
455         } until ($err || $self->{quit});
456         $err;
457 }
458
459 sub imap_idle_once ($$$$) {
460         my ($self, $mic, $intvl, $url) = @_;
461         my $i = $intvl //= (29 * 60);
462         my $end = now() + $intvl;
463         warn "I: $url idling for ${intvl}s\n";
464         local $0 = "IDLE $0";
465         unless ($mic->idle) {
466                 return if $self->{quit};
467                 return "E: IDLE failed on $url: $!";
468         }
469         $self->{idle_mic} = $mic; # for ->quit
470         my @res;
471         until ($self->{quit} || grep(/^\* [0-9]+ EXISTS/, @res) || $i <= 0) {
472                 @res = $mic->idle_data($i);
473                 $i = $end - now();
474         }
475         delete $self->{idle_mic};
476         unless ($self->{quit}) {
477                 $mic->IsConnected or return "E: IDLE disconnected on $url";
478                 $mic->done or return "E: IDLE DONE failed on $url: $!";
479         }
480         undef;
481 }
482
483 # idles on a single URI
484 sub watch_imap_idle_1 ($$$) {
485         my ($self, $uri, $intvl) = @_;
486         my $sec = imap_section($uri);
487         my $mic_arg = $self->{mic_arg}->{$sec} or
488                         die "BUG: no Mail::IMAPClient->new arg for $sec";
489         my $mic;
490         local $0 = $uri->mailbox." $sec";
491         until ($self->{quit}) {
492                 $mic //= delete($self->{mics}->{$sec}) //
493                                 PublicInbox::IMAPClient->new(%$mic_arg);
494                 my $err = imap_fetch_all($self, $mic, $uri);
495                 $err //= imap_idle_once($self, $mic, $intvl, $uri->as_string);
496                 if ($err && !$self->{quit}) {
497                         warn $err, "\n";
498                         $mic = undef;
499                         sleep 60 unless $self->{quit};
500                 }
501         }
502 }
503
504 sub watch_atfork_child ($) {
505         my ($self) = @_;
506         delete $self->{idle_pids};
507         delete $self->{poll_pids};
508         delete $self->{opendirs};
509         PublicInbox::DS->Reset;
510         PublicInbox::Sigfd::sig_setmask($self->{oldset});
511         %SIG = (%SIG, %{$self->{sig}});
512 }
513
514 sub watch_atfork_parent ($) {
515         my ($self) = @_;
516         _done_for_now($self);
517         $self->{mics} = {}; # going to be forking, so disconnect
518 }
519
520 sub imap_idle_reap { # PublicInbox::DS::dwaitpid callback
521         my ($self, $pid) = @_;
522         my $uri_intvl = delete $self->{idle_pids}->{$pid} or
523                 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
524
525         my ($uri, $intvl) = @$uri_intvl;
526         my $url = $uri->as_string;
527         return if $self->{quit};
528         warn "W: PID=$pid on $url died: \$?=$?\n" if $?;
529         push @{$self->{idle_todo}}, $uri_intvl;
530         PubicInbox::DS::requeue($self); # call ->event_step to respawn
531 }
532
533 sub imap_idle_fork ($$) {
534         my ($self, $uri_intvl) = @_;
535         my ($uri, $intvl) = @$uri_intvl;
536         defined(my $pid = fork) or die "fork: $!";
537         if ($pid == 0) {
538                 watch_atfork_child($self);
539                 watch_imap_idle_1($self, $uri, $intvl);
540                 _exit(0);
541         }
542         $self->{idle_pids}->{$pid} = $uri_intvl;
543         PublicInbox::DS::dwaitpid($pid, \&imap_idle_reap, $self);
544 }
545
546 sub event_step {
547         my ($self) = @_;
548         return if $self->{quit};
549         my $idle_todo = $self->{idle_todo};
550         if ($idle_todo && @$idle_todo) {
551                 watch_atfork_parent($self);
552                 while (my $uri_intvl = shift(@$idle_todo)) {
553                         imap_idle_fork($self, $uri_intvl);
554                 }
555         }
556         goto(&fs_scan_step) if $self->{mdre};
557 }
558
559 sub watch_imap_fetch_all ($$) {
560         my ($self, $uris) = @_;
561         for my $uri (@$uris) {
562                 my $sec = imap_section($uri);
563                 my $mic_arg = $self->{mic_arg}->{$sec} or
564                         die "BUG: no Mail::IMAPClient->new arg for $sec";
565                 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or next;
566                 my $err = imap_fetch_all($self, $mic, $uri);
567                 last if $self->{quit};
568                 warn $err, "\n" if $err;
569         }
570 }
571
572 sub imap_fetch_fork ($) { # DS::add_timer callback
573         my ($self, $intvl, $uris) = @{$_[0]};
574         return if $self->{quit};
575         watch_atfork_parent($self);
576         defined(my $pid = fork) or die "fork: $!";
577         if ($pid == 0) {
578                 watch_atfork_child($self);
579                 watch_imap_fetch_all($self, $uris);
580                 _exit(0);
581         }
582         $self->{poll_pids}->{$pid} = [ $intvl, $uris ];
583         PublicInbox::DS::dwaitpid($pid, \&imap_fetch_reap, $self);
584 }
585
586 sub imap_fetch_reap { # PublicInbox::DS::dwaitpid callback
587         my ($self, $pid) = @_;
588         my $intvl_uris = delete $self->{poll_pids}->{$pid} or
589                 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
590         return if $self->{quit};
591         my ($intvl, $uris) = @$intvl_uris;
592         if ($?) {
593                 warn "W: PID=$pid died: \$?=$?\n",
594                         map { $_->as_string."\n" } @$uris;
595         }
596         warn('I: will check ', $_->as_string, " in ${intvl}s\n") for @$uris;
597         PublicInbox::DS::add_timer($intvl, \&imap_fetch_fork,
598                                         [$self, $intvl, $uris]);
599 }
600
601 sub watch_imap_init ($) {
602         my ($self) = @_;
603         eval { require PublicInbox::IMAPClient } or
604                 die "Mail::IMAPClient is required for IMAP:\n$@\n";
605         eval { require Git } or
606                 die "Git (Perl module) is required for IMAP:\n$@\n";
607         eval { require PublicInbox::IMAPTracker } or
608                 die "DBD::SQLite is required for IMAP\n:$@\n";
609
610         my $mic_args = imap_common_init($self); # read args from config
611
612         # make sure we can connect and cache the credentials in memory
613         $self->{mic_arg} = {}; # schema://authority => IMAPClient->new args
614         my $mics = $self->{mics} = {}; # schema://authority => IMAPClient obj
615         for my $url (sort keys %{$self->{imap}}) {
616                 my $uri = PublicInbox::URIimap->new($url);
617                 $mics->{imap_section($uri)} //= mic_for($self, $uri, $mic_args);
618         }
619
620         my $idle = []; # [ [ uri1, intvl1 ], [uri2, intvl2] ]
621         my $poll = {}; # intvl_seconds => [ uri1, uri2 ]
622         for my $url (keys %{$self->{imap}}) {
623                 my $uri = PublicInbox::URIimap->new($url);
624                 my $sec = imap_section($uri);
625                 my $mic = $mics->{$sec};
626                 my $intvl = $self->{imap_opt}->{$sec}->{poll_intvl};
627                 if ($mic->has_capability('IDLE') && !$intvl) {
628                         $intvl = $self->{imap_opt}->{$sec}->{idle_intvl};
629                         push @$idle, [ $uri, $intvl // () ];
630                 } else {
631                         push @{$poll->{$intvl || 120}}, $uri;
632                 }
633         }
634         if (scalar @$idle) {
635                 $self->{idle_pids} = {};
636                 $self->{idle_todo} = $idle;
637                 PublicInbox::DS::requeue($self); # ->event_step to fork
638         }
639         return unless scalar keys %$poll;
640         $self->{poll_pids} = {};
641
642         # poll all URIs for a given interval sequentially
643         while (my ($intvl, $uris) = each %$poll) {
644                 PublicInbox::DS::add_timer(0, \&imap_fetch_fork,
645                                                 [$self, $intvl, $uris]);
646         }
647 }
648
649 sub watch {
650         my ($self, $sig, $oldset) = @_;
651         $self->{oldset} = $oldset;
652         $self->{sig} = $sig;
653         watch_imap_init($self) if $self->{imap};
654         watch_fs_init($self) if $self->{mdre};
655         PublicInbox::DS->SetPostLoopCallback(sub {});
656         PublicInbox::DS->EventLoop until $self->{quit};
657         _done_for_now($self);
658 }
659
660 sub trigger_scan {
661         my ($self, $op) = @_;
662         push @{$self->{ops}}, $op;
663         PublicInbox::DS::requeue($self);
664 }
665
666 sub fs_scan_step {
667         my ($self) = @_;
668         return if $self->{quit};
669         my $op = shift @{$self->{ops}};
670
671         # continue existing scan
672         my $max = 10;
673         my $opendirs = $self->{opendirs};
674         my @dirnames = keys %$opendirs;
675         foreach my $dir (@dirnames) {
676                 my $dh = delete $opendirs->{$dir};
677                 my $n = $max;
678                 while (my $fn = readdir($dh)) {
679                         _try_path($self, "$dir/$fn");
680                         last if --$n < 0;
681                 }
682                 $opendirs->{$dir} = $dh if $n < 0;
683         }
684         if ($op && $op eq 'full') {
685                 foreach my $dir (keys %{$self->{mdmap}}) {
686                         next if $opendirs->{$dir}; # already in progress
687                         my $ok = opendir(my $dh, $dir);
688                         unless ($ok) {
689                                 warn "failed to open $dir: $!\n";
690                                 next;
691                         }
692                         my $n = $max;
693                         while (my $fn = readdir($dh)) {
694                                 _try_path($self, "$dir/$fn");
695                                 last if --$n < 0;
696                         }
697                         $opendirs->{$dir} = $dh if $n < 0;
698                 }
699         }
700         _done_for_now($self);
701         # do we have more work to do?
702         PublicInbox::DS::requeue($self) if keys %$opendirs;
703 }
704
705 sub scan {
706         my ($self, $op) = @_;
707         push @{$self->{ops}}, $op;
708         goto &fs_scan_step;
709 }
710
711 sub _importer_for {
712         my ($self, $ibx) = @_;
713         my $importers = $self->{importers};
714         my $im = $importers->{"$ibx"} ||= $ibx->importer(0);
715         if (scalar(keys(%$importers)) > 2) {
716                 delete $importers->{"$ibx"};
717                 _done_for_now($self);
718         }
719
720         $importers->{"$ibx"} = $im;
721 }
722
723 sub _spamcheck_cb {
724         my ($sc) = @_;
725         sub {
726                 my ($mime) = @_;
727                 my $tmp = '';
728                 if ($sc->spamcheck($mime, \$tmp)) {
729                         return PublicInbox::Eml->new(\$tmp);
730                 }
731                 warn $mime->header('Message-ID')." failed spam check\n";
732                 undef;
733         }
734 }
735
736 sub is_maildir {
737         $_[0] =~ s!\Amaildir:!! or return;
738         $_[0] =~ tr!/!/!s;
739         $_[0] =~ s!/\z!!;
740         $_[0];
741 }
742
743 sub is_watchspam {
744         my ($cur, $ws, $ibx) = @_;
745         if ($ws && !ref($ws) && $ws eq 'watchspam') {
746                 warn <<EOF;
747 E: $cur is a spam folder and cannot be used for `$ibx->{name}' input
748 EOF
749                 return 1;
750         }
751         undef;
752 }
753
754 sub imap_url {
755         my ($url) = @_;
756         require PublicInbox::URIimap;
757         my $uri = PublicInbox::URIimap->new($url);
758         $uri ? $uri->canonical->as_string : undef;
759 }
760
761 1;