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