]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/IMAP.pm
imap: UID FETCH: optimize (UID FLAGS) harder
[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).  We may return a dummy message
13 #   in the future if a client requests a non-existent MSN, but that seems
14 #   unecessary with mutt.
15
16 package PublicInbox::IMAP;
17 use strict;
18 use base qw(PublicInbox::DS);
19 use fields qw(imapd logged_in ibx long_cb -login_tag
20         uid_min -idle_tag -idle_max);
21 use PublicInbox::Eml;
22 use PublicInbox::EmlContentFoo qw(parse_content_disposition);
23 use PublicInbox::DS qw(now);
24 use PublicInbox::Syscall qw(EPOLLIN EPOLLONESHOT);
25 use PublicInbox::GitAsyncCat;
26 use Text::ParseWords qw(parse_line);
27 use Errno qw(EAGAIN);
28 use Time::Local qw(timegm);
29 use POSIX qw(strftime);
30
31 my $Address;
32 for my $mod (qw(Email::Address::XS Mail::Address)) {
33         eval "require $mod" or next;
34         $Address = $mod and last;
35 }
36 die "neither Email::Address::XS nor Mail::Address loaded: $@" if !$Address;
37
38 sub LINE_MAX () { 512 } # does RFC 3501 have a limit like RFC 977?
39
40 # changing this will cause grief for clients which cache
41 sub UID_BLOCK () { 50_000 }
42
43 # these values area also used for sorting
44 sub NEED_SMSG () { 1 }
45 sub NEED_BLOB () { NEED_SMSG|2 }
46 sub NEED_EML () { NEED_BLOB|4 }
47 my $OP_EML_NEW = [ NEED_EML - 1, \&op_eml_new ];
48
49 my %FETCH_NEED = (
50         'BODY[HEADER]' => [ NEED_EML, \&emit_rfc822_header ],
51         'BODY[TEXT]' => [ NEED_EML, \&emit_rfc822_text ],
52         'BODY[]' => [ NEED_BLOB, \&emit_rfc822 ],
53         'RFC822.HEADER' => [ NEED_EML, \&emit_rfc822_header ],
54         'RFC822.TEXT' => [ NEED_EML, \&emit_rfc822_text ],
55         'RFC822.SIZE' => [ NEED_BLOB, \&emit_rfc822_size ],
56         RFC822 => [ NEED_BLOB, \&emit_rfc822 ],
57         BODY => [ NEED_EML, \&emit_body ],
58         BODYSTRUCTURE => [ NEED_EML, \&emit_bodystructure ],
59         ENVELOPE => [ NEED_EML, \&emit_envelope ],
60         FLAGS => [ 0, \&emit_flags ],
61         INTERNALDATE => [ NEED_SMSG, \&emit_internaldate ],
62 );
63 my %FETCH_ATT = map { $_ => [ $_ ] } keys %FETCH_NEED;
64
65 # aliases (RFC 3501 section 6.4.5)
66 $FETCH_ATT{FAST} = [ qw(FLAGS INTERNALDATE RFC822.SIZE) ];
67 $FETCH_ATT{ALL} = [ @{$FETCH_ATT{FAST}}, 'ENVELOPE' ];
68 $FETCH_ATT{FULL} = [ @{$FETCH_ATT{ALL}}, 'BODY' ];
69
70 for my $att (keys %FETCH_ATT) {
71         my %h = map { $_ => $FETCH_NEED{$_} } @{$FETCH_ATT{$att}};
72         $FETCH_ATT{$att} = \%h;
73 }
74 undef %FETCH_NEED;
75
76 my $valid_range = '[0-9]+|[0-9]+:[0-9]+|[0-9]+:\*';
77 $valid_range = qr/\A(?:$valid_range)(?:,(?:$valid_range))*\z/;
78
79 my @MoY = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
80 my %MoY;
81 @MoY{@MoY} = (0..11);
82
83 sub greet ($) {
84         my ($self) = @_;
85         my $capa = capa($self);
86         $self->write(\"* OK [$capa] public-inbox-imapd ready\r\n");
87 }
88
89 sub new ($$$) {
90         my ($class, $sock, $imapd) = @_;
91         my $self = fields::new($class);
92         my $ev = EPOLLIN;
93         my $wbuf;
94         if ($sock->can('accept_SSL') && !$sock->accept_SSL) {
95                 return CORE::close($sock) if $! != EAGAIN;
96                 $ev = PublicInbox::TLS::epollbit();
97                 $wbuf = [ \&PublicInbox::DS::accept_tls_step, \&greet ];
98         }
99         $self->SUPER::new($sock, $ev | EPOLLONESHOT);
100         $self->{imapd} = $imapd;
101         if ($wbuf) {
102                 $self->{wbuf} = $wbuf;
103         } else {
104                 greet($self);
105         }
106         $self->update_idle_time;
107         $self;
108 }
109
110 sub capa ($) {
111         my ($self) = @_;
112
113         # dovecot advertises IDLE pre-login; perhaps because some clients
114         # depend on it, so we'll do the same
115         my $capa = 'CAPABILITY IMAP4rev1 IDLE';
116         if ($self->{logged_in}) {
117                 $capa .= ' COMPRESS=DEFLATE';
118         } else {
119                 if (!($self->{sock} // $self)->can('accept_SSL') &&
120                         $self->{imapd}->{accept_tls}) {
121                         $capa .= ' STARTTLS';
122                 }
123                 $capa .= ' AUTH=ANONYMOUS';
124         }
125 }
126
127 sub login_success ($$) {
128         my ($self, $tag) = @_;
129         $self->{logged_in} = 1;
130         my $capa = capa($self);
131         "$tag OK [$capa] Logged in\r\n";
132 }
133
134 sub auth_challenge_ok ($) {
135         my ($self) = @_;
136         my $tag = delete($self->{-login_tag}) or return;
137         login_success($self, $tag);
138 }
139
140 sub cmd_login ($$$$) {
141         my ($self, $tag) = @_; # ignore ($user, $password) = ($_[2], $_[3])
142         login_success($self, $tag);
143 }
144
145 sub cmd_close ($$) {
146         my ($self, $tag) = @_;
147         delete $self->{uid_min};
148         delete $self->{ibx} ? "$tag OK Close done\r\n"
149                                 : "$tag BAD No mailbox\r\n";
150 }
151
152 sub cmd_logout ($$) {
153         my ($self, $tag) = @_;
154         delete $self->{logged_in};
155         $self->write(\"* BYE logging out\r\n$tag OK Logout done\r\n");
156         $self->shutdn; # PublicInbox::DS::shutdn
157         undef;
158 }
159
160 sub cmd_authenticate ($$$) {
161         my ($self, $tag) = @_; # $method = $_[2], should be "ANONYMOUS"
162         $self->{-login_tag} = $tag;
163         "+\r\n"; # challenge
164 }
165
166 sub cmd_capability ($$) {
167         my ($self, $tag) = @_;
168         '* '.capa($self)."\r\n$tag OK Capability done\r\n";
169 }
170
171 sub cmd_noop ($$) { "$_[1] OK Noop done\r\n" }
172
173 # called by PublicInbox::InboxIdle
174 sub on_inbox_unlock {
175         my ($self, $ibx) = @_;
176         my $new = $ibx->mm->max;
177         defined(my $old = $self->{-idle_max}) or die 'BUG: -idle_max unset';
178         if ($new > $old) {
179                 $self->{-idle_max} = $new;
180                 $self->msg_more("* $_ EXISTS\r\n") for (($old + 1)..($new - 1));
181                 $self->write(\"* $new EXISTS\r\n");
182         }
183 }
184
185 sub cmd_idle ($$) {
186         my ($self, $tag) = @_;
187         # IDLE seems allowed by dovecot w/o a mailbox selected *shrug*
188         my $ibx = $self->{ibx} or return "$tag BAD no mailbox selected\r\n";
189         $ibx->subscribe_unlock(fileno($self->{sock}), $self);
190         $self->{imapd}->idler_start;
191         $self->{-idle_tag} = $tag;
192         $self->{-idle_max} = $ibx->mm->max // 0;
193         "+ idling\r\n"
194 }
195
196 sub cmd_done ($$) {
197         my ($self, $tag) = @_; # $tag is "DONE" (case-insensitive)
198         defined(my $idle_tag = delete $self->{-idle_tag}) or
199                 return "$tag BAD not idle\r\n";
200         my $ibx = $self->{ibx} or do {
201                 warn "BUG: idle_tag set w/o inbox";
202                 return "$tag BAD internal bug\r\n";
203         };
204         $ibx->unsubscribe_unlock(fileno($self->{sock}));
205         "$idle_tag OK Idle done\r\n";
206 }
207
208 sub ensure_ranges_exist ($$$) {
209         my ($imapd, $ibx, $max) = @_;
210         my $mailboxes = $imapd->{mailboxes};
211         my $mb_top = $ibx->{newsgroup};
212         my @created;
213         for (my $i = int($max/UID_BLOCK); $i >= 0; --$i) {
214                 my $sub_mailbox = "$mb_top.$i";
215                 last if exists $mailboxes->{$sub_mailbox};
216                 $mailboxes->{$sub_mailbox} = $ibx;
217                 push @created, $sub_mailbox;
218         }
219         return unless @created;
220         my $l = $imapd->{inboxlist} or return;
221         push @$l, map { qq[* LIST (\\HasNoChildren) "." $_\r\n] } @created;
222 }
223
224 sub inbox_lookup ($$) {
225         my ($self, $mailbox) = @_;
226         my ($ibx, $exists, $uidnext);
227         if ($mailbox =~ /\A(.+)\.([0-9]+)\z/) {
228                 # old mail: inbox.comp.foo.$uid_block_idx
229                 my ($mb_top, $uid_min) = ($1, $2 * UID_BLOCK + 1);
230
231                 $ibx = $self->{imapd}->{mailboxes}->{lc $mailbox} or return;
232                 $exists = $ibx->mm->max // 0;
233                 $self->{uid_min} = $uid_min;
234                 ensure_ranges_exist($self->{imapd}, $ibx, $exists);
235                 my $uid_end = $uid_min + UID_BLOCK - 1;
236                 $exists = $uid_end if $exists > $uid_end;
237                 $uidnext = $exists + 1;
238         } else { # check for dummy inboxes
239                 $ibx = $self->{imapd}->{mailboxes}->{lc $mailbox} or return;
240                 delete $self->{uid_min};
241                 $exists = 0;
242                 $uidnext = 1;
243         }
244         ($ibx, $exists, $uidnext);
245 }
246
247 sub cmd_examine ($$$) {
248         my ($self, $tag, $mailbox) = @_;
249         my ($ibx, $exists, $uidnext) = inbox_lookup($self, $mailbox);
250         return "$tag NO Mailbox doesn't exist: $mailbox\r\n" if !$ibx;
251
252         # XXX: do we need this? RFC 5162/7162
253         my $ret = $self->{ibx} ? "* OK [CLOSED] previous closed\r\n" : '';
254         $self->{ibx} = $ibx;
255         $ret .= <<EOF;
256 * $exists EXISTS\r
257 * $exists RECENT\r
258 * FLAGS (\\Seen)\r
259 * OK [PERMANENTFLAGS ()] Read-only mailbox\r
260 * OK [UNSEEN $exists]\r
261 * OK [UIDNEXT $uidnext]\r
262 * OK [UIDVALIDITY $ibx->{uidvalidity}]\r
263 $tag OK [READ-ONLY] EXAMINE/SELECT done\r
264 EOF
265 }
266
267 sub _esc ($) {
268         my ($v) = @_;
269         if (!defined($v)) {
270                 'NIL';
271         } elsif ($v =~ /[{"\r\n%*\\\[]/) { # literal string
272                 '{' . length($v) . "}\r\n" . $v;
273         } else { # quoted string
274                 qq{"$v"}
275         }
276 }
277
278 sub addr_envelope ($$;$) {
279         my ($eml, $x, $y) = @_;
280         my $v = $eml->header_raw($x) //
281                 ($y ? $eml->header_raw($y) : undef) // return 'NIL';
282
283         my @x = $Address->parse($v) or return 'NIL';
284         '(' . join('',
285                 map { '(' . join(' ',
286                                 _esc($_->name), 'NIL',
287                                 _esc($_->user), _esc($_->host)
288                         ) . ')'
289                 } @x) .
290         ')';
291 }
292
293 sub eml_envelope ($) {
294         my ($eml) = @_;
295         '(' . join(' ',
296                 _esc($eml->header_raw('Date')),
297                 _esc($eml->header_raw('Subject')),
298                 addr_envelope($eml, 'From'),
299                 addr_envelope($eml, 'Sender', 'From'),
300                 addr_envelope($eml, 'Reply-To', 'From'),
301                 addr_envelope($eml, 'To'),
302                 addr_envelope($eml, 'Cc'),
303                 addr_envelope($eml, 'Bcc'),
304                 _esc($eml->header_raw('In-Reply-To')),
305                 _esc($eml->header_raw('Message-ID')),
306         ) . ')';
307 }
308
309 sub _esc_hash ($) {
310         my ($hash) = @_;
311         if ($hash && scalar keys %$hash) {
312                 $hash = [ %$hash ]; # flatten hash into 1-dimensional array
313                 '(' . join(' ', map { _esc($_) } @$hash) . ')';
314         } else {
315                 'NIL';
316         }
317 }
318
319 sub body_disposition ($) {
320         my ($eml) = @_;
321         my $cd = $eml->header_raw('Content-Disposition') or return 'NIL';
322         $cd = parse_content_disposition($cd);
323         my $buf = '('._esc($cd->{type});
324         $buf .= ' ' . _esc_hash(delete $cd->{attributes});
325         $buf .= ')';
326 }
327
328 sub body_leaf ($$;$) {
329         my ($eml, $structure, $hold) = @_;
330         my $buf = '';
331         $eml->{is_submsg} and # parent was a message/(rfc822|news|global)
332                 $buf .= eml_envelope($eml). ' ';
333         my $ct = $eml->ct;
334         $buf .= '('._esc($ct->{type}).' ';
335         $buf .= _esc($ct->{subtype});
336         $buf .= ' ' . _esc_hash(delete $ct->{attributes});
337         $buf .= ' ' . _esc($eml->header_raw('Content-ID'));
338         $buf .= ' ' . _esc($eml->header_raw('Content-Description'));
339         my $cte = $eml->header_raw('Content-Transfer-Encoding') // '7bit';
340         $buf .= ' ' . _esc($cte);
341         $buf .= ' ' . $eml->{imap_body_len};
342         $buf .= ' '.($eml->body_raw =~ tr/\n/\n/) if lc($ct->{type}) eq 'text';
343
344         # for message/(rfc822|global|news), $hold[0] should have envelope
345         $buf .= ' ' . (@$hold ? join('', @$hold) : 'NIL') if $hold;
346
347         if ($structure) {
348                 $buf .= ' '._esc($eml->header_raw('Content-MD5'));
349                 $buf .= ' '. body_disposition($eml);
350                 $buf .= ' '._esc($eml->header_raw('Content-Language'));
351                 $buf .= ' '._esc($eml->header_raw('Content-Location'));
352         }
353         $buf .= ')';
354 }
355
356 sub body_parent ($$$) {
357         my ($eml, $structure, $hold) = @_;
358         my $ct = $eml->ct;
359         my $type = lc($ct->{type});
360         if ($type eq 'multipart') {
361                 my $buf = '(';
362                 $buf .= @$hold ? join('', @$hold) : 'NIL';
363                 $buf .= ' '._esc($ct->{subtype});
364                 if ($structure) {
365                         $buf .= ' '._esc_hash(delete $ct->{attributes});
366                         $buf .= ' '.body_disposition($eml);
367                         $buf .= ' '._esc($eml->header_raw('Content-Language'));
368                         $buf .= ' '._esc($eml->header_raw('Content-Location'));
369                 }
370                 $buf .= ')';
371                 @$hold = ($buf);
372         } else { # message/(rfc822|global|news)
373                 @$hold = (body_leaf($eml, $structure, $hold));
374         }
375 }
376
377 # this is gross, but we need to process the parent part AFTER
378 # the child parts are done
379 sub bodystructure_prep {
380         my ($p, $q) = @_;
381         my ($eml, $depth) = @$p; # ignore idx
382         # set length here, as $eml->{bdy} gets deleted for message/rfc822
383         $eml->{imap_body_len} = length($eml->body_raw);
384         push @$q, $eml, $depth;
385 }
386
387 # for FETCH BODY and FETCH BODYSTRUCTURE
388 sub fetch_body ($;$) {
389         my ($eml, $structure) = @_;
390         my @q;
391         $eml->each_part(\&bodystructure_prep, \@q, 0, 1);
392         my $cur_depth = 0;
393         my @hold;
394         do {
395                 my ($part, $depth) = splice(@q, -2);
396                 my $is_mp_parent = $depth == ($cur_depth - 1);
397                 $cur_depth = $depth;
398
399                 if ($is_mp_parent) {
400                         body_parent($part, $structure, \@hold);
401                 } else {
402                         unshift @hold, body_leaf($part, $structure);
403                 }
404         } while (@q);
405         join('', @hold);
406 }
407
408 sub requeue_once ($) {
409         my ($self) = @_;
410         # COMPRESS users all share the same DEFLATE context.
411         # Flush it here to ensure clients don't see
412         # each other's data
413         $self->zflush;
414
415         # no recursion, schedule another call ASAP,
416         # but only after all pending writes are done.
417         # autovivify wbuf:
418         my $new_size = push(@{$self->{wbuf}}, \&long_step);
419
420         # wbuf may be populated by $cb, no need to rearm if so:
421         $self->requeue if $new_size == 1;
422 }
423
424 sub uid_fetch_cb { # called by git->cat_async via git_async_cat
425         my ($bref, $oid, $type, $size, $fetch_m_arg) = @_;
426         my ($self, undef, $msgs, undef, $ops, $partial) = @$fetch_m_arg;
427         my $smsg = shift @$msgs or die 'BUG: no smsg';
428         if (!defined($oid)) {
429                 # it's possible to have TOCTOU if an admin runs
430                 # public-inbox-(edit|purge), just move onto the next message
431                 return requeue_once($self);
432         } else {
433                 $smsg->{blob} eq $oid or die "BUG: $smsg->{blob} != $oid";
434         }
435         $$bref =~ s/(?<!\r)\n/\r\n/sg; # make strict clients happy
436
437         # fixup old bug from import (pre-a0c07cba0e5d8b6a)
438         $$bref =~ s/\A[\r\n]*From [^\r\n]*\r\n//s;
439         $self->msg_more("* $smsg->{num} FETCH (UID $smsg->{num}");
440         my $eml;
441         for (my $i = 0; $i < @$ops;) {
442                 my $k = $ops->[$i++];
443                 $ops->[$i++]->($self, $k, $smsg, $bref, $eml);
444         }
445         partial_emit($self, $partial, $eml) if $partial;
446         $self->msg_more(")\r\n");
447         requeue_once($self);
448 }
449
450 sub emit_rfc822 {
451         my ($self, $k, undef, $bref) = @_;
452         $self->msg_more(" $k {" . length($$bref)."}\r\n");
453         $self->msg_more($$bref);
454 }
455
456 # Mail::IMAPClient::message_string cares about this by default
457 # (->Ignoresizeerrors attribute)
458 sub emit_rfc822_size {
459         my ($self, $k, undef, $bref) = @_;
460         $self->msg_more(' RFC822.SIZE ' . length($$bref));
461 }
462
463 sub emit_internaldate {
464         my ($self, undef, $smsg) = @_;
465         $self->msg_more(' INTERNALDATE "'.$smsg->internaldate.'"');
466 }
467
468 sub emit_flags { $_[0]->msg_more(' FLAGS ()') }
469
470 sub emit_envelope {
471         my ($self, undef, undef, undef, $eml) = @_;
472         $self->msg_more(' ENVELOPE '.eml_envelope($eml));
473 }
474
475 sub emit_rfc822_header {
476         my ($self, $k, undef, undef, $eml) = @_;
477         $self->msg_more(" $k {".length(${$eml->{hdr}})."}\r\n");
478         $self->msg_more(${$eml->{hdr}});
479 }
480
481 # n.b. this is sorted to be after any emit_eml_new ops
482 sub emit_rfc822_text {
483         my ($self, $k, undef, $bref) = @_;
484         $self->msg_more(" $k {".length($$bref)."}\r\n");
485         $self->msg_more($$bref);
486 }
487
488 sub emit_bodystructure {
489         my ($self, undef, undef, undef, $eml) = @_;
490         $self->msg_more(' BODYSTRUCTURE '.fetch_body($eml, 1));
491 }
492
493 sub emit_body {
494         my ($self, undef, undef, undef, $eml) = @_;
495         $self->msg_more(' BODY '.fetch_body($eml));
496 }
497
498 # set $eml once ($_[4] == $eml, $_[3] == $bref)
499 sub op_eml_new { $_[4] = PublicInbox::Eml->new($_[3]) }
500
501 sub uid_clamp ($$$) {
502         my ($self, $beg, $end) = @_;
503         my $uid_min = $self->{uid_min} or return;
504         my $uid_end = $uid_min + UID_BLOCK - 1;
505         $$beg = $uid_min if $$beg < $uid_min;
506         $$end = $uid_end if $$end > $uid_end;
507 }
508
509 sub range_step ($$) {
510         my ($self, $range_csv) = @_;
511         my ($beg, $end, $range);
512         if ($$range_csv =~ s/\A([^,]+),//) {
513                 $range = $1;
514         } else {
515                 $range = $$range_csv;
516                 $$range_csv = undef;
517         }
518         if ($range =~ /\A([0-9]+):([0-9]+)\z/) {
519                 ($beg, $end) = ($1 + 0, $2 + 0);
520         } elsif ($range =~ /\A([0-9]+):\*\z/) {
521                 $beg = $1 + 0;
522                 $end = $self->{ibx}->mm->max // 0;
523                 my $uid_end = ($self->{uid_min} // 1) - 1 + UID_BLOCK;
524                 $end = $uid_end if $end > $uid_end;
525                 $beg = $end if $beg > $end;
526         } elsif ($range =~ /\A[0-9]+\z/) {
527                 $beg = $end = $range + 0;
528                 undef $range;
529         } else {
530                 return 'BAD fetch range';
531         }
532         uid_clamp($self, \$beg, \$end) if defined($range);
533         [ $beg, $end, $$range_csv ];
534 }
535
536 sub refill_range ($$$) {
537         my ($self, $msgs, $range_info) = @_;
538         my ($beg, $end, $range_csv) = @$range_info;
539         if (scalar(@$msgs = @{$self->{ibx}->over->query_xover($beg, $end)})) {
540                 $range_info->[0] = $msgs->[-1]->{num} + 1;
541                 return;
542         }
543         return 'OK Fetch done' if !$range_csv;
544         my $next_range = range_step($self, \$range_csv);
545         return $next_range if !ref($next_range); # error
546         @$range_info = @$next_range;
547         undef; # keep looping
548 }
549
550 sub uid_fetch_msg { # long_response
551         my ($self, $tag, $msgs, $range_info) = @_; # \@ops, \@partial
552         while (!@$msgs) { # rare
553                 if (my $end = refill_range($self, $msgs, $range_info)) {
554                         $self->write(\"$tag $end\r\n");
555                         return;
556                 }
557         }
558         git_async_cat($self->{ibx}->git, $msgs->[0]->{blob},
559                         \&uid_fetch_cb, \@_);
560 }
561
562 sub uid_fetch_smsg { # long_response
563         my ($self, $tag, $msgs, $range_info, $ops) = @_;
564         while (!@$msgs) { # rare
565                 if (my $end = refill_range($self, $msgs, $range_info)) {
566                         $self->write(\"$tag $end\r\n");
567                         return;
568                 }
569         }
570         for my $smsg (@$msgs) {
571                 $self->msg_more("* $smsg->{num} FETCH (UID $smsg->{num}");
572                 for (my $i = 0; $i < @$ops;) {
573                         my $k = $ops->[$i++];
574                         $ops->[$i++]->($self, $k, $smsg);
575                 }
576                 $self->msg_more(")\r\n");
577         }
578         @$msgs = ();
579         1; # more
580 }
581
582 sub uid_fetch_uid { # long_response
583         my ($self, $tag, $uids, $range_info, $ops) = @_;
584         while (!@$uids) { # rare
585                 my ($beg, $end, $range_csv) = @$range_info;
586                 if (scalar(@$uids = @{$self->{ibx}->over->
587                                         uid_range($beg, $end)})) {
588                         $range_info->[0] = $uids->[-1] + 1;
589                 } elsif (!$range_csv) {
590                         $self->write(\"$tag OK Fetch done\r\n");
591                         return;
592                 } else {
593                         my $next_range = range_step($self, \$range_csv);
594                         if (!ref($next_range)) { # error
595                                 $self->write(\"$tag $next_range\r\n");
596                                 return;
597                         }
598                         @$range_info = @$next_range;
599                 }
600                 # continue looping
601         }
602         for (@$uids) {
603                 $self->msg_more("* $_ FETCH (UID $_");
604                 for (my $i = 0; $i < @$ops;) {
605                         my $k = $ops->[$i++];
606                         $ops->[$i++]->($self, $k);
607                 }
608                 $self->msg_more(")\r\n");
609         }
610         @$uids = ();
611         1; # more
612 }
613
614 sub cmd_status ($$$;@) {
615         my ($self, $tag, $mailbox, @items) = @_;
616         return "$tag BAD no items\r\n" if !scalar(@items);
617         ($items[0] !~ s/\A\(//s || $items[-1] !~ s/\)\z//s) and
618                 return "$tag BAD invalid args\r\n";
619         my ($ibx, $exists, $uidnext) = inbox_lookup($self, $mailbox);
620         return "$tag NO Mailbox doesn't exist: $mailbox\r\n" if !$ibx;
621         my @it;
622         for my $it (@items) {
623                 $it = uc($it);
624                 push @it, $it;
625                 if ($it =~ /\A(?:MESSAGES|UNSEEN|RECENT)\z/) {
626                         push @it, $exists;
627                 } elsif ($it eq 'UIDNEXT') {
628                         push @it, $uidnext;
629                 } elsif ($it eq 'UIDVALIDITY') {
630                         push @it, $ibx->{uidvalidity};
631                 } else {
632                         return "$tag BAD invalid item\r\n";
633                 }
634         }
635         return "$tag BAD no items\r\n" if !@it;
636         "* STATUS $mailbox (".join(' ', @it).")\r\n" .
637         "$tag OK Status done\r\n";
638 }
639
640 my %patmap = ('*' => '.*', '%' => '[^\.]*');
641 sub cmd_list ($$$$) {
642         my ($self, $tag, $refname, $wildcard) = @_;
643         my $l = $self->{imapd}->{inboxlist};
644         if ($refname eq '' && $wildcard eq '') {
645                 # request for hierarchy delimiter
646                 $l = [ qq[* LIST (\\Noselect) "." ""\r\n] ];
647         } elsif ($refname ne '' || $wildcard ne '*') {
648                 $wildcard = lc $wildcard;
649                 $wildcard =~ s!([^a-z0-9_])!$patmap{$1} // "\Q$1"!eg;
650                 $l = [ grep(/ \Q$refname\E$wildcard\r\n\z/s, @$l) ];
651         }
652         \(join('', @$l, "$tag OK List done\r\n"));
653 }
654
655 sub cmd_lsub ($$$$) {
656         my (undef, $tag) = @_; # same args as cmd_list
657         "$tag OK Lsub done\r\n";
658 }
659
660 sub eml_index_offs_i { # PublicInbox::Eml::each_part callback
661         my ($p, $all) = @_;
662         my ($eml, undef, $idx) = @$p;
663         if ($idx && lc($eml->ct->{type}) eq 'multipart') {
664                 $eml->{imap_bdy} = $eml->{bdy} // \'';
665         }
666         $all->{$idx} = $eml; # $idx => Eml
667 }
668
669 # prepares an index for BODY[$SECTION_IDX] fetches
670 sub eml_body_idx ($$) {
671         my ($eml, $section_idx) = @_;
672         my $idx = $eml->{imap_all_parts} //= do {
673                 my $all = {};
674                 $eml->each_part(\&eml_index_offs_i, $all, 0, 1);
675                 # top-level of multipart, BODY[0] not allowed (nz-number)
676                 delete $all->{0};
677                 $all;
678         };
679         $idx->{$section_idx};
680 }
681
682 # BODY[($SECTION_IDX)?(.$SECTION_NAME)?]<$offset.$bytes>
683 sub partial_body {
684         my ($eml, $section_idx, $section_name) = @_;
685         if (defined $section_idx) {
686                 $eml = eml_body_idx($eml, $section_idx) or return;
687         }
688         if (defined $section_name) {
689                 if ($section_name eq 'MIME') {
690                         # RFC 3501 6.4.5 states:
691                         #       The MIME part specifier MUST be prefixed
692                         #       by one or more numeric part specifiers
693                         return unless defined $section_idx;
694                         return $eml->header_obj->as_string . "\r\n";
695                 }
696                 my $bdy = $eml->{bdy} // $eml->{imap_bdy} // \'';
697                 $eml = PublicInbox::Eml->new($$bdy);
698                 if ($section_name eq 'TEXT') {
699                         return $eml->body_raw;
700                 } elsif ($section_name eq 'HEADER') {
701                         return $eml->header_obj->as_string . "\r\n";
702                 } else {
703                         die "BUG: bad section_name=$section_name";
704                 }
705         }
706         ${$eml->{bdy} // $eml->{imap_bdy} // \''};
707 }
708
709 # similar to what's in PublicInbox::Eml::re_memo, but doesn't memoize
710 # to avoid OOM with malicious users
711 sub hdrs_regexp ($) {
712         my ($hdrs) = @_;
713         my $names = join('|', map { "\Q$_" } split(/[ \t]+/, $hdrs));
714         qr/^(?:$names):[ \t]*[^\n]*\r?\n # 1st line
715                 # continuation lines:
716                 (?:[^:\n]*?[ \t]+[^\n]*\r?\n)*
717                 /ismx;
718 }
719
720 # BODY[($SECTION_IDX.)?HEADER.FIELDS.NOT ($HDRS)]<$offset.$bytes>
721 sub partial_hdr_not {
722         my ($eml, $section_idx, $hdrs_re) = @_;
723         if (defined $section_idx) {
724                 $eml = eml_body_idx($eml, $section_idx) or return;
725         }
726         my $str = $eml->header_obj->as_string;
727         $str =~ s/$hdrs_re//g;
728         $str .= "\r\n";
729 }
730
731 # BODY[($SECTION_IDX.)?HEADER.FIELDS ($HDRS)]<$offset.$bytes>
732 sub partial_hdr_get {
733         my ($eml, $section_idx, $hdrs_re) = @_;
734         if (defined $section_idx) {
735                 $eml = eml_body_idx($eml, $section_idx) or return;
736         }
737         my $str = $eml->header_obj->as_string;
738         join('', ($str =~ m/($hdrs_re)/g), "\r\n");
739 }
740
741 sub partial_prepare ($$$) {
742         my ($partial, $want, $att) = @_;
743
744         # recombine [ "BODY[1.HEADER.FIELDS", "(foo", "bar)]" ]
745         # back to: "BODY[1.HEADER.FIELDS (foo bar)]"
746         return unless $att =~ /\ABODY\[/s;
747         until (rindex($att, ']') >= 0) {
748                 my $next = shift @$want or return;
749                 $att .= ' ' . uc($next);
750         }
751         if ($att =~ /\ABODY\[([0-9]+(?:\.[0-9]+)*)? # 1 - section_idx
752                         (?:\.(HEADER|MIME|TEXT))? # 2 - section_name
753                         \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 3, 4
754                 $partial->{$att} = [ \&partial_body, $1, $2, $3, $4 ];
755         } elsif ($att =~ /\ABODY\[(?:([0-9]+(?:\.[0-9]+)*)\.)? # 1 - section_idx
756                                 (?:HEADER\.FIELDS(\.NOT)?)\x20 # 2
757                                 \(([A-Z0-9\-\x20]+)\) # 3 - hdrs
758                         \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 4 5
759                 my $tmp = $partial->{$att} = [ $2 ? \&partial_hdr_not
760                                                 : \&partial_hdr_get,
761                                                 $1, undef, $4, $5 ];
762                 $tmp->[2] = hdrs_regexp($3);
763         } else {
764                 undef;
765         }
766 }
767
768 sub partial_emit ($$$) {
769         my ($self, $partial, $eml) = @_;
770         for (@$partial) {
771                 my ($k, $cb, @args) = @$_;
772                 my ($offset, $len) = splice(@args, -2);
773                 # $cb is partial_body|partial_hdr_get|partial_hdr_not
774                 my $str = $cb->($eml, @args) // '';
775                 if (defined $offset) {
776                         if (defined $len) {
777                                 $str = substr($str, $offset, $len);
778                                 $k =~ s/\.$len>\z/>/ or warn
779 "BUG: unable to remove `.$len>' from `$k'";
780                         } else {
781                                 $str = substr($str, $offset);
782                                 $len = length($str);
783                         }
784                 } else {
785                         $len = length($str);
786                 }
787                 $self->msg_more(" $k {$len}\r\n");
788                 $self->msg_more($str);
789         }
790 }
791
792 sub fetch_compile ($) {
793         my ($want) = @_;
794         if ($want->[0] =~ s/\A\(//s) {
795                 $want->[-1] =~ s/\)\z//s or return 'BAD no rparen';
796         }
797         my (%partial, %seen, @op);
798         my $need = 0;
799         while (defined(my $att = shift @$want)) {
800                 $att = uc($att);
801                 next if $att eq 'UID'; # always returned
802                 $att =~ s/\ABODY\.PEEK\[/BODY\[/; # we're read-only
803                 my $x = $FETCH_ATT{$att};
804                 if ($x) {
805                         while (my ($k, $fl_cb) = each %$x) {
806                                 next if $seen{$k}++;
807                                 $need |= $fl_cb->[0];
808
809                                 # insert a special op to convert $bref to $eml
810                                 # the first time we need it
811                                 if ($need == NEED_EML && !$seen{$need}++) {
812                                         push @op, $OP_EML_NEW;
813                                 }
814                                 # $fl_cb = [ flags, \&emit_foo ]
815                                 push @op, [ @$fl_cb , $k ];
816                         }
817                 } elsif (!partial_prepare(\%partial, $want, $att)) {
818                         return "BAD param: $att";
819                 }
820         }
821         my @r;
822
823         # stabilize partial order for consistency and ease-of-debugging:
824         if (scalar keys %partial) {
825                 $need = NEED_EML;
826                 push @op, $OP_EML_NEW if !$seen{$need}++;
827                 $r[2] = [ map { [ $_, @{$partial{$_}} ] } sort keys %partial ];
828         }
829
830         $r[0] = $need & NEED_BLOB ? \&uid_fetch_msg :
831                 ($need & NEED_SMSG ? \&uid_fetch_smsg : \&uid_fetch_uid);
832
833         # r[1] = [ $key1, $cb1, $key2, $cb2, ... ]
834         use sort 'stable'; # makes output more consistent
835         $r[1] = [ map { ($_->[2], $_->[1]) } sort { $a->[0] <=> $b->[0] } @op ];
836         @r;
837 }
838
839 sub cmd_uid_fetch ($$$;@) {
840         my ($self, $tag, $range_csv, @want) = @_;
841         my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
842         my ($cb, $ops, $partial) = fetch_compile(\@want);
843         return "$tag $cb\r\n" unless $ops;
844
845         $range_csv = 'bad' if $range_csv !~ $valid_range;
846         my $range_info = range_step($self, \$range_csv);
847         return "$tag $range_info\r\n" if !ref($range_info);
848         long_response($self, $cb, $tag, [], $range_info, $ops, $partial);
849 }
850
851 sub parse_date ($) { # 02-Oct-1993
852         my ($date_text) = @_;
853         my ($dd, $mon, $yyyy) = split(/-/, $_[0], 3);
854         defined($yyyy) or return;
855         my $mm = $MoY{$mon} // return;
856         $dd =~ /\A[0123]?[0-9]\z/ or return;
857         $yyyy =~ /\A[0-9]{4,}\z/ or return; # Y10K-compatible!
858         timegm(0, 0, 0, $dd, $mm, $yyyy);
859 }
860
861 sub uid_search_uid_range { # long_response
862         my ($self, $tag, $beg, $end, $sql) = @_;
863         my $uids = $self->{ibx}->over->uid_range($$beg, $end, $sql);
864         if (@$uids) {
865                 $$beg = $uids->[-1] + 1;
866                 $self->msg_more(join(' ', '', @$uids));
867         } else {
868                 $self->write(\"\r\n$tag OK Search done\r\n");
869                 undef;
870         }
871 }
872
873 sub date_search {
874         my ($q, $k, $d) = @_;
875         my $sql = $q->{sql};
876
877         # Date: header
878         if ($k eq 'SENTON') {
879                 my $end = $d + 86399; # no leap day...
880                 my $da = strftime('%Y%m%d%H%M%S', gmtime($d));
881                 my $db = strftime('%Y%m%d%H%M%S', gmtime($end));
882                 $q->{xap} .= " dt:$da..$db";
883                 $$sql .= " AND ds >= $d AND ds <= $end" if defined($sql);
884         } elsif ($k eq 'SENTBEFORE') {
885                 $q->{xap} .= ' d:..'.strftime('%Y%m%d', gmtime($d));
886                 $$sql .= " AND ds <= $d" if defined($sql);
887         } elsif ($k eq 'SENTSINCE') {
888                 $q->{xap} .= ' d:'.strftime('%Y%m%d', gmtime($d)).'..';
889                 $$sql .= " AND ds >= $d" if defined($sql);
890
891         # INTERNALDATE (Received)
892         } elsif ($k eq 'ON') {
893                 my $end = $d + 86399; # no leap day...
894                 $q->{xap} .= " ts:$d..$end";
895                 $$sql .= " AND ts >= $d AND ts <= $end" if defined($sql);
896         } elsif ($k eq 'BEFORE') {
897                 $q->{xap} .= " ts:..$d";
898                 $$sql .= " AND ts <= $d" if defined($sql);
899         } elsif ($k eq 'SINCE') {
900                 $q->{xap} .= " ts:$d..";
901                 $$sql .= " AND ts >= $d" if defined($sql);
902         } else {
903                 die "BUG: $k not recognized";
904         }
905 }
906
907 # IMAP to Xapian search key mapping
908 my %I2X = (
909         SUBJECT => 's:',
910         BODY => 'b:',
911         FROM => 'f:',
912         TEXT => '', # n.b. does not include all headers
913         TO => 't:',
914         CC => 'c:',
915         # BCC => 'bcc:', # TODO
916         # KEYWORD # TODO ? dfpre,dfpost,...
917 );
918
919 sub parse_query {
920         my ($self, $rest) = @_;
921         if (uc($rest->[0]) eq 'CHARSET') {
922                 shift @$rest;
923                 defined(my $c = shift @$rest) or return 'BAD missing charset';
924                 $c =~ /\A(?:UTF-8|US-ASCII)\z/ or return 'NO [BADCHARSET]';
925         }
926
927         my $sql = ''; # date conditions, {sql} deleted if Xapian is needed
928         my $q = { xap => '', sql => \$sql };
929         while (@$rest) {
930                 my $k = uc(shift @$rest);
931                 # default criteria
932                 next if $k =~ /\A(?:ALL|RECENT|UNSEEN|NEW)\z/;
933                 next if $k eq 'AND'; # the default, until we support OR
934                 if ($k =~ $valid_range) { # sequence numbers == UIDs
935                         push @{$q->{uid}}, $k;
936                 } elsif ($k eq 'UID') {
937                         $k = shift(@$rest) // '';
938                         $k =~ $valid_range or return 'BAD UID range';
939                         push @{$q->{uid}}, $k;
940                 } elsif ($k =~ /\A(?:SENT)?(?:SINCE|ON|BEFORE)\z/) {
941                         my $d = parse_date(shift(@$rest) // '');
942                         defined $d or return "BAD $k date format";
943                         date_search($q, $k, $d);
944                 } elsif ($k =~ /\A(?:SMALLER|LARGER)\z/) {
945                         delete $q->{sql}; # can't use over.sqlite3
946                         my $bytes = shift(@$rest) // '';
947                         $bytes =~ /\A[0-9]+\z/ or return "BAD $k not a number";
948                         $q->{xap} .= ' bytes:' . ($k eq 'SMALLER' ?
949                                                         '..'.(--$bytes) :
950                                                         (++$bytes).'..');
951                 } elsif (defined(my $xk = $I2X{$k})) {
952                         delete $q->{sql}; # can't use over.sqlite3
953                         my $arg = shift @$rest;
954                         defined($arg) or return "BAD $k no arg";
955
956                         # Xapian can't handle [*"] in probabilistic terms
957                         $arg =~ tr/*"//d;
958                         $q->{xap} .= qq[ $xk:"$arg"];
959                 } else {
960                         # TODO: parentheses, OR, NOT ...
961                         return "BAD $k not supported (yet?)";
962                 }
963         }
964
965         # favor using over.sqlite3 if possible, since Xapian is optional
966         if (exists $q->{sql}) {
967                 delete($q->{xap});
968                 delete($q->{sql}) if $sql eq '';
969         } elsif (!$self->{ibx}->search) {
970                 return 'BAD Xapian not configured for mailbox';
971         }
972
973         if (my $uid = $q->{uid}) {
974                 ((@$uid > 1) || $uid->[0] =~ /,/) and
975                         return 'BAD multiple ranges not supported, yet';
976                 ($q->{sql} // $q->{xap}) and
977                         return 'BAD ranges and queries do not mix, yet';
978                 $q->{uid} = join(',', @$uid); # TODO: multiple ranges
979         }
980         $q;
981 }
982
983 sub cmd_uid_search ($$$;) {
984         my ($self, $tag) = splice(@_, 0, 2);
985         my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
986         my $q = parse_query($self, \@_);
987         return "$tag $q\r\n" if !ref($q);
988         my $sql = delete $q->{sql};
989
990         if (!scalar(keys %$q)) {
991                 $self->msg_more('* SEARCH');
992                 my $beg = $self->{uid_min} // 1;
993                 my $end = $ibx->mm->max;
994                 uid_clamp($self, \$beg, \$end);
995                 long_response($self, \&uid_search_uid_range,
996                                 $tag, \$beg, $end, $sql);
997         } elsif (my $uid = $q->{uid}) {
998                 if ($uid =~ /\A([0-9]+):([0-9]+|\*)\z/s) {
999                         my ($beg, $end) = ($1, $2);
1000                         $end = $ibx->mm->max if $end eq '*';
1001                         uid_clamp($self, \$beg, \$end);
1002                         $self->msg_more('* SEARCH');
1003                         long_response($self, \&uid_search_uid_range,
1004                                         $tag, \$beg, $end, $sql);
1005                 } elsif ($uid =~ /\A[0-9]+\z/s) {
1006                         $uid = $ibx->over->get_art($uid) ? " $uid" : '';
1007                         "* SEARCH$uid\r\n$tag OK Search done\r\n";
1008                 } else {
1009                         "$tag BAD Error\r\n";
1010                 }
1011         } else {
1012                 "$tag BAD Error\r\n";
1013         }
1014 }
1015
1016 sub args_ok ($$) { # duplicated from PublicInbox::NNTP
1017         my ($cb, $argc) = @_;
1018         my $tot = prototype $cb;
1019         my ($nreq, undef) = split(';', $tot);
1020         $nreq = ($nreq =~ tr/$//) - 1;
1021         $tot = ($tot =~ tr/$//) - 1;
1022         ($argc <= $tot && $argc >= $nreq);
1023 }
1024
1025 # returns 1 if we can continue, 0 if not due to buffered writes or disconnect
1026 sub process_line ($$) {
1027         my ($self, $l) = @_;
1028         my ($tag, $req, @args) = parse_line('[ \t]+', 0, $l);
1029         pop(@args) if (@args && !defined($args[-1]));
1030         if (@args && uc($req) eq 'UID') {
1031                 $req .= "_".(shift @args);
1032         }
1033         my $res = eval {
1034                 if (my $cmd = $self->can('cmd_'.lc($req // ''))) {
1035                         defined($self->{-idle_tag}) ?
1036                                 "$self->{-idle_tag} BAD expected DONE\r\n" :
1037                                 $cmd->($self, $tag, @args);
1038                 } elsif (uc($tag // '') eq 'DONE' && !defined($req)) {
1039                         cmd_done($self, $tag);
1040                 } else { # this is weird
1041                         auth_challenge_ok($self) //
1042                                         ($tag // '*') .
1043                                         ' BAD Error in IMAP command '.
1044                                         ($req // '(???)').
1045                                         ": Unknown command\r\n";
1046                 }
1047         };
1048         my $err = $@;
1049         if ($err && $self->{sock}) {
1050                 $l =~ s/\r?\n//s;
1051                 err($self, 'error from: %s (%s)', $l, $err);
1052                 $tag //= '*';
1053                 $res = "$tag BAD program fault - command not performed\r\n";
1054         }
1055         return 0 unless defined $res;
1056         $self->write($res);
1057 }
1058
1059 sub long_step {
1060         my ($self) = @_;
1061         # wbuf is unset or empty, here; {long} may add to it
1062         my ($fd, $cb, $t0, @args) = @{$self->{long_cb}};
1063         my $more = eval { $cb->($self, @args) };
1064         if ($@ || !$self->{sock}) { # something bad happened...
1065                 delete $self->{long_cb};
1066                 my $elapsed = now() - $t0;
1067                 if ($@) {
1068                         err($self,
1069                             "%s during long response[$fd] - %0.6f",
1070                             $@, $elapsed);
1071                 }
1072                 out($self, " deferred[$fd] aborted - %0.6f", $elapsed);
1073                 $self->close;
1074         } elsif ($more) { # $self->{wbuf}:
1075                 $self->update_idle_time;
1076
1077                 # control passed to $more may be a GitAsyncCat object
1078                 requeue_once($self) if !ref($more);
1079         } else { # all done!
1080                 delete $self->{long_cb};
1081                 my $elapsed = now() - $t0;
1082                 my $fd = fileno($self->{sock});
1083                 out($self, " deferred[$fd] done - %0.6f", $elapsed);
1084                 my $wbuf = $self->{wbuf}; # do NOT autovivify
1085
1086                 $self->requeue unless $wbuf && @$wbuf;
1087         }
1088 }
1089
1090 sub err ($$;@) {
1091         my ($self, $fmt, @args) = @_;
1092         printf { $self->{imapd}->{err} } $fmt."\n", @args;
1093 }
1094
1095 sub out ($$;@) {
1096         my ($self, $fmt, @args) = @_;
1097         printf { $self->{imapd}->{out} } $fmt."\n", @args;
1098 }
1099
1100 sub long_response ($$;@) {
1101         my ($self, $cb, @args) = @_; # cb returns true if more, false if done
1102
1103         my $sock = $self->{sock} or return;
1104         # make sure we disable reading during a long response,
1105         # clients should not be sending us stuff and making us do more
1106         # work while we are stream a response to them
1107         $self->{long_cb} = [ fileno($sock), $cb, now(), @args ];
1108         long_step($self); # kick off!
1109         undef;
1110 }
1111
1112 # callback used by PublicInbox::DS for any (e)poll (in/out/hup/err)
1113 sub event_step {
1114         my ($self) = @_;
1115
1116         return unless $self->flush_write && $self->{sock} && !$self->{long_cb};
1117
1118         $self->update_idle_time;
1119         # only read more requests if we've drained the write buffer,
1120         # otherwise we can be buffering infinitely w/o backpressure
1121
1122         my $rbuf = $self->{rbuf} // \(my $x = '');
1123         my $line = index($$rbuf, "\n");
1124         while ($line < 0) {
1125                 return $self->close if length($$rbuf) >= LINE_MAX;
1126                 $self->do_read($rbuf, LINE_MAX, length($$rbuf)) or return;
1127                 $line = index($$rbuf, "\n");
1128         }
1129         $line = substr($$rbuf, 0, $line + 1, '');
1130         $line =~ s/\r?\n\z//s;
1131         return $self->close if $line =~ /[[:cntrl:]]/s;
1132         my $t0 = now();
1133         my $fd = fileno($self->{sock});
1134         my $r = eval { process_line($self, $line) };
1135         my $pending = $self->{wbuf} ? ' pending' : '';
1136         out($self, "[$fd] %s - %0.6f$pending - $r", $line, now() - $t0);
1137
1138         return $self->close if $r < 0;
1139         $self->rbuf_idle($rbuf);
1140         $self->update_idle_time;
1141
1142         # maybe there's more pipelined data, or we'll have
1143         # to register it for socket-readiness notifications
1144         $self->requeue unless $pending;
1145 }
1146
1147 sub compressed { undef }
1148
1149 sub zflush {} # overridden by IMAPdeflate
1150
1151 # RFC 4978
1152 sub cmd_compress ($$$) {
1153         my ($self, $tag, $alg) = @_;
1154         return "$tag BAD DEFLATE only\r\n" if uc($alg) ne "DEFLATE";
1155         return "$tag BAD COMPRESS active\r\n" if $self->compressed;
1156
1157         # CRIME made TLS compression obsolete
1158         # return "$tag NO [COMPRESSIONACTIVE]\r\n" if $self->tls_compressed;
1159
1160         PublicInbox::IMAPdeflate->enable($self, $tag);
1161         $self->requeue;
1162         undef
1163 }
1164
1165 sub cmd_starttls ($$) {
1166         my ($self, $tag) = @_;
1167         my $sock = $self->{sock} or return;
1168         if ($sock->can('stop_SSL') || $self->compressed) {
1169                 return "$tag BAD TLS or compression already enabled\r\n";
1170         }
1171         my $opt = $self->{imapd}->{accept_tls} or
1172                 return "$tag BAD can not initiate TLS negotiation\r\n";
1173         $self->write(\"$tag OK begin TLS negotiation now\r\n");
1174         $self->{sock} = IO::Socket::SSL->start_SSL($sock, %$opt);
1175         $self->requeue if PublicInbox::DS::accept_tls_step($self);
1176         undef;
1177 }
1178
1179 # for graceful shutdown in PublicInbox::Daemon:
1180 sub busy {
1181         my ($self, $now) = @_;
1182         ($self->{rbuf} || $self->{wbuf} || $self->not_idle_long($now));
1183 }
1184
1185 sub close {
1186         my ($self) = @_;
1187         if (my $ibx = delete $self->{ibx}) {
1188                 if (my $sock = $self->{sock}) {;
1189                         $ibx->unsubscribe_unlock(fileno($sock));
1190                 }
1191         }
1192         $self->SUPER::close; # PublicInbox::DS::close
1193 }
1194
1195 # we're read-only, so SELECT and EXAMINE do the same thing
1196 no warnings 'once';
1197 *cmd_select = \&cmd_examine;
1198 *cmd_fetch = \&cmd_uid_fetch;
1199
1200 1;