diff --git a/extras/utils/portunion.go b/extras/utils/portunion.go index 20a31d0f1b..f76a6fd0a6 100644 --- a/extras/utils/portunion.go +++ b/extras/utils/portunion.go @@ -74,7 +74,7 @@ func (u PortUnion) Normalize() PortUnion { normalized := PortUnion{u[0]} for _, current := range u[1:] { last := &normalized[len(normalized)-1] - if current.Start <= last.End+1 { + if uint32(current.Start) <= uint32(last.End)+1 { if current.End > last.End { last.End = current.End } @@ -89,8 +89,8 @@ func (u PortUnion) Normalize() PortUnion { func (u PortUnion) Ports() []uint16 { var ports []uint16 for _, r := range u { - for i := r.Start; i <= r.End; i++ { - ports = append(ports, i) + for i := uint32(r.Start); i <= uint32(r.End); i++ { + ports = append(ports, uint16(i)) } } return ports diff --git a/extras/utils/portunion_test.go b/extras/utils/portunion_test.go index 551bae137a..ba056a3741 100644 --- a/extras/utils/portunion_test.go +++ b/extras/utils/portunion_test.go @@ -2,6 +2,7 @@ package utils import ( "reflect" + "slices" "testing" ) @@ -51,6 +52,16 @@ func TestParsePortUnion(t *testing.T) { s: "5678,1200-1236,9100-9012,1234-1240", want: PortUnion{{1200, 1240}, {5678, 5678}, {9012, 9100}}, }, + { + name: "multiple ports and ranges with 65535 (reversed, unsorted, overlapping)", + s: "5678,1200-1236,65531-65535,65532-65534,9100-9012,1234-1240", + want: PortUnion{{1200, 1240}, {5678, 5678}, {9012, 9100}, {65531, 65535}}, + }, + { + name: "multiple ports and ranges with 65535 (reversed, unsorted, overlapping) 2", + s: "5678,1200-1236,65532-65535,65531-65534,9100-9012,1234-1240", + want: PortUnion{{1200, 1240}, {5678, 5678}, {9012, 9100}, {65531, 65535}}, + }, { name: "invalid 1", s: "1234-", @@ -90,3 +101,50 @@ func TestParsePortUnion(t *testing.T) { }) } } + +func TestPortUnion_Ports(t *testing.T) { + tests := []struct { + name string + pu PortUnion + want []uint16 + }{ + { + name: "single port", + pu: PortUnion{{1234, 1234}}, + want: []uint16{1234}, + }, + { + name: "multiple ports", + pu: PortUnion{{1234, 1236}}, + want: []uint16{1234, 1235, 1236}, + }, + { + name: "multiple ports and ranges", + pu: PortUnion{{1234, 1236}, {5678, 5680}, {9000, 9002}}, + want: []uint16{1234, 1235, 1236, 5678, 5679, 5680, 9000, 9001, 9002}, + }, + { + name: "single port 65535", + pu: PortUnion{{65535, 65535}}, + want: []uint16{65535}, + }, + { + name: "port range with 65535", + pu: PortUnion{{65530, 65535}}, + want: []uint16{65530, 65531, 65532, 65533, 65534, 65535}, + }, + { + name: "multiple ports and ranges with 65535", + pu: PortUnion{{65530, 65535}, {1234, 1236}}, + want: []uint16{65530, 65531, 65532, 65533, 65534, 65535, 1234, 1235, 1236}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := tt.pu.Ports(); !slices.Equal(got, tt.want) { + t.Errorf("PortUnion.Ports() = %v, want %v", got, tt.want) + } + }) + } +}