net_linux.go 13.5 KB
Newer Older
1 2
// +build linux

S
Shirou WAKAYAMA 已提交
3
package net
4 5

import (
6
	"encoding/hex"
7
	"errors"
8 9 10 11
	"fmt"
	"io/ioutil"
	"net"
	"os"
12
	"strconv"
13
	"strings"
14
	"syscall"
W
WAKAYAMA shirou 已提交
15

16
	"github.com/shirou/gopsutil/internal/common"
17 18
)

19 20 21 22 23
// NetIOCounters returnes network I/O statistics for every network
// interface installed on the system.  If pernic argument is false,
// return only sum of all information (which name is 'all'). If true,
// every network interface installed on the system is returned
// separately.
24
func NetIOCounters(pernic bool) ([]NetIOCountersStat, error) {
25
	filename := common.HostProc("net/dev")
26 27 28 29
	return NetIOCountersByFile(pernic, filename)
}

func NetIOCountersByFile(pernic bool, filename string) ([]NetIOCountersStat, error) {
W
WAKAYAMA shirou 已提交
30
	lines, err := common.ReadLines(filename)
31
	if err != nil {
32
		return nil, err
33 34 35 36
	}

	statlen := len(lines) - 1

S
Shirou WAKAYAMA 已提交
37
	ret := make([]NetIOCountersStat, 0, statlen)
38 39

	for _, line := range lines[2:] {
40 41 42 43 44 45
		parts := strings.SplitN(line, ":", 2)
		if len(parts) != 2 {
			continue
		}
		interfaceName := strings.TrimSpace(parts[0])
		if interfaceName == "" {
46 47
			continue
		}
48

49 50
		fields := strings.Fields(strings.TrimSpace(parts[1]))
		bytesRecv, err := strconv.ParseUint(fields[0], 10, 64)
51 52 53
		if err != nil {
			return ret, err
		}
54
		packetsRecv, err := strconv.ParseUint(fields[1], 10, 64)
55 56 57
		if err != nil {
			return ret, err
		}
58
		errIn, err := strconv.ParseUint(fields[2], 10, 64)
59 60 61
		if err != nil {
			return ret, err
		}
62
		dropIn, err := strconv.ParseUint(fields[3], 10, 64)
63 64 65
		if err != nil {
			return ret, err
		}
66
		bytesSent, err := strconv.ParseUint(fields[8], 10, 64)
67 68 69
		if err != nil {
			return ret, err
		}
70
		packetsSent, err := strconv.ParseUint(fields[9], 10, 64)
71 72 73
		if err != nil {
			return ret, err
		}
74
		errOut, err := strconv.ParseUint(fields[10], 10, 64)
75 76 77
		if err != nil {
			return ret, err
		}
78
		dropOut, err := strconv.ParseUint(fields[13], 10, 64)
79 80 81 82
		if err != nil {
			return ret, err
		}

S
Shirou WAKAYAMA 已提交
83
		nic := NetIOCountersStat{
84
			Name:        interfaceName,
85 86 87 88 89 90 91 92
			BytesRecv:   bytesRecv,
			PacketsRecv: packetsRecv,
			Errin:       errIn,
			Dropin:      dropIn,
			BytesSent:   bytesSent,
			PacketsSent: packetsSent,
			Errout:      errOut,
			Dropout:     dropOut,
93 94 95
		}
		ret = append(ret, nic)
	}
96 97 98 99 100

	if pernic == false {
		return getNetIOCountersAll(ret)
	}

101 102
	return ret, nil
}
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128

var netProtocols = []string{
	"ip",
	"icmp",
	"icmpmsg",
	"tcp",
	"udp",
	"udplite",
}

