libzip.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. package playground
  2. import (
  3. "archive/tar"
  4. "archive/zip"
  5. "bytes"
  6. "compress/gzip"
  7. "encoding/json"
  8. "errors"
  9. "io"
  10. "path"
  11. "strings"
  12. "time"
  13. "github.com/robertkrimen/otto"
  14. )
  15. // The playground's ziplib handles zip, tar, tar.gz and gz on the drive; 7z
  16. // needs the server.
  17. type archived struct {
  18. name string // slash path inside the archive, folders end with "/"
  19. data []byte
  20. }
  21. // collect gathers files and folders for an archive: a folder is added with
  22. // its contents under its own name, as ArozOS does.
  23. func (r *run) collect(sources []string) ([]archived, error) {
  24. var out []archived
  25. for _, src := range sources {
  26. list, err := r.fs.Walk(src)
  27. if err != nil {
  28. return nil, fsErr("stat", src, err)
  29. }
  30. base := path.Dir(Clean(src))
  31. for _, e := range list {
  32. rel := strings.TrimPrefix(strings.TrimPrefix(e.Vpath, base), "/")
  33. if i := strings.Index(rel, ":/"); i >= 0 {
  34. rel = rel[i+2:]
  35. }
  36. if e.Dir {
  37. if rel != "" {
  38. out = append(out, archived{name: rel + "/"})
  39. }
  40. continue
  41. }
  42. b, _ := r.fs.ReadFile(e.Vpath)
  43. out = append(out, archived{name: rel, data: b})
  44. }
  45. }
  46. return out, nil
  47. }
  48. func buildZip(items []archived) []byte {
  49. var buf bytes.Buffer
  50. zw := zip.NewWriter(&buf)
  51. for _, it := range items {
  52. h := &zip.FileHeader{Name: it.name, Method: zip.Deflate, Modified: time.Now()}
  53. if strings.HasSuffix(it.name, "/") {
  54. h.Method = zip.Store
  55. }
  56. w, _ := zw.CreateHeader(h)
  57. w.Write(it.data)
  58. }
  59. zw.Close()
  60. return buf.Bytes()
  61. }
  62. func buildTar(items []archived) []byte {
  63. var buf bytes.Buffer
  64. tw := tar.NewWriter(&buf)
  65. for _, it := range items {
  66. h := &tar.Header{Name: it.name, Mode: 0o644, Size: int64(len(it.data)), ModTime: time.Now(), Typeflag: tar.TypeReg}
  67. if strings.HasSuffix(it.name, "/") {
  68. h.Typeflag, h.Mode, h.Size = tar.TypeDir, 0o755, 0
  69. }
  70. tw.WriteHeader(h)
  71. tw.Write(it.data)
  72. }
  73. tw.Close()
  74. return buf.Bytes()
  75. }
  76. func gz(b []byte) []byte {
  77. var buf bytes.Buffer
  78. w := gzip.NewWriter(&buf)
  79. w.Write(b)
  80. w.Close()
  81. return buf.Bytes()
  82. }
  83. func gunzip(b []byte) ([]byte, error) {
  84. zr, err := gzip.NewReader(bytes.NewReader(b))
  85. if err != nil {
  86. return nil, err
  87. }
  88. return io.ReadAll(io.LimitReader(zr, 256<<20))
  89. }
  90. // archiveType sniffs an archive: "zip", "tar", "tar.gz", "gz", "7z" or "".
  91. func archiveType(name string, b []byte) string {
  92. switch {
  93. case bytes.HasPrefix(b, []byte("PK\x03\x04")) || bytes.HasPrefix(b, []byte("PK\x05\x06")):
  94. return "zip"
  95. case bytes.HasPrefix(b, []byte("7z\xbc\xaf\x27\x1c")):
  96. return "7z"
  97. case bytes.HasPrefix(b, []byte{0x1f, 0x8b}):
  98. if inner, err := gunzip(b); err == nil && len(inner) > 262 && string(inner[257:262]) == "ustar" {
  99. return "tar.gz"
  100. }
  101. return "gz"
  102. case len(b) > 262 && string(b[257:262]) == "ustar":
  103. return "tar"
  104. }
  105. return ""
  106. }
  107. // readArchive lists the entries of a zip or (gzipped) tar.
  108. func readArchive(kind string, b []byte) ([]archived, error) {
  109. var out []archived
  110. switch kind {
  111. case "zip":
  112. zr, err := zip.NewReader(bytes.NewReader(b), int64(len(b)))
  113. if err != nil {
  114. return nil, err
  115. }
  116. for _, f := range zr.File {
  117. if f.FileInfo().IsDir() {
  118. out = append(out, archived{name: strings.TrimSuffix(f.Name, "/") + "/"})
  119. continue
  120. }
  121. rc, err := f.Open()
  122. if err != nil {
  123. return nil, err
  124. }
  125. data, err := io.ReadAll(io.LimitReader(rc, 256<<20))
  126. rc.Close()
  127. if err != nil {
  128. return nil, err
  129. }
  130. out = append(out, archived{name: f.Name, data: data})
  131. }
  132. case "tar.gz", "tar":
  133. if kind == "tar.gz" {
  134. var err error
  135. if b, err = gunzip(b); err != nil {
  136. return nil, err
  137. }
  138. }
  139. tr := tar.NewReader(bytes.NewReader(b))
  140. for {
  141. h, err := tr.Next()
  142. if err == io.EOF {
  143. break
  144. }
  145. if err != nil {
  146. return nil, err
  147. }
  148. if h.Typeflag == tar.TypeDir {
  149. out = append(out, archived{name: strings.TrimSuffix(h.Name, "/") + "/"})
  150. continue
  151. }
  152. data, _ := io.ReadAll(io.LimitReader(tr, 256<<20))
  153. out = append(out, archived{name: h.Name, data: data})
  154. }
  155. default:
  156. return nil, errors.New("unsupported archive type")
  157. }
  158. return out, nil
  159. }
  160. // extract writes entries below dest, refusing names that climb out of it.
  161. func (r *run) extract(items []archived, dest string, only []string) error {
  162. dest = Clean(dest)
  163. if err := r.fs.MkdirAll(dest); err != nil {
  164. return err
  165. }
  166. for _, it := range items {
  167. name := strings.TrimPrefix(path.Clean("/"+it.name), "/")
  168. if strings.HasPrefix(path.Clean(it.name), "..") {
  169. return errors.New("illegal file path in archive: " + it.name)
  170. }
  171. if only != nil && !wanted(name, only) {
  172. continue
  173. }
  174. target := Clean(dest + "/" + name)
  175. if strings.HasSuffix(it.name, "/") {
  176. r.fs.MkdirAll(target)
  177. continue
  178. }
  179. r.fs.MkdirAll(path.Dir(target))
  180. if err := r.fs.WriteFile(target, it.data); err != nil {
  181. return err
  182. }
  183. }
  184. return nil
  185. }
  186. func wanted(name string, only []string) bool {
  187. for _, o := range only {
  188. o = strings.Trim(o, "/")
  189. if name == o || strings.HasPrefix(name, o+"/") {
  190. return true
  191. }
  192. }
  193. return false
  194. }
  195. func (r *run) injectZiplib(vm *otto.Otto) {
  196. readable := func(call otto.FunctionCall, i int) string {
  197. p, _ := argString(call, i)
  198. if !r.canRead(p) {
  199. r.denied(vm, p)
  200. }
  201. return p
  202. }
  203. writable := func(call otto.FunctionCall, i int) string {
  204. p, _ := argString(call, i)
  205. if !r.canWrite(p) {
  206. r.denied(vm, p)
  207. }
  208. return p
  209. }
  210. sources := func(call otto.FunctionCall) []string {
  211. a := call.Argument(0)
  212. var list []string
  213. if a.IsObject() {
  214. exp, _ := a.Export()
  215. if arr, ok := exp.([]interface{}); ok {
  216. for _, v := range arr {
  217. if s, ok := v.(string); ok {
  218. list = append(list, s)
  219. }
  220. }
  221. } else if arr, ok := exp.([]string); ok {
  222. list = arr
  223. }
  224. } else {
  225. s, _ := a.ToString()
  226. list = []string{s}
  227. }
  228. for _, s := range list {
  229. if !r.canRead(s) {
  230. r.denied(vm, s)
  231. }
  232. }
  233. return list
  234. }
  235. create := func(kind string) func(otto.FunctionCall) otto.Value {
  236. return func(call otto.FunctionCall) otto.Value {
  237. src := sources(call)
  238. out := writable(call, 1)
  239. items, err := r.collect(src)
  240. if err != nil {
  241. return r.raise(vm, "ZipLibError", err)
  242. }
  243. var b []byte
  244. switch kind {
  245. case "zip":
  246. b = buildZip(items)
  247. case "tar":
  248. b = buildTar(items)
  249. case "tar.gz":
  250. b = gz(buildTar(items))
  251. case "gz":
  252. if len(items) != 1 || strings.HasSuffix(items[0].name, "/") {
  253. return r.raise(vm, "ZipLibError", errors.New("gz compresses a single file"))
  254. }
  255. b = gz(items[0].data)
  256. }
  257. if err := r.fs.WriteFile(out, b); err != nil {
  258. return r.raise(vm, "ZipLibError", fsErr("open", out, err))
  259. }
  260. return otto.TrueValue()
  261. }
  262. }
  263. open := func(p string) (string, []byte, error) {
  264. b, err := r.fs.ReadFile(p)
  265. if err != nil {
  266. return "", nil, fsErr("open", p, err)
  267. }
  268. return archiveType(p, b), b, nil
  269. }
  270. extract := func(want string) func(otto.FunctionCall) otto.Value {
  271. return func(call otto.FunctionCall) otto.Value {
  272. src, dest := readable(call, 0), writable(call, 1)
  273. kind, b, err := open(src)
  274. if err != nil {
  275. return r.raise(vm, "ZipLibError", err)
  276. }
  277. if want != "" && kind != want {
  278. return r.raise(vm, "ZipLibError", errors.New(src+" is not a "+want+" file"))
  279. }
  280. if kind == "7z" {
  281. return r.raise(vm, "ZipLibError", errors.New("7z archives need the server; the playground handles zip, tar, tar.gz and gz"))
  282. }
  283. if kind == "gz" {
  284. data, err := gunzip(b)
  285. if err != nil {
  286. return r.raise(vm, "ZipLibError", err)
  287. }
  288. r.fs.MkdirAll(dest)
  289. name := strings.TrimSuffix(path.Base(Clean(src)), ".gz")
  290. if err := r.fs.WriteFile(Clean(dest+"/"+name), data); err != nil {
  291. return r.raise(vm, "ZipLibError", err)
  292. }
  293. return otto.TrueValue()
  294. }
  295. items, err := readArchive(kind, b)
  296. if err == nil {
  297. err = r.extract(items, dest, nil)
  298. }
  299. if err != nil {
  300. return r.raise(vm, "ZipLibError", err)
  301. }
  302. return otto.TrueValue()
  303. }
  304. }
  305. vm.Set("_ziplib_createZipFile", create("zip"))
  306. vm.Set("_ziplib_createTarFile", create("tar"))
  307. vm.Set("_ziplib_createTarGzFile", create("tar.gz"))
  308. vm.Set("_ziplib_createGzFile", create("gz"))
  309. vm.Set("_ziplib_extractZipFile", extract("zip"))
  310. vm.Set("_ziplib_extractTarFile", extract("tar"))
  311. vm.Set("_ziplib_extractTarGzFile", extract("tar.gz"))
  312. vm.Set("_ziplib_extractGzFile", extract("gz"))
  313. vm.Set("_ziplib_extractAnyFile", extract(""))
  314. vm.Set("_ziplib_createAnyZipFile", func(call otto.FunctionCall) otto.Value {
  315. format, ok := argString(call, 2)
  316. if !ok || format == "" {
  317. out, _ := argString(call, 1)
  318. switch {
  319. case strings.HasSuffix(out, ".tar.gz") || strings.HasSuffix(out, ".tgz"):
  320. format = "tar.gz"
  321. case strings.HasSuffix(out, ".tar"):
  322. format = "tar"
  323. case strings.HasSuffix(out, ".gz"):
  324. format = "gz"
  325. default:
  326. format = "zip"
  327. }
  328. }
  329. format = strings.TrimPrefix(strings.ToLower(format), ".")
  330. if format == "tgz" {
  331. format = "tar.gz"
  332. }
  333. if format != "zip" && format != "tar" && format != "tar.gz" && format != "gz" {
  334. return r.raise(vm, "ZipLibError", errors.New("unsupported format "+format))
  335. }
  336. return create(format)(call)
  337. })
  338. vm.Set("_ziplib_isValidZipFile", func(call otto.FunctionCall) otto.Value {
  339. kind, _, err := open(readable(call, 0))
  340. return boolValue(err == nil && kind != "" && kind != "7z")
  341. })
  342. vm.Set("_ziplib_getCompressFileType", func(call otto.FunctionCall) otto.Value {
  343. //"unknown" for a file that is no archive, as on ArozOS
  344. kind, _, err := open(readable(call, 0))
  345. if err != nil || kind == "" {
  346. kind = "unknown"
  347. }
  348. out, _ := vm.ToValue(kind)
  349. return out
  350. })
  351. //listing reads a zip file's entries and throws when it cannot
  352. listing := func(call otto.FunctionCall) []archived {
  353. kind, b, err := open(readable(call, 0))
  354. if err == nil && kind != "zip" {
  355. err = errors.New("not a zip file")
  356. }
  357. var items []archived
  358. if err == nil {
  359. items, err = readArchive(kind, b)
  360. }
  361. if err != nil {
  362. r.raise(vm, "ZipLibError", err)
  363. }
  364. return items
  365. }
  366. vm.Set("_ziplib_listZipFileContents", func(call otto.FunctionCall) otto.Value {
  367. items := listing(call)
  368. type tnode struct {
  369. Name string `json:"name"`
  370. IsDir bool `json:"isDir"`
  371. Size int64 `json:"size"`
  372. Children map[string]*tnode `json:"children,omitempty"`
  373. }
  374. root := &tnode{Name: "/", IsDir: true, Children: map[string]*tnode{}}
  375. for _, it := range items {
  376. parts := strings.Split(it.name, "/")
  377. cur := root
  378. for i, p := range parts {
  379. if p == "" {
  380. continue
  381. }
  382. last := i == len(parts)-1
  383. if cur.Children == nil {
  384. cur.Children = map[string]*tnode{}
  385. }
  386. if cur.Children[p] == nil {
  387. cur.Children[p] = &tnode{Name: p, IsDir: !last || strings.HasSuffix(it.name, "/")}
  388. if last && !strings.HasSuffix(it.name, "/") {
  389. cur.Children[p].Size = int64(len(it.data))
  390. }
  391. }
  392. cur = cur.Children[p]
  393. }
  394. }
  395. b, _ := json.Marshal(root)
  396. out, _ := vm.ToValue(string(b))
  397. return out
  398. })
  399. vm.Set("_ziplib_listZipFileDir", func(call otto.FunctionCall) otto.Value {
  400. items := listing(call)
  401. dir, _ := argString(call, 1)
  402. dir = strings.Trim(dir, "/")
  403. if dir == "undefined" {
  404. dir = ""
  405. }
  406. seen := map[string]bool{}
  407. list := []string{}
  408. for _, it := range items {
  409. name := strings.TrimSuffix(it.name, "/")
  410. rest := name
  411. if dir != "" {
  412. if !strings.HasPrefix(name, dir+"/") {
  413. continue
  414. }
  415. rest = name[len(dir)+1:]
  416. }
  417. child := strings.SplitN(rest, "/", 2)[0]
  418. if child == "" || seen[child] {
  419. continue
  420. }
  421. seen[child] = true
  422. if strings.Contains(rest, "/") || strings.HasSuffix(it.name, "/") {
  423. child += "/"
  424. }
  425. list = append(list, child)
  426. }
  427. out, _ := vm.ToValue(list)
  428. return out
  429. })
  430. vm.Set("_ziplib_getFileFromZip", func(call otto.FunctionCall) otto.Value {
  431. items := listing(call)
  432. want, _ := argString(call, 1)
  433. want = strings.TrimPrefix(want, "/")
  434. for _, it := range items {
  435. if it.name == want {
  436. dest := "tmp:/ziplib/" + path.Base(want)
  437. r.fs.MkdirAll("tmp:/ziplib")
  438. if err := r.fs.WriteFile(dest, it.data); err != nil {
  439. return r.raise(vm, "ZipLibError", err)
  440. }
  441. out, _ := vm.ToValue(dest)
  442. return out
  443. }
  444. }
  445. return r.raise(vm, "ZipLibError", errors.New("file not found in zip: "+want))
  446. })
  447. vm.Set("_ziplib_extractPartialZip", func(call otto.FunctionCall) otto.Value {
  448. src := readable(call, 0)
  449. var only []string
  450. exp, _ := call.Argument(1).Export()
  451. switch v := exp.(type) {
  452. case []interface{}:
  453. for _, x := range v {
  454. if s, ok := x.(string); ok {
  455. only = append(only, s)
  456. }
  457. }
  458. case []string:
  459. only = v
  460. case string:
  461. only = []string{v}
  462. }
  463. dest := writable(call, 2)
  464. kind, b, err := open(src)
  465. var items []archived
  466. if err == nil {
  467. items, err = readArchive(kind, b)
  468. }
  469. if err == nil {
  470. err = r.extract(items, dest, only)
  471. }
  472. if err != nil {
  473. return r.raise(vm, "ZipLibError", err)
  474. }
  475. return otto.TrueValue()
  476. })
  477. vm.Set("_ziplib_addFileToZip", func(call otto.FunctionCall) otto.Value {
  478. zipPath := writable(call, 0)
  479. src, _ := argString(call, 1)
  480. if !r.canRead(src) {
  481. r.denied(vm, src)
  482. }
  483. inner, _ := argString(call, 2)
  484. kind, b, err := open(zipPath)
  485. var items []archived
  486. if err == nil && kind == "zip" {
  487. items, err = readArchive(kind, b)
  488. } else if err == nil {
  489. err = errors.New("not a zip file")
  490. }
  491. var add []archived
  492. if err == nil {
  493. add, err = r.collect([]string{src})
  494. }
  495. if err != nil {
  496. return r.raise(vm, "ZipLibError", err)
  497. }
  498. prefix := strings.Trim(inner, "/")
  499. if inner == "undefined" {
  500. prefix = ""
  501. }
  502. for _, a := range add {
  503. if prefix != "" {
  504. a.name = prefix + "/" + a.name
  505. }
  506. items = append(items, a)
  507. }
  508. if err := r.fs.WriteFile(zipPath, buildZip(items)); err != nil {
  509. return r.raise(vm, "ZipLibError", err)
  510. }
  511. return otto.TrueValue()
  512. })
  513. vm.Set("_ziplib_getZipFileInfo", func(call otto.FunctionCall) otto.Value {
  514. items := listing(call)
  515. p, _ := argString(call, 0)
  516. raw, _ := r.fs.ReadFile(p)
  517. info := map[string]interface{}{"fileCount": 0, "dirCount": 0, "totalUncompressedSize": 0, "totalCompressedSize": len(raw)}
  518. var files, dirs, size int
  519. for _, it := range items {
  520. if strings.HasSuffix(it.name, "/") {
  521. dirs++
  522. } else {
  523. files++
  524. size += len(it.data)
  525. }
  526. }
  527. info["fileCount"], info["dirCount"], info["totalUncompressedSize"] = files, dirs, size
  528. b, _ := json.Marshal(info)
  529. out, _ := vm.ToValue(string(b))
  530. return out
  531. })
  532. no7z := func(call otto.FunctionCall) otto.Value {
  533. return r.raise(vm, "ZipLibError", errors.New("7z archives need the server; the playground handles zip, tar, tar.gz and gz"))
  534. }
  535. for _, n := range []string{"extract7zFile", "list7zFileDir", "list7zFileContents", "getFileFrom7z", "extractPartial7z", "get7zFileInfo"} {
  536. vm.Set("_ziplib_"+n, no7z)
  537. }
  538. vm.Run(`
  539. var ziplib = {};
  540. ziplib.extractZipFile = _ziplib_extractZipFile;
  541. ziplib.createZipFile = _ziplib_createZipFile;
  542. ziplib.createTarFile = _ziplib_createTarFile;
  543. ziplib.extractTarFile = _ziplib_extractTarFile;
  544. ziplib.createTarGzFile = _ziplib_createTarGzFile;
  545. ziplib.extractTarGzFile = _ziplib_extractTarGzFile;
  546. ziplib.createGzFile = _ziplib_createGzFile;
  547. ziplib.extractGzFile = _ziplib_extractGzFile;
  548. ziplib.isValidZipFile = _ziplib_isValidZipFile;
  549. ziplib.listZipFileContents = _ziplib_listZipFileContents;
  550. ziplib.listZipFileDir = _ziplib_listZipFileDir;
  551. ziplib.getFileFromZip = _ziplib_getFileFromZip;
  552. ziplib.getCompressFileType = _ziplib_getCompressFileType;
  553. ziplib.extractAnyFile = _ziplib_extractAnyFile;
  554. ziplib.createAnyZipFile = _ziplib_createAnyZipFile;
  555. ziplib.extractPartialZip = _ziplib_extractPartialZip;
  556. ziplib.addFileToZip = _ziplib_addFileToZip;
  557. ziplib.getZipFileInfo = _ziplib_getZipFileInfo;
  558. ziplib.extract7zFile = _ziplib_extract7zFile;
  559. ziplib.list7zFileDir = _ziplib_list7zFileDir;
  560. ziplib.list7zFileContents = _ziplib_list7zFileContents;
  561. ziplib.getFileFrom7z = _ziplib_getFileFrom7z;
  562. ziplib.extractPartial7z = _ziplib_extractPartial7z;
  563. ziplib.get7zFileInfo = _ziplib_get7zFileInfo;
  564. `)
  565. }