//Rather than storing session state directly chrome appends a pickled command to a
//session file as tabs are manipulated. These commands are subsequently used to
//reconstruct the session when the browser is restarted. Thus obtaining the
//working tab set involves attemping to simulate the reconstruction process
//performed by chrome (which is an implementation detail liable to change).
//A file has the following format:
//"SNSS"
//int32 version number (should be 1)
//...
type group struct {
high uint64
low uint64
name string
}
type window struct {
activeTabIdx uint32
id uint32
deleted bool
tabs []*tab
}
type histItem struct {
idx uint32
url string
title string
}
type tab struct {
id uint32
history []*histItem
idx uint32 //The tab position in the window (a relative value)
win uint32 //the id of the window to which the tab belongs
deleted bool
currentHistoryIdx uint32
group *group //May be null
}
Assistant
//indexed by id
var tabs = map[uint32]*tab{}
var windows = map[uint32]*window{}
var groups = map[string]*group{}
func getWindow(id uint32) *window {
if _, ok := windows[id]; !ok {
windows[id] = &window{id: id}
}
func getTab(id uint32) *tab {
if _, ok := tabs[id]; !ok {
tabs[id] = &tab{id: id}
}
return tabs[id]
}
func readUint8(r io.Reader) uint8 {
var b [1]byte
if n, err := r.Read(b[:]); err != nil || n != 1 {
if err != nil {
panic(err)
}
panic(fmt.Errorf("Failed to read int8."))
}
return uint8(b[0])
}
func readUint16(r io.Reader) uint16 {
var b [2]byte
if n, err := r.Read(b[:]); err != nil || n != 2 {
if err != nil {
panic(err)
}
panic(fmt.Errorf("Failed to read int16."))
}
return uint16(b[0]) | uint16(b[1])<<8
}
func readUint32(r io.Reader) uint32 {
var b [4]byte
if n, err := r.Read(b[:]); err != nil || n != 4 {
if err != nil {
panic(err)
}
b := make([]byte, rsz)
if n, err := io.ReadFull(r, b); err != nil {
panic(err)
} else if n != len(b) {
panic(fmt.Errorf("Failed to read string"))
}
return string(b[:sz]) //don't return padding
}
//Reads a pickled 16 bit string: NOTE: chrome appears to store the internal c++ std representation
//which is not guaranteed to be UTF16 and may vary by platform and locale (aka this works on
//MY machine :P).
b := make([]byte, rsz)
if n, err := io.ReadFull(r, b); err != nil {
panic(err)
} else if n != len(b) {
panic(fmt.Errorf("Failed to read string"))
}
var s []uint16
for i := 0; i < int(sz*2); i += 2 {
s = append(s, uint16(b[i+1])<<8|uint16(b[i]))
}
return string(utf16.Decode(s))
}
//Normalized output structures (as distinct from the lower case internal ones which correspond to SNSS structures)
type Result struct {
Windows []*Window json:"windows"
}
type Tab struct {
Active bool json:"active"
History []*HistoryItem json:"history"
Url string json:"url"
Title string json:"title"
Deleted bool json:"deleted"
Group string json:"group"
}
type Window struct {
Tabs []*Tab json:"tabs"
Active bool json:"active"
Deleted bool json:"deleted"
}
type HistoryItem struct {
Url string json:"url"
Title string json:"title"
}
func parse(path string) Result {
fh, err := os.Open(path)
if err != nil {
panic(err)
}
var magic [4]byte
if n, err := fh.Read(magic[:4]); err != nil || n != 4 {
panic(err)
}
ver := readUint32(fh)
if magic != [4]byte{0x53, 0x4E, 0x53, 0x53} || //0x534E5353 == "SNSS"
(ver != 1 && ver != 3) { //TODO (hotfix): Review https://source.chromium.org/chromium/chromium/src/+/807acce36a4baa1004d23ae896b07e2148ea1533 and implement neccesary changes.
panic(fmt.Errorf("Invalid SNSS file: (version %d)", ver))
}
var activeWindow *window
readCommand := func() (typ uint8, data io.Reader, eof bool) {
defer func() {
if e := recover(); e == io.EOF {
eof = true
return
} else if e != nil {
panic(err)
}
}()
sz := int(readUint16(fh)) - 1
typ = readUint8(fh)
buf := make([]byte, sz)
if n, err := fh.Read(buf); err != nil {
panic(err)
} else if n != sz {
panic(fmt.Errorf("Failed to read %d bytes", n))
}
return typ, bytes.NewBuffer(buf), false
}
for {
typ, data, eof := readCommand()
if eof {
break
}
//Note: Some commands are pickled whilst others are raw struct
//dumps from memory, the former have a 32 bit size header whilst the
//latter may include padding between members.
switch typ {
case kCommandUpdateTabNavigation:
readUint32(data) //size of the data (again)
id := readUint32(data)
histIdx := readUint32(data)
url := readString(data)
title := readString16(data)
t := getTab(id)
var item *histItem
for _, h := range t.history {
if h.idx == histIdx {
item = h
break
}
}
if item == nil {
item = &histItem{idx: histIdx}
t.history = append(t.history, item)
}
item.url = url
item.title = title
case kCommandSetSelectedTabInIndex: //Sets the active tab index in window, note that 'tab index' is a derived value and not present in any data.
id := readUint32(data)
idx := readUint32(data)
getWindow(id).activeTabIdx = idx
case kCommandSetTabGroupMetadata2:
readUint32(data) //Size
high := readUint64(data)
low := readUint64(data)
name := readString16(data)
getGroup(high, low).name = name
case kCommandSetTabGroup:
id := readUint32(data)
readUint32(data) //Struct padding
high := readUint64(data)
low := readUint64(data)
getTab(id).group = getGroup(high, low)
case kCommandSetTabWindow:
win := readUint32(data)
id := readUint32(data)
getTab(id).win = win
case kCommandWindowClosed:
id := readUint32(data)
getWindow(id).deleted = true
case kCommandTabClosed:
id := readUint32(data)
getTab(id).deleted = true
case kCommandSetTabIndexInWindow:
id := readUint32(data)
index := readUint32(data)
getTab(id).idx = index
case kCommandSetActiveWindow:
id := readUint32(data)
activeWindow = getWindow(id)
case kCommandLastActiveTime: //TODO implement properly
//id := readUint32(data)
//time := readUint64(data)
//getTab(id)._lastActiveTime = time //figure out how to interpret this.
case kCommandSetSelectedNavigationIndex:
id := readUint32(data)
idx := readUint32(data) //The current position within history
getTab(id).currentHistoryIdx = idx
}
}
for _, t := range tabs {
sort.Slice(t.history, func(i, j int) bool {
return t.history[i].idx < t.history[j].idx
})
w := getWindow(t.win)
w.tabs = append(w.tabs, t)
}
for _, w := range windows {
sort.Slice(w.tabs, func(i, j int) bool {
return w.tabs[i].idx < w.tabs[j].idx
})
}
var Windows []*Window
for _, w := range windows {
W := &Window{Active: w == activeWindow, Deleted: w.deleted}
idx := 0
for _, t := range w.tabs {
groupName := ""
if t.group != nil {
groupName = t.group.name
}
T := &Tab{Active: idx == int(w.activeTabIdx), Deleted: t.deleted, Group: groupName}
for _, h := range t.history {
T.History = append(T.History, &HistoryItem{h.url, h.title})
if h.idx == t.currentHistoryIdx { //Truncate history to avoid having to deal with trees TODO: find a better way to export this.
T.Url = h.url
T.Title = h.title
break
}
}
W.Tabs = append(W.Tabs, T)
if !t.deleted {
idx++
}
}
Windows = append(Windows, W)
}
return Result{Windows}
}
func findSession(_path string) string {
var cfile = ""
ents, err := ioutil.ReadDir(_path)
if err != nil {
panic(err)
}
cmp := func(candidate string) {
if cfile != "" {
info1, err := os.Stat(candidate)
if err != nil {
panic(err)
}
info2, err := os.Stat(cfile)
if err != nil {
panic(err)
}
if info1.ModTime().Sub(info2.ModTime()) > 0 {
cfile = candidate
}
} else {
cfile = candidate
}
}
for _, ent := range ents {
if ent.IsDir() {
if cand := findSession(path.Join(_path, ent.Name())); cand != "" {
cmp(cand)
}
} else if strings.Index(ent.Name(), "Session_") == 0 {
cmp(path.Join(_path, ent.Name()))
}
}
return cfile
}
func tabPrintf(format string, tab *Tab, includeHistory bool) {
if includeHistory {
for _, item := range tab.History {
s := strings.Replace(format, "%u", item.Url, -1)
s = strings.Replace(s, "%g", tab.Group, -1)
s = strings.Replace(s, "%t", item.Title, -1)
s = strings.Replace(s, "\n", "\n", -1)
s = strings.Replace(s, "\t", "\t", -1)
s = strings.Replace(s, "\0", "\x00", -1)
os.Stdout.Write([]byte(s))
}
} else {
s := strings.Replace(format, "%u", tab.Url, -1)
s = strings.Replace(s, "%g", tab.Group, -1)
s = strings.Replace(s, "%t", tab.Title, -1)
s = strings.Replace(s, "\\n", "\n", -1)
s = strings.Replace(s, "\\t", "\t", -1)
s = strings.Replace(s, "\\0", "\x00", -1)
os.Stdout.Write([]byte(s))
}
}
func main() {
var jsonFlag bool
var activeFlag bool
var deletedFlag bool
var historyFlag bool
var outputFmt string
flag.BoolVar(&jsonFlag, "json", false, "Produce json formatted output. Note that this includes all tabs along with their history and any corresponding metadata. Useful for other scripts.")
flag.BoolVar(&activeFlag, "active", false, "Print the currently active tab.")
flag.StringVar(&outputFmt, "printf", "%u\n", "The output format for tabs if -json is not specified (%u = url, %t = title, %g = group).")
flag.BoolVar(&deletedFlag, "deleted", false, "Include tabs which have been deleted.")
flag.BoolVar(&historyFlag, "history", false, "Include the history of each tab in the output.")
flag.Usage = func() {
fmt.Printf("Usage:
-session-dump [options] ([session file] | [chrome dir])\n\n")
fmt.Printf(`If a chrome directory is supplied the most recent session file
contained within it is used. If neither a directory or file
is supplied then the program will use ~/.config/chrome by
default
`)
flag.PrintDefaults()
}
flag.Parse()
target := os.ExpandEnv("$HOME/.config/chromium")
if _, err := os.Stat(target); os.IsNotExist(err) {
target = os.ExpandEnv("$HOME/.config/google-chrome")
}
if _, err := os.Stat(target); os.IsNotExist(err) {
target = os.ExpandEnv("$HOME/.config/chrome")
}
if len(flag.Args()) >= 1 {
target = flag.Args()[0]
}
if info, err := os.Stat(target); err == nil && info.IsDir() {
target = findSession(target)
}
if target == "" {
panic(fmt.Errorf("Unable to find session file."))
}
data := parse(target)
if jsonFlag {
b, err := json.Marshal(data)
if err != nil {
panic(err)
}
fmt.Println(string(b))
} else if activeFlag {
for _, win := range data.Windows {
if win.Active {
for _, tab := range win.Tabs {
if tab.Active {
tabPrintf(outputFmt, tab, historyFlag)
}
}
}
}
} else {
for _, win := range data.Windows {
if deletedFlag || !win.Deleted {
for _, tab := range win.Tabs {
if deletedFlag || !tab.Deleted {
tabPrintf(outputFmt, tab, historyFlag)
}
}
}
}
}
}
"""
Sure! Below is a Python script that replicates the functionality of the provided Go program. This script parses Chrome's session files, reconstructs the state of windows and tabs, and outputs the information based on the specified command-line options.
Python Script: chrome_session_dump.py
#!/usr/bin/env python3
import argparse
import os
import struct
import sys
import json
from pathlib import Path
from collections import defaultdict
import datetime
# Constants for command types
K_COMMAND_UPDATE_TAB_NAVIGATION = 6
K_COMMAND_SET_SELECTED_TAB_IN_INDEX = 8
K_COMMAND_SET_TAB_WINDOW = 0
K_COMMAND_SET_TAB_GROUP = 25
K_COMMAND_SET_TAB_GROUP_METADATA2 = 27
K_COMMAND_SET_SELECTED_NAVIGATION_INDEX = 7
K_COMMAND_TAB_CLOSED = 16
K_COMMAND_WINDOW_CLOSED = 17
K_COMMAND_SET_TAB_INDEX_IN_WINDOW = 2
K_COMMAND_SET_ACTIVE_WINDOW = 20
K_COMMAND_LAST_ACTIVE_TIME = 21
MAGIC_HEADER = b"SNSS"
# Data Structures
class Group:
def __init__(self, high, low, name=""):
self.high = high
self.low = low
self.name = name
class Window:
def __init__(self, id):
self.id = id
self.active_tab_idx = 0
self.deleted = False
self.tabs = []
class HistoryItem:
def __init__(self, idx, url="", title=""):
self.idx = idx
self.url = url
self.title = title
class Tab:
def __init__(self, id):
self.id = id
self.history = []
self.idx = 0
self.win = 0
self.deleted = False
self.current_history_idx = 0
self.group = None
class Result:
def __init__(self):
self.windows = []
# Helper Functions
def read_uint8(f):
data = f.read(1)
if len(data) != 1:
raise EOFError("Failed to read uint8.")
return struct.unpack("<B", data)[0]
def read_uint16(f):
data = f.read(2)
if len(data) != 2:
raise EOFError("Failed to read uint16.")
return struct.unpack("<H", data)[0]
def read_uint32(f):
data = f.read(4)
if len(data) != 4:
raise EOFError("Failed to read uint32.")
return struct.unpack("<I", data)[0]
def read_uint64(f):
data = f.read(8)
if len(data) != 8:
raise EOFError("Failed to read uint64.")
return struct.unpack("<Q", data)[0]
def read_string(f):
sz = read_uint32(f)
rsz = sz
if rsz % 4 != 0:
rsz += 4 - (rsz % 4)
data = f.read(rsz)
if len(data) != rsz:
raise EOFError("Failed to read string.")
return data[:sz].decode('utf-8', errors='replace')
def read_string16(f):
sz = read_uint32(f)
rsz = sz * 2
if rsz % 4 != 0:
rsz += 4 - (rsz % 4)
data = f.read(rsz)
if len(data) != rsz:
raise EOFError("Failed to read string16.")
# Interpret as little-endian UTF-16
return data[:sz*2].decode('utf-16le', errors='replace')
# Main Parsing Function
def parse_session(file_path):
tabs = {}
windows = {}
groups = {}
active_window = None
def get_window(id):
if id not in windows:
windows[id] = Window(id)
return windows[id]
def get_group(high, low):
key = f"{high:x}{low:x}"
if key not in groups:
groups[key] = Group(high, low)
return groups[key]
def get_tab(id):
if id not in tabs:
tabs[id] = Tab(id)
return tabs[id]
with open(file_path, 'rb') as f:
# Read and validate magic header
magic = f.read(4)
if magic != MAGIC_HEADER:
raise ValueError("Invalid SNSS file: Incorrect magic header.")
# Read and validate version
version = read_uint32(f)
if version not in [1, 3]:
raise ValueError(f"Invalid SNSS file: Unsupported version {version}.")
while True:
try:
sz = read_uint16(f) -1
cmd_type = read_uint8(f)
payload = f.read(sz)
if len(payload) != sz:
raise EOFError("Incomplete command payload.")
data = io.BytesIO(payload)
if cmd_type == K_COMMAND_UPDATE_TAB_NAVIGATION:
data_size = read_uint32(data)
tab_id = read_uint32(data)
hist_idx = read_uint32(data)
url = read_string(data)
title = read_string16(data)
tab = get_tab(tab_id)
# Find or create history item
item = next((h for h in tab.history if h.idx == hist_idx), None)
if not item:
item = HistoryItem(hist_idx)
tab.history.append(item)
item.url = url
item.title = title
elif cmd_type == K_COMMAND_SET_SELECTED_TAB_IN_INDEX:
win_id = read_uint32(data)
idx = read_uint32(data)
win = get_window(win_id)
win.active_tab_idx = idx
elif cmd_type == K_COMMAND_SET_TAB_GROUP_METADATA2:
data_size = read_uint32(data)
high = read_uint64(data)
low = read_uint64(data)
name = read_string16(data)
group = get_group(high, low)
group.name = name
elif cmd_type == K_COMMAND_SET_TAB_GROUP:
tab_id = read_uint32(data)
padding = read_uint32(data) # Struct padding
high = read_uint64(data)
low = read_uint64(data)
tab = get_tab(tab_id)
tab.group = get_group(high, low)
elif cmd_type == K_COMMAND_SET_TAB_WINDOW:
win_id = read_uint32(data)
tab_id = read_uint32(data)
tab = get_tab(tab_id)
tab.win = win_id
elif cmd_type == K_COMMAND_WINDOW_CLOSED:
win_id = read_uint32(data)
win = get_window(win_id)
win.deleted = True
elif cmd_type == K_COMMAND_TAB_CLOSED:
tab_id = read_uint32(data)
tab = get_tab(tab_id)
tab.deleted = True
elif cmd_type == K_COMMAND_SET_TAB_INDEX_IN_WINDOW:
tab_id = read_uint32(data)
index = read_uint32(data)
tab = get_tab(tab_id)
tab.idx = index
elif cmd_type == K_COMMAND_SET_ACTIVE_WINDOW:
win_id = read_uint32(data)
active_window = get_window(win_id)
elif cmd_type == K_COMMAND_LAST_ACTIVE_TIME:
# Skipping proper implementation as noted in Go code
data.read(4 + 8) # Skip id and time
elif cmd_type == K_COMMAND_SET_SELECTED_NAVIGATION_INDEX:
tab_id = read_uint32(data)
idx = read_uint32(data)
tab = get_tab(tab_id)
tab.current_history_idx = idx
else:
# Unknown command type; skip
pass
except EOFError:
break
# Organize tabs into windows
for tab in tabs.values():
# Skip tabs without a window
if tab.win == 0:
continue
win = get_window(tab.win)
win.tabs.append(tab)
# Sort tabs within windows
for win in windows.values():
win.tabs.sort(key=lambda t: t.idx)
# Prepare Result
result = Result()
for win in windows.values():
window_obj = {
"active": (win == active_window),
"deleted": win.deleted,
"tabs": []
}
for idx, tab in enumerate(win.tabs):
if not tab.deleted:
is_active = (idx == win.active_tab_idx)
else:
is_active = False
tab_obj = {
"active": is_active,
"history": [{"url": h.url, "title": h.title} for h in sorted(tab.history, key=lambda x: x.idx)],
"url": "",
"title": "",
"deleted": tab.deleted,
"group": tab.group.name if tab.group else ""
}
# Truncate history to current_history_idx
for h in sorted(tab.history, key=lambda x: x.idx):
tab_obj["history"].append({"url": h.url, "title": h.title})
if h.idx == tab.current_history_idx:
tab_obj["url"] = h.url
tab_obj["title"] = h.title
break
window_obj["tabs"].append(tab_obj)
result.windows.append(window_obj)
return result
# Function to find the latest session file
def find_session(path):
session_files = []
for root, dirs, files in os.walk(path):
for file in files:
if file.startswith("Session_"):
full_path = os.path.join(root, file)
session_files.append(full_path)
if not session_files:
return ""
# Return the most recently modified session file
session_files.sort(key=lambda x: os.path.getmtime(x), reverse=True)
return session_files[0]
# Function to handle printf-like formatting
def format_output(format_str, tab, include_history):
outputs = []
if include_history:
for item in tab["history"]:
s = format_str.replace("%u", item["url"])
s = s.replace("%g", tab["group"])
s = s.replace("%t", item["title"])
s = s.replace("\\n", "\n")
s = s.replace("\\t", "\t")
s = s.replace("\\0", "\x00")
outputs.append(s)
else:
s = format_str.replace("%u", tab["url"])
s = s.replace("%g", tab["group"])
s = s.replace("%t", tab["title"])
s = s.replace("\\n", "\n")
s = s.replace("\\t", "\t")
s = s.replace("\\0", "\x00")
outputs.append(s)
return "".join(outputs)
# Main Function
def main():
parser = argparse.ArgumentParser(
description="Chrome Session Dump - Parses Chrome's session files to extract window and tab information."
)
parser.add_argument(
"target",
nargs="?",
default=None,
help="Path to the session file or Chrome directory. Defaults to Chrome's config directory."
)
parser.add_argument(
"--json",
action="store_true",
help="Produce JSON formatted output. Includes all tabs with their history and metadata."
)
parser.add_argument(
"--active",
action="store_true",
help="Print the currently active tab."
)
parser.add_argument(
"--deleted",
action="store_true",
help="Include tabs and windows that have been deleted."
)
parser.add_argument(
"--history",
action="store_true",
help="Include the history of each tab in the output."
)
parser.add_argument(
"--printf",
default="%u\n",
help="The output format for tabs if --json is not specified. (Default: '%%u\\n')"
)
args = parser.parse_args()
# Determine the target path
if args.target:
target = Path(os.path.expanduser(args.target))
else:
# Default Chrome config directories
possible_dirs = [
Path.home() / ".config" / "chromium",
Path.home() / ".config" / "google-chrome",
Path.home() / ".config" / "chrome"
]
target = next((d for d in possible_dirs if d.exists()), None)
if not target:
print("Default Chrome config directories not found. Please specify a session file or Chrome directory.", file=sys.stderr)
sys.exit(1)
# If target is a directory, find the latest session file
if target.is_dir():
session_file = find_session(str(target))
if not session_file:
print("No session file found in the specified directory.", file=sys.stderr)
sys.exit(1)
else:
session_file = str(target)
# Parse the session file
try:
result = parse_session(session_file)
except Exception as e:
print(f"Error parsing session file: {e}", file=sys.stderr)
sys.exit(1)
# Output the results
if args.json:
print(json.dumps({
"windows": result.windows
}, indent=2))
elif args.active:
for win in result.windows:
if win["active"]:
for tab in win["tabs"]:
if tab["active"]:
output = format_output(args.printf, tab, args.history)
print(output, end='')
else:
for win in result.windows:
if not win["deleted"] or args.deleted:
for tab in win["tabs"]:
if not tab["deleted"] or args.deleted:
output = format_output(args.printf, tab, args.history)
print(output, end='')
if __name__ == "__main__":
import io
main()
Explanation of the Python Script
Imports and Constants:
The script uses standard Python libraries such as argparse for command-line parsing, struct for binary data handling, and json for JSON output.
Constants are defined to represent different command types, mirroring the Go constants.
Data Structures:
Classes Group, Window, HistoryItem, and Tab represent the respective entities in the Chrome session.
The Result class holds all reconstructed windows.
Helper Functions:
Functions like read_uint8, read_uint16, read_uint32, and read_uint64 read binary data from the session file.
read_string and read_string16 handle reading UTF-8 and UTF-16LE encoded strings, respectively.
find_session recursively searches for the latest session file within the given directory.
Parsing Logic (parse_session):
Opens the session file and validates the magic header and version.
Iteratively reads commands from the file, processing each based on its type.
Updates the tabs, windows, and groups dictionaries accordingly.
After parsing all commands, organizes tabs into their respective windows and sorts them.
Formatting Output (format_output):
Handles the --printf formatting option, replacing placeholders with actual tab data.
Main Function:
Parses command-line arguments using argparse.
Determines the target session file, either from the provided argument or by searching default Chrome directories.
Calls parse_session to process the session file.
Outputs the result in JSON format or as formatted text based on the provided options.
Execution Entry Point:
The script checks if it's run as the main program and calls the main function accordingly.
python3 chrome_session_dump.py /path/to/Session_File
# or
python3 chrome_session_dump.py /path/to/chrome/directory
Notes
Error Handling: The script includes basic error handling for issues like missing session files or unsupported file formats.
Dependencies: The script uses only standard Python libraries and doesn't require any external dependencies.
Compatibility: Ensure you're using Python 3.6 or later for optimal compatibility.
Permissions: Depending on your system's configuration, you might need appropriate permissions to read Chrome's session files.
This Python script should provide functionality equivalent to the provided Go program, allowing you to parse and extract information from Chrome's session files effectively.