| 1 |
package main |
| 2 |
|
| 3 |
import ( |
| 4 |
"archive/tar" |
| 5 |
"debug/elf" |
| 6 |
"debug/macho" |
| 7 |
"debug/pe" |
| 8 |
"errors" |
| 9 |
"flag" |
| 10 |
"fmt" |
| 11 |
"io" |
| 12 |
"os" |
| 13 |
"path" |
| 14 |
"path/filepath" |
| 15 |
"strings" |
| 16 |
|
| 17 |
"github.com/klauspost/compress/s2" |
| 18 |
) |
| 19 |
|
| 20 |
const ( |
| 21 |
opUnpack = iota + 1 |
| 22 |
opUnTar |
| 23 |
) |
| 24 |
|
| 25 |
var ( |
| 26 |
help = flag.Bool("help", false, "Display help") |
| 27 |
untarFlag = flag.Bool("untar", true, "Untar tar files if specified at creation") |
| 28 |
forceUntar = flag.Bool("force-untar", false, "Always untar file") |
| 29 |
quiet = flag.Bool("q", false, "Don't write any output to terminal, except errors") |
| 30 |
) |
| 31 |
|
| 32 |
func main() { |
| 33 |
flag.Parse() |
| 34 |
me, err := os.Executable() |
| 35 |
exitErr(err) |
| 36 |
args := flag.Args() |
| 37 |
invalidArgs := len(args) > 1 |
| 38 |
if *help || invalidArgs { |
| 39 |
_, _ = fmt.Fprintf(os.Stderr, "s2sx Self Extracting Archive\n\n") |
| 40 |
_, _ = fmt.Fprintf(os.Stderr, "Usage: %s [options] [output-file/dir]\n\n", os.Args[0]) |
| 41 |
_, _ = fmt.Fprintf(os.Stderr, "Use - as file name to extract to stdout when not untarring.\n\n") |
| 42 |
_, _ = fmt.Fprintln(os.Stderr, `Options:`) |
| 43 |
flag.PrintDefaults() |
| 44 |
if invalidArgs { |
| 45 |
os.Exit(1) |
| 46 |
} |
| 47 |
os.Exit(0) |
| 48 |
} |
| 49 |
stdout := len(args) > 0 && args[0] == "-" |
| 50 |
*quiet = *quiet || stdout |
| 51 |
|
| 52 |
f, err := os.Open(me) |
| 53 |
exitErr(err) |
| 54 |
defer f.Close() |
| 55 |
stat, err := f.Stat() |
| 56 |
exitErr(err) |
| 57 |
rd, err := newReader(f, stat.Size()) |
| 58 |
exitErr(err) |
| 59 |
f2, err := os.Open(me + ".more") |
| 60 |
if err == nil { |
| 61 |
rd = io.MultiReader(rd, f2) |
| 62 |
} |
| 63 |
if !os.IsNotExist(err) { |
| 64 |
exitErr(err) |
| 65 |
} |
| 66 |
var tmp [1]byte |
| 67 |
_, err = io.ReadFull(rd, tmp[:]) |
| 68 |
exitErr(err) |
| 69 |
dec := s2.NewReader(rd) |
| 70 |
if !*untarFlag { |
| 71 |
tmp[0] = opUnpack |
| 72 |
} |
| 73 |
if *forceUntar { |
| 74 |
tmp[0] = opUnTar |
| 75 |
} |
| 76 |
switch tmp[0] { |
| 77 |
case opUnpack: |
| 78 |
outname := me + "-extracted" |
| 79 |
if idx := strings.Index(me, ".s2sx"); idx > 0 { |
| 80 |
// Trim from '.s2sx' |
| 81 |
outname = me[:idx] |
| 82 |
} |
| 83 |
var out io.Writer |
| 84 |
if stdout { |
| 85 |
out = os.Stdout |
| 86 |
} else { |
| 87 |
if len(args) > 0 { |
| 88 |
outname, err = filepath.Abs(args[0]) |
| 89 |
exitErr(err) |
| 90 |
} |
| 91 |
if !*quiet { |
| 92 |
fmt.Printf("Extracting to \"%s\"...", outname) |
| 93 |
} |
| 94 |
f, err := os.Create(outname) |
| 95 |
exitErr(err) |
| 96 |
defer f.Close() |
| 97 |
out = f |
| 98 |
} |
| 99 |
_, err = dec.DecodeConcurrent(out, 0) |
| 100 |
exitErr(err) |
| 101 |
|
| 102 |
case opUnTar: |
| 103 |
dir, err := os.Getwd() |
| 104 |
if err != nil { |
| 105 |
dir = filepath.Dir(me) |
| 106 |
} |
| 107 |
if len(args) > 0 { |
| 108 |
if args[0] == "-" { |
| 109 |
exitErr(errors.New("cannot untar files to stdout. Use -untar=false to skip untar operation")) |
| 110 |
} |
| 111 |
if filepath.IsAbs(args[0]) { |
| 112 |
dir = args[0] |
| 113 |
} else { |
| 114 |
dir = filepath.Join(dir, args[0]) |
| 115 |
} |
| 116 |
} |
| 117 |
if !*quiet { |
| 118 |
fmt.Printf("Extracting TAR file to %s...\n", dir) |
| 119 |
} |
| 120 |
exitErr(untar(dir, dec)) |
| 121 |
default: |
| 122 |
exitErr(fmt.Errorf("unknown operation: %d", tmp[0])) |
| 123 |
} |
| 124 |
if !*quiet { |
| 125 |
fmt.Println("\nDone.") |
| 126 |
} |
| 127 |
} |
| 128 |
|
| 129 |
func exitErr(err error) { |
| 130 |
if err != nil { |
| 131 |
fmt.Fprintln(os.Stderr, "\nERROR:", err.Error()) |
| 132 |
os.Exit(2) |
| 133 |
} |
| 134 |
} |
| 135 |
|
| 136 |
func newReader(rda io.ReaderAt, size int64) (io.Reader, error) { |
| 137 |
handlers := []func(io.ReaderAt, int64) (io.Reader, error){ |
| 138 |
exeReaderMacho, |
| 139 |
exeReaderElf, |
| 140 |
exeReaderPe, |
| 141 |
} |
| 142 |
|
| 143 |
for _, handler := range handlers { |
| 144 |
zfile, err := handler(rda, size) |
| 145 |
if err == nil { |
| 146 |
return zfile, nil |
| 147 |
} |
| 148 |
} |
| 149 |
return nil, errors.New("no archive data found") |
| 150 |
} |
| 151 |
|
| 152 |
// zipExeReaderPe treats the file as a Portable Executable binary |
| 153 |
func exeReaderPe(rda io.ReaderAt, size int64) (io.Reader, error) { |
| 154 |
file, err := pe.NewFile(rda) |
| 155 |
if err != nil { |
| 156 |
return nil, err |
| 157 |
} |
| 158 |
|
| 159 |
var max int64 |
| 160 |
for _, sec := range file.Sections { |
| 161 |
end := int64(sec.Offset + sec.Size) |
| 162 |
if end > max { |
| 163 |
max = end |
| 164 |
} |
| 165 |
} |
| 166 |
|
| 167 |
if size == max { |
| 168 |
return nil, errors.New("data not found") |
| 169 |
} |
| 170 |
return io.NewSectionReader(rda, max, size-max), nil |
| 171 |
} |
| 172 |
|
| 173 |
// zipExeReaderElf treats the file as a ELF binary |
| 174 |
func exeReaderElf(rda io.ReaderAt, size int64) (io.Reader, error) { |
| 175 |
file, err := elf.NewFile(rda) |
| 176 |
if err != nil { |
| 177 |
return nil, err |
| 178 |
} |
| 179 |
|
| 180 |
var max int64 |
| 181 |
for _, sect := range file.Sections { |
| 182 |
if sect.Type == elf.SHT_NOBITS { |
| 183 |
continue |
| 184 |
} |
| 185 |
|
| 186 |
// Move to end of file pointer |
| 187 |
end := int64(sect.Offset + sect.Size) |
| 188 |
if end > max { |
| 189 |
max = end |
| 190 |
} |
| 191 |
} |
| 192 |
|
| 193 |
if size == max { |
| 194 |
return nil, errors.New("data not found") |
| 195 |
} |
| 196 |
return io.NewSectionReader(rda, max, size-max), nil |
| 197 |
} |
| 198 |
|
| 199 |
// zipExeReaderMacho treats the file as a Mach-O binary |
| 200 |
func exeReaderMacho(rda io.ReaderAt, size int64) (io.Reader, error) { |
| 201 |
file, err := macho.NewFile(rda) |
| 202 |
if err != nil { |
| 203 |
return nil, err |
| 204 |
} |
| 205 |
|
| 206 |
var max int64 |
| 207 |
for _, load := range file.Loads { |
| 208 |
seg, ok := load.(*macho.Segment) |
| 209 |
if ok { |
| 210 |
// Move to end of file pointer |
| 211 |
end := int64(seg.Offset + seg.Filesz) |
| 212 |
if end > max { |
| 213 |
max = end |
| 214 |
} |
| 215 |
} |
| 216 |
} |
| 217 |
|
| 218 |
// No zip file within binary, try appended to end |
| 219 |
if size == max { |
| 220 |
return nil, errors.New("data not found") |
| 221 |
} |
| 222 |
return io.NewSectionReader(rda, max, size-max), nil |
| 223 |
} |
| 224 |
|
| 225 |
// untar takes a destination path and a reader; a tar reader loops over the tarfile |
| 226 |
// creating the file structure at 'dst' along the way, and writing any files |
| 227 |
func untar(dst string, r io.Reader) error { |
| 228 |
tr := tar.NewReader(r) |
| 229 |
|
| 230 |
for { |
| 231 |
header, err := tr.Next() |
| 232 |
|
| 233 |
switch { |
| 234 |
|
| 235 |
// if no more files are found return |
| 236 |
case err == io.EOF: |
| 237 |
return nil |
| 238 |
|
| 239 |
// return any other error |
| 240 |
case err != nil: |
| 241 |
return err |
| 242 |
|
| 243 |
// if the header is nil, just skip it (not sure how this happens) |
| 244 |
case header == nil: |
| 245 |
continue |
| 246 |
} |
| 247 |
|
| 248 |
// the target location where the dir/file should be created |
| 249 |
if err := checkPath(dst, header.Name); err != nil { |
| 250 |
return err |
| 251 |
} |
| 252 |
target := filepath.Join(dst, header.Name) |
| 253 |
|
| 254 |
// check the file type |
| 255 |
switch header.Typeflag { |
| 256 |
|
| 257 |
// if its a dir and it doesn't exist create it |
| 258 |
case tar.TypeDir: |
| 259 |
if !*quiet { |
| 260 |
fmt.Println(target) |
| 261 |
} |
| 262 |
if _, err := os.Stat(target); err != nil { |
| 263 |
if err := os.MkdirAll(target, 0755); err != nil { |
| 264 |
return err |
| 265 |
} |
| 266 |
} |
| 267 |
|
| 268 |
// if it's a file create it |
| 269 |
case tar.TypeReg, tar.TypeChar, tar.TypeBlock, tar.TypeFifo, tar.TypeGNUSparse: |
| 270 |
target = path.Clean(target) |
| 271 |
if !*quiet { |
| 272 |
fmt.Println(target) |
| 273 |
} |
| 274 |
|
| 275 |
f, err := os.OpenFile(target, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.FileMode(header.Mode)) |
| 276 |
if err != nil { |
| 277 |
if os.IsNotExist(err) { |
| 278 |
if err := os.MkdirAll(filepath.Dir(target), 0755); err != nil { |
| 279 |
return err |
| 280 |
} |
| 281 |
f, err = os.OpenFile(target, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.FileMode(header.Mode)) |
| 282 |
} |
| 283 |
if err != nil { |
| 284 |
return err |
| 285 |
} |
| 286 |
} |
| 287 |
|
| 288 |
// copy over contents |
| 289 |
if _, err := io.Copy(f, tr); err != nil { |
| 290 |
return err |
| 291 |
} |
| 292 |
|
| 293 |
f.Close() |
| 294 |
case tar.TypeSymlink: |
| 295 |
target = path.Clean(target) |
| 296 |
// A symlink target is resolved relative to the link's own |
| 297 |
// directory (or used as-is when absolute); reject any that |
| 298 |
// escape dst so the link cannot point outside the archive root. |
| 299 |
linkTarget := header.Linkname |
| 300 |
if !filepath.IsAbs(linkTarget) { |
| 301 |
linkTarget = filepath.Join(filepath.Dir(target), linkTarget) |
| 302 |
} |
| 303 |
if !within(dst, linkTarget) { |
| 304 |
return fmt.Errorf("illegal link target: %s", header.Linkname) |
| 305 |
} |
| 306 |
if !*quiet { |
| 307 |
fmt.Println(target) |
| 308 |
} |
| 309 |
|
| 310 |
err := writeNewSymbolicLink(target, header.Linkname) |
| 311 |
if err != nil { |
| 312 |
return err |
| 313 |
} |
| 314 |
case tar.TypeLink: |
| 315 |
target = path.Clean(target) |
| 316 |
// Hardlink targets are relative to the archive root. |
| 317 |
if err := checkPath(dst, header.Linkname); err != nil { |
| 318 |
return err |
| 319 |
} |
| 320 |
if !*quiet { |
| 321 |
fmt.Println(target) |
| 322 |
} |
| 323 |
|
| 324 |
err := writeNewHardLink(target, filepath.Join(dst, header.Linkname)) |
| 325 |
if err != nil { |
| 326 |
return err |
| 327 |
} |
| 328 |
} |
| 329 |
} |
| 330 |
} |
| 331 |
|
| 332 |
// Thanks to https://github.com/mholt/archiver for the following: |
| 333 |
|
| 334 |
func checkPath(dst, filename string) error { |
| 335 |
//prevent path traversal attacks |
| 336 |
if !within(dst, filepath.Join(dst, filename)) { |
| 337 |
return fmt.Errorf("illegal file path: %s", filename) |
| 338 |
} |
| 339 |
return nil |
| 340 |
} |
| 341 |
|
| 342 |
// within reports whether target stays inside dst. A raw strings.HasPrefix |
| 343 |
// check is not separator-aware: dst "out" would wrongly accept the sibling |
| 344 |
// "out_evil". filepath.Rel collapses the path and a ".." result means escape. |
| 345 |
func within(dst, target string) bool { |
| 346 |
rel, err := filepath.Rel(dst, target) |
| 347 |
if err != nil { |
| 348 |
return false |
| 349 |
} |
| 350 |
return rel != ".." && !strings.HasPrefix(rel, ".."+string(os.PathSeparator)) |
| 351 |
} |
| 352 |
|
| 353 |
func writeNewSymbolicLink(fpath string, target string) error { |
| 354 |
err := os.MkdirAll(filepath.Dir(fpath), 0755) |
| 355 |
if err != nil { |
| 356 |
return fmt.Errorf("%s: making directory for file: %v", fpath, err) |
| 357 |
} |
| 358 |
|
| 359 |
_, err = os.Lstat(fpath) |
| 360 |
if err == nil { |
| 361 |
err = os.Remove(fpath) |
| 362 |
if err != nil { |
| 363 |
return fmt.Errorf("%s: failed to unlink: %+v", fpath, err) |
| 364 |
} |
| 365 |
} |
| 366 |
|
| 367 |
err = os.Symlink(target, fpath) |
| 368 |
if err != nil { |
| 369 |
return fmt.Errorf("%s: making symbolic link for: %v", fpath, err) |
| 370 |
} |
| 371 |
return nil |
| 372 |
} |
| 373 |
|
| 374 |
func writeNewHardLink(fpath string, target string) error { |
| 375 |
err := os.MkdirAll(filepath.Dir(fpath), 0755) |
| 376 |
if err != nil { |
| 377 |
return fmt.Errorf("%s: making directory for file: %v", fpath, err) |
| 378 |
} |
| 379 |
|
| 380 |
_, err = os.Lstat(fpath) |
| 381 |
if err == nil { |
| 382 |
err = os.Remove(fpath) |
| 383 |
if err != nil { |
| 384 |
return fmt.Errorf("%s: failed to unlink: %+v", fpath, err) |
| 385 |
} |
| 386 |
} |
| 387 |
|
| 388 |
err = os.Link(target, fpath) |
| 389 |
if err != nil { |
| 390 |
return fmt.Errorf("%s: making hard link for: %v", fpath, err) |
| 391 |
} |
| 392 |
return nil |
| 393 |
} |