tun.go 5.4 KB

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