userFunc.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. package agi
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "io/ioutil"
  6. "log"
  7. "net/http"
  8. "path/filepath"
  9. "github.com/robertkrimen/otto"
  10. "imuslab.com/arozos/mod/filesystem"
  11. "imuslab.com/arozos/mod/filesystem/arozfs"
  12. user "imuslab.com/arozos/mod/user"
  13. )
  14. //Define path translation function
  15. func virtualPathToRealPath(vpath string, u *user.User) (*filesystem.FileSystemHandler, string, error) {
  16. fsh, err := u.GetFileSystemHandlerFromVirtualPath(vpath)
  17. if err != nil {
  18. return nil, "", err
  19. }
  20. rpath, err := fsh.FileSystemAbstraction.VirtualPathToRealPath(vpath, u.Username)
  21. if err != nil {
  22. return nil, "", err
  23. }
  24. return fsh, rpath, nil
  25. }
  26. func realpathToVirtualpath(fsh *filesystem.FileSystemHandler, path string, u *user.User) (string, error) {
  27. return fsh.FileSystemAbstraction.RealPathToVirtualPath(path, u.Username)
  28. }
  29. //Inject user based functions into the virtual machine
  30. //Note that the fsh might be nil and scriptPath must be real path of script being executed
  31. //**Use local file system check if fsh == nil**
  32. func (g *Gateway) injectUserFunctions(vm *otto.Otto, fsh *filesystem.FileSystemHandler, scriptPath string, scriptScope string, u *user.User, w http.ResponseWriter, r *http.Request) {
  33. username := u.Username
  34. vm.Set("USERNAME", username)
  35. vm.Set("USERICON", u.GetUserIcon())
  36. vm.Set("USERQUOTA_TOTAL", u.StorageQuota.TotalStorageQuota)
  37. vm.Set("USERQUOTA_USED", u.StorageQuota.UsedStorageQuota)
  38. vm.Set("USER_VROOTS", u.GetAllAccessibleFileSystemHandler())
  39. vm.Set("USER_MODULES", u.GetUserAccessibleModules())
  40. //File system and path related
  41. vm.Set("decodeVirtualPath", func(call otto.FunctionCall) otto.Value {
  42. log.Println("Call to deprecated function decodeVirtualPath")
  43. return otto.FalseValue()
  44. })
  45. vm.Set("decodeAbsoluteVirtualPath", func(call otto.FunctionCall) otto.Value {
  46. log.Println("Call to deprecated function decodeAbsoluteVirtualPath")
  47. return otto.FalseValue()
  48. })
  49. vm.Set("encodeRealPath", func(call otto.FunctionCall) otto.Value {
  50. log.Println("Call to deprecated function encodeRealPath")
  51. return otto.FalseValue()
  52. })
  53. //Check if a given virtual path is readonly
  54. vm.Set("pathCanWrite", func(call otto.FunctionCall) otto.Value {
  55. vpath, _ := call.Argument(0).ToString()
  56. if u.CanWrite(vpath) {
  57. return otto.TrueValue()
  58. } else {
  59. return otto.FalseValue()
  60. }
  61. })
  62. //Permission related
  63. vm.Set("getUserPermissionGroup", func(call otto.FunctionCall) otto.Value {
  64. groupinfo := u.GetUserPermissionGroup()
  65. jsonString, _ := json.Marshal(groupinfo)
  66. reply, _ := vm.ToValue(string(jsonString))
  67. return reply
  68. })
  69. vm.Set("userIsAdmin", func(call otto.FunctionCall) otto.Value {
  70. reply, _ := vm.ToValue(u.IsAdmin())
  71. return reply
  72. })
  73. //User Account Related
  74. /*
  75. userExists(username);
  76. */
  77. vm.Set("userExists", func(call otto.FunctionCall) otto.Value {
  78. if u.IsAdmin() {
  79. //Get username from function paramter
  80. username, err := call.Argument(0).ToString()
  81. if err != nil || username == "undefined" {
  82. g.raiseError(errors.New("username is undefined"))
  83. reply, _ := vm.ToValue(nil)
  84. return reply
  85. }
  86. //Check if user exists
  87. userExists := u.Parent().GetAuthAgent().UserExists(username)
  88. if userExists {
  89. return otto.TrueValue()
  90. } else {
  91. return otto.FalseValue()
  92. }
  93. } else {
  94. g.raiseError(errors.New("Permission Denied: userExists require admin permission"))
  95. return otto.FalseValue()
  96. }
  97. })
  98. /*
  99. createUser(username, password, defaultGroup);
  100. */
  101. vm.Set("createUser", func(call otto.FunctionCall) otto.Value {
  102. if u.IsAdmin() {
  103. //Ok. Create user base on given information
  104. username, err := call.Argument(0).ToString()
  105. if err != nil || username == "undefined" {
  106. g.raiseError(errors.New("username is undefined"))
  107. reply, _ := vm.ToValue(false)
  108. return reply
  109. }
  110. password, err := call.Argument(1).ToString()
  111. if err != nil || password == "undefined" {
  112. g.raiseError(errors.New("password is undefined"))
  113. reply, _ := vm.ToValue(false)
  114. return reply
  115. }
  116. defaultGroup, err := call.Argument(2).ToString()
  117. if err != nil || defaultGroup == "undefined" {
  118. g.raiseError(errors.New("defaultGroup is undefined"))
  119. reply, _ := vm.ToValue(false)
  120. return reply
  121. }
  122. //Check if username already used
  123. userExists := u.Parent().GetAuthAgent().UserExists(username)
  124. if userExists {
  125. g.raiseError(errors.New("Username already exists"))
  126. reply, _ := vm.ToValue(false)
  127. return reply
  128. }
  129. //Check if the given permission group exists
  130. groupExists := u.Parent().GetPermissionHandler().GroupExists(defaultGroup)
  131. if !groupExists {
  132. g.raiseError(errors.New(defaultGroup + " user-group not exists"))
  133. reply, _ := vm.ToValue(false)
  134. return reply
  135. }
  136. //Create the user
  137. err = u.Parent().GetAuthAgent().CreateUserAccount(username, password, []string{defaultGroup})
  138. if err != nil {
  139. g.raiseError(errors.New("User creation failed: " + err.Error()))
  140. reply, _ := vm.ToValue(false)
  141. return reply
  142. }
  143. return otto.TrueValue()
  144. } else {
  145. g.raiseError(errors.New("Permission Denied: createUser require admin permission"))
  146. return otto.FalseValue()
  147. }
  148. })
  149. vm.Set("editUser", func(call otto.FunctionCall) otto.Value {
  150. if u.IsAdmin() {
  151. } else {
  152. g.raiseError(errors.New("Permission Denied: editUser require admin permission"))
  153. return otto.FalseValue()
  154. }
  155. //libname, err := call.Argument(0).ToString()
  156. return otto.FalseValue()
  157. })
  158. /*
  159. removeUser(username)
  160. */
  161. vm.Set("removeUser", func(call otto.FunctionCall) otto.Value {
  162. if u.IsAdmin() {
  163. //Get username from function paramters
  164. username, err := call.Argument(0).ToString()
  165. if err != nil || username == "undefined" {
  166. g.raiseError(errors.New("username is undefined"))
  167. reply, _ := vm.ToValue(false)
  168. return reply
  169. }
  170. //Check if the user exists
  171. userExists := u.Parent().GetAuthAgent().UserExists(username)
  172. if !userExists {
  173. g.raiseError(errors.New(username + " not exists"))
  174. reply, _ := vm.ToValue(false)
  175. return reply
  176. }
  177. //User exists. Remove it from the system
  178. err = u.Parent().GetAuthAgent().UnregisterUser(username)
  179. if err != nil {
  180. g.raiseError(errors.New("User removal failed: " + err.Error()))
  181. reply, _ := vm.ToValue(false)
  182. return reply
  183. }
  184. return otto.TrueValue()
  185. } else {
  186. g.raiseError(errors.New("Permission Denied: removeUser require admin permission"))
  187. return otto.FalseValue()
  188. }
  189. })
  190. vm.Set("getUserInfoByName", func(call otto.FunctionCall) otto.Value {
  191. //libname, err := call.Argument(0).ToString()
  192. if u.IsAdmin() {
  193. } else {
  194. g.raiseError(errors.New("Permission Denied: getUserInfoByName require admin permission"))
  195. return otto.FalseValue()
  196. }
  197. return otto.TrueValue()
  198. })
  199. //Allow real time library includsion into the virtual machine
  200. vm.Set("requirelib", func(call otto.FunctionCall) otto.Value {
  201. libname, err := call.Argument(0).ToString()
  202. if err != nil {
  203. g.raiseError(err)
  204. reply, _ := vm.ToValue(nil)
  205. return reply
  206. }
  207. //Handle special case on high level libraries
  208. if libname == "websocket" && w != nil && r != nil {
  209. g.injectWebSocketFunctions(vm, u, w, r)
  210. return otto.TrueValue()
  211. } else {
  212. //Check if the library name exists. If yes, run the initiation script on the vm
  213. if entryPoint, ok := g.LoadedAGILibrary[libname]; ok {
  214. entryPoint(vm, u, fsh, scriptPath)
  215. return otto.TrueValue()
  216. } else {
  217. //Lib not exists
  218. log.Println("Lib not found: " + libname)
  219. return otto.FalseValue()
  220. }
  221. }
  222. })
  223. //Execd (Execute & detach) run another script and detach the execution
  224. vm.Set("execd", func(call otto.FunctionCall) otto.Value {
  225. //Check if the pkg is already registered
  226. scriptName, err := call.Argument(0).ToString()
  227. if err != nil {
  228. g.raiseError(err)
  229. return otto.FalseValue()
  230. }
  231. //Carry the payload to the forked process if there are any
  232. payload, _ := call.Argument(1).ToString()
  233. //Check if the script file exists
  234. targetScriptPath := arozfs.ToSlash(filepath.Join(filepath.Dir(scriptPath), scriptName))
  235. if fsh != nil {
  236. if !fsh.FileSystemAbstraction.FileExists(targetScriptPath) {
  237. g.raiseError(errors.New("[AGI] Target path not exists!"))
  238. return otto.FalseValue()
  239. }
  240. } else {
  241. if !filesystem.FileExists(targetScriptPath) {
  242. g.raiseError(errors.New("[AGI] Target path not exists!"))
  243. return otto.FalseValue()
  244. }
  245. }
  246. //Run the script
  247. scriptContent, _ := ioutil.ReadFile(targetScriptPath)
  248. go func() {
  249. //Create a new VM to execute the script (also for isolation)
  250. vm := otto.New()
  251. //Inject standard libs into the vm
  252. g.injectStandardLibs(vm, scriptPath, scriptScope)
  253. g.injectUserFunctions(vm, fsh, scriptPath, scriptScope, u, w, r)
  254. vm.Set("PARENT_DETACHED", true)
  255. vm.Set("PARENT_PAYLOAD", payload)
  256. _, err = vm.Run(string(scriptContent))
  257. if err != nil {
  258. //Script execution failed
  259. log.Println("Script Execution Failed: ", err.Error())
  260. g.raiseError(err)
  261. }
  262. }()
  263. return otto.TrueValue()
  264. })
  265. }