mirror of
https://github.com/phishingclub/phishingclub.git
synced 2026-12-06 01:53:42 +01:00
255 lines
8.1 KiB
Go
255 lines
8.1 KiB
Go
package dbcopy
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
"fmt"
|
|
"net/url"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"gorm.io/driver/sqlite"
|
|
"gorm.io/gorm"
|
|
"gorm.io/gorm/clause"
|
|
"gorm.io/gorm/logger"
|
|
)
|
|
|
|
// ErrSourceDSN is returned for a sqlite DSN the copy can not open read only
|
|
var ErrSourceDSN = errors.New("the sqlite DSN can not be opened read only")
|
|
|
|
// sourceMaxConns is the pool of the source: one connection reads the rows in
|
|
// one read transaction, the other asks for the data version, see Run
|
|
const sourceMaxConns = 2
|
|
|
|
// OpenSource opens the sqlite database of dsn read only. It uses plain
|
|
// gorm.Open with the sqlite driver of mattn and never records the engine of
|
|
// the process (dbengine.SetActive), so a process that opened the postgres
|
|
// target before can open it too. The handle is only for this package, see
|
|
// the package comment.
|
|
//
|
|
// The DSN becomes a file: URI of the absolute path with fixed parameters,
|
|
// see readOnlyDSN: mattn drops the parameters of a DSN that is not a URI
|
|
// before it opens the file, so mode=ro would be lost and a missing file
|
|
// would be made as a new empty database. With mode=ro a missing file is an
|
|
// error. query_only refuses any write on top.
|
|
func OpenSource(dsn string) (*gorm.DB, error) {
|
|
roDSN, err := readOnlyDSN(dsn)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
db, err := gorm.Open(sqlite.Open(roDSN), &gorm.Config{
|
|
Logger: logger.Default.LogMode(logger.Silent),
|
|
})
|
|
if err != nil {
|
|
return nil, sourceOpenError(err)
|
|
}
|
|
sqlDB, err := db.DB()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
sqlDB.SetMaxOpenConns(sourceMaxConns)
|
|
sqlDB.SetMaxIdleConns(sourceMaxConns)
|
|
// gorm opens lazily on some versions, a first read makes a missing or
|
|
// unreadable file fail here
|
|
var n int64
|
|
if err := db.Raw("SELECT COUNT(*) FROM sqlite_master").Scan(&n).Error; err != nil {
|
|
_ = sqlDB.Close()
|
|
return nil, sourceOpenError(err)
|
|
}
|
|
return db, nil
|
|
}
|
|
|
|
// sourceOpenError adds the usual cause to an open error
|
|
func sourceOpenError(err error) error {
|
|
text := strings.ToLower(err.Error())
|
|
if strings.Contains(text, "unable to open") || strings.Contains(text, "readonly") || strings.Contains(text, "read only") {
|
|
return fmt.Errorf(
|
|
"%w: %v; check the path in the config, and run the command as the user of the service, "+
|
|
"sqlite needs to read the database file and to read or make its -shm file next to it",
|
|
ErrSourceDSN, err,
|
|
)
|
|
}
|
|
return fmt.Errorf("%w: %v", ErrSourceDSN, err)
|
|
}
|
|
|
|
// hasControl is true when s holds a NUL or another control character
|
|
func hasControl(s string) bool {
|
|
for _, r := range s {
|
|
if r < 0x20 || r == 0x7f {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// SourceFile returns the absolute path of the sqlite file a DSN names. A
|
|
// relative path is taken from the working directory, as sqlite does. Only
|
|
// the path is kept, the copy opens it with its own parameters.
|
|
func SourceFile(dsn string) (string, error) {
|
|
dsn = strings.TrimSpace(dsn)
|
|
if dsn == "" {
|
|
return "", fmt.Errorf("%w: the DSN is empty", ErrSourceDSN)
|
|
}
|
|
// sqlite stops reading a URI at a # and a C string at a NUL, either
|
|
// would cut off the parameters the copy adds
|
|
if strings.Contains(dsn, "#") || hasControl(dsn) {
|
|
return "", fmt.Errorf("%w: the DSN holds a # or a control character", ErrSourceDSN)
|
|
}
|
|
if strings.Contains(dsn, ":memory:") || strings.Contains(dsn, "mode=memory") {
|
|
return "", fmt.Errorf("%w: an in memory database holds nothing to copy", ErrSourceDSN)
|
|
}
|
|
path := dsn
|
|
if rest, ok := strings.CutPrefix(dsn, "file:"); ok {
|
|
p, _, _ := strings.Cut(rest, "?")
|
|
switch {
|
|
case strings.HasPrefix(p, "//localhost/"):
|
|
p = strings.TrimPrefix(p, "//localhost")
|
|
case strings.HasPrefix(p, "///"):
|
|
p = strings.TrimPrefix(p, "//")
|
|
case strings.HasPrefix(p, "//"):
|
|
return "", fmt.Errorf("%w: a file: URI with a host is not supported", ErrSourceDSN)
|
|
}
|
|
decoded, err := url.PathUnescape(p)
|
|
if err != nil {
|
|
return "", fmt.Errorf("%w: the path can not be read", ErrSourceDSN)
|
|
}
|
|
if hasControl(decoded) {
|
|
return "", fmt.Errorf("%w: the path holds a control character", ErrSourceDSN)
|
|
}
|
|
path = decoded
|
|
} else if strings.ContainsAny(dsn, "?%") {
|
|
// mattn cuts a path that is not a URI at the ?, a % would be read as
|
|
// an escape once the path is a URI
|
|
return "", fmt.Errorf("%w: a path with ? or %% must be given as a file: URI", ErrSourceDSN)
|
|
}
|
|
if path == "" {
|
|
return "", fmt.Errorf("%w: the DSN names no file", ErrSourceDSN)
|
|
}
|
|
abs, err := filepath.Abs(path)
|
|
if err != nil {
|
|
return "", fmt.Errorf("%w: %v", ErrSourceDSN, err)
|
|
}
|
|
return abs, nil
|
|
}
|
|
|
|
// uriPathEscaper escapes the characters a URI path reads in its own way
|
|
var uriPathEscaper = strings.NewReplacer("%", "%25", "?", "%3f", "#", "%23")
|
|
|
|
// readOnlyDSN returns the file of dsn as a file: URI that opens read only.
|
|
// The parameters of the operator are not kept: they could turn off the
|
|
// locking (nolock, immutable, vfs) the copy relies on or ask for write
|
|
// access, and none of them changes what the copy reads.
|
|
func readOnlyDSN(dsn string) (string, error) {
|
|
path, err := SourceFile(dsn)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return "file:" + uriPathEscaper.Replace(path) + "?mode=ro&_query_only=true", nil
|
|
}
|
|
|
|
// sourceColumn is a column of a source table
|
|
type sourceColumn struct {
|
|
Name string
|
|
Type string
|
|
}
|
|
|
|
// sourceTables returns the tables of the source, sqlite internal tables left
|
|
// out
|
|
func sourceTables(src *gorm.DB) ([]string, error) {
|
|
var names []string
|
|
err := src.Raw("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").Scan(&names).Error
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out := names[:0]
|
|
for _, n := range names {
|
|
if strings.HasPrefix(n, "sqlite_") {
|
|
continue
|
|
}
|
|
out = append(out, n)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// sourceColumns returns the columns of a source table with their declared
|
|
// type in lower case, as mattn compares it
|
|
func sourceColumns(src *gorm.DB, table string) ([]sourceColumn, error) {
|
|
var cols []sourceColumn
|
|
err := src.Raw("SELECT name, type FROM pragma_table_info(?) ORDER BY cid", table).Scan(&cols).Error
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for i := range cols {
|
|
cols[i].Type = strings.ToLower(cols[i].Type)
|
|
}
|
|
return cols, nil
|
|
}
|
|
|
|
// sourceRowCount counts the rows of a source table
|
|
func sourceRowCount(src *gorm.DB, table string) (int64, error) {
|
|
var n int64
|
|
err := src.Raw("SELECT COUNT(*) FROM ?", clause.Table{Name: table}).Scan(&n).Error
|
|
return n, err
|
|
}
|
|
|
|
// sourceValueCount counts the values of a source column that are not NULL
|
|
func sourceValueCount(src *gorm.DB, table, column string) (int64, error) {
|
|
var n int64
|
|
err := src.Raw("SELECT COUNT(?) FROM ?", clause.Column{Name: column}, clause.Table{Name: table}).Scan(&n).Error
|
|
return n, err
|
|
}
|
|
|
|
// quickCheck runs the sqlite integrity check that reads every page once
|
|
func quickCheck(src *gorm.DB) error {
|
|
var results []string
|
|
if err := src.Raw("PRAGMA quick_check").Scan(&results).Error; err != nil {
|
|
return err
|
|
}
|
|
if len(results) == 1 && results[0] == "ok" {
|
|
return nil
|
|
}
|
|
n := len(results)
|
|
if n > 3 {
|
|
results = results[:3]
|
|
}
|
|
// the messages name tables and indexes of the file, printed safe
|
|
return fmt.Errorf("the sqlite integrity check found %d problems, for example: %s", n, SafeText(strings.Join(results, "; ")))
|
|
}
|
|
|
|
// dataVersionProbe holds a connection of the source that is not the one of
|
|
// the read transaction. PRAGMA data_version on one connection changes when
|
|
// another connection, of this process or another, commits a change to the
|
|
// file, so two reads on the same connection show whether anything was
|
|
// written in between.
|
|
type dataVersionProbe struct {
|
|
conn *sql.Conn
|
|
}
|
|
|
|
// newDataVersionProbe takes a connection of the source for the probe
|
|
func newDataVersionProbe(ctx context.Context, src *gorm.DB) (*dataVersionProbe, error) {
|
|
sqlDB, err := src.DB()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
conn, err := sqlDB.Conn(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &dataVersionProbe{conn: conn}, nil
|
|
}
|
|
|
|
// read returns the data version the probe connection sees
|
|
func (p *dataVersionProbe) read(ctx context.Context) (int64, error) {
|
|
var v int64
|
|
if err := p.conn.QueryRowContext(ctx, "PRAGMA data_version").Scan(&v); err != nil {
|
|
return 0, err
|
|
}
|
|
return v, nil
|
|
}
|
|
|
|
// close gives the connection back
|
|
func (p *dataVersionProbe) close() {
|
|
_ = p.conn.Close()
|
|
}
|