]> Sergey Matveev's repositories - public-inbox.git/blob - t/nntpd.t
imap: improve IDLE handling at graceful shutdown
[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
16 # FIXME: make easier to test both versions
17 my $version = $ENV{PI_TEST_VERSION} || 1;
18 require_git('2.6') if $version == 2;
19 my $lsof = which('lsof');
20 my $fast_idle = eval { require Linux::Inotify2; 1 } //
21                 eval { require IO::KQueue; 1 };
22
23 my ($tmpdir, $for_destroy) = tmpdir();
24 my $home = "$tmpdir/pi-home";
25 my $err = "$tmpdir/stderr.log";
26 my $out = "$tmpdir/stdout.log";
27 my $inboxdir = "$tmpdir/main.git";
28 my $group = 'test-nntpd';
29 my $addr = $group . '@example.com';
30 SKIP: {
31         skip "git 2.6+ required for V2Writable", 1 if $version == 1;
32         use_ok 'PublicInbox::V2Writable';
33 }
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/', $addr);
51         push @cmd, "-V$version", '-Lbasic';
52         ok(run_script(\@cmd), 'init OK');
53         is(xsys(qw(git config), "--file=$home/.public-inbox/config",
54                         "publicinbox.$group.newsgroup", $group),
55                 0, 'enabled newsgroup');
56         my $len;
57
58         $ibx = PublicInbox::InboxWritable->new($ibx);
59         my $im = $ibx->importer(0);
60
61         # ensure successful message delivery
62         {
63                 my $mime = PublicInbox::Eml->new(<<EOF);
64 To: =?utf-8?Q?El=C3=A9anor?= <you\@example.com>
65 From: =?utf-8?Q?El=C3=A9anor?= <me\@example.com>
66 Cc: $addr
67 Message-Id: <nntp\@example.com>
68 Content-Type: text/plain; charset=utf-8
69 Subject: Testing for    =?utf-8?Q?El=C3=A9anor?=
70 Date: Thu, 01 Jan 1970 06:06:06 +0000
71 Content-Transfer-Encoding: 8bit
72 References: <ref        tab     squeezed>
73
74 This is a test message for El\xc3\xa9anor
75 EOF
76                 my $list_id = $addr;
77                 $list_id =~ s/@/./;
78                 $mime->header_set('List-Id', "<$list_id>");
79                 my $str = $mime->as_string;
80                 $str =~ s/(?<!\r)\n/\r\n/sg;
81                 $len = length($str);
82                 undef $str;
83                 $im->add($mime);
84                 $im->done;
85                 if ($version == 1) {
86                         ok(run_script(['-index', $ibx->{inboxdir}]),
87                                 'indexed v1');
88                 }
89         }
90
91         ok($sock, 'sock created');
92         my $cmd = [ '-nntpd', '-W0', "--stdout=$out", "--stderr=$err" ];
93         $td = start_script($cmd, undef, { 3 => $sock });
94         my $host_port = $sock->sockhost . ':' . $sock->sockport;
95         my $n = Net::NNTP->new($host_port);
96         my $list = $n->list;
97         is_deeply($list, { $group => [ qw(1 1 n) ] }, 'LIST works');
98         is_deeply([$n->group($group)], [ qw(0 1 1), $group ], 'GROUP works');
99         is_deeply($n->listgroup($group), [1], 'listgroup OK');
100         # TODO: Net::NNTP::listgroup does not support range at the moment
101
102         {
103                 my $expect = [ qw(Subject: From: Date: Message-ID:
104                                 References: Bytes: Lines: Xref:full) ];
105                 is_deeply($n->overview_fmt, $expect,
106                         'RFC3977 8.4.2 compliant LIST OVERVIEW.FMT');
107         }
108         SKIP: {
109                 $n->can('starttls') or
110                         skip('Net::NNTP too old to support STARTTLS', 2);
111                 require_mods('IO::Socket::SSL', 2);
112                 eval {
113                         IO::Socket::SSL->VERSION(2.007);
114                 } or skip(<<EOF, 2);
115 IO::Socket::SSL <2.007 not supported by Net::NNTP
116 EOF
117                 ok(!$n->starttls, 'STARTTLS fails when unconfigured');
118                 is($n->code, 580, 'got 580 code on server w/o TLS');
119         };
120
121         my $mid = '<nntp@example.com>';
122         my %xhdr = (
123                 'message-id' => $mid,
124                 subject => "Testing for El\xc3\xa9anor",
125                 'date' => 'Thu, 01 Jan 1970 06:06:06 +0000',
126                 'from' => "El\xc3\xa9anor <me\@example.com>",
127                 'to' => "El\xc3\xa9anor <you\@example.com>",
128                 'cc' => $addr,
129                 'xref' => hostname . " $group:1",
130                 'references' => '<reftabsqueezed>',
131         );
132
133         my $s = tcp_connect($sock);
134         sysread($s, my $buf, 4096);
135         is($buf, "201 " . hostname . " ready - post via email\r\n",
136                 'got greeting');
137
138         ok(syswrite($s, "   \r\n"), 'wrote spaces');
139         ok(syswrite($s, "\r\n"), 'wrote nothing');
140         syswrite($s, "NEWGROUPS\t19990424 000000 \033GMT\007\r\n");
141         is(0, sysread($s, $buf, 4096), 'GOT EOF on cntrl');
142
143         $s = tcp_connect($sock);
144         sysread($s, $buf, 4096);
145         is($buf, "201 " . hostname . " ready - post via email\r\n",
146                 'got greeting');
147
148         syswrite($s, "CAPABILITIES\r\n");
149         $buf = read_til_dot($s);
150         like($buf, qr/\r\nVERSION 2\r\n/s, 'CAPABILITIES works');
151         unlike($buf, qr/STARTTLS/s, 'STARTTLS not advertised');
152         my $deflate_capa = qr/\r\nCOMPRESS DEFLATE\r\n/;
153         if (eval { require Compress::Raw::Zlib }) {
154                 like($buf, $deflate_capa, 'DEFLATE advertised');
155         } else {
156                 unlike($buf, $deflate_capa,
157                         'DEFLATE not advertised (Compress::Raw::Zlib missing)');
158         }
159
160         syswrite($s, "NEWGROUPS 19990424 000000 GMT\r\n");
161         $buf = read_til_dot($s);
162         like($buf, qr/\A231 list of /, 'newgroups OK');
163
164         while (my ($k, $v) = each %xhdr) {
165                 is_deeply($n->xhdr("$k $mid"), { $mid => $v },
166                           "XHDR $k by message-id works");
167                 is_deeply($n->xhdr("$k 1"), { 1 => $v },
168                           "$k by article number works");
169                 is_deeply($n->xhdr("$k 1-"), { 1 => $v },
170                           "$k by article range works");
171                 $buf = '';
172                 syswrite($s, "HDR $k $mid\r\n");
173                 $buf = read_til_dot($s);
174                 my @r = split("\r\n", $buf);
175                 like($r[0], qr/\A225 /, '225 response for HDR');
176                 is($r[1], "0 $v", 'got expected response for HDR');
177         }
178
179         {
180                 my $nogroup = Net::NNTP->new($host_port);
181                 while (my ($k, $v) = each %xhdr) {
182                         is_deeply($nogroup->xhdr("$k $mid"), { $mid => $v },
183                                   "$k by message-id works without group");
184                 }
185         }
186
187         is_deeply($n->xover('1-'), {
188                 '1' => ["Testing for El\xc3\xa9anor",
189                         "El\xc3\xa9anor <me\@example.com>",
190                         'Thu, 01 Jan 1970 06:06:06 +0000',
191                         '<nntp@example.com>',
192                         '<reftabsqueezed>',
193                         $len,
194                         '1',
195                         'Xref: '. hostname . ' test-nntpd:1'] },
196                 "XOVER range works");
197
198         is_deeply($n->xover('1'), {
199                 '1' => ["Testing for El\xc3\xa9anor",
200                         "El\xc3\xa9anor <me\@example.com>",
201                         'Thu, 01 Jan 1970 06:06:06 +0000',
202                         '<nntp@example.com>',
203                         '<reftabsqueezed>',
204                         $len,
205                         '1',
206                         'Xref: '. hostname . ' test-nntpd:1'] },
207                 "XOVER by article works");
208
209         is_deeply($n->head(1), $n->head('<nntp@example.com>'), 'HEAD OK');
210         is_deeply($n->body(1), $n->body('<nntp@example.com>'), 'BODY OK');
211         is($n->body(1)->[0], "This is a test message for El\xc3\xa9anor\n",
212                 'body really matches');
213         my $art = $n->article(1);
214         is(ref($art), 'ARRAY', 'got array for ARTICLE');
215         is_deeply($art, $n->article('<nntp@example.com>'), 'ARTICLE OK');
216         is($n->article(999), undef, 'non-existent num');
217         is($n->article('<non-existent@example>'), undef, 'non-existent mid');
218
219         {
220                 syswrite($s, "OVER $mid\r\n");
221                 $buf = read_til_dot($s);
222                 my @r = split("\r\n", $buf);
223                 like($r[0], qr/^224 /, 'got 224 response for OVER');
224                 is($r[1], "0\tTesting for El\xc3\xa9anor\t" .
225                         "El\xc3\xa9anor <me\@example.com>\t" .
226                         "Thu, 01 Jan 1970 06:06:06 +0000\t" .
227                         "$mid\t<reftabsqueezed>\t$len\t1" .
228                         "\tXref: " . hostname . " test-nntpd:0",
229                         'OVER by Message-ID works');
230                 is($r[2], '.', 'correctly terminated response');
231         }
232
233         is_deeply($n->xhdr(qw(Cc 1-)), { 1 => 'test-nntpd@example.com' },
234                  'XHDR Cc 1- works');
235         is_deeply($n->xhdr(qw(References 1-)), { 1 => '<reftabsqueezed>' },
236                  'XHDR References 1- works)');
237         is_deeply($n->xhdr(qw(list-id 1-)), {},
238                  'XHDR on invalid header returns empty');
239
240         my $mids = $n->newnews(0, '*');
241         is_deeply($mids, ['<nntp@example.com>'], 'NEWNEWS works');
242         {
243                 my $t0 = time;
244                 my $date = $n->date;
245                 my $t1 = time;
246                 ok($date >= $t0, 'valid date after start');
247                 ok($date <= $t1, 'valid date before stop');
248         }
249         if ('leafnode interop') {
250                 my $for_leafnode = PublicInbox::Eml->new(<<"");
251 From: longheader\@example.com
252 To: $addr
253 Subject: none
254 Date: Fri, 02 Oct 1993 00:00:00 +0000
255
256                 my $long_hdr = 'for-leafnode-'.('y'x200).'@example.com';
257                 $for_leafnode->header_set('Message-ID', "<$long_hdr>");
258                 $im->add($for_leafnode);
259                 $im->done;
260                 if ($version == 1) {
261                         ok(run_script(['-index', $ibx->{inboxdir}]),
262                                 'indexed v1');
263                 }
264                 my $hdr = $n->head("<$long_hdr>");
265                 my $expect = qr/\AMessage-ID: /i . qr/\Q<$long_hdr>\E/;
266                 ok(scalar(grep(/$expect/, @$hdr)), 'Message-ID not folded');
267                 ok(scalar(grep(/^Path:/, @$hdr)), 'Path: header found');
268
269                 # it's possible for v2 messages to have 2+ Message-IDs,
270                 # but leafnode can't handle it
271                 if ($version != 1) {
272                         my @mids = ("<$long_hdr>", '<2mid@wtf>');
273                         $for_leafnode->header_set('Message-ID', @mids);
274                         $for_leafnode->body_set('not-a-dupe');
275                         my $warn = '';
276                         local $SIG{__WARN__} = sub { $warn .= join('', @_) };
277                         $im->add($for_leafnode);
278                         $im->done;
279                         like($warn, qr/reused/, 'warned for reused MID');
280                         $hdr = $n->head('<2mid@wtf>');
281                         my @hmids = grep(/\AMessage-ID: /i, @$hdr);
282                         is(scalar(@hmids), 1, 'Single Message-ID in header');
283                         like($hmids[0], qr/: <2mid\@wtf>/, 'got expected mid');
284                 }
285         }
286
287         # pipelined requests:
288         {
289                 my $nreq = 90;
290                 syswrite($s, "GROUP $group\r\n");
291                 my $res = <$s>;
292                 my $rdr = fork;
293                 if ($rdr == 0) {
294                         use POSIX qw(_exit);
295                         for (1..$nreq) {
296                                 <$s> =~ /\A224 / or _exit(1);
297                                 <$s> =~ /\A1/ or _exit(2);
298                                 <$s> eq ".\r\n" or _exit(3);
299                         }
300                         _exit(0);
301                 }
302                 for (1..$nreq) {
303                         syswrite($s, "XOVER 1\r\n");
304                 }
305                 is($rdr, waitpid($rdr, 0), 'reader done');
306                 is($? >> 8, 0, 'no errors');
307         }
308         my $noerr = { 2 => \(my $null) };
309         SKIP: {
310                 if ($INC{'Search/Xapian.pm'} && ($ENV{TEST_RUN_MODE}//2)) {
311                         skip 'Search/Xapian.pm pre-loaded (by t/run.perl?)', 1;
312                 }
313                 $lsof or skip 'lsof missing', 1;
314                 my @of = xqx([$lsof, '-p', $td->{pid}], undef, $noerr);
315                 skip('lsof broken', 1) if (!scalar(@of) || $?);
316                 my @xap = grep m!Search/Xapian!, @of;
317                 is_deeply(\@xap, [], 'Xapian not loaded in nntpd');
318         }
319         # -compact requires Xapian
320         SKIP: {
321                 require_mods('Search::Xapian', 2);
322                 which('xapian-compact') or skip 'xapian-compact missing', 2;
323                 is(xsys(qw(git config), "--file=$home/.public-inbox/config",
324                                 "publicinbox.$group.indexlevel", 'medium'),
325                         0, 'upgraded indexlevel');
326                 my $ex = eml_load('t/data/0001.patch');
327                 is($n->article($ex->header('Message-ID')), undef,
328                         'article did not exist');
329                 $im->add($ex);
330                 $im->done;
331                 ok(run_script([qw(-index --reindex -c), $ibx->{inboxdir}],
332                                 undef, $noerr), '-compacted');
333                 select(undef, undef, undef, $fast_idle ? 0.1 : 2.1);
334                 $art = $n->article($ex->header('Message-ID'));
335                 ok($art, 'new article retrieved after compact');
336                 $lsof or skip 'lsof missing', 1;
337                 ($^O =~ /\A(?:linux)\z/) or
338                         skip "lsof /(deleted)/ check untested on $^O", 1;
339                 my @of = xqx([$lsof, '-p', $td->{pid}], undef, $noerr);
340                 is(scalar(grep(/\(deleted\)/, @of)), 0, 'no deleted files');
341         };
342         {
343                 setsockopt($s, IPPROTO_TCP, TCP_NODELAY, 1);
344                 syswrite($s, 'HDR List-id 1-');
345                 select(undef, undef, undef, 0.15);
346                 ok($td->kill, 'killed nntpd');
347                 select(undef, undef, undef, 0.15);
348                 syswrite($s, "\r\n");
349                 $buf = '';
350                 do {
351                         sysread($s, $buf, 4096, length($buf));
352                 } until ($buf =~ /\r\n\z/);
353                 my @r = split("\r\n", $buf);
354                 like($r[0], qr/^5\d\d /,
355                         'got 5xx response for unoptimized HDR');
356                 is(scalar @r, 1, 'only one response line');
357         }
358         $n = $s = undef;
359         $td->join;
360         is($?, 0, 'no error in exited process');
361         my $eout = do {
362                 open my $fh, '<', $err or die "open $err failed: $!";
363                 local $/;
364                 <$fh>;
365         };
366         unlike($eout, qr/wide/i, 'no Wide character warnings');
367 }
368
369 $td = undef;
370 done_testing();
371
372 sub read_til_dot {
373         my ($s) = @_;
374         my $buf = '';
375         do {
376                 sysread($s, $buf, 4096, length($buf));
377         } until ($buf =~ /\r\n\.\r\n\z/);
378         $buf;
379 }
380
381 1;