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);
11 # TODO: trim this down, this is huge
12 our @EXPORT = qw(uri_new uri_scheme uri_section
15 cfg_bool cfg_intvl imap_common_init
18 # avoid exposing deprecated "snews" to users.
19 my %SCHEME_MAP = ('snews' => 'nntps');
23 my $scheme = $uri->scheme;
24 $SCHEME_MAP{$scheme} // $scheme;
27 # returns the git config section name, e.g [imap "imaps://user@example.com"]
28 # without the mailbox, so we can share connections between different inboxes
31 uri_scheme($uri) . '://' . $uri->authority;
34 sub auth_anon_cb { '' }; # for Mail::IMAPClient::Authcallback
36 sub mic_for { # mic = Mail::IMAPClient
37 my ($self, $url, $mic_args, $lei) = @_;
38 require PublicInbox::URIimap;
39 my $uri = PublicInbox::URIimap->new($url);
40 require PublicInbox::GitCredential;
43 protocol => $uri->scheme,
45 username => $uri->user,
46 password => $uri->password,
47 }, 'PublicInbox::GitCredential';
48 my $common = $mic_args->{uri_section($uri)} // {};
49 # IMAPClient and Net::Netrc both mishandles `0', so we pass `127.0.0.1'
50 my $host = $cred->{host};
51 $host = '127.0.0.1' if $host eq '0';
55 Ssl => $uri->scheme eq 'imaps',
56 Keepalive => 1, # SO_KEEPALIVE
57 %$common, # may set Starttls, Compress, Debug ....
59 require PublicInbox::IMAPClient;
60 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or
61 die "E: <$url> new: $@\n";
63 # default to using STARTTLS if it's available, but allow
64 # it to be disabled since I usually connect to localhost
65 if (!$mic_arg->{Ssl} && !defined($mic_arg->{Starttls}) &&
66 $mic->has_capability('STARTTLS') &&
67 $mic->can('starttls')) {
68 $mic->starttls or die "E: <$url> STARTTLS: $@\n";
71 # do we even need credentials?
72 if (!defined($cred->{username}) &&
73 $mic->has_capability('AUTH=ANONYMOUS')) {
77 $cred->check_netrc unless defined $cred->{password};
78 $cred->fill($lei); # may prompt user here
79 $mic->User($mic_arg->{User} = $cred->{username});
80 $mic->Password($mic_arg->{Password} = $cred->{password});
81 } else { # AUTH=ANONYMOUS
82 $mic->Authmechanism($mic_arg->{Authmechanism} = 'ANONYMOUS');
83 $mic_arg->{Authcallback} = 'auth_anon_cb';
84 $mic->Authcallback(\&auth_anon_cb);
87 if ($mic->login && $mic->IsAuthenticated) {
88 # success! keep IMAPClient->new arg in case we get disconnected
89 $self->{mic_arg}->{uri_section($uri)} = $mic_arg;
91 $err = "E: <$url> LOGIN: $@\n";
94 $cred->run($mic ? 'approve' : 'reject') if $cred;
96 $lei ? $lei->fail($err) : warn($err);
105 # URI::snews exists, URI::nntps does not, so use URI::snews
106 $url =~ s!\Anntps://!snews://!i;
110 # Net::NNTP doesn't support CAPABILITIES, yet
111 sub try_starttls ($) {
113 return if $host =~ /\.onion\z/s;
114 return if $host =~ /\A127\.[0-9]+\.[0-9]+\.[0-9]+\z/s;
115 return if $host eq '::1';
120 my ($nn_arg, $nntp_opt, $url) = @_;
121 my $nn = Net::NNTP->new(%$nn_arg) or die "E: <$url> new: $!\n";
123 # default to using STARTTLS if it's available, but allow
124 # it to be disabled for localhost/VPN users
125 if (!$nn_arg->{SSL} && $nn->can('starttls')) {
126 if (!defined($nntp_opt->{starttls}) &&
127 try_starttls($nn_arg->{Host})) {
128 # soft fail by default
129 $nn->starttls or warn <<"";
130 W: <$url> STARTTLS tried and failed (not requested)
132 } elsif ($nntp_opt->{starttls}) {
133 # hard fail if explicitly configured
134 $nn->starttls or die <<"";
135 E: <$url> STARTTLS requested and failed
138 } elsif ($nntp_opt->{starttls}) {
139 $nn->can('starttls') or
140 die "E: <$url> Net::NNTP too old for STARTTLS\n";
141 $nn->starttls or die <<"";
142 E: <$url> STARTTLS requested and failed
148 sub nn_for ($$$;$) { # nn = Net::NNTP
149 my ($self, $url, $nn_args, $lei) = @_;
150 my $uri = uri_new($url);
151 my $sec = uri_section($uri);
152 my $nntp_opt = $self->{nntp_opt}->{$sec} //= {};
153 my $host = $uri->host;
154 # Net::NNTP and Net::Netrc both mishandle `0', so we pass `127.0.0.1'
155 $host = '127.0.0.1' if $host eq '0';
158 if (defined(my $ui = $uri->userinfo)) {
159 require PublicInbox::GitCredential;
162 protocol => uri_scheme($uri),
164 }, 'PublicInbox::GitCredential';
165 ($u, $p) = split(/:/, $ui, 2);
166 ($cred->{username}, $cred->{password}) = ($u, $p);
167 $cred->check_netrc unless defined $p;
169 my $common = $nn_args->{$sec} // {};
173 SSL => $uri->secure, # snews == nntps
174 %$common, # may Debug ....
176 my $nn = nn_new($nn_arg, $nntp_opt, $url);
179 $cred->fill($lei); # may prompt user here
180 if ($nn->authinfo($u, $p)) {
181 push @{$nntp_opt->{-postconn}}, [ 'authinfo', $u, $p ];
183 warn "E: <$url> AUTHINFO $u XXXX failed\n";
188 if ($nntp_opt->{compress}) {
189 # https://rt.cpan.org/Ticket/Display.html?id=129967
190 if ($nn->can('compress')) {
192 push @{$nntp_opt->{-postconn}}, [ 'compress' ];
194 warn "W: <$url> COMPRESS failed\n";
197 delete $nntp_opt->{compress};
199 W: <$url> COMPRESS not supported by Net::NNTP
200 W: see https://rt.cpan.org/Ticket/Display.html?id=129967 for updates
205 $self->{nn_arg}->{$sec} = $nn_arg;
206 $cred->run($nn ? 'approve' : 'reject') if $cred;
212 require PublicInbox::URIimap;
213 my $uri = PublicInbox::URIimap->new($url);
214 $uri ? $uri->canonical->as_string : undef;
217 my %IS_NNTP = (news => 1, snews => 1, nntp => 1);
220 my $uri = uri_new($url);
221 return unless $uri && $IS_NNTP{$uri->scheme} && $uri->group;
222 $url = $uri->canonical->as_string;
223 # nntps is IANA registered, snews is deprecated
224 $url =~ s!\Asnews://!nntps://!;
228 sub cfg_intvl ($$$) {
229 my ($cfg, $key, $url) = @_;
230 my $v = $cfg->urlmatch($key, $url) // return;
231 $v =~ /\A[0-9]+(?:\.[0-9]+)?\z/s and return $v + 0;
232 if (ref($v) eq 'ARRAY') {
233 $v = join(', ', @$v);
234 warn "W: $key has multiple values: $v\nW: $key ignored\n";
236 warn "W: $key=$v is not a numeric value in seconds\n";
241 my ($cfg, $key, $url) = @_;
242 my $orig = $cfg->urlmatch($key, $url) // return;
243 my $bool = $cfg->git_bool($orig);
244 warn "W: $key=$orig for $url is not boolean\n" unless defined($bool);
248 # flesh out common IMAP-specific data structures
249 sub imap_common_init ($;$) {
250 my ($self, $lei) = @_;
251 $self->{quiet} = 1 if $lei && $lei->{opt}->{quiet};
252 eval { require PublicInbox::IMAPClient } or
253 die "Mail::IMAPClient is required for IMAP:\n$@\n";
254 eval { require PublicInbox::IMAPTracker } or
255 die "DBD::SQLite is required for IMAP\n:$@\n";
256 require PublicInbox::URIimap;
257 my $cfg = $self->{pi_cfg} // $lei->_lei_cfg;
258 my $mic_args = {}; # scheme://authority => Mail:IMAPClient arg
259 for my $url (@{$self->{imap_order}}) {
260 my $uri = PublicInbox::URIimap->new($url);
261 my $sec = uri_section($uri);
262 for my $k (qw(Starttls Debug Compress)) {
263 my $bool = cfg_bool($cfg, "imap.$k", $url) // next;
264 $mic_args->{$sec}->{$k} = $bool;
266 my $to = cfg_intvl($cfg, 'imap.timeout', $url);
267 $mic_args->{$sec}->{Timeout} = $to if $to;
268 for my $k (qw(pollInterval idleInterval)) {
269 $to = cfg_intvl($cfg, "imap.$k", $url) // next;
270 $self->{imap_opt}->{$sec}->{$k} = $to;
272 my $k = 'imap.fetchBatchSize';
273 my $bs = $cfg->urlmatch($k, $url) // next;
274 if ($bs =~ /\A([0-9]+)\z/) {
275 $self->{imap_opt}->{$sec}->{batch_size} = $bs;
277 warn "$k=$bs is not an integer\n";
280 # make sure we can connect and cache the credentials in memory
281 $self->{mic_arg} = {}; # schema://authority => IMAPClient->new args
282 my $mics = {}; # schema://authority => IMAPClient obj
283 for my $url (@{$self->{imap_order}}) {
284 my $uri = PublicInbox::URIimap->new($url);
285 my $sec = uri_section($uri);
286 $mics->{$sec} //= mic_for($self, $url, $mic_args, $lei);
292 my ($self, $arg) = @_;
293 if (my $url = imap_url($arg)) {
294 push @{$self->{imap_order}}, $url;
296 push @{$self->{unsupported_url}}, $arg;
302 if (my $u = $self->{unsupported_url}) {
303 return "Unsupported URL(s): @$u";
305 if ($self->{imap_order}) {
306 eval { require PublicInbox::IMAPClient } or
307 die "Mail::IMAPClient is required for IMAP:\n$@\n";
314 '\Answered' => 'answered',
315 '\Flagged' => 'flagged',
319 sub _imap_do_msg ($$$$$) {
320 my ($self, $url, $uid, $raw, $flags) = @_;
321 # our target audience expects LF-only, save storage
322 $$raw =~ s/\r\n/\n/sg;
324 for my $f (split(/ /, $flags)) {
325 my $k = $IMAPflags2kw{$f} // next; # TODO: X-Label?
328 my ($eml_cb, @args) = @{$self->{eml_each}};
329 $eml_cb->($url, $uid, $kw, PublicInbox::Eml->new($raw), @args);
332 sub _imap_fetch_all ($$$) {
333 my ($self, $mic, $url) = @_;
334 my $uri = PublicInbox::URIimap->new($url);
335 my $sec = uri_section($uri);
336 my $mbx = $uri->mailbox;
337 $mic->Clear(1); # trim results history
338 $mic->examine($mbx) or return "E: EXAMINE $mbx ($sec) failed: $!";
339 my ($r_uidval, $r_uidnext);
340 for ($mic->Results) {
341 /^\* OK \[UIDVALIDITY ([0-9]+)\].*/ and $r_uidval = $1;
342 /^\* OK \[UIDNEXT ([0-9]+)\].*/ and $r_uidnext = $1;
343 last if $r_uidval && $r_uidnext;
345 $r_uidval //= $mic->uidvalidity($mbx) //
346 return "E: $url cannot get UIDVALIDITY";
347 $r_uidnext //= $mic->uidnext($mbx) //
348 return "E: $url cannot get UIDNEXT";
349 my $itrk = $self->{incremental} ?
350 PublicInbox::IMAPTracker->new($url) : 0;
351 my ($l_uidval, $l_uid) = $itrk ? $itrk->get_last : ();
352 $l_uidval //= $r_uidval; # first time
354 if ($l_uidval != $r_uidval) {
355 return "E: $url UIDVALIDITY mismatch\n".
356 "E: local=$l_uidval != remote=$r_uidval";
358 my $r_uid = $r_uidnext - 1;
359 if ($l_uid != 1 && $l_uid > $r_uid) {
360 return "E: $url local UID exceeds remote ($l_uid > $r_uid)\n".
361 "E: $url strangely, UIDVALIDLITY matches ($l_uidval)\n";
363 return if $l_uid >= $r_uid; # nothing to do
365 warn "# $url fetching UID $l_uid:$r_uid\n" unless $self->{quiet};
366 $mic->Uid(1); # the default, we hope
367 my $bs = $self->{imap_opt}->{$sec}->{batch_size} // 1;
368 my $req = $mic->imap4rev1 ? 'BODY.PEEK[]' : 'RFC822.PEEK';
374 # I wish "UID FETCH $START:*" could work, but:
375 # 1) servers do not need to return results in any order
376 # 2) Mail::IMAPClient doesn't offer a streaming API
377 $uids = $mic->search("UID $l_uid:*") or
378 return "E: $url UID SEARCH $l_uid:* error: $!";
379 return if scalar(@$uids) == 0;
381 # RFC 3501 doesn't seem to indicate order of UID SEARCH
382 # responses, so sort it ourselves. Order matters so
383 # IMAPTracker can store the newest UID.
384 @$uids = sort { $a <=> $b } @$uids;
386 # Did we actually get new messages?
387 return if $uids->[0] < $l_uid;
389 $l_uid = $uids->[-1] + 1; # for next search
391 my $n = $self->{max_batch};
392 while (scalar @$uids) {
393 my @batch = splice(@$uids, 0, $bs);
394 $batch = join(',', @batch);
395 local $0 = "UID:$batch $mbx $sec";
396 my $r = $mic->fetch_hash($batch, $req, 'FLAGS');
397 unless ($r) { # network error?
398 $err = "E: $url UID FETCH $batch error: $!";
401 for my $uid (@batch) {
402 # messages get deleted, so holes appear
403 my $per_uid = delete $r->{$uid} // next;
404 my $raw = delete($per_uid->{$key}) // next;
405 _imap_do_msg($self, $url, $uid, \$raw,
408 last if $self->{quit};
410 last if $self->{quit};
412 $itrk->update_last($r_uidval, $last_uid) if $itrk;
413 } until ($err || $self->{quit});
418 my ($self, $url, $eml_cb, @args) = @_;
419 my $uri = PublicInbox::URIimap->new($url);
420 my $sec = uri_section($uri);
421 my $mic_arg = $self->{mic_arg}->{$sec} or
422 die "BUG: no Mail::IMAPClient->new arg for $sec";
423 local $0 = $uri->mailbox." $sec";
424 my $cb_name = $mic_arg->{Authcallback};
425 if (ref($cb_name) ne 'CODE') {
426 $mic_arg->{Authcallback} = $self->can($cb_name);
428 my $mic = PublicInbox::IMAPClient->new(%$mic_arg, Debug => 0);
430 if ($mic && $mic->IsConnected) {
431 local $self->{eml_each} = [ $eml_cb, @args ];
432 $err = _imap_fetch_all($self, $mic, $url);
434 $err = "E: not connected: $!";
439 sub new { bless {}, shift };