PageRenderTime 73ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/Lib/test/test_socket.py

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