agi.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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.4" //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("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("AJI 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. return &gatewayObject, nil
  82. }
  83. func (g *Gateway) RunScript(script string) error {
  84. //Create a new vm for this request
  85. vm := otto.New()
  86. //Only allow non user based operations
  87. g.injectStandardLibs(vm, "", "./web/")
  88. _, err := vm.Run(script)
  89. if err != nil {
  90. log.Println("Script Execution Failed: ", err.Error())
  91. return err
  92. }
  93. return nil
  94. }
  95. func (g *Gateway) RegisterLib(libname string, entryPoint AgiLibIntergface) error {
  96. _, ok := g.LoadedAGILibrary[libname]
  97. if ok {
  98. //This lib already registered. Return error
  99. return errors.New("This library name already registered")
  100. } else {
  101. g.LoadedAGILibrary[libname] = entryPoint
  102. }
  103. return nil
  104. }
  105. func (g *Gateway) raiseError(err error) {
  106. log.Println("*AGI Engine* [Runtime Error] " + err.Error())
  107. //To be implemented
  108. }
  109. //Check if this table is restricted table. Return true if the access is valid
  110. func (g *Gateway) filterDBTable(tablename string, existsCheck bool) bool {
  111. //Check if table is restricted
  112. if stringInSlice(tablename, g.ReservedTables) {
  113. return false
  114. }
  115. //Check if table exists
  116. if existsCheck {
  117. if !g.Option.UserHandler.GetDatabase().TableExists(tablename) {
  118. return false
  119. }
  120. }
  121. return true
  122. }
  123. //Handle request from RESTFUL API
  124. func (g *Gateway) APIHandler(w http.ResponseWriter, r *http.Request, thisuser *user.User) {
  125. scriptContent, err := mv(r, "script", true)
  126. if err != nil {
  127. w.WriteHeader(http.StatusBadRequest)
  128. w.Write([]byte("400 - Bad Request (Missing script content)"))
  129. return
  130. }
  131. g.ExecuteAGIScript(scriptContent, "", "", w, r, thisuser)
  132. }
  133. //Handle user requests
  134. func (g *Gateway) InterfaceHandler(w http.ResponseWriter, r *http.Request, thisuser *user.User) {
  135. //Get user object from the request
  136. startupRoot := g.Option.StartupRoot
  137. startupRoot = filepath.ToSlash(filepath.Clean(startupRoot))
  138. //Get the script files for the plugin
  139. scriptFile, err := mv(r, "script", false)
  140. if err != nil {
  141. sendErrorResponse(w, "Invalid script path")
  142. return
  143. }
  144. scriptFile = specialURIDecode(scriptFile)
  145. //Check if the script path exists
  146. scriptExists := false
  147. scriptScope := "./web/"
  148. for _, thisScope := range g.Option.ActivateScope {
  149. thisScope = filepath.ToSlash(filepath.Clean(thisScope))
  150. if fileExists(thisScope + "/" + scriptFile) {
  151. scriptExists = true
  152. scriptFile = thisScope + "/" + scriptFile
  153. scriptScope = thisScope
  154. }
  155. }
  156. if !scriptExists {
  157. sendErrorResponse(w, "Script not found")
  158. return
  159. }
  160. //Check for user permission on this module
  161. moduleName := getScriptRoot(scriptFile, scriptScope)
  162. if !thisuser.GetModuleAccessPermission(moduleName) {
  163. w.WriteHeader(http.StatusForbidden)
  164. if g.Option.BuildVersion == "development" {
  165. w.Write([]byte("Permission denied: User do not have permission to access " + moduleName))
  166. } else {
  167. w.Write([]byte("403 Forbidden"))
  168. }
  169. return
  170. }
  171. //Check the given file is actually agi script
  172. if !(filepath.Ext(scriptFile) == ".agi" || filepath.Ext(scriptFile) == ".js") {
  173. w.WriteHeader(http.StatusForbidden)
  174. if g.Option.BuildVersion == "development" {
  175. w.Write([]byte("AGI script must have file extension of .agi or .js"))
  176. } else {
  177. w.Write([]byte("403 Forbidden"))
  178. }
  179. return
  180. }
  181. //Get the content of the script
  182. scriptContentByte, _ := ioutil.ReadFile(scriptFile)
  183. scriptContent := string(scriptContentByte)
  184. g.ExecuteAGIScript(scriptContent, scriptFile, scriptScope, w, r, thisuser)
  185. }
  186. /*
  187. Executing the given AGI Script contents. Requires:
  188. scriptContent: The AGI command sequence
  189. scriptFile: The filepath of the script file
  190. scriptScope: The scope of the script file, aka the module base path
  191. w / r : Web request and response writer
  192. thisuser: userObject
  193. */
  194. func (g *Gateway) ExecuteAGIScript(scriptContent string, scriptFile string, scriptScope string, w http.ResponseWriter, r *http.Request, thisuser *user.User) {
  195. //Create a new vm for this request
  196. vm := otto.New()
  197. //Inject standard libs into the vm
  198. g.injectStandardLibs(vm, scriptFile, scriptScope)
  199. g.injectUserFunctions(vm, thisuser, w, r)
  200. //Detect cotent type
  201. contentType := r.Header.Get("Content-type")
  202. if strings.Contains(contentType, "application/json") {
  203. //For shitty people who use Angular
  204. body, _ := ioutil.ReadAll(r.Body)
  205. vm.Set("POST_data", string(body))
  206. } else {
  207. r.ParseForm()
  208. //Insert all paramters into the vm
  209. for k, v := range r.PostForm {
  210. if len(v) == 1 {
  211. vm.Set(k, v[0])
  212. } else {
  213. vm.Set(k, v)
  214. }
  215. }
  216. }
  217. _, err := vm.Run(scriptContent)
  218. if err != nil {
  219. scriptpath, _ := filepath.Abs(scriptFile)
  220. g.RenderErrorTemplate(w, err.Error(), scriptpath)
  221. return
  222. }
  223. //Get the return valu from the script
  224. value, err := vm.Get("HTTP_RESP")
  225. if err != nil {
  226. sendTextResponse(w, "")
  227. return
  228. }
  229. valueString, err := value.ToString()
  230. //Get respond header type from the vm
  231. header, _ := vm.Get("HTTP_HEADER")
  232. headerString, _ := header.ToString()
  233. if headerString != "" {
  234. w.Header().Set("Content-Type", headerString)
  235. }
  236. w.Write([]byte(valueString))
  237. }
  238. /*
  239. Execute AGI script with given user information
  240. */
  241. func (g *Gateway) ExecuteAGIScriptAsUser(scriptFile string, targetUser *user.User) (string, error) {
  242. //Create a new vm for this request
  243. vm := otto.New()
  244. //Inject standard libs into the vm
  245. g.injectStandardLibs(vm, scriptFile, "")
  246. g.injectUserFunctions(vm, targetUser, nil, nil)
  247. //Try to read the script content
  248. scriptContent, err := ioutil.ReadFile(scriptFile)
  249. if err != nil {
  250. return "", err
  251. }
  252. _, err = vm.Run(scriptContent)
  253. if err != nil {
  254. return "", err
  255. }
  256. //Get the return valu from the script
  257. value, err := vm.Get("HTTP_RESP")
  258. if err != nil {
  259. return "", err
  260. }
  261. valueString, err := value.ToString()
  262. return valueString, nil
  263. }