networkBytes_linux.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. * Copyright (c) 2023, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package server
  20. import (
  21. "bufio"
  22. "os"
  23. "strconv"
  24. "strings"
  25. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  26. )
  27. func getNetworkBytesTransferred() (int64, int64, error) {
  28. file, err := os.Open("/proc/net/dev")
  29. if err != nil {
  30. return 0, 0, errors.Trace(err)
  31. }
  32. defer file.Close()
  33. var totalNetworkBytesReceived, totalNetworkBytesSent int64
  34. scanner := bufio.NewScanner(file)
  35. // Parsing based on the formats used by dev_seq_show and dev_seq_printf_stats:
  36. // https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/net/core/net-procfs.c#n105
  37. for scanner.Scan() {
  38. line := scanner.Text()
  39. fields := strings.Fields(line)
  40. // Skip header lines, loopback interface and tunnel interface
  41. if len(fields) < 17 || fields[0] == "Inter-|" || fields[0] == "face" ||
  42. strings.HasPrefix(fields[0], "lo") || strings.HasPrefix(fields[0], "tun") ||
  43. strings.HasPrefix(fields[0], "ipsec") || strings.HasPrefix(fields[0], "ppp") {
  44. continue
  45. }
  46. // Parse received bytes
  47. receivedNetworkBytes, err := strconv.ParseInt(fields[1], 10, 64)
  48. if err != nil {
  49. return 0, 0, errors.Trace(err)
  50. }
  51. // Parse sent bytes
  52. sentNetworkBytes, err := strconv.ParseInt(fields[9], 10, 64)
  53. if err != nil {
  54. return 0, 0, errors.Trace(err)
  55. }
  56. totalNetworkBytesReceived += receivedNetworkBytes
  57. totalNetworkBytesSent += sentNetworkBytes
  58. }
  59. if scanner.Err() != nil {
  60. return 0, 0, errors.Trace(scanner.Err())
  61. }
  62. return totalNetworkBytesReceived, totalNetworkBytesSent, nil
  63. }