PageRenderTime 40ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

/Lib/test/test_socket.py

https://bitbucket.org/pombredanne/cpython
Python | 4862 lines | 4490 code | 194 blank | 178 comment | 53 complexity | b1eff7364c201dacfce594d5ae3d8484 MD5 | raw file
Possible License(s): 0BSD
  1. #!/usr/bin/env python3
  2. import unittest
  3. from test import support
  4. from unittest.case import _ExpectedFailure
  5. import errno
  6. import io
  7. import socket
  8. import select
  9. import tempfile
  10. import _testcapi
  11. import time
  12. import traceback
  13. import queue
  14. import sys
  15. import os
  16. import array
  17. import platform
  18. import contextlib
  19. from weakref import proxy
  20. import signal
  21. import math
  22. import pickle
  23. import struct
  24. try:
  25. import fcntl
  26. except ImportError:
  27. fcntl = False
  28. try:
  29. import multiprocessing
  30. except ImportError:
  31. multiprocessing = False
  32. HOST = support.HOST
  33. MSG = 'Michael Gilfix was here\u1234\r\n'.encode('utf-8') ## test unicode string and carriage return
  34. try:
  35. import _thread as thread
  36. import threading
  37. except ImportError:
  38. thread = None
  39. threading = None
  40. def _have_socket_can():
  41. """Check whether CAN sockets are supported on this host."""
  42. try:
  43. s = socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
  44. except (AttributeError, OSError):
  45. return False
  46. else:
  47. s.close()
  48. return True
  49. def _have_socket_rds():
  50. """Check whether RDS sockets are supported on this host."""
  51. try:
  52. s = socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0)
  53. except (AttributeError, OSError):
  54. return False
  55. else:
  56. s.close()
  57. return True
  58. HAVE_SOCKET_CAN = _have_socket_can()
  59. HAVE_SOCKET_RDS = _have_socket_rds()
  60. # Size in bytes of the int type
  61. SIZEOF_INT = array.array("i").itemsize
  62. class SocketTCPTest(unittest.TestCase):
  63. def setUp(self):
  64. self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  65. self.port = support.bind_port(self.serv)
  66. self.serv.listen(1)
  67. def tearDown(self):
  68. self.serv.close()
  69. self.serv = None
  70. class SocketUDPTest(unittest.TestCase):
  71. def setUp(self):
  72. self.serv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  73. self.port = support.bind_port(self.serv)
  74. def tearDown(self):
  75. self.serv.close()
  76. self.serv = None
  77. class ThreadSafeCleanupTestCase(unittest.TestCase):
  78. """Subclass of unittest.TestCase with thread-safe cleanup methods.
  79. This subclass protects the addCleanup() and doCleanups() methods
  80. with a recursive lock.
  81. """
  82. if threading:
  83. def __init__(self, *args, **kwargs):
  84. super().__init__(*args, **kwargs)
  85. self._cleanup_lock = threading.RLock()
  86. def addCleanup(self, *args, **kwargs):
  87. with self._cleanup_lock:
  88. return super().addCleanup(*args, **kwargs)
  89. def doCleanups(self, *args, **kwargs):
  90. with self._cleanup_lock:
  91. return super().doCleanups(*args, **kwargs)
  92. class SocketCANTest(unittest.TestCase):
  93. """To be able to run this test, a `vcan0` CAN interface can be created with
  94. the following commands:
  95. # modprobe vcan
  96. # ip link add dev vcan0 type vcan
  97. # ifconfig vcan0 up
  98. """
  99. interface = 'vcan0'
  100. bufsize = 128
  101. def setUp(self):
  102. self.s = socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
  103. self.addCleanup(self.s.close)
  104. try:
  105. self.s.bind((self.interface,))
  106. except OSError:
  107. self.skipTest('network interface `%s` does not exist' %
  108. self.interface)
  109. class SocketRDSTest(unittest.TestCase):
  110. """To be able to run this test, the `rds` kernel module must be loaded:
  111. # modprobe rds
  112. """
  113. bufsize = 8192
  114. def setUp(self):
  115. self.serv = socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0)
  116. self.addCleanup(self.serv.close)
  117. try:
  118. self.port = support.bind_port(self.serv)
  119. except OSError:
  120. self.skipTest('unable to bind RDS socket')
  121. class ThreadableTest:
  122. """Threadable Test class
  123. The ThreadableTest class makes it easy to create a threaded
  124. client/server pair from an existing unit test. To create a
  125. new threaded class from an existing unit test, use multiple
  126. inheritance:
  127. class NewClass (OldClass, ThreadableTest):
  128. pass
  129. This class defines two new fixture functions with obvious
  130. purposes for overriding:
  131. clientSetUp ()
  132. clientTearDown ()
  133. Any new test functions within the class must then define
  134. tests in pairs, where the test name is preceeded with a
  135. '_' to indicate the client portion of the test. Ex:
  136. def testFoo(self):
  137. # Server portion
  138. def _testFoo(self):
  139. # Client portion
  140. Any exceptions raised by the clients during their tests
  141. are caught and transferred to the main thread to alert
  142. the testing framework.
  143. Note, the server setup function cannot call any blocking
  144. functions that rely on the client thread during setup,
  145. unless serverExplicitReady() is called just before
  146. the blocking call (such as in setting up a client/server
  147. connection and performing the accept() in setUp().
  148. """
  149. def __init__(self):
  150. # Swap the true setup function
  151. self.__setUp = self.setUp
  152. self.__tearDown = self.tearDown
  153. self.setUp = self._setUp
  154. self.tearDown = self._tearDown
  155. def serverExplicitReady(self):
  156. """This method allows the server to explicitly indicate that
  157. it wants the client thread to proceed. This is useful if the
  158. server is about to execute a blocking routine that is
  159. dependent upon the client thread during its setup routine."""
  160. self.server_ready.set()
  161. def _setUp(self):
  162. self.server_ready = threading.Event()
  163. self.client_ready = threading.Event()
  164. self.done = threading.Event()
  165. self.queue = queue.Queue(1)
  166. self.server_crashed = False
  167. # Do some munging to start the client test.
  168. methodname = self.id()
  169. i = methodname.rfind('.')
  170. methodname = methodname[i+1:]
  171. test_method = getattr(self, '_' + methodname)
  172. self.client_thread = thread.start_new_thread(
  173. self.clientRun, (test_method,))
  174. try:
  175. self.__setUp()
  176. except:
  177. self.server_crashed = True
  178. raise
  179. finally:
  180. self.server_ready.set()
  181. self.client_ready.wait()
  182. def _tearDown(self):
  183. self.__tearDown()
  184. self.done.wait()
  185. if self.queue.qsize():
  186. exc = self.queue.get()
  187. raise exc
  188. def clientRun(self, test_func):
  189. self.server_ready.wait()
  190. self.clientSetUp()
  191. self.client_ready.set()
  192. if self.server_crashed:
  193. self.clientTearDown()
  194. return
  195. if not hasattr(test_func, '__call__'):
  196. raise TypeError("test_func must be a callable function")
  197. try:
  198. test_func()
  199. except _ExpectedFailure:
  200. # We deliberately ignore expected failures
  201. pass
  202. except BaseException as e:
  203. self.queue.put(e)
  204. finally:
  205. self.clientTearDown()
  206. def clientSetUp(self):
  207. raise NotImplementedError("clientSetUp must be implemented.")
  208. def clientTearDown(self):
  209. self.done.set()
  210. thread.exit()
  211. class ThreadedTCPSocketTest(SocketTCPTest, ThreadableTest):
  212. def __init__(self, methodName='runTest'):
  213. SocketTCPTest.__init__(self, methodName=methodName)
  214. ThreadableTest.__init__(self)
  215. def clientSetUp(self):
  216. self.cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  217. def clientTearDown(self):
  218. self.cli.close()
  219. self.cli = None
  220. ThreadableTest.clientTearDown(self)
  221. class ThreadedUDPSocketTest(SocketUDPTest, ThreadableTest):
  222. def __init__(self, methodName='runTest'):
  223. SocketUDPTest.__init__(self, methodName=methodName)
  224. ThreadableTest.__init__(self)
  225. def clientSetUp(self):
  226. self.cli = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  227. def clientTearDown(self):
  228. self.cli.close()
  229. self.cli = None
  230. ThreadableTest.clientTearDown(self)
  231. class ThreadedCANSocketTest(SocketCANTest, ThreadableTest):
  232. def __init__(self, methodName='runTest'):
  233. SocketCANTest.__init__(self, methodName=methodName)
  234. ThreadableTest.__init__(self)
  235. def clientSetUp(self):
  236. self.cli = socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
  237. try:
  238. self.cli.bind((self.interface,))
  239. except OSError:
  240. # skipTest should not be called here, and will be called in the
  241. # server instead
  242. pass
  243. def clientTearDown(self):
  244. self.cli.close()
  245. self.cli = None
  246. ThreadableTest.clientTearDown(self)
  247. class ThreadedRDSSocketTest(SocketRDSTest, ThreadableTest):
  248. def __init__(self, methodName='runTest'):
  249. SocketRDSTest.__init__(self, methodName=methodName)
  250. ThreadableTest.__init__(self)
  251. def clientSetUp(self):
  252. self.cli = socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0)
  253. try:
  254. # RDS sockets must be bound explicitly to send or receive data
  255. self.cli.bind((HOST, 0))
  256. self.cli_addr = self.cli.getsockname()
  257. except OSError:
  258. # skipTest should not be called here, and will be called in the
  259. # server instead
  260. pass
  261. def clientTearDown(self):
  262. self.cli.close()
  263. self.cli = None
  264. ThreadableTest.clientTearDown(self)
  265. class SocketConnectedTest(ThreadedTCPSocketTest):
  266. """Socket tests for client-server connection.
  267. self.cli_conn is a client socket connected to the server. The
  268. setUp() method guarantees that it is connected to the server.
  269. """
  270. def __init__(self, methodName='runTest'):
  271. ThreadedTCPSocketTest.__init__(self, methodName=methodName)
  272. def setUp(self):
  273. ThreadedTCPSocketTest.setUp(self)
  274. # Indicate explicitly we're ready for the client thread to
  275. # proceed and then perform the blocking call to accept
  276. self.serverExplicitReady()
  277. conn, addr = self.serv.accept()
  278. self.cli_conn = conn
  279. def tearDown(self):
  280. self.cli_conn.close()
  281. self.cli_conn = None
  282. ThreadedTCPSocketTest.tearDown(self)
  283. def clientSetUp(self):
  284. ThreadedTCPSocketTest.clientSetUp(self)
  285. self.cli.connect((HOST, self.port))
  286. self.serv_conn = self.cli
  287. def clientTearDown(self):
  288. self.serv_conn.close()
  289. self.serv_conn = None
  290. ThreadedTCPSocketTest.clientTearDown(self)
  291. class SocketPairTest(unittest.TestCase, ThreadableTest):
  292. def __init__(self, methodName='runTest'):
  293. unittest.TestCase.__init__(self, methodName=methodName)
  294. ThreadableTest.__init__(self)
  295. def setUp(self):
  296. self.serv, self.cli = socket.socketpair()
  297. def tearDown(self):
  298. self.serv.close()
  299. self.serv = None
  300. def clientSetUp(self):
  301. pass
  302. def clientTearDown(self):
  303. self.cli.close()
  304. self.cli = None
  305. ThreadableTest.clientTearDown(self)
  306. # The following classes are used by the sendmsg()/recvmsg() tests.
  307. # Combining, for instance, ConnectedStreamTestMixin and TCPTestBase
  308. # gives a drop-in replacement for SocketConnectedTest, but different
  309. # address families can be used, and the attributes serv_addr and
  310. # cli_addr will be set to the addresses of the endpoints.
  311. class SocketTestBase(unittest.TestCase):
  312. """A base class for socket tests.
  313. Subclasses must provide methods newSocket() to return a new socket
  314. and bindSock(sock) to bind it to an unused address.
  315. Creates a socket self.serv and sets self.serv_addr to its address.
  316. """
  317. def setUp(self):
  318. self.serv = self.newSocket()
  319. self.bindServer()
  320. def bindServer(self):
  321. """Bind server socket and set self.serv_addr to its address."""
  322. self.bindSock(self.serv)
  323. self.serv_addr = self.serv.getsockname()
  324. def tearDown(self):
  325. self.serv.close()
  326. self.serv = None
  327. class SocketListeningTestMixin(SocketTestBase):
  328. """Mixin to listen on the server socket."""
  329. def setUp(self):
  330. super().setUp()
  331. self.serv.listen(1)
  332. class ThreadedSocketTestMixin(ThreadSafeCleanupTestCase, SocketTestBase,
  333. ThreadableTest):
  334. """Mixin to add client socket and allow client/server tests.
  335. Client socket is self.cli and its address is self.cli_addr. See
  336. ThreadableTest for usage information.
  337. """
  338. def __init__(self, *args, **kwargs):
  339. super().__init__(*args, **kwargs)
  340. ThreadableTest.__init__(self)
  341. def clientSetUp(self):
  342. self.cli = self.newClientSocket()
  343. self.bindClient()
  344. def newClientSocket(self):
  345. """Return a new socket for use as client."""
  346. return self.newSocket()
  347. def bindClient(self):
  348. """Bind client socket and set self.cli_addr to its address."""
  349. self.bindSock(self.cli)
  350. self.cli_addr = self.cli.getsockname()
  351. def clientTearDown(self):
  352. self.cli.close()
  353. self.cli = None
  354. ThreadableTest.clientTearDown(self)
  355. class ConnectedStreamTestMixin(SocketListeningTestMixin,
  356. ThreadedSocketTestMixin):
  357. """Mixin to allow client/server stream tests with connected client.
  358. Server's socket representing connection to client is self.cli_conn
  359. and client's connection to server is self.serv_conn. (Based on
  360. SocketConnectedTest.)
  361. """
  362. def setUp(self):
  363. super().setUp()
  364. # Indicate explicitly we're ready for the client thread to
  365. # proceed and then perform the blocking call to accept
  366. self.serverExplicitReady()
  367. conn, addr = self.serv.accept()
  368. self.cli_conn = conn
  369. def tearDown(self):
  370. self.cli_conn.close()
  371. self.cli_conn = None
  372. super().tearDown()
  373. def clientSetUp(self):
  374. super().clientSetUp()
  375. self.cli.connect(self.serv_addr)
  376. self.serv_conn = self.cli
  377. def clientTearDown(self):
  378. self.serv_conn.close()
  379. self.serv_conn = None
  380. super().clientTearDown()
  381. class UnixSocketTestBase(SocketTestBase):
  382. """Base class for Unix-domain socket tests."""
  383. # This class is used for file descriptor passing tests, so we
  384. # create the sockets in a private directory so that other users
  385. # can't send anything that might be problematic for a privileged
  386. # user running the tests.
  387. def setUp(self):
  388. self.dir_path = tempfile.mkdtemp()
  389. self.addCleanup(os.rmdir, self.dir_path)
  390. super().setUp()
  391. def bindSock(self, sock):
  392. path = tempfile.mktemp(dir=self.dir_path)
  393. sock.bind(path)
  394. self.addCleanup(support.unlink, path)
  395. class UnixStreamBase(UnixSocketTestBase):
  396. """Base class for Unix-domain SOCK_STREAM tests."""
  397. def newSocket(self):
  398. return socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  399. class InetTestBase(SocketTestBase):
  400. """Base class for IPv4 socket tests."""
  401. host = HOST
  402. def setUp(self):
  403. super().setUp()
  404. self.port = self.serv_addr[1]
  405. def bindSock(self, sock):
  406. support.bind_port(sock, host=self.host)
  407. class TCPTestBase(InetTestBase):
  408. """Base class for TCP-over-IPv4 tests."""
  409. def newSocket(self):
  410. return socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  411. class UDPTestBase(InetTestBase):
  412. """Base class for UDP-over-IPv4 tests."""
  413. def newSocket(self):
  414. return socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  415. class SCTPStreamBase(InetTestBase):
  416. """Base class for SCTP tests in one-to-one (SOCK_STREAM) mode."""
  417. def newSocket(self):
  418. return socket.socket(socket.AF_INET, socket.SOCK_STREAM,
  419. socket.IPPROTO_SCTP)
  420. class Inet6TestBase(InetTestBase):
  421. """Base class for IPv6 socket tests."""
  422. # Don't use "localhost" here - it may not have an IPv6 address
  423. # assigned to it by default (e.g. in /etc/hosts), and if someone
  424. # has assigned it an IPv4-mapped address, then it's unlikely to
  425. # work with the full IPv6 API.
  426. host = "::1"
  427. class UDP6TestBase(Inet6TestBase):
  428. """Base class for UDP-over-IPv6 tests."""
  429. def newSocket(self):
  430. return socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
  431. # Test-skipping decorators for use with ThreadableTest.
  432. def skipWithClientIf(condition, reason):
  433. """Skip decorated test if condition is true, add client_skip decorator.
  434. If the decorated object is not a class, sets its attribute
  435. "client_skip" to a decorator which will return an empty function
  436. if the test is to be skipped, or the original function if it is
  437. not. This can be used to avoid running the client part of a
  438. skipped test when using ThreadableTest.
  439. """
  440. def client_pass(*args, **kwargs):
  441. pass
  442. def skipdec(obj):
  443. retval = unittest.skip(reason)(obj)
  444. if not isinstance(obj, type):
  445. retval.client_skip = lambda f: client_pass
  446. return retval
  447. def noskipdec(obj):
  448. if not (isinstance(obj, type) or hasattr(obj, "client_skip")):
  449. obj.client_skip = lambda f: f
  450. return obj
  451. return skipdec if condition else noskipdec
  452. def requireAttrs(obj, *attributes):
  453. """Skip decorated test if obj is missing any of the given attributes.
  454. Sets client_skip attribute as skipWithClientIf() does.
  455. """
  456. missing = [name for name in attributes if not hasattr(obj, name)]
  457. return skipWithClientIf(
  458. missing, "don't have " + ", ".join(name for name in missing))
  459. def requireSocket(*args):
  460. """Skip decorated test if a socket cannot be created with given arguments.
  461. When an argument is given as a string, will use the value of that
  462. attribute of the socket module, or skip the test if it doesn't
  463. exist. Sets client_skip attribute as skipWithClientIf() does.
  464. """
  465. err = None
  466. missing = [obj for obj in args if
  467. isinstance(obj, str) and not hasattr(socket, obj)]
  468. if missing:
  469. err = "don't have " + ", ".join(name for name in missing)
  470. else:
  471. callargs = [getattr(socket, obj) if isinstance(obj, str) else obj
  472. for obj in args]
  473. try:
  474. s = socket.socket(*callargs)
  475. except OSError as e:
  476. # XXX: check errno?
  477. err = str(e)
  478. else:
  479. s.close()
  480. return skipWithClientIf(
  481. err is not None,
  482. "can't create socket({0}): {1}".format(
  483. ", ".join(str(o) for o in args), err))
  484. #######################################################################
  485. ## Begin Tests
  486. class GeneralModuleTests(unittest.TestCase):
  487. def test_repr(self):
  488. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  489. self.addCleanup(s.close)
  490. self.assertTrue(repr(s).startswith("<socket.socket object"))
  491. def test_weakref(self):
  492. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  493. p = proxy(s)
  494. self.assertEqual(p.fileno(), s.fileno())
  495. s.close()
  496. s = None
  497. try:
  498. p.fileno()
  499. except ReferenceError:
  500. pass
  501. else:
  502. self.fail('Socket proxy still exists')
  503. def testSocketError(self):
  504. # Testing socket module exceptions
  505. msg = "Error raising socket exception (%s)."
  506. with self.assertRaises(OSError, msg=msg % 'OSError'):
  507. raise OSError
  508. with self.assertRaises(OSError, msg=msg % 'socket.herror'):
  509. raise socket.herror
  510. with self.assertRaises(OSError, msg=msg % 'socket.gaierror'):
  511. raise socket.gaierror
  512. def testSendtoErrors(self):
  513. # Testing that sendto doens't masks failures. See #10169.
  514. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  515. self.addCleanup(s.close)
  516. s.bind(('', 0))
  517. sockname = s.getsockname()
  518. # 2 args
  519. with self.assertRaises(TypeError) as cm:
  520. s.sendto('\u2620', sockname)
  521. self.assertEqual(str(cm.exception),
  522. "'str' does not support the buffer interface")
  523. with self.assertRaises(TypeError) as cm:
  524. s.sendto(5j, sockname)
  525. self.assertEqual(str(cm.exception),
  526. "'complex' does not support the buffer interface")
  527. with self.assertRaises(TypeError) as cm:
  528. s.sendto(b'foo', None)
  529. self.assertIn('not NoneType',str(cm.exception))
  530. # 3 args
  531. with self.assertRaises(TypeError) as cm:
  532. s.sendto('\u2620', 0, sockname)
  533. self.assertEqual(str(cm.exception),
  534. "'str' does not support the buffer interface")
  535. with self.assertRaises(TypeError) as cm:
  536. s.sendto(5j, 0, sockname)
  537. self.assertEqual(str(cm.exception),
  538. "'complex' does not support the buffer interface")
  539. with self.assertRaises(TypeError) as cm:
  540. s.sendto(b'foo', 0, None)
  541. self.assertIn('not NoneType', str(cm.exception))
  542. with self.assertRaises(TypeError) as cm:
  543. s.sendto(b'foo', 'bar', sockname)
  544. self.assertIn('an integer is required', str(cm.exception))
  545. with self.assertRaises(TypeError) as cm:
  546. s.sendto(b'foo', None, None)
  547. self.assertIn('an integer is required', str(cm.exception))
  548. # wrong number of args
  549. with self.assertRaises(TypeError) as cm:
  550. s.sendto(b'foo')
  551. self.assertIn('(1 given)', str(cm.exception))
  552. with self.assertRaises(TypeError) as cm:
  553. s.sendto(b'foo', 0, sockname, 4)
  554. self.assertIn('(4 given)', str(cm.exception))
  555. def testCrucialConstants(self):
  556. # Testing for mission critical constants
  557. socket.AF_INET
  558. socket.SOCK_STREAM
  559. socket.SOCK_DGRAM
  560. socket.SOCK_RAW
  561. socket.SOCK_RDM
  562. socket.SOCK_SEQPACKET
  563. socket.SOL_SOCKET
  564. socket.SO_REUSEADDR
  565. def testHostnameRes(self):
  566. # Testing hostname resolution mechanisms
  567. hostname = socket.gethostname()
  568. try:
  569. ip = socket.gethostbyname(hostname)
  570. except OSError:
  571. # Probably name lookup wasn't set up right; skip this test
  572. return
  573. self.assertTrue(ip.find('.') >= 0, "Error resolving host to ip.")
  574. try:
  575. hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
  576. except OSError:
  577. # Probably a similar problem as above; skip this test
  578. return
  579. all_host_names = [hostname, hname] + aliases
  580. fqhn = socket.getfqdn(ip)
  581. if not fqhn in all_host_names:
  582. self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names)))
  583. @unittest.skipUnless(hasattr(socket, 'sethostname'), "test needs socket.sethostname()")
  584. @unittest.skipUnless(hasattr(socket, 'gethostname'), "test needs socket.gethostname()")
  585. def test_sethostname(self):
  586. oldhn = socket.gethostname()
  587. try:
  588. socket.sethostname('new')
  589. except OSError as e:
  590. if e.errno == errno.EPERM:
  591. self.skipTest("test should be run as root")
  592. else:
  593. raise
  594. try:
  595. # running test as root!
  596. self.assertEqual(socket.gethostname(), 'new')
  597. # Should work with bytes objects too
  598. socket.sethostname(b'bar')
  599. self.assertEqual(socket.gethostname(), 'bar')
  600. finally:
  601. socket.sethostname(oldhn)
  602. @unittest.skipUnless(hasattr(socket, 'if_nameindex'),
  603. 'socket.if_nameindex() not available.')
  604. def testInterfaceNameIndex(self):
  605. interfaces = socket.if_nameindex()
  606. for index, name in interfaces:
  607. self.assertIsInstance(index, int)
  608. self.assertIsInstance(name, str)
  609. # interface indices are non-zero integers
  610. self.assertGreater(index, 0)
  611. _index = socket.if_nametoindex(name)
  612. self.assertIsInstance(_index, int)
  613. self.assertEqual(index, _index)
  614. _name = socket.if_indextoname(index)
  615. self.assertIsInstance(_name, str)
  616. self.assertEqual(name, _name)
  617. @unittest.skipUnless(hasattr(socket, 'if_nameindex'),
  618. 'socket.if_nameindex() not available.')
  619. def testInvalidInterfaceNameIndex(self):
  620. # test nonexistent interface index/name
  621. self.assertRaises(OSError, socket.if_indextoname, 0)
  622. self.assertRaises(OSError, socket.if_nametoindex, '_DEADBEEF')
  623. # test with invalid values
  624. self.assertRaises(TypeError, socket.if_nametoindex, 0)
  625. self.assertRaises(TypeError, socket.if_indextoname, '_DEADBEEF')
  626. def testRefCountGetNameInfo(self):
  627. # Testing reference count for getnameinfo
  628. if hasattr(sys, "getrefcount"):
  629. try:
  630. # On some versions, this loses a reference
  631. orig = sys.getrefcount(__name__)
  632. socket.getnameinfo(__name__,0)
  633. except TypeError:
  634. if sys.getrefcount(__name__) != orig:
  635. self.fail("socket.getnameinfo loses a reference")
  636. def testInterpreterCrash(self):
  637. # Making sure getnameinfo doesn't crash the interpreter
  638. try:
  639. # On some versions, this crashes the interpreter.
  640. socket.getnameinfo(('x', 0, 0, 0), 0)
  641. except OSError:
  642. pass
  643. def testNtoH(self):
  644. # This just checks that htons etc. are their own inverse,
  645. # when looking at the lower 16 or 32 bits.
  646. sizes = {socket.htonl: 32, socket.ntohl: 32,
  647. socket.htons: 16, socket.ntohs: 16}
  648. for func, size in sizes.items():
  649. mask = (1<<size) - 1
  650. for i in (0, 1, 0xffff, ~0xffff, 2, 0x01234567, 0x76543210):
  651. self.assertEqual(i & mask, func(func(i&mask)) & mask)
  652. swapped = func(mask)
  653. self.assertEqual(swapped & mask, mask)
  654. self.assertRaises(OverflowError, func, 1<<34)
  655. def testNtoHErrors(self):
  656. good_values = [ 1, 2, 3, 1, 2, 3 ]
  657. bad_values = [ -1, -2, -3, -1, -2, -3 ]
  658. for k in good_values:
  659. socket.ntohl(k)
  660. socket.ntohs(k)
  661. socket.htonl(k)
  662. socket.htons(k)
  663. for k in bad_values:
  664. self.assertRaises(OverflowError, socket.ntohl, k)
  665. self.assertRaises(OverflowError, socket.ntohs, k)
  666. self.assertRaises(OverflowError, socket.htonl, k)
  667. self.assertRaises(OverflowError, socket.htons, k)
  668. def testGetServBy(self):
  669. eq = self.assertEqual
  670. # Find one service that exists, then check all the related interfaces.
  671. # I've ordered this by protocols that have both a tcp and udp
  672. # protocol, at least for modern Linuxes.
  673. if (sys.platform.startswith(('freebsd', 'netbsd'))
  674. or sys.platform in ('linux', 'darwin')):
  675. # avoid the 'echo' service on this platform, as there is an
  676. # assumption breaking non-standard port/protocol entry
  677. services = ('daytime', 'qotd', 'domain')
  678. else:
  679. services = ('echo', 'daytime', 'domain')
  680. for service in services:
  681. try:
  682. port = socket.getservbyname(service, 'tcp')
  683. break
  684. except OSError:
  685. pass
  686. else:
  687. raise OSError
  688. # Try same call with optional protocol omitted
  689. port2 = socket.getservbyname(service)
  690. eq(port, port2)
  691. # Try udp, but don't barf it it doesn't exist
  692. try:
  693. udpport = socket.getservbyname(service, 'udp')
  694. except OSError:
  695. udpport = None
  696. else:
  697. eq(udpport, port)
  698. # Now make sure the lookup by port returns the same service name
  699. eq(socket.getservbyport(port2), service)
  700. eq(socket.getservbyport(port, 'tcp'), service)
  701. if udpport is not None:
  702. eq(socket.getservbyport(udpport, 'udp'), service)
  703. # Make sure getservbyport does not accept out of range ports.
  704. self.assertRaises(OverflowError, socket.getservbyport, -1)
  705. self.assertRaises(OverflowError, socket.getservbyport, 65536)
  706. def testDefaultTimeout(self):
  707. # Testing default timeout
  708. # The default timeout should initially be None
  709. self.assertEqual(socket.getdefaulttimeout(), None)
  710. s = socket.socket()
  711. self.assertEqual(s.gettimeout(), None)
  712. s.close()
  713. # Set the default timeout to 10, and see if it propagates
  714. socket.setdefaulttimeout(10)
  715. self.assertEqual(socket.getdefaulttimeout(), 10)
  716. s = socket.socket()
  717. self.assertEqual(s.gettimeout(), 10)
  718. s.close()
  719. # Reset the default timeout to None, and see if it propagates
  720. socket.setdefaulttimeout(None)
  721. self.assertEqual(socket.getdefaulttimeout(), None)
  722. s = socket.socket()
  723. self.assertEqual(s.gettimeout(), None)
  724. s.close()
  725. # Check that setting it to an invalid value raises ValueError
  726. self.assertRaises(ValueError, socket.setdefaulttimeout, -1)
  727. # Check that setting it to an invalid type raises TypeError
  728. self.assertRaises(TypeError, socket.setdefaulttimeout, "spam")
  729. def testIPv4_inet_aton_fourbytes(self):
  730. if not hasattr(socket, 'inet_aton'):
  731. return # No inet_aton, nothing to check
  732. # Test that issue1008086 and issue767150 are fixed.
  733. # It must return 4 bytes.
  734. self.assertEqual(b'\x00'*4, socket.inet_aton('0.0.0.0'))
  735. self.assertEqual(b'\xff'*4, socket.inet_aton('255.255.255.255'))
  736. def testIPv4toString(self):
  737. if not hasattr(socket, 'inet_pton'):
  738. return # No inet_pton() on this platform
  739. from socket import inet_aton as f, inet_pton, AF_INET
  740. g = lambda a: inet_pton(AF_INET, a)
  741. assertInvalid = lambda func,a: self.assertRaises(
  742. (OSError, ValueError), func, a
  743. )
  744. self.assertEqual(b'\x00\x00\x00\x00', f('0.0.0.0'))
  745. self.assertEqual(b'\xff\x00\xff\x00', f('255.0.255.0'))
  746. self.assertEqual(b'\xaa\xaa\xaa\xaa', f('170.170.170.170'))
  747. self.assertEqual(b'\x01\x02\x03\x04', f('1.2.3.4'))
  748. self.assertEqual(b'\xff\xff\xff\xff', f('255.255.255.255'))
  749. assertInvalid(f, '0.0.0.')
  750. assertInvalid(f, '300.0.0.0')
  751. assertInvalid(f, 'a.0.0.0')
  752. assertInvalid(f, '1.2.3.4.5')
  753. assertInvalid(f, '::1')
  754. self.assertEqual(b'\x00\x00\x00\x00', g('0.0.0.0'))
  755. self.assertEqual(b'\xff\x00\xff\x00', g('255.0.255.0'))
  756. self.assertEqual(b'\xaa\xaa\xaa\xaa', g('170.170.170.170'))
  757. self.assertEqual(b'\xff\xff\xff\xff', g('255.255.255.255'))
  758. assertInvalid(g, '0.0.0.')
  759. assertInvalid(g, '300.0.0.0')
  760. assertInvalid(g, 'a.0.0.0')
  761. assertInvalid(g, '1.2.3.4.5')
  762. assertInvalid(g, '::1')
  763. def testIPv6toString(self):
  764. if not hasattr(socket, 'inet_pton'):
  765. return # No inet_pton() on this platform
  766. try:
  767. from socket import inet_pton, AF_INET6, has_ipv6
  768. if not has_ipv6:
  769. return
  770. except ImportError:
  771. return
  772. f = lambda a: inet_pton(AF_INET6, a)
  773. assertInvalid = lambda a: self.assertRaises(
  774. (OSError, ValueError), f, a
  775. )
  776. self.assertEqual(b'\x00' * 16, f('::'))
  777. self.assertEqual(b'\x00' * 16, f('0::0'))
  778. self.assertEqual(b'\x00\x01' + b'\x00' * 14, f('1::'))
  779. self.assertEqual(
  780. b'\x45\xef\x76\xcb\x00\x1a\x56\xef\xaf\xeb\x0b\xac\x19\x24\xae\xae',
  781. f('45ef:76cb:1a:56ef:afeb:bac:1924:aeae')
  782. )
  783. self.assertEqual(
  784. b'\xad\x42\x0a\xbc' + b'\x00' * 4 + b'\x01\x27\x00\x00\x02\x54\x00\x02',
  785. f('ad42:abc::127:0:254:2')
  786. )
  787. self.assertEqual(b'\x00\x12\x00\x0a' + b'\x00' * 12, f('12:a::'))
  788. assertInvalid('0x20::')
  789. assertInvalid(':::')
  790. assertInvalid('::0::')
  791. assertInvalid('1::abc::')
  792. assertInvalid('1::abc::def')
  793. assertInvalid('1:2:3:4:5:6:')
  794. assertInvalid('1:2:3:4:5:6')
  795. assertInvalid('1:2:3:4:5:6:7:8:')
  796. assertInvalid('1:2:3:4:5:6:7:8:0')
  797. self.assertEqual(b'\x00' * 12 + b'\xfe\x2a\x17\x40',
  798. f('::254.42.23.64')
  799. )
  800. self.assertEqual(
  801. b'\x00\x42' + b'\x00' * 8 + b'\xa2\x9b\xfe\x2a\x17\x40',
  802. f('42::a29b:254.42.23.64')
  803. )
  804. self.assertEqual(
  805. b'\x00\x42\xa8\xb9\x00\x00\x00\x02\xff\xff\xa2\x9b\xfe\x2a\x17\x40',
  806. f('42:a8b9:0:2:ffff:a29b:254.42.23.64')
  807. )
  808. assertInvalid('255.254.253.252')
  809. assertInvalid('1::260.2.3.0')
  810. assertInvalid('1::0.be.e.0')
  811. assertInvalid('1:2:3:4:5:6:7:1.2.3.4')
  812. assertInvalid('::1.2.3.4:0')
  813. assertInvalid('0.100.200.0:3:4:5:6:7:8')
  814. def testStringToIPv4(self):
  815. if not hasattr(socket, 'inet_ntop'):
  816. return # No inet_ntop() on this platform
  817. from socket import inet_ntoa as f, inet_ntop, AF_INET
  818. g = lambda a: inet_ntop(AF_INET, a)
  819. assertInvalid = lambda func,a: self.assertRaises(
  820. (OSError, ValueError), func, a
  821. )
  822. self.assertEqual('1.0.1.0', f(b'\x01\x00\x01\x00'))
  823. self.assertEqual('170.85.170.85', f(b'\xaa\x55\xaa\x55'))
  824. self.assertEqual('255.255.255.255', f(b'\xff\xff\xff\xff'))
  825. self.assertEqual('1.2.3.4', f(b'\x01\x02\x03\x04'))
  826. assertInvalid(f, b'\x00' * 3)
  827. assertInvalid(f, b'\x00' * 5)
  828. assertInvalid(f, b'\x00' * 16)
  829. self.assertEqual('1.0.1.0', g(b'\x01\x00\x01\x00'))
  830. self.assertEqual('170.85.170.85', g(b'\xaa\x55\xaa\x55'))
  831. self.assertEqual('255.255.255.255', g(b'\xff\xff\xff\xff'))
  832. assertInvalid(g, b'\x00' * 3)
  833. assertInvalid(g, b'\x00' * 5)
  834. assertInvalid(g, b'\x00' * 16)
  835. def testStringToIPv6(self):
  836. if not hasattr(socket, 'inet_ntop'):
  837. return # No inet_ntop() on this platform
  838. try:
  839. from socket import inet_ntop, AF_INET6, has_ipv6
  840. if not has_ipv6:
  841. return
  842. except ImportError:
  843. return
  844. f = lambda a: inet_ntop(AF_INET6, a)
  845. assertInvalid = lambda a: self.assertRaises(
  846. (OSError, ValueError), f, a
  847. )
  848. self.assertEqual('::', f(b'\x00' * 16))
  849. self.assertEqual('::1', f(b'\x00' * 15 + b'\x01'))
  850. self.assertEqual(
  851. 'aef:b01:506:1001:ffff:9997:55:170',
  852. f(b'\x0a\xef\x0b\x01\x05\x06\x10\x01\xff\xff\x99\x97\x00\x55\x01\x70')
  853. )
  854. assertInvalid(b'\x12' * 15)
  855. assertInvalid(b'\x12' * 17)
  856. assertInvalid(b'\x12' * 4)
  857. # XXX The following don't test module-level functionality...
  858. def testSockName(self):
  859. # Testing getsockname()
  860. port = support.find_unused_port()
  861. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  862. self.addCleanup(sock.close)
  863. sock.bind(("0.0.0.0", port))
  864. name = sock.getsockname()
  865. # XXX(nnorwitz): http://tinyurl.com/os5jz seems to indicate
  866. # it reasonable to get the host's addr in addition to 0.0.0.0.
  867. # At least for eCos. This is required for the S/390 to pass.
  868. try:
  869. my_ip_addr = socket.gethostbyname(socket.gethostname())
  870. except OSError:
  871. # Probably name lookup wasn't set up right; skip this test
  872. return
  873. self.assertIn(name[0], ("0.0.0.0", my_ip_addr), '%s invalid' % name[0])
  874. self.assertEqual(name[1], port)
  875. def testGetSockOpt(self):
  876. # Testing getsockopt()
  877. # We know a socket should start without reuse==0
  878. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  879. self.addCleanup(sock.close)
  880. reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
  881. self.assertFalse(reuse != 0, "initial mode is reuse")
  882. def testSetSockOpt(self):
  883. # Testing setsockopt()
  884. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  885. self.addCleanup(sock.close)
  886. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  887. reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
  888. self.assertFalse(reuse == 0, "failed to set reuse mode")
  889. def testSendAfterClose(self):
  890. # testing send() after close() with timeout
  891. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  892. sock.settimeout(1)
  893. sock.close()
  894. self.assertRaises(OSError, sock.send, b"spam")
  895. def testNewAttributes(self):
  896. # testing .family, .type and .protocol
  897. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  898. self.assertEqual(sock.family, socket.AF_INET)
  899. self.assertEqual(sock.type, socket.SOCK_STREAM)
  900. self.assertEqual(sock.proto, 0)
  901. sock.close()
  902. def test_getsockaddrarg(self):
  903. host = '0.0.0.0'
  904. port = support.find_unused_port()
  905. big_port = port + 65536
  906. neg_port = port - 65536
  907. sock = socket.socket()
  908. try:
  909. self.assertRaises(OverflowError, sock.bind, (host, big_port))
  910. self.assertRaises(OverflowError, sock.bind, (host, neg_port))
  911. sock.bind((host, port))
  912. finally:
  913. sock.close()
  914. @unittest.skipUnless(os.name == "nt", "Windows specific")
  915. def test_sock_ioctl(self):
  916. self.assertTrue(hasattr(socket.socket, 'ioctl'))
  917. self.assertTrue(hasattr(socket, 'SIO_RCVALL'))
  918. self.assertTrue(hasattr(socket, 'RCVALL_ON'))
  919. self.assertTrue(hasattr(socket, 'RCVALL_OFF'))
  920. self.assertTrue(hasattr(socket, 'SIO_KEEPALIVE_VALS'))
  921. s = socket.socket()
  922. self.addCleanup(s.close)
  923. self.assertRaises(ValueError, s.ioctl, -1, None)
  924. s.ioctl(socket.SIO_KEEPALIVE_VALS, (1, 100, 100))
  925. def testGetaddrinfo(self):
  926. try:
  927. socket.getaddrinfo('localhost', 80)
  928. except socket.gaierror as err:
  929. if err.errno == socket.EAI_SERVICE:
  930. # see http://bugs.python.org/issue1282647
  931. self.skipTest("buggy libc version")
  932. raise
  933. # len of every sequence is supposed to be == 5
  934. for info in socket.getaddrinfo(HOST, None):
  935. self.assertEqual(len(info), 5)
  936. # host can be a domain name, a string representation of an
  937. # IPv4/v6 address or None
  938. socket.getaddrinfo('localhost', 80)
  939. socket.getaddrinfo('127.0.0.1', 80)
  940. socket.getaddrinfo(None, 80)
  941. if support.IPV6_ENABLED:
  942. socket.getaddrinfo('::1', 80)
  943. # port can be a string service name such as "http", a numeric
  944. # port number or None
  945. socket.getaddrinfo(HOST, "http")
  946. socket.getaddrinfo(HOST, 80)
  947. socket.getaddrinfo(HOST, None)
  948. # test family and socktype filters
  949. infos = socket.getaddrinfo(HOST, None, socket.AF_INET)
  950. for family, _, _, _, _ in infos:
  951. self.assertEqual(family, socket.AF_INET)
  952. infos = socket.getaddrinfo(HOST, None, 0, socket.SOCK_STREAM)
  953. for _, socktype, _, _, _ in infos:
  954. self.assertEqual(socktype, socket.SOCK_STREAM)
  955. # test proto and flags arguments
  956. socket.getaddrinfo(HOST, None, 0, 0, socket.SOL_TCP)
  957. socket.getaddrinfo(HOST, None, 0, 0, 0, socket.AI_PASSIVE)
  958. # a server willing to support both IPv4 and IPv6 will
  959. # usually do this
  960. socket.getaddrinfo(None, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0,
  961. socket.AI_PASSIVE)
  962. # test keyword arguments
  963. a = socket.getaddrinfo(HOST, None)
  964. b = socket.getaddrinfo(host=HOST, port=None)
  965. self.assertEqual(a, b)
  966. a = socket.getaddrinfo(HOST, None, socket.AF_INET)
  967. b = socket.getaddrinfo(HOST, None, family=socket.AF_INET)
  968. self.assertEqual(a, b)
  969. a = socket.getaddrinfo(HOST, None, 0, socket.SOCK_STREAM)
  970. b = socket.getaddrinfo(HOST, None, type=socket.SOCK_STREAM)
  971. self.assertEqual(a, b)
  972. a = socket.getaddrinfo(HOST, None, 0, 0, socket.SOL_TCP)
  973. b = socket.getaddrinfo(HOST, None, proto=socket.SOL_TCP)
  974. self.assertEqual(a, b)
  975. a = socket.getaddrinfo(HOST, None, 0, 0, 0, socket.AI_PASSIVE)
  976. b = socket.getaddrinfo(HOST, None, flags=socket.AI_PASSIVE)
  977. self.assertEqual(a, b)
  978. a = socket.getaddrinfo(None, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0,
  979. socket.AI_PASSIVE)
  980. b = socket.getaddrinfo(host=None, port=0, family=socket.AF_UNSPEC,
  981. type=socket.SOCK_STREAM, proto=0,
  982. flags=socket.AI_PASSIVE)
  983. self.assertEqual(a, b)
  984. # Issue #6697.
  985. self.assertRaises(UnicodeEncodeError, socket.getaddrinfo, 'localhost', '\uD800')
  986. def test_getnameinfo(self):
  987. # only IP addresses are allowed
  988. self.assertRaises(OSError, socket.getnameinfo, ('mail.python.org',0), 0)
  989. @unittest.skipUnless(support.is_resource_enabled('network'),
  990. 'network is not enabled')
  991. def test_idna(self):
  992. # Check for internet access before running test (issue #12804).
  993. try:
  994. socket.gethostbyname('python.org')
  995. except socket.gaierror as e:
  996. if e.errno == socket.EAI_NODATA:
  997. self.skipTest('internet access required for this test')
  998. # these should all be successful
  999. socket.gethostbyname('испытание.python.org')
  1000. socket.gethostbyname_ex('испытание.python.org')
  1001. socket.getaddrinfo('испытание.python.org',0,socket.AF_UNSPEC,socket.SOCK_STREAM)
  1002. # this may not work if the forward lookup choses the IPv6 address, as that doesn't
  1003. # have a reverse entry yet
  1004. # socket.gethostbyaddr('испытание.python.org')
  1005. def check_sendall_interrupted(self, with_timeout):
  1006. # socketpair() is not stricly required, but it makes things easier.
  1007. if not hasattr(signal, 'alarm') or not hasattr(socket, 'socketpair'):
  1008. self.skipTest("signal.alarm and socket.socketpair required for this test")
  1009. # Our signal handlers clobber the C errno by calling a math function
  1010. # with an invalid domain value.
  1011. def ok_handler(*args):
  1012. self.assertRaises(ValueError, math.acosh, 0)
  1013. def raising_handler(*args):
  1014. self.assertRaises(ValueError, math.acosh, 0)
  1015. 1 // 0
  1016. c, s = socket.socketpair()
  1017. old_alarm = signal.signal(signal.SIGALRM, raising_handler)
  1018. try:
  1019. if with_timeout:
  1020. # Just above the one second minimum for signal.alarm
  1021. c.settimeout(1.5)
  1022. with self.assertRaises(ZeroDivisionError):
  1023. signal.alarm(1)
  1024. c.sendall(b"x" * (1024**2))
  1025. if with_timeout:
  1026. signal.signal(signal.SIGALRM, ok_handler)
  1027. signal.alarm(1)
  1028. self.assertRaises(socket.timeout, c.sendall, b"x" * (1024**2))
  1029. finally:
  1030. signal.signal(signal.SIGALRM, old_alarm)
  1031. c.close()
  1032. s.close()
  1033. def test_sendall_interrupted(self):
  1034. self.check_sendall_interrupted(False)
  1035. def test_sendall_interrupted_with_timeout(self):
  1036. self.check_sendall_interrupted(True)
  1037. def test_dealloc_warn(self):
  1038. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  1039. r = repr(sock)
  1040. with self.assertWarns(ResourceWarning) as cm:
  1041. sock = None
  1042. support.gc_collect()
  1043. self.assertIn(r, str(cm.warning.args[0]))
  1044. # An open socket file object gets dereferenced after the socket
  1045. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  1046. f = sock.makefile('rb')
  1047. r = repr(sock)
  1048. sock = None
  1049. support.gc_collect()
  1050. with self.assertWarns(ResourceWarning):
  1051. f = None
  1052. support.gc_collect()
  1053. def test_name_closed_socketio(self):
  1054. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
  1055. fp = sock.makefile("rb")
  1056. fp.close()
  1057. self.assertEqual(repr(fp), "<_io.BufferedReader name=-1>")
  1058. def test_unusable_closed_socketio(self):
  1059. with socket.socket() as sock:
  1060. fp = sock.makefile("rb", buffering=0)
  1061. self.assertTrue(fp.readable())
  1062. self.assertFalse(fp.writable())
  1063. self.assertFalse(fp.seekable())
  1064. fp.close()
  1065. self.assertRaises(ValueError, fp.readable)
  1066. self.assertRaises(ValueError, fp.writable)
  1067. self.assertRaises(ValueError, fp.seekable)
  1068. def test_pickle(self):
  1069. sock = socket.socket()
  1070. with sock:
  1071. for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
  1072. self.assertRaises(TypeError, pickle.dumps, sock, protocol)
  1073. def test_listen_backlog0(self):
  1074. srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  1075. srv.bind((HOST, 0))
  1076. # backlog = 0
  1077. srv.listen(0)
  1078. srv.close()
  1079. @unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 required for this test.')
  1080. def test_flowinfo(self):
  1081. self.assertRaises(OverflowError, socket.getnameinfo,
  1082. ('::1',0, 0xffffffff), 0)
  1083. with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s:
  1084. self.assertRaises(OverflowError, s.bind, ('::1', 0, -10))
  1085. @unittest.skipUnless(HAVE_SOCKET_CAN, 'SocketCan required for this test.')
  1086. class BasicCANTest(unittest.TestCase):
  1087. def testCrucialConstants(self):
  1088. socket.AF_CAN
  1089. socket.PF_CAN
  1090. socket.CAN_RAW
  1091. def testCreateSocket(self):
  1092. with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
  1093. pass
  1094. def testBindAny(self):
  1095. with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
  1096. s.bind(('', ))
  1097. def testTooLongInterfaceName(self):
  1098. # most systems limit IFNAMSIZ to 16, take 1024 to be sure
  1099. with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
  1100. self.assertRaisesRegex(OSError, 'interface name too long',
  1101. s.bind, ('x' * 1024,))
  1102. @unittest.skipUnless(hasattr(socket, "CAN_RAW_LOOPBACK"),
  1103. 'socket.CAN_RAW_LOOPBACK required for this test.')
  1104. def testLoopback(self):
  1105. with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
  1106. for loopback in (0, 1):
  1107. s.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_LOOPBACK,
  1108. loopback)
  1109. self.assertEqual(loopback,
  1110. s.getsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_LOOPBACK))
  1111. @unittest.skipUnless(hasattr(socket, "CAN_RAW_FILTER"),
  1112. 'socket.CAN_RAW_FILTER required for this test.')
  1113. def testFilter(self):
  1114. can_id, can_mask = 0x200, 0x700
  1115. can_filter = struct.pack("=II", can_id, can_mask)
  1116. with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
  1117. s.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_FILTER, can_filter)
  1118. self.assertEqual(can_filter,
  1119. s.getsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_FILTER, 8))
  1120. @unittest.skipUnless(HAVE_SOCKET_CAN, 'SocketCan required for this test.')
  1121. @unittest.skipUnless(thread, 'Threading required for this test.')
  1122. class CANTest(ThreadedCANSocketTest):
  1123. """The CAN frame structure is defined in <linux/can.h>:
  1124. struct can_frame {
  1125. canid_t can_id; /* 32 bit CAN_ID + EFF/RTR/ERR flags */
  1126. __u8 can_dlc; /* data length code: 0 .. 8 */
  1127. __u8 data[8] __attribute__((aligned(8)));
  1128. };
  1129. """
  1130. can_frame_fmt = "=IB3x8s"
  1131. def __init__(self, methodName='runTest'):
  1132. ThreadedCANSocketTest.__init__(self, methodName=methodName)
  1133. @classmethod
  1134. def build_can_frame(cls, can_id, data):
  1135. """Build a CAN frame."""
  1136. can_dlc = len(data)
  1137. data = data.ljust(8, b'\x00')
  1138. return struct.pack(cls.can_frame_fmt, can_id, can_dlc, data)
  1139. @classmethod
  1140. def dissect_can_frame(cls, frame):
  1141. """Dissect a CAN frame."""
  1142. can_id, can_dlc, data = struct.unpack(cls.can_frame_fmt, frame)
  1143. return (can_id, can_dlc, data[:can_dlc])
  1144. def testSendFrame(self):
  1145. cf, addr = self.s.recvfrom(self.bufsize)
  1146. self.assertEqual(self.cf, cf)
  1147. self.assertEqual(addr[0], self.interface)
  1148. self.assertEqual(addr[1], socket.AF_CAN)
  1149. def _testSendFrame(self):
  1150. self.cf = self.build_can_frame(0x00, b'\x01\x02\x03\x04\x05')
  1151. self.cli.send(self.cf)
  1152. def testSendMaxFrame(self):
  1153. cf, addr = self.s.recvfrom(self.bufsize)
  1154. self.assertEqual(self.cf, cf)
  1155. def _testSendMaxFrame(self):
  1156. self.cf = self.build_can_frame(0x00, b'\x07' * 8)
  1157. self.cli.send(self.cf)
  1158. def testSendMultiFrames(self):
  1159. cf, addr = self.s.recvfrom(self.bufsize)
  1160. self.assertEqual(self.cf1, cf)
  1161. cf, addr = self.s.recvfrom(self.bufsize)
  1162. self.assertEqual(self.cf2, cf)
  1163. def _testSendMultiFrames(self):
  1164. self.cf1 = self.build_can_frame(0x07, b'\x44\x33\x22\x11')
  1165. self.cli.send(self.cf1)
  1166. self.cf2 = self.build_can_frame(0x12, b'\x99\x22\x33')
  1167. self.cli.send(self.cf2)
  1168. @unittest.skipUnless(HAVE_SOCKET_RDS, 'RDS sockets required for this test.')
  1169. class BasicRDSTest(unittest.TestCase):
  1170. def testCrucialConstants(self):
  1171. socket.AF_RDS
  1172. socket.PF_RDS
  1173. def testCreateSocket(self):
  1174. with socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0) as s:
  1175. pass
  1176. def testSocketBufferSize(self):
  1177. bufsize = 16384
  1178. with socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0) as s:
  1179. s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, bufsize)
  1180. s.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, bufsize)
  1181. @unittest.skipUnless(HAVE_SOCKET_RDS, 'RDS sockets required for this test.')
  1182. @unittest.skipUnless(thread, 'Threading required for this test.')
  1183. class RDSTest(ThreadedRDSSocketTest):
  1184. def __init__(self, methodName='runTest'):
  1185. ThreadedRDSSocketTest.__init__(self, methodName=methodName)
  1186. def setUp(self):
  1187. super().setUp()
  1188. self.evt = threading.Event()
  1189. def testSendAndRecv(self):
  1190. data, addr = self.serv.recvfrom(self.bufsize)
  1191. self.assertEqual(self.data, data)
  1192. self.assertEqual(self.cli_addr, addr)
  1193. def _testSendAndRecv(self):
  1194. self.data = b'spam'
  1195. self.cli.sendto(self.data, 0, (HOST, self.port))
  1196. def testPeek(self):
  1197. data, addr = self.serv.recvfrom(self.bufsize, socket.MSG_PEEK)
  1198. self.assertEqual(self.data, data)
  1199. data, addr = self.serv.recvfrom(self.bufsize)
  1200. self.assertEqual(self.data, data)
  1201. def _testPeek(self):
  1202. self.data = b'spam'
  1203. self.cli.sendto(self.data, 0, (HOST, self.port))
  1204. @requireAttrs(socket.socket, 'recvmsg')
  1205. def testSendAndRecvMsg(self):
  1206. data, ancdata, msg_flags, addr = self.serv.recvmsg(self.bufsize)
  1207. self.assertEqual(self.data, data)
  1208. @requireAttrs(socket.socket, 'sendmsg')
  1209. def _testSendAndRecvMsg(self):
  1210. self.data = b'hello ' * 10
  1211. self.cli.sendmsg([self.data], (), 0, (HOST, self.port))
  1212. def testSendAndRecvMulti(self):
  1213. data, addr = self.serv.recvfrom(self.bufsize)
  1214. self.assertEqual(self.data1, data)
  1215. data, addr = self.serv.recvfrom(self.bufsize)
  1216. self.assertEqual(self.data2, data)
  1217. def _testSendAndRecvMulti(self):
  1218. self.data1 = b'bacon'
  1219. self.cli.sendto(self.data1, 0, (HOST, self.port))
  1220. self.data2 = b'egg'
  1221. self.cli.sendto(self.data2, 0, (HOST, self.port))
  1222. def testSelect(self):
  1223. r, w, x = select.select([self.serv], [], [], 3.0)
  1224. self.assertIn(self.serv, r)
  1225. data, addr = self.serv.recvfrom(self.bufsize)
  1226. self.assertEqual(self.data, data)
  1227. def _testSelect(self):
  1228. self.data = b'select'
  1229. self.cli.sendto(self.data, 0, (HOST, self.port))
  1230. def testCongestion(self):
  1231. # wait until the sender is done
  1232. self.evt.wait()
  1233. def _testCongestion(self):
  1234. # test the behavior in case of congestion
  1235. self.data = b'fill'
  1236. self.cli.setblocking(False)
  1237. try:
  1238. # try to lower the receiver's socket buffer size
  1239. self.cli.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 16384)
  1240. except OSError:
  1241. pass
  1242. with self.assertRaises(OSError) as cm:
  1243. try:
  1244. # fill the receiver's socket buffer
  1245. while True:
  1246. self.cli.sendto(self.data, 0, (HOST, self.port))
  1247. finally:
  1248. # signal the receiver we're done
  1249. self.evt.set()
  1250. # sendto() should have failed with ENOBUFS
  1251. self.assertEqual(cm.exception.errno, errno.ENOBUFS)
  1252. # and we should have received a congestion notification through poll
  1253. r, w, x = select.select([self.serv], [], [], 3.0)
  1254. self.assertIn(self.serv, r)
  1255. @unittest.skipUnless(thread, 'Threading required for this test.')
  1256. class BasicTCPTest(SocketConnectedTest):
  1257. def __init__(self, methodName='runTest'):
  1258. SocketConnectedTest.__init__(self, methodName=methodName)
  1259. def testRecv(self):
  1260. # Testing large receive over TCP
  1261. msg = self.cli_conn.recv(1024)
  1262. self.assertEqual(msg, MSG)
  1263. def _testRecv(self):
  1264. self.serv_conn.send(MSG)
  1265. def testOverFlowRecv(self):
  1266. # Testing receive in chunks over TCP
  1267. seg1 = self.cli_conn.recv(len(MSG) - 3)
  1268. seg2 = self.cli_conn.recv(1024)
  1269. msg = seg1 + seg2
  1270. self.assertEqual(msg, MSG)
  1271. def _testOverFlowRecv(self):
  1272. self.serv_conn.send(MSG)
  1273. def testRecvFrom(self):
  1274. # Testing large recvfrom() over TCP
  1275. msg, addr = self.cli_conn.recvfrom(1024)
  1276. self.assertEqual(msg, MSG)
  1277. def _testRecvFrom(self):
  1278. self.serv_conn.send(MSG)
  1279. def testOverFlowRecvFrom(self):
  1280. # Testing recvfrom() in chunks over TCP
  1281. seg1, addr = self.cli_conn.recvfrom(len(MSG)-3)
  1282. seg2, addr = self.cli_conn.recvfrom(1024)
  1283. msg = seg1 + seg2
  1284. self.assertEqual(msg, MSG)
  1285. def _testOverFlowRecvFrom(self):
  1286. self.serv_conn.send(MSG)
  1287. def testSendAll(self):
  1288. # Testing sendall() with a 2048 byte string over TCP
  1289. msg = b''
  1290. while 1:
  1291. read = self.cli_conn.recv(1024)
  1292. if not read:
  1293. break
  1294. msg += read
  1295. self.assertEqual(msg, b'f' * 2048)
  1296. def _testSendAll(self):
  1297. big_chunk = b'f' * 2048
  1298. self.serv_conn.sendall(big_chunk)
  1299. def testFromFd(self):
  1300. # Testing fromfd()
  1301. fd = self.cli_conn.fileno()
  1302. sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
  1303. self.addCleanup(sock.close)
  1304. self.assertIsInstance(sock, socket.socket)
  1305. msg = sock.recv(1024)
  1306. self.assertEqual(msg, MSG)
  1307. def _testFromFd(self):
  1308. self.serv_conn.send(MSG)
  1309. def testDup(self):
  1310. # Testing dup()
  1311. sock = self.cli_conn.dup()
  1312. self.addCleanup(sock.close)
  1313. msg = sock.recv(1024)
  1314. self.assertEqual(msg, MSG)
  1315. def _testDup(self):
  1316. self.serv_conn.send(MSG)
  1317. def testShutdown(self):
  1318. # Testing shutdown()
  1319. msg = self.cli_conn.recv(1024)
  1320. self.assertEqual(msg, MSG)
  1321. # wait for _testShutdown to finish: on OS X, when the server
  1322. # closes the connection the client also becomes disconnected,
  1323. # and the client's shutdown call will fail. (Issue #4397.)
  1324. self.done.wait()
  1325. def _testShutdown(self):
  1326. self.serv_conn.send(MSG)
  1327. self.serv_conn.shutdown(2)
  1328. def testDetach(self):
  1329. # Testing detach()
  1330. fileno = self.cli_conn.fileno()
  1331. f = self.cli_conn.detach()
  1332. self.assertEqual(f, fileno)
  1333. # cli_conn cannot be used anymore...
  1334. self.assertTrue(self.cli_conn._closed)
  1335. self.assertRaises(OSError, self.cli_conn.recv, 1024)
  1336. self.cli_conn.close()
  1337. # ...but we can create another socket using the (still open)
  1338. # file descriptor
  1339. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, fileno=f)
  1340. self.addCleanup(sock.close)
  1341. msg = sock.recv(1024)
  1342. self.assertEqual(msg, MSG)
  1343. def _testDetach(self):
  1344. self.serv_conn.send(MSG)
  1345. @unittest.skipUnless(thread, 'Threading required for this test.')
  1346. class BasicUDPTest(ThreadedUDPSocketTest):
  1347. def __init__(self, methodName='runTest'):
  1348. ThreadedUDPSocketTest.__init__(self, methodName=methodName)
  1349. def testSendtoAndRecv(self):
  1350. # Testing sendto() and Recv() over UDP
  1351. msg = self.serv.recv(len(MSG))
  1352. self.assertEqual(msg, MSG)
  1353. def _testSendtoAndRecv(self):
  1354. self.cli.sendto(MSG, 0, (HOST, self.port))
  1355. def testRecvFrom(self):
  1356. # Testing recvfrom() over UDP
  1357. msg, addr = self.serv.recvfrom(len(MSG))
  1358. self.assertEqual(msg, MSG)
  1359. def _testRecvFrom(self):
  1360. self.cli.sendto(MSG, 0, (HOST, self.port))
  1361. def testRecvFromNegative(self):
  1362. # Negative lengths passed to recvfrom should give ValueError.
  1363. self.assertRaises(ValueError, self.serv.recvfrom, -1)
  1364. def _testRecvFromNegative(self):
  1365. self.cli.sendto(MSG, 0, (HOST, self.port))
  1366. # Tests for the sendmsg()/recvmsg() interface. Where possible, the
  1367. # same test code is used with different families and types of socket
  1368. # (e.g. stream, datagram), and tests using recvmsg() are repeated
  1369. # using recvmsg_into().
  1370. #
  1371. # The generic test classes such as SendmsgTests and
  1372. # RecvmsgGenericTests inherit from SendrecvmsgBase and expect to be
  1373. # supplied with sockets cli_sock and serv_sock representing the
  1374. # client's and the server's end of the connection respectively, and
  1375. # attributes cli_addr and serv_addr holding their (numeric where
  1376. # appropriate) addresses.
  1377. #
  1378. # The final concrete test classes combine these with subclasses of
  1379. # SocketTestBase which set up client and server sockets of a specific
  1380. # type, and with subclasses of SendrecvmsgBase such as
  1381. # SendrecvmsgDgramBase and SendrecvmsgConnectedBase which map these
  1382. # sockets to cli_sock and serv_sock and override the methods and
  1383. # attributes of SendrecvmsgBase to fill in destination addresses if
  1384. # needed when sending, check for specific flags in msg_flags, etc.
  1385. #
  1386. # RecvmsgIntoMixin provides a version of doRecvmsg() implemented using
  1387. # recvmsg_into().
  1388. # XXX: like the other datagram (UDP) tests in this module, the code
  1389. # here assumes that datagram delivery on the local machine will be
  1390. # reliable.
  1391. class SendrecvmsgBase(ThreadSafeCleanupTestCase):
  1392. # Base class for sendmsg()/recvmsg() tests.
  1393. # Time in seconds to wait before considering a test failed, or
  1394. # None for no timeout. Not all tests actually set a timeout.
  1395. fail_timeout = 3.0
  1396. def setUp(self):
  1397. self.misc_event = threading.Event()
  1398. super().setUp()
  1399. def sendToServer(self, msg):
  1400. # Send msg to the server.
  1401. return self.cli_sock.send(msg)
  1402. # Tuple of alternative default arguments for sendmsg() when called
  1403. # via sendmsgToServer() (e.g. to include a destination address).
  1404. sendmsg_to_server_defaults = ()
  1405. def sendmsgToServer(self, *args):
  1406. # Call sendmsg() on self.cli_sock with the given arguments,
  1407. # filling in any arguments which are not supplied with the
  1408. # corresponding items of self.sendmsg_to_server_defaults, if
  1409. # any.
  1410. return self.cli_sock.sendmsg(
  1411. *(args + self.sendmsg_to_server_defaults[len(args):]))
  1412. def doRecvmsg(self, sock, bufsize, *args):
  1413. # Call recvmsg() on sock with given arguments and return its
  1414. # result. Should be used for tests which can use either
  1415. # recvmsg() or recvmsg_into() - RecvmsgIntoMixin overrides
  1416. # this method with one which emulates it using recvmsg_into(),
  1417. # thus allowing the same test to be used for both methods.
  1418. result = sock.recvmsg(bufsize, *args)
  1419. self.registerRecvmsgResult(result)
  1420. return result
  1421. def registerRecvmsgResult(self, result):
  1422. # Called by doRecvmsg() with the return value of recvmsg() or
  1423. # recvmsg_into(). Can be overridden to arrange cleanup based
  1424. # on the returned ancillary data, for instance.
  1425. pass
  1426. def checkRecvmsgAddress(self, addr1, addr2):
  1427. # Called to compare the received address with the address of
  1428. # the peer.
  1429. self.assertEqual(addr1, addr2)
  1430. # Flags that are normally unset in msg_flags
  1431. msg_flags_common_unset = 0
  1432. for name in ("MSG_CTRUNC", "MSG_OOB"):
  1433. msg_flags_common_unset |= getattr(socket, name, 0)
  1434. # Flags that are normally set
  1435. msg_flags_common_set = 0
  1436. # Flags set when a complete record has been received (e.g. MSG_EOR
  1437. # for SCTP)
  1438. msg_flags_eor_indicator = 0
  1439. # Flags set when a complete record has not been received
  1440. # (e.g. MSG_TRUNC for datagram sockets)
  1441. msg_flags_non_eor_indicator = 0
  1442. def checkFlags(self, flags, eor=None, checkset=0, checkunset=0, ignore=0):
  1443. # Method to check the value of msg_flags returned by recvmsg[_into]().
  1444. #
  1445. # Checks that all bits in msg_flags_common_set attribute are
  1446. # set in "flags" and all bits in msg_flags_common_unset are
  1447. # unset.
  1448. #
  1449. # The "eor" argument specifies whether the flags should
  1450. # indicate that a full record (or datagram) has been received.
  1451. # If "eor" is None, no checks are done; otherwise, checks
  1452. # that:
  1453. #
  1454. # * if "eor" is true, all bits in msg_flags_eor_indicator are
  1455. # set and all bits in msg_flags_non_eor_indicator are unset
  1456. #
  1457. # * if "eor" is false, all bits in msg_flags_non_eor_indicator
  1458. # are set and all bits in msg_flags_eor_indicator are unset
  1459. #
  1460. # If "checkset" and/or "checkunset" are supplied, they require
  1461. # the given bits to be set or unset respectively, overriding
  1462. # what the attributes require for those bits.
  1463. #
  1464. # If any bits are set in "ignore", they will not be checked,
  1465. # regardless of the other inputs.
  1466. #
  1467. # Will raise Exception if the inputs require a bit to be both
  1468. # set and unset, and it is not ignored.
  1469. defaultset = self.msg_flags_common_set
  1470. defaultunset = self.msg_flags_common_unset
  1471. if eor:
  1472. defaultset |= self.msg_flags_eor_indicator
  1473. defaultunset |= self.msg_flags_non_eor_indicator
  1474. elif eor is not None:
  1475. defaultset |= self.msg_flags_non_eor_indicator
  1476. defaultunset |= self.msg_flags_eor_indicator
  1477. # Function arguments override defaults
  1478. defaultset &= ~checkunset
  1479. defaultunset &= ~checkset
  1480. # Merge arguments with remaining defaults, and check for conflicts
  1481. checkset |= defaultset
  1482. checkunset |= defaultunset
  1483. inboth = checkset & checkunset & ~ignore
  1484. if inboth:
  1485. raise Exception("contradictory set, unset requirements for flags "
  1486. "{0:#x}".format(inboth))
  1487. # Compare with given msg_flags value
  1488. mask = (checkset | checkunset) & ~ignore
  1489. self.assertEqual(flags & mask, checkset & mask)
  1490. class RecvmsgIntoMixin(SendrecvmsgBase):
  1491. # Mixin to implement doRecvmsg() using recvmsg_into().
  1492. def doRecvmsg(self, sock, bufsize, *args):
  1493. buf = bytearray(bufsize)
  1494. result = sock.recvmsg_into([buf], *args)
  1495. self.registerRecvmsgResult(result)
  1496. self.assertGreaterEqual(result[0], 0)
  1497. self.assertLessEqual(result[0], bufsize)
  1498. return (bytes(buf[:result[0]]),) + result[1:]
  1499. class SendrecvmsgDgramFlagsBase(SendrecvmsgBase):
  1500. # Defines flags to be checked in msg_flags for datagram sockets.
  1501. @property
  1502. def msg_flags_non_eor_indicator(self):
  1503. return super().msg_flags_non_eor_indicator | socket.MSG_TRUNC
  1504. class SendrecvmsgSCTPFlagsBase(SendrecvmsgBase):
  1505. # Defines flags to be checked in msg_flags for SCTP sockets.
  1506. @property
  1507. def msg_flags_eor_indicator(self):
  1508. return super().msg_flags_eor_indicator | socket.MSG_EOR
  1509. class SendrecvmsgConnectionlessBase(SendrecvmsgBase):
  1510. # Base class for tests on connectionless-mode sockets. Users must
  1511. # supply sockets on attributes cli and serv to be mapped to
  1512. # cli_sock and serv_sock respectively.
  1513. @property
  1514. def serv_sock(self):
  1515. return self.serv
  1516. @property
  1517. def cli_sock(self):
  1518. return self.cli
  1519. @property
  1520. def sendmsg_to_server_defaults(self):
  1521. return ([], [], 0, self.serv_addr)
  1522. def sendToServer(self, msg):
  1523. return self.cli_sock.sendto(msg, self.serv_addr)
  1524. class SendrecvmsgConnectedBase(SendrecvmsgBase):
  1525. # Base class for tests on connected sockets. Users must supply
  1526. # sockets on attributes serv_conn and cli_conn (representing the
  1527. # connections *to* the server and the client), to be mapped to
  1528. # cli_sock and serv_sock respectively.
  1529. @property
  1530. def serv_sock(self):
  1531. return self.cli_conn
  1532. @property
  1533. def cli_sock(self):
  1534. return self.serv_conn
  1535. def checkRecvmsgAddress(self, addr1, addr2):
  1536. # Address is currently "unspecified" for a connected socket,
  1537. # so we don't examine it
  1538. pass
  1539. class SendrecvmsgServerTimeoutBase(SendrecvmsgBase):
  1540. # Base class to set a timeout on server's socket.
  1541. def setUp(self):
  1542. super().setUp()
  1543. self.serv_sock.settimeout(self.fail_timeout)
  1544. class SendmsgTests(SendrecvmsgServerTimeoutBase):
  1545. # Tests for sendmsg() which can use any socket type and do not
  1546. # involve recvmsg() or recvmsg_into().
  1547. def testSendmsg(self):
  1548. # Send a simple message with sendmsg().
  1549. self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
  1550. def _testSendmsg(self):
  1551. self.assertEqual(self.sendmsgToServer([MSG]), len(MSG))
  1552. def testSendmsgDataGenerator(self):
  1553. # Send from buffer obtained from a generator (not a sequence).
  1554. self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
  1555. def _testSendmsgDataGenerator(self):
  1556. self.assertEqual(self.sendmsgToServer((o for o in [MSG])),
  1557. len(MSG))
  1558. def testSendmsgAncillaryGenerator(self):
  1559. # Gather (empty) ancillary data from a generator.
  1560. self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
  1561. def _testSendmsgAncillaryGenerator(self):
  1562. self.assertEqual(self.sendmsgToServer([MSG], (o for o in [])),
  1563. len(MSG))
  1564. def testSendmsgArray(self):
  1565. # Send data from an array instead of the usual bytes object.
  1566. self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
  1567. def _testSendmsgArray(self):
  1568. self.assertEqual(self.sendmsgToServer([array.array("B", MSG)]),
  1569. len(MSG))
  1570. def testSendmsgGather(self):
  1571. # Send message data from more than one buffer (gather write).
  1572. self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
  1573. def _testSendmsgGather(self):
  1574. self.assertEqual(self.sendmsgToServer([MSG[:3], MSG[3:]]), len(MSG))
  1575. def testSendmsgBadArgs(self):
  1576. # Check that sendmsg() rejects invalid arguments.
  1577. self.assertEqual(self.serv_sock.recv(1000), b"done")
  1578. def _testSendmsgBadArgs(self):
  1579. self.assertRaises(TypeError, self.cli_sock.sendmsg)
  1580. self.assertRaises(TypeError, self.sendmsgToServer,
  1581. b"not in an iterable")
  1582. self.assertRaises(TypeError, self.sendmsgToServer,
  1583. object())
  1584. self.assertRaises(TypeError, self.sendmsgToServer,
  1585. [object()])
  1586. self.assertRaises(TypeError, self.sendmsgToServer,
  1587. [MSG, object()])
  1588. self.assertRaises(TypeError, self.sendmsgToServer,
  1589. [MSG], object())
  1590. self.assertRaises(TypeError, self.sendmsgToServer,
  1591. [MSG], [], object())
  1592. self.assertRaises(TypeError, self.sendmsgToServer,
  1593. [MSG], [], 0, object())
  1594. self.sendToServer(b"done")
  1595. def testSendmsgBadCmsg(self):
  1596. # Check that invalid ancillary data items are rejected.
  1597. self.assertEqual(self.serv_sock.recv(1000), b"done")
  1598. def _testSendmsgBadCmsg(self):
  1599. self.assertRaises(TypeError, self.sendmsgToServer,
  1600. [MSG], [object()])
  1601. self.assertRaises(TypeError, self.sendmsgToServer,
  1602. [MSG], [(object(), 0, b"data")])
  1603. self.assertRaises(TypeError, self.sendmsgToServer,
  1604. [MSG], [(0, object(), b"data")])
  1605. self.assertRaises(TypeError, self.sendmsgToServer,
  1606. [MSG], [(0, 0, object())])
  1607. self.assertRaises(TypeError, self.sendmsgToServer,
  1608. [MSG], [(0, 0)])
  1609. self.assertRaises(TypeError, self.sendmsgToServer,
  1610. [MSG], [(0, 0, b"data", 42)])
  1611. self.sendToServer(b"done")
  1612. @requireAttrs(socket, "CMSG_SPACE")
  1613. def testSendmsgBadMultiCmsg(self):
  1614. # Check that invalid ancillary data items are rejected when
  1615. # more than one item is present.
  1616. self.assertEqual(self.serv_sock.recv(1000), b"done")
  1617. @testSendmsgBadMultiCmsg.client_skip
  1618. def _testSendmsgBadMultiCmsg(self):
  1619. self.assertRaises(TypeError, self.sendmsgToServer,
  1620. [MSG], [0, 0, b""])
  1621. self.assertRaises(TypeError, self.sendmsgToServer,
  1622. [MSG], [(0, 0, b""), object()])
  1623. self.sendToServer(b"done")
  1624. def testSendmsgExcessCmsgReject(self):
  1625. # Check that sendmsg() rejects excess ancillary data items
  1626. # when the number that can be sent is limited.
  1627. self.assertEqual(self.serv_sock.recv(1000), b"done")
  1628. def _testSendmsgExcessCmsgReject(self):
  1629. if not hasattr(socket, "CMSG_SPACE"):
  1630. # Can only send one item
  1631. with self.assertRaises(OSError) as cm:
  1632. self.sendmsgToServer([MSG], [(0, 0, b""), (0, 0, b"")])
  1633. self.assertIsNone(cm.exception.errno)
  1634. self.sendToServer(b"done")
  1635. def testSendmsgAfterClose(self):
  1636. # Check that sendmsg() fails on a closed socket.
  1637. pass
  1638. def _testSendmsgAfterClose(self):
  1639. self.cli_sock.close()
  1640. self.assertRaises(OSError, self.sendmsgToServer, [MSG])
  1641. class SendmsgStreamTests(SendmsgTests):
  1642. # Tests for sendmsg() which require a stream socket and do not
  1643. # involve recvmsg() or recvmsg_into().
  1644. def testSendmsgExplicitNoneAddr(self):
  1645. # Check that peer address can be specified as None.
  1646. self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
  1647. def _testSendmsgExplicitNoneAddr(self):
  1648. self.assertEqual(self.sendmsgToServer([MSG], [], 0, None), len(MSG))
  1649. def testSendmsgTimeout(self):
  1650. # Check that timeout works with sendmsg().
  1651. self.assertEqual(self.serv_sock.recv(512), b"a"*512)
  1652. self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
  1653. def _testSendmsgTimeout(self):
  1654. try:
  1655. self.cli_sock.settimeout(0.03)
  1656. with self.assertRaises(socket.timeout):
  1657. while True:
  1658. self.sendmsgToServer([b"a"*512])
  1659. finally:
  1660. self.misc_event.set()
  1661. # XXX: would be nice to have more tests for sendmsg flags argument.
  1662. # Linux supports MSG_DONTWAIT when sending, but in general, it
  1663. # only works when receiving. Could add other platforms if they
  1664. # support it too.
  1665. @skipWithClientIf(sys.platform not in {"linux2"},
  1666. "MSG_DONTWAIT not known to work on this platform when "
  1667. "sending")
  1668. def testSendmsgDontWait(self):
  1669. # Check that MSG_DONTWAIT in flags causes non-blocking behaviour.
  1670. self.assertEqual(self.serv_sock.recv(512), b"a"*512)
  1671. self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
  1672. @testSendmsgDontWait.client_skip
  1673. def _testSendmsgDontWait(self):
  1674. try:
  1675. with self.assertRaises(OSError) as cm:
  1676. while True:
  1677. self.sendmsgToServer([b"a"*512], [], socket.MSG_DONTWAIT)
  1678. self.assertIn(cm.exception.errno,
  1679. (errno.EAGAIN, errno.EWOULDBLOCK))
  1680. finally:
  1681. self.misc_event.set()
  1682. class SendmsgConnectionlessTests(SendmsgTests):
  1683. # Tests for sendmsg() which require a connectionless-mode
  1684. # (e.g. datagram) socket, and do not involve recvmsg() or
  1685. # recvmsg_into().
  1686. def testSendmsgNoDestAddr(self):
  1687. # Check that sendmsg() fails when no destination address is
  1688. # given for unconnected socket.
  1689. pass
  1690. def _testSendmsgNoDestAddr(self):
  1691. self.assertRaises(OSError, self.cli_sock.sendmsg,
  1692. [MSG])
  1693. self.assertRaises(OSError, self.cli_sock.sendmsg,
  1694. [MSG], [], 0, None)
  1695. class RecvmsgGenericTests(SendrecvmsgBase):
  1696. # Tests for recvmsg() which can also be emulated using
  1697. # recvmsg_into(), and can use any socket type.
  1698. def testRecvmsg(self):
  1699. # Receive a simple message with recvmsg[_into]().
  1700. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, len(MSG))
  1701. self.assertEqual(msg, MSG)
  1702. self.checkRecvmsgAddress(addr, self.cli_addr)
  1703. self.assertEqual(ancdata, [])
  1704. self.checkFlags(flags, eor=True)
  1705. def _testRecvmsg(self):
  1706. self.sendToServer(MSG)
  1707. def testRecvmsgExplicitDefaults(self):
  1708. # Test recvmsg[_into]() with default arguments provided explicitly.
  1709. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
  1710. len(MSG), 0, 0)
  1711. self.assertEqual(msg, MSG)
  1712. self.checkRecvmsgAddress(addr, self.cli_addr)
  1713. self.assertEqual(ancdata, [])
  1714. self.checkFlags(flags, eor=True)
  1715. def _testRecvmsgExplicitDefaults(self):
  1716. self.sendToServer(MSG)
  1717. def testRecvmsgShorter(self):
  1718. # Receive a message smaller than buffer.
  1719. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
  1720. len(MSG) + 42)
  1721. self.assertEqual(msg, MSG)
  1722. self.checkRecvmsgAddress(addr, self.cli_addr)
  1723. self.assertEqual(ancdata, [])
  1724. self.checkFlags(flags, eor=True)
  1725. def _testRecvmsgShorter(self):
  1726. self.sendToServer(MSG)
  1727. # FreeBSD < 8 doesn't always set the MSG_TRUNC flag when a truncated
  1728. # datagram is received (issue #13001).
  1729. @support.requires_freebsd_version(8)
  1730. def testRecvmsgTrunc(self):
  1731. # Receive part of message, check for truncation indicators.
  1732. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
  1733. len(MSG) - 3)
  1734. self.assertEqual(msg, MSG[:-3])
  1735. self.checkRecvmsgAddress(addr, self.cli_addr)
  1736. self.assertEqual(ancdata, [])
  1737. self.checkFlags(flags, eor=False)
  1738. @support.requires_freebsd_version(8)
  1739. def _testRecvmsgTrunc(self):
  1740. self.sendToServer(MSG)
  1741. def testRecvmsgShortAncillaryBuf(self):
  1742. # Test ancillary data buffer too small to hold any ancillary data.
  1743. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
  1744. len(MSG), 1)
  1745. self.assertEqual(msg, MSG)
  1746. self.checkRecvmsgAddress(addr, self.cli_addr)
  1747. self.assertEqual(ancdata, [])
  1748. self.checkFlags(flags, eor=True)
  1749. def _testRecvmsgShortAncillaryBuf(self):
  1750. self.sendToServer(MSG)
  1751. def testRecvmsgLongAncillaryBuf(self):
  1752. # Test large ancillary data buffer.
  1753. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
  1754. len(MSG), 10240)
  1755. self.assertEqual(msg, MSG)
  1756. self.checkRecvmsgAddress(addr, self.cli_addr)
  1757. self.assertEqual(ancdata, [])
  1758. self.checkFlags(flags, eor=True)
  1759. def _testRecvmsgLongAncillaryBuf(self):
  1760. self.sendToServer(MSG)
  1761. def testRecvmsgAfterClose(self):
  1762. # Check that recvmsg[_into]() fails on a closed socket.
  1763. self.serv_sock.close()
  1764. self.assertRaises(OSError, self.doRecvmsg, self.serv_sock, 1024)
  1765. def _testRecvmsgAfterClose(self):
  1766. pass
  1767. def testRecvmsgTimeout(self):
  1768. # Check that timeout works.
  1769. try:
  1770. self.serv_sock.settimeout(0.03)
  1771. self.assertRaises(socket.timeout,
  1772. self.doRecvmsg, self.serv_sock, len(MSG))
  1773. finally:
  1774. self.misc_event.set()
  1775. def _testRecvmsgTimeout(self):
  1776. self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
  1777. @requireAttrs(socket, "MSG_PEEK")
  1778. def testRecvmsgPeek(self):
  1779. # Check that MSG_PEEK in flags enables examination of pending
  1780. # data without consuming it.
  1781. # Receive part of data with MSG_PEEK.
  1782. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
  1783. len(MSG) - 3, 0,
  1784. socket.MSG_PEEK)
  1785. self.assertEqual(msg, MSG[:-3])
  1786. self.checkRecvmsgAddress(addr, self.cli_addr)
  1787. self.assertEqual(ancdata, [])
  1788. # Ignoring MSG_TRUNC here (so this test is the same for stream
  1789. # and datagram sockets). Some wording in POSIX seems to
  1790. # suggest that it needn't be set when peeking, but that may
  1791. # just be a slip.
  1792. self.checkFlags(flags, eor=False,
  1793. ignore=getattr(socket, "MSG_TRUNC", 0))
  1794. # Receive all data with MSG_PEEK.
  1795. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
  1796. len(MSG), 0,
  1797. socket.MSG_PEEK)
  1798. self.assertEqual(msg, MSG)
  1799. self.checkRecvmsgAddress(addr, self.cli_addr)
  1800. self.assertEqual(ancdata, [])
  1801. self.checkFlags(flags, eor=True)
  1802. # Check that the same data can still be received normally.
  1803. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, len(MSG))
  1804. self.assertEqual(msg, MSG)
  1805. self.checkRecvmsgAddress(addr, self.cli_addr)
  1806. self.assertEqual(ancdata, [])
  1807. self.checkFlags(flags, eor=True)
  1808. @testRecvmsgPeek.client_skip
  1809. def _testRecvmsgPeek(self):
  1810. self.sendToServer(MSG)
  1811. @requireAttrs(socket.socket, "sendmsg")
  1812. def testRecvmsgFromSendmsg(self):
  1813. # Test receiving with recvmsg[_into]() when message is sent
  1814. # using sendmsg().
  1815. self.serv_sock.settimeout(self.fail_timeout)
  1816. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, len(MSG))
  1817. self.assertEqual(msg, MSG)
  1818. self.checkRecvmsgAddress(addr, self.cli_addr)
  1819. self.assertEqual(ancdata, [])
  1820. self.checkFlags(flags, eor=True)
  1821. @testRecvmsgFromSendmsg.client_skip
  1822. def _testRecvmsgFromSendmsg(self):
  1823. self.assertEqual(self.sendmsgToServer([MSG[:3], MSG[3:]]), len(MSG))
  1824. class RecvmsgGenericStreamTests(RecvmsgGenericTests):
  1825. # Tests which require a stream socket and can use either recvmsg()
  1826. # or recvmsg_into().
  1827. def testRecvmsgEOF(self):
  1828. # Receive end-of-stream indicator (b"", peer socket closed).
  1829. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, 1024)
  1830. self.assertEqual(msg, b"")
  1831. self.checkRecvmsgAddress(addr, self.cli_addr)
  1832. self.assertEqual(ancdata, [])
  1833. self.checkFlags(flags, eor=None) # Might not have end-of-record marker
  1834. def _testRecvmsgEOF(self):
  1835. self.cli_sock.close()
  1836. def testRecvmsgOverflow(self):
  1837. # Receive a message in more than one chunk.
  1838. seg1, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
  1839. len(MSG) - 3)
  1840. self.checkRecvmsgAddress(addr, self.cli_addr)
  1841. self.assertEqual(ancdata, [])
  1842. self.checkFlags(flags, eor=False)
  1843. seg2, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, 1024)
  1844. self.checkRecvmsgAddress(addr, self.cli_addr)
  1845. self.assertEqual(ancdata, [])
  1846. self.checkFlags(flags, eor=True)
  1847. msg = seg1 + seg2
  1848. self.assertEqual(msg, MSG)
  1849. def _testRecvmsgOverflow(self):
  1850. self.sendToServer(MSG)
  1851. class RecvmsgTests(RecvmsgGenericTests):
  1852. # Tests for recvmsg() which can use any socket type.
  1853. def testRecvmsgBadArgs(self):
  1854. # Check that recvmsg() rejects invalid arguments.
  1855. self.assertRaises(TypeError, self.serv_sock.recvmsg)
  1856. self.assertRaises(ValueError, self.serv_sock.recvmsg,
  1857. -1, 0, 0)
  1858. self.assertRaises(ValueError, self.serv_sock.recvmsg,
  1859. len(MSG), -1, 0)
  1860. self.assertRaises(TypeError, self.serv_sock.recvmsg,
  1861. [bytearray(10)], 0, 0)
  1862. self.assertRaises(TypeError, self.serv_sock.recvmsg,
  1863. object(), 0, 0)
  1864. self.assertRaises(TypeError, self.serv_sock.recvmsg,
  1865. len(MSG), object(), 0)
  1866. self.assertRaises(TypeError, self.serv_sock.recvmsg,
  1867. len(MSG), 0, object())
  1868. msg, ancdata, flags, addr = self.serv_sock.recvmsg(len(MSG), 0, 0)
  1869. self.assertEqual(msg, MSG)
  1870. self.checkRecvmsgAddress(addr, self.cli_addr)
  1871. self.assertEqual(ancdata, [])
  1872. self.checkFlags(flags, eor=True)
  1873. def _testRecvmsgBadArgs(self):
  1874. self.sendToServer(MSG)
  1875. class RecvmsgIntoTests(RecvmsgIntoMixin, RecvmsgGenericTests):
  1876. # Tests for recvmsg_into() which can use any socket type.
  1877. def testRecvmsgIntoBadArgs(self):
  1878. # Check that recvmsg_into() rejects invalid arguments.
  1879. buf = bytearray(len(MSG))
  1880. self.assertRaises(TypeError, self.serv_sock.recvmsg_into)
  1881. self.assertRaises(TypeError, self.serv_sock.recvmsg_into,
  1882. len(MSG), 0, 0)
  1883. self.assertRaises(TypeError, self.serv_sock.recvmsg_into,
  1884. buf, 0, 0)
  1885. self.assertRaises(TypeError, self.serv_sock.recvmsg_into,
  1886. [object()], 0, 0)
  1887. self.assertRaises(TypeError, self.serv_sock.recvmsg_into,
  1888. [b"I'm not writable"], 0, 0)
  1889. self.assertRaises(TypeError, self.serv_sock.recvmsg_into,
  1890. [buf, object()], 0, 0)
  1891. self.assertRaises(ValueError, self.serv_sock.recvmsg_into,
  1892. [buf], -1, 0)
  1893. self.assertRaises(TypeError, self.serv_sock.recvmsg_into,
  1894. [buf], object(), 0)
  1895. self.assertRaises(TypeError, self.serv_sock.recvmsg_into,
  1896. [buf], 0, object())
  1897. nbytes, ancdata, flags, addr = self.serv_sock.recvmsg_into([buf], 0, 0)
  1898. self.assertEqual(nbytes, len(MSG))
  1899. self.assertEqual(buf, bytearray(MSG))
  1900. self.checkRecvmsgAddress(addr, self.cli_addr)
  1901. self.assertEqual(ancdata, [])
  1902. self.checkFlags(flags, eor=True)
  1903. def _testRecvmsgIntoBadArgs(self):
  1904. self.sendToServer(MSG)
  1905. def testRecvmsgIntoGenerator(self):
  1906. # Receive into buffer obtained from a generator (not a sequence).
  1907. buf = bytearray(len(MSG))
  1908. nbytes, ancdata, flags, addr = self.serv_sock.recvmsg_into(
  1909. (o for o in [buf]))
  1910. self.assertEqual(nbytes, len(MSG))
  1911. self.assertEqual(buf, bytearray(MSG))
  1912. self.checkRecvmsgAddress(addr, self.cli_addr)
  1913. self.assertEqual(ancdata, [])
  1914. self.checkFlags(flags, eor=True)
  1915. def _testRecvmsgIntoGenerator(self):
  1916. self.sendToServer(MSG)
  1917. def testRecvmsgIntoArray(self):
  1918. # Receive into an array rather than the usual bytearray.
  1919. buf = array.array("B", [0] * len(MSG))
  1920. nbytes, ancdata, flags, addr = self.serv_sock.recvmsg_into([buf])
  1921. self.assertEqual(nbytes, len(MSG))
  1922. self.assertEqual(buf.tobytes(), MSG)
  1923. self.checkRecvmsgAddress(addr, self.cli_addr)
  1924. self.assertEqual(ancdata, [])
  1925. self.checkFlags(flags, eor=True)
  1926. def _testRecvmsgIntoArray(self):
  1927. self.sendToServer(MSG)
  1928. def testRecvmsgIntoScatter(self):
  1929. # Receive into multiple buffers (scatter write).
  1930. b1 = bytearray(b"----")
  1931. b2 = bytearray(b"0123456789")
  1932. b3 = bytearray(b"--------------")
  1933. nbytes, ancdata, flags, addr = self.serv_sock.recvmsg_into(
  1934. [b1, memoryview(b2)[2:9], b3])
  1935. self.assertEqual(nbytes, len(b"Mary had a little lamb"))
  1936. self.assertEqual(b1, bytearray(b"Mary"))
  1937. self.assertEqual(b2, bytearray(b"01 had a 9"))
  1938. self.assertEqual(b3, bytearray(b"little lamb---"))
  1939. self.checkRecvmsgAddress(addr, self.cli_addr)
  1940. self.assertEqual(ancdata, [])
  1941. self.checkFlags(flags, eor=True)
  1942. def _testRecvmsgIntoScatter(self):
  1943. self.sendToServer(b"Mary had a little lamb")
  1944. class CmsgMacroTests(unittest.TestCase):
  1945. # Test the functions CMSG_LEN() and CMSG_SPACE(). Tests
  1946. # assumptions used by sendmsg() and recvmsg[_into](), which share
  1947. # code with these functions.
  1948. # Match the definition in socketmodule.c
  1949. socklen_t_limit = min(0x7fffffff, _testcapi.INT_MAX)
  1950. @requireAttrs(socket, "CMSG_LEN")
  1951. def testCMSG_LEN(self):
  1952. # Test CMSG_LEN() with various valid and invalid values,
  1953. # checking the assumptions used by recvmsg() and sendmsg().
  1954. toobig = self.socklen_t_limit - socket.CMSG_LEN(0) + 1
  1955. values = list(range(257)) + list(range(toobig - 257, toobig))
  1956. # struct cmsghdr has at least three members, two of which are ints
  1957. self.assertGreater(socket.CMSG_LEN(0), array.array("i").itemsize * 2)
  1958. for n in values:
  1959. ret = socket.CMSG_LEN(n)
  1960. # This is how recvmsg() calculates the data size
  1961. self.assertEqual(ret - socket.CMSG_LEN(0), n)
  1962. self.assertLessEqual(ret, self.socklen_t_limit)
  1963. self.assertRaises(OverflowError, socket.CMSG_LEN, -1)
  1964. # sendmsg() shares code with these functions, and requires
  1965. # that it reject values over the limit.
  1966. self.assertRaises(OverflowError, socket.CMSG_LEN, toobig)
  1967. self.assertRaises(OverflowError, socket.CMSG_LEN, sys.maxsize)
  1968. @requireAttrs(socket, "CMSG_SPACE")
  1969. def testCMSG_SPACE(self):
  1970. # Test CMSG_SPACE() with various valid and invalid values,
  1971. # checking the assumptions used by sendmsg().
  1972. toobig = self.socklen_t_limit - socket.CMSG_SPACE(1) + 1
  1973. values = list(range(257)) + list(range(toobig - 257, toobig))
  1974. last = socket.CMSG_SPACE(0)
  1975. # struct cmsghdr has at least three members, two of which are ints
  1976. self.assertGreater(last, array.array("i").itemsize * 2)
  1977. for n in values:
  1978. ret = socket.CMSG_SPACE(n)
  1979. self.assertGreaterEqual(ret, last)
  1980. self.assertGreaterEqual(ret, socket.CMSG_LEN(n))
  1981. self.assertGreaterEqual(ret, n + socket.CMSG_LEN(0))
  1982. self.assertLessEqual(ret, self.socklen_t_limit)
  1983. last = ret
  1984. self.assertRaises(OverflowError, socket.CMSG_SPACE, -1)
  1985. # sendmsg() shares code with these functions, and requires
  1986. # that it reject values over the limit.
  1987. self.assertRaises(OverflowError, socket.CMSG_SPACE, toobig)
  1988. self.assertRaises(OverflowError, socket.CMSG_SPACE, sys.maxsize)
  1989. class SCMRightsTest(SendrecvmsgServerTimeoutBase):
  1990. # Tests for file descriptor passing on Unix-domain sockets.
  1991. # Invalid file descriptor value that's unlikely to evaluate to a
  1992. # real FD even if one of its bytes is replaced with a different
  1993. # value (which shouldn't actually happen).
  1994. badfd = -0x5555
  1995. def newFDs(self, n):
  1996. # Return a list of n file descriptors for newly-created files
  1997. # containing their list indices as ASCII numbers.
  1998. fds = []
  1999. for i in range(n):
  2000. fd, path = tempfile.mkstemp()
  2001. self.addCleanup(os.unlink, path)
  2002. self.addCleanup(os.close, fd)
  2003. os.write(fd, str(i).encode())
  2004. fds.append(fd)
  2005. return fds
  2006. def checkFDs(self, fds):
  2007. # Check that the file descriptors in the given list contain
  2008. # their correct list indices as ASCII numbers.
  2009. for n, fd in enumerate(fds):
  2010. os.lseek(fd, 0, os.SEEK_SET)
  2011. self.assertEqual(os.read(fd, 1024), str(n).encode())
  2012. def registerRecvmsgResult(self, result):
  2013. self.addCleanup(self.closeRecvmsgFDs, result)
  2014. def closeRecvmsgFDs(self, recvmsg_result):
  2015. # Close all file descriptors specified in the ancillary data
  2016. # of the given return value from recvmsg() or recvmsg_into().
  2017. for cmsg_level, cmsg_type, cmsg_data in recvmsg_result[1]:
  2018. if (cmsg_level == socket.SOL_SOCKET and
  2019. cmsg_type == socket.SCM_RIGHTS):
  2020. fds = array.array("i")
  2021. fds.frombytes(cmsg_data[:
  2022. len(cmsg_data) - (len(cmsg_data) % fds.itemsize)])
  2023. for fd in fds:
  2024. os.close(fd)
  2025. def createAndSendFDs(self, n):
  2026. # Send n new file descriptors created by newFDs() to the
  2027. # server, with the constant MSG as the non-ancillary data.
  2028. self.assertEqual(
  2029. self.sendmsgToServer([MSG],
  2030. [(socket.SOL_SOCKET,
  2031. socket.SCM_RIGHTS,
  2032. array.array("i", self.newFDs(n)))]),
  2033. len(MSG))
  2034. def checkRecvmsgFDs(self, numfds, result, maxcmsgs=1, ignoreflags=0):
  2035. # Check that constant MSG was received with numfds file
  2036. # descriptors in a maximum of maxcmsgs control messages (which
  2037. # must contain only complete integers). By default, check
  2038. # that MSG_CTRUNC is unset, but ignore any flags in
  2039. # ignoreflags.
  2040. msg, ancdata, flags, addr = result
  2041. self.assertEqual(msg, MSG)
  2042. self.checkRecvmsgAddress(addr, self.cli_addr)
  2043. self.checkFlags(flags, eor=True, checkunset=socket.MSG_CTRUNC,
  2044. ignore=ignoreflags)
  2045. self.assertIsInstance(ancdata, list)
  2046. self.assertLessEqual(len(ancdata), maxcmsgs)
  2047. fds = array.array("i")
  2048. for item in ancdata:
  2049. self.assertIsInstance(item, tuple)
  2050. cmsg_level, cmsg_type, cmsg_data = item
  2051. self.assertEqual(cmsg_level, socket.SOL_SOCKET)
  2052. self.assertEqual(cmsg_type, socket.SCM_RIGHTS)
  2053. self.assertIsInstance(cmsg_data, bytes)
  2054. self.assertEqual(len(cmsg_data) % SIZEOF_INT, 0)
  2055. fds.frombytes(cmsg_data)
  2056. self.assertEqual(len(fds), numfds)
  2057. self.checkFDs(fds)
  2058. def testFDPassSimple(self):
  2059. # Pass a single FD (array read from bytes object).
  2060. self.checkRecvmsgFDs(1, self.doRecvmsg(self.serv_sock,
  2061. len(MSG), 10240))
  2062. def _testFDPassSimple(self):
  2063. self.assertEqual(
  2064. self.sendmsgToServer(
  2065. [MSG],
  2066. [(socket.SOL_SOCKET,
  2067. socket.SCM_RIGHTS,
  2068. array.array("i", self.newFDs(1)).tobytes())]),
  2069. len(MSG))
  2070. def testMultipleFDPass(self):
  2071. # Pass multiple FDs in a single array.
  2072. self.checkRecvmsgFDs(4, self.doRecvmsg(self.serv_sock,
  2073. len(MSG), 10240))
  2074. def _testMultipleFDPass(self):
  2075. self.createAndSendFDs(4)
  2076. @requireAttrs(socket, "CMSG_SPACE")
  2077. def testFDPassCMSG_SPACE(self):
  2078. # Test using CMSG_SPACE() to calculate ancillary buffer size.
  2079. self.checkRecvmsgFDs(
  2080. 4, self.doRecvmsg(self.serv_sock, len(MSG),
  2081. socket.CMSG_SPACE(4 * SIZEOF_INT)))
  2082. @testFDPassCMSG_SPACE.client_skip
  2083. def _testFDPassCMSG_SPACE(self):
  2084. self.createAndSendFDs(4)
  2085. def testFDPassCMSG_LEN(self):
  2086. # Test using CMSG_LEN() to calculate ancillary buffer size.
  2087. self.checkRecvmsgFDs(1,
  2088. self.doRecvmsg(self.serv_sock, len(MSG),
  2089. socket.CMSG_LEN(4 * SIZEOF_INT)),
  2090. # RFC 3542 says implementations may set
  2091. # MSG_CTRUNC if there isn't enough space
  2092. # for trailing padding.
  2093. ignoreflags=socket.MSG_CTRUNC)
  2094. def _testFDPassCMSG_LEN(self):
  2095. self.createAndSendFDs(1)
  2096. # Issue #12958: The following test has problems on Mac OS X
  2097. @support.anticipate_failure(sys.platform == "darwin")
  2098. @requireAttrs(socket, "CMSG_SPACE")
  2099. def testFDPassSeparate(self):
  2100. # Pass two FDs in two separate arrays. Arrays may be combined
  2101. # into a single control message by the OS.
  2102. self.checkRecvmsgFDs(2,
  2103. self.doRecvmsg(self.serv_sock, len(MSG), 10240),
  2104. maxcmsgs=2)
  2105. @testFDPassSeparate.client_skip
  2106. @support.anticipate_failure(sys.platform == "darwin")
  2107. def _testFDPassSeparate(self):
  2108. fd0, fd1 = self.newFDs(2)
  2109. self.assertEqual(
  2110. self.sendmsgToServer([MSG], [(socket.SOL_SOCKET,
  2111. socket.SCM_RIGHTS,
  2112. array.array("i", [fd0])),
  2113. (socket.SOL_SOCKET,
  2114. socket.SCM_RIGHTS,
  2115. array.array("i", [fd1]))]),
  2116. len(MSG))
  2117. # Issue #12958: The following test has problems on Mac OS X
  2118. @support.anticipate_failure(sys.platform == "darwin")
  2119. @requireAttrs(socket, "CMSG_SPACE")
  2120. def testFDPassSeparateMinSpace(self):
  2121. # Pass two FDs in two separate arrays, receiving them into the
  2122. # minimum space for two arrays.
  2123. self.checkRecvmsgFDs(2,
  2124. self.doRecvmsg(self.serv_sock, len(MSG),
  2125. socket.CMSG_SPACE(SIZEOF_INT) +
  2126. socket.CMSG_LEN(SIZEOF_INT)),
  2127. maxcmsgs=2, ignoreflags=socket.MSG_CTRUNC)
  2128. @testFDPassSeparateMinSpace.client_skip
  2129. @support.anticipate_failure(sys.platform == "darwin")
  2130. def _testFDPassSeparateMinSpace(self):
  2131. fd0, fd1 = self.newFDs(2)
  2132. self.assertEqual(
  2133. self.sendmsgToServer([MSG], [(socket.SOL_SOCKET,
  2134. socket.SCM_RIGHTS,
  2135. array.array("i", [fd0])),
  2136. (socket.SOL_SOCKET,
  2137. socket.SCM_RIGHTS,
  2138. array.array("i", [fd1]))]),
  2139. len(MSG))
  2140. def sendAncillaryIfPossible(self, msg, ancdata):
  2141. # Try to send msg and ancdata to server, but if the system
  2142. # call fails, just send msg with no ancillary data.
  2143. try:
  2144. nbytes = self.sendmsgToServer([msg], ancdata)
  2145. except OSError as e:
  2146. # Check that it was the system call that failed
  2147. self.assertIsInstance(e.errno, int)
  2148. nbytes = self.sendmsgToServer([msg])
  2149. self.assertEqual(nbytes, len(msg))
  2150. def testFDPassEmpty(self):
  2151. # Try to pass an empty FD array. Can receive either no array
  2152. # or an empty array.
  2153. self.checkRecvmsgFDs(0, self.doRecvmsg(self.serv_sock,
  2154. len(MSG), 10240),
  2155. ignoreflags=socket.MSG_CTRUNC)
  2156. def _testFDPassEmpty(self):
  2157. self.sendAncillaryIfPossible(MSG, [(socket.SOL_SOCKET,
  2158. socket.SCM_RIGHTS,
  2159. b"")])
  2160. def testFDPassPartialInt(self):
  2161. # Try to pass a truncated FD array.
  2162. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
  2163. len(MSG), 10240)
  2164. self.assertEqual(msg, MSG)
  2165. self.checkRecvmsgAddress(addr, self.cli_addr)
  2166. self.checkFlags(flags, eor=True, ignore=socket.MSG_CTRUNC)
  2167. self.assertLessEqual(len(ancdata), 1)
  2168. for cmsg_level, cmsg_type, cmsg_data in ancdata:
  2169. self.assertEqual(cmsg_level, socket.SOL_SOCKET)
  2170. self.assertEqual(cmsg_type, socket.SCM_RIGHTS)
  2171. self.assertLess(len(cmsg_data), SIZEOF_INT)
  2172. def _testFDPassPartialInt(self):
  2173. self.sendAncillaryIfPossible(
  2174. MSG,
  2175. [(socket.SOL_SOCKET,
  2176. socket.SCM_RIGHTS,
  2177. array.array("i", [self.badfd]).tobytes()[:-1])])
  2178. @requireAttrs(socket, "CMSG_SPACE")
  2179. def testFDPassPartialIntInMiddle(self):
  2180. # Try to pass two FD arrays, the first of which is truncated.
  2181. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
  2182. len(MSG), 10240)
  2183. self.assertEqual(msg, MSG)
  2184. self.checkRecvmsgAddress(addr, self.cli_addr)
  2185. self.checkFlags(flags, eor=True, ignore=socket.MSG_CTRUNC)
  2186. self.assertLessEqual(len(ancdata), 2)
  2187. fds = array.array("i")
  2188. # Arrays may have been combined in a single control message
  2189. for cmsg_level, cmsg_type, cmsg_data in ancdata:
  2190. self.assertEqual(cmsg_level, socket.SOL_SOCKET)
  2191. self.assertEqual(cmsg_type, socket.SCM_RIGHTS)
  2192. fds.frombytes(cmsg_data[:
  2193. len(cmsg_data) - (len(cmsg_data) % fds.itemsize)])
  2194. self.assertLessEqual(len(fds), 2)
  2195. self.checkFDs(fds)
  2196. @testFDPassPartialIntInMiddle.client_skip
  2197. def _testFDPassPartialIntInMiddle(self):
  2198. fd0, fd1 = self.newFDs(2)
  2199. self.sendAncillaryIfPossible(
  2200. MSG,
  2201. [(socket.SOL_SOCKET,
  2202. socket.SCM_RIGHTS,
  2203. array.array("i", [fd0, self.badfd]).tobytes()[:-1]),
  2204. (socket.SOL_SOCKET,
  2205. socket.SCM_RIGHTS,
  2206. array.array("i", [fd1]))])
  2207. def checkTruncatedHeader(self, result, ignoreflags=0):
  2208. # Check that no ancillary data items are returned when data is
  2209. # truncated inside the cmsghdr structure.
  2210. msg, ancdata, flags, addr = result
  2211. self.assertEqual(msg, MSG)
  2212. self.checkRecvmsgAddress(addr, self.cli_addr)
  2213. self.assertEqual(ancdata, [])
  2214. self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC,
  2215. ignore=ignoreflags)
  2216. def testCmsgTruncNoBufSize(self):
  2217. # Check that no ancillary data is received when no buffer size
  2218. # is specified.
  2219. self.checkTruncatedHeader(self.doRecvmsg(self.serv_sock, len(MSG)),
  2220. # BSD seems to set MSG_CTRUNC only
  2221. # if an item has been partially
  2222. # received.
  2223. ignoreflags=socket.MSG_CTRUNC)
  2224. def _testCmsgTruncNoBufSize(self):
  2225. self.createAndSendFDs(1)
  2226. def testCmsgTrunc0(self):
  2227. # Check that no ancillary data is received when buffer size is 0.
  2228. self.checkTruncatedHeader(self.doRecvmsg(self.serv_sock, len(MSG), 0),
  2229. ignoreflags=socket.MSG_CTRUNC)
  2230. def _testCmsgTrunc0(self):
  2231. self.createAndSendFDs(1)
  2232. # Check that no ancillary data is returned for various non-zero
  2233. # (but still too small) buffer sizes.
  2234. def testCmsgTrunc1(self):
  2235. self.checkTruncatedHeader(self.doRecvmsg(self.serv_sock, len(MSG), 1))
  2236. def _testCmsgTrunc1(self):
  2237. self.createAndSendFDs(1)
  2238. def testCmsgTrunc2Int(self):
  2239. # The cmsghdr structure has at least three members, two of
  2240. # which are ints, so we still shouldn't see any ancillary
  2241. # data.
  2242. self.checkTruncatedHeader(self.doRecvmsg(self.serv_sock, len(MSG),
  2243. SIZEOF_INT * 2))
  2244. def _testCmsgTrunc2Int(self):
  2245. self.createAndSendFDs(1)
  2246. def testCmsgTruncLen0Minus1(self):
  2247. self.checkTruncatedHeader(self.doRecvmsg(self.serv_sock, len(MSG),
  2248. socket.CMSG_LEN(0) - 1))
  2249. def _testCmsgTruncLen0Minus1(self):
  2250. self.createAndSendFDs(1)
  2251. # The following tests try to truncate the control message in the
  2252. # middle of the FD array.
  2253. def checkTruncatedArray(self, ancbuf, maxdata, mindata=0):
  2254. # Check that file descriptor data is truncated to between
  2255. # mindata and maxdata bytes when received with buffer size
  2256. # ancbuf, and that any complete file descriptor numbers are
  2257. # valid.
  2258. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
  2259. len(MSG), ancbuf)
  2260. self.assertEqual(msg, MSG)
  2261. self.checkRecvmsgAddress(addr, self.cli_addr)
  2262. self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC)
  2263. if mindata == 0 and ancdata == []:
  2264. return
  2265. self.assertEqual(len(ancdata), 1)
  2266. cmsg_level, cmsg_type, cmsg_data = ancdata[0]
  2267. self.assertEqual(cmsg_level, socket.SOL_SOCKET)
  2268. self.assertEqual(cmsg_type, socket.SCM_RIGHTS)
  2269. self.assertGreaterEqual(len(cmsg_data), mindata)
  2270. self.assertLessEqual(len(cmsg_data), maxdata)
  2271. fds = array.array("i")
  2272. fds.frombytes(cmsg_data[:
  2273. len(cmsg_data) - (len(cmsg_data) % fds.itemsize)])
  2274. self.checkFDs(fds)
  2275. def testCmsgTruncLen0(self):
  2276. self.checkTruncatedArray(ancbuf=socket.CMSG_LEN(0), maxdata=0)
  2277. def _testCmsgTruncLen0(self):
  2278. self.createAndSendFDs(1)
  2279. def testCmsgTruncLen0Plus1(self):
  2280. self.checkTruncatedArray(ancbuf=socket.CMSG_LEN(0) + 1, maxdata=1)
  2281. def _testCmsgTruncLen0Plus1(self):
  2282. self.createAndSendFDs(2)
  2283. def testCmsgTruncLen1(self):
  2284. self.checkTruncatedArray(ancbuf=socket.CMSG_LEN(SIZEOF_INT),
  2285. maxdata=SIZEOF_INT)
  2286. def _testCmsgTruncLen1(self):
  2287. self.createAndSendFDs(2)
  2288. def testCmsgTruncLen2Minus1(self):
  2289. self.checkTruncatedArray(ancbuf=socket.CMSG_LEN(2 * SIZEOF_INT) - 1,
  2290. maxdata=(2 * SIZEOF_INT) - 1)
  2291. def _testCmsgTruncLen2Minus1(self):
  2292. self.createAndSendFDs(2)
  2293. class RFC3542AncillaryTest(SendrecvmsgServerTimeoutBase):
  2294. # Test sendmsg() and recvmsg[_into]() using the ancillary data
  2295. # features of the RFC 3542 Advanced Sockets API for IPv6.
  2296. # Currently we can only handle certain data items (e.g. traffic
  2297. # class, hop limit, MTU discovery and fragmentation settings)
  2298. # without resorting to unportable means such as the struct module,
  2299. # but the tests here are aimed at testing the ancillary data
  2300. # handling in sendmsg() and recvmsg() rather than the IPv6 API
  2301. # itself.
  2302. # Test value to use when setting hop limit of packet
  2303. hop_limit = 2
  2304. # Test value to use when setting traffic class of packet.
  2305. # -1 means "use kernel default".
  2306. traffic_class = -1
  2307. def ancillaryMapping(self, ancdata):
  2308. # Given ancillary data list ancdata, return a mapping from
  2309. # pairs (cmsg_level, cmsg_type) to corresponding cmsg_data.
  2310. # Check that no (level, type) pair appears more than once.
  2311. d = {}
  2312. for cmsg_level, cmsg_type, cmsg_data in ancdata:
  2313. self.assertNotIn((cmsg_level, cmsg_type), d)
  2314. d[(cmsg_level, cmsg_type)] = cmsg_data
  2315. return d
  2316. def checkHopLimit(self, ancbufsize, maxhop=255, ignoreflags=0):
  2317. # Receive hop limit into ancbufsize bytes of ancillary data
  2318. # space. Check that data is MSG, ancillary data is not
  2319. # truncated (but ignore any flags in ignoreflags), and hop
  2320. # limit is between 0 and maxhop inclusive.
  2321. self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
  2322. socket.IPV6_RECVHOPLIMIT, 1)
  2323. self.misc_event.set()
  2324. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
  2325. len(MSG), ancbufsize)
  2326. self.assertEqual(msg, MSG)
  2327. self.checkRecvmsgAddress(addr, self.cli_addr)
  2328. self.checkFlags(flags, eor=True, checkunset=socket.MSG_CTRUNC,
  2329. ignore=ignoreflags)
  2330. self.assertEqual(len(ancdata), 1)
  2331. self.assertIsInstance(ancdata[0], tuple)
  2332. cmsg_level, cmsg_type, cmsg_data = ancdata[0]
  2333. self.assertEqual(cmsg_level, socket.IPPROTO_IPV6)
  2334. self.assertEqual(cmsg_type, socket.IPV6_HOPLIMIT)
  2335. self.assertIsInstance(cmsg_data, bytes)
  2336. self.assertEqual(len(cmsg_data), SIZEOF_INT)
  2337. a = array.array("i")
  2338. a.frombytes(cmsg_data)
  2339. self.assertGreaterEqual(a[0], 0)
  2340. self.assertLessEqual(a[0], maxhop)
  2341. @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
  2342. def testRecvHopLimit(self):
  2343. # Test receiving the packet hop limit as ancillary data.
  2344. self.checkHopLimit(ancbufsize=10240)
  2345. @testRecvHopLimit.client_skip
  2346. def _testRecvHopLimit(self):
  2347. # Need to wait until server has asked to receive ancillary
  2348. # data, as implementations are not required to buffer it
  2349. # otherwise.
  2350. self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
  2351. self.sendToServer(MSG)
  2352. @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
  2353. def testRecvHopLimitCMSG_SPACE(self):
  2354. # Test receiving hop limit, using CMSG_SPACE to calculate buffer size.
  2355. self.checkHopLimit(ancbufsize=socket.CMSG_SPACE(SIZEOF_INT))
  2356. @testRecvHopLimitCMSG_SPACE.client_skip
  2357. def _testRecvHopLimitCMSG_SPACE(self):
  2358. self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
  2359. self.sendToServer(MSG)
  2360. # Could test receiving into buffer sized using CMSG_LEN, but RFC
  2361. # 3542 says portable applications must provide space for trailing
  2362. # padding. Implementations may set MSG_CTRUNC if there isn't
  2363. # enough space for the padding.
  2364. @requireAttrs(socket.socket, "sendmsg")
  2365. @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
  2366. def testSetHopLimit(self):
  2367. # Test setting hop limit on outgoing packet and receiving it
  2368. # at the other end.
  2369. self.checkHopLimit(ancbufsize=10240, maxhop=self.hop_limit)
  2370. @testSetHopLimit.client_skip
  2371. def _testSetHopLimit(self):
  2372. self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
  2373. self.assertEqual(
  2374. self.sendmsgToServer([MSG],
  2375. [(socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT,
  2376. array.array("i", [self.hop_limit]))]),
  2377. len(MSG))
  2378. def checkTrafficClassAndHopLimit(self, ancbufsize, maxhop=255,
  2379. ignoreflags=0):
  2380. # Receive traffic class and hop limit into ancbufsize bytes of
  2381. # ancillary data space. Check that data is MSG, ancillary
  2382. # data is not truncated (but ignore any flags in ignoreflags),
  2383. # and traffic class and hop limit are in range (hop limit no
  2384. # more than maxhop).
  2385. self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
  2386. socket.IPV6_RECVHOPLIMIT, 1)
  2387. self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
  2388. socket.IPV6_RECVTCLASS, 1)
  2389. self.misc_event.set()
  2390. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
  2391. len(MSG), ancbufsize)
  2392. self.assertEqual(msg, MSG)
  2393. self.checkRecvmsgAddress(addr, self.cli_addr)
  2394. self.checkFlags(flags, eor=True, checkunset=socket.MSG_CTRUNC,
  2395. ignore=ignoreflags)
  2396. self.assertEqual(len(ancdata), 2)
  2397. ancmap = self.ancillaryMapping(ancdata)
  2398. tcdata = ancmap[(socket.IPPROTO_IPV6, socket.IPV6_TCLASS)]
  2399. self.assertEqual(len(tcdata), SIZEOF_INT)
  2400. a = array.array("i")
  2401. a.frombytes(tcdata)
  2402. self.assertGreaterEqual(a[0], 0)
  2403. self.assertLessEqual(a[0], 255)
  2404. hldata = ancmap[(socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT)]
  2405. self.assertEqual(len(hldata), SIZEOF_INT)
  2406. a = array.array("i")
  2407. a.frombytes(hldata)
  2408. self.assertGreaterEqual(a[0], 0)
  2409. self.assertLessEqual(a[0], maxhop)
  2410. @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
  2411. "IPV6_RECVTCLASS", "IPV6_TCLASS")
  2412. def testRecvTrafficClassAndHopLimit(self):
  2413. # Test receiving traffic class and hop limit as ancillary data.
  2414. self.checkTrafficClassAndHopLimit(ancbufsize=10240)
  2415. @testRecvTrafficClassAndHopLimit.client_skip
  2416. def _testRecvTrafficClassAndHopLimit(self):
  2417. self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
  2418. self.sendToServer(MSG)
  2419. @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
  2420. "IPV6_RECVTCLASS", "IPV6_TCLASS")
  2421. def testRecvTrafficClassAndHopLimitCMSG_SPACE(self):
  2422. # Test receiving traffic class and hop limit, using
  2423. # CMSG_SPACE() to calculate buffer size.
  2424. self.checkTrafficClassAndHopLimit(
  2425. ancbufsize=socket.CMSG_SPACE(SIZEOF_INT) * 2)
  2426. @testRecvTrafficClassAndHopLimitCMSG_SPACE.client_skip
  2427. def _testRecvTrafficClassAndHopLimitCMSG_SPACE(self):
  2428. self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
  2429. self.sendToServer(MSG)
  2430. @requireAttrs(socket.socket, "sendmsg")
  2431. @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
  2432. "IPV6_RECVTCLASS", "IPV6_TCLASS")
  2433. def testSetTrafficClassAndHopLimit(self):
  2434. # Test setting traffic class and hop limit on outgoing packet,
  2435. # and receiving them at the other end.
  2436. self.checkTrafficClassAndHopLimit(ancbufsize=10240,
  2437. maxhop=self.hop_limit)
  2438. @testSetTrafficClassAndHopLimit.client_skip
  2439. def _testSetTrafficClassAndHopLimit(self):
  2440. self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
  2441. self.assertEqual(
  2442. self.sendmsgToServer([MSG],
  2443. [(socket.IPPROTO_IPV6, socket.IPV6_TCLASS,
  2444. array.array("i", [self.traffic_class])),
  2445. (socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT,
  2446. array.array("i", [self.hop_limit]))]),
  2447. len(MSG))
  2448. @requireAttrs(socket.socket, "sendmsg")
  2449. @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
  2450. "IPV6_RECVTCLASS", "IPV6_TCLASS")
  2451. def testOddCmsgSize(self):
  2452. # Try to send ancillary data with first item one byte too
  2453. # long. Fall back to sending with correct size if this fails,
  2454. # and check that second item was handled correctly.
  2455. self.checkTrafficClassAndHopLimit(ancbufsize=10240,
  2456. maxhop=self.hop_limit)
  2457. @testOddCmsgSize.client_skip
  2458. def _testOddCmsgSize(self):
  2459. self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
  2460. try:
  2461. nbytes = self.sendmsgToServer(
  2462. [MSG],
  2463. [(socket.IPPROTO_IPV6, socket.IPV6_TCLASS,
  2464. array.array("i", [self.traffic_class]).tobytes() + b"\x00"),
  2465. (socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT,
  2466. array.array("i", [self.hop_limit]))])
  2467. except OSError as e:
  2468. self.assertIsInstance(e.errno, int)
  2469. nbytes = self.sendmsgToServer(
  2470. [MSG],
  2471. [(socket.IPPROTO_IPV6, socket.IPV6_TCLASS,
  2472. array.array("i", [self.traffic_class])),
  2473. (socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT,
  2474. array.array("i", [self.hop_limit]))])
  2475. self.assertEqual(nbytes, len(MSG))
  2476. # Tests for proper handling of truncated ancillary data
  2477. def checkHopLimitTruncatedHeader(self, ancbufsize, ignoreflags=0):
  2478. # Receive hop limit into ancbufsize bytes of ancillary data
  2479. # space, which should be too small to contain the ancillary
  2480. # data header (if ancbufsize is None, pass no second argument
  2481. # to recvmsg()). Check that data is MSG, MSG_CTRUNC is set
  2482. # (unless included in ignoreflags), and no ancillary data is
  2483. # returned.
  2484. self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
  2485. socket.IPV6_RECVHOPLIMIT, 1)
  2486. self.misc_event.set()
  2487. args = () if ancbufsize is None else (ancbufsize,)
  2488. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
  2489. len(MSG), *args)
  2490. self.assertEqual(msg, MSG)
  2491. self.checkRecvmsgAddress(addr, self.cli_addr)
  2492. self.assertEqual(ancdata, [])
  2493. self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC,
  2494. ignore=ignoreflags)
  2495. @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
  2496. def testCmsgTruncNoBufSize(self):
  2497. # Check that no ancillary data is received when no ancillary
  2498. # buffer size is provided.
  2499. self.checkHopLimitTruncatedHeader(ancbufsize=None,
  2500. # BSD seems to set
  2501. # MSG_CTRUNC only if an item
  2502. # has been partially
  2503. # received.
  2504. ignoreflags=socket.MSG_CTRUNC)
  2505. @testCmsgTruncNoBufSize.client_skip
  2506. def _testCmsgTruncNoBufSize(self):
  2507. self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
  2508. self.sendToServer(MSG)
  2509. @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
  2510. def testSingleCmsgTrunc0(self):
  2511. # Check that no ancillary data is received when ancillary
  2512. # buffer size is zero.
  2513. self.checkHopLimitTruncatedHeader(ancbufsize=0,
  2514. ignoreflags=socket.MSG_CTRUNC)
  2515. @testSingleCmsgTrunc0.client_skip
  2516. def _testSingleCmsgTrunc0(self):
  2517. self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
  2518. self.sendToServer(MSG)
  2519. # Check that no ancillary data is returned for various non-zero
  2520. # (but still too small) buffer sizes.
  2521. @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
  2522. def testSingleCmsgTrunc1(self):
  2523. self.checkHopLimitTruncatedHeader(ancbufsize=1)
  2524. @testSingleCmsgTrunc1.client_skip
  2525. def _testSingleCmsgTrunc1(self):
  2526. self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
  2527. self.sendToServer(MSG)
  2528. @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
  2529. def testSingleCmsgTrunc2Int(self):
  2530. self.checkHopLimitTruncatedHeader(ancbufsize=2 * SIZEOF_INT)
  2531. @testSingleCmsgTrunc2Int.client_skip
  2532. def _testSingleCmsgTrunc2Int(self):
  2533. self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
  2534. self.sendToServer(MSG)
  2535. @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
  2536. def testSingleCmsgTruncLen0Minus1(self):
  2537. self.checkHopLimitTruncatedHeader(ancbufsize=socket.CMSG_LEN(0) - 1)
  2538. @testSingleCmsgTruncLen0Minus1.client_skip
  2539. def _testSingleCmsgTruncLen0Minus1(self):
  2540. self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
  2541. self.sendToServer(MSG)
  2542. @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
  2543. def testSingleCmsgTruncInData(self):
  2544. # Test truncation of a control message inside its associated
  2545. # data. The message may be returned with its data truncated,
  2546. # or not returned at all.
  2547. self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
  2548. socket.IPV6_RECVHOPLIMIT, 1)
  2549. self.misc_event.set()
  2550. msg, ancdata, flags, addr = self.doRecvmsg(
  2551. self.serv_sock, len(MSG), socket.CMSG_LEN(SIZEOF_INT) - 1)
  2552. self.assertEqual(msg, MSG)
  2553. self.checkRecvmsgAddress(addr, self.cli_addr)
  2554. self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC)
  2555. self.assertLessEqual(len(ancdata), 1)
  2556. if ancdata:
  2557. cmsg_level, cmsg_type, cmsg_data = ancdata[0]
  2558. self.assertEqual(cmsg_level, socket.IPPROTO_IPV6)
  2559. self.assertEqual(cmsg_type, socket.IPV6_HOPLIMIT)
  2560. self.assertLess(len(cmsg_data), SIZEOF_INT)
  2561. @testSingleCmsgTruncInData.client_skip
  2562. def _testSingleCmsgTruncInData(self):
  2563. self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
  2564. self.sendToServer(MSG)
  2565. def checkTruncatedSecondHeader(self, ancbufsize, ignoreflags=0):
  2566. # Receive traffic class and hop limit into ancbufsize bytes of
  2567. # ancillary data space, which should be large enough to
  2568. # contain the first item, but too small to contain the header
  2569. # of the second. Check that data is MSG, MSG_CTRUNC is set
  2570. # (unless included in ignoreflags), and only one ancillary
  2571. # data item is returned.
  2572. self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
  2573. socket.IPV6_RECVHOPLIMIT, 1)
  2574. self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
  2575. socket.IPV6_RECVTCLASS, 1)
  2576. self.misc_event.set()
  2577. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
  2578. len(MSG), ancbufsize)
  2579. self.assertEqual(msg, MSG)
  2580. self.checkRecvmsgAddress(addr, self.cli_addr)
  2581. self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC,
  2582. ignore=ignoreflags)
  2583. self.assertEqual(len(ancdata), 1)
  2584. cmsg_level, cmsg_type, cmsg_data = ancdata[0]
  2585. self.assertEqual(cmsg_level, socket.IPPROTO_IPV6)
  2586. self.assertIn(cmsg_type, {socket.IPV6_TCLASS, socket.IPV6_HOPLIMIT})
  2587. self.assertEqual(len(cmsg_data), SIZEOF_INT)
  2588. a = array.array("i")
  2589. a.frombytes(cmsg_data)
  2590. self.assertGreaterEqual(a[0], 0)
  2591. self.assertLessEqual(a[0], 255)
  2592. # Try the above test with various buffer sizes.
  2593. @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
  2594. "IPV6_RECVTCLASS", "IPV6_TCLASS")
  2595. def testSecondCmsgTrunc0(self):
  2596. self.checkTruncatedSecondHeader(socket.CMSG_SPACE(SIZEOF_INT),
  2597. ignoreflags=socket.MSG_CTRUNC)
  2598. @testSecondCmsgTrunc0.client_skip
  2599. def _testSecondCmsgTrunc0(self):
  2600. self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
  2601. self.sendToServer(MSG)
  2602. @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
  2603. "IPV6_RECVTCLASS", "IPV6_TCLASS")
  2604. def testSecondCmsgTrunc1(self):
  2605. self.checkTruncatedSecondHeader(socket.CMSG_SPACE(SIZEOF_INT) + 1)
  2606. @testSecondCmsgTrunc1.client_skip
  2607. def _testSecondCmsgTrunc1(self):
  2608. self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
  2609. self.sendToServer(MSG)
  2610. @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
  2611. "IPV6_RECVTCLASS", "IPV6_TCLASS")
  2612. def testSecondCmsgTrunc2Int(self):
  2613. self.checkTruncatedSecondHeader(socket.CMSG_SPACE(SIZEOF_INT) +
  2614. 2 * SIZEOF_INT)
  2615. @testSecondCmsgTrunc2Int.client_skip
  2616. def _testSecondCmsgTrunc2Int(self):
  2617. self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
  2618. self.sendToServer(MSG)
  2619. @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
  2620. "IPV6_RECVTCLASS", "IPV6_TCLASS")
  2621. def testSecondCmsgTruncLen0Minus1(self):
  2622. self.checkTruncatedSecondHeader(socket.CMSG_SPACE(SIZEOF_INT) +
  2623. socket.CMSG_LEN(0) - 1)
  2624. @testSecondCmsgTruncLen0Minus1.client_skip
  2625. def _testSecondCmsgTruncLen0Minus1(self):
  2626. self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
  2627. self.sendToServer(MSG)
  2628. @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
  2629. "IPV6_RECVTCLASS", "IPV6_TCLASS")
  2630. def testSecomdCmsgTruncInData(self):
  2631. # Test truncation of the second of two control messages inside
  2632. # its associated data.
  2633. self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
  2634. socket.IPV6_RECVHOPLIMIT, 1)
  2635. self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
  2636. socket.IPV6_RECVTCLASS, 1)
  2637. self.misc_event.set()
  2638. msg, ancdata, flags, addr = self.doRecvmsg(
  2639. self.serv_sock, len(MSG),
  2640. socket.CMSG_SPACE(SIZEOF_INT) + socket.CMSG_LEN(SIZEOF_INT) - 1)
  2641. self.assertEqual(msg, MSG)
  2642. self.checkRecvmsgAddress(addr, self.cli_addr)
  2643. self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC)
  2644. cmsg_types = {socket.IPV6_TCLASS, socket.IPV6_HOPLIMIT}
  2645. cmsg_level, cmsg_type, cmsg_data = ancdata.pop(0)
  2646. self.assertEqual(cmsg_level, socket.IPPROTO_IPV6)
  2647. cmsg_types.remove(cmsg_type)
  2648. self.assertEqual(len(cmsg_data), SIZEOF_INT)
  2649. a = array.array("i")
  2650. a.frombytes(cmsg_data)
  2651. self.assertGreaterEqual(a[0], 0)
  2652. self.assertLessEqual(a[0], 255)
  2653. if ancdata:
  2654. cmsg_level, cmsg_type, cmsg_data = ancdata.pop(0)
  2655. self.assertEqual(cmsg_level, socket.IPPROTO_IPV6)
  2656. cmsg_types.remove(cmsg_type)
  2657. self.assertLess(len(cmsg_data), SIZEOF_INT)
  2658. self.assertEqual(ancdata, [])
  2659. @testSecomdCmsgTruncInData.client_skip
  2660. def _testSecomdCmsgTruncInData(self):
  2661. self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
  2662. self.sendToServer(MSG)
  2663. # Derive concrete test classes for different socket types.
  2664. class SendrecvmsgUDPTestBase(SendrecvmsgDgramFlagsBase,
  2665. SendrecvmsgConnectionlessBase,
  2666. ThreadedSocketTestMixin, UDPTestBase):
  2667. pass
  2668. @requireAttrs(socket.socket, "sendmsg")
  2669. @unittest.skipUnless(thread, 'Threading required for this test.')
  2670. class SendmsgUDPTest(SendmsgConnectionlessTests, SendrecvmsgUDPTestBase):
  2671. pass
  2672. @requireAttrs(socket.socket, "recvmsg")
  2673. @unittest.skipUnless(thread, 'Threading required for this test.')
  2674. class RecvmsgUDPTest(RecvmsgTests, SendrecvmsgUDPTestBase):
  2675. pass
  2676. @requireAttrs(socket.socket, "recvmsg_into")
  2677. @unittest.skipUnless(thread, 'Threading required for this test.')
  2678. class RecvmsgIntoUDPTest(RecvmsgIntoTests, SendrecvmsgUDPTestBase):
  2679. pass
  2680. class SendrecvmsgUDP6TestBase(SendrecvmsgDgramFlagsBase,
  2681. SendrecvmsgConnectionlessBase,
  2682. ThreadedSocketTestMixin, UDP6TestBase):
  2683. pass
  2684. @requireAttrs(socket.socket, "sendmsg")
  2685. @unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 required for this test.')
  2686. @requireSocket("AF_INET6", "SOCK_DGRAM")
  2687. @unittest.skipUnless(thread, 'Threading required for this test.')
  2688. class SendmsgUDP6Test(SendmsgConnectionlessTests, SendrecvmsgUDP6TestBase):
  2689. pass
  2690. @requireAttrs(socket.socket, "recvmsg")
  2691. @unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 required for this test.')
  2692. @requireSocket("AF_INET6", "SOCK_DGRAM")
  2693. @unittest.skipUnless(thread, 'Threading required for this test.')
  2694. class RecvmsgUDP6Test(RecvmsgTests, SendrecvmsgUDP6TestBase):
  2695. pass
  2696. @requireAttrs(socket.socket, "recvmsg_into")
  2697. @unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 required for this test.')
  2698. @requireSocket("AF_INET6", "SOCK_DGRAM")
  2699. @unittest.skipUnless(thread, 'Threading required for this test.')
  2700. class RecvmsgIntoUDP6Test(RecvmsgIntoTests, SendrecvmsgUDP6TestBase):
  2701. pass
  2702. @requireAttrs(socket.socket, "recvmsg")
  2703. @unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 required for this test.')
  2704. @requireAttrs(socket, "IPPROTO_IPV6")
  2705. @requireSocket("AF_INET6", "SOCK_DGRAM")
  2706. @unittest.skipUnless(thread, 'Threading required for this test.')
  2707. class RecvmsgRFC3542AncillaryUDP6Test(RFC3542AncillaryTest,
  2708. SendrecvmsgUDP6TestBase):
  2709. pass
  2710. @requireAttrs(socket.socket, "recvmsg_into")
  2711. @unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 required for this test.')
  2712. @requireAttrs(socket, "IPPROTO_IPV6")
  2713. @requireSocket("AF_INET6", "SOCK_DGRAM")
  2714. @unittest.skipUnless(thread, 'Threading required for this test.')
  2715. class RecvmsgIntoRFC3542AncillaryUDP6Test(RecvmsgIntoMixin,
  2716. RFC3542AncillaryTest,
  2717. SendrecvmsgUDP6TestBase):
  2718. pass
  2719. class SendrecvmsgTCPTestBase(SendrecvmsgConnectedBase,
  2720. ConnectedStreamTestMixin, TCPTestBase):
  2721. pass
  2722. @requireAttrs(socket.socket, "sendmsg")
  2723. @unittest.skipUnless(thread, 'Threading required for this test.')
  2724. class SendmsgTCPTest(SendmsgStreamTests, SendrecvmsgTCPTestBase):
  2725. pass
  2726. @requireAttrs(socket.socket, "recvmsg")
  2727. @unittest.skipUnless(thread, 'Threading required for this test.')
  2728. class RecvmsgTCPTest(RecvmsgTests, RecvmsgGenericStreamTests,
  2729. SendrecvmsgTCPTestBase):
  2730. pass
  2731. @requireAttrs(socket.socket, "recvmsg_into")
  2732. @unittest.skipUnless(thread, 'Threading required for this test.')
  2733. class RecvmsgIntoTCPTest(RecvmsgIntoTests, RecvmsgGenericStreamTests,
  2734. SendrecvmsgTCPTestBase):
  2735. pass
  2736. class SendrecvmsgSCTPStreamTestBase(SendrecvmsgSCTPFlagsBase,
  2737. SendrecvmsgConnectedBase,
  2738. ConnectedStreamTestMixin, SCTPStreamBase):
  2739. pass
  2740. @requireAttrs(socket.socket, "sendmsg")
  2741. @requireSocket("AF_INET", "SOCK_STREAM", "IPPROTO_SCTP")
  2742. @unittest.skipUnless(thread, 'Threading required for this test.')
  2743. class SendmsgSCTPStreamTest(SendmsgStreamTests, SendrecvmsgSCTPStreamTestBase):
  2744. pass
  2745. @requireAttrs(socket.socket, "recvmsg")
  2746. @requireSocket("AF_INET", "SOCK_STREAM", "IPPROTO_SCTP")
  2747. @unittest.skipUnless(thread, 'Threading required for this test.')
  2748. class RecvmsgSCTPStreamTest(RecvmsgTests, RecvmsgGenericStreamTests,
  2749. SendrecvmsgSCTPStreamTestBase):
  2750. def testRecvmsgEOF(self):
  2751. try:
  2752. super(RecvmsgSCTPStreamTest, self).testRecvmsgEOF()
  2753. except OSError as e:
  2754. if e.errno != errno.ENOTCONN:
  2755. raise
  2756. self.skipTest("sporadic ENOTCONN (kernel issue?) - see issue #13876")
  2757. @requireAttrs(socket.socket, "recvmsg_into")
  2758. @requireSocket("AF_INET", "SOCK_STREAM", "IPPROTO_SCTP")
  2759. @unittest.skipUnless(thread, 'Threading required for this test.')
  2760. class RecvmsgIntoSCTPStreamTest(RecvmsgIntoTests, RecvmsgGenericStreamTests,
  2761. SendrecvmsgSCTPStreamTestBase):
  2762. def testRecvmsgEOF(self):
  2763. try:
  2764. super(RecvmsgIntoSCTPStreamTest, self).testRecvmsgEOF()
  2765. except OSError as e:
  2766. if e.errno != errno.ENOTCONN:
  2767. raise
  2768. self.skipTest("sporadic ENOTCONN (kernel issue?) - see issue #13876")
  2769. class SendrecvmsgUnixStreamTestBase(SendrecvmsgConnectedBase,
  2770. ConnectedStreamTestMixin, UnixStreamBase):
  2771. pass
  2772. @requireAttrs(socket.socket, "sendmsg")
  2773. @requireAttrs(socket, "AF_UNIX")
  2774. @unittest.skipUnless(thread, 'Threading required for this test.')
  2775. class SendmsgUnixStreamTest(SendmsgStreamTests, SendrecvmsgUnixStreamTestBase):
  2776. pass
  2777. @requireAttrs(socket.socket, "recvmsg")
  2778. @requireAttrs(socket, "AF_UNIX")
  2779. @unittest.skipUnless(thread, 'Threading required for this test.')
  2780. class RecvmsgUnixStreamTest(RecvmsgTests, RecvmsgGenericStreamTests,
  2781. SendrecvmsgUnixStreamTestBase):
  2782. pass
  2783. @requireAttrs(socket.socket, "recvmsg_into")
  2784. @requireAttrs(socket, "AF_UNIX")
  2785. @unittest.skipUnless(thread, 'Threading required for this test.')
  2786. class RecvmsgIntoUnixStreamTest(RecvmsgIntoTests, RecvmsgGenericStreamTests,
  2787. SendrecvmsgUnixStreamTestBase):
  2788. pass
  2789. @requireAttrs(socket.socket, "sendmsg", "recvmsg")
  2790. @requireAttrs(socket, "AF_UNIX", "SOL_SOCKET", "SCM_RIGHTS")
  2791. @unittest.skipUnless(thread, 'Threading required for this test.')
  2792. class RecvmsgSCMRightsStreamTest(SCMRightsTest, SendrecvmsgUnixStreamTestBase):
  2793. pass
  2794. @requireAttrs(socket.socket, "sendmsg", "recvmsg_into")
  2795. @requireAttrs(socket, "AF_UNIX", "SOL_SOCKET", "SCM_RIGHTS")
  2796. @unittest.skipUnless(thread, 'Threading required for this test.')
  2797. class RecvmsgIntoSCMRightsStreamTest(RecvmsgIntoMixin, SCMRightsTest,
  2798. SendrecvmsgUnixStreamTestBase):
  2799. pass
  2800. # Test interrupting the interruptible send/receive methods with a
  2801. # signal when a timeout is set. These tests avoid having multiple
  2802. # threads alive during the test so that the OS cannot deliver the
  2803. # signal to the wrong one.
  2804. class InterruptedTimeoutBase(unittest.TestCase):
  2805. # Base class for interrupted send/receive tests. Installs an
  2806. # empty handler for SIGALRM and removes it on teardown, along with
  2807. # any scheduled alarms.
  2808. def setUp(self):
  2809. super().setUp()
  2810. orig_alrm_handler = signal.signal(signal.SIGALRM,
  2811. lambda signum, frame: None)
  2812. self.addCleanup(signal.signal, signal.SIGALRM, orig_alrm_handler)
  2813. self.addCleanup(self.setAlarm, 0)
  2814. # Timeout for socket operations
  2815. timeout = 4.0
  2816. # Provide setAlarm() method to schedule delivery of SIGALRM after
  2817. # given number of seconds, or cancel it if zero, and an
  2818. # appropriate time value to use. Use setitimer() if available.
  2819. if hasattr(signal, "setitimer"):
  2820. alarm_time = 0.05
  2821. def setAlarm(self, seconds):
  2822. signal.setitimer(signal.ITIMER_REAL, seconds)
  2823. else:
  2824. # Old systems may deliver the alarm up to one second early
  2825. alarm_time = 2
  2826. def setAlarm(self, seconds):
  2827. signal.alarm(seconds)
  2828. # Require siginterrupt() in order to ensure that system calls are
  2829. # interrupted by default.
  2830. @requireAttrs(signal, "siginterrupt")
  2831. @unittest.skipUnless(hasattr(signal, "alarm") or hasattr(signal, "setitimer"),
  2832. "Don't have signal.alarm or signal.setitimer")
  2833. class InterruptedRecvTimeoutTest(InterruptedTimeoutBase, UDPTestBase):
  2834. # Test interrupting the recv*() methods with signals when a
  2835. # timeout is set.
  2836. def setUp(self):
  2837. super().setUp()
  2838. self.serv.settimeout(self.timeout)
  2839. def checkInterruptedRecv(self, func, *args, **kwargs):
  2840. # Check that func(*args, **kwargs) raises OSError with an
  2841. # errno of EINTR when interrupted by a signal.
  2842. self.setAlarm(self.alarm_time)
  2843. with self.assertRaises(OSError) as cm:
  2844. func(*args, **kwargs)
  2845. self.assertNotIsInstance(cm.exception, socket.timeout)
  2846. self.assertEqual(cm.exception.errno, errno.EINTR)
  2847. def testInterruptedRecvTimeout(self):
  2848. self.checkInterruptedRecv(self.serv.recv, 1024)
  2849. def testInterruptedRecvIntoTimeout(self):
  2850. self.checkInterruptedRecv(self.serv.recv_into, bytearray(1024))
  2851. def testInterruptedRecvfromTimeout(self):
  2852. self.checkInterruptedRecv(self.serv.recvfrom, 1024)
  2853. def testInterruptedRecvfromIntoTimeout(self):
  2854. self.checkInterruptedRecv(self.serv.recvfrom_into, bytearray(1024))
  2855. @requireAttrs(socket.socket, "recvmsg")
  2856. def testInterruptedRecvmsgTimeout(self):
  2857. self.checkInterruptedRecv(self.serv.recvmsg, 1024)
  2858. @requireAttrs(socket.socket, "recvmsg_into")
  2859. def testInterruptedRecvmsgIntoTimeout(self):
  2860. self.checkInterruptedRecv(self.serv.recvmsg_into, [bytearray(1024)])
  2861. # Require siginterrupt() in order to ensure that system calls are
  2862. # interrupted by default.
  2863. @requireAttrs(signal, "siginterrupt")
  2864. @unittest.skipUnless(hasattr(signal, "alarm") or hasattr(signal, "setitimer"),
  2865. "Don't have signal.alarm or signal.setitimer")
  2866. @unittest.skipUnless(thread, 'Threading required for this test.')
  2867. class InterruptedSendTimeoutTest(InterruptedTimeoutBase,
  2868. ThreadSafeCleanupTestCase,
  2869. SocketListeningTestMixin, TCPTestBase):
  2870. # Test interrupting the interruptible send*() methods with signals
  2871. # when a timeout is set.
  2872. def setUp(self):
  2873. super().setUp()
  2874. self.serv_conn = self.newSocket()
  2875. self.addCleanup(self.serv_conn.close)
  2876. # Use a thread to complete the connection, but wait for it to
  2877. # terminate before running the test, so that there is only one
  2878. # thread to accept the signal.
  2879. cli_thread = threading.Thread(target=self.doConnect)
  2880. cli_thread.start()
  2881. self.cli_conn, addr = self.serv.accept()
  2882. self.addCleanup(self.cli_conn.close)
  2883. cli_thread.join()
  2884. self.serv_conn.settimeout(self.timeout)
  2885. def doConnect(self):
  2886. self.serv_conn.connect(self.serv_addr)
  2887. def checkInterruptedSend(self, func, *args, **kwargs):
  2888. # Check that func(*args, **kwargs), run in a loop, raises
  2889. # OSError with an errno of EINTR when interrupted by a
  2890. # signal.
  2891. with self.assertRaises(OSError) as cm:
  2892. while True:
  2893. self.setAlarm(self.alarm_time)
  2894. func(*args, **kwargs)
  2895. self.assertNotIsInstance(cm.exception, socket.timeout)
  2896. self.assertEqual(cm.exception.errno, errno.EINTR)
  2897. # Issue #12958: The following tests have problems on Mac OS X
  2898. @support.anticipate_failure(sys.platform == "darwin")
  2899. def testInterruptedSendTimeout(self):
  2900. self.checkInterruptedSend(self.serv_conn.send, b"a"*512)
  2901. @support.anticipate_failure(sys.platform == "darwin")
  2902. def testInterruptedSendtoTimeout(self):
  2903. # Passing an actual address here as Python's wrapper for
  2904. # sendto() doesn't allow passing a zero-length one; POSIX
  2905. # requires that the address is ignored since the socket is
  2906. # connection-mode, however.
  2907. self.checkInterruptedSend(self.serv_conn.sendto, b"a"*512,
  2908. self.serv_addr)
  2909. @support.anticipate_failure(sys.platform == "darwin")
  2910. @requireAttrs(socket.socket, "sendmsg")
  2911. def testInterruptedSendmsgTimeout(self):
  2912. self.checkInterruptedSend(self.serv_conn.sendmsg, [b"a"*512])
  2913. @unittest.skipUnless(thread, 'Threading required for this test.')
  2914. class TCPCloserTest(ThreadedTCPSocketTest):
  2915. def testClose(self):
  2916. conn, addr = self.serv.accept()
  2917. conn.close()
  2918. sd = self.cli
  2919. read, write, err = select.select([sd], [], [], 1.0)
  2920. self.assertEqual(read, [sd])
  2921. self.assertEqual(sd.recv(1), b'')
  2922. # Calling close() many times should be safe.
  2923. conn.close()
  2924. conn.close()
  2925. def _testClose(self):
  2926. self.cli.connect((HOST, self.port))
  2927. time.sleep(1.0)
  2928. @unittest.skipUnless(thread, 'Threading required for this test.')
  2929. class BasicSocketPairTest(SocketPairTest):
  2930. def __init__(self, methodName='runTest'):
  2931. SocketPairTest.__init__(self, methodName=methodName)
  2932. def _check_defaults(self, sock):
  2933. self.assertIsInstance(sock, socket.socket)
  2934. if hasattr(socket, 'AF_UNIX'):
  2935. self.assertEqual(sock.family, socket.AF_UNIX)
  2936. else:
  2937. self.assertEqual(sock.family, socket.AF_INET)
  2938. self.assertEqual(sock.type, socket.SOCK_STREAM)
  2939. self.assertEqual(sock.proto, 0)
  2940. def _testDefaults(self):
  2941. self._check_defaults(self.cli)
  2942. def testDefaults(self):
  2943. self._check_defaults(self.serv)
  2944. def testRecv(self):
  2945. msg = self.serv.recv(1024)
  2946. self.assertEqual(msg, MSG)
  2947. def _testRecv(self):
  2948. self.cli.send(MSG)
  2949. def testSend(self):
  2950. self.serv.send(MSG)
  2951. def _testSend(self):
  2952. msg = self.cli.recv(1024)
  2953. self.assertEqual(msg, MSG)
  2954. @unittest.skipUnless(thread, 'Threading required for this test.')
  2955. class NonBlockingTCPTests(ThreadedTCPSocketTest):
  2956. def __init__(self, methodName='runTest'):
  2957. ThreadedTCPSocketTest.__init__(self, methodName=methodName)
  2958. def testSetBlocking(self):
  2959. # Testing whether set blocking works
  2960. self.serv.setblocking(0)
  2961. start = time.time()
  2962. try:
  2963. self.serv.accept()
  2964. except OSError:
  2965. pass
  2966. end = time.time()
  2967. self.assertTrue((end - start) < 1.0, "Error setting non-blocking mode.")
  2968. def _testSetBlocking(self):
  2969. pass
  2970. if hasattr(socket, "SOCK_NONBLOCK"):
  2971. @support.requires_linux_version(2, 6, 28)
  2972. def testInitNonBlocking(self):
  2973. # reinit server socket
  2974. self.serv.close()
  2975. self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM |
  2976. socket.SOCK_NONBLOCK)
  2977. self.port = support.bind_port(self.serv)
  2978. self.serv.listen(1)
  2979. # actual testing
  2980. start = time.time()
  2981. try:
  2982. self.serv.accept()
  2983. except OSError:
  2984. pass
  2985. end = time.time()
  2986. self.assertTrue((end - start) < 1.0, "Error creating with non-blocking mode.")
  2987. def _testInitNonBlocking(self):
  2988. pass
  2989. def testInheritFlags(self):
  2990. # Issue #7995: when calling accept() on a listening socket with a
  2991. # timeout, the resulting socket should not be non-blocking.
  2992. self.serv.settimeout(10)
  2993. try:
  2994. conn, addr = self.serv.accept()
  2995. message = conn.recv(len(MSG))
  2996. finally:
  2997. conn.close()
  2998. self.serv.settimeout(None)
  2999. def _testInheritFlags(self):
  3000. time.sleep(0.1)
  3001. self.cli.connect((HOST, self.port))
  3002. time.sleep(0.5)
  3003. self.cli.send(MSG)
  3004. def testAccept(self):
  3005. # Testing non-blocking accept
  3006. self.serv.setblocking(0)
  3007. try:
  3008. conn, addr = self.serv.accept()
  3009. except OSError:
  3010. pass
  3011. else:
  3012. self.fail("Error trying to do non-blocking accept.")
  3013. read, write, err = select.select([self.serv], [], [])
  3014. if self.serv in read:
  3015. conn, addr = self.serv.accept()
  3016. conn.close()
  3017. else:
  3018. self.fail("Error trying to do accept after select.")
  3019. def _testAccept(self):
  3020. time.sleep(0.1)
  3021. self.cli.connect((HOST, self.port))
  3022. def testConnect(self):
  3023. # Testing non-blocking connect
  3024. conn, addr = self.serv.accept()
  3025. conn.close()
  3026. def _testConnect(self):
  3027. self.cli.settimeout(10)
  3028. self.cli.connect((HOST, self.port))
  3029. def testRecv(self):
  3030. # Testing non-blocking recv
  3031. conn, addr = self.serv.accept()
  3032. conn.setblocking(0)
  3033. try:
  3034. msg = conn.recv(len(MSG))
  3035. except OSError:
  3036. pass
  3037. else:
  3038. self.fail("Error trying to do non-blocking recv.")
  3039. read, write, err = select.select([conn], [], [])
  3040. if conn in read:
  3041. msg = conn.recv(len(MSG))
  3042. conn.close()
  3043. self.assertEqual(msg, MSG)
  3044. else:
  3045. self.fail("Error during select call to non-blocking socket.")
  3046. def _testRecv(self):
  3047. self.cli.connect((HOST, self.port))
  3048. time.sleep(0.1)
  3049. self.cli.send(MSG)
  3050. @unittest.skipUnless(thread, 'Threading required for this test.')
  3051. class FileObjectClassTestCase(SocketConnectedTest):
  3052. """Unit tests for the object returned by socket.makefile()
  3053. self.read_file is the io object returned by makefile() on
  3054. the client connection. You can read from this file to
  3055. get output from the server.
  3056. self.write_file is the io object returned by makefile() on the
  3057. server connection. You can write to this file to send output
  3058. to the client.
  3059. """
  3060. bufsize = -1 # Use default buffer size
  3061. encoding = 'utf-8'
  3062. errors = 'strict'
  3063. newline = None
  3064. read_mode = 'rb'
  3065. read_msg = MSG
  3066. write_mode = 'wb'
  3067. write_msg = MSG
  3068. def __init__(self, methodName='runTest'):
  3069. SocketConnectedTest.__init__(self, methodName=methodName)
  3070. def setUp(self):
  3071. self.evt1, self.evt2, self.serv_finished, self.cli_finished = [
  3072. threading.Event() for i in range(4)]
  3073. SocketConnectedTest.setUp(self)
  3074. self.read_file = self.cli_conn.makefile(
  3075. self.read_mode, self.bufsize,
  3076. encoding = self.encoding,
  3077. errors = self.errors,
  3078. newline = self.newline)
  3079. def tearDown(self):
  3080. self.serv_finished.set()
  3081. self.read_file.close()
  3082. self.assertTrue(self.read_file.closed)
  3083. self.read_file = None
  3084. SocketConnectedTest.tearDown(self)
  3085. def clientSetUp(self):
  3086. SocketConnectedTest.clientSetUp(self)
  3087. self.write_file = self.serv_conn.makefile(
  3088. self.write_mode, self.bufsize,
  3089. encoding = self.encoding,
  3090. errors = self.errors,
  3091. newline = self.newline)
  3092. def clientTearDown(self):
  3093. self.cli_finished.set()
  3094. self.write_file.close()
  3095. self.assertTrue(self.write_file.closed)
  3096. self.write_file = None
  3097. SocketConnectedTest.clientTearDown(self)
  3098. def testReadAfterTimeout(self):
  3099. # Issue #7322: A file object must disallow further reads
  3100. # after a timeout has occurred.
  3101. self.cli_conn.settimeout(1)
  3102. self.read_file.read(3)
  3103. # First read raises a timeout
  3104. self.assertRaises(socket.timeout, self.read_file.read, 1)
  3105. # Second read is disallowed
  3106. with self.assertRaises(OSError) as ctx:
  3107. self.read_file.read(1)
  3108. self.assertIn("cannot read from timed out object", str(ctx.exception))
  3109. def _testReadAfterTimeout(self):
  3110. self.write_file.write(self.write_msg[0:3])
  3111. self.write_file.flush()
  3112. self.serv_finished.wait()
  3113. def testSmallRead(self):
  3114. # Performing small file read test
  3115. first_seg = self.read_file.read(len(self.read_msg)-3)
  3116. second_seg = self.read_file.read(3)
  3117. msg = first_seg + second_seg
  3118. self.assertEqual(msg, self.read_msg)
  3119. def _testSmallRead(self):
  3120. self.write_file.write(self.write_msg)
  3121. self.write_file.flush()
  3122. def testFullRead(self):
  3123. # read until EOF
  3124. msg = self.read_file.read()
  3125. self.assertEqual(msg, self.read_msg)
  3126. def _testFullRead(self):
  3127. self.write_file.write(self.write_msg)
  3128. self.write_file.close()
  3129. def testUnbufferedRead(self):
  3130. # Performing unbuffered file read test
  3131. buf = type(self.read_msg)()
  3132. while 1:
  3133. char = self.read_file.read(1)
  3134. if not char:
  3135. break
  3136. buf += char
  3137. self.assertEqual(buf, self.read_msg)
  3138. def _testUnbufferedRead(self):
  3139. self.write_file.write(self.write_msg)
  3140. self.write_file.flush()
  3141. def testReadline(self):
  3142. # Performing file readline test
  3143. line = self.read_file.readline()
  3144. self.assertEqual(line, self.read_msg)
  3145. def _testReadline(self):
  3146. self.write_file.write(self.write_msg)
  3147. self.write_file.flush()
  3148. def testCloseAfterMakefile(self):
  3149. # The file returned by makefile should keep the socket open.
  3150. self.cli_conn.close()
  3151. # read until EOF
  3152. msg = self.read_file.read()
  3153. self.assertEqual(msg, self.read_msg)
  3154. def _testCloseAfterMakefile(self):
  3155. self.write_file.write(self.write_msg)
  3156. self.write_file.flush()
  3157. def testMakefileAfterMakefileClose(self):
  3158. self.read_file.close()
  3159. msg = self.cli_conn.recv(len(MSG))
  3160. if isinstance(self.read_msg, str):
  3161. msg = msg.decode()
  3162. self.assertEqual(msg, self.read_msg)
  3163. def _testMakefileAfterMakefileClose(self):
  3164. self.write_file.write(self.write_msg)
  3165. self.write_file.flush()
  3166. def testClosedAttr(self):
  3167. self.assertTrue(not self.read_file.closed)
  3168. def _testClosedAttr(self):
  3169. self.assertTrue(not self.write_file.closed)
  3170. def testAttributes(self):
  3171. self.assertEqual(self.read_file.mode, self.read_mode)
  3172. self.assertEqual(self.read_file.name, self.cli_conn.fileno())
  3173. def _testAttributes(self):
  3174. self.assertEqual(self.write_file.mode, self.write_mode)
  3175. self.assertEqual(self.write_file.name, self.serv_conn.fileno())
  3176. def testRealClose(self):
  3177. self.read_file.close()
  3178. self.assertRaises(ValueError, self.read_file.fileno)
  3179. self.cli_conn.close()
  3180. self.assertRaises(OSError, self.cli_conn.getsockname)
  3181. def _testRealClose(self):
  3182. pass
  3183. class FileObjectInterruptedTestCase(unittest.TestCase):
  3184. """Test that the file object correctly handles EINTR internally."""
  3185. class MockSocket(object):
  3186. def __init__(self, recv_funcs=()):
  3187. # A generator that returns callables that we'll call for each
  3188. # call to recv().
  3189. self._recv_step = iter(recv_funcs)
  3190. def recv_into(self, buffer):
  3191. data = next(self._recv_step)()
  3192. assert len(buffer) >= len(data)
  3193. buffer[:len(data)] = data
  3194. return len(data)
  3195. def _decref_socketios(self):
  3196. pass
  3197. def _textiowrap_for_test(self, buffering=-1):
  3198. raw = socket.SocketIO(self, "r")
  3199. if buffering < 0:
  3200. buffering = io.DEFAULT_BUFFER_SIZE
  3201. if buffering == 0:
  3202. return raw
  3203. buffer = io.BufferedReader(raw, buffering)
  3204. text = io.TextIOWrapper(buffer, None, None)
  3205. text.mode = "rb"
  3206. return text
  3207. @staticmethod
  3208. def _raise_eintr():
  3209. raise OSError(errno.EINTR, "interrupted")
  3210. def _textiowrap_mock_socket(self, mock, buffering=-1):
  3211. raw = socket.SocketIO(mock, "r")
  3212. if buffering < 0:
  3213. buffering = io.DEFAULT_BUFFER_SIZE
  3214. if buffering == 0:
  3215. return raw
  3216. buffer = io.BufferedReader(raw, buffering)
  3217. text = io.TextIOWrapper(buffer, None, None)
  3218. text.mode = "rb"
  3219. return text
  3220. def _test_readline(self, size=-1, buffering=-1):
  3221. mock_sock = self.MockSocket(recv_funcs=[
  3222. lambda : b"This is the first line\nAnd the sec",
  3223. self._raise_eintr,
  3224. lambda : b"ond line is here\n",
  3225. lambda : b"",
  3226. lambda : b"", # XXX(gps): io library does an extra EOF read
  3227. ])
  3228. fo = mock_sock._textiowrap_for_test(buffering=buffering)
  3229. self.assertEqual(fo.readline(size), "This is the first line\n")
  3230. self.assertEqual(fo.readline(size), "And the second line is here\n")
  3231. def _test_read(self, size=-1, buffering=-1):
  3232. mock_sock = self.MockSocket(recv_funcs=[
  3233. lambda : b"This is the first line\nAnd the sec",
  3234. self._raise_eintr,
  3235. lambda : b"ond line is here\n",
  3236. lambda : b"",
  3237. lambda : b"", # XXX(gps): io library does an extra EOF read
  3238. ])
  3239. expecting = (b"This is the first line\n"
  3240. b"And the second line is here\n")
  3241. fo = mock_sock._textiowrap_for_test(buffering=buffering)
  3242. if buffering == 0:
  3243. data = b''
  3244. else:
  3245. data = ''
  3246. expecting = expecting.decode('utf-8')
  3247. while len(data) != len(expecting):
  3248. part = fo.read(size)
  3249. if not part:
  3250. break
  3251. data += part
  3252. self.assertEqual(data, expecting)
  3253. def test_default(self):
  3254. self._test_readline()
  3255. self._test_readline(size=100)
  3256. self._test_read()
  3257. self._test_read(size=100)
  3258. def test_with_1k_buffer(self):
  3259. self._test_readline(buffering=1024)
  3260. self._test_readline(size=100, buffering=1024)
  3261. self._test_read(buffering=1024)
  3262. self._test_read(size=100, buffering=1024)
  3263. def _test_readline_no_buffer(self, size=-1):
  3264. mock_sock = self.MockSocket(recv_funcs=[
  3265. lambda : b"a",
  3266. lambda : b"\n",
  3267. lambda : b"B",
  3268. self._raise_eintr,
  3269. lambda : b"b",
  3270. lambda : b"",
  3271. ])
  3272. fo = mock_sock._textiowrap_for_test(buffering=0)
  3273. self.assertEqual(fo.readline(size), b"a\n")
  3274. self.assertEqual(fo.readline(size), b"Bb")
  3275. def test_no_buffer(self):
  3276. self._test_readline_no_buffer()
  3277. self._test_readline_no_buffer(size=4)
  3278. self._test_read(buffering=0)
  3279. self._test_read(size=100, buffering=0)
  3280. class UnbufferedFileObjectClassTestCase(FileObjectClassTestCase):
  3281. """Repeat the tests from FileObjectClassTestCase with bufsize==0.
  3282. In this case (and in this case only), it should be possible to
  3283. create a file object, read a line from it, create another file
  3284. object, read another line from it, without loss of data in the
  3285. first file object's buffer. Note that http.client relies on this
  3286. when reading multiple requests from the same socket."""
  3287. bufsize = 0 # Use unbuffered mode
  3288. def testUnbufferedReadline(self):
  3289. # Read a line, create a new file object, read another line with it
  3290. line = self.read_file.readline() # first line
  3291. self.assertEqual(line, b"A. " + self.write_msg) # first line
  3292. self.read_file = self.cli_conn.makefile('rb', 0)
  3293. line = self.read_file.readline() # second line
  3294. self.assertEqual(line, b"B. " + self.write_msg) # second line
  3295. def _testUnbufferedReadline(self):
  3296. self.write_file.write(b"A. " + self.write_msg)
  3297. self.write_file.write(b"B. " + self.write_msg)
  3298. self.write_file.flush()
  3299. def testMakefileClose(self):
  3300. # The file returned by makefile should keep the socket open...
  3301. self.cli_conn.close()
  3302. msg = self.cli_conn.recv(1024)
  3303. self.assertEqual(msg, self.read_msg)
  3304. # ...until the file is itself closed
  3305. self.read_file.close()
  3306. self.assertRaises(OSError, self.cli_conn.recv, 1024)
  3307. def _testMakefileClose(self):
  3308. self.write_file.write(self.write_msg)
  3309. self.write_file.flush()
  3310. def testMakefileCloseSocketDestroy(self):
  3311. refcount_before = sys.getrefcount(self.cli_conn)
  3312. self.read_file.close()
  3313. refcount_after = sys.getrefcount(self.cli_conn)
  3314. self.assertEqual(refcount_before - 1, refcount_after)
  3315. def _testMakefileCloseSocketDestroy(self):
  3316. pass
  3317. # Non-blocking ops
  3318. # NOTE: to set `read_file` as non-blocking, we must call
  3319. # `cli_conn.setblocking` and vice-versa (see setUp / clientSetUp).
  3320. def testSmallReadNonBlocking(self):
  3321. self.cli_conn.setblocking(False)
  3322. self.assertEqual(self.read_file.readinto(bytearray(10)), None)
  3323. self.assertEqual(self.read_file.read(len(self.read_msg) - 3), None)
  3324. self.evt1.set()
  3325. self.evt2.wait(1.0)
  3326. first_seg = self.read_file.read(len(self.read_msg) - 3)
  3327. if first_seg is None:
  3328. # Data not arrived (can happen under Windows), wait a bit
  3329. time.sleep(0.5)
  3330. first_seg = self.read_file.read(len(self.read_msg) - 3)
  3331. buf = bytearray(10)
  3332. n = self.read_file.readinto(buf)
  3333. self.assertEqual(n, 3)
  3334. msg = first_seg + buf[:n]
  3335. self.assertEqual(msg, self.read_msg)
  3336. self.assertEqual(self.read_file.readinto(bytearray(16)), None)
  3337. self.assertEqual(self.read_file.read(1), None)
  3338. def _testSmallReadNonBlocking(self):
  3339. self.evt1.wait(1.0)
  3340. self.write_file.write(self.write_msg)
  3341. self.write_file.flush()
  3342. self.evt2.set()
  3343. # Avoid cloding the socket before the server test has finished,
  3344. # otherwise system recv() will return 0 instead of EWOULDBLOCK.
  3345. self.serv_finished.wait(5.0)
  3346. def testWriteNonBlocking(self):
  3347. self.cli_finished.wait(5.0)
  3348. # The client thread can't skip directly - the SkipTest exception
  3349. # would appear as a failure.
  3350. if self.serv_skipped:
  3351. self.skipTest(self.serv_skipped)
  3352. def _testWriteNonBlocking(self):
  3353. self.serv_skipped = None
  3354. self.serv_conn.setblocking(False)
  3355. # Try to saturate the socket buffer pipe with repeated large writes.
  3356. BIG = b"x" * (1024 ** 2)
  3357. LIMIT = 10
  3358. # The first write() succeeds since a chunk of data can be buffered
  3359. n = self.write_file.write(BIG)
  3360. self.assertGreater(n, 0)
  3361. for i in range(LIMIT):
  3362. n = self.write_file.write(BIG)
  3363. if n is None:
  3364. # Succeeded
  3365. break
  3366. self.assertGreater(n, 0)
  3367. else:
  3368. # Let us know that this test didn't manage to establish
  3369. # the expected conditions. This is not a failure in itself but,
  3370. # if it happens repeatedly, the test should be fixed.
  3371. self.serv_skipped = "failed to saturate the socket buffer"
  3372. class LineBufferedFileObjectClassTestCase(FileObjectClassTestCase):
  3373. bufsize = 1 # Default-buffered for reading; line-buffered for writing
  3374. class SmallBufferedFileObjectClassTestCase(FileObjectClassTestCase):
  3375. bufsize = 2 # Exercise the buffering code
  3376. class UnicodeReadFileObjectClassTestCase(FileObjectClassTestCase):
  3377. """Tests for socket.makefile() in text mode (rather than binary)"""
  3378. read_mode = 'r'
  3379. read_msg = MSG.decode('utf-8')
  3380. write_mode = 'wb'
  3381. write_msg = MSG
  3382. newline = ''
  3383. class UnicodeWriteFileObjectClassTestCase(FileObjectClassTestCase):
  3384. """Tests for socket.makefile() in text mode (rather than binary)"""
  3385. read_mode = 'rb'
  3386. read_msg = MSG
  3387. write_mode = 'w'
  3388. write_msg = MSG.decode('utf-8')
  3389. newline = ''
  3390. class UnicodeReadWriteFileObjectClassTestCase(FileObjectClassTestCase):
  3391. """Tests for socket.makefile() in text mode (rather than binary)"""
  3392. read_mode = 'r'
  3393. read_msg = MSG.decode('utf-8')
  3394. write_mode = 'w'
  3395. write_msg = MSG.decode('utf-8')
  3396. newline = ''
  3397. class NetworkConnectionTest(object):
  3398. """Prove network connection."""
  3399. def clientSetUp(self):
  3400. # We're inherited below by BasicTCPTest2, which also inherits
  3401. # BasicTCPTest, which defines self.port referenced below.
  3402. self.cli = socket.create_connection((HOST, self.port))
  3403. self.serv_conn = self.cli
  3404. class BasicTCPTest2(NetworkConnectionTest, BasicTCPTest):
  3405. """Tests that NetworkConnection does not break existing TCP functionality.
  3406. """
  3407. class NetworkConnectionNoServer(unittest.TestCase):
  3408. class MockSocket(socket.socket):
  3409. def connect(self, *args):
  3410. raise socket.timeout('timed out')
  3411. @contextlib.contextmanager
  3412. def mocked_socket_module(self):
  3413. """Return a socket which times out on connect"""
  3414. old_socket = socket.socket
  3415. socket.socket = self.MockSocket
  3416. try:
  3417. yield
  3418. finally:
  3419. socket.socket = old_socket
  3420. def test_connect(self):
  3421. port = support.find_unused_port()
  3422. cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  3423. self.addCleanup(cli.close)
  3424. with self.assertRaises(OSError) as cm:
  3425. cli.connect((HOST, port))
  3426. self.assertEqual(cm.exception.errno, errno.ECONNREFUSED)
  3427. def test_create_connection(self):
  3428. # Issue #9792: errors raised by create_connection() should have
  3429. # a proper errno attribute.
  3430. port = support.find_unused_port()
  3431. with self.assertRaises(OSError) as cm:
  3432. socket.create_connection((HOST, port))
  3433. # Issue #16257: create_connection() calls getaddrinfo() against
  3434. # 'localhost'. This may result in an IPV6 addr being returned
  3435. # as well as an IPV4 one:
  3436. # >>> socket.getaddrinfo('localhost', port, 0, SOCK_STREAM)
  3437. # >>> [(2, 2, 0, '', ('127.0.0.1', 41230)),
  3438. # (26, 2, 0, '', ('::1', 41230, 0, 0))]
  3439. #
  3440. # create_connection() enumerates through all the addresses returned
  3441. # and if it doesn't successfully bind to any of them, it propagates
  3442. # the last exception it encountered.
  3443. #
  3444. # On Solaris, ENETUNREACH is returned in this circumstance instead
  3445. # of ECONNREFUSED. So, if that errno exists, add it to our list of
  3446. # expected errnos.
  3447. expected_errnos = [ errno.ECONNREFUSED, ]
  3448. if hasattr(errno, 'ENETUNREACH'):
  3449. expected_errnos.append(errno.ENETUNREACH)
  3450. self.assertIn(cm.exception.errno, expected_errnos)
  3451. def test_create_connection_timeout(self):
  3452. # Issue #9792: create_connection() should not recast timeout errors
  3453. # as generic socket errors.
  3454. with self.mocked_socket_module():
  3455. with self.assertRaises(socket.timeout):
  3456. socket.create_connection((HOST, 1234))
  3457. @unittest.skipUnless(thread, 'Threading required for this test.')
  3458. class NetworkConnectionAttributesTest(SocketTCPTest, ThreadableTest):
  3459. def __init__(self, methodName='runTest'):
  3460. SocketTCPTest.__init__(self, methodName=methodName)
  3461. ThreadableTest.__init__(self)
  3462. def clientSetUp(self):
  3463. self.source_port = support.find_unused_port()
  3464. def clientTearDown(self):
  3465. self.cli.close()
  3466. self.cli = None
  3467. ThreadableTest.clientTearDown(self)
  3468. def _justAccept(self):
  3469. conn, addr = self.serv.accept()
  3470. conn.close()
  3471. testFamily = _justAccept
  3472. def _testFamily(self):
  3473. self.cli = socket.create_connection((HOST, self.port), timeout=30)
  3474. self.addCleanup(self.cli.close)
  3475. self.assertEqual(self.cli.family, 2)
  3476. testSourceAddress = _justAccept
  3477. def _testSourceAddress(self):
  3478. self.cli = socket.create_connection((HOST, self.port), timeout=30,
  3479. source_address=('', self.source_port))
  3480. self.addCleanup(self.cli.close)
  3481. self.assertEqual(self.cli.getsockname()[1], self.source_port)
  3482. # The port number being used is sufficient to show that the bind()
  3483. # call happened.
  3484. testTimeoutDefault = _justAccept
  3485. def _testTimeoutDefault(self):
  3486. # passing no explicit timeout uses socket's global default
  3487. self.assertTrue(socket.getdefaulttimeout() is None)
  3488. socket.setdefaulttimeout(42)
  3489. try:
  3490. self.cli = socket.create_connection((HOST, self.port))
  3491. self.addCleanup(self.cli.close)
  3492. finally:
  3493. socket.setdefaulttimeout(None)
  3494. self.assertEqual(self.cli.gettimeout(), 42)
  3495. testTimeoutNone = _justAccept
  3496. def _testTimeoutNone(self):
  3497. # None timeout means the same as sock.settimeout(None)
  3498. self.assertTrue(socket.getdefaulttimeout() is None)
  3499. socket.setdefaulttimeout(30)
  3500. try:
  3501. self.cli = socket.create_connection((HOST, self.port), timeout=None)
  3502. self.addCleanup(self.cli.close)
  3503. finally:
  3504. socket.setdefaulttimeout(None)
  3505. self.assertEqual(self.cli.gettimeout(), None)
  3506. testTimeoutValueNamed = _justAccept
  3507. def _testTimeoutValueNamed(self):
  3508. self.cli = socket.create_connection((HOST, self.port), timeout=30)
  3509. self.assertEqual(self.cli.gettimeout(), 30)
  3510. testTimeoutValueNonamed = _justAccept
  3511. def _testTimeoutValueNonamed(self):
  3512. self.cli = socket.create_connection((HOST, self.port), 30)
  3513. self.addCleanup(self.cli.close)
  3514. self.assertEqual(self.cli.gettimeout(), 30)
  3515. @unittest.skipUnless(thread, 'Threading required for this test.')
  3516. class NetworkConnectionBehaviourTest(SocketTCPTest, ThreadableTest):
  3517. def __init__(self, methodName='runTest'):
  3518. SocketTCPTest.__init__(self, methodName=methodName)
  3519. ThreadableTest.__init__(self)
  3520. def clientSetUp(self):
  3521. pass
  3522. def clientTearDown(self):
  3523. self.cli.close()
  3524. self.cli = None
  3525. ThreadableTest.clientTearDown(self)
  3526. def testInsideTimeout(self):
  3527. conn, addr = self.serv.accept()
  3528. self.addCleanup(conn.close)
  3529. time.sleep(3)
  3530. conn.send(b"done!")
  3531. testOutsideTimeout = testInsideTimeout
  3532. def _testInsideTimeout(self):
  3533. self.cli = sock = socket.create_connection((HOST, self.port))
  3534. data = sock.recv(5)
  3535. self.assertEqual(data, b"done!")
  3536. def _testOutsideTimeout(self):
  3537. self.cli = sock = socket.create_connection((HOST, self.port), timeout=1)
  3538. self.assertRaises(socket.timeout, lambda: sock.recv(5))
  3539. class TCPTimeoutTest(SocketTCPTest):
  3540. def testTCPTimeout(self):
  3541. def raise_timeout(*args, **kwargs):
  3542. self.serv.settimeout(1.0)
  3543. self.serv.accept()
  3544. self.assertRaises(socket.timeout, raise_timeout,
  3545. "Error generating a timeout exception (TCP)")
  3546. def testTimeoutZero(self):
  3547. ok = False
  3548. try:
  3549. self.serv.settimeout(0.0)
  3550. foo = self.serv.accept()
  3551. except socket.timeout:
  3552. self.fail("caught timeout instead of error (TCP)")
  3553. except OSError:
  3554. ok = True
  3555. except:
  3556. self.fail("caught unexpected exception (TCP)")
  3557. if not ok:
  3558. self.fail("accept() returned success when we did not expect it")
  3559. def testInterruptedTimeout(self):
  3560. # XXX I don't know how to do this test on MSWindows or any other
  3561. # plaform that doesn't support signal.alarm() or os.kill(), though
  3562. # the bug should have existed on all platforms.
  3563. if not hasattr(signal, "alarm"):
  3564. return # can only test on *nix
  3565. self.serv.settimeout(5.0) # must be longer than alarm
  3566. class Alarm(Exception):
  3567. pass
  3568. def alarm_handler(signal, frame):
  3569. raise Alarm
  3570. old_alarm = signal.signal(signal.SIGALRM, alarm_handler)
  3571. try:
  3572. signal.alarm(2) # POSIX allows alarm to be up to 1 second early
  3573. try:
  3574. foo = self.serv.accept()
  3575. except socket.timeout:
  3576. self.fail("caught timeout instead of Alarm")
  3577. except Alarm:
  3578. pass
  3579. except:
  3580. self.fail("caught other exception instead of Alarm:"
  3581. " %s(%s):\n%s" %
  3582. (sys.exc_info()[:2] + (traceback.format_exc(),)))
  3583. else:
  3584. self.fail("nothing caught")
  3585. finally:
  3586. signal.alarm(0) # shut off alarm
  3587. except Alarm:
  3588. self.fail("got Alarm in wrong place")
  3589. finally:
  3590. # no alarm can be pending. Safe to restore old handler.
  3591. signal.signal(signal.SIGALRM, old_alarm)
  3592. class UDPTimeoutTest(SocketUDPTest):
  3593. def testUDPTimeout(self):
  3594. def raise_timeout(*args, **kwargs):
  3595. self.serv.settimeout(1.0)
  3596. self.serv.recv(1024)
  3597. self.assertRaises(socket.timeout, raise_timeout,
  3598. "Error generating a timeout exception (UDP)")
  3599. def testTimeoutZero(self):
  3600. ok = False
  3601. try:
  3602. self.serv.settimeout(0.0)
  3603. foo = self.serv.recv(1024)
  3604. except socket.timeout:
  3605. self.fail("caught timeout instead of error (UDP)")
  3606. except OSError:
  3607. ok = True
  3608. except:
  3609. self.fail("caught unexpected exception (UDP)")
  3610. if not ok:
  3611. self.fail("recv() returned success when we did not expect it")
  3612. class TestExceptions(unittest.TestCase):
  3613. def testExceptionTree(self):
  3614. self.assertTrue(issubclass(OSError, Exception))
  3615. self.assertTrue(issubclass(socket.herror, OSError))
  3616. self.assertTrue(issubclass(socket.gaierror, OSError))
  3617. self.assertTrue(issubclass(socket.timeout, OSError))
  3618. class TestLinuxAbstractNamespace(unittest.TestCase):
  3619. UNIX_PATH_MAX = 108
  3620. def testLinuxAbstractNamespace(self):
  3621. address = b"\x00python-test-hello\x00\xff"
  3622. with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s1:
  3623. s1.bind(address)
  3624. s1.listen(1)
  3625. with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s2:
  3626. s2.connect(s1.getsockname())
  3627. with s1.accept()[0] as s3:
  3628. self.assertEqual(s1.getsockname(), address)
  3629. self.assertEqual(s2.getpeername(), address)
  3630. def testMaxName(self):
  3631. address = b"\x00" + b"h" * (self.UNIX_PATH_MAX - 1)
  3632. with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s:
  3633. s.bind(address)
  3634. self.assertEqual(s.getsockname(), address)
  3635. def testNameOverflow(self):
  3636. address = "\x00" + "h" * self.UNIX_PATH_MAX
  3637. with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s:
  3638. self.assertRaises(OSError, s.bind, address)
  3639. def testStrName(self):
  3640. # Check that an abstract name can be passed as a string.
  3641. s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  3642. try:
  3643. s.bind("\x00python\x00test\x00")
  3644. self.assertEqual(s.getsockname(), b"\x00python\x00test\x00")
  3645. finally:
  3646. s.close()
  3647. class TestUnixDomain(unittest.TestCase):
  3648. def setUp(self):
  3649. self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  3650. def tearDown(self):
  3651. self.sock.close()
  3652. def encoded(self, path):
  3653. # Return the given path encoded in the file system encoding,
  3654. # or skip the test if this is not possible.
  3655. try:
  3656. return os.fsencode(path)
  3657. except UnicodeEncodeError:
  3658. self.skipTest(
  3659. "Pathname {0!a} cannot be represented in file "
  3660. "system encoding {1!r}".format(
  3661. path, sys.getfilesystemencoding()))
  3662. def bind(self, sock, path):
  3663. # Bind the socket
  3664. try:
  3665. sock.bind(path)
  3666. except OSError as e:
  3667. if str(e) == "AF_UNIX path too long":
  3668. self.skipTest(
  3669. "Pathname {0!a} is too long to serve as a AF_UNIX path"
  3670. .format(path))
  3671. else:
  3672. raise
  3673. def testStrAddr(self):
  3674. # Test binding to and retrieving a normal string pathname.
  3675. path = os.path.abspath(support.TESTFN)
  3676. self.bind(self.sock, path)
  3677. self.addCleanup(support.unlink, path)
  3678. self.assertEqual(self.sock.getsockname(), path)
  3679. def testBytesAddr(self):
  3680. # Test binding to a bytes pathname.
  3681. path = os.path.abspath(support.TESTFN)
  3682. self.bind(self.sock, self.encoded(path))
  3683. self.addCleanup(support.unlink, path)
  3684. self.assertEqual(self.sock.getsockname(), path)
  3685. def testSurrogateescapeBind(self):
  3686. # Test binding to a valid non-ASCII pathname, with the
  3687. # non-ASCII bytes supplied using surrogateescape encoding.
  3688. path = os.path.abspath(support.TESTFN_UNICODE)
  3689. b = self.encoded(path)
  3690. self.bind(self.sock, b.decode("ascii", "surrogateescape"))
  3691. self.addCleanup(support.unlink, path)
  3692. self.assertEqual(self.sock.getsockname(), path)
  3693. def testUnencodableAddr(self):
  3694. # Test binding to a pathname that cannot be encoded in the
  3695. # file system encoding.
  3696. if support.TESTFN_UNENCODABLE is None:
  3697. self.skipTest("No unencodable filename available")
  3698. path = os.path.abspath(support.TESTFN_UNENCODABLE)
  3699. self.bind(self.sock, path)
  3700. self.addCleanup(support.unlink, path)
  3701. self.assertEqual(self.sock.getsockname(), path)
  3702. @unittest.skipUnless(thread, 'Threading required for this test.')
  3703. class BufferIOTest(SocketConnectedTest):
  3704. """
  3705. Test the buffer versions of socket.recv() and socket.send().
  3706. """
  3707. def __init__(self, methodName='runTest'):
  3708. SocketConnectedTest.__init__(self, methodName=methodName)
  3709. def testRecvIntoArray(self):
  3710. buf = bytearray(1024)
  3711. nbytes = self.cli_conn.recv_into(buf)
  3712. self.assertEqual(nbytes, len(MSG))
  3713. msg = buf[:len(MSG)]
  3714. self.assertEqual(msg, MSG)
  3715. def _testRecvIntoArray(self):
  3716. buf = bytes(MSG)
  3717. self.serv_conn.send(buf)
  3718. def testRecvIntoBytearray(self):
  3719. buf = bytearray(1024)
  3720. nbytes = self.cli_conn.recv_into(buf)
  3721. self.assertEqual(nbytes, len(MSG))
  3722. msg = buf[:len(MSG)]
  3723. self.assertEqual(msg, MSG)
  3724. _testRecvIntoBytearray = _testRecvIntoArray
  3725. def testRecvIntoMemoryview(self):
  3726. buf = bytearray(1024)
  3727. nbytes = self.cli_conn.recv_into(memoryview(buf))
  3728. self.assertEqual(nbytes, len(MSG))
  3729. msg = buf[:len(MSG)]
  3730. self.assertEqual(msg, MSG)
  3731. _testRecvIntoMemoryview = _testRecvIntoArray
  3732. def testRecvFromIntoArray(self):
  3733. buf = bytearray(1024)
  3734. nbytes, addr = self.cli_conn.recvfrom_into(buf)
  3735. self.assertEqual(nbytes, len(MSG))
  3736. msg = buf[:len(MSG)]
  3737. self.assertEqual(msg, MSG)
  3738. def _testRecvFromIntoArray(self):
  3739. buf = bytes(MSG)
  3740. self.serv_conn.send(buf)
  3741. def testRecvFromIntoBytearray(self):
  3742. buf = bytearray(1024)
  3743. nbytes, addr = self.cli_conn.recvfrom_into(buf)
  3744. self.assertEqual(nbytes, len(MSG))
  3745. msg = buf[:len(MSG)]
  3746. self.assertEqual(msg, MSG)
  3747. _testRecvFromIntoBytearray = _testRecvFromIntoArray
  3748. def testRecvFromIntoMemoryview(self):
  3749. buf = bytearray(1024)
  3750. nbytes, addr = self.cli_conn.recvfrom_into(memoryview(buf))
  3751. self.assertEqual(nbytes, len(MSG))
  3752. msg = buf[:len(MSG)]
  3753. self.assertEqual(msg, MSG)
  3754. _testRecvFromIntoMemoryview = _testRecvFromIntoArray
  3755. TIPC_STYPE = 2000
  3756. TIPC_LOWER = 200
  3757. TIPC_UPPER = 210
  3758. def isTipcAvailable():
  3759. """Check if the TIPC module is loaded
  3760. The TIPC module is not loaded automatically on Ubuntu and probably
  3761. other Linux distros.
  3762. """
  3763. if not hasattr(socket, "AF_TIPC"):
  3764. return False
  3765. if not os.path.isfile("/proc/modules"):
  3766. return False
  3767. with open("/proc/modules") as f:
  3768. for line in f:
  3769. if line.startswith("tipc "):
  3770. return True
  3771. if support.verbose:
  3772. print("TIPC module is not loaded, please 'sudo modprobe tipc'")
  3773. return False
  3774. class TIPCTest(unittest.TestCase):
  3775. def testRDM(self):
  3776. srv = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
  3777. cli = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
  3778. self.addCleanup(srv.close)
  3779. self.addCleanup(cli.close)
  3780. srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  3781. srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
  3782. TIPC_LOWER, TIPC_UPPER)
  3783. srv.bind(srvaddr)
  3784. sendaddr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
  3785. TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
  3786. cli.sendto(MSG, sendaddr)
  3787. msg, recvaddr = srv.recvfrom(1024)
  3788. self.assertEqual(cli.getsockname(), recvaddr)
  3789. self.assertEqual(msg, MSG)
  3790. class TIPCThreadableTest(unittest.TestCase, ThreadableTest):
  3791. def __init__(self, methodName = 'runTest'):
  3792. unittest.TestCase.__init__(self, methodName = methodName)
  3793. ThreadableTest.__init__(self)
  3794. def setUp(self):
  3795. self.srv = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
  3796. self.addCleanup(self.srv.close)
  3797. self.srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  3798. srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
  3799. TIPC_LOWER, TIPC_UPPER)
  3800. self.srv.bind(srvaddr)
  3801. self.srv.listen(5)
  3802. self.serverExplicitReady()
  3803. self.conn, self.connaddr = self.srv.accept()
  3804. self.addCleanup(self.conn.close)
  3805. def clientSetUp(self):
  3806. # The is a hittable race between serverExplicitReady() and the
  3807. # accept() call; sleep a little while to avoid it, otherwise
  3808. # we could get an exception
  3809. time.sleep(0.1)
  3810. self.cli = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
  3811. self.addCleanup(self.cli.close)
  3812. addr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
  3813. TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
  3814. self.cli.connect(addr)
  3815. self.cliaddr = self.cli.getsockname()
  3816. def testStream(self):
  3817. msg = self.conn.recv(1024)
  3818. self.assertEqual(msg, MSG)
  3819. self.assertEqual(self.cliaddr, self.connaddr)
  3820. def _testStream(self):
  3821. self.cli.send(MSG)
  3822. self.cli.close()
  3823. @unittest.skipUnless(thread, 'Threading required for this test.')
  3824. class ContextManagersTest(ThreadedTCPSocketTest):
  3825. def _testSocketClass(self):
  3826. # base test
  3827. with socket.socket() as sock:
  3828. self.assertFalse(sock._closed)
  3829. self.assertTrue(sock._closed)
  3830. # close inside with block
  3831. with socket.socket() as sock:
  3832. sock.close()
  3833. self.assertTrue(sock._closed)
  3834. # exception inside with block
  3835. with socket.socket() as sock:
  3836. self.assertRaises(OSError, sock.sendall, b'foo')
  3837. self.assertTrue(sock._closed)
  3838. def testCreateConnectionBase(self):
  3839. conn, addr = self.serv.accept()
  3840. self.addCleanup(conn.close)
  3841. data = conn.recv(1024)
  3842. conn.sendall(data)
  3843. def _testCreateConnectionBase(self):
  3844. address = self.serv.getsockname()
  3845. with socket.create_connection(address) as sock:
  3846. self.assertFalse(sock._closed)
  3847. sock.sendall(b'foo')
  3848. self.assertEqual(sock.recv(1024), b'foo')
  3849. self.assertTrue(sock._closed)
  3850. def testCreateConnectionClose(self):
  3851. conn, addr = self.serv.accept()
  3852. self.addCleanup(conn.close)
  3853. data = conn.recv(1024)
  3854. conn.sendall(data)
  3855. def _testCreateConnectionClose(self):
  3856. address = self.serv.getsockname()
  3857. with socket.create_connection(address) as sock:
  3858. sock.close()
  3859. self.assertTrue(sock._closed)
  3860. self.assertRaises(OSError, sock.sendall, b'foo')
  3861. @unittest.skipUnless(hasattr(socket, "SOCK_CLOEXEC"),
  3862. "SOCK_CLOEXEC not defined")
  3863. @unittest.skipUnless(fcntl, "module fcntl not available")
  3864. class CloexecConstantTest(unittest.TestCase):
  3865. @support.requires_linux_version(2, 6, 28)
  3866. def test_SOCK_CLOEXEC(self):
  3867. with socket.socket(socket.AF_INET,
  3868. socket.SOCK_STREAM | socket.SOCK_CLOEXEC) as s:
  3869. self.assertTrue(s.type & socket.SOCK_CLOEXEC)
  3870. self.assertTrue(fcntl.fcntl(s, fcntl.F_GETFD) & fcntl.FD_CLOEXEC)
  3871. @unittest.skipUnless(hasattr(socket, "SOCK_NONBLOCK"),
  3872. "SOCK_NONBLOCK not defined")
  3873. class NonblockConstantTest(unittest.TestCase):
  3874. def checkNonblock(self, s, nonblock=True, timeout=0.0):
  3875. if nonblock:
  3876. self.assertTrue(s.type & socket.SOCK_NONBLOCK)
  3877. self.assertEqual(s.gettimeout(), timeout)
  3878. else:
  3879. self.assertFalse(s.type & socket.SOCK_NONBLOCK)
  3880. self.assertEqual(s.gettimeout(), None)
  3881. @support.requires_linux_version(2, 6, 28)
  3882. def test_SOCK_NONBLOCK(self):
  3883. # a lot of it seems silly and redundant, but I wanted to test that
  3884. # changing back and forth worked ok
  3885. with socket.socket(socket.AF_INET,
  3886. socket.SOCK_STREAM | socket.SOCK_NONBLOCK) as s:
  3887. self.checkNonblock(s)
  3888. s.setblocking(1)
  3889. self.checkNonblock(s, False)
  3890. s.setblocking(0)
  3891. self.checkNonblock(s)
  3892. s.settimeout(None)
  3893. self.checkNonblock(s, False)
  3894. s.settimeout(2.0)
  3895. self.checkNonblock(s, timeout=2.0)
  3896. s.setblocking(1)
  3897. self.checkNonblock(s, False)
  3898. # defaulttimeout
  3899. t = socket.getdefaulttimeout()
  3900. socket.setdefaulttimeout(0.0)
  3901. with socket.socket() as s:
  3902. self.checkNonblock(s)
  3903. socket.setdefaulttimeout(None)
  3904. with socket.socket() as s:
  3905. self.checkNonblock(s, False)
  3906. socket.setdefaulttimeout(2.0)
  3907. with socket.socket() as s:
  3908. self.checkNonblock(s, timeout=2.0)
  3909. socket.setdefaulttimeout(None)
  3910. with socket.socket() as s:
  3911. self.checkNonblock(s, False)
  3912. socket.setdefaulttimeout(t)
  3913. @unittest.skipUnless(os.name == "nt", "Windows specific")
  3914. @unittest.skipUnless(multiprocessing, "need multiprocessing")
  3915. class TestSocketSharing(SocketTCPTest):
  3916. # This must be classmethod and not staticmethod or multiprocessing
  3917. # won't be able to bootstrap it.
  3918. @classmethod
  3919. def remoteProcessServer(cls, q):
  3920. # Recreate socket from shared data
  3921. sdata = q.get()
  3922. message = q.get()
  3923. s = socket.fromshare(sdata)
  3924. s2, c = s.accept()
  3925. # Send the message
  3926. s2.sendall(message)
  3927. s2.close()
  3928. s.close()
  3929. def testShare(self):
  3930. # Transfer the listening server socket to another process
  3931. # and service it from there.
  3932. # Create process:
  3933. q = multiprocessing.Queue()
  3934. p = multiprocessing.Process(target=self.remoteProcessServer, args=(q,))
  3935. p.start()
  3936. # Get the shared socket data
  3937. data = self.serv.share(p.pid)
  3938. # Pass the shared socket to the other process
  3939. addr = self.serv.getsockname()
  3940. self.serv.close()
  3941. q.put(data)
  3942. # The data that the server will send us
  3943. message = b"slapmahfro"
  3944. q.put(message)
  3945. # Connect
  3946. s = socket.create_connection(addr)
  3947. # listen for the data
  3948. m = []
  3949. while True:
  3950. data = s.recv(100)
  3951. if not data:
  3952. break
  3953. m.append(data)
  3954. s.close()
  3955. received = b"".join(m)
  3956. self.assertEqual(received, message)
  3957. p.join()
  3958. def testShareLength(self):
  3959. data = self.serv.share(os.getpid())
  3960. self.assertRaises(ValueError, socket.fromshare, data[:-1])
  3961. self.assertRaises(ValueError, socket.fromshare, data+b"foo")
  3962. def compareSockets(self, org, other):
  3963. # socket sharing is expected to work only for blocking socket
  3964. # since the internal python timout value isn't transfered.
  3965. self.assertEqual(org.gettimeout(), None)
  3966. self.assertEqual(org.gettimeout(), other.gettimeout())
  3967. self.assertEqual(org.family, other.family)
  3968. self.assertEqual(org.type, other.type)
  3969. # If the user specified "0" for proto, then
  3970. # internally windows will have picked the correct value.
  3971. # Python introspection on the socket however will still return
  3972. # 0. For the shared socket, the python value is recreated
  3973. # from the actual value, so it may not compare correctly.
  3974. if org.proto != 0:
  3975. self.assertEqual(org.proto, other.proto)
  3976. def testShareLocal(self):
  3977. data = self.serv.share(os.getpid())
  3978. s = socket.fromshare(data)
  3979. try:
  3980. self.compareSockets(self.serv, s)
  3981. finally:
  3982. s.close()
  3983. def testTypes(self):
  3984. families = [socket.AF_INET, socket.AF_INET6]
  3985. types = [socket.SOCK_STREAM, socket.SOCK_DGRAM]
  3986. for f in families:
  3987. for t in types:
  3988. try:
  3989. source = socket.socket(f, t)
  3990. except OSError:
  3991. continue # This combination is not supported
  3992. try:
  3993. data = source.share(os.getpid())
  3994. shared = socket.fromshare(data)
  3995. try:
  3996. self.compareSockets(source, shared)
  3997. finally:
  3998. shared.close()
  3999. finally:
  4000. source.close()
  4001. def test_main():
  4002. tests = [GeneralModuleTests, BasicTCPTest, TCPCloserTest, TCPTimeoutTest,
  4003. TestExceptions, BufferIOTest, BasicTCPTest2, BasicUDPTest, UDPTimeoutTest ]
  4004. tests.extend([
  4005. NonBlockingTCPTests,
  4006. FileObjectClassTestCase,
  4007. FileObjectInterruptedTestCase,
  4008. UnbufferedFileObjectClassTestCase,
  4009. LineBufferedFileObjectClassTestCase,
  4010. SmallBufferedFileObjectClassTestCase,
  4011. UnicodeReadFileObjectClassTestCase,
  4012. UnicodeWriteFileObjectClassTestCase,
  4013. UnicodeReadWriteFileObjectClassTestCase,
  4014. NetworkConnectionNoServer,
  4015. NetworkConnectionAttributesTest,
  4016. NetworkConnectionBehaviourTest,
  4017. ContextManagersTest,
  4018. CloexecConstantTest,
  4019. NonblockConstantTest
  4020. ])
  4021. if hasattr(socket, "socketpair"):
  4022. tests.append(BasicSocketPairTest)
  4023. if hasattr(socket, "AF_UNIX"):
  4024. tests.append(TestUnixDomain)
  4025. if sys.platform == 'linux':
  4026. tests.append(TestLinuxAbstractNamespace)
  4027. if isTipcAvailable():
  4028. tests.append(TIPCTest)
  4029. tests.append(TIPCThreadableTest)
  4030. tests.extend([BasicCANTest, CANTest])
  4031. tests.extend([BasicRDSTest, RDSTest])
  4032. tests.extend([
  4033. CmsgMacroTests,
  4034. SendmsgUDPTest,
  4035. RecvmsgUDPTest,
  4036. RecvmsgIntoUDPTest,
  4037. SendmsgUDP6Test,
  4038. RecvmsgUDP6Test,
  4039. RecvmsgRFC3542AncillaryUDP6Test,
  4040. RecvmsgIntoRFC3542AncillaryUDP6Test,
  4041. RecvmsgIntoUDP6Test,
  4042. SendmsgTCPTest,
  4043. RecvmsgTCPTest,
  4044. RecvmsgIntoTCPTest,
  4045. SendmsgSCTPStreamTest,
  4046. RecvmsgSCTPStreamTest,
  4047. RecvmsgIntoSCTPStreamTest,
  4048. SendmsgUnixStreamTest,
  4049. RecvmsgUnixStreamTest,
  4050. RecvmsgIntoUnixStreamTest,
  4051. RecvmsgSCMRightsStreamTest,
  4052. RecvmsgIntoSCMRightsStreamTest,
  4053. # These are slow when setitimer() is not available
  4054. InterruptedRecvTimeoutTest,
  4055. InterruptedSendTimeoutTest,
  4056. TestSocketSharing,
  4057. ])
  4058. thread_info = support.threading_setup()
  4059. support.run_unittest(*tests)
  4060. support.threading_cleanup(*thread_info)
  4061. if __name__ == "__main__":
  4062. test_main()