1 # Copyright (C) 2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # for maintaining synchronization between lei/store <=> Maildir|MH|IMAP|JMAP
5 package PublicInbox::LeiMailSync;
8 use parent qw(PublicInbox::Lock);
10 use PublicInbox::ContentHash qw(git_sha);
15 my $f = $self->{filename};
16 my $creat = $rw && !-s $f;
18 require PublicInbox::Spawn;
19 open my $fh, '+>>', $f or Carp::croak "open($f): $!";
20 PublicInbox::Spawn::nodatacow_fd(fileno($fh));
22 my $dbh = DBI->connect("dbi:SQLite:dbname=$f",'','', {
27 sqlite_use_immediate_transaction => 1,
29 # no sqlite_unicode, here, all strings are binary
30 create_tables($self, $dbh) if $rw;
31 $dbh->do('PRAGMA journal_mode = WAL') if $creat;
32 $dbh->do('PRAGMA case_sensitive_like = ON');
41 lock_path => "$f.flock",
45 sub lms_write_prepare { ($_[0]->{dbh} //= dbh_new($_[0], 1)); $_[0] }
50 my $dbh = delete $self->{dbh};
51 eval { $dbh->do('PRAGMA optimize') } if $dbh;
55 my ($self, $dbh) = @_;
56 my $lk = $self->lock_for_scope;
59 CREATE TABLE IF NOT EXISTS folders (
60 fid INTEGER PRIMARY KEY,
61 loc VARBINARY NOT NULL, /* URL;UIDVALIDITY=$N or $TYPE:/pathname */
66 CREATE TABLE IF NOT EXISTS blob2num (
67 oidbin VARBINARY NOT NULL,
68 fid INTEGER NOT NULL, /* folder ID */
69 uid INTEGER NOT NULL, /* NNTP article number, IMAP UID, MH number */
70 /* not UNIQUE(fid, uid), since we may have broken servers */
71 UNIQUE (oidbin, fid, uid)
74 # speeds up LeiImport->ck_update_kw (for "lei import") by 5-6x:
76 CREATE INDEX IF NOT EXISTS idx_fid_uid ON blob2num(fid,uid)
79 CREATE TABLE IF NOT EXISTS blob2name (
80 oidbin VARBINARY NOT NULL,
81 fid INTEGER NOT NULL, /* folder ID */
82 name VARBINARY NOT NULL, /* Maildir basename, JMAP blobId */
83 /* not UNIQUE(fid, name), since we may have broken software */
84 UNIQUE (oidbin, fid, name)
87 # speeds up LeiImport->pmdir_cb (for "lei import") by ~6x:
89 CREATE INDEX IF NOT EXISTS idx_fid_name ON blob2name(fid,name)
94 my ($self, $folder, $rw) = @_;
95 my $dbh = $self->{dbh} //= dbh_new($self, $rw);
96 my $sel = 'SELECT fid FROM folders WHERE loc = ? LIMIT 1';
97 my ($fid) = $dbh->selectrow_array($sel, undef, $folder);
98 return $fid if defined $fid;
100 # caller had trailing slash (LeiToMail)
101 if ($folder =~ s!\A((?:maildir|mh):.*?)/+\z!$1!i) {
102 ($fid) = $dbh->selectrow_array($sel, undef, $folder);
104 $dbh->do(<<EOM, undef, $folder, $fid) if $rw;
105 UPDATE folders SET loc = ? WHERE fid = ?
109 # sometimes we stored trailing slash..
110 } elsif ($folder =~ m!\A(?:maildir|mh):!i) {
111 ($fid) = $dbh->selectrow_array($sel, undef, "$folder/");
113 $dbh->do(<<EOM, undef, $folder, $fid) if $rw;
114 UPDATE folders SET loc = ? WHERE fid = ?
118 } elsif ($rw && $folder =~ m!\Aimaps?://!i) {
119 require PublicInbox::URIimap;
120 PublicInbox::URIimap->new($folder)->uidvalidity //
121 Carp::croak("BUG: $folder has no UIDVALIDITY");
125 ($fid) = $dbh->selectrow_array('SELECT MAX(fid) FROM folders');
128 # in case we're reusing, clobber existing stale refs:
129 $dbh->do('DELETE FROM blob2name WHERE fid = ?', undef, $fid);
130 $dbh->do('DELETE FROM blob2num WHERE fid = ?', undef, $fid);
132 my $sth = $dbh->prepare('INSERT INTO folders (fid, loc) VALUES (?, ?)');
133 $sth->execute($fid, $folder);
139 my ($self, @folders) = @_;
140 my $lk = $self->lock_for_scope;
141 for my $f (@folders) { $self->{fmap}->{$f} //= fid_for($self, $f, 1) }
145 my ($self, $oidbin, $folder, $id) = @_;
146 my $lk = $self->lock_for_scope;
147 my $fid = $self->{fmap}->{$folder} //= fid_for($self, $folder, 1);
149 if (ref($id)) { # scalar name
151 $sth = $self->{dbh}->prepare_cached(<<'');
152 INSERT OR IGNORE INTO blob2name (oidbin, fid, name) VALUES (?, ?, ?)
154 } else { # numeric ID (IMAP UID, MH number)
155 $sth = $self->{dbh}->prepare_cached(<<'');
156 INSERT OR IGNORE INTO blob2num (oidbin, fid, uid) VALUES (?, ?, ?)
159 $sth->execute($oidbin, $fid, $id);
163 my ($self, $folder, $id) = @_;
164 my $lk = $self->lock_for_scope;
165 my $fid = $self->{fmap}->{$folder} //= fid_for($self, $folder, 1);
167 if (ref($id)) { # scalar name
169 $sth = $self->{dbh}->prepare_cached(<<'');
170 DELETE FROM blob2name WHERE fid = ? AND name = ?
173 $sth = $self->{dbh}->prepare_cached(<<'');
174 DELETE FROM blob2num WHERE fid = ? AND uid = ?
177 $sth->execute($fid, $id);
182 my ($self, $folder, $oidbin, $id, $newbn) = @_;
183 my $lk = $self->lock_for_scope;
184 my $fid = $self->{fmap}->{$folder} //= fid_for($self, $folder, 1);
185 $self->{dbh}->begin_work;
186 my $sth = $self->{dbh}->prepare_cached(<<'');
187 UPDATE blob2name SET name = ? WHERE fid = ? AND oidbin = ? AND name = ?
189 # eval since unique constraint may fail due to race
190 my $nr = eval { $sth->execute($newbn, $fid, $oidbin, $$id) };
191 if (!defined($nr) || $nr == 0) { # $nr may be `0E0'
192 # may race with a clear_src, ensure new value exists
193 $sth = $self->{dbh}->prepare_cached(<<'');
194 INSERT OR IGNORE INTO blob2name (oidbin, fid, name) VALUES (?, ?, ?)
196 $sth->execute($oidbin, $fid, $newbn);
198 $self->{dbh}->commit;
201 # read-only, iterates every oidbin + UID or name for a given folder
203 my ($self, $folder, $cb, @args) = @_;
204 my $dbh = $self->{dbh} //= dbh_new($self);
207 if (ref($folder) eq 'HASH') {
208 $fid = $folder->{fid} // die "BUG: no `fid'";
209 @rng = grep(defined, @$folder{qw(min max)});
210 $and_ge_le = 'AND uid >= ? AND uid <= ?' if @rng;
212 $fid = $self->{fmap}->{$folder} //=
213 fid_for($self, $folder) // return;
216 # minimize implicit txn time to avoid blocking writers by
217 # batching SELECTs. This looks wonky but is necessary since
218 # $cb-> may access the DB on its own.
219 my $ary = $dbh->selectall_arrayref(<<"", undef, $fid, @rng);
220 SELECT _rowid_,oidbin,uid FROM blob2num WHERE fid = ? $and_ge_le
221 ORDER BY _rowid_ ASC LIMIT 1000
223 my $min = @$ary ? $ary->[-1]->[0] : undef;
224 while (defined $min) {
225 for my $row (@$ary) { $cb->($row->[1], $row->[2], @args) }
227 $ary = $dbh->selectall_arrayref(<<"", undef, $fid, @rng, $min);
228 SELECT _rowid_,oidbin,uid FROM blob2num
229 WHERE fid = ? $and_ge_le AND _rowid_ > ?
230 ORDER BY _rowid_ ASC LIMIT 1000
232 $min = @$ary ? $ary->[-1]->[0] : undef;
235 $ary = $dbh->selectall_arrayref(<<'', undef, $fid);
236 SELECT _rowid_,oidbin,name FROM blob2name WHERE fid = ?
237 ORDER BY _rowid_ ASC LIMIT 1000
239 $min = @$ary ? $ary->[-1]->[0] : undef;
240 while (defined $min) {
241 for my $row (@$ary) { $cb->($row->[1], \($row->[2]), @args) }
243 $ary = $dbh->selectall_arrayref(<<'', undef, $fid, $min);
244 SELECT _rowid_,oidbin,name FROM blob2name WHERE fid = ? AND _rowid_ > ?
245 ORDER BY _rowid_ ASC LIMIT 1000
247 $min = @$ary ? $ary->[-1]->[0] : undef;
252 my ($self, $folder) = @_;
253 my $dbh = $self->{dbh} //= dbh_new($self);
256 $fid = $self->{fmap}->{$folder} //= fid_for($self, $folder) // return;
257 my ($row) = $dbh->selectrow_array(<<"", undef, $fid);
258 SELECT COUNT(name) FROM blob2name WHERE fid = ?
260 $ret->{'name.count'} = $row if $row;
261 my $ntype = ($folder =~ m!\A(?:nntps?|s?news)://!i) ? 'article' :
262 (($folder =~ m!\Aimaps?://!i) ? 'uid' : "TODO<$folder>");
263 for my $op (qw(count min max)) {
264 ($row) = $dbh->selectrow_array(<<"", undef, $fid);
265 SELECT $op(uid) FROM blob2num WHERE fid = ?
268 $ret->{"$ntype.$op"} = $row;
273 # returns a { location => [ list-of-ids-or-names ] } mapping
275 my ($self, $oidbin) = @_;
276 my ($fid, $sth, $id, %fid2id);
277 my $dbh = $self->{dbh} //= dbh_new($self);
278 $sth = $dbh->prepare('SELECT fid,uid FROM blob2num WHERE oidbin = ?');
279 $sth->execute($oidbin);
280 while (my ($fid, $uid) = $sth->fetchrow_array) {
281 push @{$fid2id{$fid}}, $uid;
283 $sth = $dbh->prepare('SELECT fid,name FROM blob2name WHERE oidbin = ?');
284 $sth->execute($oidbin);
285 while (my ($fid, $name) = $sth->fetchrow_array) {
286 push @{$fid2id{$fid}}, $name;
288 $sth = $dbh->prepare('SELECT loc FROM folders WHERE fid = ? LIMIT 1');
290 while (my ($fid, $ids) = each %fid2id) {
292 my ($loc) = $sth->fetchrow_array;
293 unless (defined $loc) {
294 my $oidhex = unpack('H*', $oidbin);
295 warn "E: fid=$fid for $oidhex unknown:\n", map {
296 'E: '.(ref() ? $$_ : "#$_")."\n";
302 scalar(keys %$ret) ? $ret : undef;
305 # returns a list of folders used for completion
307 my ($self, @pfx) = @_;
308 my $sql = 'SELECT loc FROM folders';
309 if (defined($pfx[0])) {
310 $sql .= ' WHERE loc LIKE ? ESCAPE ?';
311 my $anywhere = !!$pfx[1];
313 $pfx[0] =~ s/([%_\\])/\\$1/g; # glob chars
315 substr($pfx[0], 0, 0, '%') if $anywhere;
317 @pfx = (); # [0] may've been undef
319 my $dbh = $self->{dbh} //= dbh_new($self);
320 map { $_->[0] } @{$dbh->selectall_arrayref($sql, undef, @pfx)};
324 my ($self, $oidhex, $vrfy) = @_;
325 my $dbh = $self->{dbh} //= dbh_new($self);
326 my $b2n = $dbh->prepare(<<'');
327 SELECT f.loc,b.name FROM blob2name b
328 LEFT JOIN folders f ON b.fid = f.fid
331 $b2n->execute(pack('H*', $oidhex));
332 while (my ($d, $n) = $b2n->fetchrow_array) {
333 substr($d, 0, length('maildir:')) = '';
334 # n.b. both mbsync and offlineimap use ":2," as a suffix
335 # in "new/", despite (from what I understand of reading
336 # <https://cr.yp.to/proto/maildir.html>), the ":2," only
337 # applies to files in "cur/".
338 my @try = $n =~ /:2,[a-zA-Z]+\z/ ? qw(cur new) : qw(new cur);
341 open my $fh, '<', $f or next;
342 # some (buggy) Maildir writers are non-atomic:
347 my $got = git_sha(1, \$raw)->hexdigest;
348 if ($got ne $oidhex) {
349 warn "$f changed $oidhex => $got\n";
360 my ($self, $url, $all) = @_; # $all = [ $lms->folders ];
361 $all //= [ $self->folders ];
362 require PublicInbox::URIimap;
363 my $want = PublicInbox::URIimap->new($url)->canonical;
364 my ($s, $h, $mb) = ($want->scheme, $want->host, $want->mailbox);
365 my @uri = map { PublicInbox::URIimap->new($_)->canonical }
366 grep(m!\A\Q$s\E://.*?\Q$h\E\b.*?/\Q$mb\E\b!, @$all);
369 next if $x->mailbox ne $want->mailbox;
370 next if $x->host ne $want->host;
371 next if $x->port != $want->port;
372 my $x_uidval = $x->uidvalidity;
373 next if ($want->uidvalidity // $x_uidval) != $x_uidval;
375 # allow nothing in want to possibly match ";AUTH=ANONYMOUS"
376 if (defined($x->auth) && !defined($want->auth) &&
377 !defined($want->user)) {
379 # or maybe user was forgotten on CLI:
380 } elsif (defined($x->user) && !defined($want->user)) {
382 } elsif (($x->user//"\0") eq ($want->user//"\0")) {
386 return @match if wantarray;
387 scalar(@match) <= 1 ? $match[0] :
388 "E: `$url' is ambiguous:\n\t".join("\n\t", @match)."\n";
391 sub match_nntp_url ($$$) {
392 my ($self, $url, $all) = @_; # $all = [ $lms->folders ];
393 $all //= [ $self->folders ];
394 require PublicInbox::URInntps;
395 my $want = PublicInbox::URInntps->new($url)->canonical;
396 my ($s, $h, $p) = ($want->scheme, $want->host, $want->port);
397 my $ng = $want->group; # force scalar (no article ranges)
398 my @uri = map { PublicInbox::URInntps->new($_)->canonical }
399 grep(m!\A\Q$s\E://.*?\Q$h\E\b.*?/\Q$ng\E\b!, @$all);
402 next if $x->group ne $ng || $x->host ne $h || $x->port != $p;
403 # maybe user was forgotten on CLI:
404 if (defined($x->userinfo) && !defined($want->userinfo)) {
406 } elsif (($x->userinfo//"\0") eq ($want->userinfo//"\0")) {
410 return @match if wantarray;
411 scalar(@match) <= 1 ? $match[0] :
412 "E: `$url' is ambiguous:\n\t".join("\n\t", @match)."\n";
415 # returns undef on failure, number on success
417 my ($self, $lei, $all, $folders) = @_;
418 return $lei->fail(<<EOM) if @$folders;
419 --all= not compatible with @$folders on command-line
421 my %x = map { $_ => $_ } split(/,/, $all);
422 my @ok = grep(defined, delete(@x{qw(local remote), ''}));
423 push(@ok, '') if $all eq '';
426 @no = (join(',', @no));
427 return $lei->fail(<<EOM);
428 --all=@no not accepted (must be `local' and/or `remote')
432 my @all = $self->folders;
434 if ($ok eq 'local') {
435 @inc = grep(!m!\A[a-z0-9\+]+://!i, @all);
436 } elsif ($ok eq 'remote') {
437 @inc = grep(m!\A[a-z0-9\+]+://!i, @all);
438 } elsif ($ok ne '') {
439 return $lei->fail("--all=$all not understood");
443 push(@$folders, (grep { !$seen{$_}++ } @inc));
445 scalar(@$folders) || $lei->fail(<<EOM);
446 no --mail-sync folders known to lei
450 # map CLI args to folder table entries, returns undef on failure
452 my ($self, $lei, $folders) = @_;
453 my @all = $self->folders;
454 my %all = map { $_ => 1 } @all;
457 next if $all{$_}; # ok
458 if (m!\A(maildir|mh):(.+)!i) {
460 my $d = "$type:".$lei->abs_path($2);
461 push(@no, $_) unless $all{$d};
463 } elsif (-d "$_/new" && -d "$_/cur") {
464 my $d = 'maildir:'.$lei->abs_path($_);
465 push(@no, $_) unless $all{$d};
467 } elsif (m!\Aimaps?://!i) {
469 my $res = match_imap_url($self, $orig, \@all);
473 # using `$res' instead of `$orig'
476 warn($res, "\n") if defined $res;
479 } elsif (m!\A(?:nntps?|s?news)://!i) {
481 my $res = match_nntp_url($self, $orig, \@all);
485 # using `$res' instead of `$orig'
488 warn($res, "\n") if defined $res;
496 my $no = join("\n\t", @no);
498 No sync information for: $no
499 Run `lei ls-mail-sync' to display valid choices
505 my ($self, @folders) = @_;
506 my $lk = $self->lock_for_scope;
507 for my $folder (@folders) {
508 my $fid = delete($self->{fmap}->{$folder}) //
509 fid_for($self, $folder) // next;
510 for my $t (qw(blob2name blob2num folders)) {
511 $self->{dbh}->do("DELETE FROM $t WHERE fid = ?",
517 # only used for changing canonicalization errors
519 my ($self, $old, $new) = @_;
520 my $lk = $self->lock_for_scope;
521 my $ofid = delete($self->{fmap}->{$old}) //
522 fid_for($self, $old) // return;
524 $self->{dbh}->do(<<EOM, undef, $new, $ofid);
525 UPDATE folders SET loc = ? WHERE fid = ?
528 if ($@ =~ /\bunique\b/i) {
529 my $nfid = $self->{fmap}->{$new} // fid_for($self, $new);
530 for my $t (qw(blob2name blob2num)) {
531 $self->{dbh}->do(<<EOM, undef, $nfid, $ofid);
532 UPDATE OR REPLACE $t SET fid = ? WHERE fid = ?
535 $self->{dbh}->do(<<EOM, undef, $ofid);
536 DELETE FROM folders WHERE fid = ?
541 sub num_oidbin ($$$) {
542 my ($self, $url, $uid) = @_; # $url MUST have UIDVALIDITY if IMAP
543 my $fid = $self->{fmap}->{$url} //= fid_for($self, $url) // return ();
544 my $sth = $self->{dbh}->prepare_cached(<<EOM, undef, 1);
545 SELECT oidbin FROM blob2num WHERE fid = ? AND uid = ? ORDER BY _rowid_
547 $sth->execute($fid, $uid);
548 map { $_->[0] } @{$sth->fetchall_arrayref};
551 sub name_oidbin ($$$) {
552 my ($self, $mdir, $nm) = @_;
553 my $fid = $self->{fmap}->{$mdir} //= fid_for($self, $mdir) // return;
554 my $sth = $self->{dbh}->prepare_cached(<<EOM, undef, 1);
555 SELECT oidbin FROM blob2name WHERE fid = ? AND name = ?
557 $sth->execute($fid, $nm);
558 map { $_->[0] } @{$sth->fetchall_arrayref};
562 my ($self, $lei, $uid_uri) = @_;
563 my $mailbox_uri = $uid_uri->clone;
564 $mailbox_uri->uid(undef);
565 my $folders = [ $$mailbox_uri ];
566 eval { $self->arg2folder($lei, $folders) };
567 $lei->qerr("# no sync information for $mailbox_uri") if $@;
568 map { unpack('H*',$_) } num_oidbin($self, $folders->[0], $uid_uri->uid)