netstat.go 6.8 KB

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