summaryrefslogtreecommitdiffstats
path: root/pss.py
blob: 2e5a88a09dcb2c0c8ae3ea5c48bd6c1ddb9c4422 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
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
129
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
#! /usr/bin/python
# -*- python -*-
# -*- coding: utf-8 -*-
#   Copyright (C) 2009 Red Hat Inc.
#   Written by Arnaldo Carvalho de Melo <acme@redhat.com>
#
#   This application is free software; you can redistribute it and/or
#   modify it under the terms of the GNU General Public License
#   as published by the Free Software Foundation; version 2.
#
#   This application is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#   General Public License for more details.

import getopt, inet_diag, os, procfs, re, socket, sys

version="0.2"

def not_implemented(o):
	print "%s not implemented yet" % o 

state_width = 10
addr_width = 18
serv_width = 7
screen_width = 80
netid_width = 0
( TCP_DB,
  DCCP_DB,
  UDP_DB,
  RAW_DB,
  UNIX_DG_DB,
  UNIX_ST_DB,
  PACKET_DG_DB,
  PACKET_R_DB,
  NETLINK_DB,
  MAX_DB ) = range(10)

ALL_DB = ((1 << MAX_DB) - 1)

def print_ms_timer(s):
	timeout = s.timer_expiration()

	if timeout < 0:
		timeout = 0
	secs = timeout / 1000
	minutes = secs / 60
	secs = secs % 60
	msecs = timeout % 1000
	if minutes:
		msecs = 0
		rc = "%dmin" % minutes
		if minutes > 9:
			secs = 0
	else:
		rc = ""

	if secs:
		if secs > 9:
			msecs = 0
		rc += "%d%s" % (secs, msecs and "." or "sec")

	if msecs:
		rc += "%03dms" % msecs

	return rc

class socket_link:
	def __init__(self, pid, fd):
		self.pid = pid
		self.fd	 = fd

def print_sockets(states, families, socktype, show_options = False, show_mem = False,
		  show_protocol_info = False, show_details = False,
		  show_users = False):
	if show_users:
		ps = procfs.pidstats()
		inode_re = re.compile(r"socket:\[(\d+)\]")
		inodes = {}
		for pid in ps.keys():
			dirname = "/proc/%d/fd" % pid
			try:
				filenames = os.listdir(dirname)
			except: # Process died
				continue
			for fd in filenames:
				pathname = os.path.join(dirname, fd)
				try:
					linkto = os.readlink(pathname)
				except:
					break
				inode_match = inode_re.match(linkto)
				if not inode_match:
					continue
				inode = int(inode_match.group(1))
				sock = socket_link(pid, int(fd))
				if inodes.has_key(inode):
					inodes[inode].append(sock)
				else:
					inodes[inode] = [ sock, ]
	extensions = 0
	if show_mem:
		extensions |= inet_diag.EXT_MEMORY;
	if show_protocol_info:
		extensions |= inet_diag.EXT_PROTOCOL | inet_diag.EXT_CONGESTION;
	idiag = inet_diag.create(states = states, extensions = extensions,
				 socktype = socktype); 
	print "%-*s %-6s %-6s %*s:%-*s %*s:%-*s" % \
	      (state_width, "State",
	       "Recv-Q", "Send-Q",
	       addr_width, "Local Address",
	       serv_width, "Port",
	       addr_width, "Peer Address",
	       serv_width, "Port")
	while True:
		try:
			s = idiag.get()
		except:
			break
		if not (families & (1 << s.family())):
			continue
		print "%-*s %-6d %-6d %*s:%-*d %*s:%-*d " % \
		      (state_width, s.state(),
		       s.receive_queue(), s.write_queue(),
		       addr_width, s.saddr(), serv_width, s.sport(),
		       addr_width, s.daddr(), serv_width, s.dport()),
		if show_options:
			timer = s.timer()
			if timer != "off":
				print "timer:(%s,%s,%d)" % (timer,
							    print_ms_timer(s),
							    s.retransmissions()),
		if show_users:
			inode = s.inode()
			if inodes.has_key(inode):
				print "users:(" + \
				      ",".join(map(lambda sock: '("%s",%d,%d)' % (ps[sock.pid]["stat"]["comm"],
										  sock.pid, sock.fd),
						   inodes[inode])) + ")",

		if show_details:
			uid = s.uid()
			if uid:
				print "uid:%d" % uid,
			print "ino:%d sk:%x" % (s.inode(), s.sock()),

		if show_mem:
			try:
				print "\n\t mem:(r%u,w%u,f%u,t%u)" % \
					(s.receive_queue_memory(),
					 s.write_queue_used_memory(),
					 s.write_queue_memory(),
					 s.forward_alloc()),
			except:
				pass

		if show_protocol_info:
			try:
				options = s.protocol_options()
				if options & inet_diag.PROTO_OPT_TIMESTAMPS:
					print "ts",
				if options & inet_diag.PROTO_OPT_SACK:
					print "sack",
				if options & inet_diag.PROTO_OPT_ECN:
					print "ecn",
				print s.congestion_algorithm(),
				if options & inet_diag.PROTO_OPT_WSCALE:
					print "wscale:%d,%d" % (s.receive_window_scale_shift(),
							        s.send_window_scale_shift()),
			except:
				pass

			try:
				print "rto:%g" % s.rto(),
			except:
				pass

			try:
				print "rtt:%g/%g ato:%g cwnd:%d" % \
					(s.rtt() / 1000.0, s.rttvar() / 1000.0,
					 s.ato() / 1000.0, s.cwnd()),
			except:
				pass

			try:
				ssthresh = s.ssthresh()
				if ssthresh < 0xffff:
					print "ssthresh:%d" % ssthresh,
			except:
				pass

		print

