agi.go 10 KB

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