]> Sergey Matveev's repositories - public-inbox.git/blob - t/imapd.t
imap: support fetch for BODYSTRUCTURE and BODY
[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         my $bs = $mic->get_bodystructure($r) or BAIL_OUT("bodystructure: $@");
195         ok($bs, 'got a bodystructure');
196         is(lc($bs->bodytype), 'text', '->bodytype');
197         is(lc($bs->bodyenc), '8bit', '->bodyenc');
198 }
199
200 # Mail::IMAPClient ->compress creates cyclic reference:
201 # https://rt.cpan.org/Ticket/Display.html?id=132654
202 my $compress_logout = sub {
203         my ($c) = @_;
204         ok($c->logout, 'logout ok after ->compress');
205         # all documented in Mail::IMAPClient manpage:
206         for (qw(Readmoremethod Readmethod Prewritemethod)) {
207                 $c->$_(undef);
208         }
209 };
210
211 is_deeply([$mic->has_capability('COMPRESS')], ['DEFLATE'], 'deflate cap');
212 ok($mic->compress, 'compress enabled');
213 $compress_logout->($mic);
214
215 my $have_inotify = eval { require Linux::Inotify2; 1 };
216
217 my $pi_config = PublicInbox::Config->new;
218 $pi_config->each_inbox(sub {
219         my ($ibx) = @_;
220         my $env = { ORIGINAL_RECIPIENT => $ibx->{-primary_address} };
221         my $name = $ibx->{name};
222         my $ng = $ibx->{newsgroup};
223         my $mic = Mail::IMAPClient->new(%mic_opt);
224         ok($mic && $mic->login && $mic->IsAuthenticated, "authed $name");
225         my $uidnext = $mic->uidnext($ng); # we'll fetch BODYSTRUCTURE on this
226         ok($uidnext, 'got uidnext for later fetch');
227         is_deeply([$mic->has_capability('IDLE')], ['IDLE'], "IDLE capa $name");
228         ok(!$mic->idle, "IDLE fails w/o SELECT/EXAMINE $name");
229         ok($mic->examine($ng), "EXAMINE $ng succeeds");
230         ok(my $idle_tag = $mic->idle, "IDLE succeeds on $ng");
231
232         open(my $fh, '<', 't/data/message_embed.eml') or BAIL_OUT("open: $!");
233         run_script(['-mda', '--no-precheck'], $env, { 0 => $fh }) or
234                 BAIL_OUT('-mda delivery');
235         my $t0 = Time::HiRes::time();
236         ok(my @res = $mic->idle_data(11), "IDLE succeeds on $ng");
237         is(grep(/\A\* [0-9] EXISTS\b/, @res), 1, 'got EXISTS message');
238         ok((Time::HiRes::time() - $t0) < 10, 'IDLE client notified');
239
240         my (@ino_info, $ino_fdinfo);
241         SKIP: {
242                 skip 'no inotify support', 1 unless $have_inotify;
243                 skip 'missing /proc/$PID/fd', 1 if !-d "/proc/$td->{pid}/fd";
244                 my @ino = grep {
245                         readlink($_) =~ /\binotify\b/
246                 } glob("/proc/$td->{pid}/fd/*");
247                 is(scalar(@ino), 1, 'only one inotify FD');
248                 my $ino_fd = (split('/', $ino[0]))[-1];
249                 $ino_fdinfo = "/proc/$td->{pid}/fdinfo/$ino_fd";
250                 if (open my $fh, '<', $ino_fdinfo) {
251                         local $/ = "\n";
252                         @ino_info = grep(/^inotify wd:/, <$fh>);
253                         ok(scalar(@ino_info), 'inotify has watches');
254                 } else {
255                         skip "$ino_fdinfo missing: $!", 1;
256                 }
257         };
258
259         # ensure IDLE persists across HUP, w/o extra watches or FDs
260         $td->kill('HUP') or BAIL_OUT "failed to kill -imapd: $!";
261         SKIP: {
262                 skip 'no inotify fdinfo (or support)', 2 if !@ino_info;
263                 my (@tmp, %prev);
264                 local $/ = "\n";
265                 my $end = time + 5;
266                 until (time > $end) {
267                         select undef, undef, undef, 0.01;
268                         open my $fh, '<', $ino_fdinfo or
269                                                 BAIL_OUT "$ino_fdinfo: $!";
270                         %prev = map { $_ => 1 } @ino_info;
271                         @tmp = grep(/^inotify wd:/, <$fh>);
272                         if (scalar(@tmp) == scalar(@ino_info)) {
273                                 delete @prev{@tmp};
274                                 last if scalar(keys(%prev)) == @ino_info;
275                         }
276                 }
277                 is(scalar @tmp, scalar @ino_info,
278                         'old inotify watches replaced');
279                 is(scalar keys %prev, scalar @ino_info,
280                         'no previous watches overlap');
281         };
282
283         open($fh, '<', 't/data/0001.patch') or BAIL_OUT("open: $!");
284         run_script(['-mda', '--no-precheck'], $env, { 0 => $fh }) or
285                 BAIL_OUT('-mda delivery');
286         $t0 = Time::HiRes::time();
287         ok(@res = $mic->idle_data(11), "IDLE succeeds on $ng after HUP");
288         is(grep(/\A\* [0-9] EXISTS\b/, @res), 1, 'got EXISTS message');
289         ok((Time::HiRes::time() - $t0) < 10, 'IDLE client notified');
290         ok($mic->done($idle_tag), 'IDLE DONE');
291         my $bs = $mic->get_bodystructure($uidnext);
292         ok($bs, 'BODYSTRUCTURE ok for deeply nested');
293         $ret = $mic->fetch_hash($uidnext, 'BODY') or BAIL_OUT "FETCH $@";
294         ok($ret->{$uidnext}->{BODY}, 'got something in BODY');
295 });
296
297 $td->kill;
298 $td->join;
299 is($?, 0, 'no error in exited process');
300 open my $fh, '<', $err or BAIL_OUT("open $err failed: $!");
301 my $eout = do { local $/; <$fh> };
302 unlike($eout, qr/wide/i, 'no Wide character warnings');
303
304 done_testing;