agi.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. package agi
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "io"
  6. "log"
  7. "net/http"
  8. "os"
  9. "path/filepath"
  10. "strings"
  11. "time"
  12. "github.com/robertkrimen/otto"
  13. uuid "github.com/satori/go.uuid"
  14. "imuslab.com/arozos/mod/agi/static"
  15. apt "imuslab.com/arozos/mod/apt"
  16. "imuslab.com/arozos/mod/filesystem"
  17. "imuslab.com/arozos/mod/filesystem/arozfs"
  18. metadata "imuslab.com/arozos/mod/filesystem/metadata"
  19. "imuslab.com/arozos/mod/iot"
  20. "imuslab.com/arozos/mod/share"
  21. "imuslab.com/arozos/mod/time/nightly"
  22. user "imuslab.com/arozos/mod/user"
  23. "imuslab.com/arozos/mod/utils"
  24. )
  25. /*
  26. ArOZ Online Javascript Gateway Interface (AGI)
  27. author: tobychui
  28. This script load plugins written in Javascript and run them in VM inside golang
  29. DO NOT CONFUSE PLUGIN WITH SUBSERVICE :))
  30. */
  31. var (
  32. AgiVersion string = "3.0" //Defination of the agi runtime version. Update this when new function is added
  33. //AGI Internal Error Standard
  34. errExitcall = errors.New("errExit")
  35. errTimeout = errors.New("errTimeout")
  36. )
  37. type AgiPackage struct {
  38. InitRoot string //The initialization of the root for the module that request this package
  39. }
  40. type AgiSysInfo struct {
  41. //System information
  42. BuildVersion string
  43. InternalVersion string
  44. LoadedModule []string
  45. //System Handlers
  46. UserHandler *user.UserHandler
  47. ReservedTables []string
  48. PackageManager *apt.AptPackageManager
  49. ModuleRegisterParser func(string) error
  50. FileSystemRender *metadata.RenderHandler
  51. IotManager *iot.Manager
  52. ShareManager *share.Manager
  53. NightlyManager *nightly.TaskManager
  54. //Scanning Roots
  55. StartupRoot string
  56. ActivateScope []string
  57. TempFolderPath string
  58. }
  59. type Gateway struct {
  60. ReservedTables []string
  61. NightlyScripts []string
  62. //AllowAccessPkgs map[string][]AgiPackage
  63. LoadedAGILibrary map[string]AgiLibInjectionIntergface
  64. Option *AgiSysInfo
  65. }
  66. func NewGateway(option AgiSysInfo) (*Gateway, error) {
  67. //Handle startup registration of ajgi modules
  68. gatewayObject := Gateway{
  69. ReservedTables: option.ReservedTables,
  70. NightlyScripts: []string{},
  71. //AllowAccessPkgs: map[string][]AgiPackage{},
  72. LoadedAGILibrary: map[string]AgiLibInjectionIntergface{},
  73. Option: &option,
  74. }
  75. //Start all WebApps Registration
  76. gatewayObject.InitiateAllWebAppModules()
  77. gatewayObject.RegisterNightlyOperations()
  78. //Load all the other libs entry points into the memoary
  79. gatewayObject.LoadAllFunctionalModules()
  80. return &gatewayObject, nil
  81. }
  82. func (g *Gateway) RegisterNightlyOperations() {
  83. g.Option.NightlyManager.RegisterNightlyTask(func() {
  84. //This function will execute nightly
  85. for _, scriptFile := range g.NightlyScripts {
  86. if static.IsValidAGIScript(scriptFile) {
  87. //Valid script file. Execute it with system
  88. for _, username := range g.Option.UserHandler.GetAuthAgent().ListUsers() {
  89. userinfo, err := g.Option.UserHandler.GetUserInfoFromUsername(username)
  90. if err != nil {
  91. continue
  92. }
  93. if static.CheckUserAccessToScript(userinfo, scriptFile, "") {
  94. //This user can access the module that provide this script.
  95. //Execute this script on his account.
  96. log.Println("[AGI_Nightly] WIP (" + scriptFile + ")")
  97. }
  98. }
  99. } else {
  100. //Invalid script. Skipping
  101. log.Println("[AGI_Nightly] Invalid script file: " + scriptFile)
  102. }
  103. }
  104. })
  105. }
  106. func (g *Gateway) InitiateAllWebAppModules() {
  107. startupScripts, _ := filepath.Glob(filepath.ToSlash(filepath.Clean(g.Option.StartupRoot)) + "/*/init.agi")
  108. for _, script := range startupScripts {
  109. scriptContentByte, _ := os.ReadFile(script)
  110. scriptContent := string(scriptContentByte)
  111. log.Println("[AGI] Gateway script loaded (" + script + ")")
  112. //Create a new vm for this request
  113. vm := otto.New()
  114. //Only allow non user based operations
  115. g.injectStandardLibs(vm, script, "./web/")
  116. g.injectAppdataLibFunctions(&static.AgiLibInjectionPayload{
  117. VM: vm,
  118. })
  119. _, err := vm.Run(scriptContent)
  120. if err != nil {
  121. log.Println("[AGI] Load Failed: " + script + ". Skipping.")
  122. log.Println(err)
  123. continue
  124. }
  125. }
  126. }
  127. func (g *Gateway) RunScript(script string) error {
  128. //Create a new vm for this request
  129. vm := otto.New()
  130. //Only allow non user based operations
  131. g.injectStandardLibs(vm, "", "./web/")
  132. _, err := vm.Run(script)
  133. if err != nil {
  134. log.Println("[AGI] Script Execution Failed: ", err.Error())
  135. return err
  136. }
  137. return nil
  138. }
  139. func (g *Gateway) RaiseError(err error) {
  140. log.Println("[AGI] Runtime Error " + err.Error())
  141. //To be implemented
  142. }
  143. // Check if this table is restricted table. Return true if the access is valid
  144. func (g *Gateway) filterDBTable(tablename string, existsCheck bool) bool {
  145. //Check if table is restricted
  146. if utils.StringInArray(g.ReservedTables, tablename) {
  147. return false
  148. }
  149. //Check if table exists
  150. if existsCheck {
  151. if !g.Option.UserHandler.GetDatabase().TableExists(tablename) {
  152. return false
  153. }
  154. }
  155. return true
  156. }
  157. // Handle request from RESTFUL API
  158. func (g *Gateway) APIHandler(w http.ResponseWriter, r *http.Request, thisuser *user.User) {
  159. scriptContent, err := utils.PostPara(r, "script")
  160. if err != nil {
  161. w.WriteHeader(http.StatusBadRequest)
  162. w.Write([]byte("400 - Bad Request (Missing script content)"))
  163. return
  164. }
  165. g.ExecuteAGIScript(scriptContent, nil, "", "", w, r, thisuser)
  166. }
  167. // Handle user requests
  168. func (g *Gateway) InterfaceHandler(w http.ResponseWriter, r *http.Request, thisuser *user.User) {
  169. //Get user object from the request
  170. //startupRoot := g.Option.StartupRoot
  171. //startupRoot = filepath.ToSlash(filepath.Clean(startupRoot))
  172. //Get the script files for the plugin
  173. scriptFile, err := utils.GetPara(r, "script")
  174. if err != nil {
  175. w.WriteHeader(http.StatusInternalServerError)
  176. w.Write([]byte("500 - Internal Server Error: Invalid script path"))
  177. return
  178. }
  179. scriptFile = static.SpecialURIDecode(scriptFile)
  180. //Check if the script path exists
  181. scriptExists := false
  182. scriptScope := "./web/"
  183. for _, thisScope := range g.Option.ActivateScope {
  184. thisScope = arozfs.ToSlash(filepath.Clean(thisScope))
  185. if utils.FileExists(arozfs.ToSlash(filepath.Join(thisScope, scriptFile))) {
  186. scriptExists = true
  187. scriptFile = arozfs.ToSlash(filepath.Join(thisScope, scriptFile))
  188. scriptScope = thisScope
  189. break
  190. }
  191. }
  192. if !scriptExists {
  193. w.WriteHeader(http.StatusInternalServerError)
  194. w.Write([]byte("500 - Internal Server Error: Script not exists"))
  195. return
  196. }
  197. //Check for user permission on this module
  198. moduleName := static.GetScriptRoot(scriptFile, scriptScope)
  199. if !thisuser.GetModuleAccessPermission(moduleName) {
  200. w.WriteHeader(http.StatusForbidden)
  201. if g.Option.BuildVersion == "development" {
  202. w.Write([]byte("403 Forbidden: User do not have permission to access " + moduleName))
  203. } else {
  204. w.Write([]byte("403 Forbidden"))
  205. }
  206. return
  207. }
  208. //Check the given file is actually agi script
  209. if !(filepath.Ext(scriptFile) == ".agi" || filepath.Ext(scriptFile) == ".js") {
  210. w.WriteHeader(http.StatusForbidden)
  211. if g.Option.BuildVersion == "development" {
  212. w.Write([]byte("AGI script must have file extension of .agi or .js"))
  213. } else {
  214. w.Write([]byte("403 Forbidden"))
  215. }
  216. return
  217. }
  218. //Get the content of the script
  219. scriptContentByte, err := os.ReadFile(scriptFile)
  220. if err != nil {
  221. w.WriteHeader(http.StatusInternalServerError)
  222. w.Write([]byte("500 - Internal Server Error: Script load error =>" + err.Error()))
  223. return
  224. }
  225. scriptContent := string(scriptContentByte)
  226. g.ExecuteAGIScript(scriptContent, nil, scriptFile, scriptScope, w, r, thisuser)
  227. }
  228. /*
  229. Executing the given AGI Script contents. Requires:
  230. scriptContent: The AGI command sequence
  231. scriptFile: The filepath of the script file
  232. scriptScope: The scope of the script file, aka the module base path
  233. w / r : Web request and response writer
  234. thisuser: userObject
  235. */
  236. func (g *Gateway) ExecuteAGIScript(scriptContent string, fsh *filesystem.FileSystemHandler, scriptFile string, scriptScope string, w http.ResponseWriter, r *http.Request, thisuser *user.User) {
  237. //Create a new vm for this request
  238. vm := otto.New()
  239. //Inject standard libs into the vm
  240. g.injectStandardLibs(vm, scriptFile, scriptScope)
  241. g.injectUserFunctions(vm, fsh, scriptFile, scriptScope, thisuser, w, r)
  242. //Detect cotent type
  243. contentType := r.Header.Get("Content-type")
  244. if strings.Contains(contentType, "application/json") {
  245. //For people who use Angular
  246. body, _ := io.ReadAll(r.Body)
  247. fields := map[string]interface{}{}
  248. json.Unmarshal(body, &fields)
  249. for k, v := range fields {
  250. vm.Set(k, v)
  251. }
  252. vm.Set("POST_data", string(body))
  253. } else {
  254. r.ParseForm()
  255. //Insert all paramters into the vm
  256. for k, v := range r.PostForm {
  257. if len(v) == 1 {
  258. vm.Set(k, v[0])
  259. } else {
  260. vm.Set(k, v)
  261. }
  262. }
  263. }
  264. _, err := vm.Run(scriptContent)
  265. if err != nil {
  266. scriptpath, _ := filepath.Abs(scriptFile)
  267. g.RenderErrorTemplate(w, err.Error(), scriptpath)
  268. return
  269. }
  270. //Get the return valu from the script
  271. value, err := vm.Get("HTTP_RESP")
  272. if err != nil {
  273. utils.SendTextResponse(w, "")
  274. return
  275. }
  276. valueString, err := value.ToString()
  277. //Get respond header type from the vm
  278. header, _ := vm.Get("HTTP_HEADER")
  279. headerString, _ := header.ToString()
  280. if headerString != "" {
  281. w.Header().Set("Content-Type", headerString)
  282. }
  283. w.Write([]byte(valueString))
  284. }
  285. /*
  286. Execute AGI script with given user information
  287. scriptFile must be realpath resolved by fsa VirtualPathToRealPath function
  288. Pass in http.Request pointer to enable serverless GET / POST request
  289. */
  290. func (g *Gateway) ExecuteAGIScriptAsUser(fsh *filesystem.FileSystemHandler, scriptFile string, targetUser *user.User, w http.ResponseWriter, r *http.Request) (string, error) {
  291. //Create a new vm for this request
  292. vm := otto.New()
  293. //Inject standard libs into the vm
  294. g.injectStandardLibs(vm, scriptFile, "")
  295. g.injectUserFunctions(vm, fsh, scriptFile, "", targetUser, w, r)
  296. if r != nil {
  297. //Inject serverless script to enable access to GET / POST paramters
  298. g.injectServerlessFunctions(vm, scriptFile, "", targetUser, r)
  299. }
  300. //Inject interrupt Channel
  301. vm.Interrupt = make(chan func(), 1)
  302. //Create a panic recovery logic
  303. defer func() {
  304. if caught := recover(); caught != nil {
  305. if caught == errTimeout {
  306. log.Println("[AGI] Execution timeout: " + scriptFile)
  307. return
  308. } else if caught == errExitcall {
  309. //Exit gracefully
  310. return
  311. } else {
  312. //Something screwed. Return Internal Server Error
  313. w.WriteHeader(http.StatusInternalServerError)
  314. w.Write([]byte("500 - ECMA VM crashed due to unknown reason"))
  315. //panic(caught)
  316. }
  317. }
  318. }()
  319. //Create a max runtime of 5 minutes
  320. go func() {
  321. time.Sleep(300 * time.Second) // Stop after 300 seconds
  322. vm.Interrupt <- func() {
  323. panic(errTimeout)
  324. }
  325. }()
  326. //Try to read the script content
  327. scriptContent, err := fsh.FileSystemAbstraction.ReadFile(scriptFile)
  328. if err != nil {
  329. return "", err
  330. }
  331. _, err = vm.Run(scriptContent)
  332. if err != nil {
  333. return "", err
  334. }
  335. //Get the return value from the script
  336. value, err := vm.Get("HTTP_RESP")
  337. if err != nil {
  338. return "", err
  339. }
  340. if w != nil {
  341. //Serverless: Get respond header type from the vm
  342. header, _ := vm.Get("HTTP_HEADER")
  343. headerString, _ := header.ToString()
  344. if headerString != "" {
  345. w.Header().Set("Content-Type", headerString)
  346. }
  347. }
  348. valueString, err := value.ToString()
  349. if err != nil {
  350. return "", err
  351. }
  352. return valueString, nil
  353. }
  354. /*
  355. Get user specific tmp filepath for buffering remote file. Return filepath and closer
  356. tempFilepath, closerFunction := g.getUserSpecificTempFilePath(u, "myfile.txt")
  357. //Do something with it, after done
  358. closerFunction();
  359. */
  360. func (g *Gateway) getUserSpecificTempFilePath(u *user.User, filename string) (string, func()) {
  361. uuid := uuid.NewV4().String()
  362. tmpFileLocation := filepath.Join(g.Option.TempFolderPath, "agiBuff", u.Username, uuid, filepath.Base(filename))
  363. os.MkdirAll(filepath.Dir(tmpFileLocation), 0775)
  364. return tmpFileLocation, func() {
  365. os.RemoveAll(filepath.Dir(tmpFileLocation))
  366. }
  367. }
  368. /*
  369. Buffer remote reosurces to local by fsh and rpath. Return buffer filepath on local device and its closer function
  370. */
  371. func (g *Gateway) bufferRemoteResourcesToLocal(fsh *filesystem.FileSystemHandler, u *user.User, rpath string) (string, func(), error) {
  372. buffFile, closerFunc := g.getUserSpecificTempFilePath(u, rpath)
  373. f, err := fsh.FileSystemAbstraction.ReadStream(rpath)
  374. if err != nil {
  375. return "", nil, err
  376. }
  377. defer f.Close()
  378. dest, err := os.OpenFile(buffFile, os.O_CREATE|os.O_RDWR, 0775)
  379. if err != nil {
  380. return "", nil, err
  381. }
  382. io.Copy(dest, f)
  383. dest.Close()
  384. return buffFile, func() {
  385. closerFunc()
  386. }, nil
  387. }