1 # Copyright (C) all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # Each instance of this represents a NNTP client socket
6 # nntpd: PublicInbox::NNTPD ref
7 # article: per-session current article number
8 # ibx: PublicInbox::Inbox ref
9 # long_cb: long_response private data
10 package PublicInbox::NNTP;
13 use parent qw(PublicInbox::DS);
14 use PublicInbox::MID qw(mid_escape $MID_EXTRACT);
16 use POSIX qw(strftime);
17 use PublicInbox::DS qw(now);
18 use Digest::SHA qw(sha1_hex);
19 use Time::Local qw(timegm timelocal);
20 use PublicInbox::GitAsyncCat;
21 use PublicInbox::Address;
24 LINE_MAX => 512, # RFC 977 section 2.3
25 r501 => "501 command syntax error\r\n",
26 r502 => "502 Command unavailable\r\n",
27 r221 => "221 Header follows\r\n",
28 r225 => "225 Headers follow (multi-line)\r\n",
29 r430 => "430 No article with that message-id\r\n",
32 my $ONE_MSGID = qr/\A$MID_EXTRACT\z/;
33 my @OVERVIEW = qw(Subject From Date Message-ID References);
34 my $OVERVIEW_FMT = join(":\r\n", @OVERVIEW, qw(Bytes Lines), '') .
36 my $LIST_HEADERS = join("\r\n", @OVERVIEW,
37 qw(:bytes :lines Xref To Cc)) . "\r\n.\r\n";
38 my $CAPABILITIES = <<"";
39 101 Capability list:\r
43 LIST ACTIVE ACTIVE.TIMES NEWSGROUPS OVERVIEW.FMT\r
48 sub do_greet ($) { $_[0]->write($_[0]->{nntpd}->{greet}) };
51 my ($cls, $sock, $nntpd) = @_;
52 (bless { nntpd => $nntpd }, $cls)->greet($sock)
57 my $tot = prototype $cb;
58 my ($nreq, undef) = split(/;/, $tot);
59 $nreq = ($nreq =~ tr/$//) - 1;
60 $tot = ($tot =~ tr/$//) - 1;
61 ($argc <= $tot && $argc >= $nreq);
64 # returns 1 if we can continue, 0 if not due to buffered writes or disconnect
65 sub process_line ($$) {
67 my ($req, @args) = split(/[ \t]+/, $l);
68 return 1 unless defined($req); # skip blank line
69 $req = $self->can('cmd_'.lc($req)) //
70 return $self->write(\"500 command not recognized\r\n");
71 return $self->write(\r501) unless args_ok($req, scalar @args);
72 my $res = eval { $req->($self, @args) };
74 if ($err && $self->{sock}) {
77 err($self, 'error from: %s (%s)', $l, $err);
78 $res = \"503 program fault - command not performed\r\n";
80 defined($res) ? $self->write($res) : 0;
83 # The keyword argument is not used (rfc3977 5.2.2)
84 sub cmd_capabilities ($;$) {
85 my ($self, undef) = @_;
86 my $res = $CAPABILITIES;
87 if (!$self->{sock}->can('accept_SSL') &&
88 $self->{nntpd}->{accept_tls}) {
89 $res .= "STARTTLS\r\n";
95 my ($self, $arg) = @_;
96 uc($arg) eq 'READER' ? \"201 Posting prohibited\r\n" : \r501;
99 sub cmd_slave ($) { \"202 slave status noted\r\n" }
101 sub cmd_xgtitle ($;$) {
102 my ($self, $wildmat) = @_;
103 $self->msg_more("282 list of groups and descriptions follows\r\n");
104 list_newsgroups($self, $wildmat);
107 sub list_overview_fmt ($) { $OVERVIEW_FMT }
109 sub list_headers ($;$) { $LIST_HEADERS }
111 sub list_active_i { # "LIST ACTIVE" and also just "LIST" (no args)
112 my ($self, $groupnames) = @_;
113 my @window = splice(@$groupnames, 0, 100) or return 0;
115 my $groups = $self->{nntpd}->{pi_cfg}->{-by_newsgroup};
116 for my $ngname (@window) {
117 $ibx = $groups->{$ngname} and group_line($self, $ibx);
119 scalar(@$groupnames); # continue if there's more
122 sub list_active ($;$) { # called by cmd_list
123 my ($self, $wildmat) = @_;
124 wildmat2re($wildmat);
125 $self->long_response(\&list_active_i, [
126 grep(/$wildmat/, @{$self->{nntpd}->{groupnames}}) ]);
129 sub list_active_times_i {
130 my ($self, $groupnames) = @_;
131 my @window = splice(@$groupnames, 0, 100) or return 0;
132 my $groups = $self->{nntpd}->{pi_cfg}->{-by_newsgroup};
133 for my $ngname (@window) {
134 my $ibx = $groups->{$ngname} or next;
135 my $c = eval { $ibx->uidvalidity } // time;
136 $self->msg_more("$ngname $c <$ibx->{-primary_address}>\r\n");
138 scalar(@$groupnames); # continue if there's more
141 sub list_active_times ($;$) { # called by cmd_list
142 my ($self, $wildmat) = @_;
143 wildmat2re($wildmat);
144 $self->long_response(\&list_active_times_i, [
145 grep(/$wildmat/, @{$self->{nntpd}->{groupnames}}) ]);
148 sub list_newsgroups_i {
149 my ($self, $groupnames) = @_;
150 my @window = splice(@$groupnames, 0, 100) or return 0;
151 my $groups = $self->{nntpd}->{pi_cfg}->{-by_newsgroup};
153 for my $ngname (@window) {
154 $ibx = $groups->{$ngname} and
155 $self->msg_more("$ngname ".$ibx->description."\r\n");
157 scalar(@$groupnames); # continue if there's more
160 sub list_newsgroups ($;$) { # called by cmd_list
161 my ($self, $wildmat) = @_;
162 wildmat2re($wildmat);
163 $self->long_response(\&list_newsgroups_i, [
164 grep(/$wildmat/, @{$self->{nntpd}->{groupnames}}) ]);
167 # LIST SUBSCRIPTIONS, DISTRIB.PATS are not supported
168 sub cmd_list ($;$$) {
169 my ($self, @args) = @_;
171 my $arg = shift @args;
172 $arg =~ tr/A-Z./a-z_/;
173 my $ret = $arg eq 'active';
175 $arg = $self->can($arg);
176 return r501 unless $arg && args_ok($arg, scalar @args);
177 $self->msg_more("215 information follows\r\n");
178 $arg->($self, @args);
180 $self->msg_more("215 list of newsgroups follows\r\n");
181 $self->long_response(\&list_active_i, [ # copy array
182 @{$self->{nntpd}->{groupnames}} ]);
186 sub listgroup_range_i {
187 my ($self, $beg, $end) = @_;
188 my $r = $self->{ibx}->mm(1)->msg_range($beg, $end, 'num');
189 scalar(@$r) or return;
190 $self->msg_more(join("\r\n", @$r, ''));
194 sub listgroup_all_i {
195 my ($self, $num) = @_;
196 my $ary = $self->{ibx}->over(1)->ids_after($num);
197 scalar(@$ary) or return;
198 $self->msg_more(join("\r\n", @$ary, ''));
202 sub cmd_listgroup ($;$$) {
203 my ($self, $group, $range) = @_;
204 if (defined $group) {
205 my $res = cmd_group($self, $group);
206 return $res if ref($res); # error if const strref
207 $self->msg_more($res);
209 $self->{ibx} or return \"412 no newsgroup selected\r\n";
210 if (defined $range) {
211 my $r = get_range($self, $range);
212 return $r unless ref $r;
213 $self->long_response(\&listgroup_range_i, @$r);
214 } else { # grab every article number
215 $self->long_response(\&listgroup_all_i, \(my $num = 0));
219 sub parse_time ($$;$) {
220 my ($date, $time, $gmt) = @_;
221 my ($hh, $mm, $ss) = unpack('A2A2A2', $time);
223 $gmt =~ /\A(?:UTC|GMT)\z/i or die "GM invalid: $gmt";
226 my ($YYYY, $MM, $DD);
227 if (length($date) == 8) { # RFC 3977 allows YYYYMMDD
228 ($YYYY, $MM, $DD) = unpack('A4A2A2', $date);
229 } else { # legacy clients send YYMMDD
231 ($YY, $MM, $DD) = unpack('A2A2A2', $date);
232 my @now = $gmt ? gmtime : localtime;
233 my $cur_year = $now[5] + 1900;
234 my $cur_cent = int($cur_year / 100) * 100;
235 $YYYY = (($YY + $cur_cent) > $cur_year) ?
236 ($YY + 1900) : ($YY + $cur_cent);
239 timegm($ss, $mm, $hh, $DD, $MM - 1, $YYYY);
241 timelocal($ss, $mm, $hh, $DD, $MM - 1, $YYYY);
245 sub group_line ($$) {
246 my ($self, $ibx) = @_;
247 my ($min, $max) = $ibx->mm(1)->minmax;
248 $self->msg_more("$ibx->{newsgroup} $max $min n\r\n");
252 my ($self, $ts, $i, $groupnames) = @_;
254 my $groups = $self->{nntpd}->{pi_cfg}->{-by_newsgroup};
256 my $ngname = $groupnames->[$$i++] // return;
257 my $ibx = $groups->{$ngname} or next; # expired on reload
258 next unless (eval { $ibx->uidvalidity } // 0) > $ts;
259 group_line($self, $ibx);
264 sub cmd_newgroups ($$$;$$) {
265 my ($self, $date, $time, $gmt, $dists) = @_;
266 my $ts = eval { parse_time($date, $time, $gmt) };
270 $self->msg_more("231 list of new newsgroups follows\r\n");
271 $self->long_response(\&newgroups_i, $ts, \(my $i = 0),
272 $self->{nntpd}->{groupnames});
275 sub wildmat2re (;$) {
276 return $_[0] = qr/.*/ if (!defined $_[0] || $_[0] eq '*');
281 $tmp =~ s#(?<!\\)\[(.+)(?<!\\)\]#
283 my $key = sha1_hex($orig . $salt);
284 $orig =~ s/([^\w\-])+/\Q$1/g;
288 my %map = ('*' => '.*', '?' => '.' );
289 $tmp =~ s#(?<!\\)([^\w\\])#$map{$1} || "\Q$1"#ge;
291 $tmp =~ s#([a-f0-9]{40})#
292 my $orig = $keep{$1};
293 defined $orig ? $orig : $1;
296 $_[0] = qr/\A$tmp\z/;
300 return $_[0] = qr/\A\z/ unless defined $_[0];
301 my %map = ('*' => '.*', ',' => '|');
302 $_[0] =~ s!(.)!$map{$1} || "\Q$1"!ge;
303 $_[0] = qr/\A(?:$_[0])\z/;
307 my ($self, $names, $ts, $prev) = @_;
308 my $ngname = $names->[0];
309 if (my $ibx = $self->{nntpd}->{pi_cfg}->{-by_newsgroup}->{$ngname}) {
310 if (my $over = $ibx->over) {
311 my $msgs = $over->query_ts($ts, $$prev);
313 $self->msg_more(join('', map {
316 $$prev = $msgs->[-1]->{num};
317 return 1; # continue on current group
322 if (@$names) { # continue onto next newsgroup
325 } else { # all done, break out of the long_response
330 sub cmd_newnews ($$$$;$$) {
331 my ($self, $newsgroups, $date, $time, $gmt, $dists) = @_;
332 my $ts = eval { parse_time($date, $time, $gmt) };
334 $self->msg_more("230 list of new articles by message-id follows\r\n");
335 my ($keep, $skip) = split(/!/, $newsgroups, 2);
338 my @names = grep(!/$skip/, grep(/$keep/,
339 @{$self->{nntpd}->{groupnames}}));
340 return ".\r\n" unless scalar(@names);
342 $self->long_response(\&newnews_i, \@names, $ts, \$prev);
346 my ($self, $group) = @_;
347 my $nntpd = $self->{nntpd};
348 my $ibx = $nntpd->{pi_cfg}->{-by_newsgroup}->{$group} or
349 return \"411 no such news group\r\n";
353 my ($min, $max) = $ibx->mm(1)->minmax;
354 $self->{article} = $min;
355 my $est_size = $max - $min;
356 "211 $est_size $min $max $group\r\n";
359 sub article_adj ($$) {
360 my ($self, $off) = @_;
361 my $ibx = $self->{ibx} // return \"412 no newsgroup selected\r\n";
362 my $n = $self->{article} //
363 return \"420 no current article has been selected\r\n";
366 my $mid = $ibx->mm(1)->mid_for($n) // do {
367 $n = $off > 0 ? 'next' : 'previous';
368 return "421 no $n article in this group\r\n";
370 $self->{article} = $n;
371 "223 $n <$mid> article retrieved - request text separately\r\n";
374 sub cmd_next ($) { article_adj($_[0], 1) }
375 sub cmd_last ($) { article_adj($_[0], -1) }
377 # We want to encourage using email and CC-ing everybody involved to avoid
378 # the single-point-of-failure a single server provides.
381 my $ibx = $self->{ibx};
382 $ibx ? "440 mailto:$ibx->{-primary_address} to post\r\n"
383 : \"440 posting not allowed\r\n"
388 $self->write(\"205 closing connection - goodbye!\r\n");
393 sub xref_by_tc ($$$) {
394 my ($xref, $pi_cfg, $smsg) = @_;
395 my $by_addr = $pi_cfg->{-by_addr};
396 my $mid = $smsg->{mid};
397 for my $f (qw(to cc)) {
399 $by_addr->{lc($_)} // ()
400 } (PublicInbox::Address::emails($smsg->{$f} // ''));
401 for my $ibx (@ibxs) {
402 $xref->{$ibx->{newsgroup}} //=
403 $ibx->mm(1)->num_for($mid);
409 my ($self, $cur_ibx, $smsg) = @_;
410 my $nntpd = $self->{nntpd};
411 my $cur_ng = $cur_ibx->{newsgroup};
413 if (my $ALL = $nntpd->{pi_cfg}->ALL) {
414 $xref = $ALL->nntp_xref_for($cur_ibx, $smsg);
415 xref_by_tc($xref, $nntpd->{pi_cfg}, $smsg);
417 $xref = { $cur_ng => $smsg->{num} };
418 my $mid = $smsg->{mid};
419 for my $ibx (values %{$nntpd->{pi_cfg}->{-by_newsgroup}}) {
420 $xref->{$ibx->{newsgroup}} //=
421 $ibx->mm(1)->num_for($mid);
424 my $ret = "$nntpd->{servername} $cur_ng:".delete($xref->{$cur_ng});
425 for my $ng (sort keys %$xref) {
426 my $num = $xref->{$ng} // next;
432 sub set_nntp_headers ($$) {
433 my ($hdr, $smsg) = @_;
434 my ($mid) = $smsg->{mid};
436 # leafnode (and maybe other NNTP clients) have trouble dealing
437 # with v2 messages which have multiple Message-IDs (either due
438 # to our own content-based dedupe or buggy git-send-email versions).
439 my @mids = $hdr->header_raw('Message-ID');
440 if (scalar(@mids) > 1) {
442 $hdr->header_set('Message-ID', $mid0);
443 my @alt = $hdr->header_raw('X-Alt-Message-ID');
444 my %seen = map { $_ => 1 } (@alt, $mid0);
445 push(@alt, grep { !$seen{$_}++ } @mids);
446 $hdr->header_set('X-Alt-Message-ID', @alt);
449 # clobber some existing headers
450 my $ibx = $smsg->{-ibx};
451 my $xref = xref($smsg->{nntp}, $ibx, $smsg);
452 $hdr->header_set('Xref', $xref);
455 my ($server_name, $newsgroups) = split(/ /, $xref, 2);
456 $newsgroups =~ s/:[0-9]+\b//g; # drop NNTP article numbers
457 $newsgroups =~ tr/ /,/;
458 $hdr->header_set('Newsgroups', $newsgroups);
460 # *something* here is required for leafnode, try to follow
462 $hdr->header_set('Path', $server_name . '!not-for-mail');
465 sub art_lookup ($$$) {
466 my ($self, $art, $code) = @_;
470 if ($art =~ /\A[0-9]+\z/) {
471 $err = \"423 no such article number in this group\r\n";
474 } elsif ($art =~ $ONE_MSGID) {
475 ($ibx, $n) = mid_lookup($self, $1);
482 $err = \"420 no current article has been selected\r\n";
483 $n = $self->{article} // return $err;
485 $ibx = $self->{ibx} or
486 return \"412 no newsgroup has been selected\r\n";
489 my $smsg = $ibx->over(1)->get_art($n) or return $err;
490 $smsg->{-ibx} = $ibx;
491 if ($code == 223) { # STAT
493 "223 $n <$smsg->{mid}> article retrieved - " .
494 "request text separately\r\n";
495 } else { # HEAD | BODY | ARTICLE
496 $smsg->{nntp} = $self;
497 $smsg->{nntp_code} = $code;
498 set_art($self, $art);
499 # this dereferences to `undef'
500 ${ibx_async_cat($ibx, $smsg->{blob}, \&blob_cb, $smsg)};
504 sub msg_body_write ($$) {
505 my ($self, $msg) = @_;
507 # these can momentarily double the memory consumption :<
508 $$msg =~ s/^\./../smg;
509 $$msg =~ s/(?<!\r)\n/\r\n/sg; # Alpine barfs without this
510 $$msg .= "\r\n" unless $$msg =~ /\r\n\z/s;
511 $self->msg_more($$msg);
515 my ($self, $art) = @_;
516 $self->{article} = $art if defined $art && $art =~ /\A[0-9]+\z/;
519 sub msg_hdr_write ($$) {
520 my ($eml, $smsg) = @_;
521 set_nntp_headers($eml, $smsg);
523 my $hdr = $eml->{hdr} // \(my $x = '');
524 # fixup old bug from import (pre-a0c07cba0e5d8b6a)
525 $$hdr =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
526 $$hdr =~ s/(?<!\r)\n/\r\n/sg; # Alpine barfs without this
528 # for leafnode compatibility, we need to ensure Message-ID headers
529 # are only a single line.
530 $$hdr =~ s/^(Message-ID:)[ \t]*\r\n[ \t]+([^\r]+)\r\n/$1 $2\r\n/igsm;
531 $smsg->{nntp}->msg_more($$hdr);
534 sub blob_cb { # called by git->cat_async via ibx_async_cat
535 my ($bref, $oid, $type, $size, $smsg) = @_;
536 my $self = $smsg->{nntp};
537 my $code = $smsg->{nntp_code};
538 if (!defined($oid)) {
539 # it's possible to have TOCTOU if an admin runs
540 # public-inbox-(edit|purge), just move onto the next message
541 warn "E: $smsg->{blob} missing in $smsg->{-ibx}->{inboxdir}\n";
542 return $self->requeue;
543 } elsif ($smsg->{blob} ne $oid) {
545 die "BUG: $smsg->{blob} != $oid";
547 my $r = "$code $smsg->{num} <$smsg->{mid}> article retrieved - ";
548 my $eml = PublicInbox::Eml->new($bref);
550 $self->msg_more($r .= "head and body follow\r\n");
551 msg_hdr_write($eml, $smsg);
552 $self->msg_more("\r\n");
553 msg_body_write($self, $bref);
554 } elsif ($code == 221) {
555 $self->msg_more($r .= "head follows\r\n");
556 msg_hdr_write($eml, $smsg);
557 } elsif ($code == 222) {
558 $self->msg_more($r .= "body follows\r\n");
559 msg_body_write($self, $bref);
562 die "BUG: bad code: $r";
564 $self->write(\".\r\n"); # flushes (includes ->zflush)
568 sub cmd_article ($;$) {
569 my ($self, $art) = @_;
570 art_lookup($self, $art, 220);
574 my ($self, $art) = @_;
575 art_lookup($self, $art, 221);
579 my ($self, $art) = @_;
580 art_lookup($self, $art, 222);
584 my ($self, $art) = @_;
585 art_lookup($self, $art, 223); # art may be msgid
588 sub cmd_ihave ($) { \"435 article not wanted - do not send it\r\n" }
590 sub cmd_date ($) { '111 '.strftime('%Y%m%d%H%M%S', gmtime(time))."\r\n" }
592 sub cmd_help ($) { \"100 help text follows\r\n.\r\n" }
594 # returns a ref on success
596 my ($self, $range) = @_;
597 my $ibx = $self->{ibx} //
598 return "412 no news group has been selected\r\n";
599 $range // return "420 No article(s) selected\r\n";
601 my ($min, $max) = $ibx->mm(1)->minmax;
602 if ($range =~ /\A([0-9]+)\z/) {
604 } elsif ($range =~ /\A([0-9]+)-\z/) {
605 ($beg, $end) = ($1, $max);
606 } elsif ($range =~ /\A([0-9]+)-([0-9]+)\z/) {
607 ($beg, $end) = ($1, $2);
611 $beg = $min if ($beg < $min);
612 $end = $max if ($end > $max);
613 $beg > $end ? "420 No article(s) selected\r\n" : [ \$beg, $end ];
616 sub long_response_done { $_[0]->write(\".\r\n") } # overrides superclass
618 sub hdr_msgid_range_i {
619 my ($self, $beg, $end) = @_;
620 my $r = $self->{ibx}->mm(1)->msg_range($beg, $end);
622 $self->msg_more(join('', map { "$_->[0] <$_->[1]>\r\n" } @$r));
626 sub hdr_message_id ($$$) { # optimize XHDR Message-ID [range] for slrnpull.
627 my ($self, $xhdr, $range) = @_;
629 if (defined $range && $range =~ $ONE_MSGID) {
630 my ($ibx, $n) = mid_lookup($self, $1);
631 return r430 unless $n;
632 hdr_mid_response($self, $xhdr, $ibx, $n, $range, $range);
633 } else { # numeric range
634 $range = $self->{article} unless defined $range;
635 my $r = get_range($self, $range);
636 return $r unless ref $r;
637 $self->msg_more($xhdr ? r221 : r225);
638 $self->long_response(\&hdr_msgid_range_i, @$r);
642 sub mid_lookup ($$) {
643 my ($self, $mid) = @_;
644 my $cur_ibx = $self->{ibx};
646 my $n = $cur_ibx->mm(1)->num_for($mid);
647 return ($cur_ibx, $n) if defined $n;
649 my $pi_cfg = $self->{nntpd}->{pi_cfg};
650 if (my $ALL = $pi_cfg->ALL) {
652 while (my $smsg = $ALL->over->next_by_mid($mid, \$id, \$prev)) {
653 my $xr3 = $ALL->over->get_xref3($smsg->{num});
654 if (my @x = grep(/:$smsg->{blob}\z/, @$xr3)) {
655 my ($ngname, $xnum) = split(/:/, $x[0]);
656 my $ibx = $pi_cfg->{-by_newsgroup}->{$ngname};
657 return ($ibx, $xnum) if $ibx;
658 # fall through to trying all xref3s
661 W: xref3 missing for <$mid> ($smsg->{blob}) in $ALL->{topdir}, -extindex bug?
666 my ($ngname, $xnum) = split(/:/, $x);
667 my $ibx = $pi_cfg->{-by_newsgroup}->{$ngname};
668 return ($ibx, $xnum) if $ibx;
669 warn "W: `$ngname' does not exist for #$xnum\n";
672 # no warning here, $mid is just invalid
673 } else { # slow path for non-ALL users
674 for my $ibx (values %{$pi_cfg->{-by_newsgroup}}) {
675 next if defined $cur_ibx && $ibx eq $cur_ibx;
676 my $n = $ibx->mm(1)->num_for($mid);
677 return ($ibx, $n) if defined $n;
684 my ($self, $beg, $end) = @_;
685 my $ibx = $self->{ibx};
686 my $msgs = $ibx->over(1)->query_xover($$beg, $end);
687 scalar(@$msgs) or return;
688 $$beg = $msgs->[-1]->{num} + 1;
689 $self->msg_more(join('', map {
690 "$_->{num} ".xref($self, $ibx, $_) . "\r\n";
695 sub hdr_xref ($$$) { # optimize XHDR Xref [range] for rtin
696 my ($self, $xhdr, $range) = @_;
698 if (defined $range && $range =~ $ONE_MSGID) {
700 my ($ibx, $n) = mid_lookup($self, $mid);
701 return r430 unless $n;
702 my $smsg = $ibx->over(1)->get_art($n) or return;
703 hdr_mid_response($self, $xhdr, $ibx, $n, $range,
704 xref($self, $ibx, $smsg));
705 } else { # numeric range
706 $range = $self->{article} unless defined $range;
707 my $r = get_range($self, $range);
708 return $r unless ref $r;
709 $self->msg_more($xhdr ? r221 : r225);
710 $self->long_response(\&xref_range_i, @$r);
714 sub over_header_for {
715 my ($ibx, $num, $field) = @_;
716 my $smsg = $ibx->over(1)->get_art($num) or return;
717 return PublicInbox::Smsg::date($smsg) if $field eq 'date';
722 my ($self, $beg, $end, $field) = @_;
723 my $msgs = $self->{ibx}->over(1)->query_xover($$beg, $end);
724 scalar(@$msgs) or return;
727 # ->{$field} is faster than ->$field invocations, so favor that.
728 if ($field eq 'date') {
730 $tmp .= "$s->{num} ".PublicInbox::Smsg::date($s)."\r\n"
734 $tmp .= "$s->{num} $s->{$field}\r\n";
738 $self->msg_more($tmp);
739 $$beg = $msgs->[-1]->{num} + 1;
742 sub hdr_smsg ($$$$) {
743 my ($self, $xhdr, $field, $range) = @_;
744 if (defined $range && $range =~ $ONE_MSGID) {
745 my ($ibx, $n) = mid_lookup($self, $1);
746 return r430 unless defined $n;
747 my $v = over_header_for($ibx, $n, $field);
748 hdr_mid_response($self, $xhdr, $ibx, $n, $range, $v);
749 } else { # numeric range
750 $range = $self->{article} unless defined $range;
751 my $r = get_range($self, $range);
752 return $r unless ref $r;
753 $self->msg_more($xhdr ? r221 : r225);
754 $self->long_response(\&smsg_range_i, @$r, $field);
759 my ($self, $xhdr, $header, $range) = @_;
760 my $sub = lc $header;
761 if ($sub eq 'message-id') {
762 hdr_message_id($self, $xhdr, $range);
763 } elsif ($sub eq 'xref') {
764 hdr_xref($self, $xhdr, $range);
765 } elsif ($sub =~ /\A(?:subject|references|date|from|to|cc|
767 hdr_smsg($self, $xhdr, $sub, $range);
768 } elsif ($sub =~ /\A:(bytes|lines)\z/) {
769 hdr_smsg($self, $xhdr, $1, $range);
771 $xhdr ? (r221.".\r\n") : "503 HDR not permitted on $header\r\n";
777 my ($self, $header, $range) = @_;
778 do_hdr($self, 0, $header, $range);
782 sub cmd_xhdr ($$;$) {
783 my ($self, $header, $range) = @_;
784 do_hdr($self, 1, $header, $range);
787 sub hdr_mid_prefix ($$$$$) {
788 my ($self, $xhdr, $ibx, $n, $mid) = @_;
789 return $mid if $xhdr;
791 # HDR for RFC 3977 users
792 if (my $cur_ibx = $self->{ibx}) {
793 ($cur_ibx eq $ibx) ? $n : '0';
799 sub hdr_mid_response ($$$$$$) {
800 my ($self, $xhdr, $ibx, $n, $mid, $v) = @_;
801 $self->write(($xhdr ? r221.$mid :
802 r225.hdr_mid_prefix($self, $xhdr, $ibx, $n, $mid)) .
808 my ($self, $beg, $end) = @_;
809 my $h = over_header_for($self->{ibx}, $$beg, 'references');
810 $self->msg_more("$$beg $h\r\n") if defined($h);
814 sub cmd_xrover ($;$) {
815 my ($self, $range) = @_;
816 my $ibx = $self->{ibx} or return \"412 no newsgroup selected\r\n";
817 (defined $range && $range =~ /[<>]/) and
818 return \"420 No article(s) selected\r\n"; # no message IDs
820 $range = $self->{article} unless defined $range;
821 my $r = get_range($self, $range);
822 return $r unless ref $r;
823 $self->msg_more("224 Overview information follows\r\n");
824 $self->long_response(\&xrover_i, @$r);
827 sub over_line ($$$) {
828 my ($self, $ibx, $smsg) = @_;
829 # n.b. field access and procedural calls can be
830 # 10%-15% faster than OO method calls:
831 my $s = join("\t", $smsg->{num},
834 PublicInbox::Smsg::date($smsg),
839 "Xref: " . xref($self, $ibx, $smsg));
845 my ($self, $range) = @_;
846 if ($range && $range =~ $ONE_MSGID) {
847 my ($ibx, $n) = mid_lookup($self, $1);
848 defined $n or return r430;
849 my $smsg = $ibx->over(1)->get_art($n) or return r430;
851 "224 Overview information follows (multi-line)\r\n");
853 # Only set article number column if it's the current group
855 my $cur_ibx = $self->{ibx};
856 if (!$cur_ibx || $cur_ibx ne $ibx) {
857 # set {-orig_num} for nntp_xref_for
858 $smsg->{-orig_num} = $smsg->{num};
861 over_line($self, $ibx, $smsg).".\r\n";
863 cmd_xover($self, $range);
868 my ($self, $beg, $end) = @_;
869 my $ibx = $self->{ibx};
870 my $msgs = $ibx->over(1)->query_xover($$beg, $end);
871 my $nr = scalar @$msgs or return;
874 $self->msg_more(join('', map {
875 over_line($self, $ibx, $_);
877 $$beg = $msgs->[-1]->{num} + 1;
880 sub cmd_xover ($;$) {
881 my ($self, $range) = @_;
882 $range = $self->{article} unless defined $range;
883 my $r = get_range($self, $range);
884 return $r unless ref $r;
885 my ($beg, $end) = @$r;
887 "224 Overview information follows for $$beg to $end\r\n");
888 $self->long_response(\&xover_i, @$r);
891 sub compressed { undef }
893 sub cmd_starttls ($) {
895 my $sock = $self->{sock} or return;
897 return r502 if ($sock->can('accept_SSL') || $self->compressed);
898 my $opt = $self->{nntpd}->{accept_tls} or
899 return \"580 can not initiate TLS negotiation\r\n";
900 $self->write(\"382 Continue with TLS negotiation\r\n");
901 $self->{sock} = IO::Socket::SSL->start_SSL($sock, %$opt);
902 $self->requeue if PublicInbox::DS::accept_tls_step($self);
907 sub cmd_compress ($$) {
908 my ($self, $alg) = @_;
909 return "503 Only DEFLATE is supported\r\n" if uc($alg) ne 'DEFLATE';
910 return r502 if $self->compressed;
911 PublicInbox::NNTPdeflate->enable($self);
917 my ($self, $mid) = @_;
918 return r501 unless $mid =~ $ONE_MSGID;
921 my $pi_cfg = $self->{nntpd}->{pi_cfg};
922 my $groups = $pi_cfg->{-by_newsgroup};
923 if (my $ALL = $pi_cfg->ALL) {
924 my ($id, $prev, %seen);
925 while (my $smsg = $ALL->over->next_by_mid($mid, \$id, \$prev)) {
926 my $xr3 = $ALL->over->get_xref3($smsg->{num});
928 my ($ngname, $n) = split(/:/, $x);
930 if ($groups->{$ngname} && !$seen{$x}++) {
935 } else { # slow path, no point in using long_response
936 for my $ibx (values %$groups) {
937 my $n = $ibx->mm(1)->num_for($mid) // next;
938 push @paths, "$ibx->{newsgroup}/$n";
941 return \"430 no such article on server\r\n" unless @paths;
942 '223 '.join(' ', sort(@paths))."\r\n";
946 my ($self, $fmt, @args) = @_;
947 printf { $self->{nntpd}->{err} } $fmt."\n", @args;
951 my ($self, $fmt, @args) = @_;
952 printf { $self->{nntpd}->{out} } $fmt."\n", @args;
955 # callback used by PublicInbox::DS for any (e)poll (in/out/hup/err)
959 return unless $self->flush_write && $self->{sock} && !$self->{long_cb};
961 # only read more requests if we've drained the write buffer,
962 # otherwise we can be buffering infinitely w/o backpressure
964 my $rbuf = $self->{rbuf} // \(my $x = '');
965 my $line = index($$rbuf, "\n");
967 return $self->close if length($$rbuf) >= LINE_MAX;
968 $self->do_read($rbuf, LINE_MAX, length($$rbuf)) or return;
969 $line = index($$rbuf, "\n");
971 $line = substr($$rbuf, 0, $line + 1, '');
972 $line =~ s/\r?\n\z//s;
973 return $self->close if $line =~ /[[:cntrl:]]/s;
976 my $fd = fileno($self->{sock});
977 my $r = eval { process_line($self, $line) };
978 my $pending = $self->{wbuf} ? ' pending' : '';
979 out($self, "[$fd] %s - %0.6f$pending", $line, now() - $t0);
980 return $self->close if $r < 0;
981 $self->rbuf_idle($rbuf);
983 # maybe there's more pipelined data, or we'll have
984 # to register it for socket-readiness notifications
985 $self->requeue unless $pending;
988 sub busy { # for graceful shutdown in PublicInbox::Daemon:
990 defined($self->{rbuf}) || defined($self->{wbuf})