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 # uo2m: UID Offset to MSN, this is an arrayref by default,
194 # but uo2m_hibernate can compact and deduplicate it
195 sub uo2m_ary_new ($;$) {
196 my ($self, $exists) = @_;
197 my $base = $self->{uid_base};
198 my $uids = $self->{ibx}->over->uid_range($base + 1, $base + UID_SLICE);
200 # convert UIDs to offsets from {base}
201 my @tmp; # [$UID_OFFSET] => $MSN
204 $tmp[$_ - $base] = ++$msn for @$uids;
205 $$exists = $msn if $exists;
209 # changes UID-offset-to-MSN mapping into a deduplicated scalar:
210 # uint16_t uo2m[UID_SLICE].
211 # May be swapped out for idle clients if THP is disabled.
212 sub uo2m_hibernate ($) {
214 ref(my $uo2m = $self->{uo2m}) or return;
215 my %dedupe = ( uo2m_pack($uo2m) => undef );
216 $self->{uo2m} = (keys(%dedupe))[0];
220 sub uo2m_last_uid ($) {
222 defined(my $uo2m = $self->{uo2m}) or die 'BUG: uo2m_last_uid w/o {uo2m}';
223 (ref($uo2m) ? @$uo2m : (length($uo2m) >> 1)) + $self->{uid_base};
227 # $_[0] is an arrayref of MSNs, it may have undef gaps if there
228 # are gaps in the corresponding UIDs: [ msn1, msn2, undef, msn3 ]
229 no warnings 'uninitialized';
230 pack('S*', @{$_[0]});
233 # extend {uo2m} to account for new messages which arrived since
234 # {uo2m} was created.
235 sub uo2m_extend ($$;$) {
236 my ($self, $new_uid_max) = @_;
237 defined(my $uo2m = $self->{uo2m}) or
238 return($self->{uo2m} = uo2m_ary_new($self));
239 my $beg = uo2m_last_uid($self); # last UID we've learned
240 return $uo2m if $beg >= $new_uid_max; # fast path
242 # need to extend the current range:
243 my $base = $self->{uid_base};
245 my $uids = $self->{ibx}->over->uid_range($beg, $base + UID_SLICE);
246 my @tmp; # [$UID_OFFSET] => $MSN
247 my $write_method = $_[2] // 'msg_more';
249 my $msn = $uo2m->[-1];
250 $tmp[$_ - $beg] = ++$msn for @$uids;
251 $self->$write_method("* $msn EXISTS\r\n");
255 my $msn = unpack('S', substr($uo2m, -2, 2));
256 $tmp[$_ - $beg] = ++$msn for @$uids;
257 $self->$write_method("* $msn EXISTS\r\n");
258 $uo2m .= uo2m_pack(\@tmp);
259 my %dedupe = ($uo2m => undef);
260 $self->{uo2m} = (keys %dedupe)[0];
265 my ($self, $tag) = @_;
266 defined($self->{uid_base}) and
267 uo2m_extend($self, $self->{uid_base} + UID_SLICE);
268 \"$tag OK Noop done\r\n";
271 # the flexible version which works on scalars and array refs.
272 # Must call uo2m_extend before this
274 my ($self, $uid) = @_;
275 my $uo2m = $self->{uo2m};
276 my $off = $uid - $self->{uid_base} - 1;
277 ref($uo2m) ? $uo2m->[$off] : unpack('S', substr($uo2m, $off << 1, 2));
280 # returns an arrayref of UIDs, so MSNs can be translated to UIDs via:
281 # $msn2uid->[$MSN-1] => $UID. The result of this is always ephemeral
282 # and does not live beyond the event loop.
285 my $base = $self->{uid_base};
286 my $uo2m = uo2m_extend($self, $base + UID_SLICE);
287 $uo2m = [ unpack('S*', $uo2m) ] if !ref($uo2m);
291 for my $msn (@$uo2m) {
293 $msn2uid[$msn - 1] = $uo + $base if $msn;
298 # converts a set of message sequence numbers in requests to UIDs:
299 sub msn_to_uid_range ($$) {
301 $_[1] =~ s!([0-9]+)!$msn2uid->[$1 - 1] // ($msn2uid->[-1] + 1)!sge;
304 # called by PublicInbox::InboxIdle
305 sub on_inbox_unlock {
306 my ($self, $ibx) = @_;
307 my $uid_end = $self->{uid_base} + UID_SLICE;
308 uo2m_extend($self, $uid_end, 'write');
309 my $new = uo2m_last_uid($self);
310 if ($new == $uid_end) { # max exceeded $uid_end
311 # continue idling w/o inotify
312 my $sock = $self->{sock} or return;
313 $ibx->unsubscribe_unlock(fileno($sock));
317 # called every X minute(s) or so by PublicInbox::DS::later
323 for my $i (values %$old) {
324 next if ($i->{wbuf} || !exists($i->{-idle_tag}));
325 $i->update_idle_time or next;
326 $IDLERS->{fileno($i->{sock})} = $i;
327 $i->write(\"* OK Still here\r\n");
329 $idle_timer = scalar keys %$IDLERS ?
330 PublicInbox::DS::later(\&idle_tick_all) : undef;
334 my ($self, $tag) = @_;
335 # IDLE seems allowed by dovecot w/o a mailbox selected *shrug*
336 my $ibx = $self->{ibx} or return "$tag BAD no mailbox selected\r\n";
337 my $uid_end = $self->{uid_base} + UID_SLICE;
338 uo2m_extend($self, $uid_end);
339 my $sock = $self->{sock} or return;
340 my $fd = fileno($sock);
341 $self->{-idle_tag} = $tag;
342 # only do inotify on most recent slice
343 if ($ibx->over->max < $uid_end) {
344 $ibx->subscribe_unlock($fd, $self);
345 $self->{imapd}->idler_start;
347 $idle_timer //= PublicInbox::DS::later(\&idle_tick_all);
348 $IDLERS->{$fd} = $self;
353 my ($self, $ibx) = @_;
354 my $sock = $self->{sock} or return;
355 my $fd = fileno($sock);
356 delete $IDLERS->{$fd};
357 $ibx->unsubscribe_unlock($fd);
361 my ($self, $tag) = @_; # $tag is "DONE" (case-insensitive)
362 defined(my $idle_tag = delete $self->{-idle_tag}) or
363 return "$tag BAD not idle\r\n";
364 my $ibx = $self->{ibx} or do {
365 warn "BUG: idle_tag set w/o inbox";
366 return "$tag BAD internal bug\r\n";
368 stop_idle($self, $ibx);
369 "$idle_tag OK Idle done\r\n";
372 sub ensure_slices_exist ($$$) {
373 my ($imapd, $ibx, $max) = @_;
374 defined(my $mb_top = $ibx->{newsgroup}) or return;
375 my $mailboxes = $imapd->{mailboxes};
377 for (my $i = int($max/UID_SLICE); $i >= 0; --$i) {
378 my $sub_mailbox = "$mb_top.$i";
379 last if exists $mailboxes->{$sub_mailbox};
380 $mailboxes->{$sub_mailbox} = $ibx;
381 $sub_mailbox =~ s/\Ainbox\./INBOX./i; # more familiar to users
382 push @created, $sub_mailbox;
384 return unless @created;
385 my $l = $imapd->{inboxlist} or return;
386 push @$l, map { qq[* LIST (\\HasNoChildren) "." $_\r\n] } @created;
389 sub inbox_lookup ($$;$) {
390 my ($self, $mailbox, $examine) = @_;
391 my ($ibx, $exists, $uidmax, $uid_base) = (undef, 0, 0, 0);
392 $mailbox = lc $mailbox;
393 $ibx = $self->{imapd}->{mailboxes}->{$mailbox} or return;
394 my $over = $ibx->over;
395 if ($over != $ibx) { # not a dummy
396 $mailbox =~ /\.([0-9]+)\z/ or
397 die "BUG: unexpected dummy mailbox: $mailbox\n";
398 $uid_base = $1 * UID_SLICE;
400 # ->num_highwater caches for writers, so use ->meta_accessor
401 $uidmax = $ibx->mm->meta_accessor('num_highwater') // 0;
403 $self->{uid_base} = $uid_base;
405 $self->{uo2m} = uo2m_ary_new($self, \$exists);
407 $exists = $over->imap_exists;
409 ensure_slices_exist($self->{imapd}, $ibx, $over->max);
412 $self->{uid_base} = $uid_base;
414 delete $self->{uo2m};
416 # if "INBOX.foo.bar" is selected and "INBOX.foo.bar.0",
417 # check for new UID ranges (e.g. "INBOX.foo.bar.1")
418 if (my $z = $self->{imapd}->{mailboxes}->{"$mailbox.0"}) {
419 ensure_slices_exist($self->{imapd}, $z, $z->over->max);
422 ($ibx, $exists, $uidmax + 1, $uid_base);
425 sub cmd_examine ($$$) {
426 my ($self, $tag, $mailbox) = @_;
427 # XXX: do we need this? RFC 5162/7162
428 my $ret = $self->{ibx} ? "* OK [CLOSED] previous closed\r\n" : '';
429 my ($ibx, $exists, $uidnext, $base) = inbox_lookup($self, $mailbox, 1);
430 return "$tag NO Mailbox doesn't exist: $mailbox\r\n" if !$ibx;
435 * OK [PERMANENTFLAGS ()] Read-only mailbox\r
436 * OK [UNSEEN $exists]\r
437 * OK [UIDNEXT $uidnext]\r
438 * OK [UIDVALIDITY $ibx->{uidvalidity}]\r
439 $tag OK [READ-ONLY] EXAMINE/SELECT done\r
447 } elsif ($v =~ /[{"\r\n%*\\\[]/) { # literal string
448 '{' . length($v) . "}\r\n" . $v;
449 } else { # quoted string
454 sub addr_envelope ($$;$) {
455 my ($eml, $x, $y) = @_;
456 my $v = $eml->header_raw($x) //
457 ($y ? $eml->header_raw($y) : undef) // return 'NIL';
459 my @x = $Address->parse($v) or return 'NIL';
461 map { '(' . join(' ',
462 _esc($_->name), 'NIL',
463 _esc($_->user), _esc($_->host)
469 sub eml_envelope ($) {
472 _esc($eml->header_raw('Date')),
473 _esc($eml->header_raw('Subject')),
474 addr_envelope($eml, 'From'),
475 addr_envelope($eml, 'Sender', 'From'),
476 addr_envelope($eml, 'Reply-To', 'From'),
477 addr_envelope($eml, 'To'),
478 addr_envelope($eml, 'Cc'),
479 addr_envelope($eml, 'Bcc'),
480 _esc($eml->header_raw('In-Reply-To')),
481 _esc($eml->header_raw('Message-ID')),
487 if ($hash && scalar keys %$hash) {
488 $hash = [ %$hash ]; # flatten hash into 1-dimensional array
489 '(' . join(' ', map { _esc($_) } @$hash) . ')';
495 sub body_disposition ($) {
497 my $cd = $eml->header_raw('Content-Disposition') or return 'NIL';
498 $cd = parse_content_disposition($cd);
499 my $buf = '('._esc($cd->{type});
500 $buf .= ' ' . _esc_hash(delete $cd->{attributes});
504 sub body_leaf ($$;$) {
505 my ($eml, $structure, $hold) = @_;
507 $eml->{is_submsg} and # parent was a message/(rfc822|news|global)
508 $buf .= eml_envelope($eml). ' ';
510 $buf .= '('._esc($ct->{type}).' ';
511 $buf .= _esc($ct->{subtype});
512 $buf .= ' ' . _esc_hash(delete $ct->{attributes});
513 $buf .= ' ' . _esc($eml->header_raw('Content-ID'));
514 $buf .= ' ' . _esc($eml->header_raw('Content-Description'));
515 my $cte = $eml->header_raw('Content-Transfer-Encoding') // '7bit';
516 $buf .= ' ' . _esc($cte);
517 $buf .= ' ' . $eml->{imap_body_len};
518 $buf .= ' '.($eml->body_raw =~ tr/\n/\n/) if lc($ct->{type}) eq 'text';
520 # for message/(rfc822|global|news), $hold[0] should have envelope
521 $buf .= ' ' . (@$hold ? join('', @$hold) : 'NIL') if $hold;
524 $buf .= ' '._esc($eml->header_raw('Content-MD5'));
525 $buf .= ' '. body_disposition($eml);
526 $buf .= ' '._esc($eml->header_raw('Content-Language'));
527 $buf .= ' '._esc($eml->header_raw('Content-Location'));
532 sub body_parent ($$$) {
533 my ($eml, $structure, $hold) = @_;
535 my $type = lc($ct->{type});
536 if ($type eq 'multipart') {
538 $buf .= @$hold ? join('', @$hold) : 'NIL';
539 $buf .= ' '._esc($ct->{subtype});
541 $buf .= ' '._esc_hash(delete $ct->{attributes});
542 $buf .= ' '.body_disposition($eml);
543 $buf .= ' '._esc($eml->header_raw('Content-Language'));
544 $buf .= ' '._esc($eml->header_raw('Content-Location'));
548 } else { # message/(rfc822|global|news)
549 @$hold = (body_leaf($eml, $structure, $hold));
553 # this is gross, but we need to process the parent part AFTER
554 # the child parts are done
555 sub bodystructure_prep {
557 my ($eml, $depth) = @$p; # ignore idx
558 # set length here, as $eml->{bdy} gets deleted for message/rfc822
559 $eml->{imap_body_len} = length($eml->body_raw);
560 push @$q, $eml, $depth;
563 # for FETCH BODY and FETCH BODYSTRUCTURE
564 sub fetch_body ($;$) {
565 my ($eml, $structure) = @_;
567 $eml->each_part(\&bodystructure_prep, \@q, 0, 1);
571 my ($part, $depth) = splice(@q, -2);
572 my $is_mp_parent = $depth == ($cur_depth - 1);
576 body_parent($part, $structure, \@hold);
578 unshift @hold, body_leaf($part, $structure);
584 sub requeue_once ($) {
586 # COMPRESS users all share the same DEFLATE context.
587 # Flush it here to ensure clients don't see
591 # no recursion, schedule another call ASAP,
592 # but only after all pending writes are done.
594 my $new_size = push(@{$self->{wbuf}}, \&long_step);
596 # wbuf may be populated by $cb, no need to rearm if so:
597 $self->requeue if $new_size == 1;
601 my ($self, $smsg, $bref, $ops, $partial) = @_;
602 my $uid = $smsg->{num};
603 $self->msg_more('* '.uid2msn($self, $uid)." FETCH (UID $uid");
605 for (my $i = 0; $i < @$ops;) {
607 $ops->[$i++]->($self, $k, $smsg, $bref, $eml);
609 partial_emit($self, $partial, $eml) if $partial;
610 $self->msg_more(")\r\n");
613 sub fetch_blob_cb { # called by git->cat_async via git_async_cat
614 my ($bref, $oid, $type, $size, $fetch_arg) = @_;
615 my ($self, undef, $msgs, $range_info, $ops, $partial) = @$fetch_arg;
616 my $smsg = shift @$msgs or die 'BUG: no smsg';
617 if (!defined($oid)) {
618 # it's possible to have TOCTOU if an admin runs
619 # public-inbox-(edit|purge), just move onto the next message
620 return requeue_once($self);
622 $smsg->{blob} eq $oid or die "BUG: $smsg->{blob} != $oid";
624 fetch_run_ops($self, $smsg, $bref, $ops, $partial);
629 my ($self, $k, undef, $bref) = @_;
630 $self->msg_more(" $k {" . length($$bref)."}\r\n");
631 $self->msg_more($$bref);
634 # Mail::IMAPClient::message_string cares about this by default,
635 # (->Ignoresizeerrors attribute). Admins are encouraged to
636 # --reindex for IMAP support, anyways.
637 sub emit_rfc822_size {
638 my ($self, $k, $smsg) = @_;
639 $self->msg_more(' RFC822.SIZE ' . $smsg->{bytes});
642 sub emit_internaldate {
643 my ($self, undef, $smsg) = @_;
644 $self->msg_more(' INTERNALDATE "'.$smsg->internaldate.'"');
647 sub emit_flags { $_[0]->msg_more(' FLAGS ()') }
650 my ($self, undef, undef, undef, $eml) = @_;
651 $self->msg_more(' ENVELOPE '.eml_envelope($eml));
654 sub emit_rfc822_header {
655 my ($self, $k, undef, undef, $eml) = @_;
656 $self->msg_more(" $k {".length(${$eml->{hdr}})."}\r\n");
657 $self->msg_more(${$eml->{hdr}});
660 # n.b. this is sorted to be after any emit_eml_new ops
661 sub emit_rfc822_text {
662 my ($self, $k, undef, $bref) = @_;
663 $self->msg_more(" $k {".length($$bref)."}\r\n");
664 $self->msg_more($$bref);
667 sub emit_bodystructure {
668 my ($self, undef, undef, undef, $eml) = @_;
669 $self->msg_more(' BODYSTRUCTURE '.fetch_body($eml, 1));
673 my ($self, undef, undef, undef, $eml) = @_;
674 $self->msg_more(' BODY '.fetch_body($eml));
677 # set $eml once ($_[4] == $eml, $_[3] == $bref)
678 sub op_eml_new { $_[4] = PublicInbox::Eml->new($_[3]) }
680 # s/From / fixes old bug from import (pre-a0c07cba0e5d8b6a)
682 ${$_[0]} =~ s/(?<!\r)\n/\r\n/sg;
683 ${$_[0]} =~ s/\A[\r\n]*From [^\r\n]*\r\n//s;
686 sub op_crlf_bref { to_crlf_full($_[3]) }
688 sub op_crlf_hdr { to_crlf_full($_[4]->{hdr}) }
690 sub op_crlf_bdy { ${$_[4]->{bdy}} =~ s/(?<!\r)\n/\r\n/sg if $_[4]->{bdy} }
692 sub uid_clamp ($$$) {
693 my ($self, $beg, $end) = @_;
694 my $uid_min = $self->{uid_base} + 1;
695 my $uid_end = $uid_min + UID_SLICE - 1;
696 $$beg = $uid_min if $$beg < $uid_min;
697 $$end = $uid_end if $$end > $uid_end;
700 sub range_step ($$) {
701 my ($self, $range_csv) = @_;
702 my ($beg, $end, $range);
703 if ($$range_csv =~ s/\A([^,]+),//) {
706 $range = $$range_csv;
709 my $uid_base = $self->{uid_base};
710 my $uid_end = $uid_base + UID_SLICE;
711 if ($range =~ /\A([0-9]+):([0-9]+)\z/) {
712 ($beg, $end) = ($1 + 0, $2 + 0);
713 uid_clamp($self, \$beg, \$end);
714 } elsif ($range =~ /\A([0-9]+):\*\z/) {
716 $end = $self->{ibx}->over->max;
717 $end = $uid_end if $end > $uid_end;
718 $beg = $end if $beg > $end;
719 uid_clamp($self, \$beg, \$end);
720 } elsif ($range =~ /\A[0-9]+\z/) {
721 $beg = $end = $range + 0;
722 # just let the caller do an out-of-range query if a single
723 # UID is out-of-range
724 ++$beg if ($beg <= $uid_base || $end > $uid_end);
726 return 'BAD fetch range';
728 [ $beg, $end, $$range_csv ];
731 sub refill_range ($$$) {
732 my ($self, $msgs, $range_info) = @_;
733 my ($beg, $end, $range_csv) = @$range_info;
734 if (scalar(@$msgs = @{$self->{ibx}->over->query_xover($beg, $end)})) {
735 $range_info->[0] = $msgs->[-1]->{num} + 1;
738 return 'OK Fetch done' if !$range_csv;
739 my $next_range = range_step($self, \$range_csv);
740 return $next_range if !ref($next_range); # error
741 @$range_info = @$next_range;
742 undef; # keep looping
745 sub fetch_blob { # long_response
746 my ($self, $tag, $msgs, $range_info, $ops, $partial) = @_;
747 while (!@$msgs) { # rare
748 if (my $end = refill_range($self, $msgs, $range_info)) {
749 $self->write(\"$tag $end\r\n");
753 uo2m_extend($self, $msgs->[-1]->{num});
754 git_async_cat($self->{ibx}->git, $msgs->[0]->{blob},
755 \&fetch_blob_cb, \@_);
758 sub fetch_smsg { # long_response
759 my ($self, $tag, $msgs, $range_info, $ops) = @_;
760 while (!@$msgs) { # rare
761 if (my $end = refill_range($self, $msgs, $range_info)) {
762 $self->write(\"$tag $end\r\n");
766 uo2m_extend($self, $msgs->[-1]->{num});
767 fetch_run_ops($self, $_, undef, $ops) for @$msgs;
772 sub refill_uids ($$$;$) {
773 my ($self, $uids, $range_info, $sql) = @_;
774 my ($beg, $end, $range_csv) = @$range_info;
775 my $over = $self->{ibx}->over;
777 if (scalar(@$uids = @{$over->uid_range($beg, $end, $sql)})) {
778 $range_info->[0] = $uids->[-1] + 1; # update $beg
780 } elsif (!$range_csv) {
783 my $next_range = range_step($self, \$range_csv);
784 return $next_range if !ref($next_range); # error
785 ($beg, $end, $range_csv) = @$range_info = @$next_range;
791 sub fetch_uid { # long_response
792 my ($self, $tag, $uids, $range_info, $ops) = @_;
793 if (defined(my $err = refill_uids($self, $uids, $range_info))) {
794 $err ||= 'OK Fetch done';
795 $self->write("$tag $err\r\n");
798 my $adj = $self->{uid_base} + 1;
799 my $uo2m = uo2m_extend($self, $uids->[-1]);
800 $uo2m = [ unpack('S*', $uo2m) ] if !ref($uo2m);
803 $self->msg_more("* $uo2m->[$_ - $adj] FETCH (UID $_");
804 for ($i = 0; $i < @$ops;) {
806 $ops->[$i++]->($self, $k);
808 $self->msg_more(")\r\n");
814 sub cmd_status ($$$;@) {
815 my ($self, $tag, $mailbox, @items) = @_;
816 return "$tag BAD no items\r\n" if !scalar(@items);
817 ($items[0] !~ s/\A\(//s || $items[-1] !~ s/\)\z//s) and
818 return "$tag BAD invalid args\r\n";
819 my ($ibx, $exists, $uidnext) = inbox_lookup($self, $mailbox);
820 return "$tag NO Mailbox doesn't exist: $mailbox\r\n" if !$ibx;
822 for my $it (@items) {
825 if ($it =~ /\A(?:MESSAGES|UNSEEN|RECENT)\z/) {
827 } elsif ($it eq 'UIDNEXT') {
829 } elsif ($it eq 'UIDVALIDITY') {
830 push @it, $ibx->{uidvalidity};
832 return "$tag BAD invalid item\r\n";
835 return "$tag BAD no items\r\n" if !@it;
836 "* STATUS $mailbox (".join(' ', @it).")\r\n" .
837 "$tag OK Status done\r\n";
840 my %patmap = ('*' => '.*', '%' => '[^\.]*');
841 sub cmd_list ($$$$) {
842 my ($self, $tag, $refname, $wildcard) = @_;
843 my $l = $self->{imapd}->{inboxlist};
844 if ($refname eq '' && $wildcard eq '') {
845 # request for hierarchy delimiter
846 $l = [ qq[* LIST (\\Noselect) "." ""\r\n] ];
847 } elsif ($refname ne '' || $wildcard ne '*') {
848 $wildcard =~ s!([^a-z0-9_])!$patmap{$1} // "\Q$1"!egi;
849 $l = [ grep(/ \Q$refname\E$wildcard\r\n\z/is, @$l) ];
851 \(join('', @$l, "$tag OK List done\r\n"));
854 sub cmd_lsub ($$$$) {
855 my (undef, $tag) = @_; # same args as cmd_list
856 "$tag OK Lsub done\r\n";
859 sub eml_index_offs_i { # PublicInbox::Eml::each_part callback
861 my ($eml, undef, $idx) = @$p;
862 if ($idx && lc($eml->ct->{type}) eq 'multipart') {
863 $eml->{imap_bdy} = $eml->{bdy} // \'';
865 $all->{$idx} = $eml; # $idx => Eml
868 # prepares an index for BODY[$SECTION_IDX] fetches
869 sub eml_body_idx ($$) {
870 my ($eml, $section_idx) = @_;
871 my $idx = $eml->{imap_all_parts} //= do {
873 $eml->each_part(\&eml_index_offs_i, $all, 0, 1);
874 # top-level of multipart, BODY[0] not allowed (nz-number)
878 $idx->{$section_idx};
881 # BODY[($SECTION_IDX)?(.$SECTION_NAME)?]<$offset.$bytes>
883 my ($eml, $section_idx, $section_name) = @_;
884 if (defined $section_idx) {
885 $eml = eml_body_idx($eml, $section_idx) or return;
887 if (defined $section_name) {
888 if ($section_name eq 'MIME') {
889 # RFC 3501 6.4.5 states:
890 # The MIME part specifier MUST be prefixed
891 # by one or more numeric part specifiers
892 return unless defined $section_idx;
893 return $eml->header_obj->as_string . "\r\n";
895 my $bdy = $eml->{bdy} // $eml->{imap_bdy} // \'';
896 $eml = PublicInbox::Eml->new($$bdy);
897 if ($section_name eq 'TEXT') {
898 return $eml->body_raw;
899 } elsif ($section_name eq 'HEADER') {
900 return $eml->header_obj->as_string . "\r\n";
902 die "BUG: bad section_name=$section_name";
905 ${$eml->{bdy} // $eml->{imap_bdy} // \''};
908 # similar to what's in PublicInbox::Eml::re_memo, but doesn't memoize
909 # to avoid OOM with malicious users
910 sub hdrs_regexp ($) {
912 my $names = join('|', map { "\Q$_" } split(/[ \t]+/, $hdrs));
913 qr/^(?:$names):[ \t]*[^\n]*\r?\n # 1st line
914 # continuation lines:
915 (?:[^:\n]*?[ \t]+[^\n]*\r?\n)*
919 # BODY[($SECTION_IDX.)?HEADER.FIELDS.NOT ($HDRS)]<$offset.$bytes>
920 sub partial_hdr_not {
921 my ($eml, $section_idx, $hdrs_re) = @_;
922 if (defined $section_idx) {
923 $eml = eml_body_idx($eml, $section_idx) or return;
925 my $str = $eml->header_obj->as_string;
926 $str =~ s/$hdrs_re//g;
927 $str =~ s/(?<!\r)\n/\r\n/sg;
931 # BODY[($SECTION_IDX.)?HEADER.FIELDS ($HDRS)]<$offset.$bytes>
932 sub partial_hdr_get {
933 my ($eml, $section_idx, $hdrs_re) = @_;
934 if (defined $section_idx) {
935 $eml = eml_body_idx($eml, $section_idx) or return;
937 my $str = $eml->header_obj->as_string;
938 $str = join('', ($str =~ m/($hdrs_re)/g));
939 $str =~ s/(?<!\r)\n/\r\n/sg;
943 sub partial_prepare ($$$$) {
944 my ($need, $partial, $want, $att) = @_;
946 # recombine [ "BODY[1.HEADER.FIELDS", "(foo", "bar)]" ]
947 # back to: "BODY[1.HEADER.FIELDS (foo bar)]"
948 return unless $att =~ /\ABODY\[/s;
949 until (rindex($att, ']') >= 0) {
950 my $next = shift @$want or return;
951 $att .= ' ' . uc($next);
953 if ($att =~ /\ABODY\[([0-9]+(?:\.[0-9]+)*)? # 1 - section_idx
954 (?:\.(HEADER|MIME|TEXT))? # 2 - section_name
955 \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 3, 4
956 $partial->{$att} = [ \&partial_body, $1, $2, $3, $4 ];
957 $$need |= CRLF_BREF|EML_HDR|EML_BDY;
958 } elsif ($att =~ /\ABODY\[(?:([0-9]+(?:\.[0-9]+)*)\.)? # 1 - section_idx
959 (?:HEADER\.FIELDS(\.NOT)?)\x20 # 2
960 \(([A-Z0-9\-\x20]+)\) # 3 - hdrs
961 \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 4 5
962 my $tmp = $partial->{$att} = [ $2 ? \&partial_hdr_not
965 $tmp->[2] = hdrs_regexp($3);
967 # don't emit CRLF_HDR instruction, here, partial_hdr_*
968 # will do CRLF conversion with only the extracted result
969 # and not waste time converting lines we don't care about.
976 sub partial_emit ($$$) {
977 my ($self, $partial, $eml) = @_;
979 my ($k, $cb, @args) = @$_;
980 my ($offset, $len) = splice(@args, -2);
981 # $cb is partial_body|partial_hdr_get|partial_hdr_not
982 my $str = $cb->($eml, @args) // '';
983 if (defined $offset) {
985 $str = substr($str, $offset, $len);
986 $k =~ s/\.$len>\z/>/ or warn
987 "BUG: unable to remove `.$len>' from `$k'";
989 $str = substr($str, $offset);
995 $self->msg_more(" $k {$len}\r\n");
996 $self->msg_more($str);
1000 sub fetch_compile ($) {
1002 if ($want->[0] =~ s/\A\(//s) {
1003 $want->[-1] =~ s/\)\z//s or return 'BAD no rparen';
1005 my (%partial, %seen, @op);
1007 while (defined(my $att = shift @$want)) {
1009 next if $att eq 'UID'; # always returned
1010 $att =~ s/\ABODY\.PEEK\[/BODY\[/; # we're read-only
1011 my $x = $FETCH_ATT{$att};
1013 while (my ($k, $fl_cb) = each %$x) {
1014 next if $seen{$k}++;
1015 $need |= $fl_cb->[0];
1016 push @op, [ @$fl_cb, $k ];
1018 } elsif (!partial_prepare(\$need, \%partial, $want, $att)) {
1019 return "BAD param: $att";
1024 # stabilize partial order for consistency and ease-of-debugging:
1025 if (scalar keys %partial) {
1027 $r[2] = [ map { [ $_, @{$partial{$_}} ] } sort keys %partial ];
1030 push @op, $OP_EML_NEW if ($need & (EML_HDR|EML_BDY));
1032 # do we need CRLF conversion?
1033 if ($need & CRLF_BREF) {
1034 push @op, $OP_CRLF_BREF;
1035 } elsif (my $crlf = ($need & (CRLF_HDR|CRLF_BDY))) {
1036 if ($crlf == (CRLF_HDR|CRLF_BDY)) {
1037 push @op, $OP_CRLF_BREF;
1038 } elsif ($need & CRLF_HDR) {
1039 push @op, $OP_CRLF_HDR;
1041 push @op, $OP_CRLF_BDY;
1045 $r[0] = $need & NEED_BLOB ? \&fetch_blob :
1046 ($need & NEED_SMSG ? \&fetch_smsg : \&fetch_uid);
1048 # r[1] = [ $key1, $cb1, $key2, $cb2, ... ]
1049 use sort 'stable'; # makes output more consistent
1050 $r[1] = [ map { ($_->[2], $_->[1]) } sort { $a->[0] <=> $b->[0] } @op ];
1054 sub cmd_uid_fetch ($$$$;@) {
1055 my ($self, $tag, $range_csv, @want) = @_;
1056 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1057 my ($cb, $ops, $partial) = fetch_compile(\@want);
1058 return "$tag $cb\r\n" unless $ops;
1060 # cb is one of fetch_blob, fetch_smsg, fetch_uid
1061 $range_csv = 'bad' if $range_csv !~ $valid_range;
1062 my $range_info = range_step($self, \$range_csv);
1063 return "$tag $range_info\r\n" if !ref($range_info);
1064 uo2m_hibernate($self) if $cb == \&fetch_blob; # slow, save RAM
1065 long_response($self, $cb, $tag, [], $range_info, $ops, $partial);
1068 sub cmd_fetch ($$$$;@) {
1069 my ($self, $tag, $range_csv, @want) = @_;
1070 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1071 my ($cb, $ops, $partial) = fetch_compile(\@want);
1072 return "$tag $cb\r\n" unless $ops;
1074 # cb is one of fetch_blob, fetch_smsg, fetch_uid
1075 $range_csv = 'bad' if $range_csv !~ $valid_range;
1076 msn_to_uid_range(msn2uid($self), $range_csv);
1077 my $range_info = range_step($self, \$range_csv);
1078 return "$tag $range_info\r\n" if !ref($range_info);
1079 uo2m_hibernate($self) if $cb == \&fetch_blob; # slow, save RAM
1080 long_response($self, $cb, $tag, [], $range_info, $ops, $partial);
1083 sub msn_convert ($$) {
1084 my ($self, $uids) = @_;
1085 my $adj = $self->{uid_base} + 1;
1086 my $uo2m = uo2m_extend($self, $uids->[-1]);
1087 $uo2m = [ unpack('S*', $uo2m) ] if !ref($uo2m);
1088 $_ = $uo2m->[$_ - $adj] for @$uids;
1091 sub search_uid_range { # long_response
1092 my ($self, $tag, $sql, $range_info, $want_msn) = @_;
1094 if (defined(my $err = refill_uids($self, $uids, $range_info, $sql))) {
1095 $err ||= 'OK Search done';
1096 $self->write("\r\n$tag $err\r\n");
1099 msn_convert($self, $uids) if $want_msn;
1100 $self->msg_more(join(' ', '', @$uids));
1105 my ($q, $k, $d) = @_;
1106 my $sql = $q->{sql};
1109 if ($k eq 'SENTON') {
1110 my $end = $d + 86399; # no leap day...
1111 my $da = strftime('%Y%m%d%H%M%S', gmtime($d));
1112 my $db = strftime('%Y%m%d%H%M%S', gmtime($end));
1113 $q->{xap} .= " dt:$da..$db";
1114 $$sql .= " AND ds >= $d AND ds <= $end" if defined($sql);
1115 } elsif ($k eq 'SENTBEFORE') {
1116 $q->{xap} .= ' d:..'.strftime('%Y%m%d', gmtime($d));
1117 $$sql .= " AND ds <= $d" if defined($sql);
1118 } elsif ($k eq 'SENTSINCE') {
1119 $q->{xap} .= ' d:'.strftime('%Y%m%d', gmtime($d)).'..';
1120 $$sql .= " AND ds >= $d" if defined($sql);
1122 # INTERNALDATE (Received)
1123 } elsif ($k eq 'ON') {
1124 my $end = $d + 86399; # no leap day...
1125 $q->{xap} .= " ts:$d..$end";
1126 $$sql .= " AND ts >= $d AND ts <= $end" if defined($sql);
1127 } elsif ($k eq 'BEFORE') {
1128 $q->{xap} .= " ts:..$d";
1129 $$sql .= " AND ts <= $d" if defined($sql);
1130 } elsif ($k eq 'SINCE') {
1131 $q->{xap} .= " ts:$d..";
1132 $$sql .= " AND ts >= $d" if defined($sql);
1134 die "BUG: $k not recognized";
1138 # IMAP to Xapian search key mapping
1143 TEXT => '', # n.b. does not include all headers
1146 # BCC => 'bcc:', # TODO
1147 # KEYWORD # TODO ? dfpre,dfpost,...
1150 # IMAP allows searching arbitrary headers via "HEADER $HDR_NAME $HDR_VAL"
1151 # which gets silly expensive. We only allow the headers we already index.
1152 my %H2X = (%I2X, 'MESSAGE-ID' => 'm:', 'LIST-ID' => 'l:');
1154 sub xap_append ($$$$) {
1155 my ($q, $rest, $k, $xk) = @_;
1156 delete $q->{sql}; # can't use over.sqlite3
1157 defined(my $arg = shift @$rest) or return "BAD $k no arg";
1159 # AFAIK Xapian can't handle [*"] in probabilistic terms
1161 ${$q->{xap}} .= qq[ $xk"$arg"];
1165 sub parse_query ($$) {
1166 my ($self, $query) = @_;
1167 my $q = PublicInbox::IMAPsearchqp::parse($self, $query);
1169 my $max = $self->{ibx}->over->max;
1171 uid_clamp($self, \$beg, \$max);
1172 $q->{range_info} = [ $beg, $max ];
1177 sub refill_xap ($$$$) {
1178 my ($self, $uids, $range_info, $q) = @_;
1179 my ($beg, $end) = @$range_info;
1180 my $srch = $self->{ibx}->search;
1181 my $opt = { mset => 2, limit => 1000 };
1182 my $nshard = $srch->{nshard} // 1;
1183 my $mset = $srch->query("$q uid:$beg..$end", $opt);
1184 @$uids = map { mdocid($nshard, $_) } $mset->items;
1186 $range_info->[0] = $uids->[-1] + 1; # update $beg
1187 return; # possibly more
1192 sub search_xap_range { # long_response
1193 my ($self, $tag, $q, $range_info, $want_msn) = @_;
1195 if (defined(my $err = refill_xap($self, $uids, $range_info, $q))) {
1196 $err ||= 'OK Search done';
1197 $self->write("\r\n$tag $err\r\n");
1200 msn_convert($self, $uids) if $want_msn;
1201 $self->msg_more(join(' ', '', @$uids));
1206 my ($self, $tag, $query, $want_msn) = @_;
1207 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1208 my $q = parse_query($self, $query);
1209 return "$tag $q\r\n" if !ref($q);
1210 my ($sql, $range_info) = delete @$q{qw(sql range_info)};
1211 if (!scalar(keys %$q)) { # overview.sqlite3
1212 $self->msg_more('* SEARCH');
1213 long_response($self, \&search_uid_range,
1214 $tag, $sql, $range_info, $want_msn);
1215 } elsif ($q = $q->{xap}) {
1216 $self->{ibx}->search or
1217 return "$tag BAD search not available for mailbox\r\n";
1218 $self->msg_more('* SEARCH');
1219 long_response($self, \&search_xap_range,
1220 $tag, $q, $range_info, $want_msn);
1222 "$tag BAD Error\r\n";
1226 sub cmd_uid_search ($$$) {
1227 my ($self, $tag, $query) = @_;
1228 search_common($self, $tag, $query);
1231 sub cmd_search ($$$;) {
1232 my ($self, $tag, $query) = @_;
1233 search_common($self, $tag, $query, 1);
1236 sub args_ok ($$) { # duplicated from PublicInbox::NNTP
1237 my ($cb, $argc) = @_;
1238 my $tot = prototype $cb;
1239 my ($nreq, undef) = split(';', $tot);
1240 $nreq = ($nreq =~ tr/$//) - 1;
1241 $tot = ($tot =~ tr/$//) - 1;
1242 ($argc <= $tot && $argc >= $nreq);
1245 # returns 1 if we can continue, 0 if not due to buffered writes or disconnect
1246 sub process_line ($$) {
1247 my ($self, $l) = @_;
1249 # TODO: IMAP allows literals for big requests to upload messages
1250 # (which we don't support) but maybe some big search queries use it.
1251 # RFC 3501 9 (2) doesn't permit TAB or multiple SP
1252 my ($tag, $req, @args) = parse_line('[ \t]+', 0, $l);
1253 pop(@args) if (@args && !defined($args[-1]));
1254 if (@args && uc($req) eq 'UID') {
1255 $req .= "_".(shift @args);
1258 if (defined(my $idle_tag = $self->{-idle_tag})) {
1259 (uc($tag // '') eq 'DONE' && !defined($req)) ?
1260 idle_done($self, $tag) :
1261 "$idle_tag BAD expected DONE\r\n";
1262 } elsif (my $cmd = $self->can('cmd_'.lc($req // ''))) {
1263 if ($cmd == \&cmd_uid_search || $cmd == \&cmd_search) {
1264 # preserve user-supplied quotes for search
1265 (undef, @args) = split(/ search /i, $l, 2);
1267 $cmd->($self, $tag, @args);
1268 } else { # this is weird
1269 auth_challenge_ok($self) //
1271 ' BAD Error in IMAP command '.
1273 ": Unknown command\r\n";
1277 if ($err && $self->{sock}) {
1279 err($self, 'error from: %s (%s)', $l, $err);
1281 $res = "$tag BAD program fault - command not performed\r\n";
1283 return 0 unless defined $res;
1289 # wbuf is unset or empty, here; {long} may add to it
1290 my ($fd, $cb, $t0, @args) = @{$self->{long_cb}};
1291 my $more = eval { $cb->($self, @args) };
1292 if ($@ || !$self->{sock}) { # something bad happened...
1293 delete $self->{long_cb};
1294 my $elapsed = now() - $t0;
1297 "%s during long response[$fd] - %0.6f",
1300 out($self, " deferred[$fd] aborted - %0.6f", $elapsed);
1302 } elsif ($more) { # $self->{wbuf}:
1303 $self->update_idle_time;
1305 # control passed to git_async_cat if $more == \undef
1306 requeue_once($self) if !ref($more);
1307 } else { # all done!
1308 delete $self->{long_cb};
1309 my $elapsed = now() - $t0;
1310 my $fd = fileno($self->{sock});
1311 out($self, " deferred[$fd] done - %0.6f", $elapsed);
1312 my $wbuf = $self->{wbuf}; # do NOT autovivify
1314 $self->requeue unless $wbuf && @$wbuf;
1319 my ($self, $fmt, @args) = @_;
1320 printf { $self->{imapd}->{err} } $fmt."\n", @args;
1324 my ($self, $fmt, @args) = @_;
1325 printf { $self->{imapd}->{out} } $fmt."\n", @args;
1328 sub long_response ($$;@) {
1329 my ($self, $cb, @args) = @_; # cb returns true if more, false if done
1331 my $sock = $self->{sock} or return;
1332 # make sure we disable reading during a long response,
1333 # clients should not be sending us stuff and making us do more
1334 # work while we are stream a response to them
1335 $self->{long_cb} = [ fileno($sock), $cb, now(), @args ];
1336 long_step($self); # kick off!
1340 # callback used by PublicInbox::DS for any (e)poll (in/out/hup/err)
1344 return unless $self->flush_write && $self->{sock} && !$self->{long_cb};
1346 $self->update_idle_time;
1347 # only read more requests if we've drained the write buffer,
1348 # otherwise we can be buffering infinitely w/o backpressure
1350 my $rbuf = $self->{rbuf} // \(my $x = '');
1351 my $line = index($$rbuf, "\n");
1353 if (length($$rbuf) >= LINE_MAX) {
1354 $self->write(\"\* BAD request too long\r\n");
1355 return $self->close;
1357 $self->do_read($rbuf, LINE_MAX, length($$rbuf)) or
1358 return uo2m_hibernate($self);
1359 $line = index($$rbuf, "\n");
1361 $line = substr($$rbuf, 0, $line + 1, '');
1362 $line =~ s/\r?\n\z//s;
1363 return $self->close if $line =~ /[[:cntrl:]]/s;
1365 my $fd = fileno($self->{sock});
1366 my $r = eval { process_line($self, $line) };
1367 my $pending = $self->{wbuf} ? ' pending' : '';
1368 out($self, "[$fd] %s - %0.6f$pending - $r", $line, now() - $t0);
1370 return $self->close if $r < 0;
1371 $self->rbuf_idle($rbuf);
1372 $self->update_idle_time;
1374 # maybe there's more pipelined data, or we'll have
1375 # to register it for socket-readiness notifications
1376 $self->requeue unless $pending;
1379 sub compressed { undef }
1381 sub zflush {} # overridden by IMAPdeflate
1384 sub cmd_compress ($$$) {
1385 my ($self, $tag, $alg) = @_;
1386 return "$tag BAD DEFLATE only\r\n" if uc($alg) ne "DEFLATE";
1387 return "$tag BAD COMPRESS active\r\n" if $self->compressed;
1389 # CRIME made TLS compression obsolete
1390 # return "$tag NO [COMPRESSIONACTIVE]\r\n" if $self->tls_compressed;
1392 PublicInbox::IMAPdeflate->enable($self, $tag);
1397 sub cmd_starttls ($$) {
1398 my ($self, $tag) = @_;
1399 my $sock = $self->{sock} or return;
1400 if ($sock->can('stop_SSL') || $self->compressed) {
1401 return "$tag BAD TLS or compression already enabled\r\n";
1403 my $opt = $self->{imapd}->{accept_tls} or
1404 return "$tag BAD can not initiate TLS negotiation\r\n";
1405 $self->write(\"$tag OK begin TLS negotiation now\r\n");
1406 $self->{sock} = IO::Socket::SSL->start_SSL($sock, %$opt);
1407 $self->requeue if PublicInbox::DS::accept_tls_step($self);
1411 # for graceful shutdown in PublicInbox::Daemon:
1413 my ($self, $now) = @_;
1414 if (defined($self->{-idle_tag})) {
1415 $self->write(\"* BYE server shutting down\r\n");
1416 return; # not busy anymore
1418 ($self->{rbuf} || $self->{wbuf} || $self->not_idle_long($now));
1423 if (my $ibx = delete $self->{ibx}) {
1424 stop_idle($self, $ibx);
1426 $self->SUPER::close; # PublicInbox::DS::close
1429 # we're read-only, so SELECT and EXAMINE do the same thing
1431 *cmd_select = \&cmd_examine;
1433 package PublicInbox::IMAP_preauth;
1434 our @ISA = qw(PublicInbox::IMAP);