Skip to content

Commit

Permalink
Merge pull request #91 from tigrato/fix-ping-data-race
Browse files Browse the repository at this point in the history
Fix Ping data-race
  • Loading branch information
dmcgowan authored Jun 21, 2024
2 parents 57d1ca2 + 3473c0b commit 06348fb
Showing 1 changed file with 17 additions and 8 deletions.
25 changes: 17 additions & 8 deletions connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -208,9 +208,10 @@ type Connection struct {
nextStreamId spdy.StreamId
receivedStreamId spdy.StreamId

pingIdLock sync.Mutex
pingId uint32
pingChans map[uint32]chan error
// pingLock protects pingChans and pingId
pingLock sync.Mutex
pingId uint32
pingChans map[uint32]chan error

shutdownLock sync.Mutex
shutdownChan chan error
Expand Down Expand Up @@ -274,16 +275,20 @@ func NewConnection(conn net.Conn, server bool) (*Connection, error) {
// returns the response time
func (s *Connection) Ping() (time.Duration, error) {
pid := s.pingId
s.pingIdLock.Lock()
s.pingLock.Lock()
if s.pingId > 0x7ffffffe {
s.pingId = s.pingId - 0x7ffffffe
} else {
s.pingId = s.pingId + 2
}
s.pingIdLock.Unlock()
pingChan := make(chan error)
s.pingChans[pid] = pingChan
defer delete(s.pingChans, pid)
s.pingLock.Unlock()
defer func() {
s.pingLock.Lock()
delete(s.pingChans, pid)
s.pingLock.Unlock()
}()

frame := &spdy.PingFrame{Id: pid}
startTime := time.Now()
Expand Down Expand Up @@ -612,10 +617,14 @@ func (s *Connection) handleDataFrame(frame *spdy.DataFrame) error {
}

func (s *Connection) handlePingFrame(frame *spdy.PingFrame) error {
if s.pingId&0x01 != frame.Id&0x01 {
s.pingLock.Lock()
pingId := s.pingId
pingChan, pingOk := s.pingChans[frame.Id]
s.pingLock.Unlock()

if pingId&0x01 != frame.Id&0x01 {
return s.framer.WriteFrame(frame)
}
pingChan, pingOk := s.pingChans[frame.Id]
if pingOk {
close(pingChan)
}
Expand Down

0 comments on commit 06348fb

Please sign in to comment.