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