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