agi.go 12 KB

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