netstat.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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. }
  32. // Get a new network statistic buffers
  33. func NewNetStatBuffer(recordCount int) (*NetStatBuffers, error) {
  34. //Get the initial measurements of netstats
  35. rx, tx, err := GetNetworkInterfaceStats()
  36. if err != nil {
  37. return nil, err
  38. }
  39. currnetNetSpec := RawFlowStat{
  40. RX: rx,
  41. TX: tx,
  42. }
  43. //Flood fill the stats with 0
  44. initialStats := []*FlowStat{}
  45. for i := 0; i < recordCount; i++ {
  46. initialStats = append(initialStats, &FlowStat{
  47. RX: 0,
  48. TX: 0,
  49. })
  50. }
  51. //Setup a timer to get the value from NIC accumulation stats
  52. ticker := time.NewTicker(time.Second)
  53. defer ticker.Stop()
  54. //Setup a stop channel
  55. stopCh := make(chan bool)
  56. thisNetBuffer := NetStatBuffers{
  57. StatRecordCount: recordCount,
  58. PreviousStat: &currnetNetSpec,
  59. Stats: initialStats,
  60. StopChan: stopCh,
  61. }
  62. // Update the buffer every second
  63. go func(n *NetStatBuffers) {
  64. for {
  65. select {
  66. case <-stopCh:
  67. return
  68. case <-ticker.C:
  69. // Get the latest network interface stats
  70. rx, tx, err := GetNetworkInterfaceStats()
  71. if err != nil {
  72. // Log the error, but don't stop the buffer
  73. log.Printf("Failed to get network interface stats: %v", err)
  74. continue
  75. }
  76. //Calculate the difference between this and last values
  77. drx := rx - n.PreviousStat.RX
  78. dtx := tx - n.PreviousStat.TX
  79. // Push the new stats to the buffer
  80. newStat := &FlowStat{
  81. RX: drx,
  82. TX: dtx,
  83. }
  84. //Set current rx tx as the previous rxtx
  85. n.PreviousStat = &RawFlowStat{
  86. RX: rx,
  87. TX: tx,
  88. }
  89. copy(initialStats, initialStats[1:])
  90. initialStats = append(initialStats, newStat)
  91. }
  92. }
  93. }(&thisNetBuffer)
  94. return &thisNetBuffer, nil
  95. }
  96. func (n *NetStatBuffers) HandleGetBufferedNetworkInterfaceStats(w http.ResponseWriter, r *http.Request) {
  97. js, _ := json.Marshal(n.Stats)
  98. utils.SendJSONResponse(w, string(js))
  99. }
  100. func (n *NetStatBuffers) Close() {
  101. n.StopChan <- true
  102. }
  103. func HandleGetNetworkInterfaceStats(w http.ResponseWriter, r *http.Request) {
  104. rx, tx, err := GetNetworkInterfaceStats()
  105. if err != nil {
  106. utils.SendErrorResponse(w, err.Error())
  107. return
  108. }
  109. currnetNetSpec := struct {
  110. RX int64
  111. TX int64
  112. }{
  113. rx,
  114. tx,
  115. }
  116. js, _ := json.Marshal(currnetNetSpec)
  117. utils.SendJSONResponse(w, string(js))
  118. }
  119. // Get network interface stats, return accumulated rx bits, tx bits and error if any
  120. func GetNetworkInterfaceStats() (int64, int64, error) {
  121. if runtime.GOOS == "windows" {
  122. cmd := exec.Command("wmic", "path", "Win32_PerfRawData_Tcpip_NetworkInterface", "Get", "BytesReceivedPersec,BytesSentPersec,BytesTotalPersec")
  123. out, err := cmd.Output()
  124. if err != nil {
  125. return 0, 0, err
  126. }
  127. //Filter out the first line
  128. lines := strings.Split(strings.ReplaceAll(string(out), "\r\n", "\n"), "\n")
  129. if len(lines) >= 2 && len(lines[1]) >= 0 {
  130. dataLine := lines[1]
  131. for strings.Contains(dataLine, " ") {
  132. dataLine = strings.ReplaceAll(dataLine, " ", " ")
  133. }
  134. dataLine = strings.TrimSpace(dataLine)
  135. info := strings.Split(dataLine, " ")
  136. if len(info) < 3 {
  137. return 0, 0, errors.New("Invalid wmic results")
  138. }
  139. rxString := info[0]
  140. txString := info[1]
  141. rx := int64(0)
  142. tx := int64(0)
  143. if s, err := strconv.ParseInt(rxString, 10, 64); err == nil {
  144. rx = s
  145. }
  146. if s, err := strconv.ParseInt(txString, 10, 64); err == nil {
  147. tx = s
  148. }
  149. //log.Println(rx, tx)
  150. return rx * 4, tx * 4, nil
  151. } else {
  152. //Invalid data
  153. return 0, 0, errors.New("Invalid wmic results")
  154. }
  155. } else if runtime.GOOS == "linux" {
  156. allIfaceRxByteFiles, err := filepath.Glob("/sys/class/net/*/statistics/rx_bytes")
  157. if err != nil {
  158. //Permission denied
  159. return 0, 0, errors.New("Access denied")
  160. }
  161. if len(allIfaceRxByteFiles) == 0 {
  162. return 0, 0, errors.New("No valid iface found")
  163. }
  164. rxSum := int64(0)
  165. txSum := int64(0)
  166. for _, rxByteFile := range allIfaceRxByteFiles {
  167. rxBytes, err := os.ReadFile(rxByteFile)
  168. if err == nil {
  169. rxBytesInt, err := strconv.Atoi(strings.TrimSpace(string(rxBytes)))
  170. if err == nil {
  171. rxSum += int64(rxBytesInt)
  172. }
  173. }
  174. //Usually the tx_bytes file is nearby it. Read it as well
  175. txByteFile := filepath.Join(filepath.Dir(rxByteFile), "tx_bytes")
  176. txBytes, err := os.ReadFile(txByteFile)
  177. if err == nil {
  178. txBytesInt, err := strconv.Atoi(strings.TrimSpace(string(txBytes)))
  179. if err == nil {
  180. txSum += int64(txBytesInt)
  181. }
  182. }
  183. }
  184. //Return value as bits
  185. return rxSum * 8, txSum * 8, nil
  186. } else if runtime.GOOS == "darwin" {
  187. cmd := exec.Command("netstat", "-ib") //get data from netstat -ib
  188. out, err := cmd.Output()
  189. if err != nil {
  190. return 0, 0, err
  191. }
  192. outStrs := string(out) //byte array to multi-line string
  193. for _, outStr := range strings.Split(strings.TrimSuffix(outStrs, "\n"), "\n") { //foreach multi-line string
  194. if strings.HasPrefix(outStr, "en") { //search for ethernet interface
  195. if strings.Contains(outStr, "<Link#") { //search for the link with <Link#?>
  196. outStrSplit := strings.Fields(outStr) //split by white-space
  197. rxSum, errRX := strconv.Atoi(outStrSplit[6]) //received bytes sum
  198. if errRX != nil {
  199. return 0, 0, errRX
  200. }
  201. txSum, errTX := strconv.Atoi(outStrSplit[9]) //transmitted bytes sum
  202. if errTX != nil {
  203. return 0, 0, errTX
  204. }
  205. return int64(rxSum) * 8, int64(txSum) * 8, nil
  206. }
  207. }
  208. }
  209. return 0, 0, nil //no ethernet adapters with en*/<Link#*>
  210. }
  211. return 0, 0, errors.New("Platform not supported")
  212. }