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 our %IMAPflags2kw = map {; "\\\u$_" => $_ } qw(seen answered flagged draft);
13 # TODO: trim this down, this is huge
14 our @EXPORT = qw(uri_new uri_scheme uri_section
17 cfg_bool cfg_intvl imap_common_init
20 # avoid exposing deprecated "snews" to users.
21 my %SCHEME_MAP = ('snews' => 'nntps');
25 my $scheme = $uri->scheme;
26 $SCHEME_MAP{$scheme} // $scheme;
29 # returns the git config section name, e.g [imap "imaps://user@example.com"]
30 # without the mailbox, so we can share connections between different inboxes
33 uri_scheme($uri) . '://' . $uri->authority;
36 sub auth_anon_cb { '' }; # for Mail::IMAPClient::Authcallback
38 # mic_for may prompt the user and store auth info, prepares mic_get
39 sub mic_for { # mic = Mail::IMAPClient
40 my ($self, $url, $mic_args, $lei) = @_;
41 require PublicInbox::URIimap;
42 my $uri = PublicInbox::URIimap->new($url);
43 require PublicInbox::GitCredential;
46 protocol => $uri->scheme,
48 username => $uri->user,
49 password => $uri->password,
50 }, 'PublicInbox::GitCredential';
51 my $common = $mic_args->{uri_section($uri)} // {};
52 # IMAPClient and Net::Netrc both mishandles `0', so we pass `127.0.0.1'
53 my $host = $cred->{host};
54 $host = '127.0.0.1' if $host eq '0';
58 Ssl => $uri->scheme eq 'imaps',
59 Keepalive => 1, # SO_KEEPALIVE
60 %$common, # may set Starttls, Compress, Debug ....
62 require PublicInbox::IMAPClient;
63 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or
64 die "E: <$url> new: $@\n";
66 # default to using STARTTLS if it's available, but allow
67 # it to be disabled since I usually connect to localhost
68 if (!$mic_arg->{Ssl} && !defined($mic_arg->{Starttls}) &&
69 $mic->has_capability('STARTTLS') &&
70 $mic->can('starttls')) {
71 $mic->starttls or die "E: <$url> STARTTLS: $@\n";
74 # do we even need credentials?
75 if (!defined($cred->{username}) &&
76 $mic->has_capability('AUTH=ANONYMOUS')) {
80 $cred->check_netrc unless defined $cred->{password};
81 $cred->fill($lei); # may prompt user here
82 $mic->User($mic_arg->{User} = $cred->{username});
83 $mic->Password($mic_arg->{Password} = $cred->{password});
84 } else { # AUTH=ANONYMOUS
85 $mic->Authmechanism($mic_arg->{Authmechanism} = 'ANONYMOUS');
86 $mic_arg->{Authcallback} = 'auth_anon_cb';
87 $mic->Authcallback(\&auth_anon_cb);
90 if ($mic->login && $mic->IsAuthenticated) {
91 # success! keep IMAPClient->new arg in case we get disconnected
92 $self->{mic_arg}->{uri_section($uri)} = $mic_arg;
94 $err = "E: <$url> LOGIN: $@\n";
95 if ($cred && defined($cred->{password})) {
96 $err =~ s/\Q$cred->{password}\E/*******/g;
100 $cred->run($mic ? 'approve' : 'reject') if $cred;
102 $lei ? $lei->fail($err) : warn($err);
111 # URI::snews exists, URI::nntps does not, so use URI::snews
112 $url =~ s!\Anntps://!snews://!i;
116 # Net::NNTP doesn't support CAPABILITIES, yet
117 sub try_starttls ($) {
119 return if $host =~ /\.onion\z/s;
120 return if $host =~ /\A127\.[0-9]+\.[0-9]+\.[0-9]+\z/s;
121 return if $host eq '::1';
126 my ($nn_arg, $nntp_opt, $url) = @_;
127 my $nn = Net::NNTP->new(%$nn_arg) or die "E: <$url> new: $!\n";
129 # default to using STARTTLS if it's available, but allow
130 # it to be disabled for localhost/VPN users
131 if (!$nn_arg->{SSL} && $nn->can('starttls')) {
132 if (!defined($nntp_opt->{starttls}) &&
133 try_starttls($nn_arg->{Host})) {
134 # soft fail by default
135 $nn->starttls or warn <<"";
136 W: <$url> STARTTLS tried and failed (not requested)
138 } elsif ($nntp_opt->{starttls}) {
139 # hard fail if explicitly configured
140 $nn->starttls or die <<"";
141 E: <$url> STARTTLS requested and failed
144 } elsif ($nntp_opt->{starttls}) {
145 $nn->can('starttls') or
146 die "E: <$url> Net::NNTP too old for STARTTLS\n";
147 $nn->starttls or die <<"";
148 E: <$url> STARTTLS requested and failed
154 sub nn_for ($$$;$) { # nn = Net::NNTP
155 my ($self, $url, $nn_args, $lei) = @_;
156 my $uri = uri_new($url);
157 my $sec = uri_section($uri);
158 my $nntp_opt = $self->{nntp_opt}->{$sec} //= {};
159 my $host = $uri->host;
160 # Net::NNTP and Net::Netrc both mishandle `0', so we pass `127.0.0.1'
161 $host = '127.0.0.1' if $host eq '0';
164 if (defined(my $ui = $uri->userinfo)) {
165 require PublicInbox::GitCredential;
168 protocol => uri_scheme($uri),
170 }, 'PublicInbox::GitCredential';
171 ($u, $p) = split(/:/, $ui, 2);
172 ($cred->{username}, $cred->{password}) = ($u, $p);
173 $cred->check_netrc unless defined $p;
175 my $common = $nn_args->{$sec} // {};
179 SSL => $uri->secure, # snews == nntps
180 %$common, # may Debug ....
182 my $nn = nn_new($nn_arg, $nntp_opt, $url);
185 $cred->fill($lei); # may prompt user here
186 if ($nn->authinfo($u, $p)) {
187 push @{$nntp_opt->{-postconn}}, [ 'authinfo', $u, $p ];
189 warn "E: <$url> AUTHINFO $u XXXX failed\n";
194 if ($nntp_opt->{compress}) {
195 # https://rt.cpan.org/Ticket/Display.html?id=129967
196 if ($nn->can('compress')) {
198 push @{$nntp_opt->{-postconn}}, [ 'compress' ];
200 warn "W: <$url> COMPRESS failed\n";
203 delete $nntp_opt->{compress};
205 W: <$url> COMPRESS not supported by Net::NNTP
206 W: see https://rt.cpan.org/Ticket/Display.html?id=129967 for updates
211 $self->{nn_arg}->{$sec} = $nn_arg;
212 $cred->run($nn ? 'approve' : 'reject') if $cred;
218 require PublicInbox::URIimap;
219 my $uri = PublicInbox::URIimap->new($url);
220 $uri ? $uri->canonical->as_string : undef;
223 my %IS_NNTP = (news => 1, snews => 1, nntp => 1);
226 my $uri = uri_new($url);
227 return unless $uri && $IS_NNTP{$uri->scheme} && $uri->group;
228 $url = $uri->canonical->as_string;
229 # nntps is IANA registered, snews is deprecated
230 $url =~ s!\Asnews://!nntps://!;
234 sub cfg_intvl ($$$) {
235 my ($cfg, $key, $url) = @_;
236 my $v = $cfg->urlmatch($key, $url) // return;
237 $v =~ /\A[0-9]+(?:\.[0-9]+)?\z/s and return $v + 0;
238 if (ref($v) eq 'ARRAY') {
239 $v = join(', ', @$v);
240 warn "W: $key has multiple values: $v\nW: $key ignored\n";
242 warn "W: $key=$v is not a numeric value in seconds\n";
247 my ($cfg, $key, $url) = @_;
248 my $orig = $cfg->urlmatch($key, $url) // return;
249 my $bool = $cfg->git_bool($orig);
250 warn "W: $key=$orig for $url is not boolean\n" unless defined($bool);
254 # flesh out common IMAP-specific data structures
255 sub imap_common_init ($;$) {
256 my ($self, $lei) = @_;
257 $self->{quiet} = 1 if $lei && $lei->{opt}->{quiet};
258 eval { require PublicInbox::IMAPClient } or
259 die "Mail::IMAPClient is required for IMAP:\n$@\n";
260 eval { require PublicInbox::IMAPTracker } or
261 die "DBD::SQLite is required for IMAP\n:$@\n";
262 require PublicInbox::URIimap;
263 my $cfg = $self->{pi_cfg} // $lei->_lei_cfg;
264 my $mic_args = {}; # scheme://authority => Mail:IMAPClient arg
265 for my $url (@{$self->{imap_order}}) {
266 my $uri = PublicInbox::URIimap->new($url);
267 my $sec = uri_section($uri);
268 for my $k (qw(Starttls Debug Compress)) {
269 my $bool = cfg_bool($cfg, "imap.$k", $url) // next;
270 $mic_args->{$sec}->{$k} = $bool;
272 my $to = cfg_intvl($cfg, 'imap.timeout', $url);
273 $mic_args->{$sec}->{Timeout} = $to if $to;
274 for my $k (qw(pollInterval idleInterval)) {
275 $to = cfg_intvl($cfg, "imap.$k", $url) // next;
276 $self->{imap_opt}->{$sec}->{$k} = $to;
278 my $k = 'imap.fetchBatchSize';
279 my $bs = $cfg->urlmatch($k, $url) // next;
280 if ($bs =~ /\A([0-9]+)\z/) {
281 $self->{imap_opt}->{$sec}->{batch_size} = $bs;
283 warn "$k=$bs is not an integer\n";
286 # make sure we can connect and cache the credentials in memory
287 $self->{mic_arg} = {}; # schema://authority => IMAPClient->new args
288 my $mics = {}; # schema://authority => IMAPClient obj
289 for my $url (@{$self->{imap_order}}) {
290 my $uri = PublicInbox::URIimap->new($url);
291 my $sec = uri_section($uri);
292 $mics->{$sec} //= mic_for($self, "$sec/", $mic_args, $lei);
293 next unless $self->isa('PublicInbox::NetWriter');
294 my $dst = $uri->mailbox // next;
295 my $mic = $mics->{$sec};
296 next if $mic->exists($dst); # already exists
297 $mic->create($dst) or die "CREATE $dst failed <$url>: $@";
303 my ($self, $arg) = @_;
304 if (my $url = imap_url($arg)) {
305 push @{$self->{imap_order}}, $url;
307 push @{$self->{unsupported_url}}, $arg;
313 if (my $u = $self->{unsupported_url}) {
314 return "Unsupported URL(s): @$u";
316 if ($self->{imap_order}) {
317 eval { require PublicInbox::IMAPClient } or
318 die "Mail::IMAPClient is required for IMAP:\n$@\n";
323 sub _imap_do_msg ($$$$$) {
324 my ($self, $url, $uid, $raw, $flags) = @_;
325 # our target audience expects LF-only, save storage
326 $$raw =~ s/\r\n/\n/sg;
328 for my $f (split(/ /, $flags)) {
329 my $k = $IMAPflags2kw{$f} // next; # TODO: X-Label?
332 my ($eml_cb, @args) = @{$self->{eml_each}};
333 $eml_cb->($url, $uid, $kw, PublicInbox::Eml->new($raw), @args);
336 sub _imap_fetch_all ($$$) {
337 my ($self, $mic, $url) = @_;
338 my $uri = PublicInbox::URIimap->new($url);
339 my $sec = uri_section($uri);
340 my $mbx = $uri->mailbox;
341 $mic->Clear(1); # trim results history
342 $mic->examine($mbx) or return "E: EXAMINE $mbx ($sec) failed: $!";
343 my ($r_uidval, $r_uidnext);
344 for ($mic->Results) {
345 /^\* OK \[UIDVALIDITY ([0-9]+)\].*/ and $r_uidval = $1;
346 /^\* OK \[UIDNEXT ([0-9]+)\].*/ and $r_uidnext = $1;
347 last if $r_uidval && $r_uidnext;
349 $r_uidval //= $mic->uidvalidity($mbx) //
350 return "E: $url cannot get UIDVALIDITY";
351 $r_uidnext //= $mic->uidnext($mbx) //
352 return "E: $url cannot get UIDNEXT";
353 my $itrk = $self->{incremental} ?
354 PublicInbox::IMAPTracker->new($url) : 0;
355 my ($l_uidval, $l_uid) = $itrk ? $itrk->get_last : ();
356 $l_uidval //= $r_uidval; # first time
358 if ($l_uidval != $r_uidval) {
359 return "E: $url UIDVALIDITY mismatch\n".
360 "E: local=$l_uidval != remote=$r_uidval";
362 my $r_uid = $r_uidnext - 1;
363 if ($l_uid > $r_uid) {
364 return "E: $url local UID exceeds remote ($l_uid > $r_uid)\n".
365 "E: $url strangely, UIDVALIDLITY matches ($l_uidval)\n";
367 return if $l_uid >= $r_uid; # nothing to do
370 warn "# $url fetching UID $l_uid:$r_uid\n" unless $self->{quiet};
371 $mic->Uid(1); # the default, we hope
372 my $bs = $self->{imap_opt}->{$sec}->{batch_size} // 1;
373 my $req = $mic->imap4rev1 ? 'BODY.PEEK[]' : 'RFC822.PEEK';
379 # I wish "UID FETCH $START:*" could work, but:
380 # 1) servers do not need to return results in any order
381 # 2) Mail::IMAPClient doesn't offer a streaming API
382 $uids = $mic->search("UID $l_uid:*") or
383 return "E: $url UID SEARCH $l_uid:* error: $!";
384 return if scalar(@$uids) == 0;
386 # RFC 3501 doesn't seem to indicate order of UID SEARCH
387 # responses, so sort it ourselves. Order matters so
388 # IMAPTracker can store the newest UID.
389 @$uids = sort { $a <=> $b } @$uids;
391 # Did we actually get new messages?
392 return if $uids->[0] < $l_uid;
394 $l_uid = $uids->[-1] + 1; # for next search
396 my $n = $self->{max_batch};
397 while (scalar @$uids) {
398 my @batch = splice(@$uids, 0, $bs);
399 $batch = join(',', @batch);
400 local $0 = "UID:$batch $mbx $sec";
401 my $r = $mic->fetch_hash($batch, $req, 'FLAGS');
402 unless ($r) { # network error?
403 $err = "E: $url UID FETCH $batch error: $!";
406 for my $uid (@batch) {
407 # messages get deleted, so holes appear
408 my $per_uid = delete $r->{$uid} // next;
409 my $raw = delete($per_uid->{$key}) // next;
410 _imap_do_msg($self, $url, $uid, \$raw,
413 last if $self->{quit};
415 last if $self->{quit};
417 $itrk->update_last($r_uidval, $last_uid) if $itrk;
418 } until ($err || $self->{quit});
422 # uses cached auth info prepared by mic_for
424 my ($self, $sec) = @_;
425 my $mic_arg = $self->{mic_arg}->{$sec} or
426 die "BUG: no Mail::IMAPClient->new arg for $sec";
427 if (defined(my $cb_name = $mic_arg->{Authcallback})) {
428 if (ref($cb_name) ne 'CODE') {
429 $mic_arg->{Authcallback} = $self->can($cb_name);
432 my $mic = PublicInbox::IMAPClient->new(%$mic_arg);
433 $mic && $mic->IsConnected ? $mic : undef;
437 my ($self, $url, $eml_cb, @args) = @_;
438 my $uri = PublicInbox::URIimap->new($url);
439 my $sec = uri_section($uri);
440 local $0 = $uri->mailbox." $sec";
441 my $mic = mic_get($self, $sec);
444 local $self->{eml_each} = [ $eml_cb, @args ];
445 $err = _imap_fetch_all($self, $mic, $url);
447 $err = "E: not connected: $!";
453 sub new { bless {}, shift };