]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/NetReader.pm
lei: flesh out `forwarded' kw support for Maildir and IMAP
[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 $IMAPflags2kw{'$Forwarded'} = 'forwarded';  # RFC 5550
12
13 our @EXPORT = qw(uri_section imap_uri nntp_uri);
14
15 sub ndump {
16         require Data::Dumper;
17         Data::Dumper->new(\@_)->Useqq(1)->Terse(1)->Dump;
18 }
19
20 # returns the git config section name, e.g [imap "imaps://user@example.com"]
21 # without the mailbox, so we can share connections between different inboxes
22 sub uri_section ($) {
23         my ($uri) = @_;
24         $uri->scheme . '://' . $uri->authority;
25 }
26
27 sub auth_anon_cb { '' }; # for Mail::IMAPClient::Authcallback
28
29 # mic_for may prompt the user and store auth info, prepares mic_get
30 sub mic_for { # mic = Mail::IMAPClient
31         my ($self, $url, $mic_args, $lei) = @_;
32         require PublicInbox::URIimap;
33         my $uri = PublicInbox::URIimap->new($url);
34         require PublicInbox::GitCredential;
35         my $cred = bless {
36                 url => $url,
37                 protocol => $uri->scheme,
38                 host => $uri->host,
39                 username => $uri->user,
40                 password => $uri->password,
41         }, 'PublicInbox::GitCredential';
42         my $common = $mic_args->{uri_section($uri)} // {};
43         # IMAPClient and Net::Netrc both mishandles `0', so we pass `127.0.0.1'
44         my $host = $cred->{host};
45         $host = '127.0.0.1' if $host eq '0';
46         my $mic_arg = {
47                 Port => $uri->port,
48                 Server => $host,
49                 Ssl => $uri->scheme eq 'imaps',
50                 Keepalive => 1, # SO_KEEPALIVE
51                 %$common, # may set Starttls, Compress, Debug ....
52         };
53         require PublicInbox::IMAPClient;
54         my $mic = PublicInbox::IMAPClient->new(%$mic_arg) or
55                 die "E: <$url> new: $@\n";
56
57         # default to using STARTTLS if it's available, but allow
58         # it to be disabled since I usually connect to localhost
59         if (!$mic_arg->{Ssl} && !defined($mic_arg->{Starttls}) &&
60                         $mic->has_capability('STARTTLS') &&
61                         $mic->can('starttls')) {
62                 $mic->starttls or die "E: <$url> STARTTLS: $@\n";
63         }
64
65         # do we even need credentials?
66         if (!defined($cred->{username}) &&
67                         $mic->has_capability('AUTH=ANONYMOUS')) {
68                 $cred = undef;
69         }
70         if ($cred) {
71                 $cred->check_netrc unless defined $cred->{password};
72                 $cred->fill($lei); # may prompt user here
73                 $mic->User($mic_arg->{User} = $cred->{username});
74                 $mic->Password($mic_arg->{Password} = $cred->{password});
75         } else { # AUTH=ANONYMOUS
76                 $mic->Authmechanism($mic_arg->{Authmechanism} = 'ANONYMOUS');
77                 $mic_arg->{Authcallback} = 'auth_anon_cb';
78                 $mic->Authcallback(\&auth_anon_cb);
79         }
80         my $err;
81         if ($mic->login && $mic->IsAuthenticated) {
82                 # success! keep IMAPClient->new arg in case we get disconnected
83                 $self->{mic_arg}->{uri_section($uri)} = $mic_arg;
84         } else {
85                 $err = "E: <$url> LOGIN: $@\n";
86                 if ($cred && defined($cred->{password})) {
87                         $err =~ s/\Q$cred->{password}\E/*******/g;
88                 }
89                 $mic = undef;
90         }
91         $cred->run($mic ? 'approve' : 'reject') if $cred;
92         if ($err) {
93                 $lei ? $lei->fail($err) : warn($err);
94         }
95         $mic;
96 }
97
98 # Net::NNTP doesn't support CAPABILITIES, yet
99 sub try_starttls ($) {
100         my ($host) = @_;
101         return if $host =~ /\.onion\z/s;
102         return if $host =~ /\A127\.[0-9]+\.[0-9]+\.[0-9]+\z/s;
103         return if $host eq '::1';
104         1;
105 }
106
107 sub nn_new ($$$) {
108         my ($nn_arg, $nntp_opt, $uri) = @_;
109         my $nn = Net::NNTP->new(%$nn_arg) or die "E: <$uri> new: $!\n";
110
111         # default to using STARTTLS if it's available, but allow
112         # it to be disabled for localhost/VPN users
113         if (!$nn_arg->{SSL} && $nn->can('starttls')) {
114                 if (!defined($nntp_opt->{starttls}) &&
115                                 try_starttls($nn_arg->{Host})) {
116                         # soft fail by default
117                         $nn->starttls or warn <<"";
118 W: <$uri> STARTTLS tried and failed (not requested)
119
120                 } elsif ($nntp_opt->{starttls}) {
121                         # hard fail if explicitly configured
122                         $nn->starttls or die <<"";
123 E: <$uri> STARTTLS requested and failed
124
125                 }
126         } elsif ($nntp_opt->{starttls}) {
127                 $nn->can('starttls') or
128                         die "E: <$uri> Net::NNTP too old for STARTTLS\n";
129                 $nn->starttls or die <<"";
130 E: <$uri> STARTTLS requested and failed
131
132         }
133         $nn;
134 }
135
136 sub nn_for ($$$;$) { # nn = Net::NNTP
137         my ($self, $uri, $nn_args, $lei) = @_;
138         my $sec = uri_section($uri);
139         my $nntp_opt = $self->{nntp_opt}->{$sec} //= {};
140         my $host = $uri->host;
141         # Net::NNTP and Net::Netrc both mishandle `0', so we pass `127.0.0.1'
142         $host = '127.0.0.1' if $host eq '0';
143         my $cred;
144         my ($u, $p);
145         if (defined(my $ui = $uri->userinfo)) {
146                 require PublicInbox::GitCredential;
147                 $cred = bless {
148                         url => $sec,
149                         protocol => $uri->scheme,
150                         host => $host,
151                 }, 'PublicInbox::GitCredential';
152                 ($u, $p) = split(/:/, $ui, 2);
153                 ($cred->{username}, $cred->{password}) = ($u, $p);
154                 $cred->check_netrc unless defined $p;
155         }
156         my $common = $nn_args->{$sec} // {};
157         my $nn_arg = {
158                 Port => $uri->port,
159                 Host => $host,
160                 SSL => $uri->secure, # snews == nntps
161                 %$common, # may Debug ....
162         };
163         my $nn = nn_new($nn_arg, $nntp_opt, $uri);
164         if ($cred) {
165                 $cred->fill($lei); # may prompt user here
166                 if ($nn->authinfo($u, $p)) {
167                         push @{$nntp_opt->{-postconn}}, [ 'authinfo', $u, $p ];
168                 } else {
169                         warn "E: <$uri> AUTHINFO $u XXXX failed\n";
170                         $nn = undef;
171                 }
172         }
173
174         if ($nntp_opt->{compress}) {
175                 # https://rt.cpan.org/Ticket/Display.html?id=129967
176                 if ($nn->can('compress')) {
177                         if ($nn->compress) {
178                                 push @{$nntp_opt->{-postconn}}, [ 'compress' ];
179                         } else {
180                                 warn "W: <$uri> COMPRESS failed\n";
181                         }
182                 } else {
183                         delete $nntp_opt->{compress};
184                         warn <<"";
185 W: <$uri> COMPRESS not supported by Net::NNTP
186 W: see https://rt.cpan.org/Ticket/Display.html?id=129967 for updates
187
188                 }
189         }
190
191         $self->{nn_arg}->{$sec} = $nn_arg;
192         $cred->run($nn ? 'approve' : 'reject') if $cred;
193         $nn;
194 }
195
196 sub imap_uri {
197         my ($url) = @_;
198         require PublicInbox::URIimap;
199         my $uri = PublicInbox::URIimap->new($url);
200         $uri ? $uri->canonical : undef;
201 }
202
203 my %IS_NNTP = (news => 1, snews => 1, nntp => 1, nntps => 1);
204 sub nntp_uri {
205         my ($url) = @_;
206         require PublicInbox::URInntps;
207         my $uri = PublicInbox::URInntps->new($url);
208         $uri && $IS_NNTP{$uri->scheme} && $uri->group ? $uri->canonical : undef;
209 }
210
211 sub cfg_intvl ($$$) {
212         my ($cfg, $key, $url) = @_;
213         my $v = $cfg->urlmatch($key, $url) // return;
214         $v =~ /\A[0-9]+(?:\.[0-9]+)?\z/s and return $v + 0;
215         if (ref($v) eq 'ARRAY') {
216                 $v = join(', ', @$v);
217                 warn "W: $key has multiple values: $v\nW: $key ignored\n";
218         } else {
219                 warn "W: $key=$v is not a numeric value in seconds\n";
220         }
221 }
222
223 sub cfg_bool ($$$) {
224         my ($cfg, $key, $url) = @_;
225         my $orig = $cfg->urlmatch($key, $url) // return;
226         my $bool = $cfg->git_bool($orig);
227         warn "W: $key=$orig for $url is not boolean\n" unless defined($bool);
228         $bool;
229 }
230
231 # flesh out common IMAP-specific data structures
232 sub imap_common_init ($;$) {
233         my ($self, $lei) = @_;
234         return unless $self->{imap_order};
235         $self->{quiet} = 1 if $lei && $lei->{opt}->{quiet};
236         eval { require PublicInbox::IMAPClient } or
237                 die "Mail::IMAPClient is required for IMAP:\n$@\n";
238         eval { require PublicInbox::IMAPTracker } or
239                 die "DBD::SQLite is required for IMAP\n:$@\n";
240         require PublicInbox::URIimap;
241         my $cfg = $self->{pi_cfg} // $lei->_lei_cfg;
242         my $mic_args = {}; # scheme://authority => Mail:IMAPClient arg
243         for my $uri (@{$self->{imap_order}}) {
244                 my $sec = uri_section($uri);
245                 for my $k (qw(Starttls Debug Compress)) {
246                         my $bool = cfg_bool($cfg, "imap.$k", $$uri) // next;
247                         $mic_args->{$sec}->{$k} = $bool;
248                 }
249                 my $to = cfg_intvl($cfg, 'imap.timeout', $$uri);
250                 $mic_args->{$sec}->{Timeout} = $to if $to;
251                 for my $k (qw(pollInterval idleInterval)) {
252                         $to = cfg_intvl($cfg, "imap.$k", $$uri) // next;
253                         $self->{imap_opt}->{$sec}->{$k} = $to;
254                 }
255                 my $k = 'imap.fetchBatchSize';
256                 my $bs = $cfg->urlmatch($k, $$uri) // next;
257                 if ($bs =~ /\A([0-9]+)\z/) {
258                         $self->{imap_opt}->{$sec}->{batch_size} = $bs;
259                 } else {
260                         warn "$k=$bs is not an integer\n";
261                 }
262         }
263         # make sure we can connect and cache the credentials in memory
264         $self->{mic_arg} = {}; # schema://authority => IMAPClient->new args
265         my $mics = {}; # schema://authority => IMAPClient obj
266         for my $uri (@{$self->{imap_order}}) {
267                 my $sec = uri_section($uri);
268                 my $mic = $mics->{$sec} //=
269                                 mic_for($self, "$sec/", $mic_args, $lei) //
270                                 die "Unable to continue\n";
271                 next unless $self->isa('PublicInbox::NetWriter');
272                 my $dst = $uri->mailbox // next;
273                 next if $mic->exists($dst); # already exists
274                 $mic->create($dst) or die "CREATE $dst failed <$uri>: $@";
275         }
276         $mics;
277 }
278
279 # flesh out common NNTP-specific data structures
280 sub nntp_common_init ($;$) {
281         my ($self, $lei) = @_;
282         return unless $self->{nntp_order};
283         $self->{quiet} = 1 if $lei && $lei->{opt}->{quiet};
284         eval { require Net::NNTP } or
285                 die "Net::NNTP is required for NNTP:\n$@\n";
286         eval { require PublicInbox::IMAPTracker } or
287                 die "DBD::SQLite is required for NNTP\n:$@\n";
288         my $cfg = $self->{pi_cfg} // $lei->_lei_cfg;
289         my $nn_args = {}; # scheme://authority => Net::NNTP->new arg
290         for my $uri (@{$self->{nntp_order}}) {
291                 my $sec = uri_section($uri);
292
293                 # Debug and Timeout are passed to Net::NNTP->new
294                 my $v = cfg_bool($cfg, 'nntp.Debug', $$uri);
295                 $nn_args->{$sec}->{Debug} = $v if defined $v;
296                 my $to = cfg_intvl($cfg, 'nntp.Timeout', $$uri);
297                 $nn_args->{$sec}->{Timeout} = $to if $to;
298
299                 # Net::NNTP post-connect commands
300                 for my $k (qw(starttls compress)) {
301                         $v = cfg_bool($cfg, "nntp.$k", $$uri) // next;
302                         $self->{nntp_opt}->{$sec}->{$k} = $v;
303                 }
304
305                 # internal option
306                 for my $k (qw(pollInterval)) {
307                         $to = cfg_intvl($cfg, "nntp.$k", $$uri) // next;
308                         $self->{nntp_opt}->{$sec}->{$k} = $to;
309                 }
310         }
311         # make sure we can connect and cache the credentials in memory
312         $self->{nn_arg} = {}; # schema://authority => Net::NNTP->new args
313         my %nn; # schema://authority => Net::NNTP object
314         for my $uri (@{$self->{nntp_order}}) {
315                 my $sec = uri_section($uri);
316                 $nn{$sec} //= nn_for($self, $uri, $nn_args, $lei);
317         }
318         \%nn; # for optional {nn_cached}
319 }
320
321 sub add_url {
322         my ($self, $arg) = @_;
323         my $uri;
324         if ($uri = imap_uri($arg)) {
325                 push @{$self->{imap_order}}, $uri;
326         } elsif ($uri = nntp_uri($arg)) {
327                 push @{$self->{nntp_order}}, $uri;
328         } else {
329                 push @{$self->{unsupported_url}}, $arg;
330         }
331 }
332
333 sub errors {
334         my ($self) = @_;
335         if (my $u = $self->{unsupported_url}) {
336                 return "Unsupported URL(s): @$u";
337         }
338         if ($self->{imap_order}) {
339                 eval { require PublicInbox::IMAPClient } or
340                         die "Mail::IMAPClient is required for IMAP:\n$@\n";
341         }
342         if ($self->{nntp_order}) {
343                 eval { require Net::NNTP } or
344                         die "Net::NNTP is required for NNTP:\n$@\n";
345         }
346         undef;
347 }
348
349 sub _imap_do_msg ($$$$$) {
350         my ($self, $uri, $uid, $raw, $flags) = @_;
351         # our target audience expects LF-only, save storage
352         $$raw =~ s/\r\n/\n/sg;
353         my $kw = [];
354         for my $f (split(/ /, $flags)) {
355                 if (my $k = $IMAPflags2kw{$f}) {
356                         push @$kw, $k;
357                 } elsif ($f eq "\\Recent") { # not in JMAP
358                 } elsif ($f eq "\\Deleted") { # not in JMAP
359                         return;
360                 } elsif ($self->{verbose}) {
361                         warn "# unknown IMAP flag $f <$uri;uid=$uid>\n";
362                 }
363         }
364         @$kw = sort @$kw; # for all UI/UX purposes
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                 my $msg = ndump($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, $last_art, $kw); # kw stays undef, no keywords in NNTP
560         unless ($self->{quiet}) {
561                 warn "# $uri fetching ARTICLE $beg..$end\n";
562         }
563         my $n = $self->{max_batch};
564         for ($beg..$end) {
565                 last if $self->{quit};
566                 $art = $_;
567                 if (--$n < 0) {
568                         run_commit_cb($self);
569                         $itrk->update_last(0, $last_art) if $itrk;
570                         $n = $self->{max_batch};
571                 }
572                 my $raw = $nn->article($art);
573                 unless (defined($raw)) {
574                         my $msg = ndump($nn->message);
575                         if ($nn->code == 421) { # pseudo response from Net::Cmd
576                                 $err = "E: $msg";
577                                 last;
578                         } else { # probably just a deleted message (spam)
579                                 warn "W: $msg";
580                                 next;
581                         }
582                 }
583                 $raw = join('', @$raw);
584                 $raw =~ s/\r\n/\n/sg;
585                 my ($eml_cb, @args) = @{$self->{eml_each}};
586                 $eml_cb->($uri, $art, $kw, PublicInbox::Eml->new(\$raw), @args);
587                 $last_art = $art;
588         }
589         run_commit_cb($self);
590         $itrk->update_last(0, $last_art) if $itrk;
591         $err;
592 }
593
594 sub nntp_each {
595         my ($self, $url, $eml_cb, @args) = @_;
596         my $uri = ref($url) ? $url : PublicInbox::URInntps->new($url);
597         my $sec = uri_section($uri);
598         local $0 = $uri->group ." $sec";
599         my $nn = nn_get($self, $uri);
600         return if $self->{quit};
601         my $err;
602         if ($nn) {
603                 local $self->{eml_each} = [ $eml_cb, @args ];
604                 $err = _nntp_fetch_all($self, $nn, $uri);
605         } else {
606                 $err = "E: <$uri> not connected: $!";
607         }
608         warn $err if $err;
609         $nn;
610 }
611
612 sub new { bless {}, shift };
613
614 1;