From e4132f625bd9d32269047d34868a7ab3e392ed11 Mon Sep 17 00:00:00 2001 From: JustAnotherArchivist Date: Mon, 19 Jul 2021 19:48:58 +0000 Subject: [PATCH] Fix race condition crash on concurrent accesses to the same file https://github.com/dutchcoders/transfer.sh/issues/380 --- server/handlers.go | 17 ++++++----------- server/server.go | 4 ++-- 2 files changed, 8 insertions(+), 13 deletions(-) diff --git a/server/handlers.go b/server/handlers.go index dd10e73..b9e5a69 100644 --- a/server/handlers.go +++ b/server/handlers.go @@ -625,23 +625,18 @@ func (metadata Metadata) remainingLimitHeaderValues() (remainingDownloads, remai return remainingDownloads, remainingDays } -func (s *Server) Lock(token, filename string) error { +func (s *Server) Lock(token, filename string) { key := path.Join(token, filename) - if _, ok := s.locks[key]; !ok { - s.locks[key] = &sync.Mutex{} - } - - s.locks[key].Lock() - - return nil + lock, _ := s.locks.LoadOrStore(key, &sync.Mutex{}) + lock.(*sync.Mutex).Lock() } -func (s *Server) Unlock(token, filename string) error { +func (s *Server) Unlock(token, filename string) { key := path.Join(token, filename) - s.locks[key].Unlock() - return nil + lock, _ := s.locks.LoadOrStore(key, &sync.Mutex{}) + lock.(*sync.Mutex).Unlock() } func (s *Server) CheckMetadata(token, filename string, increaseDownload bool) (Metadata, error) { diff --git a/server/server.go b/server/server.go index ed36853..b3c24e2 100644 --- a/server/server.go +++ b/server/server.go @@ -282,7 +282,7 @@ type Server struct { profilerEnabled bool - locks map[string]*sync.Mutex + locks sync.Map maxUploadSize int64 rateLimitRequests int @@ -321,7 +321,7 @@ type Server struct { func New(options ...OptionFn) (*Server, error) { s := &Server{ - locks: map[string]*sync.Mutex{}, + locks: sync.Map{}, } for _, optionFn := range options {