agi.go 8.3 KB

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