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