test_connections.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. """Tests for psutil.net_connections() and Process.net_connections() APIs."""
  6. import os
  7. import socket
  8. import textwrap
  9. from contextlib import closing
  10. from socket import AF_INET
  11. from socket import AF_INET6
  12. from socket import SOCK_DGRAM
  13. from socket import SOCK_STREAM
  14. import psutil
  15. from psutil import FREEBSD
  16. from psutil import LINUX
  17. from psutil import MACOS
  18. from psutil import NETBSD
  19. from psutil import OPENBSD
  20. from psutil import POSIX
  21. from psutil import SUNOS
  22. from psutil import WINDOWS
  23. from psutil._common import supports_ipv6
  24. from psutil.tests import AF_UNIX
  25. from psutil.tests import HAS_NET_CONNECTIONS_UNIX
  26. from psutil.tests import SKIP_SYSCONS
  27. from psutil.tests import PsutilTestCase
  28. from psutil.tests import bind_socket
  29. from psutil.tests import bind_unix_socket
  30. from psutil.tests import check_connection_ntuple
  31. from psutil.tests import create_sockets
  32. from psutil.tests import filter_proc_net_connections
  33. from psutil.tests import pytest
  34. from psutil.tests import reap_children
  35. from psutil.tests import retry_on_failure
  36. from psutil.tests import skip_on_access_denied
  37. from psutil.tests import tcp_socketpair
  38. from psutil.tests import unix_socketpair
  39. from psutil.tests import wait_for_file
  40. SOCK_SEQPACKET = getattr(socket, "SOCK_SEQPACKET", object())
  41. def this_proc_net_connections(kind):
  42. cons = psutil.Process().net_connections(kind=kind)
  43. if kind in {"all", "unix"}:
  44. return filter_proc_net_connections(cons)
  45. return cons
  46. @pytest.mark.xdist_group(name="serial")
  47. class ConnectionTestCase(PsutilTestCase):
  48. def setUp(self):
  49. assert this_proc_net_connections(kind='all') == []
  50. def tearDown(self):
  51. # Make sure we closed all resources.
  52. assert this_proc_net_connections(kind='all') == []
  53. def compare_procsys_connections(self, pid, proc_cons, kind='all'):
  54. """Given a process PID and its list of connections compare
  55. those against system-wide connections retrieved via
  56. psutil.net_connections.
  57. """
  58. try:
  59. sys_cons = psutil.net_connections(kind=kind)
  60. except psutil.AccessDenied:
  61. # On MACOS, system-wide connections are retrieved by iterating
  62. # over all processes
  63. if MACOS:
  64. return
  65. else:
  66. raise
  67. # Filter for this proc PID and exlucde PIDs from the tuple.
  68. sys_cons = [c[:-1] for c in sys_cons if c.pid == pid]
  69. sys_cons.sort()
  70. proc_cons.sort()
  71. assert proc_cons == sys_cons
  72. class TestBasicOperations(ConnectionTestCase):
  73. @pytest.mark.skipif(SKIP_SYSCONS, reason="requires root")
  74. def test_system(self):
  75. with create_sockets():
  76. for conn in psutil.net_connections(kind='all'):
  77. check_connection_ntuple(conn)
  78. def test_process(self):
  79. with create_sockets():
  80. for conn in this_proc_net_connections(kind='all'):
  81. check_connection_ntuple(conn)
  82. def test_invalid_kind(self):
  83. with pytest.raises(ValueError):
  84. this_proc_net_connections(kind='???')
  85. with pytest.raises(ValueError):
  86. psutil.net_connections(kind='???')
  87. @pytest.mark.xdist_group(name="serial")
  88. class TestUnconnectedSockets(ConnectionTestCase):
  89. """Tests sockets which are open but not connected to anything."""
  90. def get_conn_from_sock(self, sock):
  91. cons = this_proc_net_connections(kind='all')
  92. smap = {c.fd: c for c in cons}
  93. if NETBSD or FREEBSD:
  94. # NetBSD opens a UNIX socket to /var/log/run
  95. # so there may be more connections.
  96. return smap[sock.fileno()]
  97. else:
  98. assert len(cons) == 1
  99. if cons[0].fd != -1:
  100. assert smap[sock.fileno()].fd == sock.fileno()
  101. return cons[0]
  102. def check_socket(self, sock):
  103. """Given a socket, makes sure it matches the one obtained
  104. via psutil. It assumes this process created one connection
  105. only (the one supposed to be checked).
  106. """
  107. conn = self.get_conn_from_sock(sock)
  108. check_connection_ntuple(conn)
  109. # fd, family, type
  110. if conn.fd != -1:
  111. assert conn.fd == sock.fileno()
  112. assert conn.family == sock.family
  113. # see: http://bugs.python.org/issue30204
  114. assert conn.type == sock.getsockopt(socket.SOL_SOCKET, socket.SO_TYPE)
  115. # local address
  116. laddr = sock.getsockname()
  117. if not laddr and isinstance(laddr, bytes):
  118. # See: http://bugs.python.org/issue30205
  119. laddr = laddr.decode()
  120. if sock.family == AF_INET6:
  121. laddr = laddr[:2]
  122. assert conn.laddr == laddr
  123. # XXX Solaris can't retrieve system-wide UNIX sockets
  124. if sock.family == AF_UNIX and HAS_NET_CONNECTIONS_UNIX:
  125. cons = this_proc_net_connections(kind='all')
  126. self.compare_procsys_connections(os.getpid(), cons, kind='all')
  127. return conn
  128. def test_tcp_v4(self):
  129. addr = ("127.0.0.1", 0)
  130. with closing(bind_socket(AF_INET, SOCK_STREAM, addr=addr)) as sock:
  131. conn = self.check_socket(sock)
  132. assert conn.raddr == ()
  133. assert conn.status == psutil.CONN_LISTEN
  134. @pytest.mark.skipif(not supports_ipv6(), reason="IPv6 not supported")
  135. def test_tcp_v6(self):
  136. addr = ("::1", 0)
  137. with closing(bind_socket(AF_INET6, SOCK_STREAM, addr=addr)) as sock:
  138. conn = self.check_socket(sock)
  139. assert conn.raddr == ()
  140. assert conn.status == psutil.CONN_LISTEN
  141. def test_udp_v4(self):
  142. addr = ("127.0.0.1", 0)
  143. with closing(bind_socket(AF_INET, SOCK_DGRAM, addr=addr)) as sock:
  144. conn = self.check_socket(sock)
  145. assert conn.raddr == ()
  146. assert conn.status == psutil.CONN_NONE
  147. @pytest.mark.skipif(not supports_ipv6(), reason="IPv6 not supported")
  148. def test_udp_v6(self):
  149. addr = ("::1", 0)
  150. with closing(bind_socket(AF_INET6, SOCK_DGRAM, addr=addr)) as sock:
  151. conn = self.check_socket(sock)
  152. assert conn.raddr == ()
  153. assert conn.status == psutil.CONN_NONE
  154. @pytest.mark.skipif(not POSIX, reason="POSIX only")
  155. def test_unix_tcp(self):
  156. testfn = self.get_testfn()
  157. with closing(bind_unix_socket(testfn, type=SOCK_STREAM)) as sock:
  158. conn = self.check_socket(sock)
  159. assert conn.raddr == ""
  160. assert conn.status == psutil.CONN_NONE
  161. @pytest.mark.skipif(not POSIX, reason="POSIX only")
  162. def test_unix_udp(self):
  163. testfn = self.get_testfn()
  164. with closing(bind_unix_socket(testfn, type=SOCK_STREAM)) as sock:
  165. conn = self.check_socket(sock)
  166. assert conn.raddr == ""
  167. assert conn.status == psutil.CONN_NONE
  168. @pytest.mark.xdist_group(name="serial")
  169. class TestConnectedSocket(ConnectionTestCase):
  170. """Test socket pairs which are actually connected to
  171. each other.
  172. """
  173. # On SunOS, even after we close() it, the server socket stays around
  174. # in TIME_WAIT state.
  175. @pytest.mark.skipif(SUNOS, reason="unreliable on SUONS")
  176. def test_tcp(self):
  177. addr = ("127.0.0.1", 0)
  178. assert this_proc_net_connections(kind='tcp4') == []
  179. server, client = tcp_socketpair(AF_INET, addr=addr)
  180. try:
  181. cons = this_proc_net_connections(kind='tcp4')
  182. assert len(cons) == 2
  183. assert cons[0].status == psutil.CONN_ESTABLISHED
  184. assert cons[1].status == psutil.CONN_ESTABLISHED
  185. # May not be fast enough to change state so it stays
  186. # commenteed.
  187. # client.close()
  188. # cons = this_proc_net_connections(kind='all')
  189. # self.assertEqual(len(cons), 1)
  190. # self.assertEqual(cons[0].status, psutil.CONN_CLOSE_WAIT)
  191. finally:
  192. server.close()
  193. client.close()
  194. @pytest.mark.skipif(not POSIX, reason="POSIX only")
  195. def test_unix(self):
  196. testfn = self.get_testfn()
  197. server, client = unix_socketpair(testfn)
  198. try:
  199. cons = this_proc_net_connections(kind='unix')
  200. assert not (cons[0].laddr and cons[0].raddr), cons
  201. assert not (cons[1].laddr and cons[1].raddr), cons
  202. if NETBSD or FREEBSD:
  203. # On NetBSD creating a UNIX socket will cause
  204. # a UNIX connection to /var/run/log.
  205. cons = [c for c in cons if c.raddr != '/var/run/log']
  206. assert len(cons) == 2
  207. if LINUX or FREEBSD or SUNOS or OPENBSD:
  208. # remote path is never set
  209. assert cons[0].raddr == ""
  210. assert cons[1].raddr == ""
  211. # one local address should though
  212. assert testfn == (cons[0].laddr or cons[1].laddr)
  213. else:
  214. # On other systems either the laddr or raddr
  215. # of both peers are set.
  216. assert (cons[0].laddr or cons[1].laddr) == testfn
  217. finally:
  218. server.close()
  219. client.close()
  220. class TestFilters(ConnectionTestCase):
  221. def test_filters(self):
  222. def check(kind, families, types):
  223. for conn in this_proc_net_connections(kind=kind):
  224. assert conn.family in families
  225. assert conn.type in types
  226. if not SKIP_SYSCONS:
  227. for conn in psutil.net_connections(kind=kind):
  228. assert conn.family in families
  229. assert conn.type in types
  230. with create_sockets():
  231. check(
  232. 'all',
  233. [AF_INET, AF_INET6, AF_UNIX],
  234. [SOCK_STREAM, SOCK_DGRAM, SOCK_SEQPACKET],
  235. )
  236. check('inet', [AF_INET, AF_INET6], [SOCK_STREAM, SOCK_DGRAM])
  237. check('inet4', [AF_INET], [SOCK_STREAM, SOCK_DGRAM])
  238. check('tcp', [AF_INET, AF_INET6], [SOCK_STREAM])
  239. check('tcp4', [AF_INET], [SOCK_STREAM])
  240. check('tcp6', [AF_INET6], [SOCK_STREAM])
  241. check('udp', [AF_INET, AF_INET6], [SOCK_DGRAM])
  242. check('udp4', [AF_INET], [SOCK_DGRAM])
  243. check('udp6', [AF_INET6], [SOCK_DGRAM])
  244. if HAS_NET_CONNECTIONS_UNIX:
  245. check(
  246. 'unix',
  247. [AF_UNIX],
  248. [SOCK_STREAM, SOCK_DGRAM, SOCK_SEQPACKET],
  249. )
  250. @skip_on_access_denied(only_if=MACOS)
  251. def test_combos(self):
  252. reap_children()
  253. def check_conn(proc, conn, family, type, laddr, raddr, status, kinds):
  254. all_kinds = (
  255. "all",
  256. "inet",
  257. "inet4",
  258. "inet6",
  259. "tcp",
  260. "tcp4",
  261. "tcp6",
  262. "udp",
  263. "udp4",
  264. "udp6",
  265. )
  266. check_connection_ntuple(conn)
  267. assert conn.family == family
  268. assert conn.type == type
  269. assert conn.laddr == laddr
  270. assert conn.raddr == raddr
  271. assert conn.status == status
  272. for kind in all_kinds:
  273. cons = proc.net_connections(kind=kind)
  274. if kind in kinds:
  275. assert cons != []
  276. else:
  277. assert cons == []
  278. # compare against system-wide connections
  279. # XXX Solaris can't retrieve system-wide UNIX
  280. # sockets.
  281. if HAS_NET_CONNECTIONS_UNIX:
  282. self.compare_procsys_connections(proc.pid, [conn])
  283. tcp_template = textwrap.dedent("""
  284. import socket, time
  285. s = socket.socket({family}, socket.SOCK_STREAM)
  286. s.bind(('{addr}', 0))
  287. s.listen(5)
  288. with open('{testfn}', 'w') as f:
  289. f.write(str(s.getsockname()[:2]))
  290. [time.sleep(0.1) for x in range(100)]
  291. """)
  292. udp_template = textwrap.dedent("""
  293. import socket, time
  294. s = socket.socket({family}, socket.SOCK_DGRAM)
  295. s.bind(('{addr}', 0))
  296. with open('{testfn}', 'w') as f:
  297. f.write(str(s.getsockname()[:2]))
  298. [time.sleep(0.1) for x in range(100)]
  299. """)
  300. # must be relative on Windows
  301. testfile = os.path.basename(self.get_testfn(dir=os.getcwd()))
  302. tcp4_template = tcp_template.format(
  303. family=int(AF_INET), addr="127.0.0.1", testfn=testfile
  304. )
  305. udp4_template = udp_template.format(
  306. family=int(AF_INET), addr="127.0.0.1", testfn=testfile
  307. )
  308. tcp6_template = tcp_template.format(
  309. family=int(AF_INET6), addr="::1", testfn=testfile
  310. )
  311. udp6_template = udp_template.format(
  312. family=int(AF_INET6), addr="::1", testfn=testfile
  313. )
  314. # launch various subprocess instantiating a socket of various
  315. # families and types to enrich psutil results
  316. tcp4_proc = self.pyrun(tcp4_template)
  317. tcp4_addr = eval(wait_for_file(testfile, delete=True))
  318. udp4_proc = self.pyrun(udp4_template)
  319. udp4_addr = eval(wait_for_file(testfile, delete=True))
  320. if supports_ipv6():
  321. tcp6_proc = self.pyrun(tcp6_template)
  322. tcp6_addr = eval(wait_for_file(testfile, delete=True))
  323. udp6_proc = self.pyrun(udp6_template)
  324. udp6_addr = eval(wait_for_file(testfile, delete=True))
  325. else:
  326. tcp6_proc = None
  327. udp6_proc = None
  328. tcp6_addr = None
  329. udp6_addr = None
  330. for p in psutil.Process().children():
  331. cons = p.net_connections()
  332. assert len(cons) == 1
  333. for conn in cons:
  334. # TCP v4
  335. if p.pid == tcp4_proc.pid:
  336. check_conn(
  337. p,
  338. conn,
  339. AF_INET,
  340. SOCK_STREAM,
  341. tcp4_addr,
  342. (),
  343. psutil.CONN_LISTEN,
  344. ("all", "inet", "inet4", "tcp", "tcp4"),
  345. )
  346. # UDP v4
  347. elif p.pid == udp4_proc.pid:
  348. check_conn(
  349. p,
  350. conn,
  351. AF_INET,
  352. SOCK_DGRAM,
  353. udp4_addr,
  354. (),
  355. psutil.CONN_NONE,
  356. ("all", "inet", "inet4", "udp", "udp4"),
  357. )
  358. # TCP v6
  359. elif p.pid == getattr(tcp6_proc, "pid", None):
  360. check_conn(
  361. p,
  362. conn,
  363. AF_INET6,
  364. SOCK_STREAM,
  365. tcp6_addr,
  366. (),
  367. psutil.CONN_LISTEN,
  368. ("all", "inet", "inet6", "tcp", "tcp6"),
  369. )
  370. # UDP v6
  371. elif p.pid == getattr(udp6_proc, "pid", None):
  372. check_conn(
  373. p,
  374. conn,
  375. AF_INET6,
  376. SOCK_DGRAM,
  377. udp6_addr,
  378. (),
  379. psutil.CONN_NONE,
  380. ("all", "inet", "inet6", "udp", "udp6"),
  381. )
  382. def test_count(self):
  383. with create_sockets():
  384. # tcp
  385. cons = this_proc_net_connections(kind='tcp')
  386. assert len(cons) == (2 if supports_ipv6() else 1)
  387. for conn in cons:
  388. assert conn.family in {AF_INET, AF_INET6}
  389. assert conn.type == SOCK_STREAM
  390. # tcp4
  391. cons = this_proc_net_connections(kind='tcp4')
  392. assert len(cons) == 1
  393. assert cons[0].family == AF_INET
  394. assert cons[0].type == SOCK_STREAM
  395. # tcp6
  396. if supports_ipv6():
  397. cons = this_proc_net_connections(kind='tcp6')
  398. assert len(cons) == 1
  399. assert cons[0].family == AF_INET6
  400. assert cons[0].type == SOCK_STREAM
  401. # udp
  402. cons = this_proc_net_connections(kind='udp')
  403. assert len(cons) == (2 if supports_ipv6() else 1)
  404. for conn in cons:
  405. assert conn.family in {AF_INET, AF_INET6}
  406. assert conn.type == SOCK_DGRAM
  407. # udp4
  408. cons = this_proc_net_connections(kind='udp4')
  409. assert len(cons) == 1
  410. assert cons[0].family == AF_INET
  411. assert cons[0].type == SOCK_DGRAM
  412. # udp6
  413. if supports_ipv6():
  414. cons = this_proc_net_connections(kind='udp6')
  415. assert len(cons) == 1
  416. assert cons[0].family == AF_INET6
  417. assert cons[0].type == SOCK_DGRAM
  418. # inet
  419. cons = this_proc_net_connections(kind='inet')
  420. assert len(cons) == (4 if supports_ipv6() else 2)
  421. for conn in cons:
  422. assert conn.family in {AF_INET, AF_INET6}
  423. assert conn.type in {SOCK_STREAM, SOCK_DGRAM}
  424. # inet6
  425. if supports_ipv6():
  426. cons = this_proc_net_connections(kind='inet6')
  427. assert len(cons) == 2
  428. for conn in cons:
  429. assert conn.family == AF_INET6
  430. assert conn.type in {SOCK_STREAM, SOCK_DGRAM}
  431. # Skipped on BSD becayse by default the Python process
  432. # creates a UNIX socket to '/var/run/log'.
  433. if HAS_NET_CONNECTIONS_UNIX and not (FREEBSD or NETBSD):
  434. cons = this_proc_net_connections(kind='unix')
  435. assert len(cons) == 3
  436. for conn in cons:
  437. assert conn.family == AF_UNIX
  438. assert conn.type in {SOCK_STREAM, SOCK_DGRAM}
  439. @pytest.mark.skipif(SKIP_SYSCONS, reason="requires root")
  440. class TestSystemWideConnections(ConnectionTestCase):
  441. """Tests for net_connections()."""
  442. def test_it(self):
  443. def check(cons, families, types_):
  444. for conn in cons:
  445. assert conn.family in families
  446. if conn.family != AF_UNIX:
  447. assert conn.type in types_
  448. check_connection_ntuple(conn)
  449. with create_sockets():
  450. from psutil._common import conn_tmap
  451. for kind, groups in conn_tmap.items():
  452. # XXX: SunOS does not retrieve UNIX sockets.
  453. if kind == 'unix' and not HAS_NET_CONNECTIONS_UNIX:
  454. continue
  455. families, types_ = groups
  456. cons = psutil.net_connections(kind)
  457. assert len(cons) == len(set(cons))
  458. check(cons, families, types_)
  459. @retry_on_failure()
  460. def test_multi_sockets_procs(self):
  461. # Creates multiple sub processes, each creating different
  462. # sockets. For each process check that proc.net_connections()
  463. # and psutil.net_connections() return the same results.
  464. # This is done mainly to check whether net_connections()'s
  465. # pid is properly set, see:
  466. # https://github.com/giampaolo/psutil/issues/1013
  467. with create_sockets() as socks:
  468. expected = len(socks)
  469. pids = []
  470. times = 10
  471. fnames = []
  472. for _ in range(times):
  473. fname = self.get_testfn()
  474. fnames.append(fname)
  475. src = textwrap.dedent(f"""\
  476. import time, os
  477. from psutil.tests import create_sockets
  478. with create_sockets():
  479. with open(r'{fname}', 'w') as f:
  480. f.write("hello")
  481. [time.sleep(0.1) for x in range(100)]
  482. """)
  483. sproc = self.pyrun(src)
  484. pids.append(sproc.pid)
  485. # sync
  486. for fname in fnames:
  487. wait_for_file(fname)
  488. syscons = [
  489. x for x in psutil.net_connections(kind='all') if x.pid in pids
  490. ]
  491. for pid in pids:
  492. assert len([x for x in syscons if x.pid == pid]) == expected
  493. p = psutil.Process(pid)
  494. assert len(p.net_connections('all')) == expected
  495. class TestMisc(PsutilTestCase):
  496. def test_net_connection_constants(self):
  497. ints = []
  498. strs = []
  499. for name in dir(psutil):
  500. if name.startswith('CONN_'):
  501. num = getattr(psutil, name)
  502. str_ = str(num)
  503. assert str_.isupper(), str_
  504. assert str not in strs
  505. assert num not in ints
  506. ints.append(num)
  507. strs.append(str_)
  508. if SUNOS:
  509. psutil.CONN_IDLE # noqa: B018
  510. psutil.CONN_BOUND # noqa: B018
  511. if WINDOWS:
  512. psutil.CONN_DELETE_TCB # noqa: B018