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->{uid_base};
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 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;
419 # XXX: do we need this? RFC 5162/7162
420 my $ret = $self->{ibx} ? "* OK [CLOSED] previous closed\r\n" : '';
426 * OK [PERMANENTFLAGS ()] Read-only mailbox\r
427 * OK [UNSEEN $exists]\r
428 * OK [UIDNEXT $uidnext]\r
429 * OK [UIDVALIDITY $ibx->{uidvalidity}]\r
430 $tag OK [READ-ONLY] EXAMINE/SELECT done\r
438 } elsif ($v =~ /[{"\r\n%*\\\[]/) { # literal string
439 '{' . length($v) . "}\r\n" . $v;
440 } else { # quoted string
445 sub addr_envelope ($$;$) {
446 my ($eml, $x, $y) = @_;
447 my $v = $eml->header_raw($x) //
448 ($y ? $eml->header_raw($y) : undef) // return 'NIL';
450 my @x = $Address->parse($v) or return 'NIL';
452 map { '(' . join(' ',
453 _esc($_->name), 'NIL',
454 _esc($_->user), _esc($_->host)
460 sub eml_envelope ($) {
463 _esc($eml->header_raw('Date')),
464 _esc($eml->header_raw('Subject')),
465 addr_envelope($eml, 'From'),
466 addr_envelope($eml, 'Sender', 'From'),
467 addr_envelope($eml, 'Reply-To', 'From'),
468 addr_envelope($eml, 'To'),
469 addr_envelope($eml, 'Cc'),
470 addr_envelope($eml, 'Bcc'),
471 _esc($eml->header_raw('In-Reply-To')),
472 _esc($eml->header_raw('Message-ID')),
478 if ($hash && scalar keys %$hash) {
479 $hash = [ %$hash ]; # flatten hash into 1-dimensional array
480 '(' . join(' ', map { _esc($_) } @$hash) . ')';
486 sub body_disposition ($) {
488 my $cd = $eml->header_raw('Content-Disposition') or return 'NIL';
489 $cd = parse_content_disposition($cd);
490 my $buf = '('._esc($cd->{type});
491 $buf .= ' ' . _esc_hash(delete $cd->{attributes});
495 sub body_leaf ($$;$) {
496 my ($eml, $structure, $hold) = @_;
498 $eml->{is_submsg} and # parent was a message/(rfc822|news|global)
499 $buf .= eml_envelope($eml). ' ';
501 $buf .= '('._esc($ct->{type}).' ';
502 $buf .= _esc($ct->{subtype});
503 $buf .= ' ' . _esc_hash(delete $ct->{attributes});
504 $buf .= ' ' . _esc($eml->header_raw('Content-ID'));
505 $buf .= ' ' . _esc($eml->header_raw('Content-Description'));
506 my $cte = $eml->header_raw('Content-Transfer-Encoding') // '7bit';
507 $buf .= ' ' . _esc($cte);
508 $buf .= ' ' . $eml->{imap_body_len};
509 $buf .= ' '.($eml->body_raw =~ tr/\n/\n/) if lc($ct->{type}) eq 'text';
511 # for message/(rfc822|global|news), $hold[0] should have envelope
512 $buf .= ' ' . (@$hold ? join('', @$hold) : 'NIL') if $hold;
515 $buf .= ' '._esc($eml->header_raw('Content-MD5'));
516 $buf .= ' '. body_disposition($eml);
517 $buf .= ' '._esc($eml->header_raw('Content-Language'));
518 $buf .= ' '._esc($eml->header_raw('Content-Location'));
523 sub body_parent ($$$) {
524 my ($eml, $structure, $hold) = @_;
526 my $type = lc($ct->{type});
527 if ($type eq 'multipart') {
529 $buf .= @$hold ? join('', @$hold) : 'NIL';
530 $buf .= ' '._esc($ct->{subtype});
532 $buf .= ' '._esc_hash(delete $ct->{attributes});
533 $buf .= ' '.body_disposition($eml);
534 $buf .= ' '._esc($eml->header_raw('Content-Language'));
535 $buf .= ' '._esc($eml->header_raw('Content-Location'));
539 } else { # message/(rfc822|global|news)
540 @$hold = (body_leaf($eml, $structure, $hold));
544 # this is gross, but we need to process the parent part AFTER
545 # the child parts are done
546 sub bodystructure_prep {
548 my ($eml, $depth) = @$p; # ignore idx
549 # set length here, as $eml->{bdy} gets deleted for message/rfc822
550 $eml->{imap_body_len} = length($eml->body_raw);
551 push @$q, $eml, $depth;
554 # for FETCH BODY and FETCH BODYSTRUCTURE
555 sub fetch_body ($;$) {
556 my ($eml, $structure) = @_;
558 $eml->each_part(\&bodystructure_prep, \@q, 0, 1);
562 my ($part, $depth) = splice(@q, -2);
563 my $is_mp_parent = $depth == ($cur_depth - 1);
567 body_parent($part, $structure, \@hold);
569 unshift @hold, body_leaf($part, $structure);
575 sub requeue_once ($) {
577 # COMPRESS users all share the same DEFLATE context.
578 # Flush it here to ensure clients don't see
582 # no recursion, schedule another call ASAP,
583 # but only after all pending writes are done.
585 my $new_size = push(@{$self->{wbuf}}, \&long_step);
587 # wbuf may be populated by $cb, no need to rearm if so:
588 $self->requeue if $new_size == 1;
592 my ($self, $smsg, $bref, $ops, $partial) = @_;
593 my $uid = $smsg->{num};
594 $self->msg_more('* '.uid2msn($self, $uid)." FETCH (UID $uid");
596 for (my $i = 0; $i < @$ops;) {
598 $ops->[$i++]->($self, $k, $smsg, $bref, $eml);
600 partial_emit($self, $partial, $eml) if $partial;
601 $self->msg_more(")\r\n");
604 sub fetch_blob_cb { # called by git->cat_async via git_async_cat
605 my ($bref, $oid, $type, $size, $fetch_arg) = @_;
606 my ($self, undef, $msgs, $range_info, $ops, $partial) = @$fetch_arg;
607 my $smsg = shift @$msgs or die 'BUG: no smsg';
608 if (!defined($oid)) {
609 # it's possible to have TOCTOU if an admin runs
610 # public-inbox-(edit|purge), just move onto the next message
611 return requeue_once($self);
613 $smsg->{blob} eq $oid or die "BUG: $smsg->{blob} != $oid";
615 fetch_run_ops($self, $smsg, $bref, $ops, $partial);
620 my ($self, $k, undef, $bref) = @_;
621 $self->msg_more(" $k {" . length($$bref)."}\r\n");
622 $self->msg_more($$bref);
625 # Mail::IMAPClient::message_string cares about this by default,
626 # (->Ignoresizeerrors attribute). Admins are encouraged to
627 # --reindex for IMAP support, anyways.
628 sub emit_rfc822_size {
629 my ($self, $k, $smsg) = @_;
630 $self->msg_more(' RFC822.SIZE ' . $smsg->{bytes});
633 sub emit_internaldate {
634 my ($self, undef, $smsg) = @_;
635 $self->msg_more(' INTERNALDATE "'.$smsg->internaldate.'"');
638 sub emit_flags { $_[0]->msg_more(' FLAGS ()') }
641 my ($self, undef, undef, undef, $eml) = @_;
642 $self->msg_more(' ENVELOPE '.eml_envelope($eml));
645 sub emit_rfc822_header {
646 my ($self, $k, undef, undef, $eml) = @_;
647 $self->msg_more(" $k {".length(${$eml->{hdr}})."}\r\n");
648 $self->msg_more(${$eml->{hdr}});
651 # n.b. this is sorted to be after any emit_eml_new ops
652 sub emit_rfc822_text {
653 my ($self, $k, undef, $bref) = @_;
654 $self->msg_more(" $k {".length($$bref)."}\r\n");
655 $self->msg_more($$bref);
658 sub emit_bodystructure {
659 my ($self, undef, undef, undef, $eml) = @_;
660 $self->msg_more(' BODYSTRUCTURE '.fetch_body($eml, 1));
664 my ($self, undef, undef, undef, $eml) = @_;
665 $self->msg_more(' BODY '.fetch_body($eml));
668 # set $eml once ($_[4] == $eml, $_[3] == $bref)
669 sub op_eml_new { $_[4] = PublicInbox::Eml->new($_[3]) }
671 # s/From / fixes old bug from import (pre-a0c07cba0e5d8b6a)
673 ${$_[0]} =~ s/(?<!\r)\n/\r\n/sg;
674 ${$_[0]} =~ s/\A[\r\n]*From [^\r\n]*\r\n//s;
677 sub op_crlf_bref { to_crlf_full($_[3]) }
679 sub op_crlf_hdr { to_crlf_full($_[4]->{hdr}) }
681 sub op_crlf_bdy { ${$_[4]->{bdy}} =~ s/(?<!\r)\n/\r\n/sg if $_[4]->{bdy} }
683 sub uid_clamp ($$$) {
684 my ($self, $beg, $end) = @_;
685 my $uid_min = $self->{uid_base} + 1;
686 my $uid_end = $uid_min + UID_SLICE - 1;
687 $$beg = $uid_min if $$beg < $uid_min;
688 $$end = $uid_end if $$end > $uid_end;
691 sub range_step ($$) {
692 my ($self, $range_csv) = @_;
693 my ($beg, $end, $range);
694 if ($$range_csv =~ s/\A([^,]+),//) {
697 $range = $$range_csv;
700 my $uid_base = $self->{uid_base};
701 my $uid_end = $uid_base + UID_SLICE;
702 if ($range =~ /\A([0-9]+):([0-9]+)\z/) {
703 ($beg, $end) = ($1 + 0, $2 + 0);
704 uid_clamp($self, \$beg, \$end);
705 } elsif ($range =~ /\A([0-9]+):\*\z/) {
707 $end = $self->{ibx}->over->max;
708 $end = $uid_end if $end > $uid_end;
709 $beg = $end if $beg > $end;
710 uid_clamp($self, \$beg, \$end);
711 } elsif ($range =~ /\A[0-9]+\z/) {
712 $beg = $end = $range + 0;
713 # just let the caller do an out-of-range query if a single
714 # UID is out-of-range
715 ++$beg if ($beg <= $uid_base || $end > $uid_end);
717 return 'BAD fetch range';
719 [ $beg, $end, $$range_csv ];
722 sub refill_range ($$$) {
723 my ($self, $msgs, $range_info) = @_;
724 my ($beg, $end, $range_csv) = @$range_info;
725 if (scalar(@$msgs = @{$self->{ibx}->over->query_xover($beg, $end)})) {
726 $range_info->[0] = $msgs->[-1]->{num} + 1;
729 return 'OK Fetch done' if !$range_csv;
730 my $next_range = range_step($self, \$range_csv);
731 return $next_range if !ref($next_range); # error
732 @$range_info = @$next_range;
733 undef; # keep looping
736 sub fetch_blob { # long_response
737 my ($self, $tag, $msgs, $range_info, $ops, $partial) = @_;
738 while (!@$msgs) { # rare
739 if (my $end = refill_range($self, $msgs, $range_info)) {
740 $self->write(\"$tag $end\r\n");
744 uo2m_extend($self, $msgs->[-1]->{num});
745 git_async_cat($self->{ibx}->git, $msgs->[0]->{blob},
746 \&fetch_blob_cb, \@_);
749 sub fetch_smsg { # long_response
750 my ($self, $tag, $msgs, $range_info, $ops) = @_;
751 while (!@$msgs) { # rare
752 if (my $end = refill_range($self, $msgs, $range_info)) {
753 $self->write(\"$tag $end\r\n");
757 uo2m_extend($self, $msgs->[-1]->{num});
758 fetch_run_ops($self, $_, undef, $ops) for @$msgs;
763 sub refill_uids ($$$;$) {
764 my ($self, $uids, $range_info, $sql) = @_;
765 my ($beg, $end, $range_csv) = @$range_info;
766 my $over = $self->{ibx}->over;
768 if (scalar(@$uids = @{$over->uid_range($beg, $end, $sql)})) {
769 $range_info->[0] = $uids->[-1] + 1; # update $beg
771 } elsif (!$range_csv) {
774 my $next_range = range_step($self, \$range_csv);
775 return $next_range if !ref($next_range); # error
776 ($beg, $end, $range_csv) = @$range_info = @$next_range;
782 sub fetch_uid { # long_response
783 my ($self, $tag, $uids, $range_info, $ops) = @_;
784 if (defined(my $err = refill_uids($self, $uids, $range_info))) {
785 $err ||= 'OK Fetch done';
786 $self->write("$tag $err\r\n");
789 my $adj = $self->{uid_base} + 1;
790 my $uo2m = uo2m_extend($self, $uids->[-1]);
791 $uo2m = [ unpack('S*', $uo2m) ] if !ref($uo2m);
794 $self->msg_more("* $uo2m->[$_ - $adj] FETCH (UID $_");
795 for ($i = 0; $i < @$ops;) {
797 $ops->[$i++]->($self, $k);
799 $self->msg_more(")\r\n");
805 sub cmd_status ($$$;@) {
806 my ($self, $tag, $mailbox, @items) = @_;
807 return "$tag BAD no items\r\n" if !scalar(@items);
808 ($items[0] !~ s/\A\(//s || $items[-1] !~ s/\)\z//s) and
809 return "$tag BAD invalid args\r\n";
810 my ($ibx, $exists, $uidnext) = inbox_lookup($self, $mailbox);
811 return "$tag NO Mailbox doesn't exist: $mailbox\r\n" if !$ibx;
813 for my $it (@items) {
816 if ($it =~ /\A(?:MESSAGES|UNSEEN|RECENT)\z/) {
818 } elsif ($it eq 'UIDNEXT') {
820 } elsif ($it eq 'UIDVALIDITY') {
821 push @it, $ibx->{uidvalidity};
823 return "$tag BAD invalid item\r\n";
826 return "$tag BAD no items\r\n" if !@it;
827 "* STATUS $mailbox (".join(' ', @it).")\r\n" .
828 "$tag OK Status done\r\n";
831 my %patmap = ('*' => '.*', '%' => '[^\.]*');
832 sub cmd_list ($$$$) {
833 my ($self, $tag, $refname, $wildcard) = @_;
834 my $l = $self->{imapd}->{inboxlist};
835 if ($refname eq '' && $wildcard eq '') {
836 # request for hierarchy delimiter
837 $l = [ qq[* LIST (\\Noselect) "." ""\r\n] ];
838 } elsif ($refname ne '' || $wildcard ne '*') {
839 $wildcard =~ s!([^a-z0-9_])!$patmap{$1} // "\Q$1"!egi;
840 $l = [ grep(/ \Q$refname\E$wildcard\r\n\z/is, @$l) ];
842 \(join('', @$l, "$tag OK List done\r\n"));
845 sub cmd_lsub ($$$$) {
846 my (undef, $tag) = @_; # same args as cmd_list
847 "$tag OK Lsub done\r\n";
850 sub eml_index_offs_i { # PublicInbox::Eml::each_part callback
852 my ($eml, undef, $idx) = @$p;
853 if ($idx && lc($eml->ct->{type}) eq 'multipart') {
854 $eml->{imap_bdy} = $eml->{bdy} // \'';
856 $all->{$idx} = $eml; # $idx => Eml
859 # prepares an index for BODY[$SECTION_IDX] fetches
860 sub eml_body_idx ($$) {
861 my ($eml, $section_idx) = @_;
862 my $idx = $eml->{imap_all_parts} //= do {
864 $eml->each_part(\&eml_index_offs_i, $all, 0, 1);
865 # top-level of multipart, BODY[0] not allowed (nz-number)
869 $idx->{$section_idx};
872 # BODY[($SECTION_IDX)?(.$SECTION_NAME)?]<$offset.$bytes>
874 my ($eml, $section_idx, $section_name) = @_;
875 if (defined $section_idx) {
876 $eml = eml_body_idx($eml, $section_idx) or return;
878 if (defined $section_name) {
879 if ($section_name eq 'MIME') {
880 # RFC 3501 6.4.5 states:
881 # The MIME part specifier MUST be prefixed
882 # by one or more numeric part specifiers
883 return unless defined $section_idx;
884 return $eml->header_obj->as_string . "\r\n";
886 my $bdy = $eml->{bdy} // $eml->{imap_bdy} // \'';
887 $eml = PublicInbox::Eml->new($$bdy);
888 if ($section_name eq 'TEXT') {
889 return $eml->body_raw;
890 } elsif ($section_name eq 'HEADER') {
891 return $eml->header_obj->as_string . "\r\n";
893 die "BUG: bad section_name=$section_name";
896 ${$eml->{bdy} // $eml->{imap_bdy} // \''};
899 # similar to what's in PublicInbox::Eml::re_memo, but doesn't memoize
900 # to avoid OOM with malicious users
901 sub hdrs_regexp ($) {
903 my $names = join('|', map { "\Q$_" } split(/[ \t]+/, $hdrs));
904 qr/^(?:$names):[ \t]*[^\n]*\r?\n # 1st line
905 # continuation lines:
906 (?:[^:\n]*?[ \t]+[^\n]*\r?\n)*
910 # BODY[($SECTION_IDX.)?HEADER.FIELDS.NOT ($HDRS)]<$offset.$bytes>
911 sub partial_hdr_not {
912 my ($eml, $section_idx, $hdrs_re) = @_;
913 if (defined $section_idx) {
914 $eml = eml_body_idx($eml, $section_idx) or return;
916 my $str = $eml->header_obj->as_string;
917 $str =~ s/$hdrs_re//g;
918 $str =~ s/(?<!\r)\n/\r\n/sg;
922 # BODY[($SECTION_IDX.)?HEADER.FIELDS ($HDRS)]<$offset.$bytes>
923 sub partial_hdr_get {
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 = join('', ($str =~ m/($hdrs_re)/g));
930 $str =~ s/(?<!\r)\n/\r\n/sg;
934 sub partial_prepare ($$$$) {
935 my ($need, $partial, $want, $att) = @_;
937 # recombine [ "BODY[1.HEADER.FIELDS", "(foo", "bar)]" ]
938 # back to: "BODY[1.HEADER.FIELDS (foo bar)]"
939 return unless $att =~ /\ABODY\[/s;
940 until (rindex($att, ']') >= 0) {
941 my $next = shift @$want or return;
942 $att .= ' ' . uc($next);
944 if ($att =~ /\ABODY\[([0-9]+(?:\.[0-9]+)*)? # 1 - section_idx
945 (?:\.(HEADER|MIME|TEXT))? # 2 - section_name
946 \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 3, 4
947 $partial->{$att} = [ \&partial_body, $1, $2, $3, $4 ];
948 $$need |= CRLF_BREF|EML_HDR|EML_BDY;
949 } elsif ($att =~ /\ABODY\[(?:([0-9]+(?:\.[0-9]+)*)\.)? # 1 - section_idx
950 (?:HEADER\.FIELDS(\.NOT)?)\x20 # 2
951 \(([A-Z0-9\-\x20]+)\) # 3 - hdrs
952 \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 4 5
953 my $tmp = $partial->{$att} = [ $2 ? \&partial_hdr_not
956 $tmp->[2] = hdrs_regexp($3);
958 # don't emit CRLF_HDR instruction, here, partial_hdr_*
959 # will do CRLF conversion with only the extracted result
960 # and not waste time converting lines we don't care about.
967 sub partial_emit ($$$) {
968 my ($self, $partial, $eml) = @_;
970 my ($k, $cb, @args) = @$_;
971 my ($offset, $len) = splice(@args, -2);
972 # $cb is partial_body|partial_hdr_get|partial_hdr_not
973 my $str = $cb->($eml, @args) // '';
974 if (defined $offset) {
976 $str = substr($str, $offset, $len);
977 $k =~ s/\.$len>\z/>/ or warn
978 "BUG: unable to remove `.$len>' from `$k'";
980 $str = substr($str, $offset);
986 $self->msg_more(" $k {$len}\r\n");
987 $self->msg_more($str);
991 sub fetch_compile ($) {
993 if ($want->[0] =~ s/\A\(//s) {
994 $want->[-1] =~ s/\)\z//s or return 'BAD no rparen';
996 my (%partial, %seen, @op);
998 while (defined(my $att = shift @$want)) {
1000 next if $att eq 'UID'; # always returned
1001 $att =~ s/\ABODY\.PEEK\[/BODY\[/; # we're read-only
1002 my $x = $FETCH_ATT{$att};
1004 while (my ($k, $fl_cb) = each %$x) {
1005 next if $seen{$k}++;
1006 $need |= $fl_cb->[0];
1007 push @op, [ @$fl_cb, $k ];
1009 } elsif (!partial_prepare(\$need, \%partial, $want, $att)) {
1010 return "BAD param: $att";
1015 # stabilize partial order for consistency and ease-of-debugging:
1016 if (scalar keys %partial) {
1018 $r[2] = [ map { [ $_, @{$partial{$_}} ] } sort keys %partial ];
1021 push @op, $OP_EML_NEW if ($need & (EML_HDR|EML_BDY));
1023 # do we need CRLF conversion?
1024 if ($need & CRLF_BREF) {
1025 push @op, $OP_CRLF_BREF;
1026 } elsif (my $crlf = ($need & (CRLF_HDR|CRLF_BDY))) {
1027 if ($crlf == (CRLF_HDR|CRLF_BDY)) {
1028 push @op, $OP_CRLF_BREF;
1029 } elsif ($need & CRLF_HDR) {
1030 push @op, $OP_CRLF_HDR;
1032 push @op, $OP_CRLF_BDY;
1036 $r[0] = $need & NEED_BLOB ? \&fetch_blob :
1037 ($need & NEED_SMSG ? \&fetch_smsg : \&fetch_uid);
1039 # r[1] = [ $key1, $cb1, $key2, $cb2, ... ]
1040 use sort 'stable'; # makes output more consistent
1041 $r[1] = [ map { ($_->[2], $_->[1]) } sort { $a->[0] <=> $b->[0] } @op ];
1045 sub cmd_uid_fetch ($$$$;@) {
1046 my ($self, $tag, $range_csv, @want) = @_;
1047 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1048 my ($cb, $ops, $partial) = fetch_compile(\@want);
1049 return "$tag $cb\r\n" unless $ops;
1051 # cb is one of fetch_blob, fetch_smsg, fetch_uid
1052 $range_csv = 'bad' if $range_csv !~ $valid_range;
1053 my $range_info = range_step($self, \$range_csv);
1054 return "$tag $range_info\r\n" if !ref($range_info);
1055 uo2m_hibernate($self) if $cb == \&fetch_blob; # slow, save RAM
1056 long_response($self, $cb, $tag, [], $range_info, $ops, $partial);
1059 sub cmd_fetch ($$$$;@) {
1060 my ($self, $tag, $range_csv, @want) = @_;
1061 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1062 my ($cb, $ops, $partial) = fetch_compile(\@want);
1063 return "$tag $cb\r\n" unless $ops;
1065 # cb is one of fetch_blob, fetch_smsg, fetch_uid
1066 $range_csv = 'bad' if $range_csv !~ $valid_range;
1067 msn_to_uid_range(msn2uid($self), $range_csv);
1068 my $range_info = range_step($self, \$range_csv);
1069 return "$tag $range_info\r\n" if !ref($range_info);
1070 uo2m_hibernate($self) if $cb == \&fetch_blob; # slow, save RAM
1071 long_response($self, $cb, $tag, [], $range_info, $ops, $partial);
1074 sub msn_convert ($$) {
1075 my ($self, $uids) = @_;
1076 my $adj = $self->{uid_base} + 1;
1077 my $uo2m = uo2m_extend($self, $uids->[-1]);
1078 $uo2m = [ unpack('S*', $uo2m) ] if !ref($uo2m);
1079 $_ = $uo2m->[$_ - $adj] for @$uids;
1082 sub search_uid_range { # long_response
1083 my ($self, $tag, $sql, $range_info, $want_msn) = @_;
1085 if (defined(my $err = refill_uids($self, $uids, $range_info, $sql))) {
1086 $err ||= 'OK Search done';
1087 $self->write("\r\n$tag $err\r\n");
1090 msn_convert($self, $uids) if $want_msn;
1091 $self->msg_more(join(' ', '', @$uids));
1096 my ($q, $k, $d) = @_;
1097 my $sql = $q->{sql};
1100 if ($k eq 'SENTON') {
1101 my $end = $d + 86399; # no leap day...
1102 my $da = strftime('%Y%m%d%H%M%S', gmtime($d));
1103 my $db = strftime('%Y%m%d%H%M%S', gmtime($end));
1104 $q->{xap} .= " dt:$da..$db";
1105 $$sql .= " AND ds >= $d AND ds <= $end" if defined($sql);
1106 } elsif ($k eq 'SENTBEFORE') {
1107 $q->{xap} .= ' d:..'.strftime('%Y%m%d', gmtime($d));
1108 $$sql .= " AND ds <= $d" if defined($sql);
1109 } elsif ($k eq 'SENTSINCE') {
1110 $q->{xap} .= ' d:'.strftime('%Y%m%d', gmtime($d)).'..';
1111 $$sql .= " AND ds >= $d" if defined($sql);
1113 # INTERNALDATE (Received)
1114 } elsif ($k eq 'ON') {
1115 my $end = $d + 86399; # no leap day...
1116 $q->{xap} .= " ts:$d..$end";
1117 $$sql .= " AND ts >= $d AND ts <= $end" if defined($sql);
1118 } elsif ($k eq 'BEFORE') {
1119 $q->{xap} .= " ts:..$d";
1120 $$sql .= " AND ts <= $d" if defined($sql);
1121 } elsif ($k eq 'SINCE') {
1122 $q->{xap} .= " ts:$d..";
1123 $$sql .= " AND ts >= $d" if defined($sql);
1125 die "BUG: $k not recognized";
1129 # IMAP to Xapian search key mapping
1134 TEXT => '', # n.b. does not include all headers
1137 # BCC => 'bcc:', # TODO
1138 # KEYWORD # TODO ? dfpre,dfpost,...
1141 # IMAP allows searching arbitrary headers via "HEADER $HDR_NAME $HDR_VAL"
1142 # which gets silly expensive. We only allow the headers we already index.
1143 my %H2X = (%I2X, 'MESSAGE-ID' => 'm:', 'LIST-ID' => 'l:');
1145 sub xap_append ($$$$) {
1146 my ($q, $rest, $k, $xk) = @_;
1147 delete $q->{sql}; # can't use over.sqlite3
1148 defined(my $arg = shift @$rest) or return "BAD $k no arg";
1150 # AFAIK Xapian can't handle [*"] in probabilistic terms
1152 ${$q->{xap}} .= qq[ $xk"$arg"];
1156 sub parse_query ($$) {
1157 my ($self, $rest) = @_;
1158 if (uc($rest->[0]) eq 'CHARSET') {
1160 defined(my $c = shift @$rest) or return 'BAD missing charset';
1161 $c =~ /\A(?:UTF-8|US-ASCII)\z/ or return 'NO [BADCHARSET]';
1163 my $q = PublicInbox::IMAPsearchqp::parse($self, join(' ', @$rest));
1165 my $max = $self->{ibx}->over->max;
1167 uid_clamp($self, \$beg, \$max);
1168 $q->{range_info} = [ $beg, $max ];
1173 sub refill_xap ($$$$) {
1174 my ($self, $uids, $range_info, $q) = @_;
1175 my ($beg, $end) = @$range_info;
1176 my $srch = $self->{ibx}->search;
1177 my $opt = { mset => 2, limit => 1000 };
1178 my $nshard = $srch->{nshard} // 1;
1180 my $mset = $srch->query("$q uid:$beg..$end", $opt);
1181 @$uids = map { mdocid($nshard, $_) } $mset->items;
1183 $range_info->[0] = $uids->[-1] + 1; # update $beg
1191 sub search_xap_range { # long_response
1192 my ($self, $tag, $q, $range_info, $want_msn) = @_;
1194 if (defined(my $err = refill_xap($self, $uids, $range_info, $q))) {
1195 $err ||= 'OK Search done';
1196 $self->write("\r\n$tag $err\r\n");
1199 msn_convert($self, $uids) if $want_msn;
1200 $self->msg_more(join(' ', '', @$uids));
1205 my ($self, $tag, $rest, $want_msn) = @_;
1206 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1207 my $q = parse_query($self, $rest);
1208 return "$tag $q\r\n" if !ref($q);
1209 my ($sql, $range_info) = delete @$q{qw(sql range_info)};
1210 if (!scalar(keys %$q)) { # overview.sqlite3
1211 $self->msg_more('* SEARCH');
1212 long_response($self, \&search_uid_range,
1213 $tag, $sql, $range_info, $want_msn);
1214 } elsif ($q = $q->{xap}) {
1215 $self->{ibx}->search or
1216 return "$tag BAD search not available for mailbox\r\n";
1217 $self->msg_more('* SEARCH');
1218 long_response($self, \&search_xap_range,
1219 $tag, $q, $range_info, $want_msn);
1221 "$tag BAD Error\r\n";
1225 sub cmd_uid_search ($$$;) {
1226 my ($self, $tag) = splice(@_, 0, 2);
1227 search_common($self, $tag, \@_);
1230 sub cmd_search ($$$;) {
1231 my ($self, $tag) = splice(@_, 0, 2);
1232 search_common($self, $tag, \@_, 1);
1235 sub args_ok ($$) { # duplicated from PublicInbox::NNTP
1236 my ($cb, $argc) = @_;
1237 my $tot = prototype $cb;
1238 my ($nreq, undef) = split(';', $tot);
1239 $nreq = ($nreq =~ tr/$//) - 1;
1240 $tot = ($tot =~ tr/$//) - 1;
1241 ($argc <= $tot && $argc >= $nreq);
1244 # returns 1 if we can continue, 0 if not due to buffered writes or disconnect
1245 sub process_line ($$) {
1246 my ($self, $l) = @_;
1248 # TODO: IMAP allows literals for big requests to upload messages
1249 # (which we don't support) but maybe some big search queries use it.
1250 # RFC 3501 9 (2) doesn't permit TAB or multiple SP
1251 my ($tag, $req, @args) = parse_line('[ \t]+', 0, $l);
1252 pop(@args) if (@args && !defined($args[-1]));
1253 if (@args && uc($req) eq 'UID') {
1254 $req .= "_".(shift @args);
1257 if (defined(my $idle_tag = $self->{-idle_tag})) {
1258 (uc($tag // '') eq 'DONE' && !defined($req)) ?
1259 idle_done($self, $tag) :
1260 "$idle_tag BAD expected DONE\r\n";
1261 } elsif (my $cmd = $self->can('cmd_'.lc($req // ''))) {
1262 if ($cmd == \&cmd_uid_search || $cmd == \&cmd_search) {
1263 # preserve user-supplied quotes for search
1264 (undef, @args) = split(/ search /i, $l, 2);
1266 $cmd->($self, $tag, @args);
1267 } else { # this is weird
1268 auth_challenge_ok($self) //
1270 ' BAD Error in IMAP command '.
1272 ": Unknown command\r\n";
1276 if ($err && $self->{sock}) {
1278 err($self, 'error from: %s (%s)', $l, $err);
1280 $res = "$tag BAD program fault - command not performed\r\n";
1282 return 0 unless defined $res;
1288 # wbuf is unset or empty, here; {long} may add to it
1289 my ($fd, $cb, $t0, @args) = @{$self->{long_cb}};
1290 my $more = eval { $cb->($self, @args) };
1291 if ($@ || !$self->{sock}) { # something bad happened...
1292 delete $self->{long_cb};
1293 my $elapsed = now() - $t0;
1296 "%s during long response[$fd] - %0.6f",
1299 out($self, " deferred[$fd] aborted - %0.6f", $elapsed);
1301 } elsif ($more) { # $self->{wbuf}:
1302 $self->update_idle_time;
1304 # control passed to $more may be a GitAsyncCat object
1305 requeue_once($self) if !ref($more);
1306 } else { # all done!
1307 delete $self->{long_cb};
1308 my $elapsed = now() - $t0;
1309 my $fd = fileno($self->{sock});
1310 out($self, " deferred[$fd] done - %0.6f", $elapsed);
1311 my $wbuf = $self->{wbuf}; # do NOT autovivify
1313 $self->requeue unless $wbuf && @$wbuf;
1318 my ($self, $fmt, @args) = @_;
1319 printf { $self->{imapd}->{err} } $fmt."\n", @args;
1323 my ($self, $fmt, @args) = @_;
1324 printf { $self->{imapd}->{out} } $fmt."\n", @args;
1327 sub long_response ($$;@) {
1328 my ($self, $cb, @args) = @_; # cb returns true if more, false if done
1330 my $sock = $self->{sock} or return;
1331 # make sure we disable reading during a long response,
1332 # clients should not be sending us stuff and making us do more
1333 # work while we are stream a response to them
1334 $self->{long_cb} = [ fileno($sock), $cb, now(), @args ];
1335 long_step($self); # kick off!
1339 # callback used by PublicInbox::DS for any (e)poll (in/out/hup/err)
1343 return unless $self->flush_write && $self->{sock} && !$self->{long_cb};
1345 $self->update_idle_time;
1346 # only read more requests if we've drained the write buffer,
1347 # otherwise we can be buffering infinitely w/o backpressure
1349 my $rbuf = $self->{rbuf} // \(my $x = '');
1350 my $line = index($$rbuf, "\n");
1352 if (length($$rbuf) >= LINE_MAX) {
1353 $self->write(\"\* BAD request too long\r\n");
1354 return $self->close;
1356 $self->do_read($rbuf, LINE_MAX, length($$rbuf)) or
1357 return uo2m_hibernate($self);
1358 $line = index($$rbuf, "\n");
1360 $line = substr($$rbuf, 0, $line + 1, '');
1361 $line =~ s/\r?\n\z//s;
1362 return $self->close if $line =~ /[[:cntrl:]]/s;
1364 my $fd = fileno($self->{sock});
1365 my $r = eval { process_line($self, $line) };
1366 my $pending = $self->{wbuf} ? ' pending' : '';
1367 out($self, "[$fd] %s - %0.6f$pending - $r", $line, now() - $t0);
1369 return $self->close if $r < 0;
1370 $self->rbuf_idle($rbuf);
1371 $self->update_idle_time;
1373 # maybe there's more pipelined data, or we'll have
1374 # to register it for socket-readiness notifications
1375 $self->requeue unless $pending;
1378 sub compressed { undef }
1380 sub zflush {} # overridden by IMAPdeflate
1383 sub cmd_compress ($$$) {
1384 my ($self, $tag, $alg) = @_;
1385 return "$tag BAD DEFLATE only\r\n" if uc($alg) ne "DEFLATE";
1386 return "$tag BAD COMPRESS active\r\n" if $self->compressed;
1388 # CRIME made TLS compression obsolete
1389 # return "$tag NO [COMPRESSIONACTIVE]\r\n" if $self->tls_compressed;
1391 PublicInbox::IMAPdeflate->enable($self, $tag);
1396 sub cmd_starttls ($$) {
1397 my ($self, $tag) = @_;
1398 my $sock = $self->{sock} or return;
1399 if ($sock->can('stop_SSL') || $self->compressed) {
1400 return "$tag BAD TLS or compression already enabled\r\n";
1402 my $opt = $self->{imapd}->{accept_tls} or
1403 return "$tag BAD can not initiate TLS negotiation\r\n";
1404 $self->write(\"$tag OK begin TLS negotiation now\r\n");
1405 $self->{sock} = IO::Socket::SSL->start_SSL($sock, %$opt);
1406 $self->requeue if PublicInbox::DS::accept_tls_step($self);
1410 # for graceful shutdown in PublicInbox::Daemon:
1412 my ($self, $now) = @_;
1413 if (defined($self->{-idle_tag})) {
1414 $self->write(\"* BYE server shutting down\r\n");
1415 return; # not busy anymore
1417 ($self->{rbuf} || $self->{wbuf} || $self->not_idle_long($now));
1422 if (my $ibx = delete $self->{ibx}) {
1423 stop_idle($self, $ibx);
1425 $self->SUPER::close; # PublicInbox::DS::close
1428 # we're read-only, so SELECT and EXAMINE do the same thing
1430 *cmd_select = \&cmd_examine;
1432 package PublicInbox::IMAP_preauth;
1433 our @ISA = qw(PublicInbox::IMAP);