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 my $sth = $self->{dbh}->prepare_cached(<<'');
186 UPDATE blob2name SET name = ? WHERE fid = ? AND oidbin = ? AND name = ?
188 my $nr = $sth->execute($newbn, $fid, $oidbin, $$id);
189 if ($nr == 0) { # may race with a clear_src, ensure new value exists
190 $sth = $self->{dbh}->prepare_cached(<<'');
191 INSERT OR IGNORE INTO blob2name (oidbin, fid, name) VALUES (?, ?, ?)
193 $sth->execute($oidbin, $fid, $newbn);
197 # read-only, iterates every oidbin + UID or name for a given folder
199 my ($self, $folder, $cb, @args) = @_;
200 my $dbh = $self->{dbh} //= dbh_new($self);
203 if (ref($folder) eq 'HASH') {
204 $fid = $folder->{fid} // die "BUG: no `fid'";
205 @rng = grep(defined, @$folder{qw(min max)});
206 $and_ge_le = 'AND uid >= ? AND uid <= ?' if @rng;
208 $fid = $self->{fmap}->{$folder} //=
209 fid_for($self, $folder) // return;
212 # minimize implicit txn time to avoid blocking writers by
213 # batching SELECTs. This looks wonky but is necessary since
214 # $cb-> may access the DB on its own.
215 my $ary = $dbh->selectall_arrayref(<<"", undef, $fid, @rng);
216 SELECT _rowid_,oidbin,uid FROM blob2num WHERE fid = ? $and_ge_le
217 ORDER BY _rowid_ ASC LIMIT 1000
219 my $min = @$ary ? $ary->[-1]->[0] : undef;
220 while (defined $min) {
221 for my $row (@$ary) { $cb->($row->[1], $row->[2], @args) }
223 $ary = $dbh->selectall_arrayref(<<"", undef, $fid, @rng, $min);
224 SELECT _rowid_,oidbin,uid FROM blob2num
225 WHERE fid = ? $and_ge_le AND _rowid_ > ?
226 ORDER BY _rowid_ ASC LIMIT 1000
228 $min = @$ary ? $ary->[-1]->[0] : undef;
231 $ary = $dbh->selectall_arrayref(<<'', undef, $fid);
232 SELECT _rowid_,oidbin,name FROM blob2name WHERE fid = ?
233 ORDER BY _rowid_ ASC LIMIT 1000
235 $min = @$ary ? $ary->[-1]->[0] : undef;
236 while (defined $min) {
237 for my $row (@$ary) { $cb->($row->[1], \($row->[2]), @args) }
239 $ary = $dbh->selectall_arrayref(<<'', undef, $fid, $min);
240 SELECT _rowid_,oidbin,name FROM blob2name WHERE fid = ? AND _rowid_ > ?
241 ORDER BY _rowid_ ASC LIMIT 1000
243 $min = @$ary ? $ary->[-1]->[0] : undef;
248 my ($self, $folder) = @_;
249 my $dbh = $self->{dbh} //= dbh_new($self);
252 $fid = $self->{fmap}->{$folder} //= fid_for($self, $folder) // return;
253 my ($row) = $dbh->selectrow_array(<<"", undef, $fid);
254 SELECT COUNT(name) FROM blob2name WHERE fid = ?
256 $ret->{'name.count'} = $row if $row;
257 my $ntype = ($folder =~ m!\A(?:nntps?|s?news)://!i) ? 'article' :
258 (($folder =~ m!\Aimaps?://!i) ? 'uid' : "TODO<$folder>");
259 for my $op (qw(count min max)) {
260 ($row) = $dbh->selectrow_array(<<"", undef, $fid);
261 SELECT $op(uid) FROM blob2num WHERE fid = ?
264 $ret->{"$ntype.$op"} = $row;
269 # returns a { location => [ list-of-ids-or-names ] } mapping
271 my ($self, $oidbin) = @_;
272 my ($fid, $sth, $id, %fid2id);
273 my $dbh = $self->{dbh} //= dbh_new($self);
274 $sth = $dbh->prepare('SELECT fid,uid FROM blob2num WHERE oidbin = ?');
275 $sth->execute($oidbin);
276 while (my ($fid, $uid) = $sth->fetchrow_array) {
277 push @{$fid2id{$fid}}, $uid;
279 $sth = $dbh->prepare('SELECT fid,name FROM blob2name WHERE oidbin = ?');
280 $sth->execute($oidbin);
281 while (my ($fid, $name) = $sth->fetchrow_array) {
282 push @{$fid2id{$fid}}, $name;
284 $sth = $dbh->prepare('SELECT loc FROM folders WHERE fid = ? LIMIT 1');
286 while (my ($fid, $ids) = each %fid2id) {
288 my ($loc) = $sth->fetchrow_array;
289 unless (defined $loc) {
290 my $oidhex = unpack('H*', $oidbin);
291 warn "E: fid=$fid for $oidhex unknown:\n", map {
292 'E: '.(ref() ? $$_ : "#$_")."\n";
298 scalar(keys %$ret) ? $ret : undef;
301 # returns a list of folders used for completion
303 my ($self, @pfx) = @_;
304 my $sql = 'SELECT loc FROM folders';
305 if (defined($pfx[0])) {
306 $sql .= ' WHERE loc LIKE ? ESCAPE ?';
307 my $anywhere = !!$pfx[1];
309 $pfx[0] =~ s/([%_\\])/\\$1/g; # glob chars
311 substr($pfx[0], 0, 0, '%') if $anywhere;
313 @pfx = (); # [0] may've been undef
315 my $dbh = $self->{dbh} //= dbh_new($self);
316 map { $_->[0] } @{$dbh->selectall_arrayref($sql, undef, @pfx)};
320 my ($self, $oidhex, $vrfy) = @_;
321 my $dbh = $self->{dbh} //= dbh_new($self);
322 my $b2n = $dbh->prepare(<<'');
323 SELECT f.loc,b.name FROM blob2name b
324 LEFT JOIN folders f ON b.fid = f.fid
327 $b2n->execute(pack('H*', $oidhex));
328 while (my ($d, $n) = $b2n->fetchrow_array) {
329 substr($d, 0, length('maildir:')) = '';
330 # n.b. both mbsync and offlineimap use ":2," as a suffix
331 # in "new/", despite (from what I understand of reading
332 # <https://cr.yp.to/proto/maildir.html>), the ":2," only
333 # applies to files in "cur/".
334 my @try = $n =~ /:2,[a-zA-Z]+\z/ ? qw(cur new) : qw(new cur);
337 open my $fh, '<', $f or next;
338 # some (buggy) Maildir writers are non-atomic:
343 my $got = git_sha(1, \$raw)->hexdigest;
344 if ($got ne $oidhex) {
345 warn "$f changed $oidhex => $got\n";
356 my ($self, $url, $all) = @_; # $all = [ $lms->folders ];
357 $all //= [ $self->folders ];
358 require PublicInbox::URIimap;
359 my $want = PublicInbox::URIimap->new($url)->canonical;
360 my ($s, $h, $mb) = ($want->scheme, $want->host, $want->mailbox);
361 my @uri = map { PublicInbox::URIimap->new($_)->canonical }
362 grep(m!\A\Q$s\E://.*?\Q$h\E\b.*?/\Q$mb\E\b!, @$all);
365 next if $x->mailbox ne $want->mailbox;
366 next if $x->host ne $want->host;
367 next if $x->port != $want->port;
368 my $x_uidval = $x->uidvalidity;
369 next if ($want->uidvalidity // $x_uidval) != $x_uidval;
371 # allow nothing in want to possibly match ";AUTH=ANONYMOUS"
372 if (defined($x->auth) && !defined($want->auth) &&
373 !defined($want->user)) {
375 # or maybe user was forgotten on CLI:
376 } elsif (defined($x->user) && !defined($want->user)) {
378 } elsif (($x->user//"\0") eq ($want->user//"\0")) {
382 return @match if wantarray;
383 scalar(@match) <= 1 ? $match[0] :
384 "E: `$url' is ambiguous:\n\t".join("\n\t", @match)."\n";
387 sub match_nntp_url ($$$) {
388 my ($self, $url, $all) = @_; # $all = [ $lms->folders ];
389 $all //= [ $self->folders ];
390 require PublicInbox::URInntps;
391 my $want = PublicInbox::URInntps->new($url)->canonical;
392 my ($s, $h, $p) = ($want->scheme, $want->host, $want->port);
393 my $ng = $want->group; # force scalar (no article ranges)
394 my @uri = map { PublicInbox::URInntps->new($_)->canonical }
395 grep(m!\A\Q$s\E://.*?\Q$h\E\b.*?/\Q$ng\E\b!, @$all);
398 next if $x->group ne $ng || $x->host ne $h || $x->port != $p;
399 # maybe user was forgotten on CLI:
400 if (defined($x->userinfo) && !defined($want->userinfo)) {
402 } elsif (($x->userinfo//"\0") eq ($want->userinfo//"\0")) {
406 return @match if wantarray;
407 scalar(@match) <= 1 ? $match[0] :
408 "E: `$url' is ambiguous:\n\t".join("\n\t", @match)."\n";
411 # returns undef on failure, number on success
413 my ($self, $lei, $all, $folders) = @_;
414 return $lei->fail(<<EOM) if @$folders;
415 --all= not compatible with @$folders on command-line
417 my %x = map { $_ => $_ } split(/,/, $all);
418 my @ok = grep(defined, delete(@x{qw(local remote), ''}));
419 push(@ok, '') if $all eq '';
422 @no = (join(',', @no));
423 return $lei->fail(<<EOM);
424 --all=@no not accepted (must be `local' and/or `remote')
428 my @all = $self->folders;
430 if ($ok eq 'local') {
431 @inc = grep(!m!\A[a-z0-9\+]+://!i, @all);
432 } elsif ($ok eq 'remote') {
433 @inc = grep(m!\A[a-z0-9\+]+://!i, @all);
434 } elsif ($ok ne '') {
435 return $lei->fail("--all=$all not understood");
439 push(@$folders, (grep { !$seen{$_}++ } @inc));
441 scalar(@$folders) || $lei->fail(<<EOM);
442 no --mail-sync folders known to lei
446 # map CLI args to folder table entries, returns undef on failure
448 my ($self, $lei, $folders) = @_;
449 my @all = $self->folders;
450 my %all = map { $_ => 1 } @all;
453 next if $all{$_}; # ok
454 if (m!\A(maildir|mh):(.+)!i) {
456 my $d = "$type:".$lei->abs_path($2);
457 push(@no, $_) unless $all{$d};
459 } elsif (-d "$_/new" && -d "$_/cur") {
460 my $d = 'maildir:'.$lei->abs_path($_);
461 push(@no, $_) unless $all{$d};
463 } elsif (m!\Aimaps?://!i) {
465 my $res = match_imap_url($self, $orig, \@all);
469 # using `$res' instead of `$orig'
472 warn($res, "\n") if defined $res;
475 } elsif (m!\A(?:nntps?|s?news)://!i) {
477 my $res = match_nntp_url($self, $orig, \@all);
481 # using `$res' instead of `$orig'
484 warn($res, "\n") if defined $res;
492 my $no = join("\n\t", @no);
494 No sync information for: $no
495 Run `lei ls-mail-sync' to display valid choices
501 my ($self, @folders) = @_;
502 my $lk = $self->lock_for_scope;
503 for my $folder (@folders) {
504 my $fid = delete($self->{fmap}->{$folder}) //
505 fid_for($self, $folder) // next;
506 for my $t (qw(blob2name blob2num folders)) {
507 $self->{dbh}->do("DELETE FROM $t WHERE fid = ?",
513 # only used for changing canonicalization errors
515 my ($self, $old, $new) = @_;
516 my $lk = $self->lock_for_scope;
517 my $ofid = delete($self->{fmap}->{$old}) //
518 fid_for($self, $old) // return;
520 $self->{dbh}->do(<<EOM, undef, $new, $ofid);
521 UPDATE folders SET loc = ? WHERE fid = ?
524 if ($@ =~ /\bunique\b/i) {
525 my $nfid = $self->{fmap}->{$new} // fid_for($self, $new);
526 for my $t (qw(blob2name blob2num)) {
527 $self->{dbh}->do(<<EOM, undef, $nfid, $ofid);
528 UPDATE OR REPLACE $t SET fid = ? WHERE fid = ?
531 $self->{dbh}->do(<<EOM, undef, $ofid);
532 DELETE FROM folders WHERE fid = ?
537 sub num_oidbin ($$$) {
538 my ($self, $url, $uid) = @_; # $url MUST have UIDVALIDITY if IMAP
539 my $fid = $self->{fmap}->{$url} //= fid_for($self, $url) // return ();
540 my $sth = $self->{dbh}->prepare_cached(<<EOM, undef, 1);
541 SELECT oidbin FROM blob2num WHERE fid = ? AND uid = ? ORDER BY _rowid_
543 $sth->execute($fid, $uid);
544 map { $_->[0] } @{$sth->fetchall_arrayref};
547 sub name_oidbin ($$$) {
548 my ($self, $mdir, $nm) = @_;
549 my $fid = $self->{fmap}->{$mdir} //= fid_for($self, $mdir) // return;
550 my $sth = $self->{dbh}->prepare_cached(<<EOM, undef, 1);
551 SELECT oidbin FROM blob2name WHERE fid = ? AND name = ?
553 $sth->execute($fid, $nm);
554 map { $_->[0] } @{$sth->fetchall_arrayref};
558 my ($self, $lei, $uid_uri) = @_;
559 my $mailbox_uri = $uid_uri->clone;
560 $mailbox_uri->uid(undef);
561 my $folders = [ $$mailbox_uri ];
562 eval { $self->arg2folder($lei, $folders) };
563 $lei->qerr("# no sync information for $mailbox_uri") if $@;
564 map { unpack('H*',$_) } num_oidbin($self, $folders->[0], $uid_uri->uid)