agi.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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. log.Println("[Remote AGI] IP:", r.RemoteAddr, " executed the script ", pathFromDb, "(", realPath, ")", " on behalf of", userInfo.Username)
  233. // execute!
  234. g.ExecuteAGIScript(scriptContent, "", "", w, r, userInfo)
  235. }
  236. //Handle user requests
  237. func (g *Gateway) InterfaceHandler(w http.ResponseWriter, r *http.Request, thisuser *user.User) {
  238. //Get user object from the request
  239. startupRoot := g.Option.StartupRoot
  240. startupRoot = filepath.ToSlash(filepath.Clean(startupRoot))
  241. //Get the script files for the plugin
  242. scriptFile, err := mv(r, "script", false)
  243. if err != nil {
  244. sendErrorResponse(w, "Invalid script path")
  245. return
  246. }
  247. scriptFile = specialURIDecode(scriptFile)
  248. //Check if the script path exists
  249. scriptExists := false
  250. scriptScope := "./web/"
  251. for _, thisScope := range g.Option.ActivateScope {
  252. thisScope = filepath.ToSlash(filepath.Clean(thisScope))
  253. if fileExists(thisScope + "/" + scriptFile) {
  254. scriptExists = true
  255. scriptFile = thisScope + "/" + scriptFile
  256. scriptScope = thisScope
  257. }
  258. }
  259. if !scriptExists {
  260. sendErrorResponse(w, "Script not found")
  261. return
  262. }
  263. //Check for user permission on this module
  264. moduleName := getScriptRoot(scriptFile, scriptScope)
  265. if !thisuser.GetModuleAccessPermission(moduleName) {
  266. w.WriteHeader(http.StatusForbidden)
  267. if g.Option.BuildVersion == "development" {
  268. w.Write([]byte("Permission denied: User do not have permission to access " + moduleName))
  269. } else {
  270. w.Write([]byte("403 Forbidden"))
  271. }
  272. return
  273. }
  274. //Check the given file is actually agi script
  275. if !(filepath.Ext(scriptFile) == ".agi" || filepath.Ext(scriptFile) == ".js") {
  276. w.WriteHeader(http.StatusForbidden)
  277. if g.Option.BuildVersion == "development" {
  278. w.Write([]byte("AGI script must have file extension of .agi or .js"))
  279. } else {
  280. w.Write([]byte("403 Forbidden"))
  281. }
  282. return
  283. }
  284. //Get the content of the script
  285. scriptContentByte, _ := ioutil.ReadFile(scriptFile)
  286. scriptContent := string(scriptContentByte)
  287. g.ExecuteAGIScript(scriptContent, scriptFile, scriptScope, w, r, thisuser)
  288. }
  289. /*
  290. Executing the given AGI Script contents. Requires:
  291. scriptContent: The AGI command sequence
  292. scriptFile: The filepath of the script file
  293. scriptScope: The scope of the script file, aka the module base path
  294. w / r : Web request and response writer
  295. thisuser: userObject
  296. */
  297. func (g *Gateway) ExecuteAGIScript(scriptContent string, scriptFile string, scriptScope string, w http.ResponseWriter, r *http.Request, thisuser *user.User) {
  298. //Create a new vm for this request
  299. vm := otto.New()
  300. //Inject standard libs into the vm
  301. g.injectStandardLibs(vm, scriptFile, scriptScope)
  302. g.injectUserFunctions(vm, scriptFile, scriptScope, thisuser, w, r)
  303. //Detect cotent type
  304. contentType := r.Header.Get("Content-type")
  305. if strings.Contains(contentType, "application/json") {
  306. //For shitty people who use Angular
  307. body, _ := ioutil.ReadAll(r.Body)
  308. fields := map[string]interface{}{}
  309. json.Unmarshal(body, &fields)
  310. for k, v := range fields {
  311. vm.Set(k, v)
  312. }
  313. vm.Set("POST_data", string(body))
  314. } else {
  315. r.ParseForm()
  316. //Insert all paramters into the vm
  317. for k, v := range r.PostForm {
  318. if len(v) == 1 {
  319. vm.Set(k, v[0])
  320. } else {
  321. vm.Set(k, v)
  322. }
  323. }
  324. }
  325. _, err := vm.Run(scriptContent)
  326. if err != nil {
  327. scriptpath, _ := filepath.Abs(scriptFile)
  328. g.RenderErrorTemplate(w, err.Error(), scriptpath)
  329. return
  330. }
  331. //Get the return valu from the script
  332. value, err := vm.Get("HTTP_RESP")
  333. if err != nil {
  334. sendTextResponse(w, "")
  335. return
  336. }
  337. valueString, err := value.ToString()
  338. //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. w.Write([]byte(valueString))
  345. }
  346. /*
  347. Execute AGI script with given user information
  348. */
  349. func (g *Gateway) ExecuteAGIScriptAsUser(scriptFile string, targetUser *user.User) (string, error) {
  350. //Create a new vm for this request
  351. vm := otto.New()
  352. //Inject standard libs into the vm
  353. g.injectStandardLibs(vm, scriptFile, "")
  354. g.injectUserFunctions(vm, scriptFile, "", targetUser, nil, nil)
  355. //Inject interrupt Channel
  356. vm.Interrupt = make(chan func(), 1)
  357. //Create a panic recovery logic
  358. defer func() {
  359. if caught := recover(); caught != nil {
  360. if caught == timelimit {
  361. log.Println("[AGI] Execution timeout: " + scriptFile)
  362. return
  363. } else if caught == exitcall {
  364. //Exit gracefully
  365. return
  366. } else {
  367. panic(caught)
  368. }
  369. }
  370. }()
  371. //Create a max runtime of 5 minutes
  372. go func() {
  373. time.Sleep(300 * time.Second) // Stop after 300 seconds
  374. vm.Interrupt <- func() {
  375. panic(timelimit)
  376. }
  377. }()
  378. //Try to read the script content
  379. scriptContent, err := ioutil.ReadFile(scriptFile)
  380. if err != nil {
  381. return "", err
  382. }
  383. _, err = vm.Run(scriptContent)
  384. if err != nil {
  385. return "", err
  386. }
  387. //Get the return value from the script
  388. value, err := vm.Get("HTTP_RESP")
  389. if err != nil {
  390. return "", err
  391. }
  392. valueString, err := value.ToString()
  393. return valueString, nil
  394. }
  395. /*
  396. Get user specific tmp filepath for buffering remote file. Return filepath and closer
  397. tempFilepath, closerFunction := g.getUserSpecificTempFilePath(u, "myfile.txt")
  398. //Do something with it, after done
  399. closerFunction();
  400. */
  401. func (g *Gateway) getUserSpecificTempFilePath(u *user.User, filename string) (string, func()) {
  402. uuid := uuid.NewV4().String()
  403. tmpFileLocation := filepath.Join(g.Option.TempFolderPath, "agiBuff", u.Username, uuid, filepath.Base(filename))
  404. os.MkdirAll(filepath.Dir(tmpFileLocation), 0775)
  405. return tmpFileLocation, func() {
  406. os.RemoveAll(filepath.Dir(tmpFileLocation))
  407. }
  408. }
  409. /*
  410. Buffer remote reosurces to local by fsh and rpath. Return buffer filepath on local device and its closer function
  411. */
  412. func (g *Gateway) bufferRemoteResourcesToLocal(fsh *filesystem.FileSystemHandler, u *user.User, rpath string) (string, func(), error) {
  413. buffFile, closerFunc := g.getUserSpecificTempFilePath(u, rpath)
  414. f, err := fsh.FileSystemAbstraction.ReadStream(rpath)
  415. if err != nil {
  416. return "", nil, err
  417. }
  418. defer f.Close()
  419. dest, err := os.OpenFile(buffFile, os.O_CREATE|os.O_RDWR, 0775)
  420. if err != nil {
  421. return "", nil, err
  422. }
  423. io.Copy(dest, f)
  424. dest.Close()
  425. return buffFile, func() {
  426. closerFunc()
  427. }, nil
  428. }