wifi_windows.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. //go:build windows
  2. // +build windows
  3. package wifi
  4. /*
  5. WiFi connection module for Windows
  6. author: tobychui
  7. Reads interface state and scan results through the native WLAN API
  8. (wlanapi_windows.go). Earlier versions parsed the output of
  9. "chcp 65001 && netsh wlan ...", which depended on the OS language and
  10. switched the code page of the console ArozOS was running in.
  11. */
  12. import (
  13. "bytes"
  14. "errors"
  15. "sort"
  16. "strings"
  17. )
  18. // Toggle WiFi On Off. Only allow on sudo mode
  19. func (w *WiFiManager) SetInterfacePower(wlanInterface string, on bool) error {
  20. return errors.New("Windows WiFi function is currently readonly")
  21. }
  22. // CanControlInterfacePower reports whether SetInterfacePower is supported
  23. func (w *WiFiManager) CanControlInterfacePower() bool {
  24. return false
  25. }
  26. // CanConnect reports whether ConnectWiFi and RemoveWifi are supported
  27. func (w *WiFiManager) CanConnect() bool {
  28. return false
  29. }
  30. func (w *WiFiManager) GetInterfacePowerStatuts(wlanInterface string) (bool, error) {
  31. client, err := openWlanClient()
  32. if err != nil {
  33. return false, err
  34. }
  35. defer client.Close()
  36. iface, _, err := findWlanInterface(client, wlanInterface, false)
  37. if err != nil {
  38. return false, err
  39. }
  40. guid := guidFromBytes(iface.GUID)
  41. states, err := client.radioState(&guid)
  42. if err != nil {
  43. return false, err
  44. }
  45. software, hardware := radioSummary(states)
  46. return software == "on" && hardware != "off", nil
  47. }
  48. // radioSummary folds the per-PHY radio states into one software and one
  49. // hardware state: "on" when any PHY is on
  50. func radioSummary(states []wlanPhyRadioState) (string, string) {
  51. software, hardware := "unknown", "unknown"
  52. for _, s := range states {
  53. if sw := dot11RadioStateName(s.Software); sw == "on" || software == "unknown" {
  54. software = sw
  55. }
  56. if hw := dot11RadioStateName(s.Hardware); hw == "on" || hardware == "unknown" {
  57. hardware = hw
  58. }
  59. }
  60. return software, hardware
  61. }
  62. // findWlanInterface picks the interface whose friendly name, description or
  63. // GUID matches name. When nothing matches (or name is empty) the first
  64. // interface is returned if fallback is set.
  65. func findWlanInterface(client *wlanClient, name string, fallback bool) (wlanInterfaceInfo, adapterInfo, error) {
  66. ifaces, err := client.interfaces()
  67. if err != nil {
  68. return wlanInterfaceInfo{}, adapterInfo{}, err
  69. }
  70. if len(ifaces) == 0 {
  71. return wlanInterfaceInfo{}, adapterInfo{}, errors.New("Wireless Interface Not Found")
  72. }
  73. adapters := adaptersByGUID()
  74. name = strings.TrimSpace(name)
  75. for _, iface := range ifaces {
  76. guid := guidString(iface.GUID)
  77. adapter := adapters[guid]
  78. if name != "" && (strings.EqualFold(adapter.FriendlyName, name) || strings.EqualFold(iface.Description, name) || strings.EqualFold(guid, name)) {
  79. return iface, adapter, nil
  80. }
  81. }
  82. if !fallback {
  83. return wlanInterfaceInfo{}, adapterInfo{}, errors.New("wlan Interface not exists")
  84. }
  85. return ifaces[0], adapters[guidString(ifaces[0].GUID)], nil
  86. }
  87. // interfaceDisplayName is the name the rest of ArozOS uses for an interface
  88. func interfaceDisplayName(iface wlanInterfaceInfo, adapter adapterInfo) string {
  89. if adapter.FriendlyName != "" {
  90. return adapter.FriendlyName
  91. }
  92. return iface.Description
  93. }
  94. func (w *WiFiManager) ScanNearbyWiFi(interfaceName string) ([]WiFiInfo, error) {
  95. client, err := openWlanClient()
  96. if err != nil {
  97. return []WiFiInfo{}, err
  98. }
  99. defer client.Close()
  100. iface, adapter, err := findWlanInterface(client, interfaceName, true)
  101. if err != nil {
  102. return []WiFiInfo{}, err
  103. }
  104. guid := guidFromBytes(iface.GUID)
  105. displayName := interfaceDisplayName(iface, adapter)
  106. //Ask the driver for fresh results. A failed scan (for example while the
  107. //radio is off) still leaves the cached list to read.
  108. scanErr := client.scan(guid)
  109. entries, err := client.bssList(&guid)
  110. if err != nil {
  111. if scanErr != nil {
  112. return []WiFiInfo{}, scanErr
  113. }
  114. return []WiFiInfo{}, err
  115. }
  116. //Saved profiles and the fallback security per SSID
  117. networks, _ := client.availableNetworks(&guid)
  118. networkBySSID := map[string]wlanAvailableNetwork{}
  119. for _, n := range networks {
  120. key := string(n.SSID)
  121. if old, ok := networkBySSID[key]; !ok || n.Flags&wlanAvailableNetworkHasProfile != 0 && old.Flags&wlanAvailableNetworkHasProfile == 0 {
  122. networkBySSID[key] = n
  123. }
  124. }
  125. var connectedBSSID []byte
  126. if iface.State == 1 {
  127. if conn, err := client.connection(&guid); err == nil {
  128. connectedBSSID = conn.BSSID[:]
  129. }
  130. }
  131. results := []WiFiInfo{}
  132. for _, entry := range entries {
  133. info := bssInfoFromEntry(entry)
  134. info.Interface = displayName
  135. if n, ok := networkBySSID[string(entry.SSID)]; ok {
  136. info.ConnectedBefore = n.Flags&wlanAvailableNetworkHasProfile != 0
  137. if info.Security == "Open" && n.SecurityEnabled {
  138. info.Security = dot11AuthName(n.AuthAlgorithm)
  139. info.Cipher = dot11CipherName(n.CipherAlgorithm)
  140. info.EncryptionKey = true
  141. }
  142. }
  143. info.Connected = connectedBSSID != nil && bytes.Equal(connectedBSSID, entry.BSSID[:])
  144. results = append(results, info)
  145. }
  146. sort.SliceStable(results, func(i, j int) bool {
  147. return results[i].SignalDBm > results[j].SignalDBm
  148. })
  149. return results, nil
  150. }
  151. func (w *WiFiManager) GetWirelessInterfaces() ([]string, error) {
  152. client, err := openWlanClient()
  153. if err != nil {
  154. return []string{}, err
  155. }
  156. defer client.Close()
  157. ifaces, err := client.interfaces()
  158. if err != nil {
  159. return []string{}, err
  160. }
  161. adapters := adaptersByGUID()
  162. names := []string{}
  163. for _, iface := range ifaces {
  164. names = append(names, interfaceDisplayName(iface, adapters[guidString(iface.GUID)]))
  165. }
  166. return names, nil
  167. }
  168. // GetInterfaceStatus returns the live state of every wireless interface
  169. func (w *WiFiManager) GetInterfaceStatus() ([]WiFiInterfaceStatus, error) {
  170. client, err := openWlanClient()
  171. if err != nil {
  172. return []WiFiInterfaceStatus{}, err
  173. }
  174. defer client.Close()
  175. ifaces, err := client.interfaces()
  176. if err != nil {
  177. return []WiFiInterfaceStatus{}, err
  178. }
  179. adapters := adaptersByGUID()
  180. results := []WiFiInterfaceStatus{}
  181. for _, iface := range ifaces {
  182. results = append(results, interfaceStatus(client, iface, adapters[guidString(iface.GUID)]))
  183. }
  184. return results, nil
  185. }
  186. func interfaceStatus(client *wlanClient, iface wlanInterfaceInfo, adapter adapterInfo) WiFiInterfaceStatus {
  187. guid := guidFromBytes(iface.GUID)
  188. status := WiFiInterfaceStatus{
  189. Name: interfaceDisplayName(iface, adapter),
  190. Description: iface.Description,
  191. GUID: guidString(iface.GUID),
  192. MAC: adapter.MAC,
  193. State: wlanInterfaceStateName(iface.State),
  194. Connected: iface.State == 1,
  195. SoftwareRadio: "unknown",
  196. HardwareRadio: "unknown",
  197. SignalQuality: -1,
  198. IPv4: nonNil(adapter.IPv4),
  199. IPv6: nonNil(adapter.IPv6),
  200. Gateways: nonNil(adapter.Gateways),
  201. DNS: nonNil(adapter.DNS),
  202. MTU: adapter.MTU,
  203. }
  204. if states, err := client.radioState(&guid); err == nil {
  205. status.SoftwareRadio, status.HardwareRadio = radioSummary(states)
  206. }
  207. if !status.Connected {
  208. return status
  209. }
  210. conn, err := client.connection(&guid)
  211. if err != nil {
  212. return status
  213. }
  214. status.SSID, _ = ssidString(conn.SSID)
  215. status.BSSID = formatMAC(conn.BSSID[:])
  216. status.ProfileName = conn.ProfileName
  217. status.ConnectionMode = wlanConnectionModeName(conn.Mode)
  218. status.BSSType = dot11BSSTypeName(conn.BSSType)
  219. status.PHYType = dot11PhyName(conn.PhyType)
  220. status.SignalQuality = int(conn.SignalQuality)
  221. status.RxRateMbps = float64(conn.RxRateKbps) / 1000
  222. status.TxRateMbps = float64(conn.TxRateKbps) / 1000
  223. status.Security = dot11AuthName(conn.AuthAlgorithm)
  224. if !conn.SecurityEnabled {
  225. status.Security = "Open"
  226. }
  227. status.Cipher = dot11CipherName(conn.CipherAlgorithm)
  228. status.OneX = conn.OneXEnabled
  229. if ch, err := client.uint32Value(&guid, wlanIntfOpcodeChannelNumber); err == nil {
  230. status.Channel = int(ch)
  231. }
  232. if rssi, err := client.uint32Value(&guid, wlanIntfOpcodeRSSI); err == nil && int32(rssi) < 0 {
  233. status.RSSI = int(int32(rssi))
  234. } else {
  235. status.RSSI = rssiFromQuality(status.SignalQuality)
  236. }
  237. //The cached scan results describe the connected AP in detail. Reading
  238. //them does not start a new scan.
  239. if entries, err := client.bssList(&guid); err == nil {
  240. for _, entry := range entries {
  241. if !bytes.Equal(entry.BSSID[:], conn.BSSID[:]) {
  242. continue
  243. }
  244. ap := bssInfoFromEntry(entry)
  245. ap.Interface = status.Name
  246. ap.Connected = true
  247. ap.ConnectedBefore = true
  248. status.AP = &ap
  249. status.FrequencyMHz = ap.FrequencyMHz
  250. status.Band = ap.Band
  251. status.ChannelWidth = ap.ChannelWidth
  252. if ap.Channel > 0 {
  253. status.Channel = ap.Channel
  254. }
  255. if ap.PHYType != "" && status.PHYType == "" {
  256. status.PHYType = ap.PHYType
  257. }
  258. break
  259. }
  260. }
  261. if status.FrequencyMHz == 0 {
  262. status.FrequencyMHz = frequencyOfChannel(status.Channel, false)
  263. status.Band = bandOfFrequency(status.FrequencyMHz)
  264. }
  265. status.Generation = generationOfPHY(status.PHYType, status.Band)
  266. return status
  267. }
  268. func (w *WiFiManager) ConnectWiFi(ssid string, password string, connType string, identity string) (*WiFiConnectionResult, error) {
  269. return &WiFiConnectionResult{}, errors.New("Windows WiFi function is currently readonly")
  270. }
  271. // Get connected wifi ssid, interface name and error if any
  272. func (w *WiFiManager) GetConnectedWiFi() (string, string, error) {
  273. statuses, err := w.GetInterfaceStatus()
  274. if err != nil {
  275. if err == errWlanUnavailable {
  276. return "", "", nil
  277. }
  278. return "", "", err
  279. }
  280. if len(statuses) == 0 {
  281. return "", "", nil
  282. }
  283. for _, s := range statuses {
  284. if s.Connected {
  285. return s.SSID, s.Name, nil
  286. }
  287. }
  288. return "", statuses[0].Name, nil
  289. }
  290. func (w *WiFiManager) RemoveWifi(ssid string) error {
  291. return errors.New("Windows WiFi function is currently readonly")
  292. }
  293. func nonNil(list []string) []string {
  294. if list == nil {
  295. return []string{}
  296. }
  297. return list
  298. }