-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathlocalstorage.go
358 lines (295 loc) · 8.05 KB
/
localstorage.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
package chromedb
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
"github.com/h2non/filetype"
"github.com/syndtr/goleveldb/leveldb"
"github.com/syndtr/goleveldb/leveldb/opt"
"github.com/syndtr/goleveldb/leveldb/storage"
"golang.org/x/text/encoding/unicode"
"google.golang.org/protobuf/encoding/protowire"
)
func fromChromeTimestamp(microseconds int64) (time.Time, error) {
chromiumEpoch := time.Date(1601, 1, 1, 0, 0, 0, 0, time.UTC).UnixMicro()
microFromEpoch := chromiumEpoch + microseconds
timestamp := time.Unix(0, microFromEpoch*1000)
return timestamp, nil
}
func decodeString(raw []byte) (string, string, error) {
prefix := raw[0]
if prefix == 0 {
decoder := unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM).NewDecoder()
utf8bytes, err := decoder.Bytes(raw[1:])
if err != nil {
return "", "", fmt.Errorf("failed to decode UTF-16-LE: %w", err)
}
return string(utf8bytes), "UTF-16-LE", nil
} else if prefix == 1 {
return string(raw[1:]), "ISO-8859-1", nil
}
return "", "", fmt.Errorf("unknown string encoding prefix: %d", prefix)
}
type StorageMetadata struct {
StorageKey string `json:"storage_key"`
Timestamp time.Time `json:"timestamp"`
Size int `json:"size"`
}
type LocalStorageRecord struct {
StorageKey string `json:"storage_key"`
ScriptKey string `json:"script_key"`
Charset string `json:"charset"`
Decoded string `json:"-"`
MIME string `json:"mime"`
Conversions []string `json:"conversions"`
JsonType string `json:"-"`
Value json.RawMessage `json:"value"`
}
type LocalStoreDb struct {
ldb *leveldb.DB
Records []LocalStorageRecord `json:"records"`
metadata []StorageMetadata `json:"metadata"`
}
func StorageMetadataFromProtobuff(sm *StorageMetadata, data []byte) error {
fieldNum, wireType, n := protowire.ConsumeTag(data)
if fieldNum != 1 || wireType != protowire.VarintType {
return fmt.Errorf("Expected field number 1 with varint type, got field number %d with wire type %d", fieldNum, wireType)
}
timestamp, m := protowire.ConsumeVarint(data[n:])
if m < 0 {
return fmt.Errorf("Failed to decode timestamp")
}
fieldNum, wireType, n = protowire.ConsumeTag(data[n+m:])
if fieldNum != 2 || wireType != protowire.VarintType {
return fmt.Errorf("Expected field number 2 with varint type, got field number %d with wire type %d", fieldNum, wireType)
}
size, m := protowire.ConsumeVarint(data[n+m:])
if m < 0 {
return fmt.Errorf("Failed to decode size")
}
ts, err := fromChromeTimestamp(int64(timestamp))
if err != nil {
return fmt.Errorf("Failed to decode timestamp: %w", err)
}
sm.Timestamp = ts
sm.Size = int(size)
return nil
}
func LoadLocalStorage(dir string) (*LocalStoreDb, error) {
db := &leveldb.DB{}
db, err := leveldb.OpenFile(dir, &opt.Options{
ReadOnly: true,
})
// We try the ReadOnly option above, but it weirdly doesn't work when the
// db is locked. When this happens, we simply copy the db to memory and
// read from there.
if err != nil {
srcDir := dir
memStorage := storage.NewMemStorage()
// Copy the LevelDB directory contents into the memory storage
err := filepath.Walk(srcDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
relPath, err := filepath.Rel(srcDir, path)
if err != nil {
return err
}
// Skip directories, we only need files
if info.IsDir() {
return nil
}
srcFile, err := os.Open(path)
if err != nil {
return err
}
defer srcFile.Close()
data, err := io.ReadAll(srcFile)
if err != nil {
return err
}
var num int64
num = 0
re := regexp.MustCompile(`\d+`)
match := re.FindString(relPath)
if match != "" {
matchInt, err := strconv.Atoi(match)
if err == nil {
num = int64(matchInt)
}
}
// Determine the file descriptor type
var fileType storage.FileType
switch {
case strings.HasSuffix(relPath, ".ldb"):
fileType = storage.TypeTable
case strings.HasPrefix(relPath, "MANIFEST"):
fileType = storage.TypeManifest
case strings.HasSuffix(relPath, ".log"):
fileType = storage.TypeJournal
case strings.HasSuffix(relPath, ".tmp"):
fileType = storage.TypeTemp
default:
return nil
}
// Create the file in the memory storage
fd := storage.FileDesc{Type: fileType, Num: num}
if fd.Type == storage.TypeManifest {
err = memStorage.SetMeta(fd)
if err != nil {
return err
}
}
writer, err := memStorage.Create(fd)
if err != nil {
return err
}
// Write the contents to the memory storage
_, err = writer.Write(data)
if err != nil {
writer.Close()
return err
}
// Close the writer
err = writer.Close()
if err != nil {
return err
}
return nil
})
if err != nil {
fmt.Println("Error copying directory:", err)
return nil, err
}
// Open the LevelDB using the memory storage
db, err = leveldb.Open(memStorage, nil)
if err != nil {
fmt.Println("Error opening LevelDB:", err)
return nil, err
}
}
defer db.Close()
lsd := &LocalStoreDb{
ldb: db,
}
iter := db.NewIterator(nil, nil)
defer iter.Release()
for iter.Next() {
key := iter.Key()
value := iter.Value()
const (
MetaKeyPrefix = "META:"
RecordKeyPrefix = "_"
)
// metadata
if bytes.HasPrefix(key, []byte(MetaKeyPrefix)) {
storageKey := string(bytes.TrimPrefix(key, []byte(MetaKeyPrefix)))
metadata := StorageMetadata{
StorageKey: storageKey,
Timestamp: time.Time{},
Size: 0,
}
err := StorageMetadataFromProtobuff(&metadata, value)
if err != nil {
return nil, err
}
lsd.metadata = append(lsd.metadata, metadata)
// record
} else if bytes.HasPrefix(key, []byte(RecordKeyPrefix)) {
parts := bytes.SplitN(bytes.TrimPrefix(key, []byte(RecordKeyPrefix)), []byte{0}, 2)
if len(parts) != 2 {
continue
}
record := LocalStorageRecord{}
storageKey := string(parts[0])
record.StorageKey = storageKey
sk, _, err := decodeString(parts[1])
if err != nil {
return nil, fmt.Errorf("failed to decode script key: %w", err)
}
record.ScriptKey = sk
val, valEnc, err := decodeString(value)
if err != nil {
return nil, fmt.Errorf("failed to decode value: %w", err)
}
record.Decoded = val
record.Charset = valEnc
lsd.Records = append(lsd.Records, record)
}
}
return lsd, nil
}
func LocalStorageRecordToJson(r LocalStorageRecord) (string, error) {
mime := "application/octet-stream"
xfer := []string{}
b := []byte(r.Decoded)
validJson := json.Valid(b)
jsonType := ""
out := []byte{}
if validJson {
// Unmarshal the JSON into an interface{}
var v interface{}
err := json.Unmarshal(b, &v)
if err != nil {
return "", fmt.Errorf("failed to unmarshal supposedly valid JSON: %w", err)
}
mime = "application/json"
// Determine the type of the JSON value
switch v.(type) {
case float64:
jsonType = "number"
case string:
jsonType = "string"
case bool:
jsonType = "boolean"
case []interface{}:
jsonType = "array"
case map[string]interface{}:
jsonType = "object"
case nil:
jsonType = "null"
default:
jsonType = ""
}
out = b
} else {
quoted := strconv.Quote(r.Decoded)
if json.Valid([]byte(quoted)) {
out = []byte(quoted)
mime = "text/plain"
xfer = append(xfer, "strconv.Quote")
mime = http.DetectContentType(b)
mime = strings.Split(mime, ";")[0]
} else {
b64 := base64.StdEncoding.EncodeToString(b)
xfer = append(xfer, "base64.StdEncoding.EncodeToString")
out = []byte(strconv.Quote(b64))
xfer = append(xfer, "strconv.Quote")
magic, _ := filetype.Match(b)
if magic != filetype.Unknown {
mime = magic.MIME.Value
}
}
}
r.MIME = mime
r.Conversions = xfer
r.Value = out
r.JsonType = jsonType
recordJson, err := json.Marshal(r)
if err != nil {
return "", fmt.Errorf("failed to marshal record to JSON: %w", err)
}
return string(recordJson), nil
}
func (lsd *LocalStoreDb) Close() {
lsd.ldb.Close()
}