Compare commits

..

13 Commits

Author SHA1 Message Date
Caleb Gardner 80946f58e7 Fixed issue with Extended Symlinks
Removed some shadowed err's
2021-01-16 01:32:00 -06:00
Caleb Gardner 4187598783 A couple of fixes.
GetChildrenRecursively is no longer threaded so it's more consistent
Fixed GetFileAtPath, specifically when getting the root dir
2021-01-15 10:57:03 -06:00
Caleb Gardner 9cf92c4916 Removed some shadowed values (thanks gopls) 2021-01-13 11:45:10 -06:00
Caleb Gardner 407d649b3d Finished FixSymlinks (in theory) 2021-01-13 06:02:15 -06:00
Caleb Gardner dcf59a4261 The root inode is now only initialized once.
Privated File.Reader because it really shouldn't be public.
2021-01-12 01:43:03 -06:00
Caleb Gardner 1506ca0ac3 updated dependencies 2021-01-10 04:39:19 -06:00
Caleb Gardner fe9344b633 Fixed issue with not all data being extracted with ExtractTo 2021-01-10 04:25:09 -06:00
Caleb Gardner 76649fde7f Implemented WriteTo which halves decompress times.
Added a drag race benchmark (for the fun of it)
2021-01-10 03:33:33 -06:00
Caleb Gardner ee9406513c Added a new test for fun to compare vs unsquashfs 2021-01-09 10:15:56 -06:00
Caleb Gardner 18092c63aa Some cleanup, no change in functionality 2021-01-09 09:53:58 -06:00
Caleb Gardner b2d6ff56f6 Added uid/guid support.
Added permission support.
2021-01-09 02:30:04 -06:00
Caleb Gardner 4b3d5d12f8 Setup for differnet types of compression for Writer
Added some TODOs
2021-01-08 14:35:32 -06:00
Caleb Gardner 3f71404a2a Re-Write of the Writer to make it simpler 2021-01-08 05:09:38 -06:00
20 changed files with 907 additions and 457 deletions
+4
View File
@@ -11,4 +11,8 @@ The only major thing missing from squashfs reading is Xattr parsing.
Special thanks to <https://dr-emann.github.io/squashfs/> for some VERY important information in an easy to understand format. Special thanks to <https://dr-emann.github.io/squashfs/> for some VERY important information in an easy to understand format.
Thanks also to [distri's squashfs library](https://github.com/distr1/distri/tree/master/internal/squashfs) as I referenced it to figure some things out (and double check others). Thanks also to [distri's squashfs library](https://github.com/distr1/distri/tree/master/internal/squashfs) as I referenced it to figure some things out (and double check others).
## Performane
This library, decompressing the firefox AppImage and using go tests, takes about twice as long as `unsquashfs` on my quad core laptop. (~1 second with the libarary and about half a second with `unsquashfs`)
## [TODO](https://github.com/CalebQ42/squashfs/projects/1?fullscreen=true) ## [TODO](https://github.com/CalebQ42/squashfs/projects/1?fullscreen=true)
+17
View File
@@ -0,0 +1,17 @@
package squashfs
import "reflect"
func (w *Writer) compressData(data []byte) ([]byte, error) {
if reflect.DeepEqual(data, make([]byte, len(data))) {
return nil, nil
}
compressedData, err := w.compressor.Compress(data)
if err != nil {
return nil, err
}
if len(data) <= len(compressedData) {
return data, nil
}
return compressedData, nil
}
+118 -55
View File
@@ -18,39 +18,19 @@ var (
//DataReader reads data from data blocks. //DataReader reads data from data blocks.
type dataReader struct { type dataReader struct {
r *Reader r *Reader
blocks []dataBlock
curData []byte curData []byte
sizes []uint32
offset int64 //offset relative to the beginning of the squash file offset int64 //offset relative to the beginning of the squash file
curBlock int //Which block in sizes is currently cached curBlock int //Which block in sizes is currently cached
curReadOffset int //offset relative to the currently cached data curReadOffset int //offset relative to the currently cached data
} }
//DataBlock holds info about a given data block from it's size
type dataBlock struct {
begOffset int64 //The offset relative to the beginning of the squash file. Makes it easier to seek to it.
size uint32
compressed bool
uncompressedSize uint32
}
//NewDataBlock creates a new squashfs.datablock from a given size.
func newDataBlock(raw uint32) (dbs dataBlock) {
dbs.compressed = raw&(1<<24) != (1 << 24)
dbs.size = raw &^ (1 << 24)
if !dbs.compressed {
dbs.uncompressedSize = dbs.size
}
return
}
//NewDataReader creates a new data reader at the given offset, with the blocks defined by sizes //NewDataReader creates a new data reader at the given offset, with the blocks defined by sizes
func (r *Reader) newDataReader(offset int64, sizes []uint32) (*dataReader, error) { func (r *Reader) newDataReader(offset int64, sizes []uint32) (*dataReader, error) {
var dr dataReader var dr dataReader
dr.r = r dr.r = r
dr.offset = offset dr.offset = offset
for _, size := range sizes { dr.sizes = sizes
dr.blocks = append(dr.blocks, newDataBlock(size))
}
err := dr.readCurBlock() err := dr.readCurBlock()
if err != nil { if err != nil {
return nil, err return nil, err
@@ -63,29 +43,29 @@ func (r *Reader) newDataReaderFromInode(i *inode.Inode) (*dataReader, error) {
var rdr dataReader var rdr dataReader
rdr.r = r rdr.r = r
switch i.Type { switch i.Type {
case inode.BasicFileType: case inode.FileType:
fil := i.Info.(inode.BasicFile) fil := i.Info.(inode.File)
if fil.Init.BlockStart == 0 { if fil.BlockStart == 0 {
return nil, errInodeOnlyFragment return nil, errInodeOnlyFragment
} }
rdr.offset = int64(fil.Init.BlockStart) rdr.offset = int64(fil.BlockStart)
for _, sizes := range fil.BlockSizes { for _, sizes := range fil.BlockSizes {
rdr.blocks = append(rdr.blocks, newDataBlock(sizes)) rdr.sizes = append(rdr.sizes, sizes)
} }
if fil.Fragmented { if fil.Fragmented {
rdr.blocks = rdr.blocks[:len(rdr.blocks)-1] rdr.sizes = rdr.sizes[:len(rdr.sizes)-1]
} }
case inode.ExtFileType: case inode.ExtFileType:
fil := i.Info.(inode.ExtendedFile) fil := i.Info.(inode.ExtFile)
if fil.Init.BlockStart == 0 { if fil.BlockStart == 0 {
return nil, errInodeOnlyFragment return nil, errInodeOnlyFragment
} }
rdr.offset = int64(fil.Init.BlockStart) rdr.offset = int64(fil.BlockStart)
for _, sizes := range fil.BlockSizes { for _, sizes := range fil.BlockSizes {
rdr.blocks = append(rdr.blocks, newDataBlock(sizes)) rdr.sizes = append(rdr.sizes, sizes)
} }
if fil.Fragmented { if fil.Fragmented {
rdr.blocks = rdr.blocks[:len(rdr.blocks)-1] rdr.sizes = rdr.sizes[:len(rdr.sizes)-1]
} }
default: default:
return nil, errInodeNotFile return nil, errInodeNotFile
@@ -97,9 +77,14 @@ func (r *Reader) newDataReaderFromInode(i *inode.Inode) (*dataReader, error) {
return &rdr, nil return &rdr, nil
} }
//removed the compression bit from a data block size
func actualDataSize(size uint32) uint32 {
return size &^ (1 << 24)
}
func (d *dataReader) readNextBlock() error { func (d *dataReader) readNextBlock() error {
d.curBlock++ d.curBlock++
if d.curBlock >= len(d.blocks) { if d.curBlock >= len(d.sizes) {
d.curBlock-- d.curBlock--
return io.EOF return io.EOF
} }
@@ -112,37 +97,47 @@ func (d *dataReader) readNextBlock() error {
return nil return nil
} }
func (d *dataReader) readCurBlock() error { func (d *dataReader) readBlockAt(offset int64, size uint32) ([]byte, error) {
if d.curBlock >= len(d.blocks) { compressed := size&(1<<24) != (1 << 24)
return io.EOF size = size &^ (1 << 24)
if d.sizes[d.curBlock] == 0 {
return make([]byte, d.r.super.BlockSize), nil
} }
if d.blocks[d.curBlock].size == 0 { sec := io.NewSectionReader(d.r.r, offset, int64(size))
d.curData = make([]byte, d.r.super.BlockSize) if compressed {
d.blocks[d.curBlock].uncompressedSize = d.r.super.BlockSize
d.blocks[d.curBlock].begOffset = d.offset
return nil
}
sec := io.NewSectionReader(d.r.r, d.offset, int64(d.blocks[d.curBlock].size))
if d.blocks[d.curBlock].compressed {
btys, err := d.r.decompressor.Decompress(sec) btys, err := d.r.decompressor.Decompress(sec)
if err != nil { if err != nil {
return err return nil, err
} }
d.blocks[d.curBlock].uncompressedSize = uint32(len(btys)) return btys, nil
d.curData = btys
d.blocks[d.curBlock].begOffset = d.offset
d.offset += int64(d.blocks[d.curBlock].size)
return nil
} }
var buf bytes.Buffer var buf bytes.Buffer
_, err := io.Copy(&buf, sec) _, err := io.Copy(&buf, sec)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func (d *dataReader) offsetForBlock(index int) int64 {
out := d.offset
for i := 0; i < index; i++ {
out += int64(actualDataSize(d.sizes[i]))
}
return out
}
func (d *dataReader) readCurBlock() error {
if d.curBlock >= len(d.sizes) {
return io.EOF
}
offset := d.offsetForBlock(d.curBlock)
data, err := d.readBlockAt(offset, d.sizes[d.curBlock])
if err != nil { if err != nil {
return err return err
} }
d.curData = buf.Bytes() d.curData = data
d.blocks[d.curBlock].begOffset = d.offset return nil
d.offset += int64(d.blocks[d.curBlock].size)
return err
} }
func (d *dataReader) Read(p []byte) (int, error) { func (d *dataReader) Read(p []byte) (int, error) {
@@ -182,3 +177,71 @@ func (d *dataReader) Read(p []byte) (int, error) {
} }
return read, nil return read, nil
} }
// WriteTo writes all the data in the datablock to the writer. MUST BE USED ON A FRESH DATA READER.
func (d *dataReader) WriteTo(w io.Writer) (int64, error) {
type dataCache struct {
err error
data []byte
index int
}
dataChan := make(chan *dataCache)
for i := range d.sizes {
go func(index int, c chan *dataCache) {
var cache dataCache
cache.index = index
defer func() {
c <- &cache
}()
data, err := d.readBlockAt(d.offsetForBlock(index), d.sizes[index])
if err != nil {
cache.err = err
return
}
cache.data = data
return
}(i, dataChan)
}
curIndex := 0
totalWrite := int64(0)
var backlog []*dataCache
mainLoop:
for {
if curIndex == len(d.sizes) {
return totalWrite, nil
}
if len(backlog) > 0 {
for i, cache := range backlog {
if cache.index == curIndex {
writen, err := w.Write(cache.data)
totalWrite += int64(writen)
if err != nil {
return totalWrite, err
}
if len(backlog) > 0 {
backlog[i] = backlog[len(backlog)-1]
backlog = backlog[:len(backlog)-1]
} else {
backlog = nil
}
curIndex++
continue mainLoop
}
}
}
cache := <-dataChan
if cache.err != nil {
return totalWrite, cache.err
}
if cache.index == curIndex {
writen, err := w.Write(cache.data)
totalWrite += int64(writen)
if err != nil {
return totalWrite, err
}
curIndex++
} else {
backlog = append(backlog, cache)
}
}
}
+55 -58
View File
@@ -28,14 +28,18 @@ var (
//File can be either a file or folder. When reading from a squashfs, it reads from the datablocks. //File can be either a file or folder. When reading from a squashfs, it reads from the datablocks.
//When writing, this holds the information on WHERE the file will be placed inside the archive. //When writing, this holds the information on WHERE the file will be placed inside the archive.
// //
//Implements os.FileInfo and io.ReadCloser //If copying data from a squashfs, the returned reader from io.Sys() implements io.WriterTo which
//will be significantly faster then calling Read directly.
//Ex: use io.Sys().(io.Reader) for io.Copy instead of using the File directly.
//
//Implements os.FileInfo and io.Reader
type File struct { type File struct {
Reader io.Reader reader io.Reader
Parent *File Parent *File
r *Reader //Underlying reader. When writing, will probably be an os.File. When reading this is kept nil UNTIL reading to save memory. r *Reader //Underlying reader. When writing, will probably be an os.File. When reading this is kept nil UNTIL reading to save memory.
in *inode.Inode in *inode.Inode
name string name string
path string dir string
filType int //The file's type, using inode types. filType int //The file's type, using inode types.
} }
@@ -61,10 +65,10 @@ func (f *File) Name() string {
//Size is the complete size of the file. Zero if it's not a file. //Size is the complete size of the file. Zero if it's not a file.
func (f *File) Size() int64 { func (f *File) Size() int64 {
switch f.filType { switch f.filType {
case inode.BasicFileType: case inode.FileType:
return int64(f.in.Info.(inode.BasicFile).Init.Size) return int64(f.in.Info.(inode.File).Size)
case inode.ExtFileType: case inode.ExtFileType:
return int64(f.in.Info.(inode.ExtendedFile).Init.Size) return int64(f.in.Info.(inode.ExtFile).Size)
default: default:
return 0 return 0
} }
@@ -75,20 +79,20 @@ func (f *File) ModTime() time.Time {
return time.Unix(int64(f.in.Header.ModifiedTime), 0) return time.Unix(int64(f.in.Header.ModifiedTime), 0)
} }
//Sys returns the underlying reader, file.Reader. If the reader isn't initialized, it will initialize it. //Sys returns the underlying reader. If the reader isn't initialized, it will initialize it.
//If called on something other then a file, returns nil. //If called on something other then a file, returns nil.
func (f *File) Sys() interface{} { func (f *File) Sys() interface{} {
if f.IsFile() { if !f.IsFile() {
if f.Reader == nil && f.r != nil { return nil
}
if f.reader == nil && f.r != nil {
var err error var err error
f.Reader, err = f.r.newFileReader(f.in) f.reader, err = f.r.newFileReader(f.in)
if err != nil { if err != nil {
return nil return nil
} }
} }
return f.Reader return f.reader
}
return nil
} }
//GetChildren returns a *squashfs.File slice of every direct child of the directory. If the File is not a directory, will return ErrNotDirectory //GetChildren returns a *squashfs.File slice of every direct child of the directory. If the File is not a directory, will return ErrNotDirectory
@@ -112,7 +116,7 @@ func (f *File) GetChildren() (children []*File, err error) {
} }
fil.Parent = f fil.Parent = f
if f.name != "" { if f.name != "" {
fil.path = f.Path() fil.dir = f.Path()
} }
children = append(children, fil) children = append(children, fil)
} }
@@ -138,21 +142,14 @@ func (f *File) GetChildrenRecursively() (children []*File, err error) {
childFolders = append(childFolders, child) childFolders = append(childFolders, child)
} }
} }
foldChil := make(chan []*File)
errChan := make(chan error)
for _, folds := range childFolders { for _, folds := range childFolders {
go func(fil *File) { var childs []*File
childs, err := fil.GetChildrenRecursively() childs, err = folds.GetChildrenRecursively()
errChan <- err
foldChil <- childs
}(folds)
}
for range childFolders {
err = <-errChan
if err != nil { if err != nil {
fmt.Println(err)
return return
} }
children = append(children, <-foldChil...) children = append(children, childs...)
} }
return return
} }
@@ -160,26 +157,23 @@ func (f *File) GetChildrenRecursively() (children []*File, err error) {
//Path returns the path of the file within the archive. //Path returns the path of the file within the archive.
func (f *File) Path() string { func (f *File) Path() string {
if f.name == "" { if f.name == "" {
return f.path return f.dir
} }
return f.path + "/" + f.name return f.dir + "/" + f.name
} }
//GetFileAtPath tries to return the File at the given path, relative to the file. //GetFileAtPath tries to return the File at the given path, relative to the file.
//Returns nil if called on something other then a folder, OR if the path goes oustide the archive. //Returns nil if called on something other then a folder, OR if the path goes oustide the archive.
//Allows wildcards supported by path.Match (namely * and ?). //Allows wildcards supported by path.Match (namely * and ?) and will return the FIRST file that matches.
func (f *File) GetFileAtPath(dirPath string) *File { func (f *File) GetFileAtPath(dirPath string) *File {
if dirPath == "" { dirPath = path.Clean(dirPath)
dirPath = strings.TrimPrefix(dirPath, "/")
if dirPath == "" || dirPath == "." {
return f return f
} }
dirPath = strings.TrimSuffix(strings.TrimPrefix(dirPath, "/"), "/") if dirPath != "." && !f.IsDir() {
if dirPath != "" && !f.IsDir() {
return nil return nil
} }
for strings.HasSuffix(dirPath, "./") {
//since you can TECHNICALLY have an infinite amount of ./ and it would still be valid.
dirPath = strings.TrimPrefix(dirPath, "./")
}
split := strings.Split(dirPath, "/") split := strings.Split(dirPath, "/")
if split[0] == ".." && f.name == "" { if split[0] == ".." && f.name == "" {
return nil return nil
@@ -204,27 +198,27 @@ func (f *File) GetFileAtPath(dirPath string) *File {
//IsDir returns if the file is a directory. //IsDir returns if the file is a directory.
func (f *File) IsDir() bool { func (f *File) IsDir() bool {
return f.filType == inode.BasicDirectoryType || f.filType == inode.ExtDirType return f.filType == inode.DirType || f.filType == inode.ExtDirType
} }
//IsSymlink returns if the file is a symlink. //IsSymlink returns if the file is a symlink.
func (f *File) IsSymlink() bool { func (f *File) IsSymlink() bool {
return f.filType == inode.BasicSymlinkType || f.filType == inode.ExtSymlinkType return f.filType == inode.SymType || f.filType == inode.ExtSymType
} }
//IsFile returns if the file is a file. //IsFile returns if the file is a file.
func (f *File) IsFile() bool { func (f *File) IsFile() bool {
return f.filType == inode.BasicFileType || f.filType == inode.ExtFileType return f.filType == inode.FileType || f.filType == inode.ExtFileType
} }
//SymlinkPath returns the path the symlink is pointing to. If the file ISN'T a symlink, will return an empty string. //SymlinkPath returns the path the symlink is pointing to. If the file ISN'T a symlink, will return an empty string.
//If a path begins with "/" then the symlink is pointing to an absolute path (starting from root, and not a file inside the archive) //If a path begins with "/" then the symlink is pointing to an absolute path (starting from root, and not a file inside the archive)
func (f *File) SymlinkPath() string { func (f *File) SymlinkPath() string {
switch f.filType { switch f.filType {
case inode.BasicSymlinkType: case inode.SymType:
return f.in.Info.(inode.BasicSymlink).Path return f.in.Info.(inode.Sym).Path
case inode.ExtSymlinkType: case inode.ExtSymType:
return f.in.Info.(inode.ExtendedSymlink).Path return f.in.Info.(inode.ExtSym).Path
default: default:
return "" return ""
} }
@@ -319,7 +313,8 @@ func (f *File) ExtractWithOptions(path string, dereferenceSymlink, unbreakSymlin
errs = append(errs, err) errs = append(errs, err)
return return
} }
fil, err := os.Open(path + "/" + f.name) var fil *os.File
fil, err = os.Open(path + "/" + f.name)
if err != nil { if err != nil {
if verbose { if verbose {
fmt.Println("Error while opening:", path+"/"+f.name) fmt.Println("Error while opening:", path+"/"+f.name)
@@ -346,7 +341,8 @@ func (f *File) ExtractWithOptions(path string, dereferenceSymlink, unbreakSymlin
errs = append(errs, err) errs = append(errs, err)
} }
} }
children, err := f.GetChildren() var children []*File
children, err = f.GetChildren()
if err != nil { if err != nil {
if verbose { if verbose {
fmt.Println("Error getting children for:", f.Path()) fmt.Println("Error getting children for:", f.Path())
@@ -370,7 +366,8 @@ func (f *File) ExtractWithOptions(path string, dereferenceSymlink, unbreakSymlin
} }
return return
case f.IsFile(): case f.IsFile():
fil, err := os.Create(path + "/" + f.name) var fil *os.File
fil, err = os.Create(path + "/" + f.name)
if os.IsExist(err) { if os.IsExist(err) {
err = os.Remove(path + "/" + f.name) err = os.Remove(path + "/" + f.name)
if err != nil { if err != nil {
@@ -398,7 +395,7 @@ func (f *File) ExtractWithOptions(path string, dereferenceSymlink, unbreakSymlin
errs = append(errs, err) errs = append(errs, err)
return return
} //Since we will be reading from the file } //Since we will be reading from the file
_, err = io.Copy(fil, f) _, err = io.Copy(fil, f.Sys().(io.Reader))
if err != nil { if err != nil {
if verbose { if verbose {
fmt.Println("Error while Copying data to:", path+"/"+f.name) fmt.Println("Error while Copying data to:", path+"/"+f.name)
@@ -480,17 +477,17 @@ func (f *File) ExtractWithOptions(path string, dereferenceSymlink, unbreakSymlin
//Read from the file. Doesn't do anything fancy, just pases it to the underlying io.Reader. If a directory, return io.EOF. //Read from the file. Doesn't do anything fancy, just pases it to the underlying io.Reader. If a directory, return io.EOF.
func (f *File) Read(p []byte) (int, error) { func (f *File) Read(p []byte) (int, error) {
if f.IsDir() { if !f.IsFile() {
return 0, io.EOF return 0, io.EOF
} }
var err error var err error
if f.Reader == nil && f.r != nil { if f.reader == nil && f.r != nil {
f.Reader, err = f.r.newFileReader(f.in) f.reader, err = f.r.newFileReader(f.in)
if err != nil { if err != nil {
return 0, err return 0, err
} }
} }
return f.Reader.Read(p) return f.reader.Read(p)
} }
//ReadDirFromInode returns a fully populated Directory from a given Inode. //ReadDirFromInode returns a fully populated Directory from a given Inode.
@@ -500,14 +497,14 @@ func (r *Reader) readDirFromInode(i *inode.Inode) (*directory.Directory, error)
var metaOffset uint16 var metaOffset uint16
var size uint32 var size uint32
switch i.Type { switch i.Type {
case inode.BasicDirectoryType: case inode.DirType:
offset = i.Info.(inode.BasicDirectory).DirectoryIndex offset = i.Info.(inode.Dir).DirectoryIndex
metaOffset = i.Info.(inode.BasicDirectory).DirectoryOffset metaOffset = i.Info.(inode.Dir).DirectoryOffset
size = uint32(i.Info.(inode.BasicDirectory).DirectorySize) size = uint32(i.Info.(inode.Dir).DirectorySize)
case inode.ExtDirType: case inode.ExtDirType:
offset = i.Info.(inode.ExtendedDirectory).Init.DirectoryIndex offset = i.Info.(inode.ExtDir).DirectoryIndex
metaOffset = i.Info.(inode.ExtendedDirectory).Init.DirectoryOffset metaOffset = i.Info.(inode.ExtDir).DirectoryOffset
size = i.Info.(inode.ExtendedDirectory).Init.DirectorySize size = i.Info.(inode.ExtDir).DirectorySize
default: default:
return nil, errors.New("Not a directory inode") return nil, errors.New("Not a directory inode")
} }
@@ -532,7 +529,7 @@ func (r *Reader) getInodeFromEntry(en *directory.Entry) (*inode.Inode, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
_, err = br.Seek(int64(en.Init.Offset), io.SeekStart) _, err = br.Seek(int64(en.Offset), io.SeekStart)
if err != nil { if err != nil {
return nil, err return nil, err
} }
+24 -8
View File
@@ -29,20 +29,20 @@ var (
func (r *Reader) newFileReader(in *inode.Inode) (*fileReader, error) { func (r *Reader) newFileReader(in *inode.Inode) (*fileReader, error) {
var rdr fileReader var rdr fileReader
rdr.in = in rdr.in = in
if in.Type != inode.BasicFileType && in.Type != inode.ExtFileType { if in.Type != inode.FileType && in.Type != inode.ExtFileType {
return nil, errPathIsNotFile return nil, errPathIsNotFile
} }
switch in.Type { switch in.Type {
case inode.BasicFileType: case inode.FileType:
fil := in.Info.(inode.BasicFile) fil := in.Info.(inode.File)
rdr.fragged = fil.Fragmented rdr.fragged = fil.Fragmented
rdr.fragOnly = fil.Init.BlockStart == 0 rdr.fragOnly = fil.BlockStart == 0
rdr.FileSize = int(fil.Init.Size) rdr.FileSize = int(fil.Size)
case inode.ExtFileType: case inode.ExtFileType:
fil := in.Info.(inode.ExtendedFile) fil := in.Info.(inode.ExtFile)
rdr.fragged = fil.Fragmented rdr.fragged = fil.Fragmented
rdr.fragOnly = fil.Init.BlockStart == 0 rdr.fragOnly = fil.BlockStart == 0
rdr.FileSize = int(fil.Init.Size) rdr.FileSize = int(fil.Size)
} }
var err error var err error
if rdr.fragged { if rdr.fragged {
@@ -83,3 +83,19 @@ func (f *fileReader) Read(p []byte) (int, error) {
} }
return read, nil return read, nil
} }
func (f *fileReader) WriteTo(w io.Writer) (int64, error) {
if f.fragOnly {
n, err := w.Write(f.fragmentData)
return int64(n), err
}
if !f.fragged {
return f.data.WriteTo(w)
}
n, err := f.data.WriteTo(w)
if err != nil {
return int64(n), err
}
nn, err := w.Write(f.fragmentData)
return int64(nn) + n, err
}
+12 -12
View File
@@ -12,7 +12,7 @@ import (
type fragmentEntry struct { type fragmentEntry struct {
Start uint64 Start uint64
Size uint32 Size uint32
Unused uint32 // Unused uint32
} }
//GetFragmentDataFromInode returns the fragment data for a given inode. //GetFragmentDataFromInode returns the fragment data for a given inode.
@@ -21,30 +21,30 @@ func (r *Reader) getFragmentDataFromInode(in *inode.Inode) ([]byte, error) {
var size uint32 var size uint32
var fragIndex uint32 var fragIndex uint32
var fragOffset uint32 var fragOffset uint32
if in.Type == inode.BasicFileType { if in.Type == inode.FileType {
bf := in.Info.(inode.BasicFile) bf := in.Info.(inode.File)
if !bf.Fragmented { if !bf.Fragmented {
return make([]byte, 0), nil return make([]byte, 0), nil
} }
if bf.Init.BlockStart == 0 { if bf.BlockStart == 0 {
size = bf.Init.Size size = bf.Size
} else { } else {
size = bf.BlockSizes[len(bf.BlockSizes)-1] size = bf.BlockSizes[len(bf.BlockSizes)-1]
} }
fragIndex = bf.Init.FragmentIndex fragIndex = bf.FragmentIndex
fragOffset = bf.Init.FragmentOffset fragOffset = bf.FragmentOffset
} else if in.Type == inode.ExtFileType { } else if in.Type == inode.ExtFileType {
bf := in.Info.(inode.ExtendedFile) bf := in.Info.(inode.ExtFile)
if !bf.Fragmented { if !bf.Fragmented {
return make([]byte, 0), nil return make([]byte, 0), nil
} }
if bf.Init.BlockStart == 0 { if bf.BlockStart == 0 {
size = bf.Init.Size size = bf.Size
} else { } else {
size = bf.BlockSizes[len(bf.BlockSizes)-1] size = bf.BlockSizes[len(bf.BlockSizes)-1]
} }
fragIndex = bf.Init.FragmentIndex fragIndex = bf.FragmentIndex
fragOffset = bf.Init.FragmentOffset fragOffset = bf.FragmentOffset
} else { } else {
return nil, errors.New("Inode type not supported") return nil, errors.New("Inode type not supported")
} }
+5 -4
View File
@@ -3,16 +3,17 @@ module github.com/CalebQ42/squashfs
go 1.15 go 1.15
require ( require (
github.com/CalebQ42/GoAppImage v0.4.0 github.com/CalebQ42/GoAppImage v0.5.0
github.com/adrg/xdg v0.2.3 // indirect github.com/adrg/xdg v0.2.3 // indirect
github.com/google/go-cmp v0.5.4 // indirect github.com/google/go-cmp v0.5.4 // indirect
github.com/gopherjs/gopherjs v0.0.0-20200217142428-fce0ec30dd00 // indirect github.com/gopherjs/gopherjs v0.0.0-20200217142428-fce0ec30dd00 // indirect
github.com/klauspost/compress v1.11.4 github.com/klauspost/compress v1.11.6
github.com/kr/text v0.2.0 // indirect github.com/kr/text v0.2.0 // indirect
github.com/pierrec/lz4/v4 v4.1.2 github.com/pierrec/lz4/v4 v4.1.3
github.com/smartystreets/assertions v1.2.0 // indirect github.com/smartystreets/assertions v1.2.0 // indirect
github.com/stretchr/testify v1.7.0 // indirect
github.com/ulikunitz/xz v0.5.9 github.com/ulikunitz/xz v0.5.9
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776 // indirect gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
) )
+11 -8
View File
@@ -1,5 +1,5 @@
github.com/CalebQ42/GoAppImage v0.4.0 h1:aF+Y/vyo/RGhoyZEW1CMY6WyRWrZZO4ydsRFAtIGnaY= github.com/CalebQ42/GoAppImage v0.5.0 h1:znoKNXtliH754tS9sYwyOIg/0wFDjFN5Twc7PAh1rSM=
github.com/CalebQ42/GoAppImage v0.4.0/go.mod h1:qHudJKAn/dlkNWNnH4h1YKXp29EZ7Bppsn7sNP2HuvU= github.com/CalebQ42/GoAppImage v0.5.0/go.mod h1:qHudJKAn/dlkNWNnH4h1YKXp29EZ7Bppsn7sNP2HuvU=
github.com/adrg/xdg v0.2.2 h1:A7ZHKRz5KGOLJX/bg7IPzStryhvCzAE1wX+KWawPiAo= github.com/adrg/xdg v0.2.2 h1:A7ZHKRz5KGOLJX/bg7IPzStryhvCzAE1wX+KWawPiAo=
github.com/adrg/xdg v0.2.2/go.mod h1:7I2hH/IT30IsupOpKZ5ue7/qNi3CoKzD6tL3HwpaRMQ= github.com/adrg/xdg v0.2.2/go.mod h1:7I2hH/IT30IsupOpKZ5ue7/qNi3CoKzD6tL3HwpaRMQ=
github.com/adrg/xdg v0.2.3 h1:GxXngdYxNDkoUvZXjNJGwqZxWXi43MKbOOlA/00qZi4= github.com/adrg/xdg v0.2.3 h1:GxXngdYxNDkoUvZXjNJGwqZxWXi43MKbOOlA/00qZi4=
@@ -18,8 +18,8 @@ github.com/gopherjs/gopherjs v0.0.0-20200217142428-fce0ec30dd00 h1:l5lAOZEym3oK3
github.com/gopherjs/gopherjs v0.0.0-20200217142428-fce0ec30dd00/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gopherjs/gopherjs v0.0.0-20200217142428-fce0ec30dd00/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo=
github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU=
github.com/klauspost/compress v1.11.4 h1:kz40R/YWls3iqT9zX9AHN3WoVsrAWVyui5sxuLqiXqU= github.com/klauspost/compress v1.11.6 h1:EgWPCW6O3n1D5n99Zq3xXBt9uCwRGvpwGOusOLNBRSQ=
github.com/klauspost/compress v1.11.4/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= github.com/klauspost/compress v1.11.6/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs=
github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI= github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI=
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
@@ -29,8 +29,8 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
github.com/pierrec/lz4/v4 v4.1.2 h1:qvY3YFXRQE/XB8MlLzJH7mSzBs74eA2gg52YTk6jUPM= github.com/pierrec/lz4/v4 v4.1.3 h1:/dvQpkb0o1pVlSgKNQqfkavlnXaIK+hJ0LXsKRUN9D4=
github.com/pierrec/lz4/v4 v4.1.2/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= github.com/pierrec/lz4/v4 v4.1.3/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM=
@@ -39,9 +39,12 @@ github.com/smartystreets/assertions v1.2.0 h1:42S6lae5dvLc7BrLu/0ugRtcFVjoJNMC/N
github.com/smartystreets/assertions v1.2.0/go.mod h1:tcbTF8ujkAEcZ8TElKY+i30BzYlVhC/LOxJk7iOWnoo= github.com/smartystreets/assertions v1.2.0/go.mod h1:tcbTF8ujkAEcZ8TElKY+i30BzYlVhC/LOxJk7iOWnoo=
github.com/smartystreets/goconvey v1.6.4 h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIKYqbNC9s= github.com/smartystreets/goconvey v1.6.4 h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIKYqbNC9s=
github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA=
github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0= github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/ulikunitz/xz v0.5.9 h1:RsKRIA2MO8x56wkkcd3LbtcE/uMszhb6DpRf+3uwa3I= github.com/ulikunitz/xz v0.5.9 h1:RsKRIA2MO8x56wkkcd3LbtcE/uMszhb6DpRf+3uwa3I=
github.com/ulikunitz/xz v0.5.9/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14= github.com/ulikunitz/xz v0.5.9/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=
go.lsp.dev/uri v0.3.0 h1:KcZJmh6nFIBeJzTugn5JTU6OOyG0lDOo3R9KwTxTYbo= go.lsp.dev/uri v0.3.0 h1:KcZJmh6nFIBeJzTugn5JTU6OOyG0lDOo3R9KwTxTYbo=
@@ -69,5 +72,5 @@ gopkg.in/ini.v1 v1.62.0 h1:duBzk771uxoUuOlyRLkHsygud9+5lrlGjdFBb4mSKDU=
gopkg.in/ini.v1 v1.62.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/ini.v1 v1.62.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776 h1:tQIYjPdBoyREyB9XMu+nnTclpTYkz2zFM+lzLJFO4gQ= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo=
gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+19 -10
View File
@@ -15,7 +15,8 @@ type gzipInit struct {
//Gzip is a decompressor for gzip type compression. Uses zlib for compression and decompression //Gzip is a decompressor for gzip type compression. Uses zlib for compression and decompression
type Gzip struct { type Gzip struct {
CompressionLevel int32 wrt *zlib.Writer
gzipInit
HasCustomWindow bool HasCustomWindow bool
HasStrategies bool HasStrategies bool
} }
@@ -23,15 +24,13 @@ type Gzip struct {
//NewGzipCompressorWithOptions creates a new gzip compressor/decompressor with options read from the given reader. //NewGzipCompressorWithOptions creates a new gzip compressor/decompressor with options read from the given reader.
func NewGzipCompressorWithOptions(r io.Reader) (*Gzip, error) { func NewGzipCompressorWithOptions(r io.Reader) (*Gzip, error) {
var gzip Gzip var gzip Gzip
var init gzipInit err := binary.Read(r, binary.LittleEndian, &gzip.gzipInit)
err := binary.Read(r, binary.LittleEndian, &init)
if err != nil { if err != nil {
return nil, err return nil, err
} }
gzip.CompressionLevel = init.CompressionLevel
//TODO: proper support for window size and strategies //TODO: proper support for window size and strategies
gzip.HasCustomWindow = init.WindowSize != 15 gzip.HasCustomWindow = gzip.WindowSize != 15
gzip.HasStrategies = init.Strategies != 0 && init.Strategies != 1 gzip.HasStrategies = gzip.Strategies != 0 && gzip.Strategies != 1
return &gzip, nil return &gzip, nil
} }
@@ -52,15 +51,25 @@ func (g *Gzip) Decompress(r io.Reader) ([]byte, error) {
//Compress compresses the given data (as a byte array) and returns the compressed data. //Compress compresses the given data (as a byte array) and returns the compressed data.
func (g *Gzip) Compress(data []byte) ([]byte, error) { func (g *Gzip) Compress(data []byte) ([]byte, error) {
var buf bytes.Buffer var buf bytes.Buffer
wrt := zlib.NewWriter(&buf) var err error
defer wrt.Close() if g.wrt == nil {
_, err := wrt.Write(data) if g.CompressionLevel == 0 {
g.wrt = zlib.NewWriter(&buf)
} else {
g.wrt, err = zlib.NewWriterLevel(&buf, int(g.CompressionLevel))
if err != nil { if err != nil {
return nil, err return nil, err
} }
err = wrt.Flush() }
}
wrt, err := zlib.NewWriterLevel(&buf, int(g.CompressionLevel))
if err != nil { if err != nil {
return nil, err return nil, err
} }
_, err = wrt.Write(data)
if err != nil {
return nil, err
}
wrt.Close()
return buf.Bytes(), nil return buf.Bytes(), nil
} }
+18
View File
@@ -35,3 +35,21 @@ func (l *Lz4) Decompress(r io.Reader) ([]byte, error) {
_, err := io.Copy(&buf, rdr) _, err := io.Copy(&buf, rdr)
return buf.Bytes(), err return buf.Bytes(), err
} }
//Compress implements compression.Compress
func (l *Lz4) Compress(data []byte) ([]byte, error) {
var buf bytes.Buffer
w := lz4.NewWriter(&buf)
if l.HC {
err := w.Apply(lz4.CompressionLevelOption(lz4.Level9))
if err != nil {
return nil, err
}
}
_, err := w.Write(data)
if err != nil {
return nil, err
}
w.Close()
return buf.Bytes(), nil
}
+15
View File
@@ -23,3 +23,18 @@ func (l *Lzma) Decompress(rdr io.Reader) ([]byte, error) {
} }
return buf.Bytes(), nil return buf.Bytes(), nil
} }
//Compress implements compression.Compress
func (l *Lzma) Compress(data []byte) ([]byte, error) {
var buf bytes.Buffer
w, err := lzma.NewWriter(&buf)
if err != nil {
return nil, err
}
_, err = w.Write(data)
if err != nil {
return nil, err
}
w.Close()
return buf.Bytes(), nil
}
+20
View File
@@ -53,3 +53,23 @@ func (x *Xz) Decompress(rdr io.Reader) ([]byte, error) {
} }
return buf.Bytes(), nil return buf.Bytes(), nil
} }
//Compress implements compression.Compress
func (x *Xz) Compress(data []byte) ([]byte, error) {
var buf bytes.Buffer
w, err := xz.NewWriter(&buf)
if err != nil {
return nil, err
}
w.DictCap = int(x.DictionarySize)
err = w.Verify()
if err != nil {
return nil, err
}
_, err = w.Write(data)
if err != nil {
return nil, err
}
w.Close()
return buf.Bytes(), nil
}
+15
View File
@@ -34,3 +34,18 @@ func (z *Zstd) Decompress(r io.Reader) ([]byte, error) {
_, err = io.Copy(&buf, rdr) _, err = io.Copy(&buf, rdr)
return buf.Bytes(), err return buf.Bytes(), err
} }
//Compress impelements compression.Compress
func (z *Zstd) Compress(data []byte) ([]byte, error) {
var buf bytes.Buffer
w, err := zstd.NewWriter(&buf, zstd.WithEncoderLevel(zstd.EncoderLevel(z.CompressionLevel)))
if err != nil {
return nil, err
}
_, err = w.Write(data)
if err != nil {
return nil, err
}
w.Close()
return buf.Bytes(), nil
}
+6 -6
View File
@@ -13,8 +13,8 @@ type Header struct {
InodeNumber uint32 InodeNumber uint32
} }
//EntryInit is the values that can be easily decoded //EntryRaw is the values that can be easily decoded
type EntryInit struct { type EntryRaw struct {
Offset uint16 Offset uint16
InodeOffset int16 InodeOffset int16
Type uint16 Type uint16
@@ -23,19 +23,19 @@ type EntryInit struct {
//Entry is an entry in a directory. //Entry is an entry in a directory.
type Entry struct { type Entry struct {
Init EntryInit *Header
Name string Name string
Header *Header EntryRaw
} }
//NewEntry creates a new directory entry //NewEntry creates a new directory entry
func NewEntry(rdr io.Reader) (Entry, error) { func NewEntry(rdr io.Reader) (Entry, error) {
var entry Entry var entry Entry
err := binary.Read(rdr, binary.LittleEndian, &entry.Init) err := binary.Read(rdr, binary.LittleEndian, &entry.EntryRaw)
if err != nil { if err != nil {
return Entry{}, err return Entry{}, err
} }
tmp := make([]byte, entry.Init.NameSize+1) tmp := make([]byte, entry.EntryRaw.NameSize+1)
err = binary.Read(rdr, binary.LittleEndian, &tmp) err = binary.Read(rdr, binary.LittleEndian, &tmp)
if err != nil { if err != nil {
return Entry{}, err return Entry{}, err
+86 -84
View File
@@ -5,17 +5,18 @@ import (
"io" "io"
) )
//The different types of inodes as defined by inodetype
const ( const (
BasicDirectoryType = iota + 1 DirType = iota + 1
BasicFileType FileType
BasicSymlinkType SymType
BasicBlockDeviceType BlockDevType
BasicCharDeviceType CharDevType
BasicFifoType FifoType
BasicSocketType SocketType
ExtDirType ExtDirType
ExtFileType ExtFileType
ExtSymlinkType ExtSymType
ExtBlockDeviceType ExtBlockDeviceType
ExtCharDeviceType ExtCharDeviceType
ExtFifoType ExtFifoType
@@ -32,8 +33,8 @@ type Header struct {
Number uint32 Number uint32
} }
//BasicDirectory is self explainatory //Dir is self explainatory
type BasicDirectory struct { type Dir struct {
DirectoryIndex uint32 DirectoryIndex uint32
HardLinks uint32 HardLinks uint32
DirectorySize uint16 DirectorySize uint16
@@ -41,8 +42,8 @@ type BasicDirectory struct {
ParentInodeNumber uint32 ParentInodeNumber uint32
} }
//ExtendedDirectoryInit is the information that can be directoy decoded //ExtDirInit is the information that can be directoy decoded
type ExtendedDirectoryInit struct { type ExtDirInit struct {
HardLinks uint32 HardLinks uint32
DirectorySize uint32 DirectorySize uint32
DirectoryIndex uint32 DirectoryIndex uint32
@@ -52,21 +53,22 @@ type ExtendedDirectoryInit struct {
XattrIndex uint32 XattrIndex uint32
} }
//ExtendedDirectory is a directory with extra info //ExtDir is a directory with extra info
type ExtendedDirectory struct { type ExtDir struct {
Init ExtendedDirectoryInit Indexes []DirIndex
Indexes []DirectoryIndex ExtDirInit
} }
//NewExtendedDirectory creates a new ExtendedDirectory //NewExtendedDirectory creates a new ExtendedDirectory
func NewExtendedDirectory(rdr io.Reader) (ExtendedDirectory, error) { func NewExtendedDirectory(rdr io.Reader) (ExtDir, error) {
var inode ExtendedDirectory var inode ExtDir
err := binary.Read(rdr, binary.LittleEndian, &inode.Init) err := binary.Read(rdr, binary.LittleEndian, &inode.ExtDirInit)
if err != nil { if err != nil {
return inode, err return inode, err
} }
for i := uint16(0); i < inode.Init.IndexCount; i++ { for i := uint16(0); i < inode.IndexCount; i++ {
tmp, err := NewDirectoryIndex(rdr) var tmp DirIndex
tmp, err = NewDirectoryIndex(rdr)
if err != nil { if err != nil {
return inode, err return inode, err
} }
@@ -75,27 +77,27 @@ func NewExtendedDirectory(rdr io.Reader) (ExtendedDirectory, error) {
return inode, err return inode, err
} }
//DirectoryIndexInit holds the values that can be easily decoded //DirIndexInit holds the values that can be easily decoded
type DirectoryIndexInit struct { type DirIndexInit struct {
Offset uint32 Offset uint32
DirTableOffset uint32 DirTableOffset uint32
NameSize uint32 NameSize uint32
} }
//DirectoryIndex is a quick lookup provided by an ExtendedDirectory //DirIndex is a quick lookup provided by an ExtendedDirectory
type DirectoryIndex struct { type DirIndex struct {
Init DirectoryIndexInit
Name string Name string
DirIndexInit
} }
//NewDirectoryIndex return a new DirectoryIndex //NewDirectoryIndex return a new DirectoryIndex
func NewDirectoryIndex(rdr io.Reader) (DirectoryIndex, error) { func NewDirectoryIndex(rdr io.Reader) (DirIndex, error) {
var index DirectoryIndex var index DirIndex
err := binary.Read(rdr, binary.LittleEndian, &index.Init) err := binary.Read(rdr, binary.LittleEndian, &index.DirIndexInit)
if err != nil { if err != nil {
return index, err return index, err
} }
tmp := make([]byte, index.Init.NameSize+1, index.Init.NameSize+1) tmp := make([]byte, index.NameSize+1, index.NameSize+1)
err = binary.Read(rdr, binary.LittleEndian, &tmp) err = binary.Read(rdr, binary.LittleEndian, &tmp)
if err != nil { if err != nil {
return index, err return index, err
@@ -104,31 +106,31 @@ func NewDirectoryIndex(rdr io.Reader) (DirectoryIndex, error) {
return index, nil return index, nil
} }
//BasicFileInit is the information that can be directoy decoded //FileInit is the information that can be directly decoded
type BasicFileInit struct { type FileInit struct {
BlockStart uint32 BlockStart uint32
FragmentIndex uint32 FragmentIndex uint32
FragmentOffset uint32 FragmentOffset uint32
Size uint32 Size uint32
} }
//BasicFile is self explainatory //File is self explainatory
type BasicFile struct { type File struct {
Init BasicFileInit
BlockSizes []uint32 BlockSizes []uint32
Fragmented bool Fragmented bool
FileInit
} }
//NewBasicFile creates a new BasicFile //NewFile creates a new File
func NewBasicFile(rdr io.Reader, blockSize uint32) (BasicFile, error) { func NewFile(rdr io.Reader, blockSize uint32) (File, error) {
var inode BasicFile var inode File
err := binary.Read(rdr, binary.LittleEndian, &inode.Init) err := binary.Read(rdr, binary.LittleEndian, &inode.FileInit)
if err != nil { if err != nil {
return inode, err return inode, err
} }
inode.Fragmented = inode.Init.FragmentIndex != 0xFFFFFFFF inode.Fragmented = inode.FragmentIndex != 0xFFFFFFFF
blocks := inode.Init.Size / blockSize blocks := inode.Size / blockSize
if inode.Init.Size%blockSize > 0 { if inode.Size%blockSize > 0 {
blocks++ blocks++
} }
inode.BlockSizes = make([]uint32, blocks, blocks) inode.BlockSizes = make([]uint32, blocks, blocks)
@@ -136,8 +138,8 @@ func NewBasicFile(rdr io.Reader, blockSize uint32) (BasicFile, error) {
return inode, err return inode, err
} }
//ExtendedFileInit is the information that can be directly decoded //ExtFileInit is the information that can be directly decoded
type ExtendedFileInit struct { type ExtFileInit struct {
BlockStart uint32 BlockStart uint32
Size uint32 Size uint32
Sparse uint64 Sparse uint64
@@ -147,23 +149,23 @@ type ExtendedFileInit struct {
XattrIndex uint32 XattrIndex uint32
} }
//ExtendedFile is a file with more information //ExtFile is a file with more information
type ExtendedFile struct { type ExtFile struct {
Init ExtendedFileInit
BlockSizes []uint32 BlockSizes []uint32
Fragmented bool Fragmented bool
ExtFileInit
} }
//NewExtendedFile creates a new ExtendedFile //NewExtendedFile creates a new ExtendedFile
func NewExtendedFile(rdr io.Reader, blockSize uint32) (ExtendedFile, error) { func NewExtendedFile(rdr io.Reader, blockSize uint32) (ExtFile, error) {
var inode ExtendedFile var inode ExtFile
err := binary.Read(rdr, binary.LittleEndian, &inode.Init) err := binary.Read(rdr, binary.LittleEndian, &inode.ExtFileInit)
if err != nil { if err != nil {
return inode, err return inode, err
} }
inode.Fragmented = inode.Init.FragmentIndex != 0xFFFFFFFF inode.Fragmented = inode.FragmentIndex != 0xFFFFFFFF
blocks := inode.Init.Size / blockSize blocks := inode.Size / blockSize
if inode.Init.Size%blockSize > 0 { if inode.Size%blockSize > 0 {
blocks++ blocks++
} }
inode.BlockSizes = make([]uint32, blocks, blocks) inode.BlockSizes = make([]uint32, blocks, blocks)
@@ -171,27 +173,27 @@ func NewExtendedFile(rdr io.Reader, blockSize uint32) (ExtendedFile, error) {
return inode, err return inode, err
} }
//BasicSymlinkInit is all the values that can be directly decoded //SymInit is all the values that can be directly decoded
type BasicSymlinkInit struct { type SymInit struct {
HardLinks uint32 HardLinks uint32
TargetPathSize uint32 TargetPathSize uint32
} }
//BasicSymlink is a symlink //Sym is a symlink
type BasicSymlink struct { type Sym struct {
Init BasicSymlinkInit
targetPath []byte //len is TargetPathSize
Path string Path string
targetPath []byte //len is TargetPathSize
SymInit
} }
//NewBasicSymlink creates a new BasicSymlink //NewSymlink creates a new Symlink
func NewBasicSymlink(rdr io.Reader) (BasicSymlink, error) { func NewSymlink(rdr io.Reader) (Sym, error) {
var inode BasicSymlink var inode Sym
err := binary.Read(rdr, binary.LittleEndian, &inode.Init) err := binary.Read(rdr, binary.LittleEndian, &inode.SymInit)
if err != nil { if err != nil {
return inode, err return inode, err
} }
inode.targetPath = make([]byte, inode.Init.TargetPathSize, inode.Init.TargetPathSize) inode.targetPath = make([]byte, inode.TargetPathSize, inode.TargetPathSize)
err = binary.Read(rdr, binary.LittleEndian, &inode.targetPath) err = binary.Read(rdr, binary.LittleEndian, &inode.targetPath)
if err != nil { if err != nil {
return inode, err return inode, err
@@ -200,28 +202,28 @@ func NewBasicSymlink(rdr io.Reader) (BasicSymlink, error) {
return inode, err return inode, err
} }
//ExtendedSymlinkInit is all the values that can be directly decoded //ExtSymInit is all the values that can be directly decoded
type ExtendedSymlinkInit struct { type ExtSymInit struct {
HardLinks uint32 HardLinks uint32
TargetPathSize uint32 TargetPathSize uint32
} }
//ExtendedSymlink is a symlink with extra information //ExtSym is a symlink with extra information
type ExtendedSymlink struct { type ExtSym struct {
Init ExtendedSymlinkInit
targetPath []uint8
Path string Path string
targetPath []uint8
ExtSymInit
XattrIndex uint32 XattrIndex uint32
} }
//NewExtendedSymlink creates a new ExtendedSymlink //NewExtendedSymlink creates a new ExtendedSymlink
func NewExtendedSymlink(rdr io.Reader) (ExtendedSymlink, error) { func NewExtendedSymlink(rdr io.Reader) (ExtSym, error) {
var inode ExtendedSymlink var inode ExtSym
err := binary.Read(rdr, binary.LittleEndian, &inode.Init) err := binary.Read(rdr, binary.LittleEndian, &inode.ExtSymInit)
if err != nil { if err != nil {
return inode, err return inode, err
} }
inode.targetPath = make([]uint8, inode.Init.TargetPathSize, inode.Init.TargetPathSize) inode.targetPath = make([]uint8, inode.TargetPathSize, inode.TargetPathSize)
err = binary.Read(rdr, binary.LittleEndian, &inode.targetPath) err = binary.Read(rdr, binary.LittleEndian, &inode.targetPath)
if err != nil { if err != nil {
return inode, err return inode, err
@@ -231,25 +233,25 @@ func NewExtendedSymlink(rdr io.Reader) (ExtendedSymlink, error) {
return inode, err return inode, err
} }
//BasicDevice is a device //Device is a device
type BasicDevice struct { type Device struct {
HardLinks uint32 HardLinks uint32
Device uint32 Device uint32
} }
//ExtendedDevice is a device with more info //ExtDevice is a device with more info
type ExtendedDevice struct { type ExtDevice struct {
BasicDevice Device
XattrIndex uint32 XattrIndex uint32
} }
//BasicIPC is a Fifo or Socket device //IPC is a Fifo or Socket device
type BasicIPC struct { type IPC struct {
HardLink uint32 HardLink uint32
} }
//ExtendedIPC is a IPC device with extra info //ExtIPC is a IPC device with extra info
type ExtendedIPC struct { type ExtIPC struct {
BasicIPC IPC
XattrIndex uint32 XattrIndex uint32
} }
+29 -24
View File
@@ -9,9 +9,9 @@ import (
// //
//Info holds the actual Inode. Due to each inode type being a different type, it's store as an interface{} //Info holds the actual Inode. Due to each inode type being a different type, it's store as an interface{}
type Inode struct { type Inode struct {
Header Header
Type int //Type the inode type defined in the header. Here so it's easy to access
Info interface{} //Info is the parsed specific data. It's type is defined by Type. Info interface{} //Info is the parsed specific data. It's type is defined by Type.
Type int //Type the inode type defined in the header. Here so it's easy to access
Header
} }
//ProcessInode tries to read an inode from the BlockReader //ProcessInode tries to read an inode from the BlockReader
@@ -23,94 +23,99 @@ func ProcessInode(br io.Reader, blockSize uint32) (*Inode, error) {
} }
var info interface{} var info interface{}
switch head.InodeType { switch head.InodeType {
case BasicDirectoryType: case DirType:
var inode BasicDirectory var inode Dir
err = binary.Read(br, binary.LittleEndian, &inode) err = binary.Read(br, binary.LittleEndian, &inode)
if err != nil { if err != nil {
return nil, err return nil, err
} }
info = inode info = inode
case BasicFileType: case FileType:
inode, err := NewBasicFile(br, blockSize) var inode File
inode, err = NewFile(br, blockSize)
if err != nil { if err != nil {
return nil, err return nil, err
} }
info = inode info = inode
case BasicSymlinkType: case SymType:
inode, err := NewBasicSymlink(br) var inode Sym
inode, err = NewSymlink(br)
if err != nil { if err != nil {
return nil, err return nil, err
} }
info = inode info = inode
case BasicBlockDeviceType: case BlockDevType:
var inode BasicDevice var inode Device
err = binary.Read(br, binary.LittleEndian, &inode) err = binary.Read(br, binary.LittleEndian, &inode)
if err != nil { if err != nil {
return nil, err return nil, err
} }
info = inode info = inode
case BasicCharDeviceType: case CharDevType:
var inode BasicDevice var inode Device
err = binary.Read(br, binary.LittleEndian, &inode) err = binary.Read(br, binary.LittleEndian, &inode)
if err != nil { if err != nil {
return nil, err return nil, err
} }
info = inode info = inode
case BasicFifoType: case FifoType:
var inode BasicIPC var inode IPC
err = binary.Read(br, binary.LittleEndian, &inode) err = binary.Read(br, binary.LittleEndian, &inode)
if err != nil { if err != nil {
return nil, err return nil, err
} }
info = inode info = inode
case BasicSocketType: case SocketType:
var inode BasicIPC var inode IPC
err = binary.Read(br, binary.LittleEndian, &inode) err = binary.Read(br, binary.LittleEndian, &inode)
if err != nil { if err != nil {
return nil, err return nil, err
} }
info = inode info = inode
case ExtDirType: case ExtDirType:
inode, err := NewExtendedDirectory(br) var inode ExtDir
inode, err = NewExtendedDirectory(br)
if err != nil { if err != nil {
return nil, err return nil, err
} }
info = inode info = inode
case ExtFileType: case ExtFileType:
inode, err := NewExtendedFile(br, blockSize) var inode ExtFile
inode, err = NewExtendedFile(br, blockSize)
if err != nil { if err != nil {
return nil, err return nil, err
} }
info = inode info = inode
case ExtSymlinkType: case ExtSymType:
inode, err := NewExtendedSymlink(br) var inode ExtSym
inode, err = NewExtendedSymlink(br)
if err != nil { if err != nil {
return nil, err return nil, err
} }
info = inode info = inode
case ExtBlockDeviceType: case ExtBlockDeviceType:
var inode ExtendedDevice var inode ExtDevice
err = binary.Read(br, binary.LittleEndian, &inode) err = binary.Read(br, binary.LittleEndian, &inode)
if err != nil { if err != nil {
return nil, err return nil, err
} }
info = inode info = inode
case ExtCharDeviceType: case ExtCharDeviceType:
var inode ExtendedDevice var inode ExtDevice
err = binary.Read(br, binary.LittleEndian, &inode) err = binary.Read(br, binary.LittleEndian, &inode)
if err != nil { if err != nil {
return nil, err return nil, err
} }
info = inode info = inode
case ExtFifoType: case ExtFifoType:
var inode ExtendedIPC var inode ExtIPC
err = binary.Read(br, binary.LittleEndian, &inode) err = binary.Read(br, binary.LittleEndian, &inode)
if err != nil { if err != nil {
return nil, err return nil, err
} }
info = inode info = inode
case ExtSocketType: case ExtSocketType:
var inode ExtendedIPC var inode ExtIPC
err = binary.Read(br, binary.LittleEndian, &inode) err = binary.Read(br, binary.LittleEndian, &inode)
if err != nil { if err != nil {
return nil, err return nil, err
+38 -22
View File
@@ -30,6 +30,7 @@ var (
type Reader struct { type Reader struct {
r io.ReaderAt r io.ReaderAt
decompressor compression.Decompressor decompressor compression.Decompressor
root *File
fragOffsets []uint64 fragOffsets []uint64
idTable []uint32 idTable []uint32
super superblock super superblock
@@ -55,7 +56,8 @@ func NewSquashfsReader(r io.ReaderAt) (*Reader, error) {
if rdr.flags.CompressorOptions { if rdr.flags.CompressorOptions {
switch rdr.super.CompressionType { switch rdr.super.CompressionType {
case GzipCompression: case GzipCompression:
gzip, err := compression.NewGzipCompressorWithOptions(io.NewSectionReader(rdr.r, int64(binary.Size(rdr.super)), 8)) var gzip *compression.Gzip
gzip, err = compression.NewGzipCompressorWithOptions(io.NewSectionReader(rdr.r, int64(binary.Size(rdr.super)), 8))
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -64,7 +66,8 @@ func NewSquashfsReader(r io.ReaderAt) (*Reader, error) {
} }
rdr.decompressor = gzip rdr.decompressor = gzip
case XzCompression: case XzCompression:
xz, err := compression.NewXzCompressorWithOptions(io.NewSectionReader(rdr.r, int64(binary.Size(rdr.super)), 8)) var xz *compression.Xz
xz, err = compression.NewXzCompressorWithOptions(io.NewSectionReader(rdr.r, int64(binary.Size(rdr.super)), 8))
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -73,16 +76,15 @@ func NewSquashfsReader(r io.ReaderAt) (*Reader, error) {
} }
rdr.decompressor = xz rdr.decompressor = xz
case Lz4Compression: case Lz4Compression:
lz4, err := compression.NewLz4CompressorWithOptions(io.NewSectionReader(rdr.r, int64(binary.Size(rdr.super)), 8)) var lz4 *compression.Lz4
lz4, err = compression.NewLz4CompressorWithOptions(io.NewSectionReader(rdr.r, int64(binary.Size(rdr.super)), 8))
if err != nil { if err != nil {
return nil, err return nil, err
} }
if lz4.HC {
hasUnsupportedOptions = true
}
rdr.decompressor = lz4 rdr.decompressor = lz4
case ZstdCompression: case ZstdCompression:
zstd, err := compression.NewZstdCompressorWithOptions(io.NewSectionReader(rdr.r, int64(binary.Size(rdr.super)), 4)) var zstd *compression.Zstd
zstd, err = compression.NewZstdCompressorWithOptions(io.NewSectionReader(rdr.r, int64(binary.Size(rdr.super)), 4))
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -156,46 +158,56 @@ func (r *Reader) ModTime() time.Time {
//ExtractTo tries to extract ALL files to the given path. This is the same as getting the root folder and extracting that. //ExtractTo tries to extract ALL files to the given path. This is the same as getting the root folder and extracting that.
func (r *Reader) ExtractTo(path string) []error { func (r *Reader) ExtractTo(path string) []error {
root, err := r.GetRootFolder() if r.root == nil {
_, err := r.GetRootFolder()
if err != nil { if err != nil {
return []error{err} return []error{err}
} }
return root.ExtractTo(path) }
return r.root.ExtractTo(path)
} }
//GetRootFolder returns a squashfs.File that references the root directory of the squashfs archive. //GetRootFolder returns a squashfs.File that references the root directory of the squashfs archive.
func (r *Reader) GetRootFolder() (root *File, err error) { func (r *Reader) GetRootFolder() (*File, error) {
root = new(File) if r.root != nil {
return r.root, nil
}
mr, err := r.newMetadataReaderFromInodeRef(r.super.RootInodeRef) mr, err := r.newMetadataReaderFromInodeRef(r.super.RootInodeRef)
if err != nil { if err != nil {
return nil, err return nil, err
} }
var root File
root.in, err = inode.ProcessInode(mr, r.super.BlockSize) root.in, err = inode.ProcessInode(mr, r.super.BlockSize)
if err != nil { if err != nil {
return nil, err return nil, err
} }
root.path = "/" root.dir = "/"
root.filType = root.in.Type root.filType = root.in.Type
root.r = r root.r = r
return root, nil r.root = &root
return r.root, nil
} }
//GetAllFiles returns a slice of ALL files and folders contained in the squashfs. //GetAllFiles returns a slice of ALL files and folders contained in the squashfs.
func (r *Reader) GetAllFiles() (fils []*File, err error) { func (r *Reader) GetAllFiles() (fils []*File, err error) {
root, err := r.GetRootFolder() if r.root == nil {
_, err := r.GetRootFolder()
if err != nil { if err != nil {
return nil, err return nil, err
} }
return root.GetChildrenRecursively() }
return r.root.GetChildrenRecursively()
} }
//FindFile returns the first file (in the same order as Reader.GetAllFiles) that the given function returns true for. Returns nil if nothing is found. //FindFile returns the first file (in the same order as Reader.GetAllFiles) that the given function returns true for. Returns nil if nothing is found.
func (r *Reader) FindFile(query func(*File) bool) *File { func (r *Reader) FindFile(query func(*File) bool) *File {
root, err := r.GetRootFolder() if r.root == nil {
_, err := r.GetRootFolder()
if err != nil { if err != nil {
return nil return nil
} }
fils, err := root.GetChildren() }
fils, err := r.root.GetChildren()
if err != nil { if err != nil {
return nil return nil
} }
@@ -231,11 +243,13 @@ func (r *Reader) FindFile(query func(*File) bool) *File {
//FindAll returns all files where the given function returns true. //FindAll returns all files where the given function returns true.
func (r *Reader) FindAll(query func(*File) bool) (all []*File) { func (r *Reader) FindAll(query func(*File) bool) (all []*File) {
root, err := r.GetRootFolder() if r.root == nil {
_, err := r.GetRootFolder()
if err != nil { if err != nil {
return nil return nil
} }
fils, err := root.GetChildrenRecursively() }
fils, err := r.root.GetChildrenRecursively()
if err != nil { if err != nil {
return nil return nil
} }
@@ -248,10 +262,12 @@ func (r *Reader) FindAll(query func(*File) bool) (all []*File) {
} }
//GetFileAtPath will return the file at the given path. If the file cannot be found, will return nil. //GetFileAtPath will return the file at the given path. If the file cannot be found, will return nil.
func (r *Reader) GetFileAtPath(path string) *File { func (r *Reader) GetFileAtPath(filepath string) *File {
dir, err := r.GetRootFolder() if r.root == nil {
_, err := r.GetRootFolder()
if err != nil { if err != nil {
return nil return nil
} }
return dir.GetFileAtPath(path) }
return r.root.GetFileAtPath(filepath)
} }
+104 -15
View File
@@ -5,7 +5,10 @@ import (
"io" "io"
"net/http" "net/http"
"os" "os"
"os/exec"
"strconv"
"testing" "testing"
"time"
goappimage "github.com/CalebQ42/GoAppImage" goappimage "github.com/CalebQ42/GoAppImage"
) )
@@ -13,7 +16,7 @@ import (
const ( const (
downloadURL = "https://github.com/srevinsaju/Firefox-Appimage/releases/download/firefox-v84.0.r20201221152838/firefox-84.0.r20201221152838-x86_64.AppImage" downloadURL = "https://github.com/srevinsaju/Firefox-Appimage/releases/download/firefox-v84.0.r20201221152838/firefox-84.0.r20201221152838-x86_64.AppImage"
appImageName = "firefox-84.0.r20201221152838-x86_64.AppImage" appImageName = "firefox-84.0.r20201221152838-x86_64.AppImage"
squashfsName = "balenaEtcher-1.5.113-x64.AppImage.sfs" //testing with a ArchLinux root fs from the live img squashfsName = "balenaEtcher-1.5.113-x64.AppImage.sfs"
) )
func TestSquashfs(t *testing.T) { func TestSquashfs(t *testing.T) {
@@ -53,7 +56,10 @@ func TestAppImage(t *testing.T) {
} }
aiFil, err := os.Open(wd + "/testing/" + appImageName) aiFil, err := os.Open(wd + "/testing/" + appImageName)
if os.IsNotExist(err) { if os.IsNotExist(err) {
downloadTestAppImage(t, wd+"/testing") err = downloadTestAppImage(wd + "/testing")
if err != nil {
t.Fatal(err)
}
aiFil, err = os.Open(wd + "/testing/" + appImageName) aiFil, err = os.Open(wd + "/testing/" + appImageName)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@@ -63,29 +69,108 @@ func TestAppImage(t *testing.T) {
} }
defer aiFil.Close() defer aiFil.Close()
stat, _ := aiFil.Stat() stat, _ := aiFil.Stat()
os.RemoveAll(wd + "/testing/firefox")
ai := goappimage.NewAppImage(wd + "/testing/" + appImageName) ai := goappimage.NewAppImage(wd + "/testing/" + appImageName)
start := time.Now()
rdr, err := NewSquashfsReader(io.NewSectionReader(aiFil, ai.Offset, stat.Size()-ai.Offset)) rdr, err := NewSquashfsReader(io.NewSectionReader(aiFil, ai.Offset, stat.Size()-ai.Offset))
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
os.RemoveAll(wd + "testing/firefox") rt := rdr.GetFileAtPath("/")
errs := rdr.ExtractTo(wd + "/testing/firefox") fils, err := rt.GetChildrenRecursively()
if len(errs) > 0 { if err != nil {
t.Fatal(errs) t.Fatal(err)
} }
// os.RemoveAll(wd + "/testing/" + appImageName + ".d") for _, fil := range fils {
// root, _ := rdr.GetRootFolder() fmt.Println(fil.Path())
// errs := root.ExtractWithOptions(wd+"/testing/"+appImageName+".d", true, os.ModePerm, true) }
// t.Fatal(errs) fmt.Println(time.Since(start))
t.Fatal("No problemo!") t.Fatal("No problemo!")
} }
func downloadTestAppImage(t *testing.T, dir string) { func TestUnsquashfs(t *testing.T) {
t.Parallel()
wd, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
aiFil, err := os.Open(wd + "/testing/" + appImageName)
if os.IsNotExist(err) {
err = downloadTestAppImage(wd + "/testing")
if err != nil {
t.Fatal(err)
}
aiFil, err = os.Open(wd + "/testing/" + appImageName)
if err != nil {
t.Fatal(err)
}
} else if err != nil {
t.Fatal(err)
}
os.RemoveAll(wd + "/testing/unsquashFirefox")
os.RemoveAll(wd + "/testing/firefox")
ai := goappimage.NewAppImage(wd + "/testing/" + appImageName)
fmt.Println("Command:", "unsquashfs", "-d", wd+"/testing/unsquashFirefox", "-o", strconv.Itoa(int(ai.Offset)), aiFil.Name())
cmd := exec.Command("unsquashfs", "-d", wd+"/testing/unsquashFirefox", "-o", strconv.Itoa(int(ai.Offset)), aiFil.Name())
start := time.Now()
err = cmd.Run()
if err != nil {
t.Fatal(err)
}
fmt.Println(time.Since(start))
t.Fatal("HI")
}
func BenchmarkDragRace(b *testing.B) {
wd, err := os.Getwd()
if err != nil {
b.Fatal(err)
}
aiFil, err := os.Open(wd + "/testing/" + appImageName)
if os.IsNotExist(err) {
err = downloadTestAppImage(wd + "/testing")
if err != nil {
b.Fatal(err)
}
aiFil, err = os.Open(wd + "/testing/" + appImageName)
if err != nil {
b.Fatal(err)
}
} else if err != nil {
b.Fatal(err)
}
stat, _ := aiFil.Stat()
ai := goappimage.NewAppImage(wd + "/testing/" + appImageName)
os.RemoveAll(wd + "/testing/unsquashFirefox")
os.RemoveAll(wd + "/testing/firefox")
cmd := exec.Command("unsquashfs", "-d", wd+"/testing/unsquashFirefox", "-o", strconv.Itoa(int(ai.Offset)), aiFil.Name())
start := time.Now()
err = cmd.Run()
if err != nil {
b.Fatal(err)
}
unsquashTime := time.Since(start)
start = time.Now()
rdr, err := NewSquashfsReader(io.NewSectionReader(aiFil, ai.Offset, stat.Size()-ai.Offset))
if err != nil {
b.Fatal(err)
}
errs := rdr.ExtractTo(wd + "/testing/firefox")
if len(errs) > 0 {
b.Fatal(errs)
}
libTime := time.Since(start)
b.Log("Unsqushfs:", unsquashTime.Round(time.Millisecond))
b.Log("Library:", libTime.Round(time.Millisecond))
b.Log("unsquashfs is " + strconv.FormatFloat(float64(libTime.Milliseconds())/float64(unsquashTime.Milliseconds()), 'f', 2, 64) + "x faster")
}
func downloadTestAppImage(dir string) error {
//seems to time out on slow connections. Might fix that at some point... or not. It's just a test... //seems to time out on slow connections. Might fix that at some point... or not. It's just a test...
os.Mkdir(dir, os.ModePerm) os.Mkdir(dir, os.ModePerm)
appImage, err := os.Create(dir + "/" + appImageName) appImage, err := os.Create(dir + "/" + appImageName)
if err != nil { if err != nil {
t.Fatal(err) return err
} }
defer appImage.Close() defer appImage.Close()
check := http.Client{ check := http.Client{
@@ -96,13 +181,14 @@ func downloadTestAppImage(t *testing.T, dir string) {
} }
resp, err := check.Get(downloadURL) resp, err := check.Get(downloadURL)
if err != nil { if err != nil {
t.Fatal(err) return err
} }
defer resp.Body.Close() defer resp.Body.Close()
_, err = io.Copy(appImage, resp.Body) _, err = io.Copy(appImage, resp.Body)
if err != nil { if err != nil {
t.Fatal(err) return err
} }
return nil
} }
func TestCreateSquashFromAppImage(t *testing.T) { func TestCreateSquashFromAppImage(t *testing.T) {
@@ -116,7 +202,10 @@ func TestCreateSquashFromAppImage(t *testing.T) {
} }
_, err = os.Open(wd + "/testing/" + appImageName) _, err = os.Open(wd + "/testing/" + appImageName)
if os.IsNotExist(err) { if os.IsNotExist(err) {
downloadTestAppImage(t, wd+"/testing") err = downloadTestAppImage(wd + "/testing")
if err != nil {
t.Fatal(err)
}
_, err = os.Open(wd + "/testing/" + appImageName) _, err = os.Open(wd + "/testing/" + appImageName)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
+268 -123
View File
@@ -2,180 +2,325 @@ package squashfs
import ( import (
"errors" "errors"
"io"
"log" "log"
"os" "os"
"path" "path"
"sort"
"strings" "strings"
"syscall"
"github.com/CalebQ42/squashfs/internal/inode" "github.com/CalebQ42/squashfs/internal/compression"
) )
//Writer is an interface to write a squashfs. Doesn't write until you call Write (TODO: maybe not do Write...). type fileHolder struct {
//If AllowErrors is true, when errors are encountered, it just prints to the log instead of failing. reader io.Reader
type Writer struct { path string
files map[string][]*File name string
symlinkTable map[string]string //[oldpath]newpath symLocation string
symTableTemp map[string]string UID int
directories []string GUID int
compression int perm int
ResolveSymlinks bool folder bool
AllowErrors bool symlink bool
} }
//NewWriter creates a new squashfs.Writer with the default settings (gzip compression, autoresolving symlinks, and allowErrors) //Writer is used to creaste squashfs archives. Currently unusable
//TODO: Make usable
type Writer struct {
compressor compression.Compressor
structure map[string][]*fileHolder
symlinkTable map[string]string //[oldpath]newpath
uidGUIDTable []int
compressionType int
Flags superblockFlags
allowErrors bool
}
//NewWriter creates a new with the default options (Gzip compression and allow errors)
func NewWriter() (*Writer, error) { func NewWriter() (*Writer, error) {
return NewWriterWithOptions(true, true, GzipCompression) return NewWriterWithOptions(GzipCompression, true)
} }
//NewWriterWithOptions creates a new squashfs.Writer with the given options. //NewWriterWithOptions creates a new squashfs.Writer with the given options.
//ResolveSymlinks tries to make sure symlinks aren't broken. It will either try to make the link's location work //compressionType can be of any types, except LZO (which this library doesn't have support for yet)
func NewWriterWithOptions(resolveSymlinks, allowErrors bool, compressionType int) (*Writer, error) { //allowErrors determines if, when adding folders, it allows errors encountered with it's sub-directories and instead logs the errors.
func NewWriterWithOptions(compressionType int, allowErrors bool) (*Writer, error) {
if compressionType < 0 || compressionType > 6 { if compressionType < 0 || compressionType > 6 {
return nil, errors.New("Incorrect compression type") return nil, errors.New("Incorrect compression type")
} }
if compressionType == 3 { if compressionType == 3 {
return nil, errors.New("Lzo compression is not currently supported") return nil, errors.New("LZO compression is not (currently) supported")
} }
out := Writer{ return &Writer{
files: map[string][]*File{ structure: map[string][]*fileHolder{
"/": make([]*File, 0), "/": make([]*fileHolder, 0),
}, },
ResolveSymlinks: resolveSymlinks, symlinkTable: make(map[string]string),
AllowErrors: allowErrors, compressionType: compressionType,
compression: compressionType, allowErrors: allowErrors,
} }, nil
if resolveSymlinks {
out.symlinkTable = make(map[string]string)
}
return &out, nil
} }
type fileError struct { //AddFile attempts to add an os.File to the archive at it's root.
err error func (w *Writer) AddFile(file *os.File) error {
files []*File return w.AddFileToFolder("/", file)
} }
//convertFile converts the given os.File to a squashfs.File. Returns the errors and converted file to the channels. //AddFileToFolder adds the given file to the squashfs archive, placing it inside the given folder.
func (w *Writer) convertFile(squashfsPath string, file *os.File, subDir bool, fileErrChan chan fileError) { func (w *Writer) AddFileToFolder(folder string, file *os.File) error {
var out fileError name := path.Base(file.Name())
var fil File if !strings.HasSuffix(folder, "/") {
fil.Reader = file folder += "/"
fil.path = squashfsPath }
fil.name = path.Base(file.Name()) return w.AddFileTo(folder+name, file)
mode := fil.Mode() }
if mode.IsRegular() { //AddFileTo adds the given file to the squashfs archive at the given filepath.
fil.filType = inode.BasicFileType func (w *Writer) AddFileTo(filepath string, file *os.File) error {
goto successExit filepath = path.Clean(filepath)
} else if mode.IsDir() { if !strings.HasPrefix(filepath, "/") {
fil.filType = inode.BasicSymlinkType filepath = "/" + filepath
subDirs, err := file.Readdirnames(-1) }
if w.Contains(filepath) {
return errors.New("File already exists at " + filepath)
}
var holder fileHolder
holder.path, holder.name = path.Split(filepath)
holder.reader = file
stat, err := file.Stat()
if err != nil { if err != nil {
if w.AllowErrors && !subDir { return err
log.Println("Can't get sub-directories for", file.Name()) }
holder.folder = stat.IsDir()
holder.symlink = (stat.Mode()&os.ModeSymlink == os.ModeSymlink)
holder.perm = int(stat.Mode().Perm())
//Thanks to https://stackoverflow.com/questions/58179647/getting-uid-and-gid-of-a-file for uid and guid getting
if stat, ok := stat.Sys().(*syscall.Stat_t); ok {
holder.UID = int(stat.Uid)
holder.GUID = int(stat.Gid)
}
if sort.SearchInts(w.uidGUIDTable, holder.UID) == len(w.uidGUIDTable) {
w.uidGUIDTable = append(w.uidGUIDTable, holder.UID)
sort.Ints(w.uidGUIDTable)
}
if sort.SearchInts(w.uidGUIDTable, holder.GUID) == len(w.uidGUIDTable) {
w.uidGUIDTable = append(w.uidGUIDTable, holder.GUID)
sort.Ints(w.uidGUIDTable)
}
if holder.symlink {
target, err := os.Readlink(file.Name())
if err != nil {
return err
}
holder.symLocation = target
} else if holder.folder {
subDirNames, err := file.Readdirnames(-1)
if err != nil {
return err
}
dirsAdded := make([]string, 0)
for _, subDir := range subDirNames {
fil, err := os.Open(file.Name() + subDir)
if err != nil {
return err
}
err = w.AddFileToFolder(holder.path+"/"+holder.name, fil)
if err != nil && !w.allowErrors {
for _, dir := range dirsAdded {
w.Remove(dir)
}
return err
} else if err != nil {
log.Println("Error while adding", fil.Name())
log.Println(err) log.Println(err)
}
if !w.allowErrors {
dirsAdded = append(dirsAdded, holder.path+"/"+holder.name)
}
}
} else if !stat.Mode().IsRegular() {
return errors.New("Unsupported file type " + file.Name())
}
w.structure[holder.path] = append(w.structure[holder.path], &holder)
return nil
}
//AddReaderTo adds the data from the given reader to the archive as a file located at the given filepath.
//Data from the reader is not read until the squashfs archive is writen.
//If the given reader implements io.Closer, it will be closed after it is fully read.
func (w *Writer) AddReaderTo(filepath string, reader io.Reader) error {
filepath = path.Clean(filepath)
if !strings.HasPrefix(filepath, "/") {
filepath = "/" + filepath
}
if w.Contains(filepath) {
return errors.New("File already exists at " + filepath)
}
var holder fileHolder
holder.path, holder.name = path.Split(filepath)
holder.reader = reader
w.structure[holder.path] = append(w.structure[holder.path], &holder)
return nil
}
//Remove tries to remove the file(s) at the given filepath. If wildcards are used, it will remove all files that match.
//Returns true if one or more files are removed.
func (w *Writer) Remove(filepath string) bool {
var matchFound bool
filepath = path.Clean(filepath)
if !strings.HasPrefix(filepath, "/") {
filepath = "/" + filepath
}
dir, name := path.Split(filepath)
for structDir, files := range w.structure {
if match, _ := path.Match(dir, structDir); match {
for i, fil := range files {
if match, _ = path.Match(name, fil.name); match {
matchFound = true
if len(w.structure[structDir]) > 1 {
w.structure[structDir][i] = w.structure[structDir][len(w.structure[structDir])-1]
w.structure[structDir] = w.structure[structDir][:len(w.structure[structDir])-1]
} else { } else {
out.err = err w.structure[structDir] = nil
} }
goto failExit
} }
subDirChan := make(chan fileError)
for _, filName := range subDirs {
go func(filename string, returnChan chan fileError) {
subFil, err := os.Open(filename)
if err != nil {
out.err = err
returnChan <- fileError{
err: err,
} }
return
} }
w.convertFile(fil.Path(), subFil, true, subDirChan)
}(file.Name()+filName, subDirChan)
} }
for range subDirs { return matchFound
filErr := <-subDirChan
if filErr.err != nil {
if w.AllowErrors && !subDir {
log.Println("Error while adding subdirectory of", file.Name())
log.Println(filErr.err)
} else if subDir {
if out.err == nil {
out.err = filErr.err
}
} else {
out.err = err
goto failExit
} }
//FixSymlinks will scan through the squashfs archive and try to find broken symlinks and fix them.
//This done by replacing the symlink with the target file and then pointing other symlinks to that file.
//If all symlinks can be resolved, the error slice will be nil, and the bool false, otherwise all errors occured will be in the slice.
func (w *Writer) FixSymlinks() (errs []error, problems bool) {
for dir, holderSlice := range w.structure {
for i, holder := range holderSlice {
if !holder.symlink {
continue continue
} }
out.files = append(out.files, filErr.files...) sym := holder.symLocation
if !path.IsAbs(holder.symLocation) {
sym = path.Join(dir, holder.symLocation)
}
if path, ok := w.symlinkTable[sym]; ok {
w.structure[dir][i].symLocation = path
continue
}
if path.IsAbs(sym) || strings.HasPrefix(sym, "../") {
var symFil *os.File
var err error
if strings.HasPrefix(sym, "../") {
holderFil, ok := holder.reader.(*os.File)
if !ok {
problems = true
errs = append(errs, errors.New("Cannot resolve symlink at "+dir+holder.name))
continue
}
symFilPath := path.Dir(holderFil.Name())
symFilPath = path.Join(symFilPath, holder.symLocation)
symFil, err = os.Open(symFilPath)
} else {
symFil, err = os.Open(sym)
} }
goto successExit
} else if mode&os.ModeSymlink == os.ModeSymlink {
fil.filType = inode.BasicSymlinkType
symLocation, err := os.Readlink(file.Name())
if err != nil { if err != nil {
if w.AllowErrors && !subDir { problems = true
log.Println("Error while getting symlink's information for", file.Name()) errs = append(errs, err)
log.Println(err) continue
}
suc := w.Remove(dir + holder.name)
if !suc {
problems = true
errs = append(errs, errors.New("Cannot resolve symlink at "+dir+holder.name))
continue
}
err = w.AddFileTo(dir+holder.name, symFil)
if err != nil {
w.structure[dir] = append(w.structure[dir], holder)
problems = true
errs = append(errs, err)
continue
}
w.symlinkTable[sym] = dir + holder.name
} else { } else {
out.err = err symHolder := w.holderAt(sym)
if symHolder != nil {
w.symlinkTable[sym] = sym
continue
} }
goto failExit holderFil, ok := holder.reader.(*os.File)
if !ok {
problems = true
errs = append(errs, errors.New("Cannot resolve symlink at "+dir+holder.name))
continue
} }
if w.ResolveSymlinks { symFilPath := path.Dir(holderFil.Name())
if val, ok := w.symlinkTable[symLocation]; ok { symFilPath = path.Join(symFilPath, holder.symLocation)
symLocation = val symFil, err := os.Open(symFilPath)
} else if val, ok := w.symTableTemp[symLocation]; ok { if err != nil {
symLocation = val problems = true
} else { errs = append(errs, err)
//TODO: either add the file, or place the file in this location. Maybe defer this until after all the other files are added? continue
}
err = w.AddFileTo(sym, symFil)
if err != nil {
problems = true
errs = append(errs, err)
continue
}
w.symlinkTable[sym] = sym
} }
} }
//TODO: store the symLocation inside the File somehow....
} }
if w.AllowErrors && !subDir {
log.Println("Unsupported file type for", file.Name())
} else {
out.err = errors.New("Unsupported file type")
}
failExit: //before this is used, make sure to log or set the error.
fileErrChan <- out
return
successExit:
out.files = []*File{&fil}
fileErrChan <- out
return return
} }
//AddFilesToPath adds the give os.Files to the given path within the squashfs archive. func (w *Writer) holderAt(filepath string) *fileHolder {
//If AllowErrors is true, this will ALWAYS return nil filepath = path.Clean(filepath)
func (w *Writer) AddFilesToPath(squashfsPath string, files ...*os.File) error { if !strings.HasPrefix(filepath, "/") {
squashfsPath = path.Clean(squashfsPath) filepath = "/" + filepath
if strings.HasPrefix(squashfsPath, "/") {
squashfsPath = strings.TrimPrefix(squashfsPath, "/")
} }
if squashfsPath == "." { dir, name := path.Split(filepath)
squashfsPath = "/" if holderSlice, ok := w.structure[dir]; ok {
for _, holder := range holderSlice {
if holder.name == name {
return holder
} }
fileErrChan := make(chan fileError)
for _, fil := range files {
go w.convertFile(squashfsPath, fil, false, fileErrChan)
} }
return errors.New("Not yet ready") }
return nil
} }
//AddFiles adds all files given to the root directory //Contains returns whether a file is present at the given filepath
//If AllowErrors is true, this will ALWAYS return nil func (w *Writer) Contains(filepath string) bool {
func (w *Writer) AddFiles(files ...*os.File) error { filepath = path.Clean(filepath)
return w.AddFilesToPath("/", files...) if !strings.HasPrefix(filepath, "/") {
filepath = "/" + filepath
}
dir, name := path.Split(filepath)
if holderSlice, ok := w.structure[dir]; ok {
for _, holder := range holderSlice {
if holder.name == name {
return true
}
}
} }
//RemoveFileAt removes the file at filepath from the Writer.
//If multiple files match the given filepath (such as if there are wildcards), all matching files are removed.
//If one or more files are removed, returns true.
func (w *Writer) RemoveFileAt(filepath string) bool {
//TODO
return false return false
} }
//WriteToFilename creates the squashfs archive with the given filepath.
func (w *Writer) WriteToFilename(filepath string) error {
newFil, err := os.Create(filepath)
if err != nil {
return err
}
_, err = w.WriteTo(newFil)
return err
}
//WriteTo attempts to write the archive to the given io.Writer.
func (w *Writer) WriteTo(write io.Writer) (int64, error) {
//TODO
return 0, errors.New("I SAID DON'T")
}
+15
View File
@@ -0,0 +1,15 @@
package squashfs
//TODO: Allow settings the options
// func (w *Writer) SetGzipOptions() error {}
// func (w *Writer) SetLzmaOptions() error {}
// func (w *Writer) SetLzoOptions() error {}
// func (w *Writer) SetXzOptions() error {}
// func (w *Writer) SetLz4Options() error {}
// func (w *Writer) SetZstdOptions() error {}