mirror of
https://github.com/phishingclub/phishingclub.git
synced 2026-12-06 01:53:42 +01:00
373 lines
11 KiB
Go
373 lines
11 KiB
Go
package dbcopy
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"sort"
|
|
"strings"
|
|
"time"
|
|
"unicode"
|
|
"unicode/utf8"
|
|
)
|
|
|
|
// maxExamples is how many example rows the report keeps per item
|
|
const maxExamples = 5
|
|
|
|
// TableReport is what the copy did with one table
|
|
type TableReport struct {
|
|
Name string
|
|
SourceRows int64
|
|
Copied int64
|
|
Skipped int64
|
|
// NotCopied is the reason a table is left out on purpose, see
|
|
// notCopiedTables
|
|
NotCopied string
|
|
}
|
|
|
|
// CleanedItem counts the text values of a column that held a NUL or bytes
|
|
// that are not UTF-8, and were stored cleaned (dbengine.CleanText)
|
|
type CleanedItem struct {
|
|
Table string
|
|
Column string
|
|
Count int64
|
|
RowIDs []int64
|
|
}
|
|
|
|
// InvalidItem counts the values of a column that can not be copied
|
|
type InvalidItem struct {
|
|
Table string
|
|
Column string
|
|
Kind string
|
|
Count int64
|
|
RowIDs []int64
|
|
}
|
|
|
|
// OrphanExample is one row left out for a missing parent: the sqlite rowid
|
|
// of the row and the key it points at
|
|
type OrphanExample struct {
|
|
RowID int64
|
|
MissingKey string
|
|
}
|
|
|
|
// OrphanItem counts the rows of a table whose foreign key points at a row
|
|
// that is not in the target
|
|
type OrphanItem struct {
|
|
Table string
|
|
Column string
|
|
Parent string
|
|
ParentColumn string
|
|
Count int64
|
|
Examples []OrphanExample
|
|
}
|
|
|
|
// UnknownTable is a source table the application does not have
|
|
type UnknownTable struct {
|
|
Name string
|
|
Rows int64
|
|
}
|
|
|
|
// UnknownColumn is a source column the application does not have
|
|
type UnknownColumn struct {
|
|
Table string
|
|
Column string
|
|
Values int64
|
|
}
|
|
|
|
// PackageItem is an installed Bait Box package
|
|
type PackageItem struct {
|
|
PackageID string
|
|
Version string
|
|
}
|
|
|
|
// BaselineItem is an installed Bait Box resource whose baseline was not
|
|
// recomputed
|
|
type BaselineItem struct {
|
|
ResourceType string
|
|
ResourceID string
|
|
Reason string
|
|
}
|
|
|
|
// Report is the result of a copy. It holds counts, names and sqlite rowids,
|
|
// and the uuid of a missing parent row, never a value of a row.
|
|
type Report struct {
|
|
DryRun bool
|
|
Force bool
|
|
Committed bool
|
|
Duration time.Duration
|
|
// SchemaMade is set once the schema build started in the target
|
|
SchemaMade bool
|
|
// SourceRead is set once the first pass read every row
|
|
SourceRead bool
|
|
// Err is the error the run ended with
|
|
Err error
|
|
|
|
Tables []TableReport
|
|
Cleaned []CleanedItem
|
|
Invalid []InvalidItem
|
|
Orphans []OrphanItem
|
|
UnknownTables []UnknownTable
|
|
UnknownColumns []UnknownColumn
|
|
// LegacyTables and LegacyColumns are what earlier versions made and
|
|
// this version no longer has, see legacyColumns
|
|
LegacyTables []UnknownTable
|
|
LegacyColumns []UnknownColumn
|
|
ExtraTarget []string
|
|
// TimesTruncated counts the time values with digits below a
|
|
// microsecond, which postgres does not keep
|
|
TimesTruncated int64
|
|
// PackagesNotClean are the installed Bait Box packages whose installed
|
|
// content held a NUL or text that is not UTF-8
|
|
PackagesNotClean []PackageItem
|
|
|
|
// BaselinesRebased counts the Bait Box baselines made again from the
|
|
// cleaned text
|
|
BaselinesRebased int
|
|
BaselinesKept []BaselineItem
|
|
}
|
|
|
|
// Rows returns the number of source rows and of copied rows
|
|
func (r *Report) Rows() (source, copied int64) {
|
|
for _, t := range r.Tables {
|
|
source += t.SourceRows
|
|
copied += t.Copied
|
|
}
|
|
return source, copied
|
|
}
|
|
|
|
// cleanedFor returns the cleaned counter of a column, made when missing
|
|
func (r *Report) cleanedFor(table, col string) *CleanedItem {
|
|
for i := range r.Cleaned {
|
|
if r.Cleaned[i].Table == table && r.Cleaned[i].Column == col {
|
|
return &r.Cleaned[i]
|
|
}
|
|
}
|
|
r.Cleaned = append(r.Cleaned, CleanedItem{Table: table, Column: col})
|
|
return &r.Cleaned[len(r.Cleaned)-1]
|
|
}
|
|
|
|
// addInvalid counts an invalid value
|
|
func (r *Report) addInvalid(table, col string, k invalidKind, rowid int64) {
|
|
for i := range r.Invalid {
|
|
it := &r.Invalid[i]
|
|
if it.Table == table && it.Column == col && it.Kind == string(k) {
|
|
it.Count++
|
|
if len(it.RowIDs) < maxExamples {
|
|
it.RowIDs = append(it.RowIDs, rowid)
|
|
}
|
|
return
|
|
}
|
|
}
|
|
r.Invalid = append(r.Invalid, InvalidItem{Table: table, Column: col, Kind: string(k), Count: 1, RowIDs: []int64{rowid}})
|
|
}
|
|
|
|
// addOrphan counts a row left out for a missing parent
|
|
func (r *Report) addOrphan(table string, fk foreignKey, rowid int64, key string) {
|
|
for i := range r.Orphans {
|
|
it := &r.Orphans[i]
|
|
if it.Table == table && it.Column == fk.column {
|
|
it.Count++
|
|
if len(it.Examples) < maxExamples {
|
|
it.Examples = append(it.Examples, OrphanExample{RowID: rowid, MissingKey: key})
|
|
}
|
|
return
|
|
}
|
|
}
|
|
r.Orphans = append(r.Orphans, OrphanItem{
|
|
Table: table, Column: fk.column, Parent: fk.parent, ParentColumn: fk.parentColumn,
|
|
Count: 1, Examples: []OrphanExample{{RowID: rowid, MissingKey: key}},
|
|
})
|
|
}
|
|
|
|
// cleanedCount returns how many values of a table were cleaned
|
|
func (r *Report) cleanedCount(table string) int64 {
|
|
var n int64
|
|
for _, c := range r.Cleaned {
|
|
if c.Table == table {
|
|
n += c.Count
|
|
}
|
|
}
|
|
return n
|
|
}
|
|
|
|
// SafeText returns s with every control and format character, and every
|
|
// byte that is not UTF-8, written as an escape. Names and messages read
|
|
// from the sqlite file can hold any byte, and a terminal would act on an
|
|
// escape sequence in them.
|
|
func SafeText(s string) string {
|
|
var b strings.Builder
|
|
for i := 0; i < len(s); {
|
|
r, size := utf8.DecodeRuneInString(s[i:])
|
|
switch {
|
|
case r == utf8.RuneError && size == 1:
|
|
fmt.Fprintf(&b, "\\x%02x", s[i])
|
|
case unicode.Is(unicode.Cc, r) || unicode.Is(unicode.Cf, r):
|
|
fmt.Fprintf(&b, "\\u%04x", r)
|
|
default:
|
|
b.WriteString(s[i : i+size])
|
|
}
|
|
i += size
|
|
}
|
|
return b.String()
|
|
}
|
|
|
|
// Print writes the report for the operator. Every name that comes from the
|
|
// sqlite file goes through SafeText.
|
|
func (r *Report) Print(w io.Writer) {
|
|
p := func(format string, args ...any) { _, _ = fmt.Fprintf(w, format+"\n", args...) }
|
|
source, copied := r.Rows()
|
|
if len(r.Tables) > 0 {
|
|
p("")
|
|
p("Tables (in copy order):")
|
|
for _, t := range r.Tables {
|
|
line := fmt.Sprintf(" %-32s %10d rows", t.Name, t.SourceRows)
|
|
switch {
|
|
case t.NotCopied != "":
|
|
line += ", not copied: " + t.NotCopied
|
|
case t.Skipped > 0:
|
|
line += fmt.Sprintf(", %d left out", t.Skipped)
|
|
}
|
|
p("%s", line)
|
|
}
|
|
switch {
|
|
case r.Committed:
|
|
p("Rows: %d in sqlite, %d copied", source, copied)
|
|
case r.DryRun && r.Err == nil:
|
|
p("Rows: %d in sqlite, %d would be copied", source, copied)
|
|
case r.SourceRead:
|
|
p("Rows: %d in sqlite, none committed", source)
|
|
}
|
|
}
|
|
if len(r.LegacyTables) > 0 || len(r.LegacyColumns) > 0 {
|
|
p("")
|
|
p("Left over from earlier versions, which this version no longer uses (not copied):")
|
|
for _, t := range r.LegacyTables {
|
|
p(" %s: %d rows", SafeText(t.Name), t.Rows)
|
|
}
|
|
for _, c := range r.LegacyColumns {
|
|
p(" %s.%s: %d values", SafeText(c.Table), SafeText(c.Column), c.Values)
|
|
}
|
|
}
|
|
if len(r.UnknownTables) > 0 {
|
|
p("")
|
|
p("Tables in sqlite this version does not have (not copied):")
|
|
for _, t := range r.UnknownTables {
|
|
p(" %s: %d rows", SafeText(t.Name), t.Rows)
|
|
}
|
|
}
|
|
if len(r.UnknownColumns) > 0 {
|
|
p("")
|
|
p("Columns in sqlite this version does not have (not copied):")
|
|
for _, c := range r.UnknownColumns {
|
|
p(" %s.%s: %d values", SafeText(c.Table), SafeText(c.Column), c.Values)
|
|
}
|
|
}
|
|
if len(r.ExtraTarget) > 0 {
|
|
names := make([]string, 0, len(r.ExtraTarget))
|
|
for _, n := range r.ExtraTarget {
|
|
names = append(names, SafeText(n))
|
|
}
|
|
p("")
|
|
p("Empty tables in the target that are not tables of the application (left as they are): %s", strings.Join(names, ", "))
|
|
}
|
|
if len(r.Invalid) > 0 {
|
|
p("")
|
|
p("Values that can not be copied (fix them in a copy of the sqlite file, values are not shown):")
|
|
rowIDs := false
|
|
for _, it := range r.Invalid {
|
|
p(" %s.%s: %d %s, rowids %s", it.Table, it.Column, it.Count, it.Kind, joinInts(it.RowIDs))
|
|
if it.Kind == string(invalidRowID) {
|
|
rowIDs = true
|
|
}
|
|
}
|
|
if rowIDs {
|
|
p(" A rowid above 2^62 leaves postgres no room to number the new rows of the table;")
|
|
p(" give those rows a smaller rowid in a copy of the sqlite file.")
|
|
}
|
|
}
|
|
if len(r.Cleaned) > 0 {
|
|
sort.SliceStable(r.Cleaned, func(i, j int) bool {
|
|
if r.Cleaned[i].Table != r.Cleaned[j].Table {
|
|
return r.Cleaned[i].Table < r.Cleaned[j].Table
|
|
}
|
|
return r.Cleaned[i].Column < r.Cleaned[j].Column
|
|
})
|
|
p("")
|
|
p("Text with a NUL or bytes that are not UTF-8, stored with the control character U+001A")
|
|
p("in place of each NUL and of each run of such bytes:")
|
|
for _, c := range r.Cleaned {
|
|
p(" %s.%s: %d values, rowids %s", c.Table, c.Column, c.Count, joinInts(c.RowIDs))
|
|
}
|
|
p(" A cleaned value that the application checks only when it changes, such as a redirect URL, is not checked again;")
|
|
p(" look at these rows in the application after the switch.")
|
|
}
|
|
if r.TimesTruncated > 0 {
|
|
p("")
|
|
p("Times: %d values had digits below a microsecond; postgres keeps microseconds, those digits were dropped.", r.TimesTruncated)
|
|
}
|
|
if len(r.Orphans) > 0 {
|
|
p("")
|
|
if r.Force {
|
|
p("Rows left out because the row they point at is missing (--force):")
|
|
} else {
|
|
p("Rows whose foreign key points at a missing row (refused, --force leaves them out):")
|
|
}
|
|
for _, o := range r.Orphans {
|
|
examples := make([]string, 0, len(o.Examples))
|
|
for _, e := range o.Examples {
|
|
examples = append(examples, fmt.Sprintf("rowid %d -> %s", e.RowID, SafeText(e.MissingKey)))
|
|
}
|
|
p(" %s.%s -> %s.%s: %d rows (%s)", o.Table, o.Column, o.Parent, o.ParentColumn, o.Count, strings.Join(examples, ", "))
|
|
}
|
|
}
|
|
if len(r.PackagesNotClean) > 0 {
|
|
p("")
|
|
p("Bait Box packages whose installed content holds a NUL or text that is not UTF-8.")
|
|
p("Postgres refuses such a package, so an update of these fails until the author publishes a UTF-8 version:")
|
|
for _, pk := range r.PackagesNotClean {
|
|
p(" %s %s", SafeText(pk.PackageID), SafeText(pk.Version))
|
|
}
|
|
}
|
|
if r.BaselinesRebased > 0 || len(r.BaselinesKept) > 0 {
|
|
p("")
|
|
p("Bait Box: %d installed resources with cleaned text got a new baseline.", r.BaselinesRebased)
|
|
if len(r.BaselinesKept) > 0 {
|
|
p("Bait Box resources with cleaned text that keep their baseline; the next update may ask to keep or replace them:")
|
|
for _, b := range r.BaselinesKept {
|
|
p(" %s %s: %s", SafeText(b.ResourceType), SafeText(b.ResourceID), b.Reason)
|
|
}
|
|
}
|
|
}
|
|
p("")
|
|
p("%s", r.footer())
|
|
}
|
|
|
|
// footer says what the run left in the target
|
|
func (r *Report) footer() string {
|
|
const schemaLeft = " The target keeps the empty schema of this version (tables, indexes and sequences);" +
|
|
" the copy accepts such a target, a new run can use it."
|
|
switch {
|
|
case r.Committed:
|
|
return fmt.Sprintf("Copied and committed in %s.", r.Duration.Round(time.Second))
|
|
case r.DryRun && r.Err == nil:
|
|
return "Dry run: every row was rolled back." + schemaLeft
|
|
case !r.SchemaMade && errors.Is(r.Err, ErrCancelled):
|
|
return "Cancelled, nothing was written to the target."
|
|
case !r.SchemaMade:
|
|
return "Nothing was written to the target."
|
|
case errors.Is(r.Err, ErrCancelled):
|
|
return "Cancelled, every row was rolled back." + schemaLeft
|
|
default:
|
|
return "Nothing was committed, every row was rolled back." + schemaLeft
|
|
}
|
|
}
|
|
|
|
// joinInts formats a list of rowids
|
|
func joinInts(ids []int64) string {
|
|
parts := make([]string, 0, len(ids))
|
|
for _, id := range ids {
|
|
parts = append(parts, fmt.Sprintf("%d", id))
|
|
}
|
|
return strings.Join(parts, ", ")
|
|
}
|