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 logged_in 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);
32 for my $mod (qw(Email::Address::XS Mail::Address)) {
33 eval "require $mod" or next;
34 $Address = $mod and last;
36 die "neither Email::Address::XS nor Mail::Address loaded: $@" if !$Address;
38 sub LINE_MAX () { 512 } # does RFC 3501 have a limit like RFC 977?
40 # changing this will cause grief for clients which cache
41 sub UID_BLOCK () { 50_000 }
43 # these values area also used for sorting
44 sub NEED_SMSG () { 1 }
45 sub NEED_BLOB () { NEED_SMSG|2 }
46 sub NEED_EML () { NEED_BLOB|4 }
47 my $OP_EML_NEW = [ NEED_EML - 1, \&op_eml_new ];
50 'BODY[HEADER]' => [ NEED_EML, \&emit_rfc822_header ],
51 'BODY[TEXT]' => [ NEED_EML, \&emit_rfc822_text ],
52 'BODY[]' => [ NEED_BLOB, \&emit_rfc822 ],
53 'RFC822.HEADER' => [ NEED_EML, \&emit_rfc822_header ],
54 'RFC822.TEXT' => [ NEED_EML, \&emit_rfc822_text ],
55 'RFC822.SIZE' => [ NEED_BLOB, \&emit_rfc822_size ],
56 RFC822 => [ NEED_BLOB, \&emit_rfc822 ],
57 BODY => [ NEED_EML, \&emit_body ],
58 BODYSTRUCTURE => [ NEED_EML, \&emit_bodystructure ],
59 ENVELOPE => [ NEED_EML, \&emit_envelope ],
60 FLAGS => [ 0, \&emit_flags ],
61 INTERNALDATE => [ NEED_SMSG, \&emit_internaldate ],
63 my %FETCH_ATT = map { $_ => [ $_ ] } keys %FETCH_NEED;
65 # aliases (RFC 3501 section 6.4.5)
66 $FETCH_ATT{FAST} = [ qw(FLAGS INTERNALDATE RFC822.SIZE) ];
67 $FETCH_ATT{ALL} = [ @{$FETCH_ATT{FAST}}, 'ENVELOPE' ];
68 $FETCH_ATT{FULL} = [ @{$FETCH_ATT{ALL}}, 'BODY' ];
70 for my $att (keys %FETCH_ATT) {
71 my %h = map { $_ => $FETCH_NEED{$_} } @{$FETCH_ATT{$att}};
72 $FETCH_ATT{$att} = \%h;
76 my $valid_range = '[0-9]+|[0-9]+:[0-9]+|[0-9]+:\*';
77 $valid_range = qr/\A(?:$valid_range)(?:,(?:$valid_range))*\z/;
79 my @MoY = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
85 my $capa = capa($self);
86 $self->write(\"* OK [$capa] public-inbox-imapd ready\r\n");
90 my ($class, $sock, $imapd) = @_;
91 my $self = fields::new($class);
94 if ($sock->can('accept_SSL') && !$sock->accept_SSL) {
95 return CORE::close($sock) if $! != EAGAIN;
96 $ev = PublicInbox::TLS::epollbit();
97 $wbuf = [ \&PublicInbox::DS::accept_tls_step, \&greet ];
99 $self->SUPER::new($sock, $ev | EPOLLONESHOT);
100 $self->{imapd} = $imapd;
102 $self->{wbuf} = $wbuf;
106 $self->update_idle_time;
113 # dovecot advertises IDLE pre-login; perhaps because some clients
114 # depend on it, so we'll do the same
115 my $capa = 'CAPABILITY IMAP4rev1 IDLE';
116 if ($self->{logged_in}) {
117 $capa .= ' COMPRESS=DEFLATE';
119 if (!($self->{sock} // $self)->can('accept_SSL') &&
120 $self->{imapd}->{accept_tls}) {
121 $capa .= ' STARTTLS';
123 $capa .= ' AUTH=ANONYMOUS';
127 sub login_success ($$) {
128 my ($self, $tag) = @_;
129 $self->{logged_in} = 1;
130 my $capa = capa($self);
131 "$tag OK [$capa] Logged in\r\n";
134 sub auth_challenge_ok ($) {
136 my $tag = delete($self->{-login_tag}) or return;
137 login_success($self, $tag);
140 sub cmd_login ($$$$) {
141 my ($self, $tag) = @_; # ignore ($user, $password) = ($_[2], $_[3])
142 login_success($self, $tag);
146 my ($self, $tag) = @_;
147 delete $self->{uid_min};
148 delete $self->{ibx} ? "$tag OK Close done\r\n"
149 : "$tag BAD No mailbox\r\n";
152 sub cmd_logout ($$) {
153 my ($self, $tag) = @_;
154 delete @$self{qw(logged_in -idle_tag)};
155 $self->write(\"* BYE logging out\r\n$tag OK Logout done\r\n");
156 $self->shutdn; # PublicInbox::DS::shutdn
160 sub cmd_authenticate ($$$) {
161 my ($self, $tag) = @_; # $method = $_[2], should be "ANONYMOUS"
162 $self->{-login_tag} = $tag;
166 sub cmd_capability ($$) {
167 my ($self, $tag) = @_;
168 '* '.capa($self)."\r\n$tag OK Capability done\r\n";
171 sub cmd_noop ($$) { "$_[1] OK Noop done\r\n" }
173 # called by PublicInbox::InboxIdle
174 sub on_inbox_unlock {
175 my ($self, $ibx) = @_;
176 my $new = $ibx->mm->max;
177 my $uid_end = ($self->{uid_min} // 1) - 1 + UID_BLOCK;
178 defined(my $old = $self->{-idle_max}) or die 'BUG: -idle_max unset';
179 $new = $uid_end if $new > $uid_end;
181 $self->{-idle_max} = $new;
182 $self->msg_more("* $_ EXISTS\r\n") for (($old + 1)..($new - 1));
183 $self->write(\"* $new EXISTS\r\n");
184 } elsif ($new == $uid_end) { # max exceeded $uid_end
185 # continue idling w/o inotify
186 delete $self->{-idle_max};
187 my $sock = $self->{sock} or return;
188 $ibx->unsubscribe_unlock(fileno($sock));
192 # called every X minute(s) or so by PublicInbox::DS::later
198 for my $i (values %$old) {
199 next if ($i->{wbuf} || !exists($i->{-idle_tag}));
200 $i->update_idle_time or next;
201 $IDLERS->{fileno($i->{sock})} = $i;
202 $i->write(\"* OK Still here\r\n");
204 $idle_timer = scalar keys %$IDLERS ?
205 PublicInbox::DS::later(\&idle_tick_all) : undef;
209 my ($self, $tag) = @_;
210 # IDLE seems allowed by dovecot w/o a mailbox selected *shrug*
211 my $ibx = $self->{ibx} or return "$tag BAD no mailbox selected\r\n";
212 $self->{-idle_tag} = $tag;
213 my $max = $ibx->mm->max // 0;
214 my $uid_end = ($self->{uid_min} // 1) - 1 + UID_BLOCK;
215 my $sock = $self->{sock} or return;
216 my $fd = fileno($sock);
217 # only do inotify on most recent slice
218 if ($max < $uid_end) {
219 $ibx->subscribe_unlock($fd, $self);
220 $self->{imapd}->idler_start;
221 $self->{-idle_max} = $max;
223 $idle_timer //= PublicInbox::DS::later(\&idle_tick_all);
224 $IDLERS->{$fd} = $self;
230 my $sock = $self->{sock} or return;
231 my $fd = fileno($sock);
232 delete $IDLERS->{$fd};
233 $ibx->unsubscribe_unlock($fd);
237 my ($self, $tag) = @_; # $tag is "DONE" (case-insensitive)
238 defined(my $idle_tag = delete $self->{-idle_tag}) or
239 return "$tag BAD not idle\r\n";
240 my $ibx = $self->{ibx} or do {
241 warn "BUG: idle_tag set w/o inbox";
242 return "$tag BAD internal bug\r\n";
244 stop_idle($self, $ibx);
245 "$idle_tag OK Idle done\r\n";
248 sub ensure_ranges_exist ($$$) {
249 my ($imapd, $ibx, $max) = @_;
250 my $mailboxes = $imapd->{mailboxes};
251 my $mb_top = $ibx->{newsgroup};
253 for (my $i = int($max/UID_BLOCK); $i >= 0; --$i) {
254 my $sub_mailbox = "$mb_top.$i";
255 last if exists $mailboxes->{$sub_mailbox};
256 $mailboxes->{$sub_mailbox} = $ibx;
257 push @created, $sub_mailbox;
259 return unless @created;
260 my $l = $imapd->{inboxlist} or return;
261 push @$l, map { qq[* LIST (\\HasNoChildren) "." $_\r\n] } @created;
264 sub inbox_lookup ($$) {
265 my ($self, $mailbox) = @_;
266 my ($ibx, $exists, $uidnext);
267 if ($mailbox =~ /\A(.+)\.([0-9]+)\z/) {
268 # old mail: inbox.comp.foo.$uid_block_idx
269 my ($mb_top, $uid_min) = ($1, $2 * UID_BLOCK + 1);
271 $ibx = $self->{imapd}->{mailboxes}->{lc $mailbox} or return;
272 $exists = $ibx->mm->max // 0;
273 $self->{uid_min} = $uid_min;
274 ensure_ranges_exist($self->{imapd}, $ibx, $exists);
275 my $uid_end = $uid_min + UID_BLOCK - 1;
276 $exists = $uid_end if $exists > $uid_end;
277 $uidnext = $exists + 1;
278 } else { # check for dummy inboxes
279 $ibx = $self->{imapd}->{mailboxes}->{lc $mailbox} or return;
280 delete $self->{uid_min};
284 ($ibx, $exists, $uidnext);
287 sub cmd_examine ($$$) {
288 my ($self, $tag, $mailbox) = @_;
289 my ($ibx, $exists, $uidnext) = inbox_lookup($self, $mailbox);
290 return "$tag NO Mailbox doesn't exist: $mailbox\r\n" if !$ibx;
292 # XXX: do we need this? RFC 5162/7162
293 my $ret = $self->{ibx} ? "* OK [CLOSED] previous closed\r\n" : '';
299 * OK [PERMANENTFLAGS ()] Read-only mailbox\r
300 * OK [UNSEEN $exists]\r
301 * OK [UIDNEXT $uidnext]\r
302 * OK [UIDVALIDITY $ibx->{uidvalidity}]\r
303 $tag OK [READ-ONLY] EXAMINE/SELECT done\r
311 } elsif ($v =~ /[{"\r\n%*\\\[]/) { # literal string
312 '{' . length($v) . "}\r\n" . $v;
313 } else { # quoted string
318 sub addr_envelope ($$;$) {
319 my ($eml, $x, $y) = @_;
320 my $v = $eml->header_raw($x) //
321 ($y ? $eml->header_raw($y) : undef) // return 'NIL';
323 my @x = $Address->parse($v) or return 'NIL';
325 map { '(' . join(' ',
326 _esc($_->name), 'NIL',
327 _esc($_->user), _esc($_->host)
333 sub eml_envelope ($) {
336 _esc($eml->header_raw('Date')),
337 _esc($eml->header_raw('Subject')),
338 addr_envelope($eml, 'From'),
339 addr_envelope($eml, 'Sender', 'From'),
340 addr_envelope($eml, 'Reply-To', 'From'),
341 addr_envelope($eml, 'To'),
342 addr_envelope($eml, 'Cc'),
343 addr_envelope($eml, 'Bcc'),
344 _esc($eml->header_raw('In-Reply-To')),
345 _esc($eml->header_raw('Message-ID')),
351 if ($hash && scalar keys %$hash) {
352 $hash = [ %$hash ]; # flatten hash into 1-dimensional array
353 '(' . join(' ', map { _esc($_) } @$hash) . ')';
359 sub body_disposition ($) {
361 my $cd = $eml->header_raw('Content-Disposition') or return 'NIL';
362 $cd = parse_content_disposition($cd);
363 my $buf = '('._esc($cd->{type});
364 $buf .= ' ' . _esc_hash(delete $cd->{attributes});
368 sub body_leaf ($$;$) {
369 my ($eml, $structure, $hold) = @_;
371 $eml->{is_submsg} and # parent was a message/(rfc822|news|global)
372 $buf .= eml_envelope($eml). ' ';
374 $buf .= '('._esc($ct->{type}).' ';
375 $buf .= _esc($ct->{subtype});
376 $buf .= ' ' . _esc_hash(delete $ct->{attributes});
377 $buf .= ' ' . _esc($eml->header_raw('Content-ID'));
378 $buf .= ' ' . _esc($eml->header_raw('Content-Description'));
379 my $cte = $eml->header_raw('Content-Transfer-Encoding') // '7bit';
380 $buf .= ' ' . _esc($cte);
381 $buf .= ' ' . $eml->{imap_body_len};
382 $buf .= ' '.($eml->body_raw =~ tr/\n/\n/) if lc($ct->{type}) eq 'text';
384 # for message/(rfc822|global|news), $hold[0] should have envelope
385 $buf .= ' ' . (@$hold ? join('', @$hold) : 'NIL') if $hold;
388 $buf .= ' '._esc($eml->header_raw('Content-MD5'));
389 $buf .= ' '. body_disposition($eml);
390 $buf .= ' '._esc($eml->header_raw('Content-Language'));
391 $buf .= ' '._esc($eml->header_raw('Content-Location'));
396 sub body_parent ($$$) {
397 my ($eml, $structure, $hold) = @_;
399 my $type = lc($ct->{type});
400 if ($type eq 'multipart') {
402 $buf .= @$hold ? join('', @$hold) : 'NIL';
403 $buf .= ' '._esc($ct->{subtype});
405 $buf .= ' '._esc_hash(delete $ct->{attributes});
406 $buf .= ' '.body_disposition($eml);
407 $buf .= ' '._esc($eml->header_raw('Content-Language'));
408 $buf .= ' '._esc($eml->header_raw('Content-Location'));
412 } else { # message/(rfc822|global|news)
413 @$hold = (body_leaf($eml, $structure, $hold));
417 # this is gross, but we need to process the parent part AFTER
418 # the child parts are done
419 sub bodystructure_prep {
421 my ($eml, $depth) = @$p; # ignore idx
422 # set length here, as $eml->{bdy} gets deleted for message/rfc822
423 $eml->{imap_body_len} = length($eml->body_raw);
424 push @$q, $eml, $depth;
427 # for FETCH BODY and FETCH BODYSTRUCTURE
428 sub fetch_body ($;$) {
429 my ($eml, $structure) = @_;
431 $eml->each_part(\&bodystructure_prep, \@q, 0, 1);
435 my ($part, $depth) = splice(@q, -2);
436 my $is_mp_parent = $depth == ($cur_depth - 1);
440 body_parent($part, $structure, \@hold);
442 unshift @hold, body_leaf($part, $structure);
448 sub requeue_once ($) {
450 # COMPRESS users all share the same DEFLATE context.
451 # Flush it here to ensure clients don't see
455 # no recursion, schedule another call ASAP,
456 # but only after all pending writes are done.
458 my $new_size = push(@{$self->{wbuf}}, \&long_step);
460 # wbuf may be populated by $cb, no need to rearm if so:
461 $self->requeue if $new_size == 1;
464 sub uid_fetch_cb { # called by git->cat_async via git_async_cat
465 my ($bref, $oid, $type, $size, $fetch_m_arg) = @_;
466 my ($self, undef, $msgs, undef, $ops, $partial) = @$fetch_m_arg;
467 my $smsg = shift @$msgs or die 'BUG: no smsg';
468 if (!defined($oid)) {
469 # it's possible to have TOCTOU if an admin runs
470 # public-inbox-(edit|purge), just move onto the next message
471 return requeue_once($self);
473 $smsg->{blob} eq $oid or die "BUG: $smsg->{blob} != $oid";
475 $$bref =~ s/(?<!\r)\n/\r\n/sg; # make strict clients happy
477 # fixup old bug from import (pre-a0c07cba0e5d8b6a)
478 $$bref =~ s/\A[\r\n]*From [^\r\n]*\r\n//s;
479 $self->msg_more("* $smsg->{num} FETCH (UID $smsg->{num}");
481 for (my $i = 0; $i < @$ops;) {
482 my $k = $ops->[$i++];
483 $ops->[$i++]->($self, $k, $smsg, $bref, $eml);
485 partial_emit($self, $partial, $eml) if $partial;
486 $self->msg_more(")\r\n");
491 my ($self, $k, undef, $bref) = @_;
492 $self->msg_more(" $k {" . length($$bref)."}\r\n");
493 $self->msg_more($$bref);
496 # Mail::IMAPClient::message_string cares about this by default
497 # (->Ignoresizeerrors attribute)
498 sub emit_rfc822_size {
499 my ($self, $k, undef, $bref) = @_;
500 $self->msg_more(' RFC822.SIZE ' . length($$bref));
503 sub emit_internaldate {
504 my ($self, undef, $smsg) = @_;
505 $self->msg_more(' INTERNALDATE "'.$smsg->internaldate.'"');
508 sub emit_flags { $_[0]->msg_more(' FLAGS ()') }
511 my ($self, undef, undef, undef, $eml) = @_;
512 $self->msg_more(' ENVELOPE '.eml_envelope($eml));
515 sub emit_rfc822_header {
516 my ($self, $k, undef, undef, $eml) = @_;
517 $self->msg_more(" $k {".length(${$eml->{hdr}})."}\r\n");
518 $self->msg_more(${$eml->{hdr}});
521 # n.b. this is sorted to be after any emit_eml_new ops
522 sub emit_rfc822_text {
523 my ($self, $k, undef, $bref) = @_;
524 $self->msg_more(" $k {".length($$bref)."}\r\n");
525 $self->msg_more($$bref);
528 sub emit_bodystructure {
529 my ($self, undef, undef, undef, $eml) = @_;
530 $self->msg_more(' BODYSTRUCTURE '.fetch_body($eml, 1));
534 my ($self, undef, undef, undef, $eml) = @_;
535 $self->msg_more(' BODY '.fetch_body($eml));
538 # set $eml once ($_[4] == $eml, $_[3] == $bref)
539 sub op_eml_new { $_[4] = PublicInbox::Eml->new($_[3]) }
541 sub uid_clamp ($$$) {
542 my ($self, $beg, $end) = @_;
543 my $uid_min = $self->{uid_min} or return;
544 my $uid_end = $uid_min + UID_BLOCK - 1;
545 $$beg = $uid_min if $$beg < $uid_min;
546 $$end = $uid_end if $$end > $uid_end;
549 sub range_step ($$) {
550 my ($self, $range_csv) = @_;
551 my ($beg, $end, $range);
552 if ($$range_csv =~ s/\A([^,]+),//) {
555 $range = $$range_csv;
558 if ($range =~ /\A([0-9]+):([0-9]+)\z/) {
559 ($beg, $end) = ($1 + 0, $2 + 0);
560 } elsif ($range =~ /\A([0-9]+):\*\z/) {
562 $end = $self->{ibx}->mm->max // 0;
563 my $uid_end = ($self->{uid_min} // 1) - 1 + UID_BLOCK;
564 $end = $uid_end if $end > $uid_end;
565 $beg = $end if $beg > $end;
566 } elsif ($range =~ /\A[0-9]+\z/) {
567 $beg = $end = $range + 0;
570 return 'BAD fetch range';
572 uid_clamp($self, \$beg, \$end) if defined($range);
573 [ $beg, $end, $$range_csv ];
576 sub refill_range ($$$) {
577 my ($self, $msgs, $range_info) = @_;
578 my ($beg, $end, $range_csv) = @$range_info;
579 if (scalar(@$msgs = @{$self->{ibx}->over->query_xover($beg, $end)})) {
580 $range_info->[0] = $msgs->[-1]->{num} + 1;
583 return 'OK Fetch done' if !$range_csv;
584 my $next_range = range_step($self, \$range_csv);
585 return $next_range if !ref($next_range); # error
586 @$range_info = @$next_range;
587 undef; # keep looping
590 sub uid_fetch_msg { # long_response
591 my ($self, $tag, $msgs, $range_info) = @_; # \@ops, \@partial
592 while (!@$msgs) { # rare
593 if (my $end = refill_range($self, $msgs, $range_info)) {
594 $self->write(\"$tag $end\r\n");
598 git_async_cat($self->{ibx}->git, $msgs->[0]->{blob},
599 \&uid_fetch_cb, \@_);
602 sub uid_fetch_smsg { # long_response
603 my ($self, $tag, $msgs, $range_info, $ops) = @_;
604 while (!@$msgs) { # rare
605 if (my $end = refill_range($self, $msgs, $range_info)) {
606 $self->write(\"$tag $end\r\n");
610 for my $smsg (@$msgs) {
611 $self->msg_more("* $smsg->{num} FETCH (UID $smsg->{num}");
612 for (my $i = 0; $i < @$ops;) {
613 my $k = $ops->[$i++];
614 $ops->[$i++]->($self, $k, $smsg);
616 $self->msg_more(")\r\n");
622 sub uid_fetch_uid { # long_response
623 my ($self, $tag, $uids, $range_info, $ops) = @_;
624 while (!@$uids) { # rare
625 my ($beg, $end, $range_csv) = @$range_info;
626 if (scalar(@$uids = @{$self->{ibx}->over->
627 uid_range($beg, $end)})) {
628 $range_info->[0] = $uids->[-1] + 1;
629 } elsif (!$range_csv) {
630 $self->write(\"$tag OK Fetch done\r\n");
633 my $next_range = range_step($self, \$range_csv);
634 if (!ref($next_range)) { # error
635 $self->write(\"$tag $next_range\r\n");
638 @$range_info = @$next_range;
643 $self->msg_more("* $_ FETCH (UID $_");
644 for (my $i = 0; $i < @$ops;) {
645 my $k = $ops->[$i++];
646 $ops->[$i++]->($self, $k);
648 $self->msg_more(")\r\n");
654 sub cmd_status ($$$;@) {
655 my ($self, $tag, $mailbox, @items) = @_;
656 return "$tag BAD no items\r\n" if !scalar(@items);
657 ($items[0] !~ s/\A\(//s || $items[-1] !~ s/\)\z//s) and
658 return "$tag BAD invalid args\r\n";
659 my ($ibx, $exists, $uidnext) = inbox_lookup($self, $mailbox);
660 return "$tag NO Mailbox doesn't exist: $mailbox\r\n" if !$ibx;
662 for my $it (@items) {
665 if ($it =~ /\A(?:MESSAGES|UNSEEN|RECENT)\z/) {
667 } elsif ($it eq 'UIDNEXT') {
669 } elsif ($it eq 'UIDVALIDITY') {
670 push @it, $ibx->{uidvalidity};
672 return "$tag BAD invalid item\r\n";
675 return "$tag BAD no items\r\n" if !@it;
676 "* STATUS $mailbox (".join(' ', @it).")\r\n" .
677 "$tag OK Status done\r\n";
680 my %patmap = ('*' => '.*', '%' => '[^\.]*');
681 sub cmd_list ($$$$) {
682 my ($self, $tag, $refname, $wildcard) = @_;
683 my $l = $self->{imapd}->{inboxlist};
684 if ($refname eq '' && $wildcard eq '') {
685 # request for hierarchy delimiter
686 $l = [ qq[* LIST (\\Noselect) "." ""\r\n] ];
687 } elsif ($refname ne '' || $wildcard ne '*') {
688 $wildcard = lc $wildcard;
689 $wildcard =~ s!([^a-z0-9_])!$patmap{$1} // "\Q$1"!eg;
690 $l = [ grep(/ \Q$refname\E$wildcard\r\n\z/s, @$l) ];
692 \(join('', @$l, "$tag OK List done\r\n"));
695 sub cmd_lsub ($$$$) {
696 my (undef, $tag) = @_; # same args as cmd_list
697 "$tag OK Lsub done\r\n";
700 sub eml_index_offs_i { # PublicInbox::Eml::each_part callback
702 my ($eml, undef, $idx) = @$p;
703 if ($idx && lc($eml->ct->{type}) eq 'multipart') {
704 $eml->{imap_bdy} = $eml->{bdy} // \'';
706 $all->{$idx} = $eml; # $idx => Eml
709 # prepares an index for BODY[$SECTION_IDX] fetches
710 sub eml_body_idx ($$) {
711 my ($eml, $section_idx) = @_;
712 my $idx = $eml->{imap_all_parts} //= do {
714 $eml->each_part(\&eml_index_offs_i, $all, 0, 1);
715 # top-level of multipart, BODY[0] not allowed (nz-number)
719 $idx->{$section_idx};
722 # BODY[($SECTION_IDX)?(.$SECTION_NAME)?]<$offset.$bytes>
724 my ($eml, $section_idx, $section_name) = @_;
725 if (defined $section_idx) {
726 $eml = eml_body_idx($eml, $section_idx) or return;
728 if (defined $section_name) {
729 if ($section_name eq 'MIME') {
730 # RFC 3501 6.4.5 states:
731 # The MIME part specifier MUST be prefixed
732 # by one or more numeric part specifiers
733 return unless defined $section_idx;
734 return $eml->header_obj->as_string . "\r\n";
736 my $bdy = $eml->{bdy} // $eml->{imap_bdy} // \'';
737 $eml = PublicInbox::Eml->new($$bdy);
738 if ($section_name eq 'TEXT') {
739 return $eml->body_raw;
740 } elsif ($section_name eq 'HEADER') {
741 return $eml->header_obj->as_string . "\r\n";
743 die "BUG: bad section_name=$section_name";
746 ${$eml->{bdy} // $eml->{imap_bdy} // \''};
749 # similar to what's in PublicInbox::Eml::re_memo, but doesn't memoize
750 # to avoid OOM with malicious users
751 sub hdrs_regexp ($) {
753 my $names = join('|', map { "\Q$_" } split(/[ \t]+/, $hdrs));
754 qr/^(?:$names):[ \t]*[^\n]*\r?\n # 1st line
755 # continuation lines:
756 (?:[^:\n]*?[ \t]+[^\n]*\r?\n)*
760 # BODY[($SECTION_IDX.)?HEADER.FIELDS.NOT ($HDRS)]<$offset.$bytes>
761 sub partial_hdr_not {
762 my ($eml, $section_idx, $hdrs_re) = @_;
763 if (defined $section_idx) {
764 $eml = eml_body_idx($eml, $section_idx) or return;
766 my $str = $eml->header_obj->as_string;
767 $str =~ s/$hdrs_re//g;
771 # BODY[($SECTION_IDX.)?HEADER.FIELDS ($HDRS)]<$offset.$bytes>
772 sub partial_hdr_get {
773 my ($eml, $section_idx, $hdrs_re) = @_;
774 if (defined $section_idx) {
775 $eml = eml_body_idx($eml, $section_idx) or return;
777 my $str = $eml->header_obj->as_string;
778 join('', ($str =~ m/($hdrs_re)/g), "\r\n");
781 sub partial_prepare ($$$) {
782 my ($partial, $want, $att) = @_;
784 # recombine [ "BODY[1.HEADER.FIELDS", "(foo", "bar)]" ]
785 # back to: "BODY[1.HEADER.FIELDS (foo bar)]"
786 return unless $att =~ /\ABODY\[/s;
787 until (rindex($att, ']') >= 0) {
788 my $next = shift @$want or return;
789 $att .= ' ' . uc($next);
791 if ($att =~ /\ABODY\[([0-9]+(?:\.[0-9]+)*)? # 1 - section_idx
792 (?:\.(HEADER|MIME|TEXT))? # 2 - section_name
793 \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 3, 4
794 $partial->{$att} = [ \&partial_body, $1, $2, $3, $4 ];
795 } elsif ($att =~ /\ABODY\[(?:([0-9]+(?:\.[0-9]+)*)\.)? # 1 - section_idx
796 (?:HEADER\.FIELDS(\.NOT)?)\x20 # 2
797 \(([A-Z0-9\-\x20]+)\) # 3 - hdrs
798 \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 4 5
799 my $tmp = $partial->{$att} = [ $2 ? \&partial_hdr_not
802 $tmp->[2] = hdrs_regexp($3);
808 sub partial_emit ($$$) {
809 my ($self, $partial, $eml) = @_;
811 my ($k, $cb, @args) = @$_;
812 my ($offset, $len) = splice(@args, -2);
813 # $cb is partial_body|partial_hdr_get|partial_hdr_not
814 my $str = $cb->($eml, @args) // '';
815 if (defined $offset) {
817 $str = substr($str, $offset, $len);
818 $k =~ s/\.$len>\z/>/ or warn
819 "BUG: unable to remove `.$len>' from `$k'";
821 $str = substr($str, $offset);
827 $self->msg_more(" $k {$len}\r\n");
828 $self->msg_more($str);
832 sub fetch_compile ($) {
834 if ($want->[0] =~ s/\A\(//s) {
835 $want->[-1] =~ s/\)\z//s or return 'BAD no rparen';
837 my (%partial, %seen, @op);
839 while (defined(my $att = shift @$want)) {
841 next if $att eq 'UID'; # always returned
842 $att =~ s/\ABODY\.PEEK\[/BODY\[/; # we're read-only
843 my $x = $FETCH_ATT{$att};
845 while (my ($k, $fl_cb) = each %$x) {
847 $need |= $fl_cb->[0];
849 # insert a special op to convert $bref to $eml
850 # the first time we need it
851 if ($need == NEED_EML && !$seen{$need}++) {
852 push @op, $OP_EML_NEW;
854 # $fl_cb = [ flags, \&emit_foo ]
855 push @op, [ @$fl_cb , $k ];
857 } elsif (!partial_prepare(\%partial, $want, $att)) {
858 return "BAD param: $att";
863 # stabilize partial order for consistency and ease-of-debugging:
864 if (scalar keys %partial) {
866 push @op, $OP_EML_NEW if !$seen{$need}++;
867 $r[2] = [ map { [ $_, @{$partial{$_}} ] } sort keys %partial ];
870 $r[0] = $need & NEED_BLOB ? \&uid_fetch_msg :
871 ($need & NEED_SMSG ? \&uid_fetch_smsg : \&uid_fetch_uid);
873 # r[1] = [ $key1, $cb1, $key2, $cb2, ... ]
874 use sort 'stable'; # makes output more consistent
875 $r[1] = [ map { ($_->[2], $_->[1]) } sort { $a->[0] <=> $b->[0] } @op ];
879 sub cmd_uid_fetch ($$$;@) {
880 my ($self, $tag, $range_csv, @want) = @_;
881 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
882 my ($cb, $ops, $partial) = fetch_compile(\@want);
883 return "$tag $cb\r\n" unless $ops;
885 $range_csv = 'bad' if $range_csv !~ $valid_range;
886 my $range_info = range_step($self, \$range_csv);
887 return "$tag $range_info\r\n" if !ref($range_info);
888 long_response($self, $cb, $tag, [], $range_info, $ops, $partial);
891 sub parse_date ($) { # 02-Oct-1993
892 my ($date_text) = @_;
893 my ($dd, $mon, $yyyy) = split(/-/, $_[0], 3);
894 defined($yyyy) or return;
895 my $mm = $MoY{$mon} // return;
896 $dd =~ /\A[0123]?[0-9]\z/ or return;
897 $yyyy =~ /\A[0-9]{4,}\z/ or return; # Y10K-compatible!
898 timegm(0, 0, 0, $dd, $mm, $yyyy);
901 sub uid_search_uid_range { # long_response
902 my ($self, $tag, $beg, $end, $sql) = @_;
903 my $uids = $self->{ibx}->over->uid_range($$beg, $end, $sql);
905 $$beg = $uids->[-1] + 1;
906 $self->msg_more(join(' ', '', @$uids));
908 $self->write(\"\r\n$tag OK Search done\r\n");
914 my ($q, $k, $d) = @_;
918 if ($k eq 'SENTON') {
919 my $end = $d + 86399; # no leap day...
920 my $da = strftime('%Y%m%d%H%M%S', gmtime($d));
921 my $db = strftime('%Y%m%d%H%M%S', gmtime($end));
922 $q->{xap} .= " dt:$da..$db";
923 $$sql .= " AND ds >= $d AND ds <= $end" if defined($sql);
924 } elsif ($k eq 'SENTBEFORE') {
925 $q->{xap} .= ' d:..'.strftime('%Y%m%d', gmtime($d));
926 $$sql .= " AND ds <= $d" if defined($sql);
927 } elsif ($k eq 'SENTSINCE') {
928 $q->{xap} .= ' d:'.strftime('%Y%m%d', gmtime($d)).'..';
929 $$sql .= " AND ds >= $d" if defined($sql);
931 # INTERNALDATE (Received)
932 } elsif ($k eq 'ON') {
933 my $end = $d + 86399; # no leap day...
934 $q->{xap} .= " ts:$d..$end";
935 $$sql .= " AND ts >= $d AND ts <= $end" if defined($sql);
936 } elsif ($k eq 'BEFORE') {
937 $q->{xap} .= " ts:..$d";
938 $$sql .= " AND ts <= $d" if defined($sql);
939 } elsif ($k eq 'SINCE') {
940 $q->{xap} .= " ts:$d..";
941 $$sql .= " AND ts >= $d" if defined($sql);
943 die "BUG: $k not recognized";
947 # IMAP to Xapian search key mapping
952 TEXT => '', # n.b. does not include all headers
955 # BCC => 'bcc:', # TODO
956 # KEYWORD # TODO ? dfpre,dfpost,...
960 my ($self, $rest) = @_;
961 if (uc($rest->[0]) eq 'CHARSET') {
963 defined(my $c = shift @$rest) or return 'BAD missing charset';
964 $c =~ /\A(?:UTF-8|US-ASCII)\z/ or return 'NO [BADCHARSET]';
967 my $sql = ''; # date conditions, {sql} deleted if Xapian is needed
968 my $q = { xap => '', sql => \$sql };
970 my $k = uc(shift @$rest);
972 next if $k =~ /\A(?:ALL|RECENT|UNSEEN|NEW)\z/;
973 next if $k eq 'AND'; # the default, until we support OR
974 if ($k =~ $valid_range) { # sequence numbers == UIDs
975 push @{$q->{uid}}, $k;
976 } elsif ($k eq 'UID') {
977 $k = shift(@$rest) // '';
978 $k =~ $valid_range or return 'BAD UID range';
979 push @{$q->{uid}}, $k;
980 } elsif ($k =~ /\A(?:SENT)?(?:SINCE|ON|BEFORE)\z/) {
981 my $d = parse_date(shift(@$rest) // '');
982 defined $d or return "BAD $k date format";
983 date_search($q, $k, $d);
984 } elsif ($k =~ /\A(?:SMALLER|LARGER)\z/) {
985 delete $q->{sql}; # can't use over.sqlite3
986 my $bytes = shift(@$rest) // '';
987 $bytes =~ /\A[0-9]+\z/ or return "BAD $k not a number";
988 $q->{xap} .= ' bytes:' . ($k eq 'SMALLER' ?
991 } elsif (defined(my $xk = $I2X{$k})) {
992 delete $q->{sql}; # can't use over.sqlite3
993 my $arg = shift @$rest;
994 defined($arg) or return "BAD $k no arg";
996 # Xapian can't handle [*"] in probabilistic terms
998 $q->{xap} .= qq[ $xk:"$arg"];
1000 # TODO: parentheses, OR, NOT ...
1001 return "BAD $k not supported (yet?)";
1005 # favor using over.sqlite3 if possible, since Xapian is optional
1006 if (exists $q->{sql}) {
1008 delete($q->{sql}) if $sql eq '';
1009 } elsif (!$self->{ibx}->search) {
1010 return 'BAD Xapian not configured for mailbox';
1013 if (my $uid = $q->{uid}) {
1014 ((@$uid > 1) || $uid->[0] =~ /,/) and
1015 return 'BAD multiple ranges not supported, yet';
1016 ($q->{sql} // $q->{xap}) and
1017 return 'BAD ranges and queries do not mix, yet';
1018 $q->{uid} = join(',', @$uid); # TODO: multiple ranges
1023 sub cmd_uid_search ($$$;) {
1024 my ($self, $tag) = splice(@_, 0, 2);
1025 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1026 my $q = parse_query($self, \@_);
1027 return "$tag $q\r\n" if !ref($q);
1028 my $sql = delete $q->{sql};
1030 if (!scalar(keys %$q)) {
1031 $self->msg_more('* SEARCH');
1032 my $beg = $self->{uid_min} // 1;
1033 my $end = $ibx->mm->max;
1034 uid_clamp($self, \$beg, \$end);
1035 long_response($self, \&uid_search_uid_range,
1036 $tag, \$beg, $end, $sql);
1037 } elsif (my $uid = $q->{uid}) {
1038 if ($uid =~ /\A([0-9]+):([0-9]+|\*)\z/s) {
1039 my ($beg, $end) = ($1, $2);
1040 $end = $ibx->mm->max if $end eq '*';
1041 uid_clamp($self, \$beg, \$end);
1042 $self->msg_more('* SEARCH');
1043 long_response($self, \&uid_search_uid_range,
1044 $tag, \$beg, $end, $sql);
1045 } elsif ($uid =~ /\A[0-9]+\z/s) {
1046 $uid = $ibx->over->get_art($uid) ? " $uid" : '';
1047 "* SEARCH$uid\r\n$tag OK Search done\r\n";
1049 "$tag BAD Error\r\n";
1052 "$tag BAD Error\r\n";
1056 sub args_ok ($$) { # duplicated from PublicInbox::NNTP
1057 my ($cb, $argc) = @_;
1058 my $tot = prototype $cb;
1059 my ($nreq, undef) = split(';', $tot);
1060 $nreq = ($nreq =~ tr/$//) - 1;
1061 $tot = ($tot =~ tr/$//) - 1;
1062 ($argc <= $tot && $argc >= $nreq);
1065 # returns 1 if we can continue, 0 if not due to buffered writes or disconnect
1066 sub process_line ($$) {
1067 my ($self, $l) = @_;
1068 my ($tag, $req, @args) = parse_line('[ \t]+', 0, $l);
1069 pop(@args) if (@args && !defined($args[-1]));
1070 if (@args && uc($req) eq 'UID') {
1071 $req .= "_".(shift @args);
1074 if (my $cmd = $self->can('cmd_'.lc($req // ''))) {
1075 defined($self->{-idle_tag}) ?
1076 "$self->{-idle_tag} BAD expected DONE\r\n" :
1077 $cmd->($self, $tag, @args);
1078 } elsif (uc($tag // '') eq 'DONE' && !defined($req)) {
1079 cmd_done($self, $tag);
1080 } else { # this is weird
1081 auth_challenge_ok($self) //
1083 ' BAD Error in IMAP command '.
1085 ": Unknown command\r\n";
1089 if ($err && $self->{sock}) {
1091 err($self, 'error from: %s (%s)', $l, $err);
1093 $res = "$tag BAD program fault - command not performed\r\n";
1095 return 0 unless defined $res;
1101 # wbuf is unset or empty, here; {long} may add to it
1102 my ($fd, $cb, $t0, @args) = @{$self->{long_cb}};
1103 my $more = eval { $cb->($self, @args) };
1104 if ($@ || !$self->{sock}) { # something bad happened...
1105 delete $self->{long_cb};
1106 my $elapsed = now() - $t0;
1109 "%s during long response[$fd] - %0.6f",
1112 out($self, " deferred[$fd] aborted - %0.6f", $elapsed);
1114 } elsif ($more) { # $self->{wbuf}:
1115 $self->update_idle_time;
1117 # control passed to $more may be a GitAsyncCat object
1118 requeue_once($self) if !ref($more);
1119 } else { # all done!
1120 delete $self->{long_cb};
1121 my $elapsed = now() - $t0;
1122 my $fd = fileno($self->{sock});
1123 out($self, " deferred[$fd] done - %0.6f", $elapsed);
1124 my $wbuf = $self->{wbuf}; # do NOT autovivify
1126 $self->requeue unless $wbuf && @$wbuf;
1131 my ($self, $fmt, @args) = @_;
1132 printf { $self->{imapd}->{err} } $fmt."\n", @args;
1136 my ($self, $fmt, @args) = @_;
1137 printf { $self->{imapd}->{out} } $fmt."\n", @args;
1140 sub long_response ($$;@) {
1141 my ($self, $cb, @args) = @_; # cb returns true if more, false if done
1143 my $sock = $self->{sock} or return;
1144 # make sure we disable reading during a long response,
1145 # clients should not be sending us stuff and making us do more
1146 # work while we are stream a response to them
1147 $self->{long_cb} = [ fileno($sock), $cb, now(), @args ];
1148 long_step($self); # kick off!
1152 # callback used by PublicInbox::DS for any (e)poll (in/out/hup/err)
1156 return unless $self->flush_write && $self->{sock} && !$self->{long_cb};
1158 $self->update_idle_time;
1159 # only read more requests if we've drained the write buffer,
1160 # otherwise we can be buffering infinitely w/o backpressure
1162 my $rbuf = $self->{rbuf} // \(my $x = '');
1163 my $line = index($$rbuf, "\n");
1165 return $self->close if length($$rbuf) >= LINE_MAX;
1166 $self->do_read($rbuf, LINE_MAX, length($$rbuf)) or return;
1167 $line = index($$rbuf, "\n");
1169 $line = substr($$rbuf, 0, $line + 1, '');
1170 $line =~ s/\r?\n\z//s;
1171 return $self->close if $line =~ /[[:cntrl:]]/s;
1173 my $fd = fileno($self->{sock});
1174 my $r = eval { process_line($self, $line) };
1175 my $pending = $self->{wbuf} ? ' pending' : '';
1176 out($self, "[$fd] %s - %0.6f$pending - $r", $line, now() - $t0);
1178 return $self->close if $r < 0;
1179 $self->rbuf_idle($rbuf);
1180 $self->update_idle_time;
1182 # maybe there's more pipelined data, or we'll have
1183 # to register it for socket-readiness notifications
1184 $self->requeue unless $pending;
1187 sub compressed { undef }
1189 sub zflush {} # overridden by IMAPdeflate
1192 sub cmd_compress ($$$) {
1193 my ($self, $tag, $alg) = @_;
1194 return "$tag BAD DEFLATE only\r\n" if uc($alg) ne "DEFLATE";
1195 return "$tag BAD COMPRESS active\r\n" if $self->compressed;
1197 # CRIME made TLS compression obsolete
1198 # return "$tag NO [COMPRESSIONACTIVE]\r\n" if $self->tls_compressed;
1200 PublicInbox::IMAPdeflate->enable($self, $tag);
1205 sub cmd_starttls ($$) {
1206 my ($self, $tag) = @_;
1207 my $sock = $self->{sock} or return;
1208 if ($sock->can('stop_SSL') || $self->compressed) {
1209 return "$tag BAD TLS or compression already enabled\r\n";
1211 my $opt = $self->{imapd}->{accept_tls} or
1212 return "$tag BAD can not initiate TLS negotiation\r\n";
1213 $self->write(\"$tag OK begin TLS negotiation now\r\n");
1214 $self->{sock} = IO::Socket::SSL->start_SSL($sock, %$opt);
1215 $self->requeue if PublicInbox::DS::accept_tls_step($self);
1219 # for graceful shutdown in PublicInbox::Daemon:
1221 my ($self, $now) = @_;
1222 ($self->{rbuf} || $self->{wbuf} || $self->not_idle_long($now));
1227 if (my $ibx = delete $self->{ibx}) {
1228 stop_idle($self, $ibx);
1230 $self->SUPER::close; # PublicInbox::DS::close
1233 # we're read-only, so SELECT and EXAMINE do the same thing
1235 *cmd_select = \&cmd_examine;
1236 *cmd_fetch = \&cmd_uid_fetch;