Skip to content

Commit 0285806

Browse files
pionbotSean-Der
authored andcommitted
Update CI configs to v0.4.7
Update lint scripts and CI configs.
1 parent e7862c3 commit 0285806

34 files changed

+266
-128
lines changed

.golangci.yml

+74
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,80 @@ linters-settings:
33
check-shadowing: true
44
misspell:
55
locale: US
6+
exhaustive:
7+
default-signifies-exhaustive: true
8+
9+
linters:
10+
enable:
11+
- asciicheck # Simple linter to check that your code does not contain non-ASCII identifiers
12+
- bodyclose # checks whether HTTP response body is closed successfully
13+
- deadcode # Finds unused code
14+
- depguard # Go linter that checks if package imports are in a list of acceptable packages
15+
- dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f())
16+
- dupl # Tool for code clone detection
17+
- errcheck # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases
18+
- exhaustive # check exhaustiveness of enum switch statements
19+
- exportloopref # checks for pointers to enclosing loop variables
20+
- gci # Gci control golang package import order and make it always deterministic.
21+
- gochecknoglobals # Checks that no globals are present in Go code
22+
- gochecknoinits # Checks that no init functions are present in Go code
23+
- gocognit # Computes and checks the cognitive complexity of functions
24+
- goconst # Finds repeated strings that could be replaced by a constant
25+
- gocritic # The most opinionated Go source code linter
26+
- godox # Tool for detection of FIXME, TODO and other comment keywords
27+
- goerr113 # Golang linter to check the errors handling expressions
28+
- gofmt # Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification
29+
- gofumpt # Gofumpt checks whether code was gofumpt-ed.
30+
- goheader # Checks is file header matches to pattern
31+
- goimports # Goimports does everything that gofmt does. Additionally it checks unused imports
32+
- golint # Golint differs from gofmt. Gofmt reformats Go source code, whereas golint prints out style mistakes
33+
- 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.
34+
- goprintffuncname # Checks that printf-like functions are named with `f` at the end
35+
- gosec # Inspects source code for security problems
36+
- gosimple # Linter for Go source code that specializes in simplifying a code
37+
- govet # Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string
38+
- ineffassign # Detects when assignments to existing variables are not used
39+
- misspell # Finds commonly misspelled English words in comments
40+
- nakedret # Finds naked returns in functions greater than a specified function length
41+
- noctx # noctx finds sending http request without context.Context
42+
- scopelint # Scopelint checks for unpinned variables in go programs
43+
- staticcheck # Staticcheck is a go vet on steroids, applying a ton of static analysis checks
44+
- structcheck # Finds unused struct fields
45+
- stylecheck # Stylecheck is a replacement for golint
46+
- typecheck # Like the front-end of a Go compiler, parses and type-checks Go code
47+
- unconvert # Remove unnecessary type conversions
48+
- unparam # Reports unused function parameters
49+
- unused # Checks Go code for unused constants, variables, functions and types
50+
- varcheck # Finds unused global variables and constants
51+
- whitespace # Tool for detection of leading and trailing whitespace
52+
disable:
53+
- funlen # Tool for detection of long functions
54+
- gocyclo # Computes and checks the cyclomatic complexity of functions
55+
- godot # Check if comments end in a period
56+
- gomnd # An analyzer to detect magic numbers.
57+
- lll # Reports long lines
58+
- maligned # Tool to detect Go structs that would take less memory if their fields were sorted
59+
- nestif # Reports deeply nested if statements
60+
- nlreturn # nlreturn checks for a new line before return and branch statements to increase code clarity
61+
- nolintlint # Reports ill-formed or insufficient nolint directives
62+
- prealloc # Finds slice declarations that could potentially be preallocated
63+
- rowserrcheck # checks whether Err of rows is checked successfully
64+
- sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed.
65+
- testpackage # linter that makes you use a separate _test package
66+
- wsl # Whitespace Linter - Forces you to use empty lines!
67+
68+
issues:
69+
exclude-rules:
70+
# Allow complex tests, better to be self contained
71+
- path: _test\.go
72+
linters:
73+
- gocognit
74+
75+
# Allow complex main function in examples
76+
- path: examples
77+
text: "of func `main` is high"
78+
linters:
79+
- gocognit
680

781
run:
882
skip-dirs-use-default: false

README.md

+2
Original file line numberDiff line numberDiff line change
@@ -91,3 +91,5 @@ Check out the [CONTRIBUTING.md](CONTRIBUTING.md) to join the group of amazing pe
9191

9292
### License
9393
MIT License - see [LICENSE.md](LICENSE.md) for full text
94+
95+

