Fix a server crashing null pointer

This commit is contained in:
Qian Wang 2019-08-06 21:04:08 +01:00
parent f96a24f13d
commit 3002c87a49
1 changed files with 4 additions and 4 deletions

View File

@ -72,10 +72,10 @@ func (sb *switchboard) send(data []byte, connId *uint32) (int, error) {
// in particular if newConnId is removed between the RUnlock and RLock, conns[newConnId] will return // in particular if newConnId is removed between the RUnlock and RLock, conns[newConnId] will return
// a nil pointer. To prevent this we must get newConnId and the reference to conn itself in one single mutex // a nil pointer. To prevent this we must get newConnId and the reference to conn itself in one single mutex
// protection // protection
if atomic.LoadUint32(&sb.broken) == 1 { sb.connsM.RLock()
if atomic.LoadUint32(&sb.broken) == 1 || len(sb.conns) == 0 {
return 0, errBrokenSwitchboard return 0, errBrokenSwitchboard
} }
sb.connsM.RLock()
newConnId := rand.Intn(len(sb.conns)) newConnId := rand.Intn(len(sb.conns))
conn = sb.conns[uint32(newConnId)] conn = sb.conns[uint32(newConnId)]
sb.connsM.RUnlock() sb.connsM.RUnlock()
@ -85,10 +85,10 @@ func (sb *switchboard) send(data []byte, connId *uint32) (int, error) {
} }
func (sb *switchboard) assignRandomConn() (uint32, error) { func (sb *switchboard) assignRandomConn() (uint32, error) {
if atomic.LoadUint32(&sb.broken) == 1 { sb.connsM.RLock()
if atomic.LoadUint32(&sb.broken) == 1 || len(sb.conns) == 0 {
return 0, errBrokenSwitchboard return 0, errBrokenSwitchboard
} }
sb.connsM.RLock()
connId := rand.Intn(len(sb.conns)) connId := rand.Intn(len(sb.conns))
sb.connsM.RUnlock() sb.connsM.RUnlock()
return uint32(connId), nil return uint32(connId), nil