net_openbsd.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. //go:build openbsd
  2. // +build openbsd
  3. package net
  4. import (
  5. "context"
  6. "fmt"
  7. "os/exec"
  8. "regexp"
  9. "strconv"
  10. "strings"
  11. "syscall"
  12. "github.com/shirou/gopsutil/v3/internal/common"
  13. )
  14. var portMatch = regexp.MustCompile(`(.*)\.(\d+)$`)
  15. func ParseNetstat(output string, mode string,
  16. iocs map[string]IOCountersStat) error {
  17. lines := strings.Split(output, "\n")
  18. exists := make([]string, 0, len(lines)-1)
  19. columns := 6
  20. if mode == "ind" {
  21. columns = 10
  22. }
  23. for _, line := range lines {
  24. values := strings.Fields(line)
  25. if len(values) < 1 || values[0] == "Name" {
  26. continue
  27. }
  28. if common.StringsHas(exists, values[0]) {
  29. // skip if already get
  30. continue
  31. }
  32. if len(values) < columns {
  33. continue
  34. }
  35. base := 1
  36. // sometimes Address is omitted
  37. if len(values) < columns {
  38. base = 0
  39. }
  40. parsed := make([]uint64, 0, 8)
  41. var vv []string
  42. if mode == "inb" {
  43. vv = []string{
  44. values[base+3], // BytesRecv
  45. values[base+4], // BytesSent
  46. }
  47. } else {
  48. vv = []string{
  49. values[base+3], // Ipkts
  50. values[base+4], // Ierrs
  51. values[base+5], // Opkts
  52. values[base+6], // Oerrs
  53. values[base+8], // Drops
  54. }
  55. }
  56. for _, target := range vv {
  57. if target == "-" {
  58. parsed = append(parsed, 0)
  59. continue
  60. }
  61. t, err := strconv.ParseUint(target, 10, 64)
  62. if err != nil {
  63. return err
  64. }
  65. parsed = append(parsed, t)
  66. }
  67. exists = append(exists, values[0])
  68. n, present := iocs[values[0]]
  69. if !present {
  70. n = IOCountersStat{Name: values[0]}
  71. }
  72. if mode == "inb" {
  73. n.BytesRecv = parsed[0]
  74. n.BytesSent = parsed[1]
  75. } else {
  76. n.PacketsRecv = parsed[0]
  77. n.Errin = parsed[1]
  78. n.PacketsSent = parsed[2]
  79. n.Errout = parsed[3]
  80. n.Dropin = parsed[4]
  81. n.Dropout = parsed[4]
  82. }
  83. iocs[n.Name] = n
  84. }
  85. return nil
  86. }
  87. func IOCounters(pernic bool) ([]IOCountersStat, error) {
  88. return IOCountersWithContext(context.Background(), pernic)
  89. }
  90. func IOCountersWithContext(ctx context.Context, pernic bool) ([]IOCountersStat, error) {
  91. netstat, err := exec.LookPath("netstat")
  92. if err != nil {
  93. return nil, err
  94. }
  95. out, err := invoke.CommandWithContext(ctx, netstat, "-inb")
  96. if err != nil {
  97. return nil, err
  98. }
  99. out2, err := invoke.CommandWithContext(ctx, netstat, "-ind")
  100. if err != nil {
  101. return nil, err
  102. }
  103. iocs := make(map[string]IOCountersStat)
  104. lines := strings.Split(string(out), "\n")
  105. ret := make([]IOCountersStat, 0, len(lines)-1)
  106. err = ParseNetstat(string(out), "inb", iocs)
  107. if err != nil {
  108. return nil, err
  109. }
  110. err = ParseNetstat(string(out2), "ind", iocs)
  111. if err != nil {
  112. return nil, err
  113. }
  114. for _, ioc := range iocs {
  115. ret = append(ret, ioc)
  116. }
  117. if pernic == false {
  118. return getIOCountersAll(ret)
  119. }
  120. return ret, nil
  121. }
  122. // IOCountersByFile exists just for compatibility with Linux.
  123. func IOCountersByFile(pernic bool, filename string) ([]IOCountersStat, error) {
  124. return IOCountersByFileWithContext(context.Background(), pernic, filename)
  125. }
  126. func IOCountersByFileWithContext(ctx context.Context, pernic bool, filename string) ([]IOCountersStat, error) {
  127. return IOCounters(pernic)
  128. }
  129. func FilterCounters() ([]FilterStat, error) {
  130. return FilterCountersWithContext(context.Background())
  131. }
  132. func FilterCountersWithContext(ctx context.Context) ([]FilterStat, error) {
  133. return nil, common.ErrNotImplementedError
  134. }
  135. func ConntrackStats(percpu bool) ([]ConntrackStat, error) {
  136. return ConntrackStatsWithContext(context.Background(), percpu)
  137. }
  138. func ConntrackStatsWithContext(ctx context.Context, percpu bool) ([]ConntrackStat, error) {
  139. return nil, common.ErrNotImplementedError
  140. }
  141. // NetProtoCounters returns network statistics for the entire system
  142. // If protocols is empty then all protocols are returned, otherwise
  143. // just the protocols in the list are returned.
  144. // Not Implemented for OpenBSD
  145. func ProtoCounters(protocols []string) ([]ProtoCountersStat, error) {
  146. return ProtoCountersWithContext(context.Background(), protocols)
  147. }
  148. func ProtoCountersWithContext(ctx context.Context, protocols []string) ([]ProtoCountersStat, error) {
  149. return nil, common.ErrNotImplementedError
  150. }
  151. func parseNetstatLine(line string) (ConnectionStat, error) {
  152. f := strings.Fields(line)
  153. if len(f) < 5 {
  154. return ConnectionStat{}, fmt.Errorf("wrong line,%s", line)
  155. }
  156. var netType, netFamily uint32
  157. switch f[0] {
  158. case "tcp":
  159. netType = syscall.SOCK_STREAM
  160. netFamily = syscall.AF_INET
  161. case "udp":
  162. netType = syscall.SOCK_DGRAM
  163. netFamily = syscall.AF_INET
  164. case "tcp6":
  165. netType = syscall.SOCK_STREAM
  166. netFamily = syscall.AF_INET6
  167. case "udp6":
  168. netType = syscall.SOCK_DGRAM
  169. netFamily = syscall.AF_INET6
  170. default:
  171. return ConnectionStat{}, fmt.Errorf("unknown type, %s", f[0])
  172. }
  173. laddr, raddr, err := parseNetstatAddr(f[3], f[4], netFamily)
  174. if err != nil {
  175. return ConnectionStat{}, fmt.Errorf("failed to parse netaddr, %s %s", f[3], f[4])
  176. }
  177. n := ConnectionStat{
  178. Fd: uint32(0), // not supported
  179. Family: uint32(netFamily),
  180. Type: uint32(netType),
  181. Laddr: laddr,
  182. Raddr: raddr,
  183. Pid: int32(0), // not supported
  184. }
  185. if len(f) == 6 {
  186. n.Status = f[5]
  187. }
  188. return n, nil
  189. }
  190. func parseNetstatAddr(local string, remote string, family uint32) (laddr Addr, raddr Addr, err error) {
  191. parse := func(l string) (Addr, error) {
  192. matches := portMatch.FindStringSubmatch(l)
  193. if matches == nil {
  194. return Addr{}, fmt.Errorf("wrong addr, %s", l)
  195. }
  196. host := matches[1]
  197. port := matches[2]
  198. if host == "*" {
  199. switch family {
  200. case syscall.AF_INET:
  201. host = "0.0.0.0"
  202. case syscall.AF_INET6:
  203. host = "::"
  204. default:
  205. return Addr{}, fmt.Errorf("unknown family, %d", family)
  206. }
  207. }
  208. lport, err := strconv.Atoi(port)
  209. if err != nil {
  210. return Addr{}, err
  211. }
  212. return Addr{IP: host, Port: uint32(lport)}, nil
  213. }
  214. laddr, err = parse(local)
  215. if remote != "*.*" { // remote addr exists
  216. raddr, err = parse(remote)
  217. if err != nil {
  218. return laddr, raddr, err
  219. }
  220. }
  221. return laddr, raddr, err
  222. }
  223. // Return a list of network connections opened.
  224. func Connections(kind string) ([]ConnectionStat, error) {
  225. return ConnectionsWithContext(context.Background(), kind)
  226. }
  227. func ConnectionsWithContext(ctx context.Context, kind string) ([]ConnectionStat, error) {
  228. var ret []ConnectionStat
  229. args := []string{"-na"}
  230. switch strings.ToLower(kind) {
  231. default:
  232. fallthrough
  233. case "":
  234. fallthrough
  235. case "all":
  236. fallthrough
  237. case "inet":
  238. // nothing to add
  239. case "inet4":
  240. args = append(args, "-finet")
  241. case "inet6":
  242. args = append(args, "-finet6")
  243. case "tcp":
  244. args = append(args, "-ptcp")
  245. case "tcp4":
  246. args = append(args, "-ptcp", "-finet")
  247. case "tcp6":
  248. args = append(args, "-ptcp", "-finet6")
  249. case "udp":
  250. args = append(args, "-pudp")
  251. case "udp4":
  252. args = append(args, "-pudp", "-finet")
  253. case "udp6":
  254. args = append(args, "-pudp", "-finet6")
  255. case "unix":
  256. return ret, common.ErrNotImplementedError
  257. }
  258. netstat, err := exec.LookPath("netstat")
  259. if err != nil {
  260. return nil, err
  261. }
  262. out, err := invoke.CommandWithContext(ctx, netstat, args...)
  263. if err != nil {
  264. return nil, err
  265. }
  266. lines := strings.Split(string(out), "\n")
  267. for _, line := range lines {
  268. if !(strings.HasPrefix(line, "tcp") || strings.HasPrefix(line, "udp")) {
  269. continue
  270. }
  271. n, err := parseNetstatLine(line)
  272. if err != nil {
  273. continue
  274. }
  275. ret = append(ret, n)
  276. }
  277. return ret, nil
  278. }