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
25 package PublicInbox::IMAP;
27 use base qw(PublicInbox::DS);
28 use fields qw(imapd ibx long_cb -login_tag
29 uid_base -idle_tag uo2m);
31 use PublicInbox::EmlContentFoo qw(parse_content_disposition);
32 use PublicInbox::DS qw(now);
33 use PublicInbox::Syscall qw(EPOLLIN EPOLLONESHOT);
34 use PublicInbox::GitAsyncCat;
35 use Text::ParseWords qw(parse_line);
37 use Hash::Util qw(unlock_hash); # dependency of fields for perl 5.10+, anyways
38 use PublicInbox::Search;
39 use PublicInbox::IMAPsearchqp;
40 *mdocid = \&PublicInbox::Search::mdocid;
43 for my $mod (qw(Email::Address::XS Mail::Address)) {
44 eval "require $mod" or next;
45 $Address = $mod and last;
47 die "neither Email::Address::XS nor Mail::Address loaded: $@" if !$Address;
49 sub LINE_MAX () { 8000 } # RFC 2683 3.2.1.5
51 # Changing UID_SLICE will cause grief for clients which cache.
52 # This also needs to be <64K: we pack it into a uint16_t
53 # for long_response UID (offset) => MSN mappings
54 sub UID_SLICE () { 50_000 }
56 # these values area also used for sorting
57 sub NEED_SMSG () { 1 }
58 sub NEED_BLOB () { NEED_SMSG|2 }
59 sub CRLF_BREF () { 4 }
61 sub CRLF_HDR () { 16 }
63 sub CRLF_BDY () { 64 }
64 my $OP_EML_NEW = [ EML_HDR - 1, \&op_eml_new ];
65 my $OP_CRLF_BREF = [ CRLF_BREF, \&op_crlf_bref ];
66 my $OP_CRLF_HDR = [ CRLF_HDR, \&op_crlf_hdr ];
67 my $OP_CRLF_BDY = [ CRLF_BDY, \&op_crlf_bdy ];
70 'BODY[HEADER]' => [ NEED_BLOB|EML_HDR|CRLF_HDR, \&emit_rfc822_header ],
71 'BODY[TEXT]' => [ NEED_BLOB|EML_BDY|CRLF_BDY, \&emit_rfc822_text ],
72 'BODY[]' => [ NEED_BLOB|CRLF_BREF, \&emit_rfc822 ],
73 'RFC822.HEADER' => [ NEED_BLOB|EML_HDR|CRLF_HDR, \&emit_rfc822_header ],
74 'RFC822.TEXT' => [ NEED_BLOB|EML_BDY|CRLF_BDY, \&emit_rfc822_text ],
75 'RFC822.SIZE' => [ NEED_SMSG, \&emit_rfc822_size ],
76 RFC822 => [ NEED_BLOB|CRLF_BREF, \&emit_rfc822 ],
77 BODY => [ NEED_BLOB|EML_HDR|EML_BDY, \&emit_body ],
78 BODYSTRUCTURE => [ NEED_BLOB|EML_HDR|EML_BDY, \&emit_bodystructure ],
79 ENVELOPE => [ NEED_BLOB|EML_HDR, \&emit_envelope ],
80 FLAGS => [ 0, \&emit_flags ],
81 INTERNALDATE => [ NEED_SMSG, \&emit_internaldate ],
83 my %FETCH_ATT = map { $_ => [ $_ ] } keys %FETCH_NEED;
85 # aliases (RFC 3501 section 6.4.5)
86 $FETCH_ATT{FAST} = [ qw(FLAGS INTERNALDATE RFC822.SIZE) ];
87 $FETCH_ATT{ALL} = [ @{$FETCH_ATT{FAST}}, 'ENVELOPE' ];
88 $FETCH_ATT{FULL} = [ @{$FETCH_ATT{ALL}}, 'BODY' ];
90 for my $att (keys %FETCH_ATT) {
91 my %h = map { $_ => $FETCH_NEED{$_} } @{$FETCH_ATT{$att}};
92 $FETCH_ATT{$att} = \%h;
96 my $valid_range = '[0-9]+|[0-9]+:[0-9]+|[0-9]+:\*';
97 $valid_range = qr/\A(?:$valid_range)(?:,(?:$valid_range))*\z/;
99 # RFC 3501 5.4. Autologout Timer needs to be >= 30min
100 $PublicInbox::DS::EXPTIME = 60 * 30;
104 my $capa = capa($self);
105 $self->write(\"* OK [$capa] public-inbox-imapd ready\r\n");
109 my ($class, $sock, $imapd) = @_;
110 my $self = fields::new('PublicInbox::IMAP_preauth');
114 if ($sock->can('accept_SSL') && !$sock->accept_SSL) {
115 return CORE::close($sock) if $! != EAGAIN;
116 $ev = PublicInbox::TLS::epollbit();
117 $wbuf = [ \&PublicInbox::DS::accept_tls_step, \&greet ];
119 $self->SUPER::new($sock, $ev | EPOLLONESHOT);
120 $self->{imapd} = $imapd;
122 $self->{wbuf} = $wbuf;
126 $self->update_idle_time;
135 # dovecot advertises IDLE pre-login; perhaps because some clients
136 # depend on it, so we'll do the same
137 my $capa = 'CAPABILITY IMAP4rev1 IDLE';
138 if ($self->logged_in) {
139 $capa .= ' COMPRESS=DEFLATE';
141 if (!($self->{sock} // $self)->can('accept_SSL') &&
142 $self->{imapd}->{accept_tls}) {
143 $capa .= ' STARTTLS';
145 $capa .= ' AUTH=ANONYMOUS';
149 sub login_success ($$) {
150 my ($self, $tag) = @_;
151 bless $self, 'PublicInbox::IMAP';
152 my $capa = capa($self);
153 "$tag OK [$capa] Logged in\r\n";
156 sub auth_challenge_ok ($) {
158 my $tag = delete($self->{-login_tag}) or return;
159 login_success($self, $tag);
162 sub cmd_login ($$$$) {
163 my ($self, $tag) = @_; # ignore ($user, $password) = ($_[2], $_[3])
164 login_success($self, $tag);
168 my ($self, $tag) = @_;
169 delete @$self{qw(uid_base uo2m)};
170 delete $self->{ibx} ? "$tag OK Close done\r\n"
171 : "$tag BAD No mailbox\r\n";
174 sub cmd_logout ($$) {
175 my ($self, $tag) = @_;
176 delete $self->{-idle_tag};
177 $self->write(\"* BYE logging out\r\n$tag OK Logout done\r\n");
178 $self->shutdn; # PublicInbox::DS::shutdn
182 sub cmd_authenticate ($$$) {
183 my ($self, $tag) = @_; # $method = $_[2], should be "ANONYMOUS"
184 $self->{-login_tag} = $tag;
188 sub cmd_capability ($$) {
189 my ($self, $tag) = @_;
190 '* '.capa($self)."\r\n$tag OK Capability done\r\n";
193 sub cmd_noop ($$) { "$_[1] OK Noop done\r\n" }
195 # uo2m: UID Offset to MSN, this is an arrayref by default,
196 # but uo2m_hibernate can compact and deduplicate it
197 sub uo2m_ary_new ($) {
199 my $base = $self->{uid_base};
200 my $uids = $self->{ibx}->over->uid_range($base + 1, $base + UID_SLICE);
202 # convert UIDs to offsets from {base}
203 my @tmp; # [$UID_OFFSET] => $MSN
206 $tmp[$_ - $base] = ++$msn for @$uids;
210 # changes UID-offset-to-MSN mapping into a deduplicated scalar:
211 # uint16_t uo2m[UID_SLICE].
212 # May be swapped out for idle clients if THP is disabled.
213 sub uo2m_hibernate ($) {
215 ref(my $uo2m = $self->{uo2m}) or return;
216 my %dedupe = ( uo2m_pack($uo2m) => undef );
217 $self->{uo2m} = (keys(%dedupe))[0];
221 sub uo2m_last_uid ($) {
223 defined(my $uo2m = $self->{uo2m}) or die 'BUG: uo2m_last_uid w/o {uo2m}';
224 (ref($uo2m) ? @$uo2m : (length($uo2m) >> 1)) + $self->{uid_base};
228 # $_[0] is an arrayref of MSNs, it may have undef gaps if there
229 # are gaps in the corresponding UIDs: [ msn1, msn2, undef, msn3 ]
230 no warnings 'uninitialized';
231 pack('S*', @{$_[0]});
234 # extend {uo2m} to account for new messages which arrived since
235 # {uo2m} was created.
236 sub uo2m_extend ($$) {
237 my ($self, $new_uid_max) = @_;
238 defined(my $uo2m = $self->{uo2m}) or
239 return($self->{uo2m} = uo2m_ary_new($self));
240 my $beg = uo2m_last_uid($self); # last UID we've learned
241 return $uo2m if $beg >= $new_uid_max; # fast path
243 # need to extend the current range:
244 my $base = $self->{uid_base};
246 my $uids = $self->{ibx}->over->uid_range($beg, $base + UID_SLICE);
247 my @tmp; # [$UID_OFFSET] => $MSN
249 my $msn = $uo2m->[-1];
250 $tmp[$_ - $beg] = ++$msn for @$uids;
254 my $msn = unpack('S', substr($uo2m, -2, 2));
255 $tmp[$_ - $beg] = ++$msn for @$uids;
256 $uo2m .= uo2m_pack(\@tmp);
257 my %dedupe = ($uo2m => undef);
258 $self->{uo2m} = (keys %dedupe)[0];
262 # the flexible version which works on scalars and array refs.
263 # Must call uo2m_extend before this
265 my ($self, $uid) = @_;
266 my $uo2m = $self->{uo2m};
267 my $off = $uid - $self->{uid_base} - 1;
268 ref($uo2m) ? $uo2m->[$off] : unpack('S', substr($uo2m, $off << 1, 2));
271 # returns an arrayref of UIDs, so MSNs can be translated to UIDs via:
272 # $msn2uid->[$MSN-1] => $UID. The result of this is always ephemeral
273 # and does not live beyond the event loop.
276 my $base = $self->{uid_base};
277 my $uo2m = uo2m_extend($self, $base + UID_SLICE);
278 $uo2m = [ unpack('S*', $uo2m) ] if !ref($uo2m);
282 for my $msn (@$uo2m) {
284 $msn2uid[$msn - 1] = $uo + $base if $msn;
289 # converts a set of message sequence numbers in requests to UIDs:
290 sub msn_to_uid_range ($$) {
292 $_[1] =~ s!([0-9]+)!$msn2uid->[$1 - 1] // ($msn2uid->[-1] + 1)!sge;
295 # called by PublicInbox::InboxIdle
296 sub on_inbox_unlock {
297 my ($self, $ibx) = @_;
298 my $old = uo2m_last_uid($self);
299 my $uid_end = $self->{uid_base} + UID_SLICE;
300 uo2m_extend($self, $uid_end);
301 my $new = uo2m_last_uid($self);
303 my $msn = uid2msn($self, $new);
304 $self->write(\"* $msn EXISTS\r\n");
305 } elsif ($new == $uid_end) { # max exceeded $uid_end
306 # continue idling w/o inotify
307 my $sock = $self->{sock} or return;
308 $ibx->unsubscribe_unlock(fileno($sock));
312 # called every X minute(s) or so by PublicInbox::DS::later
318 for my $i (values %$old) {
319 next if ($i->{wbuf} || !exists($i->{-idle_tag}));
320 $i->update_idle_time or next;
321 $IDLERS->{fileno($i->{sock})} = $i;
322 $i->write(\"* OK Still here\r\n");
324 $idle_timer = scalar keys %$IDLERS ?
325 PublicInbox::DS::later(\&idle_tick_all) : undef;
329 my ($self, $tag) = @_;
330 # IDLE seems allowed by dovecot w/o a mailbox selected *shrug*
331 my $ibx = $self->{ibx} or return "$tag BAD no mailbox selected\r\n";
332 $self->{-idle_tag} = $tag;
333 my $max = $ibx->over->max;
334 my $uid_end = $self->{uid_base} + UID_SLICE;
335 my $sock = $self->{sock} or return;
336 my $fd = fileno($sock);
337 # only do inotify on most recent slice
338 if ($max < $uid_end) {
339 uo2m_extend($self, $uid_end);
340 $ibx->subscribe_unlock($fd, $self);
341 $self->{imapd}->idler_start;
343 $idle_timer //= PublicInbox::DS::later(\&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->{inboxlist} or return;
382 push @$l, map { qq[* LIST (\\HasNoChildren) "." $_\r\n] } @created;
385 sub inbox_lookup ($$) {
386 my ($self, $mailbox) = @_;
387 my ($ibx, $exists, $uidnext, $uid_base);
388 if ($mailbox =~ /\A(.+)\.([0-9]+)\z/) {
389 # old mail: inbox.comp.foo.$SLICE_IDX
391 $uid_base = $2 * UID_SLICE;
392 $ibx = $self->{imapd}->{mailboxes}->{lc $mailbox} or return;
394 ($exists, $uidnext, $max) = $ibx->over->imap_status($uid_base,
395 $uid_base + UID_SLICE);
396 ensure_slices_exist($self->{imapd}, $ibx, $max);
397 } else { # check for dummy inboxes
398 $mailbox = lc $mailbox;
399 $ibx = $self->{imapd}->{mailboxes}->{$mailbox} or return;
401 # if "INBOX.foo.bar" is selected and "INBOX.foo.bar.0",
402 # check for new UID ranges (e.g. "INBOX.foo.bar.1")
403 if (my $z = $self->{imapd}->{mailboxes}->{"$mailbox.0"}) {
404 ensure_slices_exist($self->{imapd}, $z, $z->over->max);
407 $uid_base = $exists = 0;
410 ($ibx, $exists, $uidnext, $uid_base);
413 sub cmd_examine ($$$) {
414 my ($self, $tag, $mailbox) = @_;
415 my ($ibx, $exists, $uidnext, $base) = inbox_lookup($self, $mailbox);
416 return "$tag NO Mailbox doesn't exist: $mailbox\r\n" if !$ibx;
417 $self->{uid_base} = $base;
418 delete $self->{uo2m};
420 # XXX: do we need this? RFC 5162/7162
421 my $ret = $self->{ibx} ? "* OK [CLOSED] previous closed\r\n" : '';
427 * OK [PERMANENTFLAGS ()] Read-only mailbox\r
428 * OK [UNSEEN $exists]\r
429 * OK [UIDNEXT $uidnext]\r
430 * OK [UIDVALIDITY $ibx->{uidvalidity}]\r
431 $tag OK [READ-ONLY] EXAMINE/SELECT done\r
439 } elsif ($v =~ /[{"\r\n%*\\\[]/) { # literal string
440 '{' . length($v) . "}\r\n" . $v;
441 } else { # quoted string
446 sub addr_envelope ($$;$) {
447 my ($eml, $x, $y) = @_;
448 my $v = $eml->header_raw($x) //
449 ($y ? $eml->header_raw($y) : undef) // return 'NIL';
451 my @x = $Address->parse($v) or return 'NIL';
453 map { '(' . join(' ',
454 _esc($_->name), 'NIL',
455 _esc($_->user), _esc($_->host)
461 sub eml_envelope ($) {
464 _esc($eml->header_raw('Date')),
465 _esc($eml->header_raw('Subject')),
466 addr_envelope($eml, 'From'),
467 addr_envelope($eml, 'Sender', 'From'),
468 addr_envelope($eml, 'Reply-To', 'From'),
469 addr_envelope($eml, 'To'),
470 addr_envelope($eml, 'Cc'),
471 addr_envelope($eml, 'Bcc'),
472 _esc($eml->header_raw('In-Reply-To')),
473 _esc($eml->header_raw('Message-ID')),
479 if ($hash && scalar keys %$hash) {
480 $hash = [ %$hash ]; # flatten hash into 1-dimensional array
481 '(' . join(' ', map { _esc($_) } @$hash) . ')';
487 sub body_disposition ($) {
489 my $cd = $eml->header_raw('Content-Disposition') or return 'NIL';
490 $cd = parse_content_disposition($cd);
491 my $buf = '('._esc($cd->{type});
492 $buf .= ' ' . _esc_hash(delete $cd->{attributes});
496 sub body_leaf ($$;$) {
497 my ($eml, $structure, $hold) = @_;
499 $eml->{is_submsg} and # parent was a message/(rfc822|news|global)
500 $buf .= eml_envelope($eml). ' ';
502 $buf .= '('._esc($ct->{type}).' ';
503 $buf .= _esc($ct->{subtype});
504 $buf .= ' ' . _esc_hash(delete $ct->{attributes});
505 $buf .= ' ' . _esc($eml->header_raw('Content-ID'));
506 $buf .= ' ' . _esc($eml->header_raw('Content-Description'));
507 my $cte = $eml->header_raw('Content-Transfer-Encoding') // '7bit';
508 $buf .= ' ' . _esc($cte);
509 $buf .= ' ' . $eml->{imap_body_len};
510 $buf .= ' '.($eml->body_raw =~ tr/\n/\n/) if lc($ct->{type}) eq 'text';
512 # for message/(rfc822|global|news), $hold[0] should have envelope
513 $buf .= ' ' . (@$hold ? join('', @$hold) : 'NIL') if $hold;
516 $buf .= ' '._esc($eml->header_raw('Content-MD5'));
517 $buf .= ' '. body_disposition($eml);
518 $buf .= ' '._esc($eml->header_raw('Content-Language'));
519 $buf .= ' '._esc($eml->header_raw('Content-Location'));
524 sub body_parent ($$$) {
525 my ($eml, $structure, $hold) = @_;
527 my $type = lc($ct->{type});
528 if ($type eq 'multipart') {
530 $buf .= @$hold ? join('', @$hold) : 'NIL';
531 $buf .= ' '._esc($ct->{subtype});
533 $buf .= ' '._esc_hash(delete $ct->{attributes});
534 $buf .= ' '.body_disposition($eml);
535 $buf .= ' '._esc($eml->header_raw('Content-Language'));
536 $buf .= ' '._esc($eml->header_raw('Content-Location'));
540 } else { # message/(rfc822|global|news)
541 @$hold = (body_leaf($eml, $structure, $hold));
545 # this is gross, but we need to process the parent part AFTER
546 # the child parts are done
547 sub bodystructure_prep {
549 my ($eml, $depth) = @$p; # ignore idx
550 # set length here, as $eml->{bdy} gets deleted for message/rfc822
551 $eml->{imap_body_len} = length($eml->body_raw);
552 push @$q, $eml, $depth;
555 # for FETCH BODY and FETCH BODYSTRUCTURE
556 sub fetch_body ($;$) {
557 my ($eml, $structure) = @_;
559 $eml->each_part(\&bodystructure_prep, \@q, 0, 1);
563 my ($part, $depth) = splice(@q, -2);
564 my $is_mp_parent = $depth == ($cur_depth - 1);
568 body_parent($part, $structure, \@hold);
570 unshift @hold, body_leaf($part, $structure);
576 sub requeue_once ($) {
578 # COMPRESS users all share the same DEFLATE context.
579 # Flush it here to ensure clients don't see
583 # no recursion, schedule another call ASAP,
584 # but only after all pending writes are done.
586 my $new_size = push(@{$self->{wbuf}}, \&long_step);
588 # wbuf may be populated by $cb, no need to rearm if so:
589 $self->requeue if $new_size == 1;
593 my ($self, $smsg, $bref, $ops, $partial) = @_;
594 my $uid = $smsg->{num};
595 $self->msg_more('* '.uid2msn($self, $uid)." FETCH (UID $uid");
597 for (my $i = 0; $i < @$ops;) {
599 $ops->[$i++]->($self, $k, $smsg, $bref, $eml);
601 partial_emit($self, $partial, $eml) if $partial;
602 $self->msg_more(")\r\n");
605 sub fetch_blob_cb { # called by git->cat_async via git_async_cat
606 my ($bref, $oid, $type, $size, $fetch_arg) = @_;
607 my ($self, undef, $msgs, $range_info, $ops, $partial) = @$fetch_arg;
608 my $smsg = shift @$msgs or die 'BUG: no smsg';
609 if (!defined($oid)) {
610 # it's possible to have TOCTOU if an admin runs
611 # public-inbox-(edit|purge), just move onto the next message
612 return requeue_once($self);
614 $smsg->{blob} eq $oid or die "BUG: $smsg->{blob} != $oid";
616 fetch_run_ops($self, $smsg, $bref, $ops, $partial);
621 my ($self, $k, undef, $bref) = @_;
622 $self->msg_more(" $k {" . length($$bref)."}\r\n");
623 $self->msg_more($$bref);
626 # Mail::IMAPClient::message_string cares about this by default,
627 # (->Ignoresizeerrors attribute). Admins are encouraged to
628 # --reindex for IMAP support, anyways.
629 sub emit_rfc822_size {
630 my ($self, $k, $smsg) = @_;
631 $self->msg_more(' RFC822.SIZE ' . $smsg->{bytes});
634 sub emit_internaldate {
635 my ($self, undef, $smsg) = @_;
636 $self->msg_more(' INTERNALDATE "'.$smsg->internaldate.'"');
639 sub emit_flags { $_[0]->msg_more(' FLAGS ()') }
642 my ($self, undef, undef, undef, $eml) = @_;
643 $self->msg_more(' ENVELOPE '.eml_envelope($eml));
646 sub emit_rfc822_header {
647 my ($self, $k, undef, undef, $eml) = @_;
648 $self->msg_more(" $k {".length(${$eml->{hdr}})."}\r\n");
649 $self->msg_more(${$eml->{hdr}});
652 # n.b. this is sorted to be after any emit_eml_new ops
653 sub emit_rfc822_text {
654 my ($self, $k, undef, $bref) = @_;
655 $self->msg_more(" $k {".length($$bref)."}\r\n");
656 $self->msg_more($$bref);
659 sub emit_bodystructure {
660 my ($self, undef, undef, undef, $eml) = @_;
661 $self->msg_more(' BODYSTRUCTURE '.fetch_body($eml, 1));
665 my ($self, undef, undef, undef, $eml) = @_;
666 $self->msg_more(' BODY '.fetch_body($eml));
669 # set $eml once ($_[4] == $eml, $_[3] == $bref)
670 sub op_eml_new { $_[4] = PublicInbox::Eml->new($_[3]) }
672 # s/From / fixes old bug from import (pre-a0c07cba0e5d8b6a)
674 ${$_[0]} =~ s/(?<!\r)\n/\r\n/sg;
675 ${$_[0]} =~ s/\A[\r\n]*From [^\r\n]*\r\n//s;
678 sub op_crlf_bref { to_crlf_full($_[3]) }
680 sub op_crlf_hdr { to_crlf_full($_[4]->{hdr}) }
682 sub op_crlf_bdy { ${$_[4]->{bdy}} =~ s/(?<!\r)\n/\r\n/sg if $_[4]->{bdy} }
684 sub uid_clamp ($$$) {
685 my ($self, $beg, $end) = @_;
686 my $uid_min = $self->{uid_base} + 1;
687 my $uid_end = $uid_min + UID_SLICE - 1;
688 $$beg = $uid_min if $$beg < $uid_min;
689 $$end = $uid_end if $$end > $uid_end;
692 sub range_step ($$) {
693 my ($self, $range_csv) = @_;
694 my ($beg, $end, $range);
695 if ($$range_csv =~ s/\A([^,]+),//) {
698 $range = $$range_csv;
701 my $uid_base = $self->{uid_base};
702 my $uid_end = $uid_base + UID_SLICE;
703 if ($range =~ /\A([0-9]+):([0-9]+)\z/) {
704 ($beg, $end) = ($1 + 0, $2 + 0);
705 uid_clamp($self, \$beg, \$end);
706 } elsif ($range =~ /\A([0-9]+):\*\z/) {
708 $end = $self->{ibx}->over->max;
709 $end = $uid_end if $end > $uid_end;
710 $beg = $end if $beg > $end;
711 uid_clamp($self, \$beg, \$end);
712 } elsif ($range =~ /\A[0-9]+\z/) {
713 $beg = $end = $range + 0;
714 # just let the caller do an out-of-range query if a single
715 # UID is out-of-range
716 ++$beg if ($beg <= $uid_base || $end > $uid_end);
718 return 'BAD fetch range';
720 [ $beg, $end, $$range_csv ];
723 sub refill_range ($$$) {
724 my ($self, $msgs, $range_info) = @_;
725 my ($beg, $end, $range_csv) = @$range_info;
726 if (scalar(@$msgs = @{$self->{ibx}->over->query_xover($beg, $end)})) {
727 $range_info->[0] = $msgs->[-1]->{num} + 1;
730 return 'OK Fetch done' if !$range_csv;
731 my $next_range = range_step($self, \$range_csv);
732 return $next_range if !ref($next_range); # error
733 @$range_info = @$next_range;
734 undef; # keep looping
737 sub fetch_blob { # long_response
738 my ($self, $tag, $msgs, $range_info, $ops, $partial) = @_;
739 while (!@$msgs) { # rare
740 if (my $end = refill_range($self, $msgs, $range_info)) {
741 $self->write(\"$tag $end\r\n");
745 uo2m_extend($self, $msgs->[-1]->{num});
746 git_async_cat($self->{ibx}->git, $msgs->[0]->{blob},
747 \&fetch_blob_cb, \@_);
750 sub fetch_smsg { # long_response
751 my ($self, $tag, $msgs, $range_info, $ops) = @_;
752 while (!@$msgs) { # rare
753 if (my $end = refill_range($self, $msgs, $range_info)) {
754 $self->write(\"$tag $end\r\n");
758 uo2m_extend($self, $msgs->[-1]->{num});
759 fetch_run_ops($self, $_, undef, $ops) for @$msgs;
764 sub refill_uids ($$$;$) {
765 my ($self, $uids, $range_info, $sql) = @_;
766 my ($beg, $end, $range_csv) = @$range_info;
767 my $over = $self->{ibx}->over;
769 if (scalar(@$uids = @{$over->uid_range($beg, $end, $sql)})) {
770 $range_info->[0] = $uids->[-1] + 1; # update $beg
772 } elsif (!$range_csv) {
775 my $next_range = range_step($self, \$range_csv);
776 return $next_range if !ref($next_range); # error
777 ($beg, $end, $range_csv) = @$range_info = @$next_range;
783 sub fetch_uid { # long_response
784 my ($self, $tag, $uids, $range_info, $ops) = @_;
785 if (defined(my $err = refill_uids($self, $uids, $range_info))) {
786 $err ||= 'OK Fetch done';
787 $self->write("$tag $err\r\n");
790 my $adj = $self->{uid_base} + 1;
791 my $uo2m = uo2m_extend($self, $uids->[-1]);
792 $uo2m = [ unpack('S*', $uo2m) ] if !ref($uo2m);
795 $self->msg_more("* $uo2m->[$_ - $adj] FETCH (UID $_");
796 for ($i = 0; $i < @$ops;) {
798 $ops->[$i++]->($self, $k);
800 $self->msg_more(")\r\n");
806 sub cmd_status ($$$;@) {
807 my ($self, $tag, $mailbox, @items) = @_;
808 return "$tag BAD no items\r\n" if !scalar(@items);
809 ($items[0] !~ s/\A\(//s || $items[-1] !~ s/\)\z//s) and
810 return "$tag BAD invalid args\r\n";
811 my ($ibx, $exists, $uidnext) = inbox_lookup($self, $mailbox);
812 return "$tag NO Mailbox doesn't exist: $mailbox\r\n" if !$ibx;
814 for my $it (@items) {
817 if ($it =~ /\A(?:MESSAGES|UNSEEN|RECENT)\z/) {
819 } elsif ($it eq 'UIDNEXT') {
821 } elsif ($it eq 'UIDVALIDITY') {
822 push @it, $ibx->{uidvalidity};
824 return "$tag BAD invalid item\r\n";
827 return "$tag BAD no items\r\n" if !@it;
828 "* STATUS $mailbox (".join(' ', @it).")\r\n" .
829 "$tag OK Status done\r\n";
832 my %patmap = ('*' => '.*', '%' => '[^\.]*');
833 sub cmd_list ($$$$) {
834 my ($self, $tag, $refname, $wildcard) = @_;
835 my $l = $self->{imapd}->{inboxlist};
836 if ($refname eq '' && $wildcard eq '') {
837 # request for hierarchy delimiter
838 $l = [ qq[* LIST (\\Noselect) "." ""\r\n] ];
839 } elsif ($refname ne '' || $wildcard ne '*') {
840 $wildcard =~ s!([^a-z0-9_])!$patmap{$1} // "\Q$1"!egi;
841 $l = [ grep(/ \Q$refname\E$wildcard\r\n\z/is, @$l) ];
843 \(join('', @$l, "$tag OK List done\r\n"));
846 sub cmd_lsub ($$$$) {
847 my (undef, $tag) = @_; # same args as cmd_list
848 "$tag OK Lsub done\r\n";
851 sub eml_index_offs_i { # PublicInbox::Eml::each_part callback
853 my ($eml, undef, $idx) = @$p;
854 if ($idx && lc($eml->ct->{type}) eq 'multipart') {
855 $eml->{imap_bdy} = $eml->{bdy} // \'';
857 $all->{$idx} = $eml; # $idx => Eml
860 # prepares an index for BODY[$SECTION_IDX] fetches
861 sub eml_body_idx ($$) {
862 my ($eml, $section_idx) = @_;
863 my $idx = $eml->{imap_all_parts} //= do {
865 $eml->each_part(\&eml_index_offs_i, $all, 0, 1);
866 # top-level of multipart, BODY[0] not allowed (nz-number)
870 $idx->{$section_idx};
873 # BODY[($SECTION_IDX)?(.$SECTION_NAME)?]<$offset.$bytes>
875 my ($eml, $section_idx, $section_name) = @_;
876 if (defined $section_idx) {
877 $eml = eml_body_idx($eml, $section_idx) or return;
879 if (defined $section_name) {
880 if ($section_name eq 'MIME') {
881 # RFC 3501 6.4.5 states:
882 # The MIME part specifier MUST be prefixed
883 # by one or more numeric part specifiers
884 return unless defined $section_idx;
885 return $eml->header_obj->as_string . "\r\n";
887 my $bdy = $eml->{bdy} // $eml->{imap_bdy} // \'';
888 $eml = PublicInbox::Eml->new($$bdy);
889 if ($section_name eq 'TEXT') {
890 return $eml->body_raw;
891 } elsif ($section_name eq 'HEADER') {
892 return $eml->header_obj->as_string . "\r\n";
894 die "BUG: bad section_name=$section_name";
897 ${$eml->{bdy} // $eml->{imap_bdy} // \''};
900 # similar to what's in PublicInbox::Eml::re_memo, but doesn't memoize
901 # to avoid OOM with malicious users
902 sub hdrs_regexp ($) {
904 my $names = join('|', map { "\Q$_" } split(/[ \t]+/, $hdrs));
905 qr/^(?:$names):[ \t]*[^\n]*\r?\n # 1st line
906 # continuation lines:
907 (?:[^:\n]*?[ \t]+[^\n]*\r?\n)*
911 # BODY[($SECTION_IDX.)?HEADER.FIELDS.NOT ($HDRS)]<$offset.$bytes>
912 sub partial_hdr_not {
913 my ($eml, $section_idx, $hdrs_re) = @_;
914 if (defined $section_idx) {
915 $eml = eml_body_idx($eml, $section_idx) or return;
917 my $str = $eml->header_obj->as_string;
918 $str =~ s/$hdrs_re//g;
919 $str =~ s/(?<!\r)\n/\r\n/sg;
923 # BODY[($SECTION_IDX.)?HEADER.FIELDS ($HDRS)]<$offset.$bytes>
924 sub partial_hdr_get {
925 my ($eml, $section_idx, $hdrs_re) = @_;
926 if (defined $section_idx) {
927 $eml = eml_body_idx($eml, $section_idx) or return;
929 my $str = $eml->header_obj->as_string;
930 $str = join('', ($str =~ m/($hdrs_re)/g));
931 $str =~ s/(?<!\r)\n/\r\n/sg;
935 sub partial_prepare ($$$$) {
936 my ($need, $partial, $want, $att) = @_;
938 # recombine [ "BODY[1.HEADER.FIELDS", "(foo", "bar)]" ]
939 # back to: "BODY[1.HEADER.FIELDS (foo bar)]"
940 return unless $att =~ /\ABODY\[/s;
941 until (rindex($att, ']') >= 0) {
942 my $next = shift @$want or return;
943 $att .= ' ' . uc($next);
945 if ($att =~ /\ABODY\[([0-9]+(?:\.[0-9]+)*)? # 1 - section_idx
946 (?:\.(HEADER|MIME|TEXT))? # 2 - section_name
947 \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 3, 4
948 $partial->{$att} = [ \&partial_body, $1, $2, $3, $4 ];
949 $$need |= CRLF_BREF|EML_HDR|EML_BDY;
950 } elsif ($att =~ /\ABODY\[(?:([0-9]+(?:\.[0-9]+)*)\.)? # 1 - section_idx
951 (?:HEADER\.FIELDS(\.NOT)?)\x20 # 2
952 \(([A-Z0-9\-\x20]+)\) # 3 - hdrs
953 \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 4 5
954 my $tmp = $partial->{$att} = [ $2 ? \&partial_hdr_not
957 $tmp->[2] = hdrs_regexp($3);
959 # don't emit CRLF_HDR instruction, here, partial_hdr_*
960 # will do CRLF conversion with only the extracted result
961 # and not waste time converting lines we don't care about.
968 sub partial_emit ($$$) {
969 my ($self, $partial, $eml) = @_;
971 my ($k, $cb, @args) = @$_;
972 my ($offset, $len) = splice(@args, -2);
973 # $cb is partial_body|partial_hdr_get|partial_hdr_not
974 my $str = $cb->($eml, @args) // '';
975 if (defined $offset) {
977 $str = substr($str, $offset, $len);
978 $k =~ s/\.$len>\z/>/ or warn
979 "BUG: unable to remove `.$len>' from `$k'";
981 $str = substr($str, $offset);
987 $self->msg_more(" $k {$len}\r\n");
988 $self->msg_more($str);
992 sub fetch_compile ($) {
994 if ($want->[0] =~ s/\A\(//s) {
995 $want->[-1] =~ s/\)\z//s or return 'BAD no rparen';
997 my (%partial, %seen, @op);
999 while (defined(my $att = shift @$want)) {
1001 next if $att eq 'UID'; # always returned
1002 $att =~ s/\ABODY\.PEEK\[/BODY\[/; # we're read-only
1003 my $x = $FETCH_ATT{$att};
1005 while (my ($k, $fl_cb) = each %$x) {
1006 next if $seen{$k}++;
1007 $need |= $fl_cb->[0];
1008 push @op, [ @$fl_cb, $k ];
1010 } elsif (!partial_prepare(\$need, \%partial, $want, $att)) {
1011 return "BAD param: $att";
1016 # stabilize partial order for consistency and ease-of-debugging:
1017 if (scalar keys %partial) {
1019 $r[2] = [ map { [ $_, @{$partial{$_}} ] } sort keys %partial ];
1022 push @op, $OP_EML_NEW if ($need & (EML_HDR|EML_BDY));
1024 # do we need CRLF conversion?
1025 if ($need & CRLF_BREF) {
1026 push @op, $OP_CRLF_BREF;
1027 } elsif (my $crlf = ($need & (CRLF_HDR|CRLF_BDY))) {
1028 if ($crlf == (CRLF_HDR|CRLF_BDY)) {
1029 push @op, $OP_CRLF_BREF;
1030 } elsif ($need & CRLF_HDR) {
1031 push @op, $OP_CRLF_HDR;
1033 push @op, $OP_CRLF_BDY;
1037 $r[0] = $need & NEED_BLOB ? \&fetch_blob :
1038 ($need & NEED_SMSG ? \&fetch_smsg : \&fetch_uid);
1040 # r[1] = [ $key1, $cb1, $key2, $cb2, ... ]
1041 use sort 'stable'; # makes output more consistent
1042 $r[1] = [ map { ($_->[2], $_->[1]) } sort { $a->[0] <=> $b->[0] } @op ];
1046 sub cmd_uid_fetch ($$$$;@) {
1047 my ($self, $tag, $range_csv, @want) = @_;
1048 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1049 my ($cb, $ops, $partial) = fetch_compile(\@want);
1050 return "$tag $cb\r\n" unless $ops;
1052 # cb is one of fetch_blob, fetch_smsg, fetch_uid
1053 $range_csv = 'bad' if $range_csv !~ $valid_range;
1054 my $range_info = range_step($self, \$range_csv);
1055 return "$tag $range_info\r\n" if !ref($range_info);
1056 uo2m_hibernate($self) if $cb == \&fetch_blob; # slow, save RAM
1057 long_response($self, $cb, $tag, [], $range_info, $ops, $partial);
1060 sub cmd_fetch ($$$$;@) {
1061 my ($self, $tag, $range_csv, @want) = @_;
1062 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1063 my ($cb, $ops, $partial) = fetch_compile(\@want);
1064 return "$tag $cb\r\n" unless $ops;
1066 # cb is one of fetch_blob, fetch_smsg, fetch_uid
1067 $range_csv = 'bad' if $range_csv !~ $valid_range;
1068 msn_to_uid_range(msn2uid($self), $range_csv);
1069 my $range_info = range_step($self, \$range_csv);
1070 return "$tag $range_info\r\n" if !ref($range_info);
1071 uo2m_hibernate($self) if $cb == \&fetch_blob; # slow, save RAM
1072 long_response($self, $cb, $tag, [], $range_info, $ops, $partial);
1075 sub msn_convert ($$) {
1076 my ($self, $uids) = @_;
1077 my $adj = $self->{uid_base} + 1;
1078 my $uo2m = uo2m_extend($self, $uids->[-1]);
1079 $uo2m = [ unpack('S*', $uo2m) ] if !ref($uo2m);
1080 $_ = $uo2m->[$_ - $adj] for @$uids;
1083 sub search_uid_range { # long_response
1084 my ($self, $tag, $sql, $range_info, $want_msn) = @_;
1086 if (defined(my $err = refill_uids($self, $uids, $range_info, $sql))) {
1087 $err ||= 'OK Search done';
1088 $self->write("\r\n$tag $err\r\n");
1091 msn_convert($self, $uids) if $want_msn;
1092 $self->msg_more(join(' ', '', @$uids));
1097 my ($q, $k, $d) = @_;
1098 my $sql = $q->{sql};
1101 if ($k eq 'SENTON') {
1102 my $end = $d + 86399; # no leap day...
1103 my $da = strftime('%Y%m%d%H%M%S', gmtime($d));
1104 my $db = strftime('%Y%m%d%H%M%S', gmtime($end));
1105 $q->{xap} .= " dt:$da..$db";
1106 $$sql .= " AND ds >= $d AND ds <= $end" if defined($sql);
1107 } elsif ($k eq 'SENTBEFORE') {
1108 $q->{xap} .= ' d:..'.strftime('%Y%m%d', gmtime($d));
1109 $$sql .= " AND ds <= $d" if defined($sql);
1110 } elsif ($k eq 'SENTSINCE') {
1111 $q->{xap} .= ' d:'.strftime('%Y%m%d', gmtime($d)).'..';
1112 $$sql .= " AND ds >= $d" if defined($sql);
1114 # INTERNALDATE (Received)
1115 } elsif ($k eq 'ON') {
1116 my $end = $d + 86399; # no leap day...
1117 $q->{xap} .= " ts:$d..$end";
1118 $$sql .= " AND ts >= $d AND ts <= $end" if defined($sql);
1119 } elsif ($k eq 'BEFORE') {
1120 $q->{xap} .= " ts:..$d";
1121 $$sql .= " AND ts <= $d" if defined($sql);
1122 } elsif ($k eq 'SINCE') {
1123 $q->{xap} .= " ts:$d..";
1124 $$sql .= " AND ts >= $d" if defined($sql);
1126 die "BUG: $k not recognized";
1130 # IMAP to Xapian search key mapping
1135 TEXT => '', # n.b. does not include all headers
1138 # BCC => 'bcc:', # TODO
1139 # KEYWORD # TODO ? dfpre,dfpost,...
1142 # IMAP allows searching arbitrary headers via "HEADER $HDR_NAME $HDR_VAL"
1143 # which gets silly expensive. We only allow the headers we already index.
1144 my %H2X = (%I2X, 'MESSAGE-ID' => 'm:', 'LIST-ID' => 'l:');
1146 sub xap_append ($$$$) {
1147 my ($q, $rest, $k, $xk) = @_;
1148 delete $q->{sql}; # can't use over.sqlite3
1149 defined(my $arg = shift @$rest) or return "BAD $k no arg";
1151 # AFAIK Xapian can't handle [*"] in probabilistic terms
1153 ${$q->{xap}} .= qq[ $xk"$arg"];
1157 sub parse_query ($$) {
1158 my ($self, $query) = @_;
1159 my $q = PublicInbox::IMAPsearchqp::parse($self, $query);
1161 my $max = $self->{ibx}->over->max;
1163 uid_clamp($self, \$beg, \$max);
1164 $q->{range_info} = [ $beg, $max ];
1169 sub refill_xap ($$$$) {
1170 my ($self, $uids, $range_info, $q) = @_;
1171 my ($beg, $end) = @$range_info;
1172 my $srch = $self->{ibx}->search;
1173 my $opt = { mset => 2, limit => 1000 };
1174 my $nshard = $srch->{nshard} // 1;
1175 my $mset = $srch->query("$q uid:$beg..$end", $opt);
1176 @$uids = map { mdocid($nshard, $_) } $mset->items;
1178 $range_info->[0] = $uids->[-1] + 1; # update $beg
1179 return; # possibly more
1184 sub search_xap_range { # long_response
1185 my ($self, $tag, $q, $range_info, $want_msn) = @_;
1187 if (defined(my $err = refill_xap($self, $uids, $range_info, $q))) {
1188 $err ||= 'OK Search done';
1189 $self->write("\r\n$tag $err\r\n");
1192 msn_convert($self, $uids) if $want_msn;
1193 $self->msg_more(join(' ', '', @$uids));
1198 my ($self, $tag, $query, $want_msn) = @_;
1199 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1200 my $q = parse_query($self, $query);
1201 return "$tag $q\r\n" if !ref($q);
1202 my ($sql, $range_info) = delete @$q{qw(sql range_info)};
1203 if (!scalar(keys %$q)) { # overview.sqlite3
1204 $self->msg_more('* SEARCH');
1205 long_response($self, \&search_uid_range,
1206 $tag, $sql, $range_info, $want_msn);
1207 } elsif ($q = $q->{xap}) {
1208 $self->{ibx}->search or
1209 return "$tag BAD search not available for mailbox\r\n";
1210 $self->msg_more('* SEARCH');
1211 long_response($self, \&search_xap_range,
1212 $tag, $q, $range_info, $want_msn);
1214 "$tag BAD Error\r\n";
1218 sub cmd_uid_search ($$$) {
1219 my ($self, $tag, $query) = @_;
1220 search_common($self, $tag, $query);
1223 sub cmd_search ($$$;) {
1224 my ($self, $tag, $query) = @_;
1225 search_common($self, $tag, $query, 1);
1228 sub args_ok ($$) { # duplicated from PublicInbox::NNTP
1229 my ($cb, $argc) = @_;
1230 my $tot = prototype $cb;
1231 my ($nreq, undef) = split(';', $tot);
1232 $nreq = ($nreq =~ tr/$//) - 1;
1233 $tot = ($tot =~ tr/$//) - 1;
1234 ($argc <= $tot && $argc >= $nreq);
1237 # returns 1 if we can continue, 0 if not due to buffered writes or disconnect
1238 sub process_line ($$) {
1239 my ($self, $l) = @_;
1241 # TODO: IMAP allows literals for big requests to upload messages
1242 # (which we don't support) but maybe some big search queries use it.
1243 # RFC 3501 9 (2) doesn't permit TAB or multiple SP
1244 my ($tag, $req, @args) = parse_line('[ \t]+', 0, $l);
1245 pop(@args) if (@args && !defined($args[-1]));
1246 if (@args && uc($req) eq 'UID') {
1247 $req .= "_".(shift @args);
1250 if (defined(my $idle_tag = $self->{-idle_tag})) {
1251 (uc($tag // '') eq 'DONE' && !defined($req)) ?
1252 idle_done($self, $tag) :
1253 "$idle_tag BAD expected DONE\r\n";
1254 } elsif (my $cmd = $self->can('cmd_'.lc($req // ''))) {
1255 if ($cmd == \&cmd_uid_search || $cmd == \&cmd_search) {
1256 # preserve user-supplied quotes for search
1257 (undef, @args) = split(/ search /i, $l, 2);
1259 $cmd->($self, $tag, @args);
1260 } else { # this is weird
1261 auth_challenge_ok($self) //
1263 ' BAD Error in IMAP command '.
1265 ": Unknown command\r\n";
1269 if ($err && $self->{sock}) {
1271 err($self, 'error from: %s (%s)', $l, $err);
1273 $res = "$tag BAD program fault - command not performed\r\n";
1275 return 0 unless defined $res;
1281 # wbuf is unset or empty, here; {long} may add to it
1282 my ($fd, $cb, $t0, @args) = @{$self->{long_cb}};
1283 my $more = eval { $cb->($self, @args) };
1284 if ($@ || !$self->{sock}) { # something bad happened...
1285 delete $self->{long_cb};
1286 my $elapsed = now() - $t0;
1289 "%s during long response[$fd] - %0.6f",
1292 out($self, " deferred[$fd] aborted - %0.6f", $elapsed);
1294 } elsif ($more) { # $self->{wbuf}:
1295 $self->update_idle_time;
1297 # control passed to $more may be a GitAsyncCat object
1298 requeue_once($self) if !ref($more);
1299 } else { # all done!
1300 delete $self->{long_cb};
1301 my $elapsed = now() - $t0;
1302 my $fd = fileno($self->{sock});
1303 out($self, " deferred[$fd] done - %0.6f", $elapsed);
1304 my $wbuf = $self->{wbuf}; # do NOT autovivify
1306 $self->requeue unless $wbuf && @$wbuf;
1311 my ($self, $fmt, @args) = @_;
1312 printf { $self->{imapd}->{err} } $fmt."\n", @args;
1316 my ($self, $fmt, @args) = @_;
1317 printf { $self->{imapd}->{out} } $fmt."\n", @args;
1320 sub long_response ($$;@) {
1321 my ($self, $cb, @args) = @_; # cb returns true if more, false if done
1323 my $sock = $self->{sock} or return;
1324 # make sure we disable reading during a long response,
1325 # clients should not be sending us stuff and making us do more
1326 # work while we are stream a response to them
1327 $self->{long_cb} = [ fileno($sock), $cb, now(), @args ];
1328 long_step($self); # kick off!
1332 # callback used by PublicInbox::DS for any (e)poll (in/out/hup/err)
1336 return unless $self->flush_write && $self->{sock} && !$self->{long_cb};
1338 $self->update_idle_time;
1339 # only read more requests if we've drained the write buffer,
1340 # otherwise we can be buffering infinitely w/o backpressure
1342 my $rbuf = $self->{rbuf} // \(my $x = '');
1343 my $line = index($$rbuf, "\n");
1345 if (length($$rbuf) >= LINE_MAX) {
1346 $self->write(\"\* BAD request too long\r\n");
1347 return $self->close;
1349 $self->do_read($rbuf, LINE_MAX, length($$rbuf)) or
1350 return uo2m_hibernate($self);
1351 $line = index($$rbuf, "\n");
1353 $line = substr($$rbuf, 0, $line + 1, '');
1354 $line =~ s/\r?\n\z//s;
1355 return $self->close if $line =~ /[[:cntrl:]]/s;
1357 my $fd = fileno($self->{sock});
1358 my $r = eval { process_line($self, $line) };
1359 my $pending = $self->{wbuf} ? ' pending' : '';
1360 out($self, "[$fd] %s - %0.6f$pending - $r", $line, now() - $t0);
1362 return $self->close if $r < 0;
1363 $self->rbuf_idle($rbuf);
1364 $self->update_idle_time;
1366 # maybe there's more pipelined data, or we'll have
1367 # to register it for socket-readiness notifications
1368 $self->requeue unless $pending;
1371 sub compressed { undef }
1373 sub zflush {} # overridden by IMAPdeflate
1376 sub cmd_compress ($$$) {
1377 my ($self, $tag, $alg) = @_;
1378 return "$tag BAD DEFLATE only\r\n" if uc($alg) ne "DEFLATE";
1379 return "$tag BAD COMPRESS active\r\n" if $self->compressed;
1381 # CRIME made TLS compression obsolete
1382 # return "$tag NO [COMPRESSIONACTIVE]\r\n" if $self->tls_compressed;
1384 PublicInbox::IMAPdeflate->enable($self, $tag);
1389 sub cmd_starttls ($$) {
1390 my ($self, $tag) = @_;
1391 my $sock = $self->{sock} or return;
1392 if ($sock->can('stop_SSL') || $self->compressed) {
1393 return "$tag BAD TLS or compression already enabled\r\n";
1395 my $opt = $self->{imapd}->{accept_tls} or
1396 return "$tag BAD can not initiate TLS negotiation\r\n";
1397 $self->write(\"$tag OK begin TLS negotiation now\r\n");
1398 $self->{sock} = IO::Socket::SSL->start_SSL($sock, %$opt);
1399 $self->requeue if PublicInbox::DS::accept_tls_step($self);
1403 # for graceful shutdown in PublicInbox::Daemon:
1405 my ($self, $now) = @_;
1406 if (defined($self->{-idle_tag})) {
1407 $self->write(\"* BYE server shutting down\r\n");
1408 return; # not busy anymore
1410 ($self->{rbuf} || $self->{wbuf} || $self->not_idle_long($now));
1415 if (my $ibx = delete $self->{ibx}) {
1416 stop_idle($self, $ibx);
1418 $self->SUPER::close; # PublicInbox::DS::close
1421 # we're read-only, so SELECT and EXAMINE do the same thing
1423 *cmd_select = \&cmd_examine;
1425 package PublicInbox::IMAP_preauth;
1426 our @ISA = qw(PublicInbox::IMAP);