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_BLOB () { 1 }
45 sub NEED_EML () { NEED_BLOB|2 }
46 my $OP_EML_NEW = [ NEED_EML - 1, \&op_eml_new ];
48 my %FETCH_NEED = ( # for future optimization
49 'BODY[HEADER]' => [ NEED_EML, \&emit_rfc822_header ],
50 'BODY[TEXT]' => [ NEED_EML, \&emit_rfc822_text ],
51 'BODY[]' => [ NEED_BLOB, \&emit_rfc822 ],
52 'RFC822.HEADER' => [ NEED_EML, \&emit_rfc822_header ],
53 'RFC822.TEXT' => [ NEED_EML, \&emit_rfc822_text ],
54 'RFC822.SIZE' => [ NEED_BLOB, \&emit_rfc822_size ],
55 RFC822 => [ NEED_BLOB, \&emit_rfc822 ],
56 BODY => [ NEED_EML, \&emit_body ],
57 BODYSTRUCTURE => [ NEED_EML, \&emit_bodystructure ],
58 ENVELOPE => [ NEED_EML, \&emit_envelope ],
59 FLAGS => [ 0, \&emit_flags ],
60 INTERNALDATE => [ 0, \&emit_internaldate ],
62 my %FETCH_ATT = map { $_ => [ $_ ] } keys %FETCH_NEED;
64 # aliases (RFC 3501 section 6.4.5)
65 $FETCH_ATT{FAST} = [ qw(FLAGS INTERNALDATE RFC822.SIZE) ];
66 $FETCH_ATT{ALL} = [ @{$FETCH_ATT{FAST}}, 'ENVELOPE' ];
67 $FETCH_ATT{FULL} = [ @{$FETCH_ATT{ALL}}, 'BODY' ];
69 for my $att (keys %FETCH_ATT) {
70 my %h = map { $_ => $FETCH_NEED{$_} } @{$FETCH_ATT{$att}};
71 $FETCH_ATT{$att} = \%h;
75 my $valid_range = '[0-9]+|[0-9]+:[0-9]+|[0-9]+:\*';
76 $valid_range = qr/\A(?:$valid_range)(?:,(?:$valid_range))*\z/;
78 my @MoY = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
84 my $capa = capa($self);
85 $self->write(\"* OK [$capa] public-inbox-imapd ready\r\n");
89 my ($class, $sock, $imapd) = @_;
90 my $self = fields::new($class);
93 if ($sock->can('accept_SSL') && !$sock->accept_SSL) {
94 return CORE::close($sock) if $! != EAGAIN;
95 $ev = PublicInbox::TLS::epollbit();
96 $wbuf = [ \&PublicInbox::DS::accept_tls_step, \&greet ];
98 $self->SUPER::new($sock, $ev | EPOLLONESHOT);
99 $self->{imapd} = $imapd;
101 $self->{wbuf} = $wbuf;
105 $self->update_idle_time;
112 # dovecot advertises IDLE pre-login; perhaps because some clients
113 # depend on it, so we'll do the same
114 my $capa = 'CAPABILITY IMAP4rev1 IDLE';
115 if ($self->{logged_in}) {
116 $capa .= ' COMPRESS=DEFLATE';
118 if (!($self->{sock} // $self)->can('accept_SSL') &&
119 $self->{imapd}->{accept_tls}) {
120 $capa .= ' STARTTLS';
122 $capa .= ' AUTH=ANONYMOUS';
126 sub login_success ($$) {
127 my ($self, $tag) = @_;
128 $self->{logged_in} = 1;
129 my $capa = capa($self);
130 "$tag OK [$capa] Logged in\r\n";
133 sub auth_challenge_ok ($) {
135 my $tag = delete($self->{-login_tag}) or return;
136 login_success($self, $tag);
139 sub cmd_login ($$$$) {
140 my ($self, $tag) = @_; # ignore ($user, $password) = ($_[2], $_[3])
141 login_success($self, $tag);
145 my ($self, $tag) = @_;
146 delete $self->{uid_min};
147 delete $self->{ibx} ? "$tag OK Close done\r\n"
148 : "$tag BAD No mailbox\r\n";
151 sub cmd_logout ($$) {
152 my ($self, $tag) = @_;
153 delete $self->{logged_in};
154 $self->write(\"* BYE logging out\r\n$tag OK Logout done\r\n");
155 $self->shutdn; # PublicInbox::DS::shutdn
159 sub cmd_authenticate ($$$) {
160 my ($self, $tag) = @_; # $method = $_[2], should be "ANONYMOUS"
161 $self->{-login_tag} = $tag;
165 sub cmd_capability ($$) {
166 my ($self, $tag) = @_;
167 '* '.capa($self)."\r\n$tag OK Capability done\r\n";
170 sub cmd_noop ($$) { "$_[1] OK Noop done\r\n" }
172 # called by PublicInbox::InboxIdle
173 sub on_inbox_unlock {
174 my ($self, $ibx) = @_;
175 my $new = $ibx->mm->max;
176 defined(my $old = $self->{-idle_max}) or die 'BUG: -idle_max unset';
178 $self->{-idle_max} = $new;
179 $self->msg_more("* $_ EXISTS\r\n") for (($old + 1)..($new - 1));
180 $self->write(\"* $new EXISTS\r\n");
185 my ($self, $tag) = @_;
186 # IDLE seems allowed by dovecot w/o a mailbox selected *shrug*
187 my $ibx = $self->{ibx} or return "$tag BAD no mailbox selected\r\n";
188 $ibx->subscribe_unlock(fileno($self->{sock}), $self);
189 $self->{imapd}->idler_start;
190 $self->{-idle_tag} = $tag;
191 $self->{-idle_max} = $ibx->mm->max // 0;
196 my ($self, $tag) = @_; # $tag is "DONE" (case-insensitive)
197 defined(my $idle_tag = delete $self->{-idle_tag}) or
198 return "$tag BAD not idle\r\n";
199 my $ibx = $self->{ibx} or do {
200 warn "BUG: idle_tag set w/o inbox";
201 return "$tag BAD internal bug\r\n";
203 $ibx->unsubscribe_unlock(fileno($self->{sock}));
204 "$idle_tag OK Idle done\r\n";
207 sub ensure_ranges_exist ($$$) {
208 my ($imapd, $ibx, $max) = @_;
209 my $mailboxes = $imapd->{mailboxes};
210 my $mb_top = $ibx->{newsgroup};
212 for (my $i = int($max/UID_BLOCK); $i >= 0; --$i) {
213 my $sub_mailbox = "$mb_top.$i";
214 last if exists $mailboxes->{$sub_mailbox};
215 $mailboxes->{$sub_mailbox} = $ibx;
216 push @created, $sub_mailbox;
218 return unless @created;
219 my $l = $imapd->{inboxlist} or return;
220 push @$l, map { qq[* LIST (\\HasNoChildren) "." $_\r\n] } @created;
223 sub inbox_lookup ($$) {
224 my ($self, $mailbox) = @_;
225 my ($ibx, $exists, $uidnext);
226 if ($mailbox =~ /\A(.+)\.([0-9]+)\z/) {
227 # old mail: inbox.comp.foo.$uid_block_idx
228 my ($mb_top, $uid_min) = ($1, $2 * UID_BLOCK + 1);
230 $ibx = $self->{imapd}->{mailboxes}->{lc $mailbox} or return;
231 $exists = $ibx->mm->max // 0;
232 $self->{uid_min} = $uid_min;
233 ensure_ranges_exist($self->{imapd}, $ibx, $exists);
234 my $uid_end = $uid_min + UID_BLOCK - 1;
235 $exists = $uid_end if $exists > $uid_end;
236 $uidnext = $exists + 1;
237 } else { # check for dummy inboxes
238 $ibx = $self->{imapd}->{mailboxes}->{lc $mailbox} or return;
239 delete $self->{uid_min};
243 ($ibx, $exists, $uidnext);
246 sub cmd_examine ($$$) {
247 my ($self, $tag, $mailbox) = @_;
248 my ($ibx, $exists, $uidnext) = inbox_lookup($self, $mailbox);
249 return "$tag NO Mailbox doesn't exist: $mailbox\r\n" if !$ibx;
251 # XXX: do we need this? RFC 5162/7162
252 my $ret = $self->{ibx} ? "* OK [CLOSED] previous closed\r\n" : '';
258 * OK [PERMANENTFLAGS ()] Read-only mailbox\r
259 * OK [UNSEEN $exists]\r
260 * OK [UIDNEXT $uidnext]\r
261 * OK [UIDVALIDITY $ibx->{uidvalidity}]\r
262 $tag OK [READ-ONLY] EXAMINE/SELECT done\r
270 } elsif ($v =~ /[{"\r\n%*\\\[]/) { # literal string
271 '{' . length($v) . "}\r\n" . $v;
272 } else { # quoted string
277 sub addr_envelope ($$;$) {
278 my ($eml, $x, $y) = @_;
279 my $v = $eml->header_raw($x) //
280 ($y ? $eml->header_raw($y) : undef) // return 'NIL';
282 my @x = $Address->parse($v) or return 'NIL';
284 map { '(' . join(' ',
285 _esc($_->name), 'NIL',
286 _esc($_->user), _esc($_->host)
292 sub eml_envelope ($) {
295 _esc($eml->header_raw('Date')),
296 _esc($eml->header_raw('Subject')),
297 addr_envelope($eml, 'From'),
298 addr_envelope($eml, 'Sender', 'From'),
299 addr_envelope($eml, 'Reply-To', 'From'),
300 addr_envelope($eml, 'To'),
301 addr_envelope($eml, 'Cc'),
302 addr_envelope($eml, 'Bcc'),
303 _esc($eml->header_raw('In-Reply-To')),
304 _esc($eml->header_raw('Message-ID')),
310 if ($hash && scalar keys %$hash) {
311 $hash = [ %$hash ]; # flatten hash into 1-dimensional array
312 '(' . join(' ', map { _esc($_) } @$hash) . ')';
318 sub body_disposition ($) {
320 my $cd = $eml->header_raw('Content-Disposition') or return 'NIL';
321 $cd = parse_content_disposition($cd);
322 my $buf = '('._esc($cd->{type});
323 $buf .= ' ' . _esc_hash(delete $cd->{attributes});
327 sub body_leaf ($$;$) {
328 my ($eml, $structure, $hold) = @_;
330 $eml->{is_submsg} and # parent was a message/(rfc822|news|global)
331 $buf .= eml_envelope($eml). ' ';
333 $buf .= '('._esc($ct->{type}).' ';
334 $buf .= _esc($ct->{subtype});
335 $buf .= ' ' . _esc_hash(delete $ct->{attributes});
336 $buf .= ' ' . _esc($eml->header_raw('Content-ID'));
337 $buf .= ' ' . _esc($eml->header_raw('Content-Description'));
338 my $cte = $eml->header_raw('Content-Transfer-Encoding') // '7bit';
339 $buf .= ' ' . _esc($cte);
340 $buf .= ' ' . $eml->{imap_body_len};
341 $buf .= ' '.($eml->body_raw =~ tr/\n/\n/) if lc($ct->{type}) eq 'text';
343 # for message/(rfc822|global|news), $hold[0] should have envelope
344 $buf .= ' ' . (@$hold ? join('', @$hold) : 'NIL') if $hold;
347 $buf .= ' '._esc($eml->header_raw('Content-MD5'));
348 $buf .= ' '. body_disposition($eml);
349 $buf .= ' '._esc($eml->header_raw('Content-Language'));
350 $buf .= ' '._esc($eml->header_raw('Content-Location'));
355 sub body_parent ($$$) {
356 my ($eml, $structure, $hold) = @_;
358 my $type = lc($ct->{type});
359 if ($type eq 'multipart') {
361 $buf .= @$hold ? join('', @$hold) : 'NIL';
362 $buf .= ' '._esc($ct->{subtype});
364 $buf .= ' '._esc_hash(delete $ct->{attributes});
365 $buf .= ' '.body_disposition($eml);
366 $buf .= ' '._esc($eml->header_raw('Content-Language'));
367 $buf .= ' '._esc($eml->header_raw('Content-Location'));
371 } else { # message/(rfc822|global|news)
372 @$hold = (body_leaf($eml, $structure, $hold));
376 # this is gross, but we need to process the parent part AFTER
377 # the child parts are done
378 sub bodystructure_prep {
380 my ($eml, $depth) = @$p; # ignore idx
381 # set length here, as $eml->{bdy} gets deleted for message/rfc822
382 $eml->{imap_body_len} = length($eml->body_raw);
383 push @$q, $eml, $depth;
386 # for FETCH BODY and FETCH BODYSTRUCTURE
387 sub fetch_body ($;$) {
388 my ($eml, $structure) = @_;
390 $eml->each_part(\&bodystructure_prep, \@q, 0, 1);
394 my ($part, $depth) = splice(@q, -2);
395 my $is_mp_parent = $depth == ($cur_depth - 1);
399 body_parent($part, $structure, \@hold);
401 unshift @hold, body_leaf($part, $structure);
407 sub requeue_once ($) {
409 # COMPRESS users all share the same DEFLATE context.
410 # Flush it here to ensure clients don't see
414 # no recursion, schedule another call ASAP,
415 # but only after all pending writes are done.
417 my $new_size = push(@{$self->{wbuf}}, \&long_step);
419 # wbuf may be populated by $cb, no need to rearm if so:
420 $self->requeue if $new_size == 1;
423 sub uid_fetch_cb { # called by git->cat_async via git_async_cat
424 my ($bref, $oid, $type, $size, $fetch_m_arg) = @_;
425 my ($self, undef, $msgs, undef, $ops, $partial) = @$fetch_m_arg;
426 my $smsg = shift @$msgs or die 'BUG: no smsg';
427 if (!defined($oid)) {
428 # it's possible to have TOCTOU if an admin runs
429 # public-inbox-(edit|purge), just move onto the next message
430 return requeue_once($self);
432 $smsg->{blob} eq $oid or die "BUG: $smsg->{blob} != $oid";
434 $$bref =~ s/(?<!\r)\n/\r\n/sg; # make strict clients happy
436 # fixup old bug from import (pre-a0c07cba0e5d8b6a)
437 $$bref =~ s/\A[\r\n]*From [^\r\n]*\r\n//s;
438 $self->msg_more("* $smsg->{num} FETCH (UID $smsg->{num}");
440 for (my $i = 0; $i < @$ops;) {
441 my $k = $ops->[$i++];
442 $ops->[$i++]->($self, $k, $smsg, $bref, $eml);
444 partial_emit($self, $partial, $eml) if $partial;
445 $self->msg_more(")\r\n");
450 my ($self, $k, undef, $bref) = @_;
451 $self->msg_more(" $k {" . length($$bref)."}\r\n");
452 $self->msg_more($$bref);
455 # Mail::IMAPClient::message_string cares about this by default
456 # (->Ignoresizeerrors attribute)
457 sub emit_rfc822_size {
458 my ($self, $k, undef, $bref) = @_;
459 $self->msg_more(' RFC822.SIZE ' . length($$bref));
462 sub emit_internaldate {
463 my ($self, undef, $smsg) = @_;
464 $self->msg_more(' INTERNALDATE "'.$smsg->internaldate.'"');
467 sub emit_flags { $_[0]->msg_more(' FLAGS ()') }
470 my ($self, undef, undef, undef, $eml) = @_;
471 $self->msg_more(' ENVELOPE '.eml_envelope($eml));
474 sub emit_rfc822_header {
475 my ($self, $k, undef, undef, $eml) = @_;
476 $self->msg_more(" $k {".length(${$eml->{hdr}})."}\r\n");
477 $self->msg_more(${$eml->{hdr}});
480 # n.b. this is sorted to be after any emit_eml_new ops
481 sub emit_rfc822_text {
482 my ($self, $k, undef, $bref) = @_;
483 $self->msg_more(" $k {".length($$bref)."}\r\n");
484 $self->msg_more($$bref);
487 sub emit_bodystructure {
488 my ($self, undef, undef, undef, $eml) = @_;
489 $self->msg_more(' BODYSTRUCTURE '.fetch_body($eml, 1));
493 my ($self, undef, undef, undef, $eml) = @_;
494 $self->msg_more(' BODY '.fetch_body($eml));
497 # set $eml once ($_[4] == $eml, $_[3] == $bref)
498 sub op_eml_new { $_[4] = PublicInbox::Eml->new($_[3]) }
500 sub uid_clamp ($$$) {
501 my ($self, $beg, $end) = @_;
502 my $uid_min = $self->{uid_min} or return;
503 my $uid_end = $uid_min + UID_BLOCK - 1;
504 $$beg = $uid_min if $$beg < $uid_min;
505 $$end = $uid_end if $$end > $uid_end;
508 sub range_step ($$) {
509 my ($self, $range_csv) = @_;
510 my ($beg, $end, $range);
511 if ($$range_csv =~ s/\A([^,]+),//) {
514 $range = $$range_csv;
517 if ($range =~ /\A([0-9]+):([0-9]+)\z/) {
518 ($beg, $end) = ($1 + 0, $2 + 0);
519 } elsif ($range =~ /\A([0-9]+):\*\z/) {
521 $end = $self->{ibx}->mm->max // 0;
522 my $uid_end = ($self->{uid_min} // 1) - 1 + UID_BLOCK;
523 $end = $uid_end if $end > $uid_end;
524 $beg = $end if $beg > $end;
525 } elsif ($range =~ /\A[0-9]+\z/) {
526 $beg = $end = $range + 0;
529 return 'BAD fetch range';
531 uid_clamp($self, \$beg, \$end) if defined($range);
532 [ $beg, $end, $$range_csv ];
535 sub refill_range ($$$) {
536 my ($self, $msgs, $range_info) = @_;
537 my ($beg, $end, $range_csv) = @$range_info;
538 if (scalar(@$msgs = @{$self->{ibx}->over->query_xover($beg, $end)})) {
539 $range_info->[0] = $msgs->[-1]->{num} + 1;
542 return 'OK Fetch done' if !$range_csv;
543 my $next_range = range_step($self, \$range_csv);
544 return $next_range if !ref($next_range); # error
545 @$range_info = @$next_range;
546 undef; # keep looping
549 sub uid_fetch_m { # long_response
550 my ($self, $tag, $msgs, $range_info) = @_; # \@ops, \@partial
551 while (!@$msgs) { # rare
552 if (my $end = refill_range($self, $msgs, $range_info)) {
553 $self->write(\"$tag $end\r\n");
557 git_async_cat($self->{ibx}->git, $msgs->[0]->{blob},
558 \&uid_fetch_cb, \@_);
561 sub cmd_status ($$$;@) {
562 my ($self, $tag, $mailbox, @items) = @_;
563 return "$tag BAD no items\r\n" if !scalar(@items);
564 ($items[0] !~ s/\A\(//s || $items[-1] !~ s/\)\z//s) and
565 return "$tag BAD invalid args\r\n";
566 my ($ibx, $exists, $uidnext) = inbox_lookup($self, $mailbox);
567 return "$tag NO Mailbox doesn't exist: $mailbox\r\n" if !$ibx;
569 for my $it (@items) {
572 if ($it =~ /\A(?:MESSAGES|UNSEEN|RECENT)\z/) {
574 } elsif ($it eq 'UIDNEXT') {
576 } elsif ($it eq 'UIDVALIDITY') {
577 push @it, $ibx->{uidvalidity};
579 return "$tag BAD invalid item\r\n";
582 return "$tag BAD no items\r\n" if !@it;
583 "* STATUS $mailbox (".join(' ', @it).")\r\n" .
584 "$tag OK Status done\r\n";
587 my %patmap = ('*' => '.*', '%' => '[^\.]*');
588 sub cmd_list ($$$$) {
589 my ($self, $tag, $refname, $wildcard) = @_;
590 my $l = $self->{imapd}->{inboxlist};
591 if ($refname eq '' && $wildcard eq '') {
592 # request for hierarchy delimiter
593 $l = [ qq[* LIST (\\Noselect) "." ""\r\n] ];
594 } elsif ($refname ne '' || $wildcard ne '*') {
595 $wildcard = lc $wildcard;
596 $wildcard =~ s!([^a-z0-9_])!$patmap{$1} // "\Q$1"!eg;
597 $l = [ grep(/ \Q$refname\E$wildcard\r\n\z/s, @$l) ];
599 \(join('', @$l, "$tag OK List done\r\n"));
602 sub cmd_lsub ($$$$) {
603 my (undef, $tag) = @_; # same args as cmd_list
604 "$tag OK Lsub done\r\n";
607 sub eml_index_offs_i { # PublicInbox::Eml::each_part callback
609 my ($eml, undef, $idx) = @$p;
610 if ($idx && lc($eml->ct->{type}) eq 'multipart') {
611 $eml->{imap_bdy} = $eml->{bdy} // \'';
613 $all->{$idx} = $eml; # $idx => Eml
616 # prepares an index for BODY[$SECTION_IDX] fetches
617 sub eml_body_idx ($$) {
618 my ($eml, $section_idx) = @_;
619 my $idx = $eml->{imap_all_parts} //= do {
621 $eml->each_part(\&eml_index_offs_i, $all, 0, 1);
622 # top-level of multipart, BODY[0] not allowed (nz-number)
626 $idx->{$section_idx};
629 # BODY[($SECTION_IDX)?(.$SECTION_NAME)?]<$offset.$bytes>
631 my ($eml, $section_idx, $section_name) = @_;
632 if (defined $section_idx) {
633 $eml = eml_body_idx($eml, $section_idx) or return;
635 if (defined $section_name) {
636 if ($section_name eq 'MIME') {
637 # RFC 3501 6.4.5 states:
638 # The MIME part specifier MUST be prefixed
639 # by one or more numeric part specifiers
640 return unless defined $section_idx;
641 return $eml->header_obj->as_string . "\r\n";
643 my $bdy = $eml->{bdy} // $eml->{imap_bdy} // \'';
644 $eml = PublicInbox::Eml->new($$bdy);
645 if ($section_name eq 'TEXT') {
646 return $eml->body_raw;
647 } elsif ($section_name eq 'HEADER') {
648 return $eml->header_obj->as_string . "\r\n";
650 die "BUG: bad section_name=$section_name";
653 ${$eml->{bdy} // $eml->{imap_bdy} // \''};
656 # similar to what's in PublicInbox::Eml::re_memo, but doesn't memoize
657 # to avoid OOM with malicious users
658 sub hdrs_regexp ($) {
660 my $names = join('|', map { "\Q$_" } split(/[ \t]+/, $hdrs));
661 qr/^(?:$names):[ \t]*[^\n]*\r?\n # 1st line
662 # continuation lines:
663 (?:[^:\n]*?[ \t]+[^\n]*\r?\n)*
667 # BODY[($SECTION_IDX.)?HEADER.FIELDS.NOT ($HDRS)]<$offset.$bytes>
668 sub partial_hdr_not {
669 my ($eml, $section_idx, $hdrs_re) = @_;
670 if (defined $section_idx) {
671 $eml = eml_body_idx($eml, $section_idx) or return;
673 my $str = $eml->header_obj->as_string;
674 $str =~ s/$hdrs_re//g;
678 # BODY[($SECTION_IDX.)?HEADER.FIELDS ($HDRS)]<$offset.$bytes>
679 sub partial_hdr_get {
680 my ($eml, $section_idx, $hdrs_re) = @_;
681 if (defined $section_idx) {
682 $eml = eml_body_idx($eml, $section_idx) or return;
684 my $str = $eml->header_obj->as_string;
685 join('', ($str =~ m/($hdrs_re)/g), "\r\n");
688 sub partial_prepare ($$$) {
689 my ($partial, $want, $att) = @_;
691 # recombine [ "BODY[1.HEADER.FIELDS", "(foo", "bar)]" ]
692 # back to: "BODY[1.HEADER.FIELDS (foo bar)]"
693 return unless $att =~ /\ABODY\[/s;
694 until (rindex($att, ']') >= 0) {
695 my $next = shift @$want or return;
696 $att .= ' ' . uc($next);
698 if ($att =~ /\ABODY\[([0-9]+(?:\.[0-9]+)*)? # 1 - section_idx
699 (?:\.(HEADER|MIME|TEXT))? # 2 - section_name
700 \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 3, 4
701 $partial->{$att} = [ \&partial_body, $1, $2, $3, $4 ];
702 } elsif ($att =~ /\ABODY\[(?:([0-9]+(?:\.[0-9]+)*)\.)? # 1 - section_idx
703 (?:HEADER\.FIELDS(\.NOT)?)\x20 # 2
704 \(([A-Z0-9\-\x20]+)\) # 3 - hdrs
705 \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 4 5
706 my $tmp = $partial->{$att} = [ $2 ? \&partial_hdr_not
709 $tmp->[2] = hdrs_regexp($3);
715 sub partial_emit ($$$) {
716 my ($self, $partial, $eml) = @_;
718 my ($k, $cb, @args) = @$_;
719 my ($offset, $len) = splice(@args, -2);
720 # $cb is partial_body|partial_hdr_get|partial_hdr_not
721 my $str = $cb->($eml, @args) // '';
722 if (defined $offset) {
724 $str = substr($str, $offset, $len);
725 $k =~ s/\.$len>\z/>/ or warn
726 "BUG: unable to remove `.$len>' from `$k'";
728 $str = substr($str, $offset);
734 $self->msg_more(" $k {$len}\r\n");
735 $self->msg_more($str);
739 sub fetch_compile ($) {
741 if ($want->[0] =~ s/\A\(//s) {
742 $want->[-1] =~ s/\)\z//s or return 'BAD no rparen';
744 my (%partial, %seen, @op);
746 while (defined(my $att = shift @$want)) {
748 next if $att eq 'UID'; # always returned
749 $att =~ s/\ABODY\.PEEK\[/BODY\[/; # we're read-only
750 my $x = $FETCH_ATT{$att};
752 while (my ($k, $fl_cb) = each %$x) {
754 $need |= $fl_cb->[0];
756 # insert a special op to convert $bref to $eml
757 # the first time we need it
758 if ($need == NEED_EML && !$seen{$need}++) {
759 push @op, $OP_EML_NEW;
761 # $fl_cb = [ flags, \&emit_foo ]
762 push @op, [ @$fl_cb , $k ];
764 } elsif (!partial_prepare(\%partial, $want, $att)) {
765 return "BAD param: $att";
770 # stabilize partial order for consistency and ease-of-debugging:
771 if (scalar keys %partial) {
773 push @op, $OP_EML_NEW if !$seen{$need}++;
774 $r[2] = [ map { [ $_, @{$partial{$_}} ] } sort keys %partial ];
779 # r[1] = [ $key1, $cb1, $key2, $cb2, ... ]
780 use sort 'stable'; # makes output more consistent
781 $r[1] = [ map { ($_->[2], $_->[1]) } sort { $a->[0] <=> $b->[0] } @op ];
785 sub cmd_uid_fetch ($$$;@) {
786 my ($self, $tag, $range_csv, @want) = @_;
787 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
788 my ($need, $ops, $partial) = fetch_compile(\@want);
789 return "$tag $need\r\n" unless $ops;
791 $range_csv = 'bad' if $range_csv !~ $valid_range;
792 my $range_info = range_step($self, \$range_csv);
793 return "$tag $range_info\r\n" if !ref($range_info);
795 long_response($self, \&uid_fetch_m,
796 $tag, [], $range_info, $ops, $partial);
799 sub parse_date ($) { # 02-Oct-1993
800 my ($date_text) = @_;
801 my ($dd, $mon, $yyyy) = split(/-/, $_[0], 3);
802 defined($yyyy) or return;
803 my $mm = $MoY{$mon} // return;
804 $dd =~ /\A[0123]?[0-9]\z/ or return;
805 $yyyy =~ /\A[0-9]{4,}\z/ or return; # Y10K-compatible!
806 timegm(0, 0, 0, $dd, $mm, $yyyy);
809 sub uid_search_uid_range { # long_response
810 my ($self, $tag, $beg, $end, $sql) = @_;
811 my $uids = $self->{ibx}->over->uid_range($$beg, $end, $sql);
813 $$beg = $uids->[-1] + 1;
814 $self->msg_more(join(' ', '', @$uids));
816 $self->write(\"\r\n$tag OK Search done\r\n");
822 my ($q, $k, $d) = @_;
826 if ($k eq 'SENTON') {
827 my $end = $d + 86399; # no leap day...
828 my $da = strftime('%Y%m%d%H%M%S', gmtime($d));
829 my $db = strftime('%Y%m%d%H%M%S', gmtime($end));
830 $q->{xap} .= " dt:$da..$db";
831 $$sql .= " AND ds >= $d AND ds <= $end" if defined($sql);
832 } elsif ($k eq 'SENTBEFORE') {
833 $q->{xap} .= ' d:..'.strftime('%Y%m%d', gmtime($d));
834 $$sql .= " AND ds <= $d" if defined($sql);
835 } elsif ($k eq 'SENTSINCE') {
836 $q->{xap} .= ' d:'.strftime('%Y%m%d', gmtime($d)).'..';
837 $$sql .= " AND ds >= $d" if defined($sql);
839 # INTERNALDATE (Received)
840 } elsif ($k eq 'ON') {
841 my $end = $d + 86399; # no leap day...
842 $q->{xap} .= " ts:$d..$end";
843 $$sql .= " AND ts >= $d AND ts <= $end" if defined($sql);
844 } elsif ($k eq 'BEFORE') {
845 $q->{xap} .= " ts:..$d";
846 $$sql .= " AND ts <= $d" if defined($sql);
847 } elsif ($k eq 'SINCE') {
848 $q->{xap} .= " ts:$d..";
849 $$sql .= " AND ts >= $d" if defined($sql);
851 die "BUG: $k not recognized";
855 # IMAP to Xapian search key mapping
860 TEXT => '', # n.b. does not include all headers
863 # BCC => 'bcc:', # TODO
864 # KEYWORD # TODO ? dfpre,dfpost,...
868 my ($self, $rest) = @_;
869 if (uc($rest->[0]) eq 'CHARSET') {
871 defined(my $c = shift @$rest) or return 'BAD missing charset';
872 $c =~ /\A(?:UTF-8|US-ASCII)\z/ or return 'NO [BADCHARSET]';
875 my $sql = ''; # date conditions, {sql} deleted if Xapian is needed
876 my $q = { xap => '', sql => \$sql };
878 my $k = uc(shift @$rest);
880 next if $k =~ /\A(?:ALL|RECENT|UNSEEN|NEW)\z/;
881 next if $k eq 'AND'; # the default, until we support OR
882 if ($k =~ $valid_range) { # sequence numbers == UIDs
883 push @{$q->{uid}}, $k;
884 } elsif ($k eq 'UID') {
885 $k = shift(@$rest) // '';
886 $k =~ $valid_range or return 'BAD UID range';
887 push @{$q->{uid}}, $k;
888 } elsif ($k =~ /\A(?:SENT)?(?:SINCE|ON|BEFORE)\z/) {
889 my $d = parse_date(shift(@$rest) // '');
890 defined $d or return "BAD $k date format";
891 date_search($q, $k, $d);
892 } elsif ($k =~ /\A(?:SMALLER|LARGER)\z/) {
893 delete $q->{sql}; # can't use over.sqlite3
894 my $bytes = shift(@$rest) // '';
895 $bytes =~ /\A[0-9]+\z/ or return "BAD $k not a number";
896 $q->{xap} .= ' bytes:' . ($k eq 'SMALLER' ?
899 } elsif (defined(my $xk = $I2X{$k})) {
900 delete $q->{sql}; # can't use over.sqlite3
901 my $arg = shift @$rest;
902 defined($arg) or return "BAD $k no arg";
904 # Xapian can't handle [*"] in probabilistic terms
906 $q->{xap} .= qq[ $xk:"$arg"];
908 # TODO: parentheses, OR, NOT ...
909 return "BAD $k not supported (yet?)";
913 # favor using over.sqlite3 if possible, since Xapian is optional
914 if (exists $q->{sql}) {
916 delete($q->{sql}) if $sql eq '';
917 } elsif (!$self->{ibx}->search) {
918 return 'BAD Xapian not configured for mailbox';
921 if (my $uid = $q->{uid}) {
922 ((@$uid > 1) || $uid->[0] =~ /,/) and
923 return 'BAD multiple ranges not supported, yet';
924 ($q->{sql} // $q->{xap}) and
925 return 'BAD ranges and queries do not mix, yet';
926 $q->{uid} = join(',', @$uid); # TODO: multiple ranges
931 sub cmd_uid_search ($$$;) {
932 my ($self, $tag) = splice(@_, 0, 2);
933 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
934 my $q = parse_query($self, \@_);
935 return "$tag $q\r\n" if !ref($q);
936 my $sql = delete $q->{sql};
938 if (!scalar(keys %$q)) {
939 $self->msg_more('* SEARCH');
940 my $beg = $self->{uid_min} // 1;
941 my $end = $ibx->mm->max;
942 uid_clamp($self, \$beg, \$end);
943 long_response($self, \&uid_search_uid_range,
944 $tag, \$beg, $end, $sql);
945 } elsif (my $uid = $q->{uid}) {
946 if ($uid =~ /\A([0-9]+):([0-9]+|\*)\z/s) {
947 my ($beg, $end) = ($1, $2);
948 $end = $ibx->mm->max if $end eq '*';
949 uid_clamp($self, \$beg, \$end);
950 $self->msg_more('* SEARCH');
951 long_response($self, \&uid_search_uid_range,
952 $tag, \$beg, $end, $sql);
953 } elsif ($uid =~ /\A[0-9]+\z/s) {
954 $uid = $ibx->over->get_art($uid) ? " $uid" : '';
955 "* SEARCH$uid\r\n$tag OK Search done\r\n";
957 "$tag BAD Error\r\n";
960 "$tag BAD Error\r\n";
964 sub args_ok ($$) { # duplicated from PublicInbox::NNTP
965 my ($cb, $argc) = @_;
966 my $tot = prototype $cb;
967 my ($nreq, undef) = split(';', $tot);
968 $nreq = ($nreq =~ tr/$//) - 1;
969 $tot = ($tot =~ tr/$//) - 1;
970 ($argc <= $tot && $argc >= $nreq);
973 # returns 1 if we can continue, 0 if not due to buffered writes or disconnect
974 sub process_line ($$) {
976 my ($tag, $req, @args) = parse_line('[ \t]+', 0, $l);
977 pop(@args) if (@args && !defined($args[-1]));
978 if (@args && uc($req) eq 'UID') {
979 $req .= "_".(shift @args);
982 if (my $cmd = $self->can('cmd_'.lc($req // ''))) {
983 defined($self->{-idle_tag}) ?
984 "$self->{-idle_tag} BAD expected DONE\r\n" :
985 $cmd->($self, $tag, @args);
986 } elsif (uc($tag // '') eq 'DONE' && !defined($req)) {
987 cmd_done($self, $tag);
988 } else { # this is weird
989 auth_challenge_ok($self) //
991 ' BAD Error in IMAP command '.
993 ": Unknown command\r\n";
997 if ($err && $self->{sock}) {
999 err($self, 'error from: %s (%s)', $l, $err);
1001 $res = "$tag BAD program fault - command not performed\r\n";
1003 return 0 unless defined $res;
1009 # wbuf is unset or empty, here; {long} may add to it
1010 my ($fd, $cb, $t0, @args) = @{$self->{long_cb}};
1011 my $more = eval { $cb->($self, @args) };
1012 if ($@ || !$self->{sock}) { # something bad happened...
1013 delete $self->{long_cb};
1014 my $elapsed = now() - $t0;
1017 "%s during long response[$fd] - %0.6f",
1020 out($self, " deferred[$fd] aborted - %0.6f", $elapsed);
1022 } elsif ($more) { # $self->{wbuf}:
1023 $self->update_idle_time;
1025 # control passed to $more may be a GitAsyncCat object
1026 requeue_once($self) if !ref($more);
1027 } else { # all done!
1028 delete $self->{long_cb};
1029 my $elapsed = now() - $t0;
1030 my $fd = fileno($self->{sock});
1031 out($self, " deferred[$fd] done - %0.6f", $elapsed);
1032 my $wbuf = $self->{wbuf}; # do NOT autovivify
1034 $self->requeue unless $wbuf && @$wbuf;
1039 my ($self, $fmt, @args) = @_;
1040 printf { $self->{imapd}->{err} } $fmt."\n", @args;
1044 my ($self, $fmt, @args) = @_;
1045 printf { $self->{imapd}->{out} } $fmt."\n", @args;
1048 sub long_response ($$;@) {
1049 my ($self, $cb, @args) = @_; # cb returns true if more, false if done
1051 my $sock = $self->{sock} or return;
1052 # make sure we disable reading during a long response,
1053 # clients should not be sending us stuff and making us do more
1054 # work while we are stream a response to them
1055 $self->{long_cb} = [ fileno($sock), $cb, now(), @args ];
1056 long_step($self); # kick off!
1060 # callback used by PublicInbox::DS for any (e)poll (in/out/hup/err)
1064 return unless $self->flush_write && $self->{sock} && !$self->{long_cb};
1066 $self->update_idle_time;
1067 # only read more requests if we've drained the write buffer,
1068 # otherwise we can be buffering infinitely w/o backpressure
1070 my $rbuf = $self->{rbuf} // \(my $x = '');
1071 my $line = index($$rbuf, "\n");
1073 return $self->close if length($$rbuf) >= LINE_MAX;
1074 $self->do_read($rbuf, LINE_MAX, length($$rbuf)) or return;
1075 $line = index($$rbuf, "\n");
1077 $line = substr($$rbuf, 0, $line + 1, '');
1078 $line =~ s/\r?\n\z//s;
1079 return $self->close if $line =~ /[[:cntrl:]]/s;
1081 my $fd = fileno($self->{sock});
1082 my $r = eval { process_line($self, $line) };
1083 my $pending = $self->{wbuf} ? ' pending' : '';
1084 out($self, "[$fd] %s - %0.6f$pending - $r", $line, now() - $t0);
1086 return $self->close if $r < 0;
1087 $self->rbuf_idle($rbuf);
1088 $self->update_idle_time;
1090 # maybe there's more pipelined data, or we'll have
1091 # to register it for socket-readiness notifications
1092 $self->requeue unless $pending;
1095 sub compressed { undef }
1097 sub zflush {} # overridden by IMAPdeflate
1100 sub cmd_compress ($$$) {
1101 my ($self, $tag, $alg) = @_;
1102 return "$tag BAD DEFLATE only\r\n" if uc($alg) ne "DEFLATE";
1103 return "$tag BAD COMPRESS active\r\n" if $self->compressed;
1105 # CRIME made TLS compression obsolete
1106 # return "$tag NO [COMPRESSIONACTIVE]\r\n" if $self->tls_compressed;
1108 PublicInbox::IMAPdeflate->enable($self, $tag);
1113 sub cmd_starttls ($$) {
1114 my ($self, $tag) = @_;
1115 my $sock = $self->{sock} or return;
1116 if ($sock->can('stop_SSL') || $self->compressed) {
1117 return "$tag BAD TLS or compression already enabled\r\n";
1119 my $opt = $self->{imapd}->{accept_tls} or
1120 return "$tag BAD can not initiate TLS negotiation\r\n";
1121 $self->write(\"$tag OK begin TLS negotiation now\r\n");
1122 $self->{sock} = IO::Socket::SSL->start_SSL($sock, %$opt);
1123 $self->requeue if PublicInbox::DS::accept_tls_step($self);
1127 # for graceful shutdown in PublicInbox::Daemon:
1129 my ($self, $now) = @_;
1130 ($self->{rbuf} || $self->{wbuf} || $self->not_idle_long($now));
1135 if (my $ibx = delete $self->{ibx}) {
1136 if (my $sock = $self->{sock}) {;
1137 $ibx->unsubscribe_unlock(fileno($sock));
1140 $self->SUPER::close; # PublicInbox::DS::close
1143 # we're read-only, so SELECT and EXAMINE do the same thing
1145 *cmd_select = \&cmd_examine;
1146 *cmd_fetch = \&cmd_uid_fetch;