]> Sergey Matveev's repositories - public-inbox.git/blobdiff - lib/PublicInbox/IMAP.pm
imap: SEARCH: clamp results to the 50K UID range
[public-inbox.git] / lib / PublicInbox / IMAP.pm
index 8c6fa7b62c957a96d190d62d8717788253e7b0d5..f9af530aa191546519c0c9aa982d7345130f9cd6 100644 (file)
@@ -24,6 +24,8 @@ use PublicInbox::Syscall qw(EPOLLIN EPOLLONESHOT);
 use PublicInbox::GitAsyncCat;
 use Text::ParseWords qw(parse_line);
 use Errno qw(EAGAIN);
+use Time::Local qw(timegm);
+use POSIX qw(strftime);
 
 my $Address;
 for my $mod (qw(Email::Address::XS Mail::Address)) {
@@ -67,6 +69,10 @@ for my $att (keys %FETCH_ATT) {
 my $valid_range = '[0-9]+|[0-9]+:[0-9]+|[0-9]+:\*';
 $valid_range = qr/\A(?:$valid_range)(?:,(?:$valid_range))*\z/;
 
+my @MoY = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
+my %MoY;
+@MoY{@MoY} = (0..11);
+
 sub greet ($) {
        my ($self) = @_;
        my $capa = capa($self);
@@ -208,42 +214,43 @@ sub ensure_ranges_exist ($$$) {
        push @$l, map { qq[* LIST (\\HasNoChildren) "." $_\r\n] } @created;
 }
 
-sub cmd_examine ($$$) {
-       my ($self, $tag, $mailbox) = @_;
-       my ($ibx, $mm, $max);
-
+sub inbox_lookup ($$) {
+       my ($self, $mailbox) = @_;
+       my ($ibx, $exists, $uidnext);
        if ($mailbox =~ /\A(.+)\.([0-9]+)\z/) {
                # old mail: inbox.comp.foo.$uid_block_idx
                my ($mb_top, $uid_min) = ($1, $2 * UID_BLOCK + 1);
 
-               $ibx = $self->{imapd}->{mailboxes}->{lc $mailbox} or
-                       return "$tag NO Mailbox doesn't exist: $mailbox\r\n";
-
-               $mm = $ibx->mm;
-               $max = $mm->max // 0;
+               $ibx = $self->{imapd}->{mailboxes}->{lc $mailbox} or return;
+               $exists = $ibx->mm->max // 0;
                $self->{uid_min} = $uid_min;
-               ensure_ranges_exist($self->{imapd}, $ibx, $max);
+               ensure_ranges_exist($self->{imapd}, $ibx, $exists);
                my $uid_end = $uid_min + UID_BLOCK - 1;
-               $max = $uid_end if $max > $uid_end;
+               $exists = $uid_end if $exists > $uid_end;
+               $uidnext = $exists + 1;
        } else { # check for dummy inboxes
-               $ibx = $self->{imapd}->{mailboxes}->{lc $mailbox} or
-                       return "$tag NO Mailbox doesn't exist: $mailbox\r\n";
+               $ibx = $self->{imapd}->{mailboxes}->{lc $mailbox} or return;
                delete $self->{uid_min};
-               $max = 0;
-               $mm = $ibx->mm;
+               $exists = 0;
+               $uidnext = 1;
        }
+       ($ibx, $exists, $uidnext);
+}
 
-       my $uidnext = $max + 1;
+sub cmd_examine ($$$) {
+       my ($self, $tag, $mailbox) = @_;
+       my ($ibx, $exists, $uidnext) = inbox_lookup($self, $mailbox);
+       return "$tag NO Mailbox doesn't exist: $mailbox\r\n" if !$ibx;
 
        # XXX: do we need this? RFC 5162/7162
        my $ret = $self->{ibx} ? "* OK [CLOSED] previous closed\r\n" : '';
        $self->{ibx} = $ibx;
        $ret .= <<EOF;
-* $max EXISTS\r
-* $max RECENT\r
+* $exists EXISTS\r
+* $exists RECENT\r
 * FLAGS (\\Seen)\r
 * OK [PERMANENTFLAGS ()] Read-only mailbox\r
-* OK [UNSEEN $max]\r
+* OK [UNSEEN $exists]\r
 * OK [UIDNEXT $uidnext]\r
 * OK [UIDVALIDITY $ibx->{uidvalidity}]\r
 $tag OK [READ-ONLY] EXAMINE/SELECT done\r
@@ -480,6 +487,14 @@ sub uid_fetch_cb { # called by git->cat_async via git_async_cat
        requeue_once($self);
 }
 
+sub uid_clamp ($$$) {
+       my ($self, $beg, $end) = @_;
+       my $uid_min = $self->{uid_min} or return;
+       my $uid_end = $uid_min + UID_BLOCK - 1;
+       $$beg = $uid_min if $$beg < $uid_min;
+       $$end = $uid_end if $$end > $uid_end;
+}
+
 sub range_step ($$) {
        my ($self, $range_csv) = @_;
        my ($beg, $end, $range);
@@ -494,6 +509,8 @@ sub range_step ($$) {
        } elsif ($range =~ /\A([0-9]+):\*\z/) {
                $beg = $1 + 0;
                $end = $self->{ibx}->mm->max // 0;
+               my $uid_end = ($self->{uid_min} // 1) - 1 + UID_BLOCK;
+               $end = $uid_end if $end > $uid_end;
                $beg = $end if $beg > $end;
        } elsif ($range =~ /\A[0-9]+\z/) {
                $beg = $end = $range + 0;
@@ -501,11 +518,7 @@ sub range_step ($$) {
        } else {
                return 'BAD fetch range';
        }
-       if (defined($range) && (my $uid_min = $self->{uid_min})) {
-               my $uid_end = $uid_min + UID_BLOCK - 1;
-               $beg = $uid_min if $beg < $uid_min;
-               $end = $uid_end if $end > $uid_end;
-       }
+       uid_clamp($self, \$beg, \$end) if defined($range);
        [ $beg, $end, $$range_csv ];
 }
 
@@ -537,23 +550,21 @@ sub uid_fetch_m { # long_response
 
 sub cmd_status ($$$;@) {
        my ($self, $tag, $mailbox, @items) = @_;
-       my $ibx = $self->{imapd}->{mailboxes}->{lc $mailbox} or
-               return "$tag NO Mailbox doesn't exist: $mailbox\r\n";
        return "$tag BAD no items\r\n" if !scalar(@items);
        ($items[0] !~ s/\A\(//s || $items[-1] !~ s/\)\z//s) and
                return "$tag BAD invalid args\r\n";
-
-       my $mm = $ibx->mm;
-       my ($max, @it);
+       my ($ibx, $exists, $uidnext) = inbox_lookup($self, $mailbox);
+       return "$tag NO Mailbox doesn't exist: $mailbox\r\n" if !$ibx;
+       my @it;
        for my $it (@items) {
                $it = uc($it);
                push @it, $it;
                if ($it =~ /\A(?:MESSAGES|UNSEEN|RECENT)\z/) {
-                       push(@it, ($max //= $mm->max // 0));
+                       push @it, $exists;
                } elsif ($it eq 'UIDNEXT') {
-                       push(@it, ($max //= $mm->max // 0) + 1);
+                       push @it, $uidnext;
                } elsif ($it eq 'UIDVALIDITY') {
-                       push(@it, $ibx->{uidvalidity});
+                       push @it, $ibx->{uidvalidity};
                } else {
                        return "$tag BAD invalid item\r\n";
                }
@@ -788,15 +799,15 @@ sub cmd_fetch ($$$;@) {
        } : $args; # error
 }
 
-sub uid_search_all { # long_response
-       my ($self, $tag, $num) = @_;
-       my $uids = $self->{ibx}->mm->ids_after($num);
-       if (scalar(@$uids)) {
-               $self->msg_more(join(' ', '', @$uids));
-       } else {
-               $self->write(\"\r\n$tag OK Search done\r\n");
-               undef;
-       }
+
+sub parse_date ($) { # 02-Oct-1993
+       my ($date_text) = @_;
+       my ($dd, $mon, $yyyy) = split(/-/, $_[0], 3);
+       defined($yyyy) or return;
+       my $mm = $MoY{$mon} // return;
+       $dd =~ /\A[0123]?[0-9]\z/ or return;
+       $yyyy =~ /\A[0-9]{4,}\z/ or return; # Y10K-compatible!
+       timegm(0, 0, 0, $dd, $mm, $yyyy);
 }
 
 sub uid_search_uid_range { # long_response
@@ -810,23 +821,137 @@ sub uid_search_uid_range { # long_response
        }
 }
 
+sub date_search {
+       my ($q, $k, $d) = @_;
+       my $sql = $q->{sql};
+
+       # Date: header
+       if ($k eq 'SENTON') {
+               my $end = $d + 86399; # no leap day...
+               my $da = strftime('%Y%m%d%H%M%S', gmtime($d));
+               my $db = strftime('%Y%m%d%H%M%S', gmtime($end));
+               $q->{xap} .= " dt:$da..$db";
+               $$sql .= " AND ds >= $d AND ds <= $end" if defined($sql);
+       } elsif ($k eq 'SENTBEFORE') {
+               $q->{xap} .= ' d:..'.strftime('%Y%m%d', gmtime($d));
+               $$sql .= " AND ds <= $d" if defined($sql);
+       } elsif ($k eq 'SENTSINCE') {
+               $q->{xap} .= ' d:'.strftime('%Y%m%d', gmtime($d)).'..';
+               $$sql .= " AND ds >= $d" if defined($sql);
+
+       # INTERNALDATE (Received)
+       } elsif ($k eq 'ON') {
+               my $end = $d + 86399; # no leap day...
+               $q->{xap} .= " ts:$d..$end";
+               $$sql .= " AND ts >= $d AND ts <= $end" if defined($sql);
+       } elsif ($k eq 'BEFORE') {
+               $q->{xap} .= " ts:..$d";
+               $$sql .= " AND ts <= $d" if defined($sql);
+       } elsif ($k eq 'SINCE') {
+               $q->{xap} .= " ts:$d..";
+               $$sql .= " AND ts >= $d" if defined($sql);
+       } else {
+               die "BUG: $k not recognized";
+       }
+}
+
+# IMAP to Xapian search key mapping
+my %I2X = (
+       SUBJECT => 's:',
+       BODY => 'b:',
+       FROM => 'f:',
+       TEXT => '', # n.b. does not include all headers
+       TO => 't:',
+       CC => 'c:',
+       # BCC => 'bcc:', # TODO
+       # KEYWORD # TODO ? dfpre,dfpost,...
+);
+
+sub parse_query {
+       my ($self, $rest) = @_;
+       if (uc($rest->[0]) eq 'CHARSET') {
+               shift @$rest;
+               defined(my $c = shift @$rest) or return 'BAD missing charset';
+               $c =~ /\A(?:UTF-8|US-ASCII)\z/ or return 'NO [BADCHARSET]';
+       }
+
+       my $sql = ''; # date conditions, {sql} deleted if Xapian is needed
+       my $q = { xap => '', sql => \$sql };
+       while (@$rest) {
+               my $k = uc(shift @$rest);
+               # default criteria
+               next if $k =~ /\A(?:ALL|RECENT|UNSEEN|NEW)\z/;
+               next if $k eq 'AND'; # the default, until we support OR
+               if ($k =~ $valid_range) { # sequence numbers == UIDs
+                       push @{$q->{uid}}, $k;
+               } elsif ($k eq 'UID') {
+                       $k = shift(@$rest) // '';
+                       $k =~ $valid_range or return 'BAD UID range';
+                       push @{$q->{uid}}, $k;
+               } elsif ($k =~ /\A(?:SENT)?(?:SINCE|ON|BEFORE)\z/) {
+                       my $d = parse_date(shift(@$rest) // '');
+                       defined $d or return "BAD $k date format";
+                       date_search($q, $k, $d);
+               } elsif ($k =~ /\A(?:SMALLER|LARGER)\z/) {
+                       delete $q->{sql}; # can't use over.sqlite3
+                       my $bytes = shift(@$rest) // '';
+                       $bytes =~ /\A[0-9]+\z/ or return "BAD $k not a number";
+                       $q->{xap} .= ' bytes:' . ($k eq 'SMALLER' ?
+                                                       '..'.(--$bytes) :
+                                                       (++$bytes).'..');
+               } elsif (defined(my $xk = $I2X{$k})) {
+                       delete $q->{sql}; # can't use over.sqlite3
+                       my $arg = shift @$rest;
+                       defined($arg) or return "BAD $k no arg";
+
+                       # Xapian can't handle [*"] in probabilistic terms
+                       $arg =~ tr/*"//d;
+                       $q->{xap} .= qq[ $xk:"$arg"];
+               } else {
+                       # TODO: parentheses, OR, NOT ...
+                       return "BAD $k not supported (yet?)";
+               }
+       }
+
+       # favor using over.sqlite3 if possible, since Xapian is optional
+       if (exists $q->{sql}) {
+               delete($q->{xap});
+               delete($q->{sql}) if $sql eq '';
+       } elsif (!$self->{ibx}->search) {
+               return 'BAD Xapian not configured for mailbox';
+       }
+
+       if (my $uid = $q->{uid}) {
+               ((@$uid > 1) || $uid->[0] =~ /,/) and
+                       return 'BAD multiple ranges not supported, yet';
+               ($q->{sql} // $q->{xap}) and
+                       return 'BAD ranges and queries do not mix, yet';
+               $q->{uid} = join(',', @$uid); # TODO: multiple ranges
+       }
+       $q;
+}
+
 sub cmd_uid_search ($$$;) {
-       my ($self, $tag, $arg, @rest) = @_;
+       my ($self, $tag) = splice(@_, 0, 2);
        my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
-       $arg = uc($arg);
-       if ($arg eq 'ALL' && !@rest) {
+       my $q = parse_query($self, \@_);
+       return "$tag $q\r\n" if !ref($q);
+
+       if (!scalar(keys %$q)) {
                $self->msg_more('* SEARCH');
-               my $num = 0;
-               long_response($self, \&uid_search_all, $tag, \$num);
-       } elsif ($arg eq 'UID' && scalar(@rest) == 1) {
-               if ($rest[0] =~ /\A([0-9]+):([0-9]+|\*)\z/s) {
+               my $beg = $self->{uid_min} // 1;
+               my $end = $ibx->mm->max;
+               uid_clamp($self, \$beg, \$end);
+               long_response($self, \&uid_search_uid_range, $tag, \$beg, $end);
+       } elsif (my $uid = $q->{uid}) {
+               if ($uid =~ /\A([0-9]+):([0-9]+|\*)\z/s) {
                        my ($beg, $end) = ($1, $2);
                        $end = $ibx->mm->max if $end eq '*';
+                       uid_clamp($self, \$beg, \$end);
                        $self->msg_more('* SEARCH');
                        long_response($self, \&uid_search_uid_range,
                                        $tag, \$beg, $end);
-               } elsif ($rest[0] =~ /\A[0-9]+\z/s) {
-                       my $uid = $rest[0];
+               } elsif ($uid =~ /\A[0-9]+\z/s) {
                        $uid = $ibx->over->get_art($uid) ? " $uid" : '';
                        "* SEARCH$uid\r\n$tag OK Search done\r\n";
                } else {
@@ -863,14 +988,17 @@ sub process_line ($$) {
                        cmd_done($self, $tag);
                } else { # this is weird
                        auth_challenge_ok($self) //
-                               "$tag BAD Error in IMAP command $req: ".
-                               "Unknown command\r\n";
+                                       ($tag // '*') .
+                                       ' BAD Error in IMAP command '.
+                                       ($req // '(???)').
+                                       ": Unknown command\r\n";
                }
        };
        my $err = $@;
        if ($err && $self->{sock}) {
                $l =~ s/\r?\n//s;
                err($self, 'error from: %s (%s)', $l, $err);
+               $tag //= '*';
                $res = "$tag BAD program fault - command not performed\r\n";
        }
        return 0 unless defined $res;