Skip to content

Commit

Permalink
Upgrade golangci-lint, more linters
Browse files Browse the repository at this point in the history
  • Loading branch information
joeturki committed Jan 11, 2025
1 parent c6bb67a commit 82373d7
Show file tree
Hide file tree
Showing 81 changed files with 1,168 additions and 769 deletions.
49 changes: 31 additions & 18 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,32 @@ linters-settings:
- ^os.Exit$
- ^panic$
- ^print(ln)?$
varnamelen:
max-distance: 12
min-name-length: 2
ignore-type-assert-ok: true
ignore-map-index-ok: true
ignore-chan-recv-ok: true
ignore-decls:
- i int
- n int
- w io.Writer
- r io.Reader
- b []byte

linters:
enable:
- asciicheck # Simple linter to check that your code does not contain non-ASCII identifiers
- bidichk # Checks for dangerous unicode character sequences
- bodyclose # checks whether HTTP response body is closed successfully
- containedctx # containedctx is a linter that detects struct contained context.Context field
- contextcheck # check the function whether use a non-inherited context
- cyclop # checks function and package cyclomatic complexity
- decorder # check declaration order and count of types, constants, variables and functions
- dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f())
- dupl # Tool for code clone detection
- durationcheck # check for two durations multiplied together
- err113 # Golang linter to check the errors handling expressions
- errcheck # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases
- errchkjson # Checks types passed to the json encoding functions. Reports unsupported types and optionally reports occations, where the check for the returned error can be omitted.
- errname # Checks that sentinel errors are prefixed with the `Err` and error types are suffixed with the `Error`.
Expand All @@ -44,68 +59,66 @@ linters:
- exportloopref # checks for pointers to enclosing loop variables
- forbidigo # Forbids identifiers
- forcetypeassert # finds forced type assertions
- funlen # Tool for detection of long functions
- gci # Gci control golang package import order and make it always deterministic.
- gochecknoglobals # Checks that no globals are present in Go code
- gochecknoinits # Checks that no init functions are present in Go code
- gocognit # Computes and checks the cognitive complexity of functions
- goconst # Finds repeated strings that could be replaced by a constant
- gocritic # The most opinionated Go source code linter
- gocyclo # Computes and checks the cyclomatic complexity of functions
- godot # Check if comments end in a period
- godox # Tool for detection of FIXME, TODO and other comment keywords
- err113 # Golang linter to check the errors handling expressions
- gofmt # Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification
- gofumpt # Gofumpt checks whether code was gofumpt-ed.
- goheader # Checks is file header matches to pattern
- goimports # Goimports does everything that gofmt does. Additionally it checks unused imports
- gomoddirectives # Manage the use of 'replace', 'retract', and 'excludes' directives in go.mod.
- gomodguard # Allow and block list linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations.
- goprintffuncname # Checks that printf-like functions are named with `f` at the end
- gosec # Inspects source code for security problems
- gosimple # Linter for Go source code that specializes in simplifying a code
- govet # Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string
- grouper # An analyzer to analyze expression groups.
- importas # Enforces consistent import aliases
- ineffassign # Detects when assignments to existing variables are not used
- lll # Reports long lines
- maintidx # maintidx measures the maintainability index of each function.
- makezero # Finds slice declarations with non-zero initial length
- misspell # Finds commonly misspelled English words in comments
- nakedret # Finds naked returns in functions greater than a specified function length
- nestif # Reports deeply nested if statements
- nilerr # Finds the code that returns nil even if it checks that the error is not nil.
- nilnil # Checks that there is no simultaneous return of `nil` error and an invalid value.
- nlreturn # nlreturn checks for a new line before return and branch statements to increase code clarity
- noctx # noctx finds sending http request without context.Context
- predeclared # find code that shadows one of Go's predeclared identifiers
- revive # golint replacement, finds style mistakes
- staticcheck # Staticcheck is a go vet on steroids, applying a ton of static analysis checks
- stylecheck # Stylecheck is a replacement for golint
- tagliatelle # Checks the struct tags.
- tenv # tenv is analyzer that detects using os.Setenv instead of t.Setenv since Go1.17
- tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes
- thelper # thelper detects golang test helpers without t.Helper() call and checks the consistency of test helpers
- typecheck # Like the front-end of a Go compiler, parses and type-checks Go code
- unconvert # Remove unnecessary type conversions
- unparam # Reports unused function parameters
- unused # Checks Go code for unused constants, variables, functions and types
- varnamelen # checks that the length of a variable's name matches its scope
- wastedassign # wastedassign finds wasted assignment statements
- whitespace # Tool for detection of leading and trailing whitespace
disable:
- depguard # Go linter that checks if package imports are in a list of acceptable packages
- containedctx # containedctx is a linter that detects struct contained context.Context field
- cyclop # checks function and package cyclomatic complexity
- funlen # Tool for detection of long functions
- gocyclo # Computes and checks the cyclomatic complexity of functions
- godot # Check if comments end in a period
- gomnd # An analyzer to detect magic numbers.
- gochecknoinits # Checks that no init functions are present in Go code
- gomodguard # Allow and block list linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations.
- interfacebloat # A linter that checks length of interface.
- ireturn # Accept Interfaces, Return Concrete Types
- lll # Reports long lines
- maintidx # maintidx measures the maintainability index of each function.
- makezero # Finds slice declarations with non-zero initial length
- nakedret # Finds naked returns in functions greater than a specified function length
- nestif # Reports deeply nested if statements
- nlreturn # nlreturn checks for a new line before return and branch statements to increase code clarity
- mnd # An analyzer to detect magic numbers
- nolintlint # Reports ill-formed or insufficient nolint directives
- paralleltest # paralleltest detects missing usage of t.Parallel() method in your Go test
- prealloc # Finds slice declarations that could potentially be preallocated
- promlinter # Check Prometheus metrics naming via promlint
- rowserrcheck # checks whether Err of rows is checked successfully
- sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed.
- testpackage # linter that makes you use a separate _test package
- thelper # thelper detects golang test helpers without t.Helper() call and checks the consistency of test helpers
- varnamelen # checks that the length of a variable's name matches its scope
- tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes
- wrapcheck # Checks that errors returned from external packages are wrapped
- wsl # Whitespace Linter - Forces you to use empty lines!

