1 # Copyright (C) 2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # Each instance of this represents an IMAP client connected to
5 # public-inbox-imapd. Much of this was taken from NNTP, but
6 # further refined while experimenting on future ideas to handle
11 # * NNTP article numbers are UIDs, mm->created_at is UIDVALIDITY
13 # * public-inboxes are sliced into mailboxes of 50K messages
14 # to not overload MUAs: $NEWSGROUP_NAME.$SLICE_INDEX
15 # Slices are similar in concept to v2 "epochs". Epochs
16 # are for the limitations of git clients, while slices are
17 # for the limitations of IMAP clients.
19 # * We also take advantage of slices being only 50K to store
20 # "UID offset" to message sequence number (MSN) mapping
21 # as a 50K uint16_t array (via pack("S*", ...)). "UID offset"
22 # is the offset from {uid_base} which determines the start of
26 # imapd: PublicInbox::IMAPD ref
27 # ibx: PublicInbox::Inbox ref
28 # long_cb: long_response private data
29 # uid_base: base UID for mailbox slice (0-based)
30 # -login_tag: IMAP TAG for LOGIN
31 # -idle_tag: IMAP response tag for IDLE
32 # uo2m: UID-to-MSN mapping
33 package PublicInbox::IMAP;
35 use parent qw(PublicInbox::DS);
37 use PublicInbox::EmlContentFoo qw(parse_content_disposition);
38 use PublicInbox::DS qw(now);
39 use PublicInbox::Syscall qw(EPOLLIN EPOLLONESHOT);
40 use PublicInbox::GitAsyncCat;
41 use Text::ParseWords qw(parse_line);
43 use PublicInbox::Search;
44 use PublicInbox::IMAPsearchqp;
45 *mdocid = \&PublicInbox::Search::mdocid;
48 for my $mod (qw(Email::Address::XS Mail::Address)) {
49 eval "require $mod" or next;
50 $Address = $mod and last;
52 die "neither Email::Address::XS nor Mail::Address loaded: $@" if !$Address;
54 sub LINE_MAX () { 8000 } # RFC 2683 3.2.1.5
56 # Changing UID_SLICE will cause grief for clients which cache.
57 # This also needs to be <64K: we pack it into a uint16_t
58 # for long_response UID (offset) => MSN mappings
59 sub UID_SLICE () { 50_000 }
61 # these values area also used for sorting
62 sub NEED_SMSG () { 1 }
63 sub NEED_BLOB () { NEED_SMSG|2 }
64 sub CRLF_BREF () { 4 }
66 sub CRLF_HDR () { 16 }
68 sub CRLF_BDY () { 64 }
69 my $OP_EML_NEW = [ EML_HDR - 1, \&op_eml_new ];
70 my $OP_CRLF_BREF = [ CRLF_BREF, \&op_crlf_bref ];
71 my $OP_CRLF_HDR = [ CRLF_HDR, \&op_crlf_hdr ];
72 my $OP_CRLF_BDY = [ CRLF_BDY, \&op_crlf_bdy ];
75 'BODY[HEADER]' => [ NEED_BLOB|EML_HDR|CRLF_HDR, \&emit_rfc822_header ],
76 'BODY[TEXT]' => [ NEED_BLOB|EML_BDY|CRLF_BDY, \&emit_rfc822_text ],
77 'BODY[]' => [ NEED_BLOB|CRLF_BREF, \&emit_rfc822 ],
78 'RFC822.HEADER' => [ NEED_BLOB|EML_HDR|CRLF_HDR, \&emit_rfc822_header ],
79 'RFC822.TEXT' => [ NEED_BLOB|EML_BDY|CRLF_BDY, \&emit_rfc822_text ],
80 'RFC822.SIZE' => [ NEED_SMSG, \&emit_rfc822_size ],
81 RFC822 => [ NEED_BLOB|CRLF_BREF, \&emit_rfc822 ],
82 BODY => [ NEED_BLOB|EML_HDR|EML_BDY, \&emit_body ],
83 BODYSTRUCTURE => [ NEED_BLOB|EML_HDR|EML_BDY, \&emit_bodystructure ],
84 ENVELOPE => [ NEED_BLOB|EML_HDR, \&emit_envelope ],
85 FLAGS => [ 0, \&emit_flags ],
86 INTERNALDATE => [ NEED_SMSG, \&emit_internaldate ],
88 my %FETCH_ATT = map { $_ => [ $_ ] } keys %FETCH_NEED;
90 # aliases (RFC 3501 section 6.4.5)
91 $FETCH_ATT{FAST} = [ qw(FLAGS INTERNALDATE RFC822.SIZE) ];
92 $FETCH_ATT{ALL} = [ @{$FETCH_ATT{FAST}}, 'ENVELOPE' ];
93 $FETCH_ATT{FULL} = [ @{$FETCH_ATT{ALL}}, 'BODY' ];
95 for my $att (keys %FETCH_ATT) {
96 my %h = map { $_ => $FETCH_NEED{$_} } @{$FETCH_ATT{$att}};
97 $FETCH_ATT{$att} = \%h;
101 my $valid_range = '[0-9]+|[0-9]+:[0-9]+|[0-9]+:\*';
102 $valid_range = qr/\A(?:$valid_range)(?:,(?:$valid_range))*\z/;
104 # RFC 3501 5.4. Autologout Timer needs to be >= 30min
105 $PublicInbox::DS::EXPTIME = 60 * 30;
109 my $capa = capa($self);
110 $self->write(\"* OK [$capa] public-inbox-imapd ready\r\n");
114 my ($class, $sock, $imapd) = @_;
115 my $self = bless { imapd => $imapd }, 'PublicInbox::IMAP_preauth';
118 if ($sock->can('accept_SSL') && !$sock->accept_SSL) {
119 return CORE::close($sock) if $! != EAGAIN;
120 $ev = PublicInbox::TLS::epollbit();
121 $wbuf = [ \&PublicInbox::DS::accept_tls_step, \&greet ];
123 $self->SUPER::new($sock, $ev | EPOLLONESHOT);
125 $self->{wbuf} = $wbuf;
129 $self->update_idle_time;
138 # dovecot advertises IDLE pre-login; perhaps because some clients
139 # depend on it, so we'll do the same
140 my $capa = 'CAPABILITY IMAP4rev1 IDLE';
141 if ($self->logged_in) {
142 $capa .= ' COMPRESS=DEFLATE';
144 if (!($self->{sock} // $self)->can('accept_SSL') &&
145 $self->{imapd}->{accept_tls}) {
146 $capa .= ' STARTTLS';
148 $capa .= ' AUTH=ANONYMOUS';
152 sub login_success ($$) {
153 my ($self, $tag) = @_;
154 bless $self, 'PublicInbox::IMAP';
155 my $capa = capa($self);
156 "$tag OK [$capa] Logged in\r\n";
159 sub auth_challenge_ok ($) {
161 my $tag = delete($self->{-login_tag}) or return;
162 login_success($self, $tag);
165 sub cmd_login ($$$$) {
166 my ($self, $tag) = @_; # ignore ($user, $password) = ($_[2], $_[3])
167 login_success($self, $tag);
171 my ($self, $tag) = @_;
172 delete @$self{qw(uid_base uo2m)};
173 delete $self->{ibx} ? "$tag OK Close done\r\n"
174 : "$tag BAD No mailbox\r\n";
177 sub cmd_logout ($$) {
178 my ($self, $tag) = @_;
179 delete $self->{-idle_tag};
180 $self->write(\"* BYE logging out\r\n$tag OK Logout done\r\n");
181 $self->shutdn; # PublicInbox::DS::shutdn
185 sub cmd_authenticate ($$$) {
186 my ($self, $tag) = @_; # $method = $_[2], should be "ANONYMOUS"
187 $self->{-login_tag} = $tag;
191 sub cmd_capability ($$) {
192 my ($self, $tag) = @_;
193 '* '.capa($self)."\r\n$tag OK Capability done\r\n";
196 # uo2m: UID Offset to MSN, this is an arrayref by default,
197 # but uo2m_hibernate can compact and deduplicate it
198 sub uo2m_ary_new ($;$) {
199 my ($self, $exists) = @_;
200 my $base = $self->{uid_base};
201 my $uids = $self->{ibx}->over->uid_range($base + 1, $base + UID_SLICE);
203 # convert UIDs to offsets from {base}
204 my @tmp; # [$UID_OFFSET] => $MSN
207 $tmp[$_ - $base] = ++$msn for @$uids;
208 $$exists = $msn if $exists;
212 # changes UID-offset-to-MSN mapping into a deduplicated scalar:
213 # uint16_t uo2m[UID_SLICE].
214 # May be swapped out for idle clients if THP is disabled.
215 sub uo2m_hibernate ($) {
217 ref(my $uo2m = $self->{uo2m}) or return;
218 my %dedupe = ( uo2m_pack($uo2m) => undef );
219 $self->{uo2m} = (keys(%dedupe))[0];
223 sub uo2m_last_uid ($) {
225 defined(my $uo2m = $self->{uo2m}) or die 'BUG: uo2m_last_uid w/o {uo2m}';
226 (ref($uo2m) ? @$uo2m : (length($uo2m) >> 1)) + $self->{uid_base};
230 # $_[0] is an arrayref of MSNs, it may have undef gaps if there
231 # are gaps in the corresponding UIDs: [ msn1, msn2, undef, msn3 ]
232 no warnings 'uninitialized';
233 pack('S*', @{$_[0]});
236 # extend {uo2m} to account for new messages which arrived since
237 # {uo2m} was created.
238 sub uo2m_extend ($$;$) {
239 my ($self, $new_uid_max) = @_;
240 defined(my $uo2m = $self->{uo2m}) or
241 return($self->{uo2m} = uo2m_ary_new($self));
242 my $beg = uo2m_last_uid($self); # last UID we've learned
243 return $uo2m if $beg >= $new_uid_max; # fast path
245 # need to extend the current range:
246 my $base = $self->{uid_base};
248 my $uids = $self->{ibx}->over->uid_range($beg, $base + UID_SLICE);
249 return $uo2m if !scalar(@$uids);
250 my @tmp; # [$UID_OFFSET] => $MSN
251 my $write_method = $_[2] // 'msg_more';
253 my $msn = $uo2m->[-1];
254 $tmp[$_ - $beg] = ++$msn for @$uids;
255 $self->$write_method("* $msn EXISTS\r\n");
259 my $msn = unpack('S', substr($uo2m, -2, 2));
260 $tmp[$_ - $beg] = ++$msn for @$uids;
261 $self->$write_method("* $msn EXISTS\r\n");
262 $uo2m .= uo2m_pack(\@tmp);
263 my %dedupe = ($uo2m => undef);
264 $self->{uo2m} = (keys %dedupe)[0];
269 my ($self, $tag) = @_;
270 defined($self->{uid_base}) and
271 uo2m_extend($self, $self->{uid_base} + UID_SLICE);
272 \"$tag OK Noop done\r\n";
275 # the flexible version which works on scalars and array refs.
276 # Must call uo2m_extend before this
278 my ($self, $uid) = @_;
279 my $uo2m = $self->{uo2m};
280 my $off = $uid - $self->{uid_base} - 1;
281 ref($uo2m) ? $uo2m->[$off] : unpack('S', substr($uo2m, $off << 1, 2));
284 # returns an arrayref of UIDs, so MSNs can be translated to UIDs via:
285 # $msn2uid->[$MSN-1] => $UID. The result of this is always ephemeral
286 # and does not live beyond the event loop.
289 my $base = $self->{uid_base};
290 my $uo2m = uo2m_extend($self, $base + UID_SLICE);
291 $uo2m = [ unpack('S*', $uo2m) ] if !ref($uo2m);
295 for my $msn (@$uo2m) {
297 $msn2uid[$msn - 1] = $uo + $base if $msn;
302 # converts a set of message sequence numbers in requests to UIDs:
303 sub msn_to_uid_range ($$) {
305 $_[1] =~ s!([0-9]+)!$msn2uid->[$1 - 1] // ($msn2uid->[-1] + 1)!sge;
308 # called by PublicInbox::InboxIdle
309 sub on_inbox_unlock {
310 my ($self, $ibx) = @_;
311 my $uid_end = $self->{uid_base} + UID_SLICE;
312 uo2m_extend($self, $uid_end, 'write');
313 my $new = uo2m_last_uid($self);
314 if ($new == $uid_end) { # max exceeded $uid_end
315 # continue idling w/o inotify
316 my $sock = $self->{sock} or return;
317 $ibx->unsubscribe_unlock(fileno($sock));
321 # called every X minute(s) or so by PublicInbox::DS::later
327 for my $i (values %$old) {
328 next if ($i->{wbuf} || !exists($i->{-idle_tag}));
329 $i->update_idle_time or next;
330 $IDLERS->{fileno($i->{sock})} = $i;
331 $i->write(\"* OK Still here\r\n");
333 $idle_timer = scalar keys %$IDLERS ?
334 PublicInbox::DS::later(\&idle_tick_all) : undef;
338 my ($self, $tag) = @_;
339 # IDLE seems allowed by dovecot w/o a mailbox selected *shrug*
340 my $ibx = $self->{ibx} or return "$tag BAD no mailbox selected\r\n";
341 my $uid_end = $self->{uid_base} + UID_SLICE;
342 uo2m_extend($self, $uid_end);
343 my $sock = $self->{sock} or return;
344 my $fd = fileno($sock);
345 $self->{-idle_tag} = $tag;
346 # only do inotify on most recent slice
347 if ($ibx->over->max < $uid_end) {
348 $ibx->subscribe_unlock($fd, $self);
349 $self->{imapd}->idler_start;
351 $idle_timer //= PublicInbox::DS::later(\&idle_tick_all);
352 $IDLERS->{$fd} = $self;
357 my ($self, $ibx) = @_;
358 my $sock = $self->{sock} or return;
359 my $fd = fileno($sock);
360 delete $IDLERS->{$fd};
361 $ibx->unsubscribe_unlock($fd);
365 my ($self, $tag) = @_; # $tag is "DONE" (case-insensitive)
366 defined(my $idle_tag = delete $self->{-idle_tag}) or
367 return "$tag BAD not idle\r\n";
368 my $ibx = $self->{ibx} or do {
369 warn "BUG: idle_tag set w/o inbox";
370 return "$tag BAD internal bug\r\n";
372 stop_idle($self, $ibx);
373 "$idle_tag OK Idle done\r\n";
376 sub ensure_slices_exist ($$$) {
377 my ($imapd, $ibx, $max) = @_;
378 defined(my $mb_top = $ibx->{newsgroup}) or return;
379 my $mailboxes = $imapd->{mailboxes};
381 for (my $i = int($max/UID_SLICE); $i >= 0; --$i) {
382 my $sub_mailbox = "$mb_top.$i";
383 last if exists $mailboxes->{$sub_mailbox};
384 $mailboxes->{$sub_mailbox} = $ibx;
385 $sub_mailbox =~ s/\Ainbox\./INBOX./i; # more familiar to users
386 push @created, $sub_mailbox;
388 return unless @created;
389 my $l = $imapd->{inboxlist} or return;
390 push @$l, map { qq[* LIST (\\HasNoChildren) "." $_\r\n] } @created;
393 sub inbox_lookup ($$;$) {
394 my ($self, $mailbox, $examine) = @_;
395 my ($ibx, $exists, $uidmax, $uid_base) = (undef, 0, 0, 0);
396 $mailbox = lc $mailbox;
397 $ibx = $self->{imapd}->{mailboxes}->{$mailbox} or return;
398 my $over = $ibx->over;
399 if ($over != $ibx) { # not a dummy
400 $mailbox =~ /\.([0-9]+)\z/ or
401 die "BUG: unexpected dummy mailbox: $mailbox\n";
402 $uid_base = $1 * UID_SLICE;
404 # ->num_highwater caches for writers, so use ->meta_accessor
405 $uidmax = $ibx->mm->meta_accessor('num_highwater') // 0;
407 $self->{uid_base} = $uid_base;
409 $self->{uo2m} = uo2m_ary_new($self, \$exists);
411 $exists = $over->imap_exists;
413 ensure_slices_exist($self->{imapd}, $ibx, $over->max);
416 $self->{uid_base} = $uid_base;
418 delete $self->{uo2m};
420 # if "INBOX.foo.bar" is selected and "INBOX.foo.bar.0",
421 # check for new UID ranges (e.g. "INBOX.foo.bar.1")
422 if (my $z = $self->{imapd}->{mailboxes}->{"$mailbox.0"}) {
423 ensure_slices_exist($self->{imapd}, $z, $z->over->max);
426 ($ibx, $exists, $uidmax + 1, $uid_base);
429 sub cmd_examine ($$$) {
430 my ($self, $tag, $mailbox) = @_;
431 # XXX: do we need this? RFC 5162/7162
432 my $ret = $self->{ibx} ? "* OK [CLOSED] previous closed\r\n" : '';
433 my ($ibx, $exists, $uidnext, $base) = inbox_lookup($self, $mailbox, 1);
434 return "$tag NO Mailbox doesn't exist: $mailbox\r\n" if !$ibx;
439 * OK [PERMANENTFLAGS ()] Read-only mailbox\r
440 * OK [UNSEEN $exists]\r
441 * OK [UIDNEXT $uidnext]\r
442 * OK [UIDVALIDITY $ibx->{uidvalidity}]\r
443 $tag OK [READ-ONLY] EXAMINE/SELECT done\r
451 } elsif ($v =~ /[{"\r\n%*\\\[]/) { # literal string
452 '{' . length($v) . "}\r\n" . $v;
453 } else { # quoted string
458 sub addr_envelope ($$;$) {
459 my ($eml, $x, $y) = @_;
460 my $v = $eml->header_raw($x) //
461 ($y ? $eml->header_raw($y) : undef) // return 'NIL';
463 my @x = $Address->parse($v) or return 'NIL';
465 map { '(' . join(' ',
466 _esc($_->name), 'NIL',
467 _esc($_->user), _esc($_->host)
473 sub eml_envelope ($) {
476 _esc($eml->header_raw('Date')),
477 _esc($eml->header_raw('Subject')),
478 addr_envelope($eml, 'From'),
479 addr_envelope($eml, 'Sender', 'From'),
480 addr_envelope($eml, 'Reply-To', 'From'),
481 addr_envelope($eml, 'To'),
482 addr_envelope($eml, 'Cc'),
483 addr_envelope($eml, 'Bcc'),
484 _esc($eml->header_raw('In-Reply-To')),
485 _esc($eml->header_raw('Message-ID')),
491 if ($hash && scalar keys %$hash) {
492 $hash = [ %$hash ]; # flatten hash into 1-dimensional array
493 '(' . join(' ', map { _esc($_) } @$hash) . ')';
499 sub body_disposition ($) {
501 my $cd = $eml->header_raw('Content-Disposition') or return 'NIL';
502 $cd = parse_content_disposition($cd);
503 my $buf = '('._esc($cd->{type});
504 $buf .= ' ' . _esc_hash(delete $cd->{attributes});
508 sub body_leaf ($$;$) {
509 my ($eml, $structure, $hold) = @_;
511 $eml->{is_submsg} and # parent was a message/(rfc822|news|global)
512 $buf .= eml_envelope($eml). ' ';
514 $buf .= '('._esc($ct->{type}).' ';
515 $buf .= _esc($ct->{subtype});
516 $buf .= ' ' . _esc_hash(delete $ct->{attributes});
517 $buf .= ' ' . _esc($eml->header_raw('Content-ID'));
518 $buf .= ' ' . _esc($eml->header_raw('Content-Description'));
519 my $cte = $eml->header_raw('Content-Transfer-Encoding') // '7bit';
520 $buf .= ' ' . _esc($cte);
521 $buf .= ' ' . $eml->{imap_body_len};
522 $buf .= ' '.($eml->body_raw =~ tr/\n/\n/) if lc($ct->{type}) eq 'text';
524 # for message/(rfc822|global|news), $hold[0] should have envelope
525 $buf .= ' ' . (@$hold ? join('', @$hold) : 'NIL') if $hold;
528 $buf .= ' '._esc($eml->header_raw('Content-MD5'));
529 $buf .= ' '. body_disposition($eml);
530 $buf .= ' '._esc($eml->header_raw('Content-Language'));
531 $buf .= ' '._esc($eml->header_raw('Content-Location'));
536 sub body_parent ($$$) {
537 my ($eml, $structure, $hold) = @_;
539 my $type = lc($ct->{type});
540 if ($type eq 'multipart') {
542 $buf .= @$hold ? join('', @$hold) : 'NIL';
543 $buf .= ' '._esc($ct->{subtype});
545 $buf .= ' '._esc_hash(delete $ct->{attributes});
546 $buf .= ' '.body_disposition($eml);
547 $buf .= ' '._esc($eml->header_raw('Content-Language'));
548 $buf .= ' '._esc($eml->header_raw('Content-Location'));
552 } else { # message/(rfc822|global|news)
553 @$hold = (body_leaf($eml, $structure, $hold));
557 # this is gross, but we need to process the parent part AFTER
558 # the child parts are done
559 sub bodystructure_prep {
561 my ($eml, $depth) = @$p; # ignore idx
562 # set length here, as $eml->{bdy} gets deleted for message/rfc822
563 $eml->{imap_body_len} = length($eml->body_raw);
564 push @$q, $eml, $depth;
567 # for FETCH BODY and FETCH BODYSTRUCTURE
568 sub fetch_body ($;$) {
569 my ($eml, $structure) = @_;
571 $eml->each_part(\&bodystructure_prep, \@q, 0, 1);
575 my ($part, $depth) = splice(@q, -2);
576 my $is_mp_parent = $depth == ($cur_depth - 1);
580 body_parent($part, $structure, \@hold);
582 unshift @hold, body_leaf($part, $structure);
588 sub requeue_once ($) {
590 # COMPRESS users all share the same DEFLATE context.
591 # Flush it here to ensure clients don't see
595 # no recursion, schedule another call ASAP,
596 # but only after all pending writes are done.
598 my $new_size = push(@{$self->{wbuf}}, \&long_step);
600 # wbuf may be populated by $cb, no need to rearm if so:
601 $self->requeue if $new_size == 1;
605 my ($self, $smsg, $bref, $ops, $partial) = @_;
606 my $uid = $smsg->{num};
607 $self->msg_more('* '.uid2msn($self, $uid)." FETCH (UID $uid");
609 for (my $i = 0; $i < @$ops;) {
611 $ops->[$i++]->($self, $k, $smsg, $bref, $eml);
613 partial_emit($self, $partial, $eml) if $partial;
614 $self->msg_more(")\r\n");
617 sub fetch_blob_cb { # called by git->cat_async via git_async_cat
618 my ($bref, $oid, $type, $size, $fetch_arg) = @_;
619 my ($self, undef, $msgs, $range_info, $ops, $partial) = @$fetch_arg;
620 my $smsg = shift @$msgs or die 'BUG: no smsg';
621 if (!defined($oid)) {
622 # it's possible to have TOCTOU if an admin runs
623 # public-inbox-(edit|purge), just move onto the next message
624 warn "E: $smsg->{blob} missing in $self->{ibx}->{inboxdir}\n";
625 return requeue_once($self);
627 $smsg->{blob} eq $oid or die "BUG: $smsg->{blob} != $oid";
629 fetch_run_ops($self, $smsg, $bref, $ops, $partial);
634 my ($self, $k, undef, $bref) = @_;
635 $self->msg_more(" $k {" . length($$bref)."}\r\n");
636 $self->msg_more($$bref);
639 # Mail::IMAPClient::message_string cares about this by default,
640 # (->Ignoresizeerrors attribute). Admins are encouraged to
641 # --reindex for IMAP support, anyways.
642 sub emit_rfc822_size {
643 my ($self, $k, $smsg) = @_;
644 $self->msg_more(' RFC822.SIZE ' . $smsg->{bytes});
647 sub emit_internaldate {
648 my ($self, undef, $smsg) = @_;
649 $self->msg_more(' INTERNALDATE "'.$smsg->internaldate.'"');
652 sub emit_flags { $_[0]->msg_more(' FLAGS ()') }
655 my ($self, undef, undef, undef, $eml) = @_;
656 $self->msg_more(' ENVELOPE '.eml_envelope($eml));
659 sub emit_rfc822_header {
660 my ($self, $k, undef, undef, $eml) = @_;
661 $self->msg_more(" $k {".length(${$eml->{hdr}})."}\r\n");
662 $self->msg_more(${$eml->{hdr}});
665 # n.b. this is sorted to be after any emit_eml_new ops
666 sub emit_rfc822_text {
667 my ($self, $k, undef, $bref) = @_;
668 $self->msg_more(" $k {".length($$bref)."}\r\n");
669 $self->msg_more($$bref);
672 sub emit_bodystructure {
673 my ($self, undef, undef, undef, $eml) = @_;
674 $self->msg_more(' BODYSTRUCTURE '.fetch_body($eml, 1));
678 my ($self, undef, undef, undef, $eml) = @_;
679 $self->msg_more(' BODY '.fetch_body($eml));
682 # set $eml once ($_[4] == $eml, $_[3] == $bref)
683 sub op_eml_new { $_[4] = PublicInbox::Eml->new($_[3]) }
685 # s/From / fixes old bug from import (pre-a0c07cba0e5d8b6a)
687 ${$_[0]} =~ s/(?<!\r)\n/\r\n/sg;
688 ${$_[0]} =~ s/\A[\r\n]*From [^\r\n]*\r\n//s;
691 sub op_crlf_bref { to_crlf_full($_[3]) }
693 sub op_crlf_hdr { to_crlf_full($_[4]->{hdr}) }
695 sub op_crlf_bdy { ${$_[4]->{bdy}} =~ s/(?<!\r)\n/\r\n/sg if $_[4]->{bdy} }
697 sub uid_clamp ($$$) {
698 my ($self, $beg, $end) = @_;
699 my $uid_min = $self->{uid_base} + 1;
700 my $uid_end = $uid_min + UID_SLICE - 1;
701 $$beg = $uid_min if $$beg < $uid_min;
702 $$end = $uid_end if $$end > $uid_end;
705 sub range_step ($$) {
706 my ($self, $range_csv) = @_;
707 my ($beg, $end, $range);
708 if ($$range_csv =~ s/\A([^,]+),//) {
711 $range = $$range_csv;
714 my $uid_base = $self->{uid_base};
715 my $uid_end = $uid_base + UID_SLICE;
716 if ($range =~ /\A([0-9]+):([0-9]+)\z/) {
717 ($beg, $end) = ($1 + 0, $2 + 0);
718 uid_clamp($self, \$beg, \$end);
719 } elsif ($range =~ /\A([0-9]+):\*\z/) {
721 $end = $self->{ibx}->over->max;
722 $end = $uid_end if $end > $uid_end;
723 $beg = $end if $beg > $end;
724 uid_clamp($self, \$beg, \$end);
725 } elsif ($range =~ /\A[0-9]+\z/) {
726 $beg = $end = $range + 0;
727 # just let the caller do an out-of-range query if a single
728 # UID is out-of-range
729 ++$beg if ($beg <= $uid_base || $end > $uid_end);
731 return 'BAD fetch range';
733 [ $beg, $end, $$range_csv ];
736 sub refill_range ($$$) {
737 my ($self, $msgs, $range_info) = @_;
738 my ($beg, $end, $range_csv) = @$range_info;
739 if (scalar(@$msgs = @{$self->{ibx}->over->query_xover($beg, $end)})) {
740 $range_info->[0] = $msgs->[-1]->{num} + 1;
743 return 'OK Fetch done' if !$range_csv;
744 my $next_range = range_step($self, \$range_csv);
745 return $next_range if !ref($next_range); # error
746 @$range_info = @$next_range;
747 undef; # keep looping
750 sub fetch_blob { # long_response
751 my ($self, $tag, $msgs, $range_info, $ops, $partial) = @_;
752 while (!@$msgs) { # rare
753 if (my $end = refill_range($self, $msgs, $range_info)) {
754 $self->write(\"$tag $end\r\n");
758 uo2m_extend($self, $msgs->[-1]->{num});
759 git_async_cat($self->{ibx}->git, $msgs->[0]->{blob},
760 \&fetch_blob_cb, \@_);
763 sub fetch_smsg { # long_response
764 my ($self, $tag, $msgs, $range_info, $ops) = @_;
765 while (!@$msgs) { # rare
766 if (my $end = refill_range($self, $msgs, $range_info)) {
767 $self->write(\"$tag $end\r\n");
771 uo2m_extend($self, $msgs->[-1]->{num});
772 fetch_run_ops($self, $_, undef, $ops) for @$msgs;
777 sub refill_uids ($$$;$) {
778 my ($self, $uids, $range_info, $sql) = @_;
779 my ($beg, $end, $range_csv) = @$range_info;
780 my $over = $self->{ibx}->over;
782 if (scalar(@$uids = @{$over->uid_range($beg, $end, $sql)})) {
783 $range_info->[0] = $uids->[-1] + 1; # update $beg
785 } elsif (!$range_csv) {
788 my $next_range = range_step($self, \$range_csv);
789 return $next_range if !ref($next_range); # error
790 ($beg, $end, $range_csv) = @$range_info = @$next_range;
796 sub fetch_uid { # long_response
797 my ($self, $tag, $uids, $range_info, $ops) = @_;
798 if (defined(my $err = refill_uids($self, $uids, $range_info))) {
799 $err ||= 'OK Fetch done';
800 $self->write("$tag $err\r\n");
803 my $adj = $self->{uid_base} + 1;
804 my $uo2m = uo2m_extend($self, $uids->[-1]);
805 $uo2m = [ unpack('S*', $uo2m) ] if !ref($uo2m);
808 $self->msg_more("* $uo2m->[$_ - $adj] FETCH (UID $_");
809 for ($i = 0; $i < @$ops;) {
811 $ops->[$i++]->($self, $k);
813 $self->msg_more(")\r\n");
819 sub cmd_status ($$$;@) {
820 my ($self, $tag, $mailbox, @items) = @_;
821 return "$tag BAD no items\r\n" if !scalar(@items);
822 ($items[0] !~ s/\A\(//s || $items[-1] !~ s/\)\z//s) and
823 return "$tag BAD invalid args\r\n";
824 my ($ibx, $exists, $uidnext) = inbox_lookup($self, $mailbox);
825 return "$tag NO Mailbox doesn't exist: $mailbox\r\n" if !$ibx;
827 for my $it (@items) {
830 if ($it =~ /\A(?:MESSAGES|UNSEEN|RECENT)\z/) {
832 } elsif ($it eq 'UIDNEXT') {
834 } elsif ($it eq 'UIDVALIDITY') {
835 push @it, $ibx->{uidvalidity};
837 return "$tag BAD invalid item\r\n";
840 return "$tag BAD no items\r\n" if !@it;
841 "* STATUS $mailbox (".join(' ', @it).")\r\n" .
842 "$tag OK Status done\r\n";
845 my %patmap = ('*' => '.*', '%' => '[^\.]*');
846 sub cmd_list ($$$$) {
847 my ($self, $tag, $refname, $wildcard) = @_;
848 my $l = $self->{imapd}->{inboxlist};
849 if ($refname eq '' && $wildcard eq '') {
850 # request for hierarchy delimiter
851 $l = [ qq[* LIST (\\Noselect) "." ""\r\n] ];
852 } elsif ($refname ne '' || $wildcard ne '*') {
853 $wildcard =~ s!([^a-z0-9_])!$patmap{$1} // "\Q$1"!egi;
854 $l = [ grep(/ \Q$refname\E$wildcard\r\n\z/is, @$l) ];
856 \(join('', @$l, "$tag OK List done\r\n"));
859 sub cmd_lsub ($$$$) {
860 my (undef, $tag) = @_; # same args as cmd_list
861 "$tag OK Lsub done\r\n";
864 sub eml_index_offs_i { # PublicInbox::Eml::each_part callback
866 my ($eml, undef, $idx) = @$p;
867 if ($idx && lc($eml->ct->{type}) eq 'multipart') {
868 $eml->{imap_bdy} = $eml->{bdy} // \'';
870 $all->{$idx} = $eml; # $idx => Eml
873 # prepares an index for BODY[$SECTION_IDX] fetches
874 sub eml_body_idx ($$) {
875 my ($eml, $section_idx) = @_;
876 my $idx = $eml->{imap_all_parts} //= do {
878 $eml->each_part(\&eml_index_offs_i, $all, 0, 1);
879 # top-level of multipart, BODY[0] not allowed (nz-number)
883 $idx->{$section_idx};
886 # BODY[($SECTION_IDX)?(.$SECTION_NAME)?]<$offset.$bytes>
888 my ($eml, $section_idx, $section_name) = @_;
889 if (defined $section_idx) {
890 $eml = eml_body_idx($eml, $section_idx) or return;
892 if (defined $section_name) {
893 if ($section_name eq 'MIME') {
894 # RFC 3501 6.4.5 states:
895 # The MIME part specifier MUST be prefixed
896 # by one or more numeric part specifiers
897 return unless defined $section_idx;
898 return $eml->header_obj->as_string . "\r\n";
900 my $bdy = $eml->{bdy} // $eml->{imap_bdy} // \'';
901 $eml = PublicInbox::Eml->new($$bdy);
902 if ($section_name eq 'TEXT') {
903 return $eml->body_raw;
904 } elsif ($section_name eq 'HEADER') {
905 return $eml->header_obj->as_string . "\r\n";
907 die "BUG: bad section_name=$section_name";
910 ${$eml->{bdy} // $eml->{imap_bdy} // \''};
913 # similar to what's in PublicInbox::Eml::re_memo, but doesn't memoize
914 # to avoid OOM with malicious users
915 sub hdrs_regexp ($) {
917 my $names = join('|', map { "\Q$_" } split(/[ \t]+/, $hdrs));
918 qr/^(?:$names):[ \t]*[^\n]*\r?\n # 1st line
919 # continuation lines:
920 (?:[^:\n]*?[ \t]+[^\n]*\r?\n)*
924 # BODY[($SECTION_IDX.)?HEADER.FIELDS.NOT ($HDRS)]<$offset.$bytes>
925 sub partial_hdr_not {
926 my ($eml, $section_idx, $hdrs_re) = @_;
927 if (defined $section_idx) {
928 $eml = eml_body_idx($eml, $section_idx) or return;
930 my $str = $eml->header_obj->as_string;
931 $str =~ s/$hdrs_re//g;
932 $str =~ s/(?<!\r)\n/\r\n/sg;
936 # BODY[($SECTION_IDX.)?HEADER.FIELDS ($HDRS)]<$offset.$bytes>
937 sub partial_hdr_get {
938 my ($eml, $section_idx, $hdrs_re) = @_;
939 if (defined $section_idx) {
940 $eml = eml_body_idx($eml, $section_idx) or return;
942 my $str = $eml->header_obj->as_string;
943 $str = join('', ($str =~ m/($hdrs_re)/g));
944 $str =~ s/(?<!\r)\n/\r\n/sg;
948 sub partial_prepare ($$$$) {
949 my ($need, $partial, $want, $att) = @_;
951 # recombine [ "BODY[1.HEADER.FIELDS", "(foo", "bar)]" ]
952 # back to: "BODY[1.HEADER.FIELDS (foo bar)]"
953 return unless $att =~ /\ABODY\[/s;
954 until (rindex($att, ']') >= 0) {
955 my $next = shift @$want or return;
956 $att .= ' ' . uc($next);
958 if ($att =~ /\ABODY\[([0-9]+(?:\.[0-9]+)*)? # 1 - section_idx
959 (?:\.(HEADER|MIME|TEXT))? # 2 - section_name
960 \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 3, 4
961 $partial->{$att} = [ \&partial_body, $1, $2, $3, $4 ];
962 $$need |= CRLF_BREF|EML_HDR|EML_BDY;
963 } elsif ($att =~ /\ABODY\[(?:([0-9]+(?:\.[0-9]+)*)\.)? # 1 - section_idx
964 (?:HEADER\.FIELDS(\.NOT)?)\x20 # 2
965 \(([A-Z0-9\-\x20]+)\) # 3 - hdrs
966 \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 4 5
967 my $tmp = $partial->{$att} = [ $2 ? \&partial_hdr_not
970 $tmp->[2] = hdrs_regexp($3);
972 # don't emit CRLF_HDR instruction, here, partial_hdr_*
973 # will do CRLF conversion with only the extracted result
974 # and not waste time converting lines we don't care about.
981 sub partial_emit ($$$) {
982 my ($self, $partial, $eml) = @_;
984 my ($k, $cb, @args) = @$_;
985 my ($offset, $len) = splice(@args, -2);
986 # $cb is partial_body|partial_hdr_get|partial_hdr_not
987 my $str = $cb->($eml, @args) // '';
988 if (defined $offset) {
990 $str = substr($str, $offset, $len);
991 $k =~ s/\.$len>\z/>/ or warn
992 "BUG: unable to remove `.$len>' from `$k'";
994 $str = substr($str, $offset);
1000 $self->msg_more(" $k {$len}\r\n");
1001 $self->msg_more($str);
1005 sub fetch_compile ($) {
1007 if ($want->[0] =~ s/\A\(//s) {
1008 $want->[-1] =~ s/\)\z//s or return 'BAD no rparen';
1010 my (%partial, %seen, @op);
1012 while (defined(my $att = shift @$want)) {
1014 next if $att eq 'UID'; # always returned
1015 $att =~ s/\ABODY\.PEEK\[/BODY\[/; # we're read-only
1016 my $x = $FETCH_ATT{$att};
1018 while (my ($k, $fl_cb) = each %$x) {
1019 next if $seen{$k}++;
1020 $need |= $fl_cb->[0];
1021 push @op, [ @$fl_cb, $k ];
1023 } elsif (!partial_prepare(\$need, \%partial, $want, $att)) {
1024 return "BAD param: $att";
1029 # stabilize partial order for consistency and ease-of-debugging:
1030 if (scalar keys %partial) {
1032 $r[2] = [ map { [ $_, @{$partial{$_}} ] } sort keys %partial ];
1035 push @op, $OP_EML_NEW if ($need & (EML_HDR|EML_BDY));
1037 # do we need CRLF conversion?
1038 if ($need & CRLF_BREF) {
1039 push @op, $OP_CRLF_BREF;
1040 } elsif (my $crlf = ($need & (CRLF_HDR|CRLF_BDY))) {
1041 if ($crlf == (CRLF_HDR|CRLF_BDY)) {
1042 push @op, $OP_CRLF_BREF;
1043 } elsif ($need & CRLF_HDR) {
1044 push @op, $OP_CRLF_HDR;
1046 push @op, $OP_CRLF_BDY;
1050 $r[0] = $need & NEED_BLOB ? \&fetch_blob :
1051 ($need & NEED_SMSG ? \&fetch_smsg : \&fetch_uid);
1053 # r[1] = [ $key1, $cb1, $key2, $cb2, ... ]
1054 use sort 'stable'; # makes output more consistent
1055 $r[1] = [ map { ($_->[2], $_->[1]) } sort { $a->[0] <=> $b->[0] } @op ];
1059 sub cmd_uid_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 my $range_info = range_step($self, \$range_csv);
1068 return "$tag $range_info\r\n" if !ref($range_info);
1069 uo2m_hibernate($self) if $cb == \&fetch_blob; # slow, save RAM
1070 long_response($self, $cb, $tag, [], $range_info, $ops, $partial);
1073 sub cmd_fetch ($$$$;@) {
1074 my ($self, $tag, $range_csv, @want) = @_;
1075 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1076 my ($cb, $ops, $partial) = fetch_compile(\@want);
1077 return "$tag $cb\r\n" unless $ops;
1079 # cb is one of fetch_blob, fetch_smsg, fetch_uid
1080 $range_csv = 'bad' if $range_csv !~ $valid_range;
1081 msn_to_uid_range(msn2uid($self), $range_csv);
1082 my $range_info = range_step($self, \$range_csv);
1083 return "$tag $range_info\r\n" if !ref($range_info);
1084 uo2m_hibernate($self) if $cb == \&fetch_blob; # slow, save RAM
1085 long_response($self, $cb, $tag, [], $range_info, $ops, $partial);
1088 sub msn_convert ($$) {
1089 my ($self, $uids) = @_;
1090 my $adj = $self->{uid_base} + 1;
1091 my $uo2m = uo2m_extend($self, $uids->[-1]);
1092 $uo2m = [ unpack('S*', $uo2m) ] if !ref($uo2m);
1093 $_ = $uo2m->[$_ - $adj] for @$uids;
1096 sub search_uid_range { # long_response
1097 my ($self, $tag, $sql, $range_info, $want_msn) = @_;
1099 if (defined(my $err = refill_uids($self, $uids, $range_info, $sql))) {
1100 $err ||= 'OK Search done';
1101 $self->write("\r\n$tag $err\r\n");
1104 msn_convert($self, $uids) if $want_msn;
1105 $self->msg_more(join(' ', '', @$uids));
1110 my ($q, $k, $d) = @_;
1111 my $sql = $q->{sql};
1114 if ($k eq 'SENTON') {
1115 my $end = $d + 86399; # no leap day...
1116 my $da = strftime('%Y%m%d%H%M%S', gmtime($d));
1117 my $db = strftime('%Y%m%d%H%M%S', gmtime($end));
1118 $q->{xap} .= " dt:$da..$db";
1119 $$sql .= " AND ds >= $d AND ds <= $end" if defined($sql);
1120 } elsif ($k eq 'SENTBEFORE') {
1121 $q->{xap} .= ' d:..'.strftime('%Y%m%d', gmtime($d));
1122 $$sql .= " AND ds <= $d" if defined($sql);
1123 } elsif ($k eq 'SENTSINCE') {
1124 $q->{xap} .= ' d:'.strftime('%Y%m%d', gmtime($d)).'..';
1125 $$sql .= " AND ds >= $d" if defined($sql);
1127 # INTERNALDATE (Received)
1128 } elsif ($k eq 'ON') {
1129 my $end = $d + 86399; # no leap day...
1130 $q->{xap} .= " ts:$d..$end";
1131 $$sql .= " AND ts >= $d AND ts <= $end" if defined($sql);
1132 } elsif ($k eq 'BEFORE') {
1133 $q->{xap} .= " ts:..$d";
1134 $$sql .= " AND ts <= $d" if defined($sql);
1135 } elsif ($k eq 'SINCE') {
1136 $q->{xap} .= " ts:$d..";
1137 $$sql .= " AND ts >= $d" if defined($sql);
1139 die "BUG: $k not recognized";
1143 # IMAP to Xapian search key mapping
1148 TEXT => '', # n.b. does not include all headers
1151 # BCC => 'bcc:', # TODO
1152 # KEYWORD # TODO ? dfpre,dfpost,...
1155 # IMAP allows searching arbitrary headers via "HEADER $HDR_NAME $HDR_VAL"
1156 # which gets silly expensive. We only allow the headers we already index.
1157 my %H2X = (%I2X, 'MESSAGE-ID' => 'm:', 'LIST-ID' => 'l:');
1159 sub xap_append ($$$$) {
1160 my ($q, $rest, $k, $xk) = @_;
1161 delete $q->{sql}; # can't use over.sqlite3
1162 defined(my $arg = shift @$rest) or return "BAD $k no arg";
1164 # AFAIK Xapian can't handle [*"] in probabilistic terms
1166 ${$q->{xap}} .= qq[ $xk"$arg"];
1170 sub parse_query ($$) {
1171 my ($self, $query) = @_;
1172 my $q = PublicInbox::IMAPsearchqp::parse($self, $query);
1174 my $max = $self->{ibx}->over->max;
1176 uid_clamp($self, \$beg, \$max);
1177 $q->{range_info} = [ $beg, $max ];
1182 sub refill_xap ($$$$) {
1183 my ($self, $uids, $range_info, $q) = @_;
1184 my ($beg, $end) = @$range_info;
1185 my $srch = $self->{ibx}->search;
1186 my $opt = { mset => 2, limit => 1000 };
1187 my $nshard = $srch->{nshard} // 1;
1188 my $mset = $srch->query("$q uid:$beg..$end", $opt);
1189 @$uids = map { mdocid($nshard, $_) } $mset->items;
1191 $range_info->[0] = $uids->[-1] + 1; # update $beg
1192 return; # possibly more
1197 sub search_xap_range { # long_response
1198 my ($self, $tag, $q, $range_info, $want_msn) = @_;
1200 if (defined(my $err = refill_xap($self, $uids, $range_info, $q))) {
1201 $err ||= 'OK Search done';
1202 $self->write("\r\n$tag $err\r\n");
1205 msn_convert($self, $uids) if $want_msn;
1206 $self->msg_more(join(' ', '', @$uids));
1211 my ($self, $tag, $query, $want_msn) = @_;
1212 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1213 my $q = parse_query($self, $query);
1214 return "$tag $q\r\n" if !ref($q);
1215 my ($sql, $range_info) = delete @$q{qw(sql range_info)};
1216 if (!scalar(keys %$q)) { # overview.sqlite3
1217 $self->msg_more('* SEARCH');
1218 long_response($self, \&search_uid_range,
1219 $tag, $sql, $range_info, $want_msn);
1220 } elsif ($q = $q->{xap}) {
1221 $self->{ibx}->search or
1222 return "$tag BAD search not available for mailbox\r\n";
1223 $self->msg_more('* SEARCH');
1224 long_response($self, \&search_xap_range,
1225 $tag, $q, $range_info, $want_msn);
1227 "$tag BAD Error\r\n";
1231 sub cmd_uid_search ($$$) {
1232 my ($self, $tag, $query) = @_;
1233 search_common($self, $tag, $query);
1236 sub cmd_search ($$$;) {
1237 my ($self, $tag, $query) = @_;
1238 search_common($self, $tag, $query, 1);
1241 sub args_ok ($$) { # duplicated from PublicInbox::NNTP
1242 my ($cb, $argc) = @_;
1243 my $tot = prototype $cb;
1244 my ($nreq, undef) = split(';', $tot);
1245 $nreq = ($nreq =~ tr/$//) - 1;
1246 $tot = ($tot =~ tr/$//) - 1;
1247 ($argc <= $tot && $argc >= $nreq);
1250 # returns 1 if we can continue, 0 if not due to buffered writes or disconnect
1251 sub process_line ($$) {
1252 my ($self, $l) = @_;
1254 # TODO: IMAP allows literals for big requests to upload messages
1255 # (which we don't support) but maybe some big search queries use it.
1256 # RFC 3501 9 (2) doesn't permit TAB or multiple SP
1257 my ($tag, $req, @args) = parse_line('[ \t]+', 0, $l);
1258 pop(@args) if (@args && !defined($args[-1]));
1259 if (@args && uc($req) eq 'UID') {
1260 $req .= "_".(shift @args);
1263 if (defined(my $idle_tag = $self->{-idle_tag})) {
1264 (uc($tag // '') eq 'DONE' && !defined($req)) ?
1265 idle_done($self, $tag) :
1266 "$idle_tag BAD expected DONE\r\n";
1267 } elsif (my $cmd = $self->can('cmd_'.lc($req // ''))) {
1268 if ($cmd == \&cmd_uid_search || $cmd == \&cmd_search) {
1269 # preserve user-supplied quotes for search
1270 (undef, @args) = split(/ search /i, $l, 2);
1272 $cmd->($self, $tag, @args);
1273 } else { # this is weird
1274 auth_challenge_ok($self) //
1276 ' BAD Error in IMAP command '.
1278 ": Unknown command\r\n";
1282 if ($err && $self->{sock}) {
1284 err($self, 'error from: %s (%s)', $l, $err);
1286 $res = "$tag BAD program fault - command not performed\r\n";
1288 return 0 unless defined $res;
1294 # wbuf is unset or empty, here; {long} may add to it
1295 my ($fd, $cb, $t0, @args) = @{$self->{long_cb}};
1296 my $more = eval { $cb->($self, @args) };
1297 if ($@ || !$self->{sock}) { # something bad happened...
1298 delete $self->{long_cb};
1299 my $elapsed = now() - $t0;
1302 "%s during long response[$fd] - %0.6f",
1305 out($self, " deferred[$fd] aborted - %0.6f", $elapsed);
1307 } elsif ($more) { # $self->{wbuf}:
1308 $self->update_idle_time;
1310 # control passed to git_async_cat if $more == \undef
1311 requeue_once($self) if !ref($more);
1312 } else { # all done!
1313 delete $self->{long_cb};
1314 my $elapsed = now() - $t0;
1315 my $fd = fileno($self->{sock});
1316 out($self, " deferred[$fd] done - %0.6f", $elapsed);
1317 my $wbuf = $self->{wbuf}; # do NOT autovivify
1319 $self->requeue unless $wbuf && @$wbuf;
1324 my ($self, $fmt, @args) = @_;
1325 printf { $self->{imapd}->{err} } $fmt."\n", @args;
1329 my ($self, $fmt, @args) = @_;
1330 printf { $self->{imapd}->{out} } $fmt."\n", @args;
1333 sub long_response ($$;@) {
1334 my ($self, $cb, @args) = @_; # cb returns true if more, false if done
1336 my $sock = $self->{sock} or return;
1337 # make sure we disable reading during a long response,
1338 # clients should not be sending us stuff and making us do more
1339 # work while we are stream a response to them
1340 $self->{long_cb} = [ fileno($sock), $cb, now(), @args ];
1341 long_step($self); # kick off!
1345 # callback used by PublicInbox::DS for any (e)poll (in/out/hup/err)
1349 return unless $self->flush_write && $self->{sock} && !$self->{long_cb};
1351 $self->update_idle_time;
1352 # only read more requests if we've drained the write buffer,
1353 # otherwise we can be buffering infinitely w/o backpressure
1355 my $rbuf = $self->{rbuf} // \(my $x = '');
1356 my $line = index($$rbuf, "\n");
1358 if (length($$rbuf) >= LINE_MAX) {
1359 $self->write(\"\* BAD request too long\r\n");
1360 return $self->close;
1362 $self->do_read($rbuf, LINE_MAX, length($$rbuf)) or
1363 return uo2m_hibernate($self);
1364 $line = index($$rbuf, "\n");
1366 $line = substr($$rbuf, 0, $line + 1, '');
1367 $line =~ s/\r?\n\z//s;
1368 return $self->close if $line =~ /[[:cntrl:]]/s;
1370 my $fd = fileno($self->{sock});
1371 my $r = eval { process_line($self, $line) };
1372 my $pending = $self->{wbuf} ? ' pending' : '';
1373 out($self, "[$fd] %s - %0.6f$pending - $r", $line, now() - $t0);
1375 return $self->close if $r < 0;
1376 $self->rbuf_idle($rbuf);
1377 $self->update_idle_time;
1379 # maybe there's more pipelined data, or we'll have
1380 # to register it for socket-readiness notifications
1381 $self->requeue unless $pending;
1384 sub compressed { undef }
1386 sub zflush {} # overridden by IMAPdeflate
1389 sub cmd_compress ($$$) {
1390 my ($self, $tag, $alg) = @_;
1391 return "$tag BAD DEFLATE only\r\n" if uc($alg) ne "DEFLATE";
1392 return "$tag BAD COMPRESS active\r\n" if $self->compressed;
1394 # CRIME made TLS compression obsolete
1395 # return "$tag NO [COMPRESSIONACTIVE]\r\n" if $self->tls_compressed;
1397 PublicInbox::IMAPdeflate->enable($self, $tag);
1402 sub cmd_starttls ($$) {
1403 my ($self, $tag) = @_;
1404 my $sock = $self->{sock} or return;
1405 if ($sock->can('stop_SSL') || $self->compressed) {
1406 return "$tag BAD TLS or compression already enabled\r\n";
1408 my $opt = $self->{imapd}->{accept_tls} or
1409 return "$tag BAD can not initiate TLS negotiation\r\n";
1410 $self->write(\"$tag OK begin TLS negotiation now\r\n");
1411 $self->{sock} = IO::Socket::SSL->start_SSL($sock, %$opt);
1412 $self->requeue if PublicInbox::DS::accept_tls_step($self);
1416 # for graceful shutdown in PublicInbox::Daemon:
1418 my ($self, $now) = @_;
1419 if (defined($self->{-idle_tag})) {
1420 $self->write(\"* BYE server shutting down\r\n");
1421 return; # not busy anymore
1423 ($self->{rbuf} || $self->{wbuf} || $self->not_idle_long($now));
1428 if (my $ibx = delete $self->{ibx}) {
1429 stop_idle($self, $ibx);
1431 $self->SUPER::close; # PublicInbox::DS::close
1434 # we're read-only, so SELECT and EXAMINE do the same thing
1436 *cmd_select = \&cmd_examine;
1438 package PublicInbox::IMAP_preauth;
1439 our @ISA = qw(PublicInbox::IMAP);