]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Watch.pm
5798508340dda6c2ba76d4afe6b2d9e5212dd926
[public-inbox.git] / lib / PublicInbox / Watch.pm
1 # Copyright (C) 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 #       https://wiki2.dovecot.org/MailboxFormat/Maildir
6 package PublicInbox::Watch;
7 use strict;
8 use v5.10.1;
9 use PublicInbox::Eml;
10 use PublicInbox::InboxWritable qw(eml_from_path);
11 use PublicInbox::MdirReader;
12 use PublicInbox::NetReader;
13 use PublicInbox::Filter::Base qw(REJECT);
14 use PublicInbox::Spamcheck;
15 use PublicInbox::DS qw(now add_timer awaitpid);
16 use PublicInbox::MID qw(mids);
17 use PublicInbox::ContentHash qw(content_hash);
18 use POSIX qw(_exit WNOHANG);
19
20 sub compile_watchheaders ($) {
21         my ($ibx) = @_;
22         my $watch_hdrs = [];
23         if (my $whs = $ibx->{watchheader}) {
24                 for (@$whs) {
25                         my ($k, $v) = split(/:/, $_, 2);
26                         # XXX should this be case-insensitive?
27                         # Or, mutt-style, case-sensitive iff
28                         # a capital letter exists?
29                         push @$watch_hdrs, [ $k, qr/\Q$v\E/ ];
30                 }
31         }
32         if (my $list_ids = $ibx->{listid}) {
33                 for (@$list_ids) {
34                         # RFC2919 section 6 stipulates
35                         # "case insensitive equality"
36                         my $re = qr/<[ \t]*\Q$_\E[ \t]*>/i;
37                         push @$watch_hdrs, ['List-Id', $re ];
38                 }
39         }
40         $ibx->{-watchheaders} = $watch_hdrs if scalar @$watch_hdrs;
41 }
42
43 sub new {
44         my ($class, $cfg) = @_;
45         my (%mdmap, $spamc);
46         my (%imap, %nntp); # url => [inbox objects] or 'watchspam'
47         my (@imap, @nntp);
48
49         # "publicinboxwatch" is the documented namespace
50         # "publicinboxlearn" is legacy but may be supported
51         # indefinitely...
52         foreach my $pfx (qw(publicinboxwatch publicinboxlearn)) {
53                 my $k = "$pfx.watchspam";
54                 my $dirs = $cfg->get_all($k) // next;
55                 for my $dir (@$dirs) {
56                         my $uri;
57                         if (is_maildir($dir)) {
58                                 # skip "new", no MUA has seen it, yet.
59                                 $mdmap{"$dir/cur"} = 'watchspam';
60                         } elsif ($uri = imap_uri($dir)) {
61                                 $imap{$$uri} = 'watchspam';
62                                 push @imap, $uri;
63                         } elsif ($uri = nntp_uri($dir)) {
64                                 $nntp{$$uri} = 'watchspam';
65                                 push @nntp, $uri;
66                         } else {
67                                 warn "unsupported $k=$dir\n";
68                         }
69                 }
70         }
71
72         my $k = 'publicinboxwatch.spamcheck';
73         my $default = undef;
74         my $spamcheck = PublicInbox::Spamcheck::get($cfg, $k, $default);
75         $spamcheck = _spamcheck_cb($spamcheck) if $spamcheck;
76
77         $cfg->each_inbox(sub {
78                 # need to make all inboxes writable for spam removal:
79                 my $ibx = $_[0] = PublicInbox::InboxWritable->new($_[0]);
80
81                 my $watches = $ibx->{watch} or return;
82                 $watches = PublicInbox::Config::_array($watches);
83                 for my $watch (@$watches) {
84                         my $uri;
85                         if (is_maildir($watch)) {
86                                 compile_watchheaders($ibx);
87                                 my ($new, $cur) = ("$watch/new", "$watch/cur");
88                                 my $cur_dst = $mdmap{$cur} //= [];
89                                 return if is_watchspam($cur, $cur_dst, $ibx);
90                                 push @{$mdmap{$new} //= []}, $ibx;
91                                 push @$cur_dst, $ibx;
92                         } elsif ($uri = imap_uri($watch)) {
93                                 my $cur_dst = $imap{$$uri} //= [];
94                                 return if is_watchspam($uri, $cur_dst, $ibx);
95                                 compile_watchheaders($ibx);
96                                 push(@imap, $uri) if 1 == push(@$cur_dst, $ibx);
97                         } elsif ($uri = nntp_uri($watch)) {
98                                 my $cur_dst = $nntp{$$uri} //= [];
99                                 return if is_watchspam($uri, $cur_dst, $ibx);
100                                 compile_watchheaders($ibx);
101                                 push(@nntp, $uri) if 1 == push(@$cur_dst, $ibx);
102                         } else {
103                                 warn "watch unsupported: $k=$watch\n";
104                         }
105                 }
106         });
107
108         my $mdre;
109         if (scalar keys %mdmap) {
110                 $mdre = join('|', map { quotemeta($_) } keys %mdmap);
111                 $mdre = qr!\A($mdre)/!;
112         }
113         return unless $mdre || scalar(keys %imap) || scalar(keys %nntp);
114
115         bless {
116                 max_batch => 10, # avoid hogging locks for too long
117                 spamcheck => $spamcheck,
118                 mdmap => \%mdmap,
119                 mdre => $mdre,
120                 pi_cfg => $cfg,
121                 imap => scalar keys %imap ? \%imap : undef,
122                 nntp => scalar keys %nntp? \%nntp : undef,
123                 imap_order => scalar(@imap) ? \@imap : undef,
124                 nntp_order => scalar(@nntp) ? \@nntp: undef,
125                 importers => {},
126                 opendirs => {}, # dirname => dirhandle (in progress scans)
127                 ops => [], # 'quit', 'full'
128         }, $class;
129 }
130
131 sub _done_for_now {
132         my ($self) = @_;
133         local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
134         for my $im (values %{$self->{importers}}) {
135                 next if !$im; # $im may be undef during cleanup
136                 eval { $im->done };
137                 warn "$im->{ibx}->{name} ->done: $@\n" if $@;
138         }
139 }
140
141 sub remove_eml_i { # each_inbox callback
142         my ($ibx, $self, $eml, $loc) = @_;
143
144         eval {
145                 # try to avoid taking a lock or unnecessary spawning
146                 my $im = $self->{importers}->{"$ibx"};
147                 my $scrubbed;
148                 if ((!$im || !$im->active) && $ibx->over) {
149                         if (content_exists($ibx, $eml)) {
150                                 # continue
151                         } elsif (my $scrub = $ibx->filter($im)) {
152                                 $scrubbed = $scrub->scrub($eml, 1);
153                                 if ($scrubbed && $scrubbed != REJECT &&
154                                           !content_exists($ibx, $scrubbed)) {
155                                         return;
156                                 }
157                         } else {
158                                 return;
159                         }
160                 }
161
162                 $im //= _importer_for($self, $ibx); # may spawn fast-import
163                 $im->remove($eml, 'spam');
164                 $scrubbed //= do {
165                         my $scrub = $ibx->filter($im);
166                         $scrub ? $scrub->scrub($eml, 1) : undef;
167                 };
168                 if ($scrubbed && $scrubbed != REJECT) {
169                         $im->remove($scrubbed, 'spam');
170                 }
171         };
172         if ($@) {
173                 warn "error removing spam at: $loc from $ibx->{name}: $@\n";
174                 _done_for_now($self);
175         }
176 }
177
178 sub _remove_spam {
179         my ($self, $path) = @_;
180         # path must be marked as (S)een
181         $path =~ /:2,[A-R]*S[T-Za-z]*\z/ or return;
182         my $eml = eml_from_path($path) or return;
183         local $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
184         $self->{pi_cfg}->each_inbox(\&remove_eml_i, $self, $eml, $path);
185 }
186
187 sub import_eml ($$$) {
188         my ($self, $ibx, $eml) = @_;
189
190         # any header match means it's eligible for the inbox:
191         if (my $watch_hdrs = $ibx->{-watchheaders}) {
192                 my $ok;
193                 for my $wh (@$watch_hdrs) {
194                         my @v = $eml->header_raw($wh->[0]);
195                         $ok = grep(/$wh->[1]/, @v) and last;
196                 }
197                 return unless $ok;
198         }
199         eval {
200                 my $im = _importer_for($self, $ibx);
201                 if (my $scrub = $ibx->filter($im)) {
202                         my $scrubbed = $scrub->scrub($eml) or return;
203                         $scrubbed == REJECT and return;
204                         $eml = $scrubbed;
205                 }
206                 $im->add($eml, $self->{spamcheck});
207         };
208         if ($@) {
209                 warn "$ibx->{name} add failed: $@\n";
210                 _done_for_now($self);
211         }
212 }
213
214 sub _try_path {
215         my ($self, $path) = @_;
216         my $fl = PublicInbox::MdirReader::maildir_path_flags($path) // return;
217         return if $fl =~ /[DT]/; # no Drafts or Trash
218         if ($path !~ $self->{mdre}) {
219                 warn "unrecognized path: $path\n";
220                 return;
221         }
222         my $inboxes = $self->{mdmap}->{$1};
223         unless ($inboxes) {
224                 warn "unmappable dir: $1\n";
225                 return;
226         }
227         my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
228         local $SIG{__WARN__} = sub {
229                 my $pfx = ($_[0] // '') =~ /^([A-Z]: )/g ? $1 : '';
230                 $warn_cb->($pfx, "path: $path\n", @_);
231         };
232         if (!ref($inboxes) && $inboxes eq 'watchspam') {
233                 return _remove_spam($self, $path);
234         }
235         foreach my $ibx (@$inboxes) {
236                 my $eml = eml_from_path($path) or next;
237                 import_eml($self, $ibx, $eml);
238         }
239 }
240
241 sub quit_done ($) {
242         my ($self) = @_;
243         return unless $self->{quit};
244
245         # don't have reliable wakeups, keep signalling
246         my $live = 0;
247         for (qw(idle_pids poll_pids)) {
248                 my $pids = $self->{$_} or next;
249                 $live += grep { kill('QUIT', $_) } keys %$pids;
250         }
251         add_timer(0.01, \&quit_done, $self) if $live;
252         $live == 0;
253 }
254
255 sub quit {
256         my ($self) = @_;
257         $self->{quit} = 1;
258         %{$self->{opendirs}} = ();
259         _done_for_now($self);
260         quit_done($self);
261         if (my $idle_mic = $self->{idle_mic}) {
262                 eval { $idle_mic->done };
263                 if ($@) {
264                         warn "IDLE DONE error: $@\n";
265                         eval { $idle_mic->disconnect };
266                         warn "IDLE LOGOUT error: $@\n" if $@;
267                 }
268         }
269 }
270
271 sub watch_fs_init ($) {
272         my ($self) = @_;
273         my $done = sub {
274                 delete $self->{done_timer};
275                 _done_for_now($self);
276         };
277         my $cb = sub { # called by PublicInbox::DirIdle::event_step
278                 _try_path($self, $_[0]->fullname);
279                 $self->{done_timer} //= PublicInbox::DS::requeue($done);
280         };
281         require PublicInbox::DirIdle;
282         # inotify_create + EPOLL_CTL_ADD
283         my $dir_idle = PublicInbox::DirIdle->new($cb);
284         $dir_idle->add_watches([keys %{$self->{mdmap}}]);
285 }
286
287 sub net_cb { # NetReader::(nntp|imap)_each callback
288         my ($uri, $art, $kw, $eml, $self, $inboxes) = @_;
289         return if grep(/\Adraft\z/, @$kw);
290         local $self->{cur_uid} = $art; # IMAP UID or NNTP article
291         if (ref($inboxes)) {
292                 my @ibx = @$inboxes;
293                 my $last = pop @ibx;
294                 for my $ibx (@ibx) {
295                         my $tmp = PublicInbox::Eml->new(\($eml->as_string));
296                         import_eml($self, $ibx, $tmp);
297                 }
298                 import_eml($self, $last, $eml);
299         } elsif ($inboxes eq 'watchspam') {
300                 if ($uri->scheme =~ /\Aimaps?\z/ && !grep(/\Aseen\z/, @$kw)) {
301                         return;
302                 }
303                 $self->{pi_cfg}->each_inbox(\&remove_eml_i,
304                                 $self, $eml, "$uri #$art");
305         } else {
306                 die "BUG: destination unknown $inboxes";
307         }
308 }
309
310 sub imap_fetch_all ($$) {
311         my ($self, $uri) = @_;
312         my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
313         $self->{incremental} = 1;
314         $self->{on_commit} = [ \&_done_for_now, $self ];
315         local $self->{cur_uid};
316         local $SIG{__WARN__} = sub {
317                 my $pfx = ($_[0] // '') =~ /^([A-Z]: |# )/g ? $1 : '';
318                 my $uid = $self->{cur_uid};
319                 $warn_cb->("$pfx$uri", $uid ? ("UID:$uid") : (), "\n", @_);
320         };
321         PublicInbox::NetReader::imap_each($self, $uri, \&net_cb, $self,
322                                         $self->{imap}->{$$uri});
323 }
324
325 sub imap_idle_once ($$$$) {
326         my ($self, $mic, $intvl, $uri) = @_;
327         my $i = $intvl //= (29 * 60);
328         my $end = now() + $intvl;
329         warn "# $uri idling for ${intvl}s\n";
330         local $0 = "IDLE $0";
331         return if $self->{quit};
332         unless ($mic->idle) {
333                 return if $self->{quit};
334                 return "E: IDLE failed on $uri: $!";
335         }
336         $self->{idle_mic} = $mic; # for ->quit
337         my @res;
338         until ($self->{quit} || !$mic->IsConnected ||
339                         grep(/^\* [0-9]+ EXISTS/, @res) || $i <= 0) {
340                 @res = $mic->idle_data($i);
341                 $i = $end - now();
342         }
343         delete $self->{idle_mic};
344         unless ($self->{quit}) {
345                 $mic->IsConnected or return "E: IDLE disconnected on $uri";
346                 $mic->done or return "E: IDLE DONE failed on $uri: $!";
347         }
348         undef;
349 }
350
351 # idles on a single URI
352 sub watch_imap_idle_1 ($$$) {
353         my ($self, $uri, $intvl) = @_;
354         my $sec = uri_section($uri);
355         my $mic_arg = $self->{net_arg}->{$sec} or
356                         die "BUG: no Mail::IMAPClient->new arg for $sec";
357         my $mic;
358         local $0 = $uri->mailbox." $sec";
359         until ($self->{quit}) {
360                 $mic //= PublicInbox::NetReader::mic_new(
361                                         $self, $mic_arg, $sec, $uri);
362                 my $err;
363                 if ($mic && $mic->IsConnected) {
364                         local $self->{mics_cached}->{$sec} = $mic;
365                         my $m = imap_fetch_all($self, $uri);
366                         $m == $mic or die "BUG: wrong mic";
367                         $mic->IsConnected and
368                                 $err = imap_idle_once($self, $mic, $intvl, $uri)
369                 } else {
370                         $err = "E: not connected: $!";
371                 }
372                 if ($err && !$self->{quit}) {
373                         warn $err, "\n";
374                         $mic = undef;
375                         sleep 60 unless $self->{quit};
376                 }
377         }
378 }
379
380 sub watch_atfork_child ($) {
381         my ($self) = @_;
382         delete $self->{idle_pids};
383         delete $self->{poll_pids};
384         delete $self->{opendirs};
385         PublicInbox::DS->Reset;
386         my $sig = delete $self->{sig};
387         $sig->{CHLD} = 'DEFAULT';
388         @SIG{keys %$sig} = values %$sig;
389         PublicInbox::DS::sig_setmask($self->{oldset});
390 }
391
392 sub watch_atfork_parent ($) { _done_for_now($_[0]) }
393
394 sub imap_idle_requeue { # DS::add_timer callback
395         my ($self, $uri_intvl) = @_;
396         return if $self->{quit};
397         push @{$self->{idle_todo}}, $uri_intvl;
398         event_step($self);
399 }
400
401 sub imap_idle_reap { # awaitpid callback
402         my ($pid, $self) = @_;
403         my $uri_intvl = delete $self->{idle_pids}->{$pid} or
404                 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
405
406         my ($uri, $intvl) = @$uri_intvl;
407         return if $self->{quit};
408         warn "W: PID=$pid on $uri died: \$?=$?\n" if $?;
409         add_timer(60, \&imap_idle_requeue, $self, $uri_intvl);
410 }
411
412 sub imap_idle_fork ($$) {
413         my ($self, $uri_intvl) = @_;
414         return if $self->{quit};
415         my ($uri, $intvl) = @$uri_intvl;
416         my $seed = rand(0xffffffff);
417         my $pid = fork // die "fork: $!";
418         if ($pid == 0) {
419                 srand($seed);
420                 eval { Net::SSLeay::randomize() };
421                 watch_atfork_child($self);
422                 watch_imap_idle_1($self, $uri, $intvl);
423                 _exit(0);
424         }
425         $self->{idle_pids}->{$pid} = $uri_intvl;
426         awaitpid($pid, \&imap_idle_reap, $self);
427 }
428
429 sub event_step {
430         my ($self) = @_;
431         return if $self->{quit};
432         my $idle_todo = $self->{idle_todo};
433         if ($idle_todo && @$idle_todo) {
434                 watch_atfork_parent($self);
435                 eval {
436                         while (my $uri_intvl = shift(@$idle_todo)) {
437                                 imap_idle_fork($self, $uri_intvl);
438                         }
439                 };
440                 die $@ if $@;
441         }
442         fs_scan_step($self) if $self->{mdre};
443 }
444
445 sub watch_imap_fetch_all ($$) {
446         my ($self, $uris) = @_;
447         for my $uri (@$uris) {
448                 imap_fetch_all($self, $uri);
449                 last if $self->{quit};
450         }
451 }
452
453 sub watch_nntp_fetch_all ($$) {
454         my ($self, $uris) = @_;
455         $self->{incremental} = 1;
456         $self->{on_commit} = [ \&_done_for_now, $self ];
457         my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
458         local $self->{cur_uid};
459         my $uri = '';
460         local $SIG{__WARN__} = sub {
461                 my $pfx = ($_[0] // '') =~ /^([A-Z]: |# )/g ? $1 : '';
462                 my $art = $self->{cur_uid};
463                 $warn_cb->("$pfx$uri", $art ? ("ARTICLE $art") : (), "\n", @_);
464         };
465         for $uri (@$uris) {
466                 PublicInbox::NetReader::nntp_each($self, $uri, \&net_cb, $self,
467                                         $self->{nntp}->{$$uri});
468                 last if $self->{quit};
469         }
470 }
471
472 sub poll_fetch_fork { # DS::add_timer callback
473         my ($self, $intvl, $uris) = @_;
474         return if $self->{quit};
475         watch_atfork_parent($self);
476         my $seed = rand(0xffffffff);
477         my $pid = fork // die "fork: $!";
478         if ($pid == 0) {
479                 srand($seed);
480                 eval { Net::SSLeay::randomize() };
481                 watch_atfork_child($self);
482                 if ($uris->[0]->scheme =~ m!\Aimaps?!i) {
483                         watch_imap_fetch_all($self, $uris);
484                 } else {
485                         watch_nntp_fetch_all($self, $uris);
486                 }
487                 _exit(0);
488         }
489         $self->{poll_pids}->{$pid} = [ $intvl, $uris ];
490         awaitpid($pid, \&poll_fetch_reap, $self);
491 }
492
493 sub poll_fetch_reap { # awaitpid callback
494         my ($pid, $self) = @_;
495         my $intvl_uris = delete $self->{poll_pids}->{$pid} or
496                 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
497         return if $self->{quit};
498         my ($intvl, $uris) = @$intvl_uris;
499         if ($?) {
500                 warn "W: PID=$pid died: \$?=$?\n", map { "$_\n" } @$uris;
501         }
502         warn("# will check $_ in ${intvl}s\n") for @$uris;
503         add_timer($intvl, \&poll_fetch_fork, $self, $intvl, $uris);
504 }
505
506 sub watch_imap_init ($$) {
507         my ($self, $poll) = @_;
508         my $mics = PublicInbox::NetReader::imap_common_init($self);
509         my $idle = []; # [ [ uri1, intvl1 ], [uri2, intvl2] ]
510         for my $uri (@{$self->{imap_order}}) {
511                 my $sec = uri_section($uri);
512                 my $mic = $mics->{$sec};
513                 my $intvl = $self->{cfg_opt}->{$sec}->{pollInterval};
514                 if ($mic->has_capability('IDLE') && !$intvl) {
515                         $intvl = $self->{cfg_opt}->{$sec}->{idleInterval};
516                         push @$idle, [ $uri, $intvl // () ];
517                 } else {
518                         push @{$poll->{$intvl || 120}}, $uri;
519                 }
520         }
521         if (scalar @$idle) {
522                 $self->{idle_todo} = $idle;
523                 PublicInbox::DS::requeue($self); # ->event_step to fork
524         }
525 }
526
527 sub watch_nntp_init ($$) {
528         my ($self, $poll) = @_;
529         PublicInbox::NetReader::nntp_common_init($self);
530         for my $uri (@{$self->{nntp_order}}) {
531                 my $sec = uri_section($uri);
532                 my $intvl = $self->{cfg_opt}->{$sec}->{pollInterval};
533                 push @{$poll->{$intvl || 120}}, $uri;
534         }
535 }
536
537 sub watch { # main entry point
538         my ($self, $sig, $oldset) = @_;
539         $self->{oldset} = $oldset;
540         $self->{sig} = $sig;
541         my $poll = {}; # intvl_seconds => [ uri1, uri2 ]
542         watch_imap_init($self, $poll) if $self->{imap};
543         watch_nntp_init($self, $poll) if $self->{nntp};
544         while (my ($intvl, $uris) = each %$poll) {
545                 # poll all URIs for a given interval sequentially
546                 add_timer(0, \&poll_fetch_fork, $self, $intvl, $uris);
547         }
548         watch_fs_init($self) if $self->{mdre};
549         PublicInbox::DS->SetPostLoopCallback(sub { !$self->quit_done });
550         PublicInbox::DS::event_loop($sig, $oldset); # calls ->event_step
551         _done_for_now($self);
552 }
553
554 sub trigger_scan {
555         my ($self, $op) = @_;
556         push @{$self->{ops}}, $op;
557         PublicInbox::DS::requeue($self);
558 }
559
560 sub fs_scan_step {
561         my ($self) = @_;
562         return if $self->{quit};
563         my $op = shift @{$self->{ops}};
564         local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
565
566         # continue existing scan
567         my $opendirs = $self->{opendirs};
568         my @dirnames = keys %$opendirs;
569         foreach my $dir (@dirnames) {
570                 my $dh = delete $opendirs->{$dir};
571                 my $n = $self->{max_batch};
572                 while (my $fn = readdir($dh)) {
573                         _try_path($self, "$dir/$fn");
574                         last if --$n < 0;
575                 }
576                 $opendirs->{$dir} = $dh if $n < 0;
577         }
578         if ($op && $op eq 'full') {
579                 foreach my $dir (keys %{$self->{mdmap}}) {
580                         next if $opendirs->{$dir}; # already in progress
581                         my $ok = opendir(my $dh, $dir);
582                         unless ($ok) {
583                                 warn "failed to open $dir: $!\n";
584                                 next;
585                         }
586                         my $n = $self->{max_batch};
587                         while (my $fn = readdir($dh)) {
588                                 _try_path($self, "$dir/$fn");
589                                 last if --$n < 0;
590                         }
591                         $opendirs->{$dir} = $dh if $n < 0;
592                 }
593         }
594         _done_for_now($self);
595         # do we have more work to do?
596         PublicInbox::DS::requeue($self) if keys %$opendirs;
597 }
598
599 sub scan {
600         my ($self, $op) = @_;
601         push @{$self->{ops}}, $op;
602         fs_scan_step($self);
603 }
604
605 sub _importer_for {
606         my ($self, $ibx) = @_;
607         my $importers = $self->{importers};
608         my $im = $importers->{"$ibx"} ||= $ibx->importer(0);
609         if (scalar(keys(%$importers)) > 2) {
610                 delete $importers->{"$ibx"};
611                 _done_for_now($self);
612         }
613
614         $importers->{"$ibx"} = $im;
615 }
616
617 # XXX consider sharing with V2Writable, this only requires read-only access
618 sub content_exists ($$) {
619         my ($ibx, $eml) = @_;
620         my $over = $ibx->over or return;
621         my $mids = mids($eml);
622         my $chash = content_hash($eml);
623         my ($id, $prev);
624         for my $mid (@$mids) {
625                 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
626                         my $cmp = $ibx->smsg_eml($smsg) or return;
627                         return 1 if $chash eq content_hash($cmp);
628                 }
629         }
630         undef;
631 }
632
633 sub _spamcheck_cb {
634         my ($sc) = @_;
635         sub { # this gets called by (V2Writable||Import)->add
636                 my ($mime, $ibx) = @_;
637                 return if content_exists($ibx, $mime);
638                 my $tmp = '';
639                 if ($sc->spamcheck($mime, \$tmp)) {
640                         return PublicInbox::Eml->new(\$tmp);
641                 }
642                 warn $mime->header('Message-ID')." failed spam check\n";
643                 undef;
644         }
645 }
646
647 sub is_maildir {
648         $_[0] =~ s!\Amaildir:!! or return;
649         $_[0] =~ tr!/!/!s;
650         $_[0] =~ s!/\z!!;
651         $_[0];
652 }
653
654 sub is_watchspam {
655         my ($cur, $ws, $ibx) = @_;
656         if ($ws && !ref($ws) && $ws eq 'watchspam') {
657                 warn <<EOF;
658 E: $cur is a spam folder and cannot be used for `$ibx->{name}' input
659 EOF
660                 return 1;
661         }
662         undef;
663 }
664
665 sub folder_select { 'select' } # for PublicInbox::NetReader
666
667 1;