netstat.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. package netstat
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "log"
  6. "net/http"
  7. "os"
  8. "os/exec"
  9. "path/filepath"
  10. "runtime"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "imuslab.com/zoraxy/mod/utils"
  15. )
  16. // Float stat store the change of RX and TX
  17. type FlowStat struct {
  18. RX int64
  19. TX int64
  20. }
  21. // A new type of FloatStat that save the raw value from rx tx
  22. type RawFlowStat struct {
  23. RX int64
  24. TX int64
  25. }
  26. type NetStatBuffers struct {
  27. StatRecordCount int //No. of record number to keep
  28. PreviousStat *RawFlowStat //The value of the last instance of netstats
  29. Stats []*FlowStat //Statistic of the flow
  30. StopChan chan bool //Channel to stop the ticker
  31. EventTicker *time.Ticker //Ticker for event logging
  32. }
  33. // Get a new network statistic buffers
  34. func NewNetStatBuffer(recordCount int) (*NetStatBuffers, error) {
  35. //Flood fill the stats with 0
  36. initialStats := []*FlowStat{}
  37. for i := 0; i < recordCount; i++ {
  38. initialStats = append(initialStats, &FlowStat{
  39. RX: 0,
  40. TX: 0,
  41. })
  42. }
  43. //Setup a timer to get the value from NIC accumulation stats
  44. ticker := time.NewTicker(time.Second)
  45. //Setup a stop channel
  46. stopCh := make(chan bool)
  47. currnetNetSpec := RawFlowStat{
  48. RX: 0,
  49. TX: 0,
  50. }
  51. thisNetBuffer := NetStatBuffers{
  52. StatRecordCount: recordCount,
  53. PreviousStat: &currnetNetSpec,
  54. Stats: initialStats,
  55. StopChan: stopCh,
  56. EventTicker: ticker,
  57. }
  58. //Get the initial measurements of netstats
  59. go func(n *NetStatBuffers) {
  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. n.PreviousStat = &RawFlowStat{
  75. RX: rx,
  76. TX: tx,
  77. }
  78. }(&thisNetBuffer)
  79. // Update the buffer every second
  80. go func(n *NetStatBuffers) {
  81. for {
  82. select {
  83. case <-n.StopChan:
  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(time.Second)
  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. cmd := exec.Command("wmic", "path", "Win32_PerfRawData_Tcpip_NetworkInterface", "Get", "BytesReceivedPersec,BytesSentPersec,BytesTotalPersec")
  168. out, err := cmd.Output()
  169. if err != nil {
  170. return 0, 0, err
  171. }
  172. defer cmd.Process.Kill()
  173. //Filter out the first line
  174. lines := strings.Split(strings.ReplaceAll(string(out), "\r\n", "\n"), "\n")
  175. if len(lines) >= 2 && len(lines[1]) >= 0 {
  176. dataLine := lines[1]
  177. for strings.Contains(dataLine, " ") {
  178. dataLine = strings.ReplaceAll(dataLine, " ", " ")
  179. }
  180. dataLine = strings.TrimSpace(dataLine)
  181. info := strings.Split(dataLine, " ")
  182. if len(info) < 3 {
  183. return 0, 0, errors.New("Invalid wmic results")
  184. }
  185. rxString := info[0]
  186. txString := info[1]
  187. rx := int64(0)
  188. tx := int64(0)
  189. if s, err := strconv.ParseInt(rxString, 10, 64); err == nil {
  190. rx = s
  191. }
  192. if s, err := strconv.ParseInt(txString, 10, 64); err == nil {
  193. tx = s
  194. }
  195. //log.Println(rx, tx)
  196. return rx * 4, tx * 4, nil
  197. } else {
  198. //Invalid data
  199. return 0, 0, errors.New("Invalid wmic results")
  200. }
  201. } else if runtime.GOOS == "linux" {
  202. allIfaceRxByteFiles, err := filepath.Glob("/sys/class/net/*/statistics/rx_bytes")
  203. if err != nil {
  204. //Permission denied
  205. return 0, 0, errors.New("Access denied")
  206. }
  207. if len(allIfaceRxByteFiles) == 0 {
  208. return 0, 0, errors.New("No valid iface found")
  209. }
  210. rxSum := int64(0)
  211. txSum := int64(0)
  212. for _, rxByteFile := range allIfaceRxByteFiles {
  213. rxBytes, err := os.ReadFile(rxByteFile)
  214. if err == nil {
  215. rxBytesInt, err := strconv.Atoi(strings.TrimSpace(string(rxBytes)))
  216. if err == nil {
  217. rxSum += int64(rxBytesInt)
  218. }
  219. }
  220. //Usually the tx_bytes file is nearby it. Read it as well
  221. txByteFile := filepath.Join(filepath.Dir(rxByteFile), "tx_bytes")
  222. txBytes, err := os.ReadFile(txByteFile)
  223. if err == nil {
  224. txBytesInt, err := strconv.Atoi(strings.TrimSpace(string(txBytes)))
  225. if err == nil {
  226. txSum += int64(txBytesInt)
  227. }
  228. }
  229. }
  230. //Return value as bits
  231. return rxSum * 8, txSum * 8, nil
  232. } else if runtime.GOOS == "darwin" {
  233. cmd := exec.Command("netstat", "-ib") //get data from netstat -ib
  234. out, err := cmd.Output()
  235. if err != nil {
  236. return 0, 0, err
  237. }
  238. outStrs := string(out) //byte array to multi-line string
  239. for _, outStr := range strings.Split(strings.TrimSuffix(outStrs, "\n"), "\n") { //foreach multi-line string
  240. if strings.HasPrefix(outStr, "en") { //search for ethernet interface
  241. if strings.Contains(outStr, "<Link#") { //search for the link with <Link#?>
  242. outStrSplit := strings.Fields(outStr) //split by white-space
  243. rxSum, errRX := strconv.Atoi(outStrSplit[6]) //received bytes sum
  244. if errRX != nil {
  245. return 0, 0, errRX
  246. }
  247. txSum, errTX := strconv.Atoi(outStrSplit[9]) //transmitted bytes sum
  248. if errTX != nil {
  249. return 0, 0, errTX
  250. }
  251. return int64(rxSum) * 8, int64(txSum) * 8, nil
  252. }
  253. }
  254. }
  255. return 0, 0, nil //no ethernet adapters with en*/<Link#*>
  256. }
  257. return 0, 0, errors.New("Platform not supported")
  258. }