Skip to content
This repository was archived by the owner on Aug 30, 2024. It is now read-only.

fix: ensure error chan is buffered in (*Dialer).negotiate #437

Merged
merged 4 commits into from
Sep 9, 2021
Merged
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
21 changes: 11 additions & 10 deletions wsnet/dial.go
Original file line number Diff line number Diff line change
Expand Up @@ -193,24 +193,20 @@ type Dialer struct {
func (d *Dialer) negotiate(ctx context.Context) (err error) {
var (
decoder = json.NewDecoder(d.conn)
errCh = make(chan error)
errCh = make(chan error, 1)
// If candidates are sent before an offer, we place them here.
// We currently have no assurances to ensure this can't happen,
// so it's better to buffer and process than fail.
pendingCandidates = []webrtc.ICECandidateInit{}
)
go func() {
defer close(errCh)
defer func() {
_ = d.conn.Close()
}()
defer func() { _ = d.conn.Close() }()

err := waitForConnectionOpen(context.Background(), d.rtc)
if err != nil {
d.log.Debug(ctx, "negotiation error", slog.Error(err))
if errors.Is(err, context.DeadlineExceeded) {
_ = d.conn.Close()
}

errCh <- fmt.Errorf("wait for connection to open: %w", err)
return
}
Expand Down Expand Up @@ -331,23 +327,28 @@ func (d *Dialer) Ping(ctx context.Context) error {
return err
}
}

d.pingMut.Lock()
defer d.pingMut.Unlock()

d.log.Debug(ctx, "sending ping")
_, err = d.ctrlrw.Write([]byte{'a'})
if err != nil {
return fmt.Errorf("write: %w", err)
}
errCh := make(chan error)

errCh := make(chan error, 1)
go func() {
// There's a race in which connections can get lost-mid ping
// in which case this would block forever.
defer close(errCh)
_, err = d.ctrlrw.Read(make([]byte, 4))
errCh <- err
}()
ctx, cancelFunc := context.WithTimeout(ctx, time.Second*15)
defer cancelFunc()

ctx, cancel := context.WithTimeout(ctx, time.Second*15)
defer cancel()

select {
case err := <-errCh:
return err
Expand Down