agi.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. package agi
  2. import (
  3. "errors"
  4. "io/ioutil"
  5. "log"
  6. "net/http"
  7. "path/filepath"
  8. "strings"
  9. "github.com/robertkrimen/otto"
  10. apt "imuslab.com/arozos/mod/apt"
  11. auth "imuslab.com/arozos/mod/auth"
  12. metadata "imuslab.com/arozos/mod/filesystem/metadata"
  13. "imuslab.com/arozos/mod/iot"
  14. user "imuslab.com/arozos/mod/user"
  15. )
  16. /*
  17. ArOZ Online Javascript Gateway Interface (AGI)
  18. author: tobychui
  19. This script load plugins written in Javascript and run them in VM inside golang
  20. DO NOT CONFUSE PLUGIN WITH SUBSERVICE :))
  21. */
  22. var (
  23. AgiVersion string = "1.5" //Defination of the agi runtime version. Update this when new function is added
  24. )
  25. type AgiLibIntergface func(*otto.Otto, *user.User) //Define the lib loader interface for AGI Libraries
  26. type AgiPackage struct {
  27. InitRoot string //The initialization of the root for the module that request this package
  28. }
  29. type AgiSysInfo struct {
  30. //System information
  31. BuildVersion string
  32. InternalVersion string
  33. LoadedModule []string
  34. //System Handlers
  35. UserHandler *user.UserHandler
  36. ReservedTables []string
  37. PackageManager *apt.AptPackageManager
  38. ModuleRegisterParser func(string) error
  39. AuthAgent *auth.AuthAgent
  40. FileSystemRender *metadata.RenderHandler
  41. IotManager *iot.Manager
  42. //Scanning Roots
  43. StartupRoot string
  44. ActivateScope []string
  45. }
  46. type Gateway struct {
  47. ReservedTables []string
  48. AllowAccessPkgs map[string][]AgiPackage
  49. LoadedAGILibrary map[string]AgiLibIntergface
  50. Option *AgiSysInfo
  51. }
  52. func NewGateway(option AgiSysInfo) (*Gateway, error) {
  53. //Handle startup registration of ajgi modules
  54. startupScripts, _ := filepath.Glob(filepath.ToSlash(filepath.Clean(option.StartupRoot)) + "/*/init.agi")
  55. gatewayObject := Gateway{
  56. ReservedTables: option.ReservedTables,
  57. AllowAccessPkgs: map[string][]AgiPackage{},
  58. LoadedAGILibrary: map[string]AgiLibIntergface{},
  59. Option: &option,
  60. }
  61. for _, script := range startupScripts {
  62. scriptContentByte, _ := ioutil.ReadFile(script)
  63. scriptContent := string(scriptContentByte)
  64. log.Println("[AGI] Gatewat script loaded (" + script + ")")
  65. //Create a new vm for this request
  66. vm := otto.New()
  67. //Only allow non user based operations
  68. gatewayObject.injectStandardLibs(vm, script, "./web/")
  69. _, err := vm.Run(scriptContent)
  70. if err != nil {
  71. log.Println("[AGI] Load Failed: " + script + ". Skipping.")
  72. log.Println(err)
  73. continue
  74. }
  75. }
  76. //Load all the other libs entry points into the memoary
  77. gatewayObject.ImageLibRegister()
  78. gatewayObject.FileLibRegister()
  79. gatewayObject.HTTPLibRegister()
  80. gatewayObject.IoTLibRegister()
  81. gatewayObject.AppdataLibRegister()
  82. return &gatewayObject, nil
  83. }
  84. func (g *Gateway) RunScript(script string) error {
  85. //Create a new vm for this request
  86. vm := otto.New()
  87. //Only allow non user based operations
  88. g.injectStandardLibs(vm, "", "./web/")
  89. _, err := vm.Run(script)
  90. if err != nil {
  91. log.Println("[AGI] Script Execution Failed: ", err.Error())
  92. return err
  93. }
  94. return nil
  95. }
  96. func (g *Gateway) RegisterLib(libname string, entryPoint AgiLibIntergface) error {
  97. _, ok := g.LoadedAGILibrary[libname]
  98. if ok {
  99. //This lib already registered. Return error
  100. return errors.New("This library name already registered")
  101. } else {
  102. g.LoadedAGILibrary[libname] = entryPoint
  103. }
  104. return nil
  105. }
  106. func (g *Gateway) raiseError(err error) {
  107. log.Println("[AGI] Runtime Error " + err.Error())
  108. //To be implemented
  109. }
  110. //Check if this table is restricted table. Return true if the access is valid
  111. func (g *Gateway) filterDBTable(tablename string, existsCheck bool) bool {
  112. //Check if table is restricted
  113. if stringInSlice(tablename, g.ReservedTables) {
  114. return false
  115. }
  116. //Check if table exists
  117. if existsCheck {
  118. if !g.Option.UserHandler.GetDatabase().TableExists(tablename) {
  119. return false
  120. }
  121. }
  122. return true
  123. }
  124. //Handle request from RESTFUL API
  125. func (g *Gateway) APIHandler(w http.ResponseWriter, r *http.Request, thisuser *user.User) {
  126. scriptContent, err := mv(r, "script", true)
  127. if err != nil {
  128. w.WriteHeader(http.StatusBadRequest)
  129. w.Write([]byte("400 - Bad Request (Missing script content)"))
  130. return
  131. }
  132. g.ExecuteAGIScript(scriptContent, "", "", w, r, thisuser)
  133. }
  134. //Handle user requests
  135. func (g *Gateway) InterfaceHandler(w http.ResponseWriter, r *http.Request, thisuser *user.User) {
  136. //Get user object from the request
  137. startupRoot := g.Option.StartupRoot
  138. startupRoot = filepath.ToSlash(filepath.Clean(startupRoot))
  139. //Get the script files for the plugin
  140. scriptFile, err := mv(r, "script", false)
  141. if err != nil {
  142. sendErrorResponse(w, "Invalid script path")
  143. return
  144. }
  145. scriptFile = specialURIDecode(scriptFile)
  146. //Check if the script path exists
  147. scriptExists := false
  148. scriptScope := "./web/"
  149. for _, thisScope := range g.Option.ActivateScope {
  150. thisScope = filepath.ToSlash(filepath.Clean(thisScope))
  151. if fileExists(thisScope + "/" + scriptFile) {
  152. scriptExists = true
  153. scriptFile = thisScope + "/" + scriptFile
  154. scriptScope = thisScope
  155. }
  156. }
  157. if !scriptExists {
  158. sendErrorResponse(w, "Script not found")
  159. return
  160. }
  161. //Check for user permission on this module
  162. moduleName := getScriptRoot(scriptFile, scriptScope)
  163. if !thisuser.GetModuleAccessPermission(moduleName) {
  164. w.WriteHeader(http.StatusForbidden)
  165. if g.Option.BuildVersion == "development" {
  166. w.Write([]byte("Permission denied: User do not have permission to access " + moduleName))
  167. } else {
  168. w.Write([]byte("403 Forbidden"))
  169. }
  170. return
  171. }
  172. //Check the given file is actually agi script
  173. if !(filepath.Ext(scriptFile) == ".agi" || filepath.Ext(scriptFile) == ".js") {
  174. w.WriteHeader(http.StatusForbidden)
  175. if g.Option.BuildVersion == "development" {
  176. w.Write([]byte("AGI script must have file extension of .agi or .js"))
  177. } else {
  178. w.Write([]byte("403 Forbidden"))
  179. }
  180. return
  181. }
  182. //Get the content of the script
  183. scriptContentByte, _ := ioutil.ReadFile(scriptFile)
  184. scriptContent := string(scriptContentByte)
  185. g.ExecuteAGIScript(scriptContent, scriptFile, scriptScope, w, r, thisuser)
  186. }
  187. /*
  188. Executing the given AGI Script contents. Requires:
  189. scriptContent: The AGI command sequence
  190. scriptFile: The filepath of the script file
  191. scriptScope: The scope of the script file, aka the module base path
  192. w / r : Web request and response writer
  193. thisuser: userObject
  194. */
  195. func (g *Gateway) ExecuteAGIScript(scriptContent string, scriptFile string, scriptScope string, w http.ResponseWriter, r *http.Request, thisuser *user.User) {
  196. //Create a new vm for this request
  197. vm := otto.New()
  198. //Inject standard libs into the vm
  199. g.injectStandardLibs(vm, scriptFile, scriptScope)
  200. g.injectUserFunctions(vm, scriptFile, scriptScope, thisuser, w, r)
  201. //Detect cotent type
  202. contentType := r.Header.Get("Content-type")
  203. if strings.Contains(contentType, "application/json") {
  204. //For shitty people who use Angular
  205. body, _ := ioutil.ReadAll(r.Body)
  206. vm.Set("POST_data", string(body))
  207. } else {
  208. r.ParseForm()
  209. //Insert all paramters into the vm
  210. for k, v := range r.PostForm {
  211. if len(v) == 1 {
  212. vm.Set(k, v[0])
  213. } else {
  214. vm.Set(k, v)
  215. }
  216. }
  217. }
  218. _, err := vm.Run(scriptContent)
  219. if err != nil {
  220. scriptpath, _ := filepath.Abs(scriptFile)
  221. g.RenderErrorTemplate(w, err.Error(), scriptpath)
  222. return
  223. }
  224. //Get the return valu from the script
  225. value, err := vm.Get("HTTP_RESP")
  226. if err != nil {
  227. sendTextResponse(w, "")
  228. return
  229. }
  230. valueString, err := value.ToString()
  231. //Get respond header type from the vm
  232. header, _ := vm.Get("HTTP_HEADER")
  233. headerString, _ := header.ToString()
  234. if headerString != "" {
  235. w.Header().Set("Content-Type", headerString)
  236. }
  237. w.Write([]byte(valueString))
  238. }
  239. /*
  240. Execute AGI script with given user information
  241. */
  242. func (g *Gateway) ExecuteAGIScriptAsUser(scriptFile string, targetUser *user.User) (string, error) {
  243. //Create a new vm for this request
  244. vm := otto.New()
  245. //Inject standard libs into the vm
  246. g.injectStandardLibs(vm, scriptFile, "")
  247. g.injectUserFunctions(vm, scriptFile, "", targetUser, nil, nil)
  248. //Try to read the script content
  249. scriptContent, err := ioutil.ReadFile(scriptFile)
  250. if err != nil {
  251. return "", err
  252. }
  253. _, err = vm.Run(scriptContent)
  254. if err != nil {
  255. return "", err
  256. }
  257. //Get the return valu from the script
  258. value, err := vm.Get("HTTP_RESP")
  259. if err != nil {
  260. return "", err
  261. }
  262. valueString, err := value.ToString()
  263. return valueString, nil
  264. }