Fix race in Torrent.String

This commit is contained in:
Matt Joiner 2019-03-12 11:22:25 +11:00
parent df47e3aaef
commit 3920c6c325
2 changed files with 7 additions and 2 deletions

2
t.go
View File

@ -115,8 +115,6 @@ func (t *Torrent) SetDisplayName(dn string) {
// The current working name for the torrent. Either the name in the info dict, // The current working name for the torrent. Either the name in the info dict,
// or a display name given such as by the dn value in a magnet link, or "". // or a display name given such as by the dn value in a magnet link, or "".
func (t *Torrent) Name() string { func (t *Torrent) Name() string {
t.cl.lock()
defer t.cl.unlock()
return t.name() return t.name()
} }

View File

@ -104,6 +104,7 @@ type Torrent struct {
// Name used if the info name isn't available. Should be cleared when the // Name used if the info name isn't available. Should be cleared when the
// Info does become available. // Info does become available.
nameMu sync.RWMutex
displayName string displayName string
// The bencoded bytes of the info dict. This is actively manipulated if // The bencoded bytes of the info dict. This is actively manipulated if
@ -260,7 +261,9 @@ func (t *Torrent) invalidateMetadata() {
for i := range t.metadataCompletedChunks { for i := range t.metadataCompletedChunks {
t.metadataCompletedChunks[i] = false t.metadataCompletedChunks[i] = false
} }
t.nameMu.Lock()
t.info = nil t.info = nil
t.nameMu.Unlock()
} }
func (t *Torrent) saveMetadataPiece(index int, data []byte) { func (t *Torrent) saveMetadataPiece(index int, data []byte) {
@ -355,7 +358,9 @@ func (t *Torrent) setInfo(info *metainfo.Info) error {
return fmt.Errorf("error opening torrent storage: %s", err) return fmt.Errorf("error opening torrent storage: %s", err)
} }
} }
t.nameMu.Lock()
t.info = info t.info = info
t.nameMu.Unlock()
t.displayName = "" // Save a few bytes lol. t.displayName = "" // Save a few bytes lol.
t.initFiles() t.initFiles()
t.cacheLength() t.cacheLength()
@ -442,6 +447,8 @@ func (t *Torrent) setMetadataSize(bytes int) (err error) {
// The current working name for the torrent. Either the name in the info dict, // The current working name for the torrent. Either the name in the info dict,
// or a display name given such as by the dn value in a magnet link, or "". // or a display name given such as by the dn value in a magnet link, or "".
func (t *Torrent) name() string { func (t *Torrent) name() string {
t.nameMu.RLock()
defer t.nameMu.RUnlock()
if t.haveInfo() { if t.haveInfo() {
return t.info.Name return t.info.Name
} }