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);
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 my $dst = $orig_uri->mailbox // next;
363 next if $mic->exists($dst); # already exists
364 $mic->create($dst) or die "CREATE $dst failed <$orig_uri>: $@";
369 # flesh out common NNTP-specific data structures
370 sub nntp_common_init ($;$) {
371 my ($self, $lei) = @_;
372 return unless $self->{nntp_order};
373 $self->{quiet} = 1 if $lei && $lei->{opt}->{quiet};
374 eval { require Net::NNTP } or
375 die "Net::NNTP is required for NNTP:\n$@\n";
376 ($lei || eval { require PublicInbox::IMAPTracker }) or
377 die "DBD::SQLite is required for NNTP\n:$@\n";
378 my $cfg = $self->{pi_cfg} // $lei->_lei_cfg;
379 my $nn_common = {}; # scheme://authority => Net::NNTP->new arg
380 for my $uri (@{$self->{nntp_order}}) {
381 my $sec = uri_section($uri);
382 my $args = $nn_common->{$sec} //= {};
384 # Debug and Timeout are passed to Net::NNTP->new
385 my $v = cfg_bool($cfg, 'nntp.Debug', $$uri);
386 $args->{Debug} = $v if defined $v;
387 my $to = cfg_intvl($cfg, 'nntp.Timeout', $$uri);
388 $args->{Timeout} = $to if $to;
389 my $sa = socks_args($cfg->urlmatch('nntp.Proxy', $$uri));
390 %$args = (%$args, %$sa) if $sa;
392 # Net::NNTP post-connect commands
393 for my $k (qw(starttls compress)) {
394 $v = cfg_bool($cfg, "nntp.$k", $$uri) // next;
395 $self->{cfg_opt}->{$sec}->{$k} = $v;
398 # -watch internal option
399 for my $k (qw(pollInterval)) {
400 $to = cfg_intvl($cfg, "nntp.$k", $$uri) // next;
401 $self->{cfg_opt}->{$sec}->{$k} = $to;
404 # make sure we can connect and cache the credentials in memory
405 my %nn; # schema://authority => Net::NNTP object
406 for my $uri (@{$self->{nntp_order}}) {
407 my $sec = uri_section($uri);
408 $nn{$sec} //= nn_for($self, $uri, $nn_common, $lei);
410 \%nn; # for optional {nn_cached}
414 my ($self, $arg, $ls_ok) = @_;
416 if ($uri = imap_uri($arg, $ls_ok)) {
417 $_[1] = $$uri; # canonicalized
418 push @{$self->{imap_order}}, $uri;
419 } elsif ($uri = nntp_uri($arg, $ls_ok)) {
420 $_[1] = $$uri; # canonicalized
421 push @{$self->{nntp_order}}, $uri;
423 push @{$self->{unsupported_url}}, $arg;
428 my ($self, $lei) = @_;
429 if (my $u = $self->{unsupported_url}) {
430 return "Unsupported URL(s): @$u";
432 if ($self->{imap_order}) {
433 eval { require PublicInbox::IMAPClient } or
434 die "Mail::IMAPClient is required for IMAP:\n$@\n";
436 if ($self->{nntp_order}) {
437 eval { require Net::NNTP } or
438 die "Net::NNTP is required for NNTP:\n$@\n";
440 my $sa = socks_args($lei ? $lei->{opt}->{proxy} : undef);
441 $self->{-proxy_cli} = $sa if $sa;
445 sub flags2kw ($$$$) {
446 my ($self, $uri, $uid, $flags) = @_;
448 for my $f (split(/ /, $flags)) {
449 if (my $k = $IMAPflags2kw{$f}) {
451 } elsif ($f eq "\\Recent") { # not in JMAP
452 } elsif ($f eq "\\Deleted") { # not in JMAP
454 } elsif ($self->{verbose}) {
455 warn "# unknown IMAP flag $f <$uri/;UID=$uid>\n";
458 @$kw = sort @$kw; # for LeiSearch->kw_changed and UI/UX purposes
462 sub _imap_do_msg ($$$$$) {
463 my ($self, $uri, $uid, $raw, $flags) = @_;
464 # our target audience expects LF-only, save storage
465 $$raw =~ s/\r\n/\n/sg;
466 my $kw = defined($flags) ?
467 (flags2kw($self, $uri, $uid, $flags) // return) : undef;
468 my ($eml_cb, @args) = @{$self->{eml_each}};
469 $eml_cb->($uri, $uid, $kw, PublicInbox::Eml->new($raw), @args);
472 sub run_commit_cb ($) {
474 my $cmt_cb_args = $self->{on_commit} or return;
475 my ($cb, @args) = @$cmt_cb_args;
479 sub itrk_last ($$;$$) {
480 my ($self, $uri, $r_uidval, $mic) = @_;
481 return (undef, undef, $r_uidval) unless $self->{incremental};
482 my ($itrk, $l_uid, $l_uidval);
483 if (defined(my $lms = $self->{-lms_ro})) { # LeiMailSync or 0
484 $uri->uidvalidity($r_uidval) if defined $r_uidval;
486 my $auth = $mic->Authmechanism // '';
487 $uri->auth($auth) if $auth eq 'ANONYMOUS';
488 my $user = $mic->User;
489 $uri->user($user) if defined($user);
492 $l_uid = ($lms && ($x = $lms->location_stats($$uri))) ?
493 $x->{'uid.max'} : undef;
494 # itrk remains undef, lei/store worker writes to
497 $itrk = PublicInbox::IMAPTracker->new($$uri);
498 ($l_uidval, $l_uid) = $itrk->get_last($$uri);
500 ($itrk, $l_uid, $l_uidval //= $r_uidval);
503 # import flags of already-seen messages
504 sub each_old_flags ($$$$) {
505 my ($self, $mic, $uri, $l_uid) = @_;
507 my $sec = uri_section($uri);
508 my $bs = ($self->{cfg_opt}->{$sec}->{batch_size} // 1) * 10000;
509 my ($eml_cb, @args) = @{$self->{eml_each}};
510 $self->{quiet} or warn "# $uri syncing flags 1:$l_uid\n";
511 for (my $n = 1; $n <= $l_uid; $n += $bs) {
513 $end = $l_uid if $end > $l_uid;
514 my $r = $mic->fetch_hash("$n:$end", 'FLAGS');
516 return if $!{EINTR} && $self->{quit};
517 return "E: $uri UID FETCH $n:$end error: $!";
519 while (my ($uid, $per_uid) = each %$r) {
520 my $kw = flags2kw($self, $uri, $uid, $per_uid->{FLAGS})
522 # LeiImport->input_net_cb
523 $eml_cb->($uri, $uid, $kw, undef, @args);
528 # returns true if PERMANENTFLAGS indicates FLAGS of already imported
529 # messages are meaningful
532 return if !defined($perm_fl);
533 for my $f (split(/[ \t]+/, $perm_fl)) {
534 return 1 if $IMAPflags2kw{$f};
539 # may be overridden in NetWriter or Watch
540 sub folder_select { $_[0]->{each_old} ? 'select' : 'examine' }
542 sub _imap_fetch_all ($$$) {
543 my ($self, $mic, $orig_uri) = @_;
544 my $sec = uri_section($orig_uri);
545 my $mbx = $orig_uri->mailbox;
546 $mic->Clear(1); # trim results history
548 # we need to check for mailbox writability to see if we care about
549 # FLAGS from already-imported messages.
550 my $cmd = $self->folder_select;
551 $mic->$cmd($mbx) or return "E: \U$cmd\E $mbx ($sec) failed: $!";
553 my ($r_uidval, $r_uidnext, $perm_fl);
554 for ($mic->Results) {
555 /^\* OK \[PERMANENTFLAGS \(([^\)]*)\)\].*/ and $perm_fl = $1;
556 /^\* OK \[UIDVALIDITY ([0-9]+)\].*/ and $r_uidval = $1;
557 /^\* OK \[UIDNEXT ([0-9]+)\].*/ and $r_uidnext = $1;
559 $r_uidval //= $mic->uidvalidity($mbx) //
560 return "E: $orig_uri cannot get UIDVALIDITY";
561 $r_uidnext //= $mic->uidnext($mbx) //
562 return "E: $orig_uri cannot get UIDNEXT";
563 my $expect = $orig_uri->uidvalidity // $r_uidval;
564 return <<EOF if $expect != $r_uidval;
565 E: $orig_uri UIDVALIDITY mismatch (got $r_uidval)
568 my $uri = $orig_uri->clone;
569 my $single_uid = $uri->uid;
570 my ($itrk, $l_uid, $l_uidval) = itrk_last($self, $uri, $r_uidval, $mic);
571 if (defined($single_uid)) {
572 $itrk = $l_uid = undef;
573 $uri->uid(undef); # for eml_cb
575 return <<EOF if $l_uidval != $r_uidval;
576 E: $uri UIDVALIDITY mismatch
577 E: local=$l_uidval != remote=$r_uidval
579 $uri->uidvalidity($r_uidval);
581 my $r_uid = $r_uidnext - 1;
582 return <<EOF if $l_uid > $r_uid;
583 E: $uri local UID exceeds remote ($l_uid > $r_uid)
584 E: $uri strangely, UIDVALIDLITY matches ($l_uidval)
586 $mic->Uid(1); # the default, we hope
588 my $use_fl = perm_fl_ok($perm_fl);
589 if (!defined($single_uid) && $self->{each_old} && $use_fl) {
590 $err = each_old_flags($self, $mic, $uri, $l_uid);
593 return if $l_uid >= $r_uid; # nothing to do
595 my ($mod, $shard) = @{$self->{shard_info} // []};
596 unless ($self->{quiet}) {
597 my $m = $mod ? " [(UID % $mod) == $shard]" : '';
598 warn "# $uri fetching UID $l_uid:$r_uid$m\n";
600 my $bs = $self->{cfg_opt}->{$sec}->{batch_size} // 1;
601 my $req = $mic->imap4rev1 ? 'BODY.PEEK[]' : 'RFC822.PEEK';
606 # I wish "UID FETCH $START:*" could work, but:
607 # 1) servers do not need to return results in any order
608 # 2) Mail::IMAPClient doesn't offer a streaming API
609 if (defined $single_uid) {
610 $uids = [ $single_uid ];
611 } elsif (!($uids = $mic->search("UID $l_uid:*"))) {
612 return if $!{EINTR} && $self->{quit};
613 return "E: $uri UID SEARCH $l_uid:* error: $!";
615 return if scalar(@$uids) == 0;
617 # RFC 3501 doesn't seem to indicate order of UID SEARCH
618 # responses, so sort it ourselves. Order matters so
619 # IMAPTracker can store the newest UID.
620 @$uids = sort { $a <=> $b } @$uids;
622 # Did we actually get new messages?
623 return if $uids->[0] < $l_uid;
625 $l_uid = $uids->[-1] + 1; # for next search
627 my $n = $self->{max_batch};
629 @$uids = grep { ($_ % $mod) == $shard } @$uids if $mod;
630 while (scalar @$uids) {
631 my @batch = splice(@$uids, 0, $bs);
632 $batch = join(',', @batch);
633 local $0 = "UID:$batch $mbx $sec";
634 my $r = $mic->fetch_hash($batch, $req, 'FLAGS');
635 unless ($r) { # network error?
636 last if $!{EINTR} && $self->{quit};
637 $err = "E: $uri UID FETCH $batch error: $!";
640 for my $uid (@batch) {
641 # messages get deleted, so holes appear
642 my $per_uid = delete $r->{$uid} // next;
643 my $raw = delete($per_uid->{$key}) // next;
644 my $fl = $use_fl ? $per_uid->{FLAGS} : undef;
645 _imap_do_msg($self, $uri, $uid, \$raw, $fl);
647 last if $self->{quit};
649 last if $self->{quit};
651 run_commit_cb($self);
652 $itrk->update_last($r_uidval, $last_uid) if $itrk;
653 } until ($err || $self->{quit} || defined($single_uid));
657 # uses cached auth info prepared by mic_for
659 my ($self, $uri) = @_;
660 my $sec = uri_section($uri);
661 # see if caller saved result of imap_common_init
662 my $cached = $self->{mics_cached};
664 my $mic = $cached->{$sec};
665 return $mic if $mic && $mic->IsConnected;
666 delete $cached->{$sec};
668 my $mic_arg = $self->{net_arg}->{$sec} or
669 die "BUG: no Mail::IMAPClient->new arg for $sec";
670 if (defined(my $cb_name = $mic_arg->{Authcallback})) {
671 if (ref($cb_name) ne 'CODE') {
672 $mic_arg->{Authcallback} = $self->can($cb_name);
675 my $mic = mic_new($self, $mic_arg, $sec, $uri);
676 $cached //= {}; # invalid placeholder if no cache enabled
677 $mic && $mic->IsConnected ? ($cached->{$sec} = $mic) : undef;
681 my ($self, $url, $eml_cb, @args) = @_;
682 my $uri = ref($url) ? $url : PublicInbox::URIimap->new($url);
683 my $sec = uri_section($uri);
684 local $0 = $uri->mailbox." $sec";
685 my $mic = mic_get($self, $uri);
688 local $self->{eml_each} = [ $eml_cb, @args ];
689 $err = _imap_fetch_all($self, $mic, $uri);
691 $err = "E: <$uri> not connected: $!";
693 die $err if $err && $self->{-can_die};
698 # may used cached auth info prepared by nn_for once
700 my ($self, $uri) = @_;
701 my $sec = uri_section($uri);
702 # see if caller saved result of nntp_common_init
703 my $cached = $self->{nn_cached} // {};
705 $nn = delete($cached->{$sec}) and return $nn;
706 my $nn_arg = $self->{net_arg}->{$sec} or
707 die "BUG: no Net::NNTP->new arg for $sec";
708 my $nntp_cfg = $self->{cfg_opt}->{$sec};
709 $nn = nn_new($nn_arg, $nntp_cfg, $uri) or return;
710 if (my $postconn = $nntp_cfg->{-postconn}) {
711 for my $m_arg (@$postconn) {
712 my ($method, @args) = @$m_arg;
713 $nn->$method(@args) and next;
714 die "E: <$uri> $method failed\n";
721 sub _nntp_fetch_all ($$$) {
722 my ($self, $nn, $uri) = @_;
723 my ($group, $num_a, $num_b) = $uri->group;
724 my $sec = uri_section($uri);
725 my ($nr, $beg, $end) = $nn->group($group);
726 unless (defined($nr)) {
727 my $msg = ndump($nn->message);
728 return "E: GROUP $group <$sec> $msg";
730 (defined($num_a) && defined($num_b) && $num_a > $num_b) and
731 return "E: $uri: backwards range: $num_a > $num_b";
732 if (defined($num_a)) { # no article numbers in mail_sync.sqlite3
736 # IMAPTracker is also used for tracking NNTP, UID == article number
737 # LIST.ACTIVE can get the equivalent of UIDVALIDITY, but that's
738 # expensive. So we assume newsgroups don't change:
739 my ($itrk, $l_art) = itrk_last($self, $uri);
741 if (defined($l_art) && !defined($num_a)) {
742 return if $l_art >= $end; # nothing to do
745 # allow users to specify articles to refetch
746 # cf. https://tools.ietf.org/id/draft-gilman-news-url-01.txt
747 # nntp://example.com/inbox.foo/$num_a-$num_b
748 $beg = $num_a if defined($num_a) && $num_a > $beg && $num_a <= $end;
749 $end = $num_b if defined($num_b) && $num_b >= $beg && $num_b < $end;
750 $end = $beg if defined($num_a) && !defined($num_b);
751 my ($err, $art, $last_art, $kw); # kw stays undef, no keywords in NNTP
752 unless ($self->{quiet}) {
753 warn "# $uri fetching ARTICLE $beg..$end\n";
755 my $n = $self->{max_batch};
757 last if $self->{quit};
760 run_commit_cb($self);
761 $itrk->update_last(0, $last_art) if $itrk;
762 $n = $self->{max_batch};
764 my $raw = $nn->article($art);
765 unless (defined($raw)) {
766 my $msg = ndump($nn->message);
767 if ($nn->code == 421) { # pseudo response from Net::Cmd
770 } else { # probably just a deleted message (spam)
775 $raw = join('', @$raw);
776 $raw =~ s/\r\n/\n/sg;
777 my ($eml_cb, @args) = @{$self->{eml_each}};
778 $eml_cb->($uri, $art, $kw, PublicInbox::Eml->new(\$raw), @args);
781 run_commit_cb($self);
782 $itrk->update_last(0, $last_art) if $itrk;
787 my ($self, $url, $eml_cb, @args) = @_;
788 my $uri = ref($url) ? $url : PublicInbox::URInntps->new($url);
789 my $sec = uri_section($uri);
790 local $0 = $uri->group ." $sec";
791 my $nn = nn_get($self, $uri);
792 return if $self->{quit};
795 local $self->{eml_each} = [ $eml_cb, @args ];
796 $err = _nntp_fetch_all($self, $nn, $uri);
798 $err = "E: <$uri> not connected: $!";
800 die $err if $err && $self->{-can_die};
805 sub new { bless {}, shift };
807 # updates $uri with UIDVALIDITY
809 my ($self, $uri) = @_;
810 my $mic = $self->mic_get($uri) or die "E: not connected: $@";
811 my $m = $self->isa('PublicInbox::NetWriter') ? 'select' : 'examine';
812 $mic->$m($uri->mailbox) or return;
814 for ($mic->Results) {
815 /^\* OK \[UIDVALIDITY ([0-9]+)\].*/ or next;
819 $uidval //= $mic->uidvalidity($uri->mailbox) or
820 die "E: failed to get uidvalidity from <$uri>: $@";
821 $uri->uidvalidity($uidval);