Skip to content

Commit

Permalink
Upgrade golangci-lint, more linters
Browse files Browse the repository at this point in the history
Introduces new linters, upgrade golangci-lint to version (v1.63.4)
  • Loading branch information
JoeTurki committed Jan 24, 2025
1 parent 687754f commit 120a11a
Show file tree
Hide file tree
Showing 8 changed files with 127 additions and 79 deletions.
49 changes: 32 additions & 17 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 @@ -46,66 +61,64 @@ linters:
- forcetypeassert # finds forced type assertions
- 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 All @@ -123,3 +136,5 @@ issues:
- path: cmd
linters:
- forbidigo
max-issues-per-linter: 0
max-same-issues: 0
71 changes: 40 additions & 31 deletions datachannel.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ type ReadWriteCloserDeadliner interface {
WriteDeadliner
}

// DataChannel represents a data channel
// DataChannel represents a data channel.
type DataChannel struct {
Config

Expand Down Expand Up @@ -95,7 +95,7 @@ func newDataChannel(stream *sctp.Stream, config *Config) *DataChannel {
}
}

// Dial opens a data channels over SCTP
// Dial opens a data channels over SCTP.
func Dial(a *sctp.Association, id uint16, config *Config) (*DataChannel, error) {
stream, err := a.OpenStream(id, sctp.PayloadTypeWebRTCBinary)
if err != nil {
Expand All @@ -110,7 +110,7 @@ func Dial(a *sctp.Association, id uint16, config *Config) (*DataChannel, error)
return dc, nil
}

// Client opens a data channel over an SCTP stream
// Client opens a data channel over an SCTP stream.
func Client(stream *sctp.Stream, config *Config) (*DataChannel, error) {
msg := &channelOpen{
ChannelType: config.ChannelType,
Expand All @@ -131,10 +131,11 @@ func Client(stream *sctp.Stream, config *Config) (*DataChannel, error) {
return nil, fmt.Errorf("failed to send ChannelOpen %w", err)
}
}

return newDataChannel(stream, config), nil
}

// Accept is used to accept incoming data channels over SCTP
// Accept is used to accept incoming data channels over SCTP.
func Accept(a *sctp.Association, config *Config, existingChannels ...*DataChannel) (*DataChannel, error) {
stream, err := a.AcceptStream()
if err != nil {
Expand All @@ -143,6 +144,7 @@ func Accept(a *sctp.Association, config *Config, existingChannels ...*DataChanne
for _, ch := range existingChannels {
if ch.StreamIdentifier() == stream.StreamIdentifier() {
ch.stream.SetDefaultPayloadType(sctp.PayloadTypeWebRTCBinary)

return ch, nil
}
}
Expand All @@ -157,7 +159,7 @@ func Accept(a *sctp.Association, config *Config, existingChannels ...*DataChanne
return dc, nil
}

// Server accepts a data channel over an SCTP stream
// Server accepts a data channel over an SCTP stream.
func Server(stream *sctp.Stream, config *Config) (*DataChannel, error) {
buffer := make([]byte, receiveMTU)
n, ppi, err := stream.ReadSCTP(buffer)
Expand Down Expand Up @@ -191,19 +193,21 @@ func Server(stream *sctp.Stream, config *Config) (*DataChannel, error) {
if err != nil {
return nil, err
}

return dataChannel, nil
}

// Read reads a packet of len(p) bytes as binary data
func (c *DataChannel) Read(p []byte) (int, error) {
n, _, err := c.ReadDataChannel(p)
// Read reads a packet of len(pkt) bytes as binary data.
func (c *DataChannel) Read(pkt []byte) (int, error) {
n, _, err := c.ReadDataChannel(pkt)

return n, err
}

// ReadDataChannel reads a packet of len(p) bytes
func (c *DataChannel) ReadDataChannel(p []byte) (int, bool, error) {
// ReadDataChannel reads a packet of len(pkt) bytes.
func (c *DataChannel) ReadDataChannel(pkt []byte) (int, bool, error) {
for {
n, ppi, err := c.stream.ReadSCTP(p)
n, ppi, err := c.stream.ReadSCTP(pkt)
if errors.Is(err, io.EOF) {
// When the peer sees that an incoming stream was
// reset, it also resets its corresponding outgoing stream.
Expand All @@ -216,39 +220,41 @@ func (c *DataChannel) ReadDataChannel(p []byte) (int, bool, error) {
}

if ppi == sctp.PayloadTypeWebRTCDCEP {
if err = c.handleDCEP(p[:n]); err != nil {
if err = c.handleDCEP(pkt[:n]); err != nil {
c.log.Errorf("Failed to handle DCEP: %s", err.Error())
}

continue
} else if ppi == sctp.PayloadTypeWebRTCBinaryEmpty || ppi == sctp.PayloadTypeWebRTCStringEmpty {
n = 0
}

atomic.AddUint32(&c.messagesReceived, 1)
atomic.AddUint64(&c.bytesReceived, uint64(n))
atomic.AddUint64(&c.bytesReceived, uint64(n)) //nolint:gosec //G115

isString := ppi == sctp.PayloadTypeWebRTCString || ppi == sctp.PayloadTypeWebRTCStringEmpty

return n, isString, err
}
}

// SetReadDeadline sets a deadline for reads to return
// SetReadDeadline sets a deadline for reads to return.
func (c *DataChannel) SetReadDeadline(t time.Time) error {
return c.stream.SetReadDeadline(t)
}

// SetWriteDeadline sets a deadline for writes to return,
// only available if the BlockWrite is enabled for sctp
// only available if the BlockWrite is enabled for sctp.
func (c *DataChannel) SetWriteDeadline(t time.Time) error {
return c.stream.SetWriteDeadline(t)
}

// MessagesSent returns the number of messages sent
// MessagesSent returns the number of messages sent.
func (c *DataChannel) MessagesSent() uint32 {
return atomic.LoadUint32(&c.messagesSent)
}

// MessagesReceived returns the number of messages received
// MessagesReceived returns the number of messages received.
func (c *DataChannel) MessagesReceived() uint32 {
return atomic.LoadUint32(&c.messagesReceived)
}
Expand Down Expand Up @@ -276,12 +282,12 @@ func (c *DataChannel) onOpenComplete() {
}
}

// BytesSent returns the number of bytes sent
// BytesSent returns the number of bytes sent.
func (c *DataChannel) BytesSent() uint64 {
return atomic.LoadUint64(&c.bytesSent)
}

// BytesReceived returns the number of bytes received
// BytesReceived returns the number of bytes received.
func (c *DataChannel) BytesReceived() uint64 {
return atomic.LoadUint64(&c.bytesReceived)
}
Expand Down Expand Up @@ -310,13 +316,13 @@ func (c *DataChannel) handleDCEP(data []byte) error {
return nil
}

// Write writes len(p) bytes from p as binary data
func (c *DataChannel) Write(p []byte) (n int, err error) {
return c.WriteDataChannel(p, false)
// Write writes len(pkt) bytes from pkt as binary data.
func (c *DataChannel) Write(pkt []byte) (n int, err error) {
return c.WriteDataChannel(pkt, false)
}

// WriteDataChannel writes len(p) bytes from p
func (c *DataChannel) WriteDataChannel(p []byte, isString bool) (n int, err error) {
// WriteDataChannel writes len(pkt) bytes from pkt.
func (c *DataChannel) WriteDataChannel(pkt []byte, isString bool) (n int, err error) {
// https://tools.ietf.org/html/draft-ietf-rtcweb-data-channel-12#section-6.6
// SCTP does not support the sending of empty user messages. Therefore,
// if an empty message has to be sent, the appropriate PPID (WebRTC
Expand All @@ -326,24 +332,26 @@ func (c *DataChannel) WriteDataChannel(p []byte, isString bool) (n int, err erro
// user message and process it as an empty message.
var ppi sctp.PayloadProtocolIdentifier
switch {
case !isString && len(p) > 0:
case !isString && len(pkt) > 0:
ppi = sctp.PayloadTypeWebRTCBinary
case !isString && len(p) == 0:
case !isString && len(pkt) == 0:
ppi = sctp.PayloadTypeWebRTCBinaryEmpty
case isString && len(p) > 0:
case isString && len(pkt) > 0:
ppi = sctp.PayloadTypeWebRTCString
case isString && len(p) == 0:
case isString && len(pkt) == 0:
ppi = sctp.PayloadTypeWebRTCStringEmpty
}

atomic.AddUint32(&c.messagesSent, 1)
atomic.AddUint64(&c.bytesSent, uint64(len(p)))
atomic.AddUint64(&c.bytesSent, uint64(len(pkt)))

if len(p) == 0 {
if len(pkt) == 0 {
_, err := c.stream.WriteSCTP([]byte{0}, ppi)

return 0, err
}
return c.stream.WriteSCTP(p, ppi)

return c.stream.WriteSCTP(pkt, ppi)
}

func (c *DataChannel) writeDataChannelAck() error {
Expand Down Expand Up @@ -417,5 +425,6 @@ func (c *DataChannel) commitReliabilityParams() error {
default:
return fmt.Errorf("%w %v", ErrInvalidChannelType, c.Config.ChannelType)
}

return nil
}
Loading

0 comments on commit 120a11a

Please sign in to comment.