2 # Copyright (C) 2020 all contributors <meta@public-inbox.org>
3 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
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));
12 my $level = '-Lbasic';
14 require_mods('Search::Xapian', 1);
19 push(@V, 2) if require_git('2.6', 1);
21 my ($tmpdir, $for_destroy) = tmpdir();
22 my $home = "$tmpdir/home";
23 local $ENV{HOME} = $home;
26 my $addr = "i$V\@example.com";
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");
37 xsys(qw(git config), "--file=$ENV{HOME}/.public-inbox/config",
38 'publicinboxmda.spamcheck', 'none') == 0 or
39 BAIL_OUT("config: $?");
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');
46 run_script(['-index', $inboxdir]) or BAIL_OUT("index $?");
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: $?");
55 Server => $sock->sockhost,
56 Port => $sock->sockport,
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');
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');
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');
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');
92 like($raw[0], qr/^\* LIST \(.*?\) "\." 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/,
100 like($raw[-1], qr/^\S+ OK /, 'response ended with OK');
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');
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');
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});
127 open my $null, '>', '/dev/null' or die;
128 my $ds = { sock => $null };
130 diag "starting benchmark...";
131 my $t = timeit(1, sub {
133 my $res = PublicInbox::IMAP::cmd_list($self, 'tag',
135 PublicInbox::DS::write($ds, $res);
138 diag timestr($t). "list all for $n inboxes $nr times";
142 my $res = PublicInbox::IMAP::cmd_list($self, 'tag',
144 PublicInbox::DS::write($ds, $res);
147 diag timestr($t). "list partial for $n inboxes $nr times";
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');
159 is_deeply(scalar $mic->flags('1'), [], '->flags works');
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');
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');
170 my $sz = $mic->fetch_hash($r, 'RFC822.size') or BAIL_OUT "FETCH $@";
171 is($sz->{1}->{'RFC822.SIZE'}, length($ret->{1}->{RFC822}),
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');
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');
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);
191 $ret = $mic->fetch_hash($r, 'FLAGS') or BAIL_OUT "FETCH $@";
192 is_deeply($ret->{1}->{FLAGS}, '', 'no flags');
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]');
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/,
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');
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');
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');
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');
225 # Mail::IMAPClient ->compress creates cyclic reference:
226 # https://rt.cpan.org/Ticket/Display.html?id=132654
227 my $compress_logout = sub {
229 ok($c->logout, 'logout ok after ->compress');
230 # all documented in Mail::IMAPClient manpage:
231 for (qw(Readmoremethod Readmethod Prewritemethod)) {
236 is_deeply([$mic->has_capability('COMPRESS')], ['DEFLATE'], 'deflate cap');
237 ok($mic->compress, 'compress enabled');
238 $compress_logout->($mic);
240 my $have_inotify = eval { require Linux::Inotify2; 1 };
242 my $pi_config = PublicInbox::Config->new;
243 $pi_config->each_inbox(sub {
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");
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');
265 my (@ino_info, $ino_fdinfo);
267 skip 'no inotify support', 1 unless $have_inotify;
268 skip 'missing /proc/$PID/fd', 1 if !-d "/proc/$td->{pid}/fd";
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) {
277 @ino_info = grep(/^inotify wd:/, <$fh>);
278 ok(scalar(@ino_info), 'inotify has watches');
280 skip "$ino_fdinfo missing: $!", 1;
284 # ensure IDLE persists across HUP, w/o extra watches or FDs
285 $td->kill('HUP') or BAIL_OUT "failed to kill -imapd: $!";
287 skip 'no inotify fdinfo (or support)', 2 if !@ino_info;
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)) {
299 last if scalar(keys(%prev)) == @ino_info;
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');
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');
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]');
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]');
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');
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');
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
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');