]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/NetReader.pm
net_reader: nntp_each: pass keywords as `undef'
[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 PublicInbox::IPC);
9 use PublicInbox::Eml;
10 our %IMAPflags2kw = map {; "\\\u$_" => $_ } qw(seen answered flagged draft);
11
12 our @EXPORT = qw(uri_section imap_uri nntp_uri);
13
14 sub ndump {
15         require Data::Dumper;
16         Data::Dumper->new(\@_)->Useqq(1)->Terse(1)->Dump;
17 }
18
19 # returns the git config section name, e.g [imap "imaps://user@example.com"]
20 # without the mailbox, so we can share connections between different inboxes
21 sub uri_section ($) {
22         my ($uri) = @_;
23         $uri->scheme . '://' . $uri->authority;
24 }
25
26 sub auth_anon_cb { '' }; # for Mail::IMAPClient::Authcallback
27
28 # mic_for may prompt the user and store auth info, prepares mic_get
29 sub mic_for { # mic = Mail::IMAPClient
30         my ($self, $url, $mic_args, $lei) = @_;
31         require PublicInbox::URIimap;
32         my $uri = PublicInbox::URIimap->new($url);
33         require PublicInbox::GitCredential;
34         my $cred = bless {
35                 url => $url,
36                 protocol => $uri->scheme,
37                 host => $uri->host,
38                 username => $uri->user,
39                 password => $uri->password,
40         }, 'PublicInbox::GitCredential';
41         my $common = $mic_args->{uri_section($uri)} // {};
42         # IMAPClient and Net::Netrc both mishandles `0', so we pass `127.0.0.1'
43         my $host = $cred->{host};
44         $host = '127.0.0.1' if $host eq '0';
45         my $mic_arg = {
46                 Port => $uri->port,
47                 Server => $host,
48                 Ssl => $uri->scheme eq 'imaps',
49                 Keepalive => 1, # SO_KEEPALIVE
50                 %$common, # may set Starttls, Compress, Debug ....
51         };
52         require PublicInbox::IMAPClient;
53         my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or
54                 die "E: <$url> new: $@\n";
55
56         # default to using STARTTLS if it's available, but allow
57         # it to be disabled since I usually connect to localhost
58         if (!$mic_arg->{Ssl} && !defined($mic_arg->{Starttls}) &&
59                         $mic->has_capability('STARTTLS') &&
60                         $mic->can('starttls')) {
61                 $mic->starttls or die "E: <$url> STARTTLS: $@\n";
62         }
63
64         # do we even need credentials?
65         if (!defined($cred->{username}) &&
66                         $mic->has_capability('AUTH=ANONYMOUS')) {
67                 $cred = undef;
68         }
69         if ($cred) {
70                 $cred->check_netrc unless defined $cred->{password};
71                 $cred->fill($lei); # may prompt user here
72                 $mic->User($mic_arg->{User} = $cred->{username});
73                 $mic->Password($mic_arg->{Password} = $cred->{password});
74         } else { # AUTH=ANONYMOUS
75                 $mic->Authmechanism($mic_arg->{Authmechanism} = 'ANONYMOUS');
76                 $mic_arg->{Authcallback} = 'auth_anon_cb';
77                 $mic->Authcallback(\&auth_anon_cb);
78         }
79         my $err;
80         if ($mic->login && $mic->IsAuthenticated) {
81                 # success! keep IMAPClient->new arg in case we get disconnected
82                 $self->{mic_arg}->{uri_section($uri)} = $mic_arg;
83         } else {
84                 $err = "E: <$url> LOGIN: $@\n";
85                 if ($cred && defined($cred->{password})) {
86                         $err =~ s/\Q$cred->{password}\E/*******/g;
87                 }
88                 $mic = undef;
89         }
90         $cred->run($mic ? 'approve' : 'reject') if $cred;
91         if ($err) {
92                 $lei ? $lei->fail($err) : warn($err);
93         }
94         $mic;
95 }
96
97 # Net::NNTP doesn't support CAPABILITIES, yet
98 sub try_starttls ($) {
99         my ($host) = @_;
100         return if $host =~ /\.onion\z/s;
101         return if $host =~ /\A127\.[0-9]+\.[0-9]+\.[0-9]+\z/s;
102         return if $host eq '::1';
103         1;
104 }
105
106 sub nn_new ($$$) {
107         my ($nn_arg, $nntp_opt, $uri) = @_;
108         my $nn = Net::NNTP->new(%$nn_arg) or die "E: <$uri> new: $!\n";
109
110         # default to using STARTTLS if it's available, but allow
111         # it to be disabled for localhost/VPN users
112         if (!$nn_arg->{SSL} && $nn->can('starttls')) {
113                 if (!defined($nntp_opt->{starttls}) &&
114                                 try_starttls($nn_arg->{Host})) {
115                         # soft fail by default
116                         $nn->starttls or warn <<"";
117 W: <$uri> STARTTLS tried and failed (not requested)
118
119                 } elsif ($nntp_opt->{starttls}) {
120                         # hard fail if explicitly configured
121                         $nn->starttls or die <<"";
122 E: <$uri> STARTTLS requested and failed
123
124                 }
125         } elsif ($nntp_opt->{starttls}) {
126                 $nn->can('starttls') or
127                         die "E: <$uri> Net::NNTP too old for STARTTLS\n";
128                 $nn->starttls or die <<"";
129 E: <$uri> STARTTLS requested and failed
130
131         }
132         $nn;
133 }
134
135 sub nn_for ($$$;$) { # nn = Net::NNTP
136         my ($self, $uri, $nn_args, $lei) = @_;
137         my $sec = uri_section($uri);
138         my $nntp_opt = $self->{nntp_opt}->{$sec} //= {};
139         my $host = $uri->host;
140         # Net::NNTP and Net::Netrc both mishandle `0', so we pass `127.0.0.1'
141         $host = '127.0.0.1' if $host eq '0';
142         my $cred;
143         my ($u, $p);
144         if (defined(my $ui = $uri->userinfo)) {
145                 require PublicInbox::GitCredential;
146                 $cred = bless {
147                         url => $sec,
148                         protocol => $uri->scheme,
149                         host => $host,
150                 }, 'PublicInbox::GitCredential';
151                 ($u, $p) = split(/:/, $ui, 2);
152                 ($cred->{username}, $cred->{password}) = ($u, $p);
153                 $cred->check_netrc unless defined $p;
154         }
155         my $common = $nn_args->{$sec} // {};
156         my $nn_arg = {
157                 Port => $uri->port,
158                 Host => $host,
159                 SSL => $uri->secure, # snews == nntps
160                 %$common, # may Debug ....
161         };
162         my $nn = nn_new($nn_arg, $nntp_opt, $uri);
163         if ($cred) {
164                 $cred->fill($lei); # may prompt user here
165                 if ($nn->authinfo($u, $p)) {
166                         push @{$nntp_opt->{-postconn}}, [ 'authinfo', $u, $p ];
167                 } else {
168                         warn "E: <$uri> AUTHINFO $u XXXX failed\n";
169                         $nn = undef;
170                 }
171         }
172
173         if ($nntp_opt->{compress}) {
174                 # https://rt.cpan.org/Ticket/Display.html?id=129967
175                 if ($nn->can('compress')) {
176                         if ($nn->compress) {
177                                 push @{$nntp_opt->{-postconn}}, [ 'compress' ];
178                         } else {
179                                 warn "W: <$uri> COMPRESS failed\n";
180                         }
181                 } else {
182                         delete $nntp_opt->{compress};
183                         warn <<"";
184 W: <$uri> COMPRESS not supported by Net::NNTP
185 W: see https://rt.cpan.org/Ticket/Display.html?id=129967 for updates
186
187                 }
188         }
189
190         $self->{nn_arg}->{$sec} = $nn_arg;
191         $cred->run($nn ? 'approve' : 'reject') if $cred;
192         $nn;
193 }
194
195 sub imap_uri {
196         my ($url) = @_;
197         require PublicInbox::URIimap;
198         my $uri = PublicInbox::URIimap->new($url);
199         $uri ? $uri->canonical : undef;
200 }
201
202 my %IS_NNTP = (news => 1, snews => 1, nntp => 1, nntps => 1);
203 sub nntp_uri {
204         my ($url) = @_;
205         require PublicInbox::URInntps;
206         my $uri = PublicInbox::URInntps->new($url);
207         $uri && $IS_NNTP{$uri->scheme} && $uri->group ? $uri->canonical : undef;
208 }
209
210 sub cfg_intvl ($$$) {
211         my ($cfg, $key, $url) = @_;
212         my $v = $cfg->urlmatch($key, $url) // return;
213         $v =~ /\A[0-9]+(?:\.[0-9]+)?\z/s and return $v + 0;
214         if (ref($v) eq 'ARRAY') {
215                 $v = join(', ', @$v);
216                 warn "W: $key has multiple values: $v\nW: $key ignored\n";
217         } else {
218                 warn "W: $key=$v is not a numeric value in seconds\n";
219         }
220 }
221
222 sub cfg_bool ($$$) {
223         my ($cfg, $key, $url) = @_;
224         my $orig = $cfg->urlmatch($key, $url) // return;
225         my $bool = $cfg->git_bool($orig);
226         warn "W: $key=$orig for $url is not boolean\n" unless defined($bool);
227         $bool;
228 }
229
230 # flesh out common IMAP-specific data structures
231 sub imap_common_init ($;$) {
232         my ($self, $lei) = @_;
233         return unless $self->{imap_order};
234         $self->{quiet} = 1 if $lei && $lei->{opt}->{quiet};
235         eval { require PublicInbox::IMAPClient } or
236                 die "Mail::IMAPClient is required for IMAP:\n$@\n";
237         eval { require PublicInbox::IMAPTracker } or
238                 die "DBD::SQLite is required for IMAP\n:$@\n";
239         require PublicInbox::URIimap;
240         my $cfg = $self->{pi_cfg} // $lei->_lei_cfg;
241         my $mic_args = {}; # scheme://authority => Mail:IMAPClient arg
242         for my $uri (@{$self->{imap_order}}) {
243                 my $sec = uri_section($uri);
244                 for my $k (qw(Starttls Debug Compress)) {
245                         my $bool = cfg_bool($cfg, "imap.$k", $$uri) // next;
246                         $mic_args->{$sec}->{$k} = $bool;
247                 }
248                 my $to = cfg_intvl($cfg, 'imap.timeout', $$uri);
249                 $mic_args->{$sec}->{Timeout} = $to if $to;
250                 for my $k (qw(pollInterval idleInterval)) {
251                         $to = cfg_intvl($cfg, "imap.$k", $$uri) // next;
252                         $self->{imap_opt}->{$sec}->{$k} = $to;
253                 }
254                 my $k = 'imap.fetchBatchSize';
255                 my $bs = $cfg->urlmatch($k, $$uri) // next;
256                 if ($bs =~ /\A([0-9]+)\z/) {
257                         $self->{imap_opt}->{$sec}->{batch_size} = $bs;
258                 } else {
259                         warn "$k=$bs is not an integer\n";
260                 }
261         }
262         # make sure we can connect and cache the credentials in memory
263         $self->{mic_arg} = {}; # schema://authority => IMAPClient->new args
264         my $mics = {}; # schema://authority => IMAPClient obj
265         for my $uri (@{$self->{imap_order}}) {
266                 my $sec = uri_section($uri);
267                 $mics->{$sec} //= mic_for($self, "$sec/", $mic_args, $lei);
268                 next unless $self->isa('PublicInbox::NetWriter');
269                 my $dst = $uri->mailbox // next;
270                 my $mic = $mics->{$sec};
271                 next if $mic->exists($dst); # already exists
272                 $mic->create($dst) or die "CREATE $dst failed <$uri>: $@";
273         }
274         $mics;
275 }
276
277 # flesh out common NNTP-specific data structures
278 sub nntp_common_init ($;$) {
279         my ($self, $lei) = @_;
280         return unless $self->{nntp_order};
281         $self->{quiet} = 1 if $lei && $lei->{opt}->{quiet};
282         eval { require Net::NNTP } or
283                 die "Net::NNTP is required for NNTP:\n$@\n";
284         eval { require PublicInbox::IMAPTracker } or
285                 die "DBD::SQLite is required for NNTP\n:$@\n";
286         my $cfg = $self->{pi_cfg} // $lei->_lei_cfg;
287         my $nn_args = {}; # scheme://authority => Net::NNTP->new arg
288         for my $uri (@{$self->{nntp_order}}) {
289                 my $sec = uri_section($uri);
290
291                 # Debug and Timeout are passed to Net::NNTP->new
292                 my $v = cfg_bool($cfg, 'nntp.Debug', $$uri);
293                 $nn_args->{$sec}->{Debug} = $v if defined $v;
294                 my $to = cfg_intvl($cfg, 'nntp.Timeout', $$uri);
295                 $nn_args->{$sec}->{Timeout} = $to if $to;
296
297                 # Net::NNTP post-connect commands
298                 for my $k (qw(starttls compress)) {
299                         $v = cfg_bool($cfg, "nntp.$k", $$uri) // next;
300                         $self->{nntp_opt}->{$sec}->{$k} = $v;
301                 }
302
303                 # internal option
304                 for my $k (qw(pollInterval)) {
305                         $to = cfg_intvl($cfg, "nntp.$k", $$uri) // next;
306                         $self->{nntp_opt}->{$sec}->{$k} = $to;
307                 }
308         }
309         # make sure we can connect and cache the credentials in memory
310         $self->{nn_arg} = {}; # schema://authority => Net::NNTP->new args
311         my %nn; # schema://authority => Net::NNTP object
312         for my $uri (@{$self->{nntp_order}}) {
313                 my $sec = uri_section($uri);
314                 $nn{$sec} //= nn_for($self, $uri, $nn_args, $lei);
315         }
316         \%nn; # for optional {nn_cached}
317 }
318
319 sub add_url {
320         my ($self, $arg) = @_;
321         my $uri;
322         if ($uri = imap_uri($arg)) {
323                 push @{$self->{imap_order}}, $uri;
324         } elsif ($uri = nntp_uri($arg)) {
325                 push @{$self->{nntp_order}}, $uri;
326         } else {
327                 push @{$self->{unsupported_url}}, $arg;
328         }
329 }
330
331 sub errors {
332         my ($self) = @_;
333         if (my $u = $self->{unsupported_url}) {
334                 return "Unsupported URL(s): @$u";
335         }
336         if ($self->{imap_order}) {
337                 eval { require PublicInbox::IMAPClient } or
338                         die "Mail::IMAPClient is required for IMAP:\n$@\n";
339         }
340         if ($self->{nntp_order}) {
341                 eval { require Net::NNTP } or
342                         die "Net::NNTP is required for NNTP:\n$@\n";
343         }
344         undef;
345 }
346
347 sub _imap_do_msg ($$$$$) {
348         my ($self, $uri, $uid, $raw, $flags) = @_;
349         # our target audience expects LF-only, save storage
350         $$raw =~ s/\r\n/\n/sg;
351         my $kw = [];
352         for my $f (split(/ /, $flags)) {
353                 if (my $k = $IMAPflags2kw{$f}) {
354                         push @$kw, $k;
355                 } elsif ($f eq "\\Recent") { # not in JMAP
356                 } elsif ($f eq "\\Deleted") { # not in JMAP
357                         return;
358                 } elsif ($self->{verbose}) {
359                         warn "# unknown IMAP flag $f <$uri;uid=$uid>\n";
360                 }
361         }
362         @$kw = sort @$kw; # for all UI/UX purposes
363         my ($eml_cb, @args) = @{$self->{eml_each}};
364         $eml_cb->($uri, $uid, $kw, PublicInbox::Eml->new($raw), @args);
365 }
366
367 sub run_commit_cb ($) {
368         my ($self) = @_;
369         my $cmt_cb_args = $self->{on_commit} or return;
370         my ($cb, @args) = @$cmt_cb_args;
371         $cb->(@args);
372 }
373
374 sub _imap_fetch_all ($$$) {
375         my ($self, $mic, $uri) = @_;
376         my $sec = uri_section($uri);
377         my $mbx = $uri->mailbox;
378         $mic->Clear(1); # trim results history
379         $mic->examine($mbx) or return "E: EXAMINE $mbx ($sec) failed: $!";
380         my ($r_uidval, $r_uidnext);
381         for ($mic->Results) {
382                 /^\* OK \[UIDVALIDITY ([0-9]+)\].*/ and $r_uidval = $1;
383                 /^\* OK \[UIDNEXT ([0-9]+)\].*/ and $r_uidnext = $1;
384                 last if $r_uidval && $r_uidnext;
385         }
386         $r_uidval //= $mic->uidvalidity($mbx) //
387                 return "E: $uri cannot get UIDVALIDITY";
388         $r_uidnext //= $mic->uidnext($mbx) //
389                 return "E: $uri cannot get UIDNEXT";
390         my $itrk = $self->{incremental} ?
391                         PublicInbox::IMAPTracker->new($$uri) : 0;
392         my ($l_uidval, $l_uid) = $itrk ? $itrk->get_last : ();
393         $l_uidval //= $r_uidval; # first time
394         $l_uid //= 0;
395         if ($l_uidval != $r_uidval) {
396                 return "E: $uri UIDVALIDITY mismatch\n".
397                         "E: local=$l_uidval != remote=$r_uidval";
398         }
399         my $r_uid = $r_uidnext - 1;
400         if ($l_uid > $r_uid) {
401                 return "E: $uri local UID exceeds remote ($l_uid > $r_uid)\n".
402                         "E: $uri strangely, UIDVALIDLITY matches ($l_uidval)\n";
403         }
404         return if $l_uid >= $r_uid; # nothing to do
405         $l_uid ||= 1;
406         my ($mod, $shard) = @{$self->{shard_info} // []};
407         unless ($self->{quiet}) {
408                 my $m = $mod ? " [(UID % $mod) == $shard]" : '';
409                 warn "# $uri fetching UID $l_uid:$r_uid$m\n";
410         }
411         $mic->Uid(1); # the default, we hope
412         my $bs = $self->{imap_opt}->{$sec}->{batch_size} // 1;
413         my $req = $mic->imap4rev1 ? 'BODY.PEEK[]' : 'RFC822.PEEK';
414         my $key = $req;
415         $key =~ s/\.PEEK//;
416         my ($uids, $batch);
417         my $err;
418         do {
419                 # I wish "UID FETCH $START:*" could work, but:
420                 # 1) servers do not need to return results in any order
421                 # 2) Mail::IMAPClient doesn't offer a streaming API
422                 unless ($uids = $mic->search("UID $l_uid:*")) {
423                         return if $!{EINTR} && $self->{quit};
424                         return "E: $uri UID SEARCH $l_uid:* error: $!";
425                 }
426                 return if scalar(@$uids) == 0;
427
428                 # RFC 3501 doesn't seem to indicate order of UID SEARCH
429                 # responses, so sort it ourselves.  Order matters so
430                 # IMAPTracker can store the newest UID.
431                 @$uids = sort { $a <=> $b } @$uids;
432
433                 # Did we actually get new messages?
434                 return if $uids->[0] < $l_uid;
435
436                 $l_uid = $uids->[-1] + 1; # for next search
437                 my $last_uid;
438                 my $n = $self->{max_batch};
439
440                 @$uids = grep { ($_ % $mod) == $shard } @$uids if $mod;
441                 while (scalar @$uids) {
442                         my @batch = splice(@$uids, 0, $bs);
443                         $batch = join(',', @batch);
444                         local $0 = "UID:$batch $mbx $sec";
445                         my $r = $mic->fetch_hash($batch, $req, 'FLAGS');
446                         unless ($r) { # network error?
447                                 last if $!{EINTR} && $self->{quit};
448                                 $err = "E: $uri UID FETCH $batch error: $!";
449                                 last;
450                         }
451                         for my $uid (@batch) {
452                                 # messages get deleted, so holes appear
453                                 my $per_uid = delete $r->{$uid} // next;
454                                 my $raw = delete($per_uid->{$key}) // next;
455                                 _imap_do_msg($self, $uri, $uid, \$raw,
456                                                 $per_uid->{FLAGS});
457                                 $last_uid = $uid;
458                                 last if $self->{quit};
459                         }
460                         last if $self->{quit};
461                 }
462                 run_commit_cb($self);
463                 $itrk->update_last($r_uidval, $last_uid) if $itrk;
464         } until ($err || $self->{quit});
465         $err;
466 }
467
468 # uses cached auth info prepared by mic_for
469 sub mic_get {
470         my ($self, $uri) = @_;
471         my $sec = uri_section($uri);
472         # see if caller saved result of imap_common_init
473         my $cached = $self->{mics_cached};
474         if ($cached) {
475                 my $mic = $cached->{$sec};
476                 return $mic if $mic && $mic->IsConnected;
477                 delete $cached->{$sec};
478         }
479         my $mic_arg = $self->{mic_arg}->{$sec} or
480                         die "BUG: no Mail::IMAPClient->new arg for $sec";
481         if (defined(my $cb_name = $mic_arg->{Authcallback})) {
482                 if (ref($cb_name) ne 'CODE') {
483                         $mic_arg->{Authcallback} = $self->can($cb_name);
484                 }
485         }
486         my $mic = PublicInbox::IMAPClient->new(%$mic_arg);
487         $cached //= {}; # invalid placeholder if no cache enabled
488         $mic && $mic->IsConnected ? ($cached->{$sec} = $mic) : undef;
489 }
490
491 sub imap_each {
492         my ($self, $url, $eml_cb, @args) = @_;
493         my $uri = ref($url) ? $url : PublicInbox::URIimap->new($url);
494         my $sec = uri_section($uri);
495         local $0 = $uri->mailbox." $sec";
496         my $mic = mic_get($self, $uri);
497         my $err;
498         if ($mic) {
499                 local $self->{eml_each} = [ $eml_cb, @args ];
500                 $err = _imap_fetch_all($self, $mic, $uri);
501         } else {
502                 $err = "E: <$uri> not connected: $!";
503         }
504         warn $err if $err;
505         $mic;
506 }
507
508 # may used cached auth info prepared by nn_for once
509 sub nn_get {
510         my ($self, $uri) = @_;
511         my $sec = uri_section($uri);
512         # see if caller saved result of nntp_common_init
513         my $cached = $self->{nn_cached} // {};
514         my $nn;
515         $nn = delete($cached->{$sec}) and return $nn;
516         my $nn_arg = $self->{nn_arg}->{$sec} or
517                         die "BUG: no Net::NNTP->new arg for $sec";
518         my $nntp_opt = $self->{nntp_opt}->{$sec};
519         $nn = nn_new($nn_arg, $nntp_opt, $uri) or return;
520         if (my $postconn = $nntp_opt->{-postconn}) {
521                 for my $m_arg (@$postconn) {
522                         my ($method, @args) = @$m_arg;
523                         $nn->$method(@args) and next;
524                         die "E: <$uri> $method failed\n";
525                         return;
526                 }
527         }
528         $nn;
529 }
530
531 sub _nntp_fetch_all ($$$) {
532         my ($self, $nn, $uri) = @_;
533         my ($group, $num_a, $num_b) = $uri->group;
534         my $sec = uri_section($uri);
535         my ($nr, $beg, $end) = $nn->group($group);
536         unless (defined($nr)) {
537                 my $msg = ndump($nn->message);
538                 return "E: GROUP $group <$sec> $msg";
539         }
540
541         # IMAPTracker is also used for tracking NNTP, UID == article number
542         # LIST.ACTIVE can get the equivalent of UIDVALIDITY, but that's
543         # expensive.  So we assume newsgroups don't change:
544         my $itrk = $self->{incremental} ?
545                         PublicInbox::IMAPTracker->new($$uri) : 0;
546         my (undef, $l_art) = $itrk ? $itrk->get_last : ();
547
548         # allow users to specify articles to refetch
549         # cf. https://tools.ietf.org/id/draft-gilman-news-url-01.txt
550         # nntp://example.com/inbox.foo/$num_a-$num_b
551         $beg = $num_a if defined($num_a) && $num_a < $beg;
552         $end = $num_b if defined($num_b) && $num_b < $end;
553         if (defined $l_art) {
554                 return if $l_art >= $end; # nothing to do
555                 $beg = $l_art + 1;
556         }
557         my ($err, $art, $last_art, $kw); # kw stays undef, no keywords in NNTP
558         unless ($self->{quiet}) {
559                 warn "# $uri fetching ARTICLE $beg..$end\n";
560         }
561         my $n = $self->{max_batch};
562         for ($beg..$end) {
563                 last if $self->{quit};
564                 $art = $_;
565                 if (--$n < 0) {
566                         run_commit_cb($self);
567                         $itrk->update_last(0, $last_art) if $itrk;
568                         $n = $self->{max_batch};
569                 }
570                 my $raw = $nn->article($art);
571                 unless (defined($raw)) {
572                         my $msg = ndump($nn->message);
573                         if ($nn->code == 421) { # pseudo response from Net::Cmd
574                                 $err = "E: $msg";
575                                 last;
576                         } else { # probably just a deleted message (spam)
577                                 warn "W: $msg";
578                                 next;
579                         }
580                 }
581                 $raw = join('', @$raw);
582                 $raw =~ s/\r\n/\n/sg;
583                 my ($eml_cb, @args) = @{$self->{eml_each}};
584                 $eml_cb->($uri, $art, $kw, PublicInbox::Eml->new(\$raw), @args);
585                 $last_art = $art;
586         }
587         run_commit_cb($self);
588         $itrk->update_last(0, $last_art) if $itrk;
589         $err;
590 }
591
592 sub nntp_each {
593         my ($self, $url, $eml_cb, @args) = @_;
594         my $uri = ref($url) ? $url : PublicInbox::URInntps->new($url);
595         my $sec = uri_section($uri);
596         local $0 = $uri->group ." $sec";
597         my $nn = nn_get($self, $uri);
598         return if $self->{quit};
599         my $err;
600         if ($nn) {
601                 local $self->{eml_each} = [ $eml_cb, @args ];
602                 $err = _nntp_fetch_all($self, $nn, $uri);
603         } else {
604                 $err = "E: <$uri> not connected: $!";
605         }
606         warn $err if $err;
607         $nn;
608 }
609
610 sub new { bless {}, shift };
611
612 1;