agi.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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. "reflect"
  12. "strings"
  13. "time"
  14. "github.com/robertkrimen/otto"
  15. uuid "github.com/satori/go.uuid"
  16. apt "imuslab.com/arozos/mod/apt"
  17. "imuslab.com/arozos/mod/common"
  18. "imuslab.com/arozos/mod/filesystem"
  19. metadata "imuslab.com/arozos/mod/filesystem/metadata"
  20. "imuslab.com/arozos/mod/iot"
  21. "imuslab.com/arozos/mod/share"
  22. "imuslab.com/arozos/mod/time/nightly"
  23. user "imuslab.com/arozos/mod/user"
  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 = "2.0" //Defination of the agi runtime version. Update this when new function is added
  33. //AGI Internal Error Standard
  34. exitcall = errors.New("Exit")
  35. timelimit = errors.New("Timelimit")
  36. )
  37. type AgiLibIntergface func(*otto.Otto, *user.User) //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 stringInSlice(tablename, g.ReservedTables) {
  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 := 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, "", "", w, r, thisuser)
  179. }
  180. //Handle request from RESTFUL API
  181. func (g *Gateway) ExtAPIHandler(w http.ResponseWriter, r *http.Request) {
  182. // obtain all information from "DB" aka our json file
  183. // this should be either db or in the constructor instead for production
  184. var db map[string]map[string]string
  185. jsonFile, err := os.Open("lambda.json")
  186. if err != nil {
  187. common.SendErrorResponse(w, "Bad config")
  188. return
  189. }
  190. jsonStr, err := ioutil.ReadAll(jsonFile)
  191. if err != nil {
  192. common.SendErrorResponse(w, "Bad config")
  193. return
  194. }
  195. json.Unmarshal([]byte(jsonStr), &db)
  196. defer jsonFile.Close()
  197. // end of our DB
  198. // get the request URI from the r.URL
  199. requestURI := filepath.ToSlash(filepath.Clean(r.URL.Path))
  200. subpathElements := strings.Split(requestURI[1:], "/")
  201. // check if it contains only two part, [rexec uuid]
  202. if len(subpathElements) != 2 {
  203. common.SendErrorResponse(w, "Bad Request, invaild request sent")
  204. return
  205. }
  206. // check if UUID exists in the database
  207. if db[subpathElements[1]] == nil || reflect.ValueOf(db[subpathElements[1]]).IsNil() {
  208. common.SendErrorResponse(w, "Bad Request, invaild UUID entered")
  209. return
  210. }
  211. // get the info from the database
  212. usernameFromDb := db[subpathElements[1]]["username"]
  213. pathFromDb := db[subpathElements[1]]["path"]
  214. // get the userinfo and the realPath
  215. userInfo, err := g.Option.UserHandler.GetUserInfoFromUsername(usernameFromDb)
  216. if err != nil {
  217. common.SendErrorResponse(w, "Bad username")
  218. return
  219. }
  220. _, realPath, err := virtualPathToRealPath(pathFromDb, userInfo)
  221. if err != nil {
  222. common.SendErrorResponse(w, "Bad filepath")
  223. return
  224. }
  225. // read the file and store it into scriptContent
  226. scriptContentByte, err := ioutil.ReadFile(realPath)
  227. if err != nil {
  228. common.SendErrorResponse(w, "Bad file I/O")
  229. return
  230. }
  231. scriptContent := string(scriptContentByte)
  232. // execute!
  233. start := time.Now()
  234. g.ExecuteAGIScript(scriptContent, "", "", w, r, userInfo)
  235. duration := time.Since(start)
  236. log.Println("[Remote AGI] IP:", r.RemoteAddr, " executed the script ", pathFromDb, "(", realPath, ")", " on behalf of", userInfo.Username, "with total duration: ", duration)
  237. }
  238. //Handle user requests
  239. func (g *Gateway) InterfaceHandler(w http.ResponseWriter, r *http.Request, thisuser *user.User) {
  240. //Get user object from the request
  241. startupRoot := g.Option.StartupRoot
  242. startupRoot = filepath.ToSlash(filepath.Clean(startupRoot))
  243. //Get the script files for the plugin
  244. scriptFile, err := mv(r, "script", false)
  245. if err != nil {
  246. sendErrorResponse(w, "Invalid script path")
  247. return
  248. }
  249. scriptFile = specialURIDecode(scriptFile)
  250. //Check if the script path exists
  251. scriptExists := false
  252. scriptScope := "./web/"
  253. for _, thisScope := range g.Option.ActivateScope {
  254. thisScope = filepath.ToSlash(filepath.Clean(thisScope))
  255. if fileExists(thisScope + "/" + scriptFile) {
  256. scriptExists = true
  257. scriptFile = thisScope + "/" + scriptFile
  258. scriptScope = thisScope
  259. }
  260. }
  261. if !scriptExists {
  262. sendErrorResponse(w, "Script not found")
  263. return
  264. }
  265. //Check for user permission on this module
  266. moduleName := getScriptRoot(scriptFile, scriptScope)
  267. if !thisuser.GetModuleAccessPermission(moduleName) {
  268. w.WriteHeader(http.StatusForbidden)
  269. if g.Option.BuildVersion == "development" {
  270. w.Write([]byte("Permission denied: User do not have permission to access " + moduleName))
  271. } else {
  272. w.Write([]byte("403 Forbidden"))
  273. }
  274. return
  275. }
  276. //Check the given file is actually agi script
  277. if !(filepath.Ext(scriptFile) == ".agi" || filepath.Ext(scriptFile) == ".js") {
  278. w.WriteHeader(http.StatusForbidden)
  279. if g.Option.BuildVersion == "development" {
  280. w.Write([]byte("AGI script must have file extension of .agi or .js"))
  281. } else {
  282. w.Write([]byte("403 Forbidden"))
  283. }
  284. return
  285. }
  286. //Get the content of the script
  287. scriptContentByte, _ := ioutil.ReadFile(scriptFile)
  288. scriptContent := string(scriptContentByte)
  289. g.ExecuteAGIScript(scriptContent, scriptFile, scriptScope, w, r, thisuser)
  290. }
  291. /*
  292. Executing the given AGI Script contents. Requires:
  293. scriptContent: The AGI command sequence
  294. scriptFile: The filepath of the script file
  295. scriptScope: The scope of the script file, aka the module base path
  296. w / r : Web request and response writer
  297. thisuser: userObject
  298. */
  299. func (g *Gateway) ExecuteAGIScript(scriptContent string, scriptFile string, scriptScope string, w http.ResponseWriter, r *http.Request, thisuser *user.User) {
  300. //Create a new vm for this request
  301. vm := otto.New()
  302. //Inject standard libs into the vm
  303. g.injectStandardLibs(vm, scriptFile, scriptScope)
  304. g.injectUserFunctions(vm, scriptFile, scriptScope, thisuser, w, r)
  305. //Detect cotent type
  306. contentType := r.Header.Get("Content-type")
  307. if strings.Contains(contentType, "application/json") {
  308. //For shitty people who use Angular
  309. body, _ := ioutil.ReadAll(r.Body)
  310. fields := map[string]interface{}{}
  311. json.Unmarshal(body, &fields)
  312. for k, v := range fields {
  313. vm.Set(k, v)
  314. }
  315. vm.Set("POST_data", string(body))
  316. } else {
  317. r.ParseForm()
  318. //Insert all paramters into the vm
  319. for k, v := range r.PostForm {
  320. if len(v) == 1 {
  321. vm.Set(k, v[0])
  322. } else {
  323. vm.Set(k, v)
  324. }
  325. }
  326. }
  327. _, err := vm.Run(scriptContent)
  328. if err != nil {
  329. scriptpath, _ := filepath.Abs(scriptFile)
  330. g.RenderErrorTemplate(w, err.Error(), scriptpath)
  331. return
  332. }
  333. //Get the return valu from the script
  334. value, err := vm.Get("HTTP_RESP")
  335. if err != nil {
  336. sendTextResponse(w, "")
  337. return
  338. }
  339. valueString, err := value.ToString()
  340. //Get respond header type from the vm
  341. header, _ := vm.Get("HTTP_HEADER")
  342. headerString, _ := header.ToString()
  343. if headerString != "" {
  344. w.Header().Set("Content-Type", headerString)
  345. }
  346. w.Write([]byte(valueString))
  347. }
  348. /*
  349. Execute AGI script with given user information
  350. */
  351. func (g *Gateway) ExecuteAGIScriptAsUser(scriptFile string, targetUser *user.User) (string, error) {
  352. //Create a new vm for this request
  353. vm := otto.New()
  354. //Inject standard libs into the vm
  355. g.injectStandardLibs(vm, scriptFile, "")
  356. g.injectUserFunctions(vm, scriptFile, "", targetUser, nil, nil)
  357. //Inject interrupt Channel
  358. vm.Interrupt = make(chan func(), 1)
  359. //Create a panic recovery logic
  360. defer func() {
  361. if caught := recover(); caught != nil {
  362. if caught == timelimit {
  363. log.Println("[AGI] Execution timeout: " + scriptFile)
  364. return
  365. } else if caught == exitcall {
  366. //Exit gracefully
  367. return
  368. } else {
  369. panic(caught)
  370. }
  371. }
  372. }()
  373. //Create a max runtime of 5 minutes
  374. go func() {
  375. time.Sleep(300 * time.Second) // Stop after 300 seconds
  376. vm.Interrupt <- func() {
  377. panic(timelimit)
  378. }
  379. }()
  380. //Try to read the script content
  381. scriptContent, err := ioutil.ReadFile(scriptFile)
  382. if err != nil {
  383. return "", err
  384. }
  385. _, err = vm.Run(scriptContent)
  386. if err != nil {
  387. return "", err
  388. }
  389. //Get the return value from the script
  390. value, err := vm.Get("HTTP_RESP")
  391. if err != nil {
  392. return "", err
  393. }
  394. valueString, err := value.ToString()
  395. return valueString, nil
  396. }
  397. /*
  398. Get user specific tmp filepath for buffering remote file. Return filepath and closer
  399. tempFilepath, closerFunction := g.getUserSpecificTempFilePath(u, "myfile.txt")
  400. //Do something with it, after done
  401. closerFunction();
  402. */
  403. func (g *Gateway) getUserSpecificTempFilePath(u *user.User, filename string) (string, func()) {
  404. uuid := uuid.NewV4().String()
  405. tmpFileLocation := filepath.Join(g.Option.TempFolderPath, "agiBuff", u.Username, uuid, filepath.Base(filename))
  406. os.MkdirAll(filepath.Dir(tmpFileLocation), 0775)
  407. return tmpFileLocation, func() {
  408. os.RemoveAll(filepath.Dir(tmpFileLocation))
  409. }
  410. }
  411. /*
  412. Buffer remote reosurces to local by fsh and rpath. Return buffer filepath on local device and its closer function
  413. */
  414. func (g *Gateway) bufferRemoteResourcesToLocal(fsh *filesystem.FileSystemHandler, u *user.User, rpath string) (string, func(), error) {
  415. buffFile, closerFunc := g.getUserSpecificTempFilePath(u, rpath)
  416. f, err := fsh.FileSystemAbstraction.ReadStream(rpath)
  417. if err != nil {
  418. return "", nil, err
  419. }
  420. defer f.Close()
  421. dest, err := os.OpenFile(buffFile, os.O_CREATE|os.O_RDWR, 0775)
  422. if err != nil {
  423. return "", nil, err
  424. }
  425. io.Copy(dest, f)
  426. dest.Close()
  427. return buffFile, func() {
  428. closerFunc()
  429. }, nil
  430. }