]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/NetReader.pm
821e5d7fb7c12179ad18a23042503e626b89155c
[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                 my $mic = $mics->{$sec} //=
268                                 mic_for($self, "$sec/", $mic_args, $lei) //
269                                 die "Unable to continue\n";
270                 next unless $self->isa('PublicInbox::NetWriter');
271                 my $dst = $uri->mailbox // next;
272                 next if $mic->exists($dst); # already exists
273                 $mic->create($dst) or die "CREATE $dst failed <$uri>: $@";
274         }
275         $mics;
276 }
277
278 # flesh out common NNTP-specific data structures
279 sub nntp_common_init ($;$) {
280         my ($self, $lei) = @_;
281         return unless $self->{nntp_order};
282         $self->{quiet} = 1 if $lei && $lei->{opt}->{quiet};
283         eval { require Net::NNTP } or
284                 die "Net::NNTP is required for NNTP:\n$@\n";
285         eval { require PublicInbox::IMAPTracker } or
286                 die "DBD::SQLite is required for NNTP\n:$@\n";
287         my $cfg = $self->{pi_cfg} // $lei->_lei_cfg;
288         my $nn_args = {}; # scheme://authority => Net::NNTP->new arg
289         for my $uri (@{$self->{nntp_order}}) {
290                 my $sec = uri_section($uri);
291
292                 # Debug and Timeout are passed to Net::NNTP->new
293                 my $v = cfg_bool($cfg, 'nntp.Debug', $$uri);
294                 $nn_args->{$sec}->{Debug} = $v if defined $v;
295                 my $to = cfg_intvl($cfg, 'nntp.Timeout', $$uri);
296                 $nn_args->{$sec}->{Timeout} = $to if $to;
297
298                 # Net::NNTP post-connect commands
299                 for my $k (qw(starttls compress)) {
300                         $v = cfg_bool($cfg, "nntp.$k", $$uri) // next;
301                         $self->{nntp_opt}->{$sec}->{$k} = $v;
302                 }
303
304                 # internal option
305                 for my $k (qw(pollInterval)) {
306                         $to = cfg_intvl($cfg, "nntp.$k", $$uri) // next;
307                         $self->{nntp_opt}->{$sec}->{$k} = $to;
308                 }
309         }
310         # make sure we can connect and cache the credentials in memory
311         $self->{nn_arg} = {}; # schema://authority => Net::NNTP->new args
312         my %nn; # schema://authority => Net::NNTP object
313         for my $uri (@{$self->{nntp_order}}) {
314                 my $sec = uri_section($uri);
315                 $nn{$sec} //= nn_for($self, $uri, $nn_args, $lei);
316         }
317         \%nn; # for optional {nn_cached}
318 }
319
320 sub add_url {
321         my ($self, $arg) = @_;
322         my $uri;
323         if ($uri = imap_uri($arg)) {
324                 push @{$self->{imap_order}}, $uri;
325         } elsif ($uri = nntp_uri($arg)) {
326                 push @{$self->{nntp_order}}, $uri;
327         } else {
328                 push @{$self->{unsupported_url}}, $arg;
329         }
330 }
331
332 sub errors {
333         my ($self) = @_;
334         if (my $u = $self->{unsupported_url}) {
335                 return "Unsupported URL(s): @$u";
336         }
337         if ($self->{imap_order}) {
338                 eval { require PublicInbox::IMAPClient } or
339                         die "Mail::IMAPClient is required for IMAP:\n$@\n";
340         }
341         if ($self->{nntp_order}) {
342                 eval { require Net::NNTP } or
343                         die "Net::NNTP is required for NNTP:\n$@\n";
344         }
345         undef;
346 }
347
348 sub _imap_do_msg ($$$$$) {
349         my ($self, $uri, $uid, $raw, $flags) = @_;
350         # our target audience expects LF-only, save storage
351         $$raw =~ s/\r\n/\n/sg;
352         my $kw = [];
353         for my $f (split(/ /, $flags)) {
354                 if (my $k = $IMAPflags2kw{$f}) {
355                         push @$kw, $k;
356                 } elsif ($f eq "\\Recent") { # not in JMAP
357                 } elsif ($f eq "\\Deleted") { # not in JMAP
358                         return;
359                 } elsif ($self->{verbose}) {
360                         warn "# unknown IMAP flag $f <$uri;uid=$uid>\n";
361                 }
362         }
363         @$kw = sort @$kw; # for all UI/UX purposes
364         my ($eml_cb, @args) = @{$self->{eml_each}};
365         $eml_cb->($uri, $uid, $kw, PublicInbox::Eml->new($raw), @args);
366 }
367
368 sub run_commit_cb ($) {
369         my ($self) = @_;
370         my $cmt_cb_args = $self->{on_commit} or return;
371         my ($cb, @args) = @$cmt_cb_args;
372         $cb->(@args);
373 }
374
375 sub _imap_fetch_all ($$$) {
376         my ($self, $mic, $uri) = @_;
377         my $sec = uri_section($uri);
378         my $mbx = $uri->mailbox;
379         $mic->Clear(1); # trim results history
380         $mic->examine($mbx) or return "E: EXAMINE $mbx ($sec) failed: $!";
381         my ($r_uidval, $r_uidnext);
382         for ($mic->Results) {
383                 /^\* OK \[UIDVALIDITY ([0-9]+)\].*/ and $r_uidval = $1;
384                 /^\* OK \[UIDNEXT ([0-9]+)\].*/ and $r_uidnext = $1;
385                 last if $r_uidval && $r_uidnext;
386         }
387         $r_uidval //= $mic->uidvalidity($mbx) //
388                 return "E: $uri cannot get UIDVALIDITY";
389         $r_uidnext //= $mic->uidnext($mbx) //
390                 return "E: $uri cannot get UIDNEXT";
391         my $itrk = $self->{incremental} ?
392                         PublicInbox::IMAPTracker->new($$uri) : 0;
393         my ($l_uidval, $l_uid) = $itrk ? $itrk->get_last : ();
394         $l_uidval //= $r_uidval; # first time
395         $l_uid //= 0;
396         if ($l_uidval != $r_uidval) {
397                 return "E: $uri UIDVALIDITY mismatch\n".
398                         "E: local=$l_uidval != remote=$r_uidval";
399         }
400         my $r_uid = $r_uidnext - 1;
401         if ($l_uid > $r_uid) {
402                 return "E: $uri local UID exceeds remote ($l_uid > $r_uid)\n".
403                         "E: $uri strangely, UIDVALIDLITY matches ($l_uidval)\n";
404         }
405         return if $l_uid >= $r_uid; # nothing to do
406         $l_uid ||= 1;
407         my ($mod, $shard) = @{$self->{shard_info} // []};
408         unless ($self->{quiet}) {
409                 my $m = $mod ? " [(UID % $mod) == $shard]" : '';
410                 warn "# $uri fetching UID $l_uid:$r_uid$m\n";
411         }
412         $mic->Uid(1); # the default, we hope
413         my $bs = $self->{imap_opt}->{$sec}->{batch_size} // 1;
414         my $req = $mic->imap4rev1 ? 'BODY.PEEK[]' : 'RFC822.PEEK';
415         my $key = $req;
416         $key =~ s/\.PEEK//;
417         my ($uids, $batch);
418         my $err;
419         do {
420                 # I wish "UID FETCH $START:*" could work, but:
421                 # 1) servers do not need to return results in any order
422                 # 2) Mail::IMAPClient doesn't offer a streaming API
423                 unless ($uids = $mic->search("UID $l_uid:*")) {
424                         return if $!{EINTR} && $self->{quit};
425                         return "E: $uri UID SEARCH $l_uid:* error: $!";
426                 }
427                 return if scalar(@$uids) == 0;
428
429                 # RFC 3501 doesn't seem to indicate order of UID SEARCH
430                 # responses, so sort it ourselves.  Order matters so
431                 # IMAPTracker can store the newest UID.
432                 @$uids = sort { $a <=> $b } @$uids;
433
434                 # Did we actually get new messages?
435                 return if $uids->[0] < $l_uid;
436
437                 $l_uid = $uids->[-1] + 1; # for next search
438                 my $last_uid;
439                 my $n = $self->{max_batch};
440
441                 @$uids = grep { ($_ % $mod) == $shard } @$uids if $mod;
442                 while (scalar @$uids) {
443                         my @batch = splice(@$uids, 0, $bs);
444                         $batch = join(',', @batch);
445                         local $0 = "UID:$batch $mbx $sec";
446                         my $r = $mic->fetch_hash($batch, $req, 'FLAGS');
447                         unless ($r) { # network error?
448                                 last if $!{EINTR} && $self->{quit};
449                                 $err = "E: $uri UID FETCH $batch error: $!";
450                                 last;
451                         }
452                         for my $uid (@batch) {
453                                 # messages get deleted, so holes appear
454                                 my $per_uid = delete $r->{$uid} // next;
455                                 my $raw = delete($per_uid->{$key}) // next;
456                                 _imap_do_msg($self, $uri, $uid, \$raw,
457                                                 $per_uid->{FLAGS});
458                                 $last_uid = $uid;
459                                 last if $self->{quit};
460                         }
461                         last if $self->{quit};
462                 }
463                 run_commit_cb($self);
464                 $itrk->update_last($r_uidval, $last_uid) if $itrk;
465         } until ($err || $self->{quit});
466         $err;
467 }
468
469 # uses cached auth info prepared by mic_for
470 sub mic_get {
471         my ($self, $uri) = @_;
472         my $sec = uri_section($uri);
473         # see if caller saved result of imap_common_init
474         my $cached = $self->{mics_cached};
475         if ($cached) {
476                 my $mic = $cached->{$sec};
477                 return $mic if $mic && $mic->IsConnected;
478                 delete $cached->{$sec};
479         }
480         my $mic_arg = $self->{mic_arg}->{$sec} or
481                         die "BUG: no Mail::IMAPClient->new arg for $sec";
482         if (defined(my $cb_name = $mic_arg->{Authcallback})) {
483                 if (ref($cb_name) ne 'CODE') {
484                         $mic_arg->{Authcallback} = $self->can($cb_name);
485                 }
486         }
487         my $mic = PublicInbox::IMAPClient->new(%$mic_arg);
488         $cached //= {}; # invalid placeholder if no cache enabled
489         $mic && $mic->IsConnected ? ($cached->{$sec} = $mic) : undef;
490 }
491
492 sub imap_each {
493         my ($self, $url, $eml_cb, @args) = @_;
494         my $uri = ref($url) ? $url : PublicInbox::URIimap->new($url);
495         my $sec = uri_section($uri);
496         local $0 = $uri->mailbox." $sec";
497         my $mic = mic_get($self, $uri);
498         my $err;
499         if ($mic) {
500                 local $self->{eml_each} = [ $eml_cb, @args ];
501                 $err = _imap_fetch_all($self, $mic, $uri);
502         } else {
503                 $err = "E: <$uri> not connected: $!";
504         }
505         warn $err if $err;
506         $mic;
507 }
508
509 # may used cached auth info prepared by nn_for once
510 sub nn_get {
511         my ($self, $uri) = @_;
512         my $sec = uri_section($uri);
513         # see if caller saved result of nntp_common_init
514         my $cached = $self->{nn_cached} // {};
515         my $nn;
516         $nn = delete($cached->{$sec}) and return $nn;
517         my $nn_arg = $self->{nn_arg}->{$sec} or
518                         die "BUG: no Net::NNTP->new arg for $sec";
519         my $nntp_opt = $self->{nntp_opt}->{$sec};
520         $nn = nn_new($nn_arg, $nntp_opt, $uri) or return;
521         if (my $postconn = $nntp_opt->{-postconn}) {
522                 for my $m_arg (@$postconn) {
523                         my ($method, @args) = @$m_arg;
524                         $nn->$method(@args) and next;
525                         die "E: <$uri> $method failed\n";
526                         return;
527                 }
528         }
529         $nn;
530 }
531
532 sub _nntp_fetch_all ($$$) {
533         my ($self, $nn, $uri) = @_;
534         my ($group, $num_a, $num_b) = $uri->group;
535         my $sec = uri_section($uri);
536         my ($nr, $beg, $end) = $nn->group($group);
537         unless (defined($nr)) {
538                 my $msg = ndump($nn->message);
539                 return "E: GROUP $group <$sec> $msg";
540         }
541
542         # IMAPTracker is also used for tracking NNTP, UID == article number
543         # LIST.ACTIVE can get the equivalent of UIDVALIDITY, but that's
544         # expensive.  So we assume newsgroups don't change:
545         my $itrk = $self->{incremental} ?
546                         PublicInbox::IMAPTracker->new($$uri) : 0;
547         my (undef, $l_art) = $itrk ? $itrk->get_last : ();
548
549         # allow users to specify articles to refetch
550         # cf. https://tools.ietf.org/id/draft-gilman-news-url-01.txt
551         # nntp://example.com/inbox.foo/$num_a-$num_b
552         $beg = $num_a if defined($num_a) && $num_a < $beg;
553         $end = $num_b if defined($num_b) && $num_b < $end;
554         if (defined $l_art) {
555                 return if $l_art >= $end; # nothing to do
556                 $beg = $l_art + 1;
557         }
558         my ($err, $art, $last_art, $kw); # kw stays undef, no keywords in NNTP
559         unless ($self->{quiet}) {
560                 warn "# $uri fetching ARTICLE $beg..$end\n";
561         }
562         my $n = $self->{max_batch};
563         for ($beg..$end) {
564                 last if $self->{quit};
565                 $art = $_;
566                 if (--$n < 0) {
567                         run_commit_cb($self);
568                         $itrk->update_last(0, $last_art) if $itrk;
569                         $n = $self->{max_batch};
570                 }
571                 my $raw = $nn->article($art);
572                 unless (defined($raw)) {
573                         my $msg = ndump($nn->message);
574                         if ($nn->code == 421) { # pseudo response from Net::Cmd
575                                 $err = "E: $msg";
576                                 last;
577                         } else { # probably just a deleted message (spam)
578                                 warn "W: $msg";
579                                 next;
580                         }
581                 }
582                 $raw = join('', @$raw);
583                 $raw =~ s/\r\n/\n/sg;
584                 my ($eml_cb, @args) = @{$self->{eml_each}};
585                 $eml_cb->($uri, $art, $kw, PublicInbox::Eml->new(\$raw), @args);
586                 $last_art = $art;
587         }
588         run_commit_cb($self);
589         $itrk->update_last(0, $last_art) if $itrk;
590         $err;
591 }
592
593 sub nntp_each {
594         my ($self, $url, $eml_cb, @args) = @_;
595         my $uri = ref($url) ? $url : PublicInbox::URInntps->new($url);
596         my $sec = uri_section($uri);
597         local $0 = $uri->group ." $sec";
598         my $nn = nn_get($self, $uri);
599         return if $self->{quit};
600         my $err;
601         if ($nn) {
602                 local $self->{eml_each} = [ $eml_cb, @args ];
603                 $err = _nntp_fetch_all($self, $nn, $uri);
604         } else {
605                 $err = "E: <$uri> not connected: $!";
606         }
607         warn $err if $err;
608         $nn;
609 }
610
611 sub new { bless {}, shift };
612
613 1;