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
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;
12 use parent qw(PublicInbox::DS);
13 use PublicInbox::MID qw(mid_escape $MID_EXTRACT);
15 use POSIX qw(strftime);
16 use PublicInbox::DS qw(now);
17 use Digest::SHA qw(sha1_hex);
18 use Time::Local qw(timegm timelocal);
19 use PublicInbox::GitAsyncCat;
20 use PublicInbox::Address;
23 LINE_MAX => 512, # RFC 977 section 2.3
24 r501 => '501 command syntax error',
25 r502 => '502 Command unavailable',
26 r221 => '221 Header follows',
27 r224 => '224 Overview information follows (multi-line)',
28 r225 => '225 Headers follow (multi-line)',
29 r430 => '430 No article with that message-id',
31 use PublicInbox::Syscall qw(EPOLLIN EPOLLONESHOT);
33 my $ONE_MSGID = qr/\A$MID_EXTRACT\z/;
34 my @OVERVIEW = qw(Subject From Date Message-ID References);
35 my $OVERVIEW_FMT = join(":\r\n", @OVERVIEW, qw(Bytes Lines), '') .
37 my $LIST_HEADERS = join("\r\n", @OVERVIEW,
38 qw(:bytes :lines Xref To Cc)) . "\r\n.";
39 my $CAPABILITIES = <<"";
40 101 Capability list:\r
44 LIST ACTIVE ACTIVE.TIMES NEWSGROUPS OVERVIEW.FMT\r
49 sub greet ($) { $_[0]->write($_[0]->{nntpd}->{greet}) };
52 my ($class, $sock, $nntpd) = @_;
53 my $self = bless { nntpd => $nntpd }, $class;
56 if ($sock->can('accept_SSL') && !$sock->accept_SSL) {
57 return CORE::close($sock) if $! != EAGAIN;
58 $ev = PublicInbox::TLS::epollbit() or return CORE::close($sock);
59 $wbuf = [ \&PublicInbox::DS::accept_tls_step, \&greet ];
61 $self->SUPER::new($sock, $ev | EPOLLONESHOT);
63 $self->{wbuf} = $wbuf;
67 $self->update_idle_time;
73 my $tot = prototype $cb;
74 my ($nreq, undef) = split(';', $tot);
75 $nreq = ($nreq =~ tr/$//) - 1;
76 $tot = ($tot =~ tr/$//) - 1;
77 ($argc <= $tot && $argc >= $nreq);
80 # returns 1 if we can continue, 0 if not due to buffered writes or disconnect
81 sub process_line ($$) {
83 my ($req, @args) = split(/[ \t]+/, $l);
84 return 1 unless defined($req); # skip blank line
85 $req = $self->can('cmd_'.lc($req));
86 return res($self, '500 command not recognized') unless $req;
87 return res($self, r501) unless args_ok($req, scalar @args);
89 my $res = eval { $req->($self, @args) };
91 if ($err && $self->{sock}) {
94 err($self, 'error from: %s (%s)', $l, $err);
95 $res = '503 program fault - command not performed';
97 defined($res) ? res($self, $res) : 0;
100 # The keyword argument is not used (rfc3977 5.2.2)
101 sub cmd_capabilities ($;$) {
102 my ($self, undef) = @_;
103 my $res = $CAPABILITIES;
104 if (!$self->{sock}->can('accept_SSL') &&
105 $self->{nntpd}->{accept_tls}) {
106 $res .= "STARTTLS\r\n";
112 my ($self, $arg) = @_;
113 uc($arg) eq 'READER' ? '201 Posting prohibited' : r501;
116 sub cmd_slave ($) { '202 slave status noted' }
118 sub cmd_xgtitle ($;$) {
119 my ($self, $wildmat) = @_;
120 more($self, '282 list of groups and descriptions follows');
121 list_newsgroups($self, $wildmat);
124 sub list_overview_fmt ($) { $OVERVIEW_FMT }
126 sub list_headers ($;$) { $LIST_HEADERS }
128 sub list_active_i { # "LIST ACTIVE" and also just "LIST" (no args)
129 my ($self, $groupnames) = @_;
130 my @window = splice(@$groupnames, 0, 100) or return 0;
132 my $groups = $self->{nntpd}->{pi_cfg}->{-by_newsgroup};
133 for my $ngname (@window) {
134 $ibx = $groups->{$ngname} and group_line($self, $ibx);
136 scalar(@$groupnames); # continue if there's more
139 sub list_active ($;$) { # called by cmd_list
140 my ($self, $wildmat) = @_;
141 wildmat2re($wildmat);
142 long_response($self, \&list_active_i, [
143 grep(/$wildmat/, @{$self->{nntpd}->{groupnames}}) ]);
146 sub list_active_times_i {
147 my ($self, $groupnames) = @_;
148 my @window = splice(@$groupnames, 0, 100) or return 0;
149 my $groups = $self->{nntpd}->{pi_cfg}->{-by_newsgroup};
150 for my $ngname (@window) {
151 my $ibx = $groups->{$ngname} or next;
152 my $c = eval { $ibx->uidvalidity } // time;
153 more($self, "$ngname $c <$ibx->{-primary_address}>");
155 scalar(@$groupnames); # continue if there's more
158 sub list_active_times ($;$) { # called by cmd_list
159 my ($self, $wildmat) = @_;
160 wildmat2re($wildmat);
161 long_response($self, \&list_active_times_i, [
162 grep(/$wildmat/, @{$self->{nntpd}->{groupnames}}) ]);
165 sub list_newsgroups_i {
166 my ($self, $groupnames) = @_;
167 my @window = splice(@$groupnames, 0, 100) or return 0;
168 my $groups = $self->{nntpd}->{pi_cfg}->{-by_newsgroup};
170 for my $ngname (@window) {
171 $ibx = $groups->{$ngname} and
172 more($self, "$ngname ".$ibx->description);
174 scalar(@$groupnames); # continue if there's more
177 sub list_newsgroups ($;$) { # called by cmd_list
178 my ($self, $wildmat) = @_;
179 wildmat2re($wildmat);
180 long_response($self, \&list_newsgroups_i, [
181 grep(/$wildmat/, @{$self->{nntpd}->{groupnames}}) ]);
184 # LIST SUBSCRIPTIONS, DISTRIB.PATS are not supported
185 sub cmd_list ($;$$) {
186 my ($self, @args) = @_;
188 my $arg = shift @args;
189 $arg =~ tr/A-Z./a-z_/;
190 my $ret = $arg eq 'active';
192 $arg = $self->can($arg);
193 return r501 unless $arg && args_ok($arg, scalar @args);
194 more($self, '215 information follows');
195 $arg->($self, @args);
197 more($self, '215 list of newsgroups follows');
198 long_response($self, \&list_active_i, [ # copy array
199 @{$self->{nntpd}->{groupnames}} ]);
203 sub listgroup_range_i {
204 my ($self, $beg, $end) = @_;
205 my $r = $self->{ibx}->mm->msg_range($beg, $end, 'num');
206 scalar(@$r) or return;
207 $self->msg_more(join('', map { "$_->[0]\r\n" } @$r));
211 sub listgroup_all_i {
212 my ($self, $num) = @_;
213 my $ary = $self->{ibx}->mm->ids_after($num);
214 scalar(@$ary) or return;
215 more($self, join("\r\n", @$ary));
219 sub cmd_listgroup ($;$$) {
220 my ($self, $group, $range) = @_;
221 if (defined $group) {
222 my $res = cmd_group($self, $group);
223 return $res if ($res !~ /\A211 /);
226 $self->{ibx} or return '412 no newsgroup selected';
227 if (defined $range) {
228 my $r = get_range($self, $range);
229 return $r unless ref $r;
230 long_response($self, \&listgroup_range_i, @$r);
231 } else { # grab every article number
232 long_response($self, \&listgroup_all_i, \(my $num = 0));
236 sub parse_time ($$;$) {
237 my ($date, $time, $gmt) = @_;
238 my ($hh, $mm, $ss) = unpack('A2A2A2', $time);
240 $gmt =~ /\A(?:UTC|GMT)\z/i or die "GM invalid: $gmt";
243 my ($YYYY, $MM, $DD);
244 if (bytes::length($date) == 8) { # RFC 3977 allows YYYYMMDD
245 ($YYYY, $MM, $DD) = unpack('A4A2A2', $date);
246 } else { # legacy clients send YYMMDD
248 ($YY, $MM, $DD) = unpack('A2A2A2', $date);
249 my @now = $gmt ? gmtime : localtime;
250 my $cur_year = $now[5] + 1900;
251 my $cur_cent = int($cur_year / 100) * 100;
252 $YYYY = (($YY + $cur_cent) > $cur_year) ?
253 ($YY + 1900) : ($YY + $cur_cent);
256 timegm($ss, $mm, $hh, $DD, $MM - 1, $YYYY);
258 timelocal($ss, $mm, $hh, $DD, $MM - 1, $YYYY);
262 sub group_line ($$) {
263 my ($self, $ibx) = @_;
264 my ($min, $max) = $ibx->mm->minmax;
265 more($self, "$ibx->{newsgroup} $max $min n");
269 my ($self, $ts, $i, $groupnames) = @_;
271 my $groups = $self->{nntpd}->{pi_cfg}->{-by_newsgroup};
273 my $ngname = $groupnames->[$$i++] // return;
274 my $ibx = $groups->{$ngname} or next; # expired on reload
275 next unless (eval { $ibx->uidvalidity } // 0) > $ts;
276 group_line($self, $ibx);
281 sub cmd_newgroups ($$$;$$) {
282 my ($self, $date, $time, $gmt, $dists) = @_;
283 my $ts = eval { parse_time($date, $time, $gmt) };
287 more($self, '231 list of new newsgroups follows');
288 long_response($self, \&newgroups_i, $ts, \(my $i = 0),
289 $self->{nntpd}->{groupnames});
292 sub wildmat2re (;$) {
293 return $_[0] = qr/.*/ if (!defined $_[0] || $_[0] eq '*');
298 $tmp =~ s#(?<!\\)\[(.+)(?<!\\)\]#
300 my $key = sha1_hex($orig . $salt);
301 $orig =~ s/([^\w\-])+/\Q$1/g;
305 my %map = ('*' => '.*', '?' => '.' );
306 $tmp =~ s#(?<!\\)([^\w\\])#$map{$1} || "\Q$1"#ge;
308 $tmp =~ s#([a-f0-9]{40})#
309 my $orig = $keep{$1};
310 defined $orig ? $orig : $1;
313 $_[0] = qr/\A$tmp\z/;
317 return $_[0] = qr/\A\z/ unless defined $_[0];
318 my %map = ('*' => '.*', ',' => '|');
319 $_[0] =~ s!(.)!$map{$1} || "\Q$1"!ge;
320 $_[0] = qr/\A(?:$_[0])\z/;
324 my ($self, $names, $ts, $prev) = @_;
325 my $ngname = $names->[0];
326 if (my $ibx = $self->{nntpd}->{pi_cfg}->{-by_newsgroup}->{$ngname}) {
327 if (my $over = $ibx->over) {
328 my $msgs = $over->query_ts($ts, $$prev);
330 $self->msg_more(join('', map {
333 $$prev = $msgs->[-1]->{num};
334 return 1; # continue on current group
339 if (@$names) { # continue onto next newsgroup
342 } else { # all done, break out of the long_response
347 sub cmd_newnews ($$$$;$$) {
348 my ($self, $newsgroups, $date, $time, $gmt, $dists) = @_;
349 my $ts = eval { parse_time($date, $time, $gmt) };
351 more($self, '230 list of new articles by message-id follows');
352 my ($keep, $skip) = split('!', $newsgroups, 2);
355 my @names = grep(!/$skip/, grep(/$keep/,
356 @{$self->{nntpd}->{groupnames}}));
357 return '.' unless scalar(@names);
359 long_response($self, \&newnews_i, \@names, $ts, \$prev);
363 my ($self, $group) = @_;
364 my $nntpd = $self->{nntpd};
365 my $ibx = $nntpd->{pi_cfg}->{-by_newsgroup}->{$group} or
366 return '411 no such news group';
370 my ($min, $max) = $ibx->mm->minmax;
371 $self->{article} = $min;
372 my $est_size = $max - $min;
373 "211 $est_size $min $max $group";
376 sub article_adj ($$) {
377 my ($self, $off) = @_;
378 my $ibx = $self->{ibx} or return '412 no newsgroup selected';
380 my $n = $self->{article};
381 defined $n or return '420 no current article has been selected';
384 my $mid = $ibx->mm->mid_for($n);
386 $n = $off > 0 ? 'next' : 'previous';
387 return "421 no $n article in this group";
389 $self->{article} = $n;
390 "223 $n <$mid> article retrieved - request text separately";
393 sub cmd_next ($) { article_adj($_[0], 1) }
394 sub cmd_last ($) { article_adj($_[0], -1) }
396 # We want to encourage using email and CC-ing everybody involved to avoid
397 # the single-point-of-failure a single server provides.
400 my $ibx = $self->{ibx};
401 $ibx ? "440 mailto:$ibx->{-primary_address} to post"
402 : '440 posting not allowed'
407 res($self, '205 closing connection - goodbye!');
412 sub header_append ($$$) {
413 my ($hdr, $k, $v) = @_;
414 my @v = $hdr->header_raw($k);
418 $hdr->header_set($k, @v, $v);
421 sub xref_by_tc ($$$) {
422 my ($xref, $pi_cfg, $smsg) = @_;
423 my $by_addr = $pi_cfg->{-by_addr};
424 my $mid = $smsg->{mid};
425 for my $f (qw(to cc)) {
427 $by_addr->{lc($_)} // ()
428 } (PublicInbox::Address::emails($smsg->{$f} // ''));
429 for my $ibx (@ibxs) {
430 my $ngname = $ibx->{newsgroup} // next;
431 next if defined $xref->{$ngname};
432 $xref->{$ngname} = eval { $ibx->mm->num_for($mid) };
438 my ($self, $cur_ibx, $smsg) = @_;
439 my $nntpd = $self->{nntpd};
440 my $cur_ng = $cur_ibx->{newsgroup};
442 if (my $ALL = $nntpd->{pi_cfg}->ALL) {
443 $xref = $ALL->nntp_xref_for($cur_ibx, $smsg);
444 xref_by_tc($xref, $nntpd->{pi_cfg}, $smsg);
446 $xref = { $cur_ng => $smsg->{num} };
447 my $mid = $smsg->{mid};
448 for my $ibx (values %{$nntpd->{pi_cfg}->{-by_newsgroup}}) {
449 next if defined($xref->{$ibx->{newsgroup}});
450 my $num = eval { $ibx->mm->num_for($mid) } // next;
451 $xref->{$ibx->{newsgroup}} = $num;
454 my $ret = "$nntpd->{servername} $cur_ng:".delete($xref->{$cur_ng});
455 $ret .= " $_:$xref->{$_}" for (sort keys %$xref);
459 sub set_nntp_headers ($$) {
460 my ($hdr, $smsg) = @_;
461 my ($mid) = $smsg->{mid};
463 # leafnode (and maybe other NNTP clients) have trouble dealing
464 # with v2 messages which have multiple Message-IDs (either due
465 # to our own content-based dedupe or buggy git-send-email versions).
466 my @mids = $hdr->header_raw('Message-ID');
467 if (scalar(@mids) > 1) {
469 $hdr->header_set('Message-ID', $mid0);
470 my @alt = $hdr->header_raw('X-Alt-Message-ID');
471 my %seen = map { $_ => 1 } (@alt, $mid0);
472 push(@alt, grep { !$seen{$_}++ } @mids);
473 $hdr->header_set('X-Alt-Message-ID', @alt);
476 # clobber some existing headers
477 my $ibx = $smsg->{-ibx};
478 my $xref = xref($smsg->{nntp}, $ibx, $smsg);
479 $hdr->header_set('Xref', $xref);
482 my ($server_name, $newsgroups) = split(/ /, $xref, 2);
483 $newsgroups =~ s/:[0-9]+\b//g; # drop NNTP article numbers
484 $newsgroups =~ tr/ /,/;
485 $hdr->header_set('Newsgroups', $newsgroups);
487 # *something* here is required for leafnode, try to follow
489 $hdr->header_set('Path', $server_name . '!not-for-mail');
492 sub art_lookup ($$$) {
493 my ($self, $art, $code) = @_;
497 if ($art =~ /\A[0-9]+\z/) {
498 $err = '423 no such article number in this group';
501 } elsif ($art =~ $ONE_MSGID) {
502 ($ibx, $n) = mid_lookup($self, $1);
509 $err = '420 no current article has been selected';
510 $n = $self->{article} // return $err;
512 $ibx = $self->{ibx} or
513 return '412 no newsgroup has been selected';
516 my $smsg = $ibx->over->get_art($n) or return $err;
517 $smsg->{-ibx} = $ibx;
518 if ($code == 223) { # STAT
520 "223 $n <$smsg->{mid}> article retrieved - " .
521 "request text separately";
522 } else { # HEAD | BODY | ARTICLE
523 $smsg->{nntp} = $self;
524 $smsg->{nntp_code} = $code;
525 set_art($self, $art);
526 # this dereferences to `undef'
527 ${git_async_cat($ibx->git, $smsg->{blob}, \&blob_cb, $smsg)};
531 sub msg_body_write ($$) {
532 my ($self, $msg) = @_;
534 # these can momentarily double the memory consumption :<
535 $$msg =~ s/^\./../smg;
536 $$msg =~ s/(?<!\r)\n/\r\n/sg; # Alpine barfs without this
537 $$msg .= "\r\n" unless $$msg =~ /\r\n\z/s;
538 $self->msg_more($$msg);
542 my ($self, $art) = @_;
543 $self->{article} = $art if defined $art && $art =~ /\A[0-9]+\z/;
546 sub msg_hdr_write ($$) {
547 my ($eml, $smsg) = @_;
548 set_nntp_headers($eml, $smsg);
550 my $hdr = $eml->{hdr} // \(my $x = '');
551 # fixup old bug from import (pre-a0c07cba0e5d8b6a)
552 $$hdr =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
553 $$hdr =~ s/(?<!\r)\n/\r\n/sg; # Alpine barfs without this
555 # for leafnode compatibility, we need to ensure Message-ID headers
556 # are only a single line.
557 $$hdr =~ s/^(Message-ID:)[ \t]*\r\n[ \t]+([^\r]+)\r\n/$1 $2\r\n/igsm;
558 $smsg->{nntp}->msg_more($$hdr);
561 sub blob_cb { # called by git->cat_async via git_async_cat
562 my ($bref, $oid, $type, $size, $smsg) = @_;
563 my $self = $smsg->{nntp};
564 my $code = $smsg->{nntp_code};
565 if (!defined($oid)) {
566 # it's possible to have TOCTOU if an admin runs
567 # public-inbox-(edit|purge), just move onto the next message
568 warn "E: $smsg->{blob} missing in $smsg->{-ibx}->{inboxdir}\n";
569 return $self->requeue;
570 } elsif ($smsg->{blob} ne $oid) {
572 die "BUG: $smsg->{blob} != $oid";
574 my $r = "$code $smsg->{num} <$smsg->{mid}> article retrieved - ";
575 my $eml = PublicInbox::Eml->new($bref);
577 more($self, $r .= 'head and body follow');
578 msg_hdr_write($eml, $smsg);
579 $self->msg_more("\r\n");
580 msg_body_write($self, $bref);
581 } elsif ($code == 221) {
582 more($self, $r .= 'head follows');
583 msg_hdr_write($eml, $smsg);
584 } elsif ($code == 222) {
585 more($self, $r .= 'body follows');
586 msg_body_write($self, $bref);
589 die "BUG: bad code: $r";
591 $self->write(\".\r\n"); # flushes (includes ->zflush)
595 sub cmd_article ($;$) {
596 my ($self, $art) = @_;
597 art_lookup($self, $art, 220);
601 my ($self, $art) = @_;
602 art_lookup($self, $art, 221);
606 my ($self, $art) = @_;
607 art_lookup($self, $art, 222);
611 my ($self, $art) = @_;
612 art_lookup($self, $art, 223); # art may be msgid
615 sub cmd_ihave ($) { '435 article not wanted - do not send it' }
617 sub cmd_date ($) { '111 '.strftime('%Y%m%d%H%M%S', gmtime(time)) }
621 more($self, '100 help text follows');
626 my ($self, $range) = @_;
627 my $ibx = $self->{ibx} or return '412 no news group has been selected';
628 defined $range or return '420 No article(s) selected';
630 my ($min, $max) = $ibx->mm->minmax;
631 if ($range =~ /\A([0-9]+)\z/) {
633 } elsif ($range =~ /\A([0-9]+)-\z/) {
634 ($beg, $end) = ($1, $max);
635 } elsif ($range =~ /\A([0-9]+)-([0-9]+)\z/) {
636 ($beg, $end) = ($1, $2);
640 $beg = $min if ($beg < $min);
641 $end = $max if ($end > $max);
642 return '420 No article(s) selected' if ($beg > $end);
648 # wbuf is unset or empty, here; {long} may add to it
649 my ($fd, $cb, $t0, @args) = @{$self->{long_cb}};
650 my $more = eval { $cb->($self, @args) };
651 if ($@ || !$self->{sock}) { # something bad happened...
652 delete $self->{long_cb};
653 my $elapsed = now() - $t0;
656 "%s during long response[$fd] - %0.6f",
659 out($self, " deferred[$fd] aborted - %0.6f", $elapsed);
661 } elsif ($more) { # $self->{wbuf}:
662 $self->update_idle_time;
664 # COMPRESS users all share the same DEFLATE context.
665 # Flush it here to ensure clients don't see
669 # no recursion, schedule another call ASAP, but only after
670 # all pending writes are done. autovivify wbuf:
671 my $new_size = push(@{$self->{wbuf}}, \&long_step);
673 # wbuf may be populated by $cb, no need to rearm if so:
674 $self->requeue if $new_size == 1;
676 delete $self->{long_cb};
678 my $elapsed = now() - $t0;
679 my $fd = fileno($self->{sock});
680 out($self, " deferred[$fd] done - %0.6f", $elapsed);
681 my $wbuf = $self->{wbuf}; # do NOT autovivify
682 $self->requeue unless $wbuf && @$wbuf;
686 sub long_response ($$;@) {
687 my ($self, $cb, @args) = @_; # cb returns true if more, false if done
689 my $sock = $self->{sock} or return;
690 # make sure we disable reading during a long response,
691 # clients should not be sending us stuff and making us do more
692 # work while we are stream a response to them
693 $self->{long_cb} = [ fileno($sock), $cb, now(), @args ];
694 long_step($self); # kick off!
698 sub hdr_msgid_range_i {
699 my ($self, $beg, $end) = @_;
700 my $r = $self->{ibx}->mm->msg_range($beg, $end);
702 $self->msg_more(join('', map { "$_->[0] <$_->[1]>\r\n" } @$r));
706 sub hdr_message_id ($$$) { # optimize XHDR Message-ID [range] for slrnpull.
707 my ($self, $xhdr, $range) = @_;
709 if (defined $range && $range =~ $ONE_MSGID) {
710 my ($ibx, $n) = mid_lookup($self, $1);
711 return r430 unless $n;
712 hdr_mid_response($self, $xhdr, $ibx, $n, $range, $range);
713 } else { # numeric range
714 $range = $self->{article} unless defined $range;
715 my $r = get_range($self, $range);
716 return $r unless ref $r;
717 more($self, $xhdr ? r221 : r225);
718 long_response($self, \&hdr_msgid_range_i, @$r);
722 sub mid_lookup ($$) {
723 my ($self, $mid) = @_;
724 my $cur_ibx = $self->{ibx};
726 my $n = $cur_ibx->mm->num_for($mid);
727 return ($cur_ibx, $n) if defined $n;
729 my $pi_cfg = $self->{nntpd}->{pi_cfg};
730 if (my $ALL = $pi_cfg->ALL) {
732 while (my $smsg = $ALL->over->next_by_mid($mid, \$id, \$prev)) {
733 my $xr3 = $ALL->over->get_xref3($smsg->{num});
734 if (my @x = grep(/:$smsg->{blob}\z/, @$xr3)) {
735 my ($ngname, $xnum) = split(/:/, $x[0]);
736 my $ibx = $pi_cfg->{-by_newsgroup}->{$ngname};
737 return ($ibx, $xnum) if $ibx;
738 # fall through to trying all xref3s
741 W: xref3 missing for <$mid> ($smsg->{blob}) in $ALL->{topdir}, -extindex bug?
746 my ($ngname, $xnum) = split(/:/, $x);
747 my $ibx = $pi_cfg->{-by_newsgroup}->{$ngname};
748 return ($ibx, $xnum) if $ibx;
749 warn "W: `$ngname' does not exist for #$xnum\n";
752 # no warning here, $mid is just invalid
753 } else { # slow path for non-ALL users
754 for my $ibx (values %{$pi_cfg->{-by_newsgroup}}) {
755 next if defined $cur_ibx && $ibx eq $cur_ibx;
756 my $n = $ibx->mm->num_for($mid);
757 return ($ibx, $n) if defined $n;
764 my ($self, $beg, $end) = @_;
765 my $ibx = $self->{ibx};
766 my $msgs = $ibx->over->query_xover($$beg, $end);
767 scalar(@$msgs) or return;
768 $$beg = $msgs->[-1]->{num} + 1;
769 $self->msg_more(join('', map {
770 "$_->{num} ".xref($self, $ibx, $_) . "\r\n";
775 sub hdr_xref ($$$) { # optimize XHDR Xref [range] for rtin
776 my ($self, $xhdr, $range) = @_;
778 if (defined $range && $range =~ $ONE_MSGID) {
780 my ($ibx, $n) = mid_lookup($self, $mid);
781 return r430 unless $n;
782 my $smsg = $ibx->over->get_art($n) or return;
783 hdr_mid_response($self, $xhdr, $ibx, $n, $range,
784 xref($self, $ibx, $smsg));
785 } else { # numeric range
786 $range = $self->{article} unless defined $range;
787 my $r = get_range($self, $range);
788 return $r unless ref $r;
789 more($self, $xhdr ? r221 : r225);
790 long_response($self, \&xref_range_i, @$r);
794 sub over_header_for {
795 my ($over, $num, $field) = @_;
796 my $smsg = $over->get_art($num) or return;
797 return PublicInbox::Smsg::date($smsg) if $field eq 'date';
802 my ($self, $beg, $end, $field) = @_;
803 my $over = $self->{ibx}->over;
804 my $msgs = $over->query_xover($$beg, $end);
805 scalar(@$msgs) or return;
808 # ->{$field} is faster than ->$field invocations, so favor that.
809 if ($field eq 'date') {
811 $tmp .= "$s->{num} ".PublicInbox::Smsg::date($s)."\r\n"
815 $tmp .= "$s->{num} $s->{$field}\r\n";
819 $self->msg_more($tmp);
820 $$beg = $msgs->[-1]->{num} + 1;
823 sub hdr_smsg ($$$$) {
824 my ($self, $xhdr, $field, $range) = @_;
825 if (defined $range && $range =~ $ONE_MSGID) {
826 my ($ibx, $n) = mid_lookup($self, $1);
827 return r430 unless defined $n;
828 my $v = over_header_for($ibx->over, $n, $field);
829 hdr_mid_response($self, $xhdr, $ibx, $n, $range, $v);
830 } else { # numeric range
831 $range = $self->{article} unless defined $range;
832 my $r = get_range($self, $range);
833 return $r unless ref $r;
834 more($self, $xhdr ? r221 : r225);
835 long_response($self, \&smsg_range_i, @$r, $field);
840 my ($self, $xhdr, $header, $range) = @_;
841 my $sub = lc $header;
842 if ($sub eq 'message-id') {
843 hdr_message_id($self, $xhdr, $range);
844 } elsif ($sub eq 'xref') {
845 hdr_xref($self, $xhdr, $range);
846 } elsif ($sub =~ /\A(?:subject|references|date|from|to|cc|
848 hdr_smsg($self, $xhdr, $sub, $range);
849 } elsif ($sub =~ /\A:(bytes|lines)\z/) {
850 hdr_smsg($self, $xhdr, $1, $range);
852 $xhdr ? (r221 . "\r\n.") : "503 HDR not permitted on $header";
858 my ($self, $header, $range) = @_;
859 do_hdr($self, 0, $header, $range);
863 sub cmd_xhdr ($$;$) {
864 my ($self, $header, $range) = @_;
865 do_hdr($self, 1, $header, $range);
868 sub hdr_mid_prefix ($$$$$) {
869 my ($self, $xhdr, $ibx, $n, $mid) = @_;
870 return $mid if $xhdr;
872 # HDR for RFC 3977 users
873 if (my $cur_ibx = $self->{ibx}) {
874 ($cur_ibx eq $ibx) ? $n : '0';
880 sub hdr_mid_response ($$$$$$) {
881 my ($self, $xhdr, $ibx, $n, $mid, $v) = @_;
884 $res .= r221 . "\r\n";
885 $res .= "$mid $v\r\n";
887 $res .= r225 . "\r\n";
888 my $pfx = hdr_mid_prefix($self, $xhdr, $ibx, $n, $mid);
889 $res .= "$pfx $v\r\n";
891 res($self, $res .= '.');
896 my ($self, $beg, $end) = @_;
897 my $h = over_header_for($self->{ibx}->over, $$beg, 'references');
898 more($self, "$$beg $h") if defined($h);
902 sub cmd_xrover ($;$) {
903 my ($self, $range) = @_;
904 my $ibx = $self->{ibx} or return '412 no newsgroup selected';
905 (defined $range && $range =~ /[<>]/) and
906 return '420 No article(s) selected'; # no message IDs
908 $range = $self->{article} unless defined $range;
909 my $r = get_range($self, $range);
910 return $r unless ref $r;
911 more($self, '224 Overview information follows');
912 long_response($self, \&xrover_i, @$r);
915 sub over_line ($$$) {
916 my ($self, $ibx, $smsg) = @_;
917 # n.b. field access and procedural calls can be
918 # 10%-15% faster than OO method calls:
919 my $s = join("\t", $smsg->{num},
922 PublicInbox::Smsg::date($smsg),
927 "Xref: " . xref($self, $ibx, $smsg));
933 my ($self, $range) = @_;
934 if ($range && $range =~ $ONE_MSGID) {
935 my ($ibx, $n) = mid_lookup($self, $1);
936 defined $n or return r430;
937 my $smsg = $ibx->over->get_art($n) or return r430;
938 more($self, '224 Overview information follows (multi-line)');
940 # Only set article number column if it's the current group
942 my $cur_ibx = $self->{ibx};
943 if (!$cur_ibx || $cur_ibx ne $ibx) {
944 # set {-orig_num} for nntp_xref_for
945 $smsg->{-orig_num} = $smsg->{num};
948 $self->msg_more(over_line($self, $ibx, $smsg));
951 cmd_xover($self, $range);
956 my ($self, $beg, $end) = @_;
957 my $ibx = $self->{ibx};
958 my $msgs = $ibx->over->query_xover($$beg, $end);
959 my $nr = scalar @$msgs or return;
962 $self->msg_more(join('', map {
963 over_line($self, $ibx, $_);
965 $$beg = $msgs->[-1]->{num} + 1;
968 sub cmd_xover ($;$) {
969 my ($self, $range) = @_;
970 $range = $self->{article} unless defined $range;
971 my $r = get_range($self, $range);
972 return $r unless ref $r;
973 my ($beg, $end) = @$r;
974 more($self, "224 Overview information follows for $$beg to $end");
975 long_response($self, \&xover_i, @$r);
978 sub compressed { undef }
980 sub cmd_starttls ($) {
982 my $sock = $self->{sock} or return;
984 return r502 if ($sock->can('accept_SSL') || $self->compressed);
985 my $opt = $self->{nntpd}->{accept_tls} or
986 return '580 can not initiate TLS negotiation';
987 res($self, '382 Continue with TLS negotiation');
988 $self->{sock} = IO::Socket::SSL->start_SSL($sock, %$opt);
989 $self->requeue if PublicInbox::DS::accept_tls_step($self);
994 sub cmd_compress ($$) {
995 my ($self, $alg) = @_;
996 return '503 Only DEFLATE is supported' if uc($alg) ne 'DEFLATE';
997 return r502 if $self->compressed;
998 PublicInbox::NNTPdeflate->enable($self);
1003 sub zflush {} # overridden by NNTPdeflate
1005 sub cmd_xpath ($$) {
1006 my ($self, $mid) = @_;
1007 return r501 unless $mid =~ $ONE_MSGID;
1010 my $pi_cfg = $self->{nntpd}->{pi_cfg};
1011 my $groups = $pi_cfg->{-by_newsgroup};
1012 if (my $ALL = $pi_cfg->ALL) {
1013 my ($id, $prev, %seen);
1014 while (my $smsg = $ALL->over->next_by_mid($mid, \$id, \$prev)) {
1015 my $xr3 = $ALL->over->get_xref3($smsg->{num});
1017 my ($ngname, $n) = split(/:/, $x);
1019 if ($groups->{$ngname} && !$seen{$x}++) {
1024 } else { # slow path, no point in using long_response
1025 for my $ibx (values %$groups) {
1026 my $n = $ibx->mm->num_for($mid) // next;
1027 push @paths, "$ibx->{newsgroup}/$n";
1030 return '430 no such article on server' unless @paths;
1031 '223 '.join(' ', sort(@paths));
1034 sub res ($$) { do_write($_[0], $_[1] . "\r\n") }
1036 sub more ($$) { $_[0]->msg_more($_[1] . "\r\n") }
1040 my $done = $self->write(\($_[1]));
1041 return 0 unless $self->{sock};
1047 my ($self, $fmt, @args) = @_;
1048 printf { $self->{nntpd}->{err} } $fmt."\n", @args;
1052 my ($self, $fmt, @args) = @_;
1053 printf { $self->{nntpd}->{out} } $fmt."\n", @args;
1056 # callback used by PublicInbox::DS for any (e)poll (in/out/hup/err)
1060 return unless $self->flush_write && $self->{sock} && !$self->{long_cb};
1062 $self->update_idle_time;
1063 # only read more requests if we've drained the write buffer,
1064 # otherwise we can be buffering infinitely w/o backpressure
1066 my $rbuf = $self->{rbuf} // \(my $x = '');
1067 my $line = index($$rbuf, "\n");
1069 return $self->close if length($$rbuf) >= LINE_MAX;
1070 $self->do_read($rbuf, LINE_MAX, length($$rbuf)) or return;
1071 $line = index($$rbuf, "\n");
1073 $line = substr($$rbuf, 0, $line + 1, '');
1074 $line =~ s/\r?\n\z//s;
1075 return $self->close if $line =~ /[[:cntrl:]]/s;
1078 my $fd = fileno($self->{sock});
1079 my $r = eval { process_line($self, $line) };
1080 my $pending = $self->{wbuf} ? ' pending' : '';
1081 out($self, "[$fd] %s - %0.6f$pending", $line, now() - $t0);
1082 return $self->close if $r < 0;
1083 $self->rbuf_idle($rbuf);
1084 $self->update_idle_time;
1086 # maybe there's more pipelined data, or we'll have
1087 # to register it for socket-readiness notifications
1088 $self->requeue unless $pending;
1091 # for graceful shutdown in PublicInbox::Daemon:
1093 my ($self, $now) = @_;
1094 ($self->{rbuf} || $self->{wbuf} || $self->not_idle_long($now));