agi.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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. utils.SendErrorResponse(w, "Invalid script path")
  176. return
  177. }
  178. scriptFile = static.SpecialURIDecode(scriptFile)
  179. //Check if the script path exists
  180. scriptExists := false
  181. scriptScope := "./web/"
  182. for _, thisScope := range g.Option.ActivateScope {
  183. thisScope = arozfs.ToSlash(filepath.Clean(thisScope))
  184. if utils.FileExists(arozfs.ToSlash(filepath.Join(thisScope, scriptFile))) {
  185. scriptExists = true
  186. scriptFile = arozfs.ToSlash(filepath.Join(thisScope, scriptFile))
  187. scriptScope = thisScope
  188. break
  189. }
  190. }
  191. if !scriptExists {
  192. utils.SendErrorResponse(w, "Script not found")
  193. return
  194. }
  195. //Check for user permission on this module
  196. moduleName := static.GetScriptRoot(scriptFile, scriptScope)
  197. if !thisuser.GetModuleAccessPermission(moduleName) {
  198. w.WriteHeader(http.StatusForbidden)
  199. if g.Option.BuildVersion == "development" {
  200. w.Write([]byte("Permission denied: User do not have permission to access " + moduleName))
  201. } else {
  202. w.Write([]byte("403 Forbidden"))
  203. }
  204. return
  205. }
  206. //Check the given file is actually agi script
  207. if !(filepath.Ext(scriptFile) == ".agi" || filepath.Ext(scriptFile) == ".js") {
  208. w.WriteHeader(http.StatusForbidden)
  209. if g.Option.BuildVersion == "development" {
  210. w.Write([]byte("AGI script must have file extension of .agi or .js"))
  211. } else {
  212. w.Write([]byte("403 Forbidden"))
  213. }
  214. return
  215. }
  216. //Get the content of the script
  217. scriptContentByte, err := os.ReadFile(scriptFile)
  218. if err != nil {
  219. w.Write([]byte("Script load error: " + err.Error()))
  220. return
  221. }
  222. scriptContent := string(scriptContentByte)
  223. g.ExecuteAGIScript(scriptContent, nil, scriptFile, scriptScope, w, r, thisuser)
  224. }
  225. /*
  226. Executing the given AGI Script contents. Requires:
  227. scriptContent: The AGI command sequence
  228. scriptFile: The filepath of the script file
  229. scriptScope: The scope of the script file, aka the module base path
  230. w / r : Web request and response writer
  231. thisuser: userObject
  232. */
  233. func (g *Gateway) ExecuteAGIScript(scriptContent string, fsh *filesystem.FileSystemHandler, scriptFile string, scriptScope string, w http.ResponseWriter, r *http.Request, thisuser *user.User) {
  234. //Create a new vm for this request
  235. vm := otto.New()
  236. //Inject standard libs into the vm
  237. g.injectStandardLibs(vm, scriptFile, scriptScope)
  238. g.injectUserFunctions(vm, fsh, scriptFile, scriptScope, thisuser, w, r)
  239. //Detect cotent type
  240. contentType := r.Header.Get("Content-type")
  241. if strings.Contains(contentType, "application/json") {
  242. //For people who use Angular
  243. body, _ := io.ReadAll(r.Body)
  244. fields := map[string]interface{}{}
  245. json.Unmarshal(body, &fields)
  246. for k, v := range fields {
  247. vm.Set(k, v)
  248. }
  249. vm.Set("POST_data", string(body))
  250. } else {
  251. r.ParseForm()
  252. //Insert all paramters into the vm
  253. for k, v := range r.PostForm {
  254. if len(v) == 1 {
  255. vm.Set(k, v[0])
  256. } else {
  257. vm.Set(k, v)
  258. }
  259. }
  260. }
  261. _, err := vm.Run(scriptContent)
  262. if err != nil {
  263. scriptpath, _ := filepath.Abs(scriptFile)
  264. g.RenderErrorTemplate(w, err.Error(), scriptpath)
  265. return
  266. }
  267. //Get the return valu from the script
  268. value, err := vm.Get("HTTP_RESP")
  269. if err != nil {
  270. utils.SendTextResponse(w, "")
  271. return
  272. }
  273. valueString, err := value.ToString()
  274. //Get respond header type from the vm
  275. header, _ := vm.Get("HTTP_HEADER")
  276. headerString, _ := header.ToString()
  277. if headerString != "" {
  278. w.Header().Set("Content-Type", headerString)
  279. }
  280. w.Write([]byte(valueString))
  281. }
  282. /*
  283. Execute AGI script with given user information
  284. scriptFile must be realpath resolved by fsa VirtualPathToRealPath function
  285. Pass in http.Request pointer to enable serverless GET / POST request
  286. */
  287. func (g *Gateway) ExecuteAGIScriptAsUser(fsh *filesystem.FileSystemHandler, scriptFile string, targetUser *user.User, w http.ResponseWriter, r *http.Request) (string, error) {
  288. //Create a new vm for this request
  289. vm := otto.New()
  290. //Inject standard libs into the vm
  291. g.injectStandardLibs(vm, scriptFile, "")
  292. g.injectUserFunctions(vm, fsh, scriptFile, "", targetUser, w, r)
  293. if r != nil {
  294. //Inject serverless script to enable access to GET / POST paramters
  295. g.injectServerlessFunctions(vm, scriptFile, "", targetUser, r)
  296. }
  297. //Inject interrupt Channel
  298. vm.Interrupt = make(chan func(), 1)
  299. //Create a panic recovery logic
  300. defer func() {
  301. if caught := recover(); caught != nil {
  302. if caught == errTimeout {
  303. log.Println("[AGI] Execution timeout: " + scriptFile)
  304. return
  305. } else if caught == errExitcall {
  306. //Exit gracefully
  307. return
  308. } else {
  309. //Something screwed. Return Internal Server Error
  310. w.WriteHeader(http.StatusInternalServerError)
  311. w.Write([]byte("500 - ECMA VM crashed due to unknown reason"))
  312. //panic(caught)
  313. }
  314. }
  315. }()
  316. //Create a max runtime of 5 minutes
  317. go func() {
  318. time.Sleep(300 * time.Second) // Stop after 300 seconds
  319. vm.Interrupt <- func() {
  320. panic(errTimeout)
  321. }
  322. }()
  323. //Try to read the script content
  324. scriptContent, err := fsh.FileSystemAbstraction.ReadFile(scriptFile)
  325. if err != nil {
  326. return "", err
  327. }
  328. _, err = vm.Run(scriptContent)
  329. if err != nil {
  330. return "", err
  331. }
  332. //Get the return value from the script
  333. value, err := vm.Get("HTTP_RESP")
  334. if err != nil {
  335. return "", err
  336. }
  337. if w != nil {
  338. //Serverless: Get respond header type from the vm
  339. header, _ := vm.Get("HTTP_HEADER")
  340. headerString, _ := header.ToString()
  341. if headerString != "" {
  342. w.Header().Set("Content-Type", headerString)
  343. }
  344. }
  345. valueString, err := value.ToString()
  346. if err != nil {
  347. return "", err
  348. }
  349. return valueString, nil
  350. }
  351. /*
  352. Get user specific tmp filepath for buffering remote file. Return filepath and closer
  353. tempFilepath, closerFunction := g.getUserSpecificTempFilePath(u, "myfile.txt")
  354. //Do something with it, after done
  355. closerFunction();
  356. */
  357. func (g *Gateway) getUserSpecificTempFilePath(u *user.User, filename string) (string, func()) {
  358. uuid := uuid.NewV4().String()
  359. tmpFileLocation := filepath.Join(g.Option.TempFolderPath, "agiBuff", u.Username, uuid, filepath.Base(filename))
  360. os.MkdirAll(filepath.Dir(tmpFileLocation), 0775)
  361. return tmpFileLocation, func() {
  362. os.RemoveAll(filepath.Dir(tmpFileLocation))
  363. }
  364. }
  365. /*
  366. Buffer remote reosurces to local by fsh and rpath. Return buffer filepath on local device and its closer function
  367. */
  368. func (g *Gateway) bufferRemoteResourcesToLocal(fsh *filesystem.FileSystemHandler, u *user.User, rpath string) (string, func(), error) {
  369. buffFile, closerFunc := g.getUserSpecificTempFilePath(u, rpath)
  370. f, err := fsh.FileSystemAbstraction.ReadStream(rpath)
  371. if err != nil {
  372. return "", nil, err
  373. }
  374. defer f.Close()
  375. dest, err := os.OpenFile(buffFile, os.O_CREATE|os.O_RDWR, 0775)
  376. if err != nil {
  377. return "", nil, err
  378. }
  379. io.Copy(dest, f)
  380. dest.Close()
  381. return buffFile, func() {
  382. closerFunc()
  383. }, nil
  384. }