agi.go 12 KB

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