netstat.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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. n.PreviousStat = &RawFlowStat{
  65. RX: rx,
  66. TX: tx,
  67. }
  68. }(&thisNetBuffer)
  69. // Update the buffer every second
  70. go func(n *NetStatBuffers) {
  71. for {
  72. select {
  73. case <-stopCh:
  74. return
  75. case <-ticker.C:
  76. if n.PreviousStat.RX == 0 && n.PreviousStat.TX == 0 {
  77. //Initiation state is still not done. Ignore request
  78. return
  79. }
  80. // Get the latest network interface stats
  81. rx, tx, err := GetNetworkInterfaceStats()
  82. if err != nil {
  83. // Log the error, but don't stop the buffer
  84. log.Printf("Failed to get network interface stats: %v", err)
  85. continue
  86. }
  87. //Calculate the difference between this and last values
  88. drx := rx - n.PreviousStat.RX
  89. dtx := tx - n.PreviousStat.TX
  90. // Push the new stats to the buffer
  91. newStat := &FlowStat{
  92. RX: drx,
  93. TX: dtx,
  94. }
  95. //Set current rx tx as the previous rxtx
  96. n.PreviousStat = &RawFlowStat{
  97. RX: rx,
  98. TX: tx,
  99. }
  100. newStats := n.Stats[1:]
  101. newStats = append(newStats, newStat)
  102. n.Stats = newStats
  103. }
  104. }
  105. }(&thisNetBuffer)
  106. return &thisNetBuffer, nil
  107. }
  108. func (n *NetStatBuffers) HandleGetBufferedNetworkInterfaceStats(w http.ResponseWriter, r *http.Request) {
  109. arr, _ := utils.GetPara(r, "array")
  110. if arr == "true" {
  111. //Restructure it into array
  112. rx := []int{}
  113. tx := []int{}
  114. for _, state := range n.Stats {
  115. rx = append(rx, int(state.RX))
  116. tx = append(tx, int(state.TX))
  117. }
  118. type info struct {
  119. Rx []int
  120. Tx []int
  121. }
  122. js, _ := json.Marshal(info{
  123. Rx: rx,
  124. Tx: tx,
  125. })
  126. utils.SendJSONResponse(w, string(js))
  127. } else {
  128. js, _ := json.Marshal(n.Stats)
  129. utils.SendJSONResponse(w, string(js))
  130. }
  131. }
  132. func (n *NetStatBuffers) Close() {
  133. n.StopChan <- true
  134. n.EventTicker.Stop()
  135. }
  136. func HandleGetNetworkInterfaceStats(w http.ResponseWriter, r *http.Request) {
  137. rx, tx, err := GetNetworkInterfaceStats()
  138. if err != nil {
  139. utils.SendErrorResponse(w, err.Error())
  140. return
  141. }
  142. currnetNetSpec := struct {
  143. RX int64
  144. TX int64
  145. }{
  146. rx,
  147. tx,
  148. }
  149. js, _ := json.Marshal(currnetNetSpec)
  150. utils.SendJSONResponse(w, string(js))
  151. }
  152. // Get network interface stats, return accumulated rx bits, tx bits and error if any
  153. func GetNetworkInterfaceStats() (int64, int64, error) {
  154. if runtime.GOOS == "windows" {
  155. cmd := exec.Command("wmic", "path", "Win32_PerfRawData_Tcpip_NetworkInterface", "Get", "BytesReceivedPersec,BytesSentPersec,BytesTotalPersec")
  156. out, err := cmd.Output()
  157. if err != nil {
  158. return 0, 0, err
  159. }
  160. //Filter out the first line
  161. lines := strings.Split(strings.ReplaceAll(string(out), "\r\n", "\n"), "\n")
  162. if len(lines) >= 2 && len(lines[1]) >= 0 {
  163. dataLine := lines[1]
  164. for strings.Contains(dataLine, " ") {
  165. dataLine = strings.ReplaceAll(dataLine, " ", " ")
  166. }
  167. dataLine = strings.TrimSpace(dataLine)
  168. info := strings.Split(dataLine, " ")
  169. if len(info) < 3 {
  170. return 0, 0, errors.New("Invalid wmic results")
  171. }
  172. rxString := info[0]
  173. txString := info[1]
  174. rx := int64(0)
  175. tx := int64(0)
  176. if s, err := strconv.ParseInt(rxString, 10, 64); err == nil {
  177. rx = s
  178. }
  179. if s, err := strconv.ParseInt(txString, 10, 64); err == nil {
  180. tx = s
  181. }
  182. //log.Println(rx, tx)
  183. return rx * 4, tx * 4, nil
  184. } else {
  185. //Invalid data
  186. return 0, 0, errors.New("Invalid wmic results")
  187. }
  188. } else if runtime.GOOS == "linux" {
  189. allIfaceRxByteFiles, err := filepath.Glob("/sys/class/net/*/statistics/rx_bytes")
  190. if err != nil {
  191. //Permission denied
  192. return 0, 0, errors.New("Access denied")
  193. }
  194. if len(allIfaceRxByteFiles) == 0 {
  195. return 0, 0, errors.New("No valid iface found")
  196. }
  197. rxSum := int64(0)
  198. txSum := int64(0)
  199. for _, rxByteFile := range allIfaceRxByteFiles {
  200. rxBytes, err := os.ReadFile(rxByteFile)
  201. if err == nil {
  202. rxBytesInt, err := strconv.Atoi(strings.TrimSpace(string(rxBytes)))
  203. if err == nil {
  204. rxSum += int64(rxBytesInt)
  205. }
  206. }
  207. //Usually the tx_bytes file is nearby it. Read it as well
  208. txByteFile := filepath.Join(filepath.Dir(rxByteFile), "tx_bytes")
  209. txBytes, err := os.ReadFile(txByteFile)
  210. if err == nil {
  211. txBytesInt, err := strconv.Atoi(strings.TrimSpace(string(txBytes)))
  212. if err == nil {
  213. txSum += int64(txBytesInt)
  214. }
  215. }
  216. }
  217. //Return value as bits
  218. return rxSum * 8, txSum * 8, nil
  219. } else if runtime.GOOS == "darwin" {
  220. cmd := exec.Command("netstat", "-ib") //get data from netstat -ib
  221. out, err := cmd.Output()
  222. if err != nil {
  223. return 0, 0, err
  224. }
  225. outStrs := string(out) //byte array to multi-line string
  226. for _, outStr := range strings.Split(strings.TrimSuffix(outStrs, "\n"), "\n") { //foreach multi-line string
  227. if strings.HasPrefix(outStr, "en") { //search for ethernet interface
  228. if strings.Contains(outStr, "<Link#") { //search for the link with <Link#?>
  229. outStrSplit := strings.Fields(outStr) //split by white-space
  230. rxSum, errRX := strconv.Atoi(outStrSplit[6]) //received bytes sum
  231. if errRX != nil {
  232. return 0, 0, errRX
  233. }
  234. txSum, errTX := strconv.Atoi(outStrSplit[9]) //transmitted bytes sum
  235. if errTX != nil {
  236. return 0, 0, errTX
  237. }
  238. return int64(rxSum) * 8, int64(txSum) * 8, nil
  239. }
  240. }
  241. }
  242. return 0, 0, nil //no ethernet adapters with en*/<Link#*>
  243. }
  244. return 0, 0, errors.New("Platform not supported")
  245. }