wifi_linux.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  1. //go:build linux
  2. // +build linux
  3. package wifi
  4. import (
  5. "errors"
  6. "fmt"
  7. "net"
  8. "os"
  9. "os/exec"
  10. "path/filepath"
  11. "sort"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "imuslab.com/arozos/mod/info/logger"
  16. "imuslab.com/arozos/mod/utils"
  17. )
  18. // Toggle WiFi On Off. Only allow on sudo mode
  19. func (w *WiFiManager) SetInterfacePower(wlanInterface string, on bool) error {
  20. status := "up"
  21. if on == false {
  22. status = "down"
  23. }
  24. cmd := exec.Command("ifconfig", wlanInterface, status)
  25. out, err := cmd.CombinedOutput()
  26. if err != nil {
  27. logger.PrintAndLog("Wifi", fmt.Sprint("*WiFi* WiFi toggle failed: ", string(out)), nil)
  28. return err
  29. }
  30. //OK
  31. return nil
  32. }
  33. func (w *WiFiManager) GetInterfacePowerStatuts(wlanInterface string) (bool, error) {
  34. //Check if interface is in list
  35. interfaceList, err := w.GetWirelessInterfaces()
  36. if err != nil {
  37. return false, err
  38. }
  39. interfaceExists := false
  40. for _, localInterface := range interfaceList {
  41. if localInterface == wlanInterface {
  42. interfaceExists = true
  43. }
  44. }
  45. if !interfaceExists {
  46. return false, errors.New("wlan Interface not exists")
  47. }
  48. //Check if the interface appears in ifconfig. If yes, this interface is online
  49. cmd := exec.Command("bash", "-c", "ifconfig | grep "+wlanInterface)
  50. out, err := cmd.CombinedOutput()
  51. if err != nil {
  52. return false, errors.New(string(out))
  53. }
  54. if strings.TrimSpace(string(out)) != "" {
  55. //Interface exists in ifconfig. Report it as powered on
  56. return true, nil
  57. } else {
  58. return false, nil
  59. }
  60. }
  61. // Scan Nearby WiFi
  62. func (w *WiFiManager) ScanNearbyWiFi(interfaceName string) ([]WiFiInfo, error) {
  63. rcmd := `iwlist ` + interfaceName + ` scan`
  64. if w.sudo_mode {
  65. rcmd = "sudo " + rcmd
  66. }
  67. cmd := exec.Command("bash", "-c", rcmd)
  68. out, err := cmd.CombinedOutput()
  69. if err != nil {
  70. //Scan failed, the following code is used to handle edge case on some SBC that only nmcli works but not iwlist
  71. /*
  72. If the interface is not supported, something like this will show up:
  73. wlan0 Interface doesn't support scanning.
  74. */
  75. if strings.Contains(string(out), "Interface doesn't support scanning") {
  76. //Try nmcli instead if exists
  77. if pkg_exists("nmcli") {
  78. logger.PrintAndLog("Wifi", "*WiFi* Running WiFi scan in nmcli compatibility mode", nil)
  79. cmd := exec.Command("bash", "-c", "nmcli d wifi list")
  80. out, err := cmd.CombinedOutput()
  81. if err != nil {
  82. return []WiFiInfo{}, err
  83. }
  84. //Parse the nmcli output
  85. lines := strings.Split(string(out), "\n")
  86. if len(lines) > 1 {
  87. //Remove the header
  88. lines = lines[1:]
  89. }
  90. results := []WiFiInfo{}
  91. //Prase the wifi information
  92. for _, line := range lines {
  93. //Replace all double space as split sign
  94. line = strings.TrimSpace(line)
  95. for strings.Contains(line, " ") {
  96. line = strings.ReplaceAll(line, " ", "$")
  97. }
  98. for strings.Contains(line, "$$") {
  99. line = strings.ReplaceAll(line, "$$", "$")
  100. }
  101. //Process the wifi info chunk
  102. wifiInfoSlice := strings.Split(line, "$")
  103. thisWifiInfo := new(WiFiInfo)
  104. if len(wifiInfoSlice) == 7 {
  105. //This is a valid entry
  106. thisWifiInfo.ESSID = strings.TrimSpace(wifiInfoSlice[0])
  107. thisWifiInfo.Quality = wifiInfoSlice[4] + "/100"
  108. thisWifiInfo.Frequency = wifiInfoSlice[3]
  109. channel, _ := strconv.Atoi(wifiInfoSlice[2])
  110. thisWifiInfo.Channel = channel
  111. thisWifiInfo.SignalLevel = w.getSignalLevelEstimation(wifiInfoSlice[5])
  112. //Check connect before
  113. if w.database.KeyExists("wifi", thisWifiInfo.ESSID) {
  114. thisWifiInfo.ConnectedBefore = true
  115. } else {
  116. thisWifiInfo.ConnectedBefore = false
  117. }
  118. } else if len(wifiInfoSlice) == 8 {
  119. //Entry with inuse * at front
  120. thisWifiInfo.ESSID = strings.TrimSpace(wifiInfoSlice[1])
  121. thisWifiInfo.Quality = wifiInfoSlice[5] + "/100"
  122. thisWifiInfo.Frequency = wifiInfoSlice[4]
  123. channel, _ := strconv.Atoi(wifiInfoSlice[2])
  124. thisWifiInfo.Channel = channel
  125. thisWifiInfo.SignalLevel = w.getSignalLevelEstimation(wifiInfoSlice[6])
  126. thisWifiInfo.ConnectedBefore = true //It is connected
  127. } else {
  128. //Line not valid. Skip this line
  129. continue
  130. }
  131. thisWifiInfo.Interface = interfaceName
  132. normalizeWiFiInfo(thisWifiInfo)
  133. results = append(results, *thisWifiInfo)
  134. }
  135. markConnectedBSS(results, interfaceName)
  136. return results, nil
  137. } else {
  138. logger.PrintAndLog("Wifi", fmt.Sprint("*WiFi* Scan Failed: ", err.Error()), nil)
  139. return []WiFiInfo{}, errors.New("Interface doesn't support scanning")
  140. }
  141. }
  142. return []WiFiInfo{}, err
  143. }
  144. //parse the output of the WiFi Scan
  145. results := parseIwlistScan(string(out))
  146. useNmcliStore := pkg_exists("nmcli")
  147. for i := range results {
  148. results[i].Interface = interfaceName
  149. if useNmcliStore {
  150. //Make use of nmcli storage
  151. results[i].ConnectedBefore = w.database.KeyExists("wifi", results[i].ESSID)
  152. } else {
  153. //Direct access to wpa_supplicant
  154. results[i].ConnectedBefore = fileExists("./system/network/wifi/ap/" + results[i].ESSID + ".config")
  155. }
  156. }
  157. markConnectedBSS(results, interfaceName)
  158. return results, nil
  159. }
  160. // markConnectedBSS flags the scan result the interface is associated with
  161. func markConnectedBSS(results []WiFiInfo, interfaceName string) {
  162. link, err := readIwLink(interfaceName)
  163. if err != nil || !link.Connected {
  164. return
  165. }
  166. for i := range results {
  167. if strings.EqualFold(results[i].Address, link.BSSID) {
  168. results[i].Connected = true
  169. }
  170. }
  171. }
  172. // readIwLink runs "iw dev <interface> link"
  173. func readIwLink(interfaceName string) (iwLinkInfo, error) {
  174. if interfaceName == "" || strings.ContainsAny(interfaceName, " /\\") {
  175. return iwLinkInfo{}, errors.New("invalid interface name")
  176. }
  177. out, err := exec.Command("iw", "dev", interfaceName, "link").CombinedOutput()
  178. if err != nil {
  179. return iwLinkInfo{}, errors.New(string(out))
  180. }
  181. return parseIwLink(string(out)), nil
  182. }
  183. // Hack the signal level out of the nmcli bars
  184. func (w *WiFiManager) getSignalLevelEstimation(bar string) string {
  185. bar = strings.TrimSpace(bar)
  186. if bar == "▂▄▆█" {
  187. return "-45 dBm[Estimated]"
  188. } else if bar == "▂▄▆_" {
  189. return "-55 dBm[Estimated]"
  190. } else if bar == "▂▄__" {
  191. return "-75 dBm[Estimated]"
  192. } else if bar == "▂___" {
  193. return "-85 dBm[Estimated]"
  194. } else {
  195. return "-95 dBm[Estimated]"
  196. }
  197. }
  198. // Get all the network interfaces
  199. func (w *WiFiManager) GetWirelessInterfaces() ([]string, error) {
  200. rcmd := `iw dev | awk '$1=="Interface"{print $2}'`
  201. cmd := exec.Command("bash", "-c", rcmd)
  202. out, err := cmd.CombinedOutput()
  203. if err != nil {
  204. return []string{}, errors.New(string(out))
  205. }
  206. interfaces := strings.Split(strings.TrimSpace(string(out)), "\n")
  207. //sort.Strings(interfaces)
  208. sort.Sort(sort.StringSlice(interfaces))
  209. return interfaces, nil
  210. }
  211. func (w *WiFiManager) ConnectWiFi(ssid string, password string, connType string, identity string) (*WiFiConnectionResult, error) {
  212. //Build the network config file
  213. //Updates 21-10-2020, use nmcli if exists
  214. if pkg_exists("nmcli") {
  215. oldSSID, _, _ := w.GetConnectedWiFi()
  216. if ssid != "" {
  217. //There is an existing connection to another wifi AP. Disconnect it
  218. cmd := exec.Command("nmcli", "con", "down", oldSSID)
  219. out, err := cmd.CombinedOutput()
  220. if err != nil {
  221. logger.PrintAndLog("Wifi", "*WiFi* Connecting previous SSID failed: "+string(out), nil)
  222. logger.PrintAndLog("Wifi", "*WiFi* Trying to connect new AP anyway", nil)
  223. }
  224. }
  225. if connType == "switch" {
  226. //Load ssid and password from database
  227. w.database.Write("wifi", ssid, &password)
  228. }
  229. //Try to connect the new AP
  230. cmd := exec.Command("nmcli", "device", "wifi", "connect", ssid, "password", password)
  231. out, err := cmd.CombinedOutput()
  232. if err != nil {
  233. logger.PrintAndLog("Wifi", "*WiFi* Connecting to SSID "+ssid+" failed: "+string(out), nil)
  234. return &WiFiConnectionResult{Success: false}, errors.New(string(out))
  235. }
  236. if connType != "switch" {
  237. //Save the ssid and password to database
  238. w.database.Write("wifi", ssid, password)
  239. }
  240. logger.PrintAndLog("Wifi", string(out), nil)
  241. //Check and return the current connection ssid
  242. //Wait until the WiFi is conencted
  243. rescanCount := 0
  244. connectedSSID, _, _ := w.GetConnectedWiFi()
  245. //Wait for 30 seconds
  246. for rescanCount < 10 && connectedSSID == "" {
  247. connectedSSID, _, _ = w.GetConnectedWiFi()
  248. logger.PrintAndLog("Wifi", fmt.Sprint(connectedSSID), nil)
  249. rescanCount = rescanCount + 1
  250. logger.PrintAndLog("Wifi", "*WiFi* Waiting WiFi Connection (Retry "+strconv.Itoa(rescanCount)+"/10)", nil)
  251. time.Sleep(3 * time.Second)
  252. }
  253. return &WiFiConnectionResult{
  254. ConnectedSSID: connectedSSID,
  255. Success: true,
  256. }, nil
  257. }
  258. //DO NOT TOUCH THE INDENTATION!! THEY MUST BE KEEP LIKE THIS
  259. writeToConfig := true
  260. networkConfigFile := ""
  261. if connType == "" {
  262. //Home use network / WPA2
  263. if password == "" {
  264. //No need password
  265. networkConfigFile = `network={
  266. ssid="` + ssid + `"
  267. key_mgmt=NONE
  268. priority={{priority}}
  269. }`
  270. } else {
  271. networkConfigFile = `network={
  272. ssid="` + ssid + `"
  273. psk="` + password + `"
  274. priority={{priority}}
  275. }`
  276. }
  277. } else if connType == "WPA-EAP" {
  278. if identity == "" {
  279. return &WiFiConnectionResult{Success: false}, errors.New("Identify not defined")
  280. }
  281. networkConfigFile = `network={
  282. ssid="` + ssid + `"
  283. key_mgmt=WPA-EAP
  284. identity="` + identity + `"
  285. password="` + password + `"
  286. }`
  287. } else if connType == "switch" {
  288. //Special case, for handling WiFi Switching without retyping the password
  289. writeToConfig = false
  290. } else {
  291. logger.PrintAndLog("Wifi", "*WiFi* Unsupported connection type", nil)
  292. return &WiFiConnectionResult{Success: false}, errors.New("Unsupported Connection Type")
  293. }
  294. //Generate new wpa_supplicant_conf from file
  295. if !fileExists("./system/network/wifi/ap") {
  296. os.MkdirAll("./system/network/wifi/ap", 0755)
  297. }
  298. if writeToConfig == true {
  299. logger.PrintAndLog("Wifi", "*WiFi* WiFi Config Generated. Writing to file...", nil)
  300. //Write config file to disk
  301. err := os.WriteFile("./system/network/wifi/ap/"+ssid+".config", []byte(networkConfigFile), 0755)
  302. if err != nil {
  303. logger.PrintAndLog("Wifi", err.Error(), nil)
  304. return &WiFiConnectionResult{Success: false}, err
  305. }
  306. } else {
  307. logger.PrintAndLog("Wifi", "*WiFi* Switching WiFi AP...", nil)
  308. }
  309. //Start creating the new wpa_supplicant file
  310. //Get header
  311. configHeader, err := os.ReadFile("./system/network/wifi/wpa_supplicant.conf_template.config")
  312. if err != nil {
  313. //Template header not found. Use default one from Raspberry Pi
  314. logger.PrintAndLog("Wifi", "*WiFi* Warning! wpa_supplicant template file not found. Using default template.", nil)
  315. configHeader = []byte(`ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
  316. update_config=1
  317. {{networks}}
  318. `)
  319. }
  320. //Build network informations
  321. networksConfigs, err := filepath.Glob("./system/network/wifi/ap/*.config")
  322. if err != nil {
  323. logger.PrintAndLog("Wifi", err.Error(), nil)
  324. return &WiFiConnectionResult{Success: false}, err
  325. }
  326. //Read each of the network and append it into a string slice
  327. networks := []string{}
  328. for _, configFile := range networksConfigs {
  329. thisNetworkConfig, err := os.ReadFile(configFile)
  330. if err != nil {
  331. logger.PrintAndLog("Wifi", "*WiFi* Failed to read Network Config File: "+configFile, nil)
  332. continue
  333. }
  334. if strings.TrimSuffix(filepath.Base(configFile), filepath.Ext(configFile)) == ssid {
  335. //The new SSID. Set this to higher priority
  336. networks = append(networks, utils.TemplateApply(string(thisNetworkConfig), map[string]string{
  337. "priority": strconv.Itoa(1),
  338. }))
  339. } else {
  340. //Old SSID. Use default priority
  341. networks = append(networks, utils.TemplateApply(string(thisNetworkConfig), map[string]string{
  342. "priority": strconv.Itoa(0),
  343. }))
  344. }
  345. }
  346. //Subsitute the results into the template
  347. networksConfigString := strings.Join(networks, "\n")
  348. newconfig := utils.TemplateApply(string(configHeader), map[string]string{
  349. "networks": networksConfigString,
  350. })
  351. //Try to write the new config to wpa_supplicant
  352. err = os.WriteFile(w.wpa_supplicant_path, []byte(newconfig), 0777)
  353. if err != nil {
  354. logger.PrintAndLog("Wifi", "*WiFi* Failed to update wpa_supplicant config, are you sure you have access permission to that file?", nil)
  355. return &WiFiConnectionResult{Success: false}, err
  356. }
  357. logger.PrintAndLog("Wifi", "*WiFi* WiFi Config Updated. Restarting Wireless Interfaces...", nil)
  358. //Restart network services
  359. cmd := exec.Command("wpa_cli", "-i", w.wan_interface_name, "reconfigure")
  360. out, err := cmd.CombinedOutput()
  361. if err != nil {
  362. //Maybe the user forgot to set the flag. Try auto detect.
  363. autoDetectedWIface, err := w.GetWirelessInterfaces()
  364. if err != nil || len(autoDetectedWIface) == 0 {
  365. logger.PrintAndLog("Wifi", "failed to restart network: "+string(out), nil)
  366. return &WiFiConnectionResult{Success: false}, err
  367. }
  368. firstWlanInterface := autoDetectedWIface[0]
  369. cmd := exec.Command("wpa_cli", "-i", firstWlanInterface, "reconfigure")
  370. out, err := cmd.CombinedOutput()
  371. if err != nil {
  372. //Really failed.
  373. logger.PrintAndLog("Wifi", "failed to restart network: "+string(out), nil)
  374. return &WiFiConnectionResult{Success: false}, err
  375. }
  376. }
  377. logger.PrintAndLog("Wifi", "*WiFi* Trying to connect new AP", nil)
  378. //Wait until the WiFi is conencted
  379. rescanCount := 0
  380. connectedSSID, _, _ := w.GetConnectedWiFi()
  381. //Wait for 30 seconds
  382. for rescanCount < 10 && connectedSSID == "" {
  383. connectedSSID, _, _ = w.GetConnectedWiFi()
  384. logger.PrintAndLog("Wifi", fmt.Sprint(connectedSSID), nil)
  385. rescanCount = rescanCount + 1
  386. logger.PrintAndLog("Wifi", "*WiFi* Waiting WiFi Connection (Retry "+strconv.Itoa(rescanCount)+"/10)", nil)
  387. time.Sleep(3 * time.Second)
  388. }
  389. result := new(WiFiConnectionResult)
  390. if (rescanCount) >= 10 {
  391. result.Success = false
  392. } else {
  393. result.ConnectedSSID = connectedSSID
  394. result.Success = true
  395. }
  396. return result, nil
  397. }
  398. // Get the current connected wifi, return ESSID, wifi interface name and error if any
  399. // Return ESSID, interface and error
  400. func (w *WiFiManager) GetConnectedWiFi() (string, string, error) {
  401. cmd := exec.Command("iwgetid")
  402. out, err := cmd.CombinedOutput()
  403. if err != nil {
  404. //Check nmcli working or not
  405. if pkg_exists("nmcli") {
  406. //Try nmcli method instead
  407. cmd := exec.Command("nmcli", "-t", "-f", "NAME,DEVICE", "connection", "show", "--active")
  408. out, err := cmd.CombinedOutput()
  409. if err != nil {
  410. return "", "", errors.New(string(out))
  411. }
  412. //nmcli return something. Use the first one
  413. outString := strings.TrimSpace(string(out))
  414. currentSSIDInfo := ""
  415. if strings.Contains(outString, "\n") {
  416. connectedIds := strings.Split(outString, "\n")
  417. for _, conn := range connectedIds {
  418. if !strings.Contains(conn, "Wired") {
  419. //The first connection that is not wired
  420. currentSSIDInfo = conn
  421. break
  422. }
  423. }
  424. } else {
  425. currentSSIDInfo = outString
  426. }
  427. if strings.Contains(currentSSIDInfo, "Wired") {
  428. //This is an ethernet port?
  429. //Nothing connected
  430. return "OFFLINE", "N/A", nil
  431. }
  432. if currentSSIDInfo == "" {
  433. //No connection to any interface, which is strange?
  434. return "", "", errors.New("No established connection")
  435. }
  436. //Split the information
  437. SSIDinfoChunk := strings.Split(currentSSIDInfo, ":")
  438. currentSSID := SSIDinfoChunk[0]
  439. interfaceName := SSIDinfoChunk[1]
  440. return currentSSID, interfaceName, nil
  441. }
  442. return "", "", errors.New(string(out))
  443. }
  444. if len(string(out)) == 0 {
  445. return "OFFLINE", "N/A", nil
  446. }
  447. //Try to parse the data
  448. trimmedData := string(out)
  449. for strings.Contains(trimmedData, " ") {
  450. trimmedData = strings.ReplaceAll(trimmedData, " ", " ")
  451. }
  452. dc := strings.Split(trimmedData, " ")
  453. if len(dc) == 0 {
  454. return "", "", errors.New("No valid wlan Interface Found")
  455. }
  456. wlanInterface := dc[0]
  457. ESSID := strings.Join(dc[1:], " ")[7:]
  458. ESSID = strings.TrimSpace(ESSID)
  459. ESSID = ESSID[:len(ESSID)-1]
  460. if strings.TrimSpace(ESSID) == "\"" {
  461. ESSID = ""
  462. }
  463. return ESSID, wlanInterface, nil
  464. }
  465. func (w *WiFiManager) CheckInterfaceIsAP(wlanInterfaceName string) (bool, error) {
  466. cmd := exec.Command("bash", "-c", "iwconfig wlan1 | grep Mode")
  467. out, err := cmd.CombinedOutput()
  468. if err != nil {
  469. return false, err
  470. }
  471. if len(string(out)) == 0 {
  472. return false, errors.New("Missing iwconfig package")
  473. }
  474. //Check if the output contains Mode:Master
  475. if strings.Contains(string(out), "Mode:Master") {
  476. return true, nil
  477. } else {
  478. return false, nil
  479. }
  480. }
  481. func (w *WiFiManager) RemoveWifi(ssid string) error {
  482. if pkg_exists("nmcli") {
  483. //Make use of nmcli storage
  484. if w.database.KeyExists("wifi", ssid) {
  485. w.database.Delete("wifi", ssid)
  486. }
  487. } else {
  488. //Fall back to systemctl
  489. if !fileInDir("./system/network/wifi/ap/"+ssid+".config", "./system/network/wifi/ap/") {
  490. return errors.New("Invalid SSID")
  491. }
  492. if fileExists("./system/network/wifi/ap/" + ssid + ".config") {
  493. os.Remove("./system/network/wifi/ap/" + ssid + ".config")
  494. } else {
  495. return errors.New("Record not found")
  496. }
  497. }
  498. return nil
  499. }
  500. // CanControlInterfacePower reports whether SetInterfacePower is supported
  501. func (w *WiFiManager) CanControlInterfacePower() bool {
  502. return true
  503. }
  504. // CanConnect reports whether ConnectWiFi and RemoveWifi are supported
  505. func (w *WiFiManager) CanConnect() bool {
  506. return true
  507. }
  508. // GetInterfaceStatus returns the live state of every wireless interface
  509. func (w *WiFiManager) GetInterfaceStatus() ([]WiFiInterfaceStatus, error) {
  510. names, err := w.GetWirelessInterfaces()
  511. if err != nil {
  512. return []WiFiInterfaceStatus{}, err
  513. }
  514. results := []WiFiInterfaceStatus{}
  515. for _, name := range names {
  516. name = strings.TrimSpace(name)
  517. if name == "" {
  518. continue
  519. }
  520. results = append(results, w.interfaceStatus(name))
  521. }
  522. return results, nil
  523. }
  524. func (w *WiFiManager) interfaceStatus(name string) WiFiInterfaceStatus {
  525. status := WiFiInterfaceStatus{
  526. Name: name,
  527. State: "disconnected",
  528. SoftwareRadio: "unknown",
  529. HardwareRadio: "unknown",
  530. SignalQuality: -1,
  531. IPv4: []string{},
  532. IPv6: []string{},
  533. Gateways: []string{},
  534. DNS: []string{},
  535. }
  536. sysDir := filepath.Join("/sys", "class", "net", name)
  537. if driver, err := filepath.EvalSymlinks(filepath.Join(sysDir, "device", "driver")); err == nil {
  538. status.Description = "Driver: " + filepath.Base(driver)
  539. }
  540. if blocked, ok := readRfkill(sysDir, "soft"); ok {
  541. status.SoftwareRadio = map[bool]string{true: "off", false: "on"}[blocked]
  542. }
  543. if blocked, ok := readRfkill(sysDir, "hard"); ok {
  544. status.HardwareRadio = map[bool]string{true: "off", false: "on"}[blocked]
  545. }
  546. if nic, err := net.InterfaceByName(name); err == nil {
  547. status.MAC = nic.HardwareAddr.String()
  548. status.MTU = nic.MTU
  549. if nic.Flags&net.FlagUp == 0 {
  550. status.State = "down"
  551. }
  552. if addrs, err := nic.Addrs(); err == nil {
  553. for _, addr := range addrs {
  554. ipnet, ok := addr.(*net.IPNet)
  555. if !ok {
  556. continue
  557. }
  558. if ipnet.IP.To4() != nil {
  559. status.IPv4 = append(status.IPv4, ipnet.String())
  560. } else {
  561. status.IPv6 = append(status.IPv6, ipnet.String())
  562. }
  563. }
  564. }
  565. }
  566. if routes, err := os.ReadFile(filepath.Join("/proc", "net", "route")); err == nil {
  567. status.Gateways = parseProcRoute(string(routes), name)
  568. }
  569. link, err := readIwLink(name)
  570. if err != nil {
  571. //No iw: fall back to the connected SSID from iwgetid / nmcli
  572. ssid, iface, err := w.GetConnectedWiFi()
  573. if err == nil && iface == name && ssid != "" && ssid != "OFFLINE" {
  574. status.SSID = ssid
  575. status.Connected = true
  576. status.State = "connected"
  577. }
  578. return status
  579. }
  580. if !link.Connected {
  581. return status
  582. }
  583. status.Connected = true
  584. status.State = "connected"
  585. status.SSID = link.SSID
  586. status.BSSID = link.BSSID
  587. status.BSSType = "Infrastructure"
  588. status.FrequencyMHz = link.FreqMHz
  589. status.Band = bandOfFrequency(link.FreqMHz)
  590. status.Channel = channelOfFrequency(link.FreqMHz)
  591. status.ChannelWidth = link.Width
  592. status.RSSI = link.SignalDBm
  593. status.SignalQuality = qualityFromRSSI(link.SignalDBm)
  594. status.RxRateMbps = link.RxRateMbps
  595. status.TxRateMbps = link.TxRateMbps
  596. status.PHYType = link.PHYType
  597. status.Generation = generationOfPHY(link.PHYType, status.Band)
  598. return status
  599. }
  600. // readRfkill reports whether any rfkill switch of the interface's PHY is
  601. // blocked (kind is "soft" or "hard"). ok is false when there is no switch.
  602. func readRfkill(sysDir string, kind string) (blocked bool, ok bool) {
  603. matches, err := filepath.Glob(filepath.Join(sysDir, "phy80211", "rfkill*", kind))
  604. if err != nil || len(matches) == 0 {
  605. return false, false
  606. }
  607. for _, m := range matches {
  608. content, err := os.ReadFile(m)
  609. if err != nil {
  610. continue
  611. }
  612. ok = true
  613. if strings.TrimSpace(string(content)) == "1" {
  614. blocked = true
  615. }
  616. }
  617. return blocked, ok
  618. }
  619. // Helper functions
  620. func fileInDir(filesourcepath string, directory string) bool {
  621. filepathAbs, err := filepath.Abs(filesourcepath)
  622. if err != nil {
  623. return false
  624. }
  625. directoryAbs, err := filepath.Abs(directory)
  626. if err != nil {
  627. return false
  628. }
  629. //Check if the filepathabs contain directoryAbs
  630. if strings.Contains(filepathAbs, directoryAbs) {
  631. return true
  632. } else {
  633. return false
  634. }
  635. }
  636. func fileExists(filename string) bool {
  637. _, err := os.Stat(filename)
  638. if os.IsNotExist(err) {
  639. return false
  640. }
  641. return true
  642. }
  643. func pkg_exists(pkgname string) bool {
  644. cmd := exec.Command("which", pkgname)
  645. out, _ := cmd.CombinedOutput()
  646. if len(string(out)) > 1 {
  647. return true
  648. } else {
  649. return false
  650. }
  651. }