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