PageRenderTime 123ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 0ms

/Lib/test/test_socket.py

https://bitbucket.org/python_mirrors/sandbox-jcea-cpython-2011
Python | 4818 lines | 4525 code | 149 blank | 144 comment | 37 complexity | 90ba3c35b2b514a7626a6d5a8e6e5427 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, socket.error, 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 socket.error:
  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 socket.error:
  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 socket.error 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(socket.error, msg=msg % 'socket.error'):
  507. raise socket.error
  508. with self.assertRaises(socket.error, msg=msg % 'socket.herror'):
  509. raise socket.herror
  510. with self.assertRaises(socket.error, 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 socket.error:
  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 socket.error:
  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 socket.error 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(socket.error, socket.if_indextoname, 0)
  622. self.assertRaises(socket.error, 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 socket.error:
  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 socket.error:
  685. pass
  686. else:
  687. raise socket.error
  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 socket.error:
  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. (socket.error, 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. (socket.error, 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. (socket.error, 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. (socket.error, 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 socket.error:
  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(socket.error, 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(socket.error, 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_pickle(self):
  1059. sock = socket.socket()
  1060. with sock:
  1061. for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
  1062. self.assertRaises(TypeError, pickle.dumps, sock, protocol)
  1063. def test_listen_backlog0(self):
  1064. srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  1065. srv.bind((HOST, 0))
  1066. # backlog = 0
  1067. srv.listen(0)
  1068. srv.close()
  1069. @unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 required for this test.')
  1070. def test_flowinfo(self):
  1071. self.assertRaises(OverflowError, socket.getnameinfo,
  1072. ('::1',0, 0xffffffff), 0)
  1073. with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s:
  1074. self.assertRaises(OverflowError, s.bind, ('::1', 0, -10))
  1075. @unittest.skipUnless(HAVE_SOCKET_CAN, 'SocketCan required for this test.')
  1076. class BasicCANTest(unittest.TestCase):
  1077. def testCrucialConstants(self):
  1078. socket.AF_CAN
  1079. socket.PF_CAN
  1080. socket.CAN_RAW
  1081. def testCreateSocket(self):
  1082. with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
  1083. pass
  1084. def testBindAny(self):
  1085. with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
  1086. s.bind(('', ))
  1087. def testTooLongInterfaceName(self):
  1088. # most systems limit IFNAMSIZ to 16, take 1024 to be sure
  1089. with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
  1090. self.assertRaisesRegex(socket.error, 'interface name too long',
  1091. s.bind, ('x' * 1024,))
  1092. @unittest.skipUnless(hasattr(socket, "CAN_RAW_LOOPBACK"),
  1093. 'socket.CAN_RAW_LOOPBACK required for this test.')
  1094. def testLoopback(self):
  1095. with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
  1096. for loopback in (0, 1):
  1097. s.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_LOOPBACK,
  1098. loopback)
  1099. self.assertEqual(loopback,
  1100. s.getsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_LOOPBACK))
  1101. @unittest.skipUnless(hasattr(socket, "CAN_RAW_FILTER"),
  1102. 'socket.CAN_RAW_FILTER required for this test.')
  1103. def testFilter(self):
  1104. can_id, can_mask = 0x200, 0x700
  1105. can_filter = struct.pack("=II", can_id, can_mask)
  1106. with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
  1107. s.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_FILTER, can_filter)
  1108. self.assertEqual(can_filter,
  1109. s.getsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_FILTER, 8))
  1110. @unittest.skipUnless(HAVE_SOCKET_CAN, 'SocketCan required for this test.')
  1111. @unittest.skipUnless(thread, 'Threading required for this test.')
  1112. class CANTest(ThreadedCANSocketTest):
  1113. """The CAN frame structure is defined in <linux/can.h>:
  1114. struct can_frame {
  1115. canid_t can_id; /* 32 bit CAN_ID + EFF/RTR/ERR flags */
  1116. __u8 can_dlc; /* data length code: 0 .. 8 */
  1117. __u8 data[8] __attribute__((aligned(8)));
  1118. };
  1119. """
  1120. can_frame_fmt = "=IB3x8s"
  1121. def __init__(self, methodName='runTest'):
  1122. ThreadedCANSocketTest.__init__(self, methodName=methodName)
  1123. @classmethod
  1124. def build_can_frame(cls, can_id, data):
  1125. """Build a CAN frame."""
  1126. can_dlc = len(data)
  1127. data = data.ljust(8, b'\x00')
  1128. return struct.pack(cls.can_frame_fmt, can_id, can_dlc, data)
  1129. @classmethod
  1130. def dissect_can_frame(cls, frame):
  1131. """Dissect a CAN frame."""
  1132. can_id, can_dlc, data = struct.unpack(cls.can_frame_fmt, frame)
  1133. return (can_id, can_dlc, data[:can_dlc])
  1134. def testSendFrame(self):
  1135. cf, addr = self.s.recvfrom(self.bufsize)
  1136. self.assertEqual(self.cf, cf)
  1137. self.assertEqual(addr[0], self.interface)
  1138. self.assertEqual(addr[1], socket.AF_CAN)
  1139. def _testSendFrame(self):
  1140. self.cf = self.build_can_frame(0x00, b'\x01\x02\x03\x04\x05')
  1141. self.cli.send(self.cf)
  1142. def testSendMaxFrame(self):
  1143. cf, addr = self.s.recvfrom(self.bufsize)
  1144. self.assertEqual(self.cf, cf)
  1145. def _testSendMaxFrame(self):
  1146. self.cf = self.build_can_frame(0x00, b'\x07' * 8)
  1147. self.cli.send(self.cf)
  1148. def testSendMultiFrames(self):
  1149. cf, addr = self.s.recvfrom(self.bufsize)
  1150. self.assertEqual(self.cf1, cf)
  1151. cf, addr = self.s.recvfrom(self.bufsize)
  1152. self.assertEqual(self.cf2, cf)
  1153. def _testSendMultiFrames(self):
  1154. self.cf1 = self.build_can_frame(0x07, b'\x44\x33\x22\x11')
  1155. self.cli.send(self.cf1)
  1156. self.cf2 = self.build_can_frame(0x12, b'\x99\x22\x33')
  1157. self.cli.send(self.cf2)
  1158. @unittest.skipUnless(HAVE_SOCKET_RDS, 'RDS sockets required for this test.')
  1159. class BasicRDSTest(unittest.TestCase):
  1160. def testCrucialConstants(self):
  1161. socket.AF_RDS
  1162. socket.PF_RDS
  1163. def testCreateSocket(self):
  1164. with socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0) as s:
  1165. pass
  1166. def testSocketBufferSize(self):
  1167. bufsize = 16384
  1168. with socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0) as s:
  1169. s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, bufsize)
  1170. s.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, bufsize)
  1171. @unittest.skipUnless(HAVE_SOCKET_RDS, 'RDS sockets required for this test.')
  1172. @unittest.skipUnless(thread, 'Threading required for this test.')
  1173. class RDSTest(ThreadedRDSSocketTest):
  1174. def __init__(self, methodName='runTest'):
  1175. ThreadedRDSSocketTest.__init__(self, methodName=methodName)
  1176. def setUp(self):
  1177. super().setUp()
  1178. self.evt = threading.Event()
  1179. def testSendAndRecv(self):
  1180. data, addr = self.serv.recvfrom(self.bufsize)
  1181. self.assertEqual(self.data, data)
  1182. self.assertEqual(self.cli_addr, addr)
  1183. def _testSendAndRecv(self):
  1184. self.data = b'spam'
  1185. self.cli.sendto(self.data, 0, (HOST, self.port))
  1186. def testPeek(self):
  1187. data, addr = self.serv.recvfrom(self.bufsize, socket.MSG_PEEK)
  1188. self.assertEqual(self.data, data)
  1189. data, addr = self.serv.recvfrom(self.bufsize)
  1190. self.assertEqual(self.data, data)
  1191. def _testPeek(self):
  1192. self.data = b'spam'
  1193. self.cli.sendto(self.data, 0, (HOST, self.port))
  1194. @requireAttrs(socket.socket, 'recvmsg')
  1195. def testSendAndRecvMsg(self):
  1196. data, ancdata, msg_flags, addr = self.serv.recvmsg(self.bufsize)
  1197. self.assertEqual(self.data, data)
  1198. @requireAttrs(socket.socket, 'sendmsg')
  1199. def _testSendAndRecvMsg(self):
  1200. self.data = b'hello ' * 10
  1201. self.cli.sendmsg([self.data], (), 0, (HOST, self.port))
  1202. def testSendAndRecvMulti(self):
  1203. data, addr = self.serv.recvfrom(self.bufsize)
  1204. self.assertEqual(self.data1, data)
  1205. data, addr = self.serv.recvfrom(self.bufsize)
  1206. self.assertEqual(self.data2, data)
  1207. def _testSendAndRecvMulti(self):
  1208. self.data1 = b'bacon'
  1209. self.cli.sendto(self.data1, 0, (HOST, self.port))
  1210. self.data2 = b'egg'
  1211. self.cli.sendto(self.data2, 0, (HOST, self.port))
  1212. def testSelect(self):
  1213. r, w, x = select.select([self.serv], [], [], 3.0)
  1214. self.assertIn(self.serv, r)
  1215. data, addr = self.serv.recvfrom(self.bufsize)
  1216. self.assertEqual(self.data, data)
  1217. def _testSelect(self):
  1218. self.data = b'select'
  1219. self.cli.sendto(self.data, 0, (HOST, self.port))
  1220. def testCongestion(self):
  1221. # wait until the sender is done
  1222. self.evt.wait()
  1223. def _testCongestion(self):
  1224. # test the behavior in case of congestion
  1225. self.data = b'fill'
  1226. self.cli.setblocking(False)
  1227. try:
  1228. # try to lower the receiver's socket buffer size
  1229. self.cli.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 16384)
  1230. except OSError:
  1231. pass
  1232. with self.assertRaises(OSError) as cm:
  1233. try:
  1234. # fill the receiver's socket buffer
  1235. while True:
  1236. self.cli.sendto(self.data, 0, (HOST, self.port))
  1237. finally:
  1238. # signal the receiver we're done
  1239. self.evt.set()
  1240. # sendto() should have failed with ENOBUFS
  1241. self.assertEqual(cm.exception.errno, errno.ENOBUFS)
  1242. # and we should have received a congestion notification through poll
  1243. r, w, x = select.select([self.serv], [], [], 3.0)
  1244. self.assertIn(self.serv, r)
  1245. @unittest.skipUnless(thread, 'Threading required for this test.')
  1246. class BasicTCPTest(SocketConnectedTest):
  1247. def __init__(self, methodName='runTest'):
  1248. SocketConnectedTest.__init__(self, methodName=methodName)
  1249. def testRecv(self):
  1250. # Testing large receive over TCP
  1251. msg = self.cli_conn.recv(1024)
  1252. self.assertEqual(msg, MSG)
  1253. def _testRecv(self):
  1254. self.serv_conn.send(MSG)
  1255. def testOverFlowRecv(self):
  1256. # Testing receive in chunks over TCP
  1257. seg1 = self.cli_conn.recv(len(MSG) - 3)
  1258. seg2 = self.cli_conn.recv(1024)
  1259. msg = seg1 + seg2
  1260. self.assertEqual(msg, MSG)
  1261. def _testOverFlowRecv(self):
  1262. self.serv_conn.send(MSG)
  1263. def testRecvFrom(self):
  1264. # Testing large recvfrom() over TCP
  1265. msg, addr = self.cli_conn.recvfrom(1024)
  1266. self.assertEqual(msg, MSG)
  1267. def _testRecvFrom(self):
  1268. self.serv_conn.send(MSG)
  1269. def testOverFlowRecvFrom(self):
  1270. # Testing recvfrom() in chunks over TCP
  1271. seg1, addr = self.cli_conn.recvfrom(len(MSG)-3)
  1272. seg2, addr = self.cli_conn.recvfrom(1024)
  1273. msg = seg1 + seg2
  1274. self.assertEqual(msg, MSG)
  1275. def _testOverFlowRecvFrom(self):
  1276. self.serv_conn.send(MSG)
  1277. def testSendAll(self):
  1278. # Testing sendall() with a 2048 byte string over TCP
  1279. msg = b''
  1280. while 1:
  1281. read = self.cli_conn.recv(1024)
  1282. if not read:
  1283. break
  1284. msg += read
  1285. self.assertEqual(msg, b'f' * 2048)
  1286. def _testSendAll(self):
  1287. big_chunk = b'f' * 2048
  1288. self.serv_conn.sendall(big_chunk)
  1289. def testFromFd(self):
  1290. # Testing fromfd()
  1291. fd = self.cli_conn.fileno()
  1292. sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
  1293. self.addCleanup(sock.close)
  1294. self.assertIsInstance(sock, socket.socket)
  1295. msg = sock.recv(1024)
  1296. self.assertEqual(msg, MSG)
  1297. def _testFromFd(self):
  1298. self.serv_conn.send(MSG)
  1299. def testDup(self):
  1300. # Testing dup()
  1301. sock = self.cli_conn.dup()
  1302. self.addCleanup(sock.close)
  1303. msg = sock.recv(1024)
  1304. self.assertEqual(msg, MSG)
  1305. def _testDup(self):
  1306. self.serv_conn.send(MSG)
  1307. def testShutdown(self):
  1308. # Testing shutdown()
  1309. msg = self.cli_conn.recv(1024)
  1310. self.assertEqual(msg, MSG)
  1311. # wait for _testShutdown to finish: on OS X, when the server
  1312. # closes the connection the client also becomes disconnected,
  1313. # and the client's shutdown call will fail. (Issue #4397.)
  1314. self.done.wait()
  1315. def _testShutdown(self):
  1316. self.serv_conn.send(MSG)
  1317. self.serv_conn.shutdown(2)
  1318. def testDetach(self):
  1319. # Testing detach()
  1320. fileno = self.cli_conn.fileno()
  1321. f = self.cli_conn.detach()
  1322. self.assertEqual(f, fileno)
  1323. # cli_conn cannot be used anymore...
  1324. self.assertTrue(self.cli_conn._closed)
  1325. self.assertRaises(socket.error, self.cli_conn.recv, 1024)
  1326. self.cli_conn.close()
  1327. # ...but we can create another socket using the (still open)
  1328. # file descriptor
  1329. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, fileno=f)
  1330. self.addCleanup(sock.close)
  1331. msg = sock.recv(1024)
  1332. self.assertEqual(msg, MSG)
  1333. def _testDetach(self):
  1334. self.serv_conn.send(MSG)
  1335. @unittest.skipUnless(thread, 'Threading required for this test.')
  1336. class BasicUDPTest(ThreadedUDPSocketTest):
  1337. def __init__(self, methodName='runTest'):
  1338. ThreadedUDPSocketTest.__init__(self, methodName=methodName)
  1339. def testSendtoAndRecv(self):
  1340. # Testing sendto() and Recv() over UDP
  1341. msg = self.serv.recv(len(MSG))
  1342. self.assertEqual(msg, MSG)
  1343. def _testSendtoAndRecv(self):
  1344. self.cli.sendto(MSG, 0, (HOST, self.port))
  1345. def testRecvFrom(self):
  1346. # Testing recvfrom() over UDP
  1347. msg, addr = self.serv.recvfrom(len(MSG))
  1348. self.assertEqual(msg, MSG)
  1349. def _testRecvFrom(self):
  1350. self.cli.sendto(MSG, 0, (HOST, self.port))
  1351. def testRecvFromNegative(self):
  1352. # Negative lengths passed to recvfrom should give ValueError.
  1353. self.assertRaises(ValueError, self.serv.recvfrom, -1)
  1354. def _testRecvFromNegative(self):
  1355. self.cli.sendto(MSG, 0, (HOST, self.port))
  1356. # Tests for the sendmsg()/recvmsg() interface. Where possible, the
  1357. # same test code is used with different families and types of socket
  1358. # (e.g. stream, datagram), and tests using recvmsg() are repeated
  1359. # using recvmsg_into().
  1360. #
  1361. # The generic test classes such as SendmsgTests and
  1362. # RecvmsgGenericTests inherit from SendrecvmsgBase and expect to be
  1363. # supplied with sockets cli_sock and serv_sock representing the
  1364. # client's and the server's end of the connection respectively, and
  1365. # attributes cli_addr and serv_addr holding their (numeric where
  1366. # appropriate) addresses.
  1367. #
  1368. # The final concrete test classes combine these with subclasses of
  1369. # SocketTestBase which set up client and server sockets of a specific
  1370. # type, and with subclasses of SendrecvmsgBase such as
  1371. # SendrecvmsgDgramBase and SendrecvmsgConnectedBase which map these
  1372. # sockets to cli_sock and serv_sock and override the methods and
  1373. # attributes of SendrecvmsgBase to fill in destination addresses if
  1374. # needed when sending, check for specific flags in msg_flags, etc.
  1375. #
  1376. # RecvmsgIntoMixin provides a version of doRecvmsg() implemented using
  1377. # recvmsg_into().
  1378. # XXX: like the other datagram (UDP) tests in this module, the code
  1379. # here assumes that datagram delivery on the local machine will be
  1380. # reliable.
  1381. class SendrecvmsgBase(ThreadSafeCleanupTestCase):
  1382. # Base class for sendmsg()/recvmsg() tests.
  1383. # Time in seconds to wait before considering a test failed, or
  1384. # None for no timeout. Not all tests actually set a timeout.
  1385. fail_timeout = 3.0
  1386. def setUp(self):
  1387. self.misc_event = threading.Event()
  1388. super().setUp()
  1389. def sendToServer(self, msg):
  1390. # Send msg to the server.
  1391. return self.cli_sock.send(msg)
  1392. # Tuple of alternative default arguments for sendmsg() when called
  1393. # via sendmsgToServer() (e.g. to include a destination address).
  1394. sendmsg_to_server_defaults = ()
  1395. def sendmsgToServer(self, *args):
  1396. # Call sendmsg() on self.cli_sock with the given arguments,
  1397. # filling in any arguments which are not supplied with the
  1398. # corresponding items of self.sendmsg_to_server_defaults, if
  1399. # any.
  1400. return self.cli_sock.sendmsg(
  1401. *(args + self.sendmsg_to_server_defaults[len(args):]))
  1402. def doRecvmsg(self, sock, bufsize, *args):
  1403. # Call recvmsg() on sock with given arguments and return its
  1404. # result. Should be used for tests which can use either
  1405. # recvmsg() or recvmsg_into() - RecvmsgIntoMixin overrides
  1406. # this method with one which emulates it using recvmsg_into(),
  1407. # thus allowing the same test to be used for both methods.
  1408. result = sock.recvmsg(bufsize, *args)
  1409. self.registerRecvmsgResult(result)
  1410. return result
  1411. def registerRecvmsgResult(self, result):
  1412. # Called by doRecvmsg() with the return value of recvmsg() or
  1413. # recvmsg_into(). Can be overridden to arrange cleanup based
  1414. # on the returned ancillary data, for instance.
  1415. pass
  1416. def checkRecvmsgAddress(self, addr1, addr2):
  1417. # Called to compare the received address with the address of
  1418. # the peer.
  1419. self.assertEqual(addr1, addr2)
  1420. # Flags that are normally unset in msg_flags
  1421. msg_flags_common_unset = 0
  1422. for name in ("MSG_CTRUNC", "MSG_OOB"):
  1423. msg_flags_common_unset |= getattr(socket, name, 0)
  1424. # Flags that are normally set
  1425. msg_flags_common_set = 0
  1426. # Flags set when a complete record has been received (e.g. MSG_EOR
  1427. # for SCTP)
  1428. msg_flags_eor_indicator = 0
  1429. # Flags set when a complete record has not been received
  1430. # (e.g. MSG_TRUNC for datagram sockets)
  1431. msg_flags_non_eor_indicator = 0
  1432. def checkFlags(self, flags, eor=None, checkset=0, checkunset=0, ignore=0):
  1433. # Method to check the value of msg_flags returned by recvmsg[_into]().
  1434. #
  1435. # Checks that all bits in msg_flags_common_set attribute are
  1436. # set in "flags" and all bits in msg_flags_common_unset are
  1437. # unset.
  1438. #
  1439. # The "eor" argument specifies whether the flags should
  1440. # indicate that a full record (or datagram) has been received.
  1441. # If "eor" is None, no checks are done; otherwise, checks
  1442. # that:
  1443. #
  1444. # * if "eor" is true, all bits in msg_flags_eor_indicator are
  1445. # set and all bits in msg_flags_non_eor_indicator are unset
  1446. #
  1447. # * if "eor" is false, all bits in msg_flags_non_eor_indicator
  1448. # are set and all bits in msg_flags_eor_indicator are unset
  1449. #
  1450. # If "checkset" and/or "checkunset" are supplied, they require
  1451. # the given bits to be set or unset respectively, overriding
  1452. # what the attributes require for those bits.
  1453. #
  1454. # If any bits are set in "ignore", they will not be checked,
  1455. # regardless of the other inputs.
  1456. #
  1457. # Will raise Exception if the inputs require a bit to be both
  1458. # set and unset, and it is not ignored.
  1459. defaultset = self.msg_flags_common_set
  1460. defaultunset = self.msg_flags_common_unset
  1461. if eor:
  1462. defaultset |= self.msg_flags_eor_indicator
  1463. defaultunset |= self.msg_flags_non_eor_indicator
  1464. elif eor is not None:
  1465. defaultset |= self.msg_flags_non_eor_indicator
  1466. defaultunset |= self.msg_flags_eor_indicator
  1467. # Function arguments override defaults
  1468. defaultset &= ~checkunset
  1469. defaultunset &= ~checkset
  1470. # Merge arguments with remaining defaults, and check for conflicts
  1471. checkset |= defaultset
  1472. checkunset |= defaultunset
  1473. inboth = checkset & checkunset & ~ignore
  1474. if inboth:
  1475. raise Exception("contradictory set, unset requirements for flags "
  1476. "{0:#x}".format(inboth))
  1477. # Compare with given msg_flags value
  1478. mask = (checkset | checkunset) & ~ignore
  1479. self.assertEqual(flags & mask, checkset & mask)
  1480. class RecvmsgIntoMixin(SendrecvmsgBase):
  1481. # Mixin to implement doRecvmsg() using recvmsg_into().
  1482. def doRecvmsg(self, sock, bufsize, *args):
  1483. buf = bytearray(bufsize)
  1484. result = sock.recvmsg_into([buf], *args)
  1485. self.registerRecvmsgResult(result)
  1486. self.assertGreaterEqual(result[0], 0)
  1487. self.assertLessEqual(result[0], bufsize)
  1488. return (bytes(buf[:result[0]]),) + result[1:]
  1489. class SendrecvmsgDgramFlagsBase(SendrecvmsgBase):
  1490. # Defines flags to be checked in msg_flags for datagram sockets.
  1491. @property
  1492. def msg_flags_non_eor_indicator(self):
  1493. return super().msg_flags_non_eor_indicator | socket.MSG_TRUNC
  1494. class SendrecvmsgSCTPFlagsBase(SendrecvmsgBase):
  1495. # Defines flags to be checked in msg_flags for SCTP sockets.
  1496. @property
  1497. def msg_flags_eor_indicator(self):
  1498. return super().msg_flags_eor_indicator | socket.MSG_EOR
  1499. class SendrecvmsgConnectionlessBase(SendrecvmsgBase):
  1500. # Base class for tests on connectionless-mode sockets. Users must
  1501. # supply sockets on attributes cli and serv to be mapped to
  1502. # cli_sock and serv_sock respectively.
  1503. @property
  1504. def serv_sock(self):
  1505. return self.serv
  1506. @property
  1507. def cli_sock(self):
  1508. return self.cli
  1509. @property
  1510. def sendmsg_to_server_defaults(self):
  1511. return ([], [], 0, self.serv_addr)
  1512. def sendToServer(self, msg):
  1513. return self.cli_sock.sendto(msg, self.serv_addr)
  1514. class SendrecvmsgConnectedBase(SendrecvmsgBase):
  1515. # Base class for tests on connected sockets. Users must supply
  1516. # sockets on attributes serv_conn and cli_conn (representing the
  1517. # connections *to* the server and the client), to be mapped to
  1518. # cli_sock and serv_sock respectively.
  1519. @property
  1520. def serv_sock(self):
  1521. return self.cli_conn
  1522. @property
  1523. def cli_sock(self):
  1524. return self.serv_conn
  1525. def checkRecvmsgAddress(self, addr1, addr2):
  1526. # Address is currently "unspecified" for a connected socket,
  1527. # so we don't examine it
  1528. pass
  1529. class SendrecvmsgServerTimeoutBase(SendrecvmsgBase):
  1530. # Base class to set a timeout on server's socket.
  1531. def setUp(self):
  1532. super().setUp()
  1533. self.serv_sock.settimeout(self.fail_timeout)
  1534. class SendmsgTests(SendrecvmsgServerTimeoutBase):
  1535. # Tests for sendmsg() which can use any socket type and do not
  1536. # involve recvmsg() or recvmsg_into().
  1537. def testSendmsg(self):
  1538. # Send a simple message with sendmsg().
  1539. self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
  1540. def _testSendmsg(self):
  1541. self.assertEqual(self.sendmsgToServer([MSG]), len(MSG))
  1542. def testSendmsgDataGenerator(self):
  1543. # Send from buffer obtained from a generator (not a sequence).
  1544. self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
  1545. def _testSendmsgDataGenerator(self):
  1546. self.assertEqual(self.sendmsgToServer((o for o in [MSG])),
  1547. len(MSG))
  1548. def testSendmsgAncillaryGenerator(self):
  1549. # Gather (empty) ancillary data from a generator.
  1550. self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
  1551. def _testSendmsgAncillaryGenerator(self):
  1552. self.assertEqual(self.sendmsgToServer([MSG], (o for o in [])),
  1553. len(MSG))
  1554. def testSendmsgArray(self):
  1555. # Send data from an array instead of the usual bytes object.
  1556. self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
  1557. def _testSendmsgArray(self):
  1558. self.assertEqual(self.sendmsgToServer([array.array("B", MSG)]),
  1559. len(MSG))
  1560. def testSendmsgGather(self):
  1561. # Send message data from more than one buffer (gather write).
  1562. self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
  1563. def _testSendmsgGather(self):
  1564. self.assertEqual(self.sendmsgToServer([MSG[:3], MSG[3:]]), len(MSG))
  1565. def testSendmsgBadArgs(self):
  1566. # Check that sendmsg() rejects invalid arguments.
  1567. self.assertEqual(self.serv_sock.recv(1000), b"done")
  1568. def _testSendmsgBadArgs(self):
  1569. self.assertRaises(TypeError, self.cli_sock.sendmsg)
  1570. self.assertRaises(TypeError, self.sendmsgToServer,
  1571. b"not in an iterable")
  1572. self.assertRaises(TypeError, self.sendmsgToServer,
  1573. object())
  1574. self.assertRaises(TypeError, self.sendmsgToServer,
  1575. [object()])
  1576. self.assertRaises(TypeError, self.sendmsgToServer,
  1577. [MSG, object()])
  1578. self.assertRaises(TypeError, self.sendmsgToServer,
  1579. [MSG], object())
  1580. self.assertRaises(TypeError, self.sendmsgToServer,
  1581. [MSG], [], object())
  1582. self.assertRaises(TypeError, self.sendmsgToServer,
  1583. [MSG], [], 0, object())
  1584. self.sendToServer(b"done")
  1585. def testSendmsgBadCmsg(self):
  1586. # Check that invalid ancillary data items are rejected.
  1587. self.assertEqual(self.serv_sock.recv(1000), b"done")
  1588. def _testSendmsgBadCmsg(self):
  1589. self.assertRaises(TypeError, self.sendmsgToServer,
  1590. [MSG], [object()])
  1591. self.assertRaises(TypeError, self.sendmsgToServer,
  1592. [MSG], [(object(), 0, b"data")])
  1593. self.assertRaises(TypeError, self.sendmsgToServer,
  1594. [MSG], [(0, object(), b"data")])
  1595. self.assertRaises(TypeError, self.sendmsgToServer,
  1596. [MSG], [(0, 0, object())])
  1597. self.assertRaises(TypeError, self.sendmsgToServer,
  1598. [MSG], [(0, 0)])
  1599. self.assertRaises(TypeError, self.sendmsgToServer,
  1600. [MSG], [(0, 0, b"data", 42)])
  1601. self.sendToServer(b"done")
  1602. @requireAttrs(socket, "CMSG_SPACE")
  1603. def testSendmsgBadMultiCmsg(self):
  1604. # Check that invalid ancillary data items are rejected when
  1605. # more than one item is present.
  1606. self.assertEqual(self.serv_sock.recv(1000), b"done")
  1607. @testSendmsgBadMultiCmsg.client_skip
  1608. def _testSendmsgBadMultiCmsg(self):
  1609. self.assertRaises(TypeError, self.sendmsgToServer,
  1610. [MSG], [0, 0, b""])
  1611. self.assertRaises(TypeError, self.sendmsgToServer,
  1612. [MSG], [(0, 0, b""), object()])
  1613. self.sendToServer(b"done")
  1614. def testSendmsgExcessCmsgReject(self):
  1615. # Check that sendmsg() rejects excess ancillary data items
  1616. # when the number that can be sent is limited.
  1617. self.assertEqual(self.serv_sock.recv(1000), b"done")
  1618. def _testSendmsgExcessCmsgReject(self):
  1619. if not hasattr(socket, "CMSG_SPACE"):
  1620. # Can only send one item
  1621. with self.assertRaises(socket.error) as cm:
  1622. self.sendmsgToServer([MSG], [(0, 0, b""), (0, 0, b"")])
  1623. self.assertIsNone(cm.exception.errno)
  1624. self.sendToServer(b"done")
  1625. def testSendmsgAfterClose(self):
  1626. # Check that sendmsg() fails on a closed socket.
  1627. pass
  1628. def _testSendmsgAfterClose(self):
  1629. self.cli_sock.close()
  1630. self.assertRaises(socket.error, self.sendmsgToServer, [MSG])
  1631. class SendmsgStreamTests(SendmsgTests):
  1632. # Tests for sendmsg() which require a stream socket and do not
  1633. # involve recvmsg() or recvmsg_into().
  1634. def testSendmsgExplicitNoneAddr(self):
  1635. # Check that peer address can be specified as None.
  1636. self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
  1637. def _testSendmsgExplicitNoneAddr(self):
  1638. self.assertEqual(self.sendmsgToServer([MSG], [], 0, None), len(MSG))
  1639. def testSendmsgTimeout(self):
  1640. # Check that timeout works with sendmsg().
  1641. self.assertEqual(self.serv_sock.recv(512), b"a"*512)
  1642. self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
  1643. def _testSendmsgTimeout(self):
  1644. try:
  1645. self.cli_sock.settimeout(0.03)
  1646. with self.assertRaises(socket.timeout):
  1647. while True:
  1648. self.sendmsgToServer([b"a"*512])
  1649. finally:
  1650. self.misc_event.set()
  1651. # XXX: would be nice to have more tests for sendmsg flags argument.
  1652. # Linux supports MSG_DONTWAIT when sending, but in general, it
  1653. # only works when receiving. Could add other platforms if they
  1654. # support it too.
  1655. @skipWithClientIf(sys.platform not in {"linux2"},
  1656. "MSG_DONTWAIT not known to work on this platform when "
  1657. "sending")
  1658. def testSendmsgDontWait(self):
  1659. # Check that MSG_DONTWAIT in flags causes non-blocking behaviour.
  1660. self.assertEqual(self.serv_sock.recv(512), b"a"*512)
  1661. self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
  1662. @testSendmsgDontWait.client_skip
  1663. def _testSendmsgDontWait(self):
  1664. try:
  1665. with self.assertRaises(socket.error) as cm:
  1666. while True:
  1667. self.sendmsgToServer([b"a"*512], [], socket.MSG_DONTWAIT)
  1668. self.assertIn(cm.exception.errno,
  1669. (errno.EAGAIN, errno.EWOULDBLOCK))
  1670. finally:
  1671. self.misc_event.set()
  1672. class SendmsgConnectionlessTests(SendmsgTests):
  1673. # Tests for sendmsg() which require a connectionless-mode
  1674. # (e.g. datagram) socket, and do not involve recvmsg() or
  1675. # recvmsg_into().
  1676. def testSendmsgNoDestAddr(self):
  1677. # Check that sendmsg() fails when no destination address is
  1678. # given for unconnected socket.
  1679. pass
  1680. def _testSendmsgNoDestAddr(self):
  1681. self.assertRaises(socket.error, self.cli_sock.sendmsg,
  1682. [MSG])
  1683. self.assertRaises(socket.error, self.cli_sock.sendmsg,
  1684. [MSG], [], 0, None)
  1685. class RecvmsgGenericTests(SendrecvmsgBase):
  1686. # Tests for recvmsg() which can also be emulated using
  1687. # recvmsg_into(), and can use any socket type.
  1688. def testRecvmsg(self):
  1689. # Receive a simple message with recvmsg[_into]().
  1690. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, len(MSG))
  1691. self.assertEqual(msg, MSG)
  1692. self.checkRecvmsgAddress(addr, self.cli_addr)
  1693. self.assertEqual(ancdata, [])
  1694. self.checkFlags(flags, eor=True)
  1695. def _testRecvmsg(self):
  1696. self.sendToServer(MSG)
  1697. def testRecvmsgExplicitDefaults(self):
  1698. # Test recvmsg[_into]() with default arguments provided explicitly.
  1699. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
  1700. len(MSG), 0, 0)
  1701. self.assertEqual(msg, MSG)
  1702. self.checkRecvmsgAddress(addr, self.cli_addr)
  1703. self.assertEqual(ancdata, [])
  1704. self.checkFlags(flags, eor=True)
  1705. def _testRecvmsgExplicitDefaults(self):
  1706. self.sendToServer(MSG)
  1707. def testRecvmsgShorter(self):
  1708. # Receive a message smaller than buffer.
  1709. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
  1710. len(MSG) + 42)
  1711. self.assertEqual(msg, MSG)
  1712. self.checkRecvmsgAddress(addr, self.cli_addr)
  1713. self.assertEqual(ancdata, [])
  1714. self.checkFlags(flags, eor=True)
  1715. def _testRecvmsgShorter(self):
  1716. self.sendToServer(MSG)
  1717. # FreeBSD < 8 doesn't always set the MSG_TRUNC flag when a truncated
  1718. # datagram is received (issue #13001).
  1719. @support.requires_freebsd_version(8)
  1720. def testRecvmsgTrunc(self):
  1721. # Receive part of message, check for truncation indicators.
  1722. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
  1723. len(MSG) - 3)
  1724. self.assertEqual(msg, MSG[:-3])
  1725. self.checkRecvmsgAddress(addr, self.cli_addr)
  1726. self.assertEqual(ancdata, [])
  1727. self.checkFlags(flags, eor=False)
  1728. @support.requires_freebsd_version(8)
  1729. def _testRecvmsgTrunc(self):
  1730. self.sendToServer(MSG)
  1731. def testRecvmsgShortAncillaryBuf(self):
  1732. # Test ancillary data buffer too small to hold any ancillary data.
  1733. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
  1734. len(MSG), 1)
  1735. self.assertEqual(msg, MSG)
  1736. self.checkRecvmsgAddress(addr, self.cli_addr)
  1737. self.assertEqual(ancdata, [])
  1738. self.checkFlags(flags, eor=True)
  1739. def _testRecvmsgShortAncillaryBuf(self):
  1740. self.sendToServer(MSG)
  1741. def testRecvmsgLongAncillaryBuf(self):
  1742. # Test large ancillary data buffer.
  1743. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
  1744. len(MSG), 10240)
  1745. self.assertEqual(msg, MSG)
  1746. self.checkRecvmsgAddress(addr, self.cli_addr)
  1747. self.assertEqual(ancdata, [])
  1748. self.checkFlags(flags, eor=True)
  1749. def _testRecvmsgLongAncillaryBuf(self):
  1750. self.sendToServer(MSG)
  1751. def testRecvmsgAfterClose(self):
  1752. # Check that recvmsg[_into]() fails on a closed socket.
  1753. self.serv_sock.close()
  1754. self.assertRaises(socket.error, self.doRecvmsg, self.serv_sock, 1024)
  1755. def _testRecvmsgAfterClose(self):
  1756. pass
  1757. def testRecvmsgTimeout(self):
  1758. # Check that timeout works.
  1759. try:
  1760. self.serv_sock.settimeout(0.03)
  1761. self.assertRaises(socket.timeout,
  1762. self.doRecvmsg, self.serv_sock, len(MSG))
  1763. finally:
  1764. self.misc_event.set()
  1765. def _testRecvmsgTimeout(self):
  1766. self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
  1767. @requireAttrs(socket, "MSG_PEEK")
  1768. def testRecvmsgPeek(self):
  1769. # Check that MSG_PEEK in flags enables examination of pending
  1770. # data without consuming it.
  1771. # Receive part of data with MSG_PEEK.
  1772. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
  1773. len(MSG) - 3, 0,
  1774. socket.MSG_PEEK)
  1775. self.assertEqual(msg, MSG[:-3])
  1776. self.checkRecvmsgAddress(addr, self.cli_addr)
  1777. self.assertEqual(ancdata, [])
  1778. # Ignoring MSG_TRUNC here (so this test is the same for stream
  1779. # and datagram sockets). Some wording in POSIX seems to
  1780. # suggest that it needn't be set when peeking, but that may
  1781. # just be a slip.
  1782. self.checkFlags(flags, eor=False,
  1783. ignore=getattr(socket, "MSG_TRUNC", 0))
  1784. # Receive all data with MSG_PEEK.
  1785. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
  1786. len(MSG), 0,
  1787. socket.MSG_PEEK)
  1788. self.assertEqual(msg, MSG)
  1789. self.checkRecvmsgAddress(addr, self.cli_addr)
  1790. self.assertEqual(ancdata, [])
  1791. self.checkFlags(flags, eor=True)
  1792. # Check that the same data can still be received normally.
  1793. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, len(MSG))
  1794. self.assertEqual(msg, MSG)
  1795. self.checkRecvmsgAddress(addr, self.cli_addr)
  1796. self.assertEqual(ancdata, [])
  1797. self.checkFlags(flags, eor=True)
  1798. @testRecvmsgPeek.client_skip
  1799. def _testRecvmsgPeek(self):
  1800. self.sendToServer(MSG)
  1801. @requireAttrs(socket.socket, "sendmsg")
  1802. def testRecvmsgFromSendmsg(self):
  1803. # Test receiving with recvmsg[_into]() when message is sent
  1804. # using sendmsg().
  1805. self.serv_sock.settimeout(self.fail_timeout)
  1806. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, len(MSG))
  1807. self.assertEqual(msg, MSG)
  1808. self.checkRecvmsgAddress(addr, self.cli_addr)
  1809. self.assertEqual(ancdata, [])
  1810. self.checkFlags(flags, eor=True)
  1811. @testRecvmsgFromSendmsg.client_skip
  1812. def _testRecvmsgFromSendmsg(self):
  1813. self.assertEqual(self.sendmsgToServer([MSG[:3], MSG[3:]]), len(MSG))
  1814. class RecvmsgGenericStreamTests(RecvmsgGenericTests):
  1815. # Tests which require a stream socket and can use either recvmsg()
  1816. # or recvmsg_into().
  1817. def testRecvmsgEOF(self):
  1818. # Receive end-of-stream indicator (b"", peer socket closed).
  1819. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, 1024)
  1820. self.assertEqual(msg, b"")
  1821. self.checkRecvmsgAddress(addr, self.cli_addr)
  1822. self.assertEqual(ancdata, [])
  1823. self.checkFlags(flags, eor=None) # Might not have end-of-record marker
  1824. def _testRecvmsgEOF(self):
  1825. self.cli_sock.close()
  1826. def testRecvmsgOverflow(self):
  1827. # Receive a message in more than one chunk.
  1828. seg1, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
  1829. len(MSG) - 3)
  1830. self.checkRecvmsgAddress(addr, self.cli_addr)
  1831. self.assertEqual(ancdata, [])
  1832. self.checkFlags(flags, eor=False)
  1833. seg2, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, 1024)
  1834. self.checkRecvmsgAddress(addr, self.cli_addr)
  1835. self.assertEqual(ancdata, [])
  1836. self.checkFlags(flags, eor=True)
  1837. msg = seg1 + seg2
  1838. self.assertEqual(msg, MSG)
  1839. def _testRecvmsgOverflow(self):
  1840. self.sendToServer(MSG)
  1841. class RecvmsgTests(RecvmsgGenericTests):
  1842. # Tests for recvmsg() which can use any socket type.
  1843. def testRecvmsgBadArgs(self):
  1844. # Check that recvmsg() rejects invalid arguments.
  1845. self.assertRaises(TypeError, self.serv_sock.recvmsg)
  1846. self.assertRaises(ValueError, self.serv_sock.recvmsg,
  1847. -1, 0, 0)
  1848. self.assertRaises(ValueError, self.serv_sock.recvmsg,
  1849. len(MSG), -1, 0)
  1850. self.assertRaises(TypeError, self.serv_sock.recvmsg,
  1851. [bytearray(10)], 0, 0)
  1852. self.assertRaises(TypeError, self.serv_sock.recvmsg,
  1853. object(), 0, 0)
  1854. self.assertRaises(TypeError, self.serv_sock.recvmsg,
  1855. len(MSG), object(), 0)
  1856. self.assertRaises(TypeError, self.serv_sock.recvmsg,
  1857. len(MSG), 0, object())
  1858. msg, ancdata, flags, addr = self.serv_sock.recvmsg(len(MSG), 0, 0)
  1859. self.assertEqual(msg, MSG)
  1860. self.checkRecvmsgAddress(addr, self.cli_addr)
  1861. self.assertEqual(ancdata, [])
  1862. self.checkFlags(flags, eor=True)
  1863. def _testRecvmsgBadArgs(self):
  1864. self.sendToServer(MSG)
  1865. class RecvmsgIntoTests(RecvmsgIntoMixin, RecvmsgGenericTests):
  1866. # Tests for recvmsg_into() which can use any socket type.
  1867. def testRecvmsgIntoBadArgs(self):
  1868. # Check that recvmsg_into() rejects invalid arguments.
  1869. buf = bytearray(len(MSG))
  1870. self.assertRaises(TypeError, self.serv_sock.recvmsg_into)
  1871. self.assertRaises(TypeError, self.serv_sock.recvmsg_into,
  1872. len(MSG), 0, 0)
  1873. self.assertRaises(TypeError, self.serv_sock.recvmsg_into,
  1874. buf, 0, 0)
  1875. self.assertRaises(TypeError, self.serv_sock.recvmsg_into,
  1876. [object()], 0, 0)
  1877. self.assertRaises(TypeError, self.serv_sock.recvmsg_into,
  1878. [b"I'm not writable"], 0, 0)
  1879. self.assertRaises(TypeError, self.serv_sock.recvmsg_into,
  1880. [buf, object()], 0, 0)
  1881. self.assertRaises(ValueError, self.serv_sock.recvmsg_into,
  1882. [buf], -1, 0)
  1883. self.assertRaises(TypeError, self.serv_sock.recvmsg_into,
  1884. [buf], object(), 0)
  1885. self.assertRaises(TypeError, self.serv_sock.recvmsg_into,
  1886. [buf], 0, object())
  1887. nbytes, ancdata, flags, addr = self.serv_sock.recvmsg_into([buf], 0, 0)
  1888. self.assertEqual(nbytes, len(MSG))
  1889. self.assertEqual(buf, bytearray(MSG))
  1890. self.checkRecvmsgAddress(addr, self.cli_addr)
  1891. self.assertEqual(ancdata, [])
  1892. self.checkFlags(flags, eor=True)
  1893. def _testRecvmsgIntoBadArgs(self):
  1894. self.sendToServer(MSG)
  1895. def testRecvmsgIntoGenerator(self):
  1896. # Receive into buffer obtained from a generator (not a sequence).
  1897. buf = bytearray(len(MSG))
  1898. nbytes, ancdata, flags, addr = self.serv_sock.recvmsg_into(
  1899. (o for o in [buf]))
  1900. self.assertEqual(nbytes, len(MSG))
  1901. self.assertEqual(buf, bytearray(MSG))
  1902. self.checkRecvmsgAddress(addr, self.cli_addr)
  1903. self.assertEqual(ancdata, [])
  1904. self.checkFlags(flags, eor=True)
  1905. def _testRecvmsgIntoGenerator(self):
  1906. self.sendToServer(MSG)
  1907. def testRecvmsgIntoArray(self):
  1908. # Receive into an array rather than the usual bytearray.
  1909. buf = array.array("B", [0] * len(MSG))
  1910. nbytes, ancdata, flags, addr = self.serv_sock.recvmsg_into([buf])
  1911. self.assertEqual(nbytes, len(MSG))
  1912. self.assertEqual(buf.tobytes(), MSG)
  1913. self.checkRecvmsgAddress(addr, self.cli_addr)
  1914. self.assertEqual(ancdata, [])
  1915. self.checkFlags(flags, eor=True)
  1916. def _testRecvmsgIntoArray(self):
  1917. self.sendToServer(MSG)
  1918. def testRecvmsgIntoScatter(self):
  1919. # Receive into multiple buffers (scatter write).
  1920. b1 = bytearray(b"----")
  1921. b2 = bytearray(b"0123456789")
  1922. b3 = bytearray(b"--------------")
  1923. nbytes, ancdata, flags, addr = self.serv_sock.recvmsg_into(
  1924. [b1, memoryview(b2)[2:9], b3])
  1925. self.assertEqual(nbytes, len(b"Mary had a little lamb"))
  1926. self.assertEqual(b1, bytearray(b"Mary"))
  1927. self.assertEqual(b2, bytearray(b"01 had a 9"))
  1928. self.assertEqual(b3, bytearray(b"little lamb---"))
  1929. self.checkRecvmsgAddress(addr, self.cli_addr)
  1930. self.assertEqual(ancdata, [])
  1931. self.checkFlags(flags, eor=True)
  1932. def _testRecvmsgIntoScatter(self):
  1933. self.sendToServer(b"Mary had a little lamb")
  1934. class CmsgMacroTests(unittest.TestCase):
  1935. # Test the functions CMSG_LEN() and CMSG_SPACE(). Tests
  1936. # assumptions used by sendmsg() and recvmsg[_into](), which share
  1937. # code with these functions.
  1938. # Match the definition in socketmodule.c
  1939. socklen_t_limit = min(0x7fffffff, _testcapi.INT_MAX)
  1940. @requireAttrs(socket, "CMSG_LEN")
  1941. def testCMSG_LEN(self):
  1942. # Test CMSG_LEN() with various valid and invalid values,
  1943. # checking the assumptions used by recvmsg() and sendmsg().
  1944. toobig = self.socklen_t_limit - socket.CMSG_LEN(0) + 1
  1945. values = list(range(257)) + list(range(toobig - 257, toobig))
  1946. # struct cmsghdr has at least three members, two of which are ints
  1947. self.assertGreater(socket.CMSG_LEN(0), array.array("i").itemsize * 2)
  1948. for n in values:
  1949. ret = socket.CMSG_LEN(n)
  1950. # This is how recvmsg() calculates the data size
  1951. self.assertEqual(ret - socket.CMSG_LEN(0), n)
  1952. self.assertLessEqual(ret, self.socklen_t_limit)
  1953. self.assertRaises(OverflowError, socket.CMSG_LEN, -1)
  1954. # sendmsg() shares code with these functions, and requires
  1955. # that it reject values over the limit.
  1956. self.assertRaises(OverflowError, socket.CMSG_LEN, toobig)
  1957. self.assertRaises(OverflowError, socket.CMSG_LEN, sys.maxsize)
  1958. @requireAttrs(socket, "CMSG_SPACE")
  1959. def testCMSG_SPACE(self):
  1960. # Test CMSG_SPACE() with various valid and invalid values,
  1961. # checking the assumptions used by sendmsg().
  1962. toobig = self.socklen_t_limit - socket.CMSG_SPACE(1) + 1
  1963. values = list(range(257)) + list(range(toobig - 257, toobig))
  1964. last = socket.CMSG_SPACE(0)
  1965. # struct cmsghdr has at least three members, two of which are ints
  1966. self.assertGreater(last, array.array("i").itemsize * 2)
  1967. for n in values:
  1968. ret = socket.CMSG_SPACE(n)
  1969. self.assertGreaterEqual(ret, last)
  1970. self.assertGreaterEqual(ret, socket.CMSG_LEN(n))
  1971. self.assertGreaterEqual(ret, n + socket.CMSG_LEN(0))
  1972. self.assertLessEqual(ret, self.socklen_t_limit)
  1973. last = ret
  1974. self.assertRaises(OverflowError, socket.CMSG_SPACE, -1)
  1975. # sendmsg() shares code with these functions, and requires
  1976. # that it reject values over the limit.
  1977. self.assertRaises(OverflowError, socket.CMSG_SPACE, toobig)
  1978. self.assertRaises(OverflowError, socket.CMSG_SPACE, sys.maxsize)
  1979. class SCMRightsTest(SendrecvmsgServerTimeoutBase):
  1980. # Tests for file descriptor passing on Unix-domain sockets.
  1981. # Invalid file descriptor value that's unlikely to evaluate to a
  1982. # real FD even if one of its bytes is replaced with a different
  1983. # value (which shouldn't actually happen).
  1984. badfd = -0x5555
  1985. def newFDs(self, n):
  1986. # Return a list of n file descriptors for newly-created files
  1987. # containing their list indices as ASCII numbers.
  1988. fds = []
  1989. for i in range(n):
  1990. fd, path = tempfile.mkstemp()
  1991. self.addCleanup(os.unlink, path)
  1992. self.addCleanup(os.close, fd)
  1993. os.write(fd, str(i).encode())
  1994. fds.append(fd)
  1995. return fds
  1996. def checkFDs(self, fds):
  1997. # Check that the file descriptors in the given list contain
  1998. # their correct list indices as ASCII numbers.
  1999. for n, fd in enumerate(fds):
  2000. os.lseek(fd, 0, os.SEEK_SET)
  2001. self.assertEqual(os.read(fd, 1024), str(n).encode())
  2002. def registerRecvmsgResult(self, result):
  2003. self.addCleanup(self.closeRecvmsgFDs, result)
  2004. def closeRecvmsgFDs(self, recvmsg_result):
  2005. # Close all file descriptors specified in the ancillary data
  2006. # of the given return value from recvmsg() or recvmsg_into().
  2007. for cmsg_level, cmsg_type, cmsg_data in recvmsg_result[1]:
  2008. if (cmsg_level == socket.SOL_SOCKET and
  2009. cmsg_type == socket.SCM_RIGHTS):
  2010. fds = array.array("i")
  2011. fds.frombytes(cmsg_data[:
  2012. len(cmsg_data) - (len(cmsg_data) % fds.itemsize)])
  2013. for fd in fds:
  2014. os.close(fd)
  2015. def createAndSendFDs(self, n):
  2016. # Send n new file descriptors created by newFDs() to the
  2017. # server, with the constant MSG as the non-ancillary data.
  2018. self.assertEqual(
  2019. self.sendmsgToServer([MSG],
  2020. [(socket.SOL_SOCKET,
  2021. socket.SCM_RIGHTS,
  2022. array.array("i", self.newFDs(n)))]),
  2023. len(MSG))
  2024. def checkRecvmsgFDs(self, numfds, result, maxcmsgs=1, ignoreflags=0):
  2025. # Check that constant MSG was received with numfds file
  2026. # descriptors in a maximum of maxcmsgs control messages (which
  2027. # must contain only complete integers). By default, check
  2028. # that MSG_CTRUNC is unset, but ignore any flags in
  2029. # ignoreflags.
  2030. msg, ancdata, flags, addr = result
  2031. self.assertEqual(msg, MSG)
  2032. self.checkRecvmsgAddress(addr, self.cli_addr)
  2033. self.checkFlags(flags, eor=True, checkunset=socket.MSG_CTRUNC,
  2034. ignore=ignoreflags)
  2035. self.assertIsInstance(ancdata, list)
  2036. self.assertLessEqual(len(ancdata), maxcmsgs)
  2037. fds = array.array("i")
  2038. for item in ancdata:
  2039. self.assertIsInstance(item, tuple)
  2040. cmsg_level, cmsg_type, cmsg_data = item
  2041. self.assertEqual(cmsg_level, socket.SOL_SOCKET)
  2042. self.assertEqual(cmsg_type, socket.SCM_RIGHTS)
  2043. self.assertIsInstance(cmsg_data, bytes)
  2044. self.assertEqual(len(cmsg_data) % SIZEOF_INT, 0)
  2045. fds.frombytes(cmsg_data)
  2046. self.assertEqual(len(fds), numfds)
  2047. self.checkFDs(fds)
  2048. def testFDPassSimple(self):
  2049. # Pass a single FD (array read from bytes object).
  2050. self.checkRecvmsgFDs(1, self.doRecvmsg(self.serv_sock,
  2051. len(MSG), 10240))
  2052. def _testFDPassSimple(self):
  2053. self.assertEqual(
  2054. self.sendmsgToServer(
  2055. [MSG],
  2056. [(socket.SOL_SOCKET,
  2057. socket.SCM_RIGHTS,
  2058. array.array("i", self.newFDs(1)).tobytes())]),
  2059. len(MSG))
  2060. def testMultipleFDPass(self):
  2061. # Pass multiple FDs in a single array.
  2062. self.checkRecvmsgFDs(4, self.doRecvmsg(self.serv_sock,
  2063. len(MSG), 10240))
  2064. def _testMultipleFDPass(self):
  2065. self.createAndSendFDs(4)
  2066. @requireAttrs(socket, "CMSG_SPACE")
  2067. def testFDPassCMSG_SPACE(self):
  2068. # Test using CMSG_SPACE() to calculate ancillary buffer size.
  2069. self.checkRecvmsgFDs(
  2070. 4, self.doRecvmsg(self.serv_sock, len(MSG),
  2071. socket.CMSG_SPACE(4 * SIZEOF_INT)))
  2072. @testFDPassCMSG_SPACE.client_skip
  2073. def _testFDPassCMSG_SPACE(self):
  2074. self.createAndSendFDs(4)
  2075. def testFDPassCMSG_LEN(self):
  2076. # Test using CMSG_LEN() to calculate ancillary buffer size.
  2077. self.checkRecvmsgFDs(1,
  2078. self.doRecvmsg(self.serv_sock, len(MSG),
  2079. socket.CMSG_LEN(4 * SIZEOF_INT)),
  2080. # RFC 3542 says implementations may set
  2081. # MSG_CTRUNC if there isn't enough space
  2082. # for trailing padding.
  2083. ignoreflags=socket.MSG_CTRUNC)
  2084. def _testFDPassCMSG_LEN(self):
  2085. self.createAndSendFDs(1)
  2086. # Issue #12958: The following test has problems on Mac OS X
  2087. @support.anticipate_failure(sys.platform == "darwin")
  2088. @requireAttrs(socket, "CMSG_SPACE")
  2089. def testFDPassSeparate(self):
  2090. # Pass two FDs in two separate arrays. Arrays may be combined
  2091. # into a single control message by the OS.
  2092. self.checkRecvmsgFDs(2,
  2093. self.doRecvmsg(self.serv_sock, len(MSG), 10240),
  2094. maxcmsgs=2)
  2095. @testFDPassSeparate.client_skip
  2096. @support.anticipate_failure(sys.platform == "darwin")
  2097. def _testFDPassSeparate(self):
  2098. fd0, fd1 = self.newFDs(2)
  2099. self.assertEqual(
  2100. self.sendmsgToServer([MSG], [(socket.SOL_SOCKET,
  2101. socket.SCM_RIGHTS,
  2102. array.array("i", [fd0])),
  2103. (socket.SOL_SOCKET,
  2104. socket.SCM_RIGHTS,
  2105. array.array("i", [fd1]))]),
  2106. len(MSG))
  2107. # Issue #12958: The following test has problems on Mac OS X
  2108. @support.anticipate_failure(sys.platform == "darwin")
  2109. @requireAttrs(socket, "CMSG_SPACE")
  2110. def testFDPassSeparateMinSpace(self):
  2111. # Pass two FDs in two separate arrays, receiving them into the
  2112. # minimum space for two arrays.
  2113. self.checkRecvmsgFDs(2,
  2114. self.doRecvmsg(self.serv_sock, len(MSG),
  2115. socket.CMSG_SPACE(SIZEOF_INT) +
  2116. socket.CMSG_LEN(SIZEOF_INT)),
  2117. maxcmsgs=2, ignoreflags=socket.MSG_CTRUNC)
  2118. @testFDPassSeparateMinSpace.client_skip
  2119. @support.anticipate_failure(sys.platform == "darwin")
  2120. def _testFDPassSeparateMinSpace(self):
  2121. fd0, fd1 = self.newFDs(2)
  2122. self.assertEqual(
  2123. self.sendmsgToServer([MSG], [(socket.SOL_SOCKET,
  2124. socket.SCM_RIGHTS,
  2125. array.array("i", [fd0])),
  2126. (socket.SOL_SOCKET,
  2127. socket.SCM_RIGHTS,
  2128. array.array("i", [fd1]))]),
  2129. len(MSG))
  2130. def sendAncillaryIfPossible(self, msg, ancdata):
  2131. # Try to send msg and ancdata to server, but if the system
  2132. # call fails, just send msg with no ancillary data.
  2133. try:
  2134. nbytes = self.sendmsgToServer([msg], ancdata)
  2135. except socket.error as e:
  2136. # Check that it was the system call that failed
  2137. self.assertIsInstance(e.errno, int)
  2138. nbytes = self.sendmsgToServer([msg])
  2139. self.assertEqual(nbytes, len(msg))
  2140. def testFDPassEmpty(self):
  2141. # Try to pass an empty FD array. Can receive either no array
  2142. # or an empty array.
  2143. self.checkRecvmsgFDs(0, self.doRecvmsg(self.serv_sock,
  2144. len(MSG), 10240),
  2145. ignoreflags=socket.MSG_CTRUNC)
  2146. def _testFDPassEmpty(self):
  2147. self.sendAncillaryIfPossible(MSG, [(socket.SOL_SOCKET,
  2148. socket.SCM_RIGHTS,
  2149. b"")])
  2150. def testFDPassPartialInt(self):
  2151. # Try to pass a truncated FD array.
  2152. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
  2153. len(MSG), 10240)
  2154. self.assertEqual(msg, MSG)
  2155. self.checkRecvmsgAddress(addr, self.cli_addr)
  2156. self.checkFlags(flags, eor=True, ignore=socket.MSG_CTRUNC)
  2157. self.assertLessEqual(len(ancdata), 1)
  2158. for cmsg_level, cmsg_type, cmsg_data in ancdata:
  2159. self.assertEqual(cmsg_level, socket.SOL_SOCKET)
  2160. self.assertEqual(cmsg_type, socket.SCM_RIGHTS)
  2161. self.assertLess(len(cmsg_data), SIZEOF_INT)
  2162. def _testFDPassPartialInt(self):
  2163. self.sendAncillaryIfPossible(
  2164. MSG,
  2165. [(socket.SOL_SOCKET,
  2166. socket.SCM_RIGHTS,
  2167. array.array("i", [self.badfd]).tobytes()[:-1])])
  2168. @requireAttrs(socket, "CMSG_SPACE")
  2169. def testFDPassPartialIntInMiddle(self):
  2170. # Try to pass two FD arrays, the first of which is truncated.
  2171. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
  2172. len(MSG), 10240)
  2173. self.assertEqual(msg, MSG)
  2174. self.checkRecvmsgAddress(addr, self.cli_addr)
  2175. self.checkFlags(flags, eor=True, ignore=socket.MSG_CTRUNC)
  2176. self.assertLessEqual(len(ancdata), 2)
  2177. fds = array.array("i")
  2178. # Arrays may have been combined in a single control message
  2179. for cmsg_level, cmsg_type, cmsg_data in ancdata:
  2180. self.assertEqual(cmsg_level, socket.SOL_SOCKET)
  2181. self.assertEqual(cmsg_type, socket.SCM_RIGHTS)
  2182. fds.frombytes(cmsg_data[:
  2183. len(cmsg_data) - (len(cmsg_data) % fds.itemsize)])
  2184. self.assertLessEqual(len(fds), 2)
  2185. self.checkFDs(fds)
  2186. @testFDPassPartialIntInMiddle.client_skip
  2187. def _testFDPassPartialIntInMiddle(self):
  2188. fd0, fd1 = self.newFDs(2)
  2189. self.sendAncillaryIfPossible(
  2190. MSG,
  2191. [(socket.SOL_SOCKET,
  2192. socket.SCM_RIGHTS,
  2193. array.array("i", [fd0, self.badfd]).tobytes()[:-1]),
  2194. (socket.SOL_SOCKET,
  2195. socket.SCM_RIGHTS,
  2196. array.array("i", [fd1]))])
  2197. def checkTruncatedHeader(self, result, ignoreflags=0):
  2198. # Check that no ancillary data items are returned when data is
  2199. # truncated inside the cmsghdr structure.
  2200. msg, ancdata, flags, addr = result
  2201. self.assertEqual(msg, MSG)
  2202. self.checkRecvmsgAddress(addr, self.cli_addr)
  2203. self.assertEqual(ancdata, [])
  2204. self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC,
  2205. ignore=ignoreflags)
  2206. def testCmsgTruncNoBufSize(self):
  2207. # Check that no ancillary data is received when no buffer size
  2208. # is specified.
  2209. self.checkTruncatedHeader(self.doRecvmsg(self.serv_sock, len(MSG)),
  2210. # BSD seems to set MSG_CTRUNC only
  2211. # if an item has been partially
  2212. # received.
  2213. ignoreflags=socket.MSG_CTRUNC)
  2214. def _testCmsgTruncNoBufSize(self):
  2215. self.createAndSendFDs(1)
  2216. def testCmsgTrunc0(self):
  2217. # Check that no ancillary data is received when buffer size is 0.
  2218. self.checkTruncatedHeader(self.doRecvmsg(self.serv_sock, len(MSG), 0),
  2219. ignoreflags=socket.MSG_CTRUNC)
  2220. def _testCmsgTrunc0(self):
  2221. self.createAndSendFDs(1)
  2222. # Check that no ancillary data is returned for various non-zero
  2223. # (but still too small) buffer sizes.
  2224. def testCmsgTrunc1(self):
  2225. self.checkTruncatedHeader(self.doRecvmsg(self.serv_sock, len(MSG), 1))
  2226. def _testCmsgTrunc1(self):
  2227. self.createAndSendFDs(1)
  2228. def testCmsgTrunc2Int(self):
  2229. # The cmsghdr structure has at least three members, two of
  2230. # which are ints, so we still shouldn't see any ancillary
  2231. # data.
  2232. self.checkTruncatedHeader(self.doRecvmsg(self.serv_sock, len(MSG),
  2233. SIZEOF_INT * 2))
  2234. def _testCmsgTrunc2Int(self):
  2235. self.createAndSendFDs(1)
  2236. def testCmsgTruncLen0Minus1(self):
  2237. self.checkTruncatedHeader(self.doRecvmsg(self.serv_sock, len(MSG),
  2238. socket.CMSG_LEN(0) - 1))
  2239. def _testCmsgTruncLen0Minus1(self):
  2240. self.createAndSendFDs(1)
  2241. # The following tests try to truncate the control message in the
  2242. # middle of the FD array.
  2243. def checkTruncatedArray(self, ancbuf, maxdata, mindata=0):
  2244. # Check that file descriptor data is truncated to between
  2245. # mindata and maxdata bytes when received with buffer size
  2246. # ancbuf, and that any complete file descriptor numbers are
  2247. # valid.
  2248. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
  2249. len(MSG), ancbuf)
  2250. self.assertEqual(msg, MSG)
  2251. self.checkRecvmsgAddress(addr, self.cli_addr)
  2252. self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC)
  2253. if mindata == 0 and ancdata == []:
  2254. return
  2255. self.assertEqual(len(ancdata), 1)
  2256. cmsg_level, cmsg_type, cmsg_data = ancdata[0]
  2257. self.assertEqual(cmsg_level, socket.SOL_SOCKET)
  2258. self.assertEqual(cmsg_type, socket.SCM_RIGHTS)
  2259. self.assertGreaterEqual(len(cmsg_data), mindata)
  2260. self.assertLessEqual(len(cmsg_data), maxdata)
  2261. fds = array.array("i")
  2262. fds.frombytes(cmsg_data[:
  2263. len(cmsg_data) - (len(cmsg_data) % fds.itemsize)])
  2264. self.checkFDs(fds)
  2265. def testCmsgTruncLen0(self):
  2266. self.checkTruncatedArray(ancbuf=socket.CMSG_LEN(0), maxdata=0)
  2267. def _testCmsgTruncLen0(self):
  2268. self.createAndSendFDs(1)
  2269. def testCmsgTruncLen0Plus1(self):
  2270. self.checkTruncatedArray(ancbuf=socket.CMSG_LEN(0) + 1, maxdata=1)
  2271. def _testCmsgTruncLen0Plus1(self):
  2272. self.createAndSendFDs(2)
  2273. def testCmsgTruncLen1(self):
  2274. self.checkTruncatedArray(ancbuf=socket.CMSG_LEN(SIZEOF_INT),
  2275. maxdata=SIZEOF_INT)
  2276. def _testCmsgTruncLen1(self):
  2277. self.createAndSendFDs(2)
  2278. def testCmsgTruncLen2Minus1(self):
  2279. self.checkTruncatedArray(ancbuf=socket.CMSG_LEN(2 * SIZEOF_INT) - 1,
  2280. maxdata=(2 * SIZEOF_INT) - 1)
  2281. def _testCmsgTruncLen2Minus1(self):
  2282. self.createAndSendFDs(2)
  2283. class RFC3542AncillaryTest(SendrecvmsgServerTimeoutBase):
  2284. # Test sendmsg() and recvmsg[_into]() using the ancillary data
  2285. # features of the RFC 3542 Advanced Sockets API for IPv6.
  2286. # Currently we can only handle certain data items (e.g. traffic
  2287. # class, hop limit, MTU discovery and fragmentation settings)
  2288. # without resorting to unportable means such as the struct module,
  2289. # but the tests here are aimed at testing the ancillary data
  2290. # handling in sendmsg() and recvmsg() rather than the IPv6 API
  2291. # itself.
  2292. # Test value to use when setting hop limit of packet
  2293. hop_limit = 2
  2294. # Test value to use when setting traffic class of packet.
  2295. # -1 means "use kernel default".
  2296. traffic_class = -1
  2297. def ancillaryMapping(self, ancdata):
  2298. # Given ancillary data list ancdata, return a mapping from
  2299. # pairs (cmsg_level, cmsg_type) to corresponding cmsg_data.
  2300. # Check that no (level, type) pair appears more than once.
  2301. d = {}
  2302. for cmsg_level, cmsg_type, cmsg_data in ancdata:
  2303. self.assertNotIn((cmsg_level, cmsg_type), d)
  2304. d[(cmsg_level, cmsg_type)] = cmsg_data
  2305. return d
  2306. def checkHopLimit(self, ancbufsize, maxhop=255, ignoreflags=0):
  2307. # Receive hop limit into ancbufsize bytes of ancillary data
  2308. # space. Check that data is MSG, ancillary data is not
  2309. # truncated (but ignore any flags in ignoreflags), and hop
  2310. # limit is between 0 and maxhop inclusive.
  2311. self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
  2312. socket.IPV6_RECVHOPLIMIT, 1)
  2313. self.misc_event.set()
  2314. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
  2315. len(MSG), ancbufsize)
  2316. self.assertEqual(msg, MSG)
  2317. self.checkRecvmsgAddress(addr, self.cli_addr)
  2318. self.checkFlags(flags, eor=True, checkunset=socket.MSG_CTRUNC,
  2319. ignore=ignoreflags)
  2320. self.assertEqual(len(ancdata), 1)
  2321. self.assertIsInstance(ancdata[0], tuple)
  2322. cmsg_level, cmsg_type, cmsg_data = ancdata[0]
  2323. self.assertEqual(cmsg_level, socket.IPPROTO_IPV6)
  2324. self.assertEqual(cmsg_type, socket.IPV6_HOPLIMIT)
  2325. self.assertIsInstance(cmsg_data, bytes)
  2326. self.assertEqual(len(cmsg_data), SIZEOF_INT)
  2327. a = array.array("i")
  2328. a.frombytes(cmsg_data)
  2329. self.assertGreaterEqual(a[0], 0)
  2330. self.assertLessEqual(a[0], maxhop)
  2331. @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
  2332. def testRecvHopLimit(self):
  2333. # Test receiving the packet hop limit as ancillary data.
  2334. self.checkHopLimit(ancbufsize=10240)
  2335. @testRecvHopLimit.client_skip
  2336. def _testRecvHopLimit(self):
  2337. # Need to wait until server has asked to receive ancillary
  2338. # data, as implementations are not required to buffer it
  2339. # otherwise.
  2340. self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
  2341. self.sendToServer(MSG)
  2342. @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
  2343. def testRecvHopLimitCMSG_SPACE(self):
  2344. # Test receiving hop limit, using CMSG_SPACE to calculate buffer size.
  2345. self.checkHopLimit(ancbufsize=socket.CMSG_SPACE(SIZEOF_INT))
  2346. @testRecvHopLimitCMSG_SPACE.client_skip
  2347. def _testRecvHopLimitCMSG_SPACE(self):
  2348. self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
  2349. self.sendToServer(MSG)
  2350. # Could test receiving into buffer sized using CMSG_LEN, but RFC
  2351. # 3542 says portable applications must provide space for trailing
  2352. # padding. Implementations may set MSG_CTRUNC if there isn't
  2353. # enough space for the padding.
  2354. @requireAttrs(socket.socket, "sendmsg")
  2355. @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
  2356. def testSetHopLimit(self):
  2357. # Test setting hop limit on outgoing packet and receiving it
  2358. # at the other end.
  2359. self.checkHopLimit(ancbufsize=10240, maxhop=self.hop_limit)
  2360. @testSetHopLimit.client_skip
  2361. def _testSetHopLimit(self):
  2362. self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
  2363. self.assertEqual(
  2364. self.sendmsgToServer([MSG],
  2365. [(socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT,
  2366. array.array("i", [self.hop_limit]))]),
  2367. len(MSG))
  2368. def checkTrafficClassAndHopLimit(self, ancbufsize, maxhop=255,
  2369. ignoreflags=0):
  2370. # Receive traffic class and hop limit into ancbufsize bytes of
  2371. # ancillary data space. Check that data is MSG, ancillary
  2372. # data is not truncated (but ignore any flags in ignoreflags),
  2373. # and traffic class and hop limit are in range (hop limit no
  2374. # more than maxhop).
  2375. self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
  2376. socket.IPV6_RECVHOPLIMIT, 1)
  2377. self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
  2378. socket.IPV6_RECVTCLASS, 1)
  2379. self.misc_event.set()
  2380. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
  2381. len(MSG), ancbufsize)
  2382. self.assertEqual(msg, MSG)
  2383. self.checkRecvmsgAddress(addr, self.cli_addr)
  2384. self.checkFlags(flags, eor=True, checkunset=socket.MSG_CTRUNC,
  2385. ignore=ignoreflags)
  2386. self.assertEqual(len(ancdata), 2)
  2387. ancmap = self.ancillaryMapping(ancdata)
  2388. tcdata = ancmap[(socket.IPPROTO_IPV6, socket.IPV6_TCLASS)]
  2389. self.assertEqual(len(tcdata), SIZEOF_INT)
  2390. a = array.array("i")
  2391. a.frombytes(tcdata)
  2392. self.assertGreaterEqual(a[0], 0)
  2393. self.assertLessEqual(a[0], 255)
  2394. hldata = ancmap[(socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT)]
  2395. self.assertEqual(len(hldata), SIZEOF_INT)
  2396. a = array.array("i")
  2397. a.frombytes(hldata)
  2398. self.assertGreaterEqual(a[0], 0)
  2399. self.assertLessEqual(a[0], maxhop)
  2400. @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
  2401. "IPV6_RECVTCLASS", "IPV6_TCLASS")
  2402. def testRecvTrafficClassAndHopLimit(self):
  2403. # Test receiving traffic class and hop limit as ancillary data.
  2404. self.checkTrafficClassAndHopLimit(ancbufsize=10240)
  2405. @testRecvTrafficClassAndHopLimit.client_skip
  2406. def _testRecvTrafficClassAndHopLimit(self):
  2407. self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
  2408. self.sendToServer(MSG)
  2409. @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
  2410. "IPV6_RECVTCLASS", "IPV6_TCLASS")
  2411. def testRecvTrafficClassAndHopLimitCMSG_SPACE(self):
  2412. # Test receiving traffic class and hop limit, using
  2413. # CMSG_SPACE() to calculate buffer size.
  2414. self.checkTrafficClassAndHopLimit(
  2415. ancbufsize=socket.CMSG_SPACE(SIZEOF_INT) * 2)
  2416. @testRecvTrafficClassAndHopLimitCMSG_SPACE.client_skip
  2417. def _testRecvTrafficClassAndHopLimitCMSG_SPACE(self):
  2418. self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
  2419. self.sendToServer(MSG)
  2420. @requireAttrs(socket.socket, "sendmsg")
  2421. @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
  2422. "IPV6_RECVTCLASS", "IPV6_TCLASS")
  2423. def testSetTrafficClassAndHopLimit(self):
  2424. # Test setting traffic class and hop limit on outgoing packet,
  2425. # and receiving them at the other end.
  2426. self.checkTrafficClassAndHopLimit(ancbufsize=10240,
  2427. maxhop=self.hop_limit)
  2428. @testSetTrafficClassAndHopLimit.client_skip
  2429. def _testSetTrafficClassAndHopLimit(self):
  2430. self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
  2431. self.assertEqual(
  2432. self.sendmsgToServer([MSG],
  2433. [(socket.IPPROTO_IPV6, socket.IPV6_TCLASS,
  2434. array.array("i", [self.traffic_class])),
  2435. (socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT,
  2436. array.array("i", [self.hop_limit]))]),
  2437. len(MSG))
  2438. @requireAttrs(socket.socket, "sendmsg")
  2439. @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
  2440. "IPV6_RECVTCLASS", "IPV6_TCLASS")
  2441. def testOddCmsgSize(self):
  2442. # Try to send ancillary data with first item one byte too
  2443. # long. Fall back to sending with correct size if this fails,
  2444. # and check that second item was handled correctly.
  2445. self.checkTrafficClassAndHopLimit(ancbufsize=10240,
  2446. maxhop=self.hop_limit)
  2447. @testOddCmsgSize.client_skip
  2448. def _testOddCmsgSize(self):
  2449. self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
  2450. try:
  2451. nbytes = self.sendmsgToServer(
  2452. [MSG],
  2453. [(socket.IPPROTO_IPV6, socket.IPV6_TCLASS,
  2454. array.array("i", [self.traffic_class]).tobytes() + b"\x00"),
  2455. (socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT,
  2456. array.array("i", [self.hop_limit]))])
  2457. except socket.error as e:
  2458. self.assertIsInstance(e.errno, int)
  2459. nbytes = self.sendmsgToServer(
  2460. [MSG],
  2461. [(socket.IPPROTO_IPV6, socket.IPV6_TCLASS,
  2462. array.array("i", [self.traffic_class])),
  2463. (socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT,
  2464. array.array("i", [self.hop_limit]))])
  2465. self.assertEqual(nbytes, len(MSG))
  2466. # Tests for proper handling of truncated ancillary data
  2467. def checkHopLimitTruncatedHeader(self, ancbufsize, ignoreflags=0):
  2468. # Receive hop limit into ancbufsize bytes of ancillary data
  2469. # space, which should be too small to contain the ancillary
  2470. # data header (if ancbufsize is None, pass no second argument
  2471. # to recvmsg()). Check that data is MSG, MSG_CTRUNC is set
  2472. # (unless included in ignoreflags), and no ancillary data is
  2473. # returned.
  2474. self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
  2475. socket.IPV6_RECVHOPLIMIT, 1)
  2476. self.misc_event.set()
  2477. args = () if ancbufsize is None else (ancbufsize,)
  2478. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
  2479. len(MSG), *args)
  2480. self.assertEqual(msg, MSG)
  2481. self.checkRecvmsgAddress(addr, self.cli_addr)
  2482. self.assertEqual(ancdata, [])
  2483. self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC,
  2484. ignore=ignoreflags)
  2485. @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
  2486. def testCmsgTruncNoBufSize(self):
  2487. # Check that no ancillary data is received when no ancillary
  2488. # buffer size is provided.
  2489. self.checkHopLimitTruncatedHeader(ancbufsize=None,
  2490. # BSD seems to set
  2491. # MSG_CTRUNC only if an item
  2492. # has been partially
  2493. # received.
  2494. ignoreflags=socket.MSG_CTRUNC)
  2495. @testCmsgTruncNoBufSize.client_skip
  2496. def _testCmsgTruncNoBufSize(self):
  2497. self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
  2498. self.sendToServer(MSG)
  2499. @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
  2500. def testSingleCmsgTrunc0(self):
  2501. # Check that no ancillary data is received when ancillary
  2502. # buffer size is zero.
  2503. self.checkHopLimitTruncatedHeader(ancbufsize=0,
  2504. ignoreflags=socket.MSG_CTRUNC)
  2505. @testSingleCmsgTrunc0.client_skip
  2506. def _testSingleCmsgTrunc0(self):
  2507. self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
  2508. self.sendToServer(MSG)
  2509. # Check that no ancillary data is returned for various non-zero
  2510. # (but still too small) buffer sizes.
  2511. @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
  2512. def testSingleCmsgTrunc1(self):
  2513. self.checkHopLimitTruncatedHeader(ancbufsize=1)
  2514. @testSingleCmsgTrunc1.client_skip
  2515. def _testSingleCmsgTrunc1(self):
  2516. self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
  2517. self.sendToServer(MSG)
  2518. @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
  2519. def testSingleCmsgTrunc2Int(self):
  2520. self.checkHopLimitTruncatedHeader(ancbufsize=2 * SIZEOF_INT)
  2521. @testSingleCmsgTrunc2Int.client_skip
  2522. def _testSingleCmsgTrunc2Int(self):
  2523. self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
  2524. self.sendToServer(MSG)
  2525. @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
  2526. def testSingleCmsgTruncLen0Minus1(self):
  2527. self.checkHopLimitTruncatedHeader(ancbufsize=socket.CMSG_LEN(0) - 1)
  2528. @testSingleCmsgTruncLen0Minus1.client_skip
  2529. def _testSingleCmsgTruncLen0Minus1(self):
  2530. self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
  2531. self.sendToServer(MSG)
  2532. @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
  2533. def testSingleCmsgTruncInData(self):
  2534. # Test truncation of a control message inside its associated
  2535. # data. The message may be returned with its data truncated,
  2536. # or not returned at all.
  2537. self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
  2538. socket.IPV6_RECVHOPLIMIT, 1)
  2539. self.misc_event.set()
  2540. msg, ancdata, flags, addr = self.doRecvmsg(
  2541. self.serv_sock, len(MSG), socket.CMSG_LEN(SIZEOF_INT) - 1)
  2542. self.assertEqual(msg, MSG)
  2543. self.checkRecvmsgAddress(addr, self.cli_addr)
  2544. self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC)
  2545. self.assertLessEqual(len(ancdata), 1)
  2546. if ancdata:
  2547. cmsg_level, cmsg_type, cmsg_data = ancdata[0]
  2548. self.assertEqual(cmsg_level, socket.IPPROTO_IPV6)
  2549. self.assertEqual(cmsg_type, socket.IPV6_HOPLIMIT)
  2550. self.assertLess(len(cmsg_data), SIZEOF_INT)
  2551. @testSingleCmsgTruncInData.client_skip
  2552. def _testSingleCmsgTruncInData(self):
  2553. self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
  2554. self.sendToServer(MSG)
  2555. def checkTruncatedSecondHeader(self, ancbufsize, ignoreflags=0):
  2556. # Receive traffic class and hop limit into ancbufsize bytes of
  2557. # ancillary data space, which should be large enough to
  2558. # contain the first item, but too small to contain the header
  2559. # of the second. Check that data is MSG, MSG_CTRUNC is set
  2560. # (unless included in ignoreflags), and only one ancillary
  2561. # data item is returned.
  2562. self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
  2563. socket.IPV6_RECVHOPLIMIT, 1)
  2564. self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
  2565. socket.IPV6_RECVTCLASS, 1)
  2566. self.misc_event.set()
  2567. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
  2568. len(MSG), ancbufsize)
  2569. self.assertEqual(msg, MSG)
  2570. self.checkRecvmsgAddress(addr, self.cli_addr)
  2571. self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC,
  2572. ignore=ignoreflags)
  2573. self.assertEqual(len(ancdata), 1)
  2574. cmsg_level, cmsg_type, cmsg_data = ancdata[0]
  2575. self.assertEqual(cmsg_level, socket.IPPROTO_IPV6)
  2576. self.assertIn(cmsg_type, {socket.IPV6_TCLASS, socket.IPV6_HOPLIMIT})
  2577. self.assertEqual(len(cmsg_data), SIZEOF_INT)
  2578. a = array.array("i")
  2579. a.frombytes(cmsg_data)
  2580. self.assertGreaterEqual(a[0], 0)
  2581. self.assertLessEqual(a[0], 255)
  2582. # Try the above test with various buffer sizes.
  2583. @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
  2584. "IPV6_RECVTCLASS", "IPV6_TCLASS")
  2585. def testSecondCmsgTrunc0(self):
  2586. self.checkTruncatedSecondHeader(socket.CMSG_SPACE(SIZEOF_INT),
  2587. ignoreflags=socket.MSG_CTRUNC)
  2588. @testSecondCmsgTrunc0.client_skip
  2589. def _testSecondCmsgTrunc0(self):
  2590. self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
  2591. self.sendToServer(MSG)
  2592. @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
  2593. "IPV6_RECVTCLASS", "IPV6_TCLASS")
  2594. def testSecondCmsgTrunc1(self):
  2595. self.checkTruncatedSecondHeader(socket.CMSG_SPACE(SIZEOF_INT) + 1)
  2596. @testSecondCmsgTrunc1.client_skip
  2597. def _testSecondCmsgTrunc1(self):
  2598. self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
  2599. self.sendToServer(MSG)
  2600. @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
  2601. "IPV6_RECVTCLASS", "IPV6_TCLASS")
  2602. def testSecondCmsgTrunc2Int(self):
  2603. self.checkTruncatedSecondHeader(socket.CMSG_SPACE(SIZEOF_INT) +
  2604. 2 * SIZEOF_INT)
  2605. @testSecondCmsgTrunc2Int.client_skip
  2606. def _testSecondCmsgTrunc2Int(self):
  2607. self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
  2608. self.sendToServer(MSG)
  2609. @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
  2610. "IPV6_RECVTCLASS", "IPV6_TCLASS")
  2611. def testSecondCmsgTruncLen0Minus1(self):
  2612. self.checkTruncatedSecondHeader(socket.CMSG_SPACE(SIZEOF_INT) +
  2613. socket.CMSG_LEN(0) - 1)
  2614. @testSecondCmsgTruncLen0Minus1.client_skip
  2615. def _testSecondCmsgTruncLen0Minus1(self):
  2616. self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
  2617. self.sendToServer(MSG)
  2618. @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
  2619. "IPV6_RECVTCLASS", "IPV6_TCLASS")
  2620. def testSecomdCmsgTruncInData(self):
  2621. # Test truncation of the second of two control messages inside
  2622. # its associated data.
  2623. self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
  2624. socket.IPV6_RECVHOPLIMIT, 1)
  2625. self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
  2626. socket.IPV6_RECVTCLASS, 1)
  2627. self.misc_event.set()
  2628. msg, ancdata, flags, addr = self.doRecvmsg(
  2629. self.serv_sock, len(MSG),
  2630. socket.CMSG_SPACE(SIZEOF_INT) + socket.CMSG_LEN(SIZEOF_INT) - 1)
  2631. self.assertEqual(msg, MSG)
  2632. self.checkRecvmsgAddress(addr, self.cli_addr)
  2633. self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC)
  2634. cmsg_types = {socket.IPV6_TCLASS, socket.IPV6_HOPLIMIT}
  2635. cmsg_level, cmsg_type, cmsg_data = ancdata.pop(0)
  2636. self.assertEqual(cmsg_level, socket.IPPROTO_IPV6)
  2637. cmsg_types.remove(cmsg_type)
  2638. self.assertEqual(len(cmsg_data), SIZEOF_INT)
  2639. a = array.array("i")
  2640. a.frombytes(cmsg_data)
  2641. self.assertGreaterEqual(a[0], 0)
  2642. self.assertLessEqual(a[0], 255)
  2643. if ancdata:
  2644. cmsg_level, cmsg_type, cmsg_data = ancdata.pop(0)
  2645. self.assertEqual(cmsg_level, socket.IPPROTO_IPV6)
  2646. cmsg_types.remove(cmsg_type)
  2647. self.assertLess(len(cmsg_data), SIZEOF_INT)
  2648. self.assertEqual(ancdata, [])
  2649. @testSecomdCmsgTruncInData.client_skip
  2650. def _testSecomdCmsgTruncInData(self):
  2651. self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
  2652. self.sendToServer(MSG)
  2653. # Derive concrete test classes for different socket types.
  2654. class SendrecvmsgUDPTestBase(SendrecvmsgDgramFlagsBase,
  2655. SendrecvmsgConnectionlessBase,
  2656. ThreadedSocketTestMixin, UDPTestBase):
  2657. pass
  2658. @requireAttrs(socket.socket, "sendmsg")
  2659. @unittest.skipUnless(thread, 'Threading required for this test.')
  2660. class SendmsgUDPTest(SendmsgConnectionlessTests, SendrecvmsgUDPTestBase):
  2661. pass
  2662. @requireAttrs(socket.socket, "recvmsg")
  2663. @unittest.skipUnless(thread, 'Threading required for this test.')
  2664. class RecvmsgUDPTest(RecvmsgTests, SendrecvmsgUDPTestBase):
  2665. pass
  2666. @requireAttrs(socket.socket, "recvmsg_into")
  2667. @unittest.skipUnless(thread, 'Threading required for this test.')
  2668. class RecvmsgIntoUDPTest(RecvmsgIntoTests, SendrecvmsgUDPTestBase):
  2669. pass
  2670. class SendrecvmsgUDP6TestBase(SendrecvmsgDgramFlagsBase,
  2671. SendrecvmsgConnectionlessBase,
  2672. ThreadedSocketTestMixin, UDP6TestBase):
  2673. pass
  2674. @requireAttrs(socket.socket, "sendmsg")
  2675. @unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 required for this test.')
  2676. @requireSocket("AF_INET6", "SOCK_DGRAM")
  2677. @unittest.skipUnless(thread, 'Threading required for this test.')
  2678. class SendmsgUDP6Test(SendmsgConnectionlessTests, SendrecvmsgUDP6TestBase):
  2679. pass
  2680. @requireAttrs(socket.socket, "recvmsg")
  2681. @unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 required for this test.')
  2682. @requireSocket("AF_INET6", "SOCK_DGRAM")
  2683. @unittest.skipUnless(thread, 'Threading required for this test.')
  2684. class RecvmsgUDP6Test(RecvmsgTests, SendrecvmsgUDP6TestBase):
  2685. pass
  2686. @requireAttrs(socket.socket, "recvmsg_into")
  2687. @unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 required for this test.')
  2688. @requireSocket("AF_INET6", "SOCK_DGRAM")
  2689. @unittest.skipUnless(thread, 'Threading required for this test.')
  2690. class RecvmsgIntoUDP6Test(RecvmsgIntoTests, SendrecvmsgUDP6TestBase):
  2691. pass
  2692. @requireAttrs(socket.socket, "recvmsg")
  2693. @unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 required for this test.')
  2694. @requireAttrs(socket, "IPPROTO_IPV6")
  2695. @requireSocket("AF_INET6", "SOCK_DGRAM")
  2696. @unittest.skipUnless(thread, 'Threading required for this test.')
  2697. class RecvmsgRFC3542AncillaryUDP6Test(RFC3542AncillaryTest,
  2698. SendrecvmsgUDP6TestBase):
  2699. pass
  2700. @requireAttrs(socket.socket, "recvmsg_into")
  2701. @unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 required for this test.')
  2702. @requireAttrs(socket, "IPPROTO_IPV6")
  2703. @requireSocket("AF_INET6", "SOCK_DGRAM")
  2704. @unittest.skipUnless(thread, 'Threading required for this test.')
  2705. class RecvmsgIntoRFC3542AncillaryUDP6Test(RecvmsgIntoMixin,
  2706. RFC3542AncillaryTest,
  2707. SendrecvmsgUDP6TestBase):
  2708. pass
  2709. class SendrecvmsgTCPTestBase(SendrecvmsgConnectedBase,
  2710. ConnectedStreamTestMixin, TCPTestBase):
  2711. pass
  2712. @requireAttrs(socket.socket, "sendmsg")
  2713. @unittest.skipUnless(thread, 'Threading required for this test.')
  2714. class SendmsgTCPTest(SendmsgStreamTests, SendrecvmsgTCPTestBase):
  2715. pass
  2716. @requireAttrs(socket.socket, "recvmsg")
  2717. @unittest.skipUnless(thread, 'Threading required for this test.')
  2718. class RecvmsgTCPTest(RecvmsgTests, RecvmsgGenericStreamTests,
  2719. SendrecvmsgTCPTestBase):
  2720. pass
  2721. @requireAttrs(socket.socket, "recvmsg_into")
  2722. @unittest.skipUnless(thread, 'Threading required for this test.')
  2723. class RecvmsgIntoTCPTest(RecvmsgIntoTests, RecvmsgGenericStreamTests,
  2724. SendrecvmsgTCPTestBase):
  2725. pass
  2726. class SendrecvmsgSCTPStreamTestBase(SendrecvmsgSCTPFlagsBase,
  2727. SendrecvmsgConnectedBase,
  2728. ConnectedStreamTestMixin, SCTPStreamBase):
  2729. pass
  2730. @requireAttrs(socket.socket, "sendmsg")
  2731. @requireSocket("AF_INET", "SOCK_STREAM", "IPPROTO_SCTP")
  2732. @unittest.skipUnless(thread, 'Threading required for this test.')
  2733. class SendmsgSCTPStreamTest(SendmsgStreamTests, SendrecvmsgSCTPStreamTestBase):
  2734. pass
  2735. @requireAttrs(socket.socket, "recvmsg")
  2736. @requireSocket("AF_INET", "SOCK_STREAM", "IPPROTO_SCTP")
  2737. @unittest.skipUnless(thread, 'Threading required for this test.')
  2738. class RecvmsgSCTPStreamTest(RecvmsgTests, RecvmsgGenericStreamTests,
  2739. SendrecvmsgSCTPStreamTestBase):
  2740. pass
  2741. @requireAttrs(socket.socket, "recvmsg_into")
  2742. @requireSocket("AF_INET", "SOCK_STREAM", "IPPROTO_SCTP")
  2743. @unittest.skipUnless(thread, 'Threading required for this test.')
  2744. class RecvmsgIntoSCTPStreamTest(RecvmsgIntoTests, RecvmsgGenericStreamTests,
  2745. SendrecvmsgSCTPStreamTestBase):
  2746. pass
  2747. class SendrecvmsgUnixStreamTestBase(SendrecvmsgConnectedBase,
  2748. ConnectedStreamTestMixin, UnixStreamBase):
  2749. pass
  2750. @requireAttrs(socket.socket, "sendmsg")
  2751. @requireAttrs(socket, "AF_UNIX")
  2752. @unittest.skipUnless(thread, 'Threading required for this test.')
  2753. class SendmsgUnixStreamTest(SendmsgStreamTests, SendrecvmsgUnixStreamTestBase):
  2754. pass
  2755. @requireAttrs(socket.socket, "recvmsg")
  2756. @requireAttrs(socket, "AF_UNIX")
  2757. @unittest.skipUnless(thread, 'Threading required for this test.')
  2758. class RecvmsgUnixStreamTest(RecvmsgTests, RecvmsgGenericStreamTests,
  2759. SendrecvmsgUnixStreamTestBase):
  2760. pass
  2761. @requireAttrs(socket.socket, "recvmsg_into")
  2762. @requireAttrs(socket, "AF_UNIX")
  2763. @unittest.skipUnless(thread, 'Threading required for this test.')
  2764. class RecvmsgIntoUnixStreamTest(RecvmsgIntoTests, RecvmsgGenericStreamTests,
  2765. SendrecvmsgUnixStreamTestBase):
  2766. pass
  2767. @requireAttrs(socket.socket, "sendmsg", "recvmsg")
  2768. @requireAttrs(socket, "AF_UNIX", "SOL_SOCKET", "SCM_RIGHTS")
  2769. @unittest.skipUnless(thread, 'Threading required for this test.')
  2770. class RecvmsgSCMRightsStreamTest(SCMRightsTest, SendrecvmsgUnixStreamTestBase):
  2771. pass
  2772. @requireAttrs(socket.socket, "sendmsg", "recvmsg_into")
  2773. @requireAttrs(socket, "AF_UNIX", "SOL_SOCKET", "SCM_RIGHTS")
  2774. @unittest.skipUnless(thread, 'Threading required for this test.')
  2775. class RecvmsgIntoSCMRightsStreamTest(RecvmsgIntoMixin, SCMRightsTest,
  2776. SendrecvmsgUnixStreamTestBase):
  2777. pass
  2778. # Test interrupting the interruptible send/receive methods with a
  2779. # signal when a timeout is set. These tests avoid having multiple
  2780. # threads alive during the test so that the OS cannot deliver the
  2781. # signal to the wrong one.
  2782. class InterruptedTimeoutBase(unittest.TestCase):
  2783. # Base class for interrupted send/receive tests. Installs an
  2784. # empty handler for SIGALRM and removes it on teardown, along with
  2785. # any scheduled alarms.
  2786. def setUp(self):
  2787. super().setUp()
  2788. orig_alrm_handler = signal.signal(signal.SIGALRM,
  2789. lambda signum, frame: None)
  2790. self.addCleanup(signal.signal, signal.SIGALRM, orig_alrm_handler)
  2791. self.addCleanup(self.setAlarm, 0)
  2792. # Timeout for socket operations
  2793. timeout = 4.0
  2794. # Provide setAlarm() method to schedule delivery of SIGALRM after
  2795. # given number of seconds, or cancel it if zero, and an
  2796. # appropriate time value to use. Use setitimer() if available.
  2797. if hasattr(signal, "setitimer"):
  2798. alarm_time = 0.05
  2799. def setAlarm(self, seconds):
  2800. signal.setitimer(signal.ITIMER_REAL, seconds)
  2801. else:
  2802. # Old systems may deliver the alarm up to one second early
  2803. alarm_time = 2
  2804. def setAlarm(self, seconds):
  2805. signal.alarm(seconds)
  2806. # Require siginterrupt() in order to ensure that system calls are
  2807. # interrupted by default.
  2808. @requireAttrs(signal, "siginterrupt")
  2809. @unittest.skipUnless(hasattr(signal, "alarm") or hasattr(signal, "setitimer"),
  2810. "Don't have signal.alarm or signal.setitimer")
  2811. class InterruptedRecvTimeoutTest(InterruptedTimeoutBase, UDPTestBase):
  2812. # Test interrupting the recv*() methods with signals when a
  2813. # timeout is set.
  2814. def setUp(self):
  2815. super().setUp()
  2816. self.serv.settimeout(self.timeout)
  2817. def checkInterruptedRecv(self, func, *args, **kwargs):
  2818. # Check that func(*args, **kwargs) raises socket.error with an
  2819. # errno of EINTR when interrupted by a signal.
  2820. self.setAlarm(self.alarm_time)
  2821. with self.assertRaises(socket.error) as cm:
  2822. func(*args, **kwargs)
  2823. self.assertNotIsInstance(cm.exception, socket.timeout)
  2824. self.assertEqual(cm.exception.errno, errno.EINTR)
  2825. def testInterruptedRecvTimeout(self):
  2826. self.checkInterruptedRecv(self.serv.recv, 1024)
  2827. def testInterruptedRecvIntoTimeout(self):
  2828. self.checkInterruptedRecv(self.serv.recv_into, bytearray(1024))
  2829. def testInterruptedRecvfromTimeout(self):
  2830. self.checkInterruptedRecv(self.serv.recvfrom, 1024)
  2831. def testInterruptedRecvfromIntoTimeout(self):
  2832. self.checkInterruptedRecv(self.serv.recvfrom_into, bytearray(1024))
  2833. @requireAttrs(socket.socket, "recvmsg")
  2834. def testInterruptedRecvmsgTimeout(self):
  2835. self.checkInterruptedRecv(self.serv.recvmsg, 1024)
  2836. @requireAttrs(socket.socket, "recvmsg_into")
  2837. def testInterruptedRecvmsgIntoTimeout(self):
  2838. self.checkInterruptedRecv(self.serv.recvmsg_into, [bytearray(1024)])
  2839. # Require siginterrupt() in order to ensure that system calls are
  2840. # interrupted by default.
  2841. @requireAttrs(signal, "siginterrupt")
  2842. @unittest.skipUnless(hasattr(signal, "alarm") or hasattr(signal, "setitimer"),
  2843. "Don't have signal.alarm or signal.setitimer")
  2844. @unittest.skipUnless(thread, 'Threading required for this test.')
  2845. class InterruptedSendTimeoutTest(InterruptedTimeoutBase,
  2846. ThreadSafeCleanupTestCase,
  2847. SocketListeningTestMixin, TCPTestBase):
  2848. # Test interrupting the interruptible send*() methods with signals
  2849. # when a timeout is set.
  2850. def setUp(self):
  2851. super().setUp()
  2852. self.serv_conn = self.newSocket()
  2853. self.addCleanup(self.serv_conn.close)
  2854. # Use a thread to complete the connection, but wait for it to
  2855. # terminate before running the test, so that there is only one
  2856. # thread to accept the signal.
  2857. cli_thread = threading.Thread(target=self.doConnect)
  2858. cli_thread.start()
  2859. self.cli_conn, addr = self.serv.accept()
  2860. self.addCleanup(self.cli_conn.close)
  2861. cli_thread.join()
  2862. self.serv_conn.settimeout(self.timeout)
  2863. def doConnect(self):
  2864. self.serv_conn.connect(self.serv_addr)
  2865. def checkInterruptedSend(self, func, *args, **kwargs):
  2866. # Check that func(*args, **kwargs), run in a loop, raises
  2867. # socket.error with an errno of EINTR when interrupted by a
  2868. # signal.
  2869. with self.assertRaises(socket.error) as cm:
  2870. while True:
  2871. self.setAlarm(self.alarm_time)
  2872. func(*args, **kwargs)
  2873. self.assertNotIsInstance(cm.exception, socket.timeout)
  2874. self.assertEqual(cm.exception.errno, errno.EINTR)
  2875. # Issue #12958: The following tests have problems on Mac OS X
  2876. @support.anticipate_failure(sys.platform == "darwin")
  2877. def testInterruptedSendTimeout(self):
  2878. self.checkInterruptedSend(self.serv_conn.send, b"a"*512)
  2879. @support.anticipate_failure(sys.platform == "darwin")
  2880. def testInterruptedSendtoTimeout(self):
  2881. # Passing an actual address here as Python's wrapper for
  2882. # sendto() doesn't allow passing a zero-length one; POSIX
  2883. # requires that the address is ignored since the socket is
  2884. # connection-mode, however.
  2885. self.checkInterruptedSend(self.serv_conn.sendto, b"a"*512,
  2886. self.serv_addr)
  2887. @support.anticipate_failure(sys.platform == "darwin")
  2888. @requireAttrs(socket.socket, "sendmsg")
  2889. def testInterruptedSendmsgTimeout(self):
  2890. self.checkInterruptedSend(self.serv_conn.sendmsg, [b"a"*512])
  2891. @unittest.skipUnless(thread, 'Threading required for this test.')
  2892. class TCPCloserTest(ThreadedTCPSocketTest):
  2893. def testClose(self):
  2894. conn, addr = self.serv.accept()
  2895. conn.close()
  2896. sd = self.cli
  2897. read, write, err = select.select([sd], [], [], 1.0)
  2898. self.assertEqual(read, [sd])
  2899. self.assertEqual(sd.recv(1), b'')
  2900. # Calling close() many times should be safe.
  2901. conn.close()
  2902. conn.close()
  2903. def _testClose(self):
  2904. self.cli.connect((HOST, self.port))
  2905. time.sleep(1.0)
  2906. @unittest.skipUnless(thread, 'Threading required for this test.')
  2907. class BasicSocketPairTest(SocketPairTest):
  2908. def __init__(self, methodName='runTest'):
  2909. SocketPairTest.__init__(self, methodName=methodName)
  2910. def _check_defaults(self, sock):
  2911. self.assertIsInstance(sock, socket.socket)
  2912. if hasattr(socket, 'AF_UNIX'):
  2913. self.assertEqual(sock.family, socket.AF_UNIX)
  2914. else:
  2915. self.assertEqual(sock.family, socket.AF_INET)
  2916. self.assertEqual(sock.type, socket.SOCK_STREAM)
  2917. self.assertEqual(sock.proto, 0)
  2918. def _testDefaults(self):
  2919. self._check_defaults(self.cli)
  2920. def testDefaults(self):
  2921. self._check_defaults(self.serv)
  2922. def testRecv(self):
  2923. msg = self.serv.recv(1024)
  2924. self.assertEqual(msg, MSG)
  2925. def _testRecv(self):
  2926. self.cli.send(MSG)
  2927. def testSend(self):
  2928. self.serv.send(MSG)
  2929. def _testSend(self):
  2930. msg = self.cli.recv(1024)
  2931. self.assertEqual(msg, MSG)
  2932. @unittest.skipUnless(thread, 'Threading required for this test.')
  2933. class NonBlockingTCPTests(ThreadedTCPSocketTest):
  2934. def __init__(self, methodName='runTest'):
  2935. ThreadedTCPSocketTest.__init__(self, methodName=methodName)
  2936. def testSetBlocking(self):
  2937. # Testing whether set blocking works
  2938. self.serv.setblocking(0)
  2939. start = time.time()
  2940. try:
  2941. self.serv.accept()
  2942. except socket.error:
  2943. pass
  2944. end = time.time()
  2945. self.assertTrue((end - start) < 1.0, "Error setting non-blocking mode.")
  2946. def _testSetBlocking(self):
  2947. pass
  2948. if hasattr(socket, "SOCK_NONBLOCK"):
  2949. @support.requires_linux_version(2, 6, 28)
  2950. def testInitNonBlocking(self):
  2951. # reinit server socket
  2952. self.serv.close()
  2953. self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM |
  2954. socket.SOCK_NONBLOCK)
  2955. self.port = support.bind_port(self.serv)
  2956. self.serv.listen(1)
  2957. # actual testing
  2958. start = time.time()
  2959. try:
  2960. self.serv.accept()
  2961. except socket.error:
  2962. pass
  2963. end = time.time()
  2964. self.assertTrue((end - start) < 1.0, "Error creating with non-blocking mode.")
  2965. def _testInitNonBlocking(self):
  2966. pass
  2967. def testInheritFlags(self):
  2968. # Issue #7995: when calling accept() on a listening socket with a
  2969. # timeout, the resulting socket should not be non-blocking.
  2970. self.serv.settimeout(10)
  2971. try:
  2972. conn, addr = self.serv.accept()
  2973. message = conn.recv(len(MSG))
  2974. finally:
  2975. conn.close()
  2976. self.serv.settimeout(None)
  2977. def _testInheritFlags(self):
  2978. time.sleep(0.1)
  2979. self.cli.connect((HOST, self.port))
  2980. time.sleep(0.5)
  2981. self.cli.send(MSG)
  2982. def testAccept(self):
  2983. # Testing non-blocking accept
  2984. self.serv.setblocking(0)
  2985. try:
  2986. conn, addr = self.serv.accept()
  2987. except socket.error:
  2988. pass
  2989. else:
  2990. self.fail("Error trying to do non-blocking accept.")
  2991. read, write, err = select.select([self.serv], [], [])
  2992. if self.serv in read:
  2993. conn, addr = self.serv.accept()
  2994. conn.close()
  2995. else:
  2996. self.fail("Error trying to do accept after select.")
  2997. def _testAccept(self):
  2998. time.sleep(0.1)
  2999. self.cli.connect((HOST, self.port))
  3000. def testConnect(self):
  3001. # Testing non-blocking connect
  3002. conn, addr = self.serv.accept()
  3003. conn.close()
  3004. def _testConnect(self):
  3005. self.cli.settimeout(10)
  3006. self.cli.connect((HOST, self.port))
  3007. def testRecv(self):
  3008. # Testing non-blocking recv
  3009. conn, addr = self.serv.accept()
  3010. conn.setblocking(0)
  3011. try:
  3012. msg = conn.recv(len(MSG))
  3013. except socket.error:
  3014. pass
  3015. else:
  3016. self.fail("Error trying to do non-blocking recv.")
  3017. read, write, err = select.select([conn], [], [])
  3018. if conn in read:
  3019. msg = conn.recv(len(MSG))
  3020. conn.close()
  3021. self.assertEqual(msg, MSG)
  3022. else:
  3023. self.fail("Error during select call to non-blocking socket.")
  3024. def _testRecv(self):
  3025. self.cli.connect((HOST, self.port))
  3026. time.sleep(0.1)
  3027. self.cli.send(MSG)
  3028. @unittest.skipUnless(thread, 'Threading required for this test.')
  3029. class FileObjectClassTestCase(SocketConnectedTest):
  3030. """Unit tests for the object returned by socket.makefile()
  3031. self.read_file is the io object returned by makefile() on
  3032. the client connection. You can read from this file to
  3033. get output from the server.
  3034. self.write_file is the io object returned by makefile() on the
  3035. server connection. You can write to this file to send output
  3036. to the client.
  3037. """
  3038. bufsize = -1 # Use default buffer size
  3039. encoding = 'utf-8'
  3040. errors = 'strict'
  3041. newline = None
  3042. read_mode = 'rb'
  3043. read_msg = MSG
  3044. write_mode = 'wb'
  3045. write_msg = MSG
  3046. def __init__(self, methodName='runTest'):
  3047. SocketConnectedTest.__init__(self, methodName=methodName)
  3048. def setUp(self):
  3049. self.evt1, self.evt2, self.serv_finished, self.cli_finished = [
  3050. threading.Event() for i in range(4)]
  3051. SocketConnectedTest.setUp(self)
  3052. self.read_file = self.cli_conn.makefile(
  3053. self.read_mode, self.bufsize,
  3054. encoding = self.encoding,
  3055. errors = self.errors,
  3056. newline = self.newline)
  3057. def tearDown(self):
  3058. self.serv_finished.set()
  3059. self.read_file.close()
  3060. self.assertTrue(self.read_file.closed)
  3061. self.read_file = None
  3062. SocketConnectedTest.tearDown(self)
  3063. def clientSetUp(self):
  3064. SocketConnectedTest.clientSetUp(self)
  3065. self.write_file = self.serv_conn.makefile(
  3066. self.write_mode, self.bufsize,
  3067. encoding = self.encoding,
  3068. errors = self.errors,
  3069. newline = self.newline)
  3070. def clientTearDown(self):
  3071. self.cli_finished.set()
  3072. self.write_file.close()
  3073. self.assertTrue(self.write_file.closed)
  3074. self.write_file = None
  3075. SocketConnectedTest.clientTearDown(self)
  3076. def testReadAfterTimeout(self):
  3077. # Issue #7322: A file object must disallow further reads
  3078. # after a timeout has occurred.
  3079. self.cli_conn.settimeout(1)
  3080. self.read_file.read(3)
  3081. # First read raises a timeout
  3082. self.assertRaises(socket.timeout, self.read_file.read, 1)
  3083. # Second read is disallowed
  3084. with self.assertRaises(IOError) as ctx:
  3085. self.read_file.read(1)
  3086. self.assertIn("cannot read from timed out object", str(ctx.exception))
  3087. def _testReadAfterTimeout(self):
  3088. self.write_file.write(self.write_msg[0:3])
  3089. self.write_file.flush()
  3090. self.serv_finished.wait()
  3091. def testSmallRead(self):
  3092. # Performing small file read test
  3093. first_seg = self.read_file.read(len(self.read_msg)-3)
  3094. second_seg = self.read_file.read(3)
  3095. msg = first_seg + second_seg
  3096. self.assertEqual(msg, self.read_msg)
  3097. def _testSmallRead(self):
  3098. self.write_file.write(self.write_msg)
  3099. self.write_file.flush()
  3100. def testFullRead(self):
  3101. # read until EOF
  3102. msg = self.read_file.read()
  3103. self.assertEqual(msg, self.read_msg)
  3104. def _testFullRead(self):
  3105. self.write_file.write(self.write_msg)
  3106. self.write_file.close()
  3107. def testUnbufferedRead(self):
  3108. # Performing unbuffered file read test
  3109. buf = type(self.read_msg)()
  3110. while 1:
  3111. char = self.read_file.read(1)
  3112. if not char:
  3113. break
  3114. buf += char
  3115. self.assertEqual(buf, self.read_msg)
  3116. def _testUnbufferedRead(self):
  3117. self.write_file.write(self.write_msg)
  3118. self.write_file.flush()
  3119. def testReadline(self):
  3120. # Performing file readline test
  3121. line = self.read_file.readline()
  3122. self.assertEqual(line, self.read_msg)
  3123. def _testReadline(self):
  3124. self.write_file.write(self.write_msg)
  3125. self.write_file.flush()
  3126. def testCloseAfterMakefile(self):
  3127. # The file returned by makefile should keep the socket open.
  3128. self.cli_conn.close()
  3129. # read until EOF
  3130. msg = self.read_file.read()
  3131. self.assertEqual(msg, self.read_msg)
  3132. def _testCloseAfterMakefile(self):
  3133. self.write_file.write(self.write_msg)
  3134. self.write_file.flush()
  3135. def testMakefileAfterMakefileClose(self):
  3136. self.read_file.close()
  3137. msg = self.cli_conn.recv(len(MSG))
  3138. if isinstance(self.read_msg, str):
  3139. msg = msg.decode()
  3140. self.assertEqual(msg, self.read_msg)
  3141. def _testMakefileAfterMakefileClose(self):
  3142. self.write_file.write(self.write_msg)
  3143. self.write_file.flush()
  3144. def testClosedAttr(self):
  3145. self.assertTrue(not self.read_file.closed)
  3146. def _testClosedAttr(self):
  3147. self.assertTrue(not self.write_file.closed)
  3148. def testAttributes(self):
  3149. self.assertEqual(self.read_file.mode, self.read_mode)
  3150. self.assertEqual(self.read_file.name, self.cli_conn.fileno())
  3151. def _testAttributes(self):
  3152. self.assertEqual(self.write_file.mode, self.write_mode)
  3153. self.assertEqual(self.write_file.name, self.serv_conn.fileno())
  3154. def testRealClose(self):
  3155. self.read_file.close()
  3156. self.assertRaises(ValueError, self.read_file.fileno)
  3157. self.cli_conn.close()
  3158. self.assertRaises(socket.error, self.cli_conn.getsockname)
  3159. def _testRealClose(self):
  3160. pass
  3161. class FileObjectInterruptedTestCase(unittest.TestCase):
  3162. """Test that the file object correctly handles EINTR internally."""
  3163. class MockSocket(object):
  3164. def __init__(self, recv_funcs=()):
  3165. # A generator that returns callables that we'll call for each
  3166. # call to recv().
  3167. self._recv_step = iter(recv_funcs)
  3168. def recv_into(self, buffer):
  3169. data = next(self._recv_step)()
  3170. assert len(buffer) >= len(data)
  3171. buffer[:len(data)] = data
  3172. return len(data)
  3173. def _decref_socketios(self):
  3174. pass
  3175. def _textiowrap_for_test(self, buffering=-1):
  3176. raw = socket.SocketIO(self, "r")
  3177. if buffering < 0:
  3178. buffering = io.DEFAULT_BUFFER_SIZE
  3179. if buffering == 0:
  3180. return raw
  3181. buffer = io.BufferedReader(raw, buffering)
  3182. text = io.TextIOWrapper(buffer, None, None)
  3183. text.mode = "rb"
  3184. return text
  3185. @staticmethod
  3186. def _raise_eintr():
  3187. raise socket.error(errno.EINTR, "interrupted")
  3188. def _textiowrap_mock_socket(self, mock, buffering=-1):
  3189. raw = socket.SocketIO(mock, "r")
  3190. if buffering < 0:
  3191. buffering = io.DEFAULT_BUFFER_SIZE
  3192. if buffering == 0:
  3193. return raw
  3194. buffer = io.BufferedReader(raw, buffering)
  3195. text = io.TextIOWrapper(buffer, None, None)
  3196. text.mode = "rb"
  3197. return text
  3198. def _test_readline(self, size=-1, buffering=-1):
  3199. mock_sock = self.MockSocket(recv_funcs=[
  3200. lambda : b"This is the first line\nAnd the sec",
  3201. self._raise_eintr,
  3202. lambda : b"ond line is here\n",
  3203. lambda : b"",
  3204. lambda : b"", # XXX(gps): io library does an extra EOF read
  3205. ])
  3206. fo = mock_sock._textiowrap_for_test(buffering=buffering)
  3207. self.assertEqual(fo.readline(size), "This is the first line\n")
  3208. self.assertEqual(fo.readline(size), "And the second line is here\n")
  3209. def _test_read(self, size=-1, buffering=-1):
  3210. mock_sock = self.MockSocket(recv_funcs=[
  3211. lambda : b"This is the first line\nAnd the sec",
  3212. self._raise_eintr,
  3213. lambda : b"ond line is here\n",
  3214. lambda : b"",
  3215. lambda : b"", # XXX(gps): io library does an extra EOF read
  3216. ])
  3217. expecting = (b"This is the first line\n"
  3218. b"And the second line is here\n")
  3219. fo = mock_sock._textiowrap_for_test(buffering=buffering)
  3220. if buffering == 0:
  3221. data = b''
  3222. else:
  3223. data = ''
  3224. expecting = expecting.decode('utf-8')
  3225. while len(data) != len(expecting):
  3226. part = fo.read(size)
  3227. if not part:
  3228. break
  3229. data += part
  3230. self.assertEqual(data, expecting)
  3231. def test_default(self):
  3232. self._test_readline()
  3233. self._test_readline(size=100)
  3234. self._test_read()
  3235. self._test_read(size=100)
  3236. def test_with_1k_buffer(self):
  3237. self._test_readline(buffering=1024)
  3238. self._test_readline(size=100, buffering=1024)
  3239. self._test_read(buffering=1024)
  3240. self._test_read(size=100, buffering=1024)
  3241. def _test_readline_no_buffer(self, size=-1):
  3242. mock_sock = self.MockSocket(recv_funcs=[
  3243. lambda : b"a",
  3244. lambda : b"\n",
  3245. lambda : b"B",
  3246. self._raise_eintr,
  3247. lambda : b"b",
  3248. lambda : b"",
  3249. ])
  3250. fo = mock_sock._textiowrap_for_test(buffering=0)
  3251. self.assertEqual(fo.readline(size), b"a\n")
  3252. self.assertEqual(fo.readline(size), b"Bb")
  3253. def test_no_buffer(self):
  3254. self._test_readline_no_buffer()
  3255. self._test_readline_no_buffer(size=4)
  3256. self._test_read(buffering=0)
  3257. self._test_read(size=100, buffering=0)
  3258. class UnbufferedFileObjectClassTestCase(FileObjectClassTestCase):
  3259. """Repeat the tests from FileObjectClassTestCase with bufsize==0.
  3260. In this case (and in this case only), it should be possible to
  3261. create a file object, read a line from it, create another file
  3262. object, read another line from it, without loss of data in the
  3263. first file object's buffer. Note that http.client relies on this
  3264. when reading multiple requests from the same socket."""
  3265. bufsize = 0 # Use unbuffered mode
  3266. def testUnbufferedReadline(self):
  3267. # Read a line, create a new file object, read another line with it
  3268. line = self.read_file.readline() # first line
  3269. self.assertEqual(line, b"A. " + self.write_msg) # first line
  3270. self.read_file = self.cli_conn.makefile('rb', 0)
  3271. line = self.read_file.readline() # second line
  3272. self.assertEqual(line, b"B. " + self.write_msg) # second line
  3273. def _testUnbufferedReadline(self):
  3274. self.write_file.write(b"A. " + self.write_msg)
  3275. self.write_file.write(b"B. " + self.write_msg)
  3276. self.write_file.flush()
  3277. def testMakefileClose(self):
  3278. # The file returned by makefile should keep the socket open...
  3279. self.cli_conn.close()
  3280. msg = self.cli_conn.recv(1024)
  3281. self.assertEqual(msg, self.read_msg)
  3282. # ...until the file is itself closed
  3283. self.read_file.close()
  3284. self.assertRaises(socket.error, self.cli_conn.recv, 1024)
  3285. def _testMakefileClose(self):
  3286. self.write_file.write(self.write_msg)
  3287. self.write_file.flush()
  3288. def testMakefileCloseSocketDestroy(self):
  3289. refcount_before = sys.getrefcount(self.cli_conn)
  3290. self.read_file.close()
  3291. refcount_after = sys.getrefcount(self.cli_conn)
  3292. self.assertEqual(refcount_before - 1, refcount_after)
  3293. def _testMakefileCloseSocketDestroy(self):
  3294. pass
  3295. # Non-blocking ops
  3296. # NOTE: to set `read_file` as non-blocking, we must call
  3297. # `cli_conn.setblocking` and vice-versa (see setUp / clientSetUp).
  3298. def testSmallReadNonBlocking(self):
  3299. self.cli_conn.setblocking(False)
  3300. self.assertEqual(self.read_file.readinto(bytearray(10)), None)
  3301. self.assertEqual(self.read_file.read(len(self.read_msg) - 3), None)
  3302. self.evt1.set()
  3303. self.evt2.wait(1.0)
  3304. first_seg = self.read_file.read(len(self.read_msg) - 3)
  3305. if first_seg is None:
  3306. # Data not arrived (can happen under Windows), wait a bit
  3307. time.sleep(0.5)
  3308. first_seg = self.read_file.read(len(self.read_msg) - 3)
  3309. buf = bytearray(10)
  3310. n = self.read_file.readinto(buf)
  3311. self.assertEqual(n, 3)
  3312. msg = first_seg + buf[:n]
  3313. self.assertEqual(msg, self.read_msg)
  3314. self.assertEqual(self.read_file.readinto(bytearray(16)), None)
  3315. self.assertEqual(self.read_file.read(1), None)
  3316. def _testSmallReadNonBlocking(self):
  3317. self.evt1.wait(1.0)
  3318. self.write_file.write(self.write_msg)
  3319. self.write_file.flush()
  3320. self.evt2.set()
  3321. # Avoid cloding the socket before the server test has finished,
  3322. # otherwise system recv() will return 0 instead of EWOULDBLOCK.
  3323. self.serv_finished.wait(5.0)
  3324. def testWriteNonBlocking(self):
  3325. self.cli_finished.wait(5.0)
  3326. # The client thread can't skip directly - the SkipTest exception
  3327. # would appear as a failure.
  3328. if self.serv_skipped:
  3329. self.skipTest(self.serv_skipped)
  3330. def _testWriteNonBlocking(self):
  3331. self.serv_skipped = None
  3332. self.serv_conn.setblocking(False)
  3333. # Try to saturate the socket buffer pipe with repeated large writes.
  3334. BIG = b"x" * (1024 ** 2)
  3335. LIMIT = 10
  3336. # The first write() succeeds since a chunk of data can be buffered
  3337. n = self.write_file.write(BIG)
  3338. self.assertGreater(n, 0)
  3339. for i in range(LIMIT):
  3340. n = self.write_file.write(BIG)
  3341. if n is None:
  3342. # Succeeded
  3343. break
  3344. self.assertGreater(n, 0)
  3345. else:
  3346. # Let us know that this test didn't manage to establish
  3347. # the expected conditions. This is not a failure in itself but,
  3348. # if it happens repeatedly, the test should be fixed.
  3349. self.serv_skipped = "failed to saturate the socket buffer"
  3350. class LineBufferedFileObjectClassTestCase(FileObjectClassTestCase):
  3351. bufsize = 1 # Default-buffered for reading; line-buffered for writing
  3352. class SmallBufferedFileObjectClassTestCase(FileObjectClassTestCase):
  3353. bufsize = 2 # Exercise the buffering code
  3354. class UnicodeReadFileObjectClassTestCase(FileObjectClassTestCase):
  3355. """Tests for socket.makefile() in text mode (rather than binary)"""
  3356. read_mode = 'r'
  3357. read_msg = MSG.decode('utf-8')
  3358. write_mode = 'wb'
  3359. write_msg = MSG
  3360. newline = ''
  3361. class UnicodeWriteFileObjectClassTestCase(FileObjectClassTestCase):
  3362. """Tests for socket.makefile() in text mode (rather than binary)"""
  3363. read_mode = 'rb'
  3364. read_msg = MSG
  3365. write_mode = 'w'
  3366. write_msg = MSG.decode('utf-8')
  3367. newline = ''
  3368. class UnicodeReadWriteFileObjectClassTestCase(FileObjectClassTestCase):
  3369. """Tests for socket.makefile() in text mode (rather than binary)"""
  3370. read_mode = 'r'
  3371. read_msg = MSG.decode('utf-8')
  3372. write_mode = 'w'
  3373. write_msg = MSG.decode('utf-8')
  3374. newline = ''
  3375. class NetworkConnectionTest(object):
  3376. """Prove network connection."""
  3377. def clientSetUp(self):
  3378. # We're inherited below by BasicTCPTest2, which also inherits
  3379. # BasicTCPTest, which defines self.port referenced below.
  3380. self.cli = socket.create_connection((HOST, self.port))
  3381. self.serv_conn = self.cli
  3382. class BasicTCPTest2(NetworkConnectionTest, BasicTCPTest):
  3383. """Tests that NetworkConnection does not break existing TCP functionality.
  3384. """
  3385. class NetworkConnectionNoServer(unittest.TestCase):
  3386. class MockSocket(socket.socket):
  3387. def connect(self, *args):
  3388. raise socket.timeout('timed out')
  3389. @contextlib.contextmanager
  3390. def mocked_socket_module(self):
  3391. """Return a socket which times out on connect"""
  3392. old_socket = socket.socket
  3393. socket.socket = self.MockSocket
  3394. try:
  3395. yield
  3396. finally:
  3397. socket.socket = old_socket
  3398. def test_connect(self):
  3399. port = support.find_unused_port()
  3400. cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  3401. self.addCleanup(cli.close)
  3402. with self.assertRaises(socket.error) as cm:
  3403. cli.connect((HOST, port))
  3404. self.assertEqual(cm.exception.errno, errno.ECONNREFUSED)
  3405. def test_create_connection(self):
  3406. # Issue #9792: errors raised by create_connection() should have
  3407. # a proper errno attribute.
  3408. port = support.find_unused_port()
  3409. with self.assertRaises(socket.error) as cm:
  3410. socket.create_connection((HOST, port))
  3411. self.assertEqual(cm.exception.errno, errno.ECONNREFUSED)
  3412. def test_create_connection_timeout(self):
  3413. # Issue #9792: create_connection() should not recast timeout errors
  3414. # as generic socket errors.
  3415. with self.mocked_socket_module():
  3416. with self.assertRaises(socket.timeout):
  3417. socket.create_connection((HOST, 1234))
  3418. @unittest.skipUnless(thread, 'Threading required for this test.')
  3419. class NetworkConnectionAttributesTest(SocketTCPTest, ThreadableTest):
  3420. def __init__(self, methodName='runTest'):
  3421. SocketTCPTest.__init__(self, methodName=methodName)
  3422. ThreadableTest.__init__(self)
  3423. def clientSetUp(self):
  3424. self.source_port = support.find_unused_port()
  3425. def clientTearDown(self):
  3426. self.cli.close()
  3427. self.cli = None
  3428. ThreadableTest.clientTearDown(self)
  3429. def _justAccept(self):
  3430. conn, addr = self.serv.accept()
  3431. conn.close()
  3432. testFamily = _justAccept
  3433. def _testFamily(self):
  3434. self.cli = socket.create_connection((HOST, self.port), timeout=30)
  3435. self.addCleanup(self.cli.close)
  3436. self.assertEqual(self.cli.family, 2)
  3437. testSourceAddress = _justAccept
  3438. def _testSourceAddress(self):
  3439. self.cli = socket.create_connection((HOST, self.port), timeout=30,
  3440. source_address=('', self.source_port))
  3441. self.addCleanup(self.cli.close)
  3442. self.assertEqual(self.cli.getsockname()[1], self.source_port)
  3443. # The port number being used is sufficient to show that the bind()
  3444. # call happened.
  3445. testTimeoutDefault = _justAccept
  3446. def _testTimeoutDefault(self):
  3447. # passing no explicit timeout uses socket's global default
  3448. self.assertTrue(socket.getdefaulttimeout() is None)
  3449. socket.setdefaulttimeout(42)
  3450. try:
  3451. self.cli = socket.create_connection((HOST, self.port))
  3452. self.addCleanup(self.cli.close)
  3453. finally:
  3454. socket.setdefaulttimeout(None)
  3455. self.assertEqual(self.cli.gettimeout(), 42)
  3456. testTimeoutNone = _justAccept
  3457. def _testTimeoutNone(self):
  3458. # None timeout means the same as sock.settimeout(None)
  3459. self.assertTrue(socket.getdefaulttimeout() is None)
  3460. socket.setdefaulttimeout(30)
  3461. try:
  3462. self.cli = socket.create_connection((HOST, self.port), timeout=None)
  3463. self.addCleanup(self.cli.close)
  3464. finally:
  3465. socket.setdefaulttimeout(None)
  3466. self.assertEqual(self.cli.gettimeout(), None)
  3467. testTimeoutValueNamed = _justAccept
  3468. def _testTimeoutValueNamed(self):
  3469. self.cli = socket.create_connection((HOST, self.port), timeout=30)
  3470. self.assertEqual(self.cli.gettimeout(), 30)
  3471. testTimeoutValueNonamed = _justAccept
  3472. def _testTimeoutValueNonamed(self):
  3473. self.cli = socket.create_connection((HOST, self.port), 30)
  3474. self.addCleanup(self.cli.close)
  3475. self.assertEqual(self.cli.gettimeout(), 30)
  3476. @unittest.skipUnless(thread, 'Threading required for this test.')
  3477. class NetworkConnectionBehaviourTest(SocketTCPTest, ThreadableTest):
  3478. def __init__(self, methodName='runTest'):
  3479. SocketTCPTest.__init__(self, methodName=methodName)
  3480. ThreadableTest.__init__(self)
  3481. def clientSetUp(self):
  3482. pass
  3483. def clientTearDown(self):
  3484. self.cli.close()
  3485. self.cli = None
  3486. ThreadableTest.clientTearDown(self)
  3487. def testInsideTimeout(self):
  3488. conn, addr = self.serv.accept()
  3489. self.addCleanup(conn.close)
  3490. time.sleep(3)
  3491. conn.send(b"done!")
  3492. testOutsideTimeout = testInsideTimeout
  3493. def _testInsideTimeout(self):
  3494. self.cli = sock = socket.create_connection((HOST, self.port))
  3495. data = sock.recv(5)
  3496. self.assertEqual(data, b"done!")
  3497. def _testOutsideTimeout(self):
  3498. self.cli = sock = socket.create_connection((HOST, self.port), timeout=1)
  3499. self.assertRaises(socket.timeout, lambda: sock.recv(5))
  3500. class TCPTimeoutTest(SocketTCPTest):
  3501. def testTCPTimeout(self):
  3502. def raise_timeout(*args, **kwargs):
  3503. self.serv.settimeout(1.0)
  3504. self.serv.accept()
  3505. self.assertRaises(socket.timeout, raise_timeout,
  3506. "Error generating a timeout exception (TCP)")
  3507. def testTimeoutZero(self):
  3508. ok = False
  3509. try:
  3510. self.serv.settimeout(0.0)
  3511. foo = self.serv.accept()
  3512. except socket.timeout:
  3513. self.fail("caught timeout instead of error (TCP)")
  3514. except socket.error:
  3515. ok = True
  3516. except:
  3517. self.fail("caught unexpected exception (TCP)")
  3518. if not ok:
  3519. self.fail("accept() returned success when we did not expect it")
  3520. def testInterruptedTimeout(self):
  3521. # XXX I don't know how to do this test on MSWindows or any other
  3522. # plaform that doesn't support signal.alarm() or os.kill(), though
  3523. # the bug should have existed on all platforms.
  3524. if not hasattr(signal, "alarm"):
  3525. return # can only test on *nix
  3526. self.serv.settimeout(5.0) # must be longer than alarm
  3527. class Alarm(Exception):
  3528. pass
  3529. def alarm_handler(signal, frame):
  3530. raise Alarm
  3531. old_alarm = signal.signal(signal.SIGALRM, alarm_handler)
  3532. try:
  3533. signal.alarm(2) # POSIX allows alarm to be up to 1 second early
  3534. try:
  3535. foo = self.serv.accept()
  3536. except socket.timeout:
  3537. self.fail("caught timeout instead of Alarm")
  3538. except Alarm:
  3539. pass
  3540. except:
  3541. self.fail("caught other exception instead of Alarm:"
  3542. " %s(%s):\n%s" %
  3543. (sys.exc_info()[:2] + (traceback.format_exc(),)))
  3544. else:
  3545. self.fail("nothing caught")
  3546. finally:
  3547. signal.alarm(0) # shut off alarm
  3548. except Alarm:
  3549. self.fail("got Alarm in wrong place")
  3550. finally:
  3551. # no alarm can be pending. Safe to restore old handler.
  3552. signal.signal(signal.SIGALRM, old_alarm)
  3553. class UDPTimeoutTest(SocketUDPTest):
  3554. def testUDPTimeout(self):
  3555. def raise_timeout(*args, **kwargs):
  3556. self.serv.settimeout(1.0)
  3557. self.serv.recv(1024)
  3558. self.assertRaises(socket.timeout, raise_timeout,
  3559. "Error generating a timeout exception (UDP)")
  3560. def testTimeoutZero(self):
  3561. ok = False
  3562. try:
  3563. self.serv.settimeout(0.0)
  3564. foo = self.serv.recv(1024)
  3565. except socket.timeout:
  3566. self.fail("caught timeout instead of error (UDP)")
  3567. except socket.error:
  3568. ok = True
  3569. except:
  3570. self.fail("caught unexpected exception (UDP)")
  3571. if not ok:
  3572. self.fail("recv() returned success when we did not expect it")
  3573. class TestExceptions(unittest.TestCase):
  3574. def testExceptionTree(self):
  3575. self.assertTrue(issubclass(socket.error, Exception))
  3576. self.assertTrue(issubclass(socket.herror, socket.error))
  3577. self.assertTrue(issubclass(socket.gaierror, socket.error))
  3578. self.assertTrue(issubclass(socket.timeout, socket.error))
  3579. class TestLinuxAbstractNamespace(unittest.TestCase):
  3580. UNIX_PATH_MAX = 108
  3581. def testLinuxAbstractNamespace(self):
  3582. address = b"\x00python-test-hello\x00\xff"
  3583. with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s1:
  3584. s1.bind(address)
  3585. s1.listen(1)
  3586. with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s2:
  3587. s2.connect(s1.getsockname())
  3588. with s1.accept()[0] as s3:
  3589. self.assertEqual(s1.getsockname(), address)
  3590. self.assertEqual(s2.getpeername(), address)
  3591. def testMaxName(self):
  3592. address = b"\x00" + b"h" * (self.UNIX_PATH_MAX - 1)
  3593. with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s:
  3594. s.bind(address)
  3595. self.assertEqual(s.getsockname(), address)
  3596. def testNameOverflow(self):
  3597. address = "\x00" + "h" * self.UNIX_PATH_MAX
  3598. with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s:
  3599. self.assertRaises(socket.error, s.bind, address)
  3600. def testStrName(self):
  3601. # Check that an abstract name can be passed as a string.
  3602. s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  3603. try:
  3604. s.bind("\x00python\x00test\x00")
  3605. self.assertEqual(s.getsockname(), b"\x00python\x00test\x00")
  3606. finally:
  3607. s.close()
  3608. class TestUnixDomain(unittest.TestCase):
  3609. def setUp(self):
  3610. self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  3611. def tearDown(self):
  3612. self.sock.close()
  3613. def encoded(self, path):
  3614. # Return the given path encoded in the file system encoding,
  3615. # or skip the test if this is not possible.
  3616. try:
  3617. return os.fsencode(path)
  3618. except UnicodeEncodeError:
  3619. self.skipTest(
  3620. "Pathname {0!a} cannot be represented in file "
  3621. "system encoding {1!r}".format(
  3622. path, sys.getfilesystemencoding()))
  3623. def bind(self, sock, path):
  3624. # Bind the socket
  3625. try:
  3626. sock.bind(path)
  3627. except OSError as e:
  3628. if str(e) == "AF_UNIX path too long":
  3629. self.skipTest(
  3630. "Pathname {0!a} is too long to serve as a AF_UNIX path"
  3631. .format(path))
  3632. else:
  3633. raise
  3634. def testStrAddr(self):
  3635. # Test binding to and retrieving a normal string pathname.
  3636. path = os.path.abspath(support.TESTFN)
  3637. self.bind(self.sock, path)
  3638. self.addCleanup(support.unlink, path)
  3639. self.assertEqual(self.sock.getsockname(), path)
  3640. def testBytesAddr(self):
  3641. # Test binding to a bytes pathname.
  3642. path = os.path.abspath(support.TESTFN)
  3643. self.bind(self.sock, self.encoded(path))
  3644. self.addCleanup(support.unlink, path)
  3645. self.assertEqual(self.sock.getsockname(), path)
  3646. def testSurrogateescapeBind(self):
  3647. # Test binding to a valid non-ASCII pathname, with the
  3648. # non-ASCII bytes supplied using surrogateescape encoding.
  3649. path = os.path.abspath(support.TESTFN_UNICODE)
  3650. b = self.encoded(path)
  3651. self.bind(self.sock, b.decode("ascii", "surrogateescape"))
  3652. self.addCleanup(support.unlink, path)
  3653. self.assertEqual(self.sock.getsockname(), path)
  3654. def testUnencodableAddr(self):
  3655. # Test binding to a pathname that cannot be encoded in the
  3656. # file system encoding.
  3657. if support.TESTFN_UNENCODABLE is None:
  3658. self.skipTest("No unencodable filename available")
  3659. path = os.path.abspath(support.TESTFN_UNENCODABLE)
  3660. self.bind(self.sock, path)
  3661. self.addCleanup(support.unlink, path)
  3662. self.assertEqual(self.sock.getsockname(), path)
  3663. @unittest.skipUnless(thread, 'Threading required for this test.')
  3664. class BufferIOTest(SocketConnectedTest):
  3665. """
  3666. Test the buffer versions of socket.recv() and socket.send().
  3667. """
  3668. def __init__(self, methodName='runTest'):
  3669. SocketConnectedTest.__init__(self, methodName=methodName)
  3670. def testRecvIntoArray(self):
  3671. buf = bytearray(1024)
  3672. nbytes = self.cli_conn.recv_into(buf)
  3673. self.assertEqual(nbytes, len(MSG))
  3674. msg = buf[:len(MSG)]
  3675. self.assertEqual(msg, MSG)
  3676. def _testRecvIntoArray(self):
  3677. buf = bytes(MSG)
  3678. self.serv_conn.send(buf)
  3679. def testRecvIntoBytearray(self):
  3680. buf = bytearray(1024)
  3681. nbytes = self.cli_conn.recv_into(buf)
  3682. self.assertEqual(nbytes, len(MSG))
  3683. msg = buf[:len(MSG)]
  3684. self.assertEqual(msg, MSG)
  3685. _testRecvIntoBytearray = _testRecvIntoArray
  3686. def testRecvIntoMemoryview(self):
  3687. buf = bytearray(1024)
  3688. nbytes = self.cli_conn.recv_into(memoryview(buf))
  3689. self.assertEqual(nbytes, len(MSG))
  3690. msg = buf[:len(MSG)]
  3691. self.assertEqual(msg, MSG)
  3692. _testRecvIntoMemoryview = _testRecvIntoArray
  3693. def testRecvFromIntoArray(self):
  3694. buf = bytearray(1024)
  3695. nbytes, addr = self.cli_conn.recvfrom_into(buf)
  3696. self.assertEqual(nbytes, len(MSG))
  3697. msg = buf[:len(MSG)]
  3698. self.assertEqual(msg, MSG)
  3699. def _testRecvFromIntoArray(self):
  3700. buf = bytes(MSG)
  3701. self.serv_conn.send(buf)
  3702. def testRecvFromIntoBytearray(self):
  3703. buf = bytearray(1024)
  3704. nbytes, addr = self.cli_conn.recvfrom_into(buf)
  3705. self.assertEqual(nbytes, len(MSG))
  3706. msg = buf[:len(MSG)]
  3707. self.assertEqual(msg, MSG)
  3708. _testRecvFromIntoBytearray = _testRecvFromIntoArray
  3709. def testRecvFromIntoMemoryview(self):
  3710. buf = bytearray(1024)
  3711. nbytes, addr = self.cli_conn.recvfrom_into(memoryview(buf))
  3712. self.assertEqual(nbytes, len(MSG))
  3713. msg = buf[:len(MSG)]
  3714. self.assertEqual(msg, MSG)
  3715. _testRecvFromIntoMemoryview = _testRecvFromIntoArray
  3716. TIPC_STYPE = 2000
  3717. TIPC_LOWER = 200
  3718. TIPC_UPPER = 210
  3719. def isTipcAvailable():
  3720. """Check if the TIPC module is loaded
  3721. The TIPC module is not loaded automatically on Ubuntu and probably
  3722. other Linux distros.
  3723. """
  3724. if not hasattr(socket, "AF_TIPC"):
  3725. return False
  3726. if not os.path.isfile("/proc/modules"):
  3727. return False
  3728. with open("/proc/modules") as f:
  3729. for line in f:
  3730. if line.startswith("tipc "):
  3731. return True
  3732. if support.verbose:
  3733. print("TIPC module is not loaded, please 'sudo modprobe tipc'")
  3734. return False
  3735. class TIPCTest(unittest.TestCase):
  3736. def testRDM(self):
  3737. srv = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
  3738. cli = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
  3739. self.addCleanup(srv.close)
  3740. self.addCleanup(cli.close)
  3741. srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  3742. srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
  3743. TIPC_LOWER, TIPC_UPPER)
  3744. srv.bind(srvaddr)
  3745. sendaddr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
  3746. TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
  3747. cli.sendto(MSG, sendaddr)
  3748. msg, recvaddr = srv.recvfrom(1024)
  3749. self.assertEqual(cli.getsockname(), recvaddr)
  3750. self.assertEqual(msg, MSG)
  3751. class TIPCThreadableTest(unittest.TestCase, ThreadableTest):
  3752. def __init__(self, methodName = 'runTest'):
  3753. unittest.TestCase.__init__(self, methodName = methodName)
  3754. ThreadableTest.__init__(self)
  3755. def setUp(self):
  3756. self.srv = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
  3757. self.addCleanup(self.srv.close)
  3758. self.srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  3759. srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
  3760. TIPC_LOWER, TIPC_UPPER)
  3761. self.srv.bind(srvaddr)
  3762. self.srv.listen(5)
  3763. self.serverExplicitReady()
  3764. self.conn, self.connaddr = self.srv.accept()
  3765. self.addCleanup(self.conn.close)
  3766. def clientSetUp(self):
  3767. # The is a hittable race between serverExplicitReady() and the
  3768. # accept() call; sleep a little while to avoid it, otherwise
  3769. # we could get an exception
  3770. time.sleep(0.1)
  3771. self.cli = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
  3772. self.addCleanup(self.cli.close)
  3773. addr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
  3774. TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
  3775. self.cli.connect(addr)
  3776. self.cliaddr = self.cli.getsockname()
  3777. def testStream(self):
  3778. msg = self.conn.recv(1024)
  3779. self.assertEqual(msg, MSG)
  3780. self.assertEqual(self.cliaddr, self.connaddr)
  3781. def _testStream(self):
  3782. self.cli.send(MSG)
  3783. self.cli.close()
  3784. @unittest.skipUnless(thread, 'Threading required for this test.')
  3785. class ContextManagersTest(ThreadedTCPSocketTest):
  3786. def _testSocketClass(self):
  3787. # base test
  3788. with socket.socket() as sock:
  3789. self.assertFalse(sock._closed)
  3790. self.assertTrue(sock._closed)
  3791. # close inside with block
  3792. with socket.socket() as sock:
  3793. sock.close()
  3794. self.assertTrue(sock._closed)
  3795. # exception inside with block
  3796. with socket.socket() as sock:
  3797. self.assertRaises(socket.error, sock.sendall, b'foo')
  3798. self.assertTrue(sock._closed)
  3799. def testCreateConnectionBase(self):
  3800. conn, addr = self.serv.accept()
  3801. self.addCleanup(conn.close)
  3802. data = conn.recv(1024)
  3803. conn.sendall(data)
  3804. def _testCreateConnectionBase(self):
  3805. address = self.serv.getsockname()
  3806. with socket.create_connection(address) as sock:
  3807. self.assertFalse(sock._closed)
  3808. sock.sendall(b'foo')
  3809. self.assertEqual(sock.recv(1024), b'foo')
  3810. self.assertTrue(sock._closed)
  3811. def testCreateConnectionClose(self):
  3812. conn, addr = self.serv.accept()
  3813. self.addCleanup(conn.close)
  3814. data = conn.recv(1024)
  3815. conn.sendall(data)
  3816. def _testCreateConnectionClose(self):
  3817. address = self.serv.getsockname()
  3818. with socket.create_connection(address) as sock:
  3819. sock.close()
  3820. self.assertTrue(sock._closed)
  3821. self.assertRaises(socket.error, sock.sendall, b'foo')
  3822. @unittest.skipUnless(hasattr(socket, "SOCK_CLOEXEC"),
  3823. "SOCK_CLOEXEC not defined")
  3824. @unittest.skipUnless(fcntl, "module fcntl not available")
  3825. class CloexecConstantTest(unittest.TestCase):
  3826. @support.requires_linux_version(2, 6, 28)
  3827. def test_SOCK_CLOEXEC(self):
  3828. with socket.socket(socket.AF_INET,
  3829. socket.SOCK_STREAM | socket.SOCK_CLOEXEC) as s:
  3830. self.assertTrue(s.type & socket.SOCK_CLOEXEC)
  3831. self.assertTrue(fcntl.fcntl(s, fcntl.F_GETFD) & fcntl.FD_CLOEXEC)
  3832. @unittest.skipUnless(hasattr(socket, "SOCK_NONBLOCK"),
  3833. "SOCK_NONBLOCK not defined")
  3834. class NonblockConstantTest(unittest.TestCase):
  3835. def checkNonblock(self, s, nonblock=True, timeout=0.0):
  3836. if nonblock:
  3837. self.assertTrue(s.type & socket.SOCK_NONBLOCK)
  3838. self.assertEqual(s.gettimeout(), timeout)
  3839. else:
  3840. self.assertFalse(s.type & socket.SOCK_NONBLOCK)
  3841. self.assertEqual(s.gettimeout(), None)
  3842. @support.requires_linux_version(2, 6, 28)
  3843. def test_SOCK_NONBLOCK(self):
  3844. # a lot of it seems silly and redundant, but I wanted to test that
  3845. # changing back and forth worked ok
  3846. with socket.socket(socket.AF_INET,
  3847. socket.SOCK_STREAM | socket.SOCK_NONBLOCK) as s:
  3848. self.checkNonblock(s)
  3849. s.setblocking(1)
  3850. self.checkNonblock(s, False)
  3851. s.setblocking(0)
  3852. self.checkNonblock(s)
  3853. s.settimeout(None)
  3854. self.checkNonblock(s, False)
  3855. s.settimeout(2.0)
  3856. self.checkNonblock(s, timeout=2.0)
  3857. s.setblocking(1)
  3858. self.checkNonblock(s, False)
  3859. # defaulttimeout
  3860. t = socket.getdefaulttimeout()
  3861. socket.setdefaulttimeout(0.0)
  3862. with socket.socket() as s:
  3863. self.checkNonblock(s)
  3864. socket.setdefaulttimeout(None)
  3865. with socket.socket() as s:
  3866. self.checkNonblock(s, False)
  3867. socket.setdefaulttimeout(2.0)
  3868. with socket.socket() as s:
  3869. self.checkNonblock(s, timeout=2.0)
  3870. socket.setdefaulttimeout(None)
  3871. with socket.socket() as s:
  3872. self.checkNonblock(s, False)
  3873. socket.setdefaulttimeout(t)
  3874. @unittest.skipUnless(os.name == "nt", "Windows specific")
  3875. @unittest.skipUnless(multiprocessing, "need multiprocessing")
  3876. class TestSocketSharing(SocketTCPTest):
  3877. # This must be classmethod and not staticmethod or multiprocessing
  3878. # won't be able to bootstrap it.
  3879. @classmethod
  3880. def remoteProcessServer(cls, q):
  3881. # Recreate socket from shared data
  3882. sdata = q.get()
  3883. message = q.get()
  3884. s = socket.fromshare(sdata)
  3885. s2, c = s.accept()
  3886. # Send the message
  3887. s2.sendall(message)
  3888. s2.close()
  3889. s.close()
  3890. def testShare(self):
  3891. # Transfer the listening server socket to another process
  3892. # and service it from there.
  3893. # Create process:
  3894. q = multiprocessing.Queue()
  3895. p = multiprocessing.Process(target=self.remoteProcessServer, args=(q,))
  3896. p.start()
  3897. # Get the shared socket data
  3898. data = self.serv.share(p.pid)
  3899. # Pass the shared socket to the other process
  3900. addr = self.serv.getsockname()
  3901. self.serv.close()
  3902. q.put(data)
  3903. # The data that the server will send us
  3904. message = b"slapmahfro"
  3905. q.put(message)
  3906. # Connect
  3907. s = socket.create_connection(addr)
  3908. # listen for the data
  3909. m = []
  3910. while True:
  3911. data = s.recv(100)
  3912. if not data:
  3913. break
  3914. m.append(data)
  3915. s.close()
  3916. received = b"".join(m)
  3917. self.assertEqual(received, message)
  3918. p.join()
  3919. def testShareLength(self):
  3920. data = self.serv.share(os.getpid())
  3921. self.assertRaises(ValueError, socket.fromshare, data[:-1])
  3922. self.assertRaises(ValueError, socket.fromshare, data+b"foo")
  3923. def compareSockets(self, org, other):
  3924. # socket sharing is expected to work only for blocking socket
  3925. # since the internal python timout value isn't transfered.
  3926. self.assertEqual(org.gettimeout(), None)
  3927. self.assertEqual(org.gettimeout(), other.gettimeout())
  3928. self.assertEqual(org.family, other.family)
  3929. self.assertEqual(org.type, other.type)
  3930. # If the user specified "0" for proto, then
  3931. # internally windows will have picked the correct value.
  3932. # Python introspection on the socket however will still return
  3933. # 0. For the shared socket, the python value is recreated
  3934. # from the actual value, so it may not compare correctly.
  3935. if org.proto != 0:
  3936. self.assertEqual(org.proto, other.proto)
  3937. def testShareLocal(self):
  3938. data = self.serv.share(os.getpid())
  3939. s = socket.fromshare(data)
  3940. try:
  3941. self.compareSockets(self.serv, s)
  3942. finally:
  3943. s.close()
  3944. def testTypes(self):
  3945. families = [socket.AF_INET, socket.AF_INET6]
  3946. types = [socket.SOCK_STREAM, socket.SOCK_DGRAM]
  3947. for f in families:
  3948. for t in types:
  3949. try:
  3950. source = socket.socket(f, t)
  3951. except OSError:
  3952. continue # This combination is not supported
  3953. try:
  3954. data = source.share(os.getpid())
  3955. shared = socket.fromshare(data)
  3956. try:
  3957. self.compareSockets(source, shared)
  3958. finally:
  3959. shared.close()
  3960. finally:
  3961. source.close()
  3962. def test_main():
  3963. tests = [GeneralModuleTests, BasicTCPTest, TCPCloserTest, TCPTimeoutTest,
  3964. TestExceptions, BufferIOTest, BasicTCPTest2, BasicUDPTest, UDPTimeoutTest ]
  3965. tests.extend([
  3966. NonBlockingTCPTests,
  3967. FileObjectClassTestCase,
  3968. FileObjectInterruptedTestCase,
  3969. UnbufferedFileObjectClassTestCase,
  3970. LineBufferedFileObjectClassTestCase,
  3971. SmallBufferedFileObjectClassTestCase,
  3972. UnicodeReadFileObjectClassTestCase,
  3973. UnicodeWriteFileObjectClassTestCase,
  3974. UnicodeReadWriteFileObjectClassTestCase,
  3975. NetworkConnectionNoServer,
  3976. NetworkConnectionAttributesTest,
  3977. NetworkConnectionBehaviourTest,
  3978. ContextManagersTest,
  3979. CloexecConstantTest,
  3980. NonblockConstantTest
  3981. ])
  3982. if hasattr(socket, "socketpair"):
  3983. tests.append(BasicSocketPairTest)
  3984. if hasattr(socket, "AF_UNIX"):
  3985. tests.append(TestUnixDomain)
  3986. if sys.platform == 'linux':
  3987. tests.append(TestLinuxAbstractNamespace)
  3988. if isTipcAvailable():
  3989. tests.append(TIPCTest)
  3990. tests.append(TIPCThreadableTest)
  3991. tests.extend([BasicCANTest, CANTest])
  3992. tests.extend([BasicRDSTest, RDSTest])
  3993. tests.extend([
  3994. CmsgMacroTests,
  3995. SendmsgUDPTest,
  3996. RecvmsgUDPTest,
  3997. RecvmsgIntoUDPTest,
  3998. SendmsgUDP6Test,
  3999. RecvmsgUDP6Test,
  4000. RecvmsgRFC3542AncillaryUDP6Test,
  4001. RecvmsgIntoRFC3542AncillaryUDP6Test,
  4002. RecvmsgIntoUDP6Test,
  4003. SendmsgTCPTest,
  4004. RecvmsgTCPTest,
  4005. RecvmsgIntoTCPTest,
  4006. SendmsgSCTPStreamTest,
  4007. RecvmsgSCTPStreamTest,
  4008. RecvmsgIntoSCTPStreamTest,
  4009. SendmsgUnixStreamTest,
  4010. RecvmsgUnixStreamTest,
  4011. RecvmsgIntoUnixStreamTest,
  4012. RecvmsgSCMRightsStreamTest,
  4013. RecvmsgIntoSCMRightsStreamTest,
  4014. # These are slow when setitimer() is not available
  4015. InterruptedRecvTimeoutTest,
  4016. InterruptedSendTimeoutTest,
  4017. TestSocketSharing,
  4018. ])
  4019. thread_info = support.threading_setup()
  4020. support.run_unittest(*tests)
  4021. support.threading_cleanup(*thread_info)
  4022. if __name__ == "__main__":
  4023. test_main()