// NetProtoCounters returns network statistics for the entire system
// If protocols is empty then all protocols are returned, otherwise
// just the protocols in the list are returned.
// Available protocols:
//   ip,icmp,icmpmsg,tcp,udp,udplite
func NetProtoCounters(protocols []string) ([]NetProtoCountersStat, error) {
	if len(protocols) == 0 {
		protocols = netProtocols
	}

	stats := make([]NetProtoCountersStat, 0, len(protocols))
	protos := make(map[string]bool, len(protocols))
	for _, p := range protocols {
		protos[p] = true
	}

129
	filename := common.HostProc("net/snmp")
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
	lines, err := common.ReadLines(filename)
	if err != nil {
		return nil, err
	}

	linecount := len(lines)
	for i := 0; i < linecount; i++ {
		line := lines[i]
		r := strings.IndexRune(line, ':')
		if r == -1 {
			return nil, errors.New(filename + " is not fomatted correctly, expected ':'.")
		}
		proto := strings.ToLower(line[:r])
		if !protos[proto] {
			// skip protocol and data line
			i++
			continue
		}

		// Read header line
		statNames := strings.Split(line[r+2:], " ")

		// Read data line
		i++
		statValues := strings.Split(lines[i][r+2:], " ")
		if len(statNames) != len(statValues) {
			return nil, errors.New(filename + " is not fomatted correctly, expected same number of columns.")
		}
		stat := NetProtoCountersStat{
			Protocol: proto,
			Stats:    make(map[string]int64, len(statNames)),
		}
		for j := range statNames {
			value, err := strconv.ParseInt(statValues[j], 10, 64)
			if err != nil {
				return nil, err
			}
			stat.Stats[statNames[j]] = value
		}
		stats = append(stats, stat)
	}
	return stats, nil
}
173 174 175 176

// NetFilterCounters returns iptables conntrack statistics
// the currently in use conntrack count and the max.
// If the file does not exist or is invalid it will return nil.
J
James Lamb 已提交
177
func NetFilterCounters() ([]NetFilterStat, error) {
178 179
	countfile := common.HostProc("sys/net/netfilter/nf_conntrack_count")
	maxfile := common.HostProc("sys/net/netfilter/nf_conntrack_max")
J
James Lamb 已提交
180 181 182

	count, err := common.ReadInts(countfile)

183 184 185
	if err != nil {
		return nil, err
	}
J
James Lamb 已提交
186
	stats := make([]NetFilterStat, 0, 1)
187

J
James Lamb 已提交
188 189
	max, err := common.ReadInts(maxfile)
	if err != nil {
190 191
		return nil, err
	}
J
James Lamb 已提交
192 193 194 195

	payload := NetFilterStat{
		ConnTrackCount: count[0],
		ConnTrackMax:   max[0],
196
	}
J
James Lamb 已提交
197 198

	stats = append(stats, payload)
199 200
	return stats, nil
}
201

202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
// http://students.mimuw.edu.pl/lxr/source/include/net/tcp_states.h
var TCPStatuses = map[string]string{
	"01": "ESTABLISHED",
	"02": "SYN_SENT",
	"03": "SYN_RECV",
	"04": "FIN_WAIT1",
	"05": "FIN_WAIT2",
	"06": "TIME_WAIT",
	"07": "CLOSE",
	"08": "CLOSE_WAIT",
	"09": "LAST_ACK",
	"0A": "LISTEN",
	"0B": "CLOSING",
}

217
type netConnectionKindType struct {
218 219
	family   uint32
	sockType uint32
220
	filename string
221 222
}

223
var kindTCP4 = netConnectionKindType{
224 225
	family:   syscall.AF_INET,
	sockType: syscall.SOCK_STREAM,
226
	filename: "tcp",
227
}
228
var kindTCP6 = netConnectionKindType{
229 230
	family:   syscall.AF_INET6,
	sockType: syscall.SOCK_STREAM,
231
	filename: "tcp6",
232
}
233
var kindUDP4 = netConnectionKindType{
234 235
	family:   syscall.AF_INET,
	sockType: syscall.SOCK_DGRAM,
236
	filename: "udp",
237
}
238
var kindUDP6 = netConnectionKindType{
239 240
	family:   syscall.AF_INET6,
	sockType: syscall.SOCK_DGRAM,
241
	filename: "udp6",
242
}
243
var kindUNIX = netConnectionKindType{
244 245
	family:   syscall.AF_UNIX,
	filename: "unix",
246 247 248
}

