Skip to content

Commit 4c24542

Browse files
committed
api/types/network: Port,PortRange: don't panic on zero values
- Prevent panic when calling .Proto() on zero values - Don't iterate on zero-value port-ranges Signed-off-by: Sebastiaan van Stijn <[email protected]>
1 parent 1e7b03a commit 4c24542

3 files changed

Lines changed: 27 additions & 1 deletion

File tree

api/types/network/port.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,9 @@ func (p Port) Num() uint16 {
7979

8080
// Proto returns p's network protocol.
8181
func (p Port) Proto() IPProtocol {
82+
if p.proto == protoZero {
83+
return ""
84+
}
8285
return p.proto.Value()
8386
}
8487

@@ -232,6 +235,9 @@ func (pr PortRange) End() uint16 {
232235

233236
// Proto returns pr's network protocol.
234237
func (pr PortRange) Proto() IPProtocol {
238+
if pr.proto == protoZero {
239+
return ""
240+
}
235241
return pr.proto.Value()
236242
}
237243

@@ -307,6 +313,9 @@ func (pr PortRange) Range() PortRange {
307313
// }
308314
func (pr PortRange) All() iter.Seq[Port] {
309315
return func(yield func(Port) bool) {
316+
if pr.proto == protoZero {
317+
return
318+
}
310319
for i := uint32(pr.Start()); i <= uint32(pr.End()); i++ {
311320
if !yield(Port{num: uint16(i), proto: pr.proto}) {
312321
return

api/types/network/port_test.go

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,9 @@ func TestPort(t *testing.T) {
2525
assert.Check(t, p.IsZero())
2626
assert.Check(t, !p.IsValid())
2727
assert.Equal(t, p.String(), "invalid port")
28+
assert.Equal(t, p.Proto(), IPProtocol(""))
29+
assert.Equal(t, p.Num(), uint16(0))
30+
assert.Equal(t, p.Range(), PortRange{})
2831

2932
t.Run("Marshal Unmarshal", func(t *testing.T) {
3033
var p Port
@@ -266,6 +269,11 @@ func TestPortRange(t *testing.T) {
266269
assert.Check(t, pr.IsZero())
267270
assert.Check(t, !pr.IsValid())
268271
assert.Equal(t, pr.String(), "invalid port range")
272+
assert.Equal(t, pr.Start(), uint16(0))
273+
assert.Equal(t, pr.End(), uint16(0))
274+
assert.Equal(t, pr.Proto(), IPProtocol(""))
275+
assert.Equal(t, pr.Range(), pr)
276+
assert.Check(t, slices.Equal(slices.Collect(pr.All()), []Port{}))
269277

270278
t.Run("Marshal Unmarshal", func(t *testing.T) {
271279
var pr PortRange
@@ -515,7 +523,7 @@ func TestPortRange(t *testing.T) {
515523
want: []Port{portFrom(1000, TCP), portFrom(1001, TCP), portFrom(1002, TCP)},
516524
},
517525
{
518-
in: "0-0/tcp",
526+
in: "0-0/tcp", // TODO(thaJeztah): should this result in "zero-value range" and an empty list?
519527
want: []Port{portFrom(0, TCP)},
520528
},
521529
{

vendor/github.com/moby/moby/api/types/network/port.go

Lines changed: 9 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)