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);
83 # RFC 3501 5.4. Autologout Timer needs to be >= 30min
84 $PublicInbox::DS::EXPTIME = 60 * 30;
88 my $capa = capa($self);
89 $self->write(\"* OK [$capa] public-inbox-imapd ready\r\n");
93 my ($class, $sock, $imapd) = @_;
94 my $self = fields::new($class);
97 if ($sock->can('accept_SSL') && !$sock->accept_SSL) {
98 return CORE::close($sock) if $! != EAGAIN;
99 $ev = PublicInbox::TLS::epollbit();
100 $wbuf = [ \&PublicInbox::DS::accept_tls_step, \&greet ];
102 $self->SUPER::new($sock, $ev | EPOLLONESHOT);
103 $self->{imapd} = $imapd;
105 $self->{wbuf} = $wbuf;
109 $self->update_idle_time;
116 # dovecot advertises IDLE pre-login; perhaps because some clients
117 # depend on it, so we'll do the same
118 my $capa = 'CAPABILITY IMAP4rev1 IDLE';
119 if ($self->{logged_in}) {
120 $capa .= ' COMPRESS=DEFLATE';
122 if (!($self->{sock} // $self)->can('accept_SSL') &&
123 $self->{imapd}->{accept_tls}) {
124 $capa .= ' STARTTLS';
126 $capa .= ' AUTH=ANONYMOUS';
130 sub login_success ($$) {
131 my ($self, $tag) = @_;
132 $self->{logged_in} = 1;
133 my $capa = capa($self);
134 "$tag OK [$capa] Logged in\r\n";
137 sub auth_challenge_ok ($) {
139 my $tag = delete($self->{-login_tag}) or return;
140 login_success($self, $tag);
143 sub cmd_login ($$$$) {
144 my ($self, $tag) = @_; # ignore ($user, $password) = ($_[2], $_[3])
145 login_success($self, $tag);
149 my ($self, $tag) = @_;
150 delete $self->{uid_min};
151 delete $self->{ibx} ? "$tag OK Close done\r\n"
152 : "$tag BAD No mailbox\r\n";
155 sub cmd_logout ($$) {
156 my ($self, $tag) = @_;
157 delete @$self{qw(logged_in -idle_tag)};
158 $self->write(\"* BYE logging out\r\n$tag OK Logout done\r\n");
159 $self->shutdn; # PublicInbox::DS::shutdn
163 sub cmd_authenticate ($$$) {
164 my ($self, $tag) = @_; # $method = $_[2], should be "ANONYMOUS"
165 $self->{-login_tag} = $tag;
169 sub cmd_capability ($$) {
170 my ($self, $tag) = @_;
171 '* '.capa($self)."\r\n$tag OK Capability done\r\n";
174 sub cmd_noop ($$) { "$_[1] OK Noop done\r\n" }
176 # called by PublicInbox::InboxIdle
177 sub on_inbox_unlock {
178 my ($self, $ibx) = @_;
179 my $new = $ibx->mm->max;
180 my $uid_end = ($self->{uid_min} // 1) - 1 + UID_BLOCK;
181 defined(my $old = $self->{-idle_max}) or die 'BUG: -idle_max unset';
182 $new = $uid_end if $new > $uid_end;
184 $self->{-idle_max} = $new;
185 $self->msg_more("* $_ EXISTS\r\n") for (($old + 1)..($new - 1));
186 $self->write(\"* $new EXISTS\r\n");
187 } elsif ($new == $uid_end) { # max exceeded $uid_end
188 # continue idling w/o inotify
189 delete $self->{-idle_max};
190 my $sock = $self->{sock} or return;
191 $ibx->unsubscribe_unlock(fileno($sock));
195 # called every X minute(s) or so by PublicInbox::DS::later
201 for my $i (values %$old) {
202 next if ($i->{wbuf} || !exists($i->{-idle_tag}));
203 $i->update_idle_time or next;
204 $IDLERS->{fileno($i->{sock})} = $i;
205 $i->write(\"* OK Still here\r\n");
207 $idle_timer = scalar keys %$IDLERS ?
208 PublicInbox::DS::later(\&idle_tick_all) : undef;
212 my ($self, $tag) = @_;
213 # IDLE seems allowed by dovecot w/o a mailbox selected *shrug*
214 my $ibx = $self->{ibx} or return "$tag BAD no mailbox selected\r\n";
215 $self->{-idle_tag} = $tag;
216 my $max = $ibx->mm->max // 0;
217 my $uid_end = ($self->{uid_min} // 1) - 1 + UID_BLOCK;
218 my $sock = $self->{sock} or return;
219 my $fd = fileno($sock);
220 # only do inotify on most recent slice
221 if ($max < $uid_end) {
222 $ibx->subscribe_unlock($fd, $self);
223 $self->{imapd}->idler_start;
224 $self->{-idle_max} = $max;
226 $idle_timer //= PublicInbox::DS::later(\&idle_tick_all);
227 $IDLERS->{$fd} = $self;
233 my $sock = $self->{sock} or return;
234 my $fd = fileno($sock);
235 delete $IDLERS->{$fd};
236 $ibx->unsubscribe_unlock($fd);
240 my ($self, $tag) = @_; # $tag is "DONE" (case-insensitive)
241 defined(my $idle_tag = delete $self->{-idle_tag}) or
242 return "$tag BAD not idle\r\n";
243 my $ibx = $self->{ibx} or do {
244 warn "BUG: idle_tag set w/o inbox";
245 return "$tag BAD internal bug\r\n";
247 stop_idle($self, $ibx);
248 "$idle_tag OK Idle done\r\n";
251 sub ensure_ranges_exist ($$$) {
252 my ($imapd, $ibx, $max) = @_;
253 my $mailboxes = $imapd->{mailboxes};
254 my $mb_top = $ibx->{newsgroup};
256 for (my $i = int($max/UID_BLOCK); $i >= 0; --$i) {
257 my $sub_mailbox = "$mb_top.$i";
258 last if exists $mailboxes->{$sub_mailbox};
259 $mailboxes->{$sub_mailbox} = $ibx;
260 push @created, $sub_mailbox;
262 return unless @created;
263 my $l = $imapd->{inboxlist} or return;
264 push @$l, map { qq[* LIST (\\HasNoChildren) "." $_\r\n] } @created;
267 sub inbox_lookup ($$) {
268 my ($self, $mailbox) = @_;
269 my ($ibx, $exists, $uidnext);
270 if ($mailbox =~ /\A(.+)\.([0-9]+)\z/) {
271 # old mail: inbox.comp.foo.$uid_block_idx
272 my ($mb_top, $uid_min) = ($1, $2 * UID_BLOCK + 1);
274 $ibx = $self->{imapd}->{mailboxes}->{lc $mailbox} or return;
275 $exists = $ibx->mm->max // 0;
276 $self->{uid_min} = $uid_min;
277 ensure_ranges_exist($self->{imapd}, $ibx, $exists);
278 my $uid_end = $uid_min + UID_BLOCK - 1;
279 $exists = $uid_end if $exists > $uid_end;
280 $uidnext = $exists + 1;
281 } else { # check for dummy inboxes
282 $ibx = $self->{imapd}->{mailboxes}->{lc $mailbox} or return;
283 delete $self->{uid_min};
287 ($ibx, $exists, $uidnext);
290 sub cmd_examine ($$$) {
291 my ($self, $tag, $mailbox) = @_;
292 my ($ibx, $exists, $uidnext) = inbox_lookup($self, $mailbox);
293 return "$tag NO Mailbox doesn't exist: $mailbox\r\n" if !$ibx;
295 # XXX: do we need this? RFC 5162/7162
296 my $ret = $self->{ibx} ? "* OK [CLOSED] previous closed\r\n" : '';
302 * OK [PERMANENTFLAGS ()] Read-only mailbox\r
303 * OK [UNSEEN $exists]\r
304 * OK [UIDNEXT $uidnext]\r
305 * OK [UIDVALIDITY $ibx->{uidvalidity}]\r
306 $tag OK [READ-ONLY] EXAMINE/SELECT done\r
314 } elsif ($v =~ /[{"\r\n%*\\\[]/) { # literal string
315 '{' . length($v) . "}\r\n" . $v;
316 } else { # quoted string
321 sub addr_envelope ($$;$) {
322 my ($eml, $x, $y) = @_;
323 my $v = $eml->header_raw($x) //
324 ($y ? $eml->header_raw($y) : undef) // return 'NIL';
326 my @x = $Address->parse($v) or return 'NIL';
328 map { '(' . join(' ',
329 _esc($_->name), 'NIL',
330 _esc($_->user), _esc($_->host)
336 sub eml_envelope ($) {
339 _esc($eml->header_raw('Date')),
340 _esc($eml->header_raw('Subject')),
341 addr_envelope($eml, 'From'),
342 addr_envelope($eml, 'Sender', 'From'),
343 addr_envelope($eml, 'Reply-To', 'From'),
344 addr_envelope($eml, 'To'),
345 addr_envelope($eml, 'Cc'),
346 addr_envelope($eml, 'Bcc'),
347 _esc($eml->header_raw('In-Reply-To')),
348 _esc($eml->header_raw('Message-ID')),
354 if ($hash && scalar keys %$hash) {
355 $hash = [ %$hash ]; # flatten hash into 1-dimensional array
356 '(' . join(' ', map { _esc($_) } @$hash) . ')';
362 sub body_disposition ($) {
364 my $cd = $eml->header_raw('Content-Disposition') or return 'NIL';
365 $cd = parse_content_disposition($cd);
366 my $buf = '('._esc($cd->{type});
367 $buf .= ' ' . _esc_hash(delete $cd->{attributes});
371 sub body_leaf ($$;$) {
372 my ($eml, $structure, $hold) = @_;
374 $eml->{is_submsg} and # parent was a message/(rfc822|news|global)
375 $buf .= eml_envelope($eml). ' ';
377 $buf .= '('._esc($ct->{type}).' ';
378 $buf .= _esc($ct->{subtype});
379 $buf .= ' ' . _esc_hash(delete $ct->{attributes});
380 $buf .= ' ' . _esc($eml->header_raw('Content-ID'));
381 $buf .= ' ' . _esc($eml->header_raw('Content-Description'));
382 my $cte = $eml->header_raw('Content-Transfer-Encoding') // '7bit';
383 $buf .= ' ' . _esc($cte);
384 $buf .= ' ' . $eml->{imap_body_len};
385 $buf .= ' '.($eml->body_raw =~ tr/\n/\n/) if lc($ct->{type}) eq 'text';
387 # for message/(rfc822|global|news), $hold[0] should have envelope
388 $buf .= ' ' . (@$hold ? join('', @$hold) : 'NIL') if $hold;
391 $buf .= ' '._esc($eml->header_raw('Content-MD5'));
392 $buf .= ' '. body_disposition($eml);
393 $buf .= ' '._esc($eml->header_raw('Content-Language'));
394 $buf .= ' '._esc($eml->header_raw('Content-Location'));
399 sub body_parent ($$$) {
400 my ($eml, $structure, $hold) = @_;
402 my $type = lc($ct->{type});
403 if ($type eq 'multipart') {
405 $buf .= @$hold ? join('', @$hold) : 'NIL';
406 $buf .= ' '._esc($ct->{subtype});
408 $buf .= ' '._esc_hash(delete $ct->{attributes});
409 $buf .= ' '.body_disposition($eml);
410 $buf .= ' '._esc($eml->header_raw('Content-Language'));
411 $buf .= ' '._esc($eml->header_raw('Content-Location'));
415 } else { # message/(rfc822|global|news)
416 @$hold = (body_leaf($eml, $structure, $hold));
420 # this is gross, but we need to process the parent part AFTER
421 # the child parts are done
422 sub bodystructure_prep {
424 my ($eml, $depth) = @$p; # ignore idx
425 # set length here, as $eml->{bdy} gets deleted for message/rfc822
426 $eml->{imap_body_len} = length($eml->body_raw);
427 push @$q, $eml, $depth;
430 # for FETCH BODY and FETCH BODYSTRUCTURE
431 sub fetch_body ($;$) {
432 my ($eml, $structure) = @_;
434 $eml->each_part(\&bodystructure_prep, \@q, 0, 1);
438 my ($part, $depth) = splice(@q, -2);
439 my $is_mp_parent = $depth == ($cur_depth - 1);
443 body_parent($part, $structure, \@hold);
445 unshift @hold, body_leaf($part, $structure);
451 sub requeue_once ($) {
453 # COMPRESS users all share the same DEFLATE context.
454 # Flush it here to ensure clients don't see
458 # no recursion, schedule another call ASAP,
459 # but only after all pending writes are done.
461 my $new_size = push(@{$self->{wbuf}}, \&long_step);
463 # wbuf may be populated by $cb, no need to rearm if so:
464 $self->requeue if $new_size == 1;
467 sub uid_fetch_cb { # called by git->cat_async via git_async_cat
468 my ($bref, $oid, $type, $size, $fetch_m_arg) = @_;
469 my ($self, undef, $msgs, undef, $ops, $partial) = @$fetch_m_arg;
470 my $smsg = shift @$msgs or die 'BUG: no smsg';
471 if (!defined($oid)) {
472 # it's possible to have TOCTOU if an admin runs
473 # public-inbox-(edit|purge), just move onto the next message
474 return requeue_once($self);
476 $smsg->{blob} eq $oid or die "BUG: $smsg->{blob} != $oid";
478 $$bref =~ s/(?<!\r)\n/\r\n/sg; # make strict clients happy
480 # fixup old bug from import (pre-a0c07cba0e5d8b6a)
481 $$bref =~ s/\A[\r\n]*From [^\r\n]*\r\n//s;
482 $self->msg_more("* $smsg->{num} FETCH (UID $smsg->{num}");
484 for (my $i = 0; $i < @$ops;) {
485 my $k = $ops->[$i++];
486 $ops->[$i++]->($self, $k, $smsg, $bref, $eml);
488 partial_emit($self, $partial, $eml) if $partial;
489 $self->msg_more(")\r\n");
494 my ($self, $k, undef, $bref) = @_;
495 $self->msg_more(" $k {" . length($$bref)."}\r\n");
496 $self->msg_more($$bref);
499 # Mail::IMAPClient::message_string cares about this by default
500 # (->Ignoresizeerrors attribute)
501 sub emit_rfc822_size {
502 my ($self, $k, undef, $bref) = @_;
503 $self->msg_more(' RFC822.SIZE ' . length($$bref));
506 sub emit_internaldate {
507 my ($self, undef, $smsg) = @_;
508 $self->msg_more(' INTERNALDATE "'.$smsg->internaldate.'"');
511 sub emit_flags { $_[0]->msg_more(' FLAGS ()') }
514 my ($self, undef, undef, undef, $eml) = @_;
515 $self->msg_more(' ENVELOPE '.eml_envelope($eml));
518 sub emit_rfc822_header {
519 my ($self, $k, undef, undef, $eml) = @_;
520 $self->msg_more(" $k {".length(${$eml->{hdr}})."}\r\n");
521 $self->msg_more(${$eml->{hdr}});
524 # n.b. this is sorted to be after any emit_eml_new ops
525 sub emit_rfc822_text {
526 my ($self, $k, undef, $bref) = @_;
527 $self->msg_more(" $k {".length($$bref)."}\r\n");
528 $self->msg_more($$bref);
531 sub emit_bodystructure {
532 my ($self, undef, undef, undef, $eml) = @_;
533 $self->msg_more(' BODYSTRUCTURE '.fetch_body($eml, 1));
537 my ($self, undef, undef, undef, $eml) = @_;
538 $self->msg_more(' BODY '.fetch_body($eml));
541 # set $eml once ($_[4] == $eml, $_[3] == $bref)
542 sub op_eml_new { $_[4] = PublicInbox::Eml->new($_[3]) }
544 sub uid_clamp ($$$) {
545 my ($self, $beg, $end) = @_;
546 my $uid_min = $self->{uid_min} or return;
547 my $uid_end = $uid_min + UID_BLOCK - 1;
548 $$beg = $uid_min if $$beg < $uid_min;
549 $$end = $uid_end if $$end > $uid_end;
552 sub range_step ($$) {
553 my ($self, $range_csv) = @_;
554 my ($beg, $end, $range);
555 if ($$range_csv =~ s/\A([^,]+),//) {
558 $range = $$range_csv;
561 if ($range =~ /\A([0-9]+):([0-9]+)\z/) {
562 ($beg, $end) = ($1 + 0, $2 + 0);
563 } elsif ($range =~ /\A([0-9]+):\*\z/) {
565 $end = $self->{ibx}->mm->max // 0;
566 my $uid_end = ($self->{uid_min} // 1) - 1 + UID_BLOCK;
567 $end = $uid_end if $end > $uid_end;
568 $beg = $end if $beg > $end;
569 } elsif ($range =~ /\A[0-9]+\z/) {
570 $beg = $end = $range + 0;
573 return 'BAD fetch range';
575 uid_clamp($self, \$beg, \$end) if defined($range);
576 [ $beg, $end, $$range_csv ];
579 sub refill_range ($$$) {
580 my ($self, $msgs, $range_info) = @_;
581 my ($beg, $end, $range_csv) = @$range_info;
582 if (scalar(@$msgs = @{$self->{ibx}->over->query_xover($beg, $end)})) {
583 $range_info->[0] = $msgs->[-1]->{num} + 1;
586 return 'OK Fetch done' if !$range_csv;
587 my $next_range = range_step($self, \$range_csv);
588 return $next_range if !ref($next_range); # error
589 @$range_info = @$next_range;
590 undef; # keep looping
593 sub uid_fetch_msg { # long_response
594 my ($self, $tag, $msgs, $range_info) = @_; # \@ops, \@partial
595 while (!@$msgs) { # rare
596 if (my $end = refill_range($self, $msgs, $range_info)) {
597 $self->write(\"$tag $end\r\n");
601 git_async_cat($self->{ibx}->git, $msgs->[0]->{blob},
602 \&uid_fetch_cb, \@_);
605 sub uid_fetch_smsg { # long_response
606 my ($self, $tag, $msgs, $range_info, $ops) = @_;
607 while (!@$msgs) { # rare
608 if (my $end = refill_range($self, $msgs, $range_info)) {
609 $self->write(\"$tag $end\r\n");
613 for my $smsg (@$msgs) {
614 $self->msg_more("* $smsg->{num} FETCH (UID $smsg->{num}");
615 for (my $i = 0; $i < @$ops;) {
616 my $k = $ops->[$i++];
617 $ops->[$i++]->($self, $k, $smsg);
619 $self->msg_more(")\r\n");
625 sub uid_fetch_uid { # long_response
626 my ($self, $tag, $uids, $range_info, $ops) = @_;
627 while (!@$uids) { # rare
628 my ($beg, $end, $range_csv) = @$range_info;
629 if (scalar(@$uids = @{$self->{ibx}->over->
630 uid_range($beg, $end)})) {
631 $range_info->[0] = $uids->[-1] + 1;
632 } elsif (!$range_csv) {
633 $self->write(\"$tag OK Fetch done\r\n");
636 my $next_range = range_step($self, \$range_csv);
637 if (!ref($next_range)) { # error
638 $self->write(\"$tag $next_range\r\n");
641 @$range_info = @$next_range;
646 $self->msg_more("* $_ FETCH (UID $_");
647 for (my $i = 0; $i < @$ops;) {
648 my $k = $ops->[$i++];
649 $ops->[$i++]->($self, $k);
651 $self->msg_more(")\r\n");
657 sub cmd_status ($$$;@) {
658 my ($self, $tag, $mailbox, @items) = @_;
659 return "$tag BAD no items\r\n" if !scalar(@items);
660 ($items[0] !~ s/\A\(//s || $items[-1] !~ s/\)\z//s) and
661 return "$tag BAD invalid args\r\n";
662 my ($ibx, $exists, $uidnext) = inbox_lookup($self, $mailbox);
663 return "$tag NO Mailbox doesn't exist: $mailbox\r\n" if !$ibx;
665 for my $it (@items) {
668 if ($it =~ /\A(?:MESSAGES|UNSEEN|RECENT)\z/) {
670 } elsif ($it eq 'UIDNEXT') {
672 } elsif ($it eq 'UIDVALIDITY') {
673 push @it, $ibx->{uidvalidity};
675 return "$tag BAD invalid item\r\n";
678 return "$tag BAD no items\r\n" if !@it;
679 "* STATUS $mailbox (".join(' ', @it).")\r\n" .
680 "$tag OK Status done\r\n";
683 my %patmap = ('*' => '.*', '%' => '[^\.]*');
684 sub cmd_list ($$$$) {
685 my ($self, $tag, $refname, $wildcard) = @_;
686 my $l = $self->{imapd}->{inboxlist};
687 if ($refname eq '' && $wildcard eq '') {
688 # request for hierarchy delimiter
689 $l = [ qq[* LIST (\\Noselect) "." ""\r\n] ];
690 } elsif ($refname ne '' || $wildcard ne '*') {
691 $wildcard = lc $wildcard;
692 $wildcard =~ s!([^a-z0-9_])!$patmap{$1} // "\Q$1"!eg;
693 $l = [ grep(/ \Q$refname\E$wildcard\r\n\z/s, @$l) ];
695 \(join('', @$l, "$tag OK List done\r\n"));
698 sub cmd_lsub ($$$$) {
699 my (undef, $tag) = @_; # same args as cmd_list
700 "$tag OK Lsub done\r\n";
703 sub eml_index_offs_i { # PublicInbox::Eml::each_part callback
705 my ($eml, undef, $idx) = @$p;
706 if ($idx && lc($eml->ct->{type}) eq 'multipart') {
707 $eml->{imap_bdy} = $eml->{bdy} // \'';
709 $all->{$idx} = $eml; # $idx => Eml
712 # prepares an index for BODY[$SECTION_IDX] fetches
713 sub eml_body_idx ($$) {
714 my ($eml, $section_idx) = @_;
715 my $idx = $eml->{imap_all_parts} //= do {
717 $eml->each_part(\&eml_index_offs_i, $all, 0, 1);
718 # top-level of multipart, BODY[0] not allowed (nz-number)
722 $idx->{$section_idx};
725 # BODY[($SECTION_IDX)?(.$SECTION_NAME)?]<$offset.$bytes>
727 my ($eml, $section_idx, $section_name) = @_;
728 if (defined $section_idx) {
729 $eml = eml_body_idx($eml, $section_idx) or return;
731 if (defined $section_name) {
732 if ($section_name eq 'MIME') {
733 # RFC 3501 6.4.5 states:
734 # The MIME part specifier MUST be prefixed
735 # by one or more numeric part specifiers
736 return unless defined $section_idx;
737 return $eml->header_obj->as_string . "\r\n";
739 my $bdy = $eml->{bdy} // $eml->{imap_bdy} // \'';
740 $eml = PublicInbox::Eml->new($$bdy);
741 if ($section_name eq 'TEXT') {
742 return $eml->body_raw;
743 } elsif ($section_name eq 'HEADER') {
744 return $eml->header_obj->as_string . "\r\n";
746 die "BUG: bad section_name=$section_name";
749 ${$eml->{bdy} // $eml->{imap_bdy} // \''};
752 # similar to what's in PublicInbox::Eml::re_memo, but doesn't memoize
753 # to avoid OOM with malicious users
754 sub hdrs_regexp ($) {
756 my $names = join('|', map { "\Q$_" } split(/[ \t]+/, $hdrs));
757 qr/^(?:$names):[ \t]*[^\n]*\r?\n # 1st line
758 # continuation lines:
759 (?:[^:\n]*?[ \t]+[^\n]*\r?\n)*
763 # BODY[($SECTION_IDX.)?HEADER.FIELDS.NOT ($HDRS)]<$offset.$bytes>
764 sub partial_hdr_not {
765 my ($eml, $section_idx, $hdrs_re) = @_;
766 if (defined $section_idx) {
767 $eml = eml_body_idx($eml, $section_idx) or return;
769 my $str = $eml->header_obj->as_string;
770 $str =~ s/$hdrs_re//g;
774 # BODY[($SECTION_IDX.)?HEADER.FIELDS ($HDRS)]<$offset.$bytes>
775 sub partial_hdr_get {
776 my ($eml, $section_idx, $hdrs_re) = @_;
777 if (defined $section_idx) {
778 $eml = eml_body_idx($eml, $section_idx) or return;
780 my $str = $eml->header_obj->as_string;
781 join('', ($str =~ m/($hdrs_re)/g), "\r\n");
784 sub partial_prepare ($$$) {
785 my ($partial, $want, $att) = @_;
787 # recombine [ "BODY[1.HEADER.FIELDS", "(foo", "bar)]" ]
788 # back to: "BODY[1.HEADER.FIELDS (foo bar)]"
789 return unless $att =~ /\ABODY\[/s;
790 until (rindex($att, ']') >= 0) {
791 my $next = shift @$want or return;
792 $att .= ' ' . uc($next);
794 if ($att =~ /\ABODY\[([0-9]+(?:\.[0-9]+)*)? # 1 - section_idx
795 (?:\.(HEADER|MIME|TEXT))? # 2 - section_name
796 \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 3, 4
797 $partial->{$att} = [ \&partial_body, $1, $2, $3, $4 ];
798 } elsif ($att =~ /\ABODY\[(?:([0-9]+(?:\.[0-9]+)*)\.)? # 1 - section_idx
799 (?:HEADER\.FIELDS(\.NOT)?)\x20 # 2
800 \(([A-Z0-9\-\x20]+)\) # 3 - hdrs
801 \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 4 5
802 my $tmp = $partial->{$att} = [ $2 ? \&partial_hdr_not
805 $tmp->[2] = hdrs_regexp($3);
811 sub partial_emit ($$$) {
812 my ($self, $partial, $eml) = @_;
814 my ($k, $cb, @args) = @$_;
815 my ($offset, $len) = splice(@args, -2);
816 # $cb is partial_body|partial_hdr_get|partial_hdr_not
817 my $str = $cb->($eml, @args) // '';
818 if (defined $offset) {
820 $str = substr($str, $offset, $len);
821 $k =~ s/\.$len>\z/>/ or warn
822 "BUG: unable to remove `.$len>' from `$k'";
824 $str = substr($str, $offset);
830 $self->msg_more(" $k {$len}\r\n");
831 $self->msg_more($str);
835 sub fetch_compile ($) {
837 if ($want->[0] =~ s/\A\(//s) {
838 $want->[-1] =~ s/\)\z//s or return 'BAD no rparen';
840 my (%partial, %seen, @op);
842 while (defined(my $att = shift @$want)) {
844 next if $att eq 'UID'; # always returned
845 $att =~ s/\ABODY\.PEEK\[/BODY\[/; # we're read-only
846 my $x = $FETCH_ATT{$att};
848 while (my ($k, $fl_cb) = each %$x) {
850 $need |= $fl_cb->[0];
852 # insert a special op to convert $bref to $eml
853 # the first time we need it
854 if ($need == NEED_EML && !$seen{$need}++) {
855 push @op, $OP_EML_NEW;
857 # $fl_cb = [ flags, \&emit_foo ]
858 push @op, [ @$fl_cb , $k ];
860 } elsif (!partial_prepare(\%partial, $want, $att)) {
861 return "BAD param: $att";
866 # stabilize partial order for consistency and ease-of-debugging:
867 if (scalar keys %partial) {
869 push @op, $OP_EML_NEW if !$seen{$need}++;
870 $r[2] = [ map { [ $_, @{$partial{$_}} ] } sort keys %partial ];
873 $r[0] = $need & NEED_BLOB ? \&uid_fetch_msg :
874 ($need & NEED_SMSG ? \&uid_fetch_smsg : \&uid_fetch_uid);
876 # r[1] = [ $key1, $cb1, $key2, $cb2, ... ]
877 use sort 'stable'; # makes output more consistent
878 $r[1] = [ map { ($_->[2], $_->[1]) } sort { $a->[0] <=> $b->[0] } @op ];
882 sub cmd_uid_fetch ($$$;@) {
883 my ($self, $tag, $range_csv, @want) = @_;
884 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
885 my ($cb, $ops, $partial) = fetch_compile(\@want);
886 return "$tag $cb\r\n" unless $ops;
888 $range_csv = 'bad' if $range_csv !~ $valid_range;
889 my $range_info = range_step($self, \$range_csv);
890 return "$tag $range_info\r\n" if !ref($range_info);
891 long_response($self, $cb, $tag, [], $range_info, $ops, $partial);
894 sub parse_date ($) { # 02-Oct-1993
895 my ($date_text) = @_;
896 my ($dd, $mon, $yyyy) = split(/-/, $_[0], 3);
897 defined($yyyy) or return;
898 my $mm = $MoY{$mon} // return;
899 $dd =~ /\A[0123]?[0-9]\z/ or return;
900 $yyyy =~ /\A[0-9]{4,}\z/ or return; # Y10K-compatible!
901 timegm(0, 0, 0, $dd, $mm, $yyyy);
904 sub uid_search_uid_range { # long_response
905 my ($self, $tag, $beg, $end, $sql) = @_;
906 my $uids = $self->{ibx}->over->uid_range($$beg, $end, $sql);
908 $$beg = $uids->[-1] + 1;
909 $self->msg_more(join(' ', '', @$uids));
911 $self->write(\"\r\n$tag OK Search done\r\n");
917 my ($q, $k, $d) = @_;
921 if ($k eq 'SENTON') {
922 my $end = $d + 86399; # no leap day...
923 my $da = strftime('%Y%m%d%H%M%S', gmtime($d));
924 my $db = strftime('%Y%m%d%H%M%S', gmtime($end));
925 $q->{xap} .= " dt:$da..$db";
926 $$sql .= " AND ds >= $d AND ds <= $end" if defined($sql);
927 } elsif ($k eq 'SENTBEFORE') {
928 $q->{xap} .= ' d:..'.strftime('%Y%m%d', gmtime($d));
929 $$sql .= " AND ds <= $d" if defined($sql);
930 } elsif ($k eq 'SENTSINCE') {
931 $q->{xap} .= ' d:'.strftime('%Y%m%d', gmtime($d)).'..';
932 $$sql .= " AND ds >= $d" if defined($sql);
934 # INTERNALDATE (Received)
935 } elsif ($k eq 'ON') {
936 my $end = $d + 86399; # no leap day...
937 $q->{xap} .= " ts:$d..$end";
938 $$sql .= " AND ts >= $d AND ts <= $end" if defined($sql);
939 } elsif ($k eq 'BEFORE') {
940 $q->{xap} .= " ts:..$d";
941 $$sql .= " AND ts <= $d" if defined($sql);
942 } elsif ($k eq 'SINCE') {
943 $q->{xap} .= " ts:$d..";
944 $$sql .= " AND ts >= $d" if defined($sql);
946 die "BUG: $k not recognized";
950 # IMAP to Xapian search key mapping
955 TEXT => '', # n.b. does not include all headers
958 # BCC => 'bcc:', # TODO
959 # KEYWORD # TODO ? dfpre,dfpost,...
963 my ($self, $rest) = @_;
964 if (uc($rest->[0]) eq 'CHARSET') {
966 defined(my $c = shift @$rest) or return 'BAD missing charset';
967 $c =~ /\A(?:UTF-8|US-ASCII)\z/ or return 'NO [BADCHARSET]';
970 my $sql = ''; # date conditions, {sql} deleted if Xapian is needed
971 my $q = { xap => '', sql => \$sql };
973 my $k = uc(shift @$rest);
975 next if $k =~ /\A(?:ALL|RECENT|UNSEEN|NEW)\z/;
976 next if $k eq 'AND'; # the default, until we support OR
977 if ($k =~ $valid_range) { # sequence numbers == UIDs
978 push @{$q->{uid}}, $k;
979 } elsif ($k eq 'UID') {
980 $k = shift(@$rest) // '';
981 $k =~ $valid_range or return 'BAD UID range';
982 push @{$q->{uid}}, $k;
983 } elsif ($k =~ /\A(?:SENT)?(?:SINCE|ON|BEFORE)\z/) {
984 my $d = parse_date(shift(@$rest) // '');
985 defined $d or return "BAD $k date format";
986 date_search($q, $k, $d);
987 } elsif ($k =~ /\A(?:SMALLER|LARGER)\z/) {
988 delete $q->{sql}; # can't use over.sqlite3
989 my $bytes = shift(@$rest) // '';
990 $bytes =~ /\A[0-9]+\z/ or return "BAD $k not a number";
991 $q->{xap} .= ' bytes:' . ($k eq 'SMALLER' ?
994 } elsif (defined(my $xk = $I2X{$k})) {
995 delete $q->{sql}; # can't use over.sqlite3
996 my $arg = shift @$rest;
997 defined($arg) or return "BAD $k no arg";
999 # Xapian can't handle [*"] in probabilistic terms
1001 $q->{xap} .= qq[ $xk:"$arg"];
1003 # TODO: parentheses, OR, NOT ...
1004 return "BAD $k not supported (yet?)";
1008 # favor using over.sqlite3 if possible, since Xapian is optional
1009 if (exists $q->{sql}) {
1011 delete($q->{sql}) if $sql eq '';
1012 } elsif (!$self->{ibx}->search) {
1013 return 'BAD Xapian not configured for mailbox';
1016 if (my $uid = $q->{uid}) {
1017 ((@$uid > 1) || $uid->[0] =~ /,/) and
1018 return 'BAD multiple ranges not supported, yet';
1019 ($q->{sql} // $q->{xap}) and
1020 return 'BAD ranges and queries do not mix, yet';
1021 $q->{uid} = join(',', @$uid); # TODO: multiple ranges
1026 sub cmd_uid_search ($$$;) {
1027 my ($self, $tag) = splice(@_, 0, 2);
1028 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1029 my $q = parse_query($self, \@_);
1030 return "$tag $q\r\n" if !ref($q);
1031 my $sql = delete $q->{sql};
1033 if (!scalar(keys %$q)) {
1034 $self->msg_more('* SEARCH');
1035 my $beg = $self->{uid_min} // 1;
1036 my $end = $ibx->mm->max;
1037 uid_clamp($self, \$beg, \$end);
1038 long_response($self, \&uid_search_uid_range,
1039 $tag, \$beg, $end, $sql);
1040 } elsif (my $uid = $q->{uid}) {
1041 if ($uid =~ /\A([0-9]+):([0-9]+|\*)\z/s) {
1042 my ($beg, $end) = ($1, $2);
1043 $end = $ibx->mm->max if $end eq '*';
1044 uid_clamp($self, \$beg, \$end);
1045 $self->msg_more('* SEARCH');
1046 long_response($self, \&uid_search_uid_range,
1047 $tag, \$beg, $end, $sql);
1048 } elsif ($uid =~ /\A[0-9]+\z/s) {
1049 $uid = $ibx->over->get_art($uid) ? " $uid" : '';
1050 "* SEARCH$uid\r\n$tag OK Search done\r\n";
1052 "$tag BAD Error\r\n";
1055 "$tag BAD Error\r\n";
1059 sub args_ok ($$) { # duplicated from PublicInbox::NNTP
1060 my ($cb, $argc) = @_;
1061 my $tot = prototype $cb;
1062 my ($nreq, undef) = split(';', $tot);
1063 $nreq = ($nreq =~ tr/$//) - 1;
1064 $tot = ($tot =~ tr/$//) - 1;
1065 ($argc <= $tot && $argc >= $nreq);
1068 # returns 1 if we can continue, 0 if not due to buffered writes or disconnect
1069 sub process_line ($$) {
1070 my ($self, $l) = @_;
1071 my ($tag, $req, @args) = parse_line('[ \t]+', 0, $l);
1072 pop(@args) if (@args && !defined($args[-1]));
1073 if (@args && uc($req) eq 'UID') {
1074 $req .= "_".(shift @args);
1077 if (my $cmd = $self->can('cmd_'.lc($req // ''))) {
1078 defined($self->{-idle_tag}) ?
1079 "$self->{-idle_tag} BAD expected DONE\r\n" :
1080 $cmd->($self, $tag, @args);
1081 } elsif (uc($tag // '') eq 'DONE' && !defined($req)) {
1082 cmd_done($self, $tag);
1083 } else { # this is weird
1084 auth_challenge_ok($self) //
1086 ' BAD Error in IMAP command '.
1088 ": Unknown command\r\n";
1092 if ($err && $self->{sock}) {
1094 err($self, 'error from: %s (%s)', $l, $err);
1096 $res = "$tag BAD program fault - command not performed\r\n";
1098 return 0 unless defined $res;
1104 # wbuf is unset or empty, here; {long} may add to it
1105 my ($fd, $cb, $t0, @args) = @{$self->{long_cb}};
1106 my $more = eval { $cb->($self, @args) };
1107 if ($@ || !$self->{sock}) { # something bad happened...
1108 delete $self->{long_cb};
1109 my $elapsed = now() - $t0;
1112 "%s during long response[$fd] - %0.6f",
1115 out($self, " deferred[$fd] aborted - %0.6f", $elapsed);
1117 } elsif ($more) { # $self->{wbuf}:
1118 $self->update_idle_time;
1120 # control passed to $more may be a GitAsyncCat object
1121 requeue_once($self) if !ref($more);
1122 } else { # all done!
1123 delete $self->{long_cb};
1124 my $elapsed = now() - $t0;
1125 my $fd = fileno($self->{sock});
1126 out($self, " deferred[$fd] done - %0.6f", $elapsed);
1127 my $wbuf = $self->{wbuf}; # do NOT autovivify
1129 $self->requeue unless $wbuf && @$wbuf;
1134 my ($self, $fmt, @args) = @_;
1135 printf { $self->{imapd}->{err} } $fmt."\n", @args;
1139 my ($self, $fmt, @args) = @_;
1140 printf { $self->{imapd}->{out} } $fmt."\n", @args;
1143 sub long_response ($$;@) {
1144 my ($self, $cb, @args) = @_; # cb returns true if more, false if done
1146 my $sock = $self->{sock} or return;
1147 # make sure we disable reading during a long response,
1148 # clients should not be sending us stuff and making us do more
1149 # work while we are stream a response to them
1150 $self->{long_cb} = [ fileno($sock), $cb, now(), @args ];
1151 long_step($self); # kick off!
1155 # callback used by PublicInbox::DS for any (e)poll (in/out/hup/err)
1159 return unless $self->flush_write && $self->{sock} && !$self->{long_cb};
1161 $self->update_idle_time;
1162 # only read more requests if we've drained the write buffer,
1163 # otherwise we can be buffering infinitely w/o backpressure
1165 my $rbuf = $self->{rbuf} // \(my $x = '');
1166 my $line = index($$rbuf, "\n");
1168 return $self->close if length($$rbuf) >= LINE_MAX;
1169 $self->do_read($rbuf, LINE_MAX, length($$rbuf)) or return;
1170 $line = index($$rbuf, "\n");
1172 $line = substr($$rbuf, 0, $line + 1, '');
1173 $line =~ s/\r?\n\z//s;
1174 return $self->close if $line =~ /[[:cntrl:]]/s;
1176 my $fd = fileno($self->{sock});
1177 my $r = eval { process_line($self, $line) };
1178 my $pending = $self->{wbuf} ? ' pending' : '';
1179 out($self, "[$fd] %s - %0.6f$pending - $r", $line, now() - $t0);
1181 return $self->close if $r < 0;
1182 $self->rbuf_idle($rbuf);
1183 $self->update_idle_time;
1185 # maybe there's more pipelined data, or we'll have
1186 # to register it for socket-readiness notifications
1187 $self->requeue unless $pending;
1190 sub compressed { undef }
1192 sub zflush {} # overridden by IMAPdeflate
1195 sub cmd_compress ($$$) {
1196 my ($self, $tag, $alg) = @_;
1197 return "$tag BAD DEFLATE only\r\n" if uc($alg) ne "DEFLATE";
1198 return "$tag BAD COMPRESS active\r\n" if $self->compressed;
1200 # CRIME made TLS compression obsolete
1201 # return "$tag NO [COMPRESSIONACTIVE]\r\n" if $self->tls_compressed;
1203 PublicInbox::IMAPdeflate->enable($self, $tag);
1208 sub cmd_starttls ($$) {
1209 my ($self, $tag) = @_;
1210 my $sock = $self->{sock} or return;
1211 if ($sock->can('stop_SSL') || $self->compressed) {
1212 return "$tag BAD TLS or compression already enabled\r\n";
1214 my $opt = $self->{imapd}->{accept_tls} or
1215 return "$tag BAD can not initiate TLS negotiation\r\n";
1216 $self->write(\"$tag OK begin TLS negotiation now\r\n");
1217 $self->{sock} = IO::Socket::SSL->start_SSL($sock, %$opt);
1218 $self->requeue if PublicInbox::DS::accept_tls_step($self);
1222 # for graceful shutdown in PublicInbox::Daemon:
1224 my ($self, $now) = @_;
1225 ($self->{rbuf} || $self->{wbuf} || $self->not_idle_long($now));
1230 if (my $ibx = delete $self->{ibx}) {
1231 stop_idle($self, $ibx);
1233 $self->SUPER::close; # PublicInbox::DS::close
1236 # we're read-only, so SELECT and EXAMINE do the same thing
1238 *cmd_select = \&cmd_examine;
1239 *cmd_fetch = \&cmd_uid_fetch;