var netConnectionKindMap = map[string][]netConnectionKindType{
249 250 251 252 253 254 255 256 257 258 259
	"all":   []netConnectionKindType{kindTCP4, kindTCP6, kindUDP4, kindUDP6, kindUNIX},
	"tcp":   []netConnectionKindType{kindTCP4, kindTCP6},
	"tcp4":  []netConnectionKindType{kindTCP4},
	"tcp6":  []netConnectionKindType{kindTCP6},
	"udp":   []netConnectionKindType{kindUDP4, kindUDP6},
	"udp4":  []netConnectionKindType{kindUDP4},
	"udp6":  []netConnectionKindType{kindUDP6},
	"unix":  []netConnectionKindType{kindUNIX},
	"inet":  []netConnectionKindType{kindTCP4, kindTCP6, kindUDP4, kindUDP6},
	"inet4": []netConnectionKindType{kindTCP4, kindUDP4},
	"inet6": []netConnectionKindType{kindTCP6, kindUDP6},
260 261 262 263
}

type inodeMap struct {
	pid int32
264
	fd  uint32
265 266
}

267 268 269 270 271 272 273 274 275
type connTmp struct {
	fd       uint32
	family   uint32
	sockType uint32
	laddr    Addr
	raddr    Addr
	status   string
	pid      int32
	boundPid int32
276
	path     string
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
}

// Return a list of network connections opened.
func NetConnections(kind string) ([]NetConnectionStat, error) {
	return NetConnectionsPid(kind, 0)
}

// Return a list of network connections opened by a process.
func NetConnectionsPid(kind string, pid int32) ([]NetConnectionStat, error) {
	tmap, ok := netConnectionKindMap[kind]
	if !ok {
		return nil, fmt.Errorf("invalid kind, %s", kind)
	}
	root := common.HostProc()
	var err error
	var inodes map[string][]inodeMap
	if pid == 0 {
		inodes, err = getProcInodesAll(root)
	} else {
		inodes, err = getProcInodes(root, pid)
297 298 299 300
		if len(inodes) == 0 {
			// no connection for the pid
			return []NetConnectionStat{}, nil
		}
301 302 303 304 305
	}
	if err != nil {
		return nil, fmt.Errorf("cound not get pid(s), %d", pid)
	}

306
	dupCheckMap := make(map[string]bool)
307
	var ret []NetConnectionStat
308

309
	for _, t := range tmap {
310
		var path string
311
		var ls []connTmp
312
		path = fmt.Sprintf("%s/net/%s", root, t.filename)
313 314
		switch t.family {
		case syscall.AF_INET:
315
			fallthrough
316 317 318
		case syscall.AF_INET6:
			ls, err = processInet(path, t, inodes, pid)
		case syscall.AF_UNIX:
319
			ls, err = processUnix(path, t, inodes, pid)
320 321 322 323
		}
		if err != nil {
			return nil, err
		}
324
		for _, c := range ls {
325
			conn := NetConnectionStat{
326
				Fd:     c.fd,
327 328
				Family: c.family,
				Type:   c.sockType,
329 330 331 332
				Laddr:  c.laddr,
				Raddr:  c.raddr,
				Status: c.status,
				Pid:    c.pid,
333 334 335 336 337 338
			}
			if c.pid == 0 {
				conn.Pid = c.boundPid
			} else {
				conn.Pid = c.pid
			}
339 340 341 342 343 344 345
			// check duplicate using JSON format
			json := conn.String()
			_, exists := dupCheckMap[json]
			if !exists {
				ret = append(ret, conn)
				dupCheckMap[json] = true
			}
346 347 348 349
		}

	}

350
	return ret, nil
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
}

