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 and message sequence numbers (MSNs)
11 # * Message sequence numbers (MSNs) can be stable since we're read-only.
12 # Most IMAP clients use UIDs (I hope). We may return a dummy message
13 # in the future if a client requests a non-existent MSN, but that seems
14 # unecessary with mutt.
16 package PublicInbox::IMAP;
18 use base qw(PublicInbox::DS);
19 use fields qw(imapd ibx long_cb -login_tag
20 uid_min -idle_tag -idle_max);
22 use PublicInbox::EmlContentFoo qw(parse_content_disposition);
23 use PublicInbox::DS qw(now);
24 use PublicInbox::Syscall qw(EPOLLIN EPOLLONESHOT);
25 use PublicInbox::GitAsyncCat;
26 use Text::ParseWords qw(parse_line);
28 use Time::Local qw(timegm);
29 use POSIX qw(strftime);
30 use Hash::Util qw(unlock_hash); # dependency of fields for perl 5.10+, anyways
33 for my $mod (qw(Email::Address::XS Mail::Address)) {
34 eval "require $mod" or next;
35 $Address = $mod and last;
37 die "neither Email::Address::XS nor Mail::Address loaded: $@" if !$Address;
39 sub LINE_MAX () { 512 } # does RFC 3501 have a limit like RFC 977?
41 # changing this will cause grief for clients which cache
42 sub UID_BLOCK () { 50_000 }
44 # these values area also used for sorting
45 sub NEED_SMSG () { 1 }
46 sub NEED_BLOB () { NEED_SMSG|2 }
47 sub NEED_EML () { NEED_BLOB|4 }
48 my $OP_EML_NEW = [ NEED_EML - 1, \&op_eml_new ];
51 'BODY[HEADER]' => [ NEED_EML, \&emit_rfc822_header ],
52 'BODY[TEXT]' => [ NEED_EML, \&emit_rfc822_text ],
53 'BODY[]' => [ NEED_BLOB, \&emit_rfc822 ],
54 'RFC822.HEADER' => [ NEED_EML, \&emit_rfc822_header ],
55 'RFC822.TEXT' => [ NEED_EML, \&emit_rfc822_text ],
56 'RFC822.SIZE' => [ NEED_BLOB, \&emit_rfc822_size ],
57 RFC822 => [ NEED_BLOB, \&emit_rfc822 ],
58 BODY => [ NEED_EML, \&emit_body ],
59 BODYSTRUCTURE => [ NEED_EML, \&emit_bodystructure ],
60 ENVELOPE => [ NEED_EML, \&emit_envelope ],
61 FLAGS => [ 0, \&emit_flags ],
62 INTERNALDATE => [ NEED_SMSG, \&emit_internaldate ],
64 my %FETCH_ATT = map { $_ => [ $_ ] } keys %FETCH_NEED;
66 # aliases (RFC 3501 section 6.4.5)
67 $FETCH_ATT{FAST} = [ qw(FLAGS INTERNALDATE RFC822.SIZE) ];
68 $FETCH_ATT{ALL} = [ @{$FETCH_ATT{FAST}}, 'ENVELOPE' ];
69 $FETCH_ATT{FULL} = [ @{$FETCH_ATT{ALL}}, 'BODY' ];
71 for my $att (keys %FETCH_ATT) {
72 my %h = map { $_ => $FETCH_NEED{$_} } @{$FETCH_ATT{$att}};
73 $FETCH_ATT{$att} = \%h;
77 my $valid_range = '[0-9]+|[0-9]+:[0-9]+|[0-9]+:\*';
78 $valid_range = qr/\A(?:$valid_range)(?:,(?:$valid_range))*\z/;
80 my @MoY = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
84 # RFC 3501 5.4. Autologout Timer needs to be >= 30min
85 $PublicInbox::DS::EXPTIME = 60 * 30;
89 my $capa = capa($self);
90 $self->write(\"* OK [$capa] public-inbox-imapd ready\r\n");
94 my ($class, $sock, $imapd) = @_;
95 my $self = fields::new('PublicInbox::IMAP_preauth');
99 if ($sock->can('accept_SSL') && !$sock->accept_SSL) {
100 return CORE::close($sock) if $! != EAGAIN;
101 $ev = PublicInbox::TLS::epollbit();
102 $wbuf = [ \&PublicInbox::DS::accept_tls_step, \&greet ];
104 $self->SUPER::new($sock, $ev | EPOLLONESHOT);
105 $self->{imapd} = $imapd;
107 $self->{wbuf} = $wbuf;
111 $self->update_idle_time;
120 # dovecot advertises IDLE pre-login; perhaps because some clients
121 # depend on it, so we'll do the same
122 my $capa = 'CAPABILITY IMAP4rev1 IDLE';
123 if ($self->logged_in) {
124 $capa .= ' COMPRESS=DEFLATE';
126 if (!($self->{sock} // $self)->can('accept_SSL') &&
127 $self->{imapd}->{accept_tls}) {
128 $capa .= ' STARTTLS';
130 $capa .= ' AUTH=ANONYMOUS';
134 sub login_success ($$) {
135 my ($self, $tag) = @_;
136 bless $self, 'PublicInbox::IMAP';
137 my $capa = capa($self);
138 "$tag OK [$capa] Logged in\r\n";
141 sub auth_challenge_ok ($) {
143 my $tag = delete($self->{-login_tag}) or return;
144 login_success($self, $tag);
147 sub cmd_login ($$$$) {
148 my ($self, $tag) = @_; # ignore ($user, $password) = ($_[2], $_[3])
149 login_success($self, $tag);
153 my ($self, $tag) = @_;
154 delete $self->{uid_min};
155 delete $self->{ibx} ? "$tag OK Close done\r\n"
156 : "$tag BAD No mailbox\r\n";
159 sub cmd_logout ($$) {
160 my ($self, $tag) = @_;
161 delete $self->{-idle_tag};
162 $self->write(\"* BYE logging out\r\n$tag OK Logout done\r\n");
163 $self->shutdn; # PublicInbox::DS::shutdn
167 sub cmd_authenticate ($$$) {
168 my ($self, $tag) = @_; # $method = $_[2], should be "ANONYMOUS"
169 $self->{-login_tag} = $tag;
173 sub cmd_capability ($$) {
174 my ($self, $tag) = @_;
175 '* '.capa($self)."\r\n$tag OK Capability done\r\n";
178 sub cmd_noop ($$) { "$_[1] OK Noop done\r\n" }
180 # called by PublicInbox::InboxIdle
181 sub on_inbox_unlock {
182 my ($self, $ibx) = @_;
183 my $new = $ibx->mm->max;
184 my $uid_end = ($self->{uid_min} // 1) - 1 + UID_BLOCK;
185 defined(my $old = $self->{-idle_max}) or die 'BUG: -idle_max unset';
186 $new = $uid_end if $new > $uid_end;
188 $self->{-idle_max} = $new;
189 $self->msg_more("* $_ EXISTS\r\n") for (($old + 1)..($new - 1));
190 $self->write(\"* $new EXISTS\r\n");
191 } elsif ($new == $uid_end) { # max exceeded $uid_end
192 # continue idling w/o inotify
193 delete $self->{-idle_max};
194 my $sock = $self->{sock} or return;
195 $ibx->unsubscribe_unlock(fileno($sock));
199 # called every X minute(s) or so by PublicInbox::DS::later
205 for my $i (values %$old) {
206 next if ($i->{wbuf} || !exists($i->{-idle_tag}));
207 $i->update_idle_time or next;
208 $IDLERS->{fileno($i->{sock})} = $i;
209 $i->write(\"* OK Still here\r\n");
211 $idle_timer = scalar keys %$IDLERS ?
212 PublicInbox::DS::later(\&idle_tick_all) : undef;
216 my ($self, $tag) = @_;
217 # IDLE seems allowed by dovecot w/o a mailbox selected *shrug*
218 my $ibx = $self->{ibx} or return "$tag BAD no mailbox selected\r\n";
219 $self->{-idle_tag} = $tag;
220 my $max = $ibx->mm->max // 0;
221 my $uid_end = ($self->{uid_min} // 1) - 1 + UID_BLOCK;
222 my $sock = $self->{sock} or return;
223 my $fd = fileno($sock);
224 # only do inotify on most recent slice
225 if ($max < $uid_end) {
226 $ibx->subscribe_unlock($fd, $self);
227 $self->{imapd}->idler_start;
228 $self->{-idle_max} = $max;
230 $idle_timer //= PublicInbox::DS::later(\&idle_tick_all);
231 $IDLERS->{$fd} = $self;
237 my $sock = $self->{sock} or return;
238 my $fd = fileno($sock);
239 delete $IDLERS->{$fd};
240 $ibx->unsubscribe_unlock($fd);
244 my ($self, $tag) = @_; # $tag is "DONE" (case-insensitive)
245 defined(my $idle_tag = delete $self->{-idle_tag}) or
246 return "$tag BAD not idle\r\n";
247 my $ibx = $self->{ibx} or do {
248 warn "BUG: idle_tag set w/o inbox";
249 return "$tag BAD internal bug\r\n";
251 stop_idle($self, $ibx);
252 "$idle_tag OK Idle done\r\n";
255 sub ensure_ranges_exist ($$$) {
256 my ($imapd, $ibx, $max) = @_;
257 my $mailboxes = $imapd->{mailboxes};
258 my $mb_top = $ibx->{newsgroup};
260 for (my $i = int($max/UID_BLOCK); $i >= 0; --$i) {
261 my $sub_mailbox = "$mb_top.$i";
262 last if exists $mailboxes->{$sub_mailbox};
263 $mailboxes->{$sub_mailbox} = $ibx;
264 push @created, $sub_mailbox;
266 return unless @created;
267 my $l = $imapd->{inboxlist} or return;
268 push @$l, map { qq[* LIST (\\HasNoChildren) "." $_\r\n] } @created;
271 sub inbox_lookup ($$) {
272 my ($self, $mailbox) = @_;
273 my ($ibx, $exists, $uidnext);
274 if ($mailbox =~ /\A(.+)\.([0-9]+)\z/) {
275 # old mail: inbox.comp.foo.$uid_block_idx
276 my ($mb_top, $uid_min) = ($1, $2 * UID_BLOCK + 1);
278 $ibx = $self->{imapd}->{mailboxes}->{lc $mailbox} or return;
279 $exists = $ibx->mm->max // 0;
280 $self->{uid_min} = $uid_min;
281 ensure_ranges_exist($self->{imapd}, $ibx, $exists);
282 my $uid_end = $uid_min + UID_BLOCK - 1;
283 $exists = $uid_end if $exists > $uid_end;
284 $uidnext = $exists + 1;
285 } else { # check for dummy inboxes
286 $ibx = $self->{imapd}->{mailboxes}->{lc $mailbox} or return;
287 delete $self->{uid_min};
291 ($ibx, $exists, $uidnext);
294 sub cmd_examine ($$$) {
295 my ($self, $tag, $mailbox) = @_;
296 my ($ibx, $exists, $uidnext) = inbox_lookup($self, $mailbox);
297 return "$tag NO Mailbox doesn't exist: $mailbox\r\n" if !$ibx;
299 # XXX: do we need this? RFC 5162/7162
300 my $ret = $self->{ibx} ? "* OK [CLOSED] previous closed\r\n" : '';
306 * OK [PERMANENTFLAGS ()] Read-only mailbox\r
307 * OK [UNSEEN $exists]\r
308 * OK [UIDNEXT $uidnext]\r
309 * OK [UIDVALIDITY $ibx->{uidvalidity}]\r
310 $tag OK [READ-ONLY] EXAMINE/SELECT done\r
318 } elsif ($v =~ /[{"\r\n%*\\\[]/) { # literal string
319 '{' . length($v) . "}\r\n" . $v;
320 } else { # quoted string
325 sub addr_envelope ($$;$) {
326 my ($eml, $x, $y) = @_;
327 my $v = $eml->header_raw($x) //
328 ($y ? $eml->header_raw($y) : undef) // return 'NIL';
330 my @x = $Address->parse($v) or return 'NIL';
332 map { '(' . join(' ',
333 _esc($_->name), 'NIL',
334 _esc($_->user), _esc($_->host)
340 sub eml_envelope ($) {
343 _esc($eml->header_raw('Date')),
344 _esc($eml->header_raw('Subject')),
345 addr_envelope($eml, 'From'),
346 addr_envelope($eml, 'Sender', 'From'),
347 addr_envelope($eml, 'Reply-To', 'From'),
348 addr_envelope($eml, 'To'),
349 addr_envelope($eml, 'Cc'),
350 addr_envelope($eml, 'Bcc'),
351 _esc($eml->header_raw('In-Reply-To')),
352 _esc($eml->header_raw('Message-ID')),
358 if ($hash && scalar keys %$hash) {
359 $hash = [ %$hash ]; # flatten hash into 1-dimensional array
360 '(' . join(' ', map { _esc($_) } @$hash) . ')';
366 sub body_disposition ($) {
368 my $cd = $eml->header_raw('Content-Disposition') or return 'NIL';
369 $cd = parse_content_disposition($cd);
370 my $buf = '('._esc($cd->{type});
371 $buf .= ' ' . _esc_hash(delete $cd->{attributes});
375 sub body_leaf ($$;$) {
376 my ($eml, $structure, $hold) = @_;
378 $eml->{is_submsg} and # parent was a message/(rfc822|news|global)
379 $buf .= eml_envelope($eml). ' ';
381 $buf .= '('._esc($ct->{type}).' ';
382 $buf .= _esc($ct->{subtype});
383 $buf .= ' ' . _esc_hash(delete $ct->{attributes});
384 $buf .= ' ' . _esc($eml->header_raw('Content-ID'));
385 $buf .= ' ' . _esc($eml->header_raw('Content-Description'));
386 my $cte = $eml->header_raw('Content-Transfer-Encoding') // '7bit';
387 $buf .= ' ' . _esc($cte);
388 $buf .= ' ' . $eml->{imap_body_len};
389 $buf .= ' '.($eml->body_raw =~ tr/\n/\n/) if lc($ct->{type}) eq 'text';
391 # for message/(rfc822|global|news), $hold[0] should have envelope
392 $buf .= ' ' . (@$hold ? join('', @$hold) : 'NIL') if $hold;
395 $buf .= ' '._esc($eml->header_raw('Content-MD5'));
396 $buf .= ' '. body_disposition($eml);
397 $buf .= ' '._esc($eml->header_raw('Content-Language'));
398 $buf .= ' '._esc($eml->header_raw('Content-Location'));
403 sub body_parent ($$$) {
404 my ($eml, $structure, $hold) = @_;
406 my $type = lc($ct->{type});
407 if ($type eq 'multipart') {
409 $buf .= @$hold ? join('', @$hold) : 'NIL';
410 $buf .= ' '._esc($ct->{subtype});
412 $buf .= ' '._esc_hash(delete $ct->{attributes});
413 $buf .= ' '.body_disposition($eml);
414 $buf .= ' '._esc($eml->header_raw('Content-Language'));
415 $buf .= ' '._esc($eml->header_raw('Content-Location'));
419 } else { # message/(rfc822|global|news)
420 @$hold = (body_leaf($eml, $structure, $hold));
424 # this is gross, but we need to process the parent part AFTER
425 # the child parts are done
426 sub bodystructure_prep {
428 my ($eml, $depth) = @$p; # ignore idx
429 # set length here, as $eml->{bdy} gets deleted for message/rfc822
430 $eml->{imap_body_len} = length($eml->body_raw);
431 push @$q, $eml, $depth;
434 # for FETCH BODY and FETCH BODYSTRUCTURE
435 sub fetch_body ($;$) {
436 my ($eml, $structure) = @_;
438 $eml->each_part(\&bodystructure_prep, \@q, 0, 1);
442 my ($part, $depth) = splice(@q, -2);
443 my $is_mp_parent = $depth == ($cur_depth - 1);
447 body_parent($part, $structure, \@hold);
449 unshift @hold, body_leaf($part, $structure);
455 sub requeue_once ($) {
457 # COMPRESS users all share the same DEFLATE context.
458 # Flush it here to ensure clients don't see
462 # no recursion, schedule another call ASAP,
463 # but only after all pending writes are done.
465 my $new_size = push(@{$self->{wbuf}}, \&long_step);
467 # wbuf may be populated by $cb, no need to rearm if so:
468 $self->requeue if $new_size == 1;
471 sub uid_fetch_cb { # called by git->cat_async via git_async_cat
472 my ($bref, $oid, $type, $size, $fetch_m_arg) = @_;
473 my ($self, undef, $msgs, undef, $ops, $partial) = @$fetch_m_arg;
474 my $smsg = shift @$msgs or die 'BUG: no smsg';
475 if (!defined($oid)) {
476 # it's possible to have TOCTOU if an admin runs
477 # public-inbox-(edit|purge), just move onto the next message
478 return requeue_once($self);
480 $smsg->{blob} eq $oid or die "BUG: $smsg->{blob} != $oid";
482 $$bref =~ s/(?<!\r)\n/\r\n/sg; # make strict clients happy
484 # fixup old bug from import (pre-a0c07cba0e5d8b6a)
485 $$bref =~ s/\A[\r\n]*From [^\r\n]*\r\n//s;
486 $self->msg_more("* $smsg->{num} FETCH (UID $smsg->{num}");
488 for (my $i = 0; $i < @$ops;) {
489 my $k = $ops->[$i++];
490 $ops->[$i++]->($self, $k, $smsg, $bref, $eml);
492 partial_emit($self, $partial, $eml) if $partial;
493 $self->msg_more(")\r\n");
498 my ($self, $k, undef, $bref) = @_;
499 $self->msg_more(" $k {" . length($$bref)."}\r\n");
500 $self->msg_more($$bref);
503 # Mail::IMAPClient::message_string cares about this by default
504 # (->Ignoresizeerrors attribute)
505 sub emit_rfc822_size {
506 my ($self, $k, undef, $bref) = @_;
507 $self->msg_more(' RFC822.SIZE ' . length($$bref));
510 sub emit_internaldate {
511 my ($self, undef, $smsg) = @_;
512 $self->msg_more(' INTERNALDATE "'.$smsg->internaldate.'"');
515 sub emit_flags { $_[0]->msg_more(' FLAGS ()') }
518 my ($self, undef, undef, undef, $eml) = @_;
519 $self->msg_more(' ENVELOPE '.eml_envelope($eml));
522 sub emit_rfc822_header {
523 my ($self, $k, undef, undef, $eml) = @_;
524 $self->msg_more(" $k {".length(${$eml->{hdr}})."}\r\n");
525 $self->msg_more(${$eml->{hdr}});
528 # n.b. this is sorted to be after any emit_eml_new ops
529 sub emit_rfc822_text {
530 my ($self, $k, undef, $bref) = @_;
531 $self->msg_more(" $k {".length($$bref)."}\r\n");
532 $self->msg_more($$bref);
535 sub emit_bodystructure {
536 my ($self, undef, undef, undef, $eml) = @_;
537 $self->msg_more(' BODYSTRUCTURE '.fetch_body($eml, 1));
541 my ($self, undef, undef, undef, $eml) = @_;
542 $self->msg_more(' BODY '.fetch_body($eml));
545 # set $eml once ($_[4] == $eml, $_[3] == $bref)
546 sub op_eml_new { $_[4] = PublicInbox::Eml->new($_[3]) }
548 sub uid_clamp ($$$) {
549 my ($self, $beg, $end) = @_;
550 my $uid_min = $self->{uid_min} or return;
551 my $uid_end = $uid_min + UID_BLOCK - 1;
552 $$beg = $uid_min if $$beg < $uid_min;
553 $$end = $uid_end if $$end > $uid_end;
556 sub range_step ($$) {
557 my ($self, $range_csv) = @_;
558 my ($beg, $end, $range);
559 if ($$range_csv =~ s/\A([^,]+),//) {
562 $range = $$range_csv;
565 if ($range =~ /\A([0-9]+):([0-9]+)\z/) {
566 ($beg, $end) = ($1 + 0, $2 + 0);
567 } elsif ($range =~ /\A([0-9]+):\*\z/) {
569 $end = $self->{ibx}->mm->max // 0;
570 my $uid_end = ($self->{uid_min} // 1) - 1 + UID_BLOCK;
571 $end = $uid_end if $end > $uid_end;
572 $beg = $end if $beg > $end;
573 } elsif ($range =~ /\A[0-9]+\z/) {
574 $beg = $end = $range + 0;
577 return 'BAD fetch range';
579 uid_clamp($self, \$beg, \$end) if defined($range);
580 [ $beg, $end, $$range_csv ];
583 sub refill_range ($$$) {
584 my ($self, $msgs, $range_info) = @_;
585 my ($beg, $end, $range_csv) = @$range_info;
586 if (scalar(@$msgs = @{$self->{ibx}->over->query_xover($beg, $end)})) {
587 $range_info->[0] = $msgs->[-1]->{num} + 1;
590 return 'OK Fetch done' if !$range_csv;
591 my $next_range = range_step($self, \$range_csv);
592 return $next_range if !ref($next_range); # error
593 @$range_info = @$next_range;
594 undef; # keep looping
597 sub uid_fetch_msg { # long_response
598 my ($self, $tag, $msgs, $range_info) = @_; # \@ops, \@partial
599 while (!@$msgs) { # rare
600 if (my $end = refill_range($self, $msgs, $range_info)) {
601 $self->write(\"$tag $end\r\n");
605 git_async_cat($self->{ibx}->git, $msgs->[0]->{blob},
606 \&uid_fetch_cb, \@_);
609 sub uid_fetch_smsg { # long_response
610 my ($self, $tag, $msgs, $range_info, $ops) = @_;
611 while (!@$msgs) { # rare
612 if (my $end = refill_range($self, $msgs, $range_info)) {
613 $self->write(\"$tag $end\r\n");
617 for my $smsg (@$msgs) {
618 $self->msg_more("* $smsg->{num} FETCH (UID $smsg->{num}");
619 for (my $i = 0; $i < @$ops;) {
620 my $k = $ops->[$i++];
621 $ops->[$i++]->($self, $k, $smsg);
623 $self->msg_more(")\r\n");
629 sub uid_fetch_uid { # long_response
630 my ($self, $tag, $uids, $range_info, $ops) = @_;
631 while (!@$uids) { # rare
632 my ($beg, $end, $range_csv) = @$range_info;
633 if (scalar(@$uids = @{$self->{ibx}->over->
634 uid_range($beg, $end)})) {
635 $range_info->[0] = $uids->[-1] + 1;
636 } elsif (!$range_csv) {
637 $self->write(\"$tag OK Fetch done\r\n");
640 my $next_range = range_step($self, \$range_csv);
641 if (!ref($next_range)) { # error
642 $self->write(\"$tag $next_range\r\n");
645 @$range_info = @$next_range;
650 $self->msg_more("* $_ FETCH (UID $_");
651 for (my $i = 0; $i < @$ops;) {
652 my $k = $ops->[$i++];
653 $ops->[$i++]->($self, $k);
655 $self->msg_more(")\r\n");
661 sub cmd_status ($$$;@) {
662 my ($self, $tag, $mailbox, @items) = @_;
663 return "$tag BAD no items\r\n" if !scalar(@items);
664 ($items[0] !~ s/\A\(//s || $items[-1] !~ s/\)\z//s) and
665 return "$tag BAD invalid args\r\n";
666 my ($ibx, $exists, $uidnext) = inbox_lookup($self, $mailbox);
667 return "$tag NO Mailbox doesn't exist: $mailbox\r\n" if !$ibx;
669 for my $it (@items) {
672 if ($it =~ /\A(?:MESSAGES|UNSEEN|RECENT)\z/) {
674 } elsif ($it eq 'UIDNEXT') {
676 } elsif ($it eq 'UIDVALIDITY') {
677 push @it, $ibx->{uidvalidity};
679 return "$tag BAD invalid item\r\n";
682 return "$tag BAD no items\r\n" if !@it;
683 "* STATUS $mailbox (".join(' ', @it).")\r\n" .
684 "$tag OK Status done\r\n";
687 my %patmap = ('*' => '.*', '%' => '[^\.]*');
688 sub cmd_list ($$$$) {
689 my ($self, $tag, $refname, $wildcard) = @_;
690 my $l = $self->{imapd}->{inboxlist};
691 if ($refname eq '' && $wildcard eq '') {
692 # request for hierarchy delimiter
693 $l = [ qq[* LIST (\\Noselect) "." ""\r\n] ];
694 } elsif ($refname ne '' || $wildcard ne '*') {
695 $wildcard = lc $wildcard;
696 $wildcard =~ s!([^a-z0-9_])!$patmap{$1} // "\Q$1"!eg;
697 $l = [ grep(/ \Q$refname\E$wildcard\r\n\z/s, @$l) ];
699 \(join('', @$l, "$tag OK List done\r\n"));
702 sub cmd_lsub ($$$$) {
703 my (undef, $tag) = @_; # same args as cmd_list
704 "$tag OK Lsub done\r\n";
707 sub eml_index_offs_i { # PublicInbox::Eml::each_part callback
709 my ($eml, undef, $idx) = @$p;
710 if ($idx && lc($eml->ct->{type}) eq 'multipart') {
711 $eml->{imap_bdy} = $eml->{bdy} // \'';
713 $all->{$idx} = $eml; # $idx => Eml
716 # prepares an index for BODY[$SECTION_IDX] fetches
717 sub eml_body_idx ($$) {
718 my ($eml, $section_idx) = @_;
719 my $idx = $eml->{imap_all_parts} //= do {
721 $eml->each_part(\&eml_index_offs_i, $all, 0, 1);
722 # top-level of multipart, BODY[0] not allowed (nz-number)
726 $idx->{$section_idx};
729 # BODY[($SECTION_IDX)?(.$SECTION_NAME)?]<$offset.$bytes>
731 my ($eml, $section_idx, $section_name) = @_;
732 if (defined $section_idx) {
733 $eml = eml_body_idx($eml, $section_idx) or return;
735 if (defined $section_name) {
736 if ($section_name eq 'MIME') {
737 # RFC 3501 6.4.5 states:
738 # The MIME part specifier MUST be prefixed
739 # by one or more numeric part specifiers
740 return unless defined $section_idx;
741 return $eml->header_obj->as_string . "\r\n";
743 my $bdy = $eml->{bdy} // $eml->{imap_bdy} // \'';
744 $eml = PublicInbox::Eml->new($$bdy);
745 if ($section_name eq 'TEXT') {
746 return $eml->body_raw;
747 } elsif ($section_name eq 'HEADER') {
748 return $eml->header_obj->as_string . "\r\n";
750 die "BUG: bad section_name=$section_name";
753 ${$eml->{bdy} // $eml->{imap_bdy} // \''};
756 # similar to what's in PublicInbox::Eml::re_memo, but doesn't memoize
757 # to avoid OOM with malicious users
758 sub hdrs_regexp ($) {
760 my $names = join('|', map { "\Q$_" } split(/[ \t]+/, $hdrs));
761 qr/^(?:$names):[ \t]*[^\n]*\r?\n # 1st line
762 # continuation lines:
763 (?:[^:\n]*?[ \t]+[^\n]*\r?\n)*
767 # BODY[($SECTION_IDX.)?HEADER.FIELDS.NOT ($HDRS)]<$offset.$bytes>
768 sub partial_hdr_not {
769 my ($eml, $section_idx, $hdrs_re) = @_;
770 if (defined $section_idx) {
771 $eml = eml_body_idx($eml, $section_idx) or return;
773 my $str = $eml->header_obj->as_string;
774 $str =~ s/$hdrs_re//g;
778 # BODY[($SECTION_IDX.)?HEADER.FIELDS ($HDRS)]<$offset.$bytes>
779 sub partial_hdr_get {
780 my ($eml, $section_idx, $hdrs_re) = @_;
781 if (defined $section_idx) {
782 $eml = eml_body_idx($eml, $section_idx) or return;
784 my $str = $eml->header_obj->as_string;
785 join('', ($str =~ m/($hdrs_re)/g), "\r\n");
788 sub partial_prepare ($$$) {
789 my ($partial, $want, $att) = @_;
791 # recombine [ "BODY[1.HEADER.FIELDS", "(foo", "bar)]" ]
792 # back to: "BODY[1.HEADER.FIELDS (foo bar)]"
793 return unless $att =~ /\ABODY\[/s;
794 until (rindex($att, ']') >= 0) {
795 my $next = shift @$want or return;
796 $att .= ' ' . uc($next);
798 if ($att =~ /\ABODY\[([0-9]+(?:\.[0-9]+)*)? # 1 - section_idx
799 (?:\.(HEADER|MIME|TEXT))? # 2 - section_name
800 \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 3, 4
801 $partial->{$att} = [ \&partial_body, $1, $2, $3, $4 ];
802 } elsif ($att =~ /\ABODY\[(?:([0-9]+(?:\.[0-9]+)*)\.)? # 1 - section_idx
803 (?:HEADER\.FIELDS(\.NOT)?)\x20 # 2
804 \(([A-Z0-9\-\x20]+)\) # 3 - hdrs
805 \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 4 5
806 my $tmp = $partial->{$att} = [ $2 ? \&partial_hdr_not
809 $tmp->[2] = hdrs_regexp($3);
815 sub partial_emit ($$$) {
816 my ($self, $partial, $eml) = @_;
818 my ($k, $cb, @args) = @$_;
819 my ($offset, $len) = splice(@args, -2);
820 # $cb is partial_body|partial_hdr_get|partial_hdr_not
821 my $str = $cb->($eml, @args) // '';
822 if (defined $offset) {
824 $str = substr($str, $offset, $len);
825 $k =~ s/\.$len>\z/>/ or warn
826 "BUG: unable to remove `.$len>' from `$k'";
828 $str = substr($str, $offset);
834 $self->msg_more(" $k {$len}\r\n");
835 $self->msg_more($str);
839 sub fetch_compile ($) {
841 if ($want->[0] =~ s/\A\(//s) {
842 $want->[-1] =~ s/\)\z//s or return 'BAD no rparen';
844 my (%partial, %seen, @op);
846 while (defined(my $att = shift @$want)) {
848 next if $att eq 'UID'; # always returned
849 $att =~ s/\ABODY\.PEEK\[/BODY\[/; # we're read-only
850 my $x = $FETCH_ATT{$att};
852 while (my ($k, $fl_cb) = each %$x) {
854 $need |= $fl_cb->[0];
856 # insert a special op to convert $bref to $eml
857 # the first time we need it
858 if ($need == NEED_EML && !$seen{$need}++) {
859 push @op, $OP_EML_NEW;
861 # $fl_cb = [ flags, \&emit_foo ]
862 push @op, [ @$fl_cb , $k ];
864 } elsif (!partial_prepare(\%partial, $want, $att)) {
865 return "BAD param: $att";
870 # stabilize partial order for consistency and ease-of-debugging:
871 if (scalar keys %partial) {
873 push @op, $OP_EML_NEW if !$seen{$need}++;
874 $r[2] = [ map { [ $_, @{$partial{$_}} ] } sort keys %partial ];
877 $r[0] = $need & NEED_BLOB ? \&uid_fetch_msg :
878 ($need & NEED_SMSG ? \&uid_fetch_smsg : \&uid_fetch_uid);
880 # r[1] = [ $key1, $cb1, $key2, $cb2, ... ]
881 use sort 'stable'; # makes output more consistent
882 $r[1] = [ map { ($_->[2], $_->[1]) } sort { $a->[0] <=> $b->[0] } @op ];
886 sub cmd_uid_fetch ($$$;@) {
887 my ($self, $tag, $range_csv, @want) = @_;
888 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
889 my ($cb, $ops, $partial) = fetch_compile(\@want);
890 return "$tag $cb\r\n" unless $ops;
892 $range_csv = 'bad' if $range_csv !~ $valid_range;
893 my $range_info = range_step($self, \$range_csv);
894 return "$tag $range_info\r\n" if !ref($range_info);
895 long_response($self, $cb, $tag, [], $range_info, $ops, $partial);
898 sub parse_date ($) { # 02-Oct-1993
899 my ($date_text) = @_;
900 my ($dd, $mon, $yyyy) = split(/-/, $_[0], 3);
901 defined($yyyy) or return;
902 my $mm = $MoY{$mon} // return;
903 $dd =~ /\A[0123]?[0-9]\z/ or return;
904 $yyyy =~ /\A[0-9]{4,}\z/ or return; # Y10K-compatible!
905 timegm(0, 0, 0, $dd, $mm, $yyyy);
908 sub uid_search_uid_range { # long_response
909 my ($self, $tag, $beg, $end, $sql) = @_;
910 my $uids = $self->{ibx}->over->uid_range($$beg, $end, $sql);
912 $$beg = $uids->[-1] + 1;
913 $self->msg_more(join(' ', '', @$uids));
915 $self->write(\"\r\n$tag OK Search done\r\n");
921 my ($q, $k, $d) = @_;
925 if ($k eq 'SENTON') {
926 my $end = $d + 86399; # no leap day...
927 my $da = strftime('%Y%m%d%H%M%S', gmtime($d));
928 my $db = strftime('%Y%m%d%H%M%S', gmtime($end));
929 $q->{xap} .= " dt:$da..$db";
930 $$sql .= " AND ds >= $d AND ds <= $end" if defined($sql);
931 } elsif ($k eq 'SENTBEFORE') {
932 $q->{xap} .= ' d:..'.strftime('%Y%m%d', gmtime($d));
933 $$sql .= " AND ds <= $d" if defined($sql);
934 } elsif ($k eq 'SENTSINCE') {
935 $q->{xap} .= ' d:'.strftime('%Y%m%d', gmtime($d)).'..';
936 $$sql .= " AND ds >= $d" if defined($sql);
938 # INTERNALDATE (Received)
939 } elsif ($k eq 'ON') {
940 my $end = $d + 86399; # no leap day...
941 $q->{xap} .= " ts:$d..$end";
942 $$sql .= " AND ts >= $d AND ts <= $end" if defined($sql);
943 } elsif ($k eq 'BEFORE') {
944 $q->{xap} .= " ts:..$d";
945 $$sql .= " AND ts <= $d" if defined($sql);
946 } elsif ($k eq 'SINCE') {
947 $q->{xap} .= " ts:$d..";
948 $$sql .= " AND ts >= $d" if defined($sql);
950 die "BUG: $k not recognized";
954 # IMAP to Xapian search key mapping
959 TEXT => '', # n.b. does not include all headers
962 # BCC => 'bcc:', # TODO
963 # KEYWORD # TODO ? dfpre,dfpost,...
967 my ($self, $rest) = @_;
968 if (uc($rest->[0]) eq 'CHARSET') {
970 defined(my $c = shift @$rest) or return 'BAD missing charset';
971 $c =~ /\A(?:UTF-8|US-ASCII)\z/ or return 'NO [BADCHARSET]';
974 my $sql = ''; # date conditions, {sql} deleted if Xapian is needed
975 my $q = { xap => '', sql => \$sql };
977 my $k = uc(shift @$rest);
979 next if $k =~ /\A(?:ALL|RECENT|UNSEEN|NEW)\z/;
980 next if $k eq 'AND'; # the default, until we support OR
981 if ($k =~ $valid_range) { # sequence numbers == UIDs
982 push @{$q->{uid}}, $k;
983 } elsif ($k eq 'UID') {
984 $k = shift(@$rest) // '';
985 $k =~ $valid_range or return 'BAD UID range';
986 push @{$q->{uid}}, $k;
987 } elsif ($k =~ /\A(?:SENT)?(?:SINCE|ON|BEFORE)\z/) {
988 my $d = parse_date(shift(@$rest) // '');
989 defined $d or return "BAD $k date format";
990 date_search($q, $k, $d);
991 } elsif ($k =~ /\A(?:SMALLER|LARGER)\z/) {
992 delete $q->{sql}; # can't use over.sqlite3
993 my $bytes = shift(@$rest) // '';
994 $bytes =~ /\A[0-9]+\z/ or return "BAD $k not a number";
995 $q->{xap} .= ' bytes:' . ($k eq 'SMALLER' ?
998 } elsif (defined(my $xk = $I2X{$k})) {
999 delete $q->{sql}; # can't use over.sqlite3
1000 my $arg = shift @$rest;
1001 defined($arg) or return "BAD $k no arg";
1003 # Xapian can't handle [*"] in probabilistic terms
1005 $q->{xap} .= qq[ $xk:"$arg"];
1007 # TODO: parentheses, OR, NOT ...
1008 return "BAD $k not supported (yet?)";
1012 # favor using over.sqlite3 if possible, since Xapian is optional
1013 if (exists $q->{sql}) {
1015 delete($q->{sql}) if $sql eq '';
1016 } elsif (!$self->{ibx}->search) {
1017 return 'BAD Xapian not configured for mailbox';
1020 if (my $uid = $q->{uid}) {
1021 ((@$uid > 1) || $uid->[0] =~ /,/) and
1022 return 'BAD multiple ranges not supported, yet';
1023 ($q->{sql} // $q->{xap}) and
1024 return 'BAD ranges and queries do not mix, yet';
1025 $q->{uid} = join(',', @$uid); # TODO: multiple ranges
1030 sub cmd_uid_search ($$$;) {
1031 my ($self, $tag) = splice(@_, 0, 2);
1032 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1033 my $q = parse_query($self, \@_);
1034 return "$tag $q\r\n" if !ref($q);
1035 my $sql = delete $q->{sql};
1037 if (!scalar(keys %$q)) {
1038 $self->msg_more('* SEARCH');
1039 my $beg = $self->{uid_min} // 1;
1040 my $end = $ibx->mm->max;
1041 uid_clamp($self, \$beg, \$end);
1042 long_response($self, \&uid_search_uid_range,
1043 $tag, \$beg, $end, $sql);
1044 } elsif (my $uid = $q->{uid}) {
1045 if ($uid =~ /\A([0-9]+):([0-9]+|\*)\z/s) {
1046 my ($beg, $end) = ($1, $2);
1047 $end = $ibx->mm->max if $end eq '*';
1048 uid_clamp($self, \$beg, \$end);
1049 $self->msg_more('* SEARCH');
1050 long_response($self, \&uid_search_uid_range,
1051 $tag, \$beg, $end, $sql);
1052 } elsif ($uid =~ /\A[0-9]+\z/s) {
1053 $uid = $ibx->over->get_art($uid) ? " $uid" : '';
1054 "* SEARCH$uid\r\n$tag OK Search done\r\n";
1056 "$tag BAD Error\r\n";
1059 "$tag BAD Error\r\n";
1063 sub args_ok ($$) { # duplicated from PublicInbox::NNTP
1064 my ($cb, $argc) = @_;
1065 my $tot = prototype $cb;
1066 my ($nreq, undef) = split(';', $tot);
1067 $nreq = ($nreq =~ tr/$//) - 1;
1068 $tot = ($tot =~ tr/$//) - 1;
1069 ($argc <= $tot && $argc >= $nreq);
1072 # returns 1 if we can continue, 0 if not due to buffered writes or disconnect
1073 sub process_line ($$) {
1074 my ($self, $l) = @_;
1075 my ($tag, $req, @args) = parse_line('[ \t]+', 0, $l);
1076 pop(@args) if (@args && !defined($args[-1]));
1077 if (@args && uc($req) eq 'UID') {
1078 $req .= "_".(shift @args);
1081 if (my $cmd = $self->can('cmd_'.lc($req // ''))) {
1082 defined($self->{-idle_tag}) ?
1083 "$self->{-idle_tag} BAD expected DONE\r\n" :
1084 $cmd->($self, $tag, @args);
1085 } elsif (uc($tag // '') eq 'DONE' && !defined($req)) {
1086 cmd_done($self, $tag);
1087 } else { # this is weird
1088 auth_challenge_ok($self) //
1090 ' BAD Error in IMAP command '.
1092 ": Unknown command\r\n";
1096 if ($err && $self->{sock}) {
1098 err($self, 'error from: %s (%s)', $l, $err);
1100 $res = "$tag BAD program fault - command not performed\r\n";
1102 return 0 unless defined $res;
1108 # wbuf is unset or empty, here; {long} may add to it
1109 my ($fd, $cb, $t0, @args) = @{$self->{long_cb}};
1110 my $more = eval { $cb->($self, @args) };
1111 if ($@ || !$self->{sock}) { # something bad happened...
1112 delete $self->{long_cb};
1113 my $elapsed = now() - $t0;
1116 "%s during long response[$fd] - %0.6f",
1119 out($self, " deferred[$fd] aborted - %0.6f", $elapsed);
1121 } elsif ($more) { # $self->{wbuf}:
1122 $self->update_idle_time;
1124 # control passed to $more may be a GitAsyncCat object
1125 requeue_once($self) if !ref($more);
1126 } else { # all done!
1127 delete $self->{long_cb};
1128 my $elapsed = now() - $t0;
1129 my $fd = fileno($self->{sock});
1130 out($self, " deferred[$fd] done - %0.6f", $elapsed);
1131 my $wbuf = $self->{wbuf}; # do NOT autovivify
1133 $self->requeue unless $wbuf && @$wbuf;
1138 my ($self, $fmt, @args) = @_;
1139 printf { $self->{imapd}->{err} } $fmt."\n", @args;
1143 my ($self, $fmt, @args) = @_;
1144 printf { $self->{imapd}->{out} } $fmt."\n", @args;
1147 sub long_response ($$;@) {
1148 my ($self, $cb, @args) = @_; # cb returns true if more, false if done
1150 my $sock = $self->{sock} or return;
1151 # make sure we disable reading during a long response,
1152 # clients should not be sending us stuff and making us do more
1153 # work while we are stream a response to them
1154 $self->{long_cb} = [ fileno($sock), $cb, now(), @args ];
1155 long_step($self); # kick off!
1159 # callback used by PublicInbox::DS for any (e)poll (in/out/hup/err)
1163 return unless $self->flush_write && $self->{sock} && !$self->{long_cb};
1165 $self->update_idle_time;
1166 # only read more requests if we've drained the write buffer,
1167 # otherwise we can be buffering infinitely w/o backpressure
1169 my $rbuf = $self->{rbuf} // \(my $x = '');
1170 my $line = index($$rbuf, "\n");
1172 return $self->close if length($$rbuf) >= LINE_MAX;
1173 $self->do_read($rbuf, LINE_MAX, length($$rbuf)) or return;
1174 $line = index($$rbuf, "\n");
1176 $line = substr($$rbuf, 0, $line + 1, '');
1177 $line =~ s/\r?\n\z//s;
1178 return $self->close if $line =~ /[[:cntrl:]]/s;
1180 my $fd = fileno($self->{sock});
1181 my $r = eval { process_line($self, $line) };
1182 my $pending = $self->{wbuf} ? ' pending' : '';
1183 out($self, "[$fd] %s - %0.6f$pending - $r", $line, now() - $t0);
1185 return $self->close if $r < 0;
1186 $self->rbuf_idle($rbuf);
1187 $self->update_idle_time;
1189 # maybe there's more pipelined data, or we'll have
1190 # to register it for socket-readiness notifications
1191 $self->requeue unless $pending;
1194 sub compressed { undef }
1196 sub zflush {} # overridden by IMAPdeflate
1199 sub cmd_compress ($$$) {
1200 my ($self, $tag, $alg) = @_;
1201 return "$tag BAD DEFLATE only\r\n" if uc($alg) ne "DEFLATE";
1202 return "$tag BAD COMPRESS active\r\n" if $self->compressed;
1204 # CRIME made TLS compression obsolete
1205 # return "$tag NO [COMPRESSIONACTIVE]\r\n" if $self->tls_compressed;
1207 PublicInbox::IMAPdeflate->enable($self, $tag);
1212 sub cmd_starttls ($$) {
1213 my ($self, $tag) = @_;
1214 my $sock = $self->{sock} or return;
1215 if ($sock->can('stop_SSL') || $self->compressed) {
1216 return "$tag BAD TLS or compression already enabled\r\n";
1218 my $opt = $self->{imapd}->{accept_tls} or
1219 return "$tag BAD can not initiate TLS negotiation\r\n";
1220 $self->write(\"$tag OK begin TLS negotiation now\r\n");
1221 $self->{sock} = IO::Socket::SSL->start_SSL($sock, %$opt);
1222 $self->requeue if PublicInbox::DS::accept_tls_step($self);
1226 # for graceful shutdown in PublicInbox::Daemon:
1228 my ($self, $now) = @_;
1229 ($self->{rbuf} || $self->{wbuf} || $self->not_idle_long($now));
1234 if (my $ibx = delete $self->{ibx}) {
1235 stop_idle($self, $ibx);
1237 $self->SUPER::close; # PublicInbox::DS::close
1240 # we're read-only, so SELECT and EXAMINE do the same thing
1242 *cmd_select = \&cmd_examine;
1243 *cmd_fetch = \&cmd_uid_fetch;
1245 package PublicInbox::IMAP_preauth;
1246 our @ISA = qw(PublicInbox::IMAP);