PageRenderTime 98ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/Lib/test/test_socket.py

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