1 # Copyright (C) 2020-2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
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
11 # * NNTP article numbers are UIDs, mm->created_at is UIDVALIDITY
13 # * public-inboxes are sliced into mailboxes of 50K messages
14 # to not overload MUAs: $NEWSGROUP_NAME.$SLICE_INDEX
15 # Slices are similar in concept to v2 "epochs". Epochs
16 # are for the limitations of git clients, while slices are
17 # for the limitations of IMAP clients.
19 # * We also take advantage of slices being only 50K to store
20 # "UID offset" to message sequence number (MSN) mapping
21 # as a 50K uint16_t array (via pack("S*", ...)). "UID offset"
22 # is the offset from {uid_base} which determines the start of
26 # imapd: PublicInbox::IMAPD ref
27 # ibx: PublicInbox::Inbox ref
28 # long_cb: long_response private data
29 # uid_base: base UID for mailbox slice (0-based)
30 # -login_tag: IMAP TAG for LOGIN
31 # -idle_tag: IMAP response tag for IDLE
32 # uo2m: UID-to-MSN mapping
33 package PublicInbox::IMAP;
35 use parent qw(PublicInbox::DS);
37 use PublicInbox::EmlContentFoo qw(parse_content_disposition);
38 use PublicInbox::DS qw(now);
39 use PublicInbox::Syscall qw(EPOLLIN EPOLLONESHOT);
40 use PublicInbox::GitAsyncCat;
41 use Text::ParseWords qw(parse_line);
43 use PublicInbox::IMAPsearchqp;
46 for my $mod (qw(Email::Address::XS Mail::Address)) {
47 eval "require $mod" or next;
48 $Address = $mod and last;
50 die "neither Email::Address::XS nor Mail::Address loaded: $@" if !$Address;
52 sub LINE_MAX () { 8000 } # RFC 2683 3.2.1.5
54 # Changing UID_SLICE will cause grief for clients which cache.
55 # This also needs to be <64K: we pack it into a uint16_t
56 # for long_response UID (offset) => MSN mappings
57 sub UID_SLICE () { 50_000 }
59 # these values area also used for sorting
60 sub NEED_SMSG () { 1 }
61 sub NEED_BLOB () { NEED_SMSG|2 }
62 sub CRLF_BREF () { 4 }
64 sub CRLF_HDR () { 16 }
66 sub CRLF_BDY () { 64 }
67 my $OP_EML_NEW = [ EML_HDR - 1, \&op_eml_new ];
68 my $OP_CRLF_BREF = [ CRLF_BREF, \&op_crlf_bref ];
69 my $OP_CRLF_HDR = [ CRLF_HDR, \&op_crlf_hdr ];
70 my $OP_CRLF_BDY = [ CRLF_BDY, \&op_crlf_bdy ];
73 'BODY[HEADER]' => [ NEED_BLOB|EML_HDR|CRLF_HDR, \&emit_rfc822_header ],
74 'BODY[TEXT]' => [ NEED_BLOB|EML_BDY|CRLF_BDY, \&emit_rfc822_text ],
75 'BODY[]' => [ NEED_BLOB|CRLF_BREF, \&emit_rfc822 ],
76 'RFC822.HEADER' => [ NEED_BLOB|EML_HDR|CRLF_HDR, \&emit_rfc822_header ],
77 'RFC822.TEXT' => [ NEED_BLOB|EML_BDY|CRLF_BDY, \&emit_rfc822_text ],
78 'RFC822.SIZE' => [ NEED_SMSG, \&emit_rfc822_size ],
79 RFC822 => [ NEED_BLOB|CRLF_BREF, \&emit_rfc822 ],
80 BODY => [ NEED_BLOB|EML_HDR|EML_BDY, \&emit_body ],
81 BODYSTRUCTURE => [ NEED_BLOB|EML_HDR|EML_BDY, \&emit_bodystructure ],
82 ENVELOPE => [ NEED_BLOB|EML_HDR, \&emit_envelope ],
83 FLAGS => [ 0, \&emit_flags ],
84 INTERNALDATE => [ NEED_SMSG, \&emit_internaldate ],
86 my %FETCH_ATT = map { $_ => [ $_ ] } keys %FETCH_NEED;
88 # aliases (RFC 3501 section 6.4.5)
89 $FETCH_ATT{FAST} = [ qw(FLAGS INTERNALDATE RFC822.SIZE) ];
90 $FETCH_ATT{ALL} = [ @{$FETCH_ATT{FAST}}, 'ENVELOPE' ];
91 $FETCH_ATT{FULL} = [ @{$FETCH_ATT{ALL}}, 'BODY' ];
93 for my $att (keys %FETCH_ATT) {
94 my %h = map { $_ => $FETCH_NEED{$_} } @{$FETCH_ATT{$att}};
95 $FETCH_ATT{$att} = \%h;
99 my $valid_range = '[0-9]+|[0-9]+:[0-9]+|[0-9]+:\*';
100 $valid_range = qr/\A(?:$valid_range)(?:,(?:$valid_range))*\z/;
104 my $capa = capa($self);
105 $self->write(\"* OK [$capa] public-inbox-imapd ready\r\n");
109 my ($class, $sock, $imapd) = @_;
110 my $self = bless { imapd => $imapd }, 'PublicInbox::IMAP_preauth';
113 if ($sock->can('accept_SSL') && !$sock->accept_SSL) {
114 return CORE::close($sock) if $! != EAGAIN;
115 $ev = PublicInbox::TLS::epollbit() or return CORE::close($sock);
116 $wbuf = [ \&PublicInbox::DS::accept_tls_step, \&greet ];
118 $self->SUPER::new($sock, $ev | EPOLLONESHOT);
120 $self->{wbuf} = $wbuf;
132 # dovecot advertises IDLE pre-login; perhaps because some clients
133 # depend on it, so we'll do the same
134 my $capa = 'CAPABILITY IMAP4rev1 IDLE';
135 if ($self->logged_in) {
136 $capa .= ' COMPRESS=DEFLATE';
138 if (!($self->{sock} // $self)->can('accept_SSL') &&
139 $self->{imapd}->{accept_tls}) {
140 $capa .= ' STARTTLS';
142 $capa .= ' AUTH=ANONYMOUS';
146 sub login_success ($$) {
147 my ($self, $tag) = @_;
148 bless $self, 'PublicInbox::IMAP';
149 my $capa = capa($self);
150 "$tag OK [$capa] Logged in\r\n";
153 sub auth_challenge_ok ($) {
155 my $tag = delete($self->{-login_tag}) or return;
156 login_success($self, $tag);
159 sub cmd_login ($$$$) {
160 my ($self, $tag) = @_; # ignore ($user, $password) = ($_[2], $_[3])
161 login_success($self, $tag);
165 my ($self, $tag) = @_;
166 delete @$self{qw(uid_base uo2m)};
167 delete $self->{ibx} ? "$tag OK Close done\r\n"
168 : "$tag BAD No mailbox\r\n";
171 sub cmd_logout ($$) {
172 my ($self, $tag) = @_;
173 delete $self->{-idle_tag};
174 $self->write(\"* BYE logging out\r\n$tag OK Logout done\r\n");
175 $self->shutdn; # PublicInbox::DS::shutdn
179 sub cmd_authenticate ($$$) {
180 my ($self, $tag) = @_; # $method = $_[2], should be "ANONYMOUS"
181 $self->{-login_tag} = $tag;
185 sub cmd_capability ($$) {
186 my ($self, $tag) = @_;
187 '* '.capa($self)."\r\n$tag OK Capability done\r\n";
190 # uo2m: UID Offset to MSN, this is an arrayref by default,
191 # but uo2m_hibernate can compact and deduplicate it
192 sub uo2m_ary_new ($;$) {
193 my ($self, $exists) = @_;
194 my $ub = $self->{uid_base};
195 my $uids = $self->{ibx}->over(1)->uid_range($ub + 1, $ub + UID_SLICE);
197 # convert UIDs to offsets from {base}
198 my @tmp; # [$UID_OFFSET] => $MSN
201 $tmp[$_ - $ub] = ++$msn for @$uids;
202 $$exists = $msn if $exists;
206 # changes UID-offset-to-MSN mapping into a deduplicated scalar:
207 # uint16_t uo2m[UID_SLICE].
208 # May be swapped out for idle clients if THP is disabled.
209 sub uo2m_hibernate ($) {
211 ref(my $uo2m = $self->{uo2m}) or return;
212 my %dedupe = ( uo2m_pack($uo2m) => undef );
213 $self->{uo2m} = (keys(%dedupe))[0];
217 sub uo2m_last_uid ($) {
219 defined(my $uo2m = $self->{uo2m}) or die 'BUG: uo2m_last_uid w/o {uo2m}';
220 (ref($uo2m) ? @$uo2m : (length($uo2m) >> 1)) + $self->{uid_base};
224 # $_[0] is an arrayref of MSNs, it may have undef gaps if there
225 # are gaps in the corresponding UIDs: [ msn1, msn2, undef, msn3 ]
226 no warnings 'uninitialized';
227 pack('S*', @{$_[0]});
230 # extend {uo2m} to account for new messages which arrived since
231 # {uo2m} was created.
232 sub uo2m_extend ($$;$) {
233 my ($self, $new_uid_max) = @_;
234 defined(my $uo2m = $self->{uo2m}) or
235 return($self->{uo2m} = uo2m_ary_new($self));
236 my $beg = uo2m_last_uid($self); # last UID we've learned
237 return $uo2m if $beg >= $new_uid_max; # fast path
239 # need to extend the current range:
240 my $base = $self->{uid_base};
242 my $uids = $self->{ibx}->over(1)->uid_range($beg, $base + UID_SLICE);
243 return $uo2m if !scalar(@$uids);
244 my @tmp; # [$UID_OFFSET] => $MSN
245 my $write_method = $_[2] // 'msg_more';
247 my $msn = $uo2m->[-1];
248 $tmp[$_ - $beg] = ++$msn for @$uids;
249 $self->$write_method("* $msn EXISTS\r\n");
253 my $msn = unpack('S', substr($uo2m, -2, 2));
254 $tmp[$_ - $beg] = ++$msn for @$uids;
255 $self->$write_method("* $msn EXISTS\r\n");
256 $uo2m .= uo2m_pack(\@tmp);
257 my %dedupe = ($uo2m => undef);
258 $self->{uo2m} = (keys %dedupe)[0];
263 my ($self, $tag) = @_;
264 defined($self->{uid_base}) and
265 uo2m_extend($self, $self->{uid_base} + UID_SLICE);
266 \"$tag OK Noop done\r\n";
269 # the flexible version which works on scalars and array refs.
270 # Must call uo2m_extend before this
272 my ($self, $uid) = @_;
273 my $uo2m = $self->{uo2m};
274 my $off = $uid - $self->{uid_base} - 1;
275 ref($uo2m) ? $uo2m->[$off] : unpack('S', substr($uo2m, $off << 1, 2));
278 # returns an arrayref of UIDs, so MSNs can be translated to UIDs via:
279 # $msn2uid->[$MSN-1] => $UID. The result of this is always ephemeral
280 # and does not live beyond the event loop.
283 my $base = $self->{uid_base};
284 my $uo2m = uo2m_extend($self, $base + UID_SLICE);
285 $uo2m = [ unpack('S*', $uo2m) ] if !ref($uo2m);
289 for my $msn (@$uo2m) {
291 $msn2uid[$msn - 1] = $uo + $base if $msn;
296 # converts a set of message sequence numbers in requests to UIDs:
297 sub msn_to_uid_range ($$) {
299 $_[1] =~ s!([0-9]+)!$msn2uid->[$1 - 1] // ($msn2uid->[-1] // 0 + 1)!sge;
302 # called by PublicInbox::InboxIdle
303 sub on_inbox_unlock {
304 my ($self, $ibx) = @_;
305 my $uid_end = $self->{uid_base} + UID_SLICE;
306 uo2m_extend($self, $uid_end, 'write');
307 my $new = uo2m_last_uid($self);
308 if ($new == $uid_end) { # max exceeded $uid_end
309 # continue idling w/o inotify
310 my $sock = $self->{sock} or return;
311 $ibx->unsubscribe_unlock(fileno($sock));
315 # called every minute or so by PublicInbox::DS::later
316 my $IDLERS; # fileno($obj->{sock}) => PublicInbox::IMAP
320 for my $i (values %$old) {
321 next if ($i->{wbuf} || !exists($i->{-idle_tag}));
322 $IDLERS->{fileno($i->{sock})} = $i;
323 $i->write(\"* OK Still here\r\n");
326 PublicInbox::DS::add_uniq_timer('idle', 60, \&idle_tick_all);
330 my ($self, $tag) = @_;
331 # IDLE seems allowed by dovecot w/o a mailbox selected *shrug*
332 my $ibx = $self->{ibx} or return "$tag BAD no mailbox selected\r\n";
333 my $uid_end = $self->{uid_base} + UID_SLICE;
334 uo2m_extend($self, $uid_end);
335 my $sock = $self->{sock} or return;
336 my $fd = fileno($sock);
337 $self->{-idle_tag} = $tag;
338 # only do inotify on most recent slice
339 if ($ibx->over(1)->max < $uid_end) {
340 $ibx->subscribe_unlock($fd, $self);
341 $self->{imapd}->idler_start;
343 PublicInbox::DS::add_uniq_timer('idle', 60, \&idle_tick_all);
344 $IDLERS->{$fd} = $self;
349 my ($self, $ibx) = @_;
350 my $sock = $self->{sock} or return;
351 my $fd = fileno($sock);
352 delete $IDLERS->{$fd};
353 $ibx->unsubscribe_unlock($fd);
357 my ($self, $tag) = @_; # $tag is "DONE" (case-insensitive)
358 defined(my $idle_tag = delete $self->{-idle_tag}) or
359 return "$tag BAD not idle\r\n";
360 my $ibx = $self->{ibx} or do {
361 warn "BUG: idle_tag set w/o inbox";
362 return "$tag BAD internal bug\r\n";
364 stop_idle($self, $ibx);
365 "$idle_tag OK Idle done\r\n";
368 sub ensure_slices_exist ($$$) {
369 my ($imapd, $ibx, $max) = @_;
370 defined(my $mb_top = $ibx->{newsgroup}) or return;
371 my $mailboxes = $imapd->{mailboxes};
373 for (my $i = int($max/UID_SLICE); $i >= 0; --$i) {
374 my $sub_mailbox = "$mb_top.$i";
375 last if exists $mailboxes->{$sub_mailbox};
376 $mailboxes->{$sub_mailbox} = $ibx;
377 $sub_mailbox =~ s/\Ainbox\./INBOX./i; # more familiar to users
378 push @created, $sub_mailbox;
380 return unless @created;
381 my $l = $imapd->{mailboxlist} or return;
382 push @$l, map { qq[* LIST (\\HasNoChildren) "." $_\r\n] } @created;
385 sub inbox_lookup ($$;$) {
386 my ($self, $mailbox, $examine) = @_;
387 my ($ibx, $exists, $uidmax, $uid_base) = (undef, 0, 0, 0);
388 $mailbox = lc $mailbox;
389 $ibx = $self->{imapd}->{mailboxes}->{$mailbox} or return;
390 my $over = $ibx->over(1);
391 if ($over != $ibx) { # not a dummy
392 $mailbox =~ /\.([0-9]+)\z/ or
393 die "BUG: unexpected dummy mailbox: $mailbox\n";
394 $uid_base = $1 * UID_SLICE;
396 $uidmax = $ibx->mm->num_highwater // 0;
398 $self->{uid_base} = $uid_base;
400 $self->{uo2m} = uo2m_ary_new($self, \$exists);
402 $exists = $over->imap_exists;
404 ensure_slices_exist($self->{imapd}, $ibx, $over->max);
407 $self->{uid_base} = $uid_base;
409 delete $self->{uo2m};
411 # if "INBOX.foo.bar" is selected and "INBOX.foo.bar.0",
412 # check for new UID ranges (e.g. "INBOX.foo.bar.1")
413 if (my $z = $self->{imapd}->{mailboxes}->{"$mailbox.0"}) {
414 ensure_slices_exist($self->{imapd}, $z,
418 ($ibx, $exists, $uidmax + 1, $uid_base);
421 sub cmd_examine ($$$) {
422 my ($self, $tag, $mailbox) = @_;
423 # XXX: do we need this? RFC 5162/7162
424 my $ret = $self->{ibx} ? "* OK [CLOSED] previous closed\r\n" : '';
425 my ($ibx, $exists, $uidnext, $base) = inbox_lookup($self, $mailbox, 1);
426 return "$tag NO Mailbox doesn't exist: $mailbox\r\n" if !$ibx;
431 * OK [PERMANENTFLAGS ()] Read-only mailbox\r
432 * OK [UNSEEN $exists]\r
433 * OK [UIDNEXT $uidnext]\r
434 * OK [UIDVALIDITY $ibx->{uidvalidity}]\r
435 $tag OK [READ-ONLY] EXAMINE/SELECT done\r
443 } elsif ($v =~ /[{"\r\n%*\\\[]/) { # literal string
444 '{' . length($v) . "}\r\n" . $v;
445 } else { # quoted string
450 sub addr_envelope ($$;$) {
451 my ($eml, $x, $y) = @_;
452 my $v = $eml->header_raw($x) //
453 ($y ? $eml->header_raw($y) : undef) // return 'NIL';
455 my @x = $Address->parse($v) or return 'NIL';
457 map { '(' . join(' ',
458 _esc($_->name), 'NIL',
459 _esc($_->user), _esc($_->host)
465 sub eml_envelope ($) {
468 _esc($eml->header_raw('Date')),
469 _esc($eml->header_raw('Subject')),
470 addr_envelope($eml, 'From'),
471 addr_envelope($eml, 'Sender', 'From'),
472 addr_envelope($eml, 'Reply-To', 'From'),
473 addr_envelope($eml, 'To'),
474 addr_envelope($eml, 'Cc'),
475 addr_envelope($eml, 'Bcc'),
476 _esc($eml->header_raw('In-Reply-To')),
477 _esc($eml->header_raw('Message-ID')),
483 if ($hash && scalar keys %$hash) {
484 $hash = [ %$hash ]; # flatten hash into 1-dimensional array
485 '(' . join(' ', map { _esc($_) } @$hash) . ')';
491 sub body_disposition ($) {
493 my $cd = $eml->header_raw('Content-Disposition') or return 'NIL';
494 $cd = parse_content_disposition($cd);
495 my $buf = '('._esc($cd->{type});
496 $buf .= ' ' . _esc_hash($cd->{attributes});
500 sub body_leaf ($$;$) {
501 my ($eml, $structure, $hold) = @_;
503 $eml->{is_submsg} and # parent was a message/(rfc822|news|global)
504 $buf .= eml_envelope($eml). ' ';
506 $buf .= '('._esc($ct->{type}).' ';
507 $buf .= _esc($ct->{subtype});
508 $buf .= ' ' . _esc_hash($ct->{attributes});
509 $buf .= ' ' . _esc($eml->header_raw('Content-ID'));
510 $buf .= ' ' . _esc($eml->header_raw('Content-Description'));
511 my $cte = $eml->header_raw('Content-Transfer-Encoding') // '7bit';
512 $buf .= ' ' . _esc($cte);
513 $buf .= ' ' . $eml->{imap_body_len};
514 $buf .= ' '.($eml->body_raw =~ tr/\n/\n/) if lc($ct->{type}) eq 'text';
516 # for message/(rfc822|global|news), $hold[0] should have envelope
517 $buf .= ' ' . (@$hold ? join('', @$hold) : 'NIL') if $hold;
520 $buf .= ' '._esc($eml->header_raw('Content-MD5'));
521 $buf .= ' '. body_disposition($eml);
522 $buf .= ' '._esc($eml->header_raw('Content-Language'));
523 $buf .= ' '._esc($eml->header_raw('Content-Location'));
528 sub body_parent ($$$) {
529 my ($eml, $structure, $hold) = @_;
531 my $type = lc($ct->{type});
532 if ($type eq 'multipart') {
534 $buf .= @$hold ? join('', @$hold) : 'NIL';
535 $buf .= ' '._esc($ct->{subtype});
537 $buf .= ' '._esc_hash($ct->{attributes});
538 $buf .= ' '.body_disposition($eml);
539 $buf .= ' '._esc($eml->header_raw('Content-Language'));
540 $buf .= ' '._esc($eml->header_raw('Content-Location'));
544 } else { # message/(rfc822|global|news)
545 @$hold = (body_leaf($eml, $structure, $hold));
549 # this is gross, but we need to process the parent part AFTER
550 # the child parts are done
551 sub bodystructure_prep {
553 my ($eml, $depth) = @$p; # ignore idx
554 # set length here, as $eml->{bdy} gets deleted for message/rfc822
555 $eml->{imap_body_len} = length($eml->body_raw);
556 push @$q, $eml, $depth;
559 # for FETCH BODY and FETCH BODYSTRUCTURE
560 sub fetch_body ($;$) {
561 my ($eml, $structure) = @_;
563 $eml->each_part(\&bodystructure_prep, \@q, 0, 1);
567 my ($part, $depth) = splice(@q, -2);
568 my $is_mp_parent = $depth == ($cur_depth - 1);
572 body_parent($part, $structure, \@hold);
574 unshift @hold, body_leaf($part, $structure);
580 sub requeue_once ($) {
582 # COMPRESS users all share the same DEFLATE context.
583 # Flush it here to ensure clients don't see
587 # no recursion, schedule another call ASAP,
588 # but only after all pending writes are done.
590 my $new_size = push(@{$self->{wbuf}}, \&long_step);
592 # wbuf may be populated by $cb, no need to rearm if so:
593 $self->requeue if $new_size == 1;
597 my ($self, $smsg, $bref, $ops, $partial) = @_;
598 my $uid = $smsg->{num};
599 $self->msg_more('* '.uid2msn($self, $uid)." FETCH (UID $uid");
601 for (my $i = 0; $i < @$ops;) {
603 $ops->[$i++]->($self, $k, $smsg, $bref, $eml);
605 partial_emit($self, $partial, $eml) if $partial;
606 $self->msg_more(")\r\n");
609 sub fetch_blob_cb { # called by git->cat_async via ibx_async_cat
610 my ($bref, $oid, $type, $size, $fetch_arg) = @_;
611 my ($self, undef, $msgs, $range_info, $ops, $partial) = @$fetch_arg;
612 my $ibx = $self->{ibx} or return $self->close; # client disconnected
613 my $smsg = shift @$msgs or die 'BUG: no smsg';
614 if (!defined($oid)) {
615 # it's possible to have TOCTOU if an admin runs
616 # public-inbox-(edit|purge), just move onto the next message
617 warn "E: $smsg->{blob} missing in $ibx->{inboxdir}\n";
618 return requeue_once($self);
620 $smsg->{blob} eq $oid or die "BUG: $smsg->{blob} != $oid";
623 if (!$self->{wbuf} && (my $nxt = $msgs->[0])) {
624 $pre = ibx_async_prefetch($ibx, $nxt->{blob},
625 \&fetch_blob_cb, $fetch_arg);
627 fetch_run_ops($self, $smsg, $bref, $ops, $partial);
628 $pre ? $self->zflush : requeue_once($self);
632 my ($self, $k, undef, $bref) = @_;
633 $self->msg_more(" $k {" . length($$bref)."}\r\n");
634 $self->msg_more($$bref);
637 # Mail::IMAPClient::message_string cares about this by default,
638 # (->Ignoresizeerrors attribute). Admins are encouraged to
639 # --reindex for IMAP support, anyways.
640 sub emit_rfc822_size {
641 my ($self, $k, $smsg) = @_;
642 $self->msg_more(' RFC822.SIZE ' . $smsg->{bytes});
645 sub emit_internaldate {
646 my ($self, undef, $smsg) = @_;
647 $self->msg_more(' INTERNALDATE "'.$smsg->internaldate.'"');
650 sub emit_flags { $_[0]->msg_more(' FLAGS ()') }
653 my ($self, undef, undef, undef, $eml) = @_;
654 $self->msg_more(' ENVELOPE '.eml_envelope($eml));
657 sub emit_rfc822_header {
658 my ($self, $k, undef, undef, $eml) = @_;
659 $self->msg_more(" $k {".length(${$eml->{hdr}})."}\r\n");
660 $self->msg_more(${$eml->{hdr}});
663 # n.b. this is sorted to be after any emit_eml_new ops
664 sub emit_rfc822_text {
665 my ($self, $k, undef, $bref) = @_;
666 $self->msg_more(" $k {".length($$bref)."}\r\n");
667 $self->msg_more($$bref);
670 sub emit_bodystructure {
671 my ($self, undef, undef, undef, $eml) = @_;
672 $self->msg_more(' BODYSTRUCTURE '.fetch_body($eml, 1));
676 my ($self, undef, undef, undef, $eml) = @_;
677 $self->msg_more(' BODY '.fetch_body($eml));
680 # set $eml once ($_[4] == $eml, $_[3] == $bref)
681 sub op_eml_new { $_[4] = PublicInbox::Eml->new($_[3]) }
683 # s/From / fixes old bug from import (pre-a0c07cba0e5d8b6a)
685 ${$_[0]} =~ s/(?<!\r)\n/\r\n/sg;
686 ${$_[0]} =~ s/\A[\r\n]*From [^\r\n]*\r\n//s;
689 sub op_crlf_bref { to_crlf_full($_[3]) }
691 sub op_crlf_hdr { to_crlf_full($_[4]->{hdr}) }
693 sub op_crlf_bdy { ${$_[4]->{bdy}} =~ s/(?<!\r)\n/\r\n/sg if $_[4]->{bdy} }
695 sub uid_clamp ($$$) {
696 my ($self, $beg, $end) = @_;
697 my $uid_min = $self->{uid_base} + 1;
698 my $uid_end = $uid_min + UID_SLICE - 1;
699 $$beg = $uid_min if $$beg < $uid_min;
700 $$end = $uid_end if $$end > $uid_end;
703 sub range_step ($$) {
704 my ($self, $range_csv) = @_;
705 my ($beg, $end, $range);
706 if ($$range_csv =~ s/\A([^,]+),//) {
709 $range = $$range_csv;
712 my $uid_base = $self->{uid_base};
713 my $uid_end = $uid_base + UID_SLICE;
714 if ($range =~ /\A([0-9]+):([0-9]+)\z/) {
715 ($beg, $end) = ($1 + 0, $2 + 0);
716 uid_clamp($self, \$beg, \$end);
717 } elsif ($range =~ /\A([0-9]+):\*\z/) {
719 $end = $self->{ibx}->over(1)->max;
720 $end = $uid_end if $end > $uid_end;
721 $beg = $end if $beg > $end;
722 uid_clamp($self, \$beg, \$end);
723 } elsif ($range =~ /\A[0-9]+\z/) {
724 $beg = $end = $range + 0;
725 # just let the caller do an out-of-range query if a single
726 # UID is out-of-range
727 ++$beg if ($beg <= $uid_base || $end > $uid_end);
729 return 'BAD fetch range';
731 [ $beg, $end, $$range_csv ];
734 sub refill_range ($$$) {
735 my ($self, $msgs, $range_info) = @_;
736 my ($beg, $end, $range_csv) = @$range_info;
737 if (scalar(@$msgs = @{$self->{ibx}->over(1)->query_xover($beg, $end)})){
738 $range_info->[0] = $msgs->[-1]->{num} + 1;
741 return 'OK Fetch done' if !$range_csv;
742 my $next_range = range_step($self, \$range_csv);
743 return $next_range if !ref($next_range); # error
744 @$range_info = @$next_range;
745 undef; # keep looping
748 sub fetch_blob { # long_response
749 my ($self, $tag, $msgs, $range_info, $ops, $partial) = @_;
750 while (!@$msgs) { # rare
751 if (my $end = refill_range($self, $msgs, $range_info)) {
752 $self->write(\"$tag $end\r\n");
756 uo2m_extend($self, $msgs->[-1]->{num});
757 ibx_async_cat($self->{ibx}, $msgs->[0]->{blob},
758 \&fetch_blob_cb, \@_);
761 sub fetch_smsg { # long_response
762 my ($self, $tag, $msgs, $range_info, $ops) = @_;
763 while (!@$msgs) { # rare
764 if (my $end = refill_range($self, $msgs, $range_info)) {
765 $self->write(\"$tag $end\r\n");
769 uo2m_extend($self, $msgs->[-1]->{num});
770 fetch_run_ops($self, $_, undef, $ops) for @$msgs;
775 sub refill_uids ($$$;$) {
776 my ($self, $uids, $range_info, $sql) = @_;
777 my ($beg, $end, $range_csv) = @$range_info;
778 my $over = $self->{ibx}->over(1);
780 if (scalar(@$uids = @{$over->uid_range($beg, $end, $sql)})) {
781 $range_info->[0] = $uids->[-1] + 1; # update $beg
783 } elsif (!$range_csv) {
786 my $next_range = range_step($self, \$range_csv);
787 return $next_range if !ref($next_range); # error
788 ($beg, $end, $range_csv) = @$range_info = @$next_range;
794 sub fetch_uid { # long_response
795 my ($self, $tag, $uids, $range_info, $ops) = @_;
796 if (defined(my $err = refill_uids($self, $uids, $range_info))) {
797 $err ||= 'OK Fetch done';
798 $self->write("$tag $err\r\n");
801 my $adj = $self->{uid_base} + 1;
802 my $uo2m = uo2m_extend($self, $uids->[-1]);
803 $uo2m = [ unpack('S*', $uo2m) ] if !ref($uo2m);
806 $self->msg_more("* $uo2m->[$_ - $adj] FETCH (UID $_");
807 for ($i = 0; $i < @$ops;) {
809 $ops->[$i++]->($self, $k);
811 $self->msg_more(")\r\n");
817 sub cmd_status ($$$;@) {
818 my ($self, $tag, $mailbox, @items) = @_;
819 return "$tag BAD no items\r\n" if !scalar(@items);
820 ($items[0] !~ s/\A\(//s || $items[-1] !~ s/\)\z//s) and
821 return "$tag BAD invalid args\r\n";
822 my ($ibx, $exists, $uidnext) = inbox_lookup($self, $mailbox);
823 return "$tag NO Mailbox doesn't exist: $mailbox\r\n" if !$ibx;
825 for my $it (@items) {
828 if ($it =~ /\A(?:MESSAGES|UNSEEN|RECENT)\z/) {
830 } elsif ($it eq 'UIDNEXT') {
832 } elsif ($it eq 'UIDVALIDITY') {
833 push @it, $ibx->{uidvalidity};
835 return "$tag BAD invalid item\r\n";
838 return "$tag BAD no items\r\n" if !@it;
839 "* STATUS $mailbox (".join(' ', @it).")\r\n" .
840 "$tag OK Status done\r\n";
843 my %patmap = ('*' => '.*', '%' => '[^\.]*');
844 sub cmd_list ($$$$) {
845 my ($self, $tag, $refname, $wildcard) = @_;
846 my $l = $self->{imapd}->{mailboxlist};
847 if ($refname eq '' && $wildcard eq '') {
848 # request for hierarchy delimiter
849 $l = [ qq[* LIST (\\Noselect) "." ""\r\n] ];
850 } elsif ($refname ne '' || $wildcard ne '*') {
851 $wildcard =~ s!([^a-z0-9_])!$patmap{$1} // "\Q$1"!egi;
852 $l = [ grep(/ \Q$refname\E$wildcard\r\n\z/is, @$l) ];
854 \(join('', @$l, "$tag OK List done\r\n"));
857 sub cmd_lsub ($$$$) {
858 my (undef, $tag) = @_; # same args as cmd_list
859 "$tag OK Lsub done\r\n";
862 sub eml_index_offs_i { # PublicInbox::Eml::each_part callback
864 my ($eml, undef, $idx) = @$p;
865 if ($idx && lc($eml->ct->{type}) eq 'multipart') {
866 $eml->{imap_bdy} = $eml->{bdy} // \'';
868 $all->{$idx} = $eml; # $idx => Eml
871 # prepares an index for BODY[$SECTION_IDX] fetches
872 sub eml_body_idx ($$) {
873 my ($eml, $section_idx) = @_;
874 my $idx = $eml->{imap_all_parts} // do {
876 $eml->each_part(\&eml_index_offs_i, $all, 0, 1);
877 # top-level of multipart, BODY[0] not allowed (nz-number)
879 $eml->{imap_all_parts} = $all;
881 $idx->{$section_idx};
884 # BODY[($SECTION_IDX)?(.$SECTION_NAME)?]<$offset.$bytes>
886 my ($eml, $section_idx, $section_name) = @_;
887 if (defined $section_idx) {
888 $eml = eml_body_idx($eml, $section_idx) or return;
890 if (defined $section_name) {
891 if ($section_name eq 'MIME') {
892 # RFC 3501 6.4.5 states:
893 # The MIME part specifier MUST be prefixed
894 # by one or more numeric part specifiers
895 return unless defined $section_idx;
896 return $eml->header_obj->as_string . "\r\n";
898 my $bdy = $eml->{bdy} // $eml->{imap_bdy} // \'';
899 $eml = PublicInbox::Eml->new($$bdy);
900 if ($section_name eq 'TEXT') {
901 return $eml->body_raw;
902 } elsif ($section_name eq 'HEADER') {
903 return $eml->header_obj->as_string . "\r\n";
905 die "BUG: bad section_name=$section_name";
908 ${$eml->{bdy} // $eml->{imap_bdy} // \''};
911 # similar to what's in PublicInbox::Eml::re_memo, but doesn't memoize
912 # to avoid OOM with malicious users
913 sub hdrs_regexp ($) {
915 my $names = join('|', map { "\Q$_" } split(/[ \t]+/, $hdrs));
916 qr/^(?:$names):[ \t]*[^\n]*\r?\n # 1st line
917 # continuation lines:
918 (?:[^:\n]*?[ \t]+[^\n]*\r?\n)*
922 # BODY[($SECTION_IDX.)?HEADER.FIELDS.NOT ($HDRS)]<$offset.$bytes>
923 sub partial_hdr_not {
924 my ($eml, $section_idx, $hdrs_re) = @_;
925 if (defined $section_idx) {
926 $eml = eml_body_idx($eml, $section_idx) or return;
928 my $str = $eml->header_obj->as_string;
929 $str =~ s/$hdrs_re//g;
930 $str =~ s/(?<!\r)\n/\r\n/sg;
934 # BODY[($SECTION_IDX.)?HEADER.FIELDS ($HDRS)]<$offset.$bytes>
935 sub partial_hdr_get {
936 my ($eml, $section_idx, $hdrs_re) = @_;
937 if (defined $section_idx) {
938 $eml = eml_body_idx($eml, $section_idx) or return;
940 my $str = $eml->header_obj->as_string;
941 $str = join('', ($str =~ m/($hdrs_re)/g));
942 $str =~ s/(?<!\r)\n/\r\n/sg;
946 sub partial_prepare ($$$$) {
947 my ($need, $partial, $want, $att) = @_;
949 # recombine [ "BODY[1.HEADER.FIELDS", "(foo", "bar)]" ]
950 # back to: "BODY[1.HEADER.FIELDS (foo bar)]"
951 return unless $att =~ /\ABODY\[/s;
952 until (rindex($att, ']') >= 0) {
953 my $next = shift @$want or return;
954 $att .= ' ' . uc($next);
956 if ($att =~ /\ABODY\[([0-9]+(?:\.[0-9]+)*)? # 1 - section_idx
957 (?:\.(HEADER|MIME|TEXT))? # 2 - section_name
958 \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 3, 4
959 $partial->{$att} = [ \&partial_body, $1, $2, $3, $4 ];
960 $$need |= CRLF_BREF|EML_HDR|EML_BDY;
961 } elsif ($att =~ /\ABODY\[(?:([0-9]+(?:\.[0-9]+)*)\.)? # 1 - section_idx
962 (?:HEADER\.FIELDS(\.NOT)?)\x20 # 2
963 \(([A-Z0-9\-\x20]+)\) # 3 - hdrs
964 \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 4 5
965 my $tmp = $partial->{$att} = [ $2 ? \&partial_hdr_not
968 $tmp->[2] = hdrs_regexp($3);
970 # don't emit CRLF_HDR instruction, here, partial_hdr_*
971 # will do CRLF conversion with only the extracted result
972 # and not waste time converting lines we don't care about.
979 sub partial_emit ($$$) {
980 my ($self, $partial, $eml) = @_;
982 my ($k, $cb, @args) = @$_;
983 my ($offset, $len) = splice(@args, -2);
984 # $cb is partial_body|partial_hdr_get|partial_hdr_not
985 my $str = $cb->($eml, @args) // '';
986 if (defined $offset) {
988 $str = substr($str, $offset, $len);
989 $k =~ s/\.$len>\z/>/ or warn
990 "BUG: unable to remove `.$len>' from `$k'";
992 $str = substr($str, $offset);
998 $self->msg_more(" $k {$len}\r\n");
999 $self->msg_more($str);
1003 sub fetch_compile ($) {
1005 if ($want->[0] =~ s/\A\(//s) {
1006 $want->[-1] =~ s/\)\z//s or return 'BAD no rparen';
1008 my (%partial, %seen, @op);
1010 while (defined(my $att = shift @$want)) {
1012 next if $att eq 'UID'; # always returned
1013 $att =~ s/\ABODY\.PEEK\[/BODY\[/; # we're read-only
1014 my $x = $FETCH_ATT{$att};
1016 while (my ($k, $fl_cb) = each %$x) {
1017 next if $seen{$k}++;
1018 $need |= $fl_cb->[0];
1019 push @op, [ @$fl_cb, $k ];
1021 } elsif (!partial_prepare(\$need, \%partial, $want, $att)) {
1022 return "BAD param: $att";
1027 # stabilize partial order for consistency and ease-of-debugging:
1028 if (scalar keys %partial) {
1030 $r[2] = [ map { [ $_, @{$partial{$_}} ] } sort keys %partial ];
1033 push @op, $OP_EML_NEW if ($need & (EML_HDR|EML_BDY));
1035 # do we need CRLF conversion?
1036 if ($need & CRLF_BREF) {
1037 push @op, $OP_CRLF_BREF;
1038 } elsif (my $crlf = ($need & (CRLF_HDR|CRLF_BDY))) {
1039 if ($crlf == (CRLF_HDR|CRLF_BDY)) {
1040 push @op, $OP_CRLF_BREF;
1041 } elsif ($need & CRLF_HDR) {
1042 push @op, $OP_CRLF_HDR;
1044 push @op, $OP_CRLF_BDY;
1048 $r[0] = $need & NEED_BLOB ? \&fetch_blob :
1049 ($need & NEED_SMSG ? \&fetch_smsg : \&fetch_uid);
1051 # r[1] = [ $key1, $cb1, $key2, $cb2, ... ]
1052 use sort 'stable'; # makes output more consistent
1053 $r[1] = [ map { ($_->[2], $_->[1]) } sort { $a->[0] <=> $b->[0] } @op ];
1057 sub cmd_uid_fetch ($$$$;@) {
1058 my ($self, $tag, $range_csv, @want) = @_;
1059 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1060 my ($cb, $ops, $partial) = fetch_compile(\@want);
1061 return "$tag $cb\r\n" unless $ops;
1063 # cb is one of fetch_blob, fetch_smsg, fetch_uid
1064 $range_csv = 'bad' if $range_csv !~ $valid_range;
1065 my $range_info = range_step($self, \$range_csv);
1066 return "$tag $range_info\r\n" if !ref($range_info);
1067 uo2m_hibernate($self) if $cb == \&fetch_blob; # slow, save RAM
1068 long_response($self, $cb, $tag, [], $range_info, $ops, $partial);
1071 sub cmd_fetch ($$$$;@) {
1072 my ($self, $tag, $range_csv, @want) = @_;
1073 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1074 my ($cb, $ops, $partial) = fetch_compile(\@want);
1075 return "$tag $cb\r\n" unless $ops;
1077 # cb is one of fetch_blob, fetch_smsg, fetch_uid
1078 $range_csv = 'bad' if $range_csv !~ $valid_range;
1079 msn_to_uid_range(msn2uid($self), $range_csv);
1080 my $range_info = range_step($self, \$range_csv);
1081 return "$tag $range_info\r\n" if !ref($range_info);
1082 uo2m_hibernate($self) if $cb == \&fetch_blob; # slow, save RAM
1083 long_response($self, $cb, $tag, [], $range_info, $ops, $partial);
1086 sub msn_convert ($$) {
1087 my ($self, $uids) = @_;
1088 my $adj = $self->{uid_base} + 1;
1089 my $uo2m = uo2m_extend($self, $uids->[-1]);
1090 $uo2m = [ unpack('S*', $uo2m) ] if !ref($uo2m);
1091 $_ = $uo2m->[$_ - $adj] for @$uids;
1094 sub search_uid_range { # long_response
1095 my ($self, $tag, $sql, $range_info, $want_msn) = @_;
1097 if (defined(my $err = refill_uids($self, $uids, $range_info, $sql))) {
1098 $err ||= 'OK Search done';
1099 $self->write("\r\n$tag $err\r\n");
1102 msn_convert($self, $uids) if $want_msn;
1103 $self->msg_more(join(' ', '', @$uids));
1107 sub parse_imap_query ($$) {
1108 my ($self, $query) = @_;
1109 my $q = PublicInbox::IMAPsearchqp::parse($self, $query);
1111 my $max = $self->{ibx}->over(1)->max;
1113 uid_clamp($self, \$beg, \$max);
1114 $q->{range_info} = [ $beg, $max ];
1120 my ($self, $tag, $query, $want_msn) = @_;
1121 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1122 my $q = parse_imap_query($self, $query);
1123 return "$tag $q\r\n" if !ref($q);
1124 my ($sql, $range_info) = delete @$q{qw(sql range_info)};
1125 if (!scalar(keys %$q)) { # overview.sqlite3
1126 $self->msg_more('* SEARCH');
1127 long_response($self, \&search_uid_range,
1128 $tag, $sql, $range_info, $want_msn);
1129 } elsif ($q = $q->{xap}) {
1130 my $srch = $self->{ibx}->isrch or
1131 return "$tag BAD search not available for mailbox\r\n";
1135 uid_range => $range_info
1137 my $mset = $srch->mset($q, $opt);
1138 my $uids = $srch->mset_to_artnums($mset, $opt);
1139 msn_convert($self, $uids) if scalar(@$uids) && $want_msn;
1140 "* SEARCH @$uids\r\n$tag OK Search done\r\n";
1142 "$tag BAD Error\r\n";
1146 sub cmd_uid_search ($$$) {
1147 my ($self, $tag, $query) = @_;
1148 search_common($self, $tag, $query);
1151 sub cmd_search ($$$;) {
1152 my ($self, $tag, $query) = @_;
1153 search_common($self, $tag, $query, 1);
1156 sub args_ok ($$) { # duplicated from PublicInbox::NNTP
1157 my ($cb, $argc) = @_;
1158 my $tot = prototype $cb;
1159 my ($nreq, undef) = split(';', $tot);
1160 $nreq = ($nreq =~ tr/$//) - 1;
1161 $tot = ($tot =~ tr/$//) - 1;
1162 ($argc <= $tot && $argc >= $nreq);
1165 # returns 1 if we can continue, 0 if not due to buffered writes or disconnect
1166 sub process_line ($$) {
1167 my ($self, $l) = @_;
1169 # TODO: IMAP allows literals for big requests to upload messages
1170 # (which we don't support) but maybe some big search queries use it.
1171 # RFC 3501 9 (2) doesn't permit TAB or multiple SP
1172 my ($tag, $req, @args) = parse_line('[ \t]+', 0, $l);
1173 pop(@args) if (@args && !defined($args[-1]));
1174 if (@args && uc($req) eq 'UID') {
1175 $req .= "_".(shift @args);
1178 if (defined(my $idle_tag = $self->{-idle_tag})) {
1179 (uc($tag // '') eq 'DONE' && !defined($req)) ?
1180 idle_done($self, $tag) :
1181 "$idle_tag BAD expected DONE\r\n";
1182 } elsif (my $cmd = $self->can('cmd_'.lc($req // ''))) {
1183 if ($cmd == \&cmd_uid_search || $cmd == \&cmd_search) {
1184 # preserve user-supplied quotes for search
1185 (undef, @args) = split(/ search /i, $l, 2);
1187 $cmd->($self, $tag, @args);
1188 } else { # this is weird
1189 auth_challenge_ok($self) //
1191 ' BAD Error in IMAP command '.
1193 ": Unknown command\r\n";
1197 if ($err && $self->{sock}) {
1199 err($self, 'error from: %s (%s)', $l, $err);
1201 $res = "$tag BAD program fault - command not performed\r\n";
1203 return 0 unless defined $res;
1209 # wbuf is unset or empty, here; {long} may add to it
1210 my ($fd, $cb, $t0, @args) = @{$self->{long_cb}};
1211 my $more = eval { $cb->($self, @args) };
1212 if ($@ || !$self->{sock}) { # something bad happened...
1213 delete $self->{long_cb};
1214 my $elapsed = now() - $t0;
1217 "%s during long response[$fd] - %0.6f",
1220 out($self, " deferred[$fd] aborted - %0.6f", $elapsed);
1222 } elsif ($more) { # $self->{wbuf}:
1223 # control passed to ibx_async_cat if $more == \undef
1224 requeue_once($self) if !ref($more);
1225 } else { # all done!
1226 delete $self->{long_cb};
1227 my $elapsed = now() - $t0;
1228 my $fd = fileno($self->{sock});
1229 out($self, " deferred[$fd] done - %0.6f", $elapsed);
1230 my $wbuf = $self->{wbuf}; # do NOT autovivify
1232 $self->requeue unless $wbuf && @$wbuf;
1237 my ($self, $fmt, @args) = @_;
1238 printf { $self->{imapd}->{err} } $fmt."\n", @args;
1242 my ($self, $fmt, @args) = @_;
1243 printf { $self->{imapd}->{out} } $fmt."\n", @args;
1246 sub long_response ($$;@) {
1247 my ($self, $cb, @args) = @_; # cb returns true if more, false if done
1249 my $sock = $self->{sock} or return;
1250 # make sure we disable reading during a long response,
1251 # clients should not be sending us stuff and making us do more
1252 # work while we are stream a response to them
1253 $self->{long_cb} = [ fileno($sock), $cb, now(), @args ];
1254 long_step($self); # kick off!
1258 # callback used by PublicInbox::DS for any (e)poll (in/out/hup/err)
1262 return unless $self->flush_write && $self->{sock} && !$self->{long_cb};
1264 # only read more requests if we've drained the write buffer,
1265 # otherwise we can be buffering infinitely w/o backpressure
1267 my $rbuf = $self->{rbuf} // \(my $x = '');
1268 my $line = index($$rbuf, "\n");
1270 if (length($$rbuf) >= LINE_MAX) {
1271 $self->write(\"\* BAD request too long\r\n");
1272 return $self->close;
1274 $self->do_read($rbuf, LINE_MAX, length($$rbuf)) or
1275 return uo2m_hibernate($self);
1276 $line = index($$rbuf, "\n");
1278 $line = substr($$rbuf, 0, $line + 1, '');
1279 $line =~ s/\r?\n\z//s;
1280 return $self->close if $line =~ /[[:cntrl:]]/s;
1282 my $fd = fileno($self->{sock});
1283 my $r = eval { process_line($self, $line) };
1284 my $pending = $self->{wbuf} ? ' pending' : '';
1285 out($self, "[$fd] %s - %0.6f$pending - $r", $line, now() - $t0);
1287 return $self->close if $r < 0;
1288 $self->rbuf_idle($rbuf);
1290 # maybe there's more pipelined data, or we'll have
1291 # to register it for socket-readiness notifications
1292 $self->requeue unless $pending;
1295 sub compressed { undef }
1297 sub zflush {} # overridden by IMAPdeflate
1300 sub cmd_compress ($$$) {
1301 my ($self, $tag, $alg) = @_;
1302 return "$tag BAD DEFLATE only\r\n" if uc($alg) ne "DEFLATE";
1303 return "$tag BAD COMPRESS active\r\n" if $self->compressed;
1305 # CRIME made TLS compression obsolete
1306 # return "$tag NO [COMPRESSIONACTIVE]\r\n" if $self->tls_compressed;
1308 PublicInbox::IMAPdeflate->enable($self, $tag);
1313 sub cmd_starttls ($$) {
1314 my ($self, $tag) = @_;
1315 my $sock = $self->{sock} or return;
1316 if ($sock->can('stop_SSL') || $self->compressed) {
1317 return "$tag BAD TLS or compression already enabled\r\n";
1319 my $opt = $self->{imapd}->{accept_tls} or
1320 return "$tag BAD can not initiate TLS negotiation\r\n";
1321 $self->write(\"$tag OK begin TLS negotiation now\r\n");
1322 $self->{sock} = IO::Socket::SSL->start_SSL($sock, %$opt);
1323 $self->requeue if PublicInbox::DS::accept_tls_step($self);
1327 sub busy { # for graceful shutdown in PublicInbox::Daemon:
1329 if (defined($self->{-idle_tag})) {
1330 $self->write(\"* BYE server shutting down\r\n");
1331 return; # not busy anymore
1333 defined($self->{rbuf}) || defined($self->{wbuf}) ||
1334 !$self->write(\"* BYE server shutting down\r\n");
1339 if (my $ibx = delete $self->{ibx}) {
1340 stop_idle($self, $ibx);
1342 $self->SUPER::close; # PublicInbox::DS::close
1345 # we're read-only, so SELECT and EXAMINE do the same thing
1347 *cmd_select = \&cmd_examine;
1349 package PublicInbox::IMAP_preauth;
1350 our @ISA = qw(PublicInbox::IMAP);