agi.go 8.0 KB

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