// getProcInodes returnes fd of the pid.
func getProcInodes(root string, pid int32) (map[string][]inodeMap, error) {
	ret := make(map[string][]inodeMap)

	dir := fmt.Sprintf("%s/%d/fd", root, pid)
	files, err := ioutil.ReadDir(dir)
	if err != nil {
		return ret, nil
	}
	for _, fd := range files {
		inodePath := fmt.Sprintf("%s/%d/fd/%s", root, pid, fd.Name())

		inode, err := os.Readlink(inodePath)
		if err != nil {
			continue
		}
369 370
		if !strings.HasPrefix(inode, "socket:[") {
			continue
371
		}
372 373 374
		// the process is using a socket
		l := len(inode)
		inode = inode[8 : l-1]
375 376 377 378
		_, ok := ret[inode]
		if !ok {
			ret[inode] = make([]inodeMap, 0)
		}
379 380 381 382
		fd, err := strconv.Atoi(fd.Name())
		if err != nil {
			continue
		}
383 384 385

		i := inodeMap{
			pid: pid,
386
			fd:  uint32(fd),
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
		}
		ret[inode] = append(ret[inode], i)
	}
	return ret, nil
}

// Pids retunres all pids.
// Note: this is a copy of process_linux.Pids()
// FIXME: Import process occures import cycle.
// move to common made other platform breaking. Need consider.
func Pids() ([]int32, error) {
	var ret []int32

	d, err := os.Open(common.HostProc())
	if err != nil {
		return nil, err
	}
	defer d.Close()

	fnames, err := d.Readdirnames(-1)
	if err != nil {
		return nil, err
	}
	for _, fname := range fnames {
		pid, err := strconv.ParseInt(fname, 10, 32)
		if err != nil {
			// if not numeric name, just skip
			continue
		}
		ret = append(ret, int32(pid))
	}

	return ret, nil
}

func getProcInodesAll(root string) (map[string][]inodeMap, error) {
	pids, err := Pids()
	if err != nil {
		return nil, err
	}
	ret := make(map[string][]inodeMap)

	for _, pid := range pids {
		t, err := getProcInodes(root, pid)
		if err != nil {
			return ret, err
		}
		if len(t) == 0 {
			continue
		}
		// TODO: update ret.
438
		ret = updateMap(ret, t)
439 440 441 442 443 444 445 446
	}
	return ret, nil
}

// decodeAddress decode addresse represents addr in proc/net/*
// ex:
// "0500000A:0016" -> "10.0.0.5", 22
// "0085002452100113070057A13F025401:0035" -> "2400:8500:1301:1052:a157:7:154:23f", 53
447
func decodeAddress(family uint32, src string) (Addr, error) {
448 449
	t := strings.Split(src, ":")
	if len(t) != 2 {
450
		return Addr{}, fmt.Errorf("does not contain port, %s", src)
451 452 453 454
	}
	addr := t[0]
	port, err := strconv.ParseInt("0x"+t[1], 0, 64)
	if err != nil {
455
		return Addr{}, fmt.Errorf("invalid port, %s", src)
456 457 458
	}
	decoded, err := hex.DecodeString(addr)
	if err != nil {
459
		return Addr{}, fmt.Errorf("decode error, %s", err)
460 461 462 463 464 465 466 467
	}
	var ip net.IP
	// Assumes this is little_endian
	if family == syscall.AF_INET {
		ip = net.IP(Reverse(decoded))
	} else { // IPv6
		ip, err = parseIPv6HexString(decoded)
		if err != nil {
468
			return Addr{}, err
469 470
		}
	}
471 472 473 474
	return Addr{
		IP:   ip.String(),
		Port: uint32(port),
	}, nil
475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
}

// Reverse reverses array of bytes.
func Reverse(s []byte) []byte {
	for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
		s[i], s[j] = s[j], s[i]
	}
	return s
}