def usage():
	print '''Usage: ss [ OPTIONS ]
       ss [ OPTIONS ] [ FILTER ]
   -h, --help		this message
   -V, --version	output version information
   -n, --numeric	don't resolve service names
   -r, --resolve	resolve host names
   -a, --all		display all sockets
   -l, --listening	display listening sockets
   -o, --options	show timer information
   -e, --extended	show detailed socket information
   -m, --memory		show socket memory usage
   -p, --processes	show process using socket
   -i, --info		show internal TCP information
   -s, --summary	show socket usage summary

   -4, --ipv4		display only IP version 4 sockets
   -6, --ipv6		display only IP version 6 sockets
   -0, --packet		display PACKET sockets
   -t, --tcp		display only TCP sockets
   -u, --udp		display only UDP sockets
   -d, --dccp		display only DCCP sockets
   -w, --raw		display only RAW sockets
   -x, --unix		display only Unix domain sockets
   -f, --family=FAMILY	display sockets of type FAMILY

   -A, --query=QUERY
       QUERY := {all|inet|tcp|udp|raw|unix|packet|netlink}[,QUERY]

   -F, --filter=FILE   read filter information from FILE
       FILTER := [ state TCP-STATE ] [ EXPRESSION ]'''

def main():
	global serv_width, state_width, addr_width, serv_width, \
	       screen_width, netid_width
	try:
		opts, args = getopt.getopt(sys.argv[1:],
					   "hVnraloempis460tudwxf:A:F:",
					   ("help", "version", "numeric",
					    "resolve", "all", "listening",
					    "options", "extended",
					    "memory", "processes", "info",
					    "summary", "ipv4", "ipv6",
					    "packet", "tcp", "udp",
					    "dccp", "raw", "unix",
					    "family=", "query=",
					    "filter="))
	except getopt.GetoptError, err:
		usage()
		print str(err)
		sys.exit(2)

	states = inet_diag.default_states
	families = (1 << socket.AF_INET) | (1 << socket.AF_INET6)
	resolve_ports = True

	if not opts:
		print_sockets(states, families, inet_diag.TCPDIAG_GETSOCK)
		sys.exit(0)

	show_options = False
	show_details = False
	show_mem = False
	show_protocol_info = False
	show_users = False
	dbs = 0

	for o, a in opts:
   		if o in ( "-V", "--version"):
			print version
   		elif o in ( "-n", "--numeric"):
			resolve_ports = False
			serv_width = 5
   		elif o in ( "-r", "--resolve"):
			not_implemented(o)
   		elif o in ( "-a", "--all"):
			states = inet_diag.SS_ALL;
   		elif o in ( "-l", "--listening"):
			states = 1 << inet_diag.SS_LISTEN;
   		elif o in ( "-o", "--options"):
			show_options = True
   		elif o in ( "-e", "--extended"):
			show_options = True
			show_details = True
   		elif o in ( "-m", "--memory"):
			show_mem = True
   		elif o in ( "-p", "--processes"):
			show_users = True
   		elif o in ( "-i", "--info"):
			show_protocol_info = True
   		elif o in ( "-s", "--summary"):
			not_implemented(o)
   		elif o in ( "-4", "--ipv4"):
			families = 1 << socket.AF_INET
   		elif o in ( "-6", "--ipv6"):
			families = 1 << socket.AF_INET6
   		elif o in ( "-0", "--packet"):
			not_implemented(o)
   		elif o in ( "-t", "--tcp"):
			dbs |= (1 << TCP_DB)
   		elif o in ( "-u", "--udp"):
			dbs |= (1 << UDP_DB)
   		elif o in ( "-d", "--dccp"):
			dbs |= (1 << DCCP_DB)
   		elif o in ( "-w", "--raw"):
			dbs |= (1 << RAW_DB)
   		elif o in ( "-x", "--unix"):
			dbs |= (1 << UNIX_DB)
   		elif o in ( "-f", "--family"):
			if a == "inet":
				families = 1 << socket.AF_INET
			elif a == "inet6":
				families = 1 << socket.AF_INET6
   		elif o in ( "-A", "--query"):
			not_implemented(o)
		else:
			usage()
			return

        addrp_width = screen_width
        addrp_width -= netid_width + 1
        addrp_width -= state_width + 1
        addrp_width -= 14
	if addrp_width & 1:
		if netid_width:
			netid_width += 1
		elif state_width:
			state_width += 1

	addrp_width /= 2
	addrp_width -= 1

	if addrp_width < 15 + serv_width + 1:
		addrp_width = 15 + serv_width + 1

	addr_width = addrp_width - serv_width - 1

	if dbs == 0 or dbs & (1 << TCP_DB):
		print_sockets(states, families,
			      inet_diag.TCPDIAG_GETSOCK, show_options,
			      show_mem, show_protocol_info,
			      show_details, show_users)

	if dbs & (1 << DCCP_DB):
		print_sockets(states, families,
			      inet_diag.DCCPDIAG_GETSOCK, show_options,
			      show_mem, show_protocol_info,
			      show_details, show_users)

if __name__ == '__main__':
    main()