wlanapi_windows.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. //go:build windows
  2. // +build windows
  3. package wifi
  4. /*
  5. Native WLAN API bindings
  6. Talks to the WLAN AutoConfig service (WlanSvc) through wlanapi.dll instead
  7. of running netsh. The API returns binary structures, so the results do not
  8. depend on the console code page or the language of the OS, and no child
  9. process (or console code page switch) is involved.
  10. */
  11. import (
  12. "errors"
  13. "net"
  14. "strconv"
  15. "strings"
  16. "sync"
  17. "time"
  18. "unsafe"
  19. "golang.org/x/sys/windows"
  20. )
  21. var (
  22. modwlanapi = windows.NewLazySystemDLL("wlanapi.dll")
  23. procWlanOpenHandle = modwlanapi.NewProc("WlanOpenHandle")
  24. procWlanCloseHandle = modwlanapi.NewProc("WlanCloseHandle")
  25. procWlanEnumInterfaces = modwlanapi.NewProc("WlanEnumInterfaces")
  26. procWlanQueryInterface = modwlanapi.NewProc("WlanQueryInterface")
  27. procWlanScan = modwlanapi.NewProc("WlanScan")
  28. procWlanGetNetworkBssList = modwlanapi.NewProc("WlanGetNetworkBssList")
  29. procWlanGetAvailableNetworkList = modwlanapi.NewProc("WlanGetAvailableNetworkList")
  30. procWlanFreeMemory = modwlanapi.NewProc("WlanFreeMemory")
  31. procWlanRegisterNotification = modwlanapi.NewProc("WlanRegisterNotification")
  32. )
  33. // WLAN_INTF_OPCODE values
  34. const (
  35. wlanIntfOpcodeRadioState = 4
  36. wlanIntfOpcodeCurrentConnection = 7
  37. wlanIntfOpcodeChannelNumber = 8
  38. wlanIntfOpcodeRSSI = 0x10000102
  39. )
  40. const (
  41. wlanClientVersion = 2 //Windows Vista and later
  42. dot11BSSTypeAny = 3
  43. wlanNotificationSourceNone = 0
  44. wlanNotificationSourceACM = 0x08
  45. wlanNotificationACMScanDone = 7
  46. wlanNotificationACMScanFail = 8
  47. wlanScanTimeout = 6 * time.Second
  48. errorServiceNotActive = 1062
  49. errorAccessDenied = 5
  50. errorNotReady = 21
  51. errorNdisDot11PowerStateOff = 0x80342002
  52. errorInvalidState = 5023
  53. errorDeviceNotConnected = 1167
  54. errorNdisInterfaceNotPresent = 0x8034000E
  55. )
  56. var errWlanUnavailable = errors.New("the WLAN API (wlanapi.dll) is not available on this system")
  57. // wlanError turns a WLAN API return code into a readable error
  58. func wlanError(fn string, code uintptr) error {
  59. switch code {
  60. case errorServiceNotActive:
  61. return errors.New("the WLAN AutoConfig service (WlanSvc) is not running")
  62. case errorAccessDenied:
  63. return errors.New("access to WiFi information was denied by Windows (allow desktop apps to use location in Privacy settings)")
  64. case errorNotReady, errorNdisDot11PowerStateOff, errorInvalidState:
  65. return errors.New("the wireless interface is not ready (the radio might be turned off)")
  66. case errorDeviceNotConnected, errorNdisInterfaceNotPresent:
  67. return errors.New("the wireless interface is not present")
  68. }
  69. return errors.New(fn + ": " + windows.Errno(code).Error())
  70. }
  71. type wlanClient struct {
  72. handle uintptr
  73. }
  74. func openWlanClient() (*wlanClient, error) {
  75. if err := modwlanapi.Load(); err != nil {
  76. return nil, errWlanUnavailable
  77. }
  78. var negotiated uint32
  79. var handle uintptr
  80. r, _, _ := procWlanOpenHandle.Call(wlanClientVersion, 0, uintptr(unsafe.Pointer(&negotiated)), uintptr(unsafe.Pointer(&handle)))
  81. if r != 0 {
  82. return nil, wlanError("WlanOpenHandle", r)
  83. }
  84. return &wlanClient{handle: handle}, nil
  85. }
  86. func (c *wlanClient) Close() {
  87. procWlanCloseHandle.Call(c.handle, 0)
  88. }
  89. // takeMemory copies size bytes of WLAN API allocated memory and frees it
  90. func takeMemory(p *byte, size int) []byte {
  91. if p == nil {
  92. return nil
  93. }
  94. defer procWlanFreeMemory.Call(uintptr(unsafe.Pointer(p)))
  95. if size <= 0 {
  96. return nil
  97. }
  98. return append([]byte{}, unsafe.Slice(p, size)...)
  99. }
  100. // readUint32At reads a DWORD from WLAN API allocated memory
  101. func readUint32At(p *byte, offset uintptr) uint32 {
  102. return *(*uint32)(unsafe.Add(unsafe.Pointer(p), offset))
  103. }
  104. func (c *wlanClient) interfaces() ([]wlanInterfaceInfo, error) {
  105. var p *byte
  106. r, _, _ := procWlanEnumInterfaces.Call(c.handle, 0, uintptr(unsafe.Pointer(&p)))
  107. if r != 0 {
  108. return nil, wlanError("WlanEnumInterfaces", r)
  109. }
  110. if p == nil {
  111. return []wlanInterfaceInfo{}, nil
  112. }
  113. n := int(readUint32At(p, 0))
  114. return parseWlanInterfaceList(takeMemory(p, 8+n*wlanInterfaceInfoSize))
  115. }
  116. func (c *wlanClient) query(guid *windows.GUID, opcode uint32) ([]byte, error) {
  117. var size uint32
  118. var p *byte
  119. r, _, _ := procWlanQueryInterface.Call(c.handle, uintptr(unsafe.Pointer(guid)), uintptr(opcode), 0,
  120. uintptr(unsafe.Pointer(&size)), uintptr(unsafe.Pointer(&p)), 0)
  121. if r != 0 {
  122. return nil, wlanError("WlanQueryInterface", r)
  123. }
  124. return takeMemory(p, int(size)), nil
  125. }
  126. func (c *wlanClient) bssList(guid *windows.GUID) ([]wlanBSSEntry, error) {
  127. var p *byte
  128. r, _, _ := procWlanGetNetworkBssList.Call(c.handle, uintptr(unsafe.Pointer(guid)), 0, dot11BSSTypeAny, 0, 0, uintptr(unsafe.Pointer(&p)))
  129. if r != 0 {
  130. return nil, wlanError("WlanGetNetworkBssList", r)
  131. }
  132. if p == nil {
  133. return []wlanBSSEntry{}, nil
  134. }
  135. total := int(readUint32At(p, 0))
  136. return parseWlanBSSList(takeMemory(p, total))
  137. }
  138. func (c *wlanClient) availableNetworks(guid *windows.GUID) ([]wlanAvailableNetwork, error) {
  139. var p *byte
  140. r, _, _ := procWlanGetAvailableNetworkList.Call(c.handle, uintptr(unsafe.Pointer(guid)), 0, 0, uintptr(unsafe.Pointer(&p)))
  141. if r != 0 {
  142. return nil, wlanError("WlanGetAvailableNetworkList", r)
  143. }
  144. if p == nil {
  145. return []wlanAvailableNetwork{}, nil
  146. }
  147. n := int(readUint32At(p, 0))
  148. return parseWlanAvailableNetworkList(takeMemory(p, 8+n*wlanAvailableNetworkSize))
  149. }
  150. func (c *wlanClient) connection(guid *windows.GUID) (*wlanConnectionAttributes, error) {
  151. b, err := c.query(guid, wlanIntfOpcodeCurrentConnection)
  152. if err != nil {
  153. return nil, err
  154. }
  155. return parseWlanConnectionAttributes(b)
  156. }
  157. func (c *wlanClient) radioState(guid *windows.GUID) ([]wlanPhyRadioState, error) {
  158. b, err := c.query(guid, wlanIntfOpcodeRadioState)
  159. if err != nil {
  160. return nil, err
  161. }
  162. return parseWlanRadioState(b)
  163. }
  164. func (c *wlanClient) uint32Value(guid *windows.GUID, opcode uint32) (uint32, error) {
  165. b, err := c.query(guid, opcode)
  166. if err != nil {
  167. return 0, err
  168. }
  169. if len(b) < 4 {
  170. return 0, errWlanTruncated
  171. }
  172. return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24, nil
  173. }
  174. /*
  175. Scanning
  176. WlanScan only starts a scan. Completion is reported through a
  177. notification callback; the callback is created once for the process
  178. (callbacks are a limited resource) and wakes the goroutines waiting for
  179. that interface.
  180. */
  181. type wlanNotificationData struct {
  182. Source uint32
  183. Code uint32
  184. InterfaceGUID windows.GUID
  185. DataSize uint32
  186. Data uintptr
  187. }
  188. var (
  189. wlanNotifyOnce sync.Once
  190. wlanNotifyCallback uintptr
  191. wlanScanMu sync.Mutex
  192. wlanScanWaiters = map[windows.GUID]map[chan struct{}]bool{}
  193. )
  194. func wlanNotificationHandler(data *wlanNotificationData, context uintptr) uintptr {
  195. if data == nil || data.Source != wlanNotificationSourceACM {
  196. return 0
  197. }
  198. if data.Code != wlanNotificationACMScanDone && data.Code != wlanNotificationACMScanFail {
  199. return 0
  200. }
  201. wlanScanMu.Lock()
  202. for ch := range wlanScanWaiters[data.InterfaceGUID] {
  203. select {
  204. case ch <- struct{}{}:
  205. default:
  206. }
  207. }
  208. wlanScanMu.Unlock()
  209. return 0
  210. }
  211. // scan triggers a scan on the interface and waits until it completes (or
  212. // times out). The results are then read with bssList.
  213. func (c *wlanClient) scan(guid windows.GUID) error {
  214. wlanNotifyOnce.Do(func() {
  215. wlanNotifyCallback = windows.NewCallback(wlanNotificationHandler)
  216. })
  217. done := make(chan struct{}, 1)
  218. wlanScanMu.Lock()
  219. if wlanScanWaiters[guid] == nil {
  220. wlanScanWaiters[guid] = map[chan struct{}]bool{}
  221. }
  222. wlanScanWaiters[guid][done] = true
  223. wlanScanMu.Unlock()
  224. defer func() {
  225. wlanScanMu.Lock()
  226. delete(wlanScanWaiters[guid], done)
  227. if len(wlanScanWaiters[guid]) == 0 {
  228. delete(wlanScanWaiters, guid)
  229. }
  230. wlanScanMu.Unlock()
  231. }()
  232. registered := false
  233. r, _, _ := procWlanRegisterNotification.Call(c.handle, wlanNotificationSourceACM, 1, wlanNotifyCallback, 0, 0, 0)
  234. if r == 0 {
  235. registered = true
  236. defer procWlanRegisterNotification.Call(c.handle, wlanNotificationSourceNone, 1, 0, 0, 0, 0)
  237. }
  238. r, _, _ = procWlanScan.Call(c.handle, uintptr(unsafe.Pointer(&guid)), 0, 0, 0)
  239. if r != 0 {
  240. return wlanError("WlanScan", r)
  241. }
  242. if !registered {
  243. //No notification: give the driver the 4 seconds it is allowed
  244. time.Sleep(4 * time.Second)
  245. return nil
  246. }
  247. select {
  248. case <-done:
  249. case <-time.After(wlanScanTimeout):
  250. }
  251. return nil
  252. }
  253. /*
  254. Adapter (IP layer) information
  255. */
  256. type adapterInfo struct {
  257. FriendlyName string
  258. Description string
  259. MAC string
  260. MTU int
  261. IPv4 []string
  262. IPv6 []string
  263. Gateways []string
  264. DNS []string
  265. }
  266. // adaptersByGUID returns the IP layer view of every adapter, keyed by the
  267. // upper case "{GUID}" adapter name the WLAN API interface GUIDs map to
  268. func adaptersByGUID() map[string]adapterInfo {
  269. result := map[string]adapterInfo{}
  270. size := uint32(16 * 1024)
  271. var buf []byte
  272. for i := 0; i < 4; i++ {
  273. buf = make([]byte, size)
  274. err := windows.GetAdaptersAddresses(windows.AF_UNSPEC,
  275. windows.GAA_FLAG_INCLUDE_GATEWAYS|windows.GAA_FLAG_SKIP_ANYCAST|windows.GAA_FLAG_SKIP_MULTICAST,
  276. 0, (*windows.IpAdapterAddresses)(unsafe.Pointer(&buf[0])), &size)
  277. if err == nil {
  278. break
  279. }
  280. if err != windows.ERROR_BUFFER_OVERFLOW {
  281. return result
  282. }
  283. buf = nil
  284. }
  285. if buf == nil {
  286. return result
  287. }
  288. for a := (*windows.IpAdapterAddresses)(unsafe.Pointer(&buf[0])); a != nil; a = a.Next {
  289. info := adapterInfo{
  290. FriendlyName: windows.UTF16PtrToString(a.FriendlyName),
  291. Description: windows.UTF16PtrToString(a.Description),
  292. MTU: int(a.Mtu),
  293. IPv4: []string{},
  294. IPv6: []string{},
  295. Gateways: []string{},
  296. DNS: []string{},
  297. }
  298. if a.PhysicalAddressLength > 0 && a.PhysicalAddressLength <= uint32(len(a.PhysicalAddress)) {
  299. info.MAC = net.HardwareAddr(a.PhysicalAddress[:a.PhysicalAddressLength]).String()
  300. }
  301. for u := a.FirstUnicastAddress; u != nil; u = u.Next {
  302. ip := u.Address.IP()
  303. if ip == nil {
  304. continue
  305. }
  306. cidr := ip.String() + "/" + strconv.Itoa(int(u.OnLinkPrefixLength))
  307. if ip.To4() != nil {
  308. info.IPv4 = append(info.IPv4, cidr)
  309. } else {
  310. info.IPv6 = append(info.IPv6, cidr)
  311. }
  312. }
  313. for g := a.FirstGatewayAddress; g != nil; g = g.Next {
  314. if ip := g.Address.IP(); ip != nil {
  315. info.Gateways = append(info.Gateways, ip.String())
  316. }
  317. }
  318. for d := a.FirstDnsServerAddress; d != nil; d = d.Next {
  319. if ip := d.Address.IP(); ip != nil {
  320. info.DNS = append(info.DNS, ip.String())
  321. }
  322. }
  323. name := strings.ToUpper(windows.BytePtrToString(a.AdapterName))
  324. result[name] = info
  325. }
  326. return result
  327. }
  328. // guidFromBytes converts the in-memory GUID bytes into a windows.GUID
  329. func guidFromBytes(b [16]byte) windows.GUID {
  330. g := windows.GUID{
  331. Data1: uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24,
  332. Data2: uint16(b[4]) | uint16(b[5])<<8,
  333. Data3: uint16(b[6]) | uint16(b[7])<<8,
  334. }
  335. copy(g.Data4[:], b[8:16])
  336. return g
  337. }