agi.go 12 KB

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