1 # Copyright (C) 2015-2020 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
5 package PublicInbox::NNTP;
8 use base qw(PublicInbox::DS);
9 use fields qw(nntpd article ng long_cb);
10 use PublicInbox::MID qw(mid_escape $MID_EXTRACT);
12 use POSIX qw(strftime);
13 use PublicInbox::DS qw(now);
14 use Digest::SHA qw(sha1_hex);
15 use Time::Local qw(timegm timelocal);
17 LINE_MAX => 512, # RFC 977 section 2.3
18 r501 => '501 command syntax error',
19 r502 => '502 Command unavailable',
20 r221 => '221 Header follows',
21 r224 => '224 Overview information follows (multi-line)',
22 r225 => '225 Headers follow (multi-line)',
23 r430 => '430 No article with that message-id',
25 use PublicInbox::Syscall qw(EPOLLIN EPOLLONESHOT);
27 my $ONE_MSGID = qr/\A$MID_EXTRACT\z/;
28 my @OVERVIEW = qw(Subject From Date Message-ID References);
29 my $OVERVIEW_FMT = join(":\r\n", @OVERVIEW, qw(Bytes Lines), '') .
31 my $LIST_HEADERS = join("\r\n", @OVERVIEW,
32 qw(:bytes :lines Xref To Cc)) . "\r\n";
33 my $CAPABILITIES = <<"";
34 101 Capability list:\r
38 LIST ACTIVE ACTIVE.TIMES NEWSGROUPS OVERVIEW.FMT\r
43 sub greet ($) { $_[0]->write($_[0]->{nntpd}->{greet}) };
46 my ($class, $sock, $nntpd) = @_;
47 my $self = fields::new($class);
50 if (ref($sock) eq 'IO::Socket::SSL' && !$sock->accept_SSL) {
51 return CORE::close($sock) if $! != EAGAIN;
52 $ev = PublicInbox::TLS::epollbit();
53 $wbuf = [ \&PublicInbox::DS::accept_tls_step, \&greet ];
55 $self->SUPER::new($sock, $ev | EPOLLONESHOT);
56 $self->{nntpd} = $nntpd;
58 $self->{wbuf} = $wbuf;
62 $self->update_idle_time;
68 my $tot = prototype $cb;
69 my ($nreq, undef) = split(';', $tot);
70 $nreq = ($nreq =~ tr/$//) - 1;
71 $tot = ($tot =~ tr/$//) - 1;
72 ($argc <= $tot && $argc >= $nreq);
75 # returns 1 if we can continue, 0 if not due to buffered writes or disconnect
76 sub process_line ($$) {
78 my ($req, @args) = split(/[ \t]+/, $l);
79 return 1 unless defined($req); # skip blank line
80 $req = $self->can('cmd_'.lc($req));
81 return res($self, '500 command not recognized') unless $req;
82 return res($self, r501) unless args_ok($req, scalar @args);
84 my $res = eval { $req->($self, @args) };
86 if ($err && $self->{sock}) {
89 err($self, 'error from: %s (%s)', $l, $err);
90 $res = '503 program fault - command not performed';
92 return 0 unless defined $res;
96 # The keyword argument is not used (rfc3977 5.2.2)
97 sub cmd_capabilities ($;$) {
98 my ($self, undef) = @_;
99 my $res = $CAPABILITIES;
100 if (ref($self->{sock}) ne 'IO::Socket::SSL' &&
101 $self->{nntpd}->{accept_tls}) {
102 $res .= "STARTTLS\r\n";
108 my ($self, $arg) = @_;
110 return r501 unless $arg eq 'READER';
111 '201 Posting prohibited';
114 sub cmd_slave ($) { '202 slave status noted' }
116 sub cmd_xgtitle ($;$) {
117 my ($self, $wildmat) = @_;
118 more($self, '282 list of groups and descriptions follows');
119 list_newsgroups($self, $wildmat);
123 sub list_overview_fmt ($) {
125 $self->msg_more($OVERVIEW_FMT);
128 sub list_headers ($;$) {
130 $self->msg_more($LIST_HEADERS);
133 sub list_active ($;$) {
134 my ($self, $wildmat) = @_;
135 wildmat2re($wildmat);
136 foreach my $ng (@{$self->{nntpd}->{grouplist}}) {
137 $ng->{newsgroup} =~ $wildmat or next;
138 group_line($self, $ng);
142 sub list_active_times ($;$) {
143 my ($self, $wildmat) = @_;
144 wildmat2re($wildmat);
145 foreach my $ng (@{$self->{nntpd}->{grouplist}}) {
146 $ng->{newsgroup} =~ $wildmat or next;
147 my $c = eval { $ng->mm->created_at } || time;
148 more($self, "$ng->{newsgroup} $c $ng->{-primary_address}");
152 sub list_newsgroups ($;$) {
153 my ($self, $wildmat) = @_;
154 wildmat2re($wildmat);
155 foreach my $ng (@{$self->{nntpd}->{grouplist}}) {
156 $ng->{newsgroup} =~ $wildmat or next;
157 my $d = $ng->description;
158 more($self, "$ng->{newsgroup} $d");
162 # LIST SUBSCRIPTIONS, DISTRIB.PATS are not supported
163 sub cmd_list ($;$$) {
164 my ($self, @args) = @_;
166 my $arg = shift @args;
167 $arg =~ tr/A-Z./a-z_/;
169 $arg = $self->can($arg);
170 return r501 unless $arg && args_ok($arg, scalar @args);
171 more($self, '215 information follows');
172 $arg->($self, @args);
174 more($self, '215 list of newsgroups follows');
175 foreach my $ng (@{$self->{nntpd}->{grouplist}}) {
176 group_line($self, $ng);
182 sub listgroup_range_i {
183 my ($self, $beg, $end) = @_;
184 my $r = $self->{ng}->mm->msg_range($beg, $end, 'num');
185 scalar(@$r) or return;
186 more($self, join("\r\n", map { $_->[0] } @$r));
190 sub listgroup_all_i {
191 my ($self, $num) = @_;
192 my $ary = $self->{ng}->mm->ids_after($num);
193 scalar(@$ary) or return;
194 more($self, join("\r\n", @$ary));
198 sub cmd_listgroup ($;$$) {
199 my ($self, $group, $range) = @_;
200 if (defined $group) {
201 my $res = cmd_group($self, $group);
202 return $res if ($res !~ /\A211 /);
205 $self->{ng} or return '412 no newsgroup selected';
206 if (defined $range) {
207 my $r = get_range($self, $range);
208 return $r unless ref $r;
209 long_response($self, \&listgroup_range_i, @$r);
210 } else { # grab every article number
211 long_response($self, \&listgroup_all_i, \(my $num = 0));
215 sub parse_time ($$;$) {
216 my ($date, $time, $gmt) = @_;
217 my ($hh, $mm, $ss) = unpack('A2A2A2', $time);
219 $gmt =~ /\A(?:UTC|GMT)\z/i or die "GM invalid: $gmt";
222 my ($YYYY, $MM, $DD);
223 if (bytes::length($date) == 8) { # RFC 3977 allows YYYYMMDD
224 ($YYYY, $MM, $DD) = unpack('A4A2A2', $date);
225 } else { # legacy clients send YYMMDD
227 ($YY, $MM, $DD) = unpack('A2A2A2', $date);
228 my @now = $gmt ? gmtime : localtime;
229 my $cur_year = $now[5] + 1900;
230 my $cur_cent = int($cur_year / 100) * 100;
231 $YYYY = (($YY + $cur_cent) > $cur_year) ?
232 ($YY + 1900) : ($YY + $cur_cent);
235 timegm($ss, $mm, $hh, $DD, $MM - 1, $YYYY);
237 timelocal($ss, $mm, $hh, $DD, $MM - 1, $YYYY);
241 sub group_line ($$) {
242 my ($self, $ng) = @_;
243 my ($min, $max) = $ng->mm->minmax;
244 more($self, "$ng->{newsgroup} $max $min n") if defined $min && defined $max;
247 sub cmd_newgroups ($$$;$$) {
248 my ($self, $date, $time, $gmt, $dists) = @_;
249 my $ts = eval { parse_time($date, $time, $gmt) };
253 more($self, '231 list of new newsgroups follows');
254 foreach my $ng (@{$self->{nntpd}->{grouplist}}) {
255 my $c = eval { $ng->mm->created_at } || 0;
256 next unless $c > $ts;
257 group_line($self, $ng);
262 sub wildmat2re (;$) {
263 return $_[0] = qr/.*/ if (!defined $_[0] || $_[0] eq '*');
268 $tmp =~ s#(?<!\\)\[(.+)(?<!\\)\]#
270 my $key = sha1_hex($orig . $salt);
271 $orig =~ s/([^\w\-])+/\Q$1/g;
275 my %map = ('*' => '.*', '?' => '.' );
276 $tmp =~ s#(?<!\\)([^\w\\])#$map{$1} || "\Q$1"#ge;
278 $tmp =~ s#([a-f0-9]{40})#
279 my $orig = $keep{$1};
280 defined $orig ? $orig : $1;
283 $_[0] = qr/\A$tmp\z/;
287 return $_[0] = qr/\A\z/ unless defined $_[0];
288 my %map = ('*' => '.*', ',' => '|');
289 $_[0] =~ s!(.)!$map{$1} || "\Q$1"!ge;
290 $_[0] = qr/\A(?:$_[0])\z/;
294 my ($self, $overs, $ts, $prev) = @_;
295 my $over = $overs->[0];
296 my $msgs = $over->query_ts($ts, $$prev);
299 join(">\r\n<", map { $_->mid } @$msgs ).
301 $$prev = $msgs->[-1]->{num};
304 if (@$overs) { # continue onto next newsgroup
307 } else { # break out of the long response.
313 sub cmd_newnews ($$$$;$$) {
314 my ($self, $newsgroups, $date, $time, $gmt, $dists) = @_;
315 my $ts = eval { parse_time($date, $time, $gmt) };
317 more($self, '230 list of new articles by message-id follows');
318 my ($keep, $skip) = split('!', $newsgroups, 2);
322 foreach my $ng (@{$self->{nntpd}->{grouplist}}) {
323 $ng->{newsgroup} =~ $keep or next;
324 $ng->{newsgroup} =~ $skip and next;
325 my $over = $ng->over or next;
328 return '.' unless @overs;
331 long_response($self, \&newnews_i, \@overs, $ts, \$prev);
335 my ($self, $group) = @_;
336 my $no_such = '411 no such news group';
337 my $ng = $self->{nntpd}->{groups}->{$group} or return $no_such;
340 my ($min, $max) = $ng->mm->minmax;
343 $self->{article} = $min;
344 my $est_size = $max - $min;
345 "211 $est_size $min $max $group";
348 sub article_adj ($$) {
349 my ($self, $off) = @_;
350 my $ng = $self->{ng} or return '412 no newsgroup selected';
352 my $n = $self->{article};
353 defined $n or return '420 no current article has been selected';
356 my $mid = $ng->mm->mid_for($n);
358 $n = $off > 0 ? 'next' : 'previous';
359 return "421 no $n article in this group";
361 $self->{article} = $n;
362 "223 $n <$mid> article retrieved - request text separately";
365 sub cmd_next ($) { article_adj($_[0], 1) }
366 sub cmd_last ($) { article_adj($_[0], -1) }
368 # We want to encourage using email and CC-ing everybody involved to avoid
369 # the single-point-of-failure a single server provides.
372 my $ng = $self->{ng};
373 $ng ? "440 mailto:$ng->{-primary_address} to post"
374 : '440 posting not allowed'
379 res($self, '205 closing connection - goodbye!');
384 sub header_append ($$$) {
385 my ($hdr, $k, $v) = @_;
386 my @v = $hdr->header($k);
390 $hdr->header_set($k, @v, $v);
394 my ($self, $ng, $n, $mid) = @_;
395 my $ret = $self->{nntpd}->{servername} . " $ng->{newsgroup}:$n";
397 # num_for is pretty cheap and sometimes we'll lookup the existence
398 # of an article without getting even the OVER info. In other words,
399 # I'm not sure if its worth optimizing by scanning To:/Cc: and
400 # PublicInbox::ExtMsg on the PSGI end is just as expensive
401 foreach my $other (@{$self->{nntpd}->{grouplist}}) {
402 next if $ng eq $other;
403 my $num = eval { $other->mm->num_for($mid) } or next;
404 $ret .= " $other->{newsgroup}:$num";
409 sub set_nntp_headers ($$$$$) {
410 my ($self, $hdr, $ng, $n, $mid) = @_;
412 # why? leafnode requires a Path: header for some inexplicable
413 # reason. We'll fake the shortest one possible.
414 $hdr->header_set('Path', 'y');
416 # leafnode (and maybe other NNTP clients) have trouble dealing
417 # with v2 messages which have multiple Message-IDs (either due
418 # to our own content-based dedupe or buggy git-send-email versions).
419 my @mids = $hdr->header('Message-ID');
420 if (scalar(@mids) > 1) {
422 $hdr->header_set('Message-ID', $mid0);
423 my @alt = $hdr->header('X-Alt-Message-ID');
424 my %seen = map { $_ => 1 } (@alt, $mid0);
425 push(@alt, grep { !$seen{$_}++ } @mids);
426 $hdr->header_set('X-Alt-Message-ID', @alt);
430 my $xref = xref($self, $ng, $n, $mid);
431 $hdr->header_set('Xref', $xref);
432 $xref =~ s/:[0-9]+//g;
433 $hdr->header_set('Newsgroups', (split(/ /, $xref, 2))[1]);
434 header_append($hdr, 'List-Post', "<mailto:$ng->{-primary_address}>");
435 if (my $url = $ng->base_url) {
436 $mid = mid_escape($mid);
437 header_append($hdr, 'Archived-At', "<$url$mid/>");
438 header_append($hdr, 'List-Archive', "<$url>");
442 sub art_lookup ($$$) {
443 my ($self, $art, $set_headers) = @_;
444 my $ng = $self->{ng};
448 if ($art =~ /\A[0-9]+\z/) {
449 $err = '423 no such article number in this group';
452 } elsif ($art =~ $ONE_MSGID) {
455 $n = $ng->mm->num_for($mid) if $ng;
456 goto found if defined $n;
457 foreach my $g (values %{$self->{nntpd}->{groups}}) {
458 $n = $g->mm->num_for($mid);
469 $err = '420 no current article has been selected';
470 $n = $self->{article};
471 defined $n or return $err;
473 $ng or return '412 no newsgroup has been selected';
474 $mid = $ng->mm->mid_for($n);
475 defined $mid or return $err;
478 my $smsg = $ng->over->get_art($n) or return $err;
479 my $msg = $ng->msg_by_smsg($smsg) or return $err;
481 # Email::Simple->new will modify $msg in-place as documented
482 # in its manpage, so what's left is the body and we won't need
483 # to call Email::Simple::body(), later
484 my $hdr = Email::Simple->new($msg)->header_obj;
485 set_nntp_headers($self, $hdr, $ng, $n, $mid) if $set_headers;
486 [ $n, $mid, $msg, $hdr ];
489 sub msg_body_write ($$) {
490 my ($self, $msg) = @_;
492 # these can momentarily double the memory consumption :<
493 $$msg =~ s/^\./../smg;
494 $$msg =~ s/(?<!\r)\n/\r\n/sg; # Alpine barfs without this
495 $$msg .= "\r\n" unless $$msg =~ /\r\n\z/s;
496 $self->msg_more($$msg);
501 my ($self, $art) = @_;
502 $self->{article} = $art if defined $art && $art =~ /\A[0-9]+\z/;
505 sub msg_hdr_write ($$$) {
506 my ($self, $hdr, $body_follows) = @_;
507 $hdr = $hdr->as_string;
508 # fixup old bug from import (pre-a0c07cba0e5d8b6a)
509 $hdr =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
511 $hdr =~ s/(?<!\r)\n/\r\n/sg; # Alpine barfs without this
513 # for leafnode compatibility, we need to ensure Message-ID headers
514 # are only a single line. We can't subclass Email::Simple::Header
515 # and override _default_fold_at in here, either; since that won't
516 # affect messages already in the archive.
517 $hdr =~ s/^(Message-ID:)[ \t]*\r\n[ \t]+([^\r]+)\r\n/$1 $2\r\n/igsm;
518 $hdr .= "\r\n" if $body_follows;
519 $self->msg_more($hdr);
522 sub cmd_article ($;$) {
523 my ($self, $art) = @_;
524 my $r = art_lookup($self, $art, 1);
525 return $r unless ref $r;
526 my ($n, $mid, $msg, $hdr) = @$r;
527 set_art($self, $art);
528 more($self, "220 $n <$mid> article retrieved - head and body follow");
529 msg_hdr_write($self, $hdr, 1);
530 msg_body_write($self, $msg);
534 my ($self, $art) = @_;
535 my $r = art_lookup($self, $art, 2);
536 return $r unless ref $r;
537 my ($n, $mid, undef, $hdr) = @$r;
538 set_art($self, $art);
539 more($self, "221 $n <$mid> article retrieved - head follows");
540 msg_hdr_write($self, $hdr, 0);
545 my ($self, $art) = @_;
546 my $r = art_lookup($self, $art, 0);
547 return $r unless ref $r;
548 my ($n, $mid, $msg) = @$r;
549 set_art($self, $art);
550 more($self, "222 $n <$mid> article retrieved - body follows");
551 msg_body_write($self, $msg);
555 my ($self, $art) = @_;
556 my $r = art_lookup($self, $art, 0);
557 return $r unless ref $r;
559 set_art($self, $art);
560 "223 $n <$mid> article retrieved - request text separately";
563 sub cmd_ihave ($) { '435 article not wanted - do not send it' }
565 sub cmd_date ($) { '111 '.strftime('%Y%m%d%H%M%S', gmtime(time)) }
569 more($self, '100 help text follows');
574 my ($self, $range) = @_;
575 my $ng = $self->{ng} or return '412 no news group has been selected';
576 defined $range or return '420 No article(s) selected';
578 my ($min, $max) = $ng->mm->minmax;
579 if ($range =~ /\A([0-9]+)\z/) {
581 } elsif ($range =~ /\A([0-9]+)-\z/) {
582 ($beg, $end) = ($1, $max);
583 } elsif ($range =~ /\A([0-9]+)-([0-9]+)\z/) {
584 ($beg, $end) = ($1, $2);
588 $beg = $min if ($beg < $min);
589 $end = $max if ($end > $max);
590 return '420 No article(s) selected' if ($beg > $end);
596 # wbuf is unset or empty, here; {long} may add to it
597 my ($fd, $cb, $t0, @args) = @{$self->{long_cb}};
598 my $more = eval { $cb->($self, @args) };
599 if ($@ || !$self->{sock}) { # something bad happened...
600 delete $self->{long_cb};
601 my $elapsed = now() - $t0;
604 "%s during long response[$fd] - %0.6f",
607 out($self, " deferred[$fd] aborted - %0.6f", $elapsed);
609 } elsif ($more) { # $self->{wbuf}:
610 $self->update_idle_time;
612 # COMPRESS users all share the same DEFLATE context.
613 # Flush it here to ensure clients don't see
617 # no recursion, schedule another call ASAP, but only after
618 # all pending writes are done. autovivify wbuf:
619 my $new_size = push(@{$self->{wbuf}}, \&long_step);
621 # wbuf may be populated by $cb, no need to rearm if so:
622 $self->requeue if $new_size == 1;
624 delete $self->{long_cb};
626 my $elapsed = now() - $t0;
627 my $fd = fileno($self->{sock});
628 out($self, " deferred[$fd] done - %0.6f", $elapsed);
629 my $wbuf = $self->{wbuf}; # do NOT autovivify
630 $self->requeue unless $wbuf && @$wbuf;
634 sub long_response ($$;@) {
635 my ($self, $cb, @args) = @_; # cb returns true if more, false if done
637 my $sock = $self->{sock} or return;
638 # make sure we disable reading during a long response,
639 # clients should not be sending us stuff and making us do more
640 # work while we are stream a response to them
641 $self->{long_cb} = [ fileno($sock), $cb, now(), @args ];
642 long_step($self); # kick off!
646 sub hdr_msgid_range_i {
647 my ($self, $beg, $end) = @_;
648 my $r = $self->{ng}->mm->msg_range($beg, $end);
650 more($self, join("\r\n", map { "$_->[0] <$_->[1]>" } @$r));
654 sub hdr_message_id ($$$) { # optimize XHDR Message-ID [range] for slrnpull.
655 my ($self, $xhdr, $range) = @_;
657 if (defined $range && $range =~ $ONE_MSGID) {
658 my ($ng, $n) = mid_lookup($self, $1);
659 return r430 unless $n;
660 hdr_mid_response($self, $xhdr, $ng, $n, $range, $range);
661 } else { # numeric range
662 $range = $self->{article} unless defined $range;
663 my $r = get_range($self, $range);
664 return $r unless ref $r;
665 more($self, $xhdr ? r221 : r225);
666 long_response($self, \&hdr_msgid_range_i, @$r);
670 sub mid_lookup ($$) {
671 my ($self, $mid) = @_;
672 my $self_ng = $self->{ng};
674 my $n = $self_ng->mm->num_for($mid);
675 return ($self_ng, $n) if defined $n;
677 foreach my $ng (values %{$self->{nntpd}->{groups}}) {
678 next if defined $self_ng && $ng eq $self_ng;
679 my $n = $ng->mm->num_for($mid);
680 return ($ng, $n) if defined $n;
686 my ($self, $beg, $end) = @_;
687 my $ng = $self->{ng};
688 my $r = $ng->mm->msg_range($beg, $end);
690 more($self, join("\r\n", map {
692 "$num ".xref($self, $ng, $num, $_->[1]);
697 sub hdr_xref ($$$) { # optimize XHDR Xref [range] for rtin
698 my ($self, $xhdr, $range) = @_;
700 if (defined $range && $range =~ $ONE_MSGID) {
702 my ($ng, $n) = mid_lookup($self, $mid);
703 return r430 unless $n;
704 hdr_mid_response($self, $xhdr, $ng, $n, $range,
705 xref($self, $ng, $n, $mid));
706 } else { # numeric range
707 $range = $self->{article} unless defined $range;
708 my $r = get_range($self, $range);
709 return $r unless ref $r;
710 more($self, $xhdr ? r221 : r225);
711 long_response($self, \&xref_range_i, @$r);
715 sub over_header_for {
716 my ($over, $num, $field) = @_;
717 my $smsg = $over->get_art($num) or return;
718 return PublicInbox::Smsg::date($smsg) if $field eq 'date';
723 my ($self, $beg, $end, $field) = @_;
724 my $over = $self->{ng}->over;
725 my $msgs = $over->query_xover($$beg, $end);
726 scalar(@$msgs) or return;
728 foreach my $s (@$msgs) {
729 $tmp .= $s->{num} . ' ' . $s->$field . "\r\n";
732 $self->msg_more($tmp);
733 $$beg = $msgs->[-1]->{num} + 1;
736 sub hdr_smsg ($$$$) {
737 my ($self, $xhdr, $field, $range) = @_;
738 if (defined $range && $range =~ $ONE_MSGID) {
739 my ($ng, $n) = mid_lookup($self, $1);
740 return r430 unless defined $n;
741 my $v = over_header_for($ng->over, $n, $field);
742 hdr_mid_response($self, $xhdr, $ng, $n, $range, $v);
743 } else { # numeric range
744 $range = $self->{article} unless defined $range;
745 my $r = get_range($self, $range);
746 return $r unless ref $r;
747 more($self, $xhdr ? r221 : r225);
748 long_response($self, \&smsg_range_i, @$r, $field);
753 my ($self, $xhdr, $header, $range) = @_;
754 my $sub = lc $header;
755 if ($sub eq 'message-id') {
756 hdr_message_id($self, $xhdr, $range);
757 } elsif ($sub eq 'xref') {
758 hdr_xref($self, $xhdr, $range);
759 } elsif ($sub =~ /\A(?:subject|references|date|from|to|cc|
761 hdr_smsg($self, $xhdr, $sub, $range);
762 } elsif ($sub =~ /\A:(bytes|lines)\z/) {
763 hdr_smsg($self, $xhdr, $1, $range);
765 $xhdr ? (r221 . "\r\n.") : "503 HDR not permitted on $header";
771 my ($self, $header, $range) = @_;
772 do_hdr($self, 0, $header, $range);
776 sub cmd_xhdr ($$;$) {
777 my ($self, $header, $range) = @_;
778 do_hdr($self, 1, $header, $range);
781 sub hdr_mid_prefix ($$$$$) {
782 my ($self, $xhdr, $ng, $n, $mid) = @_;
783 return $mid if $xhdr;
785 # HDR for RFC 3977 users
786 if (my $self_ng = $self->{ng}) {
787 ($self_ng eq $ng) ? $n : '0';
793 sub hdr_mid_response ($$$$$$) {
794 my ($self, $xhdr, $ng, $n, $mid, $v) = @_;
797 $res .= r221 . "\r\n";
798 $res .= "$mid $v\r\n";
800 $res .= r225 . "\r\n";
801 my $pfx = hdr_mid_prefix($self, $xhdr, $ng, $n, $mid);
802 $res .= "$pfx $v\r\n";
804 res($self, $res .= '.');
809 my ($self, $beg, $end) = @_;
810 my $h = over_header_for($self->{ng}->over, $$beg, 'references');
811 more($self, "$$beg $h") if defined($h);
815 sub cmd_xrover ($;$) {
816 my ($self, $range) = @_;
817 my $ng = $self->{ng} or return '412 no newsgroup selected';
818 (defined $range && $range =~ /[<>]/) and
819 return '420 No article(s) selected'; # no message IDs
821 $range = $self->{article} unless defined $range;
822 my $r = get_range($self, $range);
823 return $r unless ref $r;
824 more($self, '224 Overview information follows');
825 long_response($self, \&xrover_i, @$r);
828 sub over_line ($$$$) {
829 my ($self, $ng, $num, $smsg) = @_;
830 # n.b. field access and procedural calls can be
831 # 10%-15% faster than OO method calls:
832 my $s = join("\t", $num,
835 PublicInbox::Smsg::date($smsg),
840 "Xref: " . xref($self, $ng, $num, $smsg->{mid}));
846 my ($self, $range) = @_;
847 if ($range && $range =~ $ONE_MSGID) {
848 my ($ng, $n) = mid_lookup($self, $1);
849 defined $n or return r430;
850 my $smsg = $ng->over->get_art($n) or return r430;
851 more($self, '224 Overview information follows (multi-line)');
853 # Only set article number column if it's the current group
854 my $self_ng = $self->{ng};
855 $n = 0 if (!$self_ng || $self_ng ne $ng);
856 more($self, over_line($self, $ng, $n, $smsg));
859 cmd_xover($self, $range);
864 my ($self, $beg, $end) = @_;
865 my $ng = $self->{ng};
866 my $msgs = $ng->over->query_xover($$beg, $end);
867 my $nr = scalar @$msgs or return;
870 more($self, join("\r\n", map {
871 over_line($self, $ng, $_->{num}, $_);
873 $$beg = $msgs->[-1]->{num} + 1;
876 sub cmd_xover ($;$) {
877 my ($self, $range) = @_;
878 $range = $self->{article} unless defined $range;
879 my $r = get_range($self, $range);
880 return $r unless ref $r;
881 my ($beg, $end) = @$r;
882 more($self, "224 Overview information follows for $$beg to $end");
883 long_response($self, \&xover_i, @$r);
886 sub compressed { undef }
888 sub cmd_starttls ($) {
890 my $sock = $self->{sock} or return;
892 return r502 if (ref($sock) eq 'IO::Socket::SSL' || $self->compressed);
893 my $opt = $self->{nntpd}->{accept_tls} or
894 return '580 can not initiate TLS negotiation';
895 res($self, '382 Continue with TLS negotiation');
896 $self->{sock} = IO::Socket::SSL->start_SSL($sock, %$opt);
897 $self->requeue if PublicInbox::DS::accept_tls_step($self);
902 sub cmd_compress ($$) {
903 my ($self, $alg) = @_;
904 return '503 Only DEFLATE is supported' if uc($alg) ne 'DEFLATE';
905 return r502 if $self->compressed;
906 PublicInbox::NNTPdeflate->enable($self);
911 sub zflush {} # overridden by NNTPdeflate
914 my ($self, $mid) = @_;
915 return r501 unless $mid =~ $ONE_MSGID;
918 foreach my $ng (values %{$self->{nntpd}->{groups}}) {
919 my $n = $ng->mm->num_for($mid);
920 push @paths, "$ng->{newsgroup}/$n" if defined $n;
922 return '430 no such article on server' unless @paths;
923 '223 '.join(' ', @paths);
926 sub res ($$) { do_write($_[0], $_[1] . "\r\n") }
928 sub more ($$) { $_[0]->msg_more($_[1] . "\r\n") }
932 my $done = $self->write(\($_[1]));
933 return 0 unless $self->{sock};
939 my ($self, $fmt, @args) = @_;
940 printf { $self->{nntpd}->{err} } $fmt."\n", @args;
944 my ($self, $fmt, @args) = @_;
945 printf { $self->{nntpd}->{out} } $fmt."\n", @args;
948 # callback used by PublicInbox::DS for any (e)poll (in/out/hup/err)
952 return unless $self->flush_write && $self->{sock};
954 $self->update_idle_time;
955 # only read more requests if we've drained the write buffer,
956 # otherwise we can be buffering infinitely w/o backpressure
958 my $rbuf = $self->{rbuf} // (\(my $x = ''));
961 if (index($$rbuf, "\n") < 0) {
962 my $off = bytes::length($$rbuf);
963 $r = $self->do_read($rbuf, LINE_MAX, $off) or return;
965 while ($r > 0 && $$rbuf =~ s/\A[ \t]*([^\n]*?)\r?\n//) {
967 return $self->close if $line =~ /[[:cntrl:]]/s;
969 my $fd = fileno($self->{sock});
970 $r = eval { process_line($self, $line) };
971 my $pending = $self->{wbuf} ? ' pending' : '';
972 out($self, "[$fd] %s - %0.6f$pending", $line, now() - $t0);
975 return $self->close if $r < 0;
976 my $len = bytes::length($$rbuf);
977 return $self->close if ($len >= LINE_MAX);
978 $self->rbuf_idle($rbuf);
979 $self->update_idle_time;
981 # maybe there's more pipelined data, or we'll have
982 # to register it for socket-readiness notifications
983 $self->requeue unless $self->{wbuf};
986 # for graceful shutdown in PublicInbox::Daemon:
988 my ($self, $now) = @_;
989 ($self->{rbuf} || $self->{wbuf} || $self->not_idle_long($now));