]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/IMAP.pm
imap: support LIST command
[public-inbox.git] / lib / PublicInbox / IMAP.pm
1 # Copyright (C) 2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 #
4 # Each instance of this represents an IMAP client connected to
5 # public-inbox-imapd.  Much of this was taken from NNTP, but
6 # further refined while experimenting on future ideas to handle
7 # slow storage.
8 #
9 # data notes:
10 # * NNTP article numbers are UIDs and message sequence numbers (MSNs)
11 # * Message sequence numbers (MSNs) can be stable since we're read-only.
12 #   Most IMAP clients use UIDs (I hope), and we can return a dummy
13 #   message if a client requests a non-existent MSN.
14
15 package PublicInbox::IMAP;
16 use strict;
17 use base qw(PublicInbox::DS);
18 use fields qw(imapd logged_in ibx long_cb -login_tag
19         -idle_tag -idle_max);
20 use PublicInbox::Eml;
21 use PublicInbox::DS qw(now);
22 use PublicInbox::Syscall qw(EPOLLIN EPOLLONESHOT);
23 use Text::ParseWords qw(parse_line);
24 use Errno qw(EAGAIN);
25 my $Address;
26 for my $mod (qw(Email::Address::XS Mail::Address)) {
27         eval "require $mod" or next;
28         $Address = $mod and last;
29 }
30 die "neither Email::Address::XS nor Mail::Address loaded: $@" if !$Address;
31
32 sub LINE_MAX () { 512 } # does RFC 3501 have a limit like RFC 977?
33
34 my %FETCH_NEED_BLOB = ( # for future optimization
35         'BODY.PEEK[HEADER]' => 1,
36         'BODY.PEEK[TEXT]' => 1,
37         'BODY.PEEK[]' => 1,
38         'BODY[HEADER]' => 1,
39         'BODY[TEXT]' => 1,
40         'BODY[]' => 1,
41         'RFC822.HEADER' => 1,
42         'RFC822.SIZE' => 1, # needs CRLF conversion :<
43         'RFC822.TEXT' => 1,
44         BODY => 1,
45         BODYSTRUCTURE => 1,
46         ENVELOPE => 1,
47         FLAGS => 0,
48         INTERNALDATE => 0,
49         RFC822 => 1,
50         UID => 0,
51 );
52 my %FETCH_ATT = map { $_ => [ $_ ] } keys %FETCH_NEED_BLOB;
53
54 # aliases (RFC 3501 section 6.4.5)
55 $FETCH_ATT{FAST} = [ qw(FLAGS INTERNALDATE RFC822.SIZE) ];
56 $FETCH_ATT{ALL} = [ @{$FETCH_ATT{FAST}}, 'ENVELOPE' ];
57 $FETCH_ATT{FULL} = [ @{$FETCH_ATT{ALL}}, 'BODY' ];
58
59 for my $att (keys %FETCH_ATT) {
60         my %h = map { $_ => 1 } @{$FETCH_ATT{$att}};
61         $FETCH_ATT{$att} = \%h;
62 }
63
64 sub greet ($) {
65         my ($self) = @_;
66         my $capa = capa($self);
67         $self->write(\"* OK [$capa] public-inbox-imapd ready\r\n");
68 }
69
70 sub new ($$$) {
71         my ($class, $sock, $imapd) = @_;
72         my $self = fields::new($class);
73         my $ev = EPOLLIN;
74         my $wbuf;
75         if ($sock->can('accept_SSL') && !$sock->accept_SSL) {
76                 return CORE::close($sock) if $! != EAGAIN;
77                 $ev = PublicInbox::TLS::epollbit();
78                 $wbuf = [ \&PublicInbox::DS::accept_tls_step, \&greet ];
79         }
80         $self->SUPER::new($sock, $ev | EPOLLONESHOT);
81         $self->{imapd} = $imapd;
82         if ($wbuf) {
83                 $self->{wbuf} = $wbuf;
84         } else {
85                 greet($self);
86         }
87         $self->update_idle_time;
88         $self;
89 }
90
91 sub capa ($) {
92         my ($self) = @_;
93
94         # dovecot advertises IDLE pre-login; perhaps because some clients
95         # depend on it, so we'll do the same
96         my $capa = 'CAPABILITY IMAP4rev1 IDLE';
97         if ($self->{logged_in}) {
98                 $capa .= ' COMPRESS=DEFLATE';
99         } else {
100                 if (!($self->{sock} // $self)->can('accept_SSL') &&
101                         $self->{imapd}->{accept_tls}) {
102                         $capa .= ' STARTTLS';
103                 }
104                 $capa .= ' AUTH=ANONYMOUS';
105         }
106 }
107
108 sub login_success ($$) {
109         my ($self, $tag) = @_;
110         $self->{logged_in} = 1;
111         my $capa = capa($self);
112         "$tag OK [$capa] Logged in\r\n";
113 }
114
115 sub auth_challenge_ok ($) {
116         my ($self) = @_;
117         my $tag = delete($self->{-login_tag}) or return;
118         login_success($self, $tag);
119 }
120
121 sub cmd_login ($$$$) {
122         my ($self, $tag) = @_; # ignore ($user, $password) = ($_[2], $_[3])
123         login_success($self, $tag);
124 }
125
126 sub cmd_logout ($$) {
127         my ($self, $tag) = @_;
128         delete $self->{logged_in};
129         $self->write(\"* BYE logging out\r\n$tag OK logout completed\r\n");
130         $self->shutdn; # PublicInbox::DS::shutdn
131         undef;
132 }
133
134 sub cmd_authenticate ($$$) {
135         my ($self, $tag) = @_; # $method = $_[2], should be "ANONYMOUS"
136         $self->{-login_tag} = $tag;
137         "+\r\n"; # challenge
138 }
139
140 sub cmd_capability ($$) {
141         my ($self, $tag) = @_;
142         '* '.capa($self)."\r\n$tag OK\r\n";
143 }
144
145 sub cmd_noop ($$) { "$_[1] OK NOOP completed\r\n" }
146
147 # called by PublicInbox::InboxIdle
148 sub on_inbox_unlock {
149         my ($self, $ibx) = @_;
150         my $new = $ibx->mm->max;
151         defined(my $old = $self->{-idle_max}) or die 'BUG: -idle_max unset';
152         if ($new > $old) {
153                 $self->{-idle_max} = $new;
154                 $self->msg_more("* $_ EXISTS\r\n") for (($old + 1)..($new - 1));
155                 $self->write(\"* $new EXISTS\r\n");
156         }
157 }
158
159 sub cmd_idle ($$) {
160         my ($self, $tag) = @_;
161         # IDLE seems allowed by dovecot w/o a mailbox selected *shrug*
162         my $ibx = $self->{ibx} or return "$tag BAD no mailbox selected\r\n";
163         $ibx->subscribe_unlock(fileno($self->{sock}), $self);
164         $self->{imapd}->idler_start;
165         $self->{-idle_tag} = $tag;
166         $self->{-idle_max} = $ibx->mm->max // 0;
167         "+ idling\r\n"
168 }
169
170 sub cmd_done ($$) {
171         my ($self, $tag) = @_; # $tag is "DONE" (case-insensitive)
172         defined(my $idle_tag = delete $self->{-idle_tag}) or
173                 return "$tag BAD not idle\r\n";
174         my $ibx = $self->{ibx} or do {
175                 warn "BUG: idle_tag set w/o inbox";
176                 return "$tag BAD internal bug\r\n";
177         };
178         $ibx->unsubscribe_unlock(fileno($self->{sock}));
179         "$idle_tag OK Idle completed\r\n";
180 }
181
182 sub cmd_examine ($$$) {
183         my ($self, $tag, $mailbox) = @_;
184         my $ibx = $self->{imapd}->{groups}->{$mailbox} or
185                 return "$tag NO Mailbox doesn't exist: $mailbox\r\n";
186         my $mm = $ibx->mm;
187         my $max = $mm->max // 0;
188         # RFC 3501 2.3.1.1 -  "A good UIDVALIDITY value to use in
189         # this case is a 32-bit representation of the creation
190         # date/time of the mailbox"
191         my $uidvalidity = $mm->created_at or return "$tag BAD UIDVALIDITY\r\n";
192         my $uidnext = $max + 1;
193
194         # XXX: do we need this? RFC 5162/7162
195         my $ret = $self->{ibx} ? "* OK [CLOSED] previous closed\r\n" : '';
196         $self->{ibx} = $ibx;
197         $ret .= <<EOF;
198 * $max EXISTS\r
199 * $max RECENT\r
200 * FLAGS (\\Seen)\r
201 * OK [PERMANENTFLAGS ()] Read-only mailbox\r
202 EOF
203         $ret .= "* OK [UNSEEN $max]\r\n" if $max;
204         $ret .= "* OK [UIDNEXT $uidnext]\r\n" if defined $uidnext;
205         $ret .= "* OK [UIDVALIDITY $uidvalidity]\r\n" if defined $uidvalidity;
206         $ret .= "$tag OK [READ-ONLY] EXAMINE/SELECT complete\r\n";
207 }
208
209 sub _esc ($) {
210         my ($v) = @_;
211         if (!defined($v)) {
212                 'NIL';
213         } elsif ($v =~ /[{"\r\n%*\\\[]/) { # literal string
214                 '{' . length($v) . "}\r\n" . $v;
215         } else { # quoted string
216                 qq{"$v"}
217         }
218 }
219
220 sub addr_envelope ($$;$) {
221         my ($eml, $x, $y) = @_;
222         my $v = $eml->header_raw($x) //
223                 ($y ? $eml->header_raw($y) : undef) // return 'NIL';
224
225         my @x = $Address->parse($v) or return 'NIL';
226         '(' . join('',
227                 map { '(' . join(' ',
228                                 _esc($_->name), 'NIL',
229                                 _esc($_->user), _esc($_->host)
230                         ) . ')'
231                 } @x) .
232         ')';
233 }
234
235 sub eml_envelope ($) {
236         my ($eml) = @_;
237         '(' . join(' ',
238                 _esc($eml->header_raw('Date')),
239                 _esc($eml->header_raw('Subject')),
240                 addr_envelope($eml, 'From'),
241                 addr_envelope($eml, 'Sender', 'From'),
242                 addr_envelope($eml, 'Reply-To', 'From'),
243                 addr_envelope($eml, 'To'),
244                 addr_envelope($eml, 'Cc'),
245                 addr_envelope($eml, 'Bcc'),
246                 _esc($eml->header_raw('In-Reply-To')),
247                 _esc($eml->header_raw('Message-ID')),
248         ) . ')';
249 }
250
251 sub uid_fetch_cb { # called by git->cat_async
252         my ($bref, $oid, $type, $size, $fetch_m_arg) = @_;
253         my ($self, undef, $ibx, undef, undef, $msgs, $want) = @$fetch_m_arg;
254         my $smsg = shift @$msgs or die 'BUG: no smsg';
255         $smsg->{blob} eq $oid or die "BUG: $smsg->{blob} != $oid";
256         $$bref =~ s/(?<!\r)\n/\r\n/sg; # make strict clients happy
257
258         # fixup old bug from import (pre-a0c07cba0e5d8b6a)
259         $$bref =~ s/\A[\r\n]*From [^\r\n]*\r\n//s;
260
261         $self->msg_more("* $smsg->{num} FETCH (UID $smsg->{num}");
262
263         $want->{'RFC822.SIZE'} and
264                 $self->msg_more(' RFC822.SIZE '.length($$bref));
265         $want->{INTERNALDATE} and
266                 $self->msg_more(' INTERNALDATE "'.$smsg->internaldate.'"');
267         $want->{FLAGS} and $self->msg_more(' FLAGS ()');
268         for ('RFC822', 'BODY[]', 'BODY.PEEK[]') {
269                 next unless $want->{$_};
270                 $self->msg_more(" $_ {".length($$bref)."}\r\n");
271                 $self->msg_more($$bref);
272         }
273
274         my $eml = PublicInbox::Eml->new($bref);
275
276         $want->{ENVELOPE} and
277                 $self->msg_more(' ENVELOPE '.eml_envelope($eml));
278
279         for my $f ('RFC822.HEADER', 'BODY[HEADER]', 'BODY.PEEK[HEADER]') {
280                 next unless $want->{$f};
281                 $self->msg_more(" $f {".length(${$eml->{hdr}})."}\r\n");
282                 $self->msg_more(${$eml->{hdr}});
283         }
284         for my $f ('RFC822.TEXT', 'BODY[TEXT]') {
285                 next unless $want->{$f};
286                 $self->msg_more(" $f {".length($$bref)."}\r\n");
287                 $self->msg_more($$bref);
288         }
289         # TODO BODY/BODYSTRUCTURE, specific headers
290         $self->msg_more(")\r\n");
291 }
292
293 sub uid_fetch_m { # long_response
294         my ($self, $tag, $ibx, $beg, $end, $msgs, $want) = @_;
295         if (!@$msgs) { # refill
296                 @$msgs = @{$ibx->over->query_xover($$beg, $end)};
297                 if (!@$msgs) {
298                         $self->write(\"$tag OK Fetch done\r\n");
299                         return;
300                 }
301                 $$beg = $msgs->[-1]->{num} + 1;
302         }
303         my $git = $ibx->git;
304         $git->cat_async_begin; # TODO: actually make async
305         $git->cat_async($msgs->[0]->{blob}, \&uid_fetch_cb, \@_);
306         $git->cat_async_wait;
307         1;
308 }
309
310 sub cmd_status ($$$;@) {
311         my ($self, $tag, $mailbox, @items) = @_;
312         my $ibx = $self->{imapd}->{groups}->{$mailbox} or
313                 return "$tag NO Mailbox doesn't exist: $mailbox\r\n";
314         return "$tag BAD no items\r\n" if !scalar(@items);
315         ($items[0] !~ s/\A\(//s || $items[-1] !~ s/\)\z//s) and
316                 return "$tag BAD invalid args\r\n";
317
318         my $mm = $ibx->mm;
319         my ($max, @it);
320         for my $it (@items) {
321                 $it = uc($it);
322                 push @it, $it;
323                 if ($it =~ /\A(?:MESSAGES|UNSEEN|RECENT)\z/) {
324                         push(@it, ($max //= $mm->max // 0));
325                 } elsif ($it eq 'UIDNEXT') {
326                         push(@it, ($max //= $mm->max // 0) + 1);
327                 } elsif ($it eq 'UIDVALIDITY') {
328                         push(@it, $mm->created_at //
329                                 return("$tag BAD UIDVALIDITY\r\n"));
330                 } else {
331                         return "$tag BAD invalid item\r\n";
332                 }
333         }
334         return "$tag BAD no items\r\n" if !@it;
335         "* STATUS $mailbox (".join(' ', @it).")\r\n" .
336         "$tag OK Status complete\r\n";
337 }
338
339 my %patmap = ('*' => '.*', '%' => '[^\.]*');
340 sub cmd_list ($$$$) {
341         my ($self, $tag, $refname, $wildcard) = @_;
342         my $l = $self->{imapd}->{inboxlist};
343         if ($refname eq '' && $wildcard eq '') {
344                 # request for hierarchy delimiter
345                 $l = [ qq[* LIST (\\Noselect) "." ""\r\n] ];
346         } elsif ($refname ne '' || $wildcard ne '*') {
347                 $wildcard =~ s!([^a-z0-9_])!$patmap{$1} // "\Q$1"!eig;
348                 $l = [ grep(/ \Q$refname\E$wildcard\r\n\z/s, @$l) ];
349         }
350         \(join('', @$l, "$tag OK List complete\r\n"));
351 }
352
353 sub cmd_uid_fetch ($$$;@) {
354         my ($self, $tag, $range, @want) = @_;
355         my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
356         if ($want[0] =~ s/\A\(//s) {
357                 $want[-1] =~ s/\)\z//s or return "$tag BAD no rparen\r\n";
358         }
359         my %want = map {;
360                 my $x = $FETCH_ATT{uc($_)} or return "$tag BAD param: $_\r\n";
361                 %$x;
362         } @want;
363         my ($beg, $end);
364         my $msgs = [];
365         if ($range =~ /\A([0-9]+):([0-9]+)\z/s) {
366                 ($beg, $end) = ($1, $2);
367         } elsif ($range =~ /\A([0-9]+):\*\z/s) {
368                 ($beg, $end) =  ($1, $ibx->mm->max // 0);
369         } elsif ($range =~ /\A[0-9]+\z/) {
370                 my $smsg = $ibx->over->get_art($range) or return "$tag OK\r\n";
371                 push @$msgs, $smsg;
372                 ($beg, $end) = ($range, 0);
373         } else {
374                 return "$tag BAD\r\n";
375         }
376         long_response($self, \&uid_fetch_m, $tag, $ibx,
377                                 \$beg, $end, $msgs, \%want);
378 }
379
380 sub uid_search_all { # long_response
381         my ($self, $tag, $ibx, $num) = @_;
382         my $uids = $ibx->mm->ids_after($num);
383         if (scalar(@$uids)) {
384                 $self->msg_more(join(' ', '', @$uids));
385         } else {
386                 $self->write(\"\r\n$tag OK\r\n");
387                 undef;
388         }
389 }
390
391 sub uid_search_uid_range { # long_response
392         my ($self, $tag, $ibx, $beg, $end) = @_;
393         my $uids = $ibx->mm->msg_range($beg, $end, 'num');
394         if (@$uids) {
395                 $self->msg_more(join('', map { " $_->[0]" } @$uids));
396         } else {
397                 $self->write(\"\r\n$tag OK\r\n");
398                 undef;
399         }
400 }
401
402 sub cmd_uid_search ($$$;) {
403         my ($self, $tag, $arg, @rest) = @_;
404         my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
405         $arg = uc($arg);
406         if ($arg eq 'ALL' && !@rest) {
407                 $self->msg_more('* SEARCH');
408                 my $num = 0;
409                 long_response($self, \&uid_search_all, $tag, $ibx, \$num);
410         } elsif ($arg eq 'UID' && scalar(@rest) == 1) {
411                 if ($rest[0] =~ /\A([0-9]+):([0-9]+|\*)\z/s) {
412                         my ($beg, $end) = ($1, $2);
413                         $end = $ibx->mm->max if $end eq '*';
414                         $self->msg_more('* SEARCH');
415                         long_response($self, \&uid_search_uid_range,
416                                         $tag, $ibx, \$beg, $end);
417                 } elsif ($rest[0] =~ /\A[0-9]+\z/s) {
418                         my $uid = $rest[0];
419                         $uid = $ibx->over->get_art($uid) ? " $uid" : '';
420                         "* SEARCH$uid\r\n$tag OK\r\n";
421                 } else {
422                         "$tag BAD\r\n";
423                 }
424         } else {
425                 "$tag BAD\r\n";
426         }
427 }
428
429 sub args_ok ($$) { # duplicated from PublicInbox::NNTP
430         my ($cb, $argc) = @_;
431         my $tot = prototype $cb;
432         my ($nreq, undef) = split(';', $tot);
433         $nreq = ($nreq =~ tr/$//) - 1;
434         $tot = ($tot =~ tr/$//) - 1;
435         ($argc <= $tot && $argc >= $nreq);
436 }
437
438 # returns 1 if we can continue, 0 if not due to buffered writes or disconnect
439 sub process_line ($$) {
440         my ($self, $l) = @_;
441         my ($tag, $req, @args) = parse_line('[ \t]+', 0, $l);
442         pop(@args) if (@args && !defined($args[-1]));
443         if (@args && uc($req) eq 'UID') {
444                 $req .= "_".(shift @args);
445         }
446         my $res = eval {
447                 if (my $cmd = $self->can('cmd_'.lc($req // ''))) {
448                         defined($self->{-idle_tag}) ?
449                                 "$self->{-idle_tag} BAD expected DONE\r\n" :
450                                 $cmd->($self, $tag, @args);
451                 } elsif (uc($tag // '') eq 'DONE' && !defined($req)) {
452                         cmd_done($self, $tag);
453                 } else { # this is weird
454                         auth_challenge_ok($self) //
455                                 "$tag BAD Error in IMAP command $req: ".
456                                 "Unknown command\r\n";
457                 }
458         };
459         my $err = $@;
460         if ($err && $self->{sock}) {
461                 $l =~ s/\r?\n//s;
462                 err($self, 'error from: %s (%s)', $l, $err);
463                 $res = "$tag BAD program fault - command not performed\r\n";
464         }
465         return 0 unless defined $res;
466         $self->write($res);
467 }
468
469 sub long_step {
470         my ($self) = @_;
471         # wbuf is unset or empty, here; {long} may add to it
472         my ($fd, $cb, $t0, @args) = @{$self->{long_cb}};
473         my $more = eval { $cb->($self, @args) };
474         if ($@ || !$self->{sock}) { # something bad happened...
475                 delete $self->{long_cb};
476                 my $elapsed = now() - $t0;
477                 if ($@) {
478                         err($self,
479                             "%s during long response[$fd] - %0.6f",
480                             $@, $elapsed);
481                 }
482                 out($self, " deferred[$fd] aborted - %0.6f", $elapsed);
483                 $self->close;
484         } elsif ($more) { # $self->{wbuf}:
485                 $self->update_idle_time;
486
487                 # COMPRESS users all share the same DEFLATE context.
488                 # Flush it here to ensure clients don't see
489                 # each other's data
490                 $self->zflush;
491
492                 # no recursion, schedule another call ASAP, but only after
493                 # all pending writes are done.  autovivify wbuf:
494                 my $new_size = push(@{$self->{wbuf}}, \&long_step);
495
496                 # wbuf may be populated by $cb, no need to rearm if so:
497                 $self->requeue if $new_size == 1;
498         } else { # all done!
499                 delete $self->{long_cb};
500                 my $elapsed = now() - $t0;
501                 my $fd = fileno($self->{sock});
502                 out($self, " deferred[$fd] done - %0.6f", $elapsed);
503                 my $wbuf = $self->{wbuf}; # do NOT autovivify
504
505                 $self->requeue unless $wbuf && @$wbuf;
506         }
507 }
508
509 sub err ($$;@) {
510         my ($self, $fmt, @args) = @_;
511         printf { $self->{imapd}->{err} } $fmt."\n", @args;
512 }
513
514 sub out ($$;@) {
515         my ($self, $fmt, @args) = @_;
516         printf { $self->{imapd}->{out} } $fmt."\n", @args;
517 }
518
519 sub long_response ($$;@) {
520         my ($self, $cb, @args) = @_; # cb returns true if more, false if done
521
522         my $sock = $self->{sock} or return;
523         # make sure we disable reading during a long response,
524         # clients should not be sending us stuff and making us do more
525         # work while we are stream a response to them
526         $self->{long_cb} = [ fileno($sock), $cb, now(), @args ];
527         long_step($self); # kick off!
528         undef;
529 }
530
531 # callback used by PublicInbox::DS for any (e)poll (in/out/hup/err)
532 sub event_step {
533         my ($self) = @_;
534
535         return unless $self->flush_write && $self->{sock};
536
537         $self->update_idle_time;
538         # only read more requests if we've drained the write buffer,
539         # otherwise we can be buffering infinitely w/o backpressure
540
541         my $rbuf = $self->{rbuf} // (\(my $x = ''));
542         my $r = 1;
543
544         if (index($$rbuf, "\n") < 0) {
545                 my $off = length($$rbuf);
546                 $r = $self->do_read($rbuf, LINE_MAX, $off) or return;
547         }
548         while ($r > 0 && $$rbuf =~ s/\A[ \t]*([^\n]*?)\r?\n//) {
549                 my $line = $1;
550                 return $self->close if $line =~ /[[:cntrl:]]/s;
551                 my $t0 = now();
552                 my $fd = fileno($self->{sock});
553                 $r = eval { process_line($self, $line) };
554                 my $pending = $self->{wbuf} ? ' pending' : '';
555                 out($self, "[$fd] %s - %0.6f$pending", $line, now() - $t0);
556         }
557
558         return $self->close if $r < 0;
559         my $len = length($$rbuf);
560         return $self->close if ($len >= LINE_MAX);
561         $self->rbuf_idle($rbuf);
562         $self->update_idle_time;
563
564         # maybe there's more pipelined data, or we'll have
565         # to register it for socket-readiness notifications
566         $self->requeue unless $self->{wbuf};
567 }
568
569 sub compressed { undef }
570
571 sub zflush {} # overridden by IMAPdeflate
572
573 # RFC 4978
574 sub cmd_compress ($$$) {
575         my ($self, $tag, $alg) = @_;
576         return "$tag BAD DEFLATE only\r\n" if uc($alg) ne "DEFLATE";
577         return "$tag BAD COMPRESS active\r\n" if $self->compressed;
578
579         # CRIME made TLS compression obsolete
580         # return "$tag NO [COMPRESSIONACTIVE]\r\n" if $self->tls_compressed;
581
582         PublicInbox::IMAPdeflate->enable($self, $tag);
583         $self->requeue;
584         undef
585 }
586
587 sub cmd_starttls ($$) {
588         my ($self, $tag) = @_;
589         my $sock = $self->{sock} or return;
590         if ($sock->can('stop_SSL') || $self->compressed) {
591                 return "$tag BAD TLS or compression already enabled\r\n";
592         }
593         my $opt = $self->{imapd}->{accept_tls} or
594                 return "$tag BAD can not initiate TLS negotiation\r\n";
595         $self->write(\"$tag OK begin TLS negotiation now\r\n");
596         $self->{sock} = IO::Socket::SSL->start_SSL($sock, %$opt);
597         $self->requeue if PublicInbox::DS::accept_tls_step($self);
598         undef;
599 }
600
601 # for graceful shutdown in PublicInbox::Daemon:
602 sub busy {
603         my ($self, $now) = @_;
604         ($self->{rbuf} || $self->{wbuf} || $self->not_idle_long($now));
605 }
606
607 sub close {
608         my ($self) = @_;
609         if (my $ibx = delete $self->{ibx}) {
610                 if (my $sock = $self->{sock}) {;
611                         $ibx->unsubscribe_unlock(fileno($sock));
612                 }
613         }
614         $self->SUPER::close; # PublicInbox::DS::close
615 }
616
617 # we're read-only, so SELECT and EXAMINE do the same thing
618 no warnings 'once';
619 *cmd_select = \&cmd_examine;
620
621 1;