]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/NetReader.pm
watch: move imap_common_init to NetReader
[public-inbox.git] / lib / PublicInbox / NetReader.pm
1 # Copyright (C) 2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # common reader code for IMAP and NNTP (and maybe JMAP)
5 package PublicInbox::NetReader;
6 use strict;
7 use v5.10.1;
8 use parent qw(Exporter);
9
10 # TODO: trim this down, this is huge
11 our @EXPORT = qw(uri_new uri_scheme uri_section
12                 mic_for nn_new nn_for
13                 imap_url nntp_url
14                 cfg_bool cfg_intvl imap_common_init
15                 );
16
17 # avoid exposing deprecated "snews" to users.
18 my %SCHEME_MAP = ('snews' => 'nntps');
19
20 sub uri_scheme ($) {
21         my ($uri) = @_;
22         my $scheme = $uri->scheme;
23         $SCHEME_MAP{$scheme} // $scheme;
24 }
25
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
28 sub uri_section ($) {
29         my ($uri) = @_;
30         uri_scheme($uri) . '://' . $uri->authority;
31 }
32
33 sub auth_anon_cb { '' }; # for Mail::IMAPClient::Authcallback
34
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;
40         my $cred = bless {
41                 url => $url,
42                 protocol => $uri->scheme,
43                 host => $uri->host,
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';
51         my $mic_arg = {
52                 Port => $uri->port,
53                 Server => $host,
54                 Ssl => $uri->scheme eq 'imaps',
55                 Keepalive => 1, # SO_KEEPALIVE
56                 %$common, # may set Starttls, Compress, Debug ....
57         };
58         require PublicInbox::IMAPClient;
59         my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or
60                 die "E: <$url> new: $@\n";
61
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";
68         }
69
70         # do we even need credentials?
71         if (!defined($cred->{username}) &&
72                         $mic->has_capability('AUTH=ANONYMOUS')) {
73                 $cred = undef;
74         }
75         if ($cred) {
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);
83         }
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;
87         } else {
88                 warn "E: <$url> LOGIN: $@\n";
89                 $mic = undef;
90         }
91         $cred->run($mic ? 'approve' : 'reject') if $cred;
92         $mic;
93 }
94
95 sub uri_new {
96         my ($url) = @_;
97         require URI;
98
99         # URI::snews exists, URI::nntps does not, so use URI::snews
100         $url =~ s!\Anntps://!snews://!i;
101         URI->new($url);
102 }
103
104 # Net::NNTP doesn't support CAPABILITIES, yet
105 sub try_starttls ($) {
106         my ($host) = @_;
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';
110         1;
111 }
112
113 sub nn_new ($$$) {
114         my ($nn_arg, $nntp_opt, $url) = @_;
115         my $nn = Net::NNTP->new(%$nn_arg) or die "E: <$url> new: $!\n";
116
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)
125
126                 } elsif ($nntp_opt->{starttls}) {
127                         # hard fail if explicitly configured
128                         $nn->starttls or die <<"";
129 E: <$url> STARTTLS requested and failed
130
131                 }
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
137
138         }
139         $nn;
140 }
141
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';
150         my $cred;
151         my ($u, $p);
152         if (defined(my $ui = $uri->userinfo)) {
153                 require PublicInbox::GitCredential;
154                 $cred = bless {
155                         url => $sec,
156                         protocol => uri_scheme($uri),
157                         host => $host,
158                 }, 'PublicInbox::GitCredential';
159                 ($u, $p) = split(/:/, $ui, 2);
160                 ($cred->{username}, $cred->{password}) = ($u, $p);
161                 $cred->check_netrc unless defined $p;
162         }
163         my $common = $nn_args->{$sec} // {};
164         my $nn_arg = {
165                 Port => $uri->port,
166                 Host => $host,
167                 SSL => $uri->secure, # snews == nntps
168                 %$common, # may Debug ....
169         };
170         my $nn = nn_new($nn_arg, $nntp_opt, $url);
171
172         if ($cred) {
173                 $cred->fill; # may prompt user here
174                 if ($nn->authinfo($u, $p)) {
175                         push @{$nntp_opt->{-postconn}}, [ 'authinfo', $u, $p ];
176                 } else {
177                         warn "E: <$url> AUTHINFO $u XXXX failed\n";
178                         $nn = undef;
179                 }
180         }
181
182         if ($nntp_opt->{compress}) {
183                 # https://rt.cpan.org/Ticket/Display.html?id=129967
184                 if ($nn->can('compress')) {
185                         if ($nn->compress) {
186                                 push @{$nntp_opt->{-postconn}}, [ 'compress' ];
187                         } else {
188                                 warn "W: <$url> COMPRESS failed\n";
189                         }
190                 } else {
191                         delete $nntp_opt->{compress};
192                         warn <<"";
193 W: <$url> COMPRESS not supported by Net::NNTP
194 W: see https://rt.cpan.org/Ticket/Display.html?id=129967 for updates
195
196                 }
197         }
198
199         $self->{nn_arg}->{$sec} = $nn_arg;
200         $cred->run($nn ? 'approve' : 'reject') if $cred;
201         $nn;
202 }
203
204 sub imap_url {
205         my ($url) = @_;
206         require PublicInbox::URIimap;
207         my $uri = PublicInbox::URIimap->new($url);
208         $uri ? $uri->canonical->as_string : undef;
209 }
210
211 my %IS_NNTP = (news => 1, snews => 1, nntp => 1);
212 sub nntp_url {
213         my ($url) = @_;
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://!;
219         $url;
220 }
221
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";
229         } else {
230                 warn "W: $key=$v is not a numeric value in seconds\n";
231         }
232 }
233
234 sub cfg_bool ($$$) {
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);
239         $bool;
240 }
241
242 # flesh out common IMAP-specific data structures
243 sub imap_common_init ($) {
244         my ($self) = @_;
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;
258                 }
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;
264                 }
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;
269                 } else {
270                         warn "$k=$bs is not an integer\n";
271                 }
272         }
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);
279         }
280         $mics;
281 }
282
283 1;