|
| 1 | +package safari |
| 2 | + |
| 3 | +import ( |
| 4 | + "database/sql" |
| 5 | + "fmt" |
| 6 | + "os" |
| 7 | + "path/filepath" |
| 8 | + "regexp" |
| 9 | + "strings" |
| 10 | + |
| 11 | + _ "modernc.org/sqlite" |
| 12 | + |
| 13 | + "github.com/moond4rk/hackbrowserdata/log" |
| 14 | +) |
| 15 | + |
| 16 | +// profileContext tracks the uppercase (Safari/Profiles/<UUID>) and lowercase |
| 17 | +// (WebKit/WebsiteDataStore/<uuid>) UUID forms a named profile needs. Both empty ⇒ default profile. |
| 18 | +type profileContext struct { |
| 19 | + name string |
| 20 | + uuidUpper string |
| 21 | + uuidLower string |
| 22 | + legacyHome string // ~/Library/Safari |
| 23 | + container string // ~/Library/Containers/com.apple.Safari/Data/Library |
| 24 | +} |
| 25 | + |
| 26 | +func (p profileContext) isDefault() bool { return p.uuidUpper == "" } |
| 27 | + |
| 28 | +// downloadOwnerUUID is the value Safari writes into DownloadEntryProfileUUIDStringKey |
| 29 | +// for downloads that belong to this profile. The default profile uses the sentinel |
| 30 | +// "DefaultProfile"; named profiles use their uppercase UUID. |
| 31 | +func (p profileContext) downloadOwnerUUID() string { |
| 32 | + if p.isDefault() { |
| 33 | + return defaultProfileSentinel |
| 34 | + } |
| 35 | + return p.uuidUpper |
| 36 | +} |
| 37 | + |
| 38 | +// SafariTabs.db lists profiles in bookmarks rows with subtype=2. external_uuid "DefaultProfile" |
| 39 | +// is the sentinel for the implicit default, which has no per-UUID directory. |
| 40 | +const ( |
| 41 | + safariTabsDBRelPath = "Safari/SafariTabs.db" |
| 42 | + safariProfileSubtype = 2 |
| 43 | + defaultProfileSentinel = "DefaultProfile" |
| 44 | +) |
| 45 | + |
| 46 | +// Path-unsafe bytes for filenames/CSV values; Unicode letters (CJK etc.) survive. |
| 47 | +var unsafeNameChars = regexp.MustCompile(`[/\\:*?"<>|\x00-\x1f]+`) |
| 48 | + |
| 49 | +// Canonical 8-4-4-4-12 hex UUID — format check only, no semantic parse. |
| 50 | +var uuidPattern = regexp.MustCompile(`^[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$`) |
| 51 | + |
| 52 | +// discoverSafariProfiles always lists the default first, then named profiles from SafariTabs.db |
| 53 | +// (authoritative) with a ReadDir fallback only if the DB itself is unreadable. |
| 54 | +func discoverSafariProfiles(legacyHome string) []profileContext { |
| 55 | + container := deriveContainerRoot(legacyHome) |
| 56 | + |
| 57 | + profiles := []profileContext{{ |
| 58 | + name: "default", |
| 59 | + legacyHome: legacyHome, |
| 60 | + container: container, |
| 61 | + }} |
| 62 | + |
| 63 | + named, err := readNamedProfilesFromDB(container) |
| 64 | + if err != nil { |
| 65 | + // Empty DB (nil, nil) is authoritative; fall back only when DB itself is unreadable. |
| 66 | + named = readNamedProfilesFromDir(container) |
| 67 | + } |
| 68 | + for _, p := range named { |
| 69 | + p.legacyHome = legacyHome |
| 70 | + p.container = container |
| 71 | + profiles = append(profiles, p) |
| 72 | + } |
| 73 | + |
| 74 | + disambiguateNames(profiles) |
| 75 | + return profiles |
| 76 | +} |
| 77 | + |
| 78 | +func deriveContainerRoot(legacyHome string) string { |
| 79 | + return filepath.Join(filepath.Dir(legacyHome), "Containers", "com.apple.Safari", "Data", "Library") |
| 80 | +} |
| 81 | + |
| 82 | +// readNamedProfilesFromDB returns (nil, err) when the DB is missing/unreadable so the caller can |
| 83 | +// try the ReadDir fallback; (slice, nil) — possibly empty — is authoritative. |
| 84 | +func readNamedProfilesFromDB(container string) ([]profileContext, error) { |
| 85 | + // Read-only + immutable so we don't disturb Safari's live WAL. |
| 86 | + dsn := "file:" + filepath.Join(container, safariTabsDBRelPath) + "?mode=ro&immutable=1" |
| 87 | + db, err := sql.Open("sqlite", dsn) |
| 88 | + if err != nil { |
| 89 | + return nil, fmt.Errorf("open SafariTabs.db: %w", err) |
| 90 | + } |
| 91 | + defer db.Close() |
| 92 | + |
| 93 | + // Ping forces connection; sql.Open is lazy and won't detect a missing file. |
| 94 | + if err := db.Ping(); err != nil { |
| 95 | + return nil, fmt.Errorf("ping SafariTabs.db: %w", err) |
| 96 | + } |
| 97 | + |
| 98 | + rows, err := db.Query( |
| 99 | + `SELECT external_uuid, title FROM bookmarks WHERE subtype = ? AND external_uuid != ?`, |
| 100 | + safariProfileSubtype, defaultProfileSentinel, |
| 101 | + ) |
| 102 | + if err != nil { |
| 103 | + return nil, fmt.Errorf("query SafariTabs.db: %w", err) |
| 104 | + } |
| 105 | + defer rows.Close() |
| 106 | + |
| 107 | + var out []profileContext |
| 108 | + for rows.Next() { |
| 109 | + var externalUUID, title sql.NullString |
| 110 | + if err := rows.Scan(&externalUUID, &title); err != nil { |
| 111 | + log.Debugf("safari profiles: scan row: %v", err) |
| 112 | + continue |
| 113 | + } |
| 114 | + if !isCanonicalUUID(externalUUID.String) { |
| 115 | + continue |
| 116 | + } |
| 117 | + out = append(out, newNamedProfile(externalUUID.String, title.String)) |
| 118 | + } |
| 119 | + if err := rows.Err(); err != nil { |
| 120 | + return nil, fmt.Errorf("iterate SafariTabs.db rows: %w", err) |
| 121 | + } |
| 122 | + return out, nil |
| 123 | +} |
| 124 | + |
| 125 | +// readNamedProfilesFromDir is the fallback for missing SafariTabs.db. Names are synthesized from UUIDs. |
| 126 | +func readNamedProfilesFromDir(container string) []profileContext { |
| 127 | + entries, err := os.ReadDir(filepath.Join(container, "Safari", "Profiles")) |
| 128 | + if err != nil { |
| 129 | + return nil |
| 130 | + } |
| 131 | + |
| 132 | + var out []profileContext |
| 133 | + for _, e := range entries { |
| 134 | + if !e.IsDir() || !isCanonicalUUID(e.Name()) { |
| 135 | + continue |
| 136 | + } |
| 137 | + out = append(out, newNamedProfile(e.Name(), "")) |
| 138 | + } |
| 139 | + return out |
| 140 | +} |
| 141 | + |
| 142 | +func newNamedProfile(upperUUID, title string) profileContext { |
| 143 | + return profileContext{ |
| 144 | + name: resolveProfileName(title, upperUUID), |
| 145 | + uuidUpper: upperUUID, |
| 146 | + uuidLower: strings.ToLower(upperUUID), |
| 147 | + } |
| 148 | +} |
| 149 | + |
| 150 | +func isCanonicalUUID(s string) bool { return uuidPattern.MatchString(s) } |
| 151 | + |
| 152 | +// resolveProfileName prefers the SafariTabs.db title, falling back to "profile-<uuid[:8]>". |
| 153 | +func resolveProfileName(title, upperUUID string) string { |
| 154 | + if name := sanitizeProfileName(title); name != "" { |
| 155 | + return name |
| 156 | + } |
| 157 | + return "profile-" + strings.ToLower(upperUUID[:8]) |
| 158 | +} |
| 159 | + |
| 160 | +func sanitizeProfileName(name string) string { |
| 161 | + name = strings.TrimSpace(name) |
| 162 | + if name == "" { |
| 163 | + return "" |
| 164 | + } |
| 165 | + return unsafeNameChars.ReplaceAllString(name, "_") |
| 166 | +} |
| 167 | + |
| 168 | +// disambiguateNames appends "-2", "-3", … to duplicate names, in place. |
| 169 | +func disambiguateNames(profiles []profileContext) { |
| 170 | + occurrences := make(map[string]int, len(profiles)) |
| 171 | + for i := range profiles { |
| 172 | + original := profiles[i].name |
| 173 | + if prior := occurrences[original]; prior > 0 { |
| 174 | + profiles[i].name = fmt.Sprintf("%s-%d", original, prior+1) |
| 175 | + } |
| 176 | + occurrences[original]++ |
| 177 | + } |
| 178 | +} |
0 commit comments