1 # Copyright (C) 2020 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::Search;
44 use PublicInbox::IMAPsearchqp;
45 *mdocid = \&PublicInbox::Search::mdocid;
48 for my $mod (qw(Email::Address::XS Mail::Address)) {
49 eval "require $mod" or next;
50 $Address = $mod and last;
52 die "neither Email::Address::XS nor Mail::Address loaded: $@" if !$Address;
54 sub LINE_MAX () { 8000 } # RFC 2683 3.2.1.5
56 # Changing UID_SLICE will cause grief for clients which cache.
57 # This also needs to be <64K: we pack it into a uint16_t
58 # for long_response UID (offset) => MSN mappings
59 sub UID_SLICE () { 50_000 }
61 # these values area also used for sorting
62 sub NEED_SMSG () { 1 }
63 sub NEED_BLOB () { NEED_SMSG|2 }
64 sub CRLF_BREF () { 4 }
66 sub CRLF_HDR () { 16 }
68 sub CRLF_BDY () { 64 }
69 my $OP_EML_NEW = [ EML_HDR - 1, \&op_eml_new ];
70 my $OP_CRLF_BREF = [ CRLF_BREF, \&op_crlf_bref ];
71 my $OP_CRLF_HDR = [ CRLF_HDR, \&op_crlf_hdr ];
72 my $OP_CRLF_BDY = [ CRLF_BDY, \&op_crlf_bdy ];
75 'BODY[HEADER]' => [ NEED_BLOB|EML_HDR|CRLF_HDR, \&emit_rfc822_header ],
76 'BODY[TEXT]' => [ NEED_BLOB|EML_BDY|CRLF_BDY, \&emit_rfc822_text ],
77 'BODY[]' => [ NEED_BLOB|CRLF_BREF, \&emit_rfc822 ],
78 'RFC822.HEADER' => [ NEED_BLOB|EML_HDR|CRLF_HDR, \&emit_rfc822_header ],
79 'RFC822.TEXT' => [ NEED_BLOB|EML_BDY|CRLF_BDY, \&emit_rfc822_text ],
80 'RFC822.SIZE' => [ NEED_SMSG, \&emit_rfc822_size ],
81 RFC822 => [ NEED_BLOB|CRLF_BREF, \&emit_rfc822 ],
82 BODY => [ NEED_BLOB|EML_HDR|EML_BDY, \&emit_body ],
83 BODYSTRUCTURE => [ NEED_BLOB|EML_HDR|EML_BDY, \&emit_bodystructure ],
84 ENVELOPE => [ NEED_BLOB|EML_HDR, \&emit_envelope ],
85 FLAGS => [ 0, \&emit_flags ],
86 INTERNALDATE => [ NEED_SMSG, \&emit_internaldate ],
88 my %FETCH_ATT = map { $_ => [ $_ ] } keys %FETCH_NEED;
90 # aliases (RFC 3501 section 6.4.5)
91 $FETCH_ATT{FAST} = [ qw(FLAGS INTERNALDATE RFC822.SIZE) ];
92 $FETCH_ATT{ALL} = [ @{$FETCH_ATT{FAST}}, 'ENVELOPE' ];
93 $FETCH_ATT{FULL} = [ @{$FETCH_ATT{ALL}}, 'BODY' ];
95 for my $att (keys %FETCH_ATT) {
96 my %h = map { $_ => $FETCH_NEED{$_} } @{$FETCH_ATT{$att}};
97 $FETCH_ATT{$att} = \%h;
101 my $valid_range = '[0-9]+|[0-9]+:[0-9]+|[0-9]+:\*';
102 $valid_range = qr/\A(?:$valid_range)(?:,(?:$valid_range))*\z/;
104 # RFC 3501 5.4. Autologout Timer needs to be >= 30min
105 $PublicInbox::DS::EXPTIME = 60 * 30;
109 my $capa = capa($self);
110 $self->write(\"* OK [$capa] public-inbox-imapd ready\r\n");
114 my ($class, $sock, $imapd) = @_;
115 my $self = bless { imapd => $imapd }, 'PublicInbox::IMAP_preauth';
118 if ($sock->can('accept_SSL') && !$sock->accept_SSL) {
119 return CORE::close($sock) if $! != EAGAIN;
120 $ev = PublicInbox::TLS::epollbit();
121 $wbuf = [ \&PublicInbox::DS::accept_tls_step, \&greet ];
123 $self->SUPER::new($sock, $ev | EPOLLONESHOT);
125 $self->{wbuf} = $wbuf;
129 $self->update_idle_time;
138 # dovecot advertises IDLE pre-login; perhaps because some clients
139 # depend on it, so we'll do the same
140 my $capa = 'CAPABILITY IMAP4rev1 IDLE';
141 if ($self->logged_in) {
142 $capa .= ' COMPRESS=DEFLATE';
144 if (!($self->{sock} // $self)->can('accept_SSL') &&
145 $self->{imapd}->{accept_tls}) {
146 $capa .= ' STARTTLS';
148 $capa .= ' AUTH=ANONYMOUS';
152 sub login_success ($$) {
153 my ($self, $tag) = @_;
154 bless $self, 'PublicInbox::IMAP';
155 my $capa = capa($self);
156 "$tag OK [$capa] Logged in\r\n";
159 sub auth_challenge_ok ($) {
161 my $tag = delete($self->{-login_tag}) or return;
162 login_success($self, $tag);
165 sub cmd_login ($$$$) {
166 my ($self, $tag) = @_; # ignore ($user, $password) = ($_[2], $_[3])
167 login_success($self, $tag);
171 my ($self, $tag) = @_;
172 delete @$self{qw(uid_base uo2m)};
173 delete $self->{ibx} ? "$tag OK Close done\r\n"
174 : "$tag BAD No mailbox\r\n";
177 sub cmd_logout ($$) {
178 my ($self, $tag) = @_;
179 delete $self->{-idle_tag};
180 $self->write(\"* BYE logging out\r\n$tag OK Logout done\r\n");
181 $self->shutdn; # PublicInbox::DS::shutdn
185 sub cmd_authenticate ($$$) {
186 my ($self, $tag) = @_; # $method = $_[2], should be "ANONYMOUS"
187 $self->{-login_tag} = $tag;
191 sub cmd_capability ($$) {
192 my ($self, $tag) = @_;
193 '* '.capa($self)."\r\n$tag OK Capability done\r\n";
196 # uo2m: UID Offset to MSN, this is an arrayref by default,
197 # but uo2m_hibernate can compact and deduplicate it
198 sub uo2m_ary_new ($;$) {
199 my ($self, $exists) = @_;
200 my $base = $self->{uid_base};
201 my $uids = $self->{ibx}->over->uid_range($base + 1, $base + UID_SLICE);
203 # convert UIDs to offsets from {base}
204 my @tmp; # [$UID_OFFSET] => $MSN
207 $tmp[$_ - $base] = ++$msn for @$uids;
208 $$exists = $msn if $exists;
212 # changes UID-offset-to-MSN mapping into a deduplicated scalar:
213 # uint16_t uo2m[UID_SLICE].
214 # May be swapped out for idle clients if THP is disabled.
215 sub uo2m_hibernate ($) {
217 ref(my $uo2m = $self->{uo2m}) or return;
218 my %dedupe = ( uo2m_pack($uo2m) => undef );
219 $self->{uo2m} = (keys(%dedupe))[0];
223 sub uo2m_last_uid ($) {
225 defined(my $uo2m = $self->{uo2m}) or die 'BUG: uo2m_last_uid w/o {uo2m}';
226 (ref($uo2m) ? @$uo2m : (length($uo2m) >> 1)) + $self->{uid_base};
230 # $_[0] is an arrayref of MSNs, it may have undef gaps if there
231 # are gaps in the corresponding UIDs: [ msn1, msn2, undef, msn3 ]
232 no warnings 'uninitialized';
233 pack('S*', @{$_[0]});
236 # extend {uo2m} to account for new messages which arrived since
237 # {uo2m} was created.
238 sub uo2m_extend ($$;$) {
239 my ($self, $new_uid_max) = @_;
240 defined(my $uo2m = $self->{uo2m}) or
241 return($self->{uo2m} = uo2m_ary_new($self));
242 my $beg = uo2m_last_uid($self); # last UID we've learned
243 return $uo2m if $beg >= $new_uid_max; # fast path
245 # need to extend the current range:
246 my $base = $self->{uid_base};
248 my $uids = $self->{ibx}->over->uid_range($beg, $base + UID_SLICE);
249 return $uo2m if !scalar(@$uids);
250 my @tmp; # [$UID_OFFSET] => $MSN
251 my $write_method = $_[2] // 'msg_more';
253 my $msn = $uo2m->[-1];
254 $tmp[$_ - $beg] = ++$msn for @$uids;
255 $self->$write_method("* $msn EXISTS\r\n");
259 my $msn = unpack('S', substr($uo2m, -2, 2));
260 $tmp[$_ - $beg] = ++$msn for @$uids;
261 $self->$write_method("* $msn EXISTS\r\n");
262 $uo2m .= uo2m_pack(\@tmp);
263 my %dedupe = ($uo2m => undef);
264 $self->{uo2m} = (keys %dedupe)[0];
269 my ($self, $tag) = @_;
270 defined($self->{uid_base}) and
271 uo2m_extend($self, $self->{uid_base} + UID_SLICE);
272 \"$tag OK Noop done\r\n";
275 # the flexible version which works on scalars and array refs.
276 # Must call uo2m_extend before this
278 my ($self, $uid) = @_;
279 my $uo2m = $self->{uo2m};
280 my $off = $uid - $self->{uid_base} - 1;
281 ref($uo2m) ? $uo2m->[$off] : unpack('S', substr($uo2m, $off << 1, 2));
284 # returns an arrayref of UIDs, so MSNs can be translated to UIDs via:
285 # $msn2uid->[$MSN-1] => $UID. The result of this is always ephemeral
286 # and does not live beyond the event loop.
289 my $base = $self->{uid_base};
290 my $uo2m = uo2m_extend($self, $base + UID_SLICE);
291 $uo2m = [ unpack('S*', $uo2m) ] if !ref($uo2m);
295 for my $msn (@$uo2m) {
297 $msn2uid[$msn - 1] = $uo + $base if $msn;
302 # converts a set of message sequence numbers in requests to UIDs:
303 sub msn_to_uid_range ($$) {
305 $_[1] =~ s!([0-9]+)!$msn2uid->[$1 - 1] // ($msn2uid->[-1] + 1)!sge;
308 # called by PublicInbox::InboxIdle
309 sub on_inbox_unlock {
310 my ($self, $ibx) = @_;
311 my $uid_end = $self->{uid_base} + UID_SLICE;
312 uo2m_extend($self, $uid_end, 'write');
313 my $new = uo2m_last_uid($self);
314 if ($new == $uid_end) { # max exceeded $uid_end
315 # continue idling w/o inotify
316 my $sock = $self->{sock} or return;
317 $ibx->unsubscribe_unlock(fileno($sock));
321 # called every X minute(s) or so by PublicInbox::DS::later
327 for my $i (values %$old) {
328 next if ($i->{wbuf} || !exists($i->{-idle_tag}));
329 $i->update_idle_time or next;
330 $IDLERS->{fileno($i->{sock})} = $i;
331 $i->write(\"* OK Still here\r\n");
333 $idle_timer = scalar keys %$IDLERS ?
334 PublicInbox::DS::later(\&idle_tick_all) : undef;
338 my ($self, $tag) = @_;
339 # IDLE seems allowed by dovecot w/o a mailbox selected *shrug*
340 my $ibx = $self->{ibx} or return "$tag BAD no mailbox selected\r\n";
341 my $uid_end = $self->{uid_base} + UID_SLICE;
342 uo2m_extend($self, $uid_end);
343 my $sock = $self->{sock} or return;
344 my $fd = fileno($sock);
345 $self->{-idle_tag} = $tag;
346 # only do inotify on most recent slice
347 if ($ibx->over->max < $uid_end) {
348 $ibx->subscribe_unlock($fd, $self);
349 $self->{imapd}->idler_start;
351 $idle_timer //= PublicInbox::DS::later(\&idle_tick_all);
352 $IDLERS->{$fd} = $self;
357 my ($self, $ibx) = @_;
358 my $sock = $self->{sock} or return;
359 my $fd = fileno($sock);
360 delete $IDLERS->{$fd};
361 $ibx->unsubscribe_unlock($fd);
365 my ($self, $tag) = @_; # $tag is "DONE" (case-insensitive)
366 defined(my $idle_tag = delete $self->{-idle_tag}) or
367 return "$tag BAD not idle\r\n";
368 my $ibx = $self->{ibx} or do {
369 warn "BUG: idle_tag set w/o inbox";
370 return "$tag BAD internal bug\r\n";
372 stop_idle($self, $ibx);
373 "$idle_tag OK Idle done\r\n";
376 sub ensure_slices_exist ($$$) {
377 my ($imapd, $ibx, $max) = @_;
378 defined(my $mb_top = $ibx->{newsgroup}) or return;
379 my $mailboxes = $imapd->{mailboxes};
381 for (my $i = int($max/UID_SLICE); $i >= 0; --$i) {
382 my $sub_mailbox = "$mb_top.$i";
383 last if exists $mailboxes->{$sub_mailbox};
384 $mailboxes->{$sub_mailbox} = $ibx;
385 $sub_mailbox =~ s/\Ainbox\./INBOX./i; # more familiar to users
386 push @created, $sub_mailbox;
388 return unless @created;
389 my $l = $imapd->{inboxlist} or return;
390 push @$l, map { qq[* LIST (\\HasNoChildren) "." $_\r\n] } @created;
393 sub inbox_lookup ($$;$) {
394 my ($self, $mailbox, $examine) = @_;
395 my ($ibx, $exists, $uidmax, $uid_base) = (undef, 0, 0, 0);
396 $mailbox = lc $mailbox;
397 $ibx = $self->{imapd}->{mailboxes}->{$mailbox} or return;
398 my $over = $ibx->over;
399 if ($over != $ibx) { # not a dummy
400 $mailbox =~ /\.([0-9]+)\z/ or
401 die "BUG: unexpected dummy mailbox: $mailbox\n";
402 $uid_base = $1 * UID_SLICE;
404 # ->num_highwater caches for writers, so use ->meta_accessor
405 $uidmax = $ibx->mm->meta_accessor('num_highwater') // 0;
407 $self->{uid_base} = $uid_base;
409 $self->{uo2m} = uo2m_ary_new($self, \$exists);
411 $exists = $over->imap_exists;
413 ensure_slices_exist($self->{imapd}, $ibx, $over->max);
416 $self->{uid_base} = $uid_base;
418 delete $self->{uo2m};
420 # if "INBOX.foo.bar" is selected and "INBOX.foo.bar.0",
421 # check for new UID ranges (e.g. "INBOX.foo.bar.1")
422 if (my $z = $self->{imapd}->{mailboxes}->{"$mailbox.0"}) {
423 ensure_slices_exist($self->{imapd}, $z, $z->over->max);
426 ($ibx, $exists, $uidmax + 1, $uid_base);
429 sub cmd_examine ($$$) {
430 my ($self, $tag, $mailbox) = @_;
431 # XXX: do we need this? RFC 5162/7162
432 my $ret = $self->{ibx} ? "* OK [CLOSED] previous closed\r\n" : '';
433 my ($ibx, $exists, $uidnext, $base) = inbox_lookup($self, $mailbox, 1);
434 return "$tag NO Mailbox doesn't exist: $mailbox\r\n" if !$ibx;
439 * OK [PERMANENTFLAGS ()] Read-only mailbox\r
440 * OK [UNSEEN $exists]\r
441 * OK [UIDNEXT $uidnext]\r
442 * OK [UIDVALIDITY $ibx->{uidvalidity}]\r
443 $tag OK [READ-ONLY] EXAMINE/SELECT done\r
451 } elsif ($v =~ /[{"\r\n%*\\\[]/) { # literal string
452 '{' . length($v) . "}\r\n" . $v;
453 } else { # quoted string
458 sub addr_envelope ($$;$) {
459 my ($eml, $x, $y) = @_;
460 my $v = $eml->header_raw($x) //
461 ($y ? $eml->header_raw($y) : undef) // return 'NIL';
463 my @x = $Address->parse($v) or return 'NIL';
465 map { '(' . join(' ',
466 _esc($_->name), 'NIL',
467 _esc($_->user), _esc($_->host)
473 sub eml_envelope ($) {
476 _esc($eml->header_raw('Date')),
477 _esc($eml->header_raw('Subject')),
478 addr_envelope($eml, 'From'),
479 addr_envelope($eml, 'Sender', 'From'),
480 addr_envelope($eml, 'Reply-To', 'From'),
481 addr_envelope($eml, 'To'),
482 addr_envelope($eml, 'Cc'),
483 addr_envelope($eml, 'Bcc'),
484 _esc($eml->header_raw('In-Reply-To')),
485 _esc($eml->header_raw('Message-ID')),
491 if ($hash && scalar keys %$hash) {
492 $hash = [ %$hash ]; # flatten hash into 1-dimensional array
493 '(' . join(' ', map { _esc($_) } @$hash) . ')';
499 sub body_disposition ($) {
501 my $cd = $eml->header_raw('Content-Disposition') or return 'NIL';
502 $cd = parse_content_disposition($cd);
503 my $buf = '('._esc($cd->{type});
504 $buf .= ' ' . _esc_hash(delete $cd->{attributes});
508 sub body_leaf ($$;$) {
509 my ($eml, $structure, $hold) = @_;
511 $eml->{is_submsg} and # parent was a message/(rfc822|news|global)
512 $buf .= eml_envelope($eml). ' ';
514 $buf .= '('._esc($ct->{type}).' ';
515 $buf .= _esc($ct->{subtype});
516 $buf .= ' ' . _esc_hash(delete $ct->{attributes});
517 $buf .= ' ' . _esc($eml->header_raw('Content-ID'));
518 $buf .= ' ' . _esc($eml->header_raw('Content-Description'));
519 my $cte = $eml->header_raw('Content-Transfer-Encoding') // '7bit';
520 $buf .= ' ' . _esc($cte);
521 $buf .= ' ' . $eml->{imap_body_len};
522 $buf .= ' '.($eml->body_raw =~ tr/\n/\n/) if lc($ct->{type}) eq 'text';
524 # for message/(rfc822|global|news), $hold[0] should have envelope
525 $buf .= ' ' . (@$hold ? join('', @$hold) : 'NIL') if $hold;
528 $buf .= ' '._esc($eml->header_raw('Content-MD5'));
529 $buf .= ' '. body_disposition($eml);
530 $buf .= ' '._esc($eml->header_raw('Content-Language'));
531 $buf .= ' '._esc($eml->header_raw('Content-Location'));
536 sub body_parent ($$$) {
537 my ($eml, $structure, $hold) = @_;
539 my $type = lc($ct->{type});
540 if ($type eq 'multipart') {
542 $buf .= @$hold ? join('', @$hold) : 'NIL';
543 $buf .= ' '._esc($ct->{subtype});
545 $buf .= ' '._esc_hash(delete $ct->{attributes});
546 $buf .= ' '.body_disposition($eml);
547 $buf .= ' '._esc($eml->header_raw('Content-Language'));
548 $buf .= ' '._esc($eml->header_raw('Content-Location'));
552 } else { # message/(rfc822|global|news)
553 @$hold = (body_leaf($eml, $structure, $hold));
557 # this is gross, but we need to process the parent part AFTER
558 # the child parts are done
559 sub bodystructure_prep {
561 my ($eml, $depth) = @$p; # ignore idx
562 # set length here, as $eml->{bdy} gets deleted for message/rfc822
563 $eml->{imap_body_len} = length($eml->body_raw);
564 push @$q, $eml, $depth;
567 # for FETCH BODY and FETCH BODYSTRUCTURE
568 sub fetch_body ($;$) {
569 my ($eml, $structure) = @_;
571 $eml->each_part(\&bodystructure_prep, \@q, 0, 1);
575 my ($part, $depth) = splice(@q, -2);
576 my $is_mp_parent = $depth == ($cur_depth - 1);
580 body_parent($part, $structure, \@hold);
582 unshift @hold, body_leaf($part, $structure);
588 sub requeue_once ($) {
590 # COMPRESS users all share the same DEFLATE context.
591 # Flush it here to ensure clients don't see
595 # no recursion, schedule another call ASAP,
596 # but only after all pending writes are done.
598 my $new_size = push(@{$self->{wbuf}}, \&long_step);
600 # wbuf may be populated by $cb, no need to rearm if so:
601 $self->requeue if $new_size == 1;
605 my ($self, $smsg, $bref, $ops, $partial) = @_;
606 my $uid = $smsg->{num};
607 $self->msg_more('* '.uid2msn($self, $uid)." FETCH (UID $uid");
609 for (my $i = 0; $i < @$ops;) {
611 $ops->[$i++]->($self, $k, $smsg, $bref, $eml);
613 partial_emit($self, $partial, $eml) if $partial;
614 $self->msg_more(")\r\n");
617 sub fetch_blob_cb { # called by git->cat_async via git_async_cat
618 my ($bref, $oid, $type, $size, $fetch_arg) = @_;
619 my ($self, undef, $msgs, $range_info, $ops, $partial) = @$fetch_arg;
620 my $smsg = shift @$msgs or die 'BUG: no smsg';
621 if (!defined($oid)) {
622 # it's possible to have TOCTOU if an admin runs
623 # public-inbox-(edit|purge), just move onto the next message
624 warn "E: $smsg->{blob} missing in $self->{ibx}->{inboxdir}\n";
625 return requeue_once($self);
627 $smsg->{blob} eq $oid or die "BUG: $smsg->{blob} != $oid";
630 if (!$self->{wbuf} && (my $nxt = $msgs->[0])) {
631 $pre = $self->{ibx}->git->async_prefetch($nxt->{blob},
632 \&fetch_blob_cb, $fetch_arg);
634 fetch_run_ops($self, $smsg, $bref, $ops, $partial);
635 $pre ? $self->zflush : requeue_once($self);
639 my ($self, $k, undef, $bref) = @_;
640 $self->msg_more(" $k {" . length($$bref)."}\r\n");
641 $self->msg_more($$bref);
644 # Mail::IMAPClient::message_string cares about this by default,
645 # (->Ignoresizeerrors attribute). Admins are encouraged to
646 # --reindex for IMAP support, anyways.
647 sub emit_rfc822_size {
648 my ($self, $k, $smsg) = @_;
649 $self->msg_more(' RFC822.SIZE ' . $smsg->{bytes});
652 sub emit_internaldate {
653 my ($self, undef, $smsg) = @_;
654 $self->msg_more(' INTERNALDATE "'.$smsg->internaldate.'"');
657 sub emit_flags { $_[0]->msg_more(' FLAGS ()') }
660 my ($self, undef, undef, undef, $eml) = @_;
661 $self->msg_more(' ENVELOPE '.eml_envelope($eml));
664 sub emit_rfc822_header {
665 my ($self, $k, undef, undef, $eml) = @_;
666 $self->msg_more(" $k {".length(${$eml->{hdr}})."}\r\n");
667 $self->msg_more(${$eml->{hdr}});
670 # n.b. this is sorted to be after any emit_eml_new ops
671 sub emit_rfc822_text {
672 my ($self, $k, undef, $bref) = @_;
673 $self->msg_more(" $k {".length($$bref)."}\r\n");
674 $self->msg_more($$bref);
677 sub emit_bodystructure {
678 my ($self, undef, undef, undef, $eml) = @_;
679 $self->msg_more(' BODYSTRUCTURE '.fetch_body($eml, 1));
683 my ($self, undef, undef, undef, $eml) = @_;
684 $self->msg_more(' BODY '.fetch_body($eml));
687 # set $eml once ($_[4] == $eml, $_[3] == $bref)
688 sub op_eml_new { $_[4] = PublicInbox::Eml->new($_[3]) }
690 # s/From / fixes old bug from import (pre-a0c07cba0e5d8b6a)
692 ${$_[0]} =~ s/(?<!\r)\n/\r\n/sg;
693 ${$_[0]} =~ s/\A[\r\n]*From [^\r\n]*\r\n//s;
696 sub op_crlf_bref { to_crlf_full($_[3]) }
698 sub op_crlf_hdr { to_crlf_full($_[4]->{hdr}) }
700 sub op_crlf_bdy { ${$_[4]->{bdy}} =~ s/(?<!\r)\n/\r\n/sg if $_[4]->{bdy} }
702 sub uid_clamp ($$$) {
703 my ($self, $beg, $end) = @_;
704 my $uid_min = $self->{uid_base} + 1;
705 my $uid_end = $uid_min + UID_SLICE - 1;
706 $$beg = $uid_min if $$beg < $uid_min;
707 $$end = $uid_end if $$end > $uid_end;
710 sub range_step ($$) {
711 my ($self, $range_csv) = @_;
712 my ($beg, $end, $range);
713 if ($$range_csv =~ s/\A([^,]+),//) {
716 $range = $$range_csv;
719 my $uid_base = $self->{uid_base};
720 my $uid_end = $uid_base + UID_SLICE;
721 if ($range =~ /\A([0-9]+):([0-9]+)\z/) {
722 ($beg, $end) = ($1 + 0, $2 + 0);
723 uid_clamp($self, \$beg, \$end);
724 } elsif ($range =~ /\A([0-9]+):\*\z/) {
726 $end = $self->{ibx}->over->max;
727 $end = $uid_end if $end > $uid_end;
728 $beg = $end if $beg > $end;
729 uid_clamp($self, \$beg, \$end);
730 } elsif ($range =~ /\A[0-9]+\z/) {
731 $beg = $end = $range + 0;
732 # just let the caller do an out-of-range query if a single
733 # UID is out-of-range
734 ++$beg if ($beg <= $uid_base || $end > $uid_end);
736 return 'BAD fetch range';
738 [ $beg, $end, $$range_csv ];
741 sub refill_range ($$$) {
742 my ($self, $msgs, $range_info) = @_;
743 my ($beg, $end, $range_csv) = @$range_info;
744 if (scalar(@$msgs = @{$self->{ibx}->over->query_xover($beg, $end)})) {
745 $range_info->[0] = $msgs->[-1]->{num} + 1;
748 return 'OK Fetch done' if !$range_csv;
749 my $next_range = range_step($self, \$range_csv);
750 return $next_range if !ref($next_range); # error
751 @$range_info = @$next_range;
752 undef; # keep looping
755 sub fetch_blob { # long_response
756 my ($self, $tag, $msgs, $range_info, $ops, $partial) = @_;
757 while (!@$msgs) { # rare
758 if (my $end = refill_range($self, $msgs, $range_info)) {
759 $self->write(\"$tag $end\r\n");
763 uo2m_extend($self, $msgs->[-1]->{num});
764 git_async_cat($self->{ibx}->git, $msgs->[0]->{blob},
765 \&fetch_blob_cb, \@_);
768 sub fetch_smsg { # long_response
769 my ($self, $tag, $msgs, $range_info, $ops) = @_;
770 while (!@$msgs) { # rare
771 if (my $end = refill_range($self, $msgs, $range_info)) {
772 $self->write(\"$tag $end\r\n");
776 uo2m_extend($self, $msgs->[-1]->{num});
777 fetch_run_ops($self, $_, undef, $ops) for @$msgs;
782 sub refill_uids ($$$;$) {
783 my ($self, $uids, $range_info, $sql) = @_;
784 my ($beg, $end, $range_csv) = @$range_info;
785 my $over = $self->{ibx}->over;
787 if (scalar(@$uids = @{$over->uid_range($beg, $end, $sql)})) {
788 $range_info->[0] = $uids->[-1] + 1; # update $beg
790 } elsif (!$range_csv) {
793 my $next_range = range_step($self, \$range_csv);
794 return $next_range if !ref($next_range); # error
795 ($beg, $end, $range_csv) = @$range_info = @$next_range;
801 sub fetch_uid { # long_response
802 my ($self, $tag, $uids, $range_info, $ops) = @_;
803 if (defined(my $err = refill_uids($self, $uids, $range_info))) {
804 $err ||= 'OK Fetch done';
805 $self->write("$tag $err\r\n");
808 my $adj = $self->{uid_base} + 1;
809 my $uo2m = uo2m_extend($self, $uids->[-1]);
810 $uo2m = [ unpack('S*', $uo2m) ] if !ref($uo2m);
813 $self->msg_more("* $uo2m->[$_ - $adj] FETCH (UID $_");
814 for ($i = 0; $i < @$ops;) {
816 $ops->[$i++]->($self, $k);
818 $self->msg_more(")\r\n");
824 sub cmd_status ($$$;@) {
825 my ($self, $tag, $mailbox, @items) = @_;
826 return "$tag BAD no items\r\n" if !scalar(@items);
827 ($items[0] !~ s/\A\(//s || $items[-1] !~ s/\)\z//s) and
828 return "$tag BAD invalid args\r\n";
829 my ($ibx, $exists, $uidnext) = inbox_lookup($self, $mailbox);
830 return "$tag NO Mailbox doesn't exist: $mailbox\r\n" if !$ibx;
832 for my $it (@items) {
835 if ($it =~ /\A(?:MESSAGES|UNSEEN|RECENT)\z/) {
837 } elsif ($it eq 'UIDNEXT') {
839 } elsif ($it eq 'UIDVALIDITY') {
840 push @it, $ibx->{uidvalidity};
842 return "$tag BAD invalid item\r\n";
845 return "$tag BAD no items\r\n" if !@it;
846 "* STATUS $mailbox (".join(' ', @it).")\r\n" .
847 "$tag OK Status done\r\n";
850 my %patmap = ('*' => '.*', '%' => '[^\.]*');
851 sub cmd_list ($$$$) {
852 my ($self, $tag, $refname, $wildcard) = @_;
853 my $l = $self->{imapd}->{inboxlist};
854 if ($refname eq '' && $wildcard eq '') {
855 # request for hierarchy delimiter
856 $l = [ qq[* LIST (\\Noselect) "." ""\r\n] ];
857 } elsif ($refname ne '' || $wildcard ne '*') {
858 $wildcard =~ s!([^a-z0-9_])!$patmap{$1} // "\Q$1"!egi;
859 $l = [ grep(/ \Q$refname\E$wildcard\r\n\z/is, @$l) ];
861 \(join('', @$l, "$tag OK List done\r\n"));
864 sub cmd_lsub ($$$$) {
865 my (undef, $tag) = @_; # same args as cmd_list
866 "$tag OK Lsub done\r\n";
869 sub eml_index_offs_i { # PublicInbox::Eml::each_part callback
871 my ($eml, undef, $idx) = @$p;
872 if ($idx && lc($eml->ct->{type}) eq 'multipart') {
873 $eml->{imap_bdy} = $eml->{bdy} // \'';
875 $all->{$idx} = $eml; # $idx => Eml
878 # prepares an index for BODY[$SECTION_IDX] fetches
879 sub eml_body_idx ($$) {
880 my ($eml, $section_idx) = @_;
881 my $idx = $eml->{imap_all_parts} //= do {
883 $eml->each_part(\&eml_index_offs_i, $all, 0, 1);
884 # top-level of multipart, BODY[0] not allowed (nz-number)
888 $idx->{$section_idx};
891 # BODY[($SECTION_IDX)?(.$SECTION_NAME)?]<$offset.$bytes>
893 my ($eml, $section_idx, $section_name) = @_;
894 if (defined $section_idx) {
895 $eml = eml_body_idx($eml, $section_idx) or return;
897 if (defined $section_name) {
898 if ($section_name eq 'MIME') {
899 # RFC 3501 6.4.5 states:
900 # The MIME part specifier MUST be prefixed
901 # by one or more numeric part specifiers
902 return unless defined $section_idx;
903 return $eml->header_obj->as_string . "\r\n";
905 my $bdy = $eml->{bdy} // $eml->{imap_bdy} // \'';
906 $eml = PublicInbox::Eml->new($$bdy);
907 if ($section_name eq 'TEXT') {
908 return $eml->body_raw;
909 } elsif ($section_name eq 'HEADER') {
910 return $eml->header_obj->as_string . "\r\n";
912 die "BUG: bad section_name=$section_name";
915 ${$eml->{bdy} // $eml->{imap_bdy} // \''};
918 # similar to what's in PublicInbox::Eml::re_memo, but doesn't memoize
919 # to avoid OOM with malicious users
920 sub hdrs_regexp ($) {
922 my $names = join('|', map { "\Q$_" } split(/[ \t]+/, $hdrs));
923 qr/^(?:$names):[ \t]*[^\n]*\r?\n # 1st line
924 # continuation lines:
925 (?:[^:\n]*?[ \t]+[^\n]*\r?\n)*
929 # BODY[($SECTION_IDX.)?HEADER.FIELDS.NOT ($HDRS)]<$offset.$bytes>
930 sub partial_hdr_not {
931 my ($eml, $section_idx, $hdrs_re) = @_;
932 if (defined $section_idx) {
933 $eml = eml_body_idx($eml, $section_idx) or return;
935 my $str = $eml->header_obj->as_string;
936 $str =~ s/$hdrs_re//g;
937 $str =~ s/(?<!\r)\n/\r\n/sg;
941 # BODY[($SECTION_IDX.)?HEADER.FIELDS ($HDRS)]<$offset.$bytes>
942 sub partial_hdr_get {
943 my ($eml, $section_idx, $hdrs_re) = @_;
944 if (defined $section_idx) {
945 $eml = eml_body_idx($eml, $section_idx) or return;
947 my $str = $eml->header_obj->as_string;
948 $str = join('', ($str =~ m/($hdrs_re)/g));
949 $str =~ s/(?<!\r)\n/\r\n/sg;
953 sub partial_prepare ($$$$) {
954 my ($need, $partial, $want, $att) = @_;
956 # recombine [ "BODY[1.HEADER.FIELDS", "(foo", "bar)]" ]
957 # back to: "BODY[1.HEADER.FIELDS (foo bar)]"
958 return unless $att =~ /\ABODY\[/s;
959 until (rindex($att, ']') >= 0) {
960 my $next = shift @$want or return;
961 $att .= ' ' . uc($next);
963 if ($att =~ /\ABODY\[([0-9]+(?:\.[0-9]+)*)? # 1 - section_idx
964 (?:\.(HEADER|MIME|TEXT))? # 2 - section_name
965 \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 3, 4
966 $partial->{$att} = [ \&partial_body, $1, $2, $3, $4 ];
967 $$need |= CRLF_BREF|EML_HDR|EML_BDY;
968 } elsif ($att =~ /\ABODY\[(?:([0-9]+(?:\.[0-9]+)*)\.)? # 1 - section_idx
969 (?:HEADER\.FIELDS(\.NOT)?)\x20 # 2
970 \(([A-Z0-9\-\x20]+)\) # 3 - hdrs
971 \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 4 5
972 my $tmp = $partial->{$att} = [ $2 ? \&partial_hdr_not
975 $tmp->[2] = hdrs_regexp($3);
977 # don't emit CRLF_HDR instruction, here, partial_hdr_*
978 # will do CRLF conversion with only the extracted result
979 # and not waste time converting lines we don't care about.
986 sub partial_emit ($$$) {
987 my ($self, $partial, $eml) = @_;
989 my ($k, $cb, @args) = @$_;
990 my ($offset, $len) = splice(@args, -2);
991 # $cb is partial_body|partial_hdr_get|partial_hdr_not
992 my $str = $cb->($eml, @args) // '';
993 if (defined $offset) {
995 $str = substr($str, $offset, $len);
996 $k =~ s/\.$len>\z/>/ or warn
997 "BUG: unable to remove `.$len>' from `$k'";
999 $str = substr($str, $offset);
1000 $len = length($str);
1003 $len = length($str);
1005 $self->msg_more(" $k {$len}\r\n");
1006 $self->msg_more($str);
1010 sub fetch_compile ($) {
1012 if ($want->[0] =~ s/\A\(//s) {
1013 $want->[-1] =~ s/\)\z//s or return 'BAD no rparen';
1015 my (%partial, %seen, @op);
1017 while (defined(my $att = shift @$want)) {
1019 next if $att eq 'UID'; # always returned
1020 $att =~ s/\ABODY\.PEEK\[/BODY\[/; # we're read-only
1021 my $x = $FETCH_ATT{$att};
1023 while (my ($k, $fl_cb) = each %$x) {
1024 next if $seen{$k}++;
1025 $need |= $fl_cb->[0];
1026 push @op, [ @$fl_cb, $k ];
1028 } elsif (!partial_prepare(\$need, \%partial, $want, $att)) {
1029 return "BAD param: $att";
1034 # stabilize partial order for consistency and ease-of-debugging:
1035 if (scalar keys %partial) {
1037 $r[2] = [ map { [ $_, @{$partial{$_}} ] } sort keys %partial ];
1040 push @op, $OP_EML_NEW if ($need & (EML_HDR|EML_BDY));
1042 # do we need CRLF conversion?
1043 if ($need & CRLF_BREF) {
1044 push @op, $OP_CRLF_BREF;
1045 } elsif (my $crlf = ($need & (CRLF_HDR|CRLF_BDY))) {
1046 if ($crlf == (CRLF_HDR|CRLF_BDY)) {
1047 push @op, $OP_CRLF_BREF;
1048 } elsif ($need & CRLF_HDR) {
1049 push @op, $OP_CRLF_HDR;
1051 push @op, $OP_CRLF_BDY;
1055 $r[0] = $need & NEED_BLOB ? \&fetch_blob :
1056 ($need & NEED_SMSG ? \&fetch_smsg : \&fetch_uid);
1058 # r[1] = [ $key1, $cb1, $key2, $cb2, ... ]
1059 use sort 'stable'; # makes output more consistent
1060 $r[1] = [ map { ($_->[2], $_->[1]) } sort { $a->[0] <=> $b->[0] } @op ];
1064 sub cmd_uid_fetch ($$$$;@) {
1065 my ($self, $tag, $range_csv, @want) = @_;
1066 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1067 my ($cb, $ops, $partial) = fetch_compile(\@want);
1068 return "$tag $cb\r\n" unless $ops;
1070 # cb is one of fetch_blob, fetch_smsg, fetch_uid
1071 $range_csv = 'bad' if $range_csv !~ $valid_range;
1072 my $range_info = range_step($self, \$range_csv);
1073 return "$tag $range_info\r\n" if !ref($range_info);
1074 uo2m_hibernate($self) if $cb == \&fetch_blob; # slow, save RAM
1075 long_response($self, $cb, $tag, [], $range_info, $ops, $partial);
1078 sub cmd_fetch ($$$$;@) {
1079 my ($self, $tag, $range_csv, @want) = @_;
1080 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1081 my ($cb, $ops, $partial) = fetch_compile(\@want);
1082 return "$tag $cb\r\n" unless $ops;
1084 # cb is one of fetch_blob, fetch_smsg, fetch_uid
1085 $range_csv = 'bad' if $range_csv !~ $valid_range;
1086 msn_to_uid_range(msn2uid($self), $range_csv);
1087 my $range_info = range_step($self, \$range_csv);
1088 return "$tag $range_info\r\n" if !ref($range_info);
1089 uo2m_hibernate($self) if $cb == \&fetch_blob; # slow, save RAM
1090 long_response($self, $cb, $tag, [], $range_info, $ops, $partial);
1093 sub msn_convert ($$) {
1094 my ($self, $uids) = @_;
1095 my $adj = $self->{uid_base} + 1;
1096 my $uo2m = uo2m_extend($self, $uids->[-1]);
1097 $uo2m = [ unpack('S*', $uo2m) ] if !ref($uo2m);
1098 $_ = $uo2m->[$_ - $adj] for @$uids;
1101 sub search_uid_range { # long_response
1102 my ($self, $tag, $sql, $range_info, $want_msn) = @_;
1104 if (defined(my $err = refill_uids($self, $uids, $range_info, $sql))) {
1105 $err ||= 'OK Search done';
1106 $self->write("\r\n$tag $err\r\n");
1109 msn_convert($self, $uids) if $want_msn;
1110 $self->msg_more(join(' ', '', @$uids));
1115 my ($q, $k, $d) = @_;
1116 my $sql = $q->{sql};
1119 if ($k eq 'SENTON') {
1120 my $end = $d + 86399; # no leap day...
1121 my $da = strftime('%Y%m%d%H%M%S', gmtime($d));
1122 my $db = strftime('%Y%m%d%H%M%S', gmtime($end));
1123 $q->{xap} .= " dt:$da..$db";
1124 $$sql .= " AND ds >= $d AND ds <= $end" if defined($sql);
1125 } elsif ($k eq 'SENTBEFORE') {
1126 $q->{xap} .= ' d:..'.strftime('%Y%m%d', gmtime($d));
1127 $$sql .= " AND ds <= $d" if defined($sql);
1128 } elsif ($k eq 'SENTSINCE') {
1129 $q->{xap} .= ' d:'.strftime('%Y%m%d', gmtime($d)).'..';
1130 $$sql .= " AND ds >= $d" if defined($sql);
1132 # INTERNALDATE (Received)
1133 } elsif ($k eq 'ON') {
1134 my $end = $d + 86399; # no leap day...
1135 $q->{xap} .= " ts:$d..$end";
1136 $$sql .= " AND ts >= $d AND ts <= $end" if defined($sql);
1137 } elsif ($k eq 'BEFORE') {
1138 $q->{xap} .= " ts:..$d";
1139 $$sql .= " AND ts <= $d" if defined($sql);
1140 } elsif ($k eq 'SINCE') {
1141 $q->{xap} .= " ts:$d..";
1142 $$sql .= " AND ts >= $d" if defined($sql);
1144 die "BUG: $k not recognized";
1148 # IMAP to Xapian search key mapping
1153 TEXT => '', # n.b. does not include all headers
1156 # BCC => 'bcc:', # TODO
1157 # KEYWORD # TODO ? dfpre,dfpost,...
1160 # IMAP allows searching arbitrary headers via "HEADER $HDR_NAME $HDR_VAL"
1161 # which gets silly expensive. We only allow the headers we already index.
1162 my %H2X = (%I2X, 'MESSAGE-ID' => 'm:', 'LIST-ID' => 'l:');
1164 sub xap_append ($$$$) {
1165 my ($q, $rest, $k, $xk) = @_;
1166 delete $q->{sql}; # can't use over.sqlite3
1167 defined(my $arg = shift @$rest) or return "BAD $k no arg";
1169 # AFAIK Xapian can't handle [*"] in probabilistic terms
1171 ${$q->{xap}} .= qq[ $xk"$arg"];
1175 sub parse_query ($$) {
1176 my ($self, $query) = @_;
1177 my $q = PublicInbox::IMAPsearchqp::parse($self, $query);
1179 my $max = $self->{ibx}->over->max;
1181 uid_clamp($self, \$beg, \$max);
1182 $q->{range_info} = [ $beg, $max ];
1187 sub refill_xap ($$$$) {
1188 my ($self, $uids, $range_info, $q) = @_;
1189 my ($beg, $end) = @$range_info;
1190 my $srch = $self->{ibx}->search;
1191 my $opt = { mset => 2, limit => 1000 };
1192 my $nshard = $srch->{nshard} // 1;
1193 my $mset = $srch->query("$q uid:$beg..$end", $opt);
1194 @$uids = map { mdocid($nshard, $_) } $mset->items;
1196 $range_info->[0] = $uids->[-1] + 1; # update $beg
1197 return; # possibly more
1202 sub search_xap_range { # long_response
1203 my ($self, $tag, $q, $range_info, $want_msn) = @_;
1205 if (defined(my $err = refill_xap($self, $uids, $range_info, $q))) {
1206 $err ||= 'OK Search done';
1207 $self->write("\r\n$tag $err\r\n");
1210 msn_convert($self, $uids) if $want_msn;
1211 $self->msg_more(join(' ', '', @$uids));
1216 my ($self, $tag, $query, $want_msn) = @_;
1217 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1218 my $q = parse_query($self, $query);
1219 return "$tag $q\r\n" if !ref($q);
1220 my ($sql, $range_info) = delete @$q{qw(sql range_info)};
1221 if (!scalar(keys %$q)) { # overview.sqlite3
1222 $self->msg_more('* SEARCH');
1223 long_response($self, \&search_uid_range,
1224 $tag, $sql, $range_info, $want_msn);
1225 } elsif ($q = $q->{xap}) {
1226 $self->{ibx}->search or
1227 return "$tag BAD search not available for mailbox\r\n";
1228 $self->msg_more('* SEARCH');
1229 long_response($self, \&search_xap_range,
1230 $tag, $q, $range_info, $want_msn);
1232 "$tag BAD Error\r\n";
1236 sub cmd_uid_search ($$$) {
1237 my ($self, $tag, $query) = @_;
1238 search_common($self, $tag, $query);
1241 sub cmd_search ($$$;) {
1242 my ($self, $tag, $query) = @_;
1243 search_common($self, $tag, $query, 1);
1246 sub args_ok ($$) { # duplicated from PublicInbox::NNTP
1247 my ($cb, $argc) = @_;
1248 my $tot = prototype $cb;
1249 my ($nreq, undef) = split(';', $tot);
1250 $nreq = ($nreq =~ tr/$//) - 1;
1251 $tot = ($tot =~ tr/$//) - 1;
1252 ($argc <= $tot && $argc >= $nreq);
1255 # returns 1 if we can continue, 0 if not due to buffered writes or disconnect
1256 sub process_line ($$) {
1257 my ($self, $l) = @_;
1259 # TODO: IMAP allows literals for big requests to upload messages
1260 # (which we don't support) but maybe some big search queries use it.
1261 # RFC 3501 9 (2) doesn't permit TAB or multiple SP
1262 my ($tag, $req, @args) = parse_line('[ \t]+', 0, $l);
1263 pop(@args) if (@args && !defined($args[-1]));
1264 if (@args && uc($req) eq 'UID') {
1265 $req .= "_".(shift @args);
1268 if (defined(my $idle_tag = $self->{-idle_tag})) {
1269 (uc($tag // '') eq 'DONE' && !defined($req)) ?
1270 idle_done($self, $tag) :
1271 "$idle_tag BAD expected DONE\r\n";
1272 } elsif (my $cmd = $self->can('cmd_'.lc($req // ''))) {
1273 if ($cmd == \&cmd_uid_search || $cmd == \&cmd_search) {
1274 # preserve user-supplied quotes for search
1275 (undef, @args) = split(/ search /i, $l, 2);
1277 $cmd->($self, $tag, @args);
1278 } else { # this is weird
1279 auth_challenge_ok($self) //
1281 ' BAD Error in IMAP command '.
1283 ": Unknown command\r\n";
1287 if ($err && $self->{sock}) {
1289 err($self, 'error from: %s (%s)', $l, $err);
1291 $res = "$tag BAD program fault - command not performed\r\n";
1293 return 0 unless defined $res;
1299 # wbuf is unset or empty, here; {long} may add to it
1300 my ($fd, $cb, $t0, @args) = @{$self->{long_cb}};
1301 my $more = eval { $cb->($self, @args) };
1302 if ($@ || !$self->{sock}) { # something bad happened...
1303 delete $self->{long_cb};
1304 my $elapsed = now() - $t0;
1307 "%s during long response[$fd] - %0.6f",
1310 out($self, " deferred[$fd] aborted - %0.6f", $elapsed);
1312 } elsif ($more) { # $self->{wbuf}:
1313 $self->update_idle_time;
1315 # control passed to git_async_cat if $more == \undef
1316 requeue_once($self) if !ref($more);
1317 } else { # all done!
1318 delete $self->{long_cb};
1319 my $elapsed = now() - $t0;
1320 my $fd = fileno($self->{sock});
1321 out($self, " deferred[$fd] done - %0.6f", $elapsed);
1322 my $wbuf = $self->{wbuf}; # do NOT autovivify
1324 $self->requeue unless $wbuf && @$wbuf;
1329 my ($self, $fmt, @args) = @_;
1330 printf { $self->{imapd}->{err} } $fmt."\n", @args;
1334 my ($self, $fmt, @args) = @_;
1335 printf { $self->{imapd}->{out} } $fmt."\n", @args;
1338 sub long_response ($$;@) {
1339 my ($self, $cb, @args) = @_; # cb returns true if more, false if done
1341 my $sock = $self->{sock} or return;
1342 # make sure we disable reading during a long response,
1343 # clients should not be sending us stuff and making us do more
1344 # work while we are stream a response to them
1345 $self->{long_cb} = [ fileno($sock), $cb, now(), @args ];
1346 long_step($self); # kick off!
1350 # callback used by PublicInbox::DS for any (e)poll (in/out/hup/err)
1354 return unless $self->flush_write && $self->{sock} && !$self->{long_cb};
1356 $self->update_idle_time;
1357 # only read more requests if we've drained the write buffer,
1358 # otherwise we can be buffering infinitely w/o backpressure
1360 my $rbuf = $self->{rbuf} // \(my $x = '');
1361 my $line = index($$rbuf, "\n");
1363 if (length($$rbuf) >= LINE_MAX) {
1364 $self->write(\"\* BAD request too long\r\n");
1365 return $self->close;
1367 $self->do_read($rbuf, LINE_MAX, length($$rbuf)) or
1368 return uo2m_hibernate($self);
1369 $line = index($$rbuf, "\n");
1371 $line = substr($$rbuf, 0, $line + 1, '');
1372 $line =~ s/\r?\n\z//s;
1373 return $self->close if $line =~ /[[:cntrl:]]/s;
1375 my $fd = fileno($self->{sock});
1376 my $r = eval { process_line($self, $line) };
1377 my $pending = $self->{wbuf} ? ' pending' : '';
1378 out($self, "[$fd] %s - %0.6f$pending - $r", $line, now() - $t0);
1380 return $self->close if $r < 0;
1381 $self->rbuf_idle($rbuf);
1382 $self->update_idle_time;
1384 # maybe there's more pipelined data, or we'll have
1385 # to register it for socket-readiness notifications
1386 $self->requeue unless $pending;
1389 sub compressed { undef }
1391 sub zflush {} # overridden by IMAPdeflate
1394 sub cmd_compress ($$$) {
1395 my ($self, $tag, $alg) = @_;
1396 return "$tag BAD DEFLATE only\r\n" if uc($alg) ne "DEFLATE";
1397 return "$tag BAD COMPRESS active\r\n" if $self->compressed;
1399 # CRIME made TLS compression obsolete
1400 # return "$tag NO [COMPRESSIONACTIVE]\r\n" if $self->tls_compressed;
1402 PublicInbox::IMAPdeflate->enable($self, $tag);
1407 sub cmd_starttls ($$) {
1408 my ($self, $tag) = @_;
1409 my $sock = $self->{sock} or return;
1410 if ($sock->can('stop_SSL') || $self->compressed) {
1411 return "$tag BAD TLS or compression already enabled\r\n";
1413 my $opt = $self->{imapd}->{accept_tls} or
1414 return "$tag BAD can not initiate TLS negotiation\r\n";
1415 $self->write(\"$tag OK begin TLS negotiation now\r\n");
1416 $self->{sock} = IO::Socket::SSL->start_SSL($sock, %$opt);
1417 $self->requeue if PublicInbox::DS::accept_tls_step($self);
1421 # for graceful shutdown in PublicInbox::Daemon:
1423 my ($self, $now) = @_;
1424 if (defined($self->{-idle_tag})) {
1425 $self->write(\"* BYE server shutting down\r\n");
1426 return; # not busy anymore
1428 ($self->{rbuf} || $self->{wbuf} || $self->not_idle_long($now));
1433 if (my $ibx = delete $self->{ibx}) {
1434 stop_idle($self, $ibx);
1436 $self->SUPER::close; # PublicInbox::DS::close
1439 # we're read-only, so SELECT and EXAMINE do the same thing
1441 *cmd_select = \&cmd_examine;
1443 package PublicInbox::IMAP_preauth;
1444 our @ISA = qw(PublicInbox::IMAP);