]> Sergey Matveev's repositories - public-inbox.git/blob - t/imapd.t
imapclient: wrapper for Mail::IMAPClient
[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 for my $r ('1:*', '1') {
121         $ret = $mic->fetch_hash($r, 'RFC822') or BAIL_OUT "FETCH $@";
122         is_deeply([keys %$ret], [1]);
123         like($ret->{1}->{RFC822}, qr/\r\n\r\nThis is a test/, 'read full');
124
125         # ensure Mail::IMAPClient behaves
126         my $str = $mic->message_string($r) or BAIL_OUT "->message_string: $@";
127         is($str, $ret->{1}->{RFC822}, '->message_string works as expected');
128
129         my $sz = $mic->fetch_hash($r, 'RFC822.size') or BAIL_OUT "FETCH $@";
130         is($sz->{1}->{'RFC822.SIZE'}, length($ret->{1}->{RFC822}),
131                 'RFC822.SIZE');
132
133         $ret = $mic->fetch_hash($r, 'RFC822.HEADER') or BAIL_OUT "FETCH $@";
134         is_deeply([keys %$ret], [1]);
135         like($ret->{1}->{'RFC822.HEADER'},
136                 qr/^Message-ID: <testmessage\@example\.com>/ms, 'read header');
137
138         $ret = $mic->fetch_hash($r, 'INTERNALDATE') or BAIL_OUT "FETCH $@";
139         is($ret->{1}->{'INTERNALDATE'}, '01-Jan-1970 00:00:00 +0000',
140                 'internaldate matches');
141         ok(!$mic->fetch_hash($r, 'INFERNALDATE'), 'bogus attribute fails');
142
143         my $envelope = $mic->get_envelope($r) or BAIL_OUT("get_envelope: $@");
144         is($envelope->{bcc}, 'NIL', 'empty bcc');
145         is($envelope->{messageid}, '<testmessage@example.com>', 'messageid');
146         is(scalar @{$envelope->{to}}, 1, 'one {to} header');
147         # *sigh* too much to verify...
148         #use Data::Dumper; diag Dumper($envelope);
149
150         $ret = $mic->fetch_hash($r, 'FLAGS') or BAIL_OUT "FETCH $@";
151         is_deeply($ret->{1}->{FLAGS}, '', 'no flags');
152
153         $ret = $mic->fetch_hash($r, 'BODY[1]') or BAIL_OUT "FETCH $@";
154         like($ret->{1}->{'BODY[1]'}, qr/\AThis is a test message/, 'BODY[1]');
155
156         $ret = $mic->fetch_hash($r, 'BODY[1]<1>') or BAIL_OUT "FETCH $@";
157         like($ret->{1}->{'BODY[1]<1>'}, qr/\Ahis is a test message/,
158                         'BODY[1]<1>');
159
160         $ret = $mic->fetch_hash($r, 'BODY[1]<2.3>') or BAIL_OUT "FETCH $@";
161         is($ret->{1}->{'BODY[1]<2>'}, "is ", 'BODY[1]<2.3>');
162         $ret = $mic->bodypart_string($r, 1, 3, 2) or
163                                         BAIL_OUT "bodypart_string $@";
164         is($ret, "is ", 'bodypart string');
165
166         $ret = $mic->fetch_hash($r, 'BODY[HEADER.FIELDS.NOT (Message-ID)]')
167                 or BAIL_OUT "FETCH $@";
168         $ret = $ret->{1}->{'BODY[HEADER.FIELDS.NOT (MESSAGE-ID)]'};
169         unlike($ret, qr/message-id/i, 'Message-ID excluded');
170         like($ret, qr/\r\n\r\n\z/s, 'got header end');
171
172         $ret = $mic->fetch_hash($r, 'BODY[HEADER.FIELDS (Message-ID)]')
173                 or BAIL_OUT "FETCH $@";
174         is($ret->{1}->{'BODY[HEADER.FIELDS (MESSAGE-ID)]'},
175                 'Message-ID: <testmessage@example.com>'."\r\n\r\n",
176                 'got only Message-ID');
177
178         my $bs = $mic->get_bodystructure($r) or BAIL_OUT("bodystructure: $@");
179         ok($bs, 'got a bodystructure');
180         is(lc($bs->bodytype), 'text', '->bodytype');
181         is(lc($bs->bodyenc), '8bit', '->bodyenc');
182 }
183
184 is_deeply([$mic->has_capability('COMPRESS')], ['DEFLATE'], 'deflate cap');
185 SKIP: {
186         skip 'Mail::IMAPClient too old for ->compress', 2 if !$can_compress;
187         my $c = $imap_client->new(%mic_opt);
188         ok($c && $c->compress, 'compress enabled');
189         ok($c->examine('inbox.i1'), 'EXAMINE succeeds after COMPRESS');
190         $ret = $c->search('uid 1:*') or BAIL_OUT "SEARCH FAIL $@";
191         is_deeply($ret, [ 1 ], 'search UID 1:* works after compression');
192 }
193
194 ok($mic->logout, 'logout works');
195
196 my $have_inotify = eval { require Linux::Inotify2; 1 };
197
198 my $pi_config = PublicInbox::Config->new;
199 $pi_config->each_inbox(sub {
200         my ($ibx) = @_;
201         my $env = { ORIGINAL_RECIPIENT => $ibx->{-primary_address} };
202         my $name = $ibx->{name};
203         my $ng = $ibx->{newsgroup};
204         my $mic = $imap_client->new(%mic_opt);
205         ok($mic && $mic->login && $mic->IsAuthenticated, "authed $name");
206         my $uidnext = $mic->uidnext($ng); # we'll fetch BODYSTRUCTURE on this
207         ok($uidnext, 'got uidnext for later fetch');
208         is_deeply([$mic->has_capability('IDLE')], ['IDLE'], "IDLE capa $name");
209         ok(!$mic->idle, "IDLE fails w/o SELECT/EXAMINE $name");
210         ok($mic->examine($ng), "EXAMINE $ng succeeds");
211         ok(my $idle_tag = $mic->idle, "IDLE succeeds on $ng");
212
213         open(my $fh, '<', 't/data/message_embed.eml') or BAIL_OUT("open: $!");
214         run_script(['-mda', '--no-precheck'], $env, { 0 => $fh }) or
215                 BAIL_OUT('-mda delivery');
216         my $t0 = Time::HiRes::time();
217         ok(my @res = $mic->idle_data(11), "IDLE succeeds on $ng");
218         is(grep(/\A\* [0-9] EXISTS\b/, @res), 1, 'got EXISTS message');
219         ok((Time::HiRes::time() - $t0) < 10, 'IDLE client notified');
220
221         my (@ino_info, $ino_fdinfo);
222         SKIP: {
223                 skip 'no inotify support', 1 unless $have_inotify;
224                 skip 'missing /proc/$PID/fd', 1 if !-d "/proc/$td->{pid}/fd";
225                 my @ino = grep {
226                         readlink($_) =~ /\binotify\b/
227                 } glob("/proc/$td->{pid}/fd/*");
228                 is(scalar(@ino), 1, 'only one inotify FD');
229                 my $ino_fd = (split('/', $ino[0]))[-1];
230                 $ino_fdinfo = "/proc/$td->{pid}/fdinfo/$ino_fd";
231                 if (open my $fh, '<', $ino_fdinfo) {
232                         local $/ = "\n";
233                         @ino_info = grep(/^inotify wd:/, <$fh>);
234                         ok(scalar(@ino_info), 'inotify has watches');
235                 } else {
236                         skip "$ino_fdinfo missing: $!", 1;
237                 }
238         };
239
240         # ensure IDLE persists across HUP, w/o extra watches or FDs
241         $td->kill('HUP') or BAIL_OUT "failed to kill -imapd: $!";
242         SKIP: {
243                 skip 'no inotify fdinfo (or support)', 2 if !@ino_info;
244                 my (@tmp, %prev);
245                 local $/ = "\n";
246                 my $end = time + 5;
247                 until (time > $end) {
248                         select undef, undef, undef, 0.01;
249                         open my $fh, '<', $ino_fdinfo or
250                                                 BAIL_OUT "$ino_fdinfo: $!";
251                         %prev = map { $_ => 1 } @ino_info;
252                         @tmp = grep(/^inotify wd:/, <$fh>);
253                         if (scalar(@tmp) == scalar(@ino_info)) {
254                                 delete @prev{@tmp};
255                                 last if scalar(keys(%prev)) == @ino_info;
256                         }
257                 }
258                 is(scalar @tmp, scalar @ino_info,
259                         'old inotify watches replaced');
260                 is(scalar keys %prev, scalar @ino_info,
261                         'no previous watches overlap');
262         };
263
264         open($fh, '<', 't/data/0001.patch') or BAIL_OUT("open: $!");
265         run_script(['-mda', '--no-precheck'], $env, { 0 => $fh }) or
266                 BAIL_OUT('-mda delivery');
267         $t0 = Time::HiRes::time();
268         ok(@res = $mic->idle_data(11), "IDLE succeeds on $ng after HUP");
269         is(grep(/\A\* [0-9] EXISTS\b/, @res), 1, 'got EXISTS message');
270         ok((Time::HiRes::time() - $t0) < 10, 'IDLE client notified');
271         ok($mic->done($idle_tag), 'IDLE DONE');
272         my $bs = $mic->get_bodystructure($uidnext);
273         ok($bs, 'BODYSTRUCTURE ok for deeply nested');
274         $ret = $mic->fetch_hash($uidnext, 'BODY') or BAIL_OUT "FETCH $@";
275         ok($ret->{$uidnext}->{BODY}, 'got something in BODY');
276
277         # this matches dovecot behavior
278         $ret = $mic->fetch_hash($uidnext, 'BODY[1]') or BAIL_OUT "FETCH $@";
279         is($ret->{$uidnext}->{'BODY[1]'},
280                 "testing embedded message harder\r\n", 'BODY[1]');
281         $ret = $mic->fetch_hash($uidnext, 'BODY[2]') or BAIL_OUT "FETCH $@";
282         like($ret->{$uidnext}->{'BODY[2]'},
283                 qr/\ADate: Sat, 18 Apr 2020 22:20:20 /, 'BODY[2]');
284
285         $ret = $mic->fetch_hash($uidnext, 'BODY[2.1.1]') or BAIL_OUT "FETCH $@";
286         is($ret->{$uidnext}->{'BODY[2.1.1]'},
287                 "testing embedded message\r\n", 'BODY[2.1.1]');
288
289         $ret = $mic->fetch_hash($uidnext, 'BODY[2.1.2]') or BAIL_OUT "FETCH $@";
290         like($ret->{$uidnext}->{'BODY[2.1.2]'}, qr/\AFrom: /,
291                 'BODY[2.1.2] tip matched');
292         like($ret->{$uidnext}->{'BODY[2.1.2]'},
293                  # trailing CRLF may vary depending on MIME parser
294                  qr/done_testing;(?:\r\n){1,2}\z/,
295                 'BODY[2.1.2] tail matched');
296
297         $ret = $mic->fetch_hash("1:$uidnext", 'BODY[2.HEADER]') or
298                                                 BAIL_OUT "2.HEADER $@";
299         like($ret->{$uidnext}->{'BODY[2.HEADER]'},
300                 qr/\ADate: Sat, 18 Apr 2020 22:20:20 /,
301                 '2.HEADER of message/rfc822');
302
303         $ret = $mic->fetch_hash($uidnext, 'BODY[2.MIME]') or
304                 BAIL_OUT "2.MIME $@";
305         is($ret->{$uidnext}->{'BODY[2.MIME]'}, <<EOF, 'BODY[2.MIME]');
306 Content-Type: message/rfc822\r
307 Content-Disposition: attachment; filename="embed2x\.eml"\r
308 \r
309 EOF
310 }); # each_inbox
311
312 # message sequence numbers :<
313 is($mic->Uid(0), 0, 'disable UID on '.ref($mic));
314 ok($mic->reconnect, 'reconnected');
315 $ret = $mic->fetch_hash('1,2:3', 'RFC822') or BAIL_OUT "FETCH $@";
316 is(scalar keys %$ret, 3, 'got all 3 messages with comma-separated sequence');
317 $ret = $mic->fetch_hash('1:*', 'RFC822') or BAIL_OUT "FETCH $@";
318 is(scalar keys %$ret, 3, 'got all 3 messages');
319 {
320         my $rdr = { 0 => \($ret->{1}->{RFC822}) };
321         my $env = { HOME => $ENV{HOME} };
322         my @cmd = qw(-learn rm --all);
323         run_script(\@cmd, $env, $rdr) or BAIL_OUT('-learn rm');
324 }
325 my $r2 = $mic->fetch_hash('1:*', 'BODY.PEEK[]') or BAIL_OUT "FETCH $@";
326 is(scalar keys %$r2, 3, 'still got all 3 messages');
327 like($r2->{1}->{'BODY[]'}, qr/dummy message #1/, 'got dummy message 1');
328 is($r2->{2}->{'BODY[]'}, $ret->{2}->{RFC822}, 'message 2 unchanged');
329 is($r2->{3}->{'BODY[]'}, $ret->{3}->{RFC822}, 'message 3 unchanged');
330 $r2 = $mic->fetch_hash(2, 'BODY.PEEK[HEADER.FIELDS (message-id)]')
331                         or BAIL_OUT "FETCH $@";
332 is($r2->{2}->{'BODY[HEADER.FIELDS (MESSAGE-ID)]'},
333         'Message-ID: <20200418222508.GA13918@dcvr>'."\r\n\r\n",
334         'BODY.PEEK[HEADER.FIELDS ...] drops .PEEK');
335 ok($mic->close, 'CLOSE works');
336 ok(!$mic->close, 'CLOSE not idempotent');
337 ok($mic->logout, 'logged out');
338
339 $td->kill;
340 $td->join;
341 is($?, 0, 'no error in exited process');
342 open my $fh, '<', $err or BAIL_OUT("open $err failed: $!");
343 my $eout = do { local $/; <$fh> };
344 unlike($eout, qr/wide/i, 'no Wide character warnings');
345
346 done_testing;