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->over->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->over->max;
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;
287 ($exists, $uidnext, $max) = $ibx->over->imap_status($uid_base,
288 $uid_base + UID_BLOCK);
289 ensure_ranges_exist($self->{imapd}, $ibx, $max);
290 } else { # check for dummy inboxes
291 $mailbox = lc $mailbox;
292 $ibx = $self->{imapd}->{mailboxes}->{$mailbox} or return;
294 # if "INBOX.foo.bar" is selected and "INBOX.foo.bar.0",
295 # check for new UID ranges (e.g. "INBOX.foo.bar.1")
296 if (my $z = $self->{imapd}->{mailboxes}->{"$mailbox.0"}) {
297 ensure_ranges_exist($self->{imapd}, $z, $z->over->max);
300 $uid_base = $exists = 0;
303 ($ibx, $exists, $uidnext, $uid_base);
306 sub cmd_examine ($$$) {
307 my ($self, $tag, $mailbox) = @_;
308 my ($ibx, $exists, $uidnext, $base) = inbox_lookup($self, $mailbox);
309 return "$tag NO Mailbox doesn't exist: $mailbox\r\n" if !$ibx;
310 $self->{uid_base} = $base;
312 # XXX: do we need this? RFC 5162/7162
313 my $ret = $self->{ibx} ? "* OK [CLOSED] previous closed\r\n" : '';
319 * OK [PERMANENTFLAGS ()] Read-only mailbox\r
320 * OK [UNSEEN $exists]\r
321 * OK [UIDNEXT $uidnext]\r
322 * OK [UIDVALIDITY $ibx->{uidvalidity}]\r
323 $tag OK [READ-ONLY] EXAMINE/SELECT done\r
331 } elsif ($v =~ /[{"\r\n%*\\\[]/) { # literal string
332 '{' . length($v) . "}\r\n" . $v;
333 } else { # quoted string
338 sub addr_envelope ($$;$) {
339 my ($eml, $x, $y) = @_;
340 my $v = $eml->header_raw($x) //
341 ($y ? $eml->header_raw($y) : undef) // return 'NIL';
343 my @x = $Address->parse($v) or return 'NIL';
345 map { '(' . join(' ',
346 _esc($_->name), 'NIL',
347 _esc($_->user), _esc($_->host)
353 sub eml_envelope ($) {
356 _esc($eml->header_raw('Date')),
357 _esc($eml->header_raw('Subject')),
358 addr_envelope($eml, 'From'),
359 addr_envelope($eml, 'Sender', 'From'),
360 addr_envelope($eml, 'Reply-To', 'From'),
361 addr_envelope($eml, 'To'),
362 addr_envelope($eml, 'Cc'),
363 addr_envelope($eml, 'Bcc'),
364 _esc($eml->header_raw('In-Reply-To')),
365 _esc($eml->header_raw('Message-ID')),
371 if ($hash && scalar keys %$hash) {
372 $hash = [ %$hash ]; # flatten hash into 1-dimensional array
373 '(' . join(' ', map { _esc($_) } @$hash) . ')';
379 sub body_disposition ($) {
381 my $cd = $eml->header_raw('Content-Disposition') or return 'NIL';
382 $cd = parse_content_disposition($cd);
383 my $buf = '('._esc($cd->{type});
384 $buf .= ' ' . _esc_hash(delete $cd->{attributes});
388 sub body_leaf ($$;$) {
389 my ($eml, $structure, $hold) = @_;
391 $eml->{is_submsg} and # parent was a message/(rfc822|news|global)
392 $buf .= eml_envelope($eml). ' ';
394 $buf .= '('._esc($ct->{type}).' ';
395 $buf .= _esc($ct->{subtype});
396 $buf .= ' ' . _esc_hash(delete $ct->{attributes});
397 $buf .= ' ' . _esc($eml->header_raw('Content-ID'));
398 $buf .= ' ' . _esc($eml->header_raw('Content-Description'));
399 my $cte = $eml->header_raw('Content-Transfer-Encoding') // '7bit';
400 $buf .= ' ' . _esc($cte);
401 $buf .= ' ' . $eml->{imap_body_len};
402 $buf .= ' '.($eml->body_raw =~ tr/\n/\n/) if lc($ct->{type}) eq 'text';
404 # for message/(rfc822|global|news), $hold[0] should have envelope
405 $buf .= ' ' . (@$hold ? join('', @$hold) : 'NIL') if $hold;
408 $buf .= ' '._esc($eml->header_raw('Content-MD5'));
409 $buf .= ' '. body_disposition($eml);
410 $buf .= ' '._esc($eml->header_raw('Content-Language'));
411 $buf .= ' '._esc($eml->header_raw('Content-Location'));
416 sub body_parent ($$$) {
417 my ($eml, $structure, $hold) = @_;
419 my $type = lc($ct->{type});
420 if ($type eq 'multipart') {
422 $buf .= @$hold ? join('', @$hold) : 'NIL';
423 $buf .= ' '._esc($ct->{subtype});
425 $buf .= ' '._esc_hash(delete $ct->{attributes});
426 $buf .= ' '.body_disposition($eml);
427 $buf .= ' '._esc($eml->header_raw('Content-Language'));
428 $buf .= ' '._esc($eml->header_raw('Content-Location'));
432 } else { # message/(rfc822|global|news)
433 @$hold = (body_leaf($eml, $structure, $hold));
437 # this is gross, but we need to process the parent part AFTER
438 # the child parts are done
439 sub bodystructure_prep {
441 my ($eml, $depth) = @$p; # ignore idx
442 # set length here, as $eml->{bdy} gets deleted for message/rfc822
443 $eml->{imap_body_len} = length($eml->body_raw);
444 push @$q, $eml, $depth;
447 # for FETCH BODY and FETCH BODYSTRUCTURE
448 sub fetch_body ($;$) {
449 my ($eml, $structure) = @_;
451 $eml->each_part(\&bodystructure_prep, \@q, 0, 1);
455 my ($part, $depth) = splice(@q, -2);
456 my $is_mp_parent = $depth == ($cur_depth - 1);
460 body_parent($part, $structure, \@hold);
462 unshift @hold, body_leaf($part, $structure);
468 sub requeue_once ($) {
470 # COMPRESS users all share the same DEFLATE context.
471 # Flush it here to ensure clients don't see
475 # no recursion, schedule another call ASAP,
476 # but only after all pending writes are done.
478 my $new_size = push(@{$self->{wbuf}}, \&long_step);
480 # wbuf may be populated by $cb, no need to rearm if so:
481 $self->requeue if $new_size == 1;
484 # my ($msn, $UID) = @_;
485 sub fetch_msn_uid ($$) { '* '.(${$_[0]}++).' FETCH (UID '.$_[1] }
488 my ($self, $msn, $smsg, $bref, $ops, $partial) = @_;
489 $self->msg_more(fetch_msn_uid($msn, $smsg->{num}));
491 for (my $i = 0; $i < @$ops;) {
493 $ops->[$i++]->($self, $k, $smsg, $bref, $eml);
495 partial_emit($self, $partial, $eml) if $partial;
496 $self->msg_more(")\r\n");
499 sub fetch_blob_cb { # called by git->cat_async via git_async_cat
500 my ($bref, $oid, $type, $size, $fetch_arg) = @_;
501 my ($self, undef, $msgs, $range_info, $ops, $partial) = @$fetch_arg;
502 my $smsg = shift @$msgs or die 'BUG: no smsg';
503 if (!defined($oid)) {
504 # it's possible to have TOCTOU if an admin runs
505 # public-inbox-(edit|purge), just move onto the next message
506 return requeue_once($self);
508 $smsg->{blob} eq $oid or die "BUG: $smsg->{blob} != $oid";
510 fetch_run_ops($self, $range_info->[3], $smsg, $bref, $ops, $partial);
515 my ($self, $k, undef, $bref) = @_;
516 $self->msg_more(" $k {" . length($$bref)."}\r\n");
517 $self->msg_more($$bref);
520 # Mail::IMAPClient::message_string cares about this by default,
521 # (->Ignoresizeerrors attribute). Admins are encouraged to
522 # --reindex for IMAP support, anyways.
523 sub emit_rfc822_size {
524 my ($self, $k, $smsg) = @_;
525 $self->msg_more(' RFC822.SIZE ' . $smsg->{bytes});
528 sub emit_internaldate {
529 my ($self, undef, $smsg) = @_;
530 $self->msg_more(' INTERNALDATE "'.$smsg->internaldate.'"');
533 sub emit_flags { $_[0]->msg_more(' FLAGS ()') }
536 my ($self, undef, undef, undef, $eml) = @_;
537 $self->msg_more(' ENVELOPE '.eml_envelope($eml));
540 sub emit_rfc822_header {
541 my ($self, $k, undef, undef, $eml) = @_;
542 $self->msg_more(" $k {".length(${$eml->{hdr}})."}\r\n");
543 $self->msg_more(${$eml->{hdr}});
546 # n.b. this is sorted to be after any emit_eml_new ops
547 sub emit_rfc822_text {
548 my ($self, $k, undef, $bref) = @_;
549 $self->msg_more(" $k {".length($$bref)."}\r\n");
550 $self->msg_more($$bref);
553 sub emit_bodystructure {
554 my ($self, undef, undef, undef, $eml) = @_;
555 $self->msg_more(' BODYSTRUCTURE '.fetch_body($eml, 1));
559 my ($self, undef, undef, undef, $eml) = @_;
560 $self->msg_more(' BODY '.fetch_body($eml));
563 # set $eml once ($_[4] == $eml, $_[3] == $bref)
564 sub op_eml_new { $_[4] = PublicInbox::Eml->new($_[3]) }
566 # s/From / fixes old bug from import (pre-a0c07cba0e5d8b6a)
568 ${$_[0]} =~ s/(?<!\r)\n/\r\n/sg;
569 ${$_[0]} =~ s/\A[\r\n]*From [^\r\n]*\r\n//s;
572 sub op_crlf_bref { to_crlf_full($_[3]) }
574 sub op_crlf_hdr { to_crlf_full($_[4]->{hdr}) }
576 sub op_crlf_bdy { ${$_[4]->{bdy}} =~ s/(?<!\r)\n/\r\n/sg if $_[4]->{bdy} }
578 sub uid_clamp ($$$) {
579 my ($self, $beg, $end) = @_;
580 my $uid_min = $self->{uid_base} + 1;
581 my $uid_end = $uid_min + UID_BLOCK - 1;
582 $$beg = $uid_min if $$beg < $uid_min;
583 $$end = $uid_end if $$end > $uid_end;
586 sub range_step ($$) {
587 my ($self, $range_csv) = @_;
588 my ($beg, $end, $range);
589 if ($$range_csv =~ s/\A([^,]+),//) {
592 $range = $$range_csv;
595 if ($range =~ /\A([0-9]+):([0-9]+)\z/) {
596 ($beg, $end) = ($1 + 0, $2 + 0);
597 } elsif ($range =~ /\A([0-9]+):\*\z/) {
599 $end = $self->{ibx}->over->max;
600 my $uid_end = $self->{uid_base} + UID_BLOCK;
601 $end = $uid_end if $end > $uid_end;
602 $beg = $end if $beg > $end;
603 } elsif ($range =~ /\A[0-9]+\z/) {
604 $beg = $end = $range + 0;
607 return 'BAD fetch range';
609 uid_clamp($self, \$beg, \$end) if defined($range);
610 my $msn = $beg - $self->{uid_base};
611 [ $beg, $end, $$range_csv, \$msn ];
614 sub refill_range ($$$) {
615 my ($self, $msgs, $range_info) = @_;
616 my ($beg, $end, $range_csv) = @$range_info;
617 if (scalar(@$msgs = @{$self->{ibx}->over->query_xover($beg, $end)})) {
618 $range_info->[0] = $msgs->[-1]->{num} + 1;
621 return 'OK Fetch done' if !$range_csv;
622 my $next_range = range_step($self, \$range_csv);
623 return $next_range if !ref($next_range); # error
624 @$range_info = @$next_range;
625 undef; # keep looping
628 sub fetch_blob { # long_response
629 my ($self, $tag, $msgs, $range_info, $ops, $partial) = @_;
630 while (!@$msgs) { # rare
631 if (my $end = refill_range($self, $msgs, $range_info)) {
632 $self->write(\"$tag $end\r\n");
636 git_async_cat($self->{ibx}->git, $msgs->[0]->{blob},
637 \&fetch_blob_cb, \@_);
640 sub fetch_smsg { # long_response
641 my ($self, $tag, $msgs, $range_info, $ops) = @_;
642 while (!@$msgs) { # rare
643 if (my $end = refill_range($self, $msgs, $range_info)) {
644 $self->write(\"$tag $end\r\n");
648 fetch_run_ops($self, $range_info->[3], $_, undef, $ops) for @$msgs;
653 sub fetch_uid { # long_response
654 my ($self, $tag, $uids, $range_info, $ops) = @_;
656 while (!@$uids) { # rare
657 my ($beg, $end, $range_csv) = @$range_info;
658 if (scalar(@$uids = @{$self->{ibx}->over->
659 uid_range($beg, $end)})) {
660 $range_info->[0] = $uids->[-1] + 1;
661 } elsif (!$range_csv) {
662 $self->write(\"$tag OK Fetch done\r\n");
665 my $next_range = range_step($self, \$range_csv);
666 if (!ref($next_range)) { # error
667 $self->write(\"$tag $next_range\r\n");
670 @$range_info = @$next_range;
675 my $msn = $range_info->[3];
677 $self->msg_more(fetch_msn_uid($msn, $_));
678 for ($i = 0; $i < @$ops;) {
680 $ops->[$i++]->($self, $k);
682 $self->msg_more(")\r\n");
688 sub cmd_status ($$$;@) {
689 my ($self, $tag, $mailbox, @items) = @_;
690 return "$tag BAD no items\r\n" if !scalar(@items);
691 ($items[0] !~ s/\A\(//s || $items[-1] !~ s/\)\z//s) and
692 return "$tag BAD invalid args\r\n";
693 my ($ibx, $exists, $uidnext) = inbox_lookup($self, $mailbox);
694 return "$tag NO Mailbox doesn't exist: $mailbox\r\n" if !$ibx;
696 for my $it (@items) {
699 if ($it =~ /\A(?:MESSAGES|UNSEEN|RECENT)\z/) {
701 } elsif ($it eq 'UIDNEXT') {
703 } elsif ($it eq 'UIDVALIDITY') {
704 push @it, $ibx->{uidvalidity};
706 return "$tag BAD invalid item\r\n";
709 return "$tag BAD no items\r\n" if !@it;
710 "* STATUS $mailbox (".join(' ', @it).")\r\n" .
711 "$tag OK Status done\r\n";
714 my %patmap = ('*' => '.*', '%' => '[^\.]*');
715 sub cmd_list ($$$$) {
716 my ($self, $tag, $refname, $wildcard) = @_;
717 my $l = $self->{imapd}->{inboxlist};
718 if ($refname eq '' && $wildcard eq '') {
719 # request for hierarchy delimiter
720 $l = [ qq[* LIST (\\Noselect) "." ""\r\n] ];
721 } elsif ($refname ne '' || $wildcard ne '*') {
722 $wildcard =~ s!([^a-z0-9_])!$patmap{$1} // "\Q$1"!egi;
723 $l = [ grep(/ \Q$refname\E$wildcard\r\n\z/is, @$l) ];
725 \(join('', @$l, "$tag OK List done\r\n"));
728 sub cmd_lsub ($$$$) {
729 my (undef, $tag) = @_; # same args as cmd_list
730 "$tag OK Lsub done\r\n";
733 sub eml_index_offs_i { # PublicInbox::Eml::each_part callback
735 my ($eml, undef, $idx) = @$p;
736 if ($idx && lc($eml->ct->{type}) eq 'multipart') {
737 $eml->{imap_bdy} = $eml->{bdy} // \'';
739 $all->{$idx} = $eml; # $idx => Eml
742 # prepares an index for BODY[$SECTION_IDX] fetches
743 sub eml_body_idx ($$) {
744 my ($eml, $section_idx) = @_;
745 my $idx = $eml->{imap_all_parts} //= do {
747 $eml->each_part(\&eml_index_offs_i, $all, 0, 1);
748 # top-level of multipart, BODY[0] not allowed (nz-number)
752 $idx->{$section_idx};
755 # BODY[($SECTION_IDX)?(.$SECTION_NAME)?]<$offset.$bytes>
757 my ($eml, $section_idx, $section_name) = @_;
758 if (defined $section_idx) {
759 $eml = eml_body_idx($eml, $section_idx) or return;
761 if (defined $section_name) {
762 if ($section_name eq 'MIME') {
763 # RFC 3501 6.4.5 states:
764 # The MIME part specifier MUST be prefixed
765 # by one or more numeric part specifiers
766 return unless defined $section_idx;
767 return $eml->header_obj->as_string . "\r\n";
769 my $bdy = $eml->{bdy} // $eml->{imap_bdy} // \'';
770 $eml = PublicInbox::Eml->new($$bdy);
771 if ($section_name eq 'TEXT') {
772 return $eml->body_raw;
773 } elsif ($section_name eq 'HEADER') {
774 return $eml->header_obj->as_string . "\r\n";
776 die "BUG: bad section_name=$section_name";
779 ${$eml->{bdy} // $eml->{imap_bdy} // \''};
782 # similar to what's in PublicInbox::Eml::re_memo, but doesn't memoize
783 # to avoid OOM with malicious users
784 sub hdrs_regexp ($) {
786 my $names = join('|', map { "\Q$_" } split(/[ \t]+/, $hdrs));
787 qr/^(?:$names):[ \t]*[^\n]*\r?\n # 1st line
788 # continuation lines:
789 (?:[^:\n]*?[ \t]+[^\n]*\r?\n)*
793 # BODY[($SECTION_IDX.)?HEADER.FIELDS.NOT ($HDRS)]<$offset.$bytes>
794 sub partial_hdr_not {
795 my ($eml, $section_idx, $hdrs_re) = @_;
796 if (defined $section_idx) {
797 $eml = eml_body_idx($eml, $section_idx) or return;
799 my $str = $eml->header_obj->as_string;
800 $str =~ s/$hdrs_re//g;
801 $str =~ s/(?<!\r)\n/\r\n/sg;
805 # BODY[($SECTION_IDX.)?HEADER.FIELDS ($HDRS)]<$offset.$bytes>
806 sub partial_hdr_get {
807 my ($eml, $section_idx, $hdrs_re) = @_;
808 if (defined $section_idx) {
809 $eml = eml_body_idx($eml, $section_idx) or return;
811 my $str = $eml->header_obj->as_string;
812 $str = join('', ($str =~ m/($hdrs_re)/g));
813 $str =~ s/(?<!\r)\n/\r\n/sg;
817 sub partial_prepare ($$$$) {
818 my ($need, $partial, $want, $att) = @_;
820 # recombine [ "BODY[1.HEADER.FIELDS", "(foo", "bar)]" ]
821 # back to: "BODY[1.HEADER.FIELDS (foo bar)]"
822 return unless $att =~ /\ABODY\[/s;
823 until (rindex($att, ']') >= 0) {
824 my $next = shift @$want or return;
825 $att .= ' ' . uc($next);
827 if ($att =~ /\ABODY\[([0-9]+(?:\.[0-9]+)*)? # 1 - section_idx
828 (?:\.(HEADER|MIME|TEXT))? # 2 - section_name
829 \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 3, 4
830 $partial->{$att} = [ \&partial_body, $1, $2, $3, $4 ];
831 $$need |= CRLF_BREF|EML_HDR|EML_BDY;
832 } elsif ($att =~ /\ABODY\[(?:([0-9]+(?:\.[0-9]+)*)\.)? # 1 - section_idx
833 (?:HEADER\.FIELDS(\.NOT)?)\x20 # 2
834 \(([A-Z0-9\-\x20]+)\) # 3 - hdrs
835 \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 4 5
836 my $tmp = $partial->{$att} = [ $2 ? \&partial_hdr_not
839 $tmp->[2] = hdrs_regexp($3);
841 # don't emit CRLF_HDR instruction, here, partial_hdr_*
842 # will do CRLF conversion with only the extracted result
843 # and not waste time converting lines we don't care about.
850 sub partial_emit ($$$) {
851 my ($self, $partial, $eml) = @_;
853 my ($k, $cb, @args) = @$_;
854 my ($offset, $len) = splice(@args, -2);
855 # $cb is partial_body|partial_hdr_get|partial_hdr_not
856 my $str = $cb->($eml, @args) // '';
857 if (defined $offset) {
859 $str = substr($str, $offset, $len);
860 $k =~ s/\.$len>\z/>/ or warn
861 "BUG: unable to remove `.$len>' from `$k'";
863 $str = substr($str, $offset);
869 $self->msg_more(" $k {$len}\r\n");
870 $self->msg_more($str);
874 sub fetch_compile ($) {
876 if ($want->[0] =~ s/\A\(//s) {
877 $want->[-1] =~ s/\)\z//s or return 'BAD no rparen';
879 my (%partial, %seen, @op);
881 while (defined(my $att = shift @$want)) {
883 next if $att eq 'UID'; # always returned
884 $att =~ s/\ABODY\.PEEK\[/BODY\[/; # we're read-only
885 my $x = $FETCH_ATT{$att};
887 while (my ($k, $fl_cb) = each %$x) {
889 $need |= $fl_cb->[0];
890 push @op, [ @$fl_cb, $k ];
892 } elsif (!partial_prepare(\$need, \%partial, $want, $att)) {
893 return "BAD param: $att";
898 # stabilize partial order for consistency and ease-of-debugging:
899 if (scalar keys %partial) {
901 $r[2] = [ map { [ $_, @{$partial{$_}} ] } sort keys %partial ];
904 push @op, $OP_EML_NEW if ($need & (EML_HDR|EML_BDY));
906 # do we need CRLF conversion?
907 if ($need & CRLF_BREF) {
908 push @op, $OP_CRLF_BREF;
909 } elsif (my $crlf = ($need & (CRLF_HDR|CRLF_BDY))) {
910 if ($crlf == (CRLF_HDR|CRLF_BDY)) {
911 push @op, $OP_CRLF_BREF;
912 } elsif ($need & CRLF_HDR) {
913 push @op, $OP_CRLF_HDR;
915 push @op, $OP_CRLF_BDY;
919 $r[0] = $need & NEED_BLOB ? \&fetch_blob :
920 ($need & NEED_SMSG ? \&fetch_smsg : \&fetch_uid);
922 # r[1] = [ $key1, $cb1, $key2, $cb2, ... ]
923 use sort 'stable'; # makes output more consistent
924 $r[1] = [ map { ($_->[2], $_->[1]) } sort { $a->[0] <=> $b->[0] } @op ];
928 sub cmd_uid_fetch ($$$$;@) {
929 my ($self, $tag, $range_csv, @want) = @_;
930 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
931 my ($cb, $ops, $partial) = fetch_compile(\@want);
932 return "$tag $cb\r\n" unless $ops;
934 $range_csv = 'bad' if $range_csv !~ $valid_range;
935 my $range_info = range_step($self, \$range_csv);
936 return "$tag $range_info\r\n" if !ref($range_info);
937 long_response($self, $cb, $tag, [], $range_info, $ops, $partial);
940 sub msn_to_uid_range ($$) {
941 my $uid_base = $_[0]->{uid_base};
942 $_[1] =~ s/([0-9]+)/$uid_base + $1/sge;
945 sub cmd_fetch ($$$$;@) {
946 my ($self, $tag, $range_csv, @want) = @_;
947 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
948 my ($cb, $ops, $partial) = fetch_compile(\@want);
949 return "$tag $cb\r\n" unless $ops;
951 # cb is one of fetch_blob, fetch_smsg, fetch_uid
952 $range_csv = 'bad' if $range_csv !~ $valid_range;
953 msn_to_uid_range($self, $range_csv);
954 my $range_info = range_step($self, \$range_csv);
955 return "$tag $range_info\r\n" if !ref($range_info);
956 long_response($self, $cb, $tag, [], $range_info, $ops, $partial);
959 sub parse_date ($) { # 02-Oct-1993
960 my ($date_text) = @_;
961 my ($dd, $mon, $yyyy) = split(/-/, $_[0], 3);
962 defined($yyyy) or return;
963 my $mm = $MoY{$mon} // return;
964 $dd =~ /\A[0123]?[0-9]\z/ or return;
965 $yyyy =~ /\A[0-9]{4,}\z/ or return; # Y10K-compatible!
966 timegm(0, 0, 0, $dd, $mm, $yyyy);
969 sub uid_search_uid_range { # long_response
970 my ($self, $tag, $beg, $end, $sql) = @_;
971 my $uids = $self->{ibx}->over->uid_range($$beg, $end, $sql);
973 $$beg = $uids->[-1] + 1;
974 $self->msg_more(join(' ', '', @$uids));
976 $self->write(\"\r\n$tag OK Search done\r\n");
982 my ($q, $k, $d) = @_;
986 if ($k eq 'SENTON') {
987 my $end = $d + 86399; # no leap day...
988 my $da = strftime('%Y%m%d%H%M%S', gmtime($d));
989 my $db = strftime('%Y%m%d%H%M%S', gmtime($end));
990 $q->{xap} .= " dt:$da..$db";
991 $$sql .= " AND ds >= $d AND ds <= $end" if defined($sql);
992 } elsif ($k eq 'SENTBEFORE') {
993 $q->{xap} .= ' d:..'.strftime('%Y%m%d', gmtime($d));
994 $$sql .= " AND ds <= $d" if defined($sql);
995 } elsif ($k eq 'SENTSINCE') {
996 $q->{xap} .= ' d:'.strftime('%Y%m%d', gmtime($d)).'..';
997 $$sql .= " AND ds >= $d" if defined($sql);
999 # INTERNALDATE (Received)
1000 } elsif ($k eq 'ON') {
1001 my $end = $d + 86399; # no leap day...
1002 $q->{xap} .= " ts:$d..$end";
1003 $$sql .= " AND ts >= $d AND ts <= $end" if defined($sql);
1004 } elsif ($k eq 'BEFORE') {
1005 $q->{xap} .= " ts:..$d";
1006 $$sql .= " AND ts <= $d" if defined($sql);
1007 } elsif ($k eq 'SINCE') {
1008 $q->{xap} .= " ts:$d..";
1009 $$sql .= " AND ts >= $d" if defined($sql);
1011 die "BUG: $k not recognized";
1015 # IMAP to Xapian search key mapping
1020 TEXT => '', # n.b. does not include all headers
1023 # BCC => 'bcc:', # TODO
1024 # KEYWORD # TODO ? dfpre,dfpost,...
1028 my ($self, $rest) = @_;
1029 if (uc($rest->[0]) eq 'CHARSET') {
1031 defined(my $c = shift @$rest) or return 'BAD missing charset';
1032 $c =~ /\A(?:UTF-8|US-ASCII)\z/ or return 'NO [BADCHARSET]';
1035 my $sql = ''; # date conditions, {sql} deleted if Xapian is needed
1036 my $q = { xap => '', sql => \$sql };
1038 my $k = uc(shift @$rest);
1040 next if $k =~ /\A(?:ALL|RECENT|UNSEEN|NEW)\z/;
1041 next if $k eq 'AND'; # the default, until we support OR
1042 if ($k =~ $valid_range) { # convert sequence numbers to UIDs
1043 msn_to_uid_range($self, $k);
1044 push @{$q->{uid}}, $k;
1045 } elsif ($k eq 'UID') {
1046 $k = shift(@$rest) // '';
1047 $k =~ $valid_range or return 'BAD UID range';
1048 push @{$q->{uid}}, $k;
1049 } elsif ($k =~ /\A(?:SENT)?(?:SINCE|ON|BEFORE)\z/) {
1050 my $d = parse_date(shift(@$rest) // '');
1051 defined $d or return "BAD $k date format";
1052 date_search($q, $k, $d);
1053 } elsif ($k =~ /\A(?:SMALLER|LARGER)\z/) {
1054 delete $q->{sql}; # can't use over.sqlite3
1055 my $bytes = shift(@$rest) // '';
1056 $bytes =~ /\A[0-9]+\z/ or return "BAD $k not a number";
1057 $q->{xap} .= ' bytes:' . ($k eq 'SMALLER' ?
1060 } elsif (defined(my $xk = $I2X{$k})) {
1061 delete $q->{sql}; # can't use over.sqlite3
1062 my $arg = shift @$rest;
1063 defined($arg) or return "BAD $k no arg";
1065 # Xapian can't handle [*"] in probabilistic terms
1067 $q->{xap} .= qq[ $xk:"$arg"];
1069 # TODO: parentheses, OR, NOT ...
1070 return "BAD $k not supported (yet?)";
1074 # favor using over.sqlite3 if possible, since Xapian is optional
1075 if (exists $q->{sql}) {
1077 delete($q->{sql}) if $sql eq '';
1078 } elsif (!$self->{ibx}->search) {
1079 return 'BAD Xapian not configured for mailbox';
1082 if (my $uid = $q->{uid}) {
1083 ((@$uid > 1) || $uid->[0] =~ /,/) and
1084 return 'BAD multiple ranges not supported, yet';
1085 ($q->{sql} // $q->{xap}) and
1086 return 'BAD ranges and queries do not mix, yet';
1087 $q->{uid} = join(',', @$uid); # TODO: multiple ranges
1092 sub cmd_uid_search ($$$;) {
1093 my ($self, $tag) = splice(@_, 0, 2);
1094 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1095 my $q = parse_query($self, \@_);
1096 return "$tag $q\r\n" if !ref($q);
1097 my $sql = delete $q->{sql};
1099 if (!scalar(keys %$q)) {
1100 $self->msg_more('* SEARCH');
1102 my $end = $ibx->over->max;
1103 uid_clamp($self, \$beg, \$end);
1104 long_response($self, \&uid_search_uid_range,
1105 $tag, \$beg, $end, $sql);
1106 } elsif (my $uid = $q->{uid}) {
1107 if ($uid =~ /\A([0-9]+):([0-9]+|\*)\z/s) {
1108 my ($beg, $end) = ($1, $2);
1109 $end = $ibx->over->max if $end eq '*';
1110 uid_clamp($self, \$beg, \$end);
1111 $self->msg_more('* SEARCH');
1112 long_response($self, \&uid_search_uid_range,
1113 $tag, \$beg, $end, $sql);
1114 } elsif ($uid =~ /\A[0-9]+\z/s) {
1115 $uid = $ibx->over->get_art($uid) ? " $uid" : '';
1116 "* SEARCH$uid\r\n$tag OK Search done\r\n";
1118 "$tag BAD Error\r\n";
1121 "$tag BAD Error\r\n";
1125 sub args_ok ($$) { # duplicated from PublicInbox::NNTP
1126 my ($cb, $argc) = @_;
1127 my $tot = prototype $cb;
1128 my ($nreq, undef) = split(';', $tot);
1129 $nreq = ($nreq =~ tr/$//) - 1;
1130 $tot = ($tot =~ tr/$//) - 1;
1131 ($argc <= $tot && $argc >= $nreq);
1134 # returns 1 if we can continue, 0 if not due to buffered writes or disconnect
1135 sub process_line ($$) {
1136 my ($self, $l) = @_;
1137 my ($tag, $req, @args) = parse_line('[ \t]+', 0, $l);
1138 pop(@args) if (@args && !defined($args[-1]));
1139 if (@args && uc($req) eq 'UID') {
1140 $req .= "_".(shift @args);
1143 if (my $cmd = $self->can('cmd_'.lc($req // ''))) {
1144 defined($self->{-idle_tag}) ?
1145 "$self->{-idle_tag} BAD expected DONE\r\n" :
1146 $cmd->($self, $tag, @args);
1147 } elsif (uc($tag // '') eq 'DONE' && !defined($req)) {
1148 cmd_done($self, $tag);
1149 } else { # this is weird
1150 auth_challenge_ok($self) //
1152 ' BAD Error in IMAP command '.
1154 ": Unknown command\r\n";
1158 if ($err && $self->{sock}) {
1160 err($self, 'error from: %s (%s)', $l, $err);
1162 $res = "$tag BAD program fault - command not performed\r\n";
1164 return 0 unless defined $res;
1170 # wbuf is unset or empty, here; {long} may add to it
1171 my ($fd, $cb, $t0, @args) = @{$self->{long_cb}};
1172 my $more = eval { $cb->($self, @args) };
1173 if ($@ || !$self->{sock}) { # something bad happened...
1174 delete $self->{long_cb};
1175 my $elapsed = now() - $t0;
1178 "%s during long response[$fd] - %0.6f",
1181 out($self, " deferred[$fd] aborted - %0.6f", $elapsed);
1183 } elsif ($more) { # $self->{wbuf}:
1184 $self->update_idle_time;
1186 # control passed to $more may be a GitAsyncCat object
1187 requeue_once($self) if !ref($more);
1188 } else { # all done!
1189 delete $self->{long_cb};
1190 my $elapsed = now() - $t0;
1191 my $fd = fileno($self->{sock});
1192 out($self, " deferred[$fd] done - %0.6f", $elapsed);
1193 my $wbuf = $self->{wbuf}; # do NOT autovivify
1195 $self->requeue unless $wbuf && @$wbuf;
1200 my ($self, $fmt, @args) = @_;
1201 printf { $self->{imapd}->{err} } $fmt."\n", @args;
1205 my ($self, $fmt, @args) = @_;
1206 printf { $self->{imapd}->{out} } $fmt."\n", @args;
1209 sub long_response ($$;@) {
1210 my ($self, $cb, @args) = @_; # cb returns true if more, false if done
1212 my $sock = $self->{sock} or return;
1213 # make sure we disable reading during a long response,
1214 # clients should not be sending us stuff and making us do more
1215 # work while we are stream a response to them
1216 $self->{long_cb} = [ fileno($sock), $cb, now(), @args ];
1217 long_step($self); # kick off!
1221 # callback used by PublicInbox::DS for any (e)poll (in/out/hup/err)
1225 return unless $self->flush_write && $self->{sock} && !$self->{long_cb};
1227 $self->update_idle_time;
1228 # only read more requests if we've drained the write buffer,
1229 # otherwise we can be buffering infinitely w/o backpressure
1231 my $rbuf = $self->{rbuf} // \(my $x = '');
1232 my $line = index($$rbuf, "\n");
1234 if (length($$rbuf) >= LINE_MAX) {
1235 $self->write(\"\* BAD request too long\r\n");
1236 return $self->close;
1238 $self->do_read($rbuf, LINE_MAX, length($$rbuf)) or return;
1239 $line = index($$rbuf, "\n");
1241 $line = substr($$rbuf, 0, $line + 1, '');
1242 $line =~ s/\r?\n\z//s;
1243 return $self->close if $line =~ /[[:cntrl:]]/s;
1245 my $fd = fileno($self->{sock});
1246 my $r = eval { process_line($self, $line) };
1247 my $pending = $self->{wbuf} ? ' pending' : '';
1248 out($self, "[$fd] %s - %0.6f$pending - $r", $line, now() - $t0);
1250 return $self->close if $r < 0;
1251 $self->rbuf_idle($rbuf);
1252 $self->update_idle_time;
1254 # maybe there's more pipelined data, or we'll have
1255 # to register it for socket-readiness notifications
1256 $self->requeue unless $pending;
1259 sub compressed { undef }
1261 sub zflush {} # overridden by IMAPdeflate
1264 sub cmd_compress ($$$) {
1265 my ($self, $tag, $alg) = @_;
1266 return "$tag BAD DEFLATE only\r\n" if uc($alg) ne "DEFLATE";
1267 return "$tag BAD COMPRESS active\r\n" if $self->compressed;
1269 # CRIME made TLS compression obsolete
1270 # return "$tag NO [COMPRESSIONACTIVE]\r\n" if $self->tls_compressed;
1272 PublicInbox::IMAPdeflate->enable($self, $tag);
1277 sub cmd_starttls ($$) {
1278 my ($self, $tag) = @_;
1279 my $sock = $self->{sock} or return;
1280 if ($sock->can('stop_SSL') || $self->compressed) {
1281 return "$tag BAD TLS or compression already enabled\r\n";
1283 my $opt = $self->{imapd}->{accept_tls} or
1284 return "$tag BAD can not initiate TLS negotiation\r\n";
1285 $self->write(\"$tag OK begin TLS negotiation now\r\n");
1286 $self->{sock} = IO::Socket::SSL->start_SSL($sock, %$opt);
1287 $self->requeue if PublicInbox::DS::accept_tls_step($self);
1291 # for graceful shutdown in PublicInbox::Daemon:
1293 my ($self, $now) = @_;
1294 ($self->{rbuf} || $self->{wbuf} || $self->not_idle_long($now));
1299 if (my $ibx = delete $self->{ibx}) {
1300 stop_idle($self, $ibx);
1302 $self->SUPER::close; # PublicInbox::DS::close
1305 # we're read-only, so SELECT and EXAMINE do the same thing
1307 *cmd_select = \&cmd_examine;
1309 package PublicInbox::IMAP_preauth;
1310 our @ISA = qw(PublicInbox::IMAP);