netstat.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. package netstat
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "log"
  7. "net/http"
  8. "os"
  9. "os/exec"
  10. "path/filepath"
  11. "runtime"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "imuslab.com/zoraxy/mod/utils"
  16. )
  17. // Float stat store the change of RX and TX
  18. type FlowStat struct {
  19. RX int64
  20. TX int64
  21. }
  22. // A new type of FloatStat that save the raw value from rx tx
  23. type RawFlowStat struct {
  24. RX int64
  25. TX int64
  26. }
  27. type NetStatBuffers struct {
  28. StatRecordCount int //No. of record number to keep
  29. PreviousStat *RawFlowStat //The value of the last instance of netstats
  30. Stats []*FlowStat //Statistic of the flow
  31. StopChan chan bool //Channel to stop the ticker
  32. EventTicker *time.Ticker //Ticker for event logging
  33. }
  34. // Get a new network statistic buffers
  35. func NewNetStatBuffer(recordCount int) (*NetStatBuffers, error) {
  36. //Flood fill the stats with 0
  37. initialStats := []*FlowStat{}
  38. for i := 0; i < recordCount; i++ {
  39. initialStats = append(initialStats, &FlowStat{
  40. RX: 0,
  41. TX: 0,
  42. })
  43. }
  44. //Setup a timer to get the value from NIC accumulation stats
  45. ticker := time.NewTicker(time.Second)
  46. //Setup a stop channel
  47. stopCh := make(chan bool)
  48. currnetNetSpec := RawFlowStat{
  49. RX: 0,
  50. TX: 0,
  51. }
  52. thisNetBuffer := NetStatBuffers{
  53. StatRecordCount: recordCount,
  54. PreviousStat: &currnetNetSpec,
  55. Stats: initialStats,
  56. StopChan: stopCh,
  57. EventTicker: ticker,
  58. }
  59. //Get the initial measurements of netstats
  60. rx, tx, err := GetNetworkInterfaceStats()
  61. if err != nil {
  62. log.Println("Unable to get NIC stats: ", err.Error())
  63. }
  64. retryCount := 0
  65. for rx == 0 && tx == 0 && retryCount < 10 {
  66. //Strange. Retry
  67. log.Println("NIC stats return all 0. Retrying...")
  68. rx, tx, err = GetNetworkInterfaceStats()
  69. if err != nil {
  70. log.Println("Unable to get NIC stats: ", err.Error())
  71. }
  72. retryCount++
  73. }
  74. thisNetBuffer.PreviousStat = &RawFlowStat{
  75. RX: rx,
  76. TX: tx,
  77. }
  78. // Update the buffer every second
  79. go func(n *NetStatBuffers) {
  80. for {
  81. select {
  82. case <-n.StopChan:
  83. fmt.Println("- Netstats listener stopped")
  84. return
  85. case <-ticker.C:
  86. if n.PreviousStat.RX == 0 && n.PreviousStat.TX == 0 {
  87. //Initiation state is still not done. Ignore request
  88. log.Println("No initial states. Waiting")
  89. return
  90. }
  91. // Get the latest network interface stats
  92. rx, tx, err := GetNetworkInterfaceStats()
  93. if err != nil {
  94. // Log the error, but don't stop the buffer
  95. log.Printf("Failed to get network interface stats: %v", err)
  96. continue
  97. }
  98. //Calculate the difference between this and last values
  99. drx := rx - n.PreviousStat.RX
  100. dtx := tx - n.PreviousStat.TX
  101. // Push the new stats to the buffer
  102. newStat := &FlowStat{
  103. RX: drx,
  104. TX: dtx,
  105. }
  106. //Set current rx tx as the previous rxtx
  107. n.PreviousStat = &RawFlowStat{
  108. RX: rx,
  109. TX: tx,
  110. }
  111. newStats := n.Stats[1:]
  112. newStats = append(newStats, newStat)
  113. n.Stats = newStats
  114. }
  115. }
  116. }(&thisNetBuffer)
  117. return &thisNetBuffer, nil
  118. }
  119. func (n *NetStatBuffers) HandleGetBufferedNetworkInterfaceStats(w http.ResponseWriter, r *http.Request) {
  120. arr, _ := utils.GetPara(r, "array")
  121. if arr == "true" {
  122. //Restructure it into array
  123. rx := []int{}
  124. tx := []int{}
  125. for _, state := range n.Stats {
  126. rx = append(rx, int(state.RX))
  127. tx = append(tx, int(state.TX))
  128. }
  129. type info struct {
  130. Rx []int
  131. Tx []int
  132. }
  133. js, _ := json.Marshal(info{
  134. Rx: rx,
  135. Tx: tx,
  136. })
  137. utils.SendJSONResponse(w, string(js))
  138. } else {
  139. js, _ := json.Marshal(n.Stats)
  140. utils.SendJSONResponse(w, string(js))
  141. }
  142. }
  143. func (n *NetStatBuffers) Close() {
  144. n.StopChan <- true
  145. time.Sleep(300 * time.Millisecond)
  146. n.EventTicker.Stop()
  147. }
  148. func HandleGetNetworkInterfaceStats(w http.ResponseWriter, r *http.Request) {
  149. rx, tx, err := GetNetworkInterfaceStats()
  150. if err != nil {
  151. utils.SendErrorResponse(w, err.Error())
  152. return
  153. }
  154. currnetNetSpec := struct {
  155. RX int64
  156. TX int64
  157. }{
  158. rx,
  159. tx,
  160. }
  161. js, _ := json.Marshal(currnetNetSpec)
  162. utils.SendJSONResponse(w, string(js))
  163. }
  164. // Get network interface stats, return accumulated rx bits, tx bits and error if any
  165. func GetNetworkInterfaceStats() (int64, int64, error) {
  166. if runtime.GOOS == "windows" {
  167. //Windows wmic sometime freeze and not respond.
  168. //The safer way is to make a bypass mechanism
  169. //when timeout with channel
  170. type wmicResult struct {
  171. RX int64
  172. TX int64
  173. Err error
  174. }
  175. callbackChan := make(chan wmicResult)
  176. cmd := exec.Command("wmic", "path", "Win32_PerfRawData_Tcpip_NetworkInterface", "Get", "BytesReceivedPersec,BytesSentPersec,BytesTotalPersec")
  177. //Execute the cmd in goroutine
  178. go func() {
  179. out, err := cmd.Output()
  180. if err != nil {
  181. callbackChan <- wmicResult{0, 0, err}
  182. }
  183. //Filter out the first line
  184. lines := strings.Split(strings.ReplaceAll(string(out), "\r\n", "\n"), "\n")
  185. if len(lines) >= 2 && len(lines[1]) >= 0 {
  186. dataLine := lines[1]
  187. for strings.Contains(dataLine, " ") {
  188. dataLine = strings.ReplaceAll(dataLine, " ", " ")
  189. }
  190. dataLine = strings.TrimSpace(dataLine)
  191. info := strings.Split(dataLine, " ")
  192. if len(info) != 3 {
  193. callbackChan <- wmicResult{0, 0, errors.New("invalid wmic results length")}
  194. }
  195. rxString := info[0]
  196. txString := info[1]
  197. rx := int64(0)
  198. tx := int64(0)
  199. if s, err := strconv.ParseInt(rxString, 10, 64); err == nil {
  200. rx = s
  201. }
  202. if s, err := strconv.ParseInt(txString, 10, 64); err == nil {
  203. tx = s
  204. }
  205. time.Sleep(100 * time.Millisecond)
  206. callbackChan <- wmicResult{rx * 4, tx * 4, nil}
  207. } else {
  208. //Invalid data
  209. callbackChan <- wmicResult{0, 0, errors.New("invalid wmic results")}
  210. }
  211. }()
  212. go func() {
  213. //Spawn a timer to terminate the cmd process if timeout
  214. var timer *time.Timer
  215. timer = time.AfterFunc(3*time.Second, func() {
  216. timer.Stop()
  217. if cmd != nil && cmd.Process != nil {
  218. cmd.Process.Kill()
  219. }
  220. callbackChan <- wmicResult{0, 0, errors.New("wmic execution timeout")}
  221. })
  222. }()
  223. result := wmicResult{}
  224. result = <-callbackChan
  225. if result.Err != nil {
  226. log.Println("Unable to extract NIC info from wmic: " + result.Err.Error())
  227. }
  228. return result.RX, result.TX, result.Err
  229. } else if runtime.GOOS == "linux" {
  230. allIfaceRxByteFiles, err := filepath.Glob("/sys/class/net/*/statistics/rx_bytes")
  231. if err != nil {
  232. //Permission denied
  233. return 0, 0, errors.New("Access denied")
  234. }
  235. if len(allIfaceRxByteFiles) == 0 {
  236. return 0, 0, errors.New("No valid iface found")
  237. }
  238. rxSum := int64(0)
  239. txSum := int64(0)
  240. for _, rxByteFile := range allIfaceRxByteFiles {
  241. rxBytes, err := os.ReadFile(rxByteFile)
  242. if err == nil {
  243. rxBytesInt, err := strconv.Atoi(strings.TrimSpace(string(rxBytes)))
  244. if err == nil {
  245. rxSum += int64(rxBytesInt)
  246. }
  247. }
  248. //Usually the tx_bytes file is nearby it. Read it as well
  249. txByteFile := filepath.Join(filepath.Dir(rxByteFile), "tx_bytes")
  250. txBytes, err := os.ReadFile(txByteFile)
  251. if err == nil {
  252. txBytesInt, err := strconv.Atoi(strings.TrimSpace(string(txBytes)))
  253. if err == nil {
  254. txSum += int64(txBytesInt)
  255. }
  256. }
  257. }
  258. //Return value as bits
  259. return rxSum * 8, txSum * 8, nil
  260. } else if runtime.GOOS == "darwin" {
  261. cmd := exec.Command("netstat", "-ib") //get data from netstat -ib
  262. out, err := cmd.Output()
  263. if err != nil {
  264. return 0, 0, err
  265. }
  266. outStrs := string(out) //byte array to multi-line string
  267. for _, outStr := range strings.Split(strings.TrimSuffix(outStrs, "\n"), "\n") { //foreach multi-line string
  268. if strings.HasPrefix(outStr, "en") { //search for ethernet interface
  269. if strings.Contains(outStr, "<Link#") { //search for the link with <Link#?>
  270. outStrSplit := strings.Fields(outStr) //split by white-space
  271. rxSum, errRX := strconv.Atoi(outStrSplit[6]) //received bytes sum
  272. if errRX != nil {
  273. return 0, 0, errRX
  274. }
  275. txSum, errTX := strconv.Atoi(outStrSplit[9]) //transmitted bytes sum
  276. if errTX != nil {
  277. return 0, 0, errTX
  278. }
  279. return int64(rxSum) * 8, int64(txSum) * 8, nil
  280. }
  281. }
  282. }
  283. return 0, 0, nil //no ethernet adapters with en*/<Link#*>
  284. }
  285. return 0, 0, errors.New("Platform not supported")
  286. }