iwparse.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. package wifi
  2. /*
  3. Linux wireless tool output parsers
  4. Pure text parsers for the output of "iwlist <if> scan" and
  5. "iw dev <if> link", kept free of build tags so they are tested on every
  6. platform. The commands themselves are run from wifi_linux.go.
  7. */
  8. import (
  9. "encoding/hex"
  10. "regexp"
  11. "strconv"
  12. "strings"
  13. )
  14. var (
  15. reIwQuality = regexp.MustCompile(`Quality[=:](\d+)/(\d+)`)
  16. reIwSignalDBm = regexp.MustCompile(`Signal level[=:](-?\d+(?:\.\d+)?) ?dBm`)
  17. reIwSignalRel = regexp.MustCompile(`Signal level[=:](\d+)/(\d+)`)
  18. reIwChannel = regexp.MustCompile(`\(Channel (\d+)\)`)
  19. reIwRate = regexp.MustCompile(`([\d.]+) Mb/s`)
  20. reIwSuiteNum = regexp.MustCompile(`unknown \((\d+)\)`)
  21. reIwWidth = regexp.MustCompile(`(\d+)MHz`)
  22. reLeadingInt = regexp.MustCompile(`^\s*(-?\d+)`)
  23. )
  24. // iwlistCell collects one "Cell" of iwlist output
  25. type iwlistCell struct {
  26. info WiFiInfo
  27. rawIEs []byte
  28. section string //"rsn" or "wpa" while inside a decoded IE
  29. hasRSN bool
  30. hasWPA bool
  31. rsnAKMs []uint32
  32. wpaAKMs []uint32
  33. rsnCiphs []uint32
  34. wpaCiphs []uint32
  35. rates []uint16
  36. inRates bool
  37. tsf uint64
  38. }
  39. // parseIwlistScan parses the output of "iwlist <interface> scan"
  40. func parseIwlistScan(out string) []WiFiInfo {
  41. results := []WiFiInfo{}
  42. var cur *iwlistCell
  43. flush := func() {
  44. if cur != nil && cur.info.Address != "" {
  45. results = append(results, cur.finish())
  46. }
  47. cur = nil
  48. }
  49. for _, raw := range strings.Split(out, "\n") {
  50. line := strings.TrimSpace(raw)
  51. if strings.HasPrefix(line, "Cell ") && strings.Contains(line, "Address:") {
  52. flush()
  53. cur = &iwlistCell{}
  54. fields := strings.Fields(line)
  55. cur.info.Address = strings.ToLower(fields[len(fields)-1])
  56. cur.info.QualityPercent = -1
  57. continue
  58. }
  59. if cur == nil || line == "" {
  60. continue
  61. }
  62. //Bit rates continue on the following lines
  63. if cur.inRates && !strings.Contains(line, ":") && reIwRate.MatchString(line) {
  64. cur.addRates(line)
  65. continue
  66. }
  67. cur.inRates = false
  68. switch {
  69. case strings.HasPrefix(line, "Channel:"):
  70. if ch, err := strconv.Atoi(strings.TrimSpace(line[len("Channel:"):])); err == nil {
  71. cur.info.Channel = ch
  72. }
  73. case strings.HasPrefix(line, "Frequency:"):
  74. value := strings.TrimSpace(line[len("Frequency:"):])
  75. cur.info.FrequencyMHz = parseFrequencyMHz(value)
  76. if m := reIwChannel.FindStringSubmatch(value); m != nil {
  77. cur.info.Channel, _ = strconv.Atoi(m[1])
  78. }
  79. case strings.HasPrefix(line, "Quality"):
  80. if m := reIwQuality.FindStringSubmatch(line); m != nil {
  81. cur.info.Quality = m[1] + "/" + m[2]
  82. a, _ := strconv.Atoi(m[1])
  83. b, _ := strconv.Atoi(m[2])
  84. if b > 0 {
  85. cur.info.QualityPercent = a * 100 / b
  86. }
  87. }
  88. if m := reIwSignalDBm.FindStringSubmatch(line); m != nil {
  89. dbm, _ := strconv.ParseFloat(m[1], 64)
  90. cur.info.SignalDBm = int(dbm)
  91. cur.info.SignalLevel = strconv.Itoa(cur.info.SignalDBm) + " dBm"
  92. } else if m := reIwSignalRel.FindStringSubmatch(line); m != nil {
  93. cur.info.SignalLevel = m[1] + "/" + m[2]
  94. }
  95. case strings.HasPrefix(line, "Encryption key:"):
  96. cur.info.EncryptionKey = strings.TrimSpace(line[len("Encryption key:"):]) == "on"
  97. case strings.HasPrefix(line, "ESSID:"):
  98. value := strings.TrimSpace(line[len("ESSID:"):])
  99. value = strings.TrimSuffix(strings.TrimPrefix(value, "\""), "\"")
  100. ssid, hidden := ssidString(unescapeIwString(value))
  101. cur.info.ESSID = ssid
  102. cur.info.Hidden = hidden
  103. case strings.HasPrefix(line, "Mode:"):
  104. switch strings.TrimSpace(line[len("Mode:"):]) {
  105. case "Master":
  106. cur.info.BSSType = "Infrastructure"
  107. case "Ad-Hoc":
  108. cur.info.BSSType = "Ad hoc"
  109. }
  110. case strings.HasPrefix(line, "Bit Rates:"):
  111. cur.inRates = true
  112. cur.addRates(line)
  113. case strings.HasPrefix(line, "IE: IEEE 802.11i/WPA2"):
  114. cur.section = "rsn"
  115. cur.hasRSN = true
  116. case strings.HasPrefix(line, "IE: WPA Version"):
  117. cur.section = "wpa"
  118. cur.hasWPA = true
  119. case strings.HasPrefix(line, "IE: Unknown:"):
  120. cur.section = ""
  121. if b, err := hex.DecodeString(strings.TrimSpace(line[len("IE: Unknown:"):])); err == nil {
  122. cur.rawIEs = append(cur.rawIEs, b...)
  123. }
  124. case strings.HasPrefix(line, "IE:"):
  125. cur.section = ""
  126. case strings.HasPrefix(line, "Pairwise Ciphers"):
  127. ciphers := parseIwSuiteList(line, map[string]uint32{"WEP-40": 1, "TKIP": 2, "WRAP": 3, "CCMP": 4, "WEP-104": 5})
  128. if cur.section == "rsn" {
  129. cur.rsnCiphs = ciphers
  130. } else if cur.section == "wpa" {
  131. cur.wpaCiphs = ciphers
  132. }
  133. case strings.HasPrefix(line, "Authentication Suites"):
  134. akms := parseIwSuiteList(line, map[string]uint32{"802.1x": 1, "PSK": 2})
  135. if cur.section == "rsn" {
  136. cur.rsnAKMs = akms
  137. } else if cur.section == "wpa" {
  138. cur.wpaAKMs = akms
  139. }
  140. case strings.HasPrefix(line, "Extra:tsf="):
  141. if v, err := strconv.ParseUint(strings.TrimSpace(line[len("Extra:tsf="):]), 16, 64); err == nil {
  142. cur.tsf = v
  143. }
  144. }
  145. }
  146. flush()
  147. return results
  148. }
  149. func (c *iwlistCell) addRates(line string) {
  150. for _, m := range reIwRate.FindAllStringSubmatch(line, -1) {
  151. if v, err := strconv.ParseFloat(m[1], 64); err == nil && v > 0 {
  152. c.rates = append(c.rates, uint16(v*2))
  153. }
  154. }
  155. }
  156. // finish combines the decoded fields with what the raw IEs reveal
  157. func (c *iwlistCell) finish() WiFiInfo {
  158. info := c.info
  159. el := parseIEs(c.rawIEs)
  160. if c.hasRSN {
  161. el.HasRSN = true
  162. el.rsnAKMs = c.rsnAKMs
  163. el.ciphers = c.rsnCiphs
  164. }
  165. if c.hasWPA {
  166. el.HasWPA = true
  167. el.wpaAKMs = c.wpaAKMs
  168. if !c.hasRSN {
  169. el.ciphers = c.wpaCiphs
  170. }
  171. }
  172. if info.ESSID == "" && !info.Hidden && el.HasSSID {
  173. info.ESSID, info.Hidden = ssidString(el.SSID)
  174. }
  175. rates := c.rates
  176. if len(rates) == 0 {
  177. rates = ratesFromIE(c.rawIEs)
  178. }
  179. _, all, legacyMax := legacyRates(rates)
  180. info.SupportedRates = all
  181. normalizeWiFiInfo(&info)
  182. phy, generation, width, center := el.phyInfo(info.Band, legacyMax)
  183. info.PHYType = phy
  184. info.Generation = generation
  185. info.ChannelWidth = width
  186. if width > 20 {
  187. info.CenterChannel = center
  188. }
  189. streams := el.spatialStreams()
  190. maxMCS := el.heMaxMCS
  191. if phy == "802.11ac" {
  192. maxMCS = el.vhtMaxMCS
  193. }
  194. info.SpatialStreams = streams
  195. info.MaxRateMbps = estimateMaxRate(phy, width, streams, maxMCS, legacyMax)
  196. info.Security = el.securityName(info.EncryptionKey)
  197. info.Cipher = el.cipherName(info.EncryptionKey)
  198. info.PMF = el.PMF
  199. info.Country = el.Country
  200. info.StationCount = el.StationCount
  201. info.ChannelUtilization = el.ChannelUtilization
  202. info.WPS = el.WPS
  203. info.Roaming = el.Roaming
  204. info.UptimeSeconds = int64(c.tsf / 1000000)
  205. return info
  206. }
  207. // parseIwSuiteList reads the names after the colon of an iwlist
  208. // "Pairwise Ciphers (n) : ..." or "Authentication Suites (n) : ..." line
  209. func parseIwSuiteList(line string, names map[string]uint32) []uint32 {
  210. i := strings.Index(line, ":")
  211. if i < 0 {
  212. return nil
  213. }
  214. value := line[i+1:]
  215. list := []uint32{}
  216. for _, m := range reIwSuiteNum.FindAllStringSubmatch(value, -1) {
  217. if v, err := strconv.Atoi(m[1]); err == nil {
  218. list = append(list, uint32(v))
  219. }
  220. }
  221. value = reIwSuiteNum.ReplaceAllString(value, "")
  222. for _, f := range strings.Fields(value) {
  223. if v, ok := names[f]; ok {
  224. list = append(list, v)
  225. }
  226. }
  227. return list
  228. }
  229. // unescapeIwString decodes the \xNN escapes iw / iwlist use for SSID bytes
  230. func unescapeIwString(s string) []byte {
  231. out := []byte{}
  232. for i := 0; i < len(s); i++ {
  233. if s[i] == '\\' && i+3 < len(s) && s[i+1] == 'x' {
  234. if b, err := hex.DecodeString(s[i+2 : i+4]); err == nil {
  235. out = append(out, b[0])
  236. i += 3
  237. continue
  238. }
  239. }
  240. out = append(out, s[i])
  241. }
  242. return out
  243. }
  244. // parseFrequencyMHz reads "2.412 GHz", "5180 MHz", "5180" or "5180.0"
  245. func parseFrequencyMHz(s string) int {
  246. fields := strings.Fields(strings.TrimSpace(s))
  247. if len(fields) == 0 {
  248. return 0
  249. }
  250. v, err := strconv.ParseFloat(fields[0], 64)
  251. if err != nil || v <= 0 {
  252. return 0
  253. }
  254. if len(fields) > 1 && strings.EqualFold(fields[1], "GHz") || len(fields) == 1 && v < 100 {
  255. v *= 1000
  256. }
  257. return int(v + 0.5)
  258. }
  259. // iwLinkInfo is the parsed output of "iw dev <interface> link"
  260. type iwLinkInfo struct {
  261. Connected bool
  262. BSSID string
  263. SSID string
  264. Hidden bool
  265. FreqMHz int
  266. SignalDBm int
  267. RxRateMbps float64
  268. TxRateMbps float64
  269. Width int
  270. PHYType string
  271. BeaconInt int
  272. }
  273. // parseIwLink parses the output of "iw dev <interface> link"
  274. func parseIwLink(out string) iwLinkInfo {
  275. link := iwLinkInfo{}
  276. for _, raw := range strings.Split(out, "\n") {
  277. line := strings.TrimSpace(raw)
  278. key, value, found := strings.Cut(line, ":")
  279. value = strings.TrimSpace(value)
  280. switch {
  281. case strings.HasPrefix(line, "Connected to "):
  282. fields := strings.Fields(line)
  283. if len(fields) >= 3 {
  284. link.Connected = true
  285. link.BSSID = strings.ToLower(fields[2])
  286. }
  287. case !found:
  288. continue
  289. case key == "SSID":
  290. link.SSID, link.Hidden = ssidString(unescapeIwString(value))
  291. case key == "freq":
  292. link.FreqMHz = parseFrequencyMHz(value)
  293. case key == "signal":
  294. if m := reLeadingInt.FindStringSubmatch(value); m != nil {
  295. link.SignalDBm, _ = strconv.Atoi(m[1])
  296. }
  297. case key == "rx bitrate" || key == "tx bitrate":
  298. rate := 0.0
  299. if f := strings.Fields(value); len(f) > 0 {
  300. rate, _ = strconv.ParseFloat(f[0], 64)
  301. }
  302. if key == "rx bitrate" {
  303. link.RxRateMbps = rate
  304. } else {
  305. link.TxRateMbps = rate
  306. }
  307. if m := reIwWidth.FindStringSubmatch(value); m != nil {
  308. if w, _ := strconv.Atoi(m[1]); w > link.Width {
  309. link.Width = w
  310. }
  311. }
  312. if phy := phyOfBitrate(value); phy != "" {
  313. link.PHYType = phy
  314. }
  315. case key == "beacon int":
  316. link.BeaconInt, _ = strconv.Atoi(value)
  317. }
  318. }
  319. return link
  320. }
  321. // phyOfBitrate maps the MCS type in an iw bitrate line to the 802.11 amendment
  322. func phyOfBitrate(s string) string {
  323. switch {
  324. case strings.Contains(s, "EHT-MCS"):
  325. return "802.11be"
  326. case strings.Contains(s, "HE-MCS"):
  327. return "802.11ax"
  328. case strings.Contains(s, "VHT-MCS"):
  329. return "802.11ac"
  330. case strings.Contains(s, "MCS"):
  331. return "802.11n"
  332. }
  333. return ""
  334. }
  335. // parseProcRoute returns the default gateways of an interface from the
  336. // content of /proc/net/route
  337. func parseProcRoute(content string, iface string) []string {
  338. gateways := []string{}
  339. for _, line := range strings.Split(content, "\n") {
  340. f := strings.Fields(line)
  341. if len(f) < 3 || f[0] != iface || f[1] != "00000000" {
  342. continue
  343. }
  344. b, err := hex.DecodeString(f[2])
  345. if err != nil || len(b) != 4 {
  346. continue
  347. }
  348. ip := strconv.Itoa(int(b[3])) + "." + strconv.Itoa(int(b[2])) + "." + strconv.Itoa(int(b[1])) + "." + strconv.Itoa(int(b[0]))
  349. if ip != "0.0.0.0" && !containsString(gateways, ip) {
  350. gateways = append(gateways, ip)
  351. }
  352. }
  353. return gateways
  354. }
  355. // normalizeWiFiInfo fills the numeric fields of a scan result from the
  356. // string fields when the platform parser did not set them
  357. func normalizeWiFiInfo(info *WiFiInfo) {
  358. if info.SignalDBm == 0 {
  359. if m := reLeadingInt.FindStringSubmatch(info.SignalLevel); m != nil && strings.Contains(info.SignalLevel, "dBm") {
  360. info.SignalDBm, _ = strconv.Atoi(m[1])
  361. }
  362. }
  363. if info.QualityPercent <= 0 {
  364. info.QualityPercent = -1
  365. if m := reIwQuality.FindStringSubmatch("Quality=" + info.Quality); m != nil {
  366. a, _ := strconv.Atoi(m[1])
  367. b, _ := strconv.Atoi(m[2])
  368. if b > 0 {
  369. info.QualityPercent = a * 100 / b
  370. }
  371. }
  372. if info.QualityPercent < 0 && info.SignalDBm != 0 {
  373. info.QualityPercent = qualityFromRSSI(info.SignalDBm)
  374. }
  375. }
  376. if info.FrequencyMHz == 0 {
  377. info.FrequencyMHz = parseFrequencyMHz(info.Frequency)
  378. if bandOfFrequency(info.FrequencyMHz) == "" {
  379. info.FrequencyMHz = 0
  380. }
  381. }
  382. if info.FrequencyMHz == 0 && info.Channel > 0 {
  383. info.FrequencyMHz = frequencyOfChannel(info.Channel, false)
  384. }
  385. if info.Channel <= 0 && info.FrequencyMHz > 0 {
  386. info.Channel = channelOfFrequency(info.FrequencyMHz)
  387. }
  388. if info.FrequencyMHz > 0 {
  389. info.Band = bandOfFrequency(info.FrequencyMHz)
  390. info.Frequency = formatFrequency(info.FrequencyMHz)
  391. }
  392. if info.Generation == "" {
  393. info.Generation = generationOfPHY(info.PHYType, info.Band)
  394. }
  395. }