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 18, 2025
1 parent 99dcc6b commit feeeebf
Show file tree
Hide file tree
Showing 147 changed files with 3,855 additions and 2,152 deletions.
47 changes: 30 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 Down
24 changes: 12 additions & 12 deletions api.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,38 +29,38 @@ type API struct {
// It uses the default Codecs and Interceptors unless you customize them
// using WithMediaEngine and WithInterceptorRegistry respectively.
func NewAPI(options ...func(*API)) *API {
a := &API{
api := &API{
interceptor: &interceptor.NoOp{},
settingEngine: &SettingEngine{},
}

for _, o := range options {
o(a)
o(api)
}

if a.settingEngine.LoggerFactory == nil {
a.settingEngine.LoggerFactory = logging.NewDefaultLoggerFactory()
if api.settingEngine.LoggerFactory == nil {
api.settingEngine.LoggerFactory = logging.NewDefaultLoggerFactory()
}

logger := a.settingEngine.LoggerFactory.NewLogger("api")
logger := api.settingEngine.LoggerFactory.NewLogger("api")

if a.mediaEngine == nil {
a.mediaEngine = &MediaEngine{}
err := a.mediaEngine.RegisterDefaultCodecs()
if api.mediaEngine == nil {
api.mediaEngine = &MediaEngine{}
err := api.mediaEngine.RegisterDefaultCodecs()
if err != nil {
logger.Errorf("Failed to register default codecs %s", err)
}
}

if a.interceptorRegistry == nil {
a.interceptorRegistry = &interceptor.Registry{}
err := RegisterDefaultInterceptors(a.mediaEngine, a.interceptorRegistry)
if api.interceptorRegistry == nil {
api.interceptorRegistry = &interceptor.Registry{}
err := RegisterDefaultInterceptors(api.mediaEngine, api.interceptorRegistry)
if err != nil {
logger.Errorf("Failed to register default interceptors %s", err)
}
}

return a
return api
}

// WithMediaEngine allows providing a MediaEngine to the API.
Expand Down
1 change: 1 addition & 0 deletions atomicbool.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,5 +27,6 @@ func (b *atomicBool) swap(value bool) bool {
if value {
i = 1
}

return atomic.SwapInt32(&(b.val), i) != 0
}
7 changes: 4 additions & 3 deletions bundlepolicy.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (
type BundlePolicy int

const (
// BundlePolicyUnknown is the enum's zero-value
// BundlePolicyUnknown is the enum's zero-value.
BundlePolicyUnknown BundlePolicy = iota

// BundlePolicyBalanced indicates to gather ICE candidates for each
Expand Down Expand Up @@ -67,18 +67,19 @@ func (t BundlePolicy) String() string {
}
}

// UnmarshalJSON parses the JSON-encoded data and stores the result
// UnmarshalJSON parses the JSON-encoded data and stores the result.
func (t *BundlePolicy) UnmarshalJSON(b []byte) error {
var val string
if err := json.Unmarshal(b, &val); err != nil {
return err
}

*t = newBundlePolicy(val)

return nil
}

// MarshalJSON returns the JSON encoding
// MarshalJSON returns the JSON encoding.
func (t BundlePolicy) MarshalJSON() ([]byte, error) {
return json.Marshal(t.String())
}
38 changes: 25 additions & 13 deletions certificate.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,28 +62,36 @@ func NewCertificate(key crypto.PrivateKey, tpl x509.Certificate) (*Certificate,
return nil, &rtcerr.UnknownError{Err: err}
}

return &Certificate{privateKey: key, x509Cert: cert, statsID: fmt.Sprintf("certificate-%d", time.Now().UnixNano())}, nil
return &Certificate{
privateKey: key,
x509Cert: cert,
statsID: fmt.Sprintf("certificate-%d", time.Now().UnixNano()),
}, nil
}

// Equals determines if two certificates are identical by comparing both the
// secretKeys and x509Certificates.
func (c Certificate) Equals(o Certificate) bool {
func (c Certificate) Equals(cert Certificate) bool {
switch cSK := c.privateKey.(type) {
case *rsa.PrivateKey:
if oSK, ok := o.privateKey.(*rsa.PrivateKey); ok {
if oSK, ok := cert.privateKey.(*rsa.PrivateKey); ok {
if cSK.N.Cmp(oSK.N) != 0 {
return false
}
return c.x509Cert.Equal(o.x509Cert)

return c.x509Cert.Equal(cert.x509Cert)
}

return false
case *ecdsa.PrivateKey:
if oSK, ok := o.privateKey.(*ecdsa.PrivateKey); ok {
if oSK, ok := cert.privateKey.(*ecdsa.PrivateKey); ok {
if cSK.X.Cmp(oSK.X) != 0 || cSK.Y.Cmp(oSK.Y) != 0 {
return false
}
return c.x509Cert.Equal(o.x509Cert)

return c.x509Cert.Equal(cert.x509Cert)
}

return false
default:
return false
Expand All @@ -95,6 +103,7 @@ func (c Certificate) Expires() time.Time {
if c.x509Cert == nil {
return time.Time{}
}

return c.x509Cert.NotAfter
}

Expand Down Expand Up @@ -150,7 +159,7 @@ func GenerateCertificate(secretKey crypto.PrivateKey) (*Certificate, error) {

// CertificateFromX509 creates a new WebRTC Certificate from a given PrivateKey and Certificate
//
// This can be used if you want to share a certificate across multiple PeerConnections
// This can be used if you want to share a certificate across multiple PeerConnections.
func CertificateFromX509(privateKey crypto.PrivateKey, certificate *x509.Certificate) Certificate {
return Certificate{privateKey, certificate, fmt.Sprintf("certificate-%d", time.Now().UnixNano())}
}
Expand All @@ -176,11 +185,12 @@ func (c Certificate) collectStats(report *statsReportCollector) error {
}

report.Collect(stats.ID, stats)

return nil
}

// CertificateFromPEM creates a fresh certificate based on a string containing
// pem blocks fort the private key and x509 certificate
// pem blocks fort the private key and x509 certificate.
func CertificateFromPEM(pems string) (*Certificate, error) {
// decode & parse the certificate
block, more := pem.Decode([]byte(pems))
Expand All @@ -206,18 +216,19 @@ func CertificateFromPEM(pems string) (*Certificate, error) {
return nil, fmt.Errorf("unable to parse private key: %w", err)
}
x := CertificateFromX509(privateKey, cert)

return &x, nil
}

// PEM returns the certificate encoded as two pem block: once for the X509
// certificate and the other for the private key
// certificate and the other for the private key.
func (c Certificate) PEM() (string, error) {
// First write the X509 certificate
var o strings.Builder
var builder strings.Builder
xcertBytes := make(
[]byte, base64.StdEncoding.EncodedLen(len(c.x509Cert.Raw)))
base64.StdEncoding.Encode(xcertBytes, c.x509Cert.Raw)
err := pem.Encode(&o, &pem.Block{Type: "CERTIFICATE", Bytes: xcertBytes})
err := pem.Encode(&builder, &pem.Block{Type: "CERTIFICATE", Bytes: xcertBytes})
if err != nil {
return "", fmt.Errorf("failed to pem encode the X certificate: %w", err)
}
Expand All @@ -226,9 +237,10 @@ func (c Certificate) PEM() (string, error) {
if err != nil {
return "", fmt.Errorf("failed to marshal private key: %w", err)
}
err = pem.Encode(&o, &pem.Block{Type: "PRIVATE KEY", Bytes: privBytes})
err = pem.Encode(&builder, &pem.Block{Type: "PRIVATE KEY", Bytes: privBytes})
if err != nil {
return "", fmt.Errorf("failed to encode private key: %w", err)
}
return o.String(), nil

return builder.String(), nil
}
1 change: 1 addition & 0 deletions configuration_common.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,6 @@ func (c Configuration) getICEServers() []ICEServer {
iceServers[iceServersIndex].URLs[urlsIndex] = rawURL
}
}

return iceServers
}
4 changes: 2 additions & 2 deletions configuration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ func TestConfiguration_getICEServers(t *testing.T) {
}

func TestConfigurationJSON(t *testing.T) {
j := `{
config := `{
"iceServers": [{"urls": ["turn:turn.example.org"],
"username": "jch",
"credential": "topsecret"
Expand All @@ -67,7 +67,7 @@ func TestConfigurationJSON(t *testing.T) {
}

var conf2 Configuration
assert.NoError(t, json.Unmarshal([]byte(j), &conf2))
assert.NoError(t, json.Unmarshal([]byte(config), &conf2))
assert.Equal(t, conf, conf2)

j2, err := json.Marshal(conf2)
Expand Down
21 changes: 14 additions & 7 deletions constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,16 @@ import "github.com/pion/dtls/v3"

const (
// default as the standard ethernet MTU
// can be overwritten with SettingEngine.SetReceiveMTU()
// can be overwritten with SettingEngine.SetReceiveMTU().
receiveMTU = 1500

// simulcastProbeCount is the amount of RTP Packets
// that handleUndeclaredSSRC will read and try to dispatch from
// mid and rid values
// mid and rid values.
simulcastProbeCount = 10

// simulcastMaxProbeRoutines is how many active routines can be used to probe
// If the total amount of incoming SSRCes exceeds this new requests will be ignored
// If the total amount of incoming SSRCes exceeds this new requests will be ignored.
simulcastMaxProbeRoutines = 25

mediaSectionApplication = "application"
Expand All @@ -33,14 +33,21 @@ const (

generatedCertificateOrigin = "WebRTC"

// AttributeRtxPayloadType is the interceptor attribute added when Read() returns an RTX packet containing the RTX stream payload type
// AttributeRtxPayloadType is the interceptor attribute added when Read()
// returns an RTX packet containing the RTX stream payload type.
AttributeRtxPayloadType = "rtx_payload_type"
// AttributeRtxSsrc is the interceptor attribute added when Read() returns an RTX packet containing the RTX stream SSRC
// AttributeRtxSsrc is the interceptor attribute added when Read()
// returns an RTX packet containing the RTX stream SSRC.
AttributeRtxSsrc = "rtx_ssrc"
// AttributeRtxSequenceNumber is the interceptor attribute added when Read() returns an RTX packet containing the RTX stream sequence number
// AttributeRtxSequenceNumber is the interceptor attribute added when
// Read() returns an RTX packet containing the RTX stream sequence number.
AttributeRtxSequenceNumber = "rtx_sequence_number"
)

func defaultSrtpProtectionProfiles() []dtls.SRTPProtectionProfile {
return []dtls.SRTPProtectionProfile{dtls.SRTP_AEAD_AES_256_GCM, dtls.SRTP_AEAD_AES_128_GCM, dtls.SRTP_AES128_CM_HMAC_SHA1_80}
return []dtls.SRTPProtectionProfile{
dtls.SRTP_AEAD_AES_256_GCM,
dtls.SRTP_AEAD_AES_128_GCM,
dtls.SRTP_AES128_CM_HMAC_SHA1_80,
}
}
Loading

0 comments on commit feeeebf

Please sign in to comment.