| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579 |
- package playground
- import (
- "archive/tar"
- "archive/zip"
- "bytes"
- "compress/gzip"
- "encoding/json"
- "errors"
- "io"
- "path"
- "strings"
- "time"
- "github.com/robertkrimen/otto"
- )
- // The playground's ziplib handles zip, tar, tar.gz and gz on the drive; 7z
- // needs the server.
- type archived struct {
- name string // slash path inside the archive, folders end with "/"
- data []byte
- }
- // collect gathers files and folders for an archive: a folder is added with
- // its contents under its own name, as ArozOS does.
- func (r *run) collect(sources []string) ([]archived, error) {
- var out []archived
- for _, src := range sources {
- list, err := r.fs.Walk(src)
- if err != nil {
- return nil, fsErr("stat", src, err)
- }
- base := path.Dir(Clean(src))
- for _, e := range list {
- rel := strings.TrimPrefix(strings.TrimPrefix(e.Vpath, base), "/")
- if i := strings.Index(rel, ":/"); i >= 0 {
- rel = rel[i+2:]
- }
- if e.Dir {
- if rel != "" {
- out = append(out, archived{name: rel + "/"})
- }
- continue
- }
- b, _ := r.fs.ReadFile(e.Vpath)
- out = append(out, archived{name: rel, data: b})
- }
- }
- return out, nil
- }
- func buildZip(items []archived) []byte {
- var buf bytes.Buffer
- zw := zip.NewWriter(&buf)
- for _, it := range items {
- h := &zip.FileHeader{Name: it.name, Method: zip.Deflate, Modified: time.Now()}
- if strings.HasSuffix(it.name, "/") {
- h.Method = zip.Store
- }
- w, _ := zw.CreateHeader(h)
- w.Write(it.data)
- }
- zw.Close()
- return buf.Bytes()
- }
- func buildTar(items []archived) []byte {
- var buf bytes.Buffer
- tw := tar.NewWriter(&buf)
- for _, it := range items {
- h := &tar.Header{Name: it.name, Mode: 0o644, Size: int64(len(it.data)), ModTime: time.Now(), Typeflag: tar.TypeReg}
- if strings.HasSuffix(it.name, "/") {
- h.Typeflag, h.Mode, h.Size = tar.TypeDir, 0o755, 0
- }
- tw.WriteHeader(h)
- tw.Write(it.data)
- }
- tw.Close()
- return buf.Bytes()
- }
- func gz(b []byte) []byte {
- var buf bytes.Buffer
- w := gzip.NewWriter(&buf)
- w.Write(b)
- w.Close()
- return buf.Bytes()
- }
- func gunzip(b []byte) ([]byte, error) {
- zr, err := gzip.NewReader(bytes.NewReader(b))
- if err != nil {
- return nil, err
- }
- return io.ReadAll(io.LimitReader(zr, 256<<20))
- }
- // archiveType sniffs an archive: "zip", "tar", "tar.gz", "gz", "7z" or "".
- func archiveType(name string, b []byte) string {
- switch {
- case bytes.HasPrefix(b, []byte("PK\x03\x04")) || bytes.HasPrefix(b, []byte("PK\x05\x06")):
- return "zip"
- case bytes.HasPrefix(b, []byte("7z\xbc\xaf\x27\x1c")):
- return "7z"
- case bytes.HasPrefix(b, []byte{0x1f, 0x8b}):
- if inner, err := gunzip(b); err == nil && len(inner) > 262 && string(inner[257:262]) == "ustar" {
- return "tar.gz"
- }
- return "gz"
- case len(b) > 262 && string(b[257:262]) == "ustar":
- return "tar"
- }
- return ""
- }
- // readArchive lists the entries of a zip or (gzipped) tar.
- func readArchive(kind string, b []byte) ([]archived, error) {
- var out []archived
- switch kind {
- case "zip":
- zr, err := zip.NewReader(bytes.NewReader(b), int64(len(b)))
- if err != nil {
- return nil, err
- }
- for _, f := range zr.File {
- if f.FileInfo().IsDir() {
- out = append(out, archived{name: strings.TrimSuffix(f.Name, "/") + "/"})
- continue
- }
- rc, err := f.Open()
- if err != nil {
- return nil, err
- }
- data, err := io.ReadAll(io.LimitReader(rc, 256<<20))
- rc.Close()
- if err != nil {
- return nil, err
- }
- out = append(out, archived{name: f.Name, data: data})
- }
- case "tar.gz", "tar":
- if kind == "tar.gz" {
- var err error
- if b, err = gunzip(b); err != nil {
- return nil, err
- }
- }
- tr := tar.NewReader(bytes.NewReader(b))
- for {
- h, err := tr.Next()
- if err == io.EOF {
- break
- }
- if err != nil {
- return nil, err
- }
- if h.Typeflag == tar.TypeDir {
- out = append(out, archived{name: strings.TrimSuffix(h.Name, "/") + "/"})
- continue
- }
- data, _ := io.ReadAll(io.LimitReader(tr, 256<<20))
- out = append(out, archived{name: h.Name, data: data})
- }
- default:
- return nil, errors.New("unsupported archive type")
- }
- return out, nil
- }
- // extract writes entries below dest, refusing names that climb out of it.
- func (r *run) extract(items []archived, dest string, only []string) error {
- dest = Clean(dest)
- if err := r.fs.MkdirAll(dest); err != nil {
- return err
- }
- for _, it := range items {
- name := strings.TrimPrefix(path.Clean("/"+it.name), "/")
- if strings.HasPrefix(path.Clean(it.name), "..") {
- return errors.New("illegal file path in archive: " + it.name)
- }
- if only != nil && !wanted(name, only) {
- continue
- }
- target := Clean(dest + "/" + name)
- if strings.HasSuffix(it.name, "/") {
- r.fs.MkdirAll(target)
- continue
- }
- r.fs.MkdirAll(path.Dir(target))
- if err := r.fs.WriteFile(target, it.data); err != nil {
- return err
- }
- }
- return nil
- }
- func wanted(name string, only []string) bool {
- for _, o := range only {
- o = strings.Trim(o, "/")
- if name == o || strings.HasPrefix(name, o+"/") {
- return true
- }
- }
- return false
- }
- func (r *run) injectZiplib(vm *otto.Otto) {
- readable := func(call otto.FunctionCall, i int) string {
- p, _ := argString(call, i)
- if !r.canRead(p) {
- r.denied(vm, p)
- }
- return p
- }
- writable := func(call otto.FunctionCall, i int) string {
- p, _ := argString(call, i)
- if !r.canWrite(p) {
- r.denied(vm, p)
- }
- return p
- }
- sources := func(call otto.FunctionCall) []string {
- a := call.Argument(0)
- var list []string
- if a.IsObject() {
- exp, _ := a.Export()
- if arr, ok := exp.([]interface{}); ok {
- for _, v := range arr {
- if s, ok := v.(string); ok {
- list = append(list, s)
- }
- }
- } else if arr, ok := exp.([]string); ok {
- list = arr
- }
- } else {
- s, _ := a.ToString()
- list = []string{s}
- }
- for _, s := range list {
- if !r.canRead(s) {
- r.denied(vm, s)
- }
- }
- return list
- }
- create := func(kind string) func(otto.FunctionCall) otto.Value {
- return func(call otto.FunctionCall) otto.Value {
- src := sources(call)
- out := writable(call, 1)
- items, err := r.collect(src)
- if err != nil {
- return r.raise(vm, "ZipLibError", err)
- }
- var b []byte
- switch kind {
- case "zip":
- b = buildZip(items)
- case "tar":
- b = buildTar(items)
- case "tar.gz":
- b = gz(buildTar(items))
- case "gz":
- if len(items) != 1 || strings.HasSuffix(items[0].name, "/") {
- return r.raise(vm, "ZipLibError", errors.New("gz compresses a single file"))
- }
- b = gz(items[0].data)
- }
- if err := r.fs.WriteFile(out, b); err != nil {
- return r.raise(vm, "ZipLibError", fsErr("open", out, err))
- }
- return otto.TrueValue()
- }
- }
- open := func(p string) (string, []byte, error) {
- b, err := r.fs.ReadFile(p)
- if err != nil {
- return "", nil, fsErr("open", p, err)
- }
- return archiveType(p, b), b, nil
- }
- extract := func(want string) func(otto.FunctionCall) otto.Value {
- return func(call otto.FunctionCall) otto.Value {
- src, dest := readable(call, 0), writable(call, 1)
- kind, b, err := open(src)
- if err != nil {
- return r.raise(vm, "ZipLibError", err)
- }
- if want != "" && kind != want {
- return r.raise(vm, "ZipLibError", errors.New(src+" is not a "+want+" file"))
- }
- if kind == "7z" {
- return r.raise(vm, "ZipLibError", errors.New("7z archives need the server; the playground handles zip, tar, tar.gz and gz"))
- }
- if kind == "gz" {
- data, err := gunzip(b)
- if err != nil {
- return r.raise(vm, "ZipLibError", err)
- }
- r.fs.MkdirAll(dest)
- name := strings.TrimSuffix(path.Base(Clean(src)), ".gz")
- if err := r.fs.WriteFile(Clean(dest+"/"+name), data); err != nil {
- return r.raise(vm, "ZipLibError", err)
- }
- return otto.TrueValue()
- }
- items, err := readArchive(kind, b)
- if err == nil {
- err = r.extract(items, dest, nil)
- }
- if err != nil {
- return r.raise(vm, "ZipLibError", err)
- }
- return otto.TrueValue()
- }
- }
- vm.Set("_ziplib_createZipFile", create("zip"))
- vm.Set("_ziplib_createTarFile", create("tar"))
- vm.Set("_ziplib_createTarGzFile", create("tar.gz"))
- vm.Set("_ziplib_createGzFile", create("gz"))
- vm.Set("_ziplib_extractZipFile", extract("zip"))
- vm.Set("_ziplib_extractTarFile", extract("tar"))
- vm.Set("_ziplib_extractTarGzFile", extract("tar.gz"))
- vm.Set("_ziplib_extractGzFile", extract("gz"))
- vm.Set("_ziplib_extractAnyFile", extract(""))
- vm.Set("_ziplib_createAnyZipFile", func(call otto.FunctionCall) otto.Value {
- format, ok := argString(call, 2)
- if !ok || format == "" {
- out, _ := argString(call, 1)
- switch {
- case strings.HasSuffix(out, ".tar.gz") || strings.HasSuffix(out, ".tgz"):
- format = "tar.gz"
- case strings.HasSuffix(out, ".tar"):
- format = "tar"
- case strings.HasSuffix(out, ".gz"):
- format = "gz"
- default:
- format = "zip"
- }
- }
- format = strings.TrimPrefix(strings.ToLower(format), ".")
- if format == "tgz" {
- format = "tar.gz"
- }
- if format != "zip" && format != "tar" && format != "tar.gz" && format != "gz" {
- return r.raise(vm, "ZipLibError", errors.New("unsupported format "+format))
- }
- return create(format)(call)
- })
- vm.Set("_ziplib_isValidZipFile", func(call otto.FunctionCall) otto.Value {
- kind, _, err := open(readable(call, 0))
- return boolValue(err == nil && kind != "" && kind != "7z")
- })
- vm.Set("_ziplib_getCompressFileType", func(call otto.FunctionCall) otto.Value {
- //"unknown" for a file that is no archive, as on ArozOS
- kind, _, err := open(readable(call, 0))
- if err != nil || kind == "" {
- kind = "unknown"
- }
- out, _ := vm.ToValue(kind)
- return out
- })
- //listing reads a zip file's entries and throws when it cannot
- listing := func(call otto.FunctionCall) []archived {
- kind, b, err := open(readable(call, 0))
- if err == nil && kind != "zip" {
- err = errors.New("not a zip file")
- }
- var items []archived
- if err == nil {
- items, err = readArchive(kind, b)
- }
- if err != nil {
- r.raise(vm, "ZipLibError", err)
- }
- return items
- }
- vm.Set("_ziplib_listZipFileContents", func(call otto.FunctionCall) otto.Value {
- items := listing(call)
- type tnode struct {
- Name string `json:"name"`
- IsDir bool `json:"isDir"`
- Size int64 `json:"size"`
- Children map[string]*tnode `json:"children,omitempty"`
- }
- root := &tnode{Name: "/", IsDir: true, Children: map[string]*tnode{}}
- for _, it := range items {
- parts := strings.Split(it.name, "/")
- cur := root
- for i, p := range parts {
- if p == "" {
- continue
- }
- last := i == len(parts)-1
- if cur.Children == nil {
- cur.Children = map[string]*tnode{}
- }
- if cur.Children[p] == nil {
- cur.Children[p] = &tnode{Name: p, IsDir: !last || strings.HasSuffix(it.name, "/")}
- if last && !strings.HasSuffix(it.name, "/") {
- cur.Children[p].Size = int64(len(it.data))
- }
- }
- cur = cur.Children[p]
- }
- }
- b, _ := json.Marshal(root)
- out, _ := vm.ToValue(string(b))
- return out
- })
- vm.Set("_ziplib_listZipFileDir", func(call otto.FunctionCall) otto.Value {
- items := listing(call)
- dir, _ := argString(call, 1)
- dir = strings.Trim(dir, "/")
- if dir == "undefined" {
- dir = ""
- }
- seen := map[string]bool{}
- list := []string{}
- for _, it := range items {
- name := strings.TrimSuffix(it.name, "/")
- rest := name
- if dir != "" {
- if !strings.HasPrefix(name, dir+"/") {
- continue
- }
- rest = name[len(dir)+1:]
- }
- child := strings.SplitN(rest, "/", 2)[0]
- if child == "" || seen[child] {
- continue
- }
- seen[child] = true
- if strings.Contains(rest, "/") || strings.HasSuffix(it.name, "/") {
- child += "/"
- }
- list = append(list, child)
- }
- out, _ := vm.ToValue(list)
- return out
- })
- vm.Set("_ziplib_getFileFromZip", func(call otto.FunctionCall) otto.Value {
- items := listing(call)
- want, _ := argString(call, 1)
- want = strings.TrimPrefix(want, "/")
- for _, it := range items {
- if it.name == want {
- dest := "tmp:/ziplib/" + path.Base(want)
- r.fs.MkdirAll("tmp:/ziplib")
- if err := r.fs.WriteFile(dest, it.data); err != nil {
- return r.raise(vm, "ZipLibError", err)
- }
- out, _ := vm.ToValue(dest)
- return out
- }
- }
- return r.raise(vm, "ZipLibError", errors.New("file not found in zip: "+want))
- })
- vm.Set("_ziplib_extractPartialZip", func(call otto.FunctionCall) otto.Value {
- src := readable(call, 0)
- var only []string
- exp, _ := call.Argument(1).Export()
- switch v := exp.(type) {
- case []interface{}:
- for _, x := range v {
- if s, ok := x.(string); ok {
- only = append(only, s)
- }
- }
- case []string:
- only = v
- case string:
- only = []string{v}
- }
- dest := writable(call, 2)
- kind, b, err := open(src)
- var items []archived
- if err == nil {
- items, err = readArchive(kind, b)
- }
- if err == nil {
- err = r.extract(items, dest, only)
- }
- if err != nil {
- return r.raise(vm, "ZipLibError", err)
- }
- return otto.TrueValue()
- })
- vm.Set("_ziplib_addFileToZip", func(call otto.FunctionCall) otto.Value {
- zipPath := writable(call, 0)
- src, _ := argString(call, 1)
- if !r.canRead(src) {
- r.denied(vm, src)
- }
- inner, _ := argString(call, 2)
- kind, b, err := open(zipPath)
- var items []archived
- if err == nil && kind == "zip" {
- items, err = readArchive(kind, b)
- } else if err == nil {
- err = errors.New("not a zip file")
- }
- var add []archived
- if err == nil {
- add, err = r.collect([]string{src})
- }
- if err != nil {
- return r.raise(vm, "ZipLibError", err)
- }
- prefix := strings.Trim(inner, "/")
- if inner == "undefined" {
- prefix = ""
- }
- for _, a := range add {
- if prefix != "" {
- a.name = prefix + "/" + a.name
- }
- items = append(items, a)
- }
- if err := r.fs.WriteFile(zipPath, buildZip(items)); err != nil {
- return r.raise(vm, "ZipLibError", err)
- }
- return otto.TrueValue()
- })
- vm.Set("_ziplib_getZipFileInfo", func(call otto.FunctionCall) otto.Value {
- items := listing(call)
- p, _ := argString(call, 0)
- raw, _ := r.fs.ReadFile(p)
- info := map[string]interface{}{"fileCount": 0, "dirCount": 0, "totalUncompressedSize": 0, "totalCompressedSize": len(raw)}
- var files, dirs, size int
- for _, it := range items {
- if strings.HasSuffix(it.name, "/") {
- dirs++
- } else {
- files++
- size += len(it.data)
- }
- }
- info["fileCount"], info["dirCount"], info["totalUncompressedSize"] = files, dirs, size
- b, _ := json.Marshal(info)
- out, _ := vm.ToValue(string(b))
- return out
- })
- no7z := func(call otto.FunctionCall) otto.Value {
- return r.raise(vm, "ZipLibError", errors.New("7z archives need the server; the playground handles zip, tar, tar.gz and gz"))
- }
- for _, n := range []string{"extract7zFile", "list7zFileDir", "list7zFileContents", "getFileFrom7z", "extractPartial7z", "get7zFileInfo"} {
- vm.Set("_ziplib_"+n, no7z)
- }
- vm.Run(`
- var ziplib = {};
- ziplib.extractZipFile = _ziplib_extractZipFile;
- ziplib.createZipFile = _ziplib_createZipFile;
- ziplib.createTarFile = _ziplib_createTarFile;
- ziplib.extractTarFile = _ziplib_extractTarFile;
- ziplib.createTarGzFile = _ziplib_createTarGzFile;
- ziplib.extractTarGzFile = _ziplib_extractTarGzFile;
- ziplib.createGzFile = _ziplib_createGzFile;
- ziplib.extractGzFile = _ziplib_extractGzFile;
- ziplib.isValidZipFile = _ziplib_isValidZipFile;
- ziplib.listZipFileContents = _ziplib_listZipFileContents;
- ziplib.listZipFileDir = _ziplib_listZipFileDir;
- ziplib.getFileFromZip = _ziplib_getFileFromZip;
- ziplib.getCompressFileType = _ziplib_getCompressFileType;
- ziplib.extractAnyFile = _ziplib_extractAnyFile;
- ziplib.createAnyZipFile = _ziplib_createAnyZipFile;
- ziplib.extractPartialZip = _ziplib_extractPartialZip;
- ziplib.addFileToZip = _ziplib_addFileToZip;
- ziplib.getZipFileInfo = _ziplib_getZipFileInfo;
- ziplib.extract7zFile = _ziplib_extract7zFile;
- ziplib.list7zFileDir = _ziplib_list7zFileDir;
- ziplib.list7zFileContents = _ziplib_list7zFileContents;
- ziplib.getFileFrom7z = _ziplib_getFileFrom7z;
- ziplib.extractPartial7z = _ziplib_extractPartial7z;
- ziplib.get7zFileInfo = _ziplib_get7zFileInfo;
- `)
- }
|