agi.go 8.3 KB

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