client.go

+14-15
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ import (
1818
const (
1919
defaultRTO = 200 * time.Millisecond
2020
maxRtxCount = 7 // total 7 requests (Rc)
21-
maxDataBufferSize = math.MaxUint16 //message size limit for Chromium
21+
maxDataBufferSize = math.MaxUint16 // message size limit for Chromium
2222
)
2323

2424
// interval [msec]
@@ -78,7 +78,7 @@ func NewClient(config *ClientConfig) (*Client, error) {
7878
log := loggerFactory.NewLogger("turnc")
7979

8080
if config.Conn == nil {
81-
return nil, fmt.Errorf("conn cannot not be nil")
81+
return nil, errNilConn
8282
}
8383

8484
if config.Net == nil {
@@ -163,7 +163,7 @@ func (c *Client) WriteTo(data []byte, to net.Addr) (int, error) {
163163
// to supply incoming data, instead.
164164
func (c *Client) Listen() error {
165165
if err := c.listenTryLock.Lock(); err != nil {
166-
return fmt.Errorf("already listening: %s", err.Error())
166+
return fmt.Errorf("%w: %s", errAlreadyListening, err.Error())
167167
}
168168

169169
go func() {
@@ -219,7 +219,6 @@ func (c *Client) SendBindingRequestTo(to net.Addr) (net.Addr, error) {
219219
return nil, err
220220
}
221221

222-
//return fmt.Sprintf("pkt_size=%d src_addr=%s refl_addr=%s:%d", size, addr, reflAddr.IP, reflAddr.Port), nil
223222
return &net.UDPAddr{
224223
IP: reflAddr.IP,
225224
Port: reflAddr.Port,
@@ -229,21 +228,21 @@ func (c *Client) SendBindingRequestTo(to net.Addr) (net.Addr, error) {
229228
// SendBindingRequest sends a new STUN request to the STUN server
230229
func (c *Client) SendBindingRequest() (net.Addr, error) {
231230
if c.stunServ == nil {
232-
return nil, fmt.Errorf("STUN server address is not set for the client")
231+
return nil, errSTUNServerAddressNotSet
233232
}
234233
return c.SendBindingRequestTo(c.stunServ)
235234
}
236235

237236
// Allocate sends a TURN allocation request to the given transport address
238237
func (c *Client) Allocate() (net.PacketConn, error) {
239238
if err := c.allocTryLock.Lock(); err != nil {
240-
return nil, fmt.Errorf("only one Allocate() caller is allowed: %s", err.Error())
239+
return nil, fmt.Errorf("%w: %s", errOneAllocateOnly, err.Error())
241240
}
242241
defer c.allocTryLock.Unlock()
243242

244243
relayedConn := c.relayedUDPConn()
245244
if relayedConn != nil {
246-
return nil, fmt.Errorf("already allocated at %s", relayedConn.LocalAddr().String())
245+
return nil, fmt.Errorf("%w: %s", errAlreadyAllocated, relayedConn.LocalAddr().String())
247246
}
248247

249248
msg, err := stun.Build(
@@ -299,9 +298,9 @@ func (c *Client) Allocate() (net.PacketConn, error) {
299298
if res.Type.Class == stun.ClassErrorResponse {
300299
var code stun.ErrorCodeAttribute
301300
if err = code.GetFrom(res); err == nil {
302-
return nil, fmt.Errorf("%s (error %s)", res.Type, code)
301+
return nil, fmt.Errorf("%s (error %s)", res.Type, code) //nolint:goerr113
303302
}
304-
return nil, fmt.Errorf("%s", res.Type)
303+
return nil, fmt.Errorf("%s", res.Type) //nolint:goerr113
305304
}
306305

307306
// Getting relayed addresses from response.
@@ -411,7 +410,7 @@ func (c *Client) HandleInbound(data []byte, from net.Addr) (bool, error) {
411410
return true, c.handleChannelData(data)
412411
case len(c.stunServStr) != 0 && from.String() == c.stunServStr:
413412
// received from STUN server but it is not a STUN message
414-
return true, fmt.Errorf("non-STUN message from STUN server")
413+
return true, errNonSTUNMessage
415414
default:
416415
// assume, this is an application data
417416
c.log.Tracef("non-STUN/TURN packect, unhandled")
@@ -426,11 +425,11 @@ func (c *Client) handleSTUNMessage(data []byte, from net.Addr) error {
426425

427426
msg := &stun.Message{Raw: raw}
428427
if err := msg.Decode(); err != nil {
429-
return fmt.Errorf("failed to decode STUN message: %s", err.Error())
428+
return fmt.Errorf("%w: %s", errFailedToDecodeSTUN, err.Error())
430429
}
431430

432431
if msg.Type.Class == stun.ClassRequest {
433-
return fmt.Errorf("unexpected STUN request message: %s", msg.String())
432+
return fmt.Errorf("%w : %s", errUnexpectedSTUNRequestMessage, msg.String())
434433
}
435434

436435
if msg.Type.Class == stun.ClassIndication {
@@ -511,7 +510,7 @@ func (c *Client) handleChannelData(data []byte) error {
511510

512511
addr, ok := relayedConn.FindAddrByChannelNumber(uint16(chData.Number))
513512
if !ok {
514-
return fmt.Errorf("binding with channel %d not found", int(chData.Number))
513+
return fmt.Errorf("%w: %d", errChannelBindNotFound, int(chData.Number))
515514
}
516515

517516
c.log.Tracef("channel data received from %s (ch=%d)", addr.String(), int(chData.Number))
@@ -533,7 +532,7 @@ func (c *Client) onRtxTimeout(trKey string, nRtx int) {
533532
// all retransmisstions failed
534533
c.trMap.Delete(trKey)
535534
if !tr.WriteResult(client.TransactionResult{
536-
Err: fmt.Errorf("all retransmissions for %s failed", trKey),
535+
Err: fmt.Errorf("%w %s", errAllRetransmissionsFailed, trKey),
537536
}) {
538537
c.log.Debug("no listener for transaction")
539538
}
@@ -546,7 +545,7 @@ func (c *Client) onRtxTimeout(trKey string, nRtx int) {
546545
if err != nil {
547546
c.trMap.Delete(trKey)
548547
if !tr.WriteResult(client.TransactionResult{
549-
Err: fmt.Errorf("failed to retransmit transaction %s", trKey),
548+
Err: fmt.Errorf("%w %s", errFailedToRetransmitTransaction, trKey),
550549
}) {
551550
c.log.Debug("no listener for transaction")
552551
}

errors.go

+19-6
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,23 @@ package turn
33
import "errors"
44

55
var (
6-
errRelayAddressInvalid = errors.New("turn: RelayAddress must be valid IP to use RelayAddressGeneratorStatic")
7-
errNoAvailableConns = errors.New("turn: PacketConnConfigs and ConnConfigs are empty, unable to proceed")
8-
errConnUnset = errors.New("turn: PacketConnConfig must have a non-nil Conn")
9-
errListenerUnset = errors.New("turn: ListenerConfig must have a non-nil Listener")
10-
errListeningAddressInvalid = errors.New("turn: RelayAddressGenerator has invalid ListeningAddress")
11-
errRelayAddressGeneratorUnset = errors.New("turn: RelayAddressGenerator in RelayConfig is unset")
6+
errRelayAddressInvalid = errors.New("turn: RelayAddress must be valid IP to use RelayAddressGeneratorStatic")
7+
errNoAvailableConns = errors.New("turn: PacketConnConfigs and ConnConfigs are empty, unable to proceed")
8+
errConnUnset = errors.New("turn: PacketConnConfig must have a non-nil Conn")
9+
errListenerUnset = errors.New("turn: ListenerConfig must have a non-nil Listener")
10+
errListeningAddressInvalid = errors.New("turn: RelayAddressGenerator has invalid ListeningAddress")
11+
errRelayAddressGeneratorUnset = errors.New("turn: RelayAddressGenerator in RelayConfig is unset")
12+
errNilConn = errors.New("turn: conn cannot not be nil")
13+
errTODO = errors.New("turn: TODO")
14+
errAlreadyListening = errors.New("turn: already listening")
15+
errFailedToClose = errors.New("turn: Server failed to close")
16+
errFailedToRetransmitTransaction = errors.New("turn: failed to retransmit transaction")
17+
errAllRetransmissionsFailed = errors.New("all retransmissions failed for")
18+
errChannelBindNotFound = errors.New("no binding found for channel")
19+
errSTUNServerAddressNotSet = errors.New("STUN server address is not set for the client")
20+
errOneAllocateOnly = errors.New("only one Allocate() caller is allowed")
21+
errAlreadyAllocated = errors.New("already allocated")
22+
errNonSTUNMessage = errors.New("non-STUN message from STUN server")
23+
errFailedToDecodeSTUN = errors.New("failed to decode STUN message")
24+
errUnexpectedSTUNRequestMessage = errors.New("unexpected STUN request message")
1225
)

internal/allocation/allocation.go

+1-2
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
package allocation
33

44
import (
5-
"fmt"
65
"net"
76
"sync"
87
"time"
@@ -95,7 +94,7 @@ func (a *Allocation) AddChannelBind(c *ChannelBind, lifetime time.Duration) erro
9594
channelByNumber := a.GetChannelByNumber(c.Number)
9695

9796
if channelByNumber != a.GetChannelByAddr(c.Peer) {
98-
return fmt.Errorf("you cannot use the same channel number with different peer")
97+
return errSameChannelDifferentPeer
9998
}
10099

101100
// Add or refresh this channel.

internal/allocation/allocation_manager.go

+10-10
Original file line numberDiff line numberDiff line change
@@ -37,11 +37,11 @@ type Manager struct {
3737
func NewManager(config ManagerConfig) (*Manager, error) {
3838
switch {
3939
case config.AllocatePacketConn == nil:
40-
return nil, fmt.Errorf("AllocatePacketConn must be set")
40+
return nil, errAllocatePacketConnMustBeSet
4141
case config.AllocateConn == nil:
42-
return nil, fmt.Errorf("AllocateConn must be set")
42+
return nil, errAllocateConnMustBeSet
4343
case config.LeveledLogger == nil:
44-
return nil, fmt.Errorf("LeveledLogger must be set")
44+
return nil, errLeveledLoggerMustBeSet
4545
}
4646

4747
return &Manager{
@@ -76,19 +76,19 @@ func (m *Manager) Close() error {
7676
func (m *Manager) CreateAllocation(fiveTuple *FiveTuple, turnSocket net.PacketConn, requestedPort int, lifetime time.Duration) (*Allocation, error) {
7777
switch {
7878
case fiveTuple == nil:
79-
return nil, fmt.Errorf("allocations must not be created with nil FivTuple")
79+
return nil, errNilFiveTuple
8080
case fiveTuple.SrcAddr == nil:
81-
return nil, fmt.Errorf("allocations must not be created with nil FiveTuple.SrcAddr")
81+
return nil, errNilFiveTupleSrcAddr
8282
case fiveTuple.DstAddr == nil:
83-
return nil, fmt.Errorf("allocations must not be created with nil FiveTuple.DstAddr")
83+
return nil, errNilFiveTupleDstAddr
8484
case turnSocket == nil:
85-
return nil, fmt.Errorf("allocations must not be created with nil turnSocket")
85+
return nil, errNilTurnSocket
8686
case lifetime == 0:
87-
return nil, fmt.Errorf("allocations must not be created with a lifetime of 0")
87+
return nil, errLifetimeZero
8888
}
8989

9090
if a := m.GetAllocation(fiveTuple); a != nil {
91-
return nil, fmt.Errorf("allocation attempt created with duplicate FiveTuple %v", fiveTuple)
91+
return nil, fmt.Errorf("%w: %v", errDupeFiveTuple, fiveTuple)
9292
}
9393
a := NewAllocation(turnSocket, fiveTuple, m.log)
9494

@@ -175,7 +175,7 @@ func (m *Manager) GetRandomEvenPort() (int, error) {
175175

176176
udpAddr, ok := addr.(*net.UDPAddr)
177177
if !ok {
178-
return 0, fmt.Errorf("failed to cast net.Addr to *net.UDPAddr")
178+
return 0, errFailedToCastUDPAddr
179179
} else if err := conn.Close(); err != nil {
180180
return 0, err
181181
} else if udpAddr.Port%2 == 1 {

internal/allocation/errors.go

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package allocation
2+
3+
import "errors"
4+
5+
var (
6+
errAllocatePacketConnMustBeSet = errors.New("AllocatePacketConn must be set")
7+
errAllocateConnMustBeSet = errors.New("AllocateConn must be set")
8+
errLeveledLoggerMustBeSet = errors.New("LeveledLogger must be set")
9+
errSameChannelDifferentPeer = errors.New("you cannot use the same channel number with different peer")
10+
errNilFiveTuple = errors.New("allocations must not be created with nil FivTuple")
11+
errNilFiveTupleSrcAddr = errors.New("allocations must not be created with nil FiveTuple.SrcAddr")
12+
errNilFiveTupleDstAddr = errors.New("allocations must not be created with nil FiveTuple.DstAddr")
13+
errNilTurnSocket = errors.New("allocations must not be created with nil turnSocket")
14+
errLifetimeZero = errors.New("allocations must not be created with a lifetime of 0")
15+
errDupeFiveTuple = errors.New("allocation attempt created with duplicate FiveTuple")
16+
errFailedToCastUDPAddr = errors.New("failed to cast net.Addr to *net.UDPAddr")
17+
)

0 commit comments

Comments
 (0)