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
10 # * NNTP article numbers are UIDs
12 package PublicInbox::IMAP;
14 use base qw(PublicInbox::DS);
15 use fields qw(imapd ibx long_cb -login_tag
16 uid_base -idle_tag -idle_max);
18 use PublicInbox::EmlContentFoo qw(parse_content_disposition);
19 use PublicInbox::DS qw(now);
20 use PublicInbox::Syscall qw(EPOLLIN EPOLLONESHOT);
21 use PublicInbox::GitAsyncCat;
22 use Text::ParseWords qw(parse_line);
24 use Time::Local qw(timegm);
25 use POSIX qw(strftime);
26 use Hash::Util qw(unlock_hash); # dependency of fields for perl 5.10+, anyways
29 for my $mod (qw(Email::Address::XS Mail::Address)) {
30 eval "require $mod" or next;
31 $Address = $mod and last;
33 die "neither Email::Address::XS nor Mail::Address loaded: $@" if !$Address;
35 sub LINE_MAX () { 8000 } # RFC 2683 3.2.1.5
37 # changing this will cause grief for clients which cache
38 sub UID_BLOCK () { 50_000 }
40 # these values area also used for sorting
41 sub NEED_SMSG () { 1 }
42 sub NEED_BLOB () { NEED_SMSG|2 }
43 sub CRLF_BREF () { 4 }
45 sub CRLF_HDR () { 16 }
47 sub CRLF_BDY () { 64 }
48 my $OP_EML_NEW = [ EML_HDR - 1, \&op_eml_new ];
49 my $OP_CRLF_BREF = [ CRLF_BREF, \&op_crlf_bref ];
50 my $OP_CRLF_HDR = [ CRLF_HDR, \&op_crlf_hdr ];
51 my $OP_CRLF_BDY = [ CRLF_BDY, \&op_crlf_bdy ];
54 'BODY[HEADER]' => [ NEED_BLOB|EML_HDR|CRLF_HDR, \&emit_rfc822_header ],
55 'BODY[TEXT]' => [ NEED_BLOB|EML_BDY|CRLF_BDY, \&emit_rfc822_text ],
56 'BODY[]' => [ NEED_BLOB|CRLF_BREF, \&emit_rfc822 ],
57 'RFC822.HEADER' => [ NEED_BLOB|EML_HDR|CRLF_HDR, \&emit_rfc822_header ],
58 'RFC822.TEXT' => [ NEED_BLOB|EML_BDY|CRLF_BDY, \&emit_rfc822_text ],
59 'RFC822.SIZE' => [ NEED_SMSG, \&emit_rfc822_size ],
60 RFC822 => [ NEED_BLOB|CRLF_BREF, \&emit_rfc822 ],
61 BODY => [ NEED_BLOB|EML_HDR|EML_BDY, \&emit_body ],
62 BODYSTRUCTURE => [ NEED_BLOB|EML_HDR|EML_BDY, \&emit_bodystructure ],
63 ENVELOPE => [ NEED_BLOB|EML_HDR, \&emit_envelope ],
64 FLAGS => [ 0, \&emit_flags ],
65 INTERNALDATE => [ NEED_SMSG, \&emit_internaldate ],
67 my %FETCH_ATT = map { $_ => [ $_ ] } keys %FETCH_NEED;
69 # aliases (RFC 3501 section 6.4.5)
70 $FETCH_ATT{FAST} = [ qw(FLAGS INTERNALDATE RFC822.SIZE) ];
71 $FETCH_ATT{ALL} = [ @{$FETCH_ATT{FAST}}, 'ENVELOPE' ];
72 $FETCH_ATT{FULL} = [ @{$FETCH_ATT{ALL}}, 'BODY' ];
74 for my $att (keys %FETCH_ATT) {
75 my %h = map { $_ => $FETCH_NEED{$_} } @{$FETCH_ATT{$att}};
76 $FETCH_ATT{$att} = \%h;
80 my $valid_range = '[0-9]+|[0-9]+:[0-9]+|[0-9]+:\*';
81 $valid_range = qr/\A(?:$valid_range)(?:,(?:$valid_range))*\z/;
83 my @MoY = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
87 # RFC 3501 5.4. Autologout Timer needs to be >= 30min
88 $PublicInbox::DS::EXPTIME = 60 * 30;
92 my $capa = capa($self);
93 $self->write(\"* OK [$capa] public-inbox-imapd ready\r\n");
97 my ($class, $sock, $imapd) = @_;
98 my $self = fields::new('PublicInbox::IMAP_preauth');
102 if ($sock->can('accept_SSL') && !$sock->accept_SSL) {
103 return CORE::close($sock) if $! != EAGAIN;
104 $ev = PublicInbox::TLS::epollbit();
105 $wbuf = [ \&PublicInbox::DS::accept_tls_step, \&greet ];
107 $self->SUPER::new($sock, $ev | EPOLLONESHOT);
108 $self->{imapd} = $imapd;
110 $self->{wbuf} = $wbuf;
114 $self->update_idle_time;
123 # dovecot advertises IDLE pre-login; perhaps because some clients
124 # depend on it, so we'll do the same
125 my $capa = 'CAPABILITY IMAP4rev1 IDLE';
126 if ($self->logged_in) {
127 $capa .= ' COMPRESS=DEFLATE';
129 if (!($self->{sock} // $self)->can('accept_SSL') &&
130 $self->{imapd}->{accept_tls}) {
131 $capa .= ' STARTTLS';
133 $capa .= ' AUTH=ANONYMOUS';
137 sub login_success ($$) {
138 my ($self, $tag) = @_;
139 bless $self, 'PublicInbox::IMAP';
140 my $capa = capa($self);
141 "$tag OK [$capa] Logged in\r\n";
144 sub auth_challenge_ok ($) {
146 my $tag = delete($self->{-login_tag}) or return;
147 login_success($self, $tag);
150 sub cmd_login ($$$$) {
151 my ($self, $tag) = @_; # ignore ($user, $password) = ($_[2], $_[3])
152 login_success($self, $tag);
156 my ($self, $tag) = @_;
157 delete $self->{uid_base};
158 delete $self->{ibx} ? "$tag OK Close done\r\n"
159 : "$tag BAD No mailbox\r\n";
162 sub cmd_logout ($$) {
163 my ($self, $tag) = @_;
164 delete $self->{-idle_tag};
165 $self->write(\"* BYE logging out\r\n$tag OK Logout done\r\n");
166 $self->shutdn; # PublicInbox::DS::shutdn
170 sub cmd_authenticate ($$$) {
171 my ($self, $tag) = @_; # $method = $_[2], should be "ANONYMOUS"
172 $self->{-login_tag} = $tag;
176 sub cmd_capability ($$) {
177 my ($self, $tag) = @_;
178 '* '.capa($self)."\r\n$tag OK Capability done\r\n";
181 sub cmd_noop ($$) { "$_[1] OK Noop done\r\n" }
183 # called by PublicInbox::InboxIdle
184 sub on_inbox_unlock {
185 my ($self, $ibx) = @_;
186 my $new = $ibx->mm->max;
187 my $uid_base = $self->{uid_base} // 0;
188 my $uid_end = $uid_base + UID_BLOCK;
189 defined(my $old = $self->{-idle_max}) or die 'BUG: -idle_max unset';
190 $new = $uid_end if $new > $uid_end;
192 $self->{-idle_max} = $new;
195 $self->msg_more("* $_ EXISTS\r\n") for (($old + 1)..($new - 1));
196 $self->write(\"* $new EXISTS\r\n");
197 } elsif ($new == $uid_end) { # max exceeded $uid_end
198 # continue idling w/o inotify
199 delete $self->{-idle_max};
200 my $sock = $self->{sock} or return;
201 $ibx->unsubscribe_unlock(fileno($sock));
205 # called every X minute(s) or so by PublicInbox::DS::later
211 for my $i (values %$old) {
212 next if ($i->{wbuf} || !exists($i->{-idle_tag}));
213 $i->update_idle_time or next;
214 $IDLERS->{fileno($i->{sock})} = $i;
215 $i->write(\"* OK Still here\r\n");
217 $idle_timer = scalar keys %$IDLERS ?
218 PublicInbox::DS::later(\&idle_tick_all) : undef;
222 my ($self, $tag) = @_;
223 # IDLE seems allowed by dovecot w/o a mailbox selected *shrug*
224 my $ibx = $self->{ibx} or return "$tag BAD no mailbox selected\r\n";
225 $self->{-idle_tag} = $tag;
226 my $max = $ibx->mm->max // 0;
227 my $uid_end = $self->{uid_base} + UID_BLOCK;
228 my $sock = $self->{sock} or return;
229 my $fd = fileno($sock);
230 # only do inotify on most recent slice
231 if ($max < $uid_end) {
232 $ibx->subscribe_unlock($fd, $self);
233 $self->{imapd}->idler_start;
234 $self->{-idle_max} = $max;
236 $idle_timer //= PublicInbox::DS::later(\&idle_tick_all);
237 $IDLERS->{$fd} = $self;
243 my $sock = $self->{sock} or return;
244 my $fd = fileno($sock);
245 delete $IDLERS->{$fd};
246 $ibx->unsubscribe_unlock($fd);
250 my ($self, $tag) = @_; # $tag is "DONE" (case-insensitive)
251 defined(my $idle_tag = delete $self->{-idle_tag}) or
252 return "$tag BAD not idle\r\n";
253 my $ibx = $self->{ibx} or do {
254 warn "BUG: idle_tag set w/o inbox";
255 return "$tag BAD internal bug\r\n";
257 stop_idle($self, $ibx);
258 "$idle_tag OK Idle done\r\n";
261 sub ensure_ranges_exist ($$$) {
262 my ($imapd, $ibx, $max) = @_;
263 defined(my $mb_top = $ibx->{newsgroup}) or return;
264 my $mailboxes = $imapd->{mailboxes};
266 for (my $i = int($max/UID_BLOCK); $i >= 0; --$i) {
267 my $sub_mailbox = "$mb_top.$i";
268 last if exists $mailboxes->{$sub_mailbox};
269 $mailboxes->{$sub_mailbox} = $ibx;
270 $sub_mailbox =~ s/\Ainbox\./INBOX./i; # more familiar to users
271 push @created, $sub_mailbox;
273 return unless @created;
274 my $l = $imapd->{inboxlist} or return;
275 push @$l, map { qq[* LIST (\\HasNoChildren) "." $_\r\n] } @created;
278 sub inbox_lookup ($$) {
279 my ($self, $mailbox) = @_;
280 my ($ibx, $exists, $uidnext, $uid_base);
281 if ($mailbox =~ /\A(.+)\.([0-9]+)\z/) {
282 # old mail: inbox.comp.foo.$uid_block_idx
284 $uid_base = $2 * UID_BLOCK;
285 $ibx = $self->{imapd}->{mailboxes}->{lc $mailbox} or return;
286 $exists = $ibx->mm->max // 0;
287 ensure_ranges_exist($self->{imapd}, $ibx, $exists);
288 my $uid_end = $uid_base + UID_BLOCK;
289 $exists = $uid_end if $exists > $uid_end;
290 $uidnext = $exists + 1;
291 $exists -= $uid_base;
292 } else { # check for dummy inboxes
293 $ibx = $self->{imapd}->{mailboxes}->{lc $mailbox} or return;
294 $uid_base = $exists = 0;
297 ($ibx, $exists, $uidnext, $uid_base);
300 sub cmd_examine ($$$) {
301 my ($self, $tag, $mailbox) = @_;
302 my ($ibx, $exists, $uidnext, $base) = inbox_lookup($self, $mailbox);
303 return "$tag NO Mailbox doesn't exist: $mailbox\r\n" if !$ibx;
304 $self->{uid_base} = $base;
306 # XXX: do we need this? RFC 5162/7162
307 my $ret = $self->{ibx} ? "* OK [CLOSED] previous closed\r\n" : '';
313 * OK [PERMANENTFLAGS ()] Read-only mailbox\r
314 * OK [UNSEEN $exists]\r
315 * OK [UIDNEXT $uidnext]\r
316 * OK [UIDVALIDITY $ibx->{uidvalidity}]\r
317 $tag OK [READ-ONLY] EXAMINE/SELECT done\r
325 } elsif ($v =~ /[{"\r\n%*\\\[]/) { # literal string
326 '{' . length($v) . "}\r\n" . $v;
327 } else { # quoted string
332 sub addr_envelope ($$;$) {
333 my ($eml, $x, $y) = @_;
334 my $v = $eml->header_raw($x) //
335 ($y ? $eml->header_raw($y) : undef) // return 'NIL';
337 my @x = $Address->parse($v) or return 'NIL';
339 map { '(' . join(' ',
340 _esc($_->name), 'NIL',
341 _esc($_->user), _esc($_->host)
347 sub eml_envelope ($) {
350 _esc($eml->header_raw('Date')),
351 _esc($eml->header_raw('Subject')),
352 addr_envelope($eml, 'From'),
353 addr_envelope($eml, 'Sender', 'From'),
354 addr_envelope($eml, 'Reply-To', 'From'),
355 addr_envelope($eml, 'To'),
356 addr_envelope($eml, 'Cc'),
357 addr_envelope($eml, 'Bcc'),
358 _esc($eml->header_raw('In-Reply-To')),
359 _esc($eml->header_raw('Message-ID')),
365 if ($hash && scalar keys %$hash) {
366 $hash = [ %$hash ]; # flatten hash into 1-dimensional array
367 '(' . join(' ', map { _esc($_) } @$hash) . ')';
373 sub body_disposition ($) {
375 my $cd = $eml->header_raw('Content-Disposition') or return 'NIL';
376 $cd = parse_content_disposition($cd);
377 my $buf = '('._esc($cd->{type});
378 $buf .= ' ' . _esc_hash(delete $cd->{attributes});
382 sub body_leaf ($$;$) {
383 my ($eml, $structure, $hold) = @_;
385 $eml->{is_submsg} and # parent was a message/(rfc822|news|global)
386 $buf .= eml_envelope($eml). ' ';
388 $buf .= '('._esc($ct->{type}).' ';
389 $buf .= _esc($ct->{subtype});
390 $buf .= ' ' . _esc_hash(delete $ct->{attributes});
391 $buf .= ' ' . _esc($eml->header_raw('Content-ID'));
392 $buf .= ' ' . _esc($eml->header_raw('Content-Description'));
393 my $cte = $eml->header_raw('Content-Transfer-Encoding') // '7bit';
394 $buf .= ' ' . _esc($cte);
395 $buf .= ' ' . $eml->{imap_body_len};
396 $buf .= ' '.($eml->body_raw =~ tr/\n/\n/) if lc($ct->{type}) eq 'text';
398 # for message/(rfc822|global|news), $hold[0] should have envelope
399 $buf .= ' ' . (@$hold ? join('', @$hold) : 'NIL') if $hold;
402 $buf .= ' '._esc($eml->header_raw('Content-MD5'));
403 $buf .= ' '. body_disposition($eml);
404 $buf .= ' '._esc($eml->header_raw('Content-Language'));
405 $buf .= ' '._esc($eml->header_raw('Content-Location'));
410 sub body_parent ($$$) {
411 my ($eml, $structure, $hold) = @_;
413 my $type = lc($ct->{type});
414 if ($type eq 'multipart') {
416 $buf .= @$hold ? join('', @$hold) : 'NIL';
417 $buf .= ' '._esc($ct->{subtype});
419 $buf .= ' '._esc_hash(delete $ct->{attributes});
420 $buf .= ' '.body_disposition($eml);
421 $buf .= ' '._esc($eml->header_raw('Content-Language'));
422 $buf .= ' '._esc($eml->header_raw('Content-Location'));
426 } else { # message/(rfc822|global|news)
427 @$hold = (body_leaf($eml, $structure, $hold));
431 # this is gross, but we need to process the parent part AFTER
432 # the child parts are done
433 sub bodystructure_prep {
435 my ($eml, $depth) = @$p; # ignore idx
436 # set length here, as $eml->{bdy} gets deleted for message/rfc822
437 $eml->{imap_body_len} = length($eml->body_raw);
438 push @$q, $eml, $depth;
441 # for FETCH BODY and FETCH BODYSTRUCTURE
442 sub fetch_body ($;$) {
443 my ($eml, $structure) = @_;
445 $eml->each_part(\&bodystructure_prep, \@q, 0, 1);
449 my ($part, $depth) = splice(@q, -2);
450 my $is_mp_parent = $depth == ($cur_depth - 1);
454 body_parent($part, $structure, \@hold);
456 unshift @hold, body_leaf($part, $structure);
462 sub requeue_once ($) {
464 # COMPRESS users all share the same DEFLATE context.
465 # Flush it here to ensure clients don't see
469 # no recursion, schedule another call ASAP,
470 # but only after all pending writes are done.
472 my $new_size = push(@{$self->{wbuf}}, \&long_step);
474 # wbuf may be populated by $cb, no need to rearm if so:
475 $self->requeue if $new_size == 1;
478 # my ($uid_base, $UID) = @_;
479 sub fetch_msn_uid ($$) { '* '.($_[1] - $_[0]).' FETCH (UID '.$_[1] }
482 my ($self, $uid_base, $smsg, $bref, $ops, $partial) = @_;
483 $self->msg_more(fetch_msn_uid($uid_base, $smsg->{num}));
485 for (my $i = 0; $i < @$ops;) {
487 $ops->[$i++]->($self, $k, $smsg, $bref, $eml);
489 partial_emit($self, $partial, $eml) if $partial;
490 $self->msg_more(")\r\n");
493 sub fetch_blob_cb { # called by git->cat_async via git_async_cat
494 my ($bref, $oid, $type, $size, $fetch_arg) = @_;
495 my ($self, undef, $msgs, undef, $ops, $partial) = @$fetch_arg;
496 my $smsg = shift @$msgs or die 'BUG: no smsg';
497 if (!defined($oid)) {
498 # it's possible to have TOCTOU if an admin runs
499 # public-inbox-(edit|purge), just move onto the next message
500 return requeue_once($self);
502 $smsg->{blob} eq $oid or die "BUG: $smsg->{blob} != $oid";
504 fetch_run_ops($self, $self->{uid_base}, $smsg, $bref, $ops, $partial);
509 my ($self, $k, undef, $bref) = @_;
510 $self->msg_more(" $k {" . length($$bref)."}\r\n");
511 $self->msg_more($$bref);
514 # Mail::IMAPClient::message_string cares about this by default,
515 # (->Ignoresizeerrors attribute). Admins are encouraged to
516 # --reindex for IMAP support, anyways.
517 sub emit_rfc822_size {
518 my ($self, $k, $smsg) = @_;
519 $self->msg_more(' RFC822.SIZE ' . $smsg->{bytes});
522 sub emit_internaldate {
523 my ($self, undef, $smsg) = @_;
524 $self->msg_more(' INTERNALDATE "'.$smsg->internaldate.'"');
527 sub emit_flags { $_[0]->msg_more(' FLAGS ()') }
530 my ($self, undef, undef, undef, $eml) = @_;
531 $self->msg_more(' ENVELOPE '.eml_envelope($eml));
534 sub emit_rfc822_header {
535 my ($self, $k, undef, undef, $eml) = @_;
536 $self->msg_more(" $k {".length(${$eml->{hdr}})."}\r\n");
537 $self->msg_more(${$eml->{hdr}});
540 # n.b. this is sorted to be after any emit_eml_new ops
541 sub emit_rfc822_text {
542 my ($self, $k, undef, $bref) = @_;
543 $self->msg_more(" $k {".length($$bref)."}\r\n");
544 $self->msg_more($$bref);
547 sub emit_bodystructure {
548 my ($self, undef, undef, undef, $eml) = @_;
549 $self->msg_more(' BODYSTRUCTURE '.fetch_body($eml, 1));
553 my ($self, undef, undef, undef, $eml) = @_;
554 $self->msg_more(' BODY '.fetch_body($eml));
557 # set $eml once ($_[4] == $eml, $_[3] == $bref)
558 sub op_eml_new { $_[4] = PublicInbox::Eml->new($_[3]) }
560 # s/From / fixes old bug from import (pre-a0c07cba0e5d8b6a)
562 ${$_[0]} =~ s/(?<!\r)\n/\r\n/sg;
563 ${$_[0]} =~ s/\A[\r\n]*From [^\r\n]*\r\n//s;
566 sub op_crlf_bref { to_crlf_full($_[3]) }
568 sub op_crlf_hdr { to_crlf_full($_[4]->{hdr}) }
570 sub op_crlf_bdy { ${$_[4]->{bdy}} =~ s/(?<!\r)\n/\r\n/sg if $_[4]->{bdy} }
572 sub uid_clamp ($$$) {
573 my ($self, $beg, $end) = @_;
574 my $uid_min = $self->{uid_base} + 1;
575 my $uid_end = $uid_min + UID_BLOCK - 1;
576 $$beg = $uid_min if $$beg < $uid_min;
577 $$end = $uid_end if $$end > $uid_end;
580 sub range_step ($$) {
581 my ($self, $range_csv) = @_;
582 my ($beg, $end, $range);
583 if ($$range_csv =~ s/\A([^,]+),//) {
586 $range = $$range_csv;
589 if ($range =~ /\A([0-9]+):([0-9]+)\z/) {
590 ($beg, $end) = ($1 + 0, $2 + 0);
591 } elsif ($range =~ /\A([0-9]+):\*\z/) {
593 $end = $self->{ibx}->mm->max // 0;
594 my $uid_end = $self->{uid_base} + UID_BLOCK;
595 $end = $uid_end if $end > $uid_end;
596 $beg = $end if $beg > $end;
597 } elsif ($range =~ /\A[0-9]+\z/) {
598 $beg = $end = $range + 0;
601 return 'BAD fetch range';
603 uid_clamp($self, \$beg, \$end) if defined($range);
604 [ $beg, $end, $$range_csv ];
607 sub refill_range ($$$) {
608 my ($self, $msgs, $range_info) = @_;
609 my ($beg, $end, $range_csv) = @$range_info;
610 if (scalar(@$msgs = @{$self->{ibx}->over->query_xover($beg, $end)})) {
611 $range_info->[0] = $msgs->[-1]->{num} + 1;
614 return 'OK Fetch done' if !$range_csv;
615 my $next_range = range_step($self, \$range_csv);
616 return $next_range if !ref($next_range); # error
617 @$range_info = @$next_range;
618 undef; # keep looping
621 sub fetch_blob { # long_response
622 my ($self, $tag, $msgs, $range_info, $ops, $partial) = @_;
623 while (!@$msgs) { # rare
624 if (my $end = refill_range($self, $msgs, $range_info)) {
625 $self->write(\"$tag $end\r\n");
629 git_async_cat($self->{ibx}->git, $msgs->[0]->{blob},
630 \&fetch_blob_cb, \@_);
633 sub fetch_smsg { # long_response
634 my ($self, $tag, $msgs, $range_info, $ops) = @_;
635 while (!@$msgs) { # rare
636 if (my $end = refill_range($self, $msgs, $range_info)) {
637 $self->write(\"$tag $end\r\n");
641 my $uid_base = $self->{uid_base};
642 fetch_run_ops($self, $uid_base, $_, undef, $ops) for @$msgs;
647 sub fetch_uid { # long_response
648 my ($self, $tag, $uids, $range_info, $ops) = @_;
650 while (!@$uids) { # rare
651 my ($beg, $end, $range_csv) = @$range_info;
652 if (scalar(@$uids = @{$self->{ibx}->over->
653 uid_range($beg, $end)})) {
654 $range_info->[0] = $uids->[-1] + 1;
655 } elsif (!$range_csv) {
656 $self->write(\"$tag OK Fetch done\r\n");
659 my $next_range = range_step($self, \$range_csv);
660 if (!ref($next_range)) { # error
661 $self->write(\"$tag $next_range\r\n");
664 @$range_info = @$next_range;
668 my $uid_base = $self->{uid_base};
671 $self->msg_more(fetch_msn_uid($uid_base, $_));
672 for ($i = 0; $i < @$ops;) {
674 $ops->[$i++]->($self, $k);
676 $self->msg_more(")\r\n");
682 sub cmd_status ($$$;@) {
683 my ($self, $tag, $mailbox, @items) = @_;
684 return "$tag BAD no items\r\n" if !scalar(@items);
685 ($items[0] !~ s/\A\(//s || $items[-1] !~ s/\)\z//s) and
686 return "$tag BAD invalid args\r\n";
687 my ($ibx, $exists, $uidnext) = inbox_lookup($self, $mailbox);
688 return "$tag NO Mailbox doesn't exist: $mailbox\r\n" if !$ibx;
690 for my $it (@items) {
693 if ($it =~ /\A(?:MESSAGES|UNSEEN|RECENT)\z/) {
695 } elsif ($it eq 'UIDNEXT') {
697 } elsif ($it eq 'UIDVALIDITY') {
698 push @it, $ibx->{uidvalidity};
700 return "$tag BAD invalid item\r\n";
703 return "$tag BAD no items\r\n" if !@it;
704 "* STATUS $mailbox (".join(' ', @it).")\r\n" .
705 "$tag OK Status done\r\n";
708 my %patmap = ('*' => '.*', '%' => '[^\.]*');
709 sub cmd_list ($$$$) {
710 my ($self, $tag, $refname, $wildcard) = @_;
711 my $l = $self->{imapd}->{inboxlist};
712 if ($refname eq '' && $wildcard eq '') {
713 # request for hierarchy delimiter
714 $l = [ qq[* LIST (\\Noselect) "." ""\r\n] ];
715 } elsif ($refname ne '' || $wildcard ne '*') {
716 $wildcard =~ s!([^a-z0-9_])!$patmap{$1} // "\Q$1"!egi;
717 $l = [ grep(/ \Q$refname\E$wildcard\r\n\z/is, @$l) ];
719 \(join('', @$l, "$tag OK List done\r\n"));
722 sub cmd_lsub ($$$$) {
723 my (undef, $tag) = @_; # same args as cmd_list
724 "$tag OK Lsub done\r\n";
727 sub eml_index_offs_i { # PublicInbox::Eml::each_part callback
729 my ($eml, undef, $idx) = @$p;
730 if ($idx && lc($eml->ct->{type}) eq 'multipart') {
731 $eml->{imap_bdy} = $eml->{bdy} // \'';
733 $all->{$idx} = $eml; # $idx => Eml
736 # prepares an index for BODY[$SECTION_IDX] fetches
737 sub eml_body_idx ($$) {
738 my ($eml, $section_idx) = @_;
739 my $idx = $eml->{imap_all_parts} //= do {
741 $eml->each_part(\&eml_index_offs_i, $all, 0, 1);
742 # top-level of multipart, BODY[0] not allowed (nz-number)
746 $idx->{$section_idx};
749 # BODY[($SECTION_IDX)?(.$SECTION_NAME)?]<$offset.$bytes>
751 my ($eml, $section_idx, $section_name) = @_;
752 if (defined $section_idx) {
753 $eml = eml_body_idx($eml, $section_idx) or return;
755 if (defined $section_name) {
756 if ($section_name eq 'MIME') {
757 # RFC 3501 6.4.5 states:
758 # The MIME part specifier MUST be prefixed
759 # by one or more numeric part specifiers
760 return unless defined $section_idx;
761 return $eml->header_obj->as_string . "\r\n";
763 my $bdy = $eml->{bdy} // $eml->{imap_bdy} // \'';
764 $eml = PublicInbox::Eml->new($$bdy);
765 if ($section_name eq 'TEXT') {
766 return $eml->body_raw;
767 } elsif ($section_name eq 'HEADER') {
768 return $eml->header_obj->as_string . "\r\n";
770 die "BUG: bad section_name=$section_name";
773 ${$eml->{bdy} // $eml->{imap_bdy} // \''};
776 # similar to what's in PublicInbox::Eml::re_memo, but doesn't memoize
777 # to avoid OOM with malicious users
778 sub hdrs_regexp ($) {
780 my $names = join('|', map { "\Q$_" } split(/[ \t]+/, $hdrs));
781 qr/^(?:$names):[ \t]*[^\n]*\r?\n # 1st line
782 # continuation lines:
783 (?:[^:\n]*?[ \t]+[^\n]*\r?\n)*
787 # BODY[($SECTION_IDX.)?HEADER.FIELDS.NOT ($HDRS)]<$offset.$bytes>
788 sub partial_hdr_not {
789 my ($eml, $section_idx, $hdrs_re) = @_;
790 if (defined $section_idx) {
791 $eml = eml_body_idx($eml, $section_idx) or return;
793 my $str = $eml->header_obj->as_string;
794 $str =~ s/$hdrs_re//g;
795 $str =~ s/(?<!\r)\n/\r\n/sg;
799 # BODY[($SECTION_IDX.)?HEADER.FIELDS ($HDRS)]<$offset.$bytes>
800 sub partial_hdr_get {
801 my ($eml, $section_idx, $hdrs_re) = @_;
802 if (defined $section_idx) {
803 $eml = eml_body_idx($eml, $section_idx) or return;
805 my $str = $eml->header_obj->as_string;
806 $str = join('', ($str =~ m/($hdrs_re)/g));
807 $str =~ s/(?<!\r)\n/\r\n/sg;
811 sub partial_prepare ($$$$) {
812 my ($need, $partial, $want, $att) = @_;
814 # recombine [ "BODY[1.HEADER.FIELDS", "(foo", "bar)]" ]
815 # back to: "BODY[1.HEADER.FIELDS (foo bar)]"
816 return unless $att =~ /\ABODY\[/s;
817 until (rindex($att, ']') >= 0) {
818 my $next = shift @$want or return;
819 $att .= ' ' . uc($next);
821 if ($att =~ /\ABODY\[([0-9]+(?:\.[0-9]+)*)? # 1 - section_idx
822 (?:\.(HEADER|MIME|TEXT))? # 2 - section_name
823 \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 3, 4
824 $partial->{$att} = [ \&partial_body, $1, $2, $3, $4 ];
825 $$need |= CRLF_BREF|EML_HDR|EML_BDY;
826 } elsif ($att =~ /\ABODY\[(?:([0-9]+(?:\.[0-9]+)*)\.)? # 1 - section_idx
827 (?:HEADER\.FIELDS(\.NOT)?)\x20 # 2
828 \(([A-Z0-9\-\x20]+)\) # 3 - hdrs
829 \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 4 5
830 my $tmp = $partial->{$att} = [ $2 ? \&partial_hdr_not
833 $tmp->[2] = hdrs_regexp($3);
835 # don't emit CRLF_HDR instruction, here, partial_hdr_*
836 # will do CRLF conversion with only the extracted result
837 # and not waste time converting lines we don't care about.
844 sub partial_emit ($$$) {
845 my ($self, $partial, $eml) = @_;
847 my ($k, $cb, @args) = @$_;
848 my ($offset, $len) = splice(@args, -2);
849 # $cb is partial_body|partial_hdr_get|partial_hdr_not
850 my $str = $cb->($eml, @args) // '';
851 if (defined $offset) {
853 $str = substr($str, $offset, $len);
854 $k =~ s/\.$len>\z/>/ or warn
855 "BUG: unable to remove `.$len>' from `$k'";
857 $str = substr($str, $offset);
863 $self->msg_more(" $k {$len}\r\n");
864 $self->msg_more($str);
868 sub fetch_compile ($) {
870 if ($want->[0] =~ s/\A\(//s) {
871 $want->[-1] =~ s/\)\z//s or return 'BAD no rparen';
873 my (%partial, %seen, @op);
875 while (defined(my $att = shift @$want)) {
877 next if $att eq 'UID'; # always returned
878 $att =~ s/\ABODY\.PEEK\[/BODY\[/; # we're read-only
879 my $x = $FETCH_ATT{$att};
881 while (my ($k, $fl_cb) = each %$x) {
883 $need |= $fl_cb->[0];
884 push @op, [ @$fl_cb, $k ];
886 } elsif (!partial_prepare(\$need, \%partial, $want, $att)) {
887 return "BAD param: $att";
892 # stabilize partial order for consistency and ease-of-debugging:
893 if (scalar keys %partial) {
895 $r[2] = [ map { [ $_, @{$partial{$_}} ] } sort keys %partial ];
898 push @op, $OP_EML_NEW if ($need & (EML_HDR|EML_BDY));
900 # do we need CRLF conversion?
901 if ($need & CRLF_BREF) {
902 push @op, $OP_CRLF_BREF;
903 } elsif (my $crlf = ($need & (CRLF_HDR|CRLF_BDY))) {
904 if ($crlf == (CRLF_HDR|CRLF_BDY)) {
905 push @op, $OP_CRLF_BREF;
906 } elsif ($need & CRLF_HDR) {
907 push @op, $OP_CRLF_HDR;
909 push @op, $OP_CRLF_BDY;
913 $r[0] = $need & NEED_BLOB ? \&fetch_blob :
914 ($need & NEED_SMSG ? \&fetch_smsg : \&fetch_uid);
916 # r[1] = [ $key1, $cb1, $key2, $cb2, ... ]
917 use sort 'stable'; # makes output more consistent
918 $r[1] = [ map { ($_->[2], $_->[1]) } sort { $a->[0] <=> $b->[0] } @op ];
922 sub cmd_uid_fetch ($$$$;@) {
923 my ($self, $tag, $range_csv, @want) = @_;
924 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
925 my ($cb, $ops, $partial) = fetch_compile(\@want);
926 return "$tag $cb\r\n" unless $ops;
928 $range_csv = 'bad' if $range_csv !~ $valid_range;
929 my $range_info = range_step($self, \$range_csv);
930 return "$tag $range_info\r\n" if !ref($range_info);
931 long_response($self, $cb, $tag, [], $range_info, $ops, $partial);
934 sub msn_to_uid_range ($$) {
935 my $uid_base = $_[0]->{uid_base};
936 $_[1] =~ s/([0-9]+)/$uid_base + $1/sge;
939 sub cmd_fetch ($$$$;@) {
940 my ($self, $tag, $range_csv, @want) = @_;
941 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
942 my ($cb, $ops, $partial) = fetch_compile(\@want);
943 return "$tag $cb\r\n" unless $ops;
945 # cb is one of fetch_blob, fetch_smsg, fetch_uid
946 $range_csv = 'bad' if $range_csv !~ $valid_range;
947 msn_to_uid_range($self, $range_csv);
948 my $range_info = range_step($self, \$range_csv);
949 return "$tag $range_info\r\n" if !ref($range_info);
950 long_response($self, $cb, $tag, [], $range_info, $ops, $partial);
953 sub parse_date ($) { # 02-Oct-1993
954 my ($date_text) = @_;
955 my ($dd, $mon, $yyyy) = split(/-/, $_[0], 3);
956 defined($yyyy) or return;
957 my $mm = $MoY{$mon} // return;
958 $dd =~ /\A[0123]?[0-9]\z/ or return;
959 $yyyy =~ /\A[0-9]{4,}\z/ or return; # Y10K-compatible!
960 timegm(0, 0, 0, $dd, $mm, $yyyy);
963 sub uid_search_uid_range { # long_response
964 my ($self, $tag, $beg, $end, $sql) = @_;
965 my $uids = $self->{ibx}->over->uid_range($$beg, $end, $sql);
967 $$beg = $uids->[-1] + 1;
968 $self->msg_more(join(' ', '', @$uids));
970 $self->write(\"\r\n$tag OK Search done\r\n");
976 my ($q, $k, $d) = @_;
980 if ($k eq 'SENTON') {
981 my $end = $d + 86399; # no leap day...
982 my $da = strftime('%Y%m%d%H%M%S', gmtime($d));
983 my $db = strftime('%Y%m%d%H%M%S', gmtime($end));
984 $q->{xap} .= " dt:$da..$db";
985 $$sql .= " AND ds >= $d AND ds <= $end" if defined($sql);
986 } elsif ($k eq 'SENTBEFORE') {
987 $q->{xap} .= ' d:..'.strftime('%Y%m%d', gmtime($d));
988 $$sql .= " AND ds <= $d" if defined($sql);
989 } elsif ($k eq 'SENTSINCE') {
990 $q->{xap} .= ' d:'.strftime('%Y%m%d', gmtime($d)).'..';
991 $$sql .= " AND ds >= $d" if defined($sql);
993 # INTERNALDATE (Received)
994 } elsif ($k eq 'ON') {
995 my $end = $d + 86399; # no leap day...
996 $q->{xap} .= " ts:$d..$end";
997 $$sql .= " AND ts >= $d AND ts <= $end" if defined($sql);
998 } elsif ($k eq 'BEFORE') {
999 $q->{xap} .= " ts:..$d";
1000 $$sql .= " AND ts <= $d" if defined($sql);
1001 } elsif ($k eq 'SINCE') {
1002 $q->{xap} .= " ts:$d..";
1003 $$sql .= " AND ts >= $d" if defined($sql);
1005 die "BUG: $k not recognized";
1009 # IMAP to Xapian search key mapping
1014 TEXT => '', # n.b. does not include all headers
1017 # BCC => 'bcc:', # TODO
1018 # KEYWORD # TODO ? dfpre,dfpost,...
1022 my ($self, $rest) = @_;
1023 if (uc($rest->[0]) eq 'CHARSET') {
1025 defined(my $c = shift @$rest) or return 'BAD missing charset';
1026 $c =~ /\A(?:UTF-8|US-ASCII)\z/ or return 'NO [BADCHARSET]';
1029 my $sql = ''; # date conditions, {sql} deleted if Xapian is needed
1030 my $q = { xap => '', sql => \$sql };
1032 my $k = uc(shift @$rest);
1034 next if $k =~ /\A(?:ALL|RECENT|UNSEEN|NEW)\z/;
1035 next if $k eq 'AND'; # the default, until we support OR
1036 if ($k =~ $valid_range) { # convert sequence numbers to UIDs
1037 msn_to_uid_range($self, $k);
1038 push @{$q->{uid}}, $k;
1039 } elsif ($k eq 'UID') {
1040 $k = shift(@$rest) // '';
1041 $k =~ $valid_range or return 'BAD UID range';
1042 push @{$q->{uid}}, $k;
1043 } elsif ($k =~ /\A(?:SENT)?(?:SINCE|ON|BEFORE)\z/) {
1044 my $d = parse_date(shift(@$rest) // '');
1045 defined $d or return "BAD $k date format";
1046 date_search($q, $k, $d);
1047 } elsif ($k =~ /\A(?:SMALLER|LARGER)\z/) {
1048 delete $q->{sql}; # can't use over.sqlite3
1049 my $bytes = shift(@$rest) // '';
1050 $bytes =~ /\A[0-9]+\z/ or return "BAD $k not a number";
1051 $q->{xap} .= ' bytes:' . ($k eq 'SMALLER' ?
1054 } elsif (defined(my $xk = $I2X{$k})) {
1055 delete $q->{sql}; # can't use over.sqlite3
1056 my $arg = shift @$rest;
1057 defined($arg) or return "BAD $k no arg";
1059 # Xapian can't handle [*"] in probabilistic terms
1061 $q->{xap} .= qq[ $xk:"$arg"];
1063 # TODO: parentheses, OR, NOT ...
1064 return "BAD $k not supported (yet?)";
1068 # favor using over.sqlite3 if possible, since Xapian is optional
1069 if (exists $q->{sql}) {
1071 delete($q->{sql}) if $sql eq '';
1072 } elsif (!$self->{ibx}->search) {
1073 return 'BAD Xapian not configured for mailbox';
1076 if (my $uid = $q->{uid}) {
1077 ((@$uid > 1) || $uid->[0] =~ /,/) and
1078 return 'BAD multiple ranges not supported, yet';
1079 ($q->{sql} // $q->{xap}) and
1080 return 'BAD ranges and queries do not mix, yet';
1081 $q->{uid} = join(',', @$uid); # TODO: multiple ranges
1086 sub cmd_uid_search ($$$;) {
1087 my ($self, $tag) = splice(@_, 0, 2);
1088 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1089 my $q = parse_query($self, \@_);
1090 return "$tag $q\r\n" if !ref($q);
1091 my $sql = delete $q->{sql};
1093 if (!scalar(keys %$q)) {
1094 $self->msg_more('* SEARCH');
1096 my $end = $ibx->mm->max // 0;
1097 uid_clamp($self, \$beg, \$end);
1098 long_response($self, \&uid_search_uid_range,
1099 $tag, \$beg, $end, $sql);
1100 } elsif (my $uid = $q->{uid}) {
1101 if ($uid =~ /\A([0-9]+):([0-9]+|\*)\z/s) {
1102 my ($beg, $end) = ($1, $2);
1103 $end = $ibx->mm->max if $end eq '*';
1104 uid_clamp($self, \$beg, \$end);
1105 $self->msg_more('* SEARCH');
1106 long_response($self, \&uid_search_uid_range,
1107 $tag, \$beg, $end, $sql);
1108 } elsif ($uid =~ /\A[0-9]+\z/s) {
1109 $uid = $ibx->over->get_art($uid) ? " $uid" : '';
1110 "* SEARCH$uid\r\n$tag OK Search done\r\n";
1112 "$tag BAD Error\r\n";
1115 "$tag BAD Error\r\n";
1119 sub args_ok ($$) { # duplicated from PublicInbox::NNTP
1120 my ($cb, $argc) = @_;
1121 my $tot = prototype $cb;
1122 my ($nreq, undef) = split(';', $tot);
1123 $nreq = ($nreq =~ tr/$//) - 1;
1124 $tot = ($tot =~ tr/$//) - 1;
1125 ($argc <= $tot && $argc >= $nreq);
1128 # returns 1 if we can continue, 0 if not due to buffered writes or disconnect
1129 sub process_line ($$) {
1130 my ($self, $l) = @_;
1131 my ($tag, $req, @args) = parse_line('[ \t]+', 0, $l);
1132 pop(@args) if (@args && !defined($args[-1]));
1133 if (@args && uc($req) eq 'UID') {
1134 $req .= "_".(shift @args);
1137 if (my $cmd = $self->can('cmd_'.lc($req // ''))) {
1138 defined($self->{-idle_tag}) ?
1139 "$self->{-idle_tag} BAD expected DONE\r\n" :
1140 $cmd->($self, $tag, @args);
1141 } elsif (uc($tag // '') eq 'DONE' && !defined($req)) {
1142 cmd_done($self, $tag);
1143 } else { # this is weird
1144 auth_challenge_ok($self) //
1146 ' BAD Error in IMAP command '.
1148 ": Unknown command\r\n";
1152 if ($err && $self->{sock}) {
1154 err($self, 'error from: %s (%s)', $l, $err);
1156 $res = "$tag BAD program fault - command not performed\r\n";
1158 return 0 unless defined $res;
1164 # wbuf is unset or empty, here; {long} may add to it
1165 my ($fd, $cb, $t0, @args) = @{$self->{long_cb}};
1166 my $more = eval { $cb->($self, @args) };
1167 if ($@ || !$self->{sock}) { # something bad happened...
1168 delete $self->{long_cb};
1169 my $elapsed = now() - $t0;
1172 "%s during long response[$fd] - %0.6f",
1175 out($self, " deferred[$fd] aborted - %0.6f", $elapsed);
1177 } elsif ($more) { # $self->{wbuf}:
1178 $self->update_idle_time;
1180 # control passed to $more may be a GitAsyncCat object
1181 requeue_once($self) if !ref($more);
1182 } else { # all done!
1183 delete $self->{long_cb};
1184 my $elapsed = now() - $t0;
1185 my $fd = fileno($self->{sock});
1186 out($self, " deferred[$fd] done - %0.6f", $elapsed);
1187 my $wbuf = $self->{wbuf}; # do NOT autovivify
1189 $self->requeue unless $wbuf && @$wbuf;
1194 my ($self, $fmt, @args) = @_;
1195 printf { $self->{imapd}->{err} } $fmt."\n", @args;
1199 my ($self, $fmt, @args) = @_;
1200 printf { $self->{imapd}->{out} } $fmt."\n", @args;
1203 sub long_response ($$;@) {
1204 my ($self, $cb, @args) = @_; # cb returns true if more, false if done
1206 my $sock = $self->{sock} or return;
1207 # make sure we disable reading during a long response,
1208 # clients should not be sending us stuff and making us do more
1209 # work while we are stream a response to them
1210 $self->{long_cb} = [ fileno($sock), $cb, now(), @args ];
1211 long_step($self); # kick off!
1215 # callback used by PublicInbox::DS for any (e)poll (in/out/hup/err)
1219 return unless $self->flush_write && $self->{sock} && !$self->{long_cb};
1221 $self->update_idle_time;
1222 # only read more requests if we've drained the write buffer,
1223 # otherwise we can be buffering infinitely w/o backpressure
1225 my $rbuf = $self->{rbuf} // \(my $x = '');
1226 my $line = index($$rbuf, "\n");
1228 if (length($$rbuf) >= LINE_MAX) {
1229 $self->write(\"\* BAD request too long\r\n");
1230 return $self->close;
1232 $self->do_read($rbuf, LINE_MAX, length($$rbuf)) or return;
1233 $line = index($$rbuf, "\n");
1235 $line = substr($$rbuf, 0, $line + 1, '');
1236 $line =~ s/\r?\n\z//s;
1237 return $self->close if $line =~ /[[:cntrl:]]/s;
1239 my $fd = fileno($self->{sock});
1240 my $r = eval { process_line($self, $line) };
1241 my $pending = $self->{wbuf} ? ' pending' : '';
1242 out($self, "[$fd] %s - %0.6f$pending - $r", $line, now() - $t0);
1244 return $self->close if $r < 0;
1245 $self->rbuf_idle($rbuf);
1246 $self->update_idle_time;
1248 # maybe there's more pipelined data, or we'll have
1249 # to register it for socket-readiness notifications
1250 $self->requeue unless $pending;
1253 sub compressed { undef }
1255 sub zflush {} # overridden by IMAPdeflate
1258 sub cmd_compress ($$$) {
1259 my ($self, $tag, $alg) = @_;
1260 return "$tag BAD DEFLATE only\r\n" if uc($alg) ne "DEFLATE";
1261 return "$tag BAD COMPRESS active\r\n" if $self->compressed;
1263 # CRIME made TLS compression obsolete
1264 # return "$tag NO [COMPRESSIONACTIVE]\r\n" if $self->tls_compressed;
1266 PublicInbox::IMAPdeflate->enable($self, $tag);
1271 sub cmd_starttls ($$) {
1272 my ($self, $tag) = @_;
1273 my $sock = $self->{sock} or return;
1274 if ($sock->can('stop_SSL') || $self->compressed) {
1275 return "$tag BAD TLS or compression already enabled\r\n";
1277 my $opt = $self->{imapd}->{accept_tls} or
1278 return "$tag BAD can not initiate TLS negotiation\r\n";
1279 $self->write(\"$tag OK begin TLS negotiation now\r\n");
1280 $self->{sock} = IO::Socket::SSL->start_SSL($sock, %$opt);
1281 $self->requeue if PublicInbox::DS::accept_tls_step($self);
1285 # for graceful shutdown in PublicInbox::Daemon:
1287 my ($self, $now) = @_;
1288 ($self->{rbuf} || $self->{wbuf} || $self->not_idle_long($now));
1293 if (my $ibx = delete $self->{ibx}) {
1294 stop_idle($self, $ibx);
1296 $self->SUPER::close; # PublicInbox::DS::close
1299 # we're read-only, so SELECT and EXAMINE do the same thing
1301 *cmd_select = \&cmd_examine;
1303 package PublicInbox::IMAP_preauth;
1304 our @ISA = qw(PublicInbox::IMAP);