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