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] }
54 my ($self, $dbh) = @_;
55 my $lk = $self->lock_for_scope;
58 CREATE TABLE IF NOT EXISTS folders (
59 fid INTEGER PRIMARY KEY,
60 loc VARBINARY NOT NULL, /* URL;UIDVALIDITY=$N or $TYPE:/pathname */
65 CREATE TABLE IF NOT EXISTS blob2num (
66 oidbin VARBINARY NOT NULL,
67 fid INTEGER NOT NULL, /* folder ID */
68 uid INTEGER NOT NULL, /* NNTP article number, IMAP UID, MH number */
69 /* not UNIQUE(fid, uid), since we may have broken servers */
70 UNIQUE (oidbin, fid, uid)
73 # speeds up LeiImport->ck_update_kw (for "lei import") by 5-6x:
75 CREATE INDEX IF NOT EXISTS idx_fid_uid ON blob2num(fid,uid)
78 CREATE TABLE IF NOT EXISTS blob2name (
79 oidbin VARBINARY NOT NULL,
80 fid INTEGER NOT NULL, /* folder ID */
81 name VARBINARY NOT NULL, /* Maildir basename, JMAP blobId */
82 /* not UNIQUE(fid, name), since we may have broken software */
83 UNIQUE (oidbin, fid, name)
86 # speeds up LeiImport->pmdir_cb (for "lei import") by ~6x:
88 CREATE INDEX IF NOT EXISTS idx_fid_name ON blob2name(fid,name)
93 my ($self, $folder, $rw) = @_;
94 my $dbh = $self->{dbh} //= dbh_new($self, $rw);
95 my $sel = 'SELECT fid FROM folders WHERE loc = ? LIMIT 1';
96 my ($fid) = $dbh->selectrow_array($sel, undef, $folder);
97 return $fid if defined $fid;
99 # caller had trailing slash (LeiToMail)
100 if ($folder =~ s!\A((?:maildir|mh):.*?)/+\z!$1!i) {
101 ($fid) = $dbh->selectrow_array($sel, undef, $folder);
103 $dbh->do(<<EOM, undef, $folder, $fid) if $rw;
104 UPDATE folders SET loc = ? WHERE fid = ?
108 # sometimes we stored trailing slash..
109 } elsif ($folder =~ m!\A(?:maildir|mh):!i) {
110 ($fid) = $dbh->selectrow_array($sel, undef, "$folder/");
112 $dbh->do(<<EOM, undef, $folder, $fid) if $rw;
113 UPDATE folders SET loc = ? WHERE fid = ?
117 } elsif ($rw && $folder =~ m!\Aimaps?://!i) {
118 require PublicInbox::URIimap;
119 PublicInbox::URIimap->new($folder)->uidvalidity //
120 Carp::croak("BUG: $folder has no UIDVALIDITY");
124 ($fid) = $dbh->selectrow_array('SELECT MAX(fid) FROM folders');
127 # in case we're reusing, clobber existing stale refs:
128 $dbh->do('DELETE FROM blob2name WHERE fid = ?', undef, $fid);
129 $dbh->do('DELETE FROM blob2num WHERE fid = ?', undef, $fid);
131 my $sth = $dbh->prepare('INSERT INTO folders (fid, loc) VALUES (?, ?)');
132 $sth->execute($fid, $folder);
138 my ($self, @folders) = @_;
139 my $lk = $self->lock_for_scope;
140 for my $f (@folders) { $self->{fmap}->{$f} //= fid_for($self, $f, 1) }
144 my ($self, $oidbin, $folder, $id) = @_;
145 my $lk = $self->lock_for_scope;
146 my $fid = $self->{fmap}->{$folder} //= fid_for($self, $folder, 1);
148 if (ref($id)) { # scalar name
150 $sth = $self->{dbh}->prepare_cached(<<'');
151 INSERT OR IGNORE INTO blob2name (oidbin, fid, name) VALUES (?, ?, ?)
153 } else { # numeric ID (IMAP UID, MH number)
154 $sth = $self->{dbh}->prepare_cached(<<'');
155 INSERT OR IGNORE INTO blob2num (oidbin, fid, uid) VALUES (?, ?, ?)
158 $sth->execute($oidbin, $fid, $id);
162 my ($self, $folder, $id) = @_;
163 my $lk = $self->lock_for_scope;
164 my $fid = $self->{fmap}->{$folder} //= fid_for($self, $folder, 1);
166 if (ref($id)) { # scalar name
168 $sth = $self->{dbh}->prepare_cached(<<'');
169 DELETE FROM blob2name WHERE fid = ? AND name = ?
172 $sth = $self->{dbh}->prepare_cached(<<'');
173 DELETE FROM blob2num WHERE fid = ? AND uid = ?
176 $sth->execute($fid, $id);
181 my ($self, $folder, $oidbin, $id, $newbn) = @_;
182 my $lk = $self->lock_for_scope;
183 my $fid = $self->{fmap}->{$folder} //= fid_for($self, $folder, 1);
184 my $sth = $self->{dbh}->prepare_cached(<<'');
185 UPDATE blob2name SET name = ? WHERE fid = ? AND oidbin = ? AND name = ?
187 my $nr = $sth->execute($newbn, $fid, $oidbin, $$id);
188 if ($nr == 0) { # may race with a clear_src, ensure new value exists
189 $sth = $self->{dbh}->prepare_cached(<<'');
190 INSERT OR IGNORE INTO blob2name (oidbin, fid, name) VALUES (?, ?, ?)
192 $sth->execute($oidbin, $fid, $newbn);
196 # read-only, iterates every oidbin + UID or name for a given folder
198 my ($self, $folder, $cb, @args) = @_;
199 my $dbh = $self->{dbh} //= dbh_new($self);
202 if (ref($folder) eq 'HASH') {
203 $fid = $folder->{fid} // die "BUG: no `fid'";
204 @rng = grep(defined, @$folder{qw(min max)});
205 $and_ge_le = 'AND uid >= ? AND uid <= ?' if @rng;
207 $fid = $self->{fmap}->{$folder} //=
208 fid_for($self, $folder) // return;
211 # minimize implicit txn time to avoid blocking writers by
212 # batching SELECTs. This looks wonky but is necessary since
213 # $cb-> may access the DB on its own.
214 my $ary = $dbh->selectall_arrayref(<<"", undef, $fid, @rng);
215 SELECT _rowid_,oidbin,uid FROM blob2num WHERE fid = ? $and_ge_le
216 ORDER BY _rowid_ ASC LIMIT 1000
218 my $min = @$ary ? $ary->[-1]->[0] : undef;
219 while (defined $min) {
220 for my $row (@$ary) { $cb->($row->[1], $row->[2], @args) }
222 $ary = $dbh->selectall_arrayref(<<"", undef, $fid, @rng, $min);
223 SELECT _rowid_,oidbin,uid FROM blob2num
224 WHERE fid = ? $and_ge_le AND _rowid_ > ?
225 ORDER BY _rowid_ ASC LIMIT 1000
227 $min = @$ary ? $ary->[-1]->[0] : undef;
230 $ary = $dbh->selectall_arrayref(<<'', undef, $fid);
231 SELECT _rowid_,oidbin,name FROM blob2name WHERE fid = ?
232 ORDER BY _rowid_ ASC LIMIT 1000
234 $min = @$ary ? $ary->[-1]->[0] : undef;
235 while (defined $min) {
236 for my $row (@$ary) { $cb->($row->[1], \($row->[2]), @args) }
238 $ary = $dbh->selectall_arrayref(<<'', undef, $fid, $min);
239 SELECT _rowid_,oidbin,name FROM blob2name WHERE fid = ? AND _rowid_ > ?
240 ORDER BY _rowid_ ASC LIMIT 1000
242 $min = @$ary ? $ary->[-1]->[0] : undef;
247 my ($self, $folder) = @_;
248 my $dbh = $self->{dbh} //= dbh_new($self);
251 $fid = $self->{fmap}->{$folder} //= fid_for($self, $folder) // return;
252 my ($row) = $dbh->selectrow_array(<<"", undef, $fid);
253 SELECT COUNT(name) FROM blob2name WHERE fid = ?
255 $ret->{'name.count'} = $row if $row;
256 my $ntype = ($folder =~ m!\A(?:nntps?|s?news)://!i) ? 'article' :
257 (($folder =~ m!\Aimaps?://!i) ? 'uid' : "TODO<$folder>");
258 for my $op (qw(count min max)) {
259 ($row) = $dbh->selectrow_array(<<"", undef, $fid);
260 SELECT $op(uid) FROM blob2num WHERE fid = ?
263 $ret->{"$ntype.$op"} = $row;
268 # returns a { location => [ list-of-ids-or-names ] } mapping
270 my ($self, $oidbin) = @_;
271 my ($fid, $sth, $id, %fid2id);
272 my $dbh = $self->{dbh} //= dbh_new($self);
273 $sth = $dbh->prepare('SELECT fid,uid FROM blob2num WHERE oidbin = ?');
274 $sth->execute($oidbin);
275 while (my ($fid, $uid) = $sth->fetchrow_array) {
276 push @{$fid2id{$fid}}, $uid;
278 $sth = $dbh->prepare('SELECT fid,name FROM blob2name WHERE oidbin = ?');
279 $sth->execute($oidbin);
280 while (my ($fid, $name) = $sth->fetchrow_array) {
281 push @{$fid2id{$fid}}, $name;
283 $sth = $dbh->prepare('SELECT loc FROM folders WHERE fid = ? LIMIT 1');
285 while (my ($fid, $ids) = each %fid2id) {
287 my ($loc) = $sth->fetchrow_array;
288 unless (defined $loc) {
289 my $oidhex = unpack('H*', $oidbin);
290 warn "E: fid=$fid for $oidhex unknown:\n", map {
291 'E: '.(ref() ? $$_ : "#$_")."\n";
297 scalar(keys %$ret) ? $ret : undef;
300 # returns a list of folders used for completion
302 my ($self, @pfx) = @_;
303 my $sql = 'SELECT loc FROM folders';
304 if (defined($pfx[0])) {
305 $sql .= ' WHERE loc LIKE ? ESCAPE ?';
306 my $anywhere = !!$pfx[1];
308 $pfx[0] =~ s/([%_\\])/\\$1/g; # glob chars
310 substr($pfx[0], 0, 0, '%') if $anywhere;
312 @pfx = (); # [0] may've been undef
314 my $dbh = $self->{dbh} //= dbh_new($self);
315 map { $_->[0] } @{$dbh->selectall_arrayref($sql, undef, @pfx)};
319 my ($self, $oidhex, $vrfy) = @_;
320 my $dbh = $self->{dbh} //= dbh_new($self);
321 my $b2n = $dbh->prepare(<<'');
322 SELECT f.loc,b.name FROM blob2name b
323 LEFT JOIN folders f ON b.fid = f.fid
326 $b2n->execute(pack('H*', $oidhex));
327 while (my ($d, $n) = $b2n->fetchrow_array) {
328 substr($d, 0, length('maildir:')) = '';
329 # n.b. both mbsync and offlineimap use ":2," as a suffix
330 # in "new/", despite (from what I understand of reading
331 # <https://cr.yp.to/proto/maildir.html>), the ":2," only
332 # applies to files in "cur/".
333 my @try = $n =~ /:2,[a-zA-Z]+\z/ ? qw(cur new) : qw(new cur);
336 open my $fh, '<', $f or next;
337 # some (buggy) Maildir writers are non-atomic:
341 if ($vrfy && git_sha(1, \$raw)->hexdigest ne $oidhex) {
342 warn "$f changed $oidhex\n";
352 my ($self, $url, $all) = @_; # $all = [ $lms->folders ];
353 $all //= [ $self->folders ];
354 require PublicInbox::URIimap;
355 my $want = PublicInbox::URIimap->new($url)->canonical;
356 my ($s, $h, $mb) = ($want->scheme, $want->host, $want->mailbox);
357 my @uri = map { PublicInbox::URIimap->new($_)->canonical }
358 grep(m!\A\Q$s\E://.*?\Q$h\E\b.*?/\Q$mb\E\b!, @$all);
361 next if $x->mailbox ne $want->mailbox;
362 next if $x->host ne $want->host;
363 next if $x->port != $want->port;
364 my $x_uidval = $x->uidvalidity;
365 next if ($want->uidvalidity // $x_uidval) != $x_uidval;
367 # allow nothing in want to possibly match ";AUTH=ANONYMOUS"
368 if (defined($x->auth) && !defined($want->auth) &&
369 !defined($want->user)) {
371 # or maybe user was forgotten on CLI:
372 } elsif (defined($x->user) && !defined($want->user)) {
374 } elsif (($x->user//"\0") eq ($want->user//"\0")) {
378 return @match if wantarray;
379 scalar(@match) <= 1 ? $match[0] :
380 "E: `$url' is ambiguous:\n\t".join("\n\t", @match)."\n";
383 sub match_nntp_url ($$$) {
384 my ($self, $url, $all) = @_; # $all = [ $lms->folders ];
385 $all //= [ $self->folders ];
386 require PublicInbox::URInntps;
387 my $want = PublicInbox::URInntps->new($url)->canonical;
388 my ($s, $h, $p) = ($want->scheme, $want->host, $want->port);
389 my $ng = $want->group; # force scalar (no article ranges)
390 my @uri = map { PublicInbox::URInntps->new($_)->canonical }
391 grep(m!\A\Q$s\E://.*?\Q$h\E\b.*?/\Q$ng\E\b!, @$all);
394 next if $x->group ne $ng || $x->host ne $h || $x->port != $p;
395 # maybe user was forgotten on CLI:
396 if (defined($x->userinfo) && !defined($want->userinfo)) {
398 } elsif (($x->userinfo//"\0") eq ($want->userinfo//"\0")) {
402 return @match if wantarray;
403 scalar(@match) <= 1 ? $match[0] :
404 "E: `$url' is ambiguous:\n\t".join("\n\t", @match)."\n";
407 # returns undef on failure, number on success
409 my ($self, $lei, $all, $folders) = @_;
410 return $lei->fail(<<EOM) if @$folders;
411 --all= not compatible with @$folders on command-line
413 my %x = map { $_ => $_ } split(/,/, $all);
414 my @ok = grep(defined, delete(@x{qw(local remote), ''}));
415 push(@ok, '') if $all eq '';
418 @no = (join(',', @no));
419 return $lei->fail(<<EOM);
420 --all=@no not accepted (must be `local' and/or `remote')
424 my @all = $self->folders;
426 if ($ok eq 'local') {
427 @inc = grep(!m!\A[a-z0-9\+]+://!i, @all);
428 } elsif ($ok eq 'remote') {
429 @inc = grep(m!\A[a-z0-9\+]+://!i, @all);
430 } elsif ($ok ne '') {
431 return $lei->fail("--all=$all not understood");
435 push(@$folders, (grep { !$seen{$_}++ } @inc));
437 scalar(@$folders) || $lei->fail(<<EOM);
438 no --mail-sync folders known to lei
442 # map CLI args to folder table entries, returns undef on failure
444 my ($self, $lei, $folders) = @_;
445 my @all = $self->folders;
446 my %all = map { $_ => 1 } @all;
449 next if $all{$_}; # ok
450 if (m!\A(maildir|mh):(.+)!i) {
452 my $d = "$type:".$lei->abs_path($2);
453 push(@no, $_) unless $all{$d};
455 } elsif (-d "$_/new" && -d "$_/cur") {
456 my $d = 'maildir:'.$lei->abs_path($_);
457 push(@no, $_) unless $all{$d};
459 } elsif (m!\Aimaps?://!i) {
461 my $res = match_imap_url($self, $orig, \@all);
465 # using `$res' instead of `$orig'
468 $lei->err($res) if defined $res;
471 } elsif (m!\A(?:nntps?|s?news)://!i) {
473 my $res = match_nntp_url($self, $orig, \@all);
477 # using `$res' instead of `$orig'
480 $lei->err($res) if defined $res;
488 my $no = join("\n\t", @no);
490 No sync information for: $no
491 Run `lei ls-mail-sync' to display valid choices
497 my ($self, @folders) = @_;
498 my $lk = $self->lock_for_scope;
499 for my $folder (@folders) {
500 my $fid = delete($self->{fmap}->{$folder}) //
501 fid_for($self, $folder) // next;
502 for my $t (qw(blob2name blob2num folders)) {
503 $self->{dbh}->do("DELETE FROM $t WHERE fid = ?",
509 # only used for changing canonicalization errors
511 my ($self, $old, $new) = @_;
512 my $lk = $self->lock_for_scope;
513 my $ofid = delete($self->{fmap}->{$old}) //
514 fid_for($self, $old) // return;
516 $self->{dbh}->do(<<EOM, undef, $new, $ofid);
517 UPDATE folders SET loc = ? WHERE fid = ?
520 if ($@ =~ /\bunique\b/i) {
521 my $nfid = $self->{fmap}->{$new} // fid_for($self, $new);
522 for my $t (qw(blob2name blob2num)) {
523 $self->{dbh}->do(<<EOM, undef, $nfid, $ofid);
524 UPDATE OR REPLACE $t SET fid = ? WHERE fid = ?
527 $self->{dbh}->do(<<EOM, undef, $ofid);
528 DELETE FROM folders WHERE fid = ?
533 sub num_oidbin ($$$) {
534 my ($self, $url, $uid) = @_; # $url MUST have UIDVALIDITY if IMAP
535 my $fid = $self->{fmap}->{$url} //= fid_for($self, $url) // return ();
536 my $sth = $self->{dbh}->prepare_cached(<<EOM, undef, 1);
537 SELECT oidbin FROM blob2num WHERE fid = ? AND uid = ? ORDER BY _rowid_
539 $sth->execute($fid, $uid);
540 map { $_->[0] } @{$sth->fetchall_arrayref};
543 sub name_oidbin ($$$) {
544 my ($self, $mdir, $nm) = @_;
545 my $fid = $self->{fmap}->{$mdir} //= fid_for($self, $mdir) // return;
546 my $sth = $self->{dbh}->prepare_cached(<<EOM, undef, 1);
547 SELECT oidbin FROM blob2name WHERE fid = ? AND name = ?
549 $sth->execute($fid, $nm);
550 map { $_->[0] } @{$sth->fetchall_arrayref};
554 my ($self, $lei, $uid_uri) = @_;
555 my $mailbox_uri = $uid_uri->clone;
556 $mailbox_uri->uid(undef);
557 my $folders = [ $$mailbox_uri ];
558 eval { $self->arg2folder($lei, $folders) };
559 $lei->qerr("# no sync information for $mailbox_uri") if $@;
560 map { unpack('H*',$_) } num_oidbin($self, $folders->[0], $uid_uri->uid)