github.com/FlowerWrong/netstack@v0.0.0-20191009141956-e5848263af28/tcpip/stack/transport_test.go (about) 1 // Copyright 2018 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 stack_test 16 17 import ( 18 "testing" 19 20 "github.com/FlowerWrong/netstack/tcpip" 21 "github.com/FlowerWrong/netstack/tcpip/buffer" 22 "github.com/FlowerWrong/netstack/tcpip/iptables" 23 "github.com/FlowerWrong/netstack/tcpip/link/channel" 24 "github.com/FlowerWrong/netstack/tcpip/link/loopback" 25 "github.com/FlowerWrong/netstack/tcpip/stack" 26 "github.com/FlowerWrong/netstack/waiter" 27 ) 28 29 const ( 30 fakeTransNumber tcpip.TransportProtocolNumber = 1 31 fakeTransHeaderLen = 3 32 ) 33 34 // fakeTransportEndpoint is a transport-layer protocol endpoint. It counts 35 // received packets; the counts of all endpoints are aggregated in the protocol 36 // descriptor. 37 // 38 // Headers of this protocol are fakeTransHeaderLen bytes, but we currently don't 39 // use it. 40 type fakeTransportEndpoint struct { 41 id stack.TransportEndpointID 42 stack *stack.Stack 43 netProto tcpip.NetworkProtocolNumber 44 proto *fakeTransportProtocol 45 peerAddr tcpip.Address 46 route stack.Route 47 48 // acceptQueue is non-nil iff bound. 49 acceptQueue []fakeTransportEndpoint 50 } 51 52 func newFakeTransportEndpoint(stack *stack.Stack, proto *fakeTransportProtocol, netProto tcpip.NetworkProtocolNumber) tcpip.Endpoint { 53 return &fakeTransportEndpoint{stack: stack, netProto: netProto, proto: proto} 54 } 55 56 func (f *fakeTransportEndpoint) Close() { 57 f.route.Release() 58 } 59 60 func (*fakeTransportEndpoint) Readiness(mask waiter.EventMask) waiter.EventMask { 61 return mask 62 } 63 64 func (*fakeTransportEndpoint) Read(*tcpip.FullAddress) (buffer.View, tcpip.ControlMessages, *tcpip.Error) { 65 return buffer.View{}, tcpip.ControlMessages{}, nil 66 } 67 68 func (f *fakeTransportEndpoint) Write(p tcpip.Payloader, opts tcpip.WriteOptions) (int64, <-chan struct{}, *tcpip.Error) { 69 if len(f.route.RemoteAddress) == 0 { 70 return 0, nil, tcpip.ErrNoRoute 71 } 72 73 hdr := buffer.NewPrependable(int(f.route.MaxHeaderLength())) 74 v, err := p.FullPayload() 75 if err != nil { 76 return 0, nil, err 77 } 78 if err := f.route.WritePacket(nil /* gso */, hdr, buffer.View(v).ToVectorisedView(), fakeTransNumber, 123 /* ttl */, false /* useDefaultTTL */); err != nil { 79 return 0, nil, err 80 } 81 82 return int64(len(v)), nil, nil 83 } 84 85 func (f *fakeTransportEndpoint) Peek([][]byte) (int64, tcpip.ControlMessages, *tcpip.Error) { 86 return 0, tcpip.ControlMessages{}, nil 87 } 88 89 // SetSockOpt sets a socket option. Currently not supported. 90 func (*fakeTransportEndpoint) SetSockOpt(interface{}) *tcpip.Error { 91 return tcpip.ErrInvalidEndpointState 92 } 93 94 // SetSockOptInt sets a socket option. Currently not supported. 95 func (*fakeTransportEndpoint) SetSockOptInt(tcpip.SockOpt, int) *tcpip.Error { 96 return tcpip.ErrInvalidEndpointState 97 } 98 99 // GetSockOptInt implements tcpip.Endpoint.GetSockOptInt. 100 func (*fakeTransportEndpoint) GetSockOptInt(opt tcpip.SockOpt) (int, *tcpip.Error) { 101 return -1, tcpip.ErrUnknownProtocolOption 102 } 103 104 // GetSockOpt implements tcpip.Endpoint.GetSockOpt. 105 func (*fakeTransportEndpoint) GetSockOpt(opt interface{}) *tcpip.Error { 106 switch opt.(type) { 107 case tcpip.ErrorOption: 108 return nil 109 } 110 return tcpip.ErrInvalidEndpointState 111 } 112 113 // Disconnect implements tcpip.Endpoint.Disconnect. 114 func (*fakeTransportEndpoint) Disconnect() *tcpip.Error { 115 return tcpip.ErrNotSupported 116 } 117 118 func (f *fakeTransportEndpoint) Connect(addr tcpip.FullAddress) *tcpip.Error { 119 f.peerAddr = addr.Addr 120 121 // Find the route. 122 r, err := f.stack.FindRoute(addr.NIC, "", addr.Addr, fakeNetNumber, false /* multicastLoop */) 123 if err != nil { 124 return tcpip.ErrNoRoute 125 } 126 defer r.Release() 127 128 // Try to register so that we can start receiving packets. 129 f.id.RemoteAddress = addr.Addr 130 err = f.stack.RegisterTransportEndpoint(0, []tcpip.NetworkProtocolNumber{fakeNetNumber}, fakeTransNumber, f.id, f, false /* reuse */, 0 /* bindToDevice */) 131 if err != nil { 132 return err 133 } 134 135 f.route = r.Clone() 136 137 return nil 138 } 139 140 func (f *fakeTransportEndpoint) ConnectEndpoint(e tcpip.Endpoint) *tcpip.Error { 141 return nil 142 } 143 144 func (*fakeTransportEndpoint) Shutdown(tcpip.ShutdownFlags) *tcpip.Error { 145 return nil 146 } 147 148 func (*fakeTransportEndpoint) Reset() { 149 } 150 151 func (*fakeTransportEndpoint) Listen(int) *tcpip.Error { 152 return nil 153 } 154 155 func (f *fakeTransportEndpoint) Accept() (tcpip.Endpoint, *waiter.Queue, *tcpip.Error) { 156 if len(f.acceptQueue) == 0 { 157 return nil, nil, nil 158 } 159 a := f.acceptQueue[0] 160 f.acceptQueue = f.acceptQueue[1:] 161 return &a, nil, nil 162 } 163 164 func (f *fakeTransportEndpoint) Bind(a tcpip.FullAddress) *tcpip.Error { 165 if err := f.stack.RegisterTransportEndpoint( 166 a.NIC, 167 []tcpip.NetworkProtocolNumber{fakeNetNumber}, 168 fakeTransNumber, 169 stack.TransportEndpointID{LocalAddress: a.Addr}, 170 f, 171 false, /* reuse */ 172 0, /* bindtoDevice */ 173 ); err != nil { 174 return err 175 } 176 f.acceptQueue = []fakeTransportEndpoint{} 177 return nil 178 } 179 180 func (*fakeTransportEndpoint) GetLocalAddress() (tcpip.FullAddress, *tcpip.Error) { 181 return tcpip.FullAddress{}, nil 182 } 183 184 func (*fakeTransportEndpoint) GetRemoteAddress() (tcpip.FullAddress, *tcpip.Error) { 185 return tcpip.FullAddress{}, nil 186 } 187 188 func (f *fakeTransportEndpoint) HandlePacket(r *stack.Route, id stack.TransportEndpointID, _ buffer.VectorisedView) { 189 // Increment the number of received packets. 190 f.proto.packetCount++ 191 if f.acceptQueue != nil { 192 f.acceptQueue = append(f.acceptQueue, fakeTransportEndpoint{ 193 id: id, 194 stack: f.stack, 195 netProto: f.netProto, 196 proto: f.proto, 197 peerAddr: r.RemoteAddress, 198 route: r.Clone(), 199 }) 200 } 201 } 202 203 func (f *fakeTransportEndpoint) HandleControlPacket(stack.TransportEndpointID, stack.ControlType, uint32, buffer.VectorisedView) { 204 // Increment the number of received control packets. 205 f.proto.controlCount++ 206 } 207 208 func (f *fakeTransportEndpoint) State() uint32 { 209 return 0 210 } 211 212 func (f *fakeTransportEndpoint) ModerateRecvBuf(copied int) { 213 } 214 215 func (f *fakeTransportEndpoint) IPTables() (iptables.IPTables, error) { 216 return iptables.IPTables{}, nil 217 } 218 219 func (f *fakeTransportEndpoint) Resume(*stack.Stack) { 220 } 221 222 type fakeTransportGoodOption bool 223 224 type fakeTransportBadOption bool 225 226 type fakeTransportInvalidValueOption int 227 228 type fakeTransportProtocolOptions struct { 229 good bool 230 } 231 232 // fakeTransportProtocol is a transport-layer protocol descriptor. It 233 // aggregates the number of packets received via endpoints of this protocol. 234 type fakeTransportProtocol struct { 235 packetCount int 236 controlCount int 237 opts fakeTransportProtocolOptions 238 } 239 240 func (*fakeTransportProtocol) Number() tcpip.TransportProtocolNumber { 241 return fakeTransNumber 242 } 243 244 func (f *fakeTransportProtocol) NewEndpoint(stack *stack.Stack, netProto tcpip.NetworkProtocolNumber, _ *waiter.Queue) (tcpip.Endpoint, *tcpip.Error) { 245 return newFakeTransportEndpoint(stack, f, netProto), nil 246 } 247 248 func (f *fakeTransportProtocol) NewRawEndpoint(stack *stack.Stack, netProto tcpip.NetworkProtocolNumber, _ *waiter.Queue) (tcpip.Endpoint, *tcpip.Error) { 249 return nil, tcpip.ErrUnknownProtocol 250 } 251 252 func (*fakeTransportProtocol) MinimumPacketSize() int { 253 return fakeTransHeaderLen 254 } 255 256 func (*fakeTransportProtocol) ParsePorts(buffer.View) (src, dst uint16, err *tcpip.Error) { 257 return 0, 0, nil 258 } 259 260 func (*fakeTransportProtocol) HandleUnknownDestinationPacket(*stack.Route, stack.TransportEndpointID, buffer.View, buffer.VectorisedView) bool { 261 return true 262 } 263 264 func (f *fakeTransportProtocol) SetOption(option interface{}) *tcpip.Error { 265 switch v := option.(type) { 266 case fakeTransportGoodOption: 267 f.opts.good = bool(v) 268 return nil 269 case fakeTransportInvalidValueOption: 270 return tcpip.ErrInvalidOptionValue 271 default: 272 return tcpip.ErrUnknownProtocolOption 273 } 274 } 275 276 func (f *fakeTransportProtocol) Option(option interface{}) *tcpip.Error { 277 switch v := option.(type) { 278 case *fakeTransportGoodOption: 279 *v = fakeTransportGoodOption(f.opts.good) 280 return nil 281 default: 282 return tcpip.ErrUnknownProtocolOption 283 } 284 } 285 286 func fakeTransFactory() stack.TransportProtocol { 287 return &fakeTransportProtocol{} 288 } 289 290 func TestTransportReceive(t *testing.T) { 291 linkEP := channel.New(10, defaultMTU, "") 292 s := stack.New(stack.Options{ 293 NetworkProtocols: []stack.NetworkProtocol{fakeNetFactory()}, 294 TransportProtocols: []stack.TransportProtocol{fakeTransFactory()}, 295 }) 296 if err := s.CreateNIC(1, linkEP); err != nil { 297 t.Fatalf("CreateNIC failed: %v", err) 298 } 299 300 { 301 subnet, err := tcpip.NewSubnet("\x00", "\x00") 302 if err != nil { 303 t.Fatal(err) 304 } 305 s.SetRouteTable([]tcpip.Route{{Destination: subnet, Gateway: "\x00", NIC: 1}}) 306 } 307 308 if err := s.AddAddress(1, fakeNetNumber, "\x01"); err != nil { 309 t.Fatalf("AddAddress failed: %v", err) 310 } 311 312 // Create endpoint and connect to remote address. 313 wq := waiter.Queue{} 314 ep, err := s.NewEndpoint(fakeTransNumber, fakeNetNumber, &wq) 315 if err != nil { 316 t.Fatalf("NewEndpoint failed: %v", err) 317 } 318 319 if err := ep.Connect(tcpip.FullAddress{0, "\x02", 0}); err != nil { 320 t.Fatalf("Connect failed: %v", err) 321 } 322 323 fakeTrans := s.TransportProtocolInstance(fakeTransNumber).(*fakeTransportProtocol) 324 325 // Create buffer that will hold the packet. 326 buf := buffer.NewView(30) 327 328 // Make sure packet with wrong protocol is not delivered. 329 buf[0] = 1 330 buf[2] = 0 331 linkEP.Inject(fakeNetNumber, buf.ToVectorisedView()) 332 if fakeTrans.packetCount != 0 { 333 t.Errorf("packetCount = %d, want %d", fakeTrans.packetCount, 0) 334 } 335 336 // Make sure packet from the wrong source is not delivered. 337 buf[0] = 1 338 buf[1] = 3 339 buf[2] = byte(fakeTransNumber) 340 linkEP.Inject(fakeNetNumber, buf.ToVectorisedView()) 341 if fakeTrans.packetCount != 0 { 342 t.Errorf("packetCount = %d, want %d", fakeTrans.packetCount, 0) 343 } 344 345 // Make sure packet is delivered. 346 buf[0] = 1 347 buf[1] = 2 348 buf[2] = byte(fakeTransNumber) 349 linkEP.Inject(fakeNetNumber, buf.ToVectorisedView()) 350 if fakeTrans.packetCount != 1 { 351 t.Errorf("packetCount = %d, want %d", fakeTrans.packetCount, 1) 352 } 353 } 354 355 func TestTransportControlReceive(t *testing.T) { 356 linkEP := channel.New(10, defaultMTU, "") 357 s := stack.New(stack.Options{ 358 NetworkProtocols: []stack.NetworkProtocol{fakeNetFactory()}, 359 TransportProtocols: []stack.TransportProtocol{fakeTransFactory()}, 360 }) 361 if err := s.CreateNIC(1, linkEP); err != nil { 362 t.Fatalf("CreateNIC failed: %v", err) 363 } 364 365 { 366 subnet, err := tcpip.NewSubnet("\x00", "\x00") 367 if err != nil { 368 t.Fatal(err) 369 } 370 s.SetRouteTable([]tcpip.Route{{Destination: subnet, Gateway: "\x00", NIC: 1}}) 371 } 372 373 if err := s.AddAddress(1, fakeNetNumber, "\x01"); err != nil { 374 t.Fatalf("AddAddress failed: %v", err) 375 } 376 377 // Create endpoint and connect to remote address. 378 wq := waiter.Queue{} 379 ep, err := s.NewEndpoint(fakeTransNumber, fakeNetNumber, &wq) 380 if err != nil { 381 t.Fatalf("NewEndpoint failed: %v", err) 382 } 383 384 if err := ep.Connect(tcpip.FullAddress{0, "\x02", 0}); err != nil { 385 t.Fatalf("Connect failed: %v", err) 386 } 387 388 fakeTrans := s.TransportProtocolInstance(fakeTransNumber).(*fakeTransportProtocol) 389 390 // Create buffer that will hold the control packet. 391 buf := buffer.NewView(2*fakeNetHeaderLen + 30) 392 393 // Outer packet contains the control protocol number. 394 buf[0] = 1 395 buf[1] = 0xfe 396 buf[2] = uint8(fakeControlProtocol) 397 398 // Make sure packet with wrong protocol is not delivered. 399 buf[fakeNetHeaderLen+0] = 0 400 buf[fakeNetHeaderLen+1] = 1 401 buf[fakeNetHeaderLen+2] = 0 402 linkEP.Inject(fakeNetNumber, buf.ToVectorisedView()) 403 if fakeTrans.controlCount != 0 { 404 t.Errorf("controlCount = %d, want %d", fakeTrans.controlCount, 0) 405 } 406 407 // Make sure packet from the wrong source is not delivered. 408 buf[fakeNetHeaderLen+0] = 3 409 buf[fakeNetHeaderLen+1] = 1 410 buf[fakeNetHeaderLen+2] = byte(fakeTransNumber) 411 linkEP.Inject(fakeNetNumber, buf.ToVectorisedView()) 412 if fakeTrans.controlCount != 0 { 413 t.Errorf("controlCount = %d, want %d", fakeTrans.controlCount, 0) 414 } 415 416 // Make sure packet is delivered. 417 buf[fakeNetHeaderLen+0] = 2 418 buf[fakeNetHeaderLen+1] = 1 419 buf[fakeNetHeaderLen+2] = byte(fakeTransNumber) 420 linkEP.Inject(fakeNetNumber, buf.ToVectorisedView()) 421 if fakeTrans.controlCount != 1 { 422 t.Errorf("controlCount = %d, want %d", fakeTrans.controlCount, 1) 423 } 424 } 425 426 func TestTransportSend(t *testing.T) { 427 linkEP := channel.New(10, defaultMTU, "") 428 s := stack.New(stack.Options{ 429 NetworkProtocols: []stack.NetworkProtocol{fakeNetFactory()}, 430 TransportProtocols: []stack.TransportProtocol{fakeTransFactory()}, 431 }) 432 if err := s.CreateNIC(1, linkEP); err != nil { 433 t.Fatalf("CreateNIC failed: %v", err) 434 } 435 436 if err := s.AddAddress(1, fakeNetNumber, "\x01"); err != nil { 437 t.Fatalf("AddAddress failed: %v", err) 438 } 439 440 { 441 subnet, err := tcpip.NewSubnet("\x00", "\x00") 442 if err != nil { 443 t.Fatal(err) 444 } 445 s.SetRouteTable([]tcpip.Route{{Destination: subnet, Gateway: "\x00", NIC: 1}}) 446 } 447 448 // Create endpoint and bind it. 449 wq := waiter.Queue{} 450 ep, err := s.NewEndpoint(fakeTransNumber, fakeNetNumber, &wq) 451 if err != nil { 452 t.Fatalf("NewEndpoint failed: %v", err) 453 } 454 455 if err := ep.Connect(tcpip.FullAddress{0, "\x02", 0}); err != nil { 456 t.Fatalf("Connect failed: %v", err) 457 } 458 459 // Create buffer that will hold the payload. 460 view := buffer.NewView(30) 461 _, _, err = ep.Write(tcpip.SlicePayload(view), tcpip.WriteOptions{}) 462 if err != nil { 463 t.Fatalf("write failed: %v", err) 464 } 465 466 fakeNet := s.NetworkProtocolInstance(fakeNetNumber).(*fakeNetworkProtocol) 467 468 if fakeNet.sendPacketCount[2] != 1 { 469 t.Errorf("sendPacketCount = %d, want %d", fakeNet.sendPacketCount[2], 1) 470 } 471 } 472 473 func TestTransportOptions(t *testing.T) { 474 s := stack.New(stack.Options{ 475 NetworkProtocols: []stack.NetworkProtocol{fakeNetFactory()}, 476 TransportProtocols: []stack.TransportProtocol{fakeTransFactory()}, 477 }) 478 479 // Try an unsupported transport protocol. 480 if err := s.SetTransportProtocolOption(tcpip.TransportProtocolNumber(99999), fakeTransportGoodOption(false)); err != tcpip.ErrUnknownProtocol { 481 t.Fatalf("SetTransportProtocolOption(fakeTrans2, blah, false) = %v, want = tcpip.ErrUnknownProtocol", err) 482 } 483 484 testCases := []struct { 485 option interface{} 486 wantErr *tcpip.Error 487 verifier func(t *testing.T, p stack.TransportProtocol) 488 }{ 489 {fakeTransportGoodOption(true), nil, func(t *testing.T, p stack.TransportProtocol) { 490 t.Helper() 491 fakeTrans := p.(*fakeTransportProtocol) 492 if fakeTrans.opts.good != true { 493 t.Fatalf("fakeTrans.opts.good = false, want = true") 494 } 495 var v fakeTransportGoodOption 496 if err := s.TransportProtocolOption(fakeTransNumber, &v); err != nil { 497 t.Fatalf("s.TransportProtocolOption(fakeTransNumber, &v) = %v, want = nil, where v is option %T", v, err) 498 } 499 if v != true { 500 t.Fatalf("s.TransportProtocolOption(fakeTransNumber, &v) returned v = %v, want = true", v) 501 } 502 503 }}, 504 {fakeTransportBadOption(true), tcpip.ErrUnknownProtocolOption, nil}, 505 {fakeTransportInvalidValueOption(1), tcpip.ErrInvalidOptionValue, nil}, 506 } 507 for _, tc := range testCases { 508 if got := s.SetTransportProtocolOption(fakeTransNumber, tc.option); got != tc.wantErr { 509 t.Errorf("s.SetTransportProtocolOption(fakeTrans, %v) = %v, want = %v", tc.option, got, tc.wantErr) 510 } 511 if tc.verifier != nil { 512 tc.verifier(t, s.TransportProtocolInstance(fakeTransNumber)) 513 } 514 } 515 } 516 517 func TestTransportForwarding(t *testing.T) { 518 s := stack.New(stack.Options{ 519 NetworkProtocols: []stack.NetworkProtocol{fakeNetFactory()}, 520 TransportProtocols: []stack.TransportProtocol{fakeTransFactory()}, 521 }) 522 s.SetForwarding(true) 523 524 // TODO(b/123449044): Change this to a channel NIC. 525 ep1 := loopback.New() 526 if err := s.CreateNIC(1, ep1); err != nil { 527 t.Fatalf("CreateNIC #1 failed: %v", err) 528 } 529 if err := s.AddAddress(1, fakeNetNumber, "\x01"); err != nil { 530 t.Fatalf("AddAddress #1 failed: %v", err) 531 } 532 533 ep2 := channel.New(10, defaultMTU, "") 534 if err := s.CreateNIC(2, ep2); err != nil { 535 t.Fatalf("CreateNIC #2 failed: %v", err) 536 } 537 if err := s.AddAddress(2, fakeNetNumber, "\x02"); err != nil { 538 t.Fatalf("AddAddress #2 failed: %v", err) 539 } 540 541 // Route all packets to address 3 to NIC 2 and all packets to address 542 // 1 to NIC 1. 543 { 544 subnet0, err := tcpip.NewSubnet("\x03", "\xff") 545 if err != nil { 546 t.Fatal(err) 547 } 548 subnet1, err := tcpip.NewSubnet("\x01", "\xff") 549 if err != nil { 550 t.Fatal(err) 551 } 552 s.SetRouteTable([]tcpip.Route{ 553 {Destination: subnet0, Gateway: "\x00", NIC: 2}, 554 {Destination: subnet1, Gateway: "\x00", NIC: 1}, 555 }) 556 } 557 558 wq := waiter.Queue{} 559 ep, err := s.NewEndpoint(fakeTransNumber, fakeNetNumber, &wq) 560 if err != nil { 561 t.Fatalf("NewEndpoint failed: %v", err) 562 } 563 564 if err := ep.Bind(tcpip.FullAddress{Addr: "\x01", NIC: 1}); err != nil { 565 t.Fatalf("Bind failed: %v", err) 566 } 567 568 // Send a packet to address 1 from address 3. 569 req := buffer.NewView(30) 570 req[0] = 1 571 req[1] = 3 572 req[2] = byte(fakeTransNumber) 573 ep2.Inject(fakeNetNumber, req.ToVectorisedView()) 574 575 aep, _, err := ep.Accept() 576 if err != nil || aep == nil { 577 t.Fatalf("Accept failed: %v, %v", aep, err) 578 } 579 580 resp := buffer.NewView(30) 581 if _, _, err := aep.Write(tcpip.SlicePayload(resp), tcpip.WriteOptions{}); err != nil { 582 t.Fatalf("Write failed: %v", err) 583 } 584 585 var p channel.PacketInfo 586 select { 587 case p = <-ep2.C: 588 default: 589 t.Fatal("Response packet not forwarded") 590 } 591 592 if dst := p.Header[0]; dst != 3 { 593 t.Errorf("Response packet has incorrect destination addresss: got = %d, want = 3", dst) 594 } 595 if src := p.Header[1]; src != 1 { 596 t.Errorf("Response packet has incorrect source addresss: got = %d, want = 3", src) 597 } 598 }