tun.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  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. //
  50. // CreateTUN creates a Wintun interface with the given name. Should a Wintun
  51. // interface with the same name exist, it is reused.
  52. //
  53. func CreateTUN(ifname string, mtu int) (Device, error) {
  54. return CreateTUNWithRequestedGUID(ifname, WintunStaticRequestedGUID, mtu)
  55. }
  56. //
  57. // CreateTUNWithRequestedGUID creates a Wintun interface with the given name and
  58. // a requested GUID. Should a Wintun interface with the same name exist, it is reused.
  59. //
  60. func CreateTUNWithRequestedGUID(ifname string, requestedGUID *windows.GUID, mtu int) (Device, error) {
  61. wt, err := wintun.CreateAdapter(ifname, WintunTunnelType, requestedGUID)
  62. if err != nil {
  63. return nil, fmt.Errorf("Error creating interface: %w", err)
  64. }
  65. tun := &NativeTun{
  66. wt: wt,
  67. name: ifname,
  68. handle: windows.InvalidHandle,
  69. }
  70. tun.session, err = wt.StartSession(0x800000) // Ring capacity, 8 MiB
  71. if err != nil {
  72. tun.wt.Close()
  73. return nil, fmt.Errorf("Error starting session: %w", err)
  74. }
  75. tun.readWait = tun.session.ReadWaitEvent()
  76. return tun, nil
  77. }
  78. func (tun *NativeTun) Name() (string, error) {
  79. return tun.name, nil
  80. }
  81. func (tun *NativeTun) File() *os.File {
  82. return nil
  83. }
  84. func (tun *NativeTun) Close() error {
  85. var err error
  86. tun.closeOnce.Do(func() {
  87. atomic.StoreInt32(&tun.close, 1)
  88. windows.SetEvent(tun.readWait)
  89. tun.running.Wait()
  90. tun.session.End()
  91. if tun.wt != nil {
  92. tun.wt.Close()
  93. }
  94. })
  95. return err
  96. }
  97. // Note: Read() and Write() assume the caller comes only from a single thread; there's no locking.
  98. func (tun *NativeTun) Read(buff []byte, offset int) (int, error) {
  99. tun.running.Add(1)
  100. defer tun.running.Done()
  101. retry:
  102. if atomic.LoadInt32(&tun.close) == 1 {
  103. return 0, os.ErrClosed
  104. }
  105. start := nanotime()
  106. shouldSpin := atomic.LoadUint64(&tun.rate.current) >= spinloopRateThreshold && uint64(start-atomic.LoadInt64(&tun.rate.nextStartTime)) <= rateMeasurementGranularity*2
  107. for {
  108. if atomic.LoadInt32(&tun.close) == 1 {
  109. return 0, os.ErrClosed
  110. }
  111. packet, err := tun.session.ReceivePacket()
  112. switch err {
  113. case nil:
  114. packetSize := len(packet)
  115. copy(buff[offset:], packet)
  116. tun.session.ReleaseReceivePacket(packet)
  117. tun.rate.update(uint64(packetSize))
  118. return packetSize, nil
  119. case windows.ERROR_NO_MORE_ITEMS:
  120. if !shouldSpin || uint64(nanotime()-start) >= spinloopDuration {
  121. windows.WaitForSingleObject(tun.readWait, windows.INFINITE)
  122. goto retry
  123. }
  124. procyield(1)
  125. continue
  126. case windows.ERROR_HANDLE_EOF:
  127. return 0, os.ErrClosed
  128. case windows.ERROR_INVALID_DATA:
  129. return 0, errors.New("Send ring corrupt")
  130. }
  131. return 0, fmt.Errorf("Read failed: %w", err)
  132. }
  133. }
  134. func (tun *NativeTun) Flush() error {
  135. return nil
  136. }
  137. func (tun *NativeTun) Write(buff []byte, offset int) (int, error) {
  138. tun.running.Add(1)
  139. defer tun.running.Done()
  140. if atomic.LoadInt32(&tun.close) == 1 {
  141. return 0, os.ErrClosed
  142. }
  143. packetSize := len(buff) - offset
  144. tun.rate.update(uint64(packetSize))
  145. packet, err := tun.session.AllocateSendPacket(packetSize)
  146. if err == nil {
  147. copy(packet, buff[offset:])
  148. tun.session.SendPacket(packet)
  149. return packetSize, nil
  150. }
  151. switch err {
  152. case windows.ERROR_HANDLE_EOF:
  153. return 0, os.ErrClosed
  154. case windows.ERROR_BUFFER_OVERFLOW:
  155. return 0, nil // Dropping when ring is full.
  156. }
  157. return 0, fmt.Errorf("Write failed: %w", err)
  158. }
  159. // LUID returns Windows interface instance ID.
  160. func (tun *NativeTun) LUID() uint64 {
  161. tun.running.Add(1)
  162. defer tun.running.Done()
  163. if atomic.LoadInt32(&tun.close) == 1 {
  164. return 0
  165. }
  166. return tun.wt.LUID()
  167. }
  168. // RunningVersion returns the running version of the Wintun driver.
  169. func (tun *NativeTun) RunningVersion() (version uint32, err error) {
  170. return wintun.RunningVersion()
  171. }
  172. func (rate *rateJuggler) update(packetLen uint64) {
  173. now := nanotime()
  174. total := atomic.AddUint64(&rate.nextByteCount, packetLen)
  175. period := uint64(now - atomic.LoadInt64(&rate.nextStartTime))
  176. if period >= rateMeasurementGranularity {
  177. if !atomic.CompareAndSwapInt32(&rate.changing, 0, 1) {
  178. return
  179. }
  180. atomic.StoreInt64(&rate.nextStartTime, now)
  181. atomic.StoreUint64(&rate.current, total*uint64(time.Second/time.Nanosecond)/period)
  182. atomic.StoreUint64(&rate.nextByteCount, 0)
  183. atomic.StoreInt32(&rate.changing, 0)
  184. }
  185. }