From 4ff0db0246fa8a2add1032220024975203b93d72 Mon Sep 17 00:00:00 2001 From: Bwko Date: Thu, 1 Dec 2016 00:56:15 +0100 Subject: [PATCH] Catch os... errors --- cmd/dump.go | 8 +++++--- cmd/serve.go | 4 +++- cmd/web.go | 5 +++-- main.go | 8 +++++++- models/models.go | 5 ++++- models/pull.go | 11 +++++++++-- models/repo.go | 30 +++++++++++++++++++++++++----- models/repo_editor.go | 18 +++++++++++++++--- models/ssh_key.go | 7 ++++++- models/user.go | 21 +++++++++++++++++---- models/wiki.go | 16 +++++++++++++--- modules/log/file.go | 5 ++++- modules/log/log.go | 7 ++++++- modules/ssh/ssh.go | 7 ++++++- 14 files changed, 123 insertions(+), 29 deletions(-) diff --git a/cmd/dump.go b/cmd/dump.go index 027f251a0c..d17b5e2fb0 100644 --- a/cmd/dump.go +++ b/cmd/dump.go @@ -79,7 +79,6 @@ func runDump(ctx *cli.Context) error { log.Printf("Packing dump files...") z, err := zip.Create(fileName) if err != nil { - os.Remove(fileName) log.Fatalf("Fail to create %s: %v", fileName, err) } @@ -102,7 +101,7 @@ func runDump(ctx *cli.Context) error { } // FIXME: SSH key file. if err = z.Close(); err != nil { - os.Remove(fileName) + _ = os.Remove(fileName) log.Fatalf("Fail to save %s: %v", fileName, err) } @@ -111,7 +110,10 @@ func runDump(ctx *cli.Context) error { } log.Printf("Removing tmp work dir: %s", TmpWorkDir) - os.RemoveAll(TmpWorkDir) + + if err := os.RemoveAll(TmpWorkDir); err != nil { + log.Fatalf("Fail to remove %s: %v", TmpWorkDir, err) + } log.Printf("Finish dumping in file %s", fileName) return nil diff --git a/cmd/serve.go b/cmd/serve.go index 2578b26dfd..3ac29d7ec3 100644 --- a/cmd/serve.go +++ b/cmd/serve.go @@ -51,7 +51,9 @@ func setup(logPath string) { if setting.UseSQLite3 || setting.UseTiDB { workDir, _ := setting.WorkDir() - os.Chdir(workDir) + if err := os.Chdir(workDir); err != nil { + log.GitLogger.Fatal(4, "Fail to change directory %s: %v", workDir, err) + } } models.SetEngine() diff --git a/cmd/web.go b/cmd/web.go index c53f518af4..5442850561 100644 --- a/cmd/web.go +++ b/cmd/web.go @@ -654,8 +654,9 @@ func runWeb(ctx *cli.Context) error { case setting.FCGI: err = fcgi.Serve(nil, m) case setting.UnixSocket: - os.Remove(listenAddr) - + if err := os.Remove(listenAddr); err != nil { + log.Fatal(4, "Fail to remove unix socket directory %s: %v", listenAddr, err) + } var listener *net.UnixListener listener, err = net.ListenUnix("unix", &net.UnixAddr{Name: listenAddr, Net: "unix"}) if err != nil { diff --git a/main.go b/main.go index b55da73fba..3383400082 100644 --- a/main.go +++ b/main.go @@ -10,6 +10,8 @@ import ( "os" "runtime" + "code.gitea.io/gitea/modules/log" + "code.gitea.io/gitea/cmd" "code.gitea.io/gitea/modules/setting" "github.com/urfave/cli" @@ -37,5 +39,9 @@ func main() { cmd.CmdAdmin, } app.Flags = append(app.Flags, []cli.Flag{}...) - app.Run(os.Args) + err := app.Run(os.Args) + if err != nil { + log.Fatal(4, "Fail to run app with %s: %v", os.Args, err) + } + } diff --git a/models/models.go b/models/models.go index bab04c661b..56306d61f5 100644 --- a/models/models.go +++ b/models/models.go @@ -192,7 +192,10 @@ func SetEngine() (err error) { // WARNING: for serv command, MUST remove the output to os.stdout, // so use log file to instead print to stdout. logPath := path.Join(setting.LogRootPath, "xorm.log") - os.MkdirAll(path.Dir(logPath), os.ModePerm) + + if err := os.MkdirAll(path.Dir(logPath), os.ModePerm); err != nil { + return fmt.Errorf("Fail to create dir %s: %v", logPath, err) + } f, err := os.Create(logPath) if err != nil { diff --git a/models/pull.go b/models/pull.go index 5157b61fef..eef9a7557b 100644 --- a/models/pull.go +++ b/models/pull.go @@ -218,7 +218,11 @@ func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository) (err error // Clone base repo. tmpBasePath := path.Join(setting.AppDataPath, "tmp/repos", com.ToStr(time.Now().Nanosecond())+".git") - os.MkdirAll(path.Dir(tmpBasePath), os.ModePerm) + + if err := os.MkdirAll(path.Dir(tmpBasePath), os.ModePerm); err != nil { + return fmt.Errorf("Fail to create dir %s: %v", tmpBasePath, err) + } + defer os.RemoveAll(path.Dir(tmpBasePath)) var stderr string @@ -622,8 +626,11 @@ func (pr *PullRequest) PushToBaseRepo() (err error) { headFile := fmt.Sprintf("refs/pull/%d/head", pr.Index) // Remove head in case there is a conflict. - os.Remove(path.Join(pr.BaseRepo.RepoPath(), headFile)) + file := path.Join(pr.BaseRepo.RepoPath(), headFile) + if err := os.Remove(file); err != nil { + return fmt.Errorf("Fail to remove dir %s: %v", path.Join(pr.BaseRepo.RepoPath(), headFile), err) + } if err = git.Push(headRepoPath, tmpRemoteName, fmt.Sprintf("%s:%s", pr.HeadBranch, headFile)); err != nil { return fmt.Errorf("Push: %v", err) } diff --git a/models/repo.go b/models/repo.go index d86956eeb5..af74e6c8fc 100644 --- a/models/repo.go +++ b/models/repo.go @@ -558,8 +558,12 @@ func (repo *Repository) SavePatch(index int64, patch []byte) error { if err != nil { return fmt.Errorf("PatchPath: %v", err) } + dir := filepath.Dir(patchPath) + + if err := os.MkdirAll(dir, os.ModePerm); err != nil { + return fmt.Errorf("Fail to create dir %s: %v", dir, err) + } - os.MkdirAll(filepath.Dir(patchPath), os.ModePerm) if err = ioutil.WriteFile(patchPath, patch, 0644); err != nil { return fmt.Errorf("WriteFile: %v", err) } @@ -669,7 +673,10 @@ func MigrateRepository(u *User, opts MigrateRepoOptions) (*Repository, error) { migrateTimeout := time.Duration(setting.Git.Timeout.Migrate) * time.Second - os.RemoveAll(repoPath) + if err := os.RemoveAll(repoPath); err != nil { + return repo, fmt.Errorf("Fail to remove %s: %v", repoPath, err) + } + if err = git.Clone(opts.RemoteAddr, repoPath, git.CloneRepoOptions{ Mirror: true, Quiet: true, @@ -680,7 +687,11 @@ func MigrateRepository(u *User, opts MigrateRepoOptions) (*Repository, error) { wikiRemotePath := wikiRemoteURL(opts.RemoteAddr) if len(wikiRemotePath) > 0 { - os.RemoveAll(wikiPath) + + if err := os.RemoveAll(wikiPath); err != nil { + return repo, fmt.Errorf("Fail to remove %s: %v", wikiPath, err) + } + if err = git.Clone(wikiRemotePath, wikiPath, git.CloneRepoOptions{ Mirror: true, Quiet: true, @@ -902,7 +913,11 @@ func initRepository(e Engine, repoPath string, u *User, repo *Repository, opts C // Initialize repository according to user's choice. if opts.AutoInit { - os.MkdirAll(tmpDir, os.ModePerm) + + if err := os.MkdirAll(tmpDir, os.ModePerm); err != nil { + return fmt.Errorf("Fail to create dir %s: %v", tmpDir, err) + } + defer os.RemoveAll(tmpDir) if err = prepareRepoCommit(repo, tmpDir, repoPath, opts); err != nil { @@ -1198,7 +1213,12 @@ func TransferOwnership(doer *User, newOwnerName string, repo *Repository) error } // Rename remote repository to new path and delete local copy. - os.MkdirAll(UserPath(newOwner.Name), os.ModePerm) + dir := UserPath(newOwner.Name) + + if err := os.MkdirAll(dir, os.ModePerm); err != nil { + return fmt.Errorf("Fail to create dir %s: %v", dir, err) + } + if err = os.Rename(RepoPath(owner.Name, repo.Name), RepoPath(newOwner.Name, repo.Name)); err != nil { return fmt.Errorf("rename repository directory: %v", err) } diff --git a/models/repo_editor.go b/models/repo_editor.go index 0d821f9f8c..b8bd46bc1d 100644 --- a/models/repo_editor.go +++ b/models/repo_editor.go @@ -104,7 +104,11 @@ func (repo *Repository) UpdateRepoFile(doer *User, opts UpdateRepoFileOptions) ( localPath := repo.LocalCopyPath() oldFilePath := path.Join(localPath, opts.OldTreeName) filePath := path.Join(localPath, opts.NewTreeName) - os.MkdirAll(path.Dir(filePath), os.ModePerm) + dir := path.Dir(filePath) + + if err := os.MkdirAll(dir, os.ModePerm); err != nil { + return fmt.Errorf("Fail to create dir %s: %v", dir, err) + } // If it's meant to be a new file, make sure it doesn't exist. if opts.IsNewFile { @@ -185,7 +189,12 @@ func (repo *Repository) GetDiffPreview(branch, treePath, content string) (diff * localPath := repo.LocalCopyPath() filePath := path.Join(localPath, treePath) - os.MkdirAll(filepath.Dir(filePath), os.ModePerm) + dir := filepath.Dir(filePath) + + if err := os.MkdirAll(dir, os.ModePerm); err != nil { + return nil, fmt.Errorf("Fail to create dir %s: %v", dir, err) + } + if err = ioutil.WriteFile(filePath, []byte(content), 0666); err != nil { return nil, fmt.Errorf("WriteFile: %v", err) } @@ -475,7 +484,10 @@ func (repo *Repository) UploadRepoFiles(doer *User, opts UploadRepoFileOptions) localPath := repo.LocalCopyPath() dirPath := path.Join(localPath, opts.TreePath) - os.MkdirAll(dirPath, os.ModePerm) + + if err := os.MkdirAll(dirPath, os.ModePerm); err != nil { + return fmt.Errorf("Fail to create dir %s: %v", dirPath, err) + } // Copy uploaded files into repository. for _, upload := range uploads { diff --git a/models/ssh_key.go b/models/ssh_key.go index 53a31f6f8d..f98a6b76f4 100644 --- a/models/ssh_key.go +++ b/models/ssh_key.go @@ -373,7 +373,12 @@ func addKey(e Engine, key *PublicKey) (err error) { // Calculate fingerprint. tmpPath := strings.Replace(path.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()), "id_rsa.pub"), "\\", "/", -1) - os.MkdirAll(path.Dir(tmpPath), os.ModePerm) + dir := path.Dir(tmpPath) + + if err := os.MkdirAll(dir, os.ModePerm); err != nil { + return fmt.Errorf("Fail to create dir %s: %v", dir, err) + } + if err = ioutil.WriteFile(tmpPath, []byte(key.Content), 0644); err != nil { return err } diff --git a/models/user.go b/models/user.go index ad20abe24d..41fdf0b024 100644 --- a/models/user.go +++ b/models/user.go @@ -392,7 +392,10 @@ func (u *User) UploadAvatar(data []byte) error { return fmt.Errorf("updateUser: %v", err) } - os.MkdirAll(setting.AvatarUploadPath, os.ModePerm) + if err := os.MkdirAll(setting.AvatarUploadPath, os.ModePerm); err != nil { + return fmt.Errorf("Fail to create dir %s: %v", setting.AvatarUploadPath, err) + } + fw, err := os.Create(u.CustomAvatarPath()) if err != nil { return fmt.Errorf("Create: %v", err) @@ -409,7 +412,10 @@ func (u *User) UploadAvatar(data []byte) error { // DeleteAvatar deletes the user's custom avatar. func (u *User) DeleteAvatar() error { log.Trace("DeleteAvatar[%d]: %s", u.ID, u.CustomAvatarPath()) - os.Remove(u.CustomAvatarPath()) + + if err := os.Remove(u.CustomAvatarPath()); err != nil { + return fmt.Errorf("Fail to remove %s: %v", u.CustomAvatarPath(), err) + } u.UseCustomAvatar = false if err := UpdateUser(u); err != nil { @@ -866,9 +872,16 @@ func deleteUser(e *xorm.Session, u *User) error { // FIXME: system notice // Note: There are something just cannot be roll back, // so just keep error logs of those operations. + path := UserPath(u.Name) - os.RemoveAll(UserPath(u.Name)) - os.Remove(u.CustomAvatarPath()) + if err := os.RemoveAll(path); err != nil { + return fmt.Errorf("Fail to RemoveAll %s: %v", path, err) + } + + avatarPath := u.CustomAvatarPath() + if err := os.Remove(avatarPath); err != nil { + return fmt.Errorf("Fail to remove %s: %v", avatarPath, err) + } return nil } diff --git a/models/wiki.go b/models/wiki.go index b010baeb52..890e62b0cd 100644 --- a/models/wiki.go +++ b/models/wiki.go @@ -112,7 +112,11 @@ func (repo *Repository) updateWikiPage(doer *User, oldTitle, title, content, mes return ErrWikiAlreadyExist{filename} } } else { - os.Remove(path.Join(localPath, oldTitle+".md")) + file := path.Join(localPath, oldTitle+".md") + + if err := os.Remove(file); err != nil { + return fmt.Errorf("Fail to remove %s: %v", file, err) + } } // SECURITY: if new file is a symlink to non-exist critical file, @@ -120,7 +124,10 @@ func (repo *Repository) updateWikiPage(doer *User, oldTitle, title, content, mes // as a new page operation. // So we want to make sure the symlink is removed before write anything. // The new file we created will be in normal text format. - os.Remove(filename) + + if err := os.Remove(filename); err != nil { + return fmt.Errorf("Fail to remove %s: %v", filename, err) + } if err = ioutil.WriteFile(filename, []byte(content), 0666); err != nil { return fmt.Errorf("WriteFile: %v", err) @@ -168,7 +175,10 @@ func (repo *Repository) DeleteWikiPage(doer *User, title string) (err error) { title = ToWikiPageName(title) filename := path.Join(localPath, title+".md") - os.Remove(filename) + + if err := os.Remove(filename); err != nil { + return fmt.Errorf("Fail to remove %s: %v", filename, err) + } message := "Delete page '" + title + "'" diff --git a/modules/log/file.go b/modules/log/file.go index 563abc28f8..dc243de8d9 100644 --- a/modules/log/file.go +++ b/modules/log/file.go @@ -219,7 +219,10 @@ func (w *FileLogWriter) deleteOldLog() { if !info.IsDir() && info.ModTime().Unix() < (time.Now().Unix()-60*60*24*w.Maxdays) { if strings.HasPrefix(filepath.Base(path), filepath.Base(w.Filename)) { - os.Remove(path) + + if err := os.Remove(path); err != nil { + returnErr = fmt.Errorf("Fail to remove %s: %v", path, err) + } } } return returnErr diff --git a/modules/log/log.go b/modules/log/log.go index 5a9efe6a28..6ca6d3f7c1 100644 --- a/modules/log/log.go +++ b/modules/log/log.go @@ -42,7 +42,12 @@ func NewLogger(bufLen int64, mode, config string) { // NewGitLogger create a logger for git // FIXME: use same log level as other loggers. func NewGitLogger(logPath string) { - os.MkdirAll(path.Dir(logPath), os.ModePerm) + path := path.Dir(logPath) + + if err := os.MkdirAll(path, os.ModePerm); err != nil { + Fatal(4, "Fail to create dir %s: %v", path, err) + } + GitLogger = newLogger(0) GitLogger.SetLogger("file", fmt.Sprintf(`{"level":0,"filename":"%s","rotate":false}`, logPath)) } diff --git a/modules/ssh/ssh.go b/modules/ssh/ssh.go index 0781073f59..b35973cc32 100644 --- a/modules/ssh/ssh.go +++ b/modules/ssh/ssh.go @@ -162,7 +162,12 @@ func Listen(port int) { keyPath := filepath.Join(setting.AppDataPath, "ssh/gogs.rsa") if !com.IsExist(keyPath) { - os.MkdirAll(filepath.Dir(keyPath), os.ModePerm) + filePath := filepath.Dir(keyPath) + + if err := os.MkdirAll(filePath, os.ModePerm); err != nil { + log.Error(4, "Fail to create dir %s: %v", filePath, err) + } + _, stderr, err := com.ExecCmd("ssh-keygen", "-f", keyPath, "-t", "rsa", "-N", "") if err != nil { panic(fmt.Sprintf("Fail to generate private key: %v - %s", err, stderr))