nic.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package tun
  2. import (
  3. "github.com/v2fly/v2ray-core/v5/app/router/routercommon"
  4. "gvisor.dev/gvisor/pkg/tcpip"
  5. "gvisor.dev/gvisor/pkg/tcpip/network/ipv4"
  6. "gvisor.dev/gvisor/pkg/tcpip/network/ipv6"
  7. "gvisor.dev/gvisor/pkg/tcpip/stack"
  8. )
  9. func CreateNIC(id tcpip.NICID, linkEndpoint stack.LinkEndpoint) StackOption {
  10. return func(s *stack.Stack) error {
  11. if err := s.CreateNICWithOptions(id, linkEndpoint,
  12. stack.NICOptions{
  13. Disabled: false,
  14. QDisc: nil,
  15. }); err != nil {
  16. return newError("failed to create NIC:", err)
  17. }
  18. return nil
  19. }
  20. }
  21. func SetPromiscuousMode(id tcpip.NICID, enable bool) StackOption {
  22. return func(s *stack.Stack) error {
  23. if err := s.SetPromiscuousMode(id, enable); err != nil {
  24. return newError("failed to set promiscuous mode:", err)
  25. }
  26. return nil
  27. }
  28. }
  29. func SetSpoofing(id tcpip.NICID, enable bool) StackOption {
  30. return func(s *stack.Stack) error {
  31. if err := s.SetSpoofing(id, enable); err != nil {
  32. return newError("failed to set spoofing:", err)
  33. }
  34. return nil
  35. }
  36. }
  37. func AddProtocolAddress(id tcpip.NICID, ips []*routercommon.CIDR) StackOption {
  38. return func(s *stack.Stack) error {
  39. for _, ip := range ips {
  40. tcpIpAddr := tcpip.AddrFrom4Slice(ip.Ip)
  41. protocolAddress := tcpip.ProtocolAddress{
  42. AddressWithPrefix: tcpip.AddressWithPrefix{
  43. Address: tcpIpAddr,
  44. PrefixLen: int(ip.Prefix),
  45. },
  46. }
  47. switch tcpIpAddr.Len() {
  48. case 4:
  49. protocolAddress.Protocol = ipv4.ProtocolNumber
  50. case 16:
  51. protocolAddress.Protocol = ipv6.ProtocolNumber
  52. default:
  53. return newError("invalid IP address length:", tcpIpAddr.Len())
  54. }
  55. if err := s.AddProtocolAddress(id, protocolAddress, stack.AddressProperties{}); err != nil {
  56. return newError("failed to add protocol address:", err)
  57. }
  58. }
  59. return nil
  60. }
  61. }
  62. func SetRouteTable(id tcpip.NICID, routes []*routercommon.CIDR) StackOption {
  63. return func(s *stack.Stack) error {
  64. s.SetRouteTable(func() (table []tcpip.Route) {
  65. for _, cidrs := range routes {
  66. subnet := tcpip.AddressWithPrefix{
  67. Address: tcpip.AddrFrom4Slice(cidrs.Ip),
  68. PrefixLen: int(cidrs.Prefix),
  69. }.Subnet()
  70. route := tcpip.Route{
  71. Destination: subnet,
  72. NIC: id,
  73. }
  74. table = append(table, route)
  75. }
  76. return
  77. }())
  78. return nil
  79. }
  80. }