]> Sergey Matveev's repositories - public-inbox.git/blob - t/imapd.t
a63be0fd0c2c63ba45a2448376485548658135c5
[public-inbox.git] / t / imapd.t
1 #!perl -w
2 # Copyright (C) 2020 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 Test::More;
6 use Time::HiRes ();
7 use PublicInbox::TestCommon;
8 use PublicInbox::Config;
9 use PublicInbox::Spawn qw(which);
10 require_mods(qw(DBD::SQLite Mail::IMAPClient Mail::IMAPClient::BodyStructure));
11
12 my $level = '-Lbasic';
13 SKIP: {
14         require_mods('Search::Xapian', 1);
15         $level = '-Lmedium';
16 };
17
18 my @V = (1);
19 push(@V, 2) if require_git('2.6', 1);
20
21 my ($tmpdir, $for_destroy) = tmpdir();
22 my $home = "$tmpdir/home";
23 local $ENV{HOME} = $home;
24
25 for my $V (@V) {
26         my $addr = "i$V\@example.com";
27         my $name = "i$V";
28         my $url = "http://example.com/i$V";
29         my $inboxdir = "$tmpdir/$name";
30         my $folder = "inbox.i$V";
31         my $cmd = ['-init', "-V$V", $level, $name, $inboxdir, $url, $addr];
32         run_script($cmd) or BAIL_OUT("init $name");
33         xsys(qw(git config), "--file=$ENV{HOME}/.public-inbox/config",
34                         "publicinbox.$name.newsgroup", $folder) == 0 or
35                         BAIL_OUT("setting newsgroup $V");
36         if ($V == 1) {
37                 xsys(qw(git config), "--file=$ENV{HOME}/.public-inbox/config",
38                         'publicinboxmda.spamcheck', 'none') == 0 or
39                         BAIL_OUT("config: $?");
40         }
41         open(my $fh, '<', 't/utf8.eml') or BAIL_OUT("open t/utf8.eml: $!");
42         my $env = { ORIGINAL_RECIPIENT => $addr };
43         run_script(['-mda', '--no-precheck'], $env, { 0 => $fh }) or
44                 BAIL_OUT('-mda delivery');
45         if ($V == 1) {
46                 run_script(['-index', $inboxdir]) or BAIL_OUT("index $?");
47         }
48 }
49 my $sock = tcp_server();
50 my $err = "$tmpdir/stderr.log";
51 my $out = "$tmpdir/stdout.log";
52 my $cmd = [ '-imapd', '-W0', "--stdout=$out", "--stderr=$err" ];
53 my $td = start_script($cmd, undef, { 3 => $sock }) or BAIL_OUT("-imapd: $?");
54 my %mic_opt = (
55         Server => $sock->sockhost,
56         Port => $sock->sockport,
57         Uid => 1,
58 );
59 my $mic = Mail::IMAPClient->new(%mic_opt);
60 my $pre_login_capa = $mic->capability;
61 is(grep(/\AAUTH=ANONYMOUS\z/, @$pre_login_capa), 1,
62         'AUTH=ANONYMOUS advertised pre-login');
63
64 $mic->User('lorelei');
65 $mic->Password('Hunter2');
66 ok($mic->login && $mic->IsAuthenticated, 'LOGIN works');
67 my $post_login_capa = $mic->capability;
68 ok(join("\n", @$pre_login_capa) ne join("\n", @$post_login_capa),
69         'got different capabilities post-login');
70
71 $mic_opt{Authmechanism} = 'ANONYMOUS';
72 $mic_opt{Authcallback} = sub { '' };
73 $mic = Mail::IMAPClient->new(%mic_opt);
74 ok($mic && $mic->login && $mic->IsAuthenticated, 'AUTHENTICATE ANONYMOUS');
75 my $post_auth_anon_capa = $mic->capability;
76 is_deeply($post_auth_anon_capa, $post_login_capa,
77         'auth anon has same capabilities');
78 my $e;
79 ok(!$mic->examine('foo') && ($e = $@), 'EXAMINE non-existent');
80 like($e, qr/\bNO\b/, 'got a NO on EXAMINE for non-existent');
81 ok(!$mic->select('foo') && ($e = $@), 'EXAMINE non-existent');
82 like($e, qr/\bNO\b/, 'got a NO on EXAMINE for non-existent');
83 ok($mic->select('inbox.i1'), 'SELECT succeeds');
84 ok($mic->examine('inbox.i1'), 'EXAMINE succeeds');
85 my @raw = $mic->status('inbox.i1', qw(Messages uidnext uidvalidity));
86 is(scalar(@raw), 2, 'got status response');
87 like($raw[0], qr/\A\*\x20STATUS\x20inbox\.i1\x20
88         \(MESSAGES\x20\d+\x20UIDNEXT\x20\d+\x20UIDVALIDITY\x20\d+\)\r\n/sx);
89 like($raw[1], qr/\A\S+ OK /, 'finished status response');
90
91 @raw = $mic->list;
92 like($raw[0], qr/^\* LIST \(.*?\) "\." inbox/,
93         'got an inbox');
94 like($raw[-1], qr/^\S+ OK /, 'response ended with OK');
95 is(scalar(@raw), scalar(@V) + 2, 'default LIST response');
96 @raw = $mic->list('', 'inbox.i1');
97 is(scalar(@raw), 2, 'limited LIST response');
98 like($raw[0], qr/^\* LIST \(.*?\) "\." inbox/,
99                 'got an inbox.i1');
100 like($raw[-1], qr/^\S+ OK /, 'response ended with OK');
101
102 { # make sure we get '%' globbing right
103         my @n = map { { newsgroup => $_ } } (qw(x.y.z x.z.y));
104         my $self = { imapd => { grouplist => \@n } };
105         PublicInbox::IMAPD::refresh_inboxlist($self->{imapd});
106         my $res = PublicInbox::IMAP::cmd_list($self, 'tag', 'x', '%');
107         is(scalar($$res =~ tr/\n/\n/), 2, 'only one result');
108         like($$res, qr/ x\r\ntag OK/, 'saw expected');
109         $res = PublicInbox::IMAP::cmd_list($self, 'tag', 'x.', '%');
110         is(scalar($$res =~ tr/\n/\n/), 3, 'only one result');
111         is(scalar(my @x = ($$res =~ m/ x\.[zy]\r\n/g)), 2, 'match expected');
112
113         $res = PublicInbox::IMAP::cmd_list($self, 't', 'x.(?{die "RCE"})', '%');
114         like($$res, qr/\At OK /, 'refname does not match attempted RCE');
115         $res = PublicInbox::IMAP::cmd_list($self, 't', '', '(?{die "RCE"})%');
116         like($$res, qr/\At OK /, 'wildcard does not match attempted RCE');
117 }
118
119 if ($ENV{TEST_BENCHMARK}) {
120         use Benchmark qw(:all);
121         my @n = map { { newsgroup => "inbox.comp.foo.bar.$_" } } (0..50000);
122         push @n, map { { newsgroup => "xobni.womp.foo.bar.$_" } } (0..50000);
123         my $self = { imapd => { grouplist => \@n } };
124         PublicInbox::IMAPD::refresh_inboxlist($self->{imapd});
125
126         my $n = scalar @n;
127         open my $null, '>', '/dev/null' or die;
128         my $ds = { sock => $null };
129         my $nr = 200;
130         diag "starting benchmark...";
131         my $t = timeit(1, sub {
132                 for (0..$nr) {
133                         my $res = PublicInbox::IMAP::cmd_list($self, 'tag',
134                                                                 '', '*');
135                         PublicInbox::DS::write($ds, $res);
136                 }
137         });
138         diag timestr($t). "list all for $n inboxes $nr times";
139         $nr = 20;
140         $t = timeit(1, sub {
141                 for (0..$nr) {
142                         my $res = PublicInbox::IMAP::cmd_list($self, 'tag',
143                                                                 'inbox.', '%');
144                         PublicInbox::DS::write($ds, $res);
145                 }
146         });
147         diag timestr($t). "list partial for $n inboxes $nr times";
148 }
149
150 my $ret = $mic->search('all') or BAIL_OUT "SEARCH FAIL $@";
151 is_deeply($ret, [ 1 ], 'search all works');
152 $ret = $mic->search('uid 1') or BAIL_OUT "SEARCH FAIL $@";
153 is_deeply($ret, [ 1 ], 'search UID 1 works');
154 $ret = $mic->search('uid 1:1') or BAIL_OUT "SEARCH FAIL $@";
155 is_deeply($ret, [ 1 ], 'search UID 1:1 works');
156 $ret = $mic->search('uid 1:*') or BAIL_OUT "SEARCH FAIL $@";
157 is_deeply($ret, [ 1 ], 'search UID 1:* works');
158
159 is_deeply(scalar $mic->flags('1'), [], '->flags works');
160
161 for my $r ('1:*', '1') {
162         $ret = $mic->fetch_hash($r, 'RFC822') or BAIL_OUT "FETCH $@";
163         is_deeply([keys %$ret], [1]);
164         like($ret->{1}->{RFC822}, qr/\r\n\r\nThis is a test/, 'read full');
165
166         # ensure Mail::IMAPClient behaves
167         my $str = $mic->message_string($r) or BAIL_OUT "->message_string: $@";
168         is($str, $ret->{1}->{RFC822}, '->message_string works as expected');
169
170         my $sz = $mic->fetch_hash($r, 'RFC822.size') or BAIL_OUT "FETCH $@";
171         is($sz->{1}->{'RFC822.SIZE'}, length($ret->{1}->{RFC822}),
172                 'RFC822.SIZE');
173
174         $ret = $mic->fetch_hash($r, 'RFC822.HEADER') or BAIL_OUT "FETCH $@";
175         is_deeply([keys %$ret], [1]);
176         like($ret->{1}->{'RFC822.HEADER'},
177                 qr/^Message-ID: <testmessage\@example\.com>/ms, 'read header');
178
179         $ret = $mic->fetch_hash($r, 'INTERNALDATE') or BAIL_OUT "FETCH $@";
180         is($ret->{1}->{'INTERNALDATE'}, '01-Jan-1970 00:00:00 +0000',
181                 'internaldate matches');
182         ok(!$mic->fetch_hash($r, 'INFERNALDATE'), 'bogus attribute fails');
183
184         my $envelope = $mic->get_envelope($r) or BAIL_OUT("get_envelope: $@");
185         is($envelope->{bcc}, 'NIL', 'empty bcc');
186         is($envelope->{messageid}, '<testmessage@example.com>', 'messageid');
187         is(scalar @{$envelope->{to}}, 1, 'one {to} header');
188         # *sigh* too much to verify...
189         #use Data::Dumper; diag Dumper($envelope);
190
191         $ret = $mic->fetch_hash($r, 'FLAGS') or BAIL_OUT "FETCH $@";
192         is_deeply($ret->{1}->{FLAGS}, '', 'no flags');
193
194         $ret = $mic->fetch_hash($r, 'BODY[1]') or BAIL_OUT "FETCH $@";
195         like($ret->{1}->{'BODY[1]'}, qr/\AThis is a test message/, 'BODY[1]');
196
197         $ret = $mic->fetch_hash($r, 'BODY[1]<1>') or BAIL_OUT "FETCH $@";
198         like($ret->{1}->{'BODY[1]<1>'}, qr/\Ahis is a test message/,
199                         'BODY[1]<1>');
200
201         $ret = $mic->fetch_hash($r, 'BODY[1]<2.3>') or BAIL_OUT "FETCH $@";
202         is($ret->{1}->{'BODY[1]<2>'}, "is ", 'BODY[1]<2.3>');
203         $ret = $mic->bodypart_string($r, 1, 3, 2) or
204                                         BAIL_OUT "bodypart_string $@";
205         is($ret, "is ", 'bodypart string');
206
207         $ret = $mic->fetch_hash($r, 'BODY[HEADER.FIELDS.NOT (Message-ID)]')
208                 or BAIL_OUT "FETCH $@";
209         $ret = $ret->{1}->{'BODY[HEADER.FIELDS.NOT (MESSAGE-ID)]'};
210         unlike($ret, qr/message-id/i, 'Message-ID excluded');
211         like($ret, qr/\r\n\r\n\z/s, 'got header end');
212
213         $ret = $mic->fetch_hash($r, 'BODY[HEADER.FIELDS (Message-ID)]')
214                 or BAIL_OUT "FETCH $@";
215         is($ret->{1}->{'BODY[HEADER.FIELDS (MESSAGE-ID)]'},
216                 'Message-ID: <testmessage@example.com>'."\r\n\r\n",
217                 'got only Message-ID');
218
219         my $bs = $mic->get_bodystructure($r) or BAIL_OUT("bodystructure: $@");
220         ok($bs, 'got a bodystructure');
221         is(lc($bs->bodytype), 'text', '->bodytype');
222         is(lc($bs->bodyenc), '8bit', '->bodyenc');
223 }
224
225 # Mail::IMAPClient ->compress creates cyclic reference:
226 # https://rt.cpan.org/Ticket/Display.html?id=132654
227 my $compress_logout = sub {
228         my ($c) = @_;
229         ok($c->logout, 'logout ok after ->compress');
230         # all documented in Mail::IMAPClient manpage:
231         for (qw(Readmoremethod Readmethod Prewritemethod)) {
232                 $c->$_(undef);
233         }
234 };
235
236 is_deeply([$mic->has_capability('COMPRESS')], ['DEFLATE'], 'deflate cap');
237 ok($mic->compress, 'compress enabled');
238 $compress_logout->($mic);
239
240 my $have_inotify = eval { require Linux::Inotify2; 1 };
241
242 my $pi_config = PublicInbox::Config->new;
243 $pi_config->each_inbox(sub {
244         my ($ibx) = @_;
245         my $env = { ORIGINAL_RECIPIENT => $ibx->{-primary_address} };
246         my $name = $ibx->{name};
247         my $ng = $ibx->{newsgroup};
248         my $mic = Mail::IMAPClient->new(%mic_opt);
249         ok($mic && $mic->login && $mic->IsAuthenticated, "authed $name");
250         my $uidnext = $mic->uidnext($ng); # we'll fetch BODYSTRUCTURE on this
251         ok($uidnext, 'got uidnext for later fetch');
252         is_deeply([$mic->has_capability('IDLE')], ['IDLE'], "IDLE capa $name");
253         ok(!$mic->idle, "IDLE fails w/o SELECT/EXAMINE $name");
254         ok($mic->examine($ng), "EXAMINE $ng succeeds");
255         ok(my $idle_tag = $mic->idle, "IDLE succeeds on $ng");
256
257         open(my $fh, '<', 't/data/message_embed.eml') or BAIL_OUT("open: $!");
258         run_script(['-mda', '--no-precheck'], $env, { 0 => $fh }) or
259                 BAIL_OUT('-mda delivery');
260         my $t0 = Time::HiRes::time();
261         ok(my @res = $mic->idle_data(11), "IDLE succeeds on $ng");
262         is(grep(/\A\* [0-9] EXISTS\b/, @res), 1, 'got EXISTS message');
263         ok((Time::HiRes::time() - $t0) < 10, 'IDLE client notified');
264
265         my (@ino_info, $ino_fdinfo);
266         SKIP: {
267                 skip 'no inotify support', 1 unless $have_inotify;
268                 skip 'missing /proc/$PID/fd', 1 if !-d "/proc/$td->{pid}/fd";
269                 my @ino = grep {
270                         readlink($_) =~ /\binotify\b/
271                 } glob("/proc/$td->{pid}/fd/*");
272                 is(scalar(@ino), 1, 'only one inotify FD');
273                 my $ino_fd = (split('/', $ino[0]))[-1];
274                 $ino_fdinfo = "/proc/$td->{pid}/fdinfo/$ino_fd";
275                 if (open my $fh, '<', $ino_fdinfo) {
276                         local $/ = "\n";
277                         @ino_info = grep(/^inotify wd:/, <$fh>);
278                         ok(scalar(@ino_info), 'inotify has watches');
279                 } else {
280                         skip "$ino_fdinfo missing: $!", 1;
281                 }
282         };
283
284         # ensure IDLE persists across HUP, w/o extra watches or FDs
285         $td->kill('HUP') or BAIL_OUT "failed to kill -imapd: $!";
286         SKIP: {
287                 skip 'no inotify fdinfo (or support)', 2 if !@ino_info;
288                 my (@tmp, %prev);
289                 local $/ = "\n";
290                 my $end = time + 5;
291                 until (time > $end) {
292                         select undef, undef, undef, 0.01;
293                         open my $fh, '<', $ino_fdinfo or
294                                                 BAIL_OUT "$ino_fdinfo: $!";
295                         %prev = map { $_ => 1 } @ino_info;
296                         @tmp = grep(/^inotify wd:/, <$fh>);
297                         if (scalar(@tmp) == scalar(@ino_info)) {
298                                 delete @prev{@tmp};
299                                 last if scalar(keys(%prev)) == @ino_info;
300                         }
301                 }
302                 is(scalar @tmp, scalar @ino_info,
303                         'old inotify watches replaced');
304                 is(scalar keys %prev, scalar @ino_info,
305                         'no previous watches overlap');
306         };
307
308         open($fh, '<', 't/data/0001.patch') or BAIL_OUT("open: $!");
309         run_script(['-mda', '--no-precheck'], $env, { 0 => $fh }) or
310                 BAIL_OUT('-mda delivery');
311         $t0 = Time::HiRes::time();
312         ok(@res = $mic->idle_data(11), "IDLE succeeds on $ng after HUP");
313         is(grep(/\A\* [0-9] EXISTS\b/, @res), 1, 'got EXISTS message');
314         ok((Time::HiRes::time() - $t0) < 10, 'IDLE client notified');
315         ok($mic->done($idle_tag), 'IDLE DONE');
316         my $bs = $mic->get_bodystructure($uidnext);
317         ok($bs, 'BODYSTRUCTURE ok for deeply nested');
318         $ret = $mic->fetch_hash($uidnext, 'BODY') or BAIL_OUT "FETCH $@";
319         ok($ret->{$uidnext}->{BODY}, 'got something in BODY');
320
321         # this matches dovecot behavior
322         $ret = $mic->fetch_hash($uidnext, 'BODY[1]') or BAIL_OUT "FETCH $@";
323         is($ret->{$uidnext}->{'BODY[1]'},
324                 "testing embedded message harder\r\n", 'BODY[1]');
325         $ret = $mic->fetch_hash($uidnext, 'BODY[2]') or BAIL_OUT "FETCH $@";
326         like($ret->{$uidnext}->{'BODY[2]'},
327                 qr/\ADate: Sat, 18 Apr 2020 22:20:20 /, 'BODY[2]');
328
329         $ret = $mic->fetch_hash($uidnext, 'BODY[2.1.1]') or BAIL_OUT "FETCH $@";
330         is($ret->{$uidnext}->{'BODY[2.1.1]'},
331                 "testing embedded message\r\n", 'BODY[2.1.1]');
332
333         $ret = $mic->fetch_hash($uidnext, 'BODY[2.1.2]') or BAIL_OUT "FETCH $@";
334         like($ret->{$uidnext}->{'BODY[2.1.2]'}, qr/\AFrom: /,
335                 'BODY[2.1.2] tip matched');
336         like($ret->{$uidnext}->{'BODY[2.1.2]'},
337                  # trailing CRLF may vary depending on MIME parser
338                  qr/done_testing;(?:\r\n){1,2}\z/,
339                 'BODY[2.1.2] tail matched');
340
341         $ret = $mic->fetch_hash($uidnext, 'BODY[2.HEADER]') or
342                                                 BAIL_OUT "2.HEADER $@";
343         like($ret->{$uidnext}->{'BODY[2.HEADER]'},
344                 qr/\ADate: Sat, 18 Apr 2020 22:20:20 /,
345                 '2.HEADER of message/rfc822');
346
347         $ret = $mic->fetch_hash($uidnext, 'BODY[2.MIME]') or
348                 BAIL_OUT "2.MIME $@";
349         is($ret->{$uidnext}->{'BODY[2.MIME]'}, <<EOF, 'BODY[2.MIME]');
350 Content-Type: message/rfc822\r
351 Content-Disposition: attachment; filename="embed2x\.eml"\r
352 \r
353 EOF
354 }); # each_inbox
355
356 $td->kill;
357 $td->join;
358 is($?, 0, 'no error in exited process');
359 open my $fh, '<', $err or BAIL_OUT("open $err failed: $!");
360 my $eout = do { local $/; <$fh> };
361 unlike($eout, qr/wide/i, 'no Wide character warnings');
362
363 done_testing;