From f40dd65abb267dbc8c21d417392cf5f2dc449811 Mon Sep 17 00:00:00 2001 From: Steffen Vogel Date: Tue, 18 Apr 2023 19:11:35 +0200 Subject: [PATCH] Fix comment capitalization Comments should start with an uppercase letter. --- agent.go | 6 +++--- agent_config.go | 16 ++++++++-------- agent_test.go | 28 ++++++++++++++-------------- agent_udpmux_test.go | 10 +++++----- connectivity_vnet_test.go | 6 +++--- examples/ping-pong/main.go | 2 +- external_ip_mapper.go | 10 +++++----- external_ip_mapper_test.go | 18 +++++++++--------- gather.go | 4 ++-- gather_test.go | 8 ++++---- gather_vnet_test.go | 5 ++--- net.go | 4 ++-- selection.go | 6 +++--- tcp_mux.go | 4 ++-- tcp_mux_multi_test.go | 2 +- tcp_mux_test.go | 2 +- tcp_packet_conn.go | 11 ----------- transport.go | 2 +- transport_test.go | 16 ++++++++-------- udp_mux.go | 6 +++--- udp_mux_multi_test.go | 8 ++++---- udp_mux_test.go | 24 ++++++++++++------------ udp_mux_universal.go | 25 ++++++++++++------------- udp_mux_universal_test.go | 20 ++++++++++---------- udp_muxed_conn.go | 28 ++++++++++++++-------------- 25 files changed, 129 insertions(+), 142 deletions(-) diff --git a/agent.go b/agent.go index 0a3319d..b255d8b 100644 --- a/agent.go +++ b/agent.go @@ -47,7 +47,7 @@ type Agent struct { onConnected chan struct{} onConnectedOnce sync.Once - // force candidate to be contacted immediately (instead of waiting for task ticker) + // Force candidate to be contacted immediately (instead of waiting for task ticker) forceCandidateContact chan bool tieBreaker uint64 @@ -718,7 +718,7 @@ func (a *Agent) checkKeepalive() { if (a.keepaliveInterval != 0) && ((time.Since(selectedPair.Local.LastSent()) > a.keepaliveInterval) || (time.Since(selectedPair.Remote.LastReceived()) > a.keepaliveInterval)) { - // we use binding request instead of indication to support refresh consent schemas + // We use binding request instead of indication to support refresh consent schemas // see https://tools.ietf.org/html/rfc7675 a.selector.PingCandidate(selectedPair.Local, selectedPair.Remote) } @@ -730,7 +730,7 @@ func (a *Agent) AddRemoteCandidate(c Candidate) error { return nil } - // cannot check for network yet because it might not be applied + // Cannot check for network yet because it might not be applied // when mDNS hostname is used. if c.TCPType() == TCPTypeActive { // TCP Candidates with TCP type active will probe server passive ones, so diff --git a/agent_config.go b/agent_config.go index f7fbfce..04d74b1 100644 --- a/agent_config.go +++ b/agent_config.go @@ -25,25 +25,25 @@ const ( // defaultFailedTimeout is the default time till an Agent transitions to failed after disconnected defaultFailedTimeout = 25 * time.Second - // wait time before nominating a host candidate + // defaultHostAcceptanceMinWait is the wait time before nominating a host candidate defaultHostAcceptanceMinWait = 0 - // wait time before nominating a srflx candidate + // defaultSrflxAcceptanceMinWait is the wait time before nominating a srflx candidate defaultSrflxAcceptanceMinWait = 500 * time.Millisecond - // wait time before nominating a prflx candidate + // defaultPrflxAcceptanceMinWait is the wait time before nominating a prflx candidate defaultPrflxAcceptanceMinWait = 1000 * time.Millisecond - // wait time before nominating a relay candidate + // defaultRelayAcceptanceMinWait is the wait time before nominating a relay candidate defaultRelayAcceptanceMinWait = 2000 * time.Millisecond - // max binding request before considering a pair failed + // defaultMaxBindingRequests is the maximum number of binding requests before considering a pair failed defaultMaxBindingRequests = 7 - // the number of bytes that can be buffered before we start to error + // maxBufferSize is the number of bytes that can be buffered before we start to error maxBufferSize = 1000 * 1000 // 1MB - // wait time before binding requests can be deleted + // maxBindingRequestTimeout is the wait time before binding requests can be deleted maxBindingRequestTimeout = 4000 * time.Millisecond ) @@ -245,7 +245,7 @@ func (config *AgentConfig) initExtIPMapping(a *Agent) error { return err } if a.extIPMapper == nil { - return nil // this may happen when config.NAT1To1IPs is an empty array + return nil // This may happen when config.NAT1To1IPs is an empty array } if a.extIPMapper.candidateType == CandidateTypeHost { if a.mDNSMode == MulticastDNSModeQueryAndGather { diff --git a/agent_test.go b/agent_test.go index 9696f79..198ad4b 100644 --- a/agent_test.go +++ b/agent_test.go @@ -38,7 +38,7 @@ func TestOnSelectedCandidatePairChange(t *testing.T) { report := test.CheckRoutines(t) defer report() - // avoid deadlocks? + // Avoid deadlocks? defer test.TimeOut(1 * time.Second).Stop() a, err := NewAgent(&AgentConfig{}) @@ -77,7 +77,7 @@ func TestOnSelectedCandidatePairChange(t *testing.T) { t.Fatalf("Failed to construct remote relay candidate: %s", err) } - // select the pair + // Select the pair if err = a.run(context.Background(), func(ctx context.Context, agent *Agent) { p := newCandidatePair(hostLocal, relayRemote, false) agent.setSelectedPair(p) @@ -85,7 +85,7 @@ func TestOnSelectedCandidatePairChange(t *testing.T) { t.Fatalf("Failed to setValidPair(): %s", err) } - // ensure that the callback fired on setting the pair + // Ensure that the callback fired on setting the pair <-callbackCalled assert.NoError(t, a.Close()) } @@ -154,12 +154,12 @@ func TestHandlePeerReflexive(t *testing.T) { a.handleInbound(msg, local, remote) - // length of remote candidate list must be one now + // Length of remote candidate list must be one now if len(a.remoteCandidates) != 1 { t.Fatal("failed to add a network type to the remote candidate list") } - // length of remote candidate list for a network type must be 1 + // Length of remote candidate list for a network type must be 1 set := a.remoteCandidates[local.NetworkType()] if len(set) != 1 { t.Fatal("failed to add prflx candidate to remote candidate list") @@ -247,7 +247,7 @@ func TestHandlePeerReflexive(t *testing.T) { } // Assert that Agent on startup sends message, and doesn't wait for connectivityTicker to fire -// github.com/pion/ice/issues/15 +// https://github.com/pion/ice/issues/15 func TestConnectivityOnStartup(t *testing.T) { report := test.CheckRoutines(t) defer report() @@ -685,7 +685,7 @@ func TestCandidatePairStats(t *testing.T) { report := test.CheckRoutines(t) defer report() - // avoid deadlocks? + // Avoid deadlocks? defer test.TimeOut(1 * time.Second).Stop() a, err := NewAgent(&AgentConfig{}) @@ -818,7 +818,7 @@ func TestLocalCandidateStats(t *testing.T) { report := test.CheckRoutines(t) defer report() - // avoid deadlocks? + // Avoid deadlocks? defer test.TimeOut(1 * time.Second).Stop() a, err := NewAgent(&AgentConfig{}) @@ -899,7 +899,7 @@ func TestRemoteCandidateStats(t *testing.T) { report := test.CheckRoutines(t) defer report() - // avoid deadlocks? + // Avoid deadlocks? defer test.TimeOut(1 * time.Second).Stop() a, err := NewAgent(&AgentConfig{}) @@ -1077,7 +1077,7 @@ func TestInitExtIPMapping(t *testing.T) { // NewAgent should return if newExternalIPMapper() returns an error. _, err = NewAgent(&AgentConfig{ - NAT1To1IPs: []string{"bad.2.3.4"}, // bad IP + NAT1To1IPs: []string{"bad.2.3.4"}, // Bad IP NAT1To1IPCandidateType: CandidateTypeHost, }) if !errors.Is(err, ErrInvalidNAT1To1IPMapping) { @@ -1096,16 +1096,16 @@ func TestBindingRequestTimeout(t *testing.T) { now := time.Now() a.pendingBindingRequests = append(a.pendingBindingRequests, bindingRequest{ - timestamp: now, // valid + timestamp: now, // Valid }) a.pendingBindingRequests = append(a.pendingBindingRequests, bindingRequest{ - timestamp: now.Add(-3900 * time.Millisecond), // valid + timestamp: now.Add(-3900 * time.Millisecond), // Valid }) a.pendingBindingRequests = append(a.pendingBindingRequests, bindingRequest{ - timestamp: now.Add(-4100 * time.Millisecond), // invalid + timestamp: now.Add(-4100 * time.Millisecond), // Invalid }) a.pendingBindingRequests = append(a.pendingBindingRequests, bindingRequest{ - timestamp: now.Add(-75 * time.Hour), // invalid + timestamp: now.Add(-75 * time.Hour), // Invalid }) a.invalidatePendingBindingRequests(now) diff --git a/agent_udpmux_test.go b/agent_udpmux_test.go index 884f063..ef95d35 100644 --- a/agent_udpmux_test.go +++ b/agent_udpmux_test.go @@ -64,7 +64,7 @@ func TestMuxAgent(t *testing.T) { require.NotNil(t, pair) require.Equal(t, muxPort, pair.Local.Port()) - // send a packet to Mux + // Send a packet to Mux data := []byte("hello world") _, err = conn.Write(data) require.NoError(t, err) @@ -74,7 +74,7 @@ func TestMuxAgent(t *testing.T) { require.NoError(t, err) require.Equal(t, data, buf[:n]) - // send a packet from Mux + // Send a packet from Mux _, err = muxedConn.Write(data) require.NoError(t, err) @@ -82,16 +82,16 @@ func TestMuxAgent(t *testing.T) { require.NoError(t, err) require.Equal(t, data, buf[:n]) - // close it down + // Close it down require.NoError(t, conn.Close()) require.NoError(t, muxedConn.Close()) require.NoError(t, udpMux.Close()) - // expect error when reading from closed mux + // Expect error when reading from closed mux _, err = muxedConn.Read(data) require.Error(t, err) - // expect error when writing to closed mux + // Expect error when writing to closed mux _, err = muxedConn.Write(data) require.Error(t, err) }) diff --git a/connectivity_vnet_test.go b/connectivity_vnet_test.go index 0e387a8..a9e993f 100644 --- a/connectivity_vnet_test.go +++ b/connectivity_vnet_test.go @@ -41,8 +41,8 @@ type virtualNet struct { } func (v *virtualNet) close() { - v.server.Close() // nolint:errcheck,gosec - v.wan.Stop() // nolint:errcheck,gosec + v.server.Close() //nolint:errcheck,gosec + v.wan.Stop() //nolint:errcheck,gosec } func buildVNet(natType0, natType1 *vnet.NATType) (*virtualNet, error) { @@ -58,7 +58,7 @@ func buildVNet(natType0, natType1 *vnet.NATType) (*virtualNet, error) { } wanNet, err := vnet.NewNet(&vnet.NetConfig{ - StaticIP: vnetSTUNServerIP, // will be assigned to eth0 + StaticIP: vnetSTUNServerIP, // Will be assigned to eth0 }) if err != nil { return nil, err diff --git a/examples/ping-pong/main.go b/examples/ping-pong/main.go index 2b35e70..86f7bd1 100644 --- a/examples/ping-pong/main.go +++ b/examples/ping-pong/main.go @@ -18,7 +18,7 @@ import ( "github.com/pion/randutil" ) -// nolint:gochecknoglobals +//nolint:gochecknoglobals var ( isControlling bool iceAgent *ice.Agent diff --git a/external_ip_mapper.go b/external_ip_mapper.go index b2ed40e..3d542fb 100644 --- a/external_ip_mapper.go +++ b/external_ip_mapper.go @@ -18,9 +18,9 @@ func validateIPString(ipStr string) (net.IP, bool, error) { // ipMapping holds the mapping of local and external IP address for a particular IP family type ipMapping struct { - ipSole net.IP // when non-nil, this is the sole external IP for one local IP assumed - ipMap map[string]net.IP // local-to-external IP mapping (k: local, v: external) - valid bool // if not set any external IP, valid is false + ipSole net.IP // When non-nil, this is the sole external IP for one local IP assumed + ipMap map[string]net.IP // Local-to-external IP mapping (k: local, v: external) + valid bool // If not set any external IP, valid is false } func (m *ipMapping) setSoleIP(ip net.IP) error { @@ -41,7 +41,7 @@ func (m *ipMapping) addIPMapping(locIP, extIP net.IP) error { locIPStr := locIP.String() - // check if dup of local IP + // Check if dup of local IP if _, ok := m.ipMap[locIPStr]; ok { return ErrInvalidNAT1To1IPMapping } @@ -80,7 +80,7 @@ func newExternalIPMapper(candidateType CandidateType, ips []string) (*externalIP return nil, nil //nolint:nilnil } if candidateType == CandidateTypeUnspecified { - candidateType = CandidateTypeHost // defaults to host + candidateType = CandidateTypeHost // Defaults to host } else if candidateType != CandidateTypeHost && candidateType != CandidateTypeServerReflexive { return nil, ErrUnsupportedNAT1To1IPCandidateType } diff --git a/external_ip_mapper_test.go b/external_ip_mapper_test.go index 6631371..dbe39ad 100644 --- a/external_ip_mapper_test.go +++ b/external_ip_mapper_test.go @@ -223,13 +223,13 @@ func TestExternalIPMapper(t *testing.T) { assert.NotNil(t, m.ipv4Mapping.ipSole) assert.NotNil(t, m.ipv6Mapping.ipSole) - // find external IPv4 + // Find external IPv4 extIP, err = m.findExternalIP("10.0.0.1") assert.NoError(t, err, "should succeed") assert.Equal(t, "1.2.3.4", extIP.String(), "should match") - // find external IPv6 - extIP, err = m.findExternalIP("fe80::0001") // use '0001' instead of '1' on purpose + // Find external IPv6 + extIP, err = m.findExternalIP("fe80::0001") // Use '0001' instead of '1' on purpose assert.NoError(t, err, "should succeed") assert.Equal(t, "2200::1", extIP.String(), "should match") @@ -253,7 +253,7 @@ func TestExternalIPMapper(t *testing.T) { assert.NoError(t, err, "should succeed") assert.NotNil(t, m, "should not be nil") - // find external IPv4 + // Find external IPv4 extIP, err = m.findExternalIP("10.0.0.1") assert.NoError(t, err, "should succeed") assert.Equal(t, "1.2.3.4", extIP.String(), "should match") @@ -265,12 +265,12 @@ func TestExternalIPMapper(t *testing.T) { _, err = m.findExternalIP("10.0.0.3") assert.Error(t, err, "should fail") - // find external IPv6 - extIP, err = m.findExternalIP("fe80::0001") // use '0001' instead of '1' on purpose + // Find external IPv6 + extIP, err = m.findExternalIP("fe80::0001") // Use '0001' instead of '1' on purpose assert.NoError(t, err, "should succeed") assert.Equal(t, "2200::1", extIP.String(), "should match") - extIP, err = m.findExternalIP("fe80::0002") // use '0002' instead of '2' on purpose + extIP, err = m.findExternalIP("fe80::0002") // Use '0002' instead of '2' on purpose assert.NoError(t, err, "should succeed") assert.Equal(t, "2200::2", extIP.String(), "should match") @@ -291,7 +291,7 @@ func TestExternalIPMapper(t *testing.T) { }) assert.NoError(t, err, "should succeed") - // attempt to find IPv6 that does not exist in the map + // Attempt to find IPv6 that does not exist in the map extIP, err := m.findExternalIP("fe80::1") assert.NoError(t, err, "should succeed") assert.Equal(t, "fe80::1", extIP.String(), "should match") @@ -301,7 +301,7 @@ func TestExternalIPMapper(t *testing.T) { }) assert.NoError(t, err, "should succeed") - // attempt to find IPv4 that does not exist in the map + // Attempt to find IPv4 that does not exist in the map extIP, err = m.findExternalIP("10.0.0.1") assert.NoError(t, err, "should succeed") assert.Equal(t, "10.0.0.1", extIP.String(), "should match") diff --git a/gather.go b/gather.go index 4c356f2..8469bae 100644 --- a/gather.go +++ b/gather.go @@ -125,7 +125,7 @@ func (a *Agent) gatherCandidatesLocal(ctx context.Context, networkTypes []Networ } } - // when UDPMux is enabled, skip other UDP candidates + // When UDPMux is enabled, skip other UDP candidates if a.udpMux != nil { if err := a.gatherCandidatesLocalUDPMux(ctx); err != nil { a.log.Warnf("could not create host candidate for UDPMux: %s", err) @@ -202,7 +202,7 @@ func (a *Agent) gatherCandidatesLocal(ctx context.Context, networkTypes []Networ continue } tcpType = TCPTypePassive - // is there a way to verify that the listen address is even + // Is there a way to verify that the listen address is even // accessible from the current interface. case udp: conn, err := listenUDPInPortRange(a.net, a.log, int(a.portMax), int(a.portMin), network, &net.UDPAddr{IP: ip, Port: 0}) diff --git a/gather_test.go b/gather_test.go index 322afc3..14583c2 100644 --- a/gather_test.go +++ b/gather_test.go @@ -108,7 +108,7 @@ func TestGatherConcurrency(t *testing.T) { candidateGatheredFunc() })) - // tesing for panic + // Testing for panic for i := 0; i < 10; i++ { _ = a.GatherCandidates() } @@ -812,11 +812,11 @@ func TestUniversalUDPMuxUsage(t *testing.T) { <-candidateGathered.Done() assert.NoError(t, a.Close()) - // twice because of 2 STUN servers configured + // Twice because of 2 STUN servers configured assert.Equal(t, numSTUNS, udpMuxSrflx.getXORMappedAddrUsedTimes, "expected times that GetXORMappedAddr should be called") - // one for Restart() when agent has been initialized and one time when Close() the agent + // One for Restart() when agent has been initialized and one time when Close() the agent assert.Equal(t, 2, udpMuxSrflx.removeConnByUfragTimes, "expected times that RemoveConnByUfrag should be called") - // twice because of 2 STUN servers configured + // Twice because of 2 STUN servers configured assert.Equal(t, numSTUNS, udpMuxSrflx.getConnForURLTimes, "expected times that GetConnForURL should be called") } diff --git a/gather_vnet_test.go b/gather_vnet_test.go index 52f8479..e87f103 100644 --- a/gather_vnet_test.go +++ b/gather_vnet_test.go @@ -24,7 +24,6 @@ func TestVNetGather(t *testing.T) { defer report() loggerFactory := logging.NewDefaultLoggerFactory() - // log := loggerFactory.NewLogger("test") t.Run("No local IP address", func(t *testing.T) { n, err := vnet.NewNet(&vnet.NetConfig{}) @@ -214,7 +213,7 @@ func TestVNetGatherWithNAT1To1(t *testing.T) { Net: nw, }) assert.NoError(t, err, "should succeed") - defer a.Close() // nolint:errcheck + defer a.Close() //nolint:errcheck done := make(chan struct{}) err = a.OnCandidate(func(c Candidate) { @@ -314,7 +313,7 @@ func TestVNetGatherWithNAT1To1(t *testing.T) { Net: nw, }) assert.NoError(t, err, "should succeed") - defer a.Close() // nolint:errcheck + defer a.Close() //nolint:errcheck done := make(chan struct{}) err = a.OnCandidate(func(c Candidate) { diff --git a/net.go b/net.go index 630103a..134b39c 100644 --- a/net.go +++ b/net.go @@ -52,10 +52,10 @@ func localInterfaces(n transport.Net, interfaceFilter func(string) bool, ipFilte for _, iface := range ifaces { if iface.Flags&net.FlagUp == 0 { - continue // interface down + continue // Interface down } if (iface.Flags&net.FlagLoopback != 0) && !includeLoopback { - continue // loopback interface + continue // Loopback interface } if interfaceFilter != nil && !interfaceFilter(iface.Name) { diff --git a/selection.go b/selection.go index b14130b..5fd396c 100644 --- a/selection.go +++ b/selection.go @@ -198,7 +198,7 @@ func (s *controlledSelector) PingCandidate(local, remote Candidate) { } func (s *controlledSelector) HandleSuccessResponse(m *stun.Message, local, remote Candidate, remoteAddr net.Addr) { - // nolint:godox + //nolint:godox // TODO according to the standard we should specifically answer a failed nomination: // https://tools.ietf.org/html/rfc8445#section-7.3.1.5 // If the controlled agent does not accept the request from the @@ -288,8 +288,8 @@ type liteSelector struct { // A lite selector should not contact candidates func (s *liteSelector) ContactCandidates() { if _, ok := s.pairCandidateSelector.(*controllingSelector); ok { - // nolint:godox - // pion/ice#96 + //nolint:godox + // https://github.com/pion/ice/issues/96 // TODO: implement lite controlling agent. For now falling back to full agent. // This only happens if both peers are lite. See RFC 8445 S6.1.1 and S6.2 s.pairCandidateSelector.ContactCandidates() diff --git a/tcp_mux.go b/tcp_mux.go index d67ba83..0d26fbf 100644 --- a/tcp_mux.go +++ b/tcp_mux.go @@ -71,7 +71,7 @@ type TCPMuxParams struct { Logger logging.LeveledLogger ReadBufferSize int - // max buffer size for write op. 0 means no write buffer, the write op will block until the whole packet is written + // Maximum buffer size for write op. 0 means no write buffer, the write op will block until the whole packet is written // if the write buffer is full, the subsequent write packet will be dropped until it has enough space. // a default 4MB is recommended. WriteBufferSize int @@ -207,7 +207,7 @@ func (m *TCPMuxDefault) handleConn(conn net.Conn) { return } - if m == nil || msg.Type.Method != stun.MethodBinding { // not a stun + if m == nil || msg.Type.Method != stun.MethodBinding { // Not a STUN m.closeAndLogError(conn) m.params.Logger.Warnf("Not a STUN message from %s to %s", conn.RemoteAddr(), conn.LocalAddr()) return diff --git a/tcp_mux_multi_test.go b/tcp_mux_multi_test.go index 906db32..644cb17 100644 --- a/tcp_mux_multi_test.go +++ b/tcp_mux_multi_test.go @@ -81,7 +81,7 @@ func TestMultiTCPMux_Recv(t *testing.T) { assert.Equal(t, n, n2, "received byte size mismatch") assert.Equal(t, msg.Raw, recv, "received bytes mismatch") - // check echo response + // Check echo response n, err = pktConn.WriteTo(recv, conn.LocalAddr()) require.NoError(t, err, "error writing echo stun packet") recvEcho := make([]byte, n) diff --git a/tcp_mux_test.go b/tcp_mux_test.go index 6324cf2..5c96c21 100644 --- a/tcp_mux_test.go +++ b/tcp_mux_test.go @@ -78,7 +78,7 @@ func TestTCPMux_Recv(t *testing.T) { assert.Equal(t, n, n2, "received byte size mismatch") assert.Equal(t, msg.Raw, recv, "received bytes mismatch") - // check echo response + // Check echo response n, err = pktConn.WriteTo(recv, conn.LocalAddr()) require.NoError(t, err, "error writing echo stun packet") recvEcho := make([]byte, n) diff --git a/tcp_packet_conn.go b/tcp_packet_conn.go index b5be955..8c51fd1 100644 --- a/tcp_packet_conn.go +++ b/tcp_packet_conn.go @@ -159,7 +159,6 @@ func (t *tcpPacketConn) startReading(conn net.Conn) { for { n, err := readStreamingPacket(conn, buf) - // t.params.Logger.Infof("readStreamingPacket read %d bytes", n) if err != nil { t.params.Logger.Infof("%v: %s", errReadingStreamingPacket, err) t.handleRecv(streamingPacket{nil, conn.RemoteAddr(), err}) @@ -170,7 +169,6 @@ func (t *tcpPacketConn) startReading(conn net.Conn) { data := make([]byte, n) copy(data, buf[:n]) - // t.params.Logger.Infof("Writing read streaming packet to recvChan: %d bytes", len(data)) t.handleRecv(streamingPacket{data, conn.RemoteAddr(), nil}) } } @@ -229,15 +227,6 @@ func (t *tcpPacketConn) WriteTo(buf []byte, rAddr net.Addr) (n int, err error) { if !ok { return 0, io.ErrClosedPipe - // conn, err := net.DialTCP(tcp, nil, rAddr.(*net.TCPAddr)) - - // if err != nil { - // t.params.Logger.Tracef("DialTCP error: %s", err) - // return 0, err - // } - - // go t.startReading(conn) - // t.conns[rAddr.String()] = conn } n, err = writeStreamingPacket(conn, buf) diff --git a/transport.go b/transport.go index 2a2c528..cd37a9b 100644 --- a/transport.go +++ b/transport.go @@ -52,7 +52,7 @@ func (a *Agent) connect(ctx context.Context, isControlling bool, remoteUfrag, re return nil, err } - // block until pair selected + // Block until pair selected select { case <-a.done: return nil, a.getErr() diff --git a/transport_test.go b/transport_test.go index 3cb4d7c..b47287d 100644 --- a/transport_test.go +++ b/transport_test.go @@ -31,7 +31,7 @@ func TestStressDuplex(t *testing.T) { func testTimeout(t *testing.T, c *Conn, timeout time.Duration) { const pollRate = 100 * time.Millisecond - const margin = 20 * time.Millisecond // allow 20msec error in time + const margin = 20 * time.Millisecond // Allow 20msec error in time ticker := time.NewTicker(pollRate) defer func() { ticker.Stop() @@ -52,7 +52,7 @@ func testTimeout(t *testing.T, c *Conn, timeout time.Duration) { cs = agent.connectionState }) if err != nil { - // we should never get here. + // We should never get here. panic(err) } @@ -86,7 +86,7 @@ func TestTimeout(t *testing.T) { ca, cb := pipe(nil) err := cb.Close() if err != nil { - // we should never get here. + // We should never get here. panic(err) } @@ -97,7 +97,7 @@ func TestTimeout(t *testing.T) { ca, cb := pipeWithTimeout(5*time.Second, 3*time.Second) err := cb.Close() if err != nil { - // we should never get here. + // We should never get here. panic(err) } @@ -118,13 +118,13 @@ func TestReadClosed(t *testing.T) { err := ca.Close() if err != nil { - // we should never get here. + // We should never get here. panic(err) } err = cb.Close() if err != nil { - // we should never get here. + // We should never get here. panic(err) } @@ -354,13 +354,13 @@ func TestConnStats(t *testing.T) { err := ca.Close() if err != nil { - // we should never get here. + // We should never get here. panic(err) } err = cb.Close() if err != nil { - // we should never get here. + // We should never get here. panic(err) } } diff --git a/udp_mux.go b/udp_mux.go index e41579a..405bb7b 100644 --- a/udp_mux.go +++ b/udp_mux.go @@ -38,12 +38,12 @@ type UDPMuxDefault struct { addressMapMu sync.RWMutex addressMap map[string]*udpMuxedConn - // buffer pool to recycle buffers for net.UDPAddr encodes/decodes + // Buffer pool to recycle buffers for net.UDPAddr encodes/decodes pool *sync.Pool mu sync.Mutex - // for UDP connection listen at unspecified address + // For UDP connection listen at unspecified address localAddrsForUnspecified []net.Addr } @@ -112,7 +112,7 @@ func NewUDPMuxDefault(params UDPMuxParams) *UDPMuxDefault { closedChan: make(chan struct{}, 1), pool: &sync.Pool{ New: func() interface{} { - // big enough buffer to fit both packet and address + // Big enough buffer to fit both packet and address return newBufferHolder(receiveMTU + maxAddrSize) }, }, diff --git a/udp_mux_multi_test.go b/udp_mux_multi_test.go index d9d85dd..f62dc17 100644 --- a/udp_mux_multi_test.go +++ b/udp_mux_multi_test.go @@ -32,7 +32,7 @@ func TestMultiUDPMux(t *testing.T) { conn3, err := net.ListenUDP(udp, &net.UDPAddr{IP: net.IPv6loopback}) if err != nil { - // ipv6 is not supported on this machine + // IPv6 is not supported on this machine t.Log("ipv6 is not supported on this machine") } @@ -66,7 +66,7 @@ func TestMultiUDPMux(t *testing.T) { testMultiUDPMuxConnections(t, udpMuxMulti, "ufrag2", udp4) }() - // skip ipv6 test on i386 + // Skip ipv6 test on i386 const ptrSize = 32 << (^uintptr(0) >> 63) if ptrSize != 32 { testMultiUDPMuxConnections(t, udpMuxMulti, "ufrag3", udp6) @@ -76,7 +76,7 @@ func TestMultiUDPMux(t *testing.T) { require.NoError(t, udpMuxMulti.Close()) - // can't create more connections + // Can't create more connections _, err = udpMuxMulti.GetConn("failufrag", conn1.LocalAddr()) require.Error(t, err) } @@ -143,7 +143,7 @@ func TestUnspecifiedUDPMux(t *testing.T) { testMultiUDPMuxConnections(t, udpMuxMulti, "ufrag2", udp4) }() - // skip ipv6 test on i386 + // Skip IPv6 test on i386 const ptrSize = 32 << (^uintptr(0) >> 63) if ptrSize != 32 { testMultiUDPMuxConnections(t, udpMuxMulti, "ufrag3", udp6) diff --git a/udp_mux_test.go b/udp_mux_test.go index c6e3ab8..3fad1cc 100644 --- a/udp_mux_test.go +++ b/udp_mux_test.go @@ -91,7 +91,7 @@ func TestUDPMux(t *testing.T) { defer wg.Done() testMuxConnection(t, udpMux, "ufrag2", udp4) }() - // skip ipv6 test on i386 + // Skip IPv6 test on i386 if ptrSize != 32 { testMuxConnection(t, udpMux, "ufrag3", udp6) } @@ -103,7 +103,7 @@ func TestUDPMux(t *testing.T) { require.NoError(t, udpMux.Close()) - // can't create more connections + // Can't create more connections _, err = udpMux.GetConn("failufrag", udpMux.LocalAddr()) require.Error(t, err) }) @@ -169,13 +169,13 @@ func testMuxConnection(t *testing.T, udpMux *UDPMuxDefault, ufrag string, networ } func testMuxConnectionPair(t *testing.T, pktConn net.PacketConn, remoteConn *net.UDPConn, ufrag string) { - // initial messages are dropped + // Initial messages are dropped _, err := remoteConn.Write([]byte("dropped bytes")) require.NoError(t, err) - // wait for packet to be consumed + // Wait for packet to be consumed time.Sleep(time.Millisecond) - // write out to establish connection + // Write out to establish connection msg := stun.New() msg.Type = stun.MessageType{Method: stun.MethodBinding, Class: stun.ClassRequest} msg.Add(stun.AttrUsername, []byte(ufrag+":otherufrag")) @@ -183,18 +183,18 @@ func testMuxConnectionPair(t *testing.T, pktConn net.PacketConn, remoteConn *net _, err = pktConn.WriteTo(msg.Raw, remoteConn.LocalAddr()) require.NoError(t, err) - // ensure received + // Ensure received buf := make([]byte, receiveMTU) n, err := remoteConn.Read(buf) require.NoError(t, err) require.Equal(t, msg.Raw, buf[:n]) - // start writing packets through mux + // Start writing packets through mux targetSize := 1 * 1024 * 1024 readDone := make(chan struct{}, 1) remoteReadDone := make(chan struct{}, 1) - // read packets from the muxed side + // Read packets from the muxed side go func() { defer func() { t.Logf("closing read chan for: %s", ufrag) @@ -209,7 +209,7 @@ func testMuxConnectionPair(t *testing.T, pktConn net.PacketConn, remoteConn *net verifyPacket(t, readBuf[:n], nextSeq) - // write it back to sender + // Write it back to sender _, err = pktConn.WriteTo(readBuf[:n], remoteConn.LocalAddr()) require.NoError(t, err) @@ -239,9 +239,9 @@ func testMuxConnectionPair(t *testing.T, pktConn net.PacketConn, remoteConn *net sequence := 0 for written := 0; written < targetSize; { buf := make([]byte, receiveMTU) - // byte0-4: sequence - // bytes4-24: sha1 checksum - // bytes24-mtu: random data + // Byte 0-4: sequence + // Bytes 4-24: sha1 checksum + // Bytes2 4-mtu: random data _, err := rand.Read(buf[24:]) require.NoError(t, err) h := sha1.Sum(buf[24:]) //nolint:gosec diff --git a/udp_mux_universal.go b/udp_mux_universal.go index d8ef312..a117250 100644 --- a/udp_mux_universal.go +++ b/udp_mux_universal.go @@ -29,7 +29,7 @@ type UniversalUDPMuxDefault struct { *UDPMuxDefault params UniversalUDPMuxParams - // since we have a shared socket, for srflx candidates it makes sense to have a shared mapped address across all the agents + // Since we have a shared socket, for srflx candidates it makes sense to have a shared mapped address across all the agents // stun.XORMappedAddress indexed by the STUN server addr xorMappedMap map[string]*xorMapped } @@ -56,7 +56,7 @@ func NewUniversalUDPMuxDefault(params UniversalUDPMuxParams) *UniversalUDPMuxDef xorMappedMap: make(map[string]*xorMapped), } - // wrap UDP connection, process server reflexive messages + // Wrap UDP connection, process server reflexive messages // before they are passed to the UDPMux connection handler (connWorker) m.params.UDPConn = &udpConn{ PacketConn: params.UDPConn, @@ -64,7 +64,7 @@ func NewUniversalUDPMuxDefault(params UniversalUDPMuxParams) *UniversalUDPMuxDef logger: params.Logger, } - // embed UDPMux + // Embed UDPMux udpMuxParams := UDPMuxParams{ Logger: params.Logger, UDPConn: m.params.UDPConn, @@ -115,7 +115,7 @@ func (c *udpConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) { udpAddr, ok := addr.(*net.UDPAddr) if !ok { - // message about this err will be logged in the UDPMux + // Message about this err will be logged in the UDPMux return } @@ -135,7 +135,7 @@ func (c *udpConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) { func (m *UniversalUDPMuxDefault) isXORMappedResponse(msg *stun.Message, stunAddr string) bool { m.mu.Lock() defer m.mu.Unlock() - // check first if it is a STUN server address because remote peer can also send similar messages but as a BindingSuccess + // Check first if it is a STUN server address because remote peer can also send similar messages but as a BindingSuccess _, ok := m.xorMappedMap[stunAddr] _, err := msg.Get(stun.AttrXORMappedAddress) return err == nil && ok @@ -170,7 +170,7 @@ func (m *UniversalUDPMuxDefault) handleXORMappedResponse(stunAddr *net.UDPAddr, func (m *UniversalUDPMuxDefault) GetXORMappedAddr(serverAddr net.Addr, deadline time.Duration) (*stun.XORMappedAddress, error) { m.mu.Lock() mappedAddr, ok := m.xorMappedMap[serverAddr.String()] - // if we already have a mapping for this STUN server (address already received) + // If we already have a mapping for this STUN server (address already received) // and if it is not too old we return it without making a new request to STUN server if ok { if mappedAddr.expired() { @@ -186,17 +186,17 @@ func (m *UniversalUDPMuxDefault) GetXORMappedAddr(serverAddr net.Addr, deadline return mappedAddr.addr, nil } - // otherwise, make a STUN request to discover the address + // Otherwise, make a STUN request to discover the address // or wait for already sent request to complete waitAddrReceived, err := m.sendStun(serverAddr) if err != nil { return nil, fmt.Errorf("%w: %s", errSendSTUNPacket, err) //nolint:errorlint } - // block until response was handled by the connWorker routine and XORMappedAddress was updated + // Block until response was handled by the connWorker routine and XORMappedAddress was updated select { case <-waitAddrReceived: - // when channel closed, addr was obtained + // When channel closed, addr was obtained m.mu.Lock() mappedAddr := *m.xorMappedMap[serverAddr.String()] m.mu.Unlock() @@ -217,7 +217,7 @@ func (m *UniversalUDPMuxDefault) sendStun(serverAddr net.Addr) (chan struct{}, e m.mu.Lock() defer m.mu.Unlock() - // if record present in the map, we already sent a STUN request, + // If record present in the map, we already sent a STUN request, // just wait when waitAddrReceived will be closed addrMap, ok := m.xorMappedMap[serverAddr.String()] if !ok { @@ -249,11 +249,10 @@ type xorMapped struct { func (a *xorMapped) closeWaiters() { select { case <-a.waitAddrReceived: - // notify was close, ok, that means we received duplicate response - // just exit + // Notify was close, ok, that means we received duplicate response just exit break default: - // notify tha twe have a new addr + // Notify tha twe have a new addr close(a.waitAddrReceived) } } diff --git a/udp_mux_universal_test.go b/udp_mux_universal_test.go index edbfc77..84bf47e 100644 --- a/udp_mux_universal_test.go +++ b/udp_mux_universal_test.go @@ -57,7 +57,7 @@ func testMuxSrflxConnection(t *testing.T, udpMux *UniversalUDPMuxDefault, ufrag _ = remoteConn.Close() }() - // use small value for TTL to check expiration of the address + // Use small value for TTL to check expiration of the address udpMux.params.XORMappedAddrCacheTTL = time.Millisecond * 20 testXORIP := net.ParseIP("213.141.156.236") testXORPort := 21254 @@ -73,10 +73,10 @@ func testMuxSrflxConnection(t *testing.T, udpMux *UniversalUDPMuxDefault, ufrag require.Equal(t, address.Port, testXORPort) }() - // wait until GetXORMappedAddr calls sendStun method + // Wait until GetXORMappedAddr calls sendStun method time.Sleep(time.Millisecond) - // check that mapped address filled correctly after sent stun + // Check that mapped address filled correctly after sent stun udpMux.mu.Lock() mappedAddr, ok := udpMux.xorMappedMap[remoteConn.LocalAddr().String()] require.True(t, ok) @@ -85,12 +85,12 @@ func testMuxSrflxConnection(t *testing.T, udpMux *UniversalUDPMuxDefault, ufrag require.False(t, mappedAddr.expired()) udpMux.mu.Unlock() - // clean receiver read buffer + // Clean receiver read buffer buf := make([]byte, receiveMTU) _, err = remoteConn.Read(buf) require.NoError(t, err) - // write back to udpMux XOR message with address + // Write back to udpMux XOR message with address msg := stun.New() msg.Type = stun.MessageType{Method: stun.MethodBinding, Class: stun.ClassRequest} msg.Add(stun.AttrUsername, []byte(ufrag+":otherufrag")) @@ -105,24 +105,24 @@ func testMuxSrflxConnection(t *testing.T, udpMux *UniversalUDPMuxDefault, ufrag _, err = remoteConn.Write(msg.Raw) require.NoError(t, err) - // wait for the packet to be consumed and parsed by udpMux + // Wait for the packet to be consumed and parsed by udpMux wg.Wait() - // we should get address immediately from the cached map + // We should get address immediately from the cached map address, err := udpMux.GetXORMappedAddr(remoteConn.LocalAddr(), time.Second) require.NoError(t, err) require.NotNil(t, address) udpMux.mu.Lock() - // check mappedAddr is not pending, we didn't send stun twice + // Check mappedAddr is not pending, we didn't send stun twice require.False(t, mappedAddr.pending()) - // check expiration by TTL + // Check expiration by TTL time.Sleep(time.Millisecond * 21) require.True(t, mappedAddr.expired()) udpMux.mu.Unlock() - // after expire, we send stun request again + // After expire, we send stun request again // but we not receive response in 5 milliseconds and should get error here address, err = udpMux.GetXORMappedAddr(remoteConn.LocalAddr(), time.Millisecond*5) require.NotNil(t, err) diff --git a/udp_muxed_conn.go b/udp_muxed_conn.go index 79b0ff5..09e4b3a 100644 --- a/udp_muxed_conn.go +++ b/udp_muxed_conn.go @@ -25,10 +25,10 @@ type udpMuxedConnParams struct { // udpMuxedConn represents a logical packet conn for a single remote as identified by ufrag type udpMuxedConn struct { params *udpMuxedConnParams - // remote addresses that we have sent to on this conn + // Remote addresses that we have sent to on this conn addresses []string - // channel holding incoming packets + // Channel holding incoming packets buf *packetio.Buffer closedChan chan struct{} closeOnce sync.Once @@ -49,7 +49,7 @@ func (c *udpMuxedConn) ReadFrom(b []byte) (n int, rAddr net.Addr, err error) { buf := c.params.AddrPool.Get().(*bufferHolder) //nolint:forcetypeassert defer c.params.AddrPool.Put(buf) - // read address + // Read address total, err := c.buf.Read(buf.buf) if err != nil { return 0, nil, err @@ -60,12 +60,12 @@ func (c *udpMuxedConn) ReadFrom(b []byte) (n int, rAddr net.Addr, err error) { return 0, nil, io.ErrShortBuffer } - // read data and then address + // Read data and then address offset := 2 copy(b, buf.buf[offset:offset+dataLen]) offset += dataLen - // read address len & decode address + // Read address len & decode address addrLen := int(binary.LittleEndian.Uint16(buf.buf[offset : offset+2])) offset += 2 @@ -80,7 +80,7 @@ func (c *udpMuxedConn) WriteTo(buf []byte, rAddr net.Addr) (n int, err error) { if c.isClosed() { return 0, io.ErrClosedPipe } - // each time we write to a new address, we'll register it with the mux + // Each time we write to a new address, we'll register it with the mux addr := rAddr.String() if !c.containsAddress(addr) { c.addAddress(addr) @@ -140,7 +140,7 @@ func (c *udpMuxedConn) addAddress(addr string) { c.addresses = append(c.addresses, addr) c.mu.Unlock() - // map it on mux + // Map it on mux c.params.Mux.registerConnForAddress(c, addr) } @@ -170,30 +170,30 @@ func (c *udpMuxedConn) containsAddress(addr string) bool { } func (c *udpMuxedConn) writePacket(data []byte, addr *net.UDPAddr) error { - // write two packets, address and data + // Write two packets, address and data buf := c.params.AddrPool.Get().(*bufferHolder) //nolint:forcetypeassert defer c.params.AddrPool.Put(buf) - // format of buffer | data len | data bytes | addr len | addr bytes | + // Format of buffer | data len | data bytes | addr len | addr bytes | if len(buf.buf) < len(data)+maxAddrSize { return io.ErrShortBuffer } - // data len + // Data length binary.LittleEndian.PutUint16(buf.buf, uint16(len(data))) offset := 2 - // data + // Data copy(buf.buf[offset:], data) offset += len(data) - // write address first, leaving room for its length + // Write address first, leaving room for its length n, err := encodeUDPAddr(addr, buf.buf[offset+2:]) if err != nil { return err } total := offset + n + 2 - // address len + // Address len binary.LittleEndian.PutUint16(buf.buf[offset:], uint16(n)) if _, err := c.buf.Write(buf.buf[:total]); err != nil { @@ -228,7 +228,7 @@ func decodeUDPAddr(buf []byte) (*net.UDPAddr, error) { offset := 0 ipLen := int(binary.LittleEndian.Uint16(buf[:2])) offset += 2 - // basic bounds checking + // Basic bounds checking if ipLen+offset > len(buf) { return nil, io.ErrShortBuffer }