netstat.go 8.9 KB

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