if.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package water
  2. import (
  3. "errors"
  4. "io"
  5. )
  6. // Interface is a TUN/TAP interface.
  7. //
  8. // MultiQueue(Linux kernel > 3.8): With MultiQueue enabled, user should hold multiple
  9. // interfaces to send/receive packet in parallel.
  10. // Kernel document about MultiQueue: https://www.kernel.org/doc/Documentation/networking/tuntap.txt
  11. type Interface struct {
  12. isTAP bool
  13. io.ReadWriteCloser
  14. name string
  15. }
  16. // DeviceType is the type for specifying device types.
  17. type DeviceType int
  18. // TUN and TAP device types.
  19. const (
  20. _ = iota
  21. TUN
  22. TAP
  23. )
  24. // Config defines parameters required to create a TUN/TAP interface. It's only
  25. // used when the device is initialized. A zero-value Config is a valid
  26. // configuration.
  27. type Config struct {
  28. // DeviceType specifies whether the device is a TUN or TAP interface. A
  29. // zero-value is treated as TUN.
  30. DeviceType DeviceType
  31. // PlatformSpecificParams defines parameters that differ on different
  32. // platforms. See comments for the type for more details.
  33. PlatformSpecificParams
  34. }
  35. func defaultConfig() Config {
  36. return Config{
  37. DeviceType: TUN,
  38. PlatformSpecificParams: defaultPlatformSpecificParams(),
  39. }
  40. }
  41. var zeroConfig Config
  42. // New creates a new TUN/TAP interface using config.
  43. func New(config Config) (ifce *Interface, err error) {
  44. if zeroConfig == config {
  45. config = defaultConfig()
  46. }
  47. if config.PlatformSpecificParams == zeroConfig.PlatformSpecificParams {
  48. config.PlatformSpecificParams = defaultPlatformSpecificParams()
  49. }
  50. switch config.DeviceType {
  51. case TUN, TAP:
  52. return openDev(config)
  53. default:
  54. return nil, errors.New("unknown device type")
  55. }
  56. }
  57. // IsTUN returns true if ifce is a TUN interface.
  58. func (ifce *Interface) IsTUN() bool {
  59. return !ifce.isTAP
  60. }
  61. // IsTAP returns true if ifce is a TAP interface.
  62. func (ifce *Interface) IsTAP() bool {
  63. return ifce.isTAP
  64. }
  65. // Name returns the interface name of ifce, e.g. tun0, tap1, tun0, etc..
  66. func (ifce *Interface) Name() string {
  67. return ifce.name
  68. }