1 # Copyright (C) 2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # common reader code for IMAP and NNTP (and maybe JMAP)
5 package PublicInbox::NetReader;
8 use parent qw(Exporter PublicInbox::IPC);
10 our %IMAPflags2kw = map {; "\\\u$_" => $_ } qw(seen answered flagged draft);
12 our @EXPORT = qw(uri_section imap_uri nntp_uri);
16 Data::Dumper->new(\@_)->Useqq(1)->Terse(1)->Dump;
19 # returns the git config section name, e.g [imap "imaps://user@example.com"]
20 # without the mailbox, so we can share connections between different inboxes
23 $uri->scheme . '://' . $uri->authority;
26 sub auth_anon_cb { '' }; # for Mail::IMAPClient::Authcallback
28 # mic_for may prompt the user and store auth info, prepares mic_get
29 sub mic_for { # mic = Mail::IMAPClient
30 my ($self, $url, $mic_args, $lei) = @_;
31 require PublicInbox::URIimap;
32 my $uri = PublicInbox::URIimap->new($url);
33 require PublicInbox::GitCredential;
36 protocol => $uri->scheme,
38 username => $uri->user,
39 password => $uri->password,
40 }, 'PublicInbox::GitCredential';
41 my $common = $mic_args->{uri_section($uri)} // {};
42 # IMAPClient and Net::Netrc both mishandles `0', so we pass `127.0.0.1'
43 my $host = $cred->{host};
44 $host = '127.0.0.1' if $host eq '0';
48 Ssl => $uri->scheme eq 'imaps',
49 Keepalive => 1, # SO_KEEPALIVE
50 %$common, # may set Starttls, Compress, Debug ....
52 require PublicInbox::IMAPClient;
53 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or
54 die "E: <$url> new: $@\n";
56 # default to using STARTTLS if it's available, but allow
57 # it to be disabled since I usually connect to localhost
58 if (!$mic_arg->{Ssl} && !defined($mic_arg->{Starttls}) &&
59 $mic->has_capability('STARTTLS') &&
60 $mic->can('starttls')) {
61 $mic->starttls or die "E: <$url> STARTTLS: $@\n";
64 # do we even need credentials?
65 if (!defined($cred->{username}) &&
66 $mic->has_capability('AUTH=ANONYMOUS')) {
70 $cred->check_netrc unless defined $cred->{password};
71 $cred->fill($lei); # may prompt user here
72 $mic->User($mic_arg->{User} = $cred->{username});
73 $mic->Password($mic_arg->{Password} = $cred->{password});
74 } else { # AUTH=ANONYMOUS
75 $mic->Authmechanism($mic_arg->{Authmechanism} = 'ANONYMOUS');
76 $mic_arg->{Authcallback} = 'auth_anon_cb';
77 $mic->Authcallback(\&auth_anon_cb);
80 if ($mic->login && $mic->IsAuthenticated) {
81 # success! keep IMAPClient->new arg in case we get disconnected
82 $self->{mic_arg}->{uri_section($uri)} = $mic_arg;
84 $err = "E: <$url> LOGIN: $@\n";
85 if ($cred && defined($cred->{password})) {
86 $err =~ s/\Q$cred->{password}\E/*******/g;
90 $cred->run($mic ? 'approve' : 'reject') if $cred;
92 $lei ? $lei->fail($err) : warn($err);
97 # Net::NNTP doesn't support CAPABILITIES, yet
98 sub try_starttls ($) {
100 return if $host =~ /\.onion\z/s;
101 return if $host =~ /\A127\.[0-9]+\.[0-9]+\.[0-9]+\z/s;
102 return if $host eq '::1';
107 my ($nn_arg, $nntp_opt, $uri) = @_;
108 my $nn = Net::NNTP->new(%$nn_arg) or die "E: <$uri> new: $!\n";
110 # default to using STARTTLS if it's available, but allow
111 # it to be disabled for localhost/VPN users
112 if (!$nn_arg->{SSL} && $nn->can('starttls')) {
113 if (!defined($nntp_opt->{starttls}) &&
114 try_starttls($nn_arg->{Host})) {
115 # soft fail by default
116 $nn->starttls or warn <<"";
117 W: <$uri> STARTTLS tried and failed (not requested)
119 } elsif ($nntp_opt->{starttls}) {
120 # hard fail if explicitly configured
121 $nn->starttls or die <<"";
122 E: <$uri> STARTTLS requested and failed
125 } elsif ($nntp_opt->{starttls}) {
126 $nn->can('starttls') or
127 die "E: <$uri> Net::NNTP too old for STARTTLS\n";
128 $nn->starttls or die <<"";
129 E: <$uri> STARTTLS requested and failed
135 sub nn_for ($$$;$) { # nn = Net::NNTP
136 my ($self, $uri, $nn_args, $lei) = @_;
137 my $sec = uri_section($uri);
138 my $nntp_opt = $self->{nntp_opt}->{$sec} //= {};
139 my $host = $uri->host;
140 # Net::NNTP and Net::Netrc both mishandle `0', so we pass `127.0.0.1'
141 $host = '127.0.0.1' if $host eq '0';
144 if (defined(my $ui = $uri->userinfo)) {
145 require PublicInbox::GitCredential;
148 protocol => $uri->scheme,
150 }, 'PublicInbox::GitCredential';
151 ($u, $p) = split(/:/, $ui, 2);
152 ($cred->{username}, $cred->{password}) = ($u, $p);
153 $cred->check_netrc unless defined $p;
155 my $common = $nn_args->{$sec} // {};
159 SSL => $uri->secure, # snews == nntps
160 %$common, # may Debug ....
162 my $nn = nn_new($nn_arg, $nntp_opt, $uri);
164 $cred->fill($lei); # may prompt user here
165 if ($nn->authinfo($u, $p)) {
166 push @{$nntp_opt->{-postconn}}, [ 'authinfo', $u, $p ];
168 warn "E: <$uri> AUTHINFO $u XXXX failed\n";
173 if ($nntp_opt->{compress}) {
174 # https://rt.cpan.org/Ticket/Display.html?id=129967
175 if ($nn->can('compress')) {
177 push @{$nntp_opt->{-postconn}}, [ 'compress' ];
179 warn "W: <$uri> COMPRESS failed\n";
182 delete $nntp_opt->{compress};
184 W: <$uri> COMPRESS not supported by Net::NNTP
185 W: see https://rt.cpan.org/Ticket/Display.html?id=129967 for updates
190 $self->{nn_arg}->{$sec} = $nn_arg;
191 $cred->run($nn ? 'approve' : 'reject') if $cred;
197 require PublicInbox::URIimap;
198 my $uri = PublicInbox::URIimap->new($url);
199 $uri ? $uri->canonical : undef;
202 my %IS_NNTP = (news => 1, snews => 1, nntp => 1, nntps => 1);
205 require PublicInbox::URInntps;
206 my $uri = PublicInbox::URInntps->new($url);
207 $uri && $IS_NNTP{$uri->scheme} && $uri->group ? $uri->canonical : undef;
210 sub cfg_intvl ($$$) {
211 my ($cfg, $key, $url) = @_;
212 my $v = $cfg->urlmatch($key, $url) // return;
213 $v =~ /\A[0-9]+(?:\.[0-9]+)?\z/s and return $v + 0;
214 if (ref($v) eq 'ARRAY') {
215 $v = join(', ', @$v);
216 warn "W: $key has multiple values: $v\nW: $key ignored\n";
218 warn "W: $key=$v is not a numeric value in seconds\n";
223 my ($cfg, $key, $url) = @_;
224 my $orig = $cfg->urlmatch($key, $url) // return;
225 my $bool = $cfg->git_bool($orig);
226 warn "W: $key=$orig for $url is not boolean\n" unless defined($bool);
230 # flesh out common IMAP-specific data structures
231 sub imap_common_init ($;$) {
232 my ($self, $lei) = @_;
233 return unless $self->{imap_order};
234 $self->{quiet} = 1 if $lei && $lei->{opt}->{quiet};
235 eval { require PublicInbox::IMAPClient } or
236 die "Mail::IMAPClient is required for IMAP:\n$@\n";
237 eval { require PublicInbox::IMAPTracker } or
238 die "DBD::SQLite is required for IMAP\n:$@\n";
239 require PublicInbox::URIimap;
240 my $cfg = $self->{pi_cfg} // $lei->_lei_cfg;
241 my $mic_args = {}; # scheme://authority => Mail:IMAPClient arg
242 for my $uri (@{$self->{imap_order}}) {
243 my $sec = uri_section($uri);
244 for my $k (qw(Starttls Debug Compress)) {
245 my $bool = cfg_bool($cfg, "imap.$k", $$uri) // next;
246 $mic_args->{$sec}->{$k} = $bool;
248 my $to = cfg_intvl($cfg, 'imap.timeout', $$uri);
249 $mic_args->{$sec}->{Timeout} = $to if $to;
250 for my $k (qw(pollInterval idleInterval)) {
251 $to = cfg_intvl($cfg, "imap.$k", $$uri) // next;
252 $self->{imap_opt}->{$sec}->{$k} = $to;
254 my $k = 'imap.fetchBatchSize';
255 my $bs = $cfg->urlmatch($k, $$uri) // next;
256 if ($bs =~ /\A([0-9]+)\z/) {
257 $self->{imap_opt}->{$sec}->{batch_size} = $bs;
259 warn "$k=$bs is not an integer\n";
262 # make sure we can connect and cache the credentials in memory
263 $self->{mic_arg} = {}; # schema://authority => IMAPClient->new args
264 my $mics = {}; # schema://authority => IMAPClient obj
265 for my $uri (@{$self->{imap_order}}) {
266 my $sec = uri_section($uri);
267 my $mic = $mics->{$sec} //=
268 mic_for($self, "$sec/", $mic_args, $lei) //
269 die "Unable to continue\n";
270 next unless $self->isa('PublicInbox::NetWriter');
271 my $dst = $uri->mailbox // next;
272 next if $mic->exists($dst); # already exists
273 $mic->create($dst) or die "CREATE $dst failed <$uri>: $@";
278 # flesh out common NNTP-specific data structures
279 sub nntp_common_init ($;$) {
280 my ($self, $lei) = @_;
281 return unless $self->{nntp_order};
282 $self->{quiet} = 1 if $lei && $lei->{opt}->{quiet};
283 eval { require Net::NNTP } or
284 die "Net::NNTP is required for NNTP:\n$@\n";
285 eval { require PublicInbox::IMAPTracker } or
286 die "DBD::SQLite is required for NNTP\n:$@\n";
287 my $cfg = $self->{pi_cfg} // $lei->_lei_cfg;
288 my $nn_args = {}; # scheme://authority => Net::NNTP->new arg
289 for my $uri (@{$self->{nntp_order}}) {
290 my $sec = uri_section($uri);
292 # Debug and Timeout are passed to Net::NNTP->new
293 my $v = cfg_bool($cfg, 'nntp.Debug', $$uri);
294 $nn_args->{$sec}->{Debug} = $v if defined $v;
295 my $to = cfg_intvl($cfg, 'nntp.Timeout', $$uri);
296 $nn_args->{$sec}->{Timeout} = $to if $to;
298 # Net::NNTP post-connect commands
299 for my $k (qw(starttls compress)) {
300 $v = cfg_bool($cfg, "nntp.$k", $$uri) // next;
301 $self->{nntp_opt}->{$sec}->{$k} = $v;
305 for my $k (qw(pollInterval)) {
306 $to = cfg_intvl($cfg, "nntp.$k", $$uri) // next;
307 $self->{nntp_opt}->{$sec}->{$k} = $to;
310 # make sure we can connect and cache the credentials in memory
311 $self->{nn_arg} = {}; # schema://authority => Net::NNTP->new args
312 my %nn; # schema://authority => Net::NNTP object
313 for my $uri (@{$self->{nntp_order}}) {
314 my $sec = uri_section($uri);
315 $nn{$sec} //= nn_for($self, $uri, $nn_args, $lei);
317 \%nn; # for optional {nn_cached}
321 my ($self, $arg) = @_;
323 if ($uri = imap_uri($arg)) {
324 push @{$self->{imap_order}}, $uri;
325 } elsif ($uri = nntp_uri($arg)) {
326 push @{$self->{nntp_order}}, $uri;
328 push @{$self->{unsupported_url}}, $arg;
334 if (my $u = $self->{unsupported_url}) {
335 return "Unsupported URL(s): @$u";
337 if ($self->{imap_order}) {
338 eval { require PublicInbox::IMAPClient } or
339 die "Mail::IMAPClient is required for IMAP:\n$@\n";
341 if ($self->{nntp_order}) {
342 eval { require Net::NNTP } or
343 die "Net::NNTP is required for NNTP:\n$@\n";
348 sub _imap_do_msg ($$$$$) {
349 my ($self, $uri, $uid, $raw, $flags) = @_;
350 # our target audience expects LF-only, save storage
351 $$raw =~ s/\r\n/\n/sg;
353 for my $f (split(/ /, $flags)) {
354 if (my $k = $IMAPflags2kw{$f}) {
356 } elsif ($f eq "\\Recent") { # not in JMAP
357 } elsif ($f eq "\\Deleted") { # not in JMAP
359 } elsif ($self->{verbose}) {
360 warn "# unknown IMAP flag $f <$uri;uid=$uid>\n";
363 @$kw = sort @$kw; # for all UI/UX purposes
364 my ($eml_cb, @args) = @{$self->{eml_each}};
365 $eml_cb->($uri, $uid, $kw, PublicInbox::Eml->new($raw), @args);
368 sub run_commit_cb ($) {
370 my $cmt_cb_args = $self->{on_commit} or return;
371 my ($cb, @args) = @$cmt_cb_args;
375 sub _imap_fetch_all ($$$) {
376 my ($self, $mic, $uri) = @_;
377 my $sec = uri_section($uri);
378 my $mbx = $uri->mailbox;
379 $mic->Clear(1); # trim results history
380 $mic->examine($mbx) or return "E: EXAMINE $mbx ($sec) failed: $!";
381 my ($r_uidval, $r_uidnext);
382 for ($mic->Results) {
383 /^\* OK \[UIDVALIDITY ([0-9]+)\].*/ and $r_uidval = $1;
384 /^\* OK \[UIDNEXT ([0-9]+)\].*/ and $r_uidnext = $1;
385 last if $r_uidval && $r_uidnext;
387 $r_uidval //= $mic->uidvalidity($mbx) //
388 return "E: $uri cannot get UIDVALIDITY";
389 $r_uidnext //= $mic->uidnext($mbx) //
390 return "E: $uri cannot get UIDNEXT";
391 my $itrk = $self->{incremental} ?
392 PublicInbox::IMAPTracker->new($$uri) : 0;
393 my ($l_uidval, $l_uid) = $itrk ? $itrk->get_last : ();
394 $l_uidval //= $r_uidval; # first time
396 if ($l_uidval != $r_uidval) {
397 return "E: $uri UIDVALIDITY mismatch\n".
398 "E: local=$l_uidval != remote=$r_uidval";
400 my $r_uid = $r_uidnext - 1;
401 if ($l_uid > $r_uid) {
402 return "E: $uri local UID exceeds remote ($l_uid > $r_uid)\n".
403 "E: $uri strangely, UIDVALIDLITY matches ($l_uidval)\n";
405 return if $l_uid >= $r_uid; # nothing to do
407 my ($mod, $shard) = @{$self->{shard_info} // []};
408 unless ($self->{quiet}) {
409 my $m = $mod ? " [(UID % $mod) == $shard]" : '';
410 warn "# $uri fetching UID $l_uid:$r_uid$m\n";
412 $mic->Uid(1); # the default, we hope
413 my $bs = $self->{imap_opt}->{$sec}->{batch_size} // 1;
414 my $req = $mic->imap4rev1 ? 'BODY.PEEK[]' : 'RFC822.PEEK';
420 # I wish "UID FETCH $START:*" could work, but:
421 # 1) servers do not need to return results in any order
422 # 2) Mail::IMAPClient doesn't offer a streaming API
423 unless ($uids = $mic->search("UID $l_uid:*")) {
424 return if $!{EINTR} && $self->{quit};
425 return "E: $uri UID SEARCH $l_uid:* error: $!";
427 return if scalar(@$uids) == 0;
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;
434 # Did we actually get new messages?
435 return if $uids->[0] < $l_uid;
437 $l_uid = $uids->[-1] + 1; # for next search
439 my $n = $self->{max_batch};
441 @$uids = grep { ($_ % $mod) == $shard } @$uids if $mod;
442 while (scalar @$uids) {
443 my @batch = splice(@$uids, 0, $bs);
444 $batch = join(',', @batch);
445 local $0 = "UID:$batch $mbx $sec";
446 my $r = $mic->fetch_hash($batch, $req, 'FLAGS');
447 unless ($r) { # network error?
448 last if $!{EINTR} && $self->{quit};
449 $err = "E: $uri UID FETCH $batch error: $!";
452 for my $uid (@batch) {
453 # messages get deleted, so holes appear
454 my $per_uid = delete $r->{$uid} // next;
455 my $raw = delete($per_uid->{$key}) // next;
456 _imap_do_msg($self, $uri, $uid, \$raw,
459 last if $self->{quit};
461 last if $self->{quit};
463 run_commit_cb($self);
464 $itrk->update_last($r_uidval, $last_uid) if $itrk;
465 } until ($err || $self->{quit});
469 # uses cached auth info prepared by mic_for
471 my ($self, $uri) = @_;
472 my $sec = uri_section($uri);
473 # see if caller saved result of imap_common_init
474 my $cached = $self->{mics_cached};
476 my $mic = $cached->{$sec};
477 return $mic if $mic && $mic->IsConnected;
478 delete $cached->{$sec};
480 my $mic_arg = $self->{mic_arg}->{$sec} or
481 die "BUG: no Mail::IMAPClient->new arg for $sec";
482 if (defined(my $cb_name = $mic_arg->{Authcallback})) {
483 if (ref($cb_name) ne 'CODE') {
484 $mic_arg->{Authcallback} = $self->can($cb_name);
487 my $mic = PublicInbox::IMAPClient->new(%$mic_arg);
488 $cached //= {}; # invalid placeholder if no cache enabled
489 $mic && $mic->IsConnected ? ($cached->{$sec} = $mic) : undef;
493 my ($self, $url, $eml_cb, @args) = @_;
494 my $uri = ref($url) ? $url : PublicInbox::URIimap->new($url);
495 my $sec = uri_section($uri);
496 local $0 = $uri->mailbox." $sec";
497 my $mic = mic_get($self, $uri);
500 local $self->{eml_each} = [ $eml_cb, @args ];
501 $err = _imap_fetch_all($self, $mic, $uri);
503 $err = "E: <$uri> not connected: $!";
509 # may used cached auth info prepared by nn_for once
511 my ($self, $uri) = @_;
512 my $sec = uri_section($uri);
513 # see if caller saved result of nntp_common_init
514 my $cached = $self->{nn_cached} // {};
516 $nn = delete($cached->{$sec}) and return $nn;
517 my $nn_arg = $self->{nn_arg}->{$sec} or
518 die "BUG: no Net::NNTP->new arg for $sec";
519 my $nntp_opt = $self->{nntp_opt}->{$sec};
520 $nn = nn_new($nn_arg, $nntp_opt, $uri) or return;
521 if (my $postconn = $nntp_opt->{-postconn}) {
522 for my $m_arg (@$postconn) {
523 my ($method, @args) = @$m_arg;
524 $nn->$method(@args) and next;
525 die "E: <$uri> $method failed\n";
532 sub _nntp_fetch_all ($$$) {
533 my ($self, $nn, $uri) = @_;
534 my ($group, $num_a, $num_b) = $uri->group;
535 my $sec = uri_section($uri);
536 my ($nr, $beg, $end) = $nn->group($group);
537 unless (defined($nr)) {
538 my $msg = ndump($nn->message);
539 return "E: GROUP $group <$sec> $msg";
542 # IMAPTracker is also used for tracking NNTP, UID == article number
543 # LIST.ACTIVE can get the equivalent of UIDVALIDITY, but that's
544 # expensive. So we assume newsgroups don't change:
545 my $itrk = $self->{incremental} ?
546 PublicInbox::IMAPTracker->new($$uri) : 0;
547 my (undef, $l_art) = $itrk ? $itrk->get_last : ();
549 # allow users to specify articles to refetch
550 # cf. https://tools.ietf.org/id/draft-gilman-news-url-01.txt
551 # nntp://example.com/inbox.foo/$num_a-$num_b
552 $beg = $num_a if defined($num_a) && $num_a < $beg;
553 $end = $num_b if defined($num_b) && $num_b < $end;
554 if (defined $l_art) {
555 return if $l_art >= $end; # nothing to do
558 my ($err, $art, $last_art, $kw); # kw stays undef, no keywords in NNTP
559 unless ($self->{quiet}) {
560 warn "# $uri fetching ARTICLE $beg..$end\n";
562 my $n = $self->{max_batch};
564 last if $self->{quit};
567 run_commit_cb($self);
568 $itrk->update_last(0, $last_art) if $itrk;
569 $n = $self->{max_batch};
571 my $raw = $nn->article($art);
572 unless (defined($raw)) {
573 my $msg = ndump($nn->message);
574 if ($nn->code == 421) { # pseudo response from Net::Cmd
577 } else { # probably just a deleted message (spam)
582 $raw = join('', @$raw);
583 $raw =~ s/\r\n/\n/sg;
584 my ($eml_cb, @args) = @{$self->{eml_each}};
585 $eml_cb->($uri, $art, $kw, PublicInbox::Eml->new(\$raw), @args);
588 run_commit_cb($self);
589 $itrk->update_last(0, $last_art) if $itrk;
594 my ($self, $url, $eml_cb, @args) = @_;
595 my $uri = ref($url) ? $url : PublicInbox::URInntps->new($url);
596 my $sec = uri_section($uri);
597 local $0 = $uri->group ." $sec";
598 my $nn = nn_get($self, $uri);
599 return if $self->{quit};
602 local $self->{eml_each} = [ $eml_cb, @args ];
603 $err = _nntp_fetch_all($self, $nn, $uri);
605 $err = "E: <$uri> not connected: $!";
611 sub new { bless {}, shift };