]> Sergey Matveev's repositories - public-inbox.git/blob - t/nntpd.t
cf1c44f80b23d83ed6f4521aebdf04e18aa5a036
[public-inbox.git] / t / nntpd.t
1 #!perl -w
2 # Copyright (C) 2015-2021 all contributors <meta@public-inbox.org>
3 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 use strict; use v5.10.1; use PublicInbox::TestCommon;
5 require_mods(qw(DBD::SQLite));
6 use PublicInbox::Eml;
7 use Socket qw(IPPROTO_TCP TCP_NODELAY);
8 use Net::NNTP;
9 use Sys::Hostname;
10 use POSIX qw(_exit);
11 use Digest::SHA;
12
13 # t/nntpd-v2.t wraps this for v2
14 my $version = $ENV{PI_TEST_VERSION} || 1;
15 require_git('2.6') if $version == 2;
16 use_ok 'PublicInbox::Msgmap';
17 my $lsof = require_cmd('lsof', 1);
18 my $fast_idle = eval { require Linux::Inotify2; 1 } //
19                 eval { require IO::KQueue; 1 };
20
21 my ($tmpdir, $for_destroy) = tmpdir();
22 my $home = "$tmpdir/pi-home";
23 my $err = "$tmpdir/stderr.log";
24 my $out = "$tmpdir/stdout.log";
25 my $inboxdir = "$tmpdir/inbox";
26 my $group = 'test-nntpd';
27 my $addr = $group . '@example.com';
28 my $sock = tcp_server();
29 my $host_port = tcp_host_port($sock);
30 my $td;
31
32 my $eml = PublicInbox::Eml->new(<<EOF);
33 To: =?utf-8?Q?El=C3=A9anor?= <you\@example.com>
34 From: =?utf-8?Q?El=C3=A9anor?= <me\@example.com>
35 Cc: $addr
36 Message-Id: <nntp\@example.com>
37 Content-Type: text/plain; charset=utf-8
38 Subject: Testing for    =?utf-8?Q?El=C3=A9anor?=
39 Date: Thu, 01 Jan 1970 06:06:06 +0000
40 Content-Transfer-Encoding: 8bit
41 References: <ref        tab     squeezed>
42
43 This is a test message for El\xc3\xa9anor
44 EOF
45 my $list_id = $addr;
46 $list_id =~ s/@/./;
47 $eml->header_set('List-Id', "<$list_id>");
48 my $str = $eml->as_string;
49 $str =~ s/(?<!\r)\n/\r\n/sg;
50 my $len = length($str);
51 undef $str;
52
53 my $ibx = create_inbox "v$version", version => $version, indexlevel => 'basic',
54                         tmpdir => $inboxdir, sub {
55         my ($im, $ibx) = @_;
56         $im->add($eml) or BAIL_OUT;
57 };
58 undef $eml;
59 my $other = create_inbox "other$version", version => $version,
60                 indexlevel => 'basic', sub {
61         my ($im) = @_;
62         $im->add(eml_load 't/utf8.eml') or BAIL_OUT;
63 };
64
65 local $ENV{HOME} = $home;
66 mkdir $home or BAIL_OUT $!;
67 mkdir "$home/.public-inbox" or BAIL_OUT $!;
68 open my $cfgfh, '>', "$home/.public-inbox/config" or BAIL_OUT $!;
69 print $cfgfh <<EOF or BAIL_OUT;
70 [publicinbox "$group"]
71         inboxdir = $inboxdir
72         url = http://example.com/abc
73         address = $addr
74         indexlevel = basic
75         newsgroup = $group
76 [publicinbox "xyz"]
77         inboxdir = $other->{inboxdir}
78         url = http://example.com/xyz
79         address = e\@example.com
80         indexlevel = basic
81         newsgroup = x.y.z
82 [publicinboxMda]
83         spamcheck = none
84 EOF
85 close $cfgfh or BAIL_OUT;
86
87 {
88         my $cmd = [ '-nntpd', '-W0', "--stdout=$out", "--stderr=$err" ];
89         $td = start_script($cmd, undef, { 3 => $sock });
90         my $n = Net::NNTP->new($host_port);
91         my $list = $n->list;
92         ok(delete $list->{'x.y.z'}, 'deleted x.y.z group');
93         is_deeply($list, { $group => [ qw(1 1 n) ] }, 'LIST works');
94         is_deeply([$n->group($group)], [ qw(0 1 1), $group ], 'GROUP works');
95         is_deeply($n->listgroup($group), [1], 'listgroup OK');
96         # TODO: Net::NNTP::listgroup does not support range at the moment
97
98         {
99                 my $expect = [ qw(Subject: From: Date: Message-ID:
100                                 References: Bytes: Lines: Xref:full) ];
101                 is_deeply($n->overview_fmt, $expect,
102                         'RFC3977 8.4.2 compliant LIST OVERVIEW.FMT');
103         }
104         SKIP: {
105                 $n->can('starttls') or
106                         skip('Net::NNTP too old to support STARTTLS', 2);
107                 require_mods('IO::Socket::SSL', 2);
108                 ok(!$n->starttls, 'STARTTLS fails when unconfigured');
109                 is($n->code, 580, 'got 580 code on server w/o TLS');
110         };
111
112         my $mid = '<nntp@example.com>';
113         my %xhdr = (
114                 'message-id' => $mid,
115                 subject => "Testing for El\xc3\xa9anor",
116                 'date' => 'Thu, 01 Jan 1970 06:06:06 +0000',
117                 'from' => "El\xc3\xa9anor <me\@example.com>",
118                 'to' => "El\xc3\xa9anor <you\@example.com>",
119                 'cc' => $addr,
120                 'xref' => hostname . " $group:1",
121                 'references' => '<reftabsqueezed>',
122         );
123
124         my $s = tcp_connect($sock);
125         sysread($s, my $buf, 4096);
126         is($buf, "201 " . hostname . " ready - post via email\r\n",
127                 'got greeting');
128
129         ok(syswrite($s, "   \r\n"), 'wrote spaces');
130         ok(syswrite($s, "\r\n"), 'wrote nothing');
131         syswrite($s, "NEWGROUPS\t19990424 000000 \033GMT\007\r\n");
132         is(0, sysread($s, $buf, 4096), 'GOT EOF on cntrl');
133
134         $s = tcp_connect($sock);
135         sysread($s, $buf, 4096);
136         is($buf, "201 " . hostname . " ready - post via email\r\n",
137                 'got greeting');
138
139         syswrite($s, "CAPABILITIES\r\n");
140         $buf = read_til_dot($s);
141         like($buf, qr/\r\nVERSION 2\r\n/s, 'CAPABILITIES works');
142         unlike($buf, qr/STARTTLS/s, 'STARTTLS not advertised');
143         my $deflate_capa = qr/\r\nCOMPRESS DEFLATE\r\n/;
144         if (eval { require Compress::Raw::Zlib }) {
145                 like($buf, $deflate_capa, 'DEFLATE advertised');
146         } else {
147                 unlike($buf, $deflate_capa,
148                         'DEFLATE not advertised (Compress::Raw::Zlib missing)');
149         }
150
151         syswrite($s, "NEWGROUPS 19990424 000000 GMT\r\n");
152         $buf = read_til_dot($s);
153         like($buf, qr/\A231 list of /, 'newgroups OK');
154
155         while (my ($k, $v) = each %xhdr) {
156                 is_deeply($n->xhdr("$k $mid"), { $mid => $v },
157                           "XHDR $k by message-id works");
158                 is_deeply($n->xhdr("$k 1"), { 1 => $v },
159                           "$k by article number works");
160                 is_deeply($n->xhdr("$k 1-"), { 1 => $v },
161                           "$k by article range works");
162                 $buf = '';
163                 syswrite($s, "HDR $k $mid\r\n");
164                 $buf = read_til_dot($s);
165                 my @r = split("\r\n", $buf);
166                 like($r[0], qr/\A225 /, '225 response for HDR');
167                 is($r[1], "0 $v", 'got expected response for HDR');
168         }
169
170         {
171                 my $nogroup = Net::NNTP->new($host_port);
172                 while (my ($k, $v) = each %xhdr) {
173                         is_deeply($nogroup->xhdr("$k $mid"), { $mid => $v },
174                                   "$k by message-id works without group");
175                 }
176         }
177
178         is_deeply($n->xover('1-'), {
179                 '1' => ["Testing for El\xc3\xa9anor",
180                         "El\xc3\xa9anor <me\@example.com>",
181                         'Thu, 01 Jan 1970 06:06:06 +0000',
182                         '<nntp@example.com>',
183                         '<reftabsqueezed>',
184                         $len,
185                         '1',
186                         'Xref: '. hostname . ' test-nntpd:1'] },
187                 "XOVER range works");
188
189         is_deeply($n->xover('1'), {
190                 '1' => ["Testing for El\xc3\xa9anor",
191                         "El\xc3\xa9anor <me\@example.com>",
192                         'Thu, 01 Jan 1970 06:06:06 +0000',
193                         '<nntp@example.com>',
194                         '<reftabsqueezed>',
195                         $len,
196                         '1',
197                         'Xref: '. hostname . ' test-nntpd:1'] },
198                 "XOVER by article works");
199
200         is_deeply($n->head(1), $n->head('<nntp@example.com>'), 'HEAD OK');
201         is_deeply($n->body(1), $n->body('<nntp@example.com>'), 'BODY OK');
202         is_deeply($n->nntpstat(1), '<nntp@example.com>', 'STAT');
203         is($n->body(1)->[0], "This is a test message for El\xc3\xa9anor\n",
204                 'body really matches');
205         my $art = $n->article(1);
206         is(ref($art), 'ARRAY', 'got array for ARTICLE');
207         is_deeply($art, $n->article('<nntp@example.com>'), 'ARTICLE OK');
208         is($n->article(999), undef, 'non-existent num');
209         is($n->article('<non-existent@example>'), undef, 'non-existent mid');
210
211         {
212                 syswrite($s, "OVER $mid\r\n");
213                 $buf = read_til_dot($s);
214                 my @r = split("\r\n", $buf);
215                 like($r[0], qr/^224 /, 'got 224 response for OVER');
216                 is($r[1], "0\tTesting for El\xc3\xa9anor\t" .
217                         "El\xc3\xa9anor <me\@example.com>\t" .
218                         "Thu, 01 Jan 1970 06:06:06 +0000\t" .
219                         "$mid\t<reftabsqueezed>\t$len\t1" .
220                         "\tXref: " . hostname . " test-nntpd:0",
221                         'OVER by Message-ID works');
222                 is($r[2], '.', 'correctly terminated response');
223         }
224
225         is_deeply($n->xhdr(qw(Cc 1-)), { 1 => 'test-nntpd@example.com' },
226                  'XHDR Cc 1- works');
227         is_deeply($n->xhdr(qw(References 1-)), { 1 => '<reftabsqueezed>' },
228                  'XHDR References 1- works)');
229         is_deeply($n->xhdr(qw(list-id 1-)), {},
230                  'XHDR on invalid header returns empty');
231
232         my $mids = $n->newnews(0, $group);
233         is_deeply($mids, ['<nntp@example.com>'], 'NEWNEWS works');
234         {
235                 my $t0 = time;
236                 my $date = $n->date;
237                 my $t1 = time;
238                 ok($date >= $t0, 'valid date after start');
239                 ok($date <= $t1, 'valid date before stop');
240         }
241         if ('leafnode interop') {
242                 my $for_leafnode = PublicInbox::Eml->new(<<"");
243 From: longheader\@example.com
244 To: $addr
245 Subject: none
246 Date: Fri, 02 Oct 1993 00:00:00 +0000
247
248                 my $long_hdr = 'for-leafnode-'.('y'x200).'@example.com';
249                 $for_leafnode->header_set('Message-ID', "<$long_hdr>");
250                 my $im = $ibx->importer(0);
251                 $im->add($for_leafnode);
252                 $im->done;
253                 my $hdr = $n->head("<$long_hdr>");
254                 my $expect = qr/\AMessage-ID: /i . qr/\Q<$long_hdr>\E/;
255                 ok(scalar(grep(/$expect/, @$hdr)), 'Message-ID not folded');
256                 ok(scalar(grep(/^Path:/, @$hdr)), 'Path: header found');
257
258                 # it's possible for v2 messages to have 2+ Message-IDs,
259                 # but leafnode can't handle it
260                 if ($version != 1) {
261                         my @mids = ("<$long_hdr>", '<2mid@wtf>');
262                         $for_leafnode->header_set('Message-ID', @mids);
263                         $for_leafnode->body_set('not-a-dupe');
264                         my $warn = '';
265                         local $SIG{__WARN__} = sub { $warn .= join('', @_) };
266                         $im->add($for_leafnode);
267                         $im->done;
268                         like($warn, qr/reused/, 'warned for reused MID');
269                         $hdr = $n->head('<2mid@wtf>');
270                         my @hmids = grep(/\AMessage-ID: /i, @$hdr);
271                         is(scalar(@hmids), 1, 'Single Message-ID in header');
272                         like($hmids[0], qr/: <2mid\@wtf>/, 'got expected mid');
273                 }
274         }
275
276         ok($n->article('<testmessage@example.com>'),
277                 'cross newsgroup ARTICLE by Message-ID');
278         ok($n->body('<testmessage@example.com>'),
279                 'cross newsgroup BODY by Message-ID');
280         ok($n->head('<testmessage@example.com>'),
281                 'cross newsgroup HEAD by Message-ID');
282         is($n->xpath('<testmessage@example.com>'), 'x.y.z/1', 'xpath hit');
283         is($n->xpath('<non-existent@example.com>'), undef, 'xpath miss');
284
285         # pipelined requests:
286         {
287                 my $nreq = 90;
288                 my $nart = 2;
289                 syswrite($s, "GROUP $group\r\n");
290                 my $res = <$s>;
291                 my $rdr = fork;
292                 if ($rdr == 0) {
293                         for (1..$nreq) {
294                                 <$s> =~ /\A224 / or _exit(1);
295                                 <$s> =~ /\A1/ or _exit(2);
296                                 <$s> eq ".\r\n" or _exit(3);
297                         }
298                         my %sums;
299                         for (1..$nart) {
300                                 <$s> =~ /\A220 / or _exit(4);
301                                 my $dig = Digest::SHA->new(1);
302                                 while (my $l = <$s>) {
303                                         last if $l eq ".\r\n";
304                                         $dig->add($l);
305                                 }
306                                 $dig = $dig->hexdigest;
307                                 $sums{$dig}++;
308                         }
309                         if ($nart) {
310                                 scalar(keys(%sums)) == 1 or _exit(5);
311                                 (values(%sums))[0] == $nart or _exit(6);
312                         }
313                         _exit(0);
314                 }
315                 for (1..$nreq) {
316                         syswrite($s, "XOVER 1\r\n");
317                 }
318                 syswrite($s, "ARTICLE 1\r\n" x $nart);
319                 is($rdr, waitpid($rdr, 0), 'reader done');
320                 is($? >> 8, 0, 'no errors');
321         }
322         my $noerr = { 2 => \(my $null) };
323         SKIP: {
324                 if ($INC{'Search/Xapian.pm'} && ($ENV{TEST_RUN_MODE}//2)) {
325                         skip 'Search/Xapian.pm pre-loaded (by t/run.perl?)', 1;
326                 }
327                 $lsof or skip 'lsof missing', 1;
328                 my @of = xqx([$lsof, '-p', $td->{pid}], undef, $noerr);
329                 skip('lsof broken', 1) if (!scalar(@of) || $?);
330                 my @xap = grep m!Search/Xapian!, @of;
331                 is_deeply(\@xap, [], 'Xapian not loaded in nntpd');
332         }
333         # -compact requires Xapian
334         SKIP: {
335                 require_mods('Search::Xapian', 2);
336                 have_xapian_compact or skip 'xapian-compact missing', 2;
337                 is(xsys(qw(git config), "--file=$home/.public-inbox/config",
338                                 "publicinbox.$group.indexlevel", 'medium'),
339                         0, 'upgraded indexlevel');
340                 my $ex = eml_load('t/data/0001.patch');
341                 is($n->article($ex->header('Message-ID')), undef,
342                         'article did not exist');
343                 my $im = $ibx->importer(0);
344                 $im->add($ex);
345                 $im->done;
346                 {
347                         my $f = $ibx->mm->{dbh}->sqlite_db_filename;
348                         my $tmp = "$tmpdir/tmp.sqlite3";
349                         $ibx->mm->{dbh}->sqlite_backup_to_file($tmp);
350                         delete $ibx->{mm};
351                         rename($tmp, $f) or BAIL_OUT "rename($tmp, $f): $!";
352                 }
353                 ok(run_script([qw(-index -c -j0 --reindex), $ibx->{inboxdir}],
354                                 undef, $noerr), '-compacted');
355                 select(undef, undef, undef, $fast_idle ? 0.1 : 2.1);
356                 $art = $n->article($ex->header('Message-ID'));
357                 ok($art, 'new article retrieved after compact');
358                 $lsof or skip 'lsof missing', 1;
359                 ($^O =~ /\A(?:linux)\z/) or
360                         skip "lsof /(deleted)/ check untested on $^O", 1;
361                 my @lsof = xqx([$lsof, '-p', $td->{pid}], undef, $noerr);
362                 my $d = [ grep(/\(deleted\)/, @lsof) ];
363                 is_deeply($d, [], 'no deleted files') or diag explain($d);
364         };
365         SKIP: { test_watch($tmpdir, $host_port, $group) };
366         {
367                 setsockopt($s, IPPROTO_TCP, TCP_NODELAY, 1);
368                 syswrite($s, 'HDR List-id 1-');
369                 select(undef, undef, undef, 0.15);
370                 ok($td->kill, 'killed nntpd');
371                 select(undef, undef, undef, 0.15);
372                 syswrite($s, "\r\n");
373                 $buf = '';
374                 do {
375                         sysread($s, $buf, 4096, length($buf));
376                 } until ($buf =~ /\r\n\z/);
377                 my @r = split("\r\n", $buf);
378                 like($r[0], qr/^5\d\d /,
379                         'got 5xx response for unoptimized HDR');
380                 is(scalar @r, 1, 'only one response line');
381         }
382         $n = $s = undef;
383         $td->join;
384         is($?, 0, 'no error in exited process');
385         my $eout = do {
386                 open my $fh, '<', $err or die "open $err failed: $!";
387                 local $/;
388                 <$fh>;
389         };
390         unlike($eout, qr/wide/i, 'no Wide character warnings');
391 }
392
393 $td = undef;
394 done_testing();
395
396 sub read_til_dot {
397         my ($s) = @_;
398         my $buf = '';
399         do {
400                 sysread($s, $buf, 4096, length($buf));
401         } until ($buf =~ /\r\n\.\r\n\z/);
402         $buf;
403 }
404
405 sub test_watch {
406         my ($tmpdir, $host_port, $group) = @_;
407         use_ok 'PublicInbox::Watch';
408         use_ok 'PublicInbox::InboxIdle';
409         use_ok 'PublicInbox::Config';
410         require_git('1.8.5', 1) or skip('git 1.8.5+ needed for --urlmatch', 4);
411         my $old_env = { HOME => $ENV{HOME} };
412         my $home = "$tmpdir/watch_home";
413         mkdir $home or BAIL_OUT $!;
414         mkdir "$home/.public-inbox" or BAIL_OUT $!;
415         local $ENV{HOME} = $home;
416         my $name = 'watchnntp';
417         my $addr = "i1\@example.com";
418         my $url = "http://example.com/i1";
419         my $inboxdir = "$tmpdir/watchnntp";
420         my $cmd = ['-init', '-V1', '-Lbasic', $name, $inboxdir, $url, $addr];
421         my $nntpurl = "nntp://$host_port/$group";
422         run_script($cmd) or BAIL_OUT("init $name");
423         xsys(qw(git config), "--file=$home/.public-inbox/config",
424                         "publicinbox.$name.watch",
425                         $nntpurl) == 0 or BAIL_OUT "git config $?";
426         # try again with polling
427         xsys(qw(git config), "--file=$home/.public-inbox/config",
428                 'nntp.PollInterval', 0.11) == 0
429                 or BAIL_OUT "git config $?";
430         my $cfg = PublicInbox::Config->new;
431         PublicInbox::DS->Reset;
432         my $ii = PublicInbox::InboxIdle->new($cfg);
433         my $cb = sub { PublicInbox::DS->SetPostLoopCallback(sub {}) };
434         my $obj = bless \$cb, 'PublicInbox::TestCommon::InboxWakeup';
435         $cfg->each_inbox(sub { $_[0]->subscribe_unlock('ident', $obj) });
436         my $watcherr = "$tmpdir/watcherr";
437         open my $err_wr, '>', $watcherr or BAIL_OUT $!;
438         open my $err, '<', $watcherr or BAIL_OUT $!;
439         my $w = start_script(['-watch'], undef, { 2 => $err_wr });
440
441         diag 'waiting for initial fetch...';
442         PublicInbox::DS::event_loop();
443         diag 'inbox unlocked on initial fetch';
444         $w->kill;
445         $w->join;
446         is($?, 0, 'no error in exited -watch process');
447         $cfg->each_inbox(sub { shift->unsubscribe_unlock('ident') });
448         $ii->close;
449         PublicInbox::DS->Reset;
450         my @err = grep(!/^(?:I:|#)/, <$err>);
451         is(@err, 0, 'no warnings/errors from -watch'.join(' ', @err));
452         my @ls = xqx(['git', "--git-dir=$inboxdir", qw(ls-tree -r HEAD)]);
453         isnt(scalar(@ls), 0, 'imported something');
454 }
455
456 1;