Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use O_EXCL to create files atomically. #2

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,17 +125,17 @@ func (h *Handler) RootHandler(w http.ResponseWriter, r *http.Request) {

filename := filepath.Join(h.Config.MediaRoot, upfileHdr.Filename)

// This will always be vulnerable to races, but here we check if the
// file already exists, and return a 409 if it does. This isn't in the
// RAML, and the "official" Python API returns nothing AFAICT. This is
// Create the file with O_EXCL so that we can detect if the file
// already exists and return a 409 if it does. This isn't in the RAML,
// and the "official" Python API returns nothing AFAICT. This is
// definitely an improvement over that!
if _, err := os.Stat(filename); !os.IsNotExist(err) {
w.WriteHeader(http.StatusConflict)
}

file, err := os.Create(filename)
file, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0640)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
if os.IsExist(err) {
w.WriteHeader(http.StatusConflict)
} else {
w.WriteHeader(http.StatusInternalServerError)
}
w.Write([]byte("Error opening file: " + err.Error()))
return
}
Expand Down