Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 31 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,4 @@ issues:
- path: cmd
linters:
- forbidigo

32 changes: 20 additions & 12 deletions addr.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,31 +15,31 @@
// This attribute is used only by servers for achieving backwards
// compatibility with RFC 3489 clients.
//
// RFC 5389 Section 15.1
// RFC 5389 Section 15.1.
type MappedAddress struct {
IP net.IP
Port int
}

// AlternateServer represents ALTERNATE-SERVER attribute.
//
// RFC 5389 Section 15.11
// RFC 5389 Section 15.11.
type AlternateServer struct {
IP net.IP
Port int
}

// ResponseOrigin represents RESPONSE-ORIGIN attribute.
//
// RFC 5780 Section 7.3
// RFC 5780 Section 7.3.
type ResponseOrigin struct {
IP net.IP
Port int
}

// OtherAddress represents OTHER-ADDRESS attribute.
//
// RFC 5780 Section 7.4
// RFC 5780 Section 7.4.
type OtherAddress struct {
IP net.IP
Port int
Expand All @@ -48,12 +48,14 @@
// AddTo adds ALTERNATE-SERVER attribute to message.
func (s *AlternateServer) AddTo(m *Message) error {
a := (*MappedAddress)(s)

return a.AddToAs(m, AttrAlternateServer)
}

// GetFrom decodes ALTERNATE-SERVER from message.
func (s *AlternateServer) GetFrom(m *Message) error {
a := (*MappedAddress)(s)

return a.GetFromAs(m, AttrAlternateServer)
}

Expand All @@ -63,14 +65,14 @@

// GetFromAs decodes MAPPED-ADDRESS value in message m as an attribute of type t.
func (a *MappedAddress) GetFromAs(m *Message, t AttrType) error {
v, err := m.Get(t)
value, err := m.Get(t)
if err != nil {
return err
}
if len(v) <= 4 {
if len(value) <= 4 {
return io.ErrUnexpectedEOF
}
family := bin.Uint16(v[0:2])
family := bin.Uint16(value[0:2])
if family != familyIPv6 && family != familyIPv4 {
return newDecodeErr("xor-mapped address", "family",
fmt.Sprintf("bad value %d", family),
Expand All @@ -91,13 +93,14 @@
for i := range a.IP {
a.IP[i] = 0
}
a.Port = int(bin.Uint16(v[2:4]))
copy(a.IP, v[4:])
a.Port = int(bin.Uint16(value[2:4]))
copy(a.IP, value[4:])

return nil
}

// AddToAs adds MAPPED-ADDRESS value to m as t attribute.
func (a *MappedAddress) AddToAs(m *Message, t AttrType) error {
func (a *MappedAddress) AddToAs(msg *Message, attrType AttrType) error {
var (
family = familyIPv4
ip = a.IP
Expand All @@ -114,9 +117,10 @@
value := make([]byte, 128)
value[0] = 0 // first 8 bits are zeroes
bin.PutUint16(value[0:2], family)
bin.PutUint16(value[2:4], uint16(a.Port))
bin.PutUint16(value[2:4], uint16(a.Port)) //nolint:gosec //G115
copy(value[4:], ip)
m.Add(t, value[:4+len(ip)])
msg.Add(attrType, value[:4+len(ip)])

return nil
}

Expand All @@ -133,12 +137,14 @@
// AddTo adds OTHER-ADDRESS attribute to message.
func (o *OtherAddress) AddTo(m *Message) error {
a := (*MappedAddress)(o)

return a.AddToAs(m, AttrOtherAddress)
}

// GetFrom decodes OTHER-ADDRESS from message.
func (o *OtherAddress) GetFrom(m *Message) error {
a := (*MappedAddress)(o)

return a.GetFromAs(m, AttrOtherAddress)
}

Expand All @@ -149,12 +155,14 @@
// AddTo adds RESPONSE-ORIGIN attribute to message.
func (o *ResponseOrigin) AddTo(m *Message) error {
a := (*MappedAddress)(o)

Check warning on line 158 in addr.go

View check run for this annotation

Codecov / codecov/patch

addr.go#L158

Added line #L158 was not covered by tests
return a.AddToAs(m, AttrResponseOrigin)
}

// GetFrom decodes RESPONSE-ORIGIN from message.
func (o *ResponseOrigin) GetFrom(m *Message) error {
a := (*MappedAddress)(o)

Check warning on line 165 in addr.go

View check run for this annotation

Codecov / codecov/patch

addr.go#L165

Added line #L165 was not covered by tests
return a.GetFromAs(m, AttrResponseOrigin)
}

Expand Down
12 changes: 6 additions & 6 deletions addr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
)

func TestMappedAddress(t *testing.T) {
m := new(Message)
msg := new(Message)
addr := &MappedAddress{
IP: net.ParseIP("122.12.34.5"),
Port: 5412,
Expand All @@ -23,17 +23,17 @@ func TestMappedAddress(t *testing.T) {
badAddr := &MappedAddress{
IP: net.IP{1, 2, 3},
}
if err := badAddr.AddTo(m); err == nil {
if err := badAddr.AddTo(msg); err == nil {
t.Error("should error")
}
})
t.Run("AddTo", func(t *testing.T) {
if err := addr.AddTo(m); err != nil {
if err := addr.AddTo(msg); err != nil {
t.Error(err)
}
t.Run("GetFrom", func(t *testing.T) {
got := new(MappedAddress)
if err := got.GetFrom(m); err != nil {
if err := got.GetFrom(msg); err != nil {
t.Error(err)
}
if !got.IP.Equal(addr.IP) {
Expand All @@ -46,9 +46,9 @@ func TestMappedAddress(t *testing.T) {
}
})
t.Run("Bad family", func(t *testing.T) {
v, _ := m.Attributes.Get(AttrMappedAddress)
v, _ := msg.Attributes.Get(AttrMappedAddress)
v.Value[0] = 32
if err := got.GetFrom(m); err == nil {
if err := got.GetFrom(msg); err == nil {
t.Error("should error")
}
})
Expand Down
16 changes: 14 additions & 2 deletions agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ func NewAgent(h Handler) *Agent {
transactions: make(map[transactionID]agentTransaction),
handler: h,
}

return a
}

Expand Down Expand Up @@ -80,6 +81,7 @@ func (a *Agent) StopWithError(id [TransactionIDSize]byte, err error) error {
a.mux.Lock()
if a.closed {
a.mux.Unlock()

return ErrAgentClosed
}
t, exists := a.transactions[id]
Expand All @@ -93,6 +95,7 @@ func (a *Agent) StopWithError(id [TransactionIDSize]byte, err error) error {
TransactionID: t.id,
Error: err,
})

return nil
}

Expand Down Expand Up @@ -124,6 +127,7 @@ func (a *Agent) Start(id [TransactionIDSize]byte, deadline time.Time) error {
id: id,
deadline: deadline,
}

return nil
}

Expand All @@ -147,6 +151,7 @@ func (a *Agent) Collect(gcTime time.Time) error {
// All transactions should be already closed
// during Close() call.
a.mux.Unlock()

return ErrAgentClosed
}
// Adding all transactions with deadline before gcTime
Expand Down Expand Up @@ -175,24 +180,27 @@ func (a *Agent) Collect(gcTime time.Time) error {
event.TransactionID = id
h(event)
}

return nil
}

// Process incoming message, synchronously passing it to handler.
func (a *Agent) Process(m *Message) error {
e := Event{
event := Event{
TransactionID: m.TransactionID,
Message: m,
}
a.mux.Lock()
if a.closed {
a.mux.Unlock()

return ErrAgentClosed
}
h := a.handler
delete(a.transactions, m.TransactionID)
a.mux.Unlock()
h(e)
h(event)

return nil
}

Expand All @@ -201,10 +209,12 @@ func (a *Agent) SetHandler(h Handler) error {
a.mux.Lock()
if a.closed {
a.mux.Unlock()

return ErrAgentClosed
}
a.handler = h
a.mux.Unlock()

return nil
}

Expand All @@ -217,6 +227,7 @@ func (a *Agent) Close() error {
a.mux.Lock()
if a.closed {
a.mux.Unlock()

return ErrAgentClosed
}
for _, t := range a.transactions {
Expand All @@ -227,6 +238,7 @@ func (a *Agent) Close() error {
a.closed = true
a.handler = nil
a.mux.Unlock()

return nil
}

Expand Down
Loading
Loading