forked from CalebQ42/squashfs
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reader_file.go
518 lines (489 loc) · 13.1 KB
/
reader_file.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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
package squashfs
import (
"errors"
"io"
"io/fs"
"log"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"github.com/CalebQ42/squashfs/internal/data"
"github.com/CalebQ42/squashfs/internal/directory"
"github.com/CalebQ42/squashfs/internal/inode"
"github.com/CalebQ42/squashfs/internal/threadmanager"
)
// File represents a file inside a squashfs archive.
type File struct {
i inode.Inode
rdr io.Reader
fullRdr *data.FullReader
r *Reader
parent *FS
e directory.Entry
dirsRead int
}
var (
ErrReadNotFile = errors.New("read called on non-file")
)
func (r Reader) newFile(en directory.Entry, parent *FS) (*File, error) {
i, err := r.inodeFromDir(en)
if err != nil {
return nil, err
}
var rdr io.Reader
var full *data.FullReader
if i.Type == inode.Fil || i.Type == inode.EFil {
full, rdr, err = r.getReaders(i)
if err != nil {
return nil, err
}
}
return &File{
e: en,
i: i,
rdr: rdr,
fullRdr: full,
r: &r,
parent: parent,
}, nil
}
// Stat returns the File's fs.FileInfo
func (f File) Stat() (fs.FileInfo, error) {
return newFileInfo(f.e, f.i), nil
}
// Mode returns the file's fs.FileMode
func (f File) Mode() fs.FileMode {
switch f.e.Type {
case inode.Dir:
return fs.FileMode(f.i.Perm) | fs.ModeDir
case inode.Char:
return fs.FileMode(f.i.Perm) | fs.ModeCharDevice
case inode.Block:
return fs.FileMode(f.i.Perm) | fs.ModeDevice
case inode.Sym:
return fs.FileMode(f.i.Perm) | fs.ModeSymlink
}
return fs.FileMode(f.i.Perm)
}
// Read reads the data from the file. Only works if file is a normal file.
func (f File) Read(p []byte) (int, error) {
if f.i.Type != inode.Fil && f.i.Type != inode.EFil {
return 0, ErrReadNotFile
}
if f.rdr == nil {
return 0, fs.ErrClosed
}
return f.rdr.Read(p)
}
func (f File) ReadAt(p []byte, off int64) (int, error) {
if f.i.Type != inode.Fil && f.i.Type != inode.EFil {
return 0, ErrReadNotFile
}
return f.fullRdr.ReadAt(p, off)
}
// WriteTo writes all data from the file to the writer. This is multi-threaded.
// The underlying reader is seperate from the one used with Read and can be reused.
func (f File) WriteTo(w io.Writer) (int64, error) {
if f.i.Type != inode.Fil && f.i.Type != inode.EFil {
return 0, ErrReadNotFile
}
return f.fullRdr.WriteTo(w)
}
// Close simply nils the underlying reader.
func (f *File) Close() error {
f.rdr = nil
return nil
}
// ReadDir returns n fs.DirEntry's that's contained in the File (if it's a directory).
// If n <= 0 all fs.DirEntry's are returned.
func (f *File) ReadDir(n int) (out []fs.DirEntry, err error) {
if !f.IsDir() {
return nil, errors.New("file is not a directory")
}
ents, err := f.r.readDirectory(f.i)
if err != nil {
return nil, err
}
start, end := 0, len(ents)
if n > 0 {
start, end = f.dirsRead, f.dirsRead+n
if end > len(f.r.e) {
end = len(f.r.e)
err = io.EOF
}
}
var fi fileInfo
for _, e := range ents[start:end] {
fi, err = f.r.newFileInfo(e)
if err != nil {
f.dirsRead += len(out)
return
}
out = append(out, fs.FileInfoToDirEntry(fi))
}
f.dirsRead += len(out)
return
}
// FS returns the File as a FS.
func (f *File) FS() (*FS, error) {
if !f.IsDir() {
return nil, errors.New("File is not a directory")
}
ents, err := f.r.readDirectory(f.i)
if err != nil {
return nil, err
}
return &FS{
File: f,
e: ents,
}, nil
}
// IsDir Yep.
func (f File) IsDir() bool {
return f.i.Type == inode.Dir || f.i.Type == inode.EDir
}
// IsRegular yep.
func (f File) IsRegular() bool {
return f.i.Type == inode.Fil || f.i.Type == inode.EFil
}
// IsSymlink yep.
func (f File) IsSymlink() bool {
return f.i.Type == inode.Sym || f.i.Type == inode.ESym
}
func (f File) isDeviceOrFifo() bool {
return f.i.Type == inode.Char || f.i.Type == inode.Block || f.i.Type == inode.EChar || f.i.Type == inode.EBlock || f.i.Type == inode.Fifo || f.i.Type == inode.EFifo
}
func (f File) deviceDevices() (maj uint32, min uint32) {
var dev uint32
if f.i.Type == inode.Char || f.i.Type == inode.Block {
dev = f.i.Data.(inode.Device).Dev
} else if f.i.Type == inode.EChar || f.i.Type == inode.EBlock {
dev = f.i.Data.(inode.EDevice).Dev
}
return dev >> 8, dev & 0x000FF
}
// SymlinkPath returns the symlink's target path. Is the File isn't a symlink, returns an empty string.
func (f File) SymlinkPath() string {
switch f.i.Type {
case inode.Sym:
return string(f.i.Data.(inode.Symlink).Target)
case inode.ESym:
return string(f.i.Data.(inode.ESymlink).Target)
}
return ""
}
func (f File) path() string {
if f.parent == nil {
return f.e.Name
}
return f.parent.path() + "/" + f.e.Name
}
// GetSymlinkFile returns the File the symlink is pointing to.
// If not a symlink, or the target is unobtainable (such as it being outside the archive or it's absolute) returns nil
func (f File) GetSymlinkFile() *File {
if !f.IsSymlink() {
return nil
}
if strings.HasPrefix(f.SymlinkPath(), "/") {
return nil
}
sym, err := f.parent.Open(f.SymlinkPath())
if err != nil {
return nil
}
return sym.(*File)
}
// ExtractionOptions are available options on how to extract.
type ExtractionOptions struct {
manager *threadmanager.Manager
LogOutput io.Writer //Where error log should write.
DereferenceSymlink bool //Replace symlinks with the target file.
UnbreakSymlink bool //Try to make sure symlinks remain unbroken when extracted, without changing the symlink.
Verbose bool //Prints extra info to log on an error.
IgnorePerm bool //Ignore file's permissions and instead use Perm.
Perm fs.FileMode //Permission to use when IgnorePerm. Defaults to 0755.
notFirst bool
}
func DefaultOptions() *ExtractionOptions {
return &ExtractionOptions{
Perm: 0755,
}
}
// ExtractTo extracts the File to the given folder with the default options.
// If the File is a directory, it instead extracts the directory's contents to the folder.
func (f File) ExtractTo(folder string) error {
return f.realExtract(folder, DefaultOptions())
}
// ExtractVerbose extracts the File to the folder with the Verbose option.
func (f File) ExtractVerbose(folder string) error {
op := DefaultOptions()
op.Verbose = true
return f.realExtract(folder, op)
}
// ExtractIgnorePermissions extracts the File to the folder with the IgnorePerm option.
func (f File) ExtractIgnorePermissions(folder string) error {
op := DefaultOptions()
op.IgnorePerm = true
return f.realExtract(folder, op)
}
// ExtractSymlink extracts the File to the folder with the DereferenceSymlink option.
// If the File is a directory, it instead extracts the directory's contents to the folder.
func (f File) ExtractSymlink(folder string) error {
op := DefaultOptions()
op.DereferenceSymlink = true
return f.realExtract(folder, op)
}
// ExtractWithOptions extracts the File to the given folder with the given ExtrationOptions.
// If the File is a directory, it instead extracts the directory's contents to the folder.
func (f File) ExtractWithOptions(folder string, op *ExtractionOptions) error {
if op.Verbose && op.LogOutput != nil {
log.SetOutput(op.LogOutput)
}
return f.realExtract(folder, op)
}
func (f File) realExtract(folder string, op *ExtractionOptions) (err error) {
if op.manager == nil {
op.manager = threadmanager.NewManager(runtime.NumCPU())
}
extDir := folder + "/" + f.e.Name
if !op.notFirst {
op.notFirst = true
if f.IsDir() {
extDir = folder
_, err = os.Open(folder)
if err != nil && os.IsNotExist(err) {
err = os.Mkdir(extDir, op.Perm)
}
if err != nil {
if op.Verbose {
log.Println("Error while making", folder)
}
return
}
if !op.IgnorePerm {
defer os.Chmod(extDir, f.Mode())
defer os.Chown(extDir, int(f.r.ids[f.i.UidInd]), int(f.r.ids[f.i.GidInd]))
}
}
}
switch {
case f.IsDir():
if folder != extDir && f.e.Name != "" {
//First extract it with a permisive permission.
err = os.Mkdir(extDir, op.Perm)
if err != nil {
if op.Verbose {
log.Println("Error while making directory", extDir)
}
return
}
//Then set it to it's actual permissions once we're done with it
if !op.IgnorePerm {
defer os.Chmod(extDir, f.Mode())
defer os.Chown(extDir, int(f.r.ids[f.i.UidInd]), int(f.r.ids[f.i.GidInd]))
}
}
var filFS *FS
filFS, err = f.FS()
if err != nil {
if op.Verbose {
log.Println("Error while converting", f.path(), "to FS")
}
return err
}
errChan := make(chan error, len(filFS.e))
files := make([]directory.Entry, 0)
//Focus on making the folder tree first...
var i int
for i = 0; i < len(filFS.e); i++ {
if filFS.e[i].Type == inode.Fil {
files = append(files, filFS.e[i])
} else {
go func(index int) {
subF, goErr := f.r.newFile(filFS.e[index], filFS)
if goErr != nil {
if op.Verbose {
log.Println("Error while resolving", extDir)
}
errChan <- goErr
return
}
errChan <- subF.ExtractWithOptions(extDir, op)
}(i)
}
}
for i = 0; i < len(filFS.e)-len(files); i++ {
err = <-errChan
if err != nil {
return err
}
}
//Then we extract the files.
for i = 0; i < len(files); i++ {
go func(index int) {
n := op.manager.Lock()
defer op.manager.Unlock(n)
subF, goErr := f.r.newFile(files[index], filFS)
if goErr != nil {
if op.Verbose {
log.Println("Error while resolving", extDir)
}
errChan <- goErr
return
}
errChan <- subF.ExtractWithOptions(extDir, op)
}(i)
}
for i = 0; i < len(files); i++ {
err = <-errChan
if err != nil {
return err
}
}
case f.IsRegular():
var fil *os.File
fil, err = os.Create(extDir)
if os.IsExist(err) {
os.Remove(extDir)
fil, err = os.Create(extDir)
if err != nil {
if op.Verbose {
log.Println("Error while creating", extDir)
}
return err
}
} else if err != nil {
if op.Verbose {
log.Println("Error while creating", extDir)
}
return err
}
defer fil.Close()
_, err = io.Copy(fil, f)
if err != nil {
if op.Verbose {
log.Println("Error while copying data to", extDir)
}
return err
}
if op.IgnorePerm {
os.Chmod(extDir, op.Perm|(f.Mode()&fs.ModeType))
} else {
os.Chmod(extDir, f.Mode())
os.Chown(extDir, int(f.r.ids[f.i.UidInd]), int(f.r.ids[f.i.GidInd]))
}
case f.IsSymlink():
symPath := f.SymlinkPath()
if op.DereferenceSymlink {
fil := f.GetSymlinkFile()
if fil == nil {
if op.Verbose {
log.Println("Symlink path(", symPath, ") is unobtainable:", extDir)
}
return errors.New("cannot get symlink target")
}
fil.e.Name = f.e.Name
err = fil.realExtract(folder, op)
if err != nil {
if op.Verbose {
log.Println("Error while extracting the symlink's file:", extDir)
}
return err
}
return nil
} else if op.UnbreakSymlink {
fil := f.GetSymlinkFile()
if fil == nil {
if op.Verbose {
log.Println("Symlink path(", symPath, ") is unobtainable:", extDir)
}
return errors.New("cannot get symlink target")
}
extractLoc := filepath.Join(folder, filepath.Dir(symPath))
err = fil.realExtract(extractLoc, op)
if err != nil {
if op.Verbose {
log.Println("Error while extracting ", extDir)
}
return err
}
}
err = os.Symlink(f.SymlinkPath(), extDir)
if os.IsExist(err) {
os.Remove(extDir)
err = os.Symlink(f.SymlinkPath(), extDir)
}
if err != nil {
if op.Verbose {
log.Println("Error while making symlink:", extDir)
}
return err
}
if op.IgnorePerm {
os.Chmod(extDir, op.Perm|(f.Mode()&fs.ModeType))
} else {
os.Chmod(extDir, f.Mode())
os.Chown(extDir, int(f.r.ids[f.i.UidInd]), int(f.r.ids[f.i.GidInd]))
}
case f.isDeviceOrFifo():
if runtime.GOOS == "windows" {
if op.Verbose {
log.Println(extDir, "ignored since it's a device link and can't be created on Windows.")
}
return nil
}
_, err = exec.LookPath("mknod")
if err != nil {
if op.Verbose {
log.Println("Extracting Fifo IPC or Device and mknod is not in PATH")
}
return err
}
var typ string
if f.i.Type == inode.Char || f.i.Type == inode.EChar {
typ = "c"
} else if f.i.Type == inode.Block || f.i.Type == inode.EBlock {
typ = "b"
} else { //Fifo IPC
if runtime.GOOS == "darwin" {
if op.Verbose {
log.Println(extDir, "ignored since it's a Fifo file and can't be created on Darwin.")
}
return nil
}
typ = "p"
}
cmd := exec.Command("mknod", extDir, typ)
if typ != "p" {
maj, min := f.deviceDevices()
cmd.Args = append(cmd.Args, strconv.Itoa(int(maj)), strconv.Itoa(int(min)))
}
if op.Verbose {
cmd.Stdout = op.LogOutput
cmd.Stderr = op.LogOutput
}
err = cmd.Run()
if err != nil {
if op.Verbose {
log.Println("Error while running mknod for", extDir)
}
return err
}
if op.IgnorePerm {
os.Chmod(extDir, op.Perm|(f.Mode()&fs.ModeType))
} else {
os.Chmod(extDir, f.Mode())
os.Chown(extDir, int(f.r.ids[f.i.UidInd]), int(f.r.ids[f.i.GidInd]))
}
case f.e.Type == inode.Sock:
if op.Verbose {
log.Println(extDir, "ignored since it's a socket file.")
}
default:
return errors.New("Unsupported file type. Inode type: " + strconv.Itoa(int(f.i.Type)))
}
return nil
}