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