1 # Copyright (C) 2016-2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # ref: https://cr.yp.to/proto/maildir.html
5 # httsp://wiki2.dovecot.org/MailboxFormat/Maildir
6 package PublicInbox::Watch;
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::Sigfd;
16 use PublicInbox::DS qw(now add_timer);
17 use PublicInbox::MID qw(mids);
18 use PublicInbox::ContentHash qw(content_hash);
19 use PublicInbox::EOFpipe;
20 use POSIX qw(_exit WNOHANG);
22 sub compile_watchheaders ($) {
25 if (my $whs = $ibx->{watchheader}) {
27 my ($k, $v) = split(/:/, $_, 2);
28 # XXX should this be case-insensitive?
29 # Or, mutt-style, case-sensitive iff
30 # a capital letter exists?
31 push @$watch_hdrs, [ $k, qr/\Q$v\E/ ];
34 if (my $list_ids = $ibx->{listid}) {
36 # RFC2919 section 6 stipulates
37 # "case insensitive equality"
38 my $re = qr/<[ \t]*\Q$_\E[ \t]*>/i;
39 push @$watch_hdrs, ['List-Id', $re ];
42 $ibx->{-watchheaders} = $watch_hdrs if scalar @$watch_hdrs;
46 my ($class, $cfg) = @_;
48 my (%imap, %nntp); # url => [inbox objects] or 'watchspam'
50 # "publicinboxwatch" is the documented namespace
51 # "publicinboxlearn" is legacy but may be supported
53 foreach my $pfx (qw(publicinboxwatch publicinboxlearn)) {
54 my $k = "$pfx.watchspam";
55 defined(my $dirs = $cfg->{$k}) or next;
56 $dirs = PublicInbox::Config::_array($dirs);
57 for my $dir (@$dirs) {
59 if (is_maildir($dir)) {
60 # skip "new", no MUA has seen it, yet.
61 $mdmap{"$dir/cur"} = 'watchspam';
62 } elsif ($url = imap_url($dir)) {
63 $imap{$url} = 'watchspam';
64 } elsif ($url = nntp_url($dir)) {
65 $nntp{$url} = 'watchspam';
67 warn "unsupported $k=$dir\n";
72 my $k = 'publicinboxwatch.spamcheck';
74 my $spamcheck = PublicInbox::Spamcheck::get($cfg, $k, $default);
75 $spamcheck = _spamcheck_cb($spamcheck) if $spamcheck;
77 $cfg->each_inbox(sub {
78 # need to make all inboxes writable for spam removal:
79 my $ibx = $_[0] = PublicInbox::InboxWritable->new($_[0]);
81 my $watches = $ibx->{watch} or return;
82 $watches = PublicInbox::Config::_array($watches);
83 for my $watch (@$watches) {
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;
92 } elsif ($url = imap_url($watch)) {
93 return if is_watchspam($url, $imap{$url}, $ibx);
94 compile_watchheaders($ibx);
95 push @{$imap{$url} ||= []}, $ibx;
96 } elsif ($url = nntp_url($watch)) {
97 return if is_watchspam($url, $nntp{$url}, $ibx);
98 compile_watchheaders($ibx);
99 push @{$nntp{$url} ||= []}, $ibx;
101 warn "watch unsupported: $k=$watch\n";
107 if (scalar keys %mdmap) {
108 $mdre = join('|', map { quotemeta($_) } keys %mdmap);
109 $mdre = qr!\A($mdre)/!;
111 return unless $mdre || scalar(keys %imap) || scalar(keys %nntp);
114 max_batch => 10, # avoid hogging locks for too long
115 spamcheck => $spamcheck,
119 imap => scalar keys %imap ? \%imap : undef,
120 nntp => scalar keys %nntp? \%nntp : undef,
122 opendirs => {}, # dirname => dirhandle (in progress scans)
123 ops => [], # 'quit', 'full'
129 local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
130 for my $im (values %{$self->{importers}}) {
131 next if !$im; # $im may be undef during cleanup
133 warn "$im->{ibx}->{name} ->done: $@\n" if $@;
137 sub remove_eml_i { # each_inbox callback
138 my ($ibx, $self, $eml, $loc) = @_;
141 # try to avoid taking a lock or unnecessary spawning
142 my $im = $self->{importers}->{"$ibx"};
144 if ((!$im || !$im->active) && $ibx->over) {
145 if (content_exists($ibx, $eml)) {
147 } elsif (my $scrub = $ibx->filter($im)) {
148 $scrubbed = $scrub->scrub($eml, 1);
149 if ($scrubbed && $scrubbed != REJECT &&
150 !content_exists($ibx, $scrubbed)) {
158 $im //= _importer_for($self, $ibx); # may spawn fast-import
159 $im->remove($eml, 'spam');
161 my $scrub = $ibx->filter($im);
162 $scrub ? $scrub->scrub($eml, 1) : undef;
164 if ($scrubbed && $scrubbed != REJECT) {
165 $im->remove($scrubbed, 'spam');
169 warn "error removing spam at: $loc from $ibx->{name}: $@\n";
170 _done_for_now($self);
175 my ($self, $path) = @_;
176 # path must be marked as (S)een
177 $path =~ /:2,[A-R]*S[T-Za-z]*\z/ or return;
178 my $eml = eml_from_path($path) or return;
179 local $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
180 $self->{pi_cfg}->each_inbox(\&remove_eml_i, $self, $eml, $path);
183 sub import_eml ($$$) {
184 my ($self, $ibx, $eml) = @_;
186 # any header match means it's eligible for the inbox:
187 if (my $watch_hdrs = $ibx->{-watchheaders}) {
189 for my $wh (@$watch_hdrs) {
190 my @v = $eml->header_raw($wh->[0]);
191 $ok = grep(/$wh->[1]/, @v) and last;
196 my $im = _importer_for($self, $ibx);
197 if (my $scrub = $ibx->filter($im)) {
198 my $scrubbed = $scrub->scrub($eml) or return;
199 $scrubbed == REJECT and return;
202 $im->add($eml, $self->{spamcheck});
205 warn "$ibx->{name} add failed: $@\n";
206 _done_for_now($self);
211 my ($self, $path) = @_;
212 my $fl = PublicInbox::MdirReader::maildir_path_flags($path) // return;
213 return if $fl =~ /[DT]/; # no Drafts or Trash
214 if ($path !~ $self->{mdre}) {
215 warn "unrecognized path: $path\n";
218 my $inboxes = $self->{mdmap}->{$1};
220 warn "unmappable dir: $1\n";
223 my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
224 local $SIG{__WARN__} = sub {
225 my $pfx = ($_[0] // '') =~ /^([A-Z]: )/g ? $1 : '';
226 $warn_cb->($pfx, "path: $path\n", @_);
228 if (!ref($inboxes) && $inboxes eq 'watchspam') {
229 return _remove_spam($self, $path);
231 foreach my $ibx (@$inboxes) {
232 my $eml = eml_from_path($path) or next;
233 import_eml($self, $ibx, $eml);
239 return unless $self->{quit};
241 # don't have reliable wakeups, keep signalling
243 for (qw(idle_pids poll_pids)) {
244 my $pids = $self->{$_} or next;
246 $done = undef if kill('QUIT', $_);
255 %{$self->{opendirs}} = ();
256 _done_for_now($self);
258 if (my $idle_mic = $self->{idle_mic}) {
259 eval { $idle_mic->done };
261 warn "IDLE DONE error: $@\n";
262 eval { $idle_mic->disconnect };
263 warn "IDLE LOGOUT error: $@\n" if $@;
268 sub watch_fs_init ($) {
271 delete $self->{done_timer};
272 _done_for_now($self);
274 my $cb = sub { # called by PublicInbox::DirIdle::event_step
275 _try_path($self, $_[0]->fullname);
276 $self->{done_timer} //= PublicInbox::DS::requeue($done);
278 require PublicInbox::DirIdle;
279 # inotify_create + EPOLL_CTL_ADD
280 PublicInbox::DirIdle->new([keys %{$self->{mdmap}}], $cb);
283 sub imap_import_msg ($$$$$) {
284 my ($self, $url, $uid, $raw, $flags) = @_;
285 # our target audience expects LF-only, save storage
286 $$raw =~ s/\r\n/\n/sg;
288 my $inboxes = $self->{imap}->{$url};
290 for my $ibx (@$inboxes) {
291 my $eml = PublicInbox::Eml->new($$raw);
292 import_eml($self, $ibx, $eml);
294 } elsif ($inboxes eq 'watchspam') {
295 return if $flags !~ /\\Seen\b/; # don't remove unseen messages
296 local $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
297 my $eml = PublicInbox::Eml->new($raw);
298 $self->{pi_cfg}->each_inbox(\&remove_eml_i,
299 $self, $eml, "$url UID:$uid");
301 die "BUG: destination unknown $inboxes";
305 sub imap_fetch_all ($$$) {
306 my ($self, $mic, $url) = @_;
307 my $uri = PublicInbox::URIimap->new($url);
308 my $sec = uri_section($uri);
309 my $mbx = $uri->mailbox;
310 $mic->Clear(1); # trim results history
311 $mic->examine($mbx) or return "E: EXAMINE $mbx ($sec) failed: $!";
312 my ($r_uidval, $r_uidnext);
313 for ($mic->Results) {
314 /^\* OK \[UIDVALIDITY ([0-9]+)\].*/ and $r_uidval = $1;
315 /^\* OK \[UIDNEXT ([0-9]+)\].*/ and $r_uidnext = $1;
316 last if $r_uidval && $r_uidnext;
318 $r_uidval //= $mic->uidvalidity($mbx) //
319 return "E: $url cannot get UIDVALIDITY";
320 $r_uidnext //= $mic->uidnext($mbx) //
321 return "E: $url cannot get UIDNEXT";
322 my $itrk = PublicInbox::IMAPTracker->new($url);
323 my ($l_uidval, $l_uid) = $itrk->get_last;
324 $l_uidval //= $r_uidval; # first time
326 if ($l_uidval != $r_uidval) {
327 return "E: $url UIDVALIDITY mismatch\n".
328 "E: local=$l_uidval != remote=$r_uidval";
330 my $r_uid = $r_uidnext - 1;
331 if ($l_uid != 1 && $l_uid > $r_uid) {
332 return "E: $url local UID exceeds remote ($l_uid > $r_uid)\n".
333 "E: $url strangely, UIDVALIDLITY matches ($l_uidval)\n";
335 return if $l_uid >= $r_uid; # nothing to do
337 warn "I: $url fetching UID $l_uid:$r_uid\n";
338 $mic->Uid(1); # the default, we hope
339 my $bs = $self->{imap_opt}->{$sec}->{batch_size} // 1;
340 my $req = $mic->imap4rev1 ? 'BODY.PEEK[]' : 'RFC822.PEEK';
342 # TODO: FLAGS may be useful for personal use
346 my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
347 local $SIG{__WARN__} = sub {
348 my $pfx = ($_[0] // '') =~ /^([A-Z]: )/g ? $1 : '';
350 $warn_cb->("$pfx$url UID:$batch\n", @_);
354 # I wish "UID FETCH $START:*" could work, but:
355 # 1) servers do not need to return results in any order
356 # 2) Mail::IMAPClient doesn't offer a streaming API
357 $uids = $mic->search("UID $l_uid:*") or
358 return "E: $url UID SEARCH $l_uid:* error: $!";
359 return if scalar(@$uids) == 0;
361 # RFC 3501 doesn't seem to indicate order of UID SEARCH
362 # responses, so sort it ourselves. Order matters so
363 # IMAPTracker can store the newest UID.
364 @$uids = sort { $a <=> $b } @$uids;
366 # Did we actually get new messages?
367 return if $uids->[0] < $l_uid;
369 $l_uid = $uids->[-1] + 1; # for next search
371 my $n = $self->{max_batch};
373 while (scalar @$uids) {
375 _done_for_now($self);
376 $itrk->update_last($r_uidval, $last_uid);
377 $n = $self->{max_batch};
379 my @batch = splice(@$uids, 0, $bs);
380 $batch = join(',', @batch);
381 local $0 = "UID:$batch $mbx $sec";
382 my $r = $mic->fetch_hash($batch, $req, 'FLAGS');
383 unless ($r) { # network error?
384 $err = "E: $url UID FETCH $batch error: $!";
387 for my $uid (@batch) {
388 # messages get deleted, so holes appear
389 my $per_uid = delete $r->{$uid} // next;
390 my $raw = delete($per_uid->{$key}) // next;
391 my $fl = $per_uid->{FLAGS} // '';
392 imap_import_msg($self, $url, $uid, \$raw, $fl);
394 last if $self->{quit};
396 last if $self->{quit};
398 _done_for_now($self);
399 $itrk->update_last($r_uidval, $last_uid);
400 } until ($err || $self->{quit});
404 sub imap_idle_once ($$$$) {
405 my ($self, $mic, $intvl, $url) = @_;
406 my $i = $intvl //= (29 * 60);
407 my $end = now() + $intvl;
408 warn "I: $url idling for ${intvl}s\n";
409 local $0 = "IDLE $0";
410 unless ($mic->idle) {
411 return if $self->{quit};
412 return "E: IDLE failed on $url: $!";
414 $self->{idle_mic} = $mic; # for ->quit
416 until ($self->{quit} || !$mic->IsConnected ||
417 grep(/^\* [0-9]+ EXISTS/, @res) || $i <= 0) {
418 @res = $mic->idle_data($i);
421 delete $self->{idle_mic};
422 unless ($self->{quit}) {
423 $mic->IsConnected or return "E: IDLE disconnected on $url";
424 $mic->done or return "E: IDLE DONE failed on $url: $!";
429 # idles on a single URI
430 sub watch_imap_idle_1 ($$$) {
431 my ($self, $url, $intvl) = @_;
432 my $uri = PublicInbox::URIimap->new($url);
433 my $sec = uri_section($uri);
434 my $mic_arg = $self->{mic_arg}->{$sec} or
435 die "BUG: no Mail::IMAPClient->new arg for $sec";
437 local $0 = $uri->mailbox." $sec";
438 until ($self->{quit}) {
439 $mic //= PublicInbox::IMAPClient->new(%$mic_arg);
441 if ($mic && $mic->IsConnected) {
442 $err = imap_fetch_all($self, $mic, $url);
443 $err //= imap_idle_once($self, $mic, $intvl, $url);
445 $err = "E: not connected: $!";
447 if ($err && !$self->{quit}) {
450 sleep 60 unless $self->{quit};
455 sub watch_atfork_child ($) {
457 delete $self->{idle_pids};
458 delete $self->{poll_pids};
459 delete $self->{opendirs};
460 PublicInbox::DS->Reset;
461 %SIG = (%SIG, %{$self->{sig}}, CHLD => 'DEFAULT');
462 PublicInbox::DS::sig_setmask($self->{oldset});
465 sub watch_atfork_parent ($) {
467 _done_for_now($self);
468 PublicInbox::DS::block_signals();
471 sub imap_idle_requeue { # DS::add_timer callback
472 my ($self, $url_intvl) = @_;
473 return if $self->{quit};
474 push @{$self->{idle_todo}}, $url_intvl;
478 sub imap_idle_reap { # PublicInbox::DS::dwaitpid callback
479 my ($self, $pid) = @_;
480 my $url_intvl = delete $self->{idle_pids}->{$pid} or
481 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
483 my ($url, $intvl) = @$url_intvl;
484 return if $self->{quit};
485 warn "W: PID=$pid on $url died: \$?=$?\n" if $?;
486 add_timer(60, \&imap_idle_requeue, $self, $url_intvl);
489 sub reap { # callback for EOFpipe
490 my ($pid, $cb, $self) = @{$_[0]};
491 my $ret = waitpid($pid, 0);
493 $cb->($self, $pid); # poll_fetch_reap || imap_idle_reap
495 warn "W: waitpid($pid) => ", $ret // "($!)", "\n";
499 sub imap_idle_fork ($$) {
500 my ($self, $url_intvl) = @_;
501 my ($url, $intvl) = @$url_intvl;
502 pipe(my ($r, $w)) or die "pipe: $!";
503 my $seed = rand(0xffffffff);
504 my $pid = fork // die "fork: $!";
507 eval { Net::SSLeay::randomize() };
509 watch_atfork_child($self);
510 watch_imap_idle_1($self, $url, $intvl);
514 $self->{idle_pids}->{$pid} = $url_intvl;
515 PublicInbox::EOFpipe->new($r, \&reap, [$pid, \&imap_idle_reap, $self]);
520 return if $self->{quit};
521 my $idle_todo = $self->{idle_todo};
522 if ($idle_todo && @$idle_todo) {
523 my $oldset = watch_atfork_parent($self);
525 while (my $url_intvl = shift(@$idle_todo)) {
526 imap_idle_fork($self, $url_intvl);
529 PublicInbox::DS::sig_setmask($oldset);
532 fs_scan_step($self) if $self->{mdre};
535 sub watch_imap_fetch_all ($$) {
536 my ($self, $urls) = @_;
537 for my $url (@$urls) {
538 my $uri = PublicInbox::URIimap->new($url);
539 my $sec = uri_section($uri);
540 my $mic_arg = $self->{mic_arg}->{$sec} or
541 die "BUG: no Mail::IMAPClient->new arg for $sec";
542 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or next;
543 my $err = imap_fetch_all($self, $mic, $url);
544 last if $self->{quit};
545 warn $err, "\n" if $err;
549 sub watch_nntp_fetch_all ($$) {
550 my ($self, $urls) = @_;
551 for my $url (@$urls) {
552 my $uri = uri_new($url);
553 my $sec = uri_section($uri);
554 my $nn_arg = $self->{nn_arg}->{$sec} or
555 die "BUG: no Net::NNTP->new arg for $sec";
556 my $nntp_opt = $self->{nntp_opt}->{$sec};
557 my $nn = nn_new($nn_arg, $nntp_opt, $url);
559 warn "E: $url: \$!=$!\n";
562 last if $self->{quit};
563 if (my $postconn = $nntp_opt->{-postconn}) {
564 for my $m_arg (@$postconn) {
565 my ($method, @args) = @$m_arg;
566 $nn->$method(@args) and next;
567 warn "E: <$url> $method failed\n";
572 last if $self->{quit};
574 my $err = nntp_fetch_all($self, $nn, $url);
575 warn $err, "\n" if $err;
580 sub poll_fetch_fork { # DS::add_timer callback
581 my ($self, $intvl, $urls) = @_;
582 return if $self->{quit};
583 pipe(my ($r, $w)) or die "pipe: $!";
584 my $oldset = watch_atfork_parent($self);
585 my $seed = rand(0xffffffff);
587 if (defined($pid) && $pid == 0) {
589 eval { Net::SSLeay::randomize() };
591 watch_atfork_child($self);
592 if ($urls->[0] =~ m!\Aimaps?://!i) {
593 watch_imap_fetch_all($self, $urls);
595 watch_nntp_fetch_all($self, $urls);
600 PublicInbox::DS::sig_setmask($oldset);
601 die "fork: $!" unless defined $pid;
602 $self->{poll_pids}->{$pid} = [ $intvl, $urls ];
603 PublicInbox::EOFpipe->new($r, \&reap, [$pid, \&poll_fetch_reap, $self]);
606 sub poll_fetch_reap {
607 my ($self, $pid) = @_;
608 my $intvl_urls = delete $self->{poll_pids}->{$pid} or
609 die "BUG: PID=$pid (unknown) reaped: \$?=$?\n";
610 return if $self->{quit};
611 my ($intvl, $urls) = @$intvl_urls;
613 warn "W: PID=$pid died: \$?=$?\n", map { "$_\n" } @$urls;
615 warn("I: will check $_ in ${intvl}s\n") for @$urls;
616 add_timer($intvl, \&poll_fetch_fork, $self, $intvl, $urls);
619 sub watch_imap_init ($$) {
620 my ($self, $poll) = @_;
621 my $mics = imap_common_init($self); # read args from config
622 my $idle = []; # [ [ url1, intvl1 ], [url2, intvl2] ]
623 for my $url (keys %{$self->{imap}}) {
624 my $uri = PublicInbox::URIimap->new($url);
625 my $sec = uri_section($uri);
626 my $mic = $mics->{$sec};
627 my $intvl = $self->{imap_opt}->{$sec}->{pollInterval};
628 if ($mic->has_capability('IDLE') && !$intvl) {
629 $intvl = $self->{imap_opt}->{$sec}->{idleInterval};
630 push @$idle, [ $url, $intvl // () ];
632 push @{$poll->{$intvl || 120}}, $url;
636 $self->{idle_todo} = $idle;
637 PublicInbox::DS::requeue($self); # ->event_step to fork
641 # flesh out common NNTP-specific data structures
642 sub nntp_common_init ($) {
644 my $cfg = $self->{pi_cfg};
645 my $nn_args = {}; # scheme://authority => Net::NNTP->new arg
646 for my $url (sort keys %{$self->{nntp}}) {
647 my $sec = uri_section(uri_new($url));
649 # Debug and Timeout are passed to Net::NNTP->new
650 my $v = cfg_bool($cfg, 'nntp.Debug', $url);
651 $nn_args->{$sec}->{Debug} = $v if defined $v;
652 my $to = cfg_intvl($cfg, 'nntp.Timeout', $url);
653 $nn_args->{$sec}->{Timeout} = $to if $to;
655 # Net::NNTP post-connect commands
656 for my $k (qw(starttls compress)) {
657 $v = cfg_bool($cfg, "nntp.$k", $url) // next;
658 $self->{nntp_opt}->{$sec}->{$k} = $v;
662 for my $k (qw(pollInterval)) {
663 $to = cfg_intvl($cfg, "nntp.$k", $url) // next;
664 $self->{nntp_opt}->{$sec}->{$k} = $to;
670 sub nntp_fetch_all ($$$) {
671 my ($self, $nn, $url) = @_;
672 my $uri = uri_new($url);
673 my ($group, $num_a, $num_b) = $uri->group;
674 my $sec = uri_section($uri);
675 my ($nr, $beg, $end) = $nn->group($group);
676 unless (defined($nr)) {
677 chomp(my $msg = $nn->message);
678 return "E: GROUP $group <$sec> $msg";
681 # IMAPTracker is also used for tracking NNTP, UID == article number
682 # LIST.ACTIVE can get the equivalent of UIDVALIDITY, but that's
683 # expensive. So we assume newsgroups don't change:
684 my $itrk = PublicInbox::IMAPTracker->new($url);
685 my (undef, $l_art) = $itrk->get_last;
686 $l_art //= $beg; # initial import
688 # allow users to specify articles to refetch
689 # cf. https://tools.ietf.org/id/draft-gilman-news-url-01.txt
690 # nntp://example.com/inbox.foo/$num_a-$num_b
691 $l_art = $num_a if defined($num_a) && $num_a < $l_art;
692 $end = $num_b if defined($num_b) && $num_b < $end;
694 return if $l_art >= $end; # nothing to do
697 warn "I: $url fetching ARTICLE $beg..$end\n";
698 my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
700 local $SIG{__WARN__} = sub {
701 my $pfx = ($_[0] // '') =~ /^([A-Z]: )/g ? $1 : '';
702 $warn_cb->("$pfx$url ", $art ? ("ARTICLE $art") : (), "\n", @_);
704 my $inboxes = $self->{nntp}->{$url};
706 my $n = $self->{max_batch};
708 last if $self->{quit};
711 _done_for_now($self);
712 $itrk->update_last(0, $last_art);
713 $n = $self->{max_batch};
715 my $raw = $nn->article($art);
716 unless (defined($raw)) {
717 my $msg = $nn->message;
718 if ($nn->code == 421) { # pseudo response from Net::Cmd
721 } else { # probably just a deleted message (spam)
726 s/\r\n/\n/ for @$raw;
727 $raw = join('', @$raw);
729 for my $ibx (@$inboxes) {
730 my $eml = PublicInbox::Eml->new($raw);
731 import_eml($self, $ibx, $eml);
733 } elsif ($inboxes eq 'watchspam') {
734 my $eml = PublicInbox::Eml->new(\$raw);
735 $self->{pi_cfg}->each_inbox(\&remove_eml_i,
736 $self, $eml, "$url ARTICLE $art");
738 die "BUG: destination unknown $inboxes";
742 _done_for_now($self);
743 $itrk->update_last(0, $last_art);
747 sub watch_nntp_init ($$) {
748 my ($self, $poll) = @_;
749 eval { require Net::NNTP } or
750 die "Net::NNTP is required for NNTP:\n$@\n";
751 eval { require PublicInbox::IMAPTracker } or
752 die "DBD::SQLite is required for NNTP\n:$@\n";
754 my $nn_args = nntp_common_init($self); # read args from config
756 # make sure we can connect and cache the credentials in memory
757 $self->{nn_arg} = {}; # schema://authority => Net::NNTP->new args
758 for my $url (sort keys %{$self->{nntp}}) {
759 nn_for($self, $url, $nn_args);
761 for my $url (keys %{$self->{nntp}}) {
762 my $uri = uri_new($url);
763 my $sec = uri_section($uri);
764 my $intvl = $self->{nntp_opt}->{$sec}->{pollInterval};
765 push @{$poll->{$intvl || 120}}, $url;
769 sub watch { # main entry point
770 my ($self, $sig, $oldset) = @_;
771 $self->{oldset} = $oldset;
773 my $poll = {}; # intvl_seconds => [ url1, url2 ]
774 watch_imap_init($self, $poll) if $self->{imap};
775 watch_nntp_init($self, $poll) if $self->{nntp};
776 while (my ($intvl, $urls) = each %$poll) {
777 # poll all URLs for a given interval sequentially
778 add_timer(0, \&poll_fetch_fork, $self, $intvl, $urls);
780 watch_fs_init($self) if $self->{mdre};
781 PublicInbox::DS->SetPostLoopCallback(sub { !$self->quit_done });
782 PublicInbox::DS->EventLoop; # calls ->event_step
783 _done_for_now($self);
787 my ($self, $op) = @_;
788 push @{$self->{ops}}, $op;
789 PublicInbox::DS::requeue($self);
794 return if $self->{quit};
795 my $op = shift @{$self->{ops}};
796 local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
798 # continue existing scan
799 my $opendirs = $self->{opendirs};
800 my @dirnames = keys %$opendirs;
801 foreach my $dir (@dirnames) {
802 my $dh = delete $opendirs->{$dir};
803 my $n = $self->{max_batch};
804 while (my $fn = readdir($dh)) {
805 _try_path($self, "$dir/$fn");
808 $opendirs->{$dir} = $dh if $n < 0;
810 if ($op && $op eq 'full') {
811 foreach my $dir (keys %{$self->{mdmap}}) {
812 next if $opendirs->{$dir}; # already in progress
813 my $ok = opendir(my $dh, $dir);
815 warn "failed to open $dir: $!\n";
818 my $n = $self->{max_batch};
819 while (my $fn = readdir($dh)) {
820 _try_path($self, "$dir/$fn");
823 $opendirs->{$dir} = $dh if $n < 0;
826 _done_for_now($self);
827 # do we have more work to do?
828 PublicInbox::DS::requeue($self) if keys %$opendirs;
832 my ($self, $op) = @_;
833 push @{$self->{ops}}, $op;
838 my ($self, $ibx) = @_;
839 my $importers = $self->{importers};
840 my $im = $importers->{"$ibx"} ||= $ibx->importer(0);
841 if (scalar(keys(%$importers)) > 2) {
842 delete $importers->{"$ibx"};
843 _done_for_now($self);
846 $importers->{"$ibx"} = $im;
849 # XXX consider sharing with V2Writable, this only requires read-only access
850 sub content_exists ($$) {
851 my ($ibx, $eml) = @_;
852 my $over = $ibx->over or return;
853 my $mids = mids($eml);
854 my $chash = content_hash($eml);
856 for my $mid (@$mids) {
857 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
858 my $cmp = $ibx->smsg_eml($smsg) or return;
859 return 1 if $chash eq content_hash($cmp);
867 sub { # this gets called by (V2Writable||Import)->add
868 my ($mime, $ibx) = @_;
869 return if content_exists($ibx, $mime);
871 if ($sc->spamcheck($mime, \$tmp)) {
872 return PublicInbox::Eml->new(\$tmp);
874 warn $mime->header('Message-ID')." failed spam check\n";
880 $_[0] =~ s!\Amaildir:!! or return;
887 my ($cur, $ws, $ibx) = @_;
888 if ($ws && !ref($ws) && $ws eq 'watchspam') {
890 E: $cur is a spam folder and cannot be used for `$ibx->{name}' input