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->{logged_in};
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 defined(my $old = $self->{-idle_max}) or die 'BUG: -idle_max unset';
179 $self->{-idle_max} = $new;
180 $self->msg_more("* $_ EXISTS\r\n") for (($old + 1)..($new - 1));
181 $self->write(\"* $new EXISTS\r\n");
186 my ($self, $tag) = @_;
187 # IDLE seems allowed by dovecot w/o a mailbox selected *shrug*
188 my $ibx = $self->{ibx} or return "$tag BAD no mailbox selected\r\n";
189 $ibx->subscribe_unlock(fileno($self->{sock}), $self);
190 $self->{imapd}->idler_start;
191 $self->{-idle_tag} = $tag;
192 $self->{-idle_max} = $ibx->mm->max // 0;
197 my ($self, $tag) = @_; # $tag is "DONE" (case-insensitive)
198 defined(my $idle_tag = delete $self->{-idle_tag}) or
199 return "$tag BAD not idle\r\n";
200 my $ibx = $self->{ibx} or do {
201 warn "BUG: idle_tag set w/o inbox";
202 return "$tag BAD internal bug\r\n";
204 $ibx->unsubscribe_unlock(fileno($self->{sock}));
205 "$idle_tag OK Idle done\r\n";
208 sub ensure_ranges_exist ($$$) {
209 my ($imapd, $ibx, $max) = @_;
210 my $mailboxes = $imapd->{mailboxes};
211 my $mb_top = $ibx->{newsgroup};
213 for (my $i = int($max/UID_BLOCK); $i >= 0; --$i) {
214 my $sub_mailbox = "$mb_top.$i";
215 last if exists $mailboxes->{$sub_mailbox};
216 $mailboxes->{$sub_mailbox} = $ibx;
217 push @created, $sub_mailbox;
219 return unless @created;
220 my $l = $imapd->{inboxlist} or return;
221 push @$l, map { qq[* LIST (\\HasNoChildren) "." $_\r\n] } @created;
224 sub inbox_lookup ($$) {
225 my ($self, $mailbox) = @_;
226 my ($ibx, $exists, $uidnext);
227 if ($mailbox =~ /\A(.+)\.([0-9]+)\z/) {
228 # old mail: inbox.comp.foo.$uid_block_idx
229 my ($mb_top, $uid_min) = ($1, $2 * UID_BLOCK + 1);
231 $ibx = $self->{imapd}->{mailboxes}->{lc $mailbox} or return;
232 $exists = $ibx->mm->max // 0;
233 $self->{uid_min} = $uid_min;
234 ensure_ranges_exist($self->{imapd}, $ibx, $exists);
235 my $uid_end = $uid_min + UID_BLOCK - 1;
236 $exists = $uid_end if $exists > $uid_end;
237 $uidnext = $exists + 1;
238 } else { # check for dummy inboxes
239 $ibx = $self->{imapd}->{mailboxes}->{lc $mailbox} or return;
240 delete $self->{uid_min};
244 ($ibx, $exists, $uidnext);
247 sub cmd_examine ($$$) {
248 my ($self, $tag, $mailbox) = @_;
249 my ($ibx, $exists, $uidnext) = inbox_lookup($self, $mailbox);
250 return "$tag NO Mailbox doesn't exist: $mailbox\r\n" if !$ibx;
252 # XXX: do we need this? RFC 5162/7162
253 my $ret = $self->{ibx} ? "* OK [CLOSED] previous closed\r\n" : '';
259 * OK [PERMANENTFLAGS ()] Read-only mailbox\r
260 * OK [UNSEEN $exists]\r
261 * OK [UIDNEXT $uidnext]\r
262 * OK [UIDVALIDITY $ibx->{uidvalidity}]\r
263 $tag OK [READ-ONLY] EXAMINE/SELECT done\r
271 } elsif ($v =~ /[{"\r\n%*\\\[]/) { # literal string
272 '{' . length($v) . "}\r\n" . $v;
273 } else { # quoted string
278 sub addr_envelope ($$;$) {
279 my ($eml, $x, $y) = @_;
280 my $v = $eml->header_raw($x) //
281 ($y ? $eml->header_raw($y) : undef) // return 'NIL';
283 my @x = $Address->parse($v) or return 'NIL';
285 map { '(' . join(' ',
286 _esc($_->name), 'NIL',
287 _esc($_->user), _esc($_->host)
293 sub eml_envelope ($) {
296 _esc($eml->header_raw('Date')),
297 _esc($eml->header_raw('Subject')),
298 addr_envelope($eml, 'From'),
299 addr_envelope($eml, 'Sender', 'From'),
300 addr_envelope($eml, 'Reply-To', 'From'),
301 addr_envelope($eml, 'To'),
302 addr_envelope($eml, 'Cc'),
303 addr_envelope($eml, 'Bcc'),
304 _esc($eml->header_raw('In-Reply-To')),
305 _esc($eml->header_raw('Message-ID')),
311 if ($hash && scalar keys %$hash) {
312 $hash = [ %$hash ]; # flatten hash into 1-dimensional array
313 '(' . join(' ', map { _esc($_) } @$hash) . ')';
319 sub body_disposition ($) {
321 my $cd = $eml->header_raw('Content-Disposition') or return 'NIL';
322 $cd = parse_content_disposition($cd);
323 my $buf = '('._esc($cd->{type});
324 $buf .= ' ' . _esc_hash(delete $cd->{attributes});
328 sub body_leaf ($$;$) {
329 my ($eml, $structure, $hold) = @_;
331 $eml->{is_submsg} and # parent was a message/(rfc822|news|global)
332 $buf .= eml_envelope($eml). ' ';
334 $buf .= '('._esc($ct->{type}).' ';
335 $buf .= _esc($ct->{subtype});
336 $buf .= ' ' . _esc_hash(delete $ct->{attributes});
337 $buf .= ' ' . _esc($eml->header_raw('Content-ID'));
338 $buf .= ' ' . _esc($eml->header_raw('Content-Description'));
339 my $cte = $eml->header_raw('Content-Transfer-Encoding') // '7bit';
340 $buf .= ' ' . _esc($cte);
341 $buf .= ' ' . $eml->{imap_body_len};
342 $buf .= ' '.($eml->body_raw =~ tr/\n/\n/) if lc($ct->{type}) eq 'text';
344 # for message/(rfc822|global|news), $hold[0] should have envelope
345 $buf .= ' ' . (@$hold ? join('', @$hold) : 'NIL') if $hold;
348 $buf .= ' '._esc($eml->header_raw('Content-MD5'));
349 $buf .= ' '. body_disposition($eml);
350 $buf .= ' '._esc($eml->header_raw('Content-Language'));
351 $buf .= ' '._esc($eml->header_raw('Content-Location'));
356 sub body_parent ($$$) {
357 my ($eml, $structure, $hold) = @_;
359 my $type = lc($ct->{type});
360 if ($type eq 'multipart') {
362 $buf .= @$hold ? join('', @$hold) : 'NIL';
363 $buf .= ' '._esc($ct->{subtype});
365 $buf .= ' '._esc_hash(delete $ct->{attributes});
366 $buf .= ' '.body_disposition($eml);
367 $buf .= ' '._esc($eml->header_raw('Content-Language'));
368 $buf .= ' '._esc($eml->header_raw('Content-Location'));
372 } else { # message/(rfc822|global|news)
373 @$hold = (body_leaf($eml, $structure, $hold));
377 # this is gross, but we need to process the parent part AFTER
378 # the child parts are done
379 sub bodystructure_prep {
381 my ($eml, $depth) = @$p; # ignore idx
382 # set length here, as $eml->{bdy} gets deleted for message/rfc822
383 $eml->{imap_body_len} = length($eml->body_raw);
384 push @$q, $eml, $depth;
387 # for FETCH BODY and FETCH BODYSTRUCTURE
388 sub fetch_body ($;$) {
389 my ($eml, $structure) = @_;
391 $eml->each_part(\&bodystructure_prep, \@q, 0, 1);
395 my ($part, $depth) = splice(@q, -2);
396 my $is_mp_parent = $depth == ($cur_depth - 1);
400 body_parent($part, $structure, \@hold);
402 unshift @hold, body_leaf($part, $structure);
408 sub requeue_once ($) {
410 # COMPRESS users all share the same DEFLATE context.
411 # Flush it here to ensure clients don't see
415 # no recursion, schedule another call ASAP,
416 # but only after all pending writes are done.
418 my $new_size = push(@{$self->{wbuf}}, \&long_step);
420 # wbuf may be populated by $cb, no need to rearm if so:
421 $self->requeue if $new_size == 1;
424 sub uid_fetch_cb { # called by git->cat_async via git_async_cat
425 my ($bref, $oid, $type, $size, $fetch_m_arg) = @_;
426 my ($self, undef, $msgs, undef, $ops, $partial) = @$fetch_m_arg;
427 my $smsg = shift @$msgs or die 'BUG: no smsg';
428 if (!defined($oid)) {
429 # it's possible to have TOCTOU if an admin runs
430 # public-inbox-(edit|purge), just move onto the next message
431 return requeue_once($self);
433 $smsg->{blob} eq $oid or die "BUG: $smsg->{blob} != $oid";
435 $$bref =~ s/(?<!\r)\n/\r\n/sg; # make strict clients happy
437 # fixup old bug from import (pre-a0c07cba0e5d8b6a)
438 $$bref =~ s/\A[\r\n]*From [^\r\n]*\r\n//s;
439 $self->msg_more("* $smsg->{num} FETCH (UID $smsg->{num}");
441 for (my $i = 0; $i < @$ops;) {
442 my $k = $ops->[$i++];
443 $ops->[$i++]->($self, $k, $smsg, $bref, $eml);
445 partial_emit($self, $partial, $eml) if $partial;
446 $self->msg_more(")\r\n");
451 my ($self, $k, undef, $bref) = @_;
452 $self->msg_more(" $k {" . length($$bref)."}\r\n");
453 $self->msg_more($$bref);
456 # Mail::IMAPClient::message_string cares about this by default
457 # (->Ignoresizeerrors attribute)
458 sub emit_rfc822_size {
459 my ($self, $k, undef, $bref) = @_;
460 $self->msg_more(' RFC822.SIZE ' . length($$bref));
463 sub emit_internaldate {
464 my ($self, undef, $smsg) = @_;
465 $self->msg_more(' INTERNALDATE "'.$smsg->internaldate.'"');
468 sub emit_flags { $_[0]->msg_more(' FLAGS ()') }
471 my ($self, undef, undef, undef, $eml) = @_;
472 $self->msg_more(' ENVELOPE '.eml_envelope($eml));
475 sub emit_rfc822_header {
476 my ($self, $k, undef, undef, $eml) = @_;
477 $self->msg_more(" $k {".length(${$eml->{hdr}})."}\r\n");
478 $self->msg_more(${$eml->{hdr}});
481 # n.b. this is sorted to be after any emit_eml_new ops
482 sub emit_rfc822_text {
483 my ($self, $k, undef, $bref) = @_;
484 $self->msg_more(" $k {".length($$bref)."}\r\n");
485 $self->msg_more($$bref);
488 sub emit_bodystructure {
489 my ($self, undef, undef, undef, $eml) = @_;
490 $self->msg_more(' BODYSTRUCTURE '.fetch_body($eml, 1));
494 my ($self, undef, undef, undef, $eml) = @_;
495 $self->msg_more(' BODY '.fetch_body($eml));
498 # set $eml once ($_[4] == $eml, $_[3] == $bref)
499 sub op_eml_new { $_[4] = PublicInbox::Eml->new($_[3]) }
501 sub uid_clamp ($$$) {
502 my ($self, $beg, $end) = @_;
503 my $uid_min = $self->{uid_min} or return;
504 my $uid_end = $uid_min + UID_BLOCK - 1;
505 $$beg = $uid_min if $$beg < $uid_min;
506 $$end = $uid_end if $$end > $uid_end;
509 sub range_step ($$) {
510 my ($self, $range_csv) = @_;
511 my ($beg, $end, $range);
512 if ($$range_csv =~ s/\A([^,]+),//) {
515 $range = $$range_csv;
518 if ($range =~ /\A([0-9]+):([0-9]+)\z/) {
519 ($beg, $end) = ($1 + 0, $2 + 0);
520 } elsif ($range =~ /\A([0-9]+):\*\z/) {
522 $end = $self->{ibx}->mm->max // 0;
523 my $uid_end = ($self->{uid_min} // 1) - 1 + UID_BLOCK;
524 $end = $uid_end if $end > $uid_end;
525 $beg = $end if $beg > $end;
526 } elsif ($range =~ /\A[0-9]+\z/) {
527 $beg = $end = $range + 0;
530 return 'BAD fetch range';
532 uid_clamp($self, \$beg, \$end) if defined($range);
533 [ $beg, $end, $$range_csv ];
536 sub refill_range ($$$) {
537 my ($self, $msgs, $range_info) = @_;
538 my ($beg, $end, $range_csv) = @$range_info;
539 if (scalar(@$msgs = @{$self->{ibx}->over->query_xover($beg, $end)})) {
540 $range_info->[0] = $msgs->[-1]->{num} + 1;
543 return 'OK Fetch done' if !$range_csv;
544 my $next_range = range_step($self, \$range_csv);
545 return $next_range if !ref($next_range); # error
546 @$range_info = @$next_range;
547 undef; # keep looping
550 sub uid_fetch_msg { # long_response
551 my ($self, $tag, $msgs, $range_info) = @_; # \@ops, \@partial
552 while (!@$msgs) { # rare
553 if (my $end = refill_range($self, $msgs, $range_info)) {
554 $self->write(\"$tag $end\r\n");
558 git_async_cat($self->{ibx}->git, $msgs->[0]->{blob},
559 \&uid_fetch_cb, \@_);
562 sub uid_fetch_smsg { # long_response
563 my ($self, $tag, $msgs, $range_info, $ops) = @_;
564 while (!@$msgs) { # rare
565 if (my $end = refill_range($self, $msgs, $range_info)) {
566 $self->write(\"$tag $end\r\n");
570 for my $smsg (@$msgs) {
571 $self->msg_more("* $smsg->{num} FETCH (UID $smsg->{num}");
572 for (my $i = 0; $i < @$ops;) {
573 my $k = $ops->[$i++];
574 $ops->[$i++]->($self, $k, $smsg);
576 $self->msg_more(")\r\n");
582 sub uid_fetch_uid { # long_response
583 my ($self, $tag, $uids, $range_info, $ops) = @_;
584 while (!@$uids) { # rare
585 my ($beg, $end, $range_csv) = @$range_info;
586 if (scalar(@$uids = @{$self->{ibx}->over->
587 uid_range($beg, $end)})) {
588 $range_info->[0] = $uids->[-1] + 1;
589 } elsif (!$range_csv) {
590 $self->write(\"$tag OK Fetch done\r\n");
593 my $next_range = range_step($self, \$range_csv);
594 if (!ref($next_range)) { # error
595 $self->write(\"$tag $next_range\r\n");
598 @$range_info = @$next_range;
603 $self->msg_more("* $_ FETCH (UID $_");
604 for (my $i = 0; $i < @$ops;) {
605 my $k = $ops->[$i++];
606 $ops->[$i++]->($self, $k);
608 $self->msg_more(")\r\n");
614 sub cmd_status ($$$;@) {
615 my ($self, $tag, $mailbox, @items) = @_;
616 return "$tag BAD no items\r\n" if !scalar(@items);
617 ($items[0] !~ s/\A\(//s || $items[-1] !~ s/\)\z//s) and
618 return "$tag BAD invalid args\r\n";
619 my ($ibx, $exists, $uidnext) = inbox_lookup($self, $mailbox);
620 return "$tag NO Mailbox doesn't exist: $mailbox\r\n" if !$ibx;
622 for my $it (@items) {
625 if ($it =~ /\A(?:MESSAGES|UNSEEN|RECENT)\z/) {
627 } elsif ($it eq 'UIDNEXT') {
629 } elsif ($it eq 'UIDVALIDITY') {
630 push @it, $ibx->{uidvalidity};
632 return "$tag BAD invalid item\r\n";
635 return "$tag BAD no items\r\n" if !@it;
636 "* STATUS $mailbox (".join(' ', @it).")\r\n" .
637 "$tag OK Status done\r\n";
640 my %patmap = ('*' => '.*', '%' => '[^\.]*');
641 sub cmd_list ($$$$) {
642 my ($self, $tag, $refname, $wildcard) = @_;
643 my $l = $self->{imapd}->{inboxlist};
644 if ($refname eq '' && $wildcard eq '') {
645 # request for hierarchy delimiter
646 $l = [ qq[* LIST (\\Noselect) "." ""\r\n] ];
647 } elsif ($refname ne '' || $wildcard ne '*') {
648 $wildcard = lc $wildcard;
649 $wildcard =~ s!([^a-z0-9_])!$patmap{$1} // "\Q$1"!eg;
650 $l = [ grep(/ \Q$refname\E$wildcard\r\n\z/s, @$l) ];
652 \(join('', @$l, "$tag OK List done\r\n"));
655 sub cmd_lsub ($$$$) {
656 my (undef, $tag) = @_; # same args as cmd_list
657 "$tag OK Lsub done\r\n";
660 sub eml_index_offs_i { # PublicInbox::Eml::each_part callback
662 my ($eml, undef, $idx) = @$p;
663 if ($idx && lc($eml->ct->{type}) eq 'multipart') {
664 $eml->{imap_bdy} = $eml->{bdy} // \'';
666 $all->{$idx} = $eml; # $idx => Eml
669 # prepares an index for BODY[$SECTION_IDX] fetches
670 sub eml_body_idx ($$) {
671 my ($eml, $section_idx) = @_;
672 my $idx = $eml->{imap_all_parts} //= do {
674 $eml->each_part(\&eml_index_offs_i, $all, 0, 1);
675 # top-level of multipart, BODY[0] not allowed (nz-number)
679 $idx->{$section_idx};
682 # BODY[($SECTION_IDX)?(.$SECTION_NAME)?]<$offset.$bytes>
684 my ($eml, $section_idx, $section_name) = @_;
685 if (defined $section_idx) {
686 $eml = eml_body_idx($eml, $section_idx) or return;
688 if (defined $section_name) {
689 if ($section_name eq 'MIME') {
690 # RFC 3501 6.4.5 states:
691 # The MIME part specifier MUST be prefixed
692 # by one or more numeric part specifiers
693 return unless defined $section_idx;
694 return $eml->header_obj->as_string . "\r\n";
696 my $bdy = $eml->{bdy} // $eml->{imap_bdy} // \'';
697 $eml = PublicInbox::Eml->new($$bdy);
698 if ($section_name eq 'TEXT') {
699 return $eml->body_raw;
700 } elsif ($section_name eq 'HEADER') {
701 return $eml->header_obj->as_string . "\r\n";
703 die "BUG: bad section_name=$section_name";
706 ${$eml->{bdy} // $eml->{imap_bdy} // \''};
709 # similar to what's in PublicInbox::Eml::re_memo, but doesn't memoize
710 # to avoid OOM with malicious users
711 sub hdrs_regexp ($) {
713 my $names = join('|', map { "\Q$_" } split(/[ \t]+/, $hdrs));
714 qr/^(?:$names):[ \t]*[^\n]*\r?\n # 1st line
715 # continuation lines:
716 (?:[^:\n]*?[ \t]+[^\n]*\r?\n)*
720 # BODY[($SECTION_IDX.)?HEADER.FIELDS.NOT ($HDRS)]<$offset.$bytes>
721 sub partial_hdr_not {
722 my ($eml, $section_idx, $hdrs_re) = @_;
723 if (defined $section_idx) {
724 $eml = eml_body_idx($eml, $section_idx) or return;
726 my $str = $eml->header_obj->as_string;
727 $str =~ s/$hdrs_re//g;
731 # BODY[($SECTION_IDX.)?HEADER.FIELDS ($HDRS)]<$offset.$bytes>
732 sub partial_hdr_get {
733 my ($eml, $section_idx, $hdrs_re) = @_;
734 if (defined $section_idx) {
735 $eml = eml_body_idx($eml, $section_idx) or return;
737 my $str = $eml->header_obj->as_string;
738 join('', ($str =~ m/($hdrs_re)/g), "\r\n");
741 sub partial_prepare ($$$) {
742 my ($partial, $want, $att) = @_;
744 # recombine [ "BODY[1.HEADER.FIELDS", "(foo", "bar)]" ]
745 # back to: "BODY[1.HEADER.FIELDS (foo bar)]"
746 return unless $att =~ /\ABODY\[/s;
747 until (rindex($att, ']') >= 0) {
748 my $next = shift @$want or return;
749 $att .= ' ' . uc($next);
751 if ($att =~ /\ABODY\[([0-9]+(?:\.[0-9]+)*)? # 1 - section_idx
752 (?:\.(HEADER|MIME|TEXT))? # 2 - section_name
753 \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 3, 4
754 $partial->{$att} = [ \&partial_body, $1, $2, $3, $4 ];
755 } elsif ($att =~ /\ABODY\[(?:([0-9]+(?:\.[0-9]+)*)\.)? # 1 - section_idx
756 (?:HEADER\.FIELDS(\.NOT)?)\x20 # 2
757 \(([A-Z0-9\-\x20]+)\) # 3 - hdrs
758 \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 4 5
759 my $tmp = $partial->{$att} = [ $2 ? \&partial_hdr_not
762 $tmp->[2] = hdrs_regexp($3);
768 sub partial_emit ($$$) {
769 my ($self, $partial, $eml) = @_;
771 my ($k, $cb, @args) = @$_;
772 my ($offset, $len) = splice(@args, -2);
773 # $cb is partial_body|partial_hdr_get|partial_hdr_not
774 my $str = $cb->($eml, @args) // '';
775 if (defined $offset) {
777 $str = substr($str, $offset, $len);
778 $k =~ s/\.$len>\z/>/ or warn
779 "BUG: unable to remove `.$len>' from `$k'";
781 $str = substr($str, $offset);
787 $self->msg_more(" $k {$len}\r\n");
788 $self->msg_more($str);
792 sub fetch_compile ($) {
794 if ($want->[0] =~ s/\A\(//s) {
795 $want->[-1] =~ s/\)\z//s or return 'BAD no rparen';
797 my (%partial, %seen, @op);
799 while (defined(my $att = shift @$want)) {
801 next if $att eq 'UID'; # always returned
802 $att =~ s/\ABODY\.PEEK\[/BODY\[/; # we're read-only
803 my $x = $FETCH_ATT{$att};
805 while (my ($k, $fl_cb) = each %$x) {
807 $need |= $fl_cb->[0];
809 # insert a special op to convert $bref to $eml
810 # the first time we need it
811 if ($need == NEED_EML && !$seen{$need}++) {
812 push @op, $OP_EML_NEW;
814 # $fl_cb = [ flags, \&emit_foo ]
815 push @op, [ @$fl_cb , $k ];
817 } elsif (!partial_prepare(\%partial, $want, $att)) {
818 return "BAD param: $att";
823 # stabilize partial order for consistency and ease-of-debugging:
824 if (scalar keys %partial) {
826 push @op, $OP_EML_NEW if !$seen{$need}++;
827 $r[2] = [ map { [ $_, @{$partial{$_}} ] } sort keys %partial ];
830 $r[0] = $need & NEED_BLOB ? \&uid_fetch_msg :
831 ($need & NEED_SMSG ? \&uid_fetch_smsg : \&uid_fetch_uid);
833 # r[1] = [ $key1, $cb1, $key2, $cb2, ... ]
834 use sort 'stable'; # makes output more consistent
835 $r[1] = [ map { ($_->[2], $_->[1]) } sort { $a->[0] <=> $b->[0] } @op ];
839 sub cmd_uid_fetch ($$$;@) {
840 my ($self, $tag, $range_csv, @want) = @_;
841 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
842 my ($cb, $ops, $partial) = fetch_compile(\@want);
843 return "$tag $cb\r\n" unless $ops;
845 $range_csv = 'bad' if $range_csv !~ $valid_range;
846 my $range_info = range_step($self, \$range_csv);
847 return "$tag $range_info\r\n" if !ref($range_info);
848 long_response($self, $cb, $tag, [], $range_info, $ops, $partial);
851 sub parse_date ($) { # 02-Oct-1993
852 my ($date_text) = @_;
853 my ($dd, $mon, $yyyy) = split(/-/, $_[0], 3);
854 defined($yyyy) or return;
855 my $mm = $MoY{$mon} // return;
856 $dd =~ /\A[0123]?[0-9]\z/ or return;
857 $yyyy =~ /\A[0-9]{4,}\z/ or return; # Y10K-compatible!
858 timegm(0, 0, 0, $dd, $mm, $yyyy);
861 sub uid_search_uid_range { # long_response
862 my ($self, $tag, $beg, $end, $sql) = @_;
863 my $uids = $self->{ibx}->over->uid_range($$beg, $end, $sql);
865 $$beg = $uids->[-1] + 1;
866 $self->msg_more(join(' ', '', @$uids));
868 $self->write(\"\r\n$tag OK Search done\r\n");
874 my ($q, $k, $d) = @_;
878 if ($k eq 'SENTON') {
879 my $end = $d + 86399; # no leap day...
880 my $da = strftime('%Y%m%d%H%M%S', gmtime($d));
881 my $db = strftime('%Y%m%d%H%M%S', gmtime($end));
882 $q->{xap} .= " dt:$da..$db";
883 $$sql .= " AND ds >= $d AND ds <= $end" if defined($sql);
884 } elsif ($k eq 'SENTBEFORE') {
885 $q->{xap} .= ' d:..'.strftime('%Y%m%d', gmtime($d));
886 $$sql .= " AND ds <= $d" if defined($sql);
887 } elsif ($k eq 'SENTSINCE') {
888 $q->{xap} .= ' d:'.strftime('%Y%m%d', gmtime($d)).'..';
889 $$sql .= " AND ds >= $d" if defined($sql);
891 # INTERNALDATE (Received)
892 } elsif ($k eq 'ON') {
893 my $end = $d + 86399; # no leap day...
894 $q->{xap} .= " ts:$d..$end";
895 $$sql .= " AND ts >= $d AND ts <= $end" if defined($sql);
896 } elsif ($k eq 'BEFORE') {
897 $q->{xap} .= " ts:..$d";
898 $$sql .= " AND ts <= $d" if defined($sql);
899 } elsif ($k eq 'SINCE') {
900 $q->{xap} .= " ts:$d..";
901 $$sql .= " AND ts >= $d" if defined($sql);
903 die "BUG: $k not recognized";
907 # IMAP to Xapian search key mapping
912 TEXT => '', # n.b. does not include all headers
915 # BCC => 'bcc:', # TODO
916 # KEYWORD # TODO ? dfpre,dfpost,...
920 my ($self, $rest) = @_;
921 if (uc($rest->[0]) eq 'CHARSET') {
923 defined(my $c = shift @$rest) or return 'BAD missing charset';
924 $c =~ /\A(?:UTF-8|US-ASCII)\z/ or return 'NO [BADCHARSET]';
927 my $sql = ''; # date conditions, {sql} deleted if Xapian is needed
928 my $q = { xap => '', sql => \$sql };
930 my $k = uc(shift @$rest);
932 next if $k =~ /\A(?:ALL|RECENT|UNSEEN|NEW)\z/;
933 next if $k eq 'AND'; # the default, until we support OR
934 if ($k =~ $valid_range) { # sequence numbers == UIDs
935 push @{$q->{uid}}, $k;
936 } elsif ($k eq 'UID') {
937 $k = shift(@$rest) // '';
938 $k =~ $valid_range or return 'BAD UID range';
939 push @{$q->{uid}}, $k;
940 } elsif ($k =~ /\A(?:SENT)?(?:SINCE|ON|BEFORE)\z/) {
941 my $d = parse_date(shift(@$rest) // '');
942 defined $d or return "BAD $k date format";
943 date_search($q, $k, $d);
944 } elsif ($k =~ /\A(?:SMALLER|LARGER)\z/) {
945 delete $q->{sql}; # can't use over.sqlite3
946 my $bytes = shift(@$rest) // '';
947 $bytes =~ /\A[0-9]+\z/ or return "BAD $k not a number";
948 $q->{xap} .= ' bytes:' . ($k eq 'SMALLER' ?
951 } elsif (defined(my $xk = $I2X{$k})) {
952 delete $q->{sql}; # can't use over.sqlite3
953 my $arg = shift @$rest;
954 defined($arg) or return "BAD $k no arg";
956 # Xapian can't handle [*"] in probabilistic terms
958 $q->{xap} .= qq[ $xk:"$arg"];
960 # TODO: parentheses, OR, NOT ...
961 return "BAD $k not supported (yet?)";
965 # favor using over.sqlite3 if possible, since Xapian is optional
966 if (exists $q->{sql}) {
968 delete($q->{sql}) if $sql eq '';
969 } elsif (!$self->{ibx}->search) {
970 return 'BAD Xapian not configured for mailbox';
973 if (my $uid = $q->{uid}) {
974 ((@$uid > 1) || $uid->[0] =~ /,/) and
975 return 'BAD multiple ranges not supported, yet';
976 ($q->{sql} // $q->{xap}) and
977 return 'BAD ranges and queries do not mix, yet';
978 $q->{uid} = join(',', @$uid); # TODO: multiple ranges
983 sub cmd_uid_search ($$$;) {
984 my ($self, $tag) = splice(@_, 0, 2);
985 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
986 my $q = parse_query($self, \@_);
987 return "$tag $q\r\n" if !ref($q);
988 my $sql = delete $q->{sql};
990 if (!scalar(keys %$q)) {
991 $self->msg_more('* SEARCH');
992 my $beg = $self->{uid_min} // 1;
993 my $end = $ibx->mm->max;
994 uid_clamp($self, \$beg, \$end);
995 long_response($self, \&uid_search_uid_range,
996 $tag, \$beg, $end, $sql);
997 } elsif (my $uid = $q->{uid}) {
998 if ($uid =~ /\A([0-9]+):([0-9]+|\*)\z/s) {
999 my ($beg, $end) = ($1, $2);
1000 $end = $ibx->mm->max if $end eq '*';
1001 uid_clamp($self, \$beg, \$end);
1002 $self->msg_more('* SEARCH');
1003 long_response($self, \&uid_search_uid_range,
1004 $tag, \$beg, $end, $sql);
1005 } elsif ($uid =~ /\A[0-9]+\z/s) {
1006 $uid = $ibx->over->get_art($uid) ? " $uid" : '';
1007 "* SEARCH$uid\r\n$tag OK Search done\r\n";
1009 "$tag BAD Error\r\n";
1012 "$tag BAD Error\r\n";
1016 sub args_ok ($$) { # duplicated from PublicInbox::NNTP
1017 my ($cb, $argc) = @_;
1018 my $tot = prototype $cb;
1019 my ($nreq, undef) = split(';', $tot);
1020 $nreq = ($nreq =~ tr/$//) - 1;
1021 $tot = ($tot =~ tr/$//) - 1;
1022 ($argc <= $tot && $argc >= $nreq);
1025 # returns 1 if we can continue, 0 if not due to buffered writes or disconnect
1026 sub process_line ($$) {
1027 my ($self, $l) = @_;
1028 my ($tag, $req, @args) = parse_line('[ \t]+', 0, $l);
1029 pop(@args) if (@args && !defined($args[-1]));
1030 if (@args && uc($req) eq 'UID') {
1031 $req .= "_".(shift @args);
1034 if (my $cmd = $self->can('cmd_'.lc($req // ''))) {
1035 defined($self->{-idle_tag}) ?
1036 "$self->{-idle_tag} BAD expected DONE\r\n" :
1037 $cmd->($self, $tag, @args);
1038 } elsif (uc($tag // '') eq 'DONE' && !defined($req)) {
1039 cmd_done($self, $tag);
1040 } else { # this is weird
1041 auth_challenge_ok($self) //
1043 ' BAD Error in IMAP command '.
1045 ": Unknown command\r\n";
1049 if ($err && $self->{sock}) {
1051 err($self, 'error from: %s (%s)', $l, $err);
1053 $res = "$tag BAD program fault - command not performed\r\n";
1055 return 0 unless defined $res;
1061 # wbuf is unset or empty, here; {long} may add to it
1062 my ($fd, $cb, $t0, @args) = @{$self->{long_cb}};
1063 my $more = eval { $cb->($self, @args) };
1064 if ($@ || !$self->{sock}) { # something bad happened...
1065 delete $self->{long_cb};
1066 my $elapsed = now() - $t0;
1069 "%s during long response[$fd] - %0.6f",
1072 out($self, " deferred[$fd] aborted - %0.6f", $elapsed);
1074 } elsif ($more) { # $self->{wbuf}:
1075 $self->update_idle_time;
1077 # control passed to $more may be a GitAsyncCat object
1078 requeue_once($self) if !ref($more);
1079 } else { # all done!
1080 delete $self->{long_cb};
1081 my $elapsed = now() - $t0;
1082 my $fd = fileno($self->{sock});
1083 out($self, " deferred[$fd] done - %0.6f", $elapsed);
1084 my $wbuf = $self->{wbuf}; # do NOT autovivify
1086 $self->requeue unless $wbuf && @$wbuf;
1091 my ($self, $fmt, @args) = @_;
1092 printf { $self->{imapd}->{err} } $fmt."\n", @args;
1096 my ($self, $fmt, @args) = @_;
1097 printf { $self->{imapd}->{out} } $fmt."\n", @args;
1100 sub long_response ($$;@) {
1101 my ($self, $cb, @args) = @_; # cb returns true if more, false if done
1103 my $sock = $self->{sock} or return;
1104 # make sure we disable reading during a long response,
1105 # clients should not be sending us stuff and making us do more
1106 # work while we are stream a response to them
1107 $self->{long_cb} = [ fileno($sock), $cb, now(), @args ];
1108 long_step($self); # kick off!
1112 # callback used by PublicInbox::DS for any (e)poll (in/out/hup/err)
1116 return unless $self->flush_write && $self->{sock} && !$self->{long_cb};
1118 $self->update_idle_time;
1119 # only read more requests if we've drained the write buffer,
1120 # otherwise we can be buffering infinitely w/o backpressure
1122 my $rbuf = $self->{rbuf} // \(my $x = '');
1123 my $line = index($$rbuf, "\n");
1125 return $self->close if length($$rbuf) >= LINE_MAX;
1126 $self->do_read($rbuf, LINE_MAX, length($$rbuf)) or return;
1127 $line = index($$rbuf, "\n");
1129 $line = substr($$rbuf, 0, $line + 1, '');
1130 $line =~ s/\r?\n\z//s;
1131 return $self->close if $line =~ /[[:cntrl:]]/s;
1133 my $fd = fileno($self->{sock});
1134 my $r = eval { process_line($self, $line) };
1135 my $pending = $self->{wbuf} ? ' pending' : '';
1136 out($self, "[$fd] %s - %0.6f$pending - $r", $line, now() - $t0);
1138 return $self->close if $r < 0;
1139 $self->rbuf_idle($rbuf);
1140 $self->update_idle_time;
1142 # maybe there's more pipelined data, or we'll have
1143 # to register it for socket-readiness notifications
1144 $self->requeue unless $pending;
1147 sub compressed { undef }
1149 sub zflush {} # overridden by IMAPdeflate
1152 sub cmd_compress ($$$) {
1153 my ($self, $tag, $alg) = @_;
1154 return "$tag BAD DEFLATE only\r\n" if uc($alg) ne "DEFLATE";
1155 return "$tag BAD COMPRESS active\r\n" if $self->compressed;
1157 # CRIME made TLS compression obsolete
1158 # return "$tag NO [COMPRESSIONACTIVE]\r\n" if $self->tls_compressed;
1160 PublicInbox::IMAPdeflate->enable($self, $tag);
1165 sub cmd_starttls ($$) {
1166 my ($self, $tag) = @_;
1167 my $sock = $self->{sock} or return;
1168 if ($sock->can('stop_SSL') || $self->compressed) {
1169 return "$tag BAD TLS or compression already enabled\r\n";
1171 my $opt = $self->{imapd}->{accept_tls} or
1172 return "$tag BAD can not initiate TLS negotiation\r\n";
1173 $self->write(\"$tag OK begin TLS negotiation now\r\n");
1174 $self->{sock} = IO::Socket::SSL->start_SSL($sock, %$opt);
1175 $self->requeue if PublicInbox::DS::accept_tls_step($self);
1179 # for graceful shutdown in PublicInbox::Daemon:
1181 my ($self, $now) = @_;
1182 ($self->{rbuf} || $self->{wbuf} || $self->not_idle_long($now));
1187 if (my $ibx = delete $self->{ibx}) {
1188 if (my $sock = $self->{sock}) {;
1189 $ibx->unsubscribe_unlock(fileno($sock));
1192 $self->SUPER::close; # PublicInbox::DS::close
1195 # we're read-only, so SELECT and EXAMINE do the same thing
1197 *cmd_select = \&cmd_examine;
1198 *cmd_fetch = \&cmd_uid_fetch;