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