agi.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  1. package agi
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "os"
  9. "path/filepath"
  10. "strings"
  11. "sync"
  12. "time"
  13. "github.com/robertkrimen/otto"
  14. uuid "github.com/satori/go.uuid"
  15. "imuslab.com/arozos/mod/agi/static"
  16. apt "imuslab.com/arozos/mod/apt"
  17. "imuslab.com/arozos/mod/email"
  18. "imuslab.com/arozos/mod/filesystem"
  19. "imuslab.com/arozos/mod/filesystem/arozfs"
  20. metadata "imuslab.com/arozos/mod/filesystem/metadata"
  21. "imuslab.com/arozos/mod/git"
  22. "imuslab.com/arozos/mod/info/logger"
  23. "imuslab.com/arozos/mod/meetroom"
  24. notification "imuslab.com/arozos/mod/notification"
  25. "imuslab.com/arozos/mod/share"
  26. "imuslab.com/arozos/mod/sharedspace"
  27. "imuslab.com/arozos/mod/time/nightly"
  28. user "imuslab.com/arozos/mod/user"
  29. "imuslab.com/arozos/mod/utils"
  30. )
  31. /*
  32. ArOZ Online Javascript Gateway Interface (AGI)
  33. author: tobychui
  34. This script load plugins written in Javascript and run them in VM inside golang
  35. DO NOT CONFUSE PLUGIN WITH SUBSERVICE :))
  36. */
  37. var (
  38. AgiVersion string = "3.8" //Defination of the agi runtime version. Update this when new function is added
  39. //AGI Internal Error Standard
  40. errExitcall = errors.New("errExit")
  41. errTimeout = errors.New("errTimeout")
  42. // agiLogger is a stdout-only fallback used when no system-wide logger is
  43. // available. Scripts should use g.Option.Logger when present.
  44. agiLogger, _ = logger.NewTmpLogger()
  45. )
  46. type AgiPackage struct {
  47. InitRoot string //The initialization of the root for the module that request this package
  48. }
  49. type AgiSysInfo struct {
  50. //System information
  51. BuildVersion string
  52. InternalVersion string
  53. LoadedModule []string
  54. //System Handlers
  55. Logger *logger.Logger
  56. UserHandler *user.UserHandler
  57. ReservedTables []string
  58. PackageManager *apt.AptPackageManager
  59. ModuleRegisterParser func(sourceFolder string, jsonModuleConfig string) error //sourceFolder is the web app folder the init.agi lives in, e.g. "web/Office"
  60. ModuleFolderResolver func(folder string) []string //Returns the names of the modules registered from a source folder
  61. ScriptFolderDisabled func(folder string) bool //Reports whether every module of a source folder is switched off, can be nil
  62. ModuleListProvider func(username string) string //Returns JSON of accessible modules for a user
  63. ExtIconRegisterParser func(ext, iconPath string) //Called when registerExtensionIcon() fires in an init.agi
  64. FileSystemRender *metadata.RenderHandler
  65. ShareManager *share.Manager
  66. NightlyManager *nightly.TaskManager
  67. MeetRoomManager *meetroom.Manager //MeetRoom rooms for the meetroom lib (nil disables the lib)
  68. SharedSpaceManager *sharedspace.Manager //Shared collaboration spaces for the sharedspace lib (nil disables the lib)
  69. GitManager *git.Manager //Version control backend for the git lib (nil disables the lib)
  70. EmailManager *email.Manager //IMAP / SMTP mail client backend for the email lib (nil disables the lib)
  71. ClusterProvider ClusterProvider //Cluster namespace / events for the cluster lib (nil disables the lib)
  72. //NotificationSender routes a notification raised by an AGI script into the
  73. //ArozOS core notification system (nil disables the notification lib).
  74. NotificationSender func(*notification.NotificationPayload) error
  75. //Scanning Roots
  76. StartupRoot string
  77. ActivateScope []string
  78. TempFolderPath string
  79. }
  80. type Gateway struct {
  81. ReservedTables []string
  82. NightlyScripts []string
  83. //AllowAccessPkgs map[string][]AgiPackage
  84. LoadedAGILibrary map[string]AgiLibInjectionIntergface
  85. Option *AgiSysInfo
  86. endpointStats map[string]*EndpointStats // per-UUID execution statistics (in-memory)
  87. statsMux sync.RWMutex // guards endpointStats
  88. vmReg *vmRegistry // live VM lifecycle registry
  89. }
  90. func NewGateway(option AgiSysInfo) (*Gateway, error) {
  91. //Handle startup registration of ajgi modules
  92. gatewayObject := Gateway{
  93. ReservedTables: option.ReservedTables,
  94. NightlyScripts: []string{},
  95. LoadedAGILibrary: map[string]AgiLibInjectionIntergface{},
  96. Option: &option,
  97. endpointStats: make(map[string]*EndpointStats),
  98. vmReg: newVMRegistry(),
  99. }
  100. //Start all WebApps Registration
  101. gatewayObject.InitiateAllWebAppModules()
  102. gatewayObject.RegisterNightlyOperations()
  103. //Load all the other libs entry points into the memoary
  104. gatewayObject.LoadAllFunctionalModules()
  105. return &gatewayObject, nil
  106. }
  107. func (g *Gateway) RegisterNightlyOperations() {
  108. g.Option.NightlyManager.RegisterNightlyTask(func() {
  109. //This function will execute nightly
  110. for _, scriptFile := range g.NightlyScripts {
  111. if static.IsValidAGIScript(scriptFile) {
  112. //Valid script file. Execute it with system
  113. for _, username := range g.Option.UserHandler.GetAuthAgent().ListUsers() {
  114. userinfo, err := g.Option.UserHandler.GetUserInfoFromUsername(username)
  115. if err != nil {
  116. continue
  117. }
  118. if g.userCanRunScript(userinfo, filepath.Join("./web", scriptFile), "./web") {
  119. //This user can access the module that provide this script.
  120. //Execute this script on his account.
  121. logger.PrintAndLog("Agi", "[AGI_Nightly] WIP ("+scriptFile+")", nil)
  122. }
  123. }
  124. } else {
  125. //Invalid script. Skipping
  126. logger.PrintAndLog("Agi", "[AGI_Nightly] Invalid script file: "+scriptFile, nil)
  127. }
  128. }
  129. })
  130. }
  131. func (g *Gateway) InitiateAllWebAppModules() {
  132. startupScripts, _ := filepath.Glob(filepath.ToSlash(filepath.Clean(g.Option.StartupRoot)) + "/*/init.agi")
  133. for _, script := range startupScripts {
  134. err := g.RunWebAppInitScript(script)
  135. if err != nil {
  136. logger.PrintAndLog("Agi", "[AGI] Load Failed: "+script+". Skipping.", nil)
  137. logger.PrintAndLog("Agi", fmt.Sprint(err), nil)
  138. continue
  139. }
  140. }
  141. }
  142. // Run a web app's init.agi (e.g. "web/Office/init.agi") with system scope only.
  143. // The script path is what ties the modules it registers to their source folder.
  144. func (g *Gateway) RunWebAppInitScript(script string) error {
  145. scriptContentByte, err := os.ReadFile(script)
  146. if err != nil {
  147. return err
  148. }
  149. scriptContent := string(scriptContentByte)
  150. logger.PrintAndLog("Agi", "[AGI] Gateway script loaded ("+script+")", nil)
  151. //Create a new vm for this request
  152. vm := otto.New()
  153. //Only allow non user based operations
  154. g.injectStandardLibs(vm, script, "./web/")
  155. g.injectAppdataLibFunctions(&static.AgiLibInjectionPayload{
  156. VM: vm,
  157. })
  158. _, err = vm.Run(scriptContent)
  159. return err
  160. }
  161. // userCanRunScript checks that the user may use a module of the script's
  162. // folder, and that an admin has not switched all of that folder's modules off
  163. func (g *Gateway) userCanRunScript(thisuser *user.User, scriptFile string, scriptScope string) bool {
  164. if g.Option.ScriptFolderDisabled != nil {
  165. if folder := static.ScriptSourceFolder(scriptFile, scriptScope); folder != "" && g.Option.ScriptFolderDisabled(folder) {
  166. return false
  167. }
  168. }
  169. return static.CheckUserAccessToScript(thisuser, scriptFile, scriptScope, g.Option.ModuleFolderResolver)
  170. }
  171. func (g *Gateway) RaiseError(err error) {
  172. if err == nil {
  173. return
  174. }
  175. logger.PrintAndLog("Agi", "[AGI] Runtime Error "+err.Error(), nil)
  176. //To be implemented
  177. }
  178. // Check if this table is restricted table. Return true if the access is valid
  179. func (g *Gateway) filterDBTable(tablename string, existsCheck bool) bool {
  180. //Check if table is restricted
  181. if utils.StringInArray(g.ReservedTables, tablename) {
  182. return false
  183. }
  184. //Check if table exists
  185. if existsCheck {
  186. if !g.Option.UserHandler.GetDatabase().TableExists(tablename) {
  187. return false
  188. }
  189. }
  190. return true
  191. }
  192. // Handle request from RESTFUL API
  193. func (g *Gateway) APIHandler(w http.ResponseWriter, r *http.Request, thisuser *user.User) {
  194. scriptContent, err := utils.PostPara(r, "script")
  195. if err != nil {
  196. w.WriteHeader(http.StatusBadRequest)
  197. w.Write([]byte("400 - Bad Request (Missing script content)"))
  198. return
  199. }
  200. g.ExecuteAGIScript(scriptContent, nil, "", "", w, r, thisuser)
  201. }
  202. // Handle user requests
  203. func (g *Gateway) InterfaceHandler(w http.ResponseWriter, r *http.Request, thisuser *user.User) {
  204. //Get user object from the request
  205. //startupRoot := g.Option.StartupRoot
  206. //startupRoot = filepath.ToSlash(filepath.Clean(startupRoot))
  207. //Get the script files for the plugin
  208. scriptFile, err := utils.GetPara(r, "script")
  209. if err != nil {
  210. w.WriteHeader(http.StatusInternalServerError)
  211. w.Write([]byte("500 - Internal Server Error: Invalid script path"))
  212. return
  213. }
  214. scriptFile = static.SpecialURIDecode(scriptFile)
  215. //Check if the script path exists
  216. scriptExists := false
  217. scriptScope := "./web/"
  218. for _, thisScope := range g.Option.ActivateScope {
  219. thisScope = arozfs.ToSlash(filepath.Clean(thisScope))
  220. if utils.FileExists(arozfs.ToSlash(filepath.Join(thisScope, scriptFile))) {
  221. scriptExists = true
  222. scriptFile = arozfs.ToSlash(filepath.Join(thisScope, scriptFile))
  223. scriptScope = thisScope
  224. break
  225. }
  226. }
  227. if !scriptExists {
  228. w.WriteHeader(http.StatusInternalServerError)
  229. w.Write([]byte("500 - Internal Server Error: Script not exists"))
  230. return
  231. }
  232. //Check for user permission on this module
  233. if !g.userCanRunScript(thisuser, scriptFile, scriptScope) {
  234. moduleName := static.GetScriptRoot(scriptFile, scriptScope)
  235. w.WriteHeader(http.StatusForbidden)
  236. if g.Option.BuildVersion == "development" {
  237. w.Write([]byte("403 Forbidden: User do not have permission to access " + moduleName))
  238. } else {
  239. w.Write([]byte("403 Forbidden"))
  240. }
  241. return
  242. }
  243. //Check the given file is actually agi script
  244. if !(filepath.Ext(scriptFile) == ".agi" || filepath.Ext(scriptFile) == ".js") {
  245. w.WriteHeader(http.StatusForbidden)
  246. if g.Option.BuildVersion == "development" {
  247. w.Write([]byte("AGI script must have file extension of .agi or .js"))
  248. } else {
  249. w.Write([]byte("403 Forbidden"))
  250. }
  251. return
  252. }
  253. //Get the content of the script
  254. scriptContentByte, err := os.ReadFile(scriptFile)
  255. if err != nil {
  256. w.WriteHeader(http.StatusInternalServerError)
  257. w.Write([]byte("500 - Internal Server Error: Script load error =>" + err.Error()))
  258. return
  259. }
  260. scriptContent := string(scriptContentByte)
  261. g.ExecuteAGIScript(scriptContent, nil, scriptFile, scriptScope, w, r, thisuser)
  262. }
  263. /*
  264. Executing the given AGI Script contents. Requires:
  265. scriptContent: The AGI command sequence
  266. scriptFile: The filepath of the script file
  267. scriptScope: The scope of the script file, aka the module base path
  268. w / r : Web request and response writer
  269. thisuser: userObject
  270. */
  271. func (g *Gateway) ExecuteAGIScript(scriptContent string, fsh *filesystem.FileSystemHandler, scriptFile string, scriptScope string, w http.ResponseWriter, r *http.Request, thisuser *user.User) {
  272. // Check if developer debug mode is requested via URL query param (set AGI_DEV=true in ao_module)
  273. devMode := r.URL.Query().Get("agi_devmode") == "true"
  274. //Create a new vm for this request
  275. vm := otto.New()
  276. vm.Interrupt = make(chan func(), 1) // required for force-stop support
  277. //Inject standard libs into the vm; capture execID for registry correlation
  278. execID := g.injectStandardLibs(vm, scriptFile, scriptScope)
  279. releaseLibResources := g.injectUserFunctions(vm, fsh, scriptFile, scriptScope, thisuser, w, r)
  280. username := ""
  281. if thisuser != nil {
  282. username = thisuser.Username
  283. }
  284. // Register in the VM lifecycle registry so it can be listed and force-stopped
  285. g.vmReg.register(&VMRecord{
  286. ExecID: execID,
  287. ScriptFile: scriptFile,
  288. Username: username,
  289. StartTime: time.Now(),
  290. interruptCh: vm.Interrupt,
  291. })
  292. defer func() {
  293. g.vmReg.unregister(execID)
  294. //Release library resources (open SQLite handles, etc.) on every exit path
  295. releaseLibResources()
  296. if caught := recover(); caught != nil {
  297. switch caught {
  298. case errForceStop:
  299. logger.PrintAndLog("Agi", fmt.Sprintf("[AGI] VM %s force-stopped (script: %s, user: %s)", execID, scriptFile, username), nil)
  300. w.WriteHeader(http.StatusServiceUnavailable)
  301. w.Write([]byte("503 - Script execution was force-terminated"))
  302. case errExitcall:
  303. // exit() in AGI script — clean early termination, not an error.
  304. // check anything else in the buffered response and send it before returning, if needed.
  305. value, err := vm.Get("HTTP_RESP")
  306. if err == nil {
  307. valueString, err := value.ToString()
  308. if err == nil && valueString != "" {
  309. w.Write([]byte(valueString))
  310. }
  311. }
  312. default:
  313. panic(caught) // re-panic anything we don't own
  314. }
  315. }
  316. }()
  317. //Detect cotent type
  318. contentType := r.Header.Get("Content-type")
  319. if strings.Contains(contentType, "application/json") {
  320. //For people who use Angular
  321. body, _ := io.ReadAll(r.Body)
  322. fields := map[string]interface{}{}
  323. json.Unmarshal(body, &fields)
  324. for k, v := range fields {
  325. vm.Set(k, v)
  326. }
  327. vm.Set("POST_data", string(body))
  328. } else {
  329. r.ParseForm()
  330. //Insert all paramters into the vm
  331. for k, v := range r.PostForm {
  332. if len(v) == 1 {
  333. vm.Set(k, v[0])
  334. } else {
  335. vm.Set(k, v)
  336. }
  337. }
  338. }
  339. _, err := vm.Run(scriptContent)
  340. if err != nil {
  341. username := ""
  342. if thisuser != nil {
  343. username = thisuser.Username
  344. }
  345. logger.PrintAndLog("Agi", fmt.Sprintf("[AGI][%s] Script error in %s (user: %s): %s", execID, scriptFile, username, err.Error()), nil)
  346. if devMode {
  347. // Return a detailed JSON error payload for developer inspection
  348. errMsg := err.Error()
  349. stackTrace := errMsg
  350. if ottoErr, ok := err.(*otto.Error); ok {
  351. stackTrace = ottoErr.String()
  352. }
  353. errPayload, _ := json.Marshal(map[string]interface{}{
  354. "error": true,
  355. "message": errMsg,
  356. "stacktrace": stackTrace,
  357. "script": scriptFile,
  358. "user": username,
  359. })
  360. w.Header().Set("Content-Type", "application/json")
  361. w.WriteHeader(http.StatusInternalServerError)
  362. w.Write(errPayload)
  363. } else {
  364. scriptpath, _ := filepath.Abs(scriptFile)
  365. g.RenderErrorTemplate(w, err.Error(), scriptpath)
  366. }
  367. return
  368. }
  369. //Get the return valu from the script
  370. value, err := vm.Get("HTTP_RESP")
  371. if err != nil {
  372. utils.SendTextResponse(w, "")
  373. return
  374. }
  375. valueString, err := value.ToString()
  376. //Get respond header type from the vm
  377. header, _ := vm.Get("HTTP_HEADER")
  378. headerString, _ := header.ToString()
  379. if headerString != "" {
  380. w.Header().Set("Content-Type", headerString)
  381. }
  382. w.Write([]byte(valueString))
  383. }
  384. /*
  385. Execute AGI script with given user information
  386. scriptFile must be realpath resolved by fsa VirtualPathToRealPath function
  387. Pass in http.Request pointer to enable serverless GET / POST request
  388. */
  389. // ExecuteAGIScriptAsUser runs an AGI script on behalf of targetUser.
  390. // Returns (execID, output, error) where execID matches the EXECUTION_ID
  391. // constant injected into the script's VM environment.
  392. func (g *Gateway) ExecuteAGIScriptAsUser(fsh *filesystem.FileSystemHandler, scriptFile string, targetUser *user.User, w http.ResponseWriter, r *http.Request) (string, string, error) {
  393. //Create a new vm for this request
  394. vm := otto.New()
  395. //Inject standard libs into the vm; capture the execution ID for log correlation.
  396. execID := g.injectStandardLibs(vm, scriptFile, "")
  397. releaseLibResources := g.injectUserFunctions(vm, fsh, scriptFile, "", targetUser, w, r)
  398. if r != nil {
  399. //Inject serverless script to enable access to GET / POST paramters
  400. g.injectServerlessFunctions(vm, scriptFile, "", targetUser, r)
  401. }
  402. //Inject interrupt Channel
  403. vm.Interrupt = make(chan func(), 1)
  404. // Register in the VM lifecycle registry
  405. g.vmReg.register(&VMRecord{
  406. ExecID: execID,
  407. ScriptFile: scriptFile,
  408. Username: targetUser.Username,
  409. StartTime: time.Now(),
  410. interruptCh: vm.Interrupt,
  411. })
  412. //Create a panic recovery logic
  413. defer func() {
  414. g.vmReg.unregister(execID)
  415. //Release library resources (open SQLite handles, etc.) on every exit path
  416. releaseLibResources()
  417. if caught := recover(); caught != nil {
  418. if caught == errTimeout {
  419. logger.PrintAndLog("Agi", fmt.Sprintf("[AGI] Execution timeout: %s (user: %s)", scriptFile, targetUser.Username), nil)
  420. return
  421. } else if caught == errExitcall {
  422. //Exit gracefully
  423. return
  424. } else if caught == errForceStop {
  425. logger.PrintAndLog("Agi", fmt.Sprintf("[AGI] VM %s force-stopped (script: %s, user: %s)", execID, scriptFile, targetUser.Username), nil)
  426. if w != nil {
  427. w.WriteHeader(http.StatusServiceUnavailable)
  428. w.Write([]byte("503 - Script execution was force-terminated"))
  429. }
  430. } else {
  431. //Something screwed. Return Internal Server Error
  432. logger.PrintAndLog("Agi", fmt.Sprintf("[AGI] VM crash in %s (user: %s): %v", scriptFile, targetUser.Username, caught), nil)
  433. if w != nil {
  434. devMode := r != nil && r.URL.Query().Get("agi_devmode") == "true"
  435. if devMode {
  436. errPayload, _ := json.Marshal(map[string]interface{}{
  437. "error": true,
  438. "message": fmt.Sprintf("VM crash: %v", caught),
  439. "stacktrace": fmt.Sprintf("VM crash: %v", caught),
  440. "script": scriptFile,
  441. "user": targetUser.Username,
  442. })
  443. w.Header().Set("Content-Type", "application/json")
  444. w.WriteHeader(http.StatusInternalServerError)
  445. w.Write(errPayload)
  446. } else {
  447. w.WriteHeader(http.StatusInternalServerError)
  448. w.Write([]byte("500 - ECMA VM crashed due to unknown reason"))
  449. }
  450. }
  451. }
  452. }
  453. }()
  454. //Create a max runtime of 5 minutes
  455. go func() {
  456. time.Sleep(300 * time.Second) // Stop after 300 seconds
  457. vm.Interrupt <- func() {
  458. panic(errTimeout)
  459. }
  460. }()
  461. //Try to read the script content.
  462. // When fsh is nil (e.g. app-root scripts), fall back to reading from the OS filesystem.
  463. var scriptContent []byte
  464. var err error
  465. if fsh != nil {
  466. scriptContent, err = fsh.FileSystemAbstraction.ReadFile(scriptFile)
  467. } else {
  468. scriptContent, err = os.ReadFile(scriptFile)
  469. }
  470. if err != nil {
  471. return execID, "", err
  472. }
  473. _, err = vm.Run(scriptContent)
  474. if err != nil {
  475. logger.PrintAndLog("Agi", fmt.Sprintf("[AGI][%s] Script error in %s (user: %s): %s", execID, scriptFile, targetUser.Username, err.Error()), nil)
  476. return execID, "", err
  477. }
  478. //Get the return value from the script
  479. value, err := vm.Get("HTTP_RESP")
  480. if err != nil {
  481. return execID, "", err
  482. }
  483. if w != nil {
  484. //Serverless: Get respond header type from the vm
  485. header, _ := vm.Get("HTTP_HEADER")
  486. headerString, _ := header.ToString()
  487. if headerString != "" {
  488. w.Header().Set("Content-Type", headerString)
  489. }
  490. }
  491. valueString, err := value.ToString()
  492. if err != nil {
  493. return execID, "", err
  494. }
  495. return execID, valueString, nil
  496. }
  497. /*
  498. Get user specific tmp filepath for buffering remote file. Return filepath and closer
  499. tempFilepath, closerFunction := g.getUserSpecificTempFilePath(u, "myfile.txt")
  500. //Do something with it, after done
  501. closerFunction();
  502. */
  503. func (g *Gateway) getUserSpecificTempFilePath(u *user.User, filename string) (string, func()) {
  504. uuid := uuid.NewV4().String()
  505. tmpFileLocation := filepath.Join(g.Option.TempFolderPath, "agiBuff", u.Username, uuid, filepath.Base(filename))
  506. os.MkdirAll(filepath.Dir(tmpFileLocation), 0775)
  507. return tmpFileLocation, func() {
  508. os.RemoveAll(filepath.Dir(tmpFileLocation))
  509. }
  510. }
  511. /*
  512. Buffer remote reosurces to local by fsh and rpath. Return buffer filepath on local device and its closer function
  513. */
  514. func (g *Gateway) bufferRemoteResourcesToLocal(fsh *filesystem.FileSystemHandler, u *user.User, rpath string) (string, func(), error) {
  515. buffFile, closerFunc := g.getUserSpecificTempFilePath(u, rpath)
  516. f, err := fsh.FileSystemAbstraction.ReadStream(rpath)
  517. if err != nil {
  518. return "", nil, err
  519. }
  520. defer f.Close()
  521. dest, err := os.OpenFile(buffFile, os.O_CREATE|os.O_RDWR, 0775)
  522. if err != nil {
  523. return "", nil, err
  524. }
  525. io.Copy(dest, f)
  526. dest.Close()
  527. return buffFile, func() {
  528. closerFunc()
  529. }, nil
  530. }