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);
10 # TODO: trim this down, this is huge
11 our @EXPORT = qw(uri_new uri_scheme uri_section
14 cfg_bool cfg_intvl imap_common_init
17 # avoid exposing deprecated "snews" to users.
18 my %SCHEME_MAP = ('snews' => 'nntps');
22 my $scheme = $uri->scheme;
23 $SCHEME_MAP{$scheme} // $scheme;
26 # returns the git config section name, e.g [imap "imaps://user@example.com"]
27 # without the mailbox, so we can share connections between different inboxes
30 uri_scheme($uri) . '://' . $uri->authority;
33 sub auth_anon_cb { '' }; # for Mail::IMAPClient::Authcallback
35 sub mic_for { # mic = Mail::IMAPClient
36 my ($self, $url, $mic_args) = @_;
37 require PublicInbox::URIimap;
38 my $uri = PublicInbox::URIimap->new($url);
39 require PublicInbox::GitCredential;
42 protocol => $uri->scheme,
44 username => $uri->user,
45 password => $uri->password,
46 }, 'PublicInbox::GitCredential';
47 my $common = $mic_args->{uri_section($uri)} // {};
48 # IMAPClient and Net::Netrc both mishandles `0', so we pass `127.0.0.1'
49 my $host = $cred->{host};
50 $host = '127.0.0.1' if $host eq '0';
54 Ssl => $uri->scheme eq 'imaps',
55 Keepalive => 1, # SO_KEEPALIVE
56 %$common, # may set Starttls, Compress, Debug ....
58 require PublicInbox::IMAPClient;
59 my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or
60 die "E: <$url> new: $@\n";
62 # default to using STARTTLS if it's available, but allow
63 # it to be disabled since I usually connect to localhost
64 if (!$mic_arg->{Ssl} && !defined($mic_arg->{Starttls}) &&
65 $mic->has_capability('STARTTLS') &&
66 $mic->can('starttls')) {
67 $mic->starttls or die "E: <$url> STARTTLS: $@\n";
70 # do we even need credentials?
71 if (!defined($cred->{username}) &&
72 $mic->has_capability('AUTH=ANONYMOUS')) {
76 $cred->check_netrc unless defined $cred->{password};
77 $cred->fill; # may prompt user here
78 $mic->User($mic_arg->{User} = $cred->{username});
79 $mic->Password($mic_arg->{Password} = $cred->{password});
80 } else { # AUTH=ANONYMOUS
81 $mic->Authmechanism($mic_arg->{Authmechanism} = 'ANONYMOUS');
82 $mic->Authcallback($mic_arg->{Authcallback} = \&auth_anon_cb);
84 if ($mic->login && $mic->IsAuthenticated) {
85 # success! keep IMAPClient->new arg in case we get disconnected
86 $self->{mic_arg}->{uri_section($uri)} = $mic_arg;
88 warn "E: <$url> LOGIN: $@\n";
91 $cred->run($mic ? 'approve' : 'reject') if $cred;
99 # URI::snews exists, URI::nntps does not, so use URI::snews
100 $url =~ s!\Anntps://!snews://!i;
104 # Net::NNTP doesn't support CAPABILITIES, yet
105 sub try_starttls ($) {
107 return if $host =~ /\.onion\z/s;
108 return if $host =~ /\A127\.[0-9]+\.[0-9]+\.[0-9]+\z/s;
109 return if $host eq '::1';
114 my ($nn_arg, $nntp_opt, $url) = @_;
115 my $nn = Net::NNTP->new(%$nn_arg) or die "E: <$url> new: $!\n";
117 # default to using STARTTLS if it's available, but allow
118 # it to be disabled for localhost/VPN users
119 if (!$nn_arg->{SSL} && $nn->can('starttls')) {
120 if (!defined($nntp_opt->{starttls}) &&
121 try_starttls($nn_arg->{Host})) {
122 # soft fail by default
123 $nn->starttls or warn <<"";
124 W: <$url> STARTTLS tried and failed (not requested)
126 } elsif ($nntp_opt->{starttls}) {
127 # hard fail if explicitly configured
128 $nn->starttls or die <<"";
129 E: <$url> STARTTLS requested and failed
132 } elsif ($nntp_opt->{starttls}) {
133 $nn->can('starttls') or
134 die "E: <$url> Net::NNTP too old for STARTTLS\n";
135 $nn->starttls or die <<"";
136 E: <$url> STARTTLS requested and failed
142 sub nn_for ($$$) { # nn = Net::NNTP
143 my ($self, $url, $nn_args) = @_;
144 my $uri = uri_new($url);
145 my $sec = uri_section($uri);
146 my $nntp_opt = $self->{nntp_opt}->{$sec} //= {};
147 my $host = $uri->host;
148 # Net::NNTP and Net::Netrc both mishandle `0', so we pass `127.0.0.1'
149 $host = '127.0.0.1' if $host eq '0';
152 if (defined(my $ui = $uri->userinfo)) {
153 require PublicInbox::GitCredential;
156 protocol => uri_scheme($uri),
158 }, 'PublicInbox::GitCredential';
159 ($u, $p) = split(/:/, $ui, 2);
160 ($cred->{username}, $cred->{password}) = ($u, $p);
161 $cred->check_netrc unless defined $p;
163 my $common = $nn_args->{$sec} // {};
167 SSL => $uri->secure, # snews == nntps
168 %$common, # may Debug ....
170 my $nn = nn_new($nn_arg, $nntp_opt, $url);
173 $cred->fill; # may prompt user here
174 if ($nn->authinfo($u, $p)) {
175 push @{$nntp_opt->{-postconn}}, [ 'authinfo', $u, $p ];
177 warn "E: <$url> AUTHINFO $u XXXX failed\n";
182 if ($nntp_opt->{compress}) {
183 # https://rt.cpan.org/Ticket/Display.html?id=129967
184 if ($nn->can('compress')) {
186 push @{$nntp_opt->{-postconn}}, [ 'compress' ];
188 warn "W: <$url> COMPRESS failed\n";
191 delete $nntp_opt->{compress};
193 W: <$url> COMPRESS not supported by Net::NNTP
194 W: see https://rt.cpan.org/Ticket/Display.html?id=129967 for updates
199 $self->{nn_arg}->{$sec} = $nn_arg;
200 $cred->run($nn ? 'approve' : 'reject') if $cred;
206 require PublicInbox::URIimap;
207 my $uri = PublicInbox::URIimap->new($url);
208 $uri ? $uri->canonical->as_string : undef;
211 my %IS_NNTP = (news => 1, snews => 1, nntp => 1);
214 my $uri = uri_new($url);
215 return unless $uri && $IS_NNTP{$uri->scheme} && $uri->group;
216 $url = $uri->canonical->as_string;
217 # nntps is IANA registered, snews is deprecated
218 $url =~ s!\Asnews://!nntps://!;
222 sub cfg_intvl ($$$) {
223 my ($cfg, $key, $url) = @_;
224 my $v = $cfg->urlmatch($key, $url) // return;
225 $v =~ /\A[0-9]+(?:\.[0-9]+)?\z/s and return $v + 0;
226 if (ref($v) eq 'ARRAY') {
227 $v = join(', ', @$v);
228 warn "W: $key has multiple values: $v\nW: $key ignored\n";
230 warn "W: $key=$v is not a numeric value in seconds\n";
235 my ($cfg, $key, $url) = @_;
236 my $orig = $cfg->urlmatch($key, $url) // return;
237 my $bool = $cfg->git_bool($orig);
238 warn "W: $key=$orig for $url is not boolean\n" unless defined($bool);
242 # flesh out common IMAP-specific data structures
243 sub imap_common_init ($) {
245 eval { require PublicInbox::IMAPClient } or
246 die "Mail::IMAPClient is required for IMAP:\n$@\n";
247 eval { require PublicInbox::IMAPTracker } or
248 die "DBD::SQLite is required for IMAP\n:$@\n";
249 require PublicInbox::URIimap;
250 my $cfg = $self->{pi_cfg};
251 my $mic_args = {}; # scheme://authority => Mail:IMAPClient arg
252 for my $url (sort keys %{$self->{imap}}) {
253 my $uri = PublicInbox::URIimap->new($url);
254 my $sec = uri_section($uri);
255 for my $k (qw(Starttls Debug Compress)) {
256 my $bool = cfg_bool($cfg, "imap.$k", $url) // next;
257 $mic_args->{$sec}->{$k} = $bool;
259 my $to = cfg_intvl($cfg, 'imap.timeout', $url);
260 $mic_args->{$sec}->{Timeout} = $to if $to;
261 for my $k (qw(pollInterval idleInterval)) {
262 $to = cfg_intvl($cfg, "imap.$k", $url) // next;
263 $self->{imap_opt}->{$sec}->{$k} = $to;
265 my $k = 'imap.fetchBatchSize';
266 my $bs = $cfg->urlmatch($k, $url) // next;
267 if ($bs =~ /\A([0-9]+)\z/) {
268 $self->{imap_opt}->{$sec}->{batch_size} = $bs;
270 warn "$k=$bs is not an integer\n";
273 # make sure we can connect and cache the credentials in memory
274 $self->{mic_arg} = {}; # schema://authority => IMAPClient->new args
275 my $mics = {}; # schema://authority => IMAPClient obj
276 for my $url (sort keys %{$self->{imap}}) {
277 my $uri = PublicInbox::URIimap->new($url);
278 $mics->{uri_section($uri)} //= mic_for($self, $url, $mic_args);