tun.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. //go:build windows
  2. // +build windows
  3. /* SPDX-License-Identifier: MIT
  4. *
  5. * Copyright (C) 2018-2021 WireGuard LLC. All Rights Reserved.
  6. */
  7. //NOTE: This file was forked from https://git.zx2c4.com/wireguard-go/tree/tun/tun_windows.go?id=851efb1bb65555e0f765a3361c8eb5ac47435b19
  8. // Mainly to shed functionality we won't be using and to fix names that display in the system
  9. package wintun
  10. import (
  11. "errors"
  12. "fmt"
  13. "os"
  14. "sync"
  15. "sync/atomic"
  16. "time"
  17. _ "unsafe"
  18. "golang.org/x/sys/windows"
  19. "golang.zx2c4.com/wintun"
  20. )
  21. const (
  22. rateMeasurementGranularity = uint64((time.Second / 2) / time.Nanosecond)
  23. spinloopRateThreshold = 800000000 / 8 // 800mbps
  24. spinloopDuration = uint64(time.Millisecond / 80 / time.Nanosecond) // ~1gbit/s
  25. )
  26. type rateJuggler struct {
  27. current uint64
  28. nextByteCount uint64
  29. nextStartTime int64
  30. changing int32
  31. }
  32. type NativeTun struct {
  33. wt *wintun.Adapter
  34. name string
  35. handle windows.Handle
  36. rate rateJuggler
  37. session wintun.Session
  38. readWait windows.Handle
  39. running sync.WaitGroup
  40. closeOnce sync.Once
  41. close int32
  42. }
  43. var WintunTunnelType = "Nebula"
  44. var WintunStaticRequestedGUID *windows.GUID
  45. //go:linkname procyield runtime.procyield
  46. func procyield(cycles uint32)
  47. //go:linkname nanotime runtime.nanotime
  48. func nanotime() int64
  49. // CreateTUN creates a Wintun interface with the given name. Should a Wintun
  50. // interface with the same name exist, it is reused.
  51. func CreateTUN(ifname string, mtu int) (Device, error) {
  52. return CreateTUNWithRequestedGUID(ifname, WintunStaticRequestedGUID, mtu)
  53. }
  54. // CreateTUNWithRequestedGUID creates a Wintun interface with the given name and
  55. // a requested GUID. Should a Wintun interface with the same name exist, it is reused.
  56. func CreateTUNWithRequestedGUID(ifname string, requestedGUID *windows.GUID, mtu int) (Device, error) {
  57. wt, err := wintun.CreateAdapter(ifname, WintunTunnelType, requestedGUID)
  58. if err != nil {
  59. return nil, fmt.Errorf("Error creating interface: %w", err)
  60. }
  61. tun := &NativeTun{
  62. wt: wt,
  63. name: ifname,
  64. handle: windows.InvalidHandle,
  65. }
  66. tun.session, err = wt.StartSession(0x800000) // Ring capacity, 8 MiB
  67. if err != nil {
  68. tun.wt.Close()
  69. return nil, fmt.Errorf("Error starting session: %w", err)
  70. }
  71. tun.readWait = tun.session.ReadWaitEvent()
  72. return tun, nil
  73. }
  74. func (tun *NativeTun) Name() (string, error) {
  75. return tun.name, nil
  76. }
  77. func (tun *NativeTun) File() *os.File {
  78. return nil
  79. }
  80. func (tun *NativeTun) Close() error {
  81. var err error
  82. tun.closeOnce.Do(func() {
  83. atomic.StoreInt32(&tun.close, 1)
  84. windows.SetEvent(tun.readWait)
  85. tun.running.Wait()
  86. tun.session.End()
  87. if tun.wt != nil {
  88. tun.wt.Close()
  89. }
  90. })
  91. return err
  92. }
  93. // Note: Read() and Write() assume the caller comes only from a single thread; there's no locking.
  94. func (tun *NativeTun) Read(buff []byte, offset int) (int, error) {
  95. tun.running.Add(1)
  96. defer tun.running.Done()
  97. retry:
  98. if atomic.LoadInt32(&tun.close) == 1 {
  99. return 0, os.ErrClosed
  100. }
  101. start := nanotime()
  102. shouldSpin := atomic.LoadUint64(&tun.rate.current) >= spinloopRateThreshold && uint64(start-atomic.LoadInt64(&tun.rate.nextStartTime)) <= rateMeasurementGranularity*2
  103. for {
  104. if atomic.LoadInt32(&tun.close) == 1 {
  105. return 0, os.ErrClosed
  106. }
  107. packet, err := tun.session.ReceivePacket()
  108. switch err {
  109. case nil:
  110. packetSize := len(packet)
  111. copy(buff[offset:], packet)
  112. tun.session.ReleaseReceivePacket(packet)
  113. tun.rate.update(uint64(packetSize))
  114. return packetSize, nil
  115. case windows.ERROR_NO_MORE_ITEMS:
  116. if !shouldSpin || uint64(nanotime()-start) >= spinloopDuration {
  117. windows.WaitForSingleObject(tun.readWait, windows.INFINITE)
  118. goto retry
  119. }
  120. procyield(1)
  121. continue
  122. case windows.ERROR_HANDLE_EOF:
  123. return 0, os.ErrClosed
  124. case windows.ERROR_INVALID_DATA:
  125. return 0, errors.New("Send ring corrupt")
  126. }
  127. return 0, fmt.Errorf("Read failed: %w", err)
  128. }
  129. }
  130. func (tun *NativeTun) Flush() error {
  131. return nil
  132. }
  133. func (tun *NativeTun) Write(buff []byte, offset int) (int, error) {
  134. tun.running.Add(1)
  135. defer tun.running.Done()
  136. if atomic.LoadInt32(&tun.close) == 1 {
  137. return 0, os.ErrClosed
  138. }
  139. packetSize := len(buff) - offset
  140. tun.rate.update(uint64(packetSize))
  141. packet, err := tun.session.AllocateSendPacket(packetSize)
  142. if err == nil {
  143. copy(packet, buff[offset:])
  144. tun.session.SendPacket(packet)
  145. return packetSize, nil
  146. }
  147. switch err {
  148. case windows.ERROR_HANDLE_EOF:
  149. return 0, os.ErrClosed
  150. case windows.ERROR_BUFFER_OVERFLOW:
  151. return 0, nil // Dropping when ring is full.
  152. }
  153. return 0, fmt.Errorf("Write failed: %w", err)
  154. }
  155. // LUID returns Windows interface instance ID.
  156. func (tun *NativeTun) LUID() uint64 {
  157. tun.running.Add(1)
  158. defer tun.running.Done()
  159. if atomic.LoadInt32(&tun.close) == 1 {
  160. return 0
  161. }
  162. return tun.wt.LUID()
  163. }
  164. // RunningVersion returns the running version of the Wintun driver.
  165. func (tun *NativeTun) RunningVersion() (version uint32, err error) {
  166. return wintun.RunningVersion()
  167. }
  168. func (rate *rateJuggler) update(packetLen uint64) {
  169. now := nanotime()
  170. total := atomic.AddUint64(&rate.nextByteCount, packetLen)
  171. period := uint64(now - atomic.LoadInt64(&rate.nextStartTime))
  172. if period >= rateMeasurementGranularity {
  173. if !atomic.CompareAndSwapInt32(&rate.changing, 0, 1) {
  174. return
  175. }
  176. atomic.StoreInt64(&rate.nextStartTime, now)
  177. atomic.StoreUint64(&rate.current, total*uint64(time.Second/time.Nanosecond)/period)
  178. atomic.StoreUint64(&rate.nextByteCount, 0)
  179. atomic.StoreInt32(&rate.changing, 0)
  180. }
  181. }