From 481df3d5430437df2cfec0a94be052ca47781b12 Mon Sep 17 00:00:00 2001 From: Dane Everitt Date: Mon, 31 Aug 2020 21:02:06 -0700 Subject: [PATCH] Only create the directory structure if it is a file being renamed; closes pterodactyl/panel#2292 --- router/router_server_files.go | 7 +++++++ server/filesystem.go | 23 ++++++++++++++--------- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/router/router_server_files.go b/router/router_server_files.go index a8ab478..2f97cce 100644 --- a/router/router_server_files.go +++ b/router/router_server_files.go @@ -149,6 +149,13 @@ func putServerRenameFiles(c *gin.Context) { } if err := g.Wait(); err != nil { + if errors.Is(err, os.ErrExist) { + c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{ + "error": "Cannot move or rename file, destination already exists.", + }) + return + } + TrackedServerError(err, s).AbortWithServerError(c) return } diff --git a/server/filesystem.go b/server/filesystem.go index cc439bf..792ceed 100644 --- a/server/filesystem.go +++ b/server/filesystem.go @@ -496,17 +496,22 @@ func (fs *Filesystem) Rename(from string, to string) error { return errors.WithStack(err) } - if f, err := os.Stat(cleanedFrom); err != nil { - return errors.WithStack(err) - } else { - d := cleanedTo - if !f.IsDir() { - d = strings.TrimSuffix(d, path.Base(cleanedTo)) - } + // If the target file or directory already exists the rename function will fail, so just + // bail out now. + if _, err := os.Stat(cleanedTo); err == nil { + return os.ErrExist + } - // Ensure that the directory we're moving into exists correctly on the system. + if cleanedTo == fs.Path() { + return errors.New("attempting to rename into an invalid directory space") + } + + d := strings.TrimSuffix(cleanedTo, path.Base(cleanedTo)) + // Ensure that the directory we're moving into exists correctly on the system. Only do this if + // we're not at the root directory level. + if d != fs.Path() { if mkerr := os.MkdirAll(d, 0644); mkerr != nil { - return errors.WithStack(mkerr) + return errors.Wrap(mkerr, "failed to create directory structure for file rename") } }