Skip to content

Commit

Permalink
Fix types and comment capitalization
Browse files Browse the repository at this point in the history
Fix types and comment capitalization
  • Loading branch information
stv0g committed Apr 12, 2023
1 parent 79fbb4e commit b674ab6
Show file tree
Hide file tree
Showing 24 changed files with 145 additions and 150 deletions.
52 changes: 26 additions & 26 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ import (

const (
defaultRTO = 200 * time.Millisecond
maxRtxCount = 7 // total 7 requests (Rc)
maxDataBufferSize = math.MaxUint16 // message size limit for Chromium
maxRtxCount = 7 // Total 7 requests (Rc)
maxDataBufferSize = math.MaxUint16 // Message size limit for Chromium
)

// interval [msec]
Expand Down Expand Up @@ -45,23 +45,23 @@ type ClientConfig struct {

// Client is a STUN server client
type Client struct {
conn net.PacketConn // read-only
stunServerAddr net.Addr // read-only
turnServerAddr net.Addr // read-only

username stun.Username // read-only
password string // read-only
realm stun.Realm // read-only
integrity stun.MessageIntegrity // read-only
software stun.Software // read-only
trMap *client.TransactionMap // thread-safe
rto time.Duration // read-only
relayedConn *client.UDPConn // protected by mutex ***
allocTryLock client.TryLock // thread-safe
listenTryLock client.TryLock // thread-safe
mutex sync.RWMutex // thread-safe
mutexTrMap sync.Mutex // thread-safe
log logging.LeveledLogger // read-only
conn net.PacketConn // Read-only
stunServerAddr net.Addr // Read-only
turnServerAddr net.Addr // Read-only

username stun.Username // Read-only
password string // Read-only
realm stun.Realm // Read-only
integrity stun.MessageIntegrity // Read-only
software stun.Software // Read-only
trMap *client.TransactionMap // Thread-safe
rto time.Duration // Read-only
relayedConn *client.UDPConn // Protected by mutex ***
allocTryLock client.TryLock // Thread-safe
listenTryLock client.TryLock // Thread-safe
mutex sync.RWMutex // Thread-safe
mutexTrMap sync.Mutex // Thread-safe
log logging.LeveledLogger // Tead-only
}

// NewClient returns a new Client instance. listeningAddress is the address and port to listen on, default "0.0.0.0:0"
Expand Down Expand Up @@ -381,10 +381,10 @@ func (c *Client) HandleInbound(data []byte, from net.Addr) (bool, error) {
case proto.IsChannelData(data):
return true, c.handleChannelData(data)
case from.String() == c.stunServerAddr.String():
// received from STUN server but it is not a STUN message
// Received from STUN server but it is not a STUN message
return true, errNonSTUNMessage
default:
// assume, this is an application data
// Assume, this is an application data
c.log.Tracef("non-STUN/TURN packet, unhandled")
}

Expand Down Expand Up @@ -425,7 +425,7 @@ func (c *Client) handleSTUNMessage(data []byte, from net.Addr) error {
relayedConn := c.relayedUDPConn()
if relayedConn == nil {
c.log.Debug("no relayed conn allocated")
return nil // silently discard
return nil // Silently discard
}

relayedConn.HandleInbound(data, from)
Expand All @@ -444,7 +444,7 @@ func (c *Client) handleSTUNMessage(data []byte, from net.Addr) error {
tr, ok := c.trMap.Find(trKey)
if !ok {
c.mutexTrMap.Unlock()
// silently discard
// Silently discard
c.log.Debugf("no transaction for %s", msg.String())
return nil
}
Expand Down Expand Up @@ -477,7 +477,7 @@ func (c *Client) handleChannelData(data []byte) error {
relayedConn := c.relayedUDPConn()
if relayedConn == nil {
c.log.Debug("no relayed conn allocated")
return nil // silently discard
return nil // Silently discard
}

addr, ok := relayedConn.FindAddrByChannelNumber(uint16(chData.Number))
Expand All @@ -497,11 +497,11 @@ func (c *Client) onRtxTimeout(trKey string, nRtx int) {

tr, ok := c.trMap.Find(trKey)
if !ok {
return // already gone
return // Already gone
}

if nRtx == maxRtxCount {
// all retransmissions failed
// All retransmissions failed
c.trMap.Delete(trKey)
if !tr.WriteResult(client.TransactionResult{
Err: fmt.Errorf("%w %s", errAllRetransmissionsFailed, trKey),
Expand Down
13 changes: 3 additions & 10 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ func TestClientWithSTUN(t *testing.T) {
}
defer c.Close()

// simple channel fo go routine start signaling
// Simple channel fo go routine start signaling
started := make(chan struct{})
finished := make(chan struct{})
var err1 error
Expand All @@ -87,8 +87,7 @@ func TestClientWithSTUN(t *testing.T) {
close(finished)
}()

// block until go routine is started to make two almost parallel requests

// Block until go routine is started to make two almost parallel requests
<-started

if _, err = c.SendBindingRequestTo(to); err != nil {
Expand Down Expand Up @@ -120,7 +119,7 @@ func TestClientWithSTUN(t *testing.T) {
to, err := net.ResolveUDPAddr("udp4", "127.0.0.1:9")
assert.NoError(t, err)

c.rto = 10 * time.Millisecond // force short timeout
c.rto = 10 * time.Millisecond // Force short timeout

_, err = c.SendBindingRequestTo(to)
assert.NotNil(t, err)
Expand All @@ -132,12 +131,6 @@ func TestClientWithSTUN(t *testing.T) {
// The subsequent Write on the allocation will cause a CreatePermission
// which will be forced to handle a stale nonce response
func TestClientNonceExpiration(t *testing.T) {
// lim := test.TimeOut(time.Second * 30)
// defer lim.Stop()

// report := test.CheckRoutines(t)
// defer report()

udpListener, err := net.ListenPacket("udp4", "0.0.0.0:3478")
assert.NoError(t, err)

Expand Down
4 changes: 2 additions & 2 deletions examples/lt-cred-generator/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,10 @@ func main() {
}

u, p, _ := turn.GenerateLongTermCredentials(*authSecret, time.Minute)
if _, err := os.Stdout.WriteString(fmt.Sprintf("%s=%s", u, p)); err != nil { // for use with xargs
if _, err := os.Stdout.WriteString(fmt.Sprintf("%s=%s", u, p)); err != nil { // For use with xargs
log.Panicf("Failed to write to stdout: %s", err)
}
if _, err := os.Stderr.WriteString("\n"); err != nil { // ignored by xargs
if _, err := os.Stderr.WriteString("\n"); err != nil { // Ignored by xargs
log.Panicf("Failed to write to stderr: %s", err)
}
}
2 changes: 1 addition & 1 deletion examples/turn-server/perm-filter/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ func main() {
s, err := turn.NewServer(turn.ServerConfig{
Realm: *realm,
// Set AuthHandler callback
// This is called everytime a user tries to authenticate with the TURN server
// This is called every time a user tries to authenticate with the TURN server
// Return the key for that user, or false when no user is found
AuthHandler: func(username string, realm string, srcAddr net.Addr) ([]byte, bool) {
if key, ok := usersMap[username]; ok {
Expand Down
6 changes: 3 additions & 3 deletions internal/allocation/allocation.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,10 @@ type Allocation struct {
closed chan interface{}
log logging.LeveledLogger

// some clients (Firefox or others using resiprocate's nICE lib) may retry allocation
// Some clients (Firefox or others using resiprocate's nICE lib) may retry allocation
// with same 5 tuple when received 413, for compatible with these clients,
// cache for response lost and client retry to implement 'stateless stack approach'
// https://datatracker.ietf.org/doc/html/rfc5766#section-6.2
// See: https://datatracker.ietf.org/doc/html/rfc5766#section-6.2
responseCache atomic.Value // *allocationResponse
}

Expand All @@ -48,7 +48,7 @@ func addr2IPFingerprint(addr net.Addr) string {
case *net.TCPAddr: // Do we really need this case?
return a.IP.String()
}
return "" // should never happen
return "" // Should never happen
}

// NewAllocation creates a new instance of NewAllocation.
Expand Down
2 changes: 1 addition & 1 deletion internal/allocation/allocation_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ func (m *Manager) GetRandomEvenPort() (int, error) {
// GrantPermission handles permission requests by calling the permission handler callback
// associated with the TURN server listener socket
func (m *Manager) GrantPermission(sourceAddr net.Addr, peerIP net.IP) error {
// no permission handler: open
// No permission handler: open
if m.permissionHandler == nil {
return nil
}
Expand Down
14 changes: 7 additions & 7 deletions internal/allocation/allocation_manager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ func TestManager(t *testing.T) {
}
}

// test invalid Allocation creations
// Test invalid Allocation creations
func subTestCreateInvalidAllocation(t *testing.T, turnSocket net.PacketConn) {
m, err := newTestManager()
assert.NoError(t, err)
Expand All @@ -60,7 +60,7 @@ func subTestCreateInvalidAllocation(t *testing.T, turnSocket net.PacketConn) {
}
}

// test valid Allocation creations
// Test valid Allocation creations
func subTestCreateAllocation(t *testing.T, turnSocket net.PacketConn) {
m, err := newTestManager()
assert.NoError(t, err)
Expand All @@ -75,7 +75,7 @@ func subTestCreateAllocation(t *testing.T, turnSocket net.PacketConn) {
}
}

// test that two allocations can't be created with the same FiveTuple
// Test that two allocations can't be created with the same FiveTuple
func subTestCreateAllocationDuplicateFiveTuple(t *testing.T, turnSocket net.PacketConn) {
m, err := newTestManager()
assert.NoError(t, err)
Expand Down Expand Up @@ -109,7 +109,7 @@ func subTestDeleteAllocation(t *testing.T, turnSocket net.PacketConn) {
}
}

// test that allocation should be closed if timeout
// Test that allocation should be closed if timeout
func subTestAllocationTimeout(t *testing.T, turnSocket net.PacketConn) {
m, err := newTestManager()
assert.NoError(t, err)
Expand All @@ -128,7 +128,7 @@ func subTestAllocationTimeout(t *testing.T, turnSocket net.PacketConn) {
allocations[index] = a
}

// make sure all allocations timeout
// Make sure all allocations timeout
time.Sleep(lifetime + time.Second)
for _, alloc := range allocations {
if !isClose(alloc.RelaySocket) {
Expand All @@ -137,7 +137,7 @@ func subTestAllocationTimeout(t *testing.T, turnSocket net.PacketConn) {
}
}

// test for manager close
// Test for manager close
func subTestManagerClose(t *testing.T, turnSocket net.PacketConn) {
m, err := newTestManager()
assert.NoError(t, err)
Expand All @@ -149,7 +149,7 @@ func subTestManagerClose(t *testing.T, turnSocket net.PacketConn) {
a2, _ := m.CreateAllocation(randomFiveTuple(), turnSocket, 0, time.Minute)
allocations[1] = a2

// make a1 timeout
// Make a1 timeout
time.Sleep(2 * time.Second)

if err := m.Close(); err != nil {
Expand Down
28 changes: 14 additions & 14 deletions internal/allocation/allocation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ func subTestAllocationRefresh(t *testing.T) {
a.Refresh(0)
wg.Wait()

// lifetimeTimer has expired
// LifetimeTimer has expired
assert.False(t, a.lifetimeTimer.Stop())
}

Expand All @@ -235,10 +235,10 @@ func subTestAllocationClose(t *testing.T) {

a := NewAllocation(nil, nil, nil)
a.RelaySocket = l
// add mock lifetimeTimer
// Add mock lifetimeTimer
a.lifetimeTimer = time.AfterFunc(proto.DefaultLifetime, func() {})

// add channel
// Add channel
addr, err := net.ResolveUDPAddr(network, "127.0.0.1:3478")
if err != nil {
t.Fatalf("failed to resolve: %s", err)
Expand All @@ -247,7 +247,7 @@ func subTestAllocationClose(t *testing.T) {
c := NewChannelBind(proto.MinChannelNumber, addr, nil)
_ = a.AddChannelBind(c, proto.DefaultLifetime)

// add permission
// Add permission
a.AddPermission(NewPermission(addr, nil))

err = a.Close()
Expand All @@ -260,20 +260,20 @@ func subTestPacketHandler(t *testing.T) {

m, _ := newTestManager()

// turn server initialization
// TURN server initialization
turnSocket, err := net.ListenPacket(network, "127.0.0.1:0")
if err != nil {
panic(err)
}

// client listener initialization
// Client listener initialization
clientListener, err := net.ListenPacket(network, "127.0.0.1:0")
if err != nil {
panic(err)
}

dataCh := make(chan []byte)
// client listener read data
// Client listener read data
go func() {
buffer := make([]byte, rtpMTU)
for {
Expand Down Expand Up @@ -303,22 +303,22 @@ func subTestPacketHandler(t *testing.T) {
panic(err)
}

// add permission with peer1 address
// Add permission with peer1 address
a.AddPermission(NewPermission(peerListener1.LocalAddr(), m.log))
// add channel with min channel number and peer2 address
// Add channel with min channel number and peer2 address
channelBind := NewChannelBind(proto.MinChannelNumber, peerListener2.LocalAddr(), m.log)
_ = a.AddChannelBind(channelBind, proto.DefaultLifetime)

_, port, _ := ipnet.AddrIPPort(a.RelaySocket.LocalAddr())
relayAddrWithHostStr := fmt.Sprintf("127.0.0.1:%d", port)
relayAddrWithHost, _ := net.ResolveUDPAddr(network, relayAddrWithHostStr)

// test for permission and data message
// Test for permission and data message
targetText := "permission"
_, _ = peerListener1.WriteTo([]byte(targetText), relayAddrWithHost)
data := <-dataCh

// resolve stun data message
// Resolve stun data message
assert.True(t, stun.IsMessage(data), "should be stun message")

var msg stun.Message
Expand All @@ -330,12 +330,12 @@ func subTestPacketHandler(t *testing.T) {
assert.Nil(t, err, "get data from stun message failed")
assert.Equal(t, targetText, string(msgData), "get message doesn't equal the target text")

// test for channel bind and channel data
// Test for channel bind and channel data
targetText2 := "channel bind"
_, _ = peerListener2.WriteTo([]byte(targetText2), relayAddrWithHost)
data = <-dataCh

// resolve channel data
// Resolve channel data
assert.True(t, proto.IsChannelData(data), "should be channel data")

channelData := proto.ChannelData{
Expand All @@ -346,7 +346,7 @@ func subTestPacketHandler(t *testing.T) {
assert.Equal(t, channelBind.Number, channelData.Number, "get channel data's number is invalid")
assert.Equal(t, targetText2, string(channelData.Data), "get data doesn't equal the target text.")

// listeners close
// Listeners close
_ = m.Close()
_ = clientListener.Close()
_ = peerListener1.Close()
Expand Down
2 changes: 1 addition & 1 deletion internal/allocation/channel_bind.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
)

// ChannelBind represents a TURN Channel
// https://tools.ietf.org/html/rfc5766#section-2.5
// See: https://tools.ietf.org/html/rfc5766#section-2.5
type ChannelBind struct {
Peer net.Addr
Number proto.ChannelNumber
Expand Down
2 changes: 1 addition & 1 deletion internal/allocation/permission.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const permissionTimeout = time.Duration(5) * time.Minute

// Permission represents a TURN permission. TURN permissions mimic the address-restricted
// filtering mechanism of NATs that comply with [RFC4787].
// https://tools.ietf.org/html/rfc5766#section-2.3
// See: https://tools.ietf.org/html/rfc5766#section-2.3
type Permission struct {
Addr net.Addr
allocation *Allocation
Expand Down
Loading

0 comments on commit b674ab6

Please sign in to comment.