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_SMSG, \&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). Admins are encouraged to
505 # --reindex for IMAP support, anyways.
506 sub emit_rfc822_size {
507 my ($self, $k, $smsg) = @_;
508 $self->msg_more(' RFC822.SIZE ' . $smsg->{bytes});
511 sub emit_internaldate {
512 my ($self, undef, $smsg) = @_;
513 $self->msg_more(' INTERNALDATE "'.$smsg->internaldate.'"');
516 sub emit_flags { $_[0]->msg_more(' FLAGS ()') }
519 my ($self, undef, undef, undef, $eml) = @_;
520 $self->msg_more(' ENVELOPE '.eml_envelope($eml));
523 sub emit_rfc822_header {
524 my ($self, $k, undef, undef, $eml) = @_;
525 $self->msg_more(" $k {".length(${$eml->{hdr}})."}\r\n");
526 $self->msg_more(${$eml->{hdr}});
529 # n.b. this is sorted to be after any emit_eml_new ops
530 sub emit_rfc822_text {
531 my ($self, $k, undef, $bref) = @_;
532 $self->msg_more(" $k {".length($$bref)."}\r\n");
533 $self->msg_more($$bref);
536 sub emit_bodystructure {
537 my ($self, undef, undef, undef, $eml) = @_;
538 $self->msg_more(' BODYSTRUCTURE '.fetch_body($eml, 1));
542 my ($self, undef, undef, undef, $eml) = @_;
543 $self->msg_more(' BODY '.fetch_body($eml));
546 # set $eml once ($_[4] == $eml, $_[3] == $bref)
547 sub op_eml_new { $_[4] = PublicInbox::Eml->new($_[3]) }
549 sub uid_clamp ($$$) {
550 my ($self, $beg, $end) = @_;
551 my $uid_min = $self->{uid_min} or return;
552 my $uid_end = $uid_min + UID_BLOCK - 1;
553 $$beg = $uid_min if $$beg < $uid_min;
554 $$end = $uid_end if $$end > $uid_end;
557 sub range_step ($$) {
558 my ($self, $range_csv) = @_;
559 my ($beg, $end, $range);
560 if ($$range_csv =~ s/\A([^,]+),//) {
563 $range = $$range_csv;
566 if ($range =~ /\A([0-9]+):([0-9]+)\z/) {
567 ($beg, $end) = ($1 + 0, $2 + 0);
568 } elsif ($range =~ /\A([0-9]+):\*\z/) {
570 $end = $self->{ibx}->mm->max // 0;
571 my $uid_end = ($self->{uid_min} // 1) - 1 + UID_BLOCK;
572 $end = $uid_end if $end > $uid_end;
573 $beg = $end if $beg > $end;
574 } elsif ($range =~ /\A[0-9]+\z/) {
575 $beg = $end = $range + 0;
578 return 'BAD fetch range';
580 uid_clamp($self, \$beg, \$end) if defined($range);
581 [ $beg, $end, $$range_csv ];
584 sub refill_range ($$$) {
585 my ($self, $msgs, $range_info) = @_;
586 my ($beg, $end, $range_csv) = @$range_info;
587 if (scalar(@$msgs = @{$self->{ibx}->over->query_xover($beg, $end)})) {
588 $range_info->[0] = $msgs->[-1]->{num} + 1;
591 return 'OK Fetch done' if !$range_csv;
592 my $next_range = range_step($self, \$range_csv);
593 return $next_range if !ref($next_range); # error
594 @$range_info = @$next_range;
595 undef; # keep looping
598 sub uid_fetch_msg { # long_response
599 my ($self, $tag, $msgs, $range_info) = @_; # \@ops, \@partial
600 while (!@$msgs) { # rare
601 if (my $end = refill_range($self, $msgs, $range_info)) {
602 $self->write(\"$tag $end\r\n");
606 git_async_cat($self->{ibx}->git, $msgs->[0]->{blob},
607 \&uid_fetch_cb, \@_);
610 sub uid_fetch_smsg { # long_response
611 my ($self, $tag, $msgs, $range_info, $ops) = @_;
612 while (!@$msgs) { # rare
613 if (my $end = refill_range($self, $msgs, $range_info)) {
614 $self->write(\"$tag $end\r\n");
618 for my $smsg (@$msgs) {
619 $self->msg_more("* $smsg->{num} FETCH (UID $smsg->{num}");
620 for (my $i = 0; $i < @$ops;) {
621 my $k = $ops->[$i++];
622 $ops->[$i++]->($self, $k, $smsg);
624 $self->msg_more(")\r\n");
630 sub uid_fetch_uid { # long_response
631 my ($self, $tag, $uids, $range_info, $ops) = @_;
632 while (!@$uids) { # rare
633 my ($beg, $end, $range_csv) = @$range_info;
634 if (scalar(@$uids = @{$self->{ibx}->over->
635 uid_range($beg, $end)})) {
636 $range_info->[0] = $uids->[-1] + 1;
637 } elsif (!$range_csv) {
638 $self->write(\"$tag OK Fetch done\r\n");
641 my $next_range = range_step($self, \$range_csv);
642 if (!ref($next_range)) { # error
643 $self->write(\"$tag $next_range\r\n");
646 @$range_info = @$next_range;
651 $self->msg_more("* $_ FETCH (UID $_");
652 for (my $i = 0; $i < @$ops;) {
653 my $k = $ops->[$i++];
654 $ops->[$i++]->($self, $k);
656 $self->msg_more(")\r\n");
662 sub cmd_status ($$$;@) {
663 my ($self, $tag, $mailbox, @items) = @_;
664 return "$tag BAD no items\r\n" if !scalar(@items);
665 ($items[0] !~ s/\A\(//s || $items[-1] !~ s/\)\z//s) and
666 return "$tag BAD invalid args\r\n";
667 my ($ibx, $exists, $uidnext) = inbox_lookup($self, $mailbox);
668 return "$tag NO Mailbox doesn't exist: $mailbox\r\n" if !$ibx;
670 for my $it (@items) {
673 if ($it =~ /\A(?:MESSAGES|UNSEEN|RECENT)\z/) {
675 } elsif ($it eq 'UIDNEXT') {
677 } elsif ($it eq 'UIDVALIDITY') {
678 push @it, $ibx->{uidvalidity};
680 return "$tag BAD invalid item\r\n";
683 return "$tag BAD no items\r\n" if !@it;
684 "* STATUS $mailbox (".join(' ', @it).")\r\n" .
685 "$tag OK Status done\r\n";
688 my %patmap = ('*' => '.*', '%' => '[^\.]*');
689 sub cmd_list ($$$$) {
690 my ($self, $tag, $refname, $wildcard) = @_;
691 my $l = $self->{imapd}->{inboxlist};
692 if ($refname eq '' && $wildcard eq '') {
693 # request for hierarchy delimiter
694 $l = [ qq[* LIST (\\Noselect) "." ""\r\n] ];
695 } elsif ($refname ne '' || $wildcard ne '*') {
696 $wildcard = lc $wildcard;
697 $wildcard =~ s!([^a-z0-9_])!$patmap{$1} // "\Q$1"!eg;
698 $l = [ grep(/ \Q$refname\E$wildcard\r\n\z/s, @$l) ];
700 \(join('', @$l, "$tag OK List done\r\n"));
703 sub cmd_lsub ($$$$) {
704 my (undef, $tag) = @_; # same args as cmd_list
705 "$tag OK Lsub done\r\n";
708 sub eml_index_offs_i { # PublicInbox::Eml::each_part callback
710 my ($eml, undef, $idx) = @$p;
711 if ($idx && lc($eml->ct->{type}) eq 'multipart') {
712 $eml->{imap_bdy} = $eml->{bdy} // \'';
714 $all->{$idx} = $eml; # $idx => Eml
717 # prepares an index for BODY[$SECTION_IDX] fetches
718 sub eml_body_idx ($$) {
719 my ($eml, $section_idx) = @_;
720 my $idx = $eml->{imap_all_parts} //= do {
722 $eml->each_part(\&eml_index_offs_i, $all, 0, 1);
723 # top-level of multipart, BODY[0] not allowed (nz-number)
727 $idx->{$section_idx};
730 # BODY[($SECTION_IDX)?(.$SECTION_NAME)?]<$offset.$bytes>
732 my ($eml, $section_idx, $section_name) = @_;
733 if (defined $section_idx) {
734 $eml = eml_body_idx($eml, $section_idx) or return;
736 if (defined $section_name) {
737 if ($section_name eq 'MIME') {
738 # RFC 3501 6.4.5 states:
739 # The MIME part specifier MUST be prefixed
740 # by one or more numeric part specifiers
741 return unless defined $section_idx;
742 return $eml->header_obj->as_string . "\r\n";
744 my $bdy = $eml->{bdy} // $eml->{imap_bdy} // \'';
745 $eml = PublicInbox::Eml->new($$bdy);
746 if ($section_name eq 'TEXT') {
747 return $eml->body_raw;
748 } elsif ($section_name eq 'HEADER') {
749 return $eml->header_obj->as_string . "\r\n";
751 die "BUG: bad section_name=$section_name";
754 ${$eml->{bdy} // $eml->{imap_bdy} // \''};
757 # similar to what's in PublicInbox::Eml::re_memo, but doesn't memoize
758 # to avoid OOM with malicious users
759 sub hdrs_regexp ($) {
761 my $names = join('|', map { "\Q$_" } split(/[ \t]+/, $hdrs));
762 qr/^(?:$names):[ \t]*[^\n]*\r?\n # 1st line
763 # continuation lines:
764 (?:[^:\n]*?[ \t]+[^\n]*\r?\n)*
768 # BODY[($SECTION_IDX.)?HEADER.FIELDS.NOT ($HDRS)]<$offset.$bytes>
769 sub partial_hdr_not {
770 my ($eml, $section_idx, $hdrs_re) = @_;
771 if (defined $section_idx) {
772 $eml = eml_body_idx($eml, $section_idx) or return;
774 my $str = $eml->header_obj->as_string;
775 $str =~ s/$hdrs_re//g;
779 # BODY[($SECTION_IDX.)?HEADER.FIELDS ($HDRS)]<$offset.$bytes>
780 sub partial_hdr_get {
781 my ($eml, $section_idx, $hdrs_re) = @_;
782 if (defined $section_idx) {
783 $eml = eml_body_idx($eml, $section_idx) or return;
785 my $str = $eml->header_obj->as_string;
786 join('', ($str =~ m/($hdrs_re)/g), "\r\n");
789 sub partial_prepare ($$$) {
790 my ($partial, $want, $att) = @_;
792 # recombine [ "BODY[1.HEADER.FIELDS", "(foo", "bar)]" ]
793 # back to: "BODY[1.HEADER.FIELDS (foo bar)]"
794 return unless $att =~ /\ABODY\[/s;
795 until (rindex($att, ']') >= 0) {
796 my $next = shift @$want or return;
797 $att .= ' ' . uc($next);
799 if ($att =~ /\ABODY\[([0-9]+(?:\.[0-9]+)*)? # 1 - section_idx
800 (?:\.(HEADER|MIME|TEXT))? # 2 - section_name
801 \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 3, 4
802 $partial->{$att} = [ \&partial_body, $1, $2, $3, $4 ];
803 } elsif ($att =~ /\ABODY\[(?:([0-9]+(?:\.[0-9]+)*)\.)? # 1 - section_idx
804 (?:HEADER\.FIELDS(\.NOT)?)\x20 # 2
805 \(([A-Z0-9\-\x20]+)\) # 3 - hdrs
806 \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 4 5
807 my $tmp = $partial->{$att} = [ $2 ? \&partial_hdr_not
810 $tmp->[2] = hdrs_regexp($3);
816 sub partial_emit ($$$) {
817 my ($self, $partial, $eml) = @_;
819 my ($k, $cb, @args) = @$_;
820 my ($offset, $len) = splice(@args, -2);
821 # $cb is partial_body|partial_hdr_get|partial_hdr_not
822 my $str = $cb->($eml, @args) // '';
823 if (defined $offset) {
825 $str = substr($str, $offset, $len);
826 $k =~ s/\.$len>\z/>/ or warn
827 "BUG: unable to remove `.$len>' from `$k'";
829 $str = substr($str, $offset);
835 $self->msg_more(" $k {$len}\r\n");
836 $self->msg_more($str);
840 sub fetch_compile ($) {
842 if ($want->[0] =~ s/\A\(//s) {
843 $want->[-1] =~ s/\)\z//s or return 'BAD no rparen';
845 my (%partial, %seen, @op);
847 while (defined(my $att = shift @$want)) {
849 next if $att eq 'UID'; # always returned
850 $att =~ s/\ABODY\.PEEK\[/BODY\[/; # we're read-only
851 my $x = $FETCH_ATT{$att};
853 while (my ($k, $fl_cb) = each %$x) {
855 $need |= $fl_cb->[0];
857 # insert a special op to convert $bref to $eml
858 # the first time we need it
859 if ($need == NEED_EML && !$seen{$need}++) {
860 push @op, $OP_EML_NEW;
862 # $fl_cb = [ flags, \&emit_foo ]
863 push @op, [ @$fl_cb , $k ];
865 } elsif (!partial_prepare(\%partial, $want, $att)) {
866 return "BAD param: $att";
871 # stabilize partial order for consistency and ease-of-debugging:
872 if (scalar keys %partial) {
874 push @op, $OP_EML_NEW if !$seen{$need}++;
875 $r[2] = [ map { [ $_, @{$partial{$_}} ] } sort keys %partial ];
878 $r[0] = $need & NEED_BLOB ? \&uid_fetch_msg :
879 ($need & NEED_SMSG ? \&uid_fetch_smsg : \&uid_fetch_uid);
881 # r[1] = [ $key1, $cb1, $key2, $cb2, ... ]
882 use sort 'stable'; # makes output more consistent
883 $r[1] = [ map { ($_->[2], $_->[1]) } sort { $a->[0] <=> $b->[0] } @op ];
887 sub cmd_uid_fetch ($$$;@) {
888 my ($self, $tag, $range_csv, @want) = @_;
889 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
890 my ($cb, $ops, $partial) = fetch_compile(\@want);
891 return "$tag $cb\r\n" unless $ops;
893 $range_csv = 'bad' if $range_csv !~ $valid_range;
894 my $range_info = range_step($self, \$range_csv);
895 return "$tag $range_info\r\n" if !ref($range_info);
896 long_response($self, $cb, $tag, [], $range_info, $ops, $partial);
899 sub parse_date ($) { # 02-Oct-1993
900 my ($date_text) = @_;
901 my ($dd, $mon, $yyyy) = split(/-/, $_[0], 3);
902 defined($yyyy) or return;
903 my $mm = $MoY{$mon} // return;
904 $dd =~ /\A[0123]?[0-9]\z/ or return;
905 $yyyy =~ /\A[0-9]{4,}\z/ or return; # Y10K-compatible!
906 timegm(0, 0, 0, $dd, $mm, $yyyy);
909 sub uid_search_uid_range { # long_response
910 my ($self, $tag, $beg, $end, $sql) = @_;
911 my $uids = $self->{ibx}->over->uid_range($$beg, $end, $sql);
913 $$beg = $uids->[-1] + 1;
914 $self->msg_more(join(' ', '', @$uids));
916 $self->write(\"\r\n$tag OK Search done\r\n");
922 my ($q, $k, $d) = @_;
926 if ($k eq 'SENTON') {
927 my $end = $d + 86399; # no leap day...
928 my $da = strftime('%Y%m%d%H%M%S', gmtime($d));
929 my $db = strftime('%Y%m%d%H%M%S', gmtime($end));
930 $q->{xap} .= " dt:$da..$db";
931 $$sql .= " AND ds >= $d AND ds <= $end" if defined($sql);
932 } elsif ($k eq 'SENTBEFORE') {
933 $q->{xap} .= ' d:..'.strftime('%Y%m%d', gmtime($d));
934 $$sql .= " AND ds <= $d" if defined($sql);
935 } elsif ($k eq 'SENTSINCE') {
936 $q->{xap} .= ' d:'.strftime('%Y%m%d', gmtime($d)).'..';
937 $$sql .= " AND ds >= $d" if defined($sql);
939 # INTERNALDATE (Received)
940 } elsif ($k eq 'ON') {
941 my $end = $d + 86399; # no leap day...
942 $q->{xap} .= " ts:$d..$end";
943 $$sql .= " AND ts >= $d AND ts <= $end" if defined($sql);
944 } elsif ($k eq 'BEFORE') {
945 $q->{xap} .= " ts:..$d";
946 $$sql .= " AND ts <= $d" if defined($sql);
947 } elsif ($k eq 'SINCE') {
948 $q->{xap} .= " ts:$d..";
949 $$sql .= " AND ts >= $d" if defined($sql);
951 die "BUG: $k not recognized";
955 # IMAP to Xapian search key mapping
960 TEXT => '', # n.b. does not include all headers
963 # BCC => 'bcc:', # TODO
964 # KEYWORD # TODO ? dfpre,dfpost,...
968 my ($self, $rest) = @_;
969 if (uc($rest->[0]) eq 'CHARSET') {
971 defined(my $c = shift @$rest) or return 'BAD missing charset';
972 $c =~ /\A(?:UTF-8|US-ASCII)\z/ or return 'NO [BADCHARSET]';
975 my $sql = ''; # date conditions, {sql} deleted if Xapian is needed
976 my $q = { xap => '', sql => \$sql };
978 my $k = uc(shift @$rest);
980 next if $k =~ /\A(?:ALL|RECENT|UNSEEN|NEW)\z/;
981 next if $k eq 'AND'; # the default, until we support OR
982 if ($k =~ $valid_range) { # sequence numbers == UIDs
983 push @{$q->{uid}}, $k;
984 } elsif ($k eq 'UID') {
985 $k = shift(@$rest) // '';
986 $k =~ $valid_range or return 'BAD UID range';
987 push @{$q->{uid}}, $k;
988 } elsif ($k =~ /\A(?:SENT)?(?:SINCE|ON|BEFORE)\z/) {
989 my $d = parse_date(shift(@$rest) // '');
990 defined $d or return "BAD $k date format";
991 date_search($q, $k, $d);
992 } elsif ($k =~ /\A(?:SMALLER|LARGER)\z/) {
993 delete $q->{sql}; # can't use over.sqlite3
994 my $bytes = shift(@$rest) // '';
995 $bytes =~ /\A[0-9]+\z/ or return "BAD $k not a number";
996 $q->{xap} .= ' bytes:' . ($k eq 'SMALLER' ?
999 } elsif (defined(my $xk = $I2X{$k})) {
1000 delete $q->{sql}; # can't use over.sqlite3
1001 my $arg = shift @$rest;
1002 defined($arg) or return "BAD $k no arg";
1004 # Xapian can't handle [*"] in probabilistic terms
1006 $q->{xap} .= qq[ $xk:"$arg"];
1008 # TODO: parentheses, OR, NOT ...
1009 return "BAD $k not supported (yet?)";
1013 # favor using over.sqlite3 if possible, since Xapian is optional
1014 if (exists $q->{sql}) {
1016 delete($q->{sql}) if $sql eq '';
1017 } elsif (!$self->{ibx}->search) {
1018 return 'BAD Xapian not configured for mailbox';
1021 if (my $uid = $q->{uid}) {
1022 ((@$uid > 1) || $uid->[0] =~ /,/) and
1023 return 'BAD multiple ranges not supported, yet';
1024 ($q->{sql} // $q->{xap}) and
1025 return 'BAD ranges and queries do not mix, yet';
1026 $q->{uid} = join(',', @$uid); # TODO: multiple ranges
1031 sub cmd_uid_search ($$$;) {
1032 my ($self, $tag) = splice(@_, 0, 2);
1033 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1034 my $q = parse_query($self, \@_);
1035 return "$tag $q\r\n" if !ref($q);
1036 my $sql = delete $q->{sql};
1038 if (!scalar(keys %$q)) {
1039 $self->msg_more('* SEARCH');
1040 my $beg = $self->{uid_min} // 1;
1041 my $end = $ibx->mm->max;
1042 uid_clamp($self, \$beg, \$end);
1043 long_response($self, \&uid_search_uid_range,
1044 $tag, \$beg, $end, $sql);
1045 } elsif (my $uid = $q->{uid}) {
1046 if ($uid =~ /\A([0-9]+):([0-9]+|\*)\z/s) {
1047 my ($beg, $end) = ($1, $2);
1048 $end = $ibx->mm->max if $end eq '*';
1049 uid_clamp($self, \$beg, \$end);
1050 $self->msg_more('* SEARCH');
1051 long_response($self, \&uid_search_uid_range,
1052 $tag, \$beg, $end, $sql);
1053 } elsif ($uid =~ /\A[0-9]+\z/s) {
1054 $uid = $ibx->over->get_art($uid) ? " $uid" : '';
1055 "* SEARCH$uid\r\n$tag OK Search done\r\n";
1057 "$tag BAD Error\r\n";
1060 "$tag BAD Error\r\n";
1064 sub args_ok ($$) { # duplicated from PublicInbox::NNTP
1065 my ($cb, $argc) = @_;
1066 my $tot = prototype $cb;
1067 my ($nreq, undef) = split(';', $tot);
1068 $nreq = ($nreq =~ tr/$//) - 1;
1069 $tot = ($tot =~ tr/$//) - 1;
1070 ($argc <= $tot && $argc >= $nreq);
1073 # returns 1 if we can continue, 0 if not due to buffered writes or disconnect
1074 sub process_line ($$) {
1075 my ($self, $l) = @_;
1076 my ($tag, $req, @args) = parse_line('[ \t]+', 0, $l);
1077 pop(@args) if (@args && !defined($args[-1]));
1078 if (@args && uc($req) eq 'UID') {
1079 $req .= "_".(shift @args);
1082 if (my $cmd = $self->can('cmd_'.lc($req // ''))) {
1083 defined($self->{-idle_tag}) ?
1084 "$self->{-idle_tag} BAD expected DONE\r\n" :
1085 $cmd->($self, $tag, @args);
1086 } elsif (uc($tag // '') eq 'DONE' && !defined($req)) {
1087 cmd_done($self, $tag);
1088 } else { # this is weird
1089 auth_challenge_ok($self) //
1091 ' BAD Error in IMAP command '.
1093 ": Unknown command\r\n";
1097 if ($err && $self->{sock}) {
1099 err($self, 'error from: %s (%s)', $l, $err);
1101 $res = "$tag BAD program fault - command not performed\r\n";
1103 return 0 unless defined $res;
1109 # wbuf is unset or empty, here; {long} may add to it
1110 my ($fd, $cb, $t0, @args) = @{$self->{long_cb}};
1111 my $more = eval { $cb->($self, @args) };
1112 if ($@ || !$self->{sock}) { # something bad happened...
1113 delete $self->{long_cb};
1114 my $elapsed = now() - $t0;
1117 "%s during long response[$fd] - %0.6f",
1120 out($self, " deferred[$fd] aborted - %0.6f", $elapsed);
1122 } elsif ($more) { # $self->{wbuf}:
1123 $self->update_idle_time;
1125 # control passed to $more may be a GitAsyncCat object
1126 requeue_once($self) if !ref($more);
1127 } else { # all done!
1128 delete $self->{long_cb};
1129 my $elapsed = now() - $t0;
1130 my $fd = fileno($self->{sock});
1131 out($self, " deferred[$fd] done - %0.6f", $elapsed);
1132 my $wbuf = $self->{wbuf}; # do NOT autovivify
1134 $self->requeue unless $wbuf && @$wbuf;
1139 my ($self, $fmt, @args) = @_;
1140 printf { $self->{imapd}->{err} } $fmt."\n", @args;
1144 my ($self, $fmt, @args) = @_;
1145 printf { $self->{imapd}->{out} } $fmt."\n", @args;
1148 sub long_response ($$;@) {
1149 my ($self, $cb, @args) = @_; # cb returns true if more, false if done
1151 my $sock = $self->{sock} or return;
1152 # make sure we disable reading during a long response,
1153 # clients should not be sending us stuff and making us do more
1154 # work while we are stream a response to them
1155 $self->{long_cb} = [ fileno($sock), $cb, now(), @args ];
1156 long_step($self); # kick off!
1160 # callback used by PublicInbox::DS for any (e)poll (in/out/hup/err)
1164 return unless $self->flush_write && $self->{sock} && !$self->{long_cb};
1166 $self->update_idle_time;
1167 # only read more requests if we've drained the write buffer,
1168 # otherwise we can be buffering infinitely w/o backpressure
1170 my $rbuf = $self->{rbuf} // \(my $x = '');
1171 my $line = index($$rbuf, "\n");
1173 return $self->close if length($$rbuf) >= LINE_MAX;
1174 $self->do_read($rbuf, LINE_MAX, length($$rbuf)) or return;
1175 $line = index($$rbuf, "\n");
1177 $line = substr($$rbuf, 0, $line + 1, '');
1178 $line =~ s/\r?\n\z//s;
1179 return $self->close if $line =~ /[[:cntrl:]]/s;
1181 my $fd = fileno($self->{sock});
1182 my $r = eval { process_line($self, $line) };
1183 my $pending = $self->{wbuf} ? ' pending' : '';
1184 out($self, "[$fd] %s - %0.6f$pending - $r", $line, now() - $t0);
1186 return $self->close if $r < 0;
1187 $self->rbuf_idle($rbuf);
1188 $self->update_idle_time;
1190 # maybe there's more pipelined data, or we'll have
1191 # to register it for socket-readiness notifications
1192 $self->requeue unless $pending;
1195 sub compressed { undef }
1197 sub zflush {} # overridden by IMAPdeflate
1200 sub cmd_compress ($$$) {
1201 my ($self, $tag, $alg) = @_;
1202 return "$tag BAD DEFLATE only\r\n" if uc($alg) ne "DEFLATE";
1203 return "$tag BAD COMPRESS active\r\n" if $self->compressed;
1205 # CRIME made TLS compression obsolete
1206 # return "$tag NO [COMPRESSIONACTIVE]\r\n" if $self->tls_compressed;
1208 PublicInbox::IMAPdeflate->enable($self, $tag);
1213 sub cmd_starttls ($$) {
1214 my ($self, $tag) = @_;
1215 my $sock = $self->{sock} or return;
1216 if ($sock->can('stop_SSL') || $self->compressed) {
1217 return "$tag BAD TLS or compression already enabled\r\n";
1219 my $opt = $self->{imapd}->{accept_tls} or
1220 return "$tag BAD can not initiate TLS negotiation\r\n";
1221 $self->write(\"$tag OK begin TLS negotiation now\r\n");
1222 $self->{sock} = IO::Socket::SSL->start_SSL($sock, %$opt);
1223 $self->requeue if PublicInbox::DS::accept_tls_step($self);
1227 # for graceful shutdown in PublicInbox::Daemon:
1229 my ($self, $now) = @_;
1230 ($self->{rbuf} || $self->{wbuf} || $self->not_idle_long($now));
1235 if (my $ibx = delete $self->{ibx}) {
1236 stop_idle($self, $ibx);
1238 $self->SUPER::close; # PublicInbox::DS::close
1241 # we're read-only, so SELECT and EXAMINE do the same thing
1243 *cmd_select = \&cmd_examine;
1244 *cmd_fetch = \&cmd_uid_fetch;
1246 package PublicInbox::IMAP_preauth;
1247 our @ISA = qw(PublicInbox::IMAP);