Expand Down
55 changes: 38 additions & 17 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ type ClientConfig struct {
LoggerFactory logging.LoggerFactory
}

// Client is a STUN server client
// Client is a STUN server client.
type Client struct {
conn net.PacketConn // Read-only
net transport.Net // Read-only
Expand All @@ -72,7 +72,8 @@ type Client struct {
log logging.LeveledLogger // Read-only
}

// NewClient returns a new Client instance. listeningAddress is the address and port to listen on, default "0.0.0.0:0"
// NewClient returns a new Client instance. listeningAddress is the address and port to listen on,
// default "0.0.0.0:0".
func NewClient(config *ClientConfig) (*Client, error) {
loggerFactory := config.LoggerFactory
if loggerFactory == nil {
Expand Down Expand Up @@ -119,7 +120,7 @@ func NewClient(config *ClientConfig) (*Client, error) {
log.Debugf("Resolved TURN server %s to %s", config.TURNServerAddr, turnServ)
}

c := &Client{
client := &Client{
conn: config.Conn,
stunServerAddr: stunServ,
turnServerAddr: turnServ,
Expand All @@ -133,25 +134,25 @@ func NewClient(config *ClientConfig) (*Client, error) {
log: log,
}

return c, nil
return client, nil
}

// TURNServerAddr return the TURN server address
// TURNServerAddr return the TURN server address.
func (c *Client) TURNServerAddr() net.Addr {
return c.turnServerAddr
}

// STUNServerAddr return the STUN server address
// STUNServerAddr return the STUN server address.
func (c *Client) STUNServerAddr() net.Addr {
return c.stunServerAddr
}

// Username returns username
// Username returns username.
func (c *Client) Username() stun.Username {
return c.username
}

// Realm return realm
// Realm return realm.
func (c *Client) Realm() stun.Realm {
return c.realm
}
Expand All @@ -175,12 +176,14 @@ func (c *Client) Listen() error {
n, from, err := c.conn.ReadFrom(buf)
if err != nil {
c.log.Debugf("Failed to read: %s. Exiting loop", err)

break
}

_, err = c.HandleInbound(buf[:n], from)
if err != nil {
c.log.Debugf("Failed to handle inbound message: %s. Exiting loop", err)

Check warning on line 186 in client.go

View check run for this annotation

Codecov / codecov/patch

client.go#L186

Added line #L186 was not covered by tests
break
}
}
Expand All @@ -191,7 +194,7 @@ func (c *Client) Listen() error {
return nil
}

// Close closes this client
// Close closes this client.
func (c *Client) Close() {
c.mutexTrMap.Lock()
defer c.mutexTrMap.Unlock()
Expand All @@ -201,7 +204,7 @@ func (c *Client) Close() {

// TransactionID & Base64: https://play.golang.org/p/EEgmJDI971P

// SendBindingRequestTo sends a new STUN request to the given transport address
// SendBindingRequestTo sends a new STUN request to the given transport address.
func (c *Client) SendBindingRequestTo(to net.Addr) (net.Addr, error) {
attrs := []stun.Setter{stun.TransactionID, stun.BindingRequest}
if len(c.software) > 0 {
Expand All @@ -228,15 +231,21 @@ func (c *Client) SendBindingRequestTo(to net.Addr) (net.Addr, error) {
}, nil
}

// SendBindingRequest sends a new STUN request to the STUN server
// SendBindingRequest sends a new STUN request to the STUN server.
func (c *Client) SendBindingRequest() (net.Addr, error) {
if c.stunServerAddr == nil {
return nil, errSTUNServerAddressNotSet
}

return c.SendBindingRequestTo(c.stunServerAddr)
}

func (c *Client) sendAllocateRequest(protocol proto.Protocol) (proto.RelayedAddress, proto.Lifetime, stun.Nonce, error) {
func (c *Client) sendAllocateRequest(protocol proto.Protocol) ( // nolint:cyclop,funlen
proto.RelayedAddress,
proto.Lifetime,
stun.Nonce,
error,
) {
var relayed proto.RelayedAddress
var lifetime proto.Lifetime
var nonce stun.Nonce
Expand Down Expand Up @@ -295,6 +304,7 @@ func (c *Client) sendAllocateRequest(protocol proto.Protocol) (proto.RelayedAddr
if err = code.GetFrom(res); err == nil {
return relayed, lifetime, nonce, fmt.Errorf("%s (error %s)", res.Type, code) //nolint:goerr113
}

return relayed, lifetime, nonce, fmt.Errorf("%s", res.Type) //nolint:goerr113
}

Expand All @@ -307,10 +317,11 @@ func (c *Client) sendAllocateRequest(protocol proto.Protocol) (proto.RelayedAddr
if err := lifetime.GetFrom(res); err != nil {
return relayed, lifetime, nonce, err
}

return relayed, lifetime, nonce, nil
}

// Allocate sends a TURN allocation request to the given transport address
// Allocate sends a TURN allocation request to the given transport address.
func (c *Client) Allocate() (net.PacketConn, error) {
if err := c.allocTryLock.Lock(); err != nil {
return nil, fmt.Errorf("%w: %s", errOneAllocateOnly, err.Error())
Expand Down Expand Up @@ -403,10 +414,11 @@ func (c *Client) CreatePermission(addrs ...net.Addr) error {
return err
}
}

return nil
}

// PerformTransaction performs STUN transaction
// PerformTransaction performs STUN transaction.
func (c *Client) PerformTransaction(msg *stun.Message, to net.Addr, ignoreResult bool) (client.TransactionResult,
error,
) {
Expand Down Expand Up @@ -442,11 +454,12 @@ func (c *Client) PerformTransaction(msg *stun.Message, to net.Addr, ignoreResult
if res.Err != nil {
return res, res.Err
}

return res, nil
}

// OnDeallocated is called when de-allocation of relay address has been complete.
// (Called by UDPConn)
// (Called by UDPConn).
func (c *Client) OnDeallocated(net.Addr) {
c.setRelayedUDPConn(nil)
c.setTCPAllocation(nil)
Expand Down Expand Up @@ -494,7 +507,7 @@ func (c *Client) HandleInbound(data []byte, from net.Addr) (bool, error) {
return false, nil
}

func (c *Client) handleSTUNMessage(data []byte, from net.Addr) error {
func (c *Client) handleSTUNMessage(data []byte, from net.Addr) error { // nolint:cyclop,funlen
raw := make([]byte, len(data))
copy(raw, data)

Expand All @@ -507,7 +520,7 @@ func (c *Client) handleSTUNMessage(data []byte, from net.Addr) error {
return fmt.Errorf("%w : %s", errUnexpectedSTUNRequestMessage, msg.String())
}

if msg.Type.Class == stun.ClassIndication {
if msg.Type.Class == stun.ClassIndication { // nolint:nestif
switch msg.Type.Method {
case stun.MethodData:
var peerAddr proto.PeerAddress
Expand All @@ -529,6 +542,7 @@ func (c *Client) handleSTUNMessage(data []byte, from net.Addr) error {
relayedConn := c.relayedUDPConn()
if relayedConn == nil {
c.log.Debug("No relayed conn allocated")

Check warning on line 545 in client.go

View check run for this annotation

Codecov / codecov/patch

client.go#L545

Added line #L545 was not covered by tests
return nil // Silently discard
}
relayedConn.HandleInbound(data, from)
Expand All @@ -553,13 +567,15 @@ func (c *Client) handleSTUNMessage(data []byte, from net.Addr) error {
allocation := c.getTCPAllocation()
if allocation == nil {
c.log.Debug("No TCP allocation exists")

Check warning on line 570 in client.go

View check run for this annotation

Codecov / codecov/patch

client.go#L570

Added line #L570 was not covered by tests
return nil // Silently discard
}

allocation.HandleConnectionAttempt(addr, cid)
default:
c.log.Debug("Received unsupported STUN method")
}

return nil
}

Expand All @@ -576,6 +592,7 @@ func (c *Client) handleSTUNMessage(data []byte, from net.Addr) error {
c.mutexTrMap.Unlock()
// Silently discard
c.log.Debugf("No transaction for %s", msg)

Check warning on line 595 in client.go

View check run for this annotation

Codecov / codecov/patch

client.go#L595

Added line #L595 was not covered by tests
return nil
}

Expand Down Expand Up @@ -607,6 +624,7 @@ func (c *Client) handleChannelData(data []byte) error {
relayedConn := c.relayedUDPConn()
if relayedConn == nil {
c.log.Debug("No relayed conn allocated")

Check warning on line 627 in client.go

View check run for this annotation

Codecov / codecov/patch

client.go#L627

Added line #L627 was not covered by tests
return nil // Silently discard
}

Expand All @@ -618,6 +636,7 @@ func (c *Client) handleChannelData(data []byte) error {
c.log.Tracef("Channel data received from %s (ch=%d)", addr.String(), int(chData.Number))

relayedConn.HandleInbound(chData.Data, addr)

Check warning on line 639 in client.go

View check run for this annotation

Codecov / codecov/patch

client.go#L639

Added line #L639 was not covered by tests
return nil
}

Expand All @@ -638,6 +657,7 @@ func (c *Client) onRtxTimeout(trKey string, nRtx int) {
}) {
c.log.Debug("No listener for transaction")
}

return
}

Expand All @@ -651,6 +671,7 @@ func (c *Client) onRtxTimeout(trKey string, nRtx int) {
}) {
c.log.Debug("No listener for transaction")
}

return
}
tr.StartRtxTimer(c.onRtxTimeout)
Expand Down
Loading

0 comments on commit 82373d7

Please sign in to comment.