// parseIPv6HexString parse array of bytes to IPv6 string
func parseIPv6HexString(src []byte) (net.IP, error) {
	if len(src) != 16 {
		return nil, fmt.Errorf("invalid IPv6 string")
	}

	buf := make([]byte, 0, 16)
	for i := 0; i < len(src); i += 4 {
		r := Reverse(src[i : i+4])
		buf = append(buf, r...)
	}
	return net.IP(buf), nil
}

499
func processInet(file string, kind netConnectionKindType, inodes map[string][]inodeMap, filterPid int32) ([]connTmp, error) {
500 501 502

	if strings.HasSuffix(file, "6") && !common.PathExists(file) {
		// IPv6 not supported, return empty.
503
		return []connTmp{}, nil
504 505 506 507 508
	}
	lines, err := common.ReadLines(file)
	if err != nil {
		return nil, err
	}
509
	var ret []connTmp
510
	// skip first line
511 512 513 514 515 516 517 518
	for _, line := range lines[1:] {
		l := strings.Fields(line)
		if len(l) < 10 {
			continue
		}
		laddr := l[1]
		raddr := l[2]
		status := l[3]
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
		inode := l[9]
		pid := int32(0)
		fd := uint32(0)
		i, exists := inodes[inode]
		if exists {
			pid = i[0].pid
			fd = i[0].fd
		}
		if filterPid > 0 && filterPid != pid {
			continue
		}
		if kind.sockType == syscall.SOCK_STREAM {
			status = TCPStatuses[status]
		} else {
			status = "NONE"
		}
		la, err := decodeAddress(kind.family, laddr)
		if err != nil {
			continue
		}
		ra, err := decodeAddress(kind.family, raddr)
540 541 542
		if err != nil {
			continue
		}
543 544 545 546 547 548 549 550 551 552

		ret = append(ret, connTmp{
			fd:       fd,
			family:   kind.family,
			sockType: kind.sockType,
			laddr:    la,
			raddr:    ra,
			status:   status,
			pid:      pid,
		})
553 554
	}

555
	return ret, nil
556 557
}

558
func processUnix(file string, kind netConnectionKindType, inodes map[string][]inodeMap, filterPid int32) ([]connTmp, error) {
559 560 561 562 563 564 565 566 567
	lines, err := common.ReadLines(file)
	if err != nil {
		return nil, err
	}

	var ret []connTmp
	// skip first line
	for _, line := range lines[1:] {
		tokens := strings.Fields(line)
568
		if len(tokens) < 6 {
569 570 571 572
			continue
		}
		st, err := strconv.Atoi(tokens[4])
		if err != nil {
573
			return nil, err
574 575 576 577 578 579 580
		}

		inode := tokens[6]

		var pairs []inodeMap
		pairs, exists := inodes[inode]
		if !exists {
581 582 583
			pairs = []inodeMap{
				inodeMap{},
			}
584 585 586 587 588 589 590 591 592 593
		}
		for _, pair := range pairs {
			if filterPid > 0 && filterPid != pair.pid {
				continue
			}
			var path string
			if len(tokens) == 8 {
				path = tokens[len(tokens)-1]
			}
			ret = append(ret, connTmp{
594
				fd:       pair.fd,
595 596
				family:   kind.family,
				sockType: uint32(st),
597 598 599 600 601 602
				laddr: Addr{
					IP: path,
				},
				pid:    pair.pid,
				status: "NONE",
				path:   path,
603 604 605
			})
		}
	}
606

607
	return ret, nil
608
}
609

610 611 612 613 614 615 616 617 618 619
func updateMap(src map[string][]inodeMap, add map[string][]inodeMap) map[string][]inodeMap {
	for key, value := range add {
		a, exists := src[key]
		if !exists {
			src[key] = value
			continue
		}
		src[key] = append(a, value...)
	}
	return src
620
}