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