]> Sergey Matveev's repositories - public-inbox.git/blob - t/imapd.t
f743bf06852176616b81f3825ee35e38d052f12a
[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         Email::Address::XS||Mail::Address Parse::RecDescent));
13 my $imap_client = 'Mail::IMAPClient';
14 my $can_compress = $imap_client->can('compress');
15 if ($can_compress) { # hope this gets fixed upstream, soon
16         require PublicInbox::IMAPClient;
17         $imap_client = 'PublicInbox::IMAPClient';
18 }
19
20 require_ok 'PublicInbox::IMAP';
21 my $first_range = '0';
22
23 my $level = 'basic';
24 SKIP: {
25         require_mods('Search::Xapian', 1);
26         $level = 'medium';
27 };
28
29 my @V = (1);
30 push(@V, 2) if require_git('2.6', 1);
31
32 my ($tmpdir, $for_destroy) = tmpdir();
33 my $home = "$tmpdir/home";
34 local $ENV{HOME} = $home;
35
36 for my $V (@V) {
37         my $addr = "i$V\@example.com";
38         my $name = "i$V";
39         my $url = "http://example.com/i$V";
40         my $inboxdir = "$tmpdir/$name";
41         my $folder = "inbox.i$V";
42         my $cmd = ['-init', "-V$V", "-L$level", "--ng=$folder",
43                 $name, $inboxdir, $url, $addr];
44         run_script($cmd) or BAIL_OUT("init $name");
45         if ($V == 1) {
46                 xsys(qw(git config), "--file=$ENV{HOME}/.public-inbox/config",
47                         'publicinboxmda.spamcheck', 'none') == 0 or
48                         BAIL_OUT("config: $?");
49         }
50         open(my $fh, '<', 't/utf8.eml') or BAIL_OUT("open t/utf8.eml: $!");
51         my $env = { ORIGINAL_RECIPIENT => $addr };
52         run_script(['-mda', '--no-precheck'], $env, { 0 => $fh }) or
53                 BAIL_OUT('-mda delivery');
54         if ($V == 1) {
55                 run_script(['-index', $inboxdir]) or BAIL_OUT("index $?");
56         }
57 }
58 my $sock = tcp_server();
59 my $err = "$tmpdir/stderr.log";
60 my $out = "$tmpdir/stdout.log";
61 my $cmd = [ '-imapd', '-W0', "--stdout=$out", "--stderr=$err" ];
62 my $td = start_script($cmd, undef, { 3 => $sock }) or BAIL_OUT("-imapd: $?");
63 my %mic_opt = (
64         Server => $sock->sockhost,
65         Port => $sock->sockport,
66         Uid => 1,
67 );
68 my $mic = $imap_client->new(%mic_opt);
69 my $pre_login_capa = $mic->capability;
70 is(grep(/\AAUTH=ANONYMOUS\z/, @$pre_login_capa), 1,
71         'AUTH=ANONYMOUS advertised pre-login');
72
73 $mic->User('lorelei');
74 $mic->Password('Hunter2');
75 ok($mic->login && $mic->IsAuthenticated, 'LOGIN works');
76 my $post_login_capa = $mic->capability;
77 ok(join("\n", @$pre_login_capa) ne join("\n", @$post_login_capa),
78         'got different capabilities post-login');
79
80 $mic_opt{Authmechanism} = 'ANONYMOUS';
81 $mic_opt{Authcallback} = sub { '' };
82 $mic = $imap_client->new(%mic_opt);
83 ok($mic && $mic->login && $mic->IsAuthenticated, 'AUTHENTICATE ANONYMOUS');
84 my $post_auth_anon_capa = $mic->capability;
85 is_deeply($post_auth_anon_capa, $post_login_capa,
86         'auth anon has same capabilities');
87 my $e;
88 ok($mic->noop, 'NOOP');
89 ok($mic->noop, 'NOOP (again)'); # for warnings
90 ok(!$mic->examine('foo') && ($e = $@), 'EXAMINE non-existent');
91 like($e, qr/\bNO\b/, 'got a NO on EXAMINE for non-existent');
92 ok(!$mic->select('foo') && ($e = $@), 'EXAMINE non-existent');
93 like($e, qr/\bNO\b/, 'got a NO on EXAMINE for non-existent');
94 my $mailbox1 = "inbox.i1.$first_range";
95 ok($mic->select('inbox.i1'), 'SELECT on parent succeeds');
96 ok($mic->noop, 'NOOP while selected');
97 ok($mic->noop, 'NOOP again while selected'); # check warnings later
98 ok($mic->select($mailbox1), 'SELECT succeeds');
99 ok($mic->examine($mailbox1), 'EXAMINE succeeds');
100 my @raw = $mic->status($mailbox1, qw(Messages uidnext uidvalidity));
101 is(scalar(@raw), 2, 'got status response');
102 like($raw[0], qr/\A\*\x20STATUS\x20inbox\.i1\.$first_range\x20
103         \(MESSAGES\x20\d+\x20UIDNEXT\x20\d+\x20UIDVALIDITY\x20\d+\)\r\n/sx);
104 like($raw[1], qr/\A\S+ OK /, 'finished status response');
105
106 my @orig_list = @raw = $mic->list;
107 like($raw[0], qr/^\* LIST \(.*?\) "\." INBOX/,
108         'got an inbox');
109 like($raw[-1], qr/^\S+ OK /, 'response ended with OK');
110 is(scalar(@raw), scalar(@V) * 2 + 2, 'default LIST response');
111 @raw = $mic->list('', 'inbox.i1');
112 is(scalar(@raw), 2, 'limited LIST response');
113 like($raw[0], qr/^\* LIST \(.*?\) "\." INBOX/,
114                 'got an inbox.i1');
115 like($raw[-1], qr/^\S+ OK /, 'response ended with OK');
116
117 my $ret = $mic->search('all') or BAIL_OUT "SEARCH FAIL $@";
118 is_deeply($ret, [ 1 ], 'search all works');
119 $ret = $mic->search('uid 1') or BAIL_OUT "SEARCH FAIL $@";
120 is_deeply($ret, [ 1 ], 'search UID 1 works');
121 $ret = $mic->search('uid 1:1') or BAIL_OUT "SEARCH FAIL $@";
122 is_deeply($ret, [ 1 ], 'search UID 1:1 works');
123 $ret = $mic->search('uid 1:*') or BAIL_OUT "SEARCH FAIL $@";
124 is_deeply($ret, [ 1 ], 'search UID 1:* works');
125 $ret = $mic->search('DELETED') or BAIL_OUT "SEARCH FAIL $@";
126 is_deeply($ret, [], 'searching for DELETED returns nothing');
127
128 SKIP: {
129         skip 'Xapian missing', 8 if $level eq 'basic';
130         my $x = $mic->search(qw(smaller 99999));
131         is_deeply($x, [1], 'SMALLER works with Xapian (hit)');
132         $x = $mic->search(qw(smaller 9));
133         is_deeply($x, [], 'SMALLER works with Xapian (miss)');
134
135         $x = $mic->search(qw(larger 99999));
136         is_deeply($x, [], 'LARGER works with Xapian (miss)');
137         $x = $mic->search(qw(larger 9));
138         is_deeply($x, [1], 'LARGER works with Xapian (hit)');
139
140         $x = $mic->search(qw(HEADER Message-ID testmessage@example.com));
141         is_deeply($x, [1], 'HEADER Message-ID works');
142
143         $x = $mic->search(qw(DRAFT HEADER Message-ID testmessage@example.com));
144         is_deeply($x, [], 'impossible (DRAFT) key filters out match');
145
146         $x = $mic->search(qw(HEADER Message-ID miss));
147         is_deeply($x, [], 'HEADER Message-ID can miss');
148
149         my @q = qw[OR HEADER Message-ID testmessage@example.com
150                         (OR FROM Ryan (OR TO Joe CC Scott))];
151         $x = $mic->search(join(' ', @q));
152         is_deeply($x, [1], 'nested query works');
153 }
154
155 is_deeply(scalar $mic->flags('1'), [], '->flags works');
156 {
157         # RFC 3501 section 6.4.8 states:
158         # Also note that a UID range of 559:* always includes the
159         # UID of the last message in the mailbox, even if 559 is
160         # higher than any assigned UID value.
161         my $exp = $mic->fetch_hash(1, 'UID');
162         $ret = $mic->fetch_hash('559:*', 'UID');
163         is_deeply($ret, $exp, 'beginning range too big');
164         {
165                 my @w; # Mail::IMAPClient hits a warning via overload
166                 local $SIG{__WARN__} = sub { push @w, @_ };
167                 $ret = $mic->fetch_hash(my $r = '559:558', 'UID');
168                 is_deeply($ret, {}, "out-of-range UID FETCH $r");
169                 @w = grep(!/\boverload\.pm\b/, @w);
170                 is_deeply(\@w, [], 'no unexpected warning');
171         }
172         $ret = $mic->fetch_hash(my $r = '558:559', 'UID');
173         is_deeply($ret, {}, "out-of-range UID FETCH $r");
174 }
175
176 for my $r ('1:*', '1') {
177         $ret = $mic->fetch_hash($r, 'RFC822') or BAIL_OUT "FETCH $@";
178         is_deeply([keys %$ret], [1]);
179         like($ret->{1}->{RFC822}, qr/\r\n\r\nThis is a test/, 'read full');
180
181         # ensure Mail::IMAPClient behaves
182         my $str = $mic->message_string($r) or BAIL_OUT "->message_string: $@";
183         is($str, $ret->{1}->{RFC822}, '->message_string works as expected');
184
185         my $sz = $mic->fetch_hash($r, 'RFC822.size') or BAIL_OUT "FETCH $@";
186         is($sz->{1}->{'RFC822.SIZE'}, length($ret->{1}->{RFC822}),
187                 'RFC822.SIZE');
188
189         $ret = $mic->fetch_hash($r, 'RFC822.HEADER') or BAIL_OUT "FETCH $@";
190         is_deeply([keys %$ret], [1]);
191         like($ret->{1}->{'RFC822.HEADER'},
192                 qr/^Message-ID: <testmessage\@example\.com>/ms, 'read header');
193
194         $ret = $mic->fetch_hash($r, 'INTERNALDATE') or BAIL_OUT "FETCH $@";
195         is($ret->{1}->{'INTERNALDATE'}, '01-Jan-1970 00:00:00 +0000',
196                 'internaldate matches');
197         ok(!$mic->fetch_hash($r, 'INFERNALDATE'), 'bogus attribute fails');
198
199         my $envelope = $mic->get_envelope($r) or BAIL_OUT("get_envelope: $@");
200         is($envelope->{bcc}, 'NIL', 'empty bcc');
201         is($envelope->{messageid}, '<testmessage@example.com>', 'messageid');
202         is(scalar @{$envelope->{to}}, 1, 'one {to} header');
203         # *sigh* too much to verify...
204         #use Data::Dumper; diag Dumper($envelope);
205
206         $ret = $mic->fetch_hash($r, 'FLAGS') or BAIL_OUT "FETCH $@";
207         is_deeply($ret->{1}->{FLAGS}, '', 'no flags');
208
209         $ret = $mic->fetch_hash($r, 'BODY[1]') or BAIL_OUT "FETCH $@";
210         like($ret->{1}->{'BODY[1]'}, qr/\AThis is a test message/, 'BODY[1]');
211
212         $ret = $mic->fetch_hash($r, 'BODY[1]<1>') or BAIL_OUT "FETCH $@";
213         like($ret->{1}->{'BODY[1]<1>'}, qr/\Ahis is a test message/,
214                         'BODY[1]<1>');
215
216         $ret = $mic->fetch_hash($r, 'BODY[1]<2.3>') or BAIL_OUT "FETCH $@";
217         is($ret->{1}->{'BODY[1]<2>'}, "is ", 'BODY[1]<2.3>');
218         $ret = $mic->bodypart_string($r, 1, 3, 2) or
219                                         BAIL_OUT "bodypart_string $@";
220         is($ret, "is ", 'bodypart string');
221
222         $ret = $mic->fetch_hash($r, 'BODY[HEADER.FIELDS.NOT (Message-ID)]')
223                 or BAIL_OUT "FETCH $@";
224         $ret = $ret->{1}->{'BODY[HEADER.FIELDS.NOT (MESSAGE-ID)]'};
225         unlike($ret, qr/message-id/i, 'Message-ID excluded');
226         like($ret, qr/\r\n\r\n\z/s, 'got header end');
227
228         $ret = $mic->fetch_hash($r, 'BODY[HEADER.FIELDS (Message-ID)]')
229                 or BAIL_OUT "FETCH $@";
230         is($ret->{1}->{'BODY[HEADER.FIELDS (MESSAGE-ID)]'},
231                 'Message-ID: <testmessage@example.com>'."\r\n\r\n",
232                 'got only Message-ID');
233
234         my $bs = $mic->get_bodystructure($r) or BAIL_OUT("bodystructure: $@");
235         ok($bs, 'got a bodystructure');
236         is(lc($bs->bodytype), 'text', '->bodytype');
237         is(lc($bs->bodyenc), '8bit', '->bodyenc');
238 }
239 ok($mic->has_capability('COMPRESS') ||
240         $mic->has_capability('COMPRESS=DEFLATE'), 'deflate cap');
241 SKIP: {
242         skip 'Mail::IMAPClient too old for ->compress', 2 if !$can_compress;
243         my $c = $imap_client->new(%mic_opt);
244         ok($c && $c->compress, 'compress enabled');
245         ok($c->examine($mailbox1), 'EXAMINE succeeds after COMPRESS');
246         $ret = $c->search('uid 1:*') or BAIL_OUT "SEARCH FAIL $@";
247         is_deeply($ret, [ 1 ], 'search UID 1:* works after compression');
248 }
249
250 ok($mic->logout, 'logout works');
251
252 my $have_inotify = eval { require Linux::Inotify2; 1 };
253
254 my $pi_config = PublicInbox::Config->new;
255 $pi_config->each_inbox(sub {
256         my ($ibx) = @_;
257         my $env = { ORIGINAL_RECIPIENT => $ibx->{-primary_address} };
258         my $name = $ibx->{name};
259         my $ng = $ibx->{newsgroup};
260         my $mic = $imap_client->new(%mic_opt);
261         ok($mic && $mic->login && $mic->IsAuthenticated, "authed $name");
262         my $mb = "$ng.$first_range";
263         my $uidnext = $mic->uidnext($mb); # we'll fetch BODYSTRUCTURE on this
264         ok($uidnext, 'got uidnext for later fetch');
265         ok($mic->has_capability('IDLE'), "IDLE capa $name");
266         ok(!$mic->idle, "IDLE fails w/o SELECT/EXAMINE $name");
267         ok($mic->examine($mb), "EXAMINE $ng succeeds");
268         ok(my $idle_tag = $mic->idle, "IDLE succeeds on $ng");
269
270         open(my $fh, '<', 't/data/message_embed.eml') or BAIL_OUT("open: $!");
271         run_script(['-mda', '--no-precheck'], $env, { 0 => $fh }) or
272                 BAIL_OUT('-mda delivery');
273         my $t0 = Time::HiRes::time();
274         ok(my @res = $mic->idle_data(11), "IDLE succeeds on $ng");
275         is(grep(/\A\* [0-9] EXISTS\b/, @res), 1, 'got EXISTS message');
276         ok((Time::HiRes::time() - $t0) < 10, 'IDLE client notified');
277
278         my (@ino_info, $ino_fdinfo);
279         SKIP: {
280                 skip 'no inotify support', 1 unless $have_inotify;
281                 skip 'missing /proc/$PID/fd', 1 if !-d "/proc/$td->{pid}/fd";
282                 my @ino = grep {
283                         readlink($_) =~ /\binotify\b/
284                 } glob("/proc/$td->{pid}/fd/*");
285                 is(scalar(@ino), 1, 'only one inotify FD');
286                 my $ino_fd = (split('/', $ino[0]))[-1];
287                 $ino_fdinfo = "/proc/$td->{pid}/fdinfo/$ino_fd";
288                 if (open my $fh, '<', $ino_fdinfo) {
289                         local $/ = "\n";
290                         @ino_info = grep(/^inotify wd:/, <$fh>);
291                         ok(scalar(@ino_info), 'inotify has watches');
292                 } else {
293                         skip "$ino_fdinfo missing: $!", 1;
294                 }
295         };
296
297         # ensure IDLE persists across HUP, w/o extra watches or FDs
298         $td->kill('HUP') or BAIL_OUT "failed to kill -imapd: $!";
299         SKIP: {
300                 skip 'no inotify fdinfo (or support)', 2 if !@ino_info;
301                 my (@tmp, %prev);
302                 local $/ = "\n";
303                 my $end = time + 5;
304                 until (time > $end) {
305                         select undef, undef, undef, 0.01;
306                         open my $fh, '<', $ino_fdinfo or
307                                                 BAIL_OUT "$ino_fdinfo: $!";
308                         %prev = map { $_ => 1 } @ino_info;
309                         @tmp = grep(/^inotify wd:/, <$fh>);
310                         if (scalar(@tmp) == scalar(@ino_info)) {
311                                 delete @prev{@tmp};
312                                 last if scalar(keys(%prev)) == @ino_info;
313                         }
314                 }
315                 is(scalar @tmp, scalar @ino_info,
316                         'old inotify watches replaced');
317                 is(scalar keys %prev, scalar @ino_info,
318                         'no previous watches overlap');
319         };
320
321         open($fh, '<', 't/data/0001.patch') or BAIL_OUT("open: $!");
322         run_script(['-mda', '--no-precheck'], $env, { 0 => $fh }) or
323                 BAIL_OUT('-mda delivery');
324         $t0 = Time::HiRes::time();
325         ok(@res = $mic->idle_data(11), "IDLE succeeds on $ng after HUP");
326         is(grep(/\A\* [0-9] EXISTS\b/, @res), 1, 'got EXISTS message');
327         ok((Time::HiRes::time() - $t0) < 10, 'IDLE client notified');
328         ok($mic->done($idle_tag), 'IDLE DONE');
329         my $bs = $mic->get_bodystructure($uidnext);
330         ok($bs, 'BODYSTRUCTURE ok for deeply nested');
331         $ret = $mic->fetch_hash($uidnext, 'BODY') or BAIL_OUT "FETCH $@";
332         ok($ret->{$uidnext}->{BODY}, 'got something in BODY');
333
334         # this matches dovecot behavior
335         $ret = $mic->fetch_hash($uidnext, 'BODY[1]') or BAIL_OUT "FETCH $@";
336         is($ret->{$uidnext}->{'BODY[1]'},
337                 "testing embedded message harder\r\n", 'BODY[1]');
338         $ret = $mic->fetch_hash($uidnext, 'BODY[2]') or BAIL_OUT "FETCH $@";
339         like($ret->{$uidnext}->{'BODY[2]'},
340                 qr/\ADate: Sat, 18 Apr 2020 22:20:20 /, 'BODY[2]');
341
342         $ret = $mic->fetch_hash($uidnext, 'BODY[2.1.1]') or BAIL_OUT "FETCH $@";
343         is($ret->{$uidnext}->{'BODY[2.1.1]'},
344                 "testing embedded message\r\n", 'BODY[2.1.1]');
345
346         $ret = $mic->fetch_hash($uidnext, 'BODY[2.1.2]') or BAIL_OUT "FETCH $@";
347         like($ret->{$uidnext}->{'BODY[2.1.2]'}, qr/\AFrom: /,
348                 'BODY[2.1.2] tip matched');
349         like($ret->{$uidnext}->{'BODY[2.1.2]'},
350                  # trailing CRLF may vary depending on MIME parser
351                  qr/done_testing;(?:\r\n){1,2}\z/,
352                 'BODY[2.1.2] tail matched');
353
354         $ret = $mic->fetch_hash("1:$uidnext", 'BODY[2.HEADER]') or
355                                                 BAIL_OUT "2.HEADER $@";
356         like($ret->{$uidnext}->{'BODY[2.HEADER]'},
357                 qr/\ADate: Sat, 18 Apr 2020 22:20:20 /,
358                 '2.HEADER of message/rfc822');
359
360         $ret = $mic->fetch_hash($uidnext, 'BODY[2.MIME]') or
361                 BAIL_OUT "2.MIME $@";
362         is($ret->{$uidnext}->{'BODY[2.MIME]'}, <<EOF, 'BODY[2.MIME]');
363 Content-Type: message/rfc822\r
364 Content-Disposition: attachment; filename="embed2x\.eml"\r
365 \r
366 EOF
367
368         my @hits = $mic->search('SENTON' => '18-Apr-2020');
369         is_deeply(\@hits, [ $uidnext ], 'search with date condition works');
370         ok($mic->examine($ng), 'EXAMINE on dummy');
371         @hits = $mic->search('SENTSINCE' => '18-Apr-2020');
372         is_deeply(\@hits, [], 'search on dummy with condition works');
373         ok(!$mic->search('SENTSINCE' => '18-Abr-2020'), 'bad month fails');
374 }); # each_inbox
375
376 # message sequence numbers :<
377 is($mic->Uid(0), 0, 'disable UID on '.ref($mic));
378 ok($mic->reconnect, 'reconnected');
379 $ret = $mic->fetch_hash('1,2:3', 'RFC822') or BAIL_OUT "FETCH $@";
380 is(scalar keys %$ret, 3, 'got all 3 messages with comma-separated sequence');
381 $ret = $mic->fetch_hash('1:*', 'RFC822') or BAIL_OUT "FETCH $@";
382 is(scalar keys %$ret, 3, 'got all 3 messages');
383
384 SKIP: {
385         # do any clients use non-UID IMAP SEARCH?
386         skip 'Xapian missing', 2 if $level eq 'basic';
387         my $x = $mic->search('all');
388         is_deeply($x, [1, 2, 3], 'MSN SEARCH works before rm');
389         $x = $mic->search(qw(header subject embedded));
390         is_deeply($x, [2], 'MSN SEARCH on Subject works before rm');
391 }
392
393 {
394         my $rdr = { 0 => \($ret->{1}->{RFC822}) };
395         my $env = { HOME => $ENV{HOME} };
396         my @cmd = qw(-learn rm --all);
397         run_script(\@cmd, $env, $rdr) or BAIL_OUT('-learn rm');
398 }
399
400 SKIP: {
401         # do any clients use non-UID IMAP SEARCH?  We only ensure
402         # MSN "SEARCH" can return a result which can be retrieved
403         # via MSN "FETCH"
404         skip 'Xapian missing', 3 if $level eq 'basic';
405         my $x = $mic->search(qw(header subject embedded));
406         is(scalar(@$x), 1, 'MSN SEARCH on Subject works after rm');
407         $x = $mic->message_string($x->[0]);
408         is($x, $ret->{2}->{RFC822}, 'message 2 unchanged');
409         $x = $mic->search(qw(text embedded));
410         is(scalar(@$x), 1, 'MSN SEARCH on TEXT works after rm');
411 }
412
413 # FIXME? no EXPUNGE response, yet
414 my $r2 = $mic->fetch_hash('1:*', 'BODY.PEEK[]') or BAIL_OUT "FETCH $@";
415 is(scalar keys %$r2, 2, 'did not get all 3 messages');
416 is($r2->{2}->{'BODY[]'}, $ret->{2}->{RFC822}, 'message 2 unchanged');
417 is($r2->{3}->{'BODY[]'}, $ret->{3}->{RFC822}, 'message 3 unchanged');
418 $r2 = $mic->fetch_hash(2, 'BODY.PEEK[HEADER.FIELDS (message-id)]')
419                         or BAIL_OUT "FETCH $@";
420 is($r2->{2}->{'BODY[HEADER.FIELDS (MESSAGE-ID)]'},
421         'Message-ID: <20200418222508.GA13918@dcvr>'."\r\n\r\n",
422         'BODY.PEEK[HEADER.FIELDS ...] drops .PEEK');
423
424 {
425         my @new_list = $mic->list;
426         # tag differs in [-1]
427         like($orig_list[-1], qr/\A\S+ OK List done\r\n/, 'orig LIST');
428         like($new_list[-1], qr/\A\S+ OK List done\r\n/, 'new LIST');
429         pop @new_list;
430         pop @orig_list;
431         # TODO: not sure if sort order matters, imapd_refresh_finalize
432         # doesn't sort, hopefully clients don't care...
433         @new_list = sort @new_list;
434         @orig_list = sort @orig_list;
435         is_deeply(\@new_list, \@orig_list, 'LIST identical');
436 }
437 ok($mic->close, 'CLOSE works');
438 ok(!$mic->close, 'CLOSE not idempotent');
439 ok($mic->logout, 'logged out');
440
441 {
442         my $c = tcp_connect($sock);
443         $c->autoflush(1);
444         like(<$c>, qr/\* OK/, 'got a greeting');
445         print $c "\r\n";
446         like(<$c>, qr/\A\* BAD Error in IMAP command/, 'empty line');
447         print $c "tagonly\r\n";
448         like(<$c>, qr/\Atagonly BAD Error in IMAP command/, 'tag-only line');
449 }
450
451 SKIP: {
452         use_ok 'PublicInbox::Watch';
453         use_ok 'PublicInbox::InboxIdle';
454         require_git('1.8.5', 1) or
455                 skip('git 1.8.5+ needed for --urlmatch', 4);
456         my $old_env = { HOME => $ENV{HOME} };
457         my $home = "$tmpdir/watch_home";
458         mkdir $home or BAIL_OUT $!;
459         mkdir "$home/.public-inbox" or BAIL_OUT $!;
460         local $ENV{HOME} = $home;
461         my $name = 'watchimap';
462         my $addr = "i1\@example.com";
463         my $url = "http://example.com/i1";
464         my $inboxdir = "$tmpdir/watchimap";
465         my $cmd = ['-init', '-V2', '-Lbasic', $name, $inboxdir, $url, $addr];
466         my ($ihost, $iport) = ($sock->sockhost, $sock->sockport);
467         my $imapurl = "imap://$ihost:$iport/inbox.i1.0";
468         run_script($cmd) or BAIL_OUT("init $name");
469         xsys(qw(git config), "--file=$home/.public-inbox/config",
470                         "publicinbox.$name.watch",
471                         $imapurl) == 0 or BAIL_OUT "git config $?";
472         my $cfg = PublicInbox::Config->new;
473         PublicInbox::DS->Reset;
474         my $ii = PublicInbox::InboxIdle->new($cfg);
475         my $cb = sub { PublicInbox::DS->SetPostLoopCallback(sub {}) };
476         my $obj = bless \$cb, 'PublicInbox::TestCommon::InboxWakeup';
477         $cfg->each_inbox(sub { $_[0]->subscribe_unlock('ident', $obj) });
478         my $watcherr = "$tmpdir/watcherr";
479         open my $err_wr, '>>', $watcherr or BAIL_OUT $!;
480         open my $err, '<', $watcherr or BAIL_OUT $!;
481         my $w = start_script(['-watch'], undef, { 2 => $err_wr });
482
483         diag 'waiting for initial fetch...';
484         PublicInbox::DS->EventLoop;
485         diag 'inbox unlocked on initial fetch, waiting for IDLE';
486
487         tick until (grep(/I: \S+ idling/, <$err>));
488         open my $fh, '<', 't/iso-2202-jp.eml' or BAIL_OUT $!;
489         $old_env->{ORIGINAL_RECIPIENT} = $addr;
490         ok(run_script([qw(-mda --no-precheck)], $old_env, { 0 => $fh }),
491                 'delivered a message for IDLE to kick -watch');
492         diag 'waiting for IMAP IDLE wakeup';
493         PublicInbox::DS->SetPostLoopCallback(undef);
494         PublicInbox::DS->EventLoop;
495         diag 'inbox unlocked on IDLE wakeup';
496
497         # try again with polling
498         xsys(qw(git config), "--file=$home/.public-inbox/config",
499                 'imap.PollInterval', 0.11) == 0
500                 or BAIL_OUT "git config $?";
501         $w->kill('HUP');
502         diag 'waiting for -watch reload + initial fetch';
503         tick until (grep(/I: will check/, <$err>));
504
505         open $fh, '<', 't/psgi_attach.eml' or BAIL_OUT $!;
506         ok(run_script([qw(-mda --no-precheck)], $old_env, { 0 => $fh }),
507                 'delivered a message for -watch PollInterval');
508
509         diag 'waiting for PollInterval wakeup';
510         PublicInbox::DS->SetPostLoopCallback(undef);
511         PublicInbox::DS->EventLoop;
512         diag 'inbox unlocked (poll)';
513         $w->kill;
514         $w->join;
515         is($?, 0, 'no error in exited -watch process');
516
517         $cfg->each_inbox(sub { shift->unsubscribe_unlock('ident') });
518         $ii->close;
519         PublicInbox::DS->Reset;
520         seek($err, 0, 0);
521         my @err = grep(!/^I:/, <$err>);
522         is(@err, 0, 'no warnings/errors from -watch'.join(' ', @err));
523
524         if ($ENV{TEST_KILL_IMAPD}) { # not sure how reliable this test can be
525                 xsys(qw(git config), "--file=$home/.public-inbox/config",
526                         qw(--unset imap.PollInterval)) == 0
527                         or BAIL_OUT "git config $?";
528                 truncate($err_wr, 0) or BAIL_OUT $!;
529                 my @t0 = times;
530                 $w = start_script(['-watch'], undef, { 2 => $err_wr });
531                 seek($err, 0, 0);
532                 tick until (grep(/I: \S+ idling/, <$err>));
533                 diag 'killing imapd, waiting for CPU spins';
534                 my $delay = 0.11;
535                 $td->kill(9);
536                 tick $delay;
537                 $w->kill;
538                 $w->join;
539                 is($?, 0, 'no error in exited -watch process');
540                 my @t1 = times;
541                 my $c = $t1[2] + $t1[3] - $t0[2] - $t0[3];
542                 my $thresh = (0.9 * $delay);
543                 diag "c=$c, threshold=$thresh";
544                 ok($c < $thresh, 'did not burn much CPU');
545                 is_deeply([grep(/ line \d+$/m, <$err>)], [],
546                                 'no backtraces from errors');
547         }
548 }
549
550 $td->kill;
551 $td->join;
552 is($?, 0, 'no error in exited process') if !$ENV{TEST_KILL_IMAPD};
553 open my $fh, '<', $err or BAIL_OUT("open $err failed: $!");
554 my $eout = do { local $/; <$fh> };
555 unlike($eout, qr/wide/i, 'no Wide character warnings');
556 unlike($eout, qr/uninitialized/i, 'no uninitialized warnings');
557
558 done_testing;