github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/pkg/tcpip/link/ethernet/ethernet_test.go (about) 1 // Copyright 2021 The gVisor Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package ethernet_test 16 17 import ( 18 "testing" 19 20 "github.com/SagerNet/gvisor/pkg/tcpip" 21 "github.com/SagerNet/gvisor/pkg/tcpip/buffer" 22 "github.com/SagerNet/gvisor/pkg/tcpip/header" 23 "github.com/SagerNet/gvisor/pkg/tcpip/link/channel" 24 "github.com/SagerNet/gvisor/pkg/tcpip/link/ethernet" 25 "github.com/SagerNet/gvisor/pkg/tcpip/stack" 26 ) 27 28 var _ stack.NetworkDispatcher = (*testNetworkDispatcher)(nil) 29 30 type testNetworkDispatcher struct { 31 networkPackets int 32 } 33 34 func (t *testNetworkDispatcher) DeliverNetworkPacket(_, _ tcpip.LinkAddress, _ tcpip.NetworkProtocolNumber, _ *stack.PacketBuffer) { 35 t.networkPackets++ 36 } 37 38 func (*testNetworkDispatcher) DeliverOutboundPacket(_, _ tcpip.LinkAddress, _ tcpip.NetworkProtocolNumber, _ *stack.PacketBuffer) { 39 } 40 41 func TestDeliverNetworkPacket(t *testing.T) { 42 const ( 43 linkAddr = tcpip.LinkAddress("\x02\x02\x03\x04\x05\x06") 44 otherLinkAddr1 = tcpip.LinkAddress("\x02\x02\x03\x04\x05\x07") 45 otherLinkAddr2 = tcpip.LinkAddress("\x02\x02\x03\x04\x05\x08") 46 ) 47 48 e := ethernet.New(channel.New(0, 0, linkAddr)) 49 var networkDispatcher testNetworkDispatcher 50 e.Attach(&networkDispatcher) 51 52 if networkDispatcher.networkPackets != 0 { 53 t.Fatalf("got networkDispatcher.networkPackets = %d, want = 0", networkDispatcher.networkPackets) 54 } 55 56 // An ethernet frame with a destination link address that is not assigned to 57 // our ethernet link endpoint should still be delivered to the network 58 // dispatcher since the ethernet endpoint is not expected to filter frames. 59 eth := buffer.NewView(header.EthernetMinimumSize) 60 header.Ethernet(eth).Encode(&header.EthernetFields{ 61 SrcAddr: otherLinkAddr1, 62 DstAddr: otherLinkAddr2, 63 Type: header.IPv4ProtocolNumber, 64 }) 65 e.DeliverNetworkPacket("", "", 0, stack.NewPacketBuffer(stack.PacketBufferOptions{ 66 Data: eth.ToVectorisedView(), 67 })) 68 if networkDispatcher.networkPackets != 1 { 69 t.Fatalf("got networkDispatcher.networkPackets = %d, want = 1", networkDispatcher.networkPackets) 70 } 71 }