1 # Copyright (C) 2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # Each instance of this represents an IMAP client connected to
5 # public-inbox-imapd. Much of this was taken from NNTP, but
6 # further refined while experimenting on future ideas to handle
11 # * NNTP article numbers are UIDs, mm->created_at is UIDVALIDITY
13 # * public-inboxes are sliced into mailboxes of 50K messages
14 # to not overload MUAs: $NEWSGROUP_NAME.$SLICE_INDEX
15 # Slices are similar in concept to v2 "epochs". Epochs
16 # are for the limitations of git clients, while slices are
17 # for the limitations of IMAP clients.
19 # * We also take advantage of slices being only 50K to store
20 # "UID offset" to message sequence number (MSN) mapping
21 # as a 50K uint16_t array (via pack("S*", ...)). "UID offset"
22 # is the offset from {uid_base} which determines the start of
26 # imapd: PublicInbox::IMAPD ref
27 # ibx: PublicInbox::Inbox ref
28 # long_cb: long_response private data
29 # uid_base: base UID for mailbox slice (0-based)
30 # -login_tag: IMAP TAG for LOGIN
31 # -idle_tag: IMAP response tag for IDLE
32 # uo2m: UID-to-MSN mapping
33 package PublicInbox::IMAP;
35 use parent qw(PublicInbox::DS);
37 use PublicInbox::EmlContentFoo qw(parse_content_disposition);
38 use PublicInbox::DS qw(now);
39 use PublicInbox::Syscall qw(EPOLLIN EPOLLONESHOT);
40 use PublicInbox::GitAsyncCat;
41 use Text::ParseWords qw(parse_line);
43 use PublicInbox::Search;
44 use PublicInbox::IMAPsearchqp;
45 *mdocid = \&PublicInbox::Search::mdocid;
48 for my $mod (qw(Email::Address::XS Mail::Address)) {
49 eval "require $mod" or next;
50 $Address = $mod and last;
52 die "neither Email::Address::XS nor Mail::Address loaded: $@" if !$Address;
54 sub LINE_MAX () { 8000 } # RFC 2683 3.2.1.5
56 # Changing UID_SLICE will cause grief for clients which cache.
57 # This also needs to be <64K: we pack it into a uint16_t
58 # for long_response UID (offset) => MSN mappings
59 sub UID_SLICE () { 50_000 }
61 # these values area also used for sorting
62 sub NEED_SMSG () { 1 }
63 sub NEED_BLOB () { NEED_SMSG|2 }
64 sub CRLF_BREF () { 4 }
66 sub CRLF_HDR () { 16 }
68 sub CRLF_BDY () { 64 }
69 my $OP_EML_NEW = [ EML_HDR - 1, \&op_eml_new ];
70 my $OP_CRLF_BREF = [ CRLF_BREF, \&op_crlf_bref ];
71 my $OP_CRLF_HDR = [ CRLF_HDR, \&op_crlf_hdr ];
72 my $OP_CRLF_BDY = [ CRLF_BDY, \&op_crlf_bdy ];
75 'BODY[HEADER]' => [ NEED_BLOB|EML_HDR|CRLF_HDR, \&emit_rfc822_header ],
76 'BODY[TEXT]' => [ NEED_BLOB|EML_BDY|CRLF_BDY, \&emit_rfc822_text ],
77 'BODY[]' => [ NEED_BLOB|CRLF_BREF, \&emit_rfc822 ],
78 'RFC822.HEADER' => [ NEED_BLOB|EML_HDR|CRLF_HDR, \&emit_rfc822_header ],
79 'RFC822.TEXT' => [ NEED_BLOB|EML_BDY|CRLF_BDY, \&emit_rfc822_text ],
80 'RFC822.SIZE' => [ NEED_SMSG, \&emit_rfc822_size ],
81 RFC822 => [ NEED_BLOB|CRLF_BREF, \&emit_rfc822 ],
82 BODY => [ NEED_BLOB|EML_HDR|EML_BDY, \&emit_body ],
83 BODYSTRUCTURE => [ NEED_BLOB|EML_HDR|EML_BDY, \&emit_bodystructure ],
84 ENVELOPE => [ NEED_BLOB|EML_HDR, \&emit_envelope ],
85 FLAGS => [ 0, \&emit_flags ],
86 INTERNALDATE => [ NEED_SMSG, \&emit_internaldate ],
88 my %FETCH_ATT = map { $_ => [ $_ ] } keys %FETCH_NEED;
90 # aliases (RFC 3501 section 6.4.5)
91 $FETCH_ATT{FAST} = [ qw(FLAGS INTERNALDATE RFC822.SIZE) ];
92 $FETCH_ATT{ALL} = [ @{$FETCH_ATT{FAST}}, 'ENVELOPE' ];
93 $FETCH_ATT{FULL} = [ @{$FETCH_ATT{ALL}}, 'BODY' ];
95 for my $att (keys %FETCH_ATT) {
96 my %h = map { $_ => $FETCH_NEED{$_} } @{$FETCH_ATT{$att}};
97 $FETCH_ATT{$att} = \%h;
101 my $valid_range = '[0-9]+|[0-9]+:[0-9]+|[0-9]+:\*';
102 $valid_range = qr/\A(?:$valid_range)(?:,(?:$valid_range))*\z/;
104 # RFC 3501 5.4. Autologout Timer needs to be >= 30min
105 $PublicInbox::DS::EXPTIME = 60 * 30;
109 my $capa = capa($self);
110 $self->write(\"* OK [$capa] public-inbox-imapd ready\r\n");
114 my ($class, $sock, $imapd) = @_;
115 my $self = bless { imapd => $imapd }, 'PublicInbox::IMAP_preauth';
118 if ($sock->can('accept_SSL') && !$sock->accept_SSL) {
119 return CORE::close($sock) if $! != EAGAIN;
120 $ev = PublicInbox::TLS::epollbit();
121 $wbuf = [ \&PublicInbox::DS::accept_tls_step, \&greet ];
123 $self->SUPER::new($sock, $ev | EPOLLONESHOT);
125 $self->{wbuf} = $wbuf;
129 $self->update_idle_time;
138 # dovecot advertises IDLE pre-login; perhaps because some clients
139 # depend on it, so we'll do the same
140 my $capa = 'CAPABILITY IMAP4rev1 IDLE';
141 if ($self->logged_in) {
142 $capa .= ' COMPRESS=DEFLATE';
144 if (!($self->{sock} // $self)->can('accept_SSL') &&
145 $self->{imapd}->{accept_tls}) {
146 $capa .= ' STARTTLS';
148 $capa .= ' AUTH=ANONYMOUS';
152 sub login_success ($$) {
153 my ($self, $tag) = @_;
154 bless $self, 'PublicInbox::IMAP';
155 my $capa = capa($self);
156 "$tag OK [$capa] Logged in\r\n";
159 sub auth_challenge_ok ($) {
161 my $tag = delete($self->{-login_tag}) or return;
162 login_success($self, $tag);
165 sub cmd_login ($$$$) {
166 my ($self, $tag) = @_; # ignore ($user, $password) = ($_[2], $_[3])
167 login_success($self, $tag);
171 my ($self, $tag) = @_;
172 delete @$self{qw(uid_base uo2m)};
173 delete $self->{ibx} ? "$tag OK Close done\r\n"
174 : "$tag BAD No mailbox\r\n";
177 sub cmd_logout ($$) {
178 my ($self, $tag) = @_;
179 delete $self->{-idle_tag};
180 $self->write(\"* BYE logging out\r\n$tag OK Logout done\r\n");
181 $self->shutdn; # PublicInbox::DS::shutdn
185 sub cmd_authenticate ($$$) {
186 my ($self, $tag) = @_; # $method = $_[2], should be "ANONYMOUS"
187 $self->{-login_tag} = $tag;
191 sub cmd_capability ($$) {
192 my ($self, $tag) = @_;
193 '* '.capa($self)."\r\n$tag OK Capability done\r\n";
196 # uo2m: UID Offset to MSN, this is an arrayref by default,
197 # but uo2m_hibernate can compact and deduplicate it
198 sub uo2m_ary_new ($;$) {
199 my ($self, $exists) = @_;
200 my $base = $self->{uid_base};
201 my $uids = $self->{ibx}->over->uid_range($base + 1, $base + UID_SLICE);
203 # convert UIDs to offsets from {base}
204 my @tmp; # [$UID_OFFSET] => $MSN
207 $tmp[$_ - $base] = ++$msn for @$uids;
208 $$exists = $msn if $exists;
212 # changes UID-offset-to-MSN mapping into a deduplicated scalar:
213 # uint16_t uo2m[UID_SLICE].
214 # May be swapped out for idle clients if THP is disabled.
215 sub uo2m_hibernate ($) {
217 ref(my $uo2m = $self->{uo2m}) or return;
218 my %dedupe = ( uo2m_pack($uo2m) => undef );
219 $self->{uo2m} = (keys(%dedupe))[0];
223 sub uo2m_last_uid ($) {
225 defined(my $uo2m = $self->{uo2m}) or die 'BUG: uo2m_last_uid w/o {uo2m}';
226 (ref($uo2m) ? @$uo2m : (length($uo2m) >> 1)) + $self->{uid_base};
230 # $_[0] is an arrayref of MSNs, it may have undef gaps if there
231 # are gaps in the corresponding UIDs: [ msn1, msn2, undef, msn3 ]
232 no warnings 'uninitialized';
233 pack('S*', @{$_[0]});
236 # extend {uo2m} to account for new messages which arrived since
237 # {uo2m} was created.
238 sub uo2m_extend ($$;$) {
239 my ($self, $new_uid_max) = @_;
240 defined(my $uo2m = $self->{uo2m}) or
241 return($self->{uo2m} = uo2m_ary_new($self));
242 my $beg = uo2m_last_uid($self); # last UID we've learned
243 return $uo2m if $beg >= $new_uid_max; # fast path
245 # need to extend the current range:
246 my $base = $self->{uid_base};
248 my $uids = $self->{ibx}->over->uid_range($beg, $base + UID_SLICE);
249 my @tmp; # [$UID_OFFSET] => $MSN
250 my $write_method = $_[2] // 'msg_more';
252 my $msn = $uo2m->[-1];
253 $tmp[$_ - $beg] = ++$msn for @$uids;
254 $self->$write_method("* $msn EXISTS\r\n");
258 my $msn = unpack('S', substr($uo2m, -2, 2));
259 $tmp[$_ - $beg] = ++$msn for @$uids;
260 $self->$write_method("* $msn EXISTS\r\n");
261 $uo2m .= uo2m_pack(\@tmp);
262 my %dedupe = ($uo2m => undef);
263 $self->{uo2m} = (keys %dedupe)[0];
268 my ($self, $tag) = @_;
269 defined($self->{uid_base}) and
270 uo2m_extend($self, $self->{uid_base} + UID_SLICE);
271 \"$tag OK Noop done\r\n";
274 # the flexible version which works on scalars and array refs.
275 # Must call uo2m_extend before this
277 my ($self, $uid) = @_;
278 my $uo2m = $self->{uo2m};
279 my $off = $uid - $self->{uid_base} - 1;
280 ref($uo2m) ? $uo2m->[$off] : unpack('S', substr($uo2m, $off << 1, 2));
283 # returns an arrayref of UIDs, so MSNs can be translated to UIDs via:
284 # $msn2uid->[$MSN-1] => $UID. The result of this is always ephemeral
285 # and does not live beyond the event loop.
288 my $base = $self->{uid_base};
289 my $uo2m = uo2m_extend($self, $base + UID_SLICE);
290 $uo2m = [ unpack('S*', $uo2m) ] if !ref($uo2m);
294 for my $msn (@$uo2m) {
296 $msn2uid[$msn - 1] = $uo + $base if $msn;
301 # converts a set of message sequence numbers in requests to UIDs:
302 sub msn_to_uid_range ($$) {
304 $_[1] =~ s!([0-9]+)!$msn2uid->[$1 - 1] // ($msn2uid->[-1] + 1)!sge;
307 # called by PublicInbox::InboxIdle
308 sub on_inbox_unlock {
309 my ($self, $ibx) = @_;
310 my $uid_end = $self->{uid_base} + UID_SLICE;
311 uo2m_extend($self, $uid_end, 'write');
312 my $new = uo2m_last_uid($self);
313 if ($new == $uid_end) { # max exceeded $uid_end
314 # continue idling w/o inotify
315 my $sock = $self->{sock} or return;
316 $ibx->unsubscribe_unlock(fileno($sock));
320 # called every X minute(s) or so by PublicInbox::DS::later
326 for my $i (values %$old) {
327 next if ($i->{wbuf} || !exists($i->{-idle_tag}));
328 $i->update_idle_time or next;
329 $IDLERS->{fileno($i->{sock})} = $i;
330 $i->write(\"* OK Still here\r\n");
332 $idle_timer = scalar keys %$IDLERS ?
333 PublicInbox::DS::later(\&idle_tick_all) : undef;
337 my ($self, $tag) = @_;
338 # IDLE seems allowed by dovecot w/o a mailbox selected *shrug*
339 my $ibx = $self->{ibx} or return "$tag BAD no mailbox selected\r\n";
340 my $uid_end = $self->{uid_base} + UID_SLICE;
341 uo2m_extend($self, $uid_end);
342 my $sock = $self->{sock} or return;
343 my $fd = fileno($sock);
344 $self->{-idle_tag} = $tag;
345 # only do inotify on most recent slice
346 if ($ibx->over->max < $uid_end) {
347 $ibx->subscribe_unlock($fd, $self);
348 $self->{imapd}->idler_start;
350 $idle_timer //= PublicInbox::DS::later(\&idle_tick_all);
351 $IDLERS->{$fd} = $self;
356 my ($self, $ibx) = @_;
357 my $sock = $self->{sock} or return;
358 my $fd = fileno($sock);
359 delete $IDLERS->{$fd};
360 $ibx->unsubscribe_unlock($fd);
364 my ($self, $tag) = @_; # $tag is "DONE" (case-insensitive)
365 defined(my $idle_tag = delete $self->{-idle_tag}) or
366 return "$tag BAD not idle\r\n";
367 my $ibx = $self->{ibx} or do {
368 warn "BUG: idle_tag set w/o inbox";
369 return "$tag BAD internal bug\r\n";
371 stop_idle($self, $ibx);
372 "$idle_tag OK Idle done\r\n";
375 sub ensure_slices_exist ($$$) {
376 my ($imapd, $ibx, $max) = @_;
377 defined(my $mb_top = $ibx->{newsgroup}) or return;
378 my $mailboxes = $imapd->{mailboxes};
380 for (my $i = int($max/UID_SLICE); $i >= 0; --$i) {
381 my $sub_mailbox = "$mb_top.$i";
382 last if exists $mailboxes->{$sub_mailbox};
383 $mailboxes->{$sub_mailbox} = $ibx;
384 $sub_mailbox =~ s/\Ainbox\./INBOX./i; # more familiar to users
385 push @created, $sub_mailbox;
387 return unless @created;
388 my $l = $imapd->{inboxlist} or return;
389 push @$l, map { qq[* LIST (\\HasNoChildren) "." $_\r\n] } @created;
392 sub inbox_lookup ($$;$) {
393 my ($self, $mailbox, $examine) = @_;
394 my ($ibx, $exists, $uidmax, $uid_base) = (undef, 0, 0, 0);
395 $mailbox = lc $mailbox;
396 $ibx = $self->{imapd}->{mailboxes}->{$mailbox} or return;
397 my $over = $ibx->over;
398 if ($over != $ibx) { # not a dummy
399 $mailbox =~ /\.([0-9]+)\z/ or
400 die "BUG: unexpected dummy mailbox: $mailbox\n";
401 $uid_base = $1 * UID_SLICE;
403 # ->num_highwater caches for writers, so use ->meta_accessor
404 $uidmax = $ibx->mm->meta_accessor('num_highwater') // 0;
406 $self->{uid_base} = $uid_base;
408 $self->{uo2m} = uo2m_ary_new($self, \$exists);
410 $exists = $over->imap_exists;
412 ensure_slices_exist($self->{imapd}, $ibx, $over->max);
415 $self->{uid_base} = $uid_base;
417 delete $self->{uo2m};
419 # if "INBOX.foo.bar" is selected and "INBOX.foo.bar.0",
420 # check for new UID ranges (e.g. "INBOX.foo.bar.1")
421 if (my $z = $self->{imapd}->{mailboxes}->{"$mailbox.0"}) {
422 ensure_slices_exist($self->{imapd}, $z, $z->over->max);
425 ($ibx, $exists, $uidmax + 1, $uid_base);
428 sub cmd_examine ($$$) {
429 my ($self, $tag, $mailbox) = @_;
430 # XXX: do we need this? RFC 5162/7162
431 my $ret = $self->{ibx} ? "* OK [CLOSED] previous closed\r\n" : '';
432 my ($ibx, $exists, $uidnext, $base) = inbox_lookup($self, $mailbox, 1);
433 return "$tag NO Mailbox doesn't exist: $mailbox\r\n" if !$ibx;
438 * OK [PERMANENTFLAGS ()] Read-only mailbox\r
439 * OK [UNSEEN $exists]\r
440 * OK [UIDNEXT $uidnext]\r
441 * OK [UIDVALIDITY $ibx->{uidvalidity}]\r
442 $tag OK [READ-ONLY] EXAMINE/SELECT done\r
450 } elsif ($v =~ /[{"\r\n%*\\\[]/) { # literal string
451 '{' . length($v) . "}\r\n" . $v;
452 } else { # quoted string
457 sub addr_envelope ($$;$) {
458 my ($eml, $x, $y) = @_;
459 my $v = $eml->header_raw($x) //
460 ($y ? $eml->header_raw($y) : undef) // return 'NIL';
462 my @x = $Address->parse($v) or return 'NIL';
464 map { '(' . join(' ',
465 _esc($_->name), 'NIL',
466 _esc($_->user), _esc($_->host)
472 sub eml_envelope ($) {
475 _esc($eml->header_raw('Date')),
476 _esc($eml->header_raw('Subject')),
477 addr_envelope($eml, 'From'),
478 addr_envelope($eml, 'Sender', 'From'),
479 addr_envelope($eml, 'Reply-To', 'From'),
480 addr_envelope($eml, 'To'),
481 addr_envelope($eml, 'Cc'),
482 addr_envelope($eml, 'Bcc'),
483 _esc($eml->header_raw('In-Reply-To')),
484 _esc($eml->header_raw('Message-ID')),
490 if ($hash && scalar keys %$hash) {
491 $hash = [ %$hash ]; # flatten hash into 1-dimensional array
492 '(' . join(' ', map { _esc($_) } @$hash) . ')';
498 sub body_disposition ($) {
500 my $cd = $eml->header_raw('Content-Disposition') or return 'NIL';
501 $cd = parse_content_disposition($cd);
502 my $buf = '('._esc($cd->{type});
503 $buf .= ' ' . _esc_hash(delete $cd->{attributes});
507 sub body_leaf ($$;$) {
508 my ($eml, $structure, $hold) = @_;
510 $eml->{is_submsg} and # parent was a message/(rfc822|news|global)
511 $buf .= eml_envelope($eml). ' ';
513 $buf .= '('._esc($ct->{type}).' ';
514 $buf .= _esc($ct->{subtype});
515 $buf .= ' ' . _esc_hash(delete $ct->{attributes});
516 $buf .= ' ' . _esc($eml->header_raw('Content-ID'));
517 $buf .= ' ' . _esc($eml->header_raw('Content-Description'));
518 my $cte = $eml->header_raw('Content-Transfer-Encoding') // '7bit';
519 $buf .= ' ' . _esc($cte);
520 $buf .= ' ' . $eml->{imap_body_len};
521 $buf .= ' '.($eml->body_raw =~ tr/\n/\n/) if lc($ct->{type}) eq 'text';
523 # for message/(rfc822|global|news), $hold[0] should have envelope
524 $buf .= ' ' . (@$hold ? join('', @$hold) : 'NIL') if $hold;
527 $buf .= ' '._esc($eml->header_raw('Content-MD5'));
528 $buf .= ' '. body_disposition($eml);
529 $buf .= ' '._esc($eml->header_raw('Content-Language'));
530 $buf .= ' '._esc($eml->header_raw('Content-Location'));
535 sub body_parent ($$$) {
536 my ($eml, $structure, $hold) = @_;
538 my $type = lc($ct->{type});
539 if ($type eq 'multipart') {
541 $buf .= @$hold ? join('', @$hold) : 'NIL';
542 $buf .= ' '._esc($ct->{subtype});
544 $buf .= ' '._esc_hash(delete $ct->{attributes});
545 $buf .= ' '.body_disposition($eml);
546 $buf .= ' '._esc($eml->header_raw('Content-Language'));
547 $buf .= ' '._esc($eml->header_raw('Content-Location'));
551 } else { # message/(rfc822|global|news)
552 @$hold = (body_leaf($eml, $structure, $hold));
556 # this is gross, but we need to process the parent part AFTER
557 # the child parts are done
558 sub bodystructure_prep {
560 my ($eml, $depth) = @$p; # ignore idx
561 # set length here, as $eml->{bdy} gets deleted for message/rfc822
562 $eml->{imap_body_len} = length($eml->body_raw);
563 push @$q, $eml, $depth;
566 # for FETCH BODY and FETCH BODYSTRUCTURE
567 sub fetch_body ($;$) {
568 my ($eml, $structure) = @_;
570 $eml->each_part(\&bodystructure_prep, \@q, 0, 1);
574 my ($part, $depth) = splice(@q, -2);
575 my $is_mp_parent = $depth == ($cur_depth - 1);
579 body_parent($part, $structure, \@hold);
581 unshift @hold, body_leaf($part, $structure);
587 sub requeue_once ($) {
589 # COMPRESS users all share the same DEFLATE context.
590 # Flush it here to ensure clients don't see
594 # no recursion, schedule another call ASAP,
595 # but only after all pending writes are done.
597 my $new_size = push(@{$self->{wbuf}}, \&long_step);
599 # wbuf may be populated by $cb, no need to rearm if so:
600 $self->requeue if $new_size == 1;
604 my ($self, $smsg, $bref, $ops, $partial) = @_;
605 my $uid = $smsg->{num};
606 $self->msg_more('* '.uid2msn($self, $uid)." FETCH (UID $uid");
608 for (my $i = 0; $i < @$ops;) {
610 $ops->[$i++]->($self, $k, $smsg, $bref, $eml);
612 partial_emit($self, $partial, $eml) if $partial;
613 $self->msg_more(")\r\n");
616 sub fetch_blob_cb { # called by git->cat_async via git_async_cat
617 my ($bref, $oid, $type, $size, $fetch_arg) = @_;
618 my ($self, undef, $msgs, $range_info, $ops, $partial) = @$fetch_arg;
619 my $smsg = shift @$msgs or die 'BUG: no smsg';
620 if (!defined($oid)) {
621 # it's possible to have TOCTOU if an admin runs
622 # public-inbox-(edit|purge), just move onto the next message
623 return requeue_once($self);
625 $smsg->{blob} eq $oid or die "BUG: $smsg->{blob} != $oid";
627 fetch_run_ops($self, $smsg, $bref, $ops, $partial);
632 my ($self, $k, undef, $bref) = @_;
633 $self->msg_more(" $k {" . length($$bref)."}\r\n");
634 $self->msg_more($$bref);
637 # Mail::IMAPClient::message_string cares about this by default,
638 # (->Ignoresizeerrors attribute). Admins are encouraged to
639 # --reindex for IMAP support, anyways.
640 sub emit_rfc822_size {
641 my ($self, $k, $smsg) = @_;
642 $self->msg_more(' RFC822.SIZE ' . $smsg->{bytes});
645 sub emit_internaldate {
646 my ($self, undef, $smsg) = @_;
647 $self->msg_more(' INTERNALDATE "'.$smsg->internaldate.'"');
650 sub emit_flags { $_[0]->msg_more(' FLAGS ()') }
653 my ($self, undef, undef, undef, $eml) = @_;
654 $self->msg_more(' ENVELOPE '.eml_envelope($eml));
657 sub emit_rfc822_header {
658 my ($self, $k, undef, undef, $eml) = @_;
659 $self->msg_more(" $k {".length(${$eml->{hdr}})."}\r\n");
660 $self->msg_more(${$eml->{hdr}});
663 # n.b. this is sorted to be after any emit_eml_new ops
664 sub emit_rfc822_text {
665 my ($self, $k, undef, $bref) = @_;
666 $self->msg_more(" $k {".length($$bref)."}\r\n");
667 $self->msg_more($$bref);
670 sub emit_bodystructure {
671 my ($self, undef, undef, undef, $eml) = @_;
672 $self->msg_more(' BODYSTRUCTURE '.fetch_body($eml, 1));
676 my ($self, undef, undef, undef, $eml) = @_;
677 $self->msg_more(' BODY '.fetch_body($eml));
680 # set $eml once ($_[4] == $eml, $_[3] == $bref)
681 sub op_eml_new { $_[4] = PublicInbox::Eml->new($_[3]) }
683 # s/From / fixes old bug from import (pre-a0c07cba0e5d8b6a)
685 ${$_[0]} =~ s/(?<!\r)\n/\r\n/sg;
686 ${$_[0]} =~ s/\A[\r\n]*From [^\r\n]*\r\n//s;
689 sub op_crlf_bref { to_crlf_full($_[3]) }
691 sub op_crlf_hdr { to_crlf_full($_[4]->{hdr}) }
693 sub op_crlf_bdy { ${$_[4]->{bdy}} =~ s/(?<!\r)\n/\r\n/sg if $_[4]->{bdy} }
695 sub uid_clamp ($$$) {
696 my ($self, $beg, $end) = @_;
697 my $uid_min = $self->{uid_base} + 1;
698 my $uid_end = $uid_min + UID_SLICE - 1;
699 $$beg = $uid_min if $$beg < $uid_min;
700 $$end = $uid_end if $$end > $uid_end;
703 sub range_step ($$) {
704 my ($self, $range_csv) = @_;
705 my ($beg, $end, $range);
706 if ($$range_csv =~ s/\A([^,]+),//) {
709 $range = $$range_csv;
712 my $uid_base = $self->{uid_base};
713 my $uid_end = $uid_base + UID_SLICE;
714 if ($range =~ /\A([0-9]+):([0-9]+)\z/) {
715 ($beg, $end) = ($1 + 0, $2 + 0);
716 uid_clamp($self, \$beg, \$end);
717 } elsif ($range =~ /\A([0-9]+):\*\z/) {
719 $end = $self->{ibx}->over->max;
720 $end = $uid_end if $end > $uid_end;
721 $beg = $end if $beg > $end;
722 uid_clamp($self, \$beg, \$end);
723 } elsif ($range =~ /\A[0-9]+\z/) {
724 $beg = $end = $range + 0;
725 # just let the caller do an out-of-range query if a single
726 # UID is out-of-range
727 ++$beg if ($beg <= $uid_base || $end > $uid_end);
729 return 'BAD fetch range';
731 [ $beg, $end, $$range_csv ];
734 sub refill_range ($$$) {
735 my ($self, $msgs, $range_info) = @_;
736 my ($beg, $end, $range_csv) = @$range_info;
737 if (scalar(@$msgs = @{$self->{ibx}->over->query_xover($beg, $end)})) {
738 $range_info->[0] = $msgs->[-1]->{num} + 1;
741 return 'OK Fetch done' if !$range_csv;
742 my $next_range = range_step($self, \$range_csv);
743 return $next_range if !ref($next_range); # error
744 @$range_info = @$next_range;
745 undef; # keep looping
748 sub fetch_blob { # long_response
749 my ($self, $tag, $msgs, $range_info, $ops, $partial) = @_;
750 while (!@$msgs) { # rare
751 if (my $end = refill_range($self, $msgs, $range_info)) {
752 $self->write(\"$tag $end\r\n");
756 uo2m_extend($self, $msgs->[-1]->{num});
757 git_async_cat($self->{ibx}->git, $msgs->[0]->{blob},
758 \&fetch_blob_cb, \@_);
761 sub fetch_smsg { # long_response
762 my ($self, $tag, $msgs, $range_info, $ops) = @_;
763 while (!@$msgs) { # rare
764 if (my $end = refill_range($self, $msgs, $range_info)) {
765 $self->write(\"$tag $end\r\n");
769 uo2m_extend($self, $msgs->[-1]->{num});
770 fetch_run_ops($self, $_, undef, $ops) for @$msgs;
775 sub refill_uids ($$$;$) {
776 my ($self, $uids, $range_info, $sql) = @_;
777 my ($beg, $end, $range_csv) = @$range_info;
778 my $over = $self->{ibx}->over;
780 if (scalar(@$uids = @{$over->uid_range($beg, $end, $sql)})) {
781 $range_info->[0] = $uids->[-1] + 1; # update $beg
783 } elsif (!$range_csv) {
786 my $next_range = range_step($self, \$range_csv);
787 return $next_range if !ref($next_range); # error
788 ($beg, $end, $range_csv) = @$range_info = @$next_range;
794 sub fetch_uid { # long_response
795 my ($self, $tag, $uids, $range_info, $ops) = @_;
796 if (defined(my $err = refill_uids($self, $uids, $range_info))) {
797 $err ||= 'OK Fetch done';
798 $self->write("$tag $err\r\n");
801 my $adj = $self->{uid_base} + 1;
802 my $uo2m = uo2m_extend($self, $uids->[-1]);
803 $uo2m = [ unpack('S*', $uo2m) ] if !ref($uo2m);
806 $self->msg_more("* $uo2m->[$_ - $adj] FETCH (UID $_");
807 for ($i = 0; $i < @$ops;) {
809 $ops->[$i++]->($self, $k);
811 $self->msg_more(")\r\n");
817 sub cmd_status ($$$;@) {
818 my ($self, $tag, $mailbox, @items) = @_;
819 return "$tag BAD no items\r\n" if !scalar(@items);
820 ($items[0] !~ s/\A\(//s || $items[-1] !~ s/\)\z//s) and
821 return "$tag BAD invalid args\r\n";
822 my ($ibx, $exists, $uidnext) = inbox_lookup($self, $mailbox);
823 return "$tag NO Mailbox doesn't exist: $mailbox\r\n" if !$ibx;
825 for my $it (@items) {
828 if ($it =~ /\A(?:MESSAGES|UNSEEN|RECENT)\z/) {
830 } elsif ($it eq 'UIDNEXT') {
832 } elsif ($it eq 'UIDVALIDITY') {
833 push @it, $ibx->{uidvalidity};
835 return "$tag BAD invalid item\r\n";
838 return "$tag BAD no items\r\n" if !@it;
839 "* STATUS $mailbox (".join(' ', @it).")\r\n" .
840 "$tag OK Status done\r\n";
843 my %patmap = ('*' => '.*', '%' => '[^\.]*');
844 sub cmd_list ($$$$) {
845 my ($self, $tag, $refname, $wildcard) = @_;
846 my $l = $self->{imapd}->{inboxlist};
847 if ($refname eq '' && $wildcard eq '') {
848 # request for hierarchy delimiter
849 $l = [ qq[* LIST (\\Noselect) "." ""\r\n] ];
850 } elsif ($refname ne '' || $wildcard ne '*') {
851 $wildcard =~ s!([^a-z0-9_])!$patmap{$1} // "\Q$1"!egi;
852 $l = [ grep(/ \Q$refname\E$wildcard\r\n\z/is, @$l) ];
854 \(join('', @$l, "$tag OK List done\r\n"));
857 sub cmd_lsub ($$$$) {
858 my (undef, $tag) = @_; # same args as cmd_list
859 "$tag OK Lsub done\r\n";
862 sub eml_index_offs_i { # PublicInbox::Eml::each_part callback
864 my ($eml, undef, $idx) = @$p;
865 if ($idx && lc($eml->ct->{type}) eq 'multipart') {
866 $eml->{imap_bdy} = $eml->{bdy} // \'';
868 $all->{$idx} = $eml; # $idx => Eml
871 # prepares an index for BODY[$SECTION_IDX] fetches
872 sub eml_body_idx ($$) {
873 my ($eml, $section_idx) = @_;
874 my $idx = $eml->{imap_all_parts} //= do {
876 $eml->each_part(\&eml_index_offs_i, $all, 0, 1);
877 # top-level of multipart, BODY[0] not allowed (nz-number)
881 $idx->{$section_idx};
884 # BODY[($SECTION_IDX)?(.$SECTION_NAME)?]<$offset.$bytes>
886 my ($eml, $section_idx, $section_name) = @_;
887 if (defined $section_idx) {
888 $eml = eml_body_idx($eml, $section_idx) or return;
890 if (defined $section_name) {
891 if ($section_name eq 'MIME') {
892 # RFC 3501 6.4.5 states:
893 # The MIME part specifier MUST be prefixed
894 # by one or more numeric part specifiers
895 return unless defined $section_idx;
896 return $eml->header_obj->as_string . "\r\n";
898 my $bdy = $eml->{bdy} // $eml->{imap_bdy} // \'';
899 $eml = PublicInbox::Eml->new($$bdy);
900 if ($section_name eq 'TEXT') {
901 return $eml->body_raw;
902 } elsif ($section_name eq 'HEADER') {
903 return $eml->header_obj->as_string . "\r\n";
905 die "BUG: bad section_name=$section_name";
908 ${$eml->{bdy} // $eml->{imap_bdy} // \''};
911 # similar to what's in PublicInbox::Eml::re_memo, but doesn't memoize
912 # to avoid OOM with malicious users
913 sub hdrs_regexp ($) {
915 my $names = join('|', map { "\Q$_" } split(/[ \t]+/, $hdrs));
916 qr/^(?:$names):[ \t]*[^\n]*\r?\n # 1st line
917 # continuation lines:
918 (?:[^:\n]*?[ \t]+[^\n]*\r?\n)*
922 # BODY[($SECTION_IDX.)?HEADER.FIELDS.NOT ($HDRS)]<$offset.$bytes>
923 sub partial_hdr_not {
924 my ($eml, $section_idx, $hdrs_re) = @_;
925 if (defined $section_idx) {
926 $eml = eml_body_idx($eml, $section_idx) or return;
928 my $str = $eml->header_obj->as_string;
929 $str =~ s/$hdrs_re//g;
930 $str =~ s/(?<!\r)\n/\r\n/sg;
934 # BODY[($SECTION_IDX.)?HEADER.FIELDS ($HDRS)]<$offset.$bytes>
935 sub partial_hdr_get {
936 my ($eml, $section_idx, $hdrs_re) = @_;
937 if (defined $section_idx) {
938 $eml = eml_body_idx($eml, $section_idx) or return;
940 my $str = $eml->header_obj->as_string;
941 $str = join('', ($str =~ m/($hdrs_re)/g));
942 $str =~ s/(?<!\r)\n/\r\n/sg;
946 sub partial_prepare ($$$$) {
947 my ($need, $partial, $want, $att) = @_;
949 # recombine [ "BODY[1.HEADER.FIELDS", "(foo", "bar)]" ]
950 # back to: "BODY[1.HEADER.FIELDS (foo bar)]"
951 return unless $att =~ /\ABODY\[/s;
952 until (rindex($att, ']') >= 0) {
953 my $next = shift @$want or return;
954 $att .= ' ' . uc($next);
956 if ($att =~ /\ABODY\[([0-9]+(?:\.[0-9]+)*)? # 1 - section_idx
957 (?:\.(HEADER|MIME|TEXT))? # 2 - section_name
958 \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 3, 4
959 $partial->{$att} = [ \&partial_body, $1, $2, $3, $4 ];
960 $$need |= CRLF_BREF|EML_HDR|EML_BDY;
961 } elsif ($att =~ /\ABODY\[(?:([0-9]+(?:\.[0-9]+)*)\.)? # 1 - section_idx
962 (?:HEADER\.FIELDS(\.NOT)?)\x20 # 2
963 \(([A-Z0-9\-\x20]+)\) # 3 - hdrs
964 \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 4 5
965 my $tmp = $partial->{$att} = [ $2 ? \&partial_hdr_not
968 $tmp->[2] = hdrs_regexp($3);
970 # don't emit CRLF_HDR instruction, here, partial_hdr_*
971 # will do CRLF conversion with only the extracted result
972 # and not waste time converting lines we don't care about.
979 sub partial_emit ($$$) {
980 my ($self, $partial, $eml) = @_;
982 my ($k, $cb, @args) = @$_;
983 my ($offset, $len) = splice(@args, -2);
984 # $cb is partial_body|partial_hdr_get|partial_hdr_not
985 my $str = $cb->($eml, @args) // '';
986 if (defined $offset) {
988 $str = substr($str, $offset, $len);
989 $k =~ s/\.$len>\z/>/ or warn
990 "BUG: unable to remove `.$len>' from `$k'";
992 $str = substr($str, $offset);
998 $self->msg_more(" $k {$len}\r\n");
999 $self->msg_more($str);
1003 sub fetch_compile ($) {
1005 if ($want->[0] =~ s/\A\(//s) {
1006 $want->[-1] =~ s/\)\z//s or return 'BAD no rparen';
1008 my (%partial, %seen, @op);
1010 while (defined(my $att = shift @$want)) {
1012 next if $att eq 'UID'; # always returned
1013 $att =~ s/\ABODY\.PEEK\[/BODY\[/; # we're read-only
1014 my $x = $FETCH_ATT{$att};
1016 while (my ($k, $fl_cb) = each %$x) {
1017 next if $seen{$k}++;
1018 $need |= $fl_cb->[0];
1019 push @op, [ @$fl_cb, $k ];
1021 } elsif (!partial_prepare(\$need, \%partial, $want, $att)) {
1022 return "BAD param: $att";
1027 # stabilize partial order for consistency and ease-of-debugging:
1028 if (scalar keys %partial) {
1030 $r[2] = [ map { [ $_, @{$partial{$_}} ] } sort keys %partial ];
1033 push @op, $OP_EML_NEW if ($need & (EML_HDR|EML_BDY));
1035 # do we need CRLF conversion?
1036 if ($need & CRLF_BREF) {
1037 push @op, $OP_CRLF_BREF;
1038 } elsif (my $crlf = ($need & (CRLF_HDR|CRLF_BDY))) {
1039 if ($crlf == (CRLF_HDR|CRLF_BDY)) {
1040 push @op, $OP_CRLF_BREF;
1041 } elsif ($need & CRLF_HDR) {
1042 push @op, $OP_CRLF_HDR;
1044 push @op, $OP_CRLF_BDY;
1048 $r[0] = $need & NEED_BLOB ? \&fetch_blob :
1049 ($need & NEED_SMSG ? \&fetch_smsg : \&fetch_uid);
1051 # r[1] = [ $key1, $cb1, $key2, $cb2, ... ]
1052 use sort 'stable'; # makes output more consistent
1053 $r[1] = [ map { ($_->[2], $_->[1]) } sort { $a->[0] <=> $b->[0] } @op ];
1057 sub cmd_uid_fetch ($$$$;@) {
1058 my ($self, $tag, $range_csv, @want) = @_;
1059 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1060 my ($cb, $ops, $partial) = fetch_compile(\@want);
1061 return "$tag $cb\r\n" unless $ops;
1063 # cb is one of fetch_blob, fetch_smsg, fetch_uid
1064 $range_csv = 'bad' if $range_csv !~ $valid_range;
1065 my $range_info = range_step($self, \$range_csv);
1066 return "$tag $range_info\r\n" if !ref($range_info);
1067 uo2m_hibernate($self) if $cb == \&fetch_blob; # slow, save RAM
1068 long_response($self, $cb, $tag, [], $range_info, $ops, $partial);
1071 sub cmd_fetch ($$$$;@) {
1072 my ($self, $tag, $range_csv, @want) = @_;
1073 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1074 my ($cb, $ops, $partial) = fetch_compile(\@want);
1075 return "$tag $cb\r\n" unless $ops;
1077 # cb is one of fetch_blob, fetch_smsg, fetch_uid
1078 $range_csv = 'bad' if $range_csv !~ $valid_range;
1079 msn_to_uid_range(msn2uid($self), $range_csv);
1080 my $range_info = range_step($self, \$range_csv);
1081 return "$tag $range_info\r\n" if !ref($range_info);
1082 uo2m_hibernate($self) if $cb == \&fetch_blob; # slow, save RAM
1083 long_response($self, $cb, $tag, [], $range_info, $ops, $partial);
1086 sub msn_convert ($$) {
1087 my ($self, $uids) = @_;
1088 my $adj = $self->{uid_base} + 1;
1089 my $uo2m = uo2m_extend($self, $uids->[-1]);
1090 $uo2m = [ unpack('S*', $uo2m) ] if !ref($uo2m);
1091 $_ = $uo2m->[$_ - $adj] for @$uids;
1094 sub search_uid_range { # long_response
1095 my ($self, $tag, $sql, $range_info, $want_msn) = @_;
1097 if (defined(my $err = refill_uids($self, $uids, $range_info, $sql))) {
1098 $err ||= 'OK Search done';
1099 $self->write("\r\n$tag $err\r\n");
1102 msn_convert($self, $uids) if $want_msn;
1103 $self->msg_more(join(' ', '', @$uids));
1108 my ($q, $k, $d) = @_;
1109 my $sql = $q->{sql};
1112 if ($k eq 'SENTON') {
1113 my $end = $d + 86399; # no leap day...
1114 my $da = strftime('%Y%m%d%H%M%S', gmtime($d));
1115 my $db = strftime('%Y%m%d%H%M%S', gmtime($end));
1116 $q->{xap} .= " dt:$da..$db";
1117 $$sql .= " AND ds >= $d AND ds <= $end" if defined($sql);
1118 } elsif ($k eq 'SENTBEFORE') {
1119 $q->{xap} .= ' d:..'.strftime('%Y%m%d', gmtime($d));
1120 $$sql .= " AND ds <= $d" if defined($sql);
1121 } elsif ($k eq 'SENTSINCE') {
1122 $q->{xap} .= ' d:'.strftime('%Y%m%d', gmtime($d)).'..';
1123 $$sql .= " AND ds >= $d" if defined($sql);
1125 # INTERNALDATE (Received)
1126 } elsif ($k eq 'ON') {
1127 my $end = $d + 86399; # no leap day...
1128 $q->{xap} .= " ts:$d..$end";
1129 $$sql .= " AND ts >= $d AND ts <= $end" if defined($sql);
1130 } elsif ($k eq 'BEFORE') {
1131 $q->{xap} .= " ts:..$d";
1132 $$sql .= " AND ts <= $d" if defined($sql);
1133 } elsif ($k eq 'SINCE') {
1134 $q->{xap} .= " ts:$d..";
1135 $$sql .= " AND ts >= $d" if defined($sql);
1137 die "BUG: $k not recognized";
1141 # IMAP to Xapian search key mapping
1146 TEXT => '', # n.b. does not include all headers
1149 # BCC => 'bcc:', # TODO
1150 # KEYWORD # TODO ? dfpre,dfpost,...
1153 # IMAP allows searching arbitrary headers via "HEADER $HDR_NAME $HDR_VAL"
1154 # which gets silly expensive. We only allow the headers we already index.
1155 my %H2X = (%I2X, 'MESSAGE-ID' => 'm:', 'LIST-ID' => 'l:');
1157 sub xap_append ($$$$) {
1158 my ($q, $rest, $k, $xk) = @_;
1159 delete $q->{sql}; # can't use over.sqlite3
1160 defined(my $arg = shift @$rest) or return "BAD $k no arg";
1162 # AFAIK Xapian can't handle [*"] in probabilistic terms
1164 ${$q->{xap}} .= qq[ $xk"$arg"];
1168 sub parse_query ($$) {
1169 my ($self, $query) = @_;
1170 my $q = PublicInbox::IMAPsearchqp::parse($self, $query);
1172 my $max = $self->{ibx}->over->max;
1174 uid_clamp($self, \$beg, \$max);
1175 $q->{range_info} = [ $beg, $max ];
1180 sub refill_xap ($$$$) {
1181 my ($self, $uids, $range_info, $q) = @_;
1182 my ($beg, $end) = @$range_info;
1183 my $srch = $self->{ibx}->search;
1184 my $opt = { mset => 2, limit => 1000 };
1185 my $nshard = $srch->{nshard} // 1;
1186 my $mset = $srch->query("$q uid:$beg..$end", $opt);
1187 @$uids = map { mdocid($nshard, $_) } $mset->items;
1189 $range_info->[0] = $uids->[-1] + 1; # update $beg
1190 return; # possibly more
1195 sub search_xap_range { # long_response
1196 my ($self, $tag, $q, $range_info, $want_msn) = @_;
1198 if (defined(my $err = refill_xap($self, $uids, $range_info, $q))) {
1199 $err ||= 'OK Search done';
1200 $self->write("\r\n$tag $err\r\n");
1203 msn_convert($self, $uids) if $want_msn;
1204 $self->msg_more(join(' ', '', @$uids));
1209 my ($self, $tag, $query, $want_msn) = @_;
1210 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1211 my $q = parse_query($self, $query);
1212 return "$tag $q\r\n" if !ref($q);
1213 my ($sql, $range_info) = delete @$q{qw(sql range_info)};
1214 if (!scalar(keys %$q)) { # overview.sqlite3
1215 $self->msg_more('* SEARCH');
1216 long_response($self, \&search_uid_range,
1217 $tag, $sql, $range_info, $want_msn);
1218 } elsif ($q = $q->{xap}) {
1219 $self->{ibx}->search or
1220 return "$tag BAD search not available for mailbox\r\n";
1221 $self->msg_more('* SEARCH');
1222 long_response($self, \&search_xap_range,
1223 $tag, $q, $range_info, $want_msn);
1225 "$tag BAD Error\r\n";
1229 sub cmd_uid_search ($$$) {
1230 my ($self, $tag, $query) = @_;
1231 search_common($self, $tag, $query);
1234 sub cmd_search ($$$;) {
1235 my ($self, $tag, $query) = @_;
1236 search_common($self, $tag, $query, 1);
1239 sub args_ok ($$) { # duplicated from PublicInbox::NNTP
1240 my ($cb, $argc) = @_;
1241 my $tot = prototype $cb;
1242 my ($nreq, undef) = split(';', $tot);
1243 $nreq = ($nreq =~ tr/$//) - 1;
1244 $tot = ($tot =~ tr/$//) - 1;
1245 ($argc <= $tot && $argc >= $nreq);
1248 # returns 1 if we can continue, 0 if not due to buffered writes or disconnect
1249 sub process_line ($$) {
1250 my ($self, $l) = @_;
1252 # TODO: IMAP allows literals for big requests to upload messages
1253 # (which we don't support) but maybe some big search queries use it.
1254 # RFC 3501 9 (2) doesn't permit TAB or multiple SP
1255 my ($tag, $req, @args) = parse_line('[ \t]+', 0, $l);
1256 pop(@args) if (@args && !defined($args[-1]));
1257 if (@args && uc($req) eq 'UID') {
1258 $req .= "_".(shift @args);
1261 if (defined(my $idle_tag = $self->{-idle_tag})) {
1262 (uc($tag // '') eq 'DONE' && !defined($req)) ?
1263 idle_done($self, $tag) :
1264 "$idle_tag BAD expected DONE\r\n";
1265 } elsif (my $cmd = $self->can('cmd_'.lc($req // ''))) {
1266 if ($cmd == \&cmd_uid_search || $cmd == \&cmd_search) {
1267 # preserve user-supplied quotes for search
1268 (undef, @args) = split(/ search /i, $l, 2);
1270 $cmd->($self, $tag, @args);
1271 } else { # this is weird
1272 auth_challenge_ok($self) //
1274 ' BAD Error in IMAP command '.
1276 ": Unknown command\r\n";
1280 if ($err && $self->{sock}) {
1282 err($self, 'error from: %s (%s)', $l, $err);
1284 $res = "$tag BAD program fault - command not performed\r\n";
1286 return 0 unless defined $res;
1292 # wbuf is unset or empty, here; {long} may add to it
1293 my ($fd, $cb, $t0, @args) = @{$self->{long_cb}};
1294 my $more = eval { $cb->($self, @args) };
1295 if ($@ || !$self->{sock}) { # something bad happened...
1296 delete $self->{long_cb};
1297 my $elapsed = now() - $t0;
1300 "%s during long response[$fd] - %0.6f",
1303 out($self, " deferred[$fd] aborted - %0.6f", $elapsed);
1305 } elsif ($more) { # $self->{wbuf}:
1306 $self->update_idle_time;
1308 # control passed to git_async_cat if $more == \undef
1309 requeue_once($self) if !ref($more);
1310 } else { # all done!
1311 delete $self->{long_cb};
1312 my $elapsed = now() - $t0;
1313 my $fd = fileno($self->{sock});
1314 out($self, " deferred[$fd] done - %0.6f", $elapsed);
1315 my $wbuf = $self->{wbuf}; # do NOT autovivify
1317 $self->requeue unless $wbuf && @$wbuf;
1322 my ($self, $fmt, @args) = @_;
1323 printf { $self->{imapd}->{err} } $fmt."\n", @args;
1327 my ($self, $fmt, @args) = @_;
1328 printf { $self->{imapd}->{out} } $fmt."\n", @args;
1331 sub long_response ($$;@) {
1332 my ($self, $cb, @args) = @_; # cb returns true if more, false if done
1334 my $sock = $self->{sock} or return;
1335 # make sure we disable reading during a long response,
1336 # clients should not be sending us stuff and making us do more
1337 # work while we are stream a response to them
1338 $self->{long_cb} = [ fileno($sock), $cb, now(), @args ];
1339 long_step($self); # kick off!
1343 # callback used by PublicInbox::DS for any (e)poll (in/out/hup/err)
1347 return unless $self->flush_write && $self->{sock} && !$self->{long_cb};
1349 $self->update_idle_time;
1350 # only read more requests if we've drained the write buffer,
1351 # otherwise we can be buffering infinitely w/o backpressure
1353 my $rbuf = $self->{rbuf} // \(my $x = '');
1354 my $line = index($$rbuf, "\n");
1356 if (length($$rbuf) >= LINE_MAX) {
1357 $self->write(\"\* BAD request too long\r\n");
1358 return $self->close;
1360 $self->do_read($rbuf, LINE_MAX, length($$rbuf)) or
1361 return uo2m_hibernate($self);
1362 $line = index($$rbuf, "\n");
1364 $line = substr($$rbuf, 0, $line + 1, '');
1365 $line =~ s/\r?\n\z//s;
1366 return $self->close if $line =~ /[[:cntrl:]]/s;
1368 my $fd = fileno($self->{sock});
1369 my $r = eval { process_line($self, $line) };
1370 my $pending = $self->{wbuf} ? ' pending' : '';
1371 out($self, "[$fd] %s - %0.6f$pending - $r", $line, now() - $t0);
1373 return $self->close if $r < 0;
1374 $self->rbuf_idle($rbuf);
1375 $self->update_idle_time;
1377 # maybe there's more pipelined data, or we'll have
1378 # to register it for socket-readiness notifications
1379 $self->requeue unless $pending;
1382 sub compressed { undef }
1384 sub zflush {} # overridden by IMAPdeflate
1387 sub cmd_compress ($$$) {
1388 my ($self, $tag, $alg) = @_;
1389 return "$tag BAD DEFLATE only\r\n" if uc($alg) ne "DEFLATE";
1390 return "$tag BAD COMPRESS active\r\n" if $self->compressed;
1392 # CRIME made TLS compression obsolete
1393 # return "$tag NO [COMPRESSIONACTIVE]\r\n" if $self->tls_compressed;
1395 PublicInbox::IMAPdeflate->enable($self, $tag);
1400 sub cmd_starttls ($$) {
1401 my ($self, $tag) = @_;
1402 my $sock = $self->{sock} or return;
1403 if ($sock->can('stop_SSL') || $self->compressed) {
1404 return "$tag BAD TLS or compression already enabled\r\n";
1406 my $opt = $self->{imapd}->{accept_tls} or
1407 return "$tag BAD can not initiate TLS negotiation\r\n";
1408 $self->write(\"$tag OK begin TLS negotiation now\r\n");
1409 $self->{sock} = IO::Socket::SSL->start_SSL($sock, %$opt);
1410 $self->requeue if PublicInbox::DS::accept_tls_step($self);
1414 # for graceful shutdown in PublicInbox::Daemon:
1416 my ($self, $now) = @_;
1417 if (defined($self->{-idle_tag})) {
1418 $self->write(\"* BYE server shutting down\r\n");
1419 return; # not busy anymore
1421 ($self->{rbuf} || $self->{wbuf} || $self->not_idle_long($now));
1426 if (my $ibx = delete $self->{ibx}) {
1427 stop_idle($self, $ibx);
1429 $self->SUPER::close; # PublicInbox::DS::close
1432 # we're read-only, so SELECT and EXAMINE do the same thing
1434 *cmd_select = \&cmd_examine;
1436 package PublicInbox::IMAP_preauth;
1437 our @ISA = qw(PublicInbox::IMAP);