1 # Copyright (C) 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 use PublicInbox::Config;
11 our %IMAPflags2kw = map {; "\\\u$_" => $_ } qw(seen answered flagged draft);
12 $IMAPflags2kw{'$Forwarded'} = 'forwarded'; # RFC 5550
14 our @EXPORT = qw(uri_section imap_uri nntp_uri);
18 Data::Dumper->new(\@_)->Useqq(1)->Terse(1)->Dump;
21 # returns the git config section name, e.g [imap "imaps://user@example.com"]
22 # without the mailbox, so we can share connections between different inboxes
25 $uri->scheme . '://' . $uri->authority;
30 return if ($val // '') eq '';
31 if ($val =~ m!\Asocks5h:// (?: \[ ([^\]]+) \] | ([^:/]+) )
32 (?::([0-9]+))?/*\z!ix) {
33 my ($h, $p) = ($1 // $2, $3 + 0);
34 $h = '127.0.0.1' if $h eq '0';
35 eval { require IO::Socket::Socks } or die <<EOM;
36 IO::Socket::Socks missing for socks5h://$h:$p
38 # for IO::Socket::Socks
39 return { ProxyAddr => $h, ProxyPort => $p };
41 die "$val not understood (only socks5h:// is supported)\n";
45 my ($self, $mic_arg, $sec, $uri) = @_;
46 my %mic_arg = (%$mic_arg, Keepalive => 1);
47 my $sa = $self->{cfg_opt}->{$sec}->{-proxy_cfg} || $self->{-proxy_cli};
49 # this `require' needed for worker[1..Inf], since socks_args
50 # only got called in worker[0]
51 require IO::Socket::Socks;
52 my %opt = (%$sa, Keepalive => 1);
53 $opt{SocksDebug} = 1 if $mic_arg{Debug};
54 $opt{ConnectAddr} = delete $mic_arg{Server};
55 $opt{ConnectPort} = delete $mic_arg{Port};
56 my $s = IO::Socket::Socks->new(%opt) or die
57 "E: <$uri> ".eval('$IO::Socket::Socks::SOCKS_ERROR');
58 if ($mic_arg->{Ssl}) { # for imaps://
59 require IO::Socket::SSL;
60 $s = IO::Socket::SSL->start_SSL($s) or die
61 "E: <$uri> ".(IO::Socket::SSL->errstr // '');
63 $mic_arg{Socket} = $s;
65 PublicInbox::IMAPClient->new(%mic_arg);
68 sub auth_anon_cb { '' }; # for Mail::IMAPClient::Authcallback
72 $uri->host =~ /\.onion\z/i or return "\n";
73 my $t = $uri->isa('PublicInbox::URIimap') ? 'imap' : 'nntp';
74 my $url = PublicInbox::Config::squote_maybe(uri_section($uri));
75 my $set_cfg = 'lei config';
76 if (!$lei) { # public-inbox-watch
77 my $f = PublicInbox::Config::squote_maybe(
78 $ENV{PI_CONFIG} || '~/.public-inbox/config');
79 $set_cfg = "git config -f $f";
81 my $dq = substr($url, 0, 1) eq "'" ? '"' : '';
84 Assuming you have Tor configured and running locally on port 9050,
85 try configuring a socks5h:// proxy:
88 $set_cfg $t.$dq\$url$dq.proxy socks5h://127.0.0.1:9050
90 ...before retrying your current command
94 # Net::NNTP doesn't support CAPABILITIES, yet; and both IMAP+NNTP
95 # servers may have multiple listen sockets.
96 sub try_starttls ($) {
98 return if $host =~ /\.onion\z/si;
99 return if $host =~ /\A127\.[0-9]+\.[0-9]+\.[0-9]+\z/s;
100 return if $host eq '::1';
104 # mic_for may prompt the user and store auth info, prepares mic_get
105 sub mic_for ($$$$) { # mic = Mail::IMAPClient
106 my ($self, $uri, $mic_common, $lei) = @_;
107 require PublicInbox::GitCredential;
110 protocol => $uri->scheme,
112 username => $uri->user,
113 password => $uri->password,
114 }, 'PublicInbox::GitCredential';
115 my $sec = uri_section($uri);
116 my $common = $mic_common->{$sec} // {};
117 # IMAPClient and Net::Netrc both mishandles `0', so we pass `127.0.0.1'
118 my $host = $cred->{host};
119 $host = '127.0.0.1' if $host eq '0';
123 %$common, # may set Starttls, Compress, Debug ....
125 $mic_arg->{Ssl} = 1 if $uri->scheme eq 'imaps';
126 require PublicInbox::IMAPClient;
127 my $mic = mic_new($self, $mic_arg, $sec, $uri);
128 ($mic && $mic->IsConnected) or
129 die "E: <$uri> new: $@".onion_hint($lei, $uri);
131 # default to using STARTTLS if it's available, but allow
132 # it to be disabled since I usually connect to localhost
133 if (!$mic_arg->{Ssl} && !defined($mic_arg->{Starttls}) &&
134 $mic->has_capability('STARTTLS') &&
135 try_starttls($host) &&
136 $mic->can('starttls')) {
137 $mic->starttls or die "E: <$uri> STARTTLS: $@\n";
140 # do we even need credentials?
141 if (!defined($cred->{username}) &&
142 $mic->has_capability('AUTH=ANONYMOUS')) {
146 my $p = $cred->{password} // $cred->check_netrc($lei);
147 $cred->fill($lei) unless defined($p); # may prompt user here
148 $mic->User($mic_arg->{User} = $cred->{username});
149 $mic->Password($mic_arg->{Password} = $cred->{password});
150 } else { # AUTH=ANONYMOUS
151 $mic->Authmechanism($mic_arg->{Authmechanism} = 'ANONYMOUS');
152 $mic_arg->{Authcallback} = 'auth_anon_cb';
153 $mic->Authcallback(\&auth_anon_cb);
156 if ($mic->login && $mic->IsAuthenticated) {
157 # success! keep IMAPClient->new arg in case we get disconnected
158 $self->{net_arg}->{$sec} = $mic_arg;
160 $uri->user($cred->{username}) if !defined($uri->user);
161 } elsif ($mic_arg->{Authmechanism} eq 'ANONYMOUS') {
162 $uri->auth('ANONYMOUS') if !defined($uri->auth);
165 $err = "E: <$uri> LOGIN: $@\n";
166 if ($cred && defined($cred->{password})) {
167 $err =~ s/\Q$cred->{password}\E/*******/g;
171 $cred->run($mic ? 'approve' : 'reject') if $cred && $cred->{filled};
173 $lei ? $lei->fail($err) : warn($err);
179 my ($nn_arg, $nntp_cfg, $uri) = @_;
181 if (defined $nn_arg->{ProxyAddr}) {
182 require PublicInbox::NetNNTPSocks;
183 $nn_arg->{SocksDebug} = 1 if $nn_arg->{Debug};
184 eval { $nn = PublicInbox::NetNNTPSocks->new_socks(%$nn_arg) };
185 die "E: <$uri> $@\n" if $@;
187 $nn = Net::NNTP->new(%$nn_arg) or return;
189 setsockopt($nn, Socket::SOL_SOCKET(), Socket::SO_KEEPALIVE(), 1);
191 # default to using STARTTLS if it's available, but allow
192 # it to be disabled for localhost/VPN users
193 if (!$nn_arg->{SSL} && $nn->can('starttls')) {
194 if (!defined($nntp_cfg->{starttls}) &&
195 try_starttls($nn_arg->{Host})) {
196 # soft fail by default
197 $nn->starttls or warn <<"";
198 W: <$uri> STARTTLS tried and failed (not requested)
200 } elsif ($nntp_cfg->{starttls}) {
201 # hard fail if explicitly configured
202 $nn->starttls or die <<"";
203 E: <$uri> STARTTLS requested and failed
206 } elsif ($nntp_cfg->{starttls}) {
207 $nn->can('starttls') or
208 die "E: <$uri> Net::NNTP too old for STARTTLS\n";
209 $nn->starttls or die <<"";
210 E: <$uri> STARTTLS requested and failed
216 sub nn_for ($$$$) { # nn = Net::NNTP
217 my ($self, $uri, $nn_common, $lei) = @_;
218 my $sec = uri_section($uri);
219 my $nntp_cfg = $self->{cfg_opt}->{$sec} //= {};
220 my $host = $uri->host;
221 # Net::NNTP and Net::Netrc both mishandle `0', so we pass `127.0.0.1'
222 $host = '127.0.0.1' if $host eq '0';
225 if (defined(my $ui = $uri->userinfo)) {
226 require PublicInbox::GitCredential;
229 protocol => $uri->scheme,
231 }, 'PublicInbox::GitCredential';
232 ($u, $p) = split(/:/, $ui, 2);
233 ($cred->{username}, $cred->{password}) = ($u, $p);
234 $p //= $cred->check_netrc($lei);
236 my $common = $nn_common->{$sec} // {};
240 %$common, # may Debug ....
242 $nn_arg->{SSL} = 1 if $uri->secure; # snews == nntps
243 my $sa = $self->{-proxy_cli};
244 %$nn_arg = (%$nn_arg, %$sa) if $sa;
245 my $nn = nn_new($nn_arg, $nntp_cfg, $uri) or
246 die "E: <$uri> new: $@".onion_hint($lei, $uri);
248 $cred->fill($lei) unless defined($p); # may prompt user here
249 if ($nn->authinfo($u, $p)) {
250 push @{$nntp_cfg->{-postconn}}, [ 'authinfo', $u, $p ];
252 warn "E: <$uri> AUTHINFO $u XXXX failed\n";
257 if ($nntp_cfg->{compress}) {
258 # https://rt.cpan.org/Ticket/Display.html?id=129967
259 if ($nn->can('compress')) {
261 push @{$nntp_cfg->{-postconn}}, [ 'compress' ];
263 warn "W: <$uri> COMPRESS failed\n";
266 delete $nntp_cfg->{compress};
268 W: <$uri> COMPRESS not supported by Net::NNTP
269 W: see https://rt.cpan.org/Ticket/Display.html?id=129967 for updates
274 $self->{net_arg}->{$sec} = $nn_arg;
275 $cred->run($nn ? 'approve' : 'reject') if $cred && $cred->{filled};
280 my ($url, $ls_ok) = @_;
281 require PublicInbox::URIimap;
282 my $uri = PublicInbox::URIimap->new($url);
283 $uri && ($ls_ok || $uri->mailbox) ? $uri->canonical : undef;
286 my %IS_NNTP = (news => 1, snews => 1, nntp => 1, nntps => 1);
288 my ($url, $ls_ok) = @_;
289 require PublicInbox::URInntps;
290 my $uri = PublicInbox::URInntps->new($url);
291 $uri && $IS_NNTP{$uri->scheme} && ($ls_ok || $uri->group) ?
292 $uri->canonical : undef;
295 sub cfg_intvl ($$$) {
296 my ($cfg, $key, $url) = @_;
297 my $v = $cfg->urlmatch($key, $url) // return;
298 $v =~ /\A[0-9]+(?:\.[0-9]+)?\z/s and return $v + 0;
299 if (ref($v) eq 'ARRAY') {
300 $v = join(', ', @$v);
301 warn "W: $key has multiple values: $v\nW: $key ignored\n";
303 warn "W: $key=$v is not a numeric value in seconds\n";
308 my ($cfg, $key, $url) = @_;
309 my $orig = $cfg->urlmatch($key, $url) // return;
310 my $bool = $cfg->git_bool($orig);
311 warn "W: $key=$orig for $url is not boolean\n" unless defined($bool);
315 # flesh out common IMAP-specific data structures
316 sub imap_common_init ($;$) {
317 my ($self, $lei) = @_;
318 return unless $self->{imap_order};
319 $self->{quiet} = 1 if $lei && $lei->{opt}->{quiet};
320 eval { require PublicInbox::IMAPClient } or
321 die "Mail::IMAPClient is required for IMAP:\n$@\n";
322 ($lei || eval { require PublicInbox::IMAPTracker }) or
323 die "DBD::SQLite is required for IMAP\n:$@\n";
324 require PublicInbox::URIimap;
325 my $cfg = $self->{pi_cfg} // $lei->_lei_cfg;
326 my $mic_common = {}; # scheme://authority => Mail:IMAPClient arg
327 for my $uri (@{$self->{imap_order}}) {
328 my $sec = uri_section($uri);
330 # knobs directly for Mail::IMAPClient->new
331 for my $k (qw(Starttls Debug Compress)) {
332 my $bool = cfg_bool($cfg, "imap.$k", $$uri) // next;
333 $mic_common->{$sec}->{$k} = $bool;
335 my $to = cfg_intvl($cfg, 'imap.timeout', $$uri);
336 $mic_common->{$sec}->{Timeout} = $to if $to;
338 # knobs we use ourselves:
339 my $sa = socks_args($cfg->urlmatch('imap.Proxy', $$uri));
340 $self->{cfg_opt}->{$sec}->{-proxy_cfg} = $sa if $sa;
341 for my $k (qw(pollInterval idleInterval)) {
342 $to = cfg_intvl($cfg, "imap.$k", $$uri) // next;
343 $self->{cfg_opt}->{$sec}->{$k} = $to;
345 my $k = 'imap.fetchBatchSize';
346 my $bs = $cfg->urlmatch($k, $$uri) // next;
347 if ($bs =~ /\A([0-9]+)\z/ && $bs > 0) {
348 $self->{cfg_opt}->{$sec}->{batch_size} = $bs;
350 warn "$k=$bs is not a positive integer\n";
353 # make sure we can connect and cache the credentials in memory
354 my $mics = {}; # schema://authority => IMAPClient obj
355 for my $orig_uri (@{$self->{imap_order}}) {
356 my $sec = uri_section($orig_uri);
357 my $uri = PublicInbox::URIimap->new("$sec/");
358 my $mic = $mics->{$sec} //=
359 mic_for($self, $uri, $mic_common, $lei) //
360 die "Unable to continue\n";
361 next unless $self->isa('PublicInbox::NetWriter');
362 next if $self->{-skip_creat};
363 my $dst = $orig_uri->mailbox // next;
364 next if $mic->exists($dst); # already exists
365 $mic->create($dst) or die "CREATE $dst failed <$orig_uri>: $@";
370 # flesh out common NNTP-specific data structures
371 sub nntp_common_init ($;$) {
372 my ($self, $lei) = @_;
373 return unless $self->{nntp_order};
374 $self->{quiet} = 1 if $lei && $lei->{opt}->{quiet};
375 eval { require Net::NNTP } or
376 die "Net::NNTP is required for NNTP:\n$@\n";
377 ($lei || eval { require PublicInbox::IMAPTracker }) or
378 die "DBD::SQLite is required for NNTP\n:$@\n";
379 my $cfg = $self->{pi_cfg} // $lei->_lei_cfg;
380 my $nn_common = {}; # scheme://authority => Net::NNTP->new arg
381 for my $uri (@{$self->{nntp_order}}) {
382 my $sec = uri_section($uri);
383 my $args = $nn_common->{$sec} //= {};
385 # Debug and Timeout are passed to Net::NNTP->new
386 my $v = cfg_bool($cfg, 'nntp.Debug', $$uri);
387 $args->{Debug} = $v if defined $v;
388 my $to = cfg_intvl($cfg, 'nntp.Timeout', $$uri);
389 $args->{Timeout} = $to if $to;
390 my $sa = socks_args($cfg->urlmatch('nntp.Proxy', $$uri));
391 %$args = (%$args, %$sa) if $sa;
393 # Net::NNTP post-connect commands
394 for my $k (qw(starttls compress)) {
395 $v = cfg_bool($cfg, "nntp.$k", $$uri) // next;
396 $self->{cfg_opt}->{$sec}->{$k} = $v;
399 # -watch internal option
400 for my $k (qw(pollInterval)) {
401 $to = cfg_intvl($cfg, "nntp.$k", $$uri) // next;
402 $self->{cfg_opt}->{$sec}->{$k} = $to;
405 # make sure we can connect and cache the credentials in memory
406 my %nn; # schema://authority => Net::NNTP object
407 for my $uri (@{$self->{nntp_order}}) {
408 my $sec = uri_section($uri);
409 $nn{$sec} //= nn_for($self, $uri, $nn_common, $lei);
411 \%nn; # for optional {nn_cached}
415 my ($self, $arg, $ls_ok) = @_;
417 if ($uri = imap_uri($arg, $ls_ok)) {
418 $_[1] = $$uri; # canonicalized
419 push @{$self->{imap_order}}, $uri;
420 } elsif ($uri = nntp_uri($arg, $ls_ok)) {
421 $_[1] = $$uri; # canonicalized
422 push @{$self->{nntp_order}}, $uri;
424 push @{$self->{unsupported_url}}, $arg;
429 my ($self, $lei) = @_;
430 if (my $u = $self->{unsupported_url}) {
431 return "Unsupported URL(s): @$u";
433 if ($self->{imap_order}) {
434 eval { require PublicInbox::IMAPClient } or
435 die "Mail::IMAPClient is required for IMAP:\n$@\n";
437 if ($self->{nntp_order}) {
438 eval { require Net::NNTP } or
439 die "Net::NNTP is required for NNTP:\n$@\n";
441 my $sa = socks_args($lei ? $lei->{opt}->{proxy} : undef);
442 $self->{-proxy_cli} = $sa if $sa;
446 sub flags2kw ($$$$) {
447 my ($self, $uri, $uid, $flags) = @_;
449 for my $f (split(/ /, $flags)) {
450 if (my $k = $IMAPflags2kw{$f}) {
452 } elsif ($f eq "\\Recent") { # not in JMAP
453 } elsif ($f eq "\\Deleted") { # not in JMAP
455 } elsif ($self->{verbose}) {
456 warn "# unknown IMAP flag $f <$uri/;UID=$uid>\n";
459 @$kw = sort @$kw; # for LeiSearch->kw_changed and UI/UX purposes
463 sub _imap_do_msg ($$$$$) {
464 my ($self, $uri, $uid, $raw, $flags) = @_;
465 # our target audience expects LF-only, save storage
466 $$raw =~ s/\r\n/\n/sg;
467 my $kw = defined($flags) ?
468 (flags2kw($self, $uri, $uid, $flags) // return) : undef;
469 my ($eml_cb, @args) = @{$self->{eml_each}};
470 $eml_cb->($uri, $uid, $kw, PublicInbox::Eml->new($raw), @args);
473 sub run_commit_cb ($) {
475 my $cmt_cb_args = $self->{on_commit} or return;
476 my ($cb, @args) = @$cmt_cb_args;
480 sub itrk_last ($$;$$) {
481 my ($self, $uri, $r_uidval, $mic) = @_;
482 return (undef, undef, $r_uidval) unless $self->{incremental};
483 my ($itrk, $l_uid, $l_uidval);
484 if (defined(my $lms = $self->{-lms_rw})) { # LeiMailSync or 0
485 $uri->uidvalidity($r_uidval) if defined $r_uidval;
487 my $auth = $mic->Authmechanism // '';
488 $uri->auth($auth) if $auth eq 'ANONYMOUS';
489 my $user = $mic->User;
490 $uri->user($user) if defined($user);
493 $l_uid = ($lms && ($x = $lms->location_stats($$uri))) ?
494 $x->{'uid.max'} : undef;
495 # itrk remains undef, lei/store worker writes to
498 $itrk = PublicInbox::IMAPTracker->new($$uri);
499 ($l_uidval, $l_uid) = $itrk->get_last($$uri);
501 ($itrk, $l_uid, $l_uidval //= $r_uidval);
504 # import flags of already-seen messages
505 sub each_old_flags ($$$$) {
506 my ($self, $mic, $uri, $l_uid) = @_;
508 my $sec = uri_section($uri);
509 my $bs = ($self->{cfg_opt}->{$sec}->{batch_size} // 1) * 10000;
510 my ($eml_cb, @args) = @{$self->{eml_each}};
511 $self->{quiet} or warn "# $uri syncing flags 1:$l_uid\n";
512 for (my $n = 1; $n <= $l_uid; $n += $bs) {
514 $end = $l_uid if $end > $l_uid;
515 my $r = $mic->fetch_hash("$n:$end", 'FLAGS');
517 return if $!{EINTR} && $self->{quit};
518 return "E: $uri UID FETCH $n:$end error: $!";
520 while (my ($uid, $per_uid) = each %$r) {
521 my $kw = flags2kw($self, $uri, $uid, $per_uid->{FLAGS})
523 # LeiImport->input_net_cb
524 $eml_cb->($uri, $uid, $kw, undef, @args);
529 # returns true if PERMANENTFLAGS indicates FLAGS of already imported
530 # messages are meaningful
533 return if !defined($perm_fl);
534 for my $f (split(/[ \t]+/, $perm_fl)) {
535 return 1 if $IMAPflags2kw{$f};
540 # may be overridden in NetWriter or Watch
541 sub folder_select { $_[0]->{each_old} ? 'select' : 'examine' }
543 sub _imap_fetch_bodies ($$$$) {
544 my ($self, $mic, $uri, $uids) = @_;
545 my $req = $mic->imap4rev1 ? 'BODY.PEEK[]' : 'RFC822.PEEK';
548 my $sec = uri_section($uri);
549 my $mbx = $uri->mailbox;
550 my $bs = $self->{cfg_opt}->{$sec}->{batch_size} // 1;
551 my ($last_uid, $err);
552 my $use_fl = $self->{-use_fl};
554 while (scalar @$uids) {
555 my @batch = splice(@$uids, 0, $bs);
556 my $batch = join(',', @batch);
557 local $0 = "UID:$batch $mbx $sec";
558 my $r = $mic->fetch_hash($batch, $req, 'FLAGS');
559 unless ($r) { # network error?
560 last if $!{EINTR} && $self->{quit};
561 $err = "E: $uri UID FETCH $batch error: $!";
564 for my $uid (@batch) {
565 # messages get deleted, so holes appear
566 my $per_uid = delete $r->{$uid} // next;
567 my $raw = delete($per_uid->{$key}) // next;
568 my $fl = $use_fl ? $per_uid->{FLAGS} : undef;
569 _imap_do_msg($self, $uri, $uid, \$raw, $fl);
571 last if $self->{quit};
573 last if $self->{quit};
578 sub _imap_fetch_all ($$$) {
579 my ($self, $mic, $orig_uri) = @_;
580 my $sec = uri_section($orig_uri);
581 my $mbx = $orig_uri->mailbox;
582 $mic->Clear(1); # trim results history
584 # we need to check for mailbox writability to see if we care about
585 # FLAGS from already-imported messages.
586 my $cmd = $self->folder_select;
587 $mic->$cmd($mbx) or return "E: \U$cmd\E $mbx ($sec) failed: $!";
589 my ($r_uidval, $r_uidnext, $perm_fl);
590 for ($mic->Results) {
591 /^\* OK \[PERMANENTFLAGS \(([^\)]*)\)\].*/ and $perm_fl = $1;
592 /^\* OK \[UIDVALIDITY ([0-9]+)\].*/ and $r_uidval = $1;
593 /^\* OK \[UIDNEXT ([0-9]+)\].*/ and $r_uidnext = $1;
595 $r_uidval //= $mic->uidvalidity($mbx) //
596 return "E: $orig_uri cannot get UIDVALIDITY";
597 $r_uidnext //= $mic->uidnext($mbx) //
598 return "E: $orig_uri cannot get UIDNEXT";
599 my $expect = $orig_uri->uidvalidity // $r_uidval;
600 return <<EOF if $expect != $r_uidval;
601 E: $orig_uri UIDVALIDITY mismatch (got $r_uidval)
604 my $uri = $orig_uri->clone;
605 my $single_uid = $uri->uid;
606 my ($itrk, $l_uid, $l_uidval) = itrk_last($self, $uri, $r_uidval, $mic);
607 if (defined($single_uid)) {
608 $itrk = $l_uid = undef;
609 $uri->uid(undef); # for eml_cb
611 return <<EOF if $l_uidval != $r_uidval;
612 E: $uri UIDVALIDITY mismatch
613 E: local=$l_uidval != remote=$r_uidval
615 $uri->uidvalidity($r_uidval);
617 my $r_uid = $r_uidnext - 1;
618 return <<EOF if $l_uid > $r_uid;
619 E: $uri local UID exceeds remote ($l_uid > $r_uid)
620 E: $uri strangely, UIDVALIDLITY matches ($l_uidval)
622 $mic->Uid(1); # the default, we hope
624 my $use_fl = perm_fl_ok($perm_fl);
625 local $self->{-use_fl} = $use_fl;
626 if (!defined($single_uid) && $self->{each_old} && $use_fl) {
627 $err = each_old_flags($self, $mic, $uri, $l_uid);
630 return if $l_uid >= $r_uid; # nothing to do
632 my ($mod, $shard) = @{$self->{shard_info} // []};
633 unless ($self->{quiet}) {
634 my $m = $mod ? " [(UID % $mod) == $shard]" : '';
635 warn "# $uri fetching UID $l_uid:$r_uid$m\n";
637 my $fetch_cb = \&_imap_fetch_bodies;
639 # I wish "UID FETCH $START:*" could work, but:
640 # 1) servers do not need to return results in any order
641 # 2) Mail::IMAPClient doesn't offer a streaming API
643 if (defined $single_uid) {
644 $uids = [ $single_uid ];
645 } elsif (!($uids = $mic->search("UID $l_uid:*"))) {
646 return if $!{EINTR} && $self->{quit};
647 return "E: $uri UID SEARCH $l_uid:* error: $!";
649 return if scalar(@$uids) == 0;
651 # RFC 3501 doesn't seem to indicate order of UID SEARCH
652 # responses, so sort it ourselves. Order matters so
653 # IMAPTracker can store the newest UID.
654 @$uids = sort { $a <=> $b } @$uids;
656 # Did we actually get new messages?
657 return if $uids->[0] < $l_uid;
659 $l_uid = $uids->[-1] + 1; # for next search
660 @$uids = grep { ($_ % $mod) == $shard } @$uids if $mod;
661 (my $last_uid, $err) = $fetch_cb->($self, $mic, $uri, $uids);
662 run_commit_cb($self);
663 $itrk->update_last($r_uidval, $last_uid) if $itrk;
664 } until ($err || $self->{quit} || defined($single_uid));
668 # uses cached auth info prepared by mic_for
670 my ($self, $uri) = @_;
671 my $sec = uri_section($uri);
672 # see if caller saved result of imap_common_init
673 my $cached = $self->{mics_cached};
675 my $mic = $cached->{$sec};
676 return $mic if $mic && $mic->IsConnected;
677 delete $cached->{$sec};
679 my $mic_arg = $self->{net_arg}->{$sec} or
680 die "BUG: no Mail::IMAPClient->new arg for $sec";
681 if (defined(my $cb_name = $mic_arg->{Authcallback})) {
682 if (ref($cb_name) ne 'CODE') {
683 $mic_arg->{Authcallback} = $self->can($cb_name);
686 my $mic = mic_new($self, $mic_arg, $sec, $uri);
687 $cached //= {}; # invalid placeholder if no cache enabled
688 $mic && $mic->IsConnected ? ($cached->{$sec} = $mic) : undef;
692 my ($self, $url, $eml_cb, @args) = @_;
693 my $uri = ref($url) ? $url : PublicInbox::URIimap->new($url);
694 my $sec = uri_section($uri);
695 local $0 = $uri->mailbox." $sec";
696 my $mic = mic_get($self, $uri);
699 local $self->{eml_each} = [ $eml_cb, @args ];
700 $err = _imap_fetch_all($self, $mic, $uri);
702 $err = "E: <$uri> not connected: $!";
704 die $err if $err && $self->{-can_die};
709 # may used cached auth info prepared by nn_for once
711 my ($self, $uri) = @_;
712 my $sec = uri_section($uri);
713 # see if caller saved result of nntp_common_init
714 my $cached = $self->{nn_cached} // {};
716 $nn = delete($cached->{$sec}) and return $nn;
717 my $nn_arg = $self->{net_arg}->{$sec} or
718 die "BUG: no Net::NNTP->new arg for $sec";
719 my $nntp_cfg = $self->{cfg_opt}->{$sec};
720 $nn = nn_new($nn_arg, $nntp_cfg, $uri) or return;
721 if (my $postconn = $nntp_cfg->{-postconn}) {
722 for my $m_arg (@$postconn) {
723 my ($method, @args) = @$m_arg;
724 $nn->$method(@args) and next;
725 die "E: <$uri> $method failed\n";
732 sub _nntp_fetch_all ($$$) {
733 my ($self, $nn, $uri) = @_;
734 my ($group, $num_a, $num_b) = $uri->group;
735 my $sec = uri_section($uri);
736 my ($nr, $beg, $end) = $nn->group($group);
737 unless (defined($nr)) {
738 my $msg = ndump($nn->message);
739 return "E: GROUP $group <$sec> $msg";
741 (defined($num_a) && defined($num_b) && $num_a > $num_b) and
742 return "E: $uri: backwards range: $num_a > $num_b";
743 if (defined($num_a)) { # no article numbers in mail_sync.sqlite3
747 # IMAPTracker is also used for tracking NNTP, UID == article number
748 # LIST.ACTIVE can get the equivalent of UIDVALIDITY, but that's
749 # expensive. So we assume newsgroups don't change:
750 my ($itrk, $l_art) = itrk_last($self, $uri);
752 if (defined($l_art) && !defined($num_a)) {
753 return if $l_art >= $end; # nothing to do
756 # allow users to specify articles to refetch
757 # cf. https://tools.ietf.org/id/draft-gilman-news-url-01.txt
758 # nntp://example.com/inbox.foo/$num_a-$num_b
759 $beg = $num_a if defined($num_a) && $num_a > $beg && $num_a <= $end;
760 $end = $num_b if defined($num_b) && $num_b >= $beg && $num_b < $end;
761 $end = $beg if defined($num_a) && !defined($num_b);
762 my ($err, $art, $last_art, $kw); # kw stays undef, no keywords in NNTP
763 unless ($self->{quiet}) {
764 warn "# $uri fetching ARTICLE $beg..$end\n";
766 my $n = $self->{max_batch};
768 last if $self->{quit};
771 run_commit_cb($self);
772 $itrk->update_last(0, $last_art) if $itrk;
773 $n = $self->{max_batch};
775 my $raw = $nn->article($art);
776 unless (defined($raw)) {
777 my $msg = ndump($nn->message);
778 if ($nn->code == 421) { # pseudo response from Net::Cmd
781 } else { # probably just a deleted message (spam)
786 $raw = join('', @$raw);
787 $raw =~ s/\r\n/\n/sg;
788 my ($eml_cb, @args) = @{$self->{eml_each}};
789 $eml_cb->($uri, $art, $kw, PublicInbox::Eml->new(\$raw), @args);
792 run_commit_cb($self);
793 $itrk->update_last(0, $last_art) if $itrk;
798 my ($self, $url, $eml_cb, @args) = @_;
799 my $uri = ref($url) ? $url : PublicInbox::URInntps->new($url);
800 my $sec = uri_section($uri);
801 local $0 = $uri->group ." $sec";
802 my $nn = nn_get($self, $uri);
803 return if $self->{quit};
806 local $self->{eml_each} = [ $eml_cb, @args ];
807 $err = _nntp_fetch_all($self, $nn, $uri);
809 $err = "E: <$uri> not connected: $!";
811 die $err if $err && $self->{-can_die};
816 sub new { bless {}, shift };
818 # updates $uri with UIDVALIDITY
820 my ($self, $uri) = @_;
821 my $mic = $self->mic_get($uri) or die "E: not connected: $@";
822 my $m = $self->isa('PublicInbox::NetWriter') ? 'select' : 'examine';
823 $mic->$m($uri->mailbox) or return;
825 for ($mic->Results) {
826 /^\* OK \[UIDVALIDITY ([0-9]+)\].*/ or next;
830 $uidval //= $mic->uidvalidity($uri->mailbox) or
831 die "E: failed to get uidvalidity from <$uri>: $@";
832 $uri->uidvalidity($uidval);