libfile.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. package playground
  2. import (
  3. "crypto/md5"
  4. "encoding/hex"
  5. "encoding/json"
  6. "errors"
  7. "path"
  8. "sort"
  9. "strings"
  10. "github.com/robertkrimen/otto"
  11. )
  12. // loadLib is requirelib(): it injects a library into vm and reports whether
  13. // the name is known.
  14. func (r *run) loadLib(vm *otto.Otto, name, script string) bool {
  15. switch name {
  16. case "filelib":
  17. r.injectFilelib(vm, script)
  18. case "imagelib":
  19. r.injectImagelib(vm, script)
  20. case "ziplib":
  21. r.injectZiplib(vm)
  22. case "appdata":
  23. r.injectAppdata(vm)
  24. case "sysinfo":
  25. r.injectSysinfo(vm)
  26. case "share":
  27. r.injectShare(vm)
  28. case "notification":
  29. r.injectNotification(vm, script)
  30. case "scheduler":
  31. r.injectScheduler(vm, script)
  32. case "websocket":
  33. r.injectWebsocket(vm)
  34. case "http":
  35. r.injectHTTP(vm)
  36. case "llm":
  37. r.injectLLM(vm, script)
  38. case "cnn":
  39. r.injectCNN(vm, script)
  40. case "sqlite":
  41. r.injectSQLite(vm, script)
  42. default:
  43. fns, ok := r.req.Catalog[name]
  44. if !ok {
  45. return false
  46. }
  47. r.injectGeneric(vm, name, fns)
  48. }
  49. return true
  50. }
  51. // NativeLibs are the libraries the playground runs for real (on the drive)
  52. // or through its service mocks; anything else in api.json is a generic mock.
  53. var NativeLibs = []string{"filelib", "imagelib", "ziplib", "appdata", "sysinfo", "share", "notification", "scheduler", "websocket", "http", "llm", "cnn", "sqlite"}
  54. // relPath is RelativeVpathRewrite: a path without a root is relative to the
  55. // script, but only for a script on a drive (a WebApp script has no drive, so
  56. // the path is used as it is and then fails).
  57. func (r *run) relPath(script, vpath string) string {
  58. if strings.Contains(vpath, ":/") || strings.HasSuffix(vpath, ":") {
  59. return vpath
  60. }
  61. if strings.HasPrefix(script, "web:/") {
  62. return vpath
  63. }
  64. return Clean(path.Join(path.Dir(script), vpath))
  65. }
  66. func denied(vm *otto.Otto, msg string) {
  67. panic(vm.MakeCustomError("PermissionDenied", msg))
  68. }
  69. func argString(call otto.FunctionCall, i int) (string, bool) {
  70. a := call.Argument(i)
  71. if a.IsUndefined() {
  72. return "undefined", false
  73. }
  74. s, err := a.ToString()
  75. return s, err == nil
  76. }
  77. func (r *run) injectFilelib(vm *otto.Otto, script string) {
  78. fs := r.fs
  79. vm.Set("_filelib_writeFile", func(call otto.FunctionCall) otto.Value {
  80. p, _ := argString(call, 0)
  81. p = r.relPath(script, p)
  82. if !r.canWrite(p) {
  83. denied(vm, "Path access denied: "+p)
  84. }
  85. content, _ := call.Argument(1).ToString()
  86. if q := r.req.User.QuotaTotal; q >= 0 && fs.UsedBytes("user")+int64(len(content)) > q {
  87. r.raise(errors.New("Storage Quota Fulled"))
  88. return otto.FalseValue()
  89. }
  90. if err := fs.WriteFile(p, []byte(content)); err != nil {
  91. r.raise(fsErr("open", p, err))
  92. return otto.FalseValue()
  93. }
  94. return otto.TrueValue()
  95. })
  96. vm.Set("_filelib_deleteFile", func(call otto.FunctionCall) otto.Value {
  97. p, _ := argString(call, 0)
  98. p = r.relPath(script, p)
  99. if !r.canWrite(p) {
  100. denied(vm, "Path access denied: "+p)
  101. }
  102. if !fs.Exists(p) {
  103. r.raise(errors.New("File not exists"))
  104. return otto.FalseValue()
  105. }
  106. // os.Remove: a folder that is not empty stays, and the call still
  107. // reports true (ArozOS ignores the error).
  108. if err := fs.Remove(p); err != nil {
  109. r.log("agi", "agi", "deleteFile left "+p+" in place: "+err.Error())
  110. }
  111. return otto.TrueValue()
  112. })
  113. vm.Set("_filelib_readFile", func(call otto.FunctionCall) otto.Value {
  114. p, _ := argString(call, 0)
  115. p = r.relPath(script, p)
  116. if !r.canRead(p) {
  117. denied(vm, "Path access denied: "+p)
  118. }
  119. b, err := fs.ReadFile(p)
  120. if err != nil {
  121. r.raise(fsErr("open", p, err))
  122. return otto.FalseValue()
  123. }
  124. out, _ := vm.ToValue(string(b))
  125. return out
  126. })
  127. vm.Set("_filelib_walk", func(call otto.FunctionCall) otto.Value {
  128. p, _ := argString(call, 0)
  129. mode, ok := argString(call, 1)
  130. if !ok {
  131. mode = "all"
  132. }
  133. p = r.relPath(script, p)
  134. if !r.canRead(p) {
  135. r.raise(errors.New("unable to resolve virtual path " + p))
  136. return otto.FalseValue()
  137. }
  138. list, _ := fs.Walk(p)
  139. results := []string{}
  140. for _, e := range list {
  141. if (mode == "file" && e.Dir) || (mode == "folder" && !e.Dir) {
  142. continue
  143. }
  144. results = append(results, e.Vpath)
  145. }
  146. out, _ := vm.ToValue(results)
  147. return out
  148. })
  149. glob := func(advanced bool) func(call otto.FunctionCall) otto.Value {
  150. return func(call otto.FunctionCall) otto.Value {
  151. pattern, _ := argString(call, 0)
  152. sortMode, ok := argString(call, 1)
  153. if !ok || sortMode == "" {
  154. sortMode = "default"
  155. }
  156. if !advanced && (path.Clean(pattern) == "/" || path.Clean(pattern) == ".") {
  157. out, _ := vm.ToValue([]string{"user:/", "tmp:/"})
  158. return out
  159. }
  160. if !(advanced && pattern == "/") && !r.canRead(pattern) {
  161. denied(vm, "Path access denied")
  162. }
  163. sortMode = r.sortMode(sortMode, path.Dir(pattern))
  164. list, err := fs.Glob(pattern)
  165. if err != nil {
  166. r.raise(err)
  167. return otto.FalseValue()
  168. }
  169. list = sortEntries(list, sortMode)
  170. results := []string{}
  171. for _, e := range list {
  172. if !isHiddenPath(e.Vpath) {
  173. results = append(results, e.Vpath)
  174. }
  175. }
  176. out, _ := vm.ToValue(results)
  177. return out
  178. }
  179. }
  180. vm.Set("_filelib_glob", glob(false))
  181. vm.Set("_filelib_aglob", glob(true))
  182. vm.Set("_filelib_readdir", func(call otto.FunctionCall) otto.Value {
  183. p, _ := argString(call, 0)
  184. p = r.relPath(script, p)
  185. if !r.canRead(p) {
  186. denied(vm, "Path access denied")
  187. }
  188. sortMode, ok := argString(call, 1)
  189. if !ok || sortMode == "" {
  190. sortMode = "default"
  191. }
  192. sortMode = r.sortMode(sortMode, p)
  193. list, err := fs.ReadDir(p)
  194. if err != nil {
  195. return otto.FalseValue()
  196. }
  197. if sortMode != "default" {
  198. list = sortEntries(list, sortMode)
  199. }
  200. type info struct {
  201. Filename string
  202. Filepath string
  203. Ext string
  204. Filesize int64
  205. Modtime int64
  206. IsDir bool
  207. }
  208. results := []info{}
  209. for _, e := range list {
  210. if strings.HasPrefix(e.Name, ".") {
  211. continue
  212. }
  213. results = append(results, info{e.Name, e.Vpath, path.Ext(e.Name), e.Size, e.Mtime.Unix(), e.Dir})
  214. }
  215. b, _ := json.Marshal(results)
  216. out, _ := vm.ToValue(string(b))
  217. return out
  218. })
  219. vm.Set("_filelib_filesize", func(call otto.FunctionCall) otto.Value {
  220. p, _ := argString(call, 0)
  221. p = r.relPath(script, p)
  222. if !r.canRead(p) {
  223. denied(vm, "Path access denied")
  224. }
  225. _, size, _, err := fs.Stat(p)
  226. if err != nil {
  227. size = -1 // GetFileSize reports -1 for a file it cannot stat
  228. }
  229. out, _ := vm.ToValue(size)
  230. return out
  231. })
  232. vm.Set("_filelib_fileExists", func(call otto.FunctionCall) otto.Value {
  233. p, _ := argString(call, 0)
  234. p = r.relPath(script, p)
  235. if !r.canRead(p) {
  236. denied(vm, "Path access denied")
  237. }
  238. return boolValue(fs.Exists(p))
  239. })
  240. vm.Set("_filelib_isDir", func(call otto.FunctionCall) otto.Value {
  241. p, _ := argString(call, 0)
  242. p = r.relPath(script, p)
  243. if !r.canRead(p) {
  244. denied(vm, "Path access denied: "+p)
  245. }
  246. if !fs.Exists(p) {
  247. panic(vm.MakeCustomError("File Not Exists", "Required path not exists"))
  248. }
  249. return boolValue(fs.IsDir(p))
  250. })
  251. vm.Set("_filelib_mkdir", func(call otto.FunctionCall) otto.Value {
  252. p, _ := argString(call, 0)
  253. if !r.canWrite(p) {
  254. denied(vm, "Path access denied")
  255. }
  256. if err := fs.MkdirAll(p); err != nil {
  257. r.log("agi", "agi", err.Error())
  258. return otto.FalseValue()
  259. }
  260. return otto.TrueValue()
  261. })
  262. vm.Set("_filelib_md5", func(call otto.FunctionCall) otto.Value {
  263. p, _ := argString(call, 0)
  264. p = r.relPath(script, p)
  265. if !r.canRead(p) {
  266. denied(vm, "Path access denied")
  267. }
  268. b, err := fs.ReadFile(p)
  269. if err != nil {
  270. return otto.FalseValue()
  271. }
  272. sum := md5.Sum(b)
  273. out, _ := vm.ToValue(hex.EncodeToString(sum[:]))
  274. return out
  275. })
  276. vm.Set("_filelib_rname", func(call otto.FunctionCall) otto.Value {
  277. p, _ := argString(call, 0)
  278. p = r.relPath(script, p)
  279. switch {
  280. case strings.HasPrefix(Clean(p), "user:/"):
  281. out, _ := vm.ToValue("User")
  282. return out
  283. case strings.HasPrefix(Clean(p), "tmp:/"):
  284. out, _ := vm.ToValue("tmp")
  285. return out
  286. }
  287. return otto.FalseValue()
  288. })
  289. vm.Set("_filelib_mtime", func(call otto.FunctionCall) otto.Value {
  290. p, _ := argString(call, 0)
  291. p = r.relPath(script, p)
  292. if !r.canRead(p) {
  293. denied(vm, "Path access denied")
  294. }
  295. unix, _ := call.Argument(1).ToBoolean()
  296. _, _, mt, err := fs.Stat(p)
  297. if err != nil {
  298. r.log("agi", "agi", fsErr("stat", p, err).Error())
  299. return otto.FalseValue()
  300. }
  301. if unix {
  302. out, _ := vm.ToValue(mt.Unix())
  303. return out
  304. }
  305. out, _ := vm.ToValue(mt.Format("2006-01-02 15:04:05"))
  306. return out
  307. })
  308. vm.Set("_filelib_writeBinaryFile", func(call otto.FunctionCall) otto.Value {
  309. p, _ := argString(call, 0)
  310. p = r.relPath(script, p)
  311. if !r.canWrite(p) {
  312. denied(vm, "Path access denied")
  313. }
  314. h, _ := call.Argument(1).ToString()
  315. b, err := hex.DecodeString(h)
  316. if err != nil {
  317. return otto.FalseValue()
  318. }
  319. if err := fs.WriteFile(p, b); err != nil {
  320. return otto.FalseValue()
  321. }
  322. return otto.TrueValue()
  323. })
  324. vm.Set("_filelib_readBinaryFile", func(call otto.FunctionCall) otto.Value {
  325. p, _ := argString(call, 0)
  326. p = r.relPath(script, p)
  327. if !r.canRead(p) {
  328. denied(vm, "Path access denied")
  329. }
  330. if !fs.Exists(p) {
  331. r.raise(errors.New("File not exists"))
  332. return otto.NullValue()
  333. }
  334. b, err := fs.ReadFile(p)
  335. if err != nil {
  336. return otto.NullValue()
  337. }
  338. out, _ := vm.ToValue(hex.EncodeToString(b))
  339. return out
  340. })
  341. vm.Run(`
  342. var filelib = {};
  343. filelib.writeFile = _filelib_writeFile;
  344. filelib.readFile = _filelib_readFile;
  345. filelib.deleteFile = _filelib_deleteFile;
  346. filelib.walk = _filelib_walk;
  347. filelib.glob = _filelib_glob;
  348. filelib.aglob = _filelib_aglob;
  349. filelib.filesize = _filelib_filesize;
  350. filelib.fileExists = _filelib_fileExists;
  351. filelib.isDir = _filelib_isDir;
  352. filelib.md5 = _filelib_md5;
  353. filelib.mkdir = _filelib_mkdir;
  354. filelib.mtime = _filelib_mtime;
  355. filelib.rootName = _filelib_rname;
  356. filelib.readBinaryFile = _filelib_readBinaryFile;
  357. filelib.writeBinaryFile = _filelib_writeBinaryFile;
  358. filelib.readdir = function(path, sortmode){
  359. var s = _filelib_readdir(path, sortmode);
  360. return JSON.parse(s);
  361. };
  362. `)
  363. }
  364. // fsErr words a drive error like the os package does on a server.
  365. func fsErr(op, vpath string, err error) error {
  366. switch {
  367. case errors.Is(err, errNotExist):
  368. return errors.New(op + " " + vpath + ": The system cannot find the file specified.")
  369. case errors.Is(err, errNoRoot):
  370. return errors.New("unable to resolve virtual path " + vpath)
  371. }
  372. return errors.New(op + " " + vpath + ": " + err.Error())
  373. }
  374. // sortModes are fssort.ValidSortModes.
  375. var sortModes = []string{"default", "reverse", "smallToLarge", "largeToSmall", "mostRecent", "leastRecent", "smart", "fileTypeAsce", "fileTypeDesc"}
  376. // sortMode resolves "user" (the File Manager's saved order, which the
  377. // playground does not have) and falls back to default for unknown modes.
  378. func (r *run) sortMode(mode, dir string) string {
  379. if mode == "user" {
  380. return "default"
  381. }
  382. if !containsString(sortModes, mode) {
  383. r.log("agi", "agi", "[AGI] Sort mode: "+mode+" not supported. Using default")
  384. return "default"
  385. }
  386. return mode
  387. }
  388. func sortEntries(list []Entry, mode string) []Entry {
  389. out := append([]Entry(nil), list...)
  390. less := map[string]func(a, b Entry) bool{
  391. "reverse": func(a, b Entry) bool { return a.Name > b.Name },
  392. "smallToLarge": func(a, b Entry) bool { return a.Size < b.Size },
  393. "largeToSmall": func(a, b Entry) bool { return a.Size > b.Size },
  394. "mostRecent": func(a, b Entry) bool { return a.Mtime.After(b.Mtime) },
  395. "leastRecent": func(a, b Entry) bool { return a.Mtime.Before(b.Mtime) },
  396. "smart": func(a, b Entry) bool { return naturalLess(a.Name, b.Name) },
  397. "fileTypeAsce": func(a, b Entry) bool { return typeKey(a) < typeKey(b) },
  398. "fileTypeDesc": func(a, b Entry) bool { return typeKey(a) > typeKey(b) },
  399. }[mode]
  400. if less != nil {
  401. sort.SliceStable(out, func(i, j int) bool { return less(out[i], out[j]) })
  402. }
  403. return out
  404. }
  405. func typeKey(e Entry) string {
  406. return strings.ToLower(path.Ext(e.Name)) + "/" + e.Name
  407. }
  408. // naturalLess orders "file2" before "file10".
  409. func naturalLess(a, b string) bool {
  410. a, b = strings.ToLower(a), strings.ToLower(b)
  411. for a != "" && b != "" {
  412. ca, cb := a[0], b[0]
  413. if isDigit(ca) && isDigit(cb) {
  414. na, ra := leadingNumber(a)
  415. nb, rb := leadingNumber(b)
  416. if len(na) != len(nb) {
  417. return len(na) < len(nb)
  418. }
  419. if na != nb {
  420. return na < nb
  421. }
  422. a, b = ra, rb
  423. continue
  424. }
  425. if ca != cb {
  426. return ca < cb
  427. }
  428. a, b = a[1:], b[1:]
  429. }
  430. return len(a) < len(b)
  431. }
  432. func isDigit(c byte) bool { return c >= '0' && c <= '9' }
  433. func leadingNumber(s string) (string, string) {
  434. i := 0
  435. for i < len(s) && isDigit(s[i]) {
  436. i++
  437. }
  438. n := strings.TrimLeft(s[:i], "0")
  439. return n, s[i:]
  440. }