Debian Codegraph @

Lib/test/test_socket.py

raw
1 import unittest
2 from unittest import mock
3 from test import support
4 from test.support import (
5 cpython_only, is_apple, os_helper, refleak_helper, socket_helper, threading_helper
6 )
7 from test.support.import_helper import ensure_lazy_imports
8 import _thread as thread
9 import array
10 import contextlib
11 import errno
12 import gc
13 import io
14 import itertools
15 import math
16 import os
17 import pickle
18 import platform
19 import queue
20 import random
21 import re
22 import select
23 import signal
24 import socket
25 import string
26 import struct
27 import sys
28 import tempfile
29 import threading
30 import time
31 import traceback
32 import warnings
33 from weakref import proxy
34 try:
35 import multiprocessing
36 except ImportError:
37 multiprocessing = False
38 try:
39 import fcntl
40 except ImportError:
41 fcntl = None
42 try:
43 import _testcapi
44 except ImportError:
45 _testcapi = None
46
47 support.requires_working_socket(module=True)
48
49 HOST = socket_helper.HOST
50 # test unicode string and carriage return
51 MSG = 'Michael Gilfix was here\u1234\r\n'.encode('utf-8')
52
53 VSOCKPORT = 1234
54 AIX = platform.system() == "AIX"
55 SOLARIS = sys.platform.startswith("sunos")
56 WSL = "microsoft-standard-WSL" in platform.release()
57
58 try:
59 import _socket
60 except ImportError:
61 _socket = None
62
63 def skipForRefleakHuntinIf(condition, issueref):
64 if not condition:
65 def decorator(f):
66 f.client_skip = lambda f: f
67 return f
68
69 else:
70 def decorator(f):
71 @contextlib.wraps(f)
72 def wrapper(*args, **kwds):
73 if refleak_helper.hunting_for_refleaks():
74 raise unittest.SkipTest(f"ignore while hunting for refleaks, see {issueref}")
75
76 return f(*args, **kwds)
77
78 def client_skip(f):
79 @contextlib.wraps(f)
80 def wrapper(*args, **kwds):
81 if refleak_helper.hunting_for_refleaks():
82 return
83
84 return f(*args, **kwds)
85
86 return wrapper
87 wrapper.client_skip = client_skip
88 return wrapper
89
90 return decorator
91
92 def get_cid():
93 if fcntl is None:
94 return None
95 if not hasattr(socket, 'IOCTL_VM_SOCKETS_GET_LOCAL_CID'):
96 return None
97 try:
98 with open("/dev/vsock", "rb") as f:
99 r = fcntl.ioctl(f, socket.IOCTL_VM_SOCKETS_GET_LOCAL_CID, " ")
100 except OSError:
101 return None
102 else:
103 return struct.unpack("I", r)[0]
104
105 def _have_socket_can():
106 """Check whether CAN sockets are supported on this host."""
107 try:
108 s = socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
109 except (AttributeError, OSError):
110 return False
111 else:
112 s.close()
113 return True
114
115 def _have_socket_can_isotp():
116 """Check whether CAN ISOTP sockets are supported on this host."""
117 try:
118 s = socket.socket(socket.PF_CAN, socket.SOCK_DGRAM, socket.CAN_ISOTP)
119 except (AttributeError, OSError):
120 return False
121 else:
122 s.close()
123 return True
124
125 def _have_socket_can_j1939():
126 """Check whether CAN J1939 sockets are supported on this host."""
127 try:
128 s = socket.socket(socket.PF_CAN, socket.SOCK_DGRAM, socket.CAN_J1939)
129 except (AttributeError, OSError):
130 return False
131 else:
132 s.close()
133 return True
134
135 def _have_socket_rds():
136 """Check whether RDS sockets are supported on this host."""
137 try:
138 s = socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0)
139 except (AttributeError, OSError):
140 return False
141 else:
142 s.close()
143 return True
144
145 def _have_socket_alg():
146 """Check whether AF_ALG sockets are supported on this host."""
147 try:
148 s = socket.socket(socket.AF_ALG, socket.SOCK_SEQPACKET, 0)
149 except (AttributeError, OSError):
150 return False
151 else:
152 s.close()
153 return True
154
155 def _have_socket_qipcrtr():
156 """Check whether AF_QIPCRTR sockets are supported on this host."""
157 try:
158 s = socket.socket(socket.AF_QIPCRTR, socket.SOCK_DGRAM, 0)
159 except (AttributeError, OSError):
160 return False
161 else:
162 s.close()
163 return True
164
165 def _have_socket_vsock():
166 """Check whether AF_VSOCK sockets are supported on this host."""
167 cid = get_cid()
168 return (cid is not None)
169
170
171 def _have_socket_bluetooth():
172 """Check whether AF_BLUETOOTH sockets are supported on this host."""
173 try:
174 # RFCOMM is supported by all platforms with bluetooth support. Windows
175 # does not support omitting the protocol.
176 s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM)
177 except (AttributeError, OSError):
178 return False
179 else:
180 s.close()
181 return True
182
183
184 def _have_socket_bluetooth_l2cap():
185 """Check whether BTPROTO_L2CAP sockets are supported on this host."""
186 try:
187 s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_SEQPACKET, socket.BTPROTO_L2CAP)
188 except (AttributeError, OSError):
189 return False
190 else:
191 s.close()
192 return True
193
194
195 def _have_socket_hyperv():
196 """Check whether AF_HYPERV sockets are supported on this host."""
197 try:
198 s = socket.socket(socket.AF_HYPERV, socket.SOCK_STREAM, socket.HV_PROTOCOL_RAW)
199 except (AttributeError, OSError):
200 return False
201 else:
202 s.close()
203 return True
204
205
206 @contextlib.contextmanager
207 def socket_setdefaulttimeout(timeout):
208 old_timeout = socket.getdefaulttimeout()
209 try:
210 socket.setdefaulttimeout(timeout)
211 yield
212 finally:
213 socket.setdefaulttimeout(old_timeout)
214
215
216 @contextlib.contextmanager
217 def downgrade_malformed_data_warning():
218 # This warning happens on macos and win, but does not always happen on linux.
219 if sys.platform not in {"win32", "darwin"}:
220 yield
221 return
222
223 with warnings.catch_warnings():
224 # TODO: gh-110012, we should investigate why this warning is happening
225 # and fix it properly.
226 warnings.filterwarnings(
227 action="always",
228 message="received malformed or improperly-truncated ancillary data",
229 category=RuntimeWarning,
230 )
231 yield
232
233
234 HAVE_SOCKET_CAN = _have_socket_can()
235
236 HAVE_SOCKET_CAN_ISOTP = _have_socket_can_isotp()
237
238 HAVE_SOCKET_CAN_J1939 = _have_socket_can_j1939()
239
240 HAVE_SOCKET_RDS = _have_socket_rds()
241
242 HAVE_SOCKET_ALG = _have_socket_alg()
243
244 HAVE_SOCKET_QIPCRTR = _have_socket_qipcrtr()
245
246 HAVE_SOCKET_VSOCK = _have_socket_vsock()
247
248 # Older Android versions block UDPLITE with SELinux.
249 HAVE_SOCKET_UDPLITE = (
250 hasattr(socket, "IPPROTO_UDPLITE")
251 and not (support.is_android and platform.android_ver().api_level < 29))
252
253 HAVE_SOCKET_BLUETOOTH = _have_socket_bluetooth()
254
255 HAVE_SOCKET_BLUETOOTH_L2CAP = _have_socket_bluetooth_l2cap()
256
257 HAVE_SOCKET_HYPERV = _have_socket_hyperv()
258
259 # Size in bytes of the int type
260 SIZEOF_INT = array.array("i").itemsize
261
262 class TestLazyImport(unittest.TestCase):
263 @cpython_only
264 def test_lazy_import(self):
265 ensure_lazy_imports("socket", {"array", "selectors"})
266
267
268 class SocketTCPTest(unittest.TestCase):
269
270 def setUp(self):
271 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
272 self.port = socket_helper.bind_port(self.serv)
273 self.serv.listen()
274
275 def tearDown(self):
276 self.serv.close()
277 self.serv = None
278
279 class SocketUDPTest(unittest.TestCase):
280
281 def setUp(self):
282 self.serv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
283 self.port = socket_helper.bind_port(self.serv)
284
285 def tearDown(self):
286 self.serv.close()
287 self.serv = None
288
289 class SocketUDPLITETest(SocketUDPTest):
290
291 def setUp(self):
292 self.serv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDPLITE)
293 self.port = socket_helper.bind_port(self.serv)
294
295
296 class SocketCANTest(unittest.TestCase):
297
298 """To be able to run this test, a `vcan0` CAN interface can be created with
299 the following commands:
300 # modprobe vcan
301 # ip link add dev vcan0 type vcan
302 # ip link set up vcan0
303 """
304 interface = 'vcan0'
305 bufsize = 128
306
307 """The CAN frame structure is defined in <linux/can.h>:
308
309 struct can_frame {
310 canid_t can_id; /* 32 bit CAN_ID + EFF/RTR/ERR flags */
311 __u8 can_dlc; /* data length code: 0 .. 8 */
312 __u8 data[8] __attribute__((aligned(8)));
313 };
314 """
315 can_frame_fmt = "=IB3x8s"
316 can_frame_size = struct.calcsize(can_frame_fmt)
317
318 """The Broadcast Management Command frame structure is defined
319 in <linux/can/bcm.h>:
320
321 struct bcm_msg_head {
322 __u32 opcode;
323 __u32 flags;
324 __u32 count;
325 struct timeval ival1, ival2;
326 canid_t can_id;
327 __u32 nframes;
328 struct can_frame frames[0];
329 }
330
331 `bcm_msg_head` must be 8 bytes aligned because of the `frames` member (see
332 `struct can_frame` definition). Must use native not standard types for packing.
333 """
334 bcm_cmd_msg_fmt = "@3I4l2I"
335 bcm_cmd_msg_fmt += "x" * (struct.calcsize(bcm_cmd_msg_fmt) % 8)
336
337 def setUp(self):
338 self.s = socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
339 self.addCleanup(self.s.close)
340 try:
341 self.s.bind((self.interface,))
342 except OSError:
343 self.skipTest('network interface `%s` does not exist' %
344 self.interface)
345
346
347 class SocketRDSTest(unittest.TestCase):
348
349 """To be able to run this test, the `rds` kernel module must be loaded:
350 # modprobe rds
351 """
352 bufsize = 8192
353
354 def setUp(self):
355 self.serv = socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0)
356 self.addCleanup(self.serv.close)
357 try:
358 self.port = socket_helper.bind_port(self.serv)
359 except OSError:
360 self.skipTest('unable to bind RDS socket')
361
362
363 class ThreadableTest:
364 """Threadable Test class
365
366 The ThreadableTest class makes it easy to create a threaded
367 client/server pair from an existing unit test. To create a
368 new threaded class from an existing unit test, use multiple
369 inheritance:
370
371 class NewClass (OldClass, ThreadableTest):
372 pass
373
374 This class defines two new fixture functions with obvious
375 purposes for overriding:
376
377 clientSetUp ()
378 clientTearDown ()
379
380 Any new test functions within the class must then define
381 tests in pairs, where the test name is preceded with a
382 '_' to indicate the client portion of the test. Ex:
383
384 def testFoo(self):
385 # Server portion
386
387 def _testFoo(self):
388 # Client portion
389
390 Any exceptions raised by the clients during their tests
391 are caught and transferred to the main thread to alert
392 the testing framework.
393
394 Note, the server setup function cannot call any blocking
395 functions that rely on the client thread during setup,
396 unless serverExplicitReady() is called just before
397 the blocking call (such as in setting up a client/server
398 connection and performing the accept() in setUp().
399 """
400
401 def __init__(self):
402 # Swap the true setup function
403 self.__setUp = self.setUp
404 self.setUp = self._setUp
405
406 def serverExplicitReady(self):
407 """This method allows the server to explicitly indicate that
408 it wants the client thread to proceed. This is useful if the
409 server is about to execute a blocking routine that is
410 dependent upon the client thread during its setup routine."""
411 self.server_ready.set()
412
413 def _setUp(self):
414 self.enterContext(threading_helper.wait_threads_exit())
415
416 self.server_ready = threading.Event()
417 self.client_ready = threading.Event()
418 self.done = threading.Event()
419 self.queue = queue.Queue(1)
420 self.server_crashed = False
421
422 def raise_queued_exception():
423 if self.queue.qsize():
424 raise self.queue.get()
425 self.addCleanup(raise_queued_exception)
426
427 # Do some munging to start the client test.
428 methodname = self.id()
429 i = methodname.rfind('.')
430 methodname = methodname[i+1:]
431 test_method = getattr(self, '_' + methodname)
432 self.client_thread = thread.start_new_thread(
433 self.clientRun, (test_method,))
434
435 try:
436 self.__setUp()
437 except:
438 self.server_crashed = True
439 raise
440 finally:
441 self.server_ready.set()
442 self.client_ready.wait()
443 self.addCleanup(self.done.wait)
444
445 def clientRun(self, test_func):
446 self.server_ready.wait()
447 try:
448 self.clientSetUp()
449 except BaseException as e:
450 self.queue.put(e)
451 self.clientTearDown()
452 return
453 finally:
454 self.client_ready.set()
455 if self.server_crashed:
456 self.clientTearDown()
457 return
458 if not hasattr(test_func, '__call__'):
459 raise TypeError("test_func must be a callable function")
460 try:
461 test_func()
462 except BaseException as e:
463 self.queue.put(e)
464 finally:
465 self.clientTearDown()
466
467 def clientSetUp(self):
468 raise NotImplementedError("clientSetUp must be implemented.")
469
470 def clientTearDown(self):
471 self.done.set()
472 thread.exit()
473
474 class ThreadedTCPSocketTest(SocketTCPTest, ThreadableTest):
475
476 def __init__(self, methodName='runTest'):
477 SocketTCPTest.__init__(self, methodName=methodName)
478 ThreadableTest.__init__(self)
479
480 def clientSetUp(self):
481 self.cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
482
483 def clientTearDown(self):
484 self.cli.close()
485 self.cli = None
486 ThreadableTest.clientTearDown(self)
487
488 class ThreadedUDPSocketTest(SocketUDPTest, ThreadableTest):
489
490 def __init__(self, methodName='runTest'):
491 SocketUDPTest.__init__(self, methodName=methodName)
492 ThreadableTest.__init__(self)
493
494 def clientSetUp(self):
495 self.cli = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
496
497 def clientTearDown(self):
498 self.cli.close()
499 self.cli = None
500 ThreadableTest.clientTearDown(self)
501
502 @unittest.skipUnless(HAVE_SOCKET_UDPLITE,
503 'UDPLITE sockets required for this test.')
504 class ThreadedUDPLITESocketTest(SocketUDPLITETest, ThreadableTest):
505
506 def __init__(self, methodName='runTest'):
507 SocketUDPLITETest.__init__(self, methodName=methodName)
508 ThreadableTest.__init__(self)
509
510 def clientSetUp(self):
511 self.cli = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDPLITE)
512
513 def clientTearDown(self):
514 self.cli.close()
515 self.cli = None
516 ThreadableTest.clientTearDown(self)
517
518 class ThreadedCANSocketTest(SocketCANTest, ThreadableTest):
519
520 def __init__(self, methodName='runTest'):
521 SocketCANTest.__init__(self, methodName=methodName)
522 ThreadableTest.__init__(self)
523
524 def clientSetUp(self):
525 self.cli = socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
526 try:
527 self.cli.bind((self.interface,))
528 except OSError:
529 # skipTest should not be called here, and will be called in the
530 # server instead
531 pass
532
533 def clientTearDown(self):
534 self.cli.close()
535 self.cli = None
536 ThreadableTest.clientTearDown(self)
537
538 class ThreadedRDSSocketTest(SocketRDSTest, ThreadableTest):
539
540 def __init__(self, methodName='runTest'):
541 SocketRDSTest.__init__(self, methodName=methodName)
542 ThreadableTest.__init__(self)
543
544 def clientSetUp(self):
545 self.cli = socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0)
546 try:
547 # RDS sockets must be bound explicitly to send or receive data
548 self.cli.bind((HOST, 0))
549 self.cli_addr = self.cli.getsockname()
550 except OSError:
551 # skipTest should not be called here, and will be called in the
552 # server instead
553 pass
554
555 def clientTearDown(self):
556 self.cli.close()
557 self.cli = None
558 ThreadableTest.clientTearDown(self)
559
560 @unittest.skipIf(fcntl is None, "need fcntl")
561 @unittest.skipIf(WSL, 'VSOCK does not work on Microsoft WSL')
562 @unittest.skipUnless(HAVE_SOCKET_VSOCK,
563 'VSOCK sockets required for this test.')
564 @unittest.skipIf(get_cid() == getattr(socket, 'VMADDR_CID_HOST', 2),
565 "This test can only be run on a virtual guest.")
566 class ThreadedVSOCKSocketStreamTest(unittest.TestCase, ThreadableTest):
567
568 def __init__(self, methodName='runTest'):
569 unittest.TestCase.__init__(self, methodName=methodName)
570 ThreadableTest.__init__(self)
571
572 def setUp(self):
573 self.serv = socket.socket(socket.AF_VSOCK, socket.SOCK_STREAM)
574 self.addCleanup(self.serv.close)
575 cid = get_cid()
576 if cid in (socket.VMADDR_CID_HOST, socket.VMADDR_CID_ANY):
577 cid = socket.VMADDR_CID_LOCAL
578 try:
579 self.serv.bind((cid, VSOCKPORT))
580 except OSError as exc:
581 if exc.errno == errno.EADDRNOTAVAIL:
582 self.skipTest(f"bind() failed with {exc!r}")
583 else:
584 raise
585 self.serv.listen()
586 self.serverExplicitReady()
587 self.serv.settimeout(support.LOOPBACK_TIMEOUT)
588 self.conn, self.connaddr = self.serv.accept()
589 self.addCleanup(self.conn.close)
590
591 def clientSetUp(self):
592 time.sleep(0.1)
593 self.cli = socket.socket(socket.AF_VSOCK, socket.SOCK_STREAM)
594 self.addCleanup(self.cli.close)
595 cid = get_cid()
596 if cid in (socket.VMADDR_CID_HOST, socket.VMADDR_CID_ANY):
597 # gh-119461: Use the local communication address (loopback)
598 cid = socket.VMADDR_CID_LOCAL
599 self.cli.connect((cid, VSOCKPORT))
600
601 def testStream(self):
602 try:
603 msg = self.conn.recv(1024)
604 except PermissionError as exc:
605 self.skipTest(repr(exc))
606 self.assertEqual(msg, MSG)
607
608 def _testStream(self):
609 self.cli.send(MSG)
610 self.cli.close()
611
612 class SocketConnectedTest(ThreadedTCPSocketTest):
613 """Socket tests for client-server connection.
614
615 self.cli_conn is a client socket connected to the server. The
616 setUp() method guarantees that it is connected to the server.
617 """
618
619 def __init__(self, methodName='runTest'):
620 ThreadedTCPSocketTest.__init__(self, methodName=methodName)
621
622 def setUp(self):
623 ThreadedTCPSocketTest.setUp(self)
624 # Indicate explicitly we're ready for the client thread to
625 # proceed and then perform the blocking call to accept
626 self.serverExplicitReady()
627 conn, addr = self.serv.accept()
628 self.cli_conn = conn
629
630 def tearDown(self):
631 self.cli_conn.close()
632 self.cli_conn = None
633 ThreadedTCPSocketTest.tearDown(self)
634
635 def clientSetUp(self):
636 ThreadedTCPSocketTest.clientSetUp(self)
637 self.cli.connect((HOST, self.port))
638 self.serv_conn = self.cli
639
640 def clientTearDown(self):
641 self.serv_conn.close()
642 self.serv_conn = None
643 ThreadedTCPSocketTest.clientTearDown(self)
644
645 class SocketPairTest(unittest.TestCase, ThreadableTest):
646
647 def __init__(self, methodName='runTest'):
648 unittest.TestCase.__init__(self, methodName=methodName)
649 ThreadableTest.__init__(self)
650 self.cli = None
651 self.serv = None
652
653 def socketpair(self):
654 # To be overridden by some child classes.
655 return socket.socketpair()
656
657 def setUp(self):
658 self.serv, self.cli = self.socketpair()
659
660 def tearDown(self):
661 if self.serv:
662 self.serv.close()
663 self.serv = None
664
665 def clientSetUp(self):
666 pass
667
668 def clientTearDown(self):
669 if self.cli:
670 self.cli.close()
671 self.cli = None
672 ThreadableTest.clientTearDown(self)
673
674
675 # The following classes are used by the sendmsg()/recvmsg() tests.
676 # Combining, for instance, ConnectedStreamTestMixin and TCPTestBase
677 # gives a drop-in replacement for SocketConnectedTest, but different
678 # address families can be used, and the attributes serv_addr and
679 # cli_addr will be set to the addresses of the endpoints.
680
681 class SocketTestBase(unittest.TestCase):
682 """A base class for socket tests.
683
684 Subclasses must provide methods newSocket() to return a new socket
685 and bindSock(sock) to bind it to an unused address.
686
687 Creates a socket self.serv and sets self.serv_addr to its address.
688 """
689
690 def setUp(self):
691 self.serv = self.newSocket()
692 self.addCleanup(self.close_server)
693 self.bindServer()
694
695 def close_server(self):
696 self.serv.close()
697 self.serv = None
698
699 def bindServer(self):
700 """Bind server socket and set self.serv_addr to its address."""
701 self.bindSock(self.serv)
702 self.serv_addr = self.serv.getsockname()
703
704
705 class SocketListeningTestMixin(SocketTestBase):
706 """Mixin to listen on the server socket."""
707
708 def setUp(self):
709 super().setUp()
710 self.serv.listen()
711
712
713 class ThreadedSocketTestMixin(SocketTestBase, ThreadableTest):
714 """Mixin to add client socket and allow client/server tests.
715
716 Client socket is self.cli and its address is self.cli_addr. See
717 ThreadableTest for usage information.
718 """
719
720 def __init__(self, *args, **kwargs):
721 super().__init__(*args, **kwargs)
722 ThreadableTest.__init__(self)
723
724 def clientSetUp(self):
725 self.cli = self.newClientSocket()
726 self.bindClient()
727
728 def newClientSocket(self):
729 """Return a new socket for use as client."""
730 return self.newSocket()
731
732 def bindClient(self):
733 """Bind client socket and set self.cli_addr to its address."""
734 self.bindSock(self.cli)
735 self.cli_addr = self.cli.getsockname()
736
737 def clientTearDown(self):
738 self.cli.close()
739 self.cli = None
740 ThreadableTest.clientTearDown(self)
741
742
743 class ConnectedStreamTestMixin(SocketListeningTestMixin,
744 ThreadedSocketTestMixin):
745 """Mixin to allow client/server stream tests with connected client.
746
747 Server's socket representing connection to client is self.cli_conn
748 and client's connection to server is self.serv_conn. (Based on
749 SocketConnectedTest.)
750 """
751
752 def setUp(self):
753 super().setUp()
754 # Indicate explicitly we're ready for the client thread to
755 # proceed and then perform the blocking call to accept
756 self.serverExplicitReady()
757 conn, addr = self.serv.accept()
758 self.cli_conn = conn
759
760 def tearDown(self):
761 self.cli_conn.close()
762 self.cli_conn = None
763 super().tearDown()
764
765 def clientSetUp(self):
766 super().clientSetUp()
767 self.cli.connect(self.serv_addr)
768 self.serv_conn = self.cli
769
770 def clientTearDown(self):
771 try:
772 self.serv_conn.close()
773 self.serv_conn = None
774 except AttributeError:
775 pass
776 super().clientTearDown()
777
778
779 class UnixSocketTestBase(SocketTestBase):
780 """Base class for Unix-domain socket tests."""
781
782 # This class is used for file descriptor passing tests, so we
783 # create the sockets in a private directory so that other users
784 # can't send anything that might be problematic for a privileged
785 # user running the tests.
786
787 def bindSock(self, sock):
788 path = socket_helper.create_unix_domain_name()
789 self.addCleanup(os_helper.unlink, path)
790 socket_helper.bind_unix_socket(sock, path)
791
792 class UnixStreamBase(UnixSocketTestBase):
793 """Base class for Unix-domain SOCK_STREAM tests."""
794
795 def newSocket(self):
796 return socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
797
798
799 class InetTestBase(SocketTestBase):
800 """Base class for IPv4 socket tests."""
801
802 host = HOST
803
804 def setUp(self):
805 super().setUp()
806 self.port = self.serv_addr[1]
807
808 def bindSock(self, sock):
809 socket_helper.bind_port(sock, host=self.host)
810
811 class TCPTestBase(InetTestBase):
812 """Base class for TCP-over-IPv4 tests."""
813
814 def newSocket(self):
815 return socket.socket(socket.AF_INET, socket.SOCK_STREAM)
816
817 class UDPTestBase(InetTestBase):
818 """Base class for UDP-over-IPv4 tests."""
819
820 def newSocket(self):
821 return socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
822
823 class UDPLITETestBase(InetTestBase):
824 """Base class for UDPLITE-over-IPv4 tests."""
825
826 def newSocket(self):
827 return socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDPLITE)
828
829 class SCTPStreamBase(InetTestBase):
830 """Base class for SCTP tests in one-to-one (SOCK_STREAM) mode."""
831
832 def newSocket(self):
833 return socket.socket(socket.AF_INET, socket.SOCK_STREAM,
834 socket.IPPROTO_SCTP)
835
836
837 class Inet6TestBase(InetTestBase):
838 """Base class for IPv6 socket tests."""
839
840 host = socket_helper.HOSTv6
841
842 class UDP6TestBase(Inet6TestBase):
843 """Base class for UDP-over-IPv6 tests."""
844
845 def newSocket(self):
846 return socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
847
848 class UDPLITE6TestBase(Inet6TestBase):
849 """Base class for UDPLITE-over-IPv6 tests."""
850
851 def newSocket(self):
852 return socket.socket(socket.AF_INET6, socket.SOCK_DGRAM, socket.IPPROTO_UDPLITE)
853
854
855 # Test-skipping decorators for use with ThreadableTest.
856
857 def skipWithClientIf(condition, reason):
858 """Skip decorated test if condition is true, add client_skip decorator.
859
860 If the decorated object is not a class, sets its attribute
861 "client_skip" to a decorator which will return an empty function
862 if the test is to be skipped, or the original function if it is
863 not. This can be used to avoid running the client part of a
864 skipped test when using ThreadableTest.
865 """
866 def client_pass(*args, **kwargs):
867 pass
868 def skipdec(obj):
869 retval = unittest.skip(reason)(obj)
870 if not isinstance(obj, type):
871 retval.client_skip = lambda f: client_pass
872 return retval
873 def noskipdec(obj):
874 if not (isinstance(obj, type) or hasattr(obj, "client_skip")):
875 obj.client_skip = lambda f: f
876 return obj
877 return skipdec if condition else noskipdec
878
879
880 def requireAttrs(obj, *attributes):
881 """Skip decorated test if obj is missing any of the given attributes.
882
883 Sets client_skip attribute as skipWithClientIf() does.
884 """
885 missing = [name for name in attributes if not hasattr(obj, name)]
886 return skipWithClientIf(
887 missing, "don't have " + ", ".join(name for name in missing))
888
889
890 def requireSocket(*args):
891 """Skip decorated test if a socket cannot be created with given arguments.
892
893 When an argument is given as a string, will use the value of that
894 attribute of the socket module, or skip the test if it doesn't
895 exist. Sets client_skip attribute as skipWithClientIf() does.
896 """
897 err = None
898 missing = [obj for obj in args if
899 isinstance(obj, str) and not hasattr(socket, obj)]
900 if missing:
901 err = "don't have " + ", ".join(name for name in missing)
902 else:
903 callargs = [getattr(socket, obj) if isinstance(obj, str) else obj
904 for obj in args]
905 try:
906 s = socket.socket(*callargs)
907 except OSError as e:
908 # XXX: check errno?
909 err = str(e)
910 else:
911 s.close()
912 return skipWithClientIf(
913 err is not None,
914 "can't create socket({0}): {1}".format(
915 ", ".join(str(o) for o in args), err))
916
917
918 #######################################################################
919 ## Begin Tests
920
921 class GeneralModuleTests(unittest.TestCase):
922
923 @unittest.skipUnless(_socket is not None, 'need _socket module')
924 def test_socket_type(self):
925 self.assertTrue(gc.is_tracked(_socket.socket))
926 with self.assertRaisesRegex(TypeError, "immutable"):
927 _socket.socket.foo = 1
928
929 def test_SocketType_is_socketobject(self):
930 import _socket
931 self.assertTrue(socket.SocketType is _socket.socket)
932 s = socket.socket()
933 self.assertIsInstance(s, socket.SocketType)
934 s.close()
935
936 def test_repr(self):
937 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
938 with s:
939 self.assertIn('fd=%i' % s.fileno(), repr(s))
940 self.assertIn('family=%s' % socket.AF_INET, repr(s))
941 self.assertIn('type=%s' % socket.SOCK_STREAM, repr(s))
942 self.assertIn('proto=0', repr(s))
943 self.assertNotIn('raddr', repr(s))
944 s.bind(('127.0.0.1', 0))
945 self.assertIn('laddr', repr(s))
946 self.assertIn(str(s.getsockname()), repr(s))
947 self.assertIn('[closed]', repr(s))
948 self.assertNotIn('laddr', repr(s))
949
950 @unittest.skipUnless(_socket is not None, 'need _socket module')
951 def test_csocket_repr(self):
952 s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
953 try:
954 expected = ('<socket object, fd=%s, family=%s, type=%s, proto=%s>'
955 % (s.fileno(), s.family, s.type, s.proto))
956 self.assertEqual(repr(s), expected)
957 finally:
958 s.close()
959 expected = ('<socket object, fd=-1, family=%s, type=%s, proto=%s>'
960 % (s.family, s.type, s.proto))
961 self.assertEqual(repr(s), expected)
962
963 def test_weakref(self):
964 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
965 p = proxy(s)
966 self.assertEqual(p.fileno(), s.fileno())
967 s = None
968 support.gc_collect() # For PyPy or other GCs.
969 try:
970 p.fileno()
971 except ReferenceError:
972 pass
973 else:
974 self.fail('Socket proxy still exists')
975
976 def testSocketError(self):
977 # Testing socket module exceptions
978 msg = "Error raising socket exception (%s)."
979 with self.assertRaises(OSError, msg=msg % 'OSError'):
980 raise OSError
981 with self.assertRaises(OSError, msg=msg % 'socket.herror'):
982 raise socket.herror
983 with self.assertRaises(OSError, msg=msg % 'socket.gaierror'):
984 raise socket.gaierror
985
986 def testSendtoErrors(self):
987 # Testing that sendto doesn't mask failures. See #10169.
988 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
989 self.addCleanup(s.close)
990 s.bind(('', 0))
991 sockname = s.getsockname()
992 # 2 args
993 with self.assertRaises(TypeError) as cm:
994 s.sendto('\u2620', sockname)
995 self.assertEqual(str(cm.exception),
996 "a bytes-like object is required, not 'str'")
997 with self.assertRaises(TypeError) as cm:
998 s.sendto(5j, sockname)
999 self.assertEqual(str(cm.exception),
1000 "a bytes-like object is required, not 'complex'")
1001 with self.assertRaises(TypeError) as cm:
1002 s.sendto(b'foo', None)
1003 self.assertIn('not NoneType',str(cm.exception))
1004 # 3 args
1005 with self.assertRaises(TypeError) as cm:
1006 s.sendto('\u2620', 0, sockname)
1007 self.assertEqual(str(cm.exception),
1008 "a bytes-like object is required, not 'str'")
1009 with self.assertRaises(TypeError) as cm:
1010 s.sendto(5j, 0, sockname)
1011 self.assertEqual(str(cm.exception),
1012 "a bytes-like object is required, not 'complex'")
1013 with self.assertRaises(TypeError) as cm:
1014 s.sendto(b'foo', 0, None)
1015 self.assertIn('not NoneType', str(cm.exception))
1016 with self.assertRaises(TypeError) as cm:
1017 s.sendto(b'foo', 'bar', sockname)
1018 with self.assertRaises(TypeError) as cm:
1019 s.sendto(b'foo', None, None)
1020 # wrong number of args
1021 with self.assertRaises(TypeError) as cm:
1022 s.sendto(b'foo')
1023 self.assertIn('(1 given)', str(cm.exception))
1024 with self.assertRaises(TypeError) as cm:
1025 s.sendto(b'foo', 0, sockname, 4)
1026 self.assertIn('(4 given)', str(cm.exception))
1027
1028 def testCrucialConstants(self):
1029 # Testing for mission critical constants
1030 socket.AF_INET
1031 if socket.has_ipv6:
1032 socket.AF_INET6
1033 socket.SOCK_STREAM
1034 socket.SOCK_DGRAM
1035 socket.SOCK_RAW
1036 socket.SOCK_RDM
1037 socket.SOCK_SEQPACKET
1038 socket.SOL_SOCKET
1039 socket.SO_REUSEADDR
1040
1041 def testCrucialIpProtoConstants(self):
1042 socket.IPPROTO_TCP
1043 socket.IPPROTO_UDP
1044 if socket.has_ipv6:
1045 socket.IPPROTO_IPV6
1046
1047 @unittest.skipUnless(os.name == "nt", "Windows specific")
1048 def testWindowsSpecificConstants(self):
1049 socket.IPPROTO_ICLFXBM
1050 socket.IPPROTO_ST
1051 socket.IPPROTO_CBT
1052 socket.IPPROTO_IGP
1053 socket.IPPROTO_RDP
1054 socket.IPPROTO_PGM
1055 socket.IPPROTO_L2TP
1056 socket.IPPROTO_SCTP
1057
1058 @unittest.skipIf(support.is_wasi, "WASI is missing these methods")
1059 def test_socket_methods(self):
1060 # socket methods that depend on a configure HAVE_ check. They should
1061 # be present on all platforms except WASI.
1062 names = [
1063 "_accept", "bind", "connect", "connect_ex", "getpeername",
1064 "getsockname", "listen", "recvfrom", "recvfrom_into", "sendto",
1065 "setsockopt", "shutdown"
1066 ]
1067 for name in names:
1068 if not hasattr(socket.socket, name):
1069 self.fail(f"socket method {name} is missing")
1070
1071 @unittest.skipUnless(sys.platform == 'darwin', 'macOS specific test')
1072 @unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test')
1073 def test3542SocketOptions(self):
1074 # Ref. issue #35569 and https://tools.ietf.org/html/rfc3542
1075 opts = {
1076 'IPV6_CHECKSUM',
1077 'IPV6_DONTFRAG',
1078 'IPV6_DSTOPTS',
1079 'IPV6_HOPLIMIT',
1080 'IPV6_HOPOPTS',
1081 'IPV6_NEXTHOP',
1082 'IPV6_PATHMTU',
1083 'IPV6_PKTINFO',
1084 'IPV6_RECVDSTOPTS',
1085 'IPV6_RECVHOPLIMIT',
1086 'IPV6_RECVHOPOPTS',
1087 'IPV6_RECVPATHMTU',
1088 'IPV6_RECVPKTINFO',
1089 'IPV6_RECVRTHDR',
1090 'IPV6_RECVTCLASS',
1091 'IPV6_RTHDR',
1092 'IPV6_RTHDRDSTOPTS',
1093 'IPV6_RTHDR_TYPE_0',
1094 'IPV6_TCLASS',
1095 'IPV6_USE_MIN_MTU',
1096 }
1097 for opt in opts:
1098 self.assertHasAttr(socket, opt)
1099
1100 def testHostnameRes(self):
1101 # Testing hostname resolution mechanisms
1102 hostname = socket.gethostname()
1103 try:
1104 ip = socket.gethostbyname(hostname)
1105 except OSError:
1106 # Probably name lookup wasn't set up right; skip this test
1107 self.skipTest('name lookup failure')
1108 self.assertTrue(ip.find('.') >= 0, "Error resolving host to ip.")
1109 try:
1110 hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
1111 except OSError:
1112 # Probably a similar problem as above; skip this test
1113 self.skipTest('name lookup failure')
1114 all_host_names = [hostname, hname] + aliases
1115 fqhn = socket.getfqdn(ip)
1116 if not fqhn in all_host_names:
1117 self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names)))
1118
1119 def test_host_resolution(self):
1120 for addr in [socket_helper.HOSTv4, '10.0.0.1', '255.255.255.255']:
1121 self.assertEqual(socket.gethostbyname(addr), addr)
1122
1123 # we don't test socket_helper.HOSTv6 because there's a chance it doesn't have
1124 # a matching name entry (e.g. 'ip6-localhost')
1125 for host in [socket_helper.HOSTv4]:
1126 self.assertIn(host, socket.gethostbyaddr(host)[2])
1127
1128 def test_host_resolution_bad_address(self):
1129 # These are all malformed IP addresses and expected not to resolve to
1130 # any result. But some ISPs, e.g. AWS and AT&T, may successfully
1131 # resolve these IPs. In particular, AT&T's DNS Error Assist service
1132 # will break this test. See https://bugs.python.org/issue42092 for a
1133 # workaround.
1134 explanation = (
1135 "resolving an invalid IP address did not raise OSError; "
1136 "can be caused by a broken DNS server"
1137 )
1138 for addr in ['0.1.1.~1', '1+.1.1.1', '::1q', '::1::2',
1139 '1:1:1:1:1:1:1:1:1']:
1140 with self.assertRaises(OSError, msg=addr):
1141 socket.gethostbyname(addr)
1142 with self.assertRaises(OSError, msg=explanation):
1143 socket.gethostbyaddr(addr)
1144
1145 @unittest.skipUnless(hasattr(socket, 'sethostname'), "test needs socket.sethostname()")
1146 @unittest.skipUnless(hasattr(socket, 'gethostname'), "test needs socket.gethostname()")
1147 def test_sethostname(self):
1148 oldhn = socket.gethostname()
1149 try:
1150 socket.sethostname('new')
1151 except OSError as e:
1152 if e.errno == errno.EPERM:
1153 self.skipTest("test should be run as root")
1154 else:
1155 raise
1156 try:
1157 # running test as root!
1158 self.assertEqual(socket.gethostname(), 'new')
1159 # Should work with bytes objects too
1160 socket.sethostname(b'bar')
1161 self.assertEqual(socket.gethostname(), 'bar')
1162 finally:
1163 socket.sethostname(oldhn)
1164
1165 @unittest.skipUnless(hasattr(socket, 'if_nameindex'),
1166 'socket.if_nameindex() not available.')
1167 @support.skip_android_selinux('if_nameindex')
1168 def testInterfaceNameIndex(self):
1169 interfaces = socket.if_nameindex()
1170 for index, name in interfaces:
1171 self.assertIsInstance(index, int)
1172 self.assertIsInstance(name, str)
1173 # interface indices are non-zero integers
1174 self.assertGreater(index, 0)
1175 _index = socket.if_nametoindex(name)
1176 self.assertIsInstance(_index, int)
1177 self.assertEqual(index, _index)
1178 _name = socket.if_indextoname(index)
1179 self.assertIsInstance(_name, str)
1180 self.assertEqual(name, _name)
1181
1182 @unittest.skipUnless(hasattr(socket, 'if_indextoname'),
1183 'socket.if_indextoname() not available.')
1184 @support.skip_android_selinux('if_indextoname')
1185 def testInvalidInterfaceIndexToName(self):
1186 with self.assertRaises(OSError) as cm:
1187 socket.if_indextoname(0)
1188 self.assertIsNotNone(cm.exception.errno)
1189
1190 self.assertRaises(ValueError, socket.if_indextoname, -1)
1191 self.assertRaises(OverflowError, socket.if_indextoname, 2**1000)
1192 self.assertRaises(TypeError, socket.if_indextoname, '_DEADBEEF')
1193 if hasattr(socket, 'if_nameindex'):
1194 indices = dict(socket.if_nameindex())
1195 for index in indices:
1196 index2 = index + 2**32
1197 if index2 not in indices:
1198 with self.assertRaises((OverflowError, OSError)):
1199 socket.if_indextoname(index2)
1200 for index in 2**32-1, 2**64-1:
1201 if index not in indices:
1202 with self.assertRaises((OverflowError, OSError)):
1203 socket.if_indextoname(index)
1204
1205 @unittest.skipUnless(hasattr(socket, 'if_nametoindex'),
1206 'socket.if_nametoindex() not available.')
1207 @support.skip_android_selinux('if_nametoindex')
1208 def testInvalidInterfaceNameToIndex(self):
1209 with self.assertRaises(OSError) as cm:
1210 socket.if_nametoindex("_DEADBEEF")
1211 self.assertIsNotNone(cm.exception.errno)
1212
1213 self.assertRaises(TypeError, socket.if_nametoindex, 0)
1214
1215 @unittest.skipUnless(hasattr(sys, 'getrefcount'),
1216 'test needs sys.getrefcount()')
1217 def testRefCountGetNameInfo(self):
1218 # Testing reference count for getnameinfo
1219 try:
1220 # On some versions, this loses a reference
1221 orig = sys.getrefcount(__name__)
1222 socket.getnameinfo(__name__,0)
1223 except TypeError:
1224 if sys.getrefcount(__name__) != orig:
1225 self.fail("socket.getnameinfo loses a reference")
1226
1227 def testInterpreterCrash(self):
1228 # Making sure getnameinfo doesn't crash the interpreter
1229 try:
1230 # On some versions, this crashes the interpreter.
1231 socket.getnameinfo(('x', 0, 0, 0), 0)
1232 except OSError:
1233 pass
1234
1235 def testNtoH(self):
1236 # This just checks that htons etc. are their own inverse,
1237 # when looking at the lower 16 or 32 bits.
1238 sizes = {socket.htonl: 32, socket.ntohl: 32,
1239 socket.htons: 16, socket.ntohs: 16}
1240 for func, size in sizes.items():
1241 mask = (1<<size) - 1
1242 for i in (0, 1, 0xffff, ~0xffff, 2, 0x01234567, 0x76543210):
1243 self.assertEqual(i & mask, func(func(i&mask)) & mask)
1244
1245 swapped = func(mask)
1246 self.assertEqual(swapped & mask, mask)
1247 self.assertRaises(OverflowError, func, 1<<34)
1248
1249 def testNtoHErrors(self):
1250 s_good_values = [0, 1, 2, 0xffff]
1251 l_good_values = s_good_values + [0xffffffff]
1252 neg_values = [-1, -2, -(1<<15)-1, -(1<<31)-1, -(1<<63)-1, -1<<1000]
1253 l_bad_values = [1<<32, 1<<1000]
1254 s_bad_values = l_bad_values + [1 << 16, (1<<31)-1, 1<<31]
1255 for k in s_good_values:
1256 socket.ntohs(k)
1257 socket.htons(k)
1258 for k in l_good_values:
1259 socket.ntohl(k)
1260 socket.htonl(k)
1261 for k in neg_values:
1262 self.assertRaises(ValueError, socket.ntohs, k)
1263 self.assertRaises(ValueError, socket.htons, k)
1264 self.assertRaises(ValueError, socket.ntohl, k)
1265 self.assertRaises(ValueError, socket.htonl, k)
1266 for k in s_bad_values:
1267 self.assertRaises(OverflowError, socket.ntohs, k)
1268 self.assertRaises(OverflowError, socket.htons, k)
1269 for k in l_bad_values:
1270 self.assertRaises(OverflowError, socket.ntohl, k)
1271 self.assertRaises(OverflowError, socket.htonl, k)
1272
1273 def testGetServBy(self):
1274 eq = self.assertEqual
1275 # Find one service that exists, then check all the related interfaces.
1276 # I've ordered this by protocols that have both a tcp and udp
1277 # protocol, at least for modern Linuxes.
1278 if (
1279 sys.platform.startswith(
1280 ('linux', 'android', 'freebsd', 'netbsd', 'gnukfreebsd'))
1281 or is_apple
1282 ):
1283 # avoid the 'echo' service on this platform, as there is an
1284 # assumption breaking non-standard port/protocol entry
1285 services = ('daytime', 'qotd', 'domain')
1286 else:
1287 services = ('echo', 'daytime', 'domain')
1288 for service in services:
1289 try:
1290 port = socket.getservbyname(service, 'tcp')
1291 break
1292 except OSError:
1293 pass
1294 else:
1295 raise OSError
1296 # Try same call with optional protocol omitted
1297 # Issue gh-71123: this fails on Android before API level 23.
1298 if not (support.is_android and platform.android_ver().api_level < 23):
1299 port2 = socket.getservbyname(service)
1300 eq(port, port2)
1301 # Try udp, but don't barf if it doesn't exist
1302 try:
1303 udpport = socket.getservbyname(service, 'udp')
1304 except OSError:
1305 udpport = None
1306 else:
1307 eq(udpport, port)
1308 # Now make sure the lookup by port returns the same service name
1309 # Issue #26936: when the protocol is omitted, this fails on Android
1310 # before API level 28.
1311 if not (support.is_android and platform.android_ver().api_level < 28):
1312 eq(socket.getservbyport(port2), service)
1313 eq(socket.getservbyport(port, 'tcp'), service)
1314 if udpport is not None:
1315 eq(socket.getservbyport(udpport, 'udp'), service)
1316 # Make sure getservbyport does not accept out of range ports.
1317 self.assertRaises(OverflowError, socket.getservbyport, -1)
1318 self.assertRaises(OverflowError, socket.getservbyport, 65536)
1319
1320 def testDefaultTimeout(self):
1321 # Testing default timeout
1322 # The default timeout should initially be None
1323 self.assertEqual(socket.getdefaulttimeout(), None)
1324 with socket.socket() as s:
1325 self.assertEqual(s.gettimeout(), None)
1326
1327 # Set the default timeout to 10, and see if it propagates
1328 with socket_setdefaulttimeout(10):
1329 self.assertEqual(socket.getdefaulttimeout(), 10)
1330 with socket.socket() as sock:
1331 self.assertEqual(sock.gettimeout(), 10)
1332
1333 # Reset the default timeout to None, and see if it propagates
1334 socket.setdefaulttimeout(None)
1335 self.assertEqual(socket.getdefaulttimeout(), None)
1336 with socket.socket() as sock:
1337 self.assertEqual(sock.gettimeout(), None)
1338
1339 # Check that setting it to an invalid value raises ValueError
1340 self.assertRaises(ValueError, socket.setdefaulttimeout, -1)
1341
1342 # Check that setting it to an invalid type raises TypeError
1343 self.assertRaises(TypeError, socket.setdefaulttimeout, "spam")
1344
1345 @unittest.skipUnless(hasattr(socket, 'inet_aton'),
1346 'test needs socket.inet_aton()')
1347 def testIPv4_inet_aton_fourbytes(self):
1348 # Test that issue1008086 and issue767150 are fixed.
1349 # It must return 4 bytes.
1350 self.assertEqual(b'\x00'*4, socket.inet_aton('0.0.0.0'))
1351 self.assertEqual(b'\xff'*4, socket.inet_aton('255.255.255.255'))
1352
1353 @unittest.skipUnless(hasattr(socket, 'inet_pton'),
1354 'test needs socket.inet_pton()')
1355 def testIPv4toString(self):
1356 from socket import inet_aton as f, inet_pton, AF_INET
1357 g = lambda a: inet_pton(AF_INET, a)
1358
1359 assertInvalid = lambda func,a: self.assertRaises(
1360 (OSError, ValueError), func, a
1361 )
1362
1363 self.assertEqual(b'\x00\x00\x00\x00', f('0.0.0.0'))
1364 self.assertEqual(b'\xff\x00\xff\x00', f('255.0.255.0'))
1365 self.assertEqual(b'\xaa\xaa\xaa\xaa', f('170.170.170.170'))
1366 self.assertEqual(b'\x01\x02\x03\x04', f('1.2.3.4'))
1367 self.assertEqual(b'\xff\xff\xff\xff', f('255.255.255.255'))
1368 # bpo-29972: inet_pton() doesn't fail on AIX
1369 if not AIX:
1370 assertInvalid(f, '0.0.0.')
1371 assertInvalid(f, '300.0.0.0')
1372 assertInvalid(f, 'a.0.0.0')
1373 assertInvalid(f, '1.2.3.4.5')
1374 assertInvalid(f, '::1')
1375
1376 self.assertEqual(b'\x00\x00\x00\x00', g('0.0.0.0'))
1377 self.assertEqual(b'\xff\x00\xff\x00', g('255.0.255.0'))
1378 self.assertEqual(b'\xaa\xaa\xaa\xaa', g('170.170.170.170'))
1379 self.assertEqual(b'\xff\xff\xff\xff', g('255.255.255.255'))
1380 assertInvalid(g, '0.0.0.')
1381 assertInvalid(g, '300.0.0.0')
1382 assertInvalid(g, 'a.0.0.0')
1383 assertInvalid(g, '1.2.3.4.5')
1384 assertInvalid(g, '::1')
1385
1386 @unittest.skipUnless(hasattr(socket, 'inet_pton'),
1387 'test needs socket.inet_pton()')
1388 def testIPv6toString(self):
1389 try:
1390 from socket import inet_pton, AF_INET6, has_ipv6
1391 if not has_ipv6:
1392 self.skipTest('IPv6 not available')
1393 except ImportError:
1394 self.skipTest('could not import needed symbols from socket')
1395
1396 if sys.platform == "win32":
1397 try:
1398 inet_pton(AF_INET6, '::')
1399 except OSError as e:
1400 if e.winerror == 10022:
1401 self.skipTest('IPv6 might not be supported')
1402
1403 f = lambda a: inet_pton(AF_INET6, a)
1404 assertInvalid = lambda a: self.assertRaises(
1405 (OSError, ValueError), f, a
1406 )
1407
1408 self.assertEqual(b'\x00' * 16, f('::'))
1409 self.assertEqual(b'\x00' * 16, f('0::0'))
1410 self.assertEqual(b'\x00\x01' + b'\x00' * 14, f('1::'))
1411 self.assertEqual(
1412 b'\x45\xef\x76\xcb\x00\x1a\x56\xef\xaf\xeb\x0b\xac\x19\x24\xae\xae',
1413 f('45ef:76cb:1a:56ef:afeb:bac:1924:aeae')
1414 )
1415 self.assertEqual(
1416 b'\xad\x42\x0a\xbc' + b'\x00' * 4 + b'\x01\x27\x00\x00\x02\x54\x00\x02',
1417 f('ad42:abc::127:0:254:2')
1418 )
1419 self.assertEqual(b'\x00\x12\x00\x0a' + b'\x00' * 12, f('12:a::'))
1420 assertInvalid('0x20::')
1421 assertInvalid(':::')
1422 assertInvalid('::0::')
1423 assertInvalid('1::abc::')
1424 assertInvalid('1::abc::def')
1425 assertInvalid('1:2:3:4:5:6')
1426 assertInvalid('1:2:3:4:5:6:')
1427 assertInvalid('1:2:3:4:5:6:7:8:0')
1428 # bpo-29972: inet_pton() doesn't fail on AIX
1429 if not AIX:
1430 assertInvalid('1:2:3:4:5:6:7:8:')
1431
1432 self.assertEqual(b'\x00' * 12 + b'\xfe\x2a\x17\x40',
1433 f('::254.42.23.64')
1434 )
1435 self.assertEqual(
1436 b'\x00\x42' + b'\x00' * 8 + b'\xa2\x9b\xfe\x2a\x17\x40',
1437 f('42::a29b:254.42.23.64')
1438 )
1439 self.assertEqual(
1440 b'\x00\x42\xa8\xb9\x00\x00\x00\x02\xff\xff\xa2\x9b\xfe\x2a\x17\x40',
1441 f('42:a8b9:0:2:ffff:a29b:254.42.23.64')
1442 )
1443 assertInvalid('255.254.253.252')
1444 assertInvalid('1::260.2.3.0')
1445 assertInvalid('1::0.be.e.0')
1446 assertInvalid('1:2:3:4:5:6:7:1.2.3.4')
1447 assertInvalid('::1.2.3.4:0')
1448 assertInvalid('0.100.200.0:3:4:5:6:7:8')
1449
1450 @unittest.skipUnless(hasattr(socket, 'inet_ntop'),
1451 'test needs socket.inet_ntop()')
1452 def testStringToIPv4(self):
1453 from socket import inet_ntoa as f, inet_ntop, AF_INET
1454 g = lambda a: inet_ntop(AF_INET, a)
1455 assertInvalid = lambda func,a: self.assertRaises(
1456 (OSError, ValueError), func, a
1457 )
1458
1459 self.assertEqual('1.0.1.0', f(b'\x01\x00\x01\x00'))
1460 self.assertEqual('170.85.170.85', f(b'\xaa\x55\xaa\x55'))
1461 self.assertEqual('255.255.255.255', f(b'\xff\xff\xff\xff'))
1462 self.assertEqual('1.2.3.4', f(b'\x01\x02\x03\x04'))
1463 assertInvalid(f, b'\x00' * 3)
1464 assertInvalid(f, b'\x00' * 5)
1465 assertInvalid(f, b'\x00' * 16)
1466 self.assertEqual('170.85.170.85', f(bytearray(b'\xaa\x55\xaa\x55')))
1467
1468 self.assertEqual('1.0.1.0', g(b'\x01\x00\x01\x00'))
1469 self.assertEqual('170.85.170.85', g(b'\xaa\x55\xaa\x55'))
1470 self.assertEqual('255.255.255.255', g(b'\xff\xff\xff\xff'))
1471 assertInvalid(g, b'\x00' * 3)
1472 assertInvalid(g, b'\x00' * 5)
1473 assertInvalid(g, b'\x00' * 16)
1474 self.assertEqual('170.85.170.85', g(bytearray(b'\xaa\x55\xaa\x55')))
1475
1476 @unittest.skipUnless(hasattr(socket, 'inet_ntop'),
1477 'test needs socket.inet_ntop()')
1478 def testStringToIPv6(self):
1479 try:
1480 from socket import inet_ntop, AF_INET6, has_ipv6
1481 if not has_ipv6:
1482 self.skipTest('IPv6 not available')
1483 except ImportError:
1484 self.skipTest('could not import needed symbols from socket')
1485
1486 if sys.platform == "win32":
1487 try:
1488 inet_ntop(AF_INET6, b'\x00' * 16)
1489 except OSError as e:
1490 if e.winerror == 10022:
1491 self.skipTest('IPv6 might not be supported')
1492
1493 f = lambda a: inet_ntop(AF_INET6, a)
1494 assertInvalid = lambda a: self.assertRaises(
1495 (OSError, ValueError), f, a
1496 )
1497
1498 self.assertEqual('::', f(b'\x00' * 16))
1499 self.assertEqual('::1', f(b'\x00' * 15 + b'\x01'))
1500 self.assertEqual(
1501 'aef:b01:506:1001:ffff:9997:55:170',
1502 f(b'\x0a\xef\x0b\x01\x05\x06\x10\x01\xff\xff\x99\x97\x00\x55\x01\x70')
1503 )
1504 self.assertEqual('::1', f(bytearray(b'\x00' * 15 + b'\x01')))
1505
1506 assertInvalid(b'\x12' * 15)
1507 assertInvalid(b'\x12' * 17)
1508 assertInvalid(b'\x12' * 4)
1509
1510 # XXX The following don't test module-level functionality...
1511
1512 def testSockName(self):
1513 # Testing getsockname()
1514 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1515 self.addCleanup(sock.close)
1516
1517 # Since find_unused_port() is inherently subject to race conditions, we
1518 # call it a couple times if necessary.
1519 for i in itertools.count():
1520 port = socket_helper.find_unused_port()
1521 try:
1522 sock.bind(("0.0.0.0", port))
1523 except OSError as e:
1524 if e.errno != errno.EADDRINUSE or i == 5:
1525 raise
1526 else:
1527 break
1528
1529 name = sock.getsockname()
1530 # XXX(nnorwitz): http://tinyurl.com/os5jz seems to indicate
1531 # it reasonable to get the host's addr in addition to 0.0.0.0.
1532 # At least for eCos. This is required for the S/390 to pass.
1533 try:
1534 my_ip_addr = socket.gethostbyname(socket.gethostname())
1535 except OSError:
1536 # Probably name lookup wasn't set up right; skip this test
1537 self.skipTest('name lookup failure')
1538 self.assertIn(name[0], ("0.0.0.0", my_ip_addr), '%s invalid' % name[0])
1539 self.assertEqual(name[1], port)
1540
1541 def testGetSockOpt(self):
1542 # Testing getsockopt()
1543 # We know a socket should start without reuse==0
1544 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1545 self.addCleanup(sock.close)
1546 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
1547 self.assertFalse(reuse != 0, "initial mode is reuse")
1548
1549 def testSetSockOpt(self):
1550 # Testing setsockopt()
1551 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1552 self.addCleanup(sock.close)
1553 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1554 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
1555 self.assertFalse(reuse == 0, "failed to set reuse mode")
1556
1557 def testSendAfterClose(self):
1558 # testing send() after close() with timeout
1559 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
1560 sock.settimeout(1)
1561 self.assertRaises(OSError, sock.send, b"spam")
1562
1563 def testCloseException(self):
1564 sock = socket.socket()
1565 sock.bind((socket._LOCALHOST, 0))
1566 socket.socket(fileno=sock.fileno()).close()
1567 try:
1568 sock.close()
1569 except OSError as err:
1570 # Winsock apparently raises ENOTSOCK
1571 self.assertIn(err.errno, (errno.EBADF, errno.ENOTSOCK))
1572 else:
1573 self.fail("close() should raise EBADF/ENOTSOCK")
1574
1575 def testNewAttributes(self):
1576 # testing .family, .type and .protocol
1577
1578 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
1579 self.assertEqual(sock.family, socket.AF_INET)
1580 if hasattr(socket, 'SOCK_CLOEXEC'):
1581 self.assertIn(sock.type,
1582 (socket.SOCK_STREAM | socket.SOCK_CLOEXEC,
1583 socket.SOCK_STREAM))
1584 else:
1585 self.assertEqual(sock.type, socket.SOCK_STREAM)
1586 self.assertEqual(sock.proto, 0)
1587
1588 def test_getsockaddrarg(self):
1589 sock = socket.socket()
1590 self.addCleanup(sock.close)
1591 port = socket_helper.find_unused_port()
1592 big_port = port + 65536
1593 neg_port = port - 65536
1594 self.assertRaises(OverflowError, sock.bind, (HOST, big_port))
1595 self.assertRaises(OverflowError, sock.bind, (HOST, neg_port))
1596 # Since find_unused_port() is inherently subject to race conditions, we
1597 # call it a couple times if necessary.
1598 for i in itertools.count():
1599 port = socket_helper.find_unused_port()
1600 try:
1601 sock.bind((HOST, port))
1602 except OSError as e:
1603 if e.errno != errno.EADDRINUSE or i == 5:
1604 raise
1605 else:
1606 break
1607
1608 @unittest.skipUnless(os.name == "nt", "Windows specific")
1609 def test_sock_ioctl(self):
1610 self.assertHasAttr(socket.socket, 'ioctl')
1611 self.assertHasAttr(socket, 'SIO_RCVALL')
1612 self.assertHasAttr(socket, 'RCVALL_ON')
1613 self.assertHasAttr(socket, 'RCVALL_OFF')
1614 self.assertHasAttr(socket, 'SIO_KEEPALIVE_VALS')
1615 s = socket.socket()
1616 self.addCleanup(s.close)
1617 self.assertRaises(ValueError, s.ioctl, -1, None)
1618 s.ioctl(socket.SIO_KEEPALIVE_VALS, (1, 100, 100))
1619
1620 @unittest.skipUnless(os.name == "nt", "Windows specific")
1621 @unittest.skipUnless(hasattr(socket, 'SIO_LOOPBACK_FAST_PATH'),
1622 'Loopback fast path support required for this test')
1623 def test_sio_loopback_fast_path(self):
1624 s = socket.socket()
1625 self.addCleanup(s.close)
1626 try:
1627 s.ioctl(socket.SIO_LOOPBACK_FAST_PATH, True)
1628 except OSError as exc:
1629 WSAEOPNOTSUPP = 10045
1630 if exc.winerror == WSAEOPNOTSUPP:
1631 self.skipTest("SIO_LOOPBACK_FAST_PATH is defined but "
1632 "doesn't implemented in this Windows version")
1633 raise
1634 self.assertRaises(TypeError, s.ioctl, socket.SIO_LOOPBACK_FAST_PATH, None)
1635
1636 def testGetaddrinfo(self):
1637 try:
1638 socket.getaddrinfo('localhost', 80)
1639 except socket.gaierror as err:
1640 if err.errno == socket.EAI_SERVICE:
1641 # see http://bugs.python.org/issue1282647
1642 self.skipTest("buggy libc version")
1643 raise
1644 # len of every sequence is supposed to be == 5
1645 for info in socket.getaddrinfo(HOST, None):
1646 self.assertEqual(len(info), 5)
1647 # host can be a domain name, a string representation of an
1648 # IPv4/v6 address or None
1649 socket.getaddrinfo('localhost', 80)
1650 socket.getaddrinfo('127.0.0.1', 80)
1651 socket.getaddrinfo(None, 80)
1652 if socket_helper.IPV6_ENABLED:
1653 socket.getaddrinfo('::1', 80)
1654 # port can be a string service name such as "http", a numeric
1655 # port number or None
1656 # Issue #26936: this fails on Android before API level 23.
1657 if not (support.is_android and platform.android_ver().api_level < 23):
1658 socket.getaddrinfo(HOST, "http")
1659 socket.getaddrinfo(HOST, 80)
1660 socket.getaddrinfo(HOST, None)
1661 # test family and socktype filters
1662 infos = socket.getaddrinfo(HOST, 80, socket.AF_INET, socket.SOCK_STREAM)
1663 for family, type, _, _, _ in infos:
1664 self.assertEqual(family, socket.AF_INET)
1665 self.assertEqual(repr(family), '<AddressFamily.AF_INET: %r>' % family.value)
1666 self.assertEqual(str(family), str(family.value))
1667 self.assertEqual(type, socket.SOCK_STREAM)
1668 self.assertEqual(repr(type), '<SocketKind.SOCK_STREAM: %r>' % type.value)
1669 self.assertEqual(str(type), str(type.value))
1670 infos = socket.getaddrinfo(HOST, None, 0, socket.SOCK_STREAM)
1671 for _, socktype, _, _, _ in infos:
1672 self.assertEqual(socktype, socket.SOCK_STREAM)
1673 # test proto and flags arguments
1674 socket.getaddrinfo(HOST, None, 0, 0, socket.SOL_TCP)
1675 socket.getaddrinfo(HOST, None, 0, 0, 0, socket.AI_PASSIVE)
1676 # a server willing to support both IPv4 and IPv6 will
1677 # usually do this
1678 socket.getaddrinfo(None, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0,
1679 socket.AI_PASSIVE)
1680 # test keyword arguments
1681 a = socket.getaddrinfo(HOST, None)
1682 b = socket.getaddrinfo(host=HOST, port=None)
1683 self.assertEqual(a, b)
1684 a = socket.getaddrinfo(HOST, None, socket.AF_INET)
1685 b = socket.getaddrinfo(HOST, None, family=socket.AF_INET)
1686 self.assertEqual(a, b)
1687 a = socket.getaddrinfo(HOST, None, 0, socket.SOCK_STREAM)
1688 b = socket.getaddrinfo(HOST, None, type=socket.SOCK_STREAM)
1689 self.assertEqual(a, b)
1690 a = socket.getaddrinfo(HOST, None, 0, 0, socket.SOL_TCP)
1691 b = socket.getaddrinfo(HOST, None, proto=socket.SOL_TCP)
1692 self.assertEqual(a, b)
1693 a = socket.getaddrinfo(HOST, None, 0, 0, 0, socket.AI_PASSIVE)
1694 b = socket.getaddrinfo(HOST, None, flags=socket.AI_PASSIVE)
1695 self.assertEqual(a, b)
1696 a = socket.getaddrinfo(None, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0,
1697 socket.AI_PASSIVE)
1698 b = socket.getaddrinfo(host=None, port=0, family=socket.AF_UNSPEC,
1699 type=socket.SOCK_STREAM, proto=0,
1700 flags=socket.AI_PASSIVE)
1701 self.assertEqual(a, b)
1702 # Issue #6697.
1703 self.assertRaises(UnicodeEncodeError, socket.getaddrinfo, 'localhost', '\uD800')
1704
1705 if hasattr(socket, 'AI_NUMERICSERV'):
1706 self.assertRaises(socket.gaierror, socket.getaddrinfo, "localhost", "http",
1707 flags=socket.AI_NUMERICSERV)
1708
1709 # Issue 17269: test workaround for OS X platform bug segfault
1710 try:
1711 # The arguments here are undefined and the call may succeed
1712 # or fail. All we care here is that it doesn't segfault.
1713 socket.getaddrinfo("localhost", None, 0, 0, 0,
1714 socket.AI_NUMERICSERV)
1715 except socket.gaierror:
1716 pass
1717
1718 @unittest.skipIf(_testcapi is None, "requires _testcapi")
1719 def test_getaddrinfo_int_port_overflow(self):
1720 # gh-74895: Test that getaddrinfo does not raise OverflowError on port.
1721 #
1722 # POSIX getaddrinfo() never specify the valid range for "service"
1723 # decimal port number values. For IPv4 and IPv6 they are technically
1724 # unsigned 16-bit values, but the API is protocol agnostic. Which values
1725 # trigger an error from the C library function varies by platform as
1726 # they do not all perform validation.
1727
1728 # The key here is that we don't want to produce OverflowError as Python
1729 # prior to 3.12 did for ints outside of a [LONG_MIN, LONG_MAX] range.
1730 # Leave the error up to the underlying string based platform C API.
1731
1732 from _testcapi import ULONG_MAX, LONG_MAX, LONG_MIN
1733 try:
1734 socket.getaddrinfo(None, ULONG_MAX + 1, type=socket.SOCK_STREAM)
1735 except OverflowError:
1736 # Platforms differ as to what values constitute a getaddrinfo() error
1737 # return. Some fail for LONG_MAX+1, others ULONG_MAX+1, and Windows
1738 # silently accepts such huge "port" aka "service" numeric values.
1739 self.fail("Either no error or socket.gaierror expected.")
1740 except socket.gaierror:
1741 pass
1742
1743 try:
1744 socket.getaddrinfo(None, LONG_MAX + 1, type=socket.SOCK_STREAM)
1745 except OverflowError:
1746 self.fail("Either no error or socket.gaierror expected.")
1747 except socket.gaierror:
1748 pass
1749
1750 try:
1751 socket.getaddrinfo(None, LONG_MAX - 0xffff + 1, type=socket.SOCK_STREAM)
1752 except OverflowError:
1753 self.fail("Either no error or socket.gaierror expected.")
1754 except socket.gaierror:
1755 pass
1756
1757 try:
1758 socket.getaddrinfo(None, LONG_MIN - 1, type=socket.SOCK_STREAM)
1759 except OverflowError:
1760 self.fail("Either no error or socket.gaierror expected.")
1761 except socket.gaierror:
1762 pass
1763
1764 socket.getaddrinfo(None, 0, type=socket.SOCK_STREAM) # No error expected.
1765 socket.getaddrinfo(None, 0xffff, type=socket.SOCK_STREAM) # No error expected.
1766
1767 def test_getnameinfo(self):
1768 # only IP addresses are allowed
1769 self.assertRaises(OSError, socket.getnameinfo, ('mail.python.org',0), 0)
1770
1771 @unittest.skipUnless(support.is_resource_enabled('network'),
1772 'network is not enabled')
1773 def test_idna(self):
1774 # Check for internet access before running test
1775 # (issue #12804, issue #25138).
1776 with socket_helper.transient_internet('python.org'):
1777 socket.gethostbyname('python.org')
1778
1779 # these should all be successful
1780 domain = 'испытание.pythontest.net'
1781 socket.gethostbyname(domain)
1782 socket.gethostbyname_ex(domain)
1783 socket.getaddrinfo(domain,0,socket.AF_UNSPEC,socket.SOCK_STREAM)
1784 # this may not work if the forward lookup chooses the IPv6 address, as that doesn't
1785 # have a reverse entry yet
1786 # socket.gethostbyaddr('испытание.python.org')
1787
1788 def check_sendall_interrupted(self, with_timeout):
1789 # socketpair() is not strictly required, but it makes things easier.
1790 if not hasattr(signal, 'alarm') or not hasattr(socket, 'socketpair'):
1791 self.skipTest("signal.alarm and socket.socketpair required for this test")
1792 # Our signal handlers clobber the C errno by calling a math function
1793 # with an invalid domain value.
1794 def ok_handler(*args):
1795 self.assertRaises(ValueError, math.acosh, 0)
1796 def raising_handler(*args):
1797 self.assertRaises(ValueError, math.acosh, 0)
1798 1 // 0
1799 c, s = socket.socketpair()
1800 old_alarm = signal.signal(signal.SIGALRM, raising_handler)
1801 try:
1802 if with_timeout:
1803 # Just above the one second minimum for signal.alarm
1804 c.settimeout(1.5)
1805 with self.assertRaises(ZeroDivisionError):
1806 signal.alarm(1)
1807 c.sendall(b"x" * support.SOCK_MAX_SIZE)
1808 if with_timeout:
1809 signal.signal(signal.SIGALRM, ok_handler)
1810 signal.alarm(1)
1811 self.assertRaises(TimeoutError, c.sendall,
1812 b"x" * support.SOCK_MAX_SIZE)
1813 finally:
1814 signal.alarm(0)
1815 signal.signal(signal.SIGALRM, old_alarm)
1816 c.close()
1817 s.close()
1818
1819 def test_sendall_interrupted(self):
1820 self.check_sendall_interrupted(False)
1821
1822 def test_sendall_interrupted_with_timeout(self):
1823 self.check_sendall_interrupted(True)
1824
1825 def test_dealloc_warn(self):
1826 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1827 r = repr(sock)
1828 with self.assertWarns(ResourceWarning) as cm:
1829 sock = None
1830 support.gc_collect()
1831 self.assertIn(r, str(cm.warning.args[0]))
1832 # An open socket file object gets dereferenced after the socket
1833 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1834 f = sock.makefile('rb')
1835 r = repr(sock)
1836 sock = None
1837 support.gc_collect()
1838 with self.assertWarns(ResourceWarning):
1839 f = None
1840 support.gc_collect()
1841
1842 def test_name_closed_socketio(self):
1843 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
1844 fp = sock.makefile("rb")
1845 fp.close()
1846 self.assertEqual(repr(fp), "<_io.BufferedReader name=-1>")
1847
1848 def test_unusable_closed_socketio(self):
1849 with socket.socket() as sock:
1850 fp = sock.makefile("rb", buffering=0)
1851 self.assertTrue(fp.readable())
1852 self.assertFalse(fp.writable())
1853 self.assertFalse(fp.seekable())
1854 fp.close()
1855 self.assertRaises(ValueError, fp.readable)
1856 self.assertRaises(ValueError, fp.writable)
1857 self.assertRaises(ValueError, fp.seekable)
1858
1859 def test_socket_close(self):
1860 sock = socket.socket()
1861 try:
1862 sock.bind((HOST, 0))
1863 socket.close(sock.fileno())
1864 with self.assertRaises(OSError):
1865 sock.listen(1)
1866 finally:
1867 with self.assertRaises(OSError):
1868 # sock.close() fails with EBADF
1869 sock.close()
1870 with self.assertRaises(TypeError):
1871 socket.close(None)
1872 with self.assertRaises(OSError):
1873 socket.close(-1)
1874
1875 def test_makefile_mode(self):
1876 for mode in 'r', 'rb', 'rw', 'w', 'wb':
1877 with self.subTest(mode=mode):
1878 with socket.socket() as sock:
1879 encoding = None if "b" in mode else "utf-8"
1880 with sock.makefile(mode, encoding=encoding) as fp:
1881 self.assertEqual(fp.mode, mode)
1882
1883 def test_makefile_invalid_mode(self):
1884 for mode in 'rt', 'x', '+', 'a':
1885 with self.subTest(mode=mode):
1886 with socket.socket() as sock:
1887 with self.assertRaisesRegex(ValueError, 'invalid mode'):
1888 sock.makefile(mode)
1889
1890 def test_pickle(self):
1891 sock = socket.socket()
1892 with sock:
1893 for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
1894 self.assertRaises(TypeError, pickle.dumps, sock, protocol)
1895 for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
1896 family = pickle.loads(pickle.dumps(socket.AF_INET, protocol))
1897 self.assertEqual(family, socket.AF_INET)
1898 type = pickle.loads(pickle.dumps(socket.SOCK_STREAM, protocol))
1899 self.assertEqual(type, socket.SOCK_STREAM)
1900
1901 def test_listen_backlog(self):
1902 for backlog in 0, -1:
1903 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as srv:
1904 srv.bind((HOST, 0))
1905 srv.listen(backlog)
1906
1907 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as srv:
1908 srv.bind((HOST, 0))
1909 srv.listen()
1910
1911 @support.cpython_only
1912 @unittest.skipIf(_testcapi is None, "requires _testcapi")
1913 def test_listen_backlog_overflow(self):
1914 # Issue 15989
1915 import _testcapi
1916 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as srv:
1917 srv.bind((HOST, 0))
1918 self.assertRaises(OverflowError, srv.listen, _testcapi.INT_MAX + 1)
1919
1920 @unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.')
1921 def test_flowinfo(self):
1922 self.assertRaises(OverflowError, socket.getnameinfo,
1923 (socket_helper.HOSTv6, 0, 0xffffffff), 0)
1924 with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s:
1925 self.assertRaises(OverflowError, s.bind, (socket_helper.HOSTv6, 0, -10))
1926
1927 @unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.')
1928 def test_getaddrinfo_ipv6_basic(self):
1929 ((*_, sockaddr),) = socket.getaddrinfo(
1930 'ff02::1de:c0:face:8D', # Note capital letter `D`.
1931 1234, socket.AF_INET6,
1932 socket.SOCK_DGRAM,
1933 socket.IPPROTO_UDP
1934 )
1935 self.assertEqual(sockaddr, ('ff02::1de:c0:face:8d', 1234, 0, 0))
1936
1937 def test_getfqdn_filter_localhost(self):
1938 self.assertEqual(socket.getfqdn(), socket.getfqdn("0.0.0.0"))
1939 self.assertEqual(socket.getfqdn(), socket.getfqdn("::"))
1940
1941 @unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.')
1942 @unittest.skipIf(sys.platform == 'win32', 'does not work on Windows')
1943 @unittest.skipIf(AIX, 'Symbolic scope id does not work')
1944 @unittest.skipUnless(hasattr(socket, 'if_nameindex'), "test needs socket.if_nameindex()")
1945 @support.skip_android_selinux('if_nameindex')
1946 def test_getaddrinfo_ipv6_scopeid_symbolic(self):
1947 # Just pick up any network interface (Linux, Mac OS X)
1948 (ifindex, test_interface) = socket.if_nameindex()[0]
1949 ((*_, sockaddr),) = socket.getaddrinfo(
1950 'ff02::1de:c0:face:8D%' + test_interface,
1951 1234, socket.AF_INET6,
1952 socket.SOCK_DGRAM,
1953 socket.IPPROTO_UDP
1954 )
1955 # Note missing interface name part in IPv6 address
1956 self.assertEqual(sockaddr, ('ff02::1de:c0:face:8d', 1234, 0, ifindex))
1957
1958 @unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.')
1959 @unittest.skipUnless(
1960 sys.platform == 'win32',
1961 'Numeric scope id does not work or undocumented')
1962 def test_getaddrinfo_ipv6_scopeid_numeric(self):
1963 # Also works on Linux and Mac OS X, but is not documented (?)
1964 # Windows, Linux and Max OS X allow nonexistent interface numbers here.
1965 ifindex = 42
1966 ((*_, sockaddr),) = socket.getaddrinfo(
1967 'ff02::1de:c0:face:8D%' + str(ifindex),
1968 1234, socket.AF_INET6,
1969 socket.SOCK_DGRAM,
1970 socket.IPPROTO_UDP
1971 )
1972 # Note missing interface name part in IPv6 address
1973 self.assertEqual(sockaddr, ('ff02::1de:c0:face:8d', 1234, 0, ifindex))
1974
1975 @unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.')
1976 @unittest.skipIf(sys.platform == 'win32', 'does not work on Windows')
1977 @unittest.skipIf(AIX, 'Symbolic scope id does not work')
1978 @unittest.skipUnless(hasattr(socket, 'if_nameindex'), "test needs socket.if_nameindex()")
1979 @support.skip_android_selinux('if_nameindex')
1980 def test_getnameinfo_ipv6_scopeid_symbolic(self):
1981 # Just pick up any network interface.
1982 (ifindex, test_interface) = socket.if_nameindex()[0]
1983 sockaddr = ('ff02::1de:c0:face:8D', 1234, 0, ifindex) # Note capital letter `D`.
1984 nameinfo = socket.getnameinfo(sockaddr, socket.NI_NUMERICHOST | socket.NI_NUMERICSERV)
1985 self.assertEqual(nameinfo, ('ff02::1de:c0:face:8d%' + test_interface, '1234'))
1986
1987 @unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.')
1988 @unittest.skipUnless( sys.platform == 'win32',
1989 'Numeric scope id does not work or undocumented')
1990 def test_getnameinfo_ipv6_scopeid_numeric(self):
1991 # Also works on Linux (undocumented), but does not work on Mac OS X
1992 # Windows and Linux allow nonexistent interface numbers here.
1993 ifindex = 42
1994 sockaddr = ('ff02::1de:c0:face:8D', 1234, 0, ifindex) # Note capital letter `D`.
1995 nameinfo = socket.getnameinfo(sockaddr, socket.NI_NUMERICHOST | socket.NI_NUMERICSERV)
1996 self.assertEqual(nameinfo, ('ff02::1de:c0:face:8d%' + str(ifindex), '1234'))
1997
1998 def test_str_for_enums(self):
1999 # Make sure that the AF_* and SOCK_* constants have enum-like string
2000 # reprs.
2001 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
2002 self.assertEqual(repr(s.family), '<AddressFamily.AF_INET: %r>' % s.family.value)
2003 self.assertEqual(repr(s.type), '<SocketKind.SOCK_STREAM: %r>' % s.type.value)
2004 self.assertEqual(str(s.family), str(s.family.value))
2005 self.assertEqual(str(s.type), str(s.type.value))
2006
2007 def test_socket_consistent_sock_type(self):
2008 SOCK_NONBLOCK = getattr(socket, 'SOCK_NONBLOCK', 0)
2009 SOCK_CLOEXEC = getattr(socket, 'SOCK_CLOEXEC', 0)
2010 sock_type = socket.SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC
2011
2012 with socket.socket(socket.AF_INET, sock_type) as s:
2013 self.assertEqual(s.type, socket.SOCK_STREAM)
2014 s.settimeout(1)
2015 self.assertEqual(s.type, socket.SOCK_STREAM)
2016 s.settimeout(0)
2017 self.assertEqual(s.type, socket.SOCK_STREAM)
2018 s.setblocking(True)
2019 self.assertEqual(s.type, socket.SOCK_STREAM)
2020 s.setblocking(False)
2021 self.assertEqual(s.type, socket.SOCK_STREAM)
2022
2023 def test_unknown_socket_family_repr(self):
2024 # Test that when created with a family that's not one of the known
2025 # AF_*/SOCK_* constants, socket.family just returns the number.
2026 #
2027 # To do this we fool socket.socket into believing it already has an
2028 # open fd because on this path it doesn't actually verify the family and
2029 # type and populates the socket object.
2030 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
2031 fd = sock.detach()
2032 unknown_family = max(socket.AddressFamily.__members__.values()) + 1
2033
2034 unknown_type = max(
2035 kind
2036 for name, kind in socket.SocketKind.__members__.items()
2037 if name not in {'SOCK_NONBLOCK', 'SOCK_CLOEXEC'}
2038 ) + 1
2039
2040 with socket.socket(
2041 family=unknown_family, type=unknown_type, proto=23,
2042 fileno=fd) as s:
2043 self.assertEqual(s.family, unknown_family)
2044 self.assertEqual(s.type, unknown_type)
2045 # some OS like macOS ignore proto
2046 self.assertIn(s.proto, {0, 23})
2047
2048 @unittest.skipUnless(hasattr(os, 'sendfile'), 'test needs os.sendfile()')
2049 def test__sendfile_use_sendfile(self):
2050 class File:
2051 def __init__(self, fd):
2052 self.fd = fd
2053
2054 def fileno(self):
2055 return self.fd
2056 with socket.socket() as sock:
2057 fd = os.open(os.curdir, os.O_RDONLY)
2058 os.close(fd)
2059 with self.assertRaises(socket._GiveupOnSendfile):
2060 sock._sendfile_use_sendfile(File(fd))
2061 with self.assertRaises(OverflowError):
2062 sock._sendfile_use_sendfile(File(2**1000))
2063 with self.assertRaises(TypeError):
2064 sock._sendfile_use_sendfile(File(None))
2065
2066 def _test_socket_fileno(self, s, family, stype):
2067 self.assertEqual(s.family, family)
2068 self.assertEqual(s.type, stype)
2069
2070 fd = s.fileno()
2071 s2 = socket.socket(fileno=fd)
2072 self.addCleanup(s2.close)
2073 # detach old fd to avoid double close
2074 s.detach()
2075 self.assertEqual(s2.family, family)
2076 self.assertEqual(s2.type, stype)
2077 self.assertEqual(s2.fileno(), fd)
2078
2079 def test_socket_fileno(self):
2080 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
2081 self.addCleanup(s.close)
2082 s.bind((socket_helper.HOST, 0))
2083 self._test_socket_fileno(s, socket.AF_INET, socket.SOCK_STREAM)
2084
2085 if hasattr(socket, "SOCK_DGRAM"):
2086 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
2087 self.addCleanup(s.close)
2088 s.bind((socket_helper.HOST, 0))
2089 self._test_socket_fileno(s, socket.AF_INET, socket.SOCK_DGRAM)
2090
2091 if socket_helper.IPV6_ENABLED:
2092 s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
2093 self.addCleanup(s.close)
2094 s.bind((socket_helper.HOSTv6, 0, 0, 0))
2095 self._test_socket_fileno(s, socket.AF_INET6, socket.SOCK_STREAM)
2096
2097 if hasattr(socket, "AF_UNIX"):
2098 unix_name = socket_helper.create_unix_domain_name()
2099 self.addCleanup(os_helper.unlink, unix_name)
2100
2101 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
2102 with s:
2103 try:
2104 s.bind(unix_name)
2105 except PermissionError:
2106 pass
2107 else:
2108 self._test_socket_fileno(s, socket.AF_UNIX,
2109 socket.SOCK_STREAM)
2110
2111 def test_socket_fileno_rejects_float(self):
2112 with self.assertRaises(TypeError):
2113 socket.socket(socket.AF_INET, socket.SOCK_STREAM, fileno=42.5)
2114
2115 def test_socket_fileno_rejects_other_types(self):
2116 with self.assertRaises(TypeError):
2117 socket.socket(socket.AF_INET, socket.SOCK_STREAM, fileno="foo")
2118
2119 def test_socket_fileno_rejects_invalid_socket(self):
2120 with self.assertRaisesRegex(ValueError, "negative file descriptor"):
2121 socket.socket(socket.AF_INET, socket.SOCK_STREAM, fileno=-1)
2122
2123 @unittest.skipIf(os.name == "nt", "Windows disallows -1 only")
2124 def test_socket_fileno_rejects_negative(self):
2125 with self.assertRaisesRegex(ValueError, "negative file descriptor"):
2126 socket.socket(socket.AF_INET, socket.SOCK_STREAM, fileno=-42)
2127
2128 def test_socket_fileno_requires_valid_fd(self):
2129 WSAENOTSOCK = 10038
2130 with self.assertRaises(OSError) as cm:
2131 socket.socket(fileno=os_helper.make_bad_fd())
2132 self.assertIn(cm.exception.errno, (errno.EBADF, WSAENOTSOCK))
2133
2134 with self.assertRaises(OSError) as cm:
2135 socket.socket(
2136 socket.AF_INET,
2137 socket.SOCK_STREAM,
2138 fileno=os_helper.make_bad_fd())
2139 self.assertIn(cm.exception.errno, (errno.EBADF, WSAENOTSOCK))
2140
2141 def test_socket_fileno_requires_socket_fd(self):
2142 with tempfile.NamedTemporaryFile() as afile:
2143 with self.assertRaises(OSError):
2144 socket.socket(fileno=afile.fileno())
2145
2146 with self.assertRaises(OSError) as cm:
2147 socket.socket(
2148 socket.AF_INET,
2149 socket.SOCK_STREAM,
2150 fileno=afile.fileno())
2151 self.assertEqual(cm.exception.errno, errno.ENOTSOCK)
2152
2153 def test_addressfamily_enum(self):
2154 import _socket, enum
2155 CheckedAddressFamily = enum._old_convert_(
2156 enum.IntEnum, 'AddressFamily', 'socket',
2157 lambda C: C.isupper() and C.startswith('AF_'),
2158 source=_socket,
2159 )
2160 enum._test_simple_enum(CheckedAddressFamily, socket.AddressFamily)
2161
2162 def test_socketkind_enum(self):
2163 import _socket, enum
2164 CheckedSocketKind = enum._old_convert_(
2165 enum.IntEnum, 'SocketKind', 'socket',
2166 lambda C: C.isupper() and C.startswith('SOCK_'),
2167 source=_socket,
2168 )
2169 enum._test_simple_enum(CheckedSocketKind, socket.SocketKind)
2170
2171 def test_msgflag_enum(self):
2172 import _socket, enum
2173 CheckedMsgFlag = enum._old_convert_(
2174 enum.IntFlag, 'MsgFlag', 'socket',
2175 lambda C: C.isupper() and C.startswith('MSG_'),
2176 source=_socket,
2177 )
2178 enum._test_simple_enum(CheckedMsgFlag, socket.MsgFlag)
2179
2180 def test_addressinfo_enum(self):
2181 import _socket, enum
2182 CheckedAddressInfo = enum._old_convert_(
2183 enum.IntFlag, 'AddressInfo', 'socket',
2184 lambda C: C.isupper() and C.startswith('AI_'),
2185 source=_socket)
2186 enum._test_simple_enum(CheckedAddressInfo, socket.AddressInfo)
2187
2188 @unittest.skipUnless(hasattr(socket.socket, "sendmsg"),"sendmsg not supported")
2189 def test_sendmsg_reentrant_ancillary_mutation(self):
2190
2191 class Mut:
2192 def __index__(self):
2193 seq.clear()
2194 return socket.SCM_RIGHTS
2195
2196 seq = [
2197 (socket.SOL_SOCKET, Mut(), b'xxxx'),
2198 (socket.SOL_SOCKET, socket.SCM_RIGHTS, b'xxxx'),
2199 ]
2200
2201 left, right = socket.socketpair()
2202 self.addCleanup(left.close)
2203 self.addCleanup(right.close)
2204 self.assertRaises(OSError, left.sendmsg, [b'x'], seq)
2205
2206
2207 @unittest.skipUnless(HAVE_SOCKET_CAN, 'SocketCan required for this test.')
2208 class BasicCANTest(unittest.TestCase):
2209
2210 def testCrucialConstants(self):
2211 socket.AF_CAN
2212 socket.PF_CAN
2213 socket.CAN_RAW
2214
2215 @unittest.skipUnless(hasattr(socket, "CAN_BCM"),
2216 'socket.CAN_BCM required for this test.')
2217 def testBCMConstants(self):
2218 socket.CAN_BCM
2219
2220 # opcodes
2221 socket.CAN_BCM_TX_SETUP # create (cyclic) transmission task
2222 socket.CAN_BCM_TX_DELETE # remove (cyclic) transmission task
2223 socket.CAN_BCM_TX_READ # read properties of (cyclic) transmission task
2224 socket.CAN_BCM_TX_SEND # send one CAN frame
2225 socket.CAN_BCM_RX_SETUP # create RX content filter subscription
2226 socket.CAN_BCM_RX_DELETE # remove RX content filter subscription
2227 socket.CAN_BCM_RX_READ # read properties of RX content filter subscription
2228 socket.CAN_BCM_TX_STATUS # reply to TX_READ request
2229 socket.CAN_BCM_TX_EXPIRED # notification on performed transmissions (count=0)
2230 socket.CAN_BCM_RX_STATUS # reply to RX_READ request
2231 socket.CAN_BCM_RX_TIMEOUT # cyclic message is absent
2232 socket.CAN_BCM_RX_CHANGED # updated CAN frame (detected content change)
2233
2234 # flags
2235 socket.CAN_BCM_SETTIMER
2236 socket.CAN_BCM_STARTTIMER
2237 socket.CAN_BCM_TX_COUNTEVT
2238 socket.CAN_BCM_TX_ANNOUNCE
2239 socket.CAN_BCM_TX_CP_CAN_ID
2240 socket.CAN_BCM_RX_FILTER_ID
2241 socket.CAN_BCM_RX_CHECK_DLC
2242 socket.CAN_BCM_RX_NO_AUTOTIMER
2243 socket.CAN_BCM_RX_ANNOUNCE_RESUME
2244 socket.CAN_BCM_TX_RESET_MULTI_IDX
2245 socket.CAN_BCM_RX_RTR_FRAME
2246
2247 def testCreateSocket(self):
2248 with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
2249 pass
2250
2251 @unittest.skipUnless(hasattr(socket, "CAN_BCM"),
2252 'socket.CAN_BCM required for this test.')
2253 def testCreateBCMSocket(self):
2254 with socket.socket(socket.PF_CAN, socket.SOCK_DGRAM, socket.CAN_BCM) as s:
2255 pass
2256
2257 def testBindAny(self):
2258 with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
2259 address = ('', )
2260 s.bind(address)
2261 self.assertEqual(s.getsockname(), address)
2262
2263 def testTooLongInterfaceName(self):
2264 # most systems limit IFNAMSIZ to 16, take 1024 to be sure
2265 with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
2266 self.assertRaisesRegex(OSError, 'interface name too long',
2267 s.bind, ('x' * 1024,))
2268
2269 @unittest.skipUnless(hasattr(socket, "CAN_RAW_LOOPBACK"),
2270 'socket.CAN_RAW_LOOPBACK required for this test.')
2271 def testLoopback(self):
2272 with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
2273 for loopback in (0, 1):
2274 s.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_LOOPBACK,
2275 loopback)
2276 self.assertEqual(loopback,
2277 s.getsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_LOOPBACK))
2278
2279 @unittest.skipUnless(hasattr(socket, "CAN_RAW_FILTER"),
2280 'socket.CAN_RAW_FILTER required for this test.')
2281 def testFilter(self):
2282 can_id, can_mask = 0x200, 0x700
2283 can_filter = struct.pack("=II", can_id, can_mask)
2284 with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
2285 s.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_FILTER, can_filter)
2286 self.assertEqual(can_filter,
2287 s.getsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_FILTER, 8))
2288 s.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_FILTER, bytearray(can_filter))
2289
2290
2291 @unittest.skipUnless(HAVE_SOCKET_CAN, 'SocketCan required for this test.')
2292 class CANTest(ThreadedCANSocketTest):
2293
2294 def __init__(self, methodName='runTest'):
2295 ThreadedCANSocketTest.__init__(self, methodName=methodName)
2296
2297 @classmethod
2298 def build_can_frame(cls, can_id, data):
2299 """Build a CAN frame."""
2300 can_dlc = len(data)
2301 data = data.ljust(8, b'\x00')
2302 return struct.pack(cls.can_frame_fmt, can_id, can_dlc, data)
2303
2304 @classmethod
2305 def dissect_can_frame(cls, frame):
2306 """Dissect a CAN frame."""
2307 can_id, can_dlc, data = struct.unpack(cls.can_frame_fmt, frame)
2308 return (can_id, can_dlc, data[:can_dlc])
2309
2310 def testSendFrame(self):
2311 cf, addr = self.s.recvfrom(self.bufsize)
2312 self.assertEqual(self.cf, cf)
2313 self.assertEqual(addr[0], self.interface)
2314
2315 def _testSendFrame(self):
2316 self.cf = self.build_can_frame(0x00, b'\x01\x02\x03\x04\x05')
2317 self.cli.send(self.cf)
2318
2319 def testSendMaxFrame(self):
2320 cf, addr = self.s.recvfrom(self.bufsize)
2321 self.assertEqual(self.cf, cf)
2322
2323 def _testSendMaxFrame(self):
2324 self.cf = self.build_can_frame(0x00, b'\x07' * 8)
2325 self.cli.send(self.cf)
2326
2327 def testSendMultiFrames(self):
2328 cf, addr = self.s.recvfrom(self.bufsize)
2329 self.assertEqual(self.cf1, cf)
2330
2331 cf, addr = self.s.recvfrom(self.bufsize)
2332 self.assertEqual(self.cf2, cf)
2333
2334 def _testSendMultiFrames(self):
2335 self.cf1 = self.build_can_frame(0x07, b'\x44\x33\x22\x11')
2336 self.cli.send(self.cf1)
2337
2338 self.cf2 = self.build_can_frame(0x12, b'\x99\x22\x33')
2339 self.cli.send(self.cf2)
2340
2341 @unittest.skipUnless(hasattr(socket, "CAN_BCM"),
2342 'socket.CAN_BCM required for this test.')
2343 def _testBCM(self):
2344 cf, addr = self.cli.recvfrom(self.bufsize)
2345 self.assertEqual(self.cf, cf)
2346 can_id, can_dlc, data = self.dissect_can_frame(cf)
2347 self.assertEqual(self.can_id, can_id)
2348 self.assertEqual(self.data, data)
2349
2350 @unittest.skipUnless(hasattr(socket, "CAN_BCM"),
2351 'socket.CAN_BCM required for this test.')
2352 def testBCM(self):
2353 bcm = socket.socket(socket.PF_CAN, socket.SOCK_DGRAM, socket.CAN_BCM)
2354 self.addCleanup(bcm.close)
2355 bcm.connect((self.interface,))
2356 self.can_id = 0x123
2357 self.data = bytes([0xc0, 0xff, 0xee])
2358 self.cf = self.build_can_frame(self.can_id, self.data)
2359 opcode = socket.CAN_BCM_TX_SEND
2360 flags = 0
2361 count = 0
2362 ival1_seconds = ival1_usec = ival2_seconds = ival2_usec = 0
2363 bcm_can_id = 0x0222
2364 nframes = 1
2365 assert len(self.cf) == 16
2366 header = struct.pack(self.bcm_cmd_msg_fmt,
2367 opcode,
2368 flags,
2369 count,
2370 ival1_seconds,
2371 ival1_usec,
2372 ival2_seconds,
2373 ival2_usec,
2374 bcm_can_id,
2375 nframes,
2376 )
2377 header_plus_frame = header + self.cf
2378 bytes_sent = bcm.send(header_plus_frame)
2379 self.assertEqual(bytes_sent, len(header_plus_frame))
2380
2381
2382 @unittest.skipUnless(HAVE_SOCKET_CAN_ISOTP, 'CAN ISOTP required for this test.')
2383 class ISOTPTest(unittest.TestCase):
2384
2385 def __init__(self, *args, **kwargs):
2386 super().__init__(*args, **kwargs)
2387 self.interface = "vcan0"
2388
2389 def testCrucialConstants(self):
2390 socket.AF_CAN
2391 socket.PF_CAN
2392 socket.CAN_ISOTP
2393 socket.SOCK_DGRAM
2394
2395 def testCreateSocket(self):
2396 with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
2397 pass
2398
2399 @unittest.skipUnless(hasattr(socket, "CAN_ISOTP"),
2400 'socket.CAN_ISOTP required for this test.')
2401 def testCreateISOTPSocket(self):
2402 with socket.socket(socket.PF_CAN, socket.SOCK_DGRAM, socket.CAN_ISOTP) as s:
2403 pass
2404
2405 def testTooLongInterfaceName(self):
2406 # most systems limit IFNAMSIZ to 16, take 1024 to be sure
2407 with socket.socket(socket.PF_CAN, socket.SOCK_DGRAM, socket.CAN_ISOTP) as s:
2408 with self.assertRaisesRegex(OSError, 'interface name too long'):
2409 s.bind(('x' * 1024, 1, 2))
2410
2411 def testBind(self):
2412 try:
2413 with socket.socket(socket.PF_CAN, socket.SOCK_DGRAM, socket.CAN_ISOTP) as s:
2414 addr = self.interface, 0x123, 0x456
2415 s.bind(addr)
2416 self.assertEqual(s.getsockname(), addr)
2417 except OSError as e:
2418 if e.errno == errno.ENODEV:
2419 self.skipTest('network interface `%s` does not exist' %
2420 self.interface)
2421 else:
2422 raise
2423
2424
2425 @unittest.skipUnless(HAVE_SOCKET_CAN_J1939, 'CAN J1939 required for this test.')
2426 class J1939Test(unittest.TestCase):
2427
2428 def __init__(self, *args, **kwargs):
2429 super().__init__(*args, **kwargs)
2430 self.interface = "vcan0"
2431
2432 @unittest.skipUnless(hasattr(socket, "CAN_J1939"),
2433 'socket.CAN_J1939 required for this test.')
2434 def testJ1939Constants(self):
2435 socket.CAN_J1939
2436
2437 socket.J1939_MAX_UNICAST_ADDR
2438 socket.J1939_IDLE_ADDR
2439 socket.J1939_NO_ADDR
2440 socket.J1939_NO_NAME
2441 socket.J1939_PGN_REQUEST
2442 socket.J1939_PGN_ADDRESS_CLAIMED
2443 socket.J1939_PGN_ADDRESS_COMMANDED
2444 socket.J1939_PGN_PDU1_MAX
2445 socket.J1939_PGN_MAX
2446 socket.J1939_NO_PGN
2447
2448 # J1939 socket options
2449 socket.SO_J1939_FILTER
2450 socket.SO_J1939_PROMISC
2451 socket.SO_J1939_SEND_PRIO
2452 socket.SO_J1939_ERRQUEUE
2453
2454 socket.SCM_J1939_DEST_ADDR
2455 socket.SCM_J1939_DEST_NAME
2456 socket.SCM_J1939_PRIO
2457 socket.SCM_J1939_ERRQUEUE
2458
2459 socket.J1939_NLA_PAD
2460 socket.J1939_NLA_BYTES_ACKED
2461
2462 socket.J1939_EE_INFO_NONE
2463 socket.J1939_EE_INFO_TX_ABORT
2464
2465 socket.J1939_FILTER_MAX
2466
2467 @unittest.skipUnless(hasattr(socket, "CAN_J1939"),
2468 'socket.CAN_J1939 required for this test.')
2469 def testCreateJ1939Socket(self):
2470 with socket.socket(socket.PF_CAN, socket.SOCK_DGRAM, socket.CAN_J1939) as s:
2471 pass
2472
2473 def testBind(self):
2474 try:
2475 with socket.socket(socket.PF_CAN, socket.SOCK_DGRAM, socket.CAN_J1939) as s:
2476 addr = self.interface, socket.J1939_NO_NAME, socket.J1939_NO_PGN, socket.J1939_NO_ADDR
2477 s.bind(addr)
2478 self.assertEqual(s.getsockname(), addr)
2479 except OSError as e:
2480 if e.errno == errno.ENODEV:
2481 self.skipTest('network interface `%s` does not exist' %
2482 self.interface)
2483 else:
2484 raise
2485
2486
2487 @unittest.skipUnless(HAVE_SOCKET_RDS, 'RDS sockets required for this test.')
2488 class BasicRDSTest(unittest.TestCase):
2489
2490 def testCrucialConstants(self):
2491 socket.AF_RDS
2492 socket.PF_RDS
2493
2494 def testCreateSocket(self):
2495 with socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0) as s:
2496 pass
2497
2498 def testSocketBufferSize(self):
2499 bufsize = 16384
2500 with socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0) as s:
2501 s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, bufsize)
2502 s.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, bufsize)
2503
2504
2505 @unittest.skipUnless(HAVE_SOCKET_RDS, 'RDS sockets required for this test.')
2506 class RDSTest(ThreadedRDSSocketTest):
2507
2508 def __init__(self, methodName='runTest'):
2509 ThreadedRDSSocketTest.__init__(self, methodName=methodName)
2510
2511 def setUp(self):
2512 super().setUp()
2513 self.evt = threading.Event()
2514
2515 def testSendAndRecv(self):
2516 data, addr = self.serv.recvfrom(self.bufsize)
2517 self.assertEqual(self.data, data)
2518 self.assertEqual(self.cli_addr, addr)
2519
2520 def _testSendAndRecv(self):
2521 self.data = b'spam'
2522 self.cli.sendto(self.data, 0, (HOST, self.port))
2523
2524 def testPeek(self):
2525 data, addr = self.serv.recvfrom(self.bufsize, socket.MSG_PEEK)
2526 self.assertEqual(self.data, data)
2527 data, addr = self.serv.recvfrom(self.bufsize)
2528 self.assertEqual(self.data, data)
2529
2530 def _testPeek(self):
2531 self.data = b'spam'
2532 self.cli.sendto(self.data, 0, (HOST, self.port))
2533
2534 @requireAttrs(socket.socket, 'recvmsg')
2535 def testSendAndRecvMsg(self):
2536 data, ancdata, msg_flags, addr = self.serv.recvmsg(self.bufsize)
2537 self.assertEqual(self.data, data)
2538
2539 @requireAttrs(socket.socket, 'sendmsg')
2540 def _testSendAndRecvMsg(self):
2541 self.data = b'hello ' * 10
2542 self.cli.sendmsg([self.data], (), 0, (HOST, self.port))
2543
2544 def testSendAndRecvMulti(self):
2545 data, addr = self.serv.recvfrom(self.bufsize)
2546 self.assertEqual(self.data1, data)
2547
2548 data, addr = self.serv.recvfrom(self.bufsize)
2549 self.assertEqual(self.data2, data)
2550
2551 def _testSendAndRecvMulti(self):
2552 self.data1 = b'bacon'
2553 self.cli.sendto(self.data1, 0, (HOST, self.port))
2554
2555 self.data2 = b'egg'
2556 self.cli.sendto(self.data2, 0, (HOST, self.port))
2557
2558 def testSelect(self):
2559 r, w, x = select.select([self.serv], [], [], 3.0)
2560 self.assertIn(self.serv, r)
2561 data, addr = self.serv.recvfrom(self.bufsize)
2562 self.assertEqual(self.data, data)
2563
2564 def _testSelect(self):
2565 self.data = b'select'
2566 self.cli.sendto(self.data, 0, (HOST, self.port))
2567
2568 @unittest.skipUnless(HAVE_SOCKET_QIPCRTR,
2569 'QIPCRTR sockets required for this test.')
2570 class BasicQIPCRTRTest(unittest.TestCase):
2571
2572 def testCrucialConstants(self):
2573 socket.AF_QIPCRTR
2574
2575 def testCreateSocket(self):
2576 with socket.socket(socket.AF_QIPCRTR, socket.SOCK_DGRAM) as s:
2577 pass
2578
2579 def testUnbound(self):
2580 with socket.socket(socket.AF_QIPCRTR, socket.SOCK_DGRAM) as s:
2581 self.assertEqual(s.getsockname()[1], 0)
2582
2583 def testBindSock(self):
2584 with socket.socket(socket.AF_QIPCRTR, socket.SOCK_DGRAM) as s:
2585 socket_helper.bind_port(s, host=s.getsockname()[0])
2586 self.assertNotEqual(s.getsockname()[1], 0)
2587
2588 def testInvalidBindSock(self):
2589 with socket.socket(socket.AF_QIPCRTR, socket.SOCK_DGRAM) as s:
2590 self.assertRaises(OSError, socket_helper.bind_port, s, host=-2)
2591
2592 def testAutoBindSock(self):
2593 with socket.socket(socket.AF_QIPCRTR, socket.SOCK_DGRAM) as s:
2594 s.connect((123, 123))
2595 self.assertNotEqual(s.getsockname()[1], 0)
2596
2597 @unittest.skipIf(fcntl is None, "need fcntl")
2598 @unittest.skipUnless(HAVE_SOCKET_VSOCK,
2599 'VSOCK sockets required for this test.')
2600 class BasicVSOCKTest(unittest.TestCase):
2601
2602 def testCrucialConstants(self):
2603 socket.AF_VSOCK
2604
2605 def testVSOCKConstants(self):
2606 socket.SO_VM_SOCKETS_BUFFER_SIZE
2607 socket.SO_VM_SOCKETS_BUFFER_MIN_SIZE
2608 socket.SO_VM_SOCKETS_BUFFER_MAX_SIZE
2609 socket.VMADDR_CID_ANY
2610 socket.VMADDR_PORT_ANY
2611 socket.VMADDR_CID_LOCAL
2612 socket.VMADDR_CID_HOST
2613 socket.VM_SOCKETS_INVALID_VERSION
2614 socket.IOCTL_VM_SOCKETS_GET_LOCAL_CID
2615
2616 def testCreateSocket(self):
2617 with socket.socket(socket.AF_VSOCK, socket.SOCK_STREAM) as s:
2618 pass
2619
2620 def testSocketBufferSize(self):
2621 with socket.socket(socket.AF_VSOCK, socket.SOCK_STREAM) as s:
2622 orig_max = s.getsockopt(socket.AF_VSOCK,
2623 socket.SO_VM_SOCKETS_BUFFER_MAX_SIZE)
2624 orig = s.getsockopt(socket.AF_VSOCK,
2625 socket.SO_VM_SOCKETS_BUFFER_SIZE)
2626 orig_min = s.getsockopt(socket.AF_VSOCK,
2627 socket.SO_VM_SOCKETS_BUFFER_MIN_SIZE)
2628
2629 s.setsockopt(socket.AF_VSOCK,
2630 socket.SO_VM_SOCKETS_BUFFER_MAX_SIZE, orig_max * 2)
2631 s.setsockopt(socket.AF_VSOCK,
2632 socket.SO_VM_SOCKETS_BUFFER_SIZE, orig * 2)
2633 s.setsockopt(socket.AF_VSOCK,
2634 socket.SO_VM_SOCKETS_BUFFER_MIN_SIZE, orig_min * 2)
2635
2636 self.assertEqual(orig_max * 2,
2637 s.getsockopt(socket.AF_VSOCK,
2638 socket.SO_VM_SOCKETS_BUFFER_MAX_SIZE))
2639 self.assertEqual(orig * 2,
2640 s.getsockopt(socket.AF_VSOCK,
2641 socket.SO_VM_SOCKETS_BUFFER_SIZE))
2642 self.assertEqual(orig_min * 2,
2643 s.getsockopt(socket.AF_VSOCK,
2644 socket.SO_VM_SOCKETS_BUFFER_MIN_SIZE))
2645
2646
2647 @unittest.skipUnless(hasattr(socket, 'AF_BLUETOOTH'),
2648 'Bluetooth sockets required for this test.')
2649 class BasicBluetoothTest(unittest.TestCase):
2650
2651 def testBluetoothConstants(self):
2652 socket.BDADDR_ANY
2653 socket.BDADDR_LOCAL
2654 socket.AF_BLUETOOTH
2655 socket.BTPROTO_RFCOMM
2656 socket.SOL_RFCOMM
2657
2658 if sys.platform == "win32":
2659 socket.SO_BTH_ENCRYPT
2660 socket.SO_BTH_MTU
2661 socket.SO_BTH_MTU_MAX
2662 socket.SO_BTH_MTU_MIN
2663
2664 if sys.platform != "win32":
2665 socket.BTPROTO_HCI
2666 socket.SOL_HCI
2667 socket.BTPROTO_L2CAP
2668 socket.SOL_L2CAP
2669 socket.BTPROTO_SCO
2670 socket.SOL_SCO
2671 socket.HCI_DATA_DIR
2672
2673 if sys.platform == "linux":
2674 socket.SOL_BLUETOOTH
2675 socket.HCI_DEV_NONE
2676 socket.HCI_CHANNEL_RAW
2677 socket.HCI_CHANNEL_USER
2678 socket.HCI_CHANNEL_MONITOR
2679 socket.HCI_CHANNEL_CONTROL
2680 socket.HCI_CHANNEL_LOGGING
2681 socket.HCI_TIME_STAMP
2682 socket.BT_SECURITY
2683 socket.BT_SECURITY_SDP
2684 socket.BT_FLUSHABLE
2685 socket.BT_POWER
2686 socket.BT_CHANNEL_POLICY
2687 socket.BT_CHANNEL_POLICY_BREDR_ONLY
2688 if hasattr(socket, 'BT_PHY'):
2689 socket.BT_PHY_BR_1M_1SLOT
2690 if hasattr(socket, 'BT_MODE'):
2691 socket.BT_MODE_BASIC
2692 if hasattr(socket, 'BT_VOICE'):
2693 socket.BT_VOICE_TRANSPARENT
2694 socket.BT_VOICE_CVSD_16BIT
2695 socket.L2CAP_LM
2696 socket.L2CAP_LM_MASTER
2697 socket.L2CAP_LM_AUTH
2698
2699 if sys.platform in ("linux", "freebsd"):
2700 socket.BDADDR_BREDR
2701 socket.BDADDR_LE_PUBLIC
2702 socket.BDADDR_LE_RANDOM
2703 socket.HCI_FILTER
2704
2705 if sys.platform.startswith(("freebsd", "netbsd", "dragonfly")):
2706 socket.SO_L2CAP_IMTU
2707 socket.SO_L2CAP_FLUSH
2708 socket.SO_RFCOMM_MTU
2709 socket.SO_RFCOMM_FC_INFO
2710 socket.SO_SCO_MTU
2711
2712 if sys.platform == "freebsd":
2713 socket.SO_SCO_CONNINFO
2714
2715 if sys.platform.startswith(("netbsd", "dragonfly")):
2716 socket.SO_HCI_EVT_FILTER
2717 socket.SO_HCI_PKT_FILTER
2718 socket.SO_L2CAP_IQOS
2719 socket.SO_L2CAP_LM
2720 socket.L2CAP_LM_AUTH
2721 socket.SO_RFCOMM_LM
2722 socket.RFCOMM_LM_AUTH
2723 socket.SO_SCO_HANDLE
2724
2725 @unittest.skipUnless(HAVE_SOCKET_BLUETOOTH,
2726 'Bluetooth sockets required for this test.')
2727 class BluetoothTest(unittest.TestCase):
2728
2729 def testCreateRfcommSocket(self):
2730 with socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM) as s:
2731 pass
2732
2733 @unittest.skipIf(sys.platform == "win32", "windows does not support L2CAP sockets")
2734 def testCreateL2capSocket(self):
2735 with socket.socket(socket.AF_BLUETOOTH, socket.SOCK_SEQPACKET, socket.BTPROTO_L2CAP) as s:
2736 pass
2737
2738 @unittest.skipIf(sys.platform == "win32", "windows does not support HCI sockets")
2739 def testCreateHciSocket(self):
2740 with socket.socket(socket.AF_BLUETOOTH, socket.SOCK_RAW, socket.BTPROTO_HCI) as s:
2741 pass
2742
2743 @unittest.skipIf(sys.platform == "win32", "windows does not support SCO sockets")
2744 def testCreateScoSocket(self):
2745 with socket.socket(socket.AF_BLUETOOTH, socket.SOCK_SEQPACKET, socket.BTPROTO_SCO) as s:
2746 pass
2747
2748 @unittest.skipUnless(HAVE_SOCKET_BLUETOOTH_L2CAP, 'Bluetooth L2CAP sockets required for this test')
2749 def testBindLeAttL2capSocket(self):
2750 BDADDR_LE_PUBLIC = support.get_attribute(socket, 'BDADDR_LE_PUBLIC')
2751 with socket.socket(socket.AF_BLUETOOTH, socket.SOCK_SEQPACKET, socket.BTPROTO_L2CAP) as f:
2752 # ATT is the only CID allowed in userspace by the Linux kernel
2753 CID_ATT = 4
2754 f.bind((socket.BDADDR_ANY, 0, CID_ATT, BDADDR_LE_PUBLIC))
2755 addr = f.getsockname()
2756 self.assertEqual(addr, (socket.BDADDR_ANY, 0, CID_ATT, BDADDR_LE_PUBLIC))
2757
2758 @unittest.skipUnless(HAVE_SOCKET_BLUETOOTH_L2CAP, 'Bluetooth L2CAP sockets required for this test')
2759 def testBindLePsmL2capSocket(self):
2760 BDADDR_LE_RANDOM = support.get_attribute(socket, 'BDADDR_LE_RANDOM')
2761 with socket.socket(socket.AF_BLUETOOTH, socket.SOCK_SEQPACKET, socket.BTPROTO_L2CAP) as f:
2762 # First user PSM in LE L2CAP
2763 psm = 0x80
2764 f.bind((socket.BDADDR_ANY, psm, 0, BDADDR_LE_RANDOM))
2765 addr = f.getsockname()
2766 self.assertEqual(addr, (socket.BDADDR_ANY, psm, 0, BDADDR_LE_RANDOM))
2767
2768 @unittest.skipUnless(HAVE_SOCKET_BLUETOOTH_L2CAP, 'Bluetooth L2CAP sockets required for this test')
2769 def testBindBrEdrL2capSocket(self):
2770 with socket.socket(socket.AF_BLUETOOTH, socket.SOCK_SEQPACKET, socket.BTPROTO_L2CAP) as f:
2771 # First user PSM in BR/EDR L2CAP
2772 psm = 0x1001
2773 f.bind((socket.BDADDR_ANY, psm))
2774 addr = f.getsockname()
2775 self.assertEqual(addr, (socket.BDADDR_ANY, psm))
2776
2777 @unittest.skipUnless(HAVE_SOCKET_BLUETOOTH_L2CAP, 'Bluetooth L2CAP sockets required for this test')
2778 def testBadL2capAddr(self):
2779 with socket.socket(socket.AF_BLUETOOTH, socket.SOCK_SEQPACKET, socket.BTPROTO_L2CAP) as f:
2780 with self.assertRaises(OSError):
2781 f.bind((socket.BDADDR_ANY, 0, 0, 0, 0))
2782 with self.assertRaises(OSError):
2783 f.bind((socket.BDADDR_ANY,))
2784 with self.assertRaises(OSError):
2785 f.bind(socket.BDADDR_ANY)
2786 with self.assertRaises(OSError):
2787 f.bind((socket.BDADDR_ANY.encode(), 0x1001))
2788 with self.assertRaises(OSError):
2789 f.bind(('\ud812', 0x1001))
2790
2791 def testBindRfcommSocket(self):
2792 with socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM) as s:
2793 channel = 0
2794 try:
2795 s.bind((socket.BDADDR_ANY, channel))
2796 except OSError as err:
2797 if sys.platform == 'win32' and err.winerror == 10050:
2798 self.skipTest(str(err))
2799 raise
2800 addr = s.getsockname()
2801 self.assertEqual(addr, (mock.ANY, channel))
2802 self.assertRegex(addr[0], r'(?i)[0-9a-f]{2}(?::[0-9a-f]{2}){4}')
2803 if sys.platform != 'win32':
2804 self.assertEqual(addr, (socket.BDADDR_ANY, channel))
2805 with socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM) as s:
2806 s.bind(addr)
2807 addr2 = s.getsockname()
2808 self.assertEqual(addr2, addr)
2809
2810 def testBadRfcommAddr(self):
2811 with socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM) as s:
2812 channel = 0
2813 with self.assertRaises(OSError):
2814 s.bind((socket.BDADDR_ANY.encode(), channel))
2815 with self.assertRaises(OSError):
2816 s.bind((socket.BDADDR_ANY,))
2817 with self.assertRaises(OSError):
2818 s.bind((socket.BDADDR_ANY, channel, 0))
2819 with self.assertRaises(OSError):
2820 s.bind((socket.BDADDR_ANY + '\0', channel))
2821 with self.assertRaises(OSError):
2822 s.bind('\ud812')
2823 with self.assertRaises(OSError):
2824 s.bind(('invalid', channel))
2825
2826 @unittest.skipUnless(hasattr(socket, 'BTPROTO_HCI'), 'Bluetooth HCI sockets required for this test')
2827 def testBindHciSocket(self):
2828 if sys.platform.startswith(('netbsd', 'dragonfly', 'freebsd')):
2829 with socket.socket(socket.AF_BLUETOOTH, socket.SOCK_RAW, socket.BTPROTO_HCI) as s:
2830 s.bind(socket.BDADDR_ANY)
2831 addr = s.getsockname()
2832 self.assertEqual(addr, socket.BDADDR_ANY)
2833 else:
2834 dev = 0
2835 with socket.socket(socket.AF_BLUETOOTH, socket.SOCK_RAW, socket.BTPROTO_HCI) as s:
2836 try:
2837 s.bind((dev,))
2838 except OSError as err:
2839 if err.errno in (errno.EINVAL, errno.ENODEV):
2840 self.skipTest(str(err))
2841 raise
2842 addr = s.getsockname()
2843 self.assertEqual(addr, dev)
2844
2845 with (self.subTest('integer'),
2846 socket.socket(socket.AF_BLUETOOTH, socket.SOCK_RAW, socket.BTPROTO_HCI) as s):
2847 s.bind(dev)
2848 addr = s.getsockname()
2849 self.assertEqual(addr, dev)
2850
2851 with (self.subTest('channel=HCI_CHANNEL_RAW'),
2852 socket.socket(socket.AF_BLUETOOTH, socket.SOCK_RAW, socket.BTPROTO_HCI) as s):
2853 channel = socket.HCI_CHANNEL_RAW
2854 s.bind((dev, channel))
2855 addr = s.getsockname()
2856 self.assertEqual(addr, dev)
2857
2858 with (self.subTest('channel=HCI_CHANNEL_USER'),
2859 socket.socket(socket.AF_BLUETOOTH, socket.SOCK_RAW, socket.BTPROTO_HCI) as s):
2860 channel = socket.HCI_CHANNEL_USER
2861 try:
2862 s.bind((dev, channel))
2863 except OSError as err:
2864 # Needs special permissions.
2865 if err.errno in (errno.EPERM, errno.EBUSY, errno.ERFKILL):
2866 self.skipTest(str(err))
2867 raise
2868 addr = s.getsockname()
2869 self.assertEqual(addr, (dev, channel))
2870
2871 @unittest.skipUnless(hasattr(socket, 'BTPROTO_HCI'), 'Bluetooth HCI sockets required for this test')
2872 def testBadHciAddr(self):
2873 with socket.socket(socket.AF_BLUETOOTH, socket.SOCK_RAW, socket.BTPROTO_HCI) as s:
2874 if sys.platform.startswith(('netbsd', 'dragonfly', 'freebsd')):
2875 with self.assertRaises(OSError):
2876 s.bind(socket.BDADDR_ANY.encode())
2877 with self.assertRaises(OSError):
2878 s.bind((socket.BDADDR_ANY,))
2879 with self.assertRaises(OSError):
2880 s.bind(socket.BDADDR_ANY + '\0')
2881 with self.assertRaises((ValueError, OSError)):
2882 s.bind(socket.BDADDR_ANY + ' '*100)
2883 with self.assertRaises(OSError):
2884 s.bind('\ud812')
2885 with self.assertRaises(OSError):
2886 s.bind('invalid')
2887 with self.assertRaises(OSError):
2888 s.bind(b'invalid')
2889 else:
2890 dev = 0
2891 with self.assertRaises(OSError):
2892 s.bind(())
2893 with self.assertRaises(OSError):
2894 s.bind((dev, socket.HCI_CHANNEL_RAW, 0, 0))
2895 with self.assertRaises(OSError):
2896 s.bind(socket.BDADDR_ANY)
2897 with self.assertRaises(OSError):
2898 s.bind(socket.BDADDR_ANY.encode())
2899
2900 @unittest.skipUnless(hasattr(socket, 'BTPROTO_SCO'), 'Bluetooth SCO sockets required for this test')
2901 def testBindScoSocket(self):
2902 with socket.socket(socket.AF_BLUETOOTH, socket.SOCK_SEQPACKET, socket.BTPROTO_SCO) as s:
2903 s.bind(socket.BDADDR_ANY)
2904 addr = s.getsockname()
2905 self.assertEqual(addr, socket.BDADDR_ANY)
2906
2907 with socket.socket(socket.AF_BLUETOOTH, socket.SOCK_SEQPACKET, socket.BTPROTO_SCO) as s:
2908 s.bind(socket.BDADDR_ANY.encode())
2909 addr = s.getsockname()
2910 self.assertEqual(addr, socket.BDADDR_ANY)
2911
2912 @unittest.skipUnless(hasattr(socket, 'BTPROTO_SCO'), 'Bluetooth SCO sockets required for this test')
2913 def testBadScoAddr(self):
2914 with socket.socket(socket.AF_BLUETOOTH, socket.SOCK_SEQPACKET, socket.BTPROTO_SCO) as s:
2915 with self.assertRaises(OSError):
2916 s.bind((socket.BDADDR_ANY,))
2917 with self.assertRaises(OSError):
2918 s.bind((socket.BDADDR_ANY.encode(),))
2919 with self.assertRaises(ValueError):
2920 s.bind(socket.BDADDR_ANY + '\0')
2921 with self.assertRaises(ValueError):
2922 s.bind(socket.BDADDR_ANY.encode() + b'\0')
2923 with self.assertRaises(UnicodeEncodeError):
2924 s.bind('\ud812')
2925 with self.assertRaises(OSError):
2926 s.bind('invalid')
2927 with self.assertRaises(OSError):
2928 s.bind(b'invalid')
2929
2930
2931 @unittest.skipUnless(HAVE_SOCKET_HYPERV,
2932 'Hyper-V sockets required for this test.')
2933 class BasicHyperVTest(unittest.TestCase):
2934
2935 def testHyperVConstants(self):
2936 socket.HVSOCKET_CONNECT_TIMEOUT
2937 socket.HVSOCKET_CONNECT_TIMEOUT_MAX
2938 socket.HVSOCKET_CONNECTED_SUSPEND
2939 socket.HVSOCKET_ADDRESS_FLAG_PASSTHRU
2940 socket.HV_GUID_ZERO
2941 socket.HV_GUID_WILDCARD
2942 socket.HV_GUID_BROADCAST
2943 socket.HV_GUID_CHILDREN
2944 socket.HV_GUID_LOOPBACK
2945 socket.HV_GUID_PARENT
2946
2947 def testCreateHyperVSocketWithUnknownProtoFailure(self):
2948 expected = r"\[WinError 10041\]"
2949 with self.assertRaisesRegex(OSError, expected):
2950 socket.socket(socket.AF_HYPERV, socket.SOCK_STREAM)
2951
2952 def testCreateHyperVSocketAddrNotTupleFailure(self):
2953 expected = "connect(): AF_HYPERV address must be tuple, not str"
2954 with socket.socket(socket.AF_HYPERV, socket.SOCK_STREAM, socket.HV_PROTOCOL_RAW) as s:
2955 with self.assertRaisesRegex(TypeError, re.escape(expected)):
2956 s.connect(socket.HV_GUID_ZERO)
2957
2958 def testCreateHyperVSocketAddrNotTupleOf2StrsFailure(self):
2959 expected = "AF_HYPERV address must be a str tuple (vm_id, service_id)"
2960 with socket.socket(socket.AF_HYPERV, socket.SOCK_STREAM, socket.HV_PROTOCOL_RAW) as s:
2961 with self.assertRaisesRegex(TypeError, re.escape(expected)):
2962 s.connect((socket.HV_GUID_ZERO,))
2963
2964 def testCreateHyperVSocketAddrNotTupleOfStrsFailure(self):
2965 expected = "AF_HYPERV address must be a str tuple (vm_id, service_id)"
2966 with socket.socket(socket.AF_HYPERV, socket.SOCK_STREAM, socket.HV_PROTOCOL_RAW) as s:
2967 with self.assertRaisesRegex(TypeError, re.escape(expected)):
2968 s.connect((1, 2))
2969
2970 def testCreateHyperVSocketAddrVmIdNotValidUUIDFailure(self):
2971 expected = "connect(): AF_HYPERV address vm_id is not a valid UUID string"
2972 with socket.socket(socket.AF_HYPERV, socket.SOCK_STREAM, socket.HV_PROTOCOL_RAW) as s:
2973 with self.assertRaisesRegex(ValueError, re.escape(expected)):
2974 s.connect(("00", socket.HV_GUID_ZERO))
2975
2976 def testCreateHyperVSocketAddrServiceIdNotValidUUIDFailure(self):
2977 expected = "connect(): AF_HYPERV address service_id is not a valid UUID string"
2978 with socket.socket(socket.AF_HYPERV, socket.SOCK_STREAM, socket.HV_PROTOCOL_RAW) as s:
2979 with self.assertRaisesRegex(ValueError, re.escape(expected)):
2980 s.connect((socket.HV_GUID_ZERO, "00"))
2981
2982
2983 class BasicTCPTest(SocketConnectedTest):
2984
2985 def __init__(self, methodName='runTest'):
2986 SocketConnectedTest.__init__(self, methodName=methodName)
2987
2988 def testRecv(self):
2989 # Testing large receive over TCP
2990 msg = self.cli_conn.recv(1024)
2991 self.assertEqual(msg, MSG)
2992
2993 def _testRecv(self):
2994 self.serv_conn.send(MSG)
2995
2996 def testOverFlowRecv(self):
2997 # Testing receive in chunks over TCP
2998 seg1 = self.cli_conn.recv(len(MSG) - 3)
2999 seg2 = self.cli_conn.recv(1024)
3000 msg = seg1 + seg2
3001 self.assertEqual(msg, MSG)
3002
3003 def _testOverFlowRecv(self):
3004 self.serv_conn.send(MSG)
3005
3006 def testRecvFrom(self):
3007 # Testing large recvfrom() over TCP
3008 msg, addr = self.cli_conn.recvfrom(1024)
3009 self.assertEqual(msg, MSG)
3010
3011 def _testRecvFrom(self):
3012 self.serv_conn.send(MSG)
3013
3014 def testOverFlowRecvFrom(self):
3015 # Testing recvfrom() in chunks over TCP
3016 seg1, addr = self.cli_conn.recvfrom(len(MSG)-3)
3017 seg2, addr = self.cli_conn.recvfrom(1024)
3018 msg = seg1 + seg2
3019 self.assertEqual(msg, MSG)
3020
3021 def _testOverFlowRecvFrom(self):
3022 self.serv_conn.send(MSG)
3023
3024 def testSendAll(self):
3025 # Testing sendall() with a 2048 byte string over TCP
3026 msg = b''
3027 while 1:
3028 read = self.cli_conn.recv(1024)
3029 if not read:
3030 break
3031 msg += read
3032 self.assertEqual(msg, b'f' * 2048)
3033
3034 def _testSendAll(self):
3035 big_chunk = b'f' * 2048
3036 self.serv_conn.sendall(big_chunk)
3037
3038 def testFromFd(self):
3039 # Testing fromfd()
3040 fd = self.cli_conn.fileno()
3041 sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
3042 self.addCleanup(sock.close)
3043 self.assertIsInstance(sock, socket.socket)
3044 msg = sock.recv(1024)
3045 self.assertEqual(msg, MSG)
3046
3047 def _testFromFd(self):
3048 self.serv_conn.send(MSG)
3049
3050 def testDup(self):
3051 # Testing dup()
3052 sock = self.cli_conn.dup()
3053 self.addCleanup(sock.close)
3054 msg = sock.recv(1024)
3055 self.assertEqual(msg, MSG)
3056
3057 def _testDup(self):
3058 self.serv_conn.send(MSG)
3059
3060 def check_shutdown(self):
3061 # Test shutdown() helper
3062 msg = self.cli_conn.recv(1024)
3063 self.assertEqual(msg, MSG)
3064 # wait for _testShutdown[_overflow] to finish: on OS X, when the server
3065 # closes the connection the client also becomes disconnected,
3066 # and the client's shutdown call will fail. (Issue #4397.)
3067 self.done.wait()
3068
3069 def testShutdown(self):
3070 self.check_shutdown()
3071
3072 def _testShutdown(self):
3073 self.serv_conn.send(MSG)
3074 self.serv_conn.shutdown(2)
3075
3076 @support.cpython_only
3077 @unittest.skipIf(_testcapi is None, "requires _testcapi")
3078 def testShutdown_overflow(self):
3079 self.check_shutdown()
3080
3081 @support.cpython_only
3082 @unittest.skipIf(_testcapi is None, "requires _testcapi")
3083 def _testShutdown_overflow(self):
3084 import _testcapi
3085 self.serv_conn.send(MSG)
3086 # Issue 15989
3087 self.assertRaises(OverflowError, self.serv_conn.shutdown,
3088 _testcapi.INT_MAX + 1)
3089 self.assertRaises(OverflowError, self.serv_conn.shutdown,
3090 2 + (_testcapi.UINT_MAX + 1))
3091 self.serv_conn.shutdown(2)
3092
3093 def testDetach(self):
3094 # Testing detach()
3095 fileno = self.cli_conn.fileno()
3096 f = self.cli_conn.detach()
3097 self.assertEqual(f, fileno)
3098 # cli_conn cannot be used anymore...
3099 self.assertTrue(self.cli_conn._closed)
3100 self.assertRaises(OSError, self.cli_conn.recv, 1024)
3101 self.cli_conn.close()
3102 # ...but we can create another socket using the (still open)
3103 # file descriptor
3104 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, fileno=f)
3105 self.addCleanup(sock.close)
3106 msg = sock.recv(1024)
3107 self.assertEqual(msg, MSG)
3108
3109 def _testDetach(self):
3110 self.serv_conn.send(MSG)
3111
3112
3113 class BasicUDPTest(ThreadedUDPSocketTest):
3114
3115 def __init__(self, methodName='runTest'):
3116 ThreadedUDPSocketTest.__init__(self, methodName=methodName)
3117
3118 def testSendtoAndRecv(self):
3119 # Testing sendto() and Recv() over UDP
3120 msg = self.serv.recv(len(MSG))
3121 self.assertEqual(msg, MSG)
3122
3123 def _testSendtoAndRecv(self):
3124 self.cli.sendto(MSG, 0, (HOST, self.port))
3125
3126 def testRecvFrom(self):
3127 # Testing recvfrom() over UDP
3128 msg, addr = self.serv.recvfrom(len(MSG))
3129 self.assertEqual(msg, MSG)
3130
3131 def _testRecvFrom(self):
3132 self.cli.sendto(MSG, 0, (HOST, self.port))
3133
3134 def testRecvFromNegative(self):
3135 # Negative lengths passed to recvfrom should give ValueError.
3136 self.assertRaises(ValueError, self.serv.recvfrom, -1)
3137
3138 def _testRecvFromNegative(self):
3139 self.cli.sendto(MSG, 0, (HOST, self.port))
3140
3141
3142 @unittest.skipUnless(HAVE_SOCKET_UDPLITE,
3143 'UDPLITE sockets required for this test.')
3144 class BasicUDPLITETest(ThreadedUDPLITESocketTest):
3145
3146 def __init__(self, methodName='runTest'):
3147 ThreadedUDPLITESocketTest.__init__(self, methodName=methodName)
3148
3149 def testSendtoAndRecv(self):
3150 # Testing sendto() and Recv() over UDPLITE
3151 msg = self.serv.recv(len(MSG))
3152 self.assertEqual(msg, MSG)
3153
3154 def _testSendtoAndRecv(self):
3155 self.cli.sendto(MSG, 0, (HOST, self.port))
3156
3157 def testRecvFrom(self):
3158 # Testing recvfrom() over UDPLITE
3159 msg, addr = self.serv.recvfrom(len(MSG))
3160 self.assertEqual(msg, MSG)
3161
3162 def _testRecvFrom(self):
3163 self.cli.sendto(MSG, 0, (HOST, self.port))
3164
3165 def testRecvFromNegative(self):
3166 # Negative lengths passed to recvfrom should give ValueError.
3167 self.assertRaises(ValueError, self.serv.recvfrom, -1)
3168
3169 def _testRecvFromNegative(self):
3170 self.cli.sendto(MSG, 0, (HOST, self.port))
3171
3172 # Tests for the sendmsg()/recvmsg() interface. Where possible, the
3173 # same test code is used with different families and types of socket
3174 # (e.g. stream, datagram), and tests using recvmsg() are repeated
3175 # using recvmsg_into().
3176 #
3177 # The generic test classes such as SendmsgTests and
3178 # RecvmsgGenericTests inherit from SendrecvmsgBase and expect to be
3179 # supplied with sockets cli_sock and serv_sock representing the
3180 # client's and the server's end of the connection respectively, and
3181 # attributes cli_addr and serv_addr holding their (numeric where
3182 # appropriate) addresses.
3183 #
3184 # The final concrete test classes combine these with subclasses of
3185 # SocketTestBase which set up client and server sockets of a specific
3186 # type, and with subclasses of SendrecvmsgBase such as
3187 # SendrecvmsgDgramBase and SendrecvmsgConnectedBase which map these
3188 # sockets to cli_sock and serv_sock and override the methods and
3189 # attributes of SendrecvmsgBase to fill in destination addresses if
3190 # needed when sending, check for specific flags in msg_flags, etc.
3191 #
3192 # RecvmsgIntoMixin provides a version of doRecvmsg() implemented using
3193 # recvmsg_into().
3194
3195 # XXX: like the other datagram (UDP) tests in this module, the code
3196 # here assumes that datagram delivery on the local machine will be
3197 # reliable.
3198
3199 class SendrecvmsgBase:
3200 # Base class for sendmsg()/recvmsg() tests.
3201
3202 # Time in seconds to wait before considering a test failed, or
3203 # None for no timeout. Not all tests actually set a timeout.
3204 fail_timeout = support.LOOPBACK_TIMEOUT
3205
3206 def setUp(self):
3207 self.misc_event = threading.Event()
3208 super().setUp()
3209
3210 def sendToServer(self, msg):
3211 # Send msg to the server.
3212 return self.cli_sock.send(msg)
3213
3214 # Tuple of alternative default arguments for sendmsg() when called
3215 # via sendmsgToServer() (e.g. to include a destination address).
3216 sendmsg_to_server_defaults = ()
3217
3218 def sendmsgToServer(self, *args):
3219 # Call sendmsg() on self.cli_sock with the given arguments,
3220 # filling in any arguments which are not supplied with the
3221 # corresponding items of self.sendmsg_to_server_defaults, if
3222 # any.
3223 return self.cli_sock.sendmsg(
3224 *(args + self.sendmsg_to_server_defaults[len(args):]))
3225
3226 def doRecvmsg(self, sock, bufsize, *args):
3227 # Call recvmsg() on sock with given arguments and return its
3228 # result. Should be used for tests which can use either
3229 # recvmsg() or recvmsg_into() - RecvmsgIntoMixin overrides
3230 # this method with one which emulates it using recvmsg_into(),
3231 # thus allowing the same test to be used for both methods.
3232 result = sock.recvmsg(bufsize, *args)
3233 self.registerRecvmsgResult(result)
3234 return result
3235
3236 def registerRecvmsgResult(self, result):
3237 # Called by doRecvmsg() with the return value of recvmsg() or
3238 # recvmsg_into(). Can be overridden to arrange cleanup based
3239 # on the returned ancillary data, for instance.
3240 pass
3241
3242 def checkRecvmsgAddress(self, addr1, addr2):
3243 # Called to compare the received address with the address of
3244 # the peer.
3245 self.assertEqual(addr1, addr2)
3246
3247 # Flags that are normally unset in msg_flags
3248 msg_flags_common_unset = 0
3249 for name in ("MSG_CTRUNC", "MSG_OOB"):
3250 msg_flags_common_unset |= getattr(socket, name, 0)
3251
3252 # Flags that are normally set
3253 msg_flags_common_set = 0
3254
3255 # Flags set when a complete record has been received (e.g. MSG_EOR
3256 # for SCTP)
3257 msg_flags_eor_indicator = 0
3258
3259 # Flags set when a complete record has not been received
3260 # (e.g. MSG_TRUNC for datagram sockets)
3261 msg_flags_non_eor_indicator = 0
3262
3263 def checkFlags(self, flags, eor=None, checkset=0, checkunset=0, ignore=0):
3264 # Method to check the value of msg_flags returned by recvmsg[_into]().
3265 #
3266 # Checks that all bits in msg_flags_common_set attribute are
3267 # set in "flags" and all bits in msg_flags_common_unset are
3268 # unset.
3269 #
3270 # The "eor" argument specifies whether the flags should
3271 # indicate that a full record (or datagram) has been received.
3272 # If "eor" is None, no checks are done; otherwise, checks
3273 # that:
3274 #
3275 # * if "eor" is true, all bits in msg_flags_eor_indicator are
3276 # set and all bits in msg_flags_non_eor_indicator are unset
3277 #
3278 # * if "eor" is false, all bits in msg_flags_non_eor_indicator
3279 # are set and all bits in msg_flags_eor_indicator are unset
3280 #
3281 # If "checkset" and/or "checkunset" are supplied, they require
3282 # the given bits to be set or unset respectively, overriding
3283 # what the attributes require for those bits.
3284 #
3285 # If any bits are set in "ignore", they will not be checked,
3286 # regardless of the other inputs.
3287 #
3288 # Will raise Exception if the inputs require a bit to be both
3289 # set and unset, and it is not ignored.
3290
3291 defaultset = self.msg_flags_common_set
3292 defaultunset = self.msg_flags_common_unset
3293
3294 if eor:
3295 defaultset |= self.msg_flags_eor_indicator
3296 defaultunset |= self.msg_flags_non_eor_indicator
3297 elif eor is not None:
3298 defaultset |= self.msg_flags_non_eor_indicator
3299 defaultunset |= self.msg_flags_eor_indicator
3300
3301 # Function arguments override defaults
3302 defaultset &= ~checkunset
3303 defaultunset &= ~checkset
3304
3305 # Merge arguments with remaining defaults, and check for conflicts
3306 checkset |= defaultset
3307 checkunset |= defaultunset
3308 inboth = checkset & checkunset & ~ignore
3309 if inboth:
3310 raise Exception("contradictory set, unset requirements for flags "
3311 "{0:#x}".format(inboth))
3312
3313 # Compare with given msg_flags value
3314 mask = (checkset | checkunset) & ~ignore
3315 self.assertEqual(flags & mask, checkset & mask)
3316
3317
3318 class RecvmsgIntoMixin(SendrecvmsgBase):
3319 # Mixin to implement doRecvmsg() using recvmsg_into().
3320
3321 def doRecvmsg(self, sock, bufsize, *args):
3322 buf = bytearray(bufsize)
3323 result = sock.recvmsg_into([buf], *args)
3324 self.registerRecvmsgResult(result)
3325 self.assertGreaterEqual(result[0], 0)
3326 self.assertLessEqual(result[0], bufsize)
3327 return (bytes(buf[:result[0]]),) + result[1:]
3328
3329
3330 class SendrecvmsgDgramFlagsBase(SendrecvmsgBase):
3331 # Defines flags to be checked in msg_flags for datagram sockets.
3332
3333 @property
3334 def msg_flags_non_eor_indicator(self):
3335 return super().msg_flags_non_eor_indicator | socket.MSG_TRUNC
3336
3337
3338 class SendrecvmsgSCTPFlagsBase(SendrecvmsgBase):
3339 # Defines flags to be checked in msg_flags for SCTP sockets.
3340
3341 @property
3342 def msg_flags_eor_indicator(self):
3343 return super().msg_flags_eor_indicator | socket.MSG_EOR
3344
3345
3346 class SendrecvmsgConnectionlessBase(SendrecvmsgBase):
3347 # Base class for tests on connectionless-mode sockets. Users must
3348 # supply sockets on attributes cli and serv to be mapped to
3349 # cli_sock and serv_sock respectively.
3350
3351 @property
3352 def serv_sock(self):
3353 return self.serv
3354
3355 @property
3356 def cli_sock(self):
3357 return self.cli
3358
3359 @property
3360 def sendmsg_to_server_defaults(self):
3361 return ([], [], 0, self.serv_addr)
3362
3363 def sendToServer(self, msg):
3364 return self.cli_sock.sendto(msg, self.serv_addr)
3365
3366
3367 class SendrecvmsgConnectedBase(SendrecvmsgBase):
3368 # Base class for tests on connected sockets. Users must supply
3369 # sockets on attributes serv_conn and cli_conn (representing the
3370 # connections *to* the server and the client), to be mapped to
3371 # cli_sock and serv_sock respectively.
3372
3373 @property
3374 def serv_sock(self):
3375 return self.cli_conn
3376
3377 @property
3378 def cli_sock(self):
3379 return self.serv_conn
3380
3381 def checkRecvmsgAddress(self, addr1, addr2):
3382 # Address is currently "unspecified" for a connected socket,
3383 # so we don't examine it
3384 pass
3385
3386
3387 class SendrecvmsgServerTimeoutBase(SendrecvmsgBase):
3388 # Base class to set a timeout on server's socket.
3389
3390 def setUp(self):
3391 super().setUp()
3392 self.serv_sock.settimeout(self.fail_timeout)
3393
3394
3395 class SendmsgTests(SendrecvmsgServerTimeoutBase):
3396 # Tests for sendmsg() which can use any socket type and do not
3397 # involve recvmsg() or recvmsg_into().
3398
3399 def testSendmsg(self):
3400 # Send a simple message with sendmsg().
3401 self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
3402
3403 def _testSendmsg(self):
3404 self.assertEqual(self.sendmsgToServer([MSG]), len(MSG))
3405
3406 def testSendmsgDataGenerator(self):
3407 # Send from buffer obtained from a generator (not a sequence).
3408 self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
3409
3410 def _testSendmsgDataGenerator(self):
3411 self.assertEqual(self.sendmsgToServer((o for o in [MSG])),
3412 len(MSG))
3413
3414 def testSendmsgAncillaryGenerator(self):
3415 # Gather (empty) ancillary data from a generator.
3416 self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
3417
3418 def _testSendmsgAncillaryGenerator(self):
3419 self.assertEqual(self.sendmsgToServer([MSG], (o for o in [])),
3420 len(MSG))
3421
3422 def testSendmsgArray(self):
3423 # Send data from an array instead of the usual bytes object.
3424 self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
3425
3426 def _testSendmsgArray(self):
3427 self.assertEqual(self.sendmsgToServer([array.array("B", MSG)]),
3428 len(MSG))
3429
3430 def testSendmsgGather(self):
3431 # Send message data from more than one buffer (gather write).
3432 self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
3433
3434 def _testSendmsgGather(self):
3435 self.assertEqual(self.sendmsgToServer([MSG[:3], MSG[3:]]), len(MSG))
3436
3437 def testSendmsgBadArgs(self):
3438 # Check that sendmsg() rejects invalid arguments.
3439 self.assertEqual(self.serv_sock.recv(1000), b"done")
3440
3441 def _testSendmsgBadArgs(self):
3442 self.assertRaises(TypeError, self.cli_sock.sendmsg)
3443 self.assertRaises(TypeError, self.sendmsgToServer,
3444 b"not in an iterable")
3445 self.assertRaises(TypeError, self.sendmsgToServer,
3446 object())
3447 self.assertRaises(TypeError, self.sendmsgToServer,
3448 [object()])
3449 self.assertRaises(TypeError, self.sendmsgToServer,
3450 [MSG, object()])
3451 self.assertRaises(TypeError, self.sendmsgToServer,
3452 [MSG], object())
3453 self.assertRaises(TypeError, self.sendmsgToServer,
3454 [MSG], [], object())
3455 self.assertRaises(TypeError, self.sendmsgToServer,
3456 [MSG], [], 0, object())
3457 self.sendToServer(b"done")
3458
3459 def testSendmsgBadCmsg(self):
3460 # Check that invalid ancillary data items are rejected.
3461 self.assertEqual(self.serv_sock.recv(1000), b"done")
3462
3463 def _testSendmsgBadCmsg(self):
3464 self.assertRaises(TypeError, self.sendmsgToServer,
3465 [MSG], [object()])
3466 self.assertRaises(TypeError, self.sendmsgToServer,
3467 [MSG], [(object(), 0, b"data")])
3468 self.assertRaises(TypeError, self.sendmsgToServer,
3469 [MSG], [(0, object(), b"data")])
3470 self.assertRaises(TypeError, self.sendmsgToServer,
3471 [MSG], [(0, 0, object())])
3472 self.assertRaises(TypeError, self.sendmsgToServer,
3473 [MSG], [(0, 0)])
3474 self.assertRaises(TypeError, self.sendmsgToServer,
3475 [MSG], [(0, 0, b"data", 42)])
3476 self.sendToServer(b"done")
3477
3478 @requireAttrs(socket, "CMSG_SPACE")
3479 def testSendmsgBadMultiCmsg(self):
3480 # Check that invalid ancillary data items are rejected when
3481 # more than one item is present.
3482 self.assertEqual(self.serv_sock.recv(1000), b"done")
3483
3484 @testSendmsgBadMultiCmsg.client_skip
3485 def _testSendmsgBadMultiCmsg(self):
3486 self.assertRaises(TypeError, self.sendmsgToServer,
3487 [MSG], [0, 0, b""])
3488 self.assertRaises(TypeError, self.sendmsgToServer,
3489 [MSG], [(0, 0, b""), object()])
3490 self.sendToServer(b"done")
3491
3492 def testSendmsgExcessCmsgReject(self):
3493 # Check that sendmsg() rejects excess ancillary data items
3494 # when the number that can be sent is limited.
3495 self.assertEqual(self.serv_sock.recv(1000), b"done")
3496
3497 def _testSendmsgExcessCmsgReject(self):
3498 if not hasattr(socket, "CMSG_SPACE"):
3499 # Can only send one item
3500 with self.assertRaises(OSError) as cm:
3501 self.sendmsgToServer([MSG], [(0, 0, b""), (0, 0, b"")])
3502 self.assertIsNone(cm.exception.errno)
3503 self.sendToServer(b"done")
3504
3505 def testSendmsgAfterClose(self):
3506 # Check that sendmsg() fails on a closed socket.
3507 pass
3508
3509 def _testSendmsgAfterClose(self):
3510 self.cli_sock.close()
3511 self.assertRaises(OSError, self.sendmsgToServer, [MSG])
3512
3513
3514 class SendmsgStreamTests(SendmsgTests):
3515 # Tests for sendmsg() which require a stream socket and do not
3516 # involve recvmsg() or recvmsg_into().
3517
3518 def testSendmsgExplicitNoneAddr(self):
3519 # Check that peer address can be specified as None.
3520 self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
3521
3522 def _testSendmsgExplicitNoneAddr(self):
3523 self.assertEqual(self.sendmsgToServer([MSG], [], 0, None), len(MSG))
3524
3525 def testSendmsgTimeout(self):
3526 # Check that timeout works with sendmsg().
3527 self.assertEqual(self.serv_sock.recv(512), b"a"*512)
3528 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
3529
3530 def _testSendmsgTimeout(self):
3531 try:
3532 self.cli_sock.settimeout(0.03)
3533 try:
3534 while True:
3535 self.sendmsgToServer([b"a"*512])
3536 except TimeoutError:
3537 pass
3538 except OSError as exc:
3539 if exc.errno != errno.ENOMEM:
3540 raise
3541 # bpo-33937 the test randomly fails on Travis CI with
3542 # "OSError: [Errno 12] Cannot allocate memory"
3543 else:
3544 self.fail("TimeoutError not raised")
3545 finally:
3546 self.misc_event.set()
3547
3548 # XXX: would be nice to have more tests for sendmsg flags argument.
3549
3550 # Linux supports MSG_DONTWAIT when sending, but in general, it
3551 # only works when receiving. Could add other platforms if they
3552 # support it too.
3553 @skipWithClientIf(sys.platform not in {"linux", "android"},
3554 "MSG_DONTWAIT not known to work on this platform when "
3555 "sending")
3556 def testSendmsgDontWait(self):
3557 # Check that MSG_DONTWAIT in flags causes non-blocking behaviour.
3558 self.assertEqual(self.serv_sock.recv(512), b"a"*512)
3559 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
3560
3561 @testSendmsgDontWait.client_skip
3562 def _testSendmsgDontWait(self):
3563 try:
3564 with self.assertRaises(OSError) as cm:
3565 while True:
3566 self.sendmsgToServer([b"a"*512], [], socket.MSG_DONTWAIT)
3567 # bpo-33937: catch also ENOMEM, the test randomly fails on Travis CI
3568 # with "OSError: [Errno 12] Cannot allocate memory"
3569 self.assertIn(cm.exception.errno,
3570 (errno.EAGAIN, errno.EWOULDBLOCK, errno.ENOMEM))
3571 finally:
3572 self.misc_event.set()
3573
3574
3575 class SendmsgConnectionlessTests(SendmsgTests):
3576 # Tests for sendmsg() which require a connectionless-mode
3577 # (e.g. datagram) socket, and do not involve recvmsg() or
3578 # recvmsg_into().
3579
3580 def testSendmsgNoDestAddr(self):
3581 # Check that sendmsg() fails when no destination address is
3582 # given for unconnected socket.
3583 pass
3584
3585 def _testSendmsgNoDestAddr(self):
3586 self.assertRaises(OSError, self.cli_sock.sendmsg,
3587 [MSG])
3588 self.assertRaises(OSError, self.cli_sock.sendmsg,
3589 [MSG], [], 0, None)
3590
3591
3592 class RecvmsgGenericTests(SendrecvmsgBase):
3593 # Tests for recvmsg() which can also be emulated using
3594 # recvmsg_into(), and can use any socket type.
3595
3596 def testRecvmsg(self):
3597 # Receive a simple message with recvmsg[_into]().
3598 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, len(MSG))
3599 self.assertEqual(msg, MSG)
3600 self.checkRecvmsgAddress(addr, self.cli_addr)
3601 self.assertEqual(ancdata, [])
3602 self.checkFlags(flags, eor=True)
3603
3604 def _testRecvmsg(self):
3605 self.sendToServer(MSG)
3606
3607 def testRecvmsgExplicitDefaults(self):
3608 # Test recvmsg[_into]() with default arguments provided explicitly.
3609 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
3610 len(MSG), 0, 0)
3611 self.assertEqual(msg, MSG)
3612 self.checkRecvmsgAddress(addr, self.cli_addr)
3613 self.assertEqual(ancdata, [])
3614 self.checkFlags(flags, eor=True)
3615
3616 def _testRecvmsgExplicitDefaults(self):
3617 self.sendToServer(MSG)
3618
3619 def testRecvmsgShorter(self):
3620 # Receive a message smaller than buffer.
3621 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
3622 len(MSG) + 42)
3623 self.assertEqual(msg, MSG)
3624 self.checkRecvmsgAddress(addr, self.cli_addr)
3625 self.assertEqual(ancdata, [])
3626 self.checkFlags(flags, eor=True)
3627
3628 def _testRecvmsgShorter(self):
3629 self.sendToServer(MSG)
3630
3631 def testRecvmsgTrunc(self):
3632 # Receive part of message, check for truncation indicators.
3633 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
3634 len(MSG) - 3)
3635 self.assertEqual(msg, MSG[:-3])
3636 self.checkRecvmsgAddress(addr, self.cli_addr)
3637 self.assertEqual(ancdata, [])
3638 self.checkFlags(flags, eor=False)
3639
3640 def _testRecvmsgTrunc(self):
3641 self.sendToServer(MSG)
3642
3643 def testRecvmsgShortAncillaryBuf(self):
3644 # Test ancillary data buffer too small to hold any ancillary data.
3645 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
3646 len(MSG), 1)
3647 self.assertEqual(msg, MSG)
3648 self.checkRecvmsgAddress(addr, self.cli_addr)
3649 self.assertEqual(ancdata, [])
3650 self.checkFlags(flags, eor=True)
3651
3652 def _testRecvmsgShortAncillaryBuf(self):
3653 self.sendToServer(MSG)
3654
3655 def testRecvmsgLongAncillaryBuf(self):
3656 # Test large ancillary data buffer.
3657 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
3658 len(MSG), 10240)
3659 self.assertEqual(msg, MSG)
3660 self.checkRecvmsgAddress(addr, self.cli_addr)
3661 self.assertEqual(ancdata, [])
3662 self.checkFlags(flags, eor=True)
3663
3664 def _testRecvmsgLongAncillaryBuf(self):
3665 self.sendToServer(MSG)
3666
3667 def testRecvmsgAfterClose(self):
3668 # Check that recvmsg[_into]() fails on a closed socket.
3669 self.serv_sock.close()
3670 self.assertRaises(OSError, self.doRecvmsg, self.serv_sock, 1024)
3671
3672 def _testRecvmsgAfterClose(self):
3673 pass
3674
3675 def testRecvmsgTimeout(self):
3676 # Check that timeout works.
3677 try:
3678 self.serv_sock.settimeout(0.03)
3679 self.assertRaises(TimeoutError,
3680 self.doRecvmsg, self.serv_sock, len(MSG))
3681 finally:
3682 self.misc_event.set()
3683
3684 def _testRecvmsgTimeout(self):
3685 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
3686
3687 @requireAttrs(socket, "MSG_PEEK")
3688 def testRecvmsgPeek(self):
3689 # Check that MSG_PEEK in flags enables examination of pending
3690 # data without consuming it.
3691
3692 # Receive part of data with MSG_PEEK.
3693 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
3694 len(MSG) - 3, 0,
3695 socket.MSG_PEEK)
3696 self.assertEqual(msg, MSG[:-3])
3697 self.checkRecvmsgAddress(addr, self.cli_addr)
3698 self.assertEqual(ancdata, [])
3699 # Ignoring MSG_TRUNC here (so this test is the same for stream
3700 # and datagram sockets). Some wording in POSIX seems to
3701 # suggest that it needn't be set when peeking, but that may
3702 # just be a slip.
3703 self.checkFlags(flags, eor=False,
3704 ignore=getattr(socket, "MSG_TRUNC", 0))
3705
3706 # Receive all data with MSG_PEEK.
3707 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
3708 len(MSG), 0,
3709 socket.MSG_PEEK)
3710 self.assertEqual(msg, MSG)
3711 self.checkRecvmsgAddress(addr, self.cli_addr)
3712 self.assertEqual(ancdata, [])
3713 self.checkFlags(flags, eor=True)
3714
3715 # Check that the same data can still be received normally.
3716 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, len(MSG))
3717 self.assertEqual(msg, MSG)
3718 self.checkRecvmsgAddress(addr, self.cli_addr)
3719 self.assertEqual(ancdata, [])
3720 self.checkFlags(flags, eor=True)
3721
3722 @testRecvmsgPeek.client_skip
3723 def _testRecvmsgPeek(self):
3724 self.sendToServer(MSG)
3725
3726 @requireAttrs(socket.socket, "sendmsg")
3727 def testRecvmsgFromSendmsg(self):
3728 # Test receiving with recvmsg[_into]() when message is sent
3729 # using sendmsg().
3730 self.serv_sock.settimeout(self.fail_timeout)
3731 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, len(MSG))
3732 self.assertEqual(msg, MSG)
3733 self.checkRecvmsgAddress(addr, self.cli_addr)
3734 self.assertEqual(ancdata, [])
3735 self.checkFlags(flags, eor=True)
3736
3737 @testRecvmsgFromSendmsg.client_skip
3738 def _testRecvmsgFromSendmsg(self):
3739 self.assertEqual(self.sendmsgToServer([MSG[:3], MSG[3:]]), len(MSG))
3740
3741
3742 class RecvmsgGenericStreamTests(RecvmsgGenericTests):
3743 # Tests which require a stream socket and can use either recvmsg()
3744 # or recvmsg_into().
3745
3746 def testRecvmsgEOF(self):
3747 # Receive end-of-stream indicator (b"", peer socket closed).
3748 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, 1024)
3749 self.assertEqual(msg, b"")
3750 self.checkRecvmsgAddress(addr, self.cli_addr)
3751 self.assertEqual(ancdata, [])
3752 self.checkFlags(flags, eor=None) # Might not have end-of-record marker
3753
3754 def _testRecvmsgEOF(self):
3755 self.cli_sock.close()
3756
3757 def testRecvmsgOverflow(self):
3758 # Receive a message in more than one chunk.
3759 seg1, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
3760 len(MSG) - 3)
3761 self.checkRecvmsgAddress(addr, self.cli_addr)
3762 self.assertEqual(ancdata, [])
3763 self.checkFlags(flags, eor=False)
3764
3765 seg2, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, 1024)
3766 self.checkRecvmsgAddress(addr, self.cli_addr)
3767 self.assertEqual(ancdata, [])
3768 self.checkFlags(flags, eor=True)
3769
3770 msg = seg1 + seg2
3771 self.assertEqual(msg, MSG)
3772
3773 def _testRecvmsgOverflow(self):
3774 self.sendToServer(MSG)
3775
3776
3777 class RecvmsgTests(RecvmsgGenericTests):
3778 # Tests for recvmsg() which can use any socket type.
3779
3780 def testRecvmsgBadArgs(self):
3781 # Check that recvmsg() rejects invalid arguments.
3782 self.assertRaises(TypeError, self.serv_sock.recvmsg)
3783 self.assertRaises(ValueError, self.serv_sock.recvmsg,
3784 -1, 0, 0)
3785 self.assertRaises(ValueError, self.serv_sock.recvmsg,
3786 len(MSG), -1, 0)
3787 self.assertRaises(TypeError, self.serv_sock.recvmsg,
3788 [bytearray(10)], 0, 0)
3789 self.assertRaises(TypeError, self.serv_sock.recvmsg,
3790 object(), 0, 0)
3791 self.assertRaises(TypeError, self.serv_sock.recvmsg,
3792 len(MSG), object(), 0)
3793 self.assertRaises(TypeError, self.serv_sock.recvmsg,
3794 len(MSG), 0, object())
3795
3796 msg, ancdata, flags, addr = self.serv_sock.recvmsg(len(MSG), 0, 0)
3797 self.assertEqual(msg, MSG)
3798 self.checkRecvmsgAddress(addr, self.cli_addr)
3799 self.assertEqual(ancdata, [])
3800 self.checkFlags(flags, eor=True)
3801
3802 def _testRecvmsgBadArgs(self):
3803 self.sendToServer(MSG)
3804
3805
3806 class RecvmsgIntoTests(RecvmsgIntoMixin, RecvmsgGenericTests):
3807 # Tests for recvmsg_into() which can use any socket type.
3808
3809 def testRecvmsgIntoBadArgs(self):
3810 # Check that recvmsg_into() rejects invalid arguments.
3811 buf = bytearray(len(MSG))
3812 self.assertRaises(TypeError, self.serv_sock.recvmsg_into)
3813 self.assertRaises(TypeError, self.serv_sock.recvmsg_into,
3814 len(MSG), 0, 0)
3815 self.assertRaises(TypeError, self.serv_sock.recvmsg_into,
3816 buf, 0, 0)
3817 self.assertRaises(TypeError, self.serv_sock.recvmsg_into,
3818 [object()], 0, 0)
3819 self.assertRaises(TypeError, self.serv_sock.recvmsg_into,
3820 [b"I'm not writable"], 0, 0)
3821 self.assertRaises(TypeError, self.serv_sock.recvmsg_into,
3822 [buf, object()], 0, 0)
3823 self.assertRaises(ValueError, self.serv_sock.recvmsg_into,
3824 [buf], -1, 0)
3825 self.assertRaises(TypeError, self.serv_sock.recvmsg_into,
3826 [buf], object(), 0)
3827 self.assertRaises(TypeError, self.serv_sock.recvmsg_into,
3828 [buf], 0, object())
3829
3830 nbytes, ancdata, flags, addr = self.serv_sock.recvmsg_into([buf], 0, 0)
3831 self.assertEqual(nbytes, len(MSG))
3832 self.assertEqual(buf, bytearray(MSG))
3833 self.checkRecvmsgAddress(addr, self.cli_addr)
3834 self.assertEqual(ancdata, [])
3835 self.checkFlags(flags, eor=True)
3836
3837 def _testRecvmsgIntoBadArgs(self):
3838 self.sendToServer(MSG)
3839
3840 def testRecvmsgIntoGenerator(self):
3841 # Receive into buffer obtained from a generator (not a sequence).
3842 buf = bytearray(len(MSG))
3843 nbytes, ancdata, flags, addr = self.serv_sock.recvmsg_into(
3844 (o for o in [buf]))
3845 self.assertEqual(nbytes, len(MSG))
3846 self.assertEqual(buf, bytearray(MSG))
3847 self.checkRecvmsgAddress(addr, self.cli_addr)
3848 self.assertEqual(ancdata, [])
3849 self.checkFlags(flags, eor=True)
3850
3851 def _testRecvmsgIntoGenerator(self):
3852 self.sendToServer(MSG)
3853
3854 def testRecvmsgIntoArray(self):
3855 # Receive into an array rather than the usual bytearray.
3856 buf = array.array("B", [0] * len(MSG))
3857 nbytes, ancdata, flags, addr = self.serv_sock.recvmsg_into([buf])
3858 self.assertEqual(nbytes, len(MSG))
3859 self.assertEqual(buf.tobytes(), MSG)
3860 self.checkRecvmsgAddress(addr, self.cli_addr)
3861 self.assertEqual(ancdata, [])
3862 self.checkFlags(flags, eor=True)
3863
3864 def _testRecvmsgIntoArray(self):
3865 self.sendToServer(MSG)
3866
3867 def testRecvmsgIntoScatter(self):
3868 # Receive into multiple buffers (scatter write).
3869 b1 = bytearray(b"----")
3870 b2 = bytearray(b"0123456789")
3871 b3 = bytearray(b"--------------")
3872 nbytes, ancdata, flags, addr = self.serv_sock.recvmsg_into(
3873 [b1, memoryview(b2)[2:9], b3])
3874 self.assertEqual(nbytes, len(b"Mary had a little lamb"))
3875 self.assertEqual(b1, bytearray(b"Mary"))
3876 self.assertEqual(b2, bytearray(b"01 had a 9"))
3877 self.assertEqual(b3, bytearray(b"little lamb---"))
3878 self.checkRecvmsgAddress(addr, self.cli_addr)
3879 self.assertEqual(ancdata, [])
3880 self.checkFlags(flags, eor=True)
3881
3882 def _testRecvmsgIntoScatter(self):
3883 self.sendToServer(b"Mary had a little lamb")
3884
3885
3886 class CmsgMacroTests(unittest.TestCase):
3887 # Test the functions CMSG_LEN() and CMSG_SPACE(). Tests
3888 # assumptions used by sendmsg() and recvmsg[_into](), which share
3889 # code with these functions.
3890
3891 # Match the definition in socketmodule.c
3892 try:
3893 import _testcapi
3894 except ImportError:
3895 socklen_t_limit = 0x7fffffff
3896 else:
3897 socklen_t_limit = min(0x7fffffff, _testcapi.INT_MAX)
3898
3899 @requireAttrs(socket, "CMSG_LEN")
3900 def testCMSG_LEN(self):
3901 # Test CMSG_LEN() with various valid and invalid values,
3902 # checking the assumptions used by recvmsg() and sendmsg().
3903 toobig = self.socklen_t_limit - socket.CMSG_LEN(0) + 1
3904 values = list(range(257)) + list(range(toobig - 257, toobig))
3905
3906 # struct cmsghdr has at least three members, two of which are ints
3907 self.assertGreater(socket.CMSG_LEN(0), array.array("i").itemsize * 2)
3908 for n in values:
3909 ret = socket.CMSG_LEN(n)
3910 # This is how recvmsg() calculates the data size
3911 self.assertEqual(ret - socket.CMSG_LEN(0), n)
3912 self.assertLessEqual(ret, self.socklen_t_limit)
3913
3914 self.assertRaises(OverflowError, socket.CMSG_LEN, -1)
3915 # sendmsg() shares code with these functions, and requires
3916 # that it reject values over the limit.
3917 self.assertRaises(OverflowError, socket.CMSG_LEN, toobig)
3918 self.assertRaises(OverflowError, socket.CMSG_LEN, sys.maxsize)
3919
3920 @requireAttrs(socket, "CMSG_SPACE")
3921 def testCMSG_SPACE(self):
3922 # Test CMSG_SPACE() with various valid and invalid values,
3923 # checking the assumptions used by sendmsg().
3924 toobig = self.socklen_t_limit - socket.CMSG_SPACE(1) + 1
3925 if SOLARIS and platform.processor() == "sparc":
3926 # On Solaris SPARC, number of bytes returned by socket.CMSG_SPACE
3927 # increases at different lengths; see gh-91214.
3928 toobig -= 3
3929 values = list(range(257)) + list(range(toobig - 257, toobig))
3930
3931 last = socket.CMSG_SPACE(0)
3932 # struct cmsghdr has at least three members, two of which are ints
3933 self.assertGreater(last, array.array("i").itemsize * 2)
3934 for n in values:
3935 ret = socket.CMSG_SPACE(n)
3936 self.assertGreaterEqual(ret, last)
3937 self.assertGreaterEqual(ret, socket.CMSG_LEN(n))
3938 self.assertGreaterEqual(ret, n + socket.CMSG_LEN(0))
3939 self.assertLessEqual(ret, self.socklen_t_limit)
3940 last = ret
3941
3942 self.assertRaises(OverflowError, socket.CMSG_SPACE, -1)
3943 # sendmsg() shares code with these functions, and requires
3944 # that it reject values over the limit.
3945 self.assertRaises(OverflowError, socket.CMSG_SPACE, toobig)
3946 self.assertRaises(OverflowError, socket.CMSG_SPACE, sys.maxsize)
3947
3948
3949 class SCMRightsTest(SendrecvmsgServerTimeoutBase):
3950 # Tests for file descriptor passing on Unix-domain sockets.
3951
3952 # Invalid file descriptor value that's unlikely to evaluate to a
3953 # real FD even if one of its bytes is replaced with a different
3954 # value (which shouldn't actually happen).
3955 badfd = -0x5555
3956
3957 def newFDs(self, n):
3958 # Return a list of n file descriptors for newly-created files
3959 # containing their list indices as ASCII numbers.
3960 fds = []
3961 for i in range(n):
3962 fd, path = tempfile.mkstemp()
3963 self.addCleanup(os.unlink, path)
3964 self.addCleanup(os.close, fd)
3965 os.write(fd, str(i).encode())
3966 fds.append(fd)
3967 return fds
3968
3969 def checkFDs(self, fds):
3970 # Check that the file descriptors in the given list contain
3971 # their correct list indices as ASCII numbers.
3972 for n, fd in enumerate(fds):
3973 os.lseek(fd, 0, os.SEEK_SET)
3974 self.assertEqual(os.read(fd, 1024), str(n).encode())
3975
3976 def registerRecvmsgResult(self, result):
3977 self.addCleanup(self.closeRecvmsgFDs, result)
3978
3979 def closeRecvmsgFDs(self, recvmsg_result):
3980 # Close all file descriptors specified in the ancillary data
3981 # of the given return value from recvmsg() or recvmsg_into().
3982 for cmsg_level, cmsg_type, cmsg_data in recvmsg_result[1]:
3983 if (cmsg_level == socket.SOL_SOCKET and
3984 cmsg_type == socket.SCM_RIGHTS):
3985 fds = array.array("i")
3986 fds.frombytes(cmsg_data[:
3987 len(cmsg_data) - (len(cmsg_data) % fds.itemsize)])
3988 for fd in fds:
3989 os.close(fd)
3990
3991 def createAndSendFDs(self, n):
3992 # Send n new file descriptors created by newFDs() to the
3993 # server, with the constant MSG as the non-ancillary data.
3994 self.assertEqual(
3995 self.sendmsgToServer([MSG],
3996 [(socket.SOL_SOCKET,
3997 socket.SCM_RIGHTS,
3998 array.array("i", self.newFDs(n)))]),
3999 len(MSG))
4000
4001 def checkRecvmsgFDs(self, numfds, result, maxcmsgs=1, ignoreflags=0):
4002 # Check that constant MSG was received with numfds file
4003 # descriptors in a maximum of maxcmsgs control messages (which
4004 # must contain only complete integers). By default, check
4005 # that MSG_CTRUNC is unset, but ignore any flags in
4006 # ignoreflags.
4007 msg, ancdata, flags, addr = result
4008 self.assertEqual(msg, MSG)
4009 self.checkRecvmsgAddress(addr, self.cli_addr)
4010 self.checkFlags(flags, eor=True, checkunset=socket.MSG_CTRUNC,
4011 ignore=ignoreflags)
4012
4013 self.assertIsInstance(ancdata, list)
4014 self.assertLessEqual(len(ancdata), maxcmsgs)
4015 fds = array.array("i")
4016 for item in ancdata:
4017 self.assertIsInstance(item, tuple)
4018 cmsg_level, cmsg_type, cmsg_data = item
4019 self.assertEqual(cmsg_level, socket.SOL_SOCKET)
4020 self.assertEqual(cmsg_type, socket.SCM_RIGHTS)
4021 self.assertIsInstance(cmsg_data, bytes)
4022 self.assertEqual(len(cmsg_data) % SIZEOF_INT, 0)
4023 fds.frombytes(cmsg_data)
4024
4025 self.assertEqual(len(fds), numfds)
4026 self.checkFDs(fds)
4027
4028 def testFDPassSimple(self):
4029 # Pass a single FD (array read from bytes object).
4030 self.checkRecvmsgFDs(1, self.doRecvmsg(self.serv_sock,
4031 len(MSG), 10240))
4032
4033 def _testFDPassSimple(self):
4034 self.assertEqual(
4035 self.sendmsgToServer(
4036 [MSG],
4037 [(socket.SOL_SOCKET,
4038 socket.SCM_RIGHTS,
4039 array.array("i", self.newFDs(1)).tobytes())]),
4040 len(MSG))
4041
4042 def testMultipleFDPass(self):
4043 # Pass multiple FDs in a single array.
4044 self.checkRecvmsgFDs(4, self.doRecvmsg(self.serv_sock,
4045 len(MSG), 10240))
4046
4047 def _testMultipleFDPass(self):
4048 self.createAndSendFDs(4)
4049
4050 @requireAttrs(socket, "CMSG_SPACE")
4051 def testFDPassCMSG_SPACE(self):
4052 # Test using CMSG_SPACE() to calculate ancillary buffer size.
4053 self.checkRecvmsgFDs(
4054 4, self.doRecvmsg(self.serv_sock, len(MSG),
4055 socket.CMSG_SPACE(4 * SIZEOF_INT)))
4056
4057 @testFDPassCMSG_SPACE.client_skip
4058 def _testFDPassCMSG_SPACE(self):
4059 self.createAndSendFDs(4)
4060
4061 def testFDPassCMSG_LEN(self):
4062 # Test using CMSG_LEN() to calculate ancillary buffer size.
4063 self.checkRecvmsgFDs(1,
4064 self.doRecvmsg(self.serv_sock, len(MSG),
4065 socket.CMSG_LEN(4 * SIZEOF_INT)),
4066 # RFC 3542 says implementations may set
4067 # MSG_CTRUNC if there isn't enough space
4068 # for trailing padding.
4069 ignoreflags=socket.MSG_CTRUNC)
4070
4071 def _testFDPassCMSG_LEN(self):
4072 self.createAndSendFDs(1)
4073
4074 @unittest.skipIf(is_apple, "skipping, see issue #12958")
4075 @unittest.skipIf(SOLARIS, "skipping, see gh-91214")
4076 @unittest.skipIf(AIX, "skipping, see issue #22397")
4077 @requireAttrs(socket, "CMSG_SPACE")
4078 def testFDPassSeparate(self):
4079 # Pass two FDs in two separate arrays. Arrays may be combined
4080 # into a single control message by the OS.
4081 self.checkRecvmsgFDs(2,
4082 self.doRecvmsg(self.serv_sock, len(MSG), 10240),
4083 maxcmsgs=2)
4084
4085 @testFDPassSeparate.client_skip
4086 @unittest.skipIf(is_apple, "skipping, see issue #12958")
4087 @unittest.skipIf(SOLARIS, "skipping, see gh-91214")
4088 @unittest.skipIf(AIX, "skipping, see issue #22397")
4089 def _testFDPassSeparate(self):
4090 fd0, fd1 = self.newFDs(2)
4091 self.assertEqual(
4092 self.sendmsgToServer([MSG], [(socket.SOL_SOCKET,
4093 socket.SCM_RIGHTS,
4094 array.array("i", [fd0])),
4095 (socket.SOL_SOCKET,
4096 socket.SCM_RIGHTS,
4097 array.array("i", [fd1]))]),
4098 len(MSG))
4099
4100 @unittest.skipIf(is_apple, "skipping, see issue #12958")
4101 @unittest.skipIf(SOLARIS, "skipping, see gh-91214")
4102 @unittest.skipIf(AIX, "skipping, see issue #22397")
4103 @requireAttrs(socket, "CMSG_SPACE")
4104 def testFDPassSeparateMinSpace(self):
4105 # Pass two FDs in two separate arrays, receiving them into the
4106 # minimum space for two arrays.
4107 num_fds = 2
4108 self.checkRecvmsgFDs(num_fds,
4109 self.doRecvmsg(self.serv_sock, len(MSG),
4110 socket.CMSG_SPACE(SIZEOF_INT) +
4111 socket.CMSG_LEN(SIZEOF_INT * num_fds)),
4112 maxcmsgs=2, ignoreflags=socket.MSG_CTRUNC)
4113
4114 @testFDPassSeparateMinSpace.client_skip
4115 @unittest.skipIf(is_apple, "skipping, see issue #12958")
4116 @unittest.skipIf(SOLARIS, "skipping, see gh-91214")
4117 @unittest.skipIf(AIX, "skipping, see issue #22397")
4118 def _testFDPassSeparateMinSpace(self):
4119 fd0, fd1 = self.newFDs(2)
4120 self.assertEqual(
4121 self.sendmsgToServer([MSG], [(socket.SOL_SOCKET,
4122 socket.SCM_RIGHTS,
4123 array.array("i", [fd0])),
4124 (socket.SOL_SOCKET,
4125 socket.SCM_RIGHTS,
4126 array.array("i", [fd1]))]),
4127 len(MSG))
4128
4129 def sendAncillaryIfPossible(self, msg, ancdata):
4130 # Try to send msg and ancdata to server, but if the system
4131 # call fails, just send msg with no ancillary data.
4132 try:
4133 nbytes = self.sendmsgToServer([msg], ancdata)
4134 except OSError as e:
4135 # Check that it was the system call that failed
4136 self.assertIsInstance(e.errno, int)
4137 nbytes = self.sendmsgToServer([msg])
4138 self.assertEqual(nbytes, len(msg))
4139
4140 @unittest.skipIf(is_apple, "skipping, see issue #12958")
4141 def testFDPassEmpty(self):
4142 # Try to pass an empty FD array. Can receive either no array
4143 # or an empty array.
4144 self.checkRecvmsgFDs(0, self.doRecvmsg(self.serv_sock,
4145 len(MSG), 10240),
4146 ignoreflags=socket.MSG_CTRUNC)
4147
4148 def _testFDPassEmpty(self):
4149 self.sendAncillaryIfPossible(MSG, [(socket.SOL_SOCKET,
4150 socket.SCM_RIGHTS,
4151 b"")])
4152
4153 def testFDPassPartialInt(self):
4154 # Try to pass a truncated FD array.
4155 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
4156 len(MSG), 10240)
4157 self.assertEqual(msg, MSG)
4158 self.checkRecvmsgAddress(addr, self.cli_addr)
4159 self.checkFlags(flags, eor=True, ignore=socket.MSG_CTRUNC)
4160 self.assertLessEqual(len(ancdata), 1)
4161 for cmsg_level, cmsg_type, cmsg_data in ancdata:
4162 self.assertEqual(cmsg_level, socket.SOL_SOCKET)
4163 self.assertEqual(cmsg_type, socket.SCM_RIGHTS)
4164 self.assertLess(len(cmsg_data), SIZEOF_INT)
4165
4166 def _testFDPassPartialInt(self):
4167 self.sendAncillaryIfPossible(
4168 MSG,
4169 [(socket.SOL_SOCKET,
4170 socket.SCM_RIGHTS,
4171 array.array("i", [self.badfd]).tobytes()[:-1])])
4172
4173 @requireAttrs(socket, "CMSG_SPACE")
4174 def testFDPassPartialIntInMiddle(self):
4175 # Try to pass two FD arrays, the first of which is truncated.
4176 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
4177 len(MSG), 10240)
4178 self.assertEqual(msg, MSG)
4179 self.checkRecvmsgAddress(addr, self.cli_addr)
4180 self.checkFlags(flags, eor=True, ignore=socket.MSG_CTRUNC)
4181 self.assertLessEqual(len(ancdata), 2)
4182 fds = array.array("i")
4183 # Arrays may have been combined in a single control message
4184 for cmsg_level, cmsg_type, cmsg_data in ancdata:
4185 self.assertEqual(cmsg_level, socket.SOL_SOCKET)
4186 self.assertEqual(cmsg_type, socket.SCM_RIGHTS)
4187 fds.frombytes(cmsg_data[:
4188 len(cmsg_data) - (len(cmsg_data) % fds.itemsize)])
4189 self.assertLessEqual(len(fds), 2)
4190 self.checkFDs(fds)
4191
4192 @testFDPassPartialIntInMiddle.client_skip
4193 def _testFDPassPartialIntInMiddle(self):
4194 fd0, fd1 = self.newFDs(2)
4195 self.sendAncillaryIfPossible(
4196 MSG,
4197 [(socket.SOL_SOCKET,
4198 socket.SCM_RIGHTS,
4199 array.array("i", [fd0, self.badfd]).tobytes()[:-1]),
4200 (socket.SOL_SOCKET,
4201 socket.SCM_RIGHTS,
4202 array.array("i", [fd1]))])
4203
4204 def checkTruncatedHeader(self, result, ignoreflags=0):
4205 # Check that no ancillary data items are returned when data is
4206 # truncated inside the cmsghdr structure.
4207 msg, ancdata, flags, addr = result
4208 self.assertEqual(msg, MSG)
4209 self.checkRecvmsgAddress(addr, self.cli_addr)
4210 self.assertEqual(ancdata, [])
4211 self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC,
4212 ignore=ignoreflags)
4213
4214 @skipForRefleakHuntinIf(sys.platform == "darwin", "#80931")
4215 def testCmsgTruncNoBufSize(self):
4216 # Check that no ancillary data is received when no buffer size
4217 # is specified.
4218 self.checkTruncatedHeader(self.doRecvmsg(self.serv_sock, len(MSG)),
4219 # BSD seems to set MSG_CTRUNC only
4220 # if an item has been partially
4221 # received.
4222 ignoreflags=socket.MSG_CTRUNC)
4223
4224 @testCmsgTruncNoBufSize.client_skip
4225 def _testCmsgTruncNoBufSize(self):
4226 self.createAndSendFDs(1)
4227
4228 @skipForRefleakHuntinIf(sys.platform == "darwin", "#80931")
4229 def testCmsgTrunc0(self):
4230 # Check that no ancillary data is received when buffer size is 0.
4231 self.checkTruncatedHeader(self.doRecvmsg(self.serv_sock, len(MSG), 0),
4232 ignoreflags=socket.MSG_CTRUNC)
4233
4234 @testCmsgTrunc0.client_skip
4235 def _testCmsgTrunc0(self):
4236 self.createAndSendFDs(1)
4237
4238 # Check that no ancillary data is returned for various non-zero
4239 # (but still too small) buffer sizes.
4240
4241 @skipForRefleakHuntinIf(sys.platform == "darwin", "#80931")
4242 def testCmsgTrunc1(self):
4243 self.checkTruncatedHeader(self.doRecvmsg(self.serv_sock, len(MSG), 1))
4244
4245 @testCmsgTrunc1.client_skip
4246 def _testCmsgTrunc1(self):
4247 self.createAndSendFDs(1)
4248
4249 @skipForRefleakHuntinIf(sys.platform == "darwin", "#80931")
4250 def testCmsgTrunc2Int(self):
4251 # The cmsghdr structure has at least three members, two of
4252 # which are ints, so we still shouldn't see any ancillary
4253 # data.
4254 self.checkTruncatedHeader(self.doRecvmsg(self.serv_sock, len(MSG),
4255 SIZEOF_INT * 2))
4256
4257 @testCmsgTrunc2Int.client_skip
4258 def _testCmsgTrunc2Int(self):
4259 self.createAndSendFDs(1)
4260
4261 @skipForRefleakHuntinIf(sys.platform == "darwin", "#80931")
4262 def testCmsgTruncLen0Minus1(self):
4263 self.checkTruncatedHeader(self.doRecvmsg(self.serv_sock, len(MSG),
4264 socket.CMSG_LEN(0) - 1))
4265
4266 @testCmsgTruncLen0Minus1.client_skip
4267 def _testCmsgTruncLen0Minus1(self):
4268 self.createAndSendFDs(1)
4269
4270 # The following tests try to truncate the control message in the
4271 # middle of the FD array.
4272
4273 def checkTruncatedArray(self, ancbuf, maxdata, mindata=0):
4274 # Check that file descriptor data is truncated to between
4275 # mindata and maxdata bytes when received with buffer size
4276 # ancbuf, and that any complete file descriptor numbers are
4277 # valid.
4278 with downgrade_malformed_data_warning(): # TODO: gh-110012
4279 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
4280 len(MSG), ancbuf)
4281 self.assertEqual(msg, MSG)
4282 self.checkRecvmsgAddress(addr, self.cli_addr)
4283 self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC)
4284
4285 if mindata == 0 and ancdata == []:
4286 return
4287 self.assertEqual(len(ancdata), 1)
4288 cmsg_level, cmsg_type, cmsg_data = ancdata[0]
4289 self.assertEqual(cmsg_level, socket.SOL_SOCKET)
4290 self.assertEqual(cmsg_type, socket.SCM_RIGHTS)
4291 self.assertGreaterEqual(len(cmsg_data), mindata)
4292 self.assertLessEqual(len(cmsg_data), maxdata)
4293 fds = array.array("i")
4294 fds.frombytes(cmsg_data[:
4295 len(cmsg_data) - (len(cmsg_data) % fds.itemsize)])
4296 self.checkFDs(fds)
4297
4298 @skipForRefleakHuntinIf(sys.platform == "darwin", "#80931")
4299 def testCmsgTruncLen0(self):
4300 self.checkTruncatedArray(ancbuf=socket.CMSG_LEN(0), maxdata=0)
4301
4302 @testCmsgTruncLen0.client_skip
4303 def _testCmsgTruncLen0(self):
4304 self.createAndSendFDs(1)
4305
4306 @skipForRefleakHuntinIf(sys.platform == "darwin", "#80931")
4307 def testCmsgTruncLen0Plus1(self):
4308 self.checkTruncatedArray(ancbuf=socket.CMSG_LEN(0) + 1, maxdata=1)
4309
4310 @testCmsgTruncLen0Plus1.client_skip
4311 def _testCmsgTruncLen0Plus1(self):
4312 self.createAndSendFDs(2)
4313
4314 @skipForRefleakHuntinIf(sys.platform == "darwin", "#80931")
4315 def testCmsgTruncLen1(self):
4316 self.checkTruncatedArray(ancbuf=socket.CMSG_LEN(SIZEOF_INT),
4317 maxdata=SIZEOF_INT)
4318
4319 @testCmsgTruncLen1.client_skip
4320 def _testCmsgTruncLen1(self):
4321 self.createAndSendFDs(2)
4322
4323
4324 @skipForRefleakHuntinIf(sys.platform == "darwin", "#80931")
4325 def testCmsgTruncLen2Minus1(self):
4326 self.checkTruncatedArray(ancbuf=socket.CMSG_LEN(2 * SIZEOF_INT) - 1,
4327 maxdata=(2 * SIZEOF_INT) - 1)
4328
4329 @testCmsgTruncLen2Minus1.client_skip
4330 def _testCmsgTruncLen2Minus1(self):
4331 self.createAndSendFDs(2)
4332
4333
4334 class RFC3542AncillaryTest(SendrecvmsgServerTimeoutBase):
4335 # Test sendmsg() and recvmsg[_into]() using the ancillary data
4336 # features of the RFC 3542 Advanced Sockets API for IPv6.
4337 # Currently we can only handle certain data items (e.g. traffic
4338 # class, hop limit, MTU discovery and fragmentation settings)
4339 # without resorting to unportable means such as the struct module,
4340 # but the tests here are aimed at testing the ancillary data
4341 # handling in sendmsg() and recvmsg() rather than the IPv6 API
4342 # itself.
4343
4344 # Test value to use when setting hop limit of packet
4345 hop_limit = 2
4346
4347 # Test value to use when setting traffic class of packet.
4348 # -1 means "use kernel default".
4349 traffic_class = -1
4350
4351 def ancillaryMapping(self, ancdata):
4352 # Given ancillary data list ancdata, return a mapping from
4353 # pairs (cmsg_level, cmsg_type) to corresponding cmsg_data.
4354 # Check that no (level, type) pair appears more than once.
4355 d = {}
4356 for cmsg_level, cmsg_type, cmsg_data in ancdata:
4357 self.assertNotIn((cmsg_level, cmsg_type), d)
4358 d[(cmsg_level, cmsg_type)] = cmsg_data
4359 return d
4360
4361 def checkHopLimit(self, ancbufsize, maxhop=255, ignoreflags=0):
4362 # Receive hop limit into ancbufsize bytes of ancillary data
4363 # space. Check that data is MSG, ancillary data is not
4364 # truncated (but ignore any flags in ignoreflags), and hop
4365 # limit is between 0 and maxhop inclusive.
4366 self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
4367 socket.IPV6_RECVHOPLIMIT, 1)
4368 self.misc_event.set()
4369 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
4370 len(MSG), ancbufsize)
4371
4372 self.assertEqual(msg, MSG)
4373 self.checkRecvmsgAddress(addr, self.cli_addr)
4374 self.checkFlags(flags, eor=True, checkunset=socket.MSG_CTRUNC,
4375 ignore=ignoreflags)
4376
4377 self.assertEqual(len(ancdata), 1)
4378 self.assertIsInstance(ancdata[0], tuple)
4379 cmsg_level, cmsg_type, cmsg_data = ancdata[0]
4380 self.assertEqual(cmsg_level, socket.IPPROTO_IPV6)
4381 self.assertEqual(cmsg_type, socket.IPV6_HOPLIMIT)
4382 self.assertIsInstance(cmsg_data, bytes)
4383 self.assertEqual(len(cmsg_data), SIZEOF_INT)
4384 a = array.array("i")
4385 a.frombytes(cmsg_data)
4386 self.assertGreaterEqual(a[0], 0)
4387 self.assertLessEqual(a[0], maxhop)
4388
4389 @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
4390 def testRecvHopLimit(self):
4391 # Test receiving the packet hop limit as ancillary data.
4392 self.checkHopLimit(ancbufsize=10240)
4393
4394 @testRecvHopLimit.client_skip
4395 def _testRecvHopLimit(self):
4396 # Need to wait until server has asked to receive ancillary
4397 # data, as implementations are not required to buffer it
4398 # otherwise.
4399 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
4400 self.sendToServer(MSG)
4401
4402 @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
4403 def testRecvHopLimitCMSG_SPACE(self):
4404 # Test receiving hop limit, using CMSG_SPACE to calculate buffer size.
4405 self.checkHopLimit(ancbufsize=socket.CMSG_SPACE(SIZEOF_INT))
4406
4407 @testRecvHopLimitCMSG_SPACE.client_skip
4408 def _testRecvHopLimitCMSG_SPACE(self):
4409 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
4410 self.sendToServer(MSG)
4411
4412 # Could test receiving into buffer sized using CMSG_LEN, but RFC
4413 # 3542 says portable applications must provide space for trailing
4414 # padding. Implementations may set MSG_CTRUNC if there isn't
4415 # enough space for the padding.
4416
4417 @requireAttrs(socket.socket, "sendmsg")
4418 @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
4419 def testSetHopLimit(self):
4420 # Test setting hop limit on outgoing packet and receiving it
4421 # at the other end.
4422 self.checkHopLimit(ancbufsize=10240, maxhop=self.hop_limit)
4423
4424 @testSetHopLimit.client_skip
4425 def _testSetHopLimit(self):
4426 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
4427 self.assertEqual(
4428 self.sendmsgToServer([MSG],
4429 [(socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT,
4430 array.array("i", [self.hop_limit]))]),
4431 len(MSG))
4432
4433 def checkTrafficClassAndHopLimit(self, ancbufsize, maxhop=255,
4434 ignoreflags=0):
4435 # Receive traffic class and hop limit into ancbufsize bytes of
4436 # ancillary data space. Check that data is MSG, ancillary
4437 # data is not truncated (but ignore any flags in ignoreflags),
4438 # and traffic class and hop limit are in range (hop limit no
4439 # more than maxhop).
4440 self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
4441 socket.IPV6_RECVHOPLIMIT, 1)
4442 self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
4443 socket.IPV6_RECVTCLASS, 1)
4444 self.misc_event.set()
4445 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
4446 len(MSG), ancbufsize)
4447
4448 self.assertEqual(msg, MSG)
4449 self.checkRecvmsgAddress(addr, self.cli_addr)
4450 self.checkFlags(flags, eor=True, checkunset=socket.MSG_CTRUNC,
4451 ignore=ignoreflags)
4452 self.assertEqual(len(ancdata), 2)
4453 ancmap = self.ancillaryMapping(ancdata)
4454
4455 tcdata = ancmap[(socket.IPPROTO_IPV6, socket.IPV6_TCLASS)]
4456 self.assertEqual(len(tcdata), SIZEOF_INT)
4457 a = array.array("i")
4458 a.frombytes(tcdata)
4459 self.assertGreaterEqual(a[0], 0)
4460 self.assertLessEqual(a[0], 255)
4461
4462 hldata = ancmap[(socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT)]
4463 self.assertEqual(len(hldata), SIZEOF_INT)
4464 a = array.array("i")
4465 a.frombytes(hldata)
4466 self.assertGreaterEqual(a[0], 0)
4467 self.assertLessEqual(a[0], maxhop)
4468
4469 @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
4470 "IPV6_RECVTCLASS", "IPV6_TCLASS")
4471 def testRecvTrafficClassAndHopLimit(self):
4472 # Test receiving traffic class and hop limit as ancillary data.
4473 self.checkTrafficClassAndHopLimit(ancbufsize=10240)
4474
4475 @testRecvTrafficClassAndHopLimit.client_skip
4476 def _testRecvTrafficClassAndHopLimit(self):
4477 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
4478 self.sendToServer(MSG)
4479
4480 @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
4481 "IPV6_RECVTCLASS", "IPV6_TCLASS")
4482 def testRecvTrafficClassAndHopLimitCMSG_SPACE(self):
4483 # Test receiving traffic class and hop limit, using
4484 # CMSG_SPACE() to calculate buffer size.
4485 self.checkTrafficClassAndHopLimit(
4486 ancbufsize=socket.CMSG_SPACE(SIZEOF_INT) * 2)
4487
4488 @testRecvTrafficClassAndHopLimitCMSG_SPACE.client_skip
4489 def _testRecvTrafficClassAndHopLimitCMSG_SPACE(self):
4490 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
4491 self.sendToServer(MSG)
4492
4493 @requireAttrs(socket.socket, "sendmsg")
4494 @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
4495 "IPV6_RECVTCLASS", "IPV6_TCLASS")
4496 def testSetTrafficClassAndHopLimit(self):
4497 # Test setting traffic class and hop limit on outgoing packet,
4498 # and receiving them at the other end.
4499 self.checkTrafficClassAndHopLimit(ancbufsize=10240,
4500 maxhop=self.hop_limit)
4501
4502 @testSetTrafficClassAndHopLimit.client_skip
4503 def _testSetTrafficClassAndHopLimit(self):
4504 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
4505 self.assertEqual(
4506 self.sendmsgToServer([MSG],
4507 [(socket.IPPROTO_IPV6, socket.IPV6_TCLASS,
4508 array.array("i", [self.traffic_class])),
4509 (socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT,
4510 array.array("i", [self.hop_limit]))]),
4511 len(MSG))
4512
4513 @requireAttrs(socket.socket, "sendmsg")
4514 @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
4515 "IPV6_RECVTCLASS", "IPV6_TCLASS")
4516 def testOddCmsgSize(self):
4517 # Try to send ancillary data with first item one byte too
4518 # long. Fall back to sending with correct size if this fails,
4519 # and check that second item was handled correctly.
4520 self.checkTrafficClassAndHopLimit(ancbufsize=10240,
4521 maxhop=self.hop_limit)
4522
4523 @testOddCmsgSize.client_skip
4524 def _testOddCmsgSize(self):
4525 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
4526 try:
4527 nbytes = self.sendmsgToServer(
4528 [MSG],
4529 [(socket.IPPROTO_IPV6, socket.IPV6_TCLASS,
4530 array.array("i", [self.traffic_class]).tobytes() + b"\x00"),
4531 (socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT,
4532 array.array("i", [self.hop_limit]))])
4533 except OSError as e:
4534 self.assertIsInstance(e.errno, int)
4535 nbytes = self.sendmsgToServer(
4536 [MSG],
4537 [(socket.IPPROTO_IPV6, socket.IPV6_TCLASS,
4538 array.array("i", [self.traffic_class])),
4539 (socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT,
4540 array.array("i", [self.hop_limit]))])
4541 self.assertEqual(nbytes, len(MSG))
4542
4543 # Tests for proper handling of truncated ancillary data
4544
4545 def checkHopLimitTruncatedHeader(self, ancbufsize, ignoreflags=0):
4546 # Receive hop limit into ancbufsize bytes of ancillary data
4547 # space, which should be too small to contain the ancillary
4548 # data header (if ancbufsize is None, pass no second argument
4549 # to recvmsg()). Check that data is MSG, MSG_CTRUNC is set
4550 # (unless included in ignoreflags), and no ancillary data is
4551 # returned.
4552 self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
4553 socket.IPV6_RECVHOPLIMIT, 1)
4554 self.misc_event.set()
4555 args = () if ancbufsize is None else (ancbufsize,)
4556 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
4557 len(MSG), *args)
4558
4559 self.assertEqual(msg, MSG)
4560 self.checkRecvmsgAddress(addr, self.cli_addr)
4561 self.assertEqual(ancdata, [])
4562 self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC,
4563 ignore=ignoreflags)
4564
4565 @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
4566 def testCmsgTruncNoBufSize(self):
4567 # Check that no ancillary data is received when no ancillary
4568 # buffer size is provided.
4569 self.checkHopLimitTruncatedHeader(ancbufsize=None,
4570 # BSD seems to set
4571 # MSG_CTRUNC only if an item
4572 # has been partially
4573 # received.
4574 ignoreflags=socket.MSG_CTRUNC)
4575
4576 @testCmsgTruncNoBufSize.client_skip
4577 def _testCmsgTruncNoBufSize(self):
4578 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
4579 self.sendToServer(MSG)
4580
4581 @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
4582 def testSingleCmsgTrunc0(self):
4583 # Check that no ancillary data is received when ancillary
4584 # buffer size is zero.
4585 self.checkHopLimitTruncatedHeader(ancbufsize=0,
4586 ignoreflags=socket.MSG_CTRUNC)
4587
4588 @testSingleCmsgTrunc0.client_skip
4589 def _testSingleCmsgTrunc0(self):
4590 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
4591 self.sendToServer(MSG)
4592
4593 # Check that no ancillary data is returned for various non-zero
4594 # (but still too small) buffer sizes.
4595
4596 @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
4597 def testSingleCmsgTrunc1(self):
4598 self.checkHopLimitTruncatedHeader(ancbufsize=1)
4599
4600 @testSingleCmsgTrunc1.client_skip
4601 def _testSingleCmsgTrunc1(self):
4602 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
4603 self.sendToServer(MSG)
4604
4605 @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
4606 def testSingleCmsgTrunc2Int(self):
4607 self.checkHopLimitTruncatedHeader(ancbufsize=2 * SIZEOF_INT)
4608
4609 @testSingleCmsgTrunc2Int.client_skip
4610 def _testSingleCmsgTrunc2Int(self):
4611 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
4612 self.sendToServer(MSG)
4613
4614 @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
4615 def testSingleCmsgTruncLen0Minus1(self):
4616 self.checkHopLimitTruncatedHeader(ancbufsize=socket.CMSG_LEN(0) - 1)
4617
4618 @testSingleCmsgTruncLen0Minus1.client_skip
4619 def _testSingleCmsgTruncLen0Minus1(self):
4620 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
4621 self.sendToServer(MSG)
4622
4623 @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
4624 def testSingleCmsgTruncInData(self):
4625 # Test truncation of a control message inside its associated
4626 # data. The message may be returned with its data truncated,
4627 # or not returned at all.
4628 self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
4629 socket.IPV6_RECVHOPLIMIT, 1)
4630 self.misc_event.set()
4631 with downgrade_malformed_data_warning(): # TODO: gh-110012
4632 msg, ancdata, flags, addr = self.doRecvmsg(
4633 self.serv_sock, len(MSG), socket.CMSG_LEN(SIZEOF_INT) - 1)
4634
4635 self.assertEqual(msg, MSG)
4636 self.checkRecvmsgAddress(addr, self.cli_addr)
4637 self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC)
4638
4639 self.assertLessEqual(len(ancdata), 1)
4640 if ancdata:
4641 cmsg_level, cmsg_type, cmsg_data = ancdata[0]
4642 self.assertEqual(cmsg_level, socket.IPPROTO_IPV6)
4643 self.assertEqual(cmsg_type, socket.IPV6_HOPLIMIT)
4644 self.assertLess(len(cmsg_data), SIZEOF_INT)
4645
4646 @testSingleCmsgTruncInData.client_skip
4647 def _testSingleCmsgTruncInData(self):
4648 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
4649 self.sendToServer(MSG)
4650
4651 def checkTruncatedSecondHeader(self, ancbufsize, ignoreflags=0):
4652 # Receive traffic class and hop limit into ancbufsize bytes of
4653 # ancillary data space, which should be large enough to
4654 # contain the first item, but too small to contain the header
4655 # of the second. Check that data is MSG, MSG_CTRUNC is set
4656 # (unless included in ignoreflags), and only one ancillary
4657 # data item is returned.
4658 self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
4659 socket.IPV6_RECVHOPLIMIT, 1)
4660 self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
4661 socket.IPV6_RECVTCLASS, 1)
4662 self.misc_event.set()
4663 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
4664 len(MSG), ancbufsize)
4665
4666 self.assertEqual(msg, MSG)
4667 self.checkRecvmsgAddress(addr, self.cli_addr)
4668 self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC,
4669 ignore=ignoreflags)
4670
4671 self.assertEqual(len(ancdata), 1)
4672 cmsg_level, cmsg_type, cmsg_data = ancdata[0]
4673 self.assertEqual(cmsg_level, socket.IPPROTO_IPV6)
4674 self.assertIn(cmsg_type, {socket.IPV6_TCLASS, socket.IPV6_HOPLIMIT})
4675 self.assertEqual(len(cmsg_data), SIZEOF_INT)
4676 a = array.array("i")
4677 a.frombytes(cmsg_data)
4678 self.assertGreaterEqual(a[0], 0)
4679 self.assertLessEqual(a[0], 255)
4680
4681 # Try the above test with various buffer sizes.
4682
4683 @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
4684 "IPV6_RECVTCLASS", "IPV6_TCLASS")
4685 def testSecondCmsgTrunc0(self):
4686 self.checkTruncatedSecondHeader(socket.CMSG_SPACE(SIZEOF_INT),
4687 ignoreflags=socket.MSG_CTRUNC)
4688
4689 @testSecondCmsgTrunc0.client_skip
4690 def _testSecondCmsgTrunc0(self):
4691 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
4692 self.sendToServer(MSG)
4693
4694 @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
4695 "IPV6_RECVTCLASS", "IPV6_TCLASS")
4696 def testSecondCmsgTrunc1(self):
4697 self.checkTruncatedSecondHeader(socket.CMSG_SPACE(SIZEOF_INT) + 1)
4698
4699 @testSecondCmsgTrunc1.client_skip
4700 def _testSecondCmsgTrunc1(self):
4701 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
4702 self.sendToServer(MSG)
4703
4704 @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
4705 "IPV6_RECVTCLASS", "IPV6_TCLASS")
4706 def testSecondCmsgTrunc2Int(self):
4707 self.checkTruncatedSecondHeader(socket.CMSG_SPACE(SIZEOF_INT) +
4708 2 * SIZEOF_INT)
4709
4710 @testSecondCmsgTrunc2Int.client_skip
4711 def _testSecondCmsgTrunc2Int(self):
4712 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
4713 self.sendToServer(MSG)
4714
4715 @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
4716 "IPV6_RECVTCLASS", "IPV6_TCLASS")
4717 def testSecondCmsgTruncLen0Minus1(self):
4718 self.checkTruncatedSecondHeader(socket.CMSG_SPACE(SIZEOF_INT) +
4719 socket.CMSG_LEN(0) - 1)
4720
4721 @testSecondCmsgTruncLen0Minus1.client_skip
4722 def _testSecondCmsgTruncLen0Minus1(self):
4723 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
4724 self.sendToServer(MSG)
4725
4726 @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
4727 "IPV6_RECVTCLASS", "IPV6_TCLASS")
4728 def testSecondCmsgTruncInData(self):
4729 # Test truncation of the second of two control messages inside
4730 # its associated data.
4731 self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
4732 socket.IPV6_RECVHOPLIMIT, 1)
4733 self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
4734 socket.IPV6_RECVTCLASS, 1)
4735 self.misc_event.set()
4736 with downgrade_malformed_data_warning(): # TODO: gh-110012
4737 msg, ancdata, flags, addr = self.doRecvmsg(
4738 self.serv_sock, len(MSG),
4739 socket.CMSG_SPACE(SIZEOF_INT) + socket.CMSG_LEN(SIZEOF_INT) - 1)
4740
4741 self.assertEqual(msg, MSG)
4742 self.checkRecvmsgAddress(addr, self.cli_addr)
4743 self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC)
4744
4745 cmsg_types = {socket.IPV6_TCLASS, socket.IPV6_HOPLIMIT}
4746
4747 cmsg_level, cmsg_type, cmsg_data = ancdata.pop(0)
4748 self.assertEqual(cmsg_level, socket.IPPROTO_IPV6)
4749 cmsg_types.remove(cmsg_type)
4750 self.assertEqual(len(cmsg_data), SIZEOF_INT)
4751 a = array.array("i")
4752 a.frombytes(cmsg_data)
4753 self.assertGreaterEqual(a[0], 0)
4754 self.assertLessEqual(a[0], 255)
4755
4756 if ancdata:
4757 cmsg_level, cmsg_type, cmsg_data = ancdata.pop(0)
4758 self.assertEqual(cmsg_level, socket.IPPROTO_IPV6)
4759 cmsg_types.remove(cmsg_type)
4760 self.assertLess(len(cmsg_data), SIZEOF_INT)
4761
4762 self.assertEqual(ancdata, [])
4763
4764 @testSecondCmsgTruncInData.client_skip
4765 def _testSecondCmsgTruncInData(self):
4766 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
4767 self.sendToServer(MSG)
4768
4769
4770 # Derive concrete test classes for different socket types.
4771
4772 class SendrecvmsgUDPTestBase(SendrecvmsgDgramFlagsBase,
4773 SendrecvmsgConnectionlessBase,
4774 ThreadedSocketTestMixin, UDPTestBase):
4775 pass
4776
4777 @requireAttrs(socket.socket, "sendmsg")
4778 class SendmsgUDPTest(SendmsgConnectionlessTests, SendrecvmsgUDPTestBase):
4779 pass
4780
4781 @requireAttrs(socket.socket, "recvmsg")
4782 class RecvmsgUDPTest(RecvmsgTests, SendrecvmsgUDPTestBase):
4783 pass
4784
4785 @requireAttrs(socket.socket, "recvmsg_into")
4786 class RecvmsgIntoUDPTest(RecvmsgIntoTests, SendrecvmsgUDPTestBase):
4787 pass
4788
4789
4790 class SendrecvmsgUDP6TestBase(SendrecvmsgDgramFlagsBase,
4791 SendrecvmsgConnectionlessBase,
4792 ThreadedSocketTestMixin, UDP6TestBase):
4793
4794 def checkRecvmsgAddress(self, addr1, addr2):
4795 # Called to compare the received address with the address of
4796 # the peer, ignoring scope ID
4797 self.assertEqual(addr1[:-1], addr2[:-1])
4798
4799 @requireAttrs(socket.socket, "sendmsg")
4800 @unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.')
4801 @requireSocket("AF_INET6", "SOCK_DGRAM")
4802 class SendmsgUDP6Test(SendmsgConnectionlessTests, SendrecvmsgUDP6TestBase):
4803 pass
4804
4805 @requireAttrs(socket.socket, "recvmsg")
4806 @unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.')
4807 @requireSocket("AF_INET6", "SOCK_DGRAM")
4808 class RecvmsgUDP6Test(RecvmsgTests, SendrecvmsgUDP6TestBase):
4809 pass
4810
4811 @requireAttrs(socket.socket, "recvmsg_into")
4812 @unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.')
4813 @requireSocket("AF_INET6", "SOCK_DGRAM")
4814 class RecvmsgIntoUDP6Test(RecvmsgIntoTests, SendrecvmsgUDP6TestBase):
4815 pass
4816
4817 @requireAttrs(socket.socket, "recvmsg")
4818 @unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.')
4819 @requireAttrs(socket, "IPPROTO_IPV6")
4820 @requireSocket("AF_INET6", "SOCK_DGRAM")
4821 class RecvmsgRFC3542AncillaryUDP6Test(RFC3542AncillaryTest,
4822 SendrecvmsgUDP6TestBase):
4823 pass
4824
4825 @requireAttrs(socket.socket, "recvmsg_into")
4826 @unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.')
4827 @requireAttrs(socket, "IPPROTO_IPV6")
4828 @requireSocket("AF_INET6", "SOCK_DGRAM")
4829 class RecvmsgIntoRFC3542AncillaryUDP6Test(RecvmsgIntoMixin,
4830 RFC3542AncillaryTest,
4831 SendrecvmsgUDP6TestBase):
4832 pass
4833
4834
4835 @unittest.skipUnless(HAVE_SOCKET_UDPLITE,
4836 'UDPLITE sockets required for this test.')
4837 class SendrecvmsgUDPLITETestBase(SendrecvmsgDgramFlagsBase,
4838 SendrecvmsgConnectionlessBase,
4839 ThreadedSocketTestMixin, UDPLITETestBase):
4840 pass
4841
4842 @unittest.skipUnless(HAVE_SOCKET_UDPLITE,
4843 'UDPLITE sockets required for this test.')
4844 @requireAttrs(socket.socket, "sendmsg")
4845 class SendmsgUDPLITETest(SendmsgConnectionlessTests, SendrecvmsgUDPLITETestBase):
4846 pass
4847
4848 @unittest.skipUnless(HAVE_SOCKET_UDPLITE,
4849 'UDPLITE sockets required for this test.')
4850 @requireAttrs(socket.socket, "recvmsg")
4851 class RecvmsgUDPLITETest(RecvmsgTests, SendrecvmsgUDPLITETestBase):
4852 pass
4853
4854 @unittest.skipUnless(HAVE_SOCKET_UDPLITE,
4855 'UDPLITE sockets required for this test.')
4856 @requireAttrs(socket.socket, "recvmsg_into")
4857 class RecvmsgIntoUDPLITETest(RecvmsgIntoTests, SendrecvmsgUDPLITETestBase):
4858 pass
4859
4860
4861 @unittest.skipUnless(HAVE_SOCKET_UDPLITE,
4862 'UDPLITE sockets required for this test.')
4863 class SendrecvmsgUDPLITE6TestBase(SendrecvmsgDgramFlagsBase,
4864 SendrecvmsgConnectionlessBase,
4865 ThreadedSocketTestMixin, UDPLITE6TestBase):
4866
4867 def checkRecvmsgAddress(self, addr1, addr2):
4868 # Called to compare the received address with the address of
4869 # the peer, ignoring scope ID
4870 self.assertEqual(addr1[:-1], addr2[:-1])
4871
4872 @requireAttrs(socket.socket, "sendmsg")
4873 @unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.')
4874 @unittest.skipUnless(HAVE_SOCKET_UDPLITE,
4875 'UDPLITE sockets required for this test.')
4876 @requireSocket("AF_INET6", "SOCK_DGRAM")
4877 class SendmsgUDPLITE6Test(SendmsgConnectionlessTests, SendrecvmsgUDPLITE6TestBase):
4878 pass
4879
4880 @requireAttrs(socket.socket, "recvmsg")
4881 @unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.')
4882 @unittest.skipUnless(HAVE_SOCKET_UDPLITE,
4883 'UDPLITE sockets required for this test.')
4884 @requireSocket("AF_INET6", "SOCK_DGRAM")
4885 class RecvmsgUDPLITE6Test(RecvmsgTests, SendrecvmsgUDPLITE6TestBase):
4886 pass
4887
4888 @requireAttrs(socket.socket, "recvmsg_into")
4889 @unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.')
4890 @unittest.skipUnless(HAVE_SOCKET_UDPLITE,
4891 'UDPLITE sockets required for this test.')
4892 @requireSocket("AF_INET6", "SOCK_DGRAM")
4893 class RecvmsgIntoUDPLITE6Test(RecvmsgIntoTests, SendrecvmsgUDPLITE6TestBase):
4894 pass
4895
4896 @requireAttrs(socket.socket, "recvmsg")
4897 @unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.')
4898 @unittest.skipUnless(HAVE_SOCKET_UDPLITE,
4899 'UDPLITE sockets required for this test.')
4900 @requireAttrs(socket, "IPPROTO_IPV6")
4901 @requireSocket("AF_INET6", "SOCK_DGRAM")
4902 class RecvmsgRFC3542AncillaryUDPLITE6Test(RFC3542AncillaryTest,
4903 SendrecvmsgUDPLITE6TestBase):
4904 pass
4905
4906 @requireAttrs(socket.socket, "recvmsg_into")
4907 @unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.')
4908 @unittest.skipUnless(HAVE_SOCKET_UDPLITE,
4909 'UDPLITE sockets required for this test.')
4910 @requireAttrs(socket, "IPPROTO_IPV6")
4911 @requireSocket("AF_INET6", "SOCK_DGRAM")
4912 class RecvmsgIntoRFC3542AncillaryUDPLITE6Test(RecvmsgIntoMixin,
4913 RFC3542AncillaryTest,
4914 SendrecvmsgUDPLITE6TestBase):
4915 pass
4916
4917
4918 class SendrecvmsgTCPTestBase(SendrecvmsgConnectedBase,
4919 ConnectedStreamTestMixin, TCPTestBase):
4920 pass
4921
4922 @requireAttrs(socket.socket, "sendmsg")
4923 class SendmsgTCPTest(SendmsgStreamTests, SendrecvmsgTCPTestBase):
4924 pass
4925
4926 @requireAttrs(socket.socket, "recvmsg")
4927 class RecvmsgTCPTest(RecvmsgTests, RecvmsgGenericStreamTests,
4928 SendrecvmsgTCPTestBase):
4929 pass
4930
4931 @requireAttrs(socket.socket, "recvmsg_into")
4932 class RecvmsgIntoTCPTest(RecvmsgIntoTests, RecvmsgGenericStreamTests,
4933 SendrecvmsgTCPTestBase):
4934 pass
4935
4936
4937 class SendrecvmsgSCTPStreamTestBase(SendrecvmsgSCTPFlagsBase,
4938 SendrecvmsgConnectedBase,
4939 ConnectedStreamTestMixin, SCTPStreamBase):
4940 pass
4941
4942 @requireAttrs(socket.socket, "sendmsg")
4943 @unittest.skipIf(AIX, "IPPROTO_SCTP: [Errno 62] Protocol not supported on AIX")
4944 @requireSocket("AF_INET", "SOCK_STREAM", "IPPROTO_SCTP")
4945 class SendmsgSCTPStreamTest(SendmsgStreamTests, SendrecvmsgSCTPStreamTestBase):
4946 pass
4947
4948 @requireAttrs(socket.socket, "recvmsg")
4949 @unittest.skipIf(AIX, "IPPROTO_SCTP: [Errno 62] Protocol not supported on AIX")
4950 @requireSocket("AF_INET", "SOCK_STREAM", "IPPROTO_SCTP")
4951 class RecvmsgSCTPStreamTest(RecvmsgTests, RecvmsgGenericStreamTests,
4952 SendrecvmsgSCTPStreamTestBase):
4953
4954 def testRecvmsgEOF(self):
4955 try:
4956 super(RecvmsgSCTPStreamTest, self).testRecvmsgEOF()
4957 except OSError as e:
4958 if e.errno != errno.ENOTCONN:
4959 raise
4960 self.skipTest("sporadic ENOTCONN (kernel issue?) - see issue #13876")
4961
4962 @requireAttrs(socket.socket, "recvmsg_into")
4963 @unittest.skipIf(AIX, "IPPROTO_SCTP: [Errno 62] Protocol not supported on AIX")
4964 @requireSocket("AF_INET", "SOCK_STREAM", "IPPROTO_SCTP")
4965 class RecvmsgIntoSCTPStreamTest(RecvmsgIntoTests, RecvmsgGenericStreamTests,
4966 SendrecvmsgSCTPStreamTestBase):
4967
4968 def testRecvmsgEOF(self):
4969 try:
4970 super(RecvmsgIntoSCTPStreamTest, self).testRecvmsgEOF()
4971 except OSError as e:
4972 if e.errno != errno.ENOTCONN:
4973 raise
4974 self.skipTest("sporadic ENOTCONN (kernel issue?) - see issue #13876")
4975
4976
4977 class SendrecvmsgUnixStreamTestBase(SendrecvmsgConnectedBase,
4978 ConnectedStreamTestMixin, UnixStreamBase):
4979 pass
4980
4981 @requireAttrs(socket.socket, "sendmsg")
4982 @requireAttrs(socket, "AF_UNIX")
4983 class SendmsgUnixStreamTest(SendmsgStreamTests, SendrecvmsgUnixStreamTestBase):
4984 pass
4985
4986 @requireAttrs(socket.socket, "recvmsg")
4987 @requireAttrs(socket, "AF_UNIX")
4988 class RecvmsgUnixStreamTest(RecvmsgTests, RecvmsgGenericStreamTests,
4989 SendrecvmsgUnixStreamTestBase):
4990 pass
4991
4992 @requireAttrs(socket.socket, "recvmsg_into")
4993 @requireAttrs(socket, "AF_UNIX")
4994 class RecvmsgIntoUnixStreamTest(RecvmsgIntoTests, RecvmsgGenericStreamTests,
4995 SendrecvmsgUnixStreamTestBase):
4996 pass
4997
4998 @requireAttrs(socket.socket, "sendmsg", "recvmsg")
4999 @requireAttrs(socket, "AF_UNIX", "SOL_SOCKET", "SCM_RIGHTS")
5000 class RecvmsgSCMRightsStreamTest(SCMRightsTest, SendrecvmsgUnixStreamTestBase):
5001 pass
5002
5003 @requireAttrs(socket.socket, "sendmsg", "recvmsg_into")
5004 @requireAttrs(socket, "AF_UNIX", "SOL_SOCKET", "SCM_RIGHTS")
5005 class RecvmsgIntoSCMRightsStreamTest(RecvmsgIntoMixin, SCMRightsTest,
5006 SendrecvmsgUnixStreamTestBase):
5007 pass
5008
5009
5010 # Test interrupting the interruptible send/receive methods with a
5011 # signal when a timeout is set. These tests avoid having multiple
5012 # threads alive during the test so that the OS cannot deliver the
5013 # signal to the wrong one.
5014
5015 class InterruptedTimeoutBase:
5016 # Base class for interrupted send/receive tests. Installs an
5017 # empty handler for SIGALRM and removes it on teardown, along with
5018 # any scheduled alarms.
5019
5020 def setUp(self):
5021 super().setUp()
5022 orig_alrm_handler = signal.signal(signal.SIGALRM,
5023 lambda signum, frame: 1 / 0)
5024 self.addCleanup(signal.signal, signal.SIGALRM, orig_alrm_handler)
5025
5026 # Timeout for socket operations
5027 timeout = support.LOOPBACK_TIMEOUT
5028
5029 # Provide setAlarm() method to schedule delivery of SIGALRM after
5030 # given number of seconds, or cancel it if zero, and an
5031 # appropriate time value to use. Use setitimer() if available.
5032 if hasattr(signal, "setitimer"):
5033 alarm_time = 0.05
5034
5035 def setAlarm(self, seconds):
5036 signal.setitimer(signal.ITIMER_REAL, seconds)
5037 else:
5038 # Old systems may deliver the alarm up to one second early
5039 alarm_time = 2
5040
5041 def setAlarm(self, seconds):
5042 signal.alarm(seconds)
5043
5044
5045 # Require siginterrupt() in order to ensure that system calls are
5046 # interrupted by default.
5047 @requireAttrs(signal, "siginterrupt")
5048 @unittest.skipUnless(hasattr(signal, "alarm") or hasattr(signal, "setitimer"),
5049 "Don't have signal.alarm or signal.setitimer")
5050 class InterruptedRecvTimeoutTest(InterruptedTimeoutBase, UDPTestBase):
5051 # Test interrupting the recv*() methods with signals when a
5052 # timeout is set.
5053
5054 def setUp(self):
5055 super().setUp()
5056 self.serv.settimeout(self.timeout)
5057
5058 def checkInterruptedRecv(self, func, *args, **kwargs):
5059 # Check that func(*args, **kwargs) raises
5060 # errno of EINTR when interrupted by a signal.
5061 try:
5062 self.setAlarm(self.alarm_time)
5063 with self.assertRaises(ZeroDivisionError) as cm:
5064 func(*args, **kwargs)
5065 finally:
5066 self.setAlarm(0)
5067
5068 def testInterruptedRecvTimeout(self):
5069 self.checkInterruptedRecv(self.serv.recv, 1024)
5070
5071 def testInterruptedRecvIntoTimeout(self):
5072 self.checkInterruptedRecv(self.serv.recv_into, bytearray(1024))
5073
5074 def testInterruptedRecvfromTimeout(self):
5075 self.checkInterruptedRecv(self.serv.recvfrom, 1024)
5076
5077 def testInterruptedRecvfromIntoTimeout(self):
5078 self.checkInterruptedRecv(self.serv.recvfrom_into, bytearray(1024))
5079
5080 @requireAttrs(socket.socket, "recvmsg")
5081 def testInterruptedRecvmsgTimeout(self):
5082 self.checkInterruptedRecv(self.serv.recvmsg, 1024)
5083
5084 @requireAttrs(socket.socket, "recvmsg_into")
5085 def testInterruptedRecvmsgIntoTimeout(self):
5086 self.checkInterruptedRecv(self.serv.recvmsg_into, [bytearray(1024)])
5087
5088
5089 # Require siginterrupt() in order to ensure that system calls are
5090 # interrupted by default.
5091 @requireAttrs(signal, "siginterrupt")
5092 @unittest.skipUnless(hasattr(signal, "alarm") or hasattr(signal, "setitimer"),
5093 "Don't have signal.alarm or signal.setitimer")
5094 class InterruptedSendTimeoutTest(InterruptedTimeoutBase,
5095 SocketListeningTestMixin, TCPTestBase):
5096 # Test interrupting the interruptible send*() methods with signals
5097 # when a timeout is set.
5098
5099 def setUp(self):
5100 super().setUp()
5101 self.serv_conn = self.newSocket()
5102 self.addCleanup(self.serv_conn.close)
5103 # Use a thread to complete the connection, but wait for it to
5104 # terminate before running the test, so that there is only one
5105 # thread to accept the signal.
5106 cli_thread = threading.Thread(target=self.doConnect)
5107 cli_thread.start()
5108 self.cli_conn, addr = self.serv.accept()
5109 self.addCleanup(self.cli_conn.close)
5110 cli_thread.join()
5111 self.serv_conn.settimeout(self.timeout)
5112
5113 def doConnect(self):
5114 self.serv_conn.connect(self.serv_addr)
5115
5116 def checkInterruptedSend(self, func, *args, **kwargs):
5117 # Check that func(*args, **kwargs), run in a loop, raises
5118 # OSError with an errno of EINTR when interrupted by a
5119 # signal.
5120 try:
5121 with self.assertRaises(ZeroDivisionError) as cm:
5122 while True:
5123 self.setAlarm(self.alarm_time)
5124 func(*args, **kwargs)
5125 finally:
5126 self.setAlarm(0)
5127
5128 # Issue #12958: The following tests have problems on OS X prior to 10.7
5129 @support.requires_mac_ver(10, 7)
5130 def testInterruptedSendTimeout(self):
5131 self.checkInterruptedSend(self.serv_conn.send, b"a"*512)
5132
5133 @support.requires_mac_ver(10, 7)
5134 def testInterruptedSendtoTimeout(self):
5135 # Passing an actual address here as Python's wrapper for
5136 # sendto() doesn't allow passing a zero-length one; POSIX
5137 # requires that the address is ignored since the socket is
5138 # connection-mode, however.
5139 self.checkInterruptedSend(self.serv_conn.sendto, b"a"*512,
5140 self.serv_addr)
5141
5142 @support.requires_mac_ver(10, 7)
5143 @requireAttrs(socket.socket, "sendmsg")
5144 def testInterruptedSendmsgTimeout(self):
5145 self.checkInterruptedSend(self.serv_conn.sendmsg, [b"a"*512])
5146
5147
5148 class TCPCloserTest(ThreadedTCPSocketTest):
5149 def testClose(self):
5150 conn, _ = self.serv.accept()
5151
5152 read, _, _ = select.select([conn], [], [], support.SHORT_TIMEOUT)
5153 self.assertEqual(read, [conn])
5154 self.assertEqual(conn.recv(1), b'x')
5155 conn.close()
5156
5157 # Calling close() many times should be safe.
5158 conn.close()
5159 conn.close()
5160
5161 def _testClose(self):
5162 self.cli.connect((HOST, self.port))
5163 self.cli.send(b'x')
5164 read, _, _ = select.select([self.cli], [], [], support.SHORT_TIMEOUT)
5165 self.assertEqual(read, [self.cli])
5166 self.assertEqual(self.cli.recv(1), b'')
5167
5168
5169 class BasicSocketPairTest(SocketPairTest):
5170
5171 def __init__(self, methodName='runTest'):
5172 SocketPairTest.__init__(self, methodName=methodName)
5173
5174 def _check_defaults(self, sock):
5175 self.assertIsInstance(sock, socket.socket)
5176 if hasattr(socket, 'AF_UNIX'):
5177 self.assertEqual(sock.family, socket.AF_UNIX)
5178 else:
5179 self.assertEqual(sock.family, socket.AF_INET)
5180 self.assertEqual(sock.type, socket.SOCK_STREAM)
5181 self.assertEqual(sock.proto, 0)
5182
5183 def _testDefaults(self):
5184 self._check_defaults(self.cli)
5185
5186 def testDefaults(self):
5187 self._check_defaults(self.serv)
5188
5189 def testRecv(self):
5190 msg = self.serv.recv(1024)
5191 self.assertEqual(msg, MSG)
5192
5193 def _testRecv(self):
5194 self.cli.send(MSG)
5195
5196 def testSend(self):
5197 self.serv.send(MSG)
5198
5199 def _testSend(self):
5200 msg = self.cli.recv(1024)
5201 self.assertEqual(msg, MSG)
5202
5203
5204 class PurePythonSocketPairTest(SocketPairTest):
5205 # Explicitly use socketpair AF_INET or AF_INET6 to ensure that is the
5206 # code path we're using regardless platform is the pure python one where
5207 # `_socket.socketpair` does not exist. (AF_INET does not work with
5208 # _socket.socketpair on many platforms).
5209 def socketpair(self):
5210 # called by super().setUp().
5211 try:
5212 return socket.socketpair(socket.AF_INET6)
5213 except OSError:
5214 return socket.socketpair(socket.AF_INET)
5215
5216 # Local imports in this class make for easy security fix backporting.
5217
5218 def setUp(self):
5219 if hasattr(_socket, "socketpair"):
5220 self._orig_sp = socket.socketpair
5221 # This forces the version using the non-OS provided socketpair
5222 # emulation via an AF_INET socket in Lib/socket.py.
5223 socket.socketpair = socket._fallback_socketpair
5224 else:
5225 # This platform already uses the non-OS provided version.
5226 self._orig_sp = None
5227 super().setUp()
5228
5229 def tearDown(self):
5230 super().tearDown()
5231 if self._orig_sp is not None:
5232 # Restore the default socket.socketpair definition.
5233 socket.socketpair = self._orig_sp
5234
5235 def test_recv(self):
5236 msg = self.serv.recv(1024)
5237 self.assertEqual(msg, MSG)
5238
5239 def _test_recv(self):
5240 self.cli.send(MSG)
5241
5242 def test_send(self):
5243 self.serv.send(MSG)
5244
5245 def _test_send(self):
5246 msg = self.cli.recv(1024)
5247 self.assertEqual(msg, MSG)
5248
5249 def test_ipv4(self):
5250 cli, srv = socket.socketpair(socket.AF_INET)
5251 cli.close()
5252 srv.close()
5253
5254 def _test_ipv4(self):
5255 pass
5256
5257 @unittest.skipIf(not hasattr(_socket, 'IPPROTO_IPV6') or
5258 not hasattr(_socket, 'IPV6_V6ONLY'),
5259 "IPV6_V6ONLY option not supported")
5260 @unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test')
5261 def test_ipv6(self):
5262 cli, srv = socket.socketpair(socket.AF_INET6)
5263 cli.close()
5264 srv.close()
5265
5266 def _test_ipv6(self):
5267 pass
5268
5269 def test_injected_authentication_failure(self):
5270 orig_getsockname = socket.socket.getsockname
5271 inject_sock = None
5272
5273 def inject_getsocketname(self):
5274 nonlocal inject_sock
5275 sockname = orig_getsockname(self)
5276 # Connect to the listening socket ahead of the
5277 # client socket.
5278 if inject_sock is None:
5279 inject_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
5280 inject_sock.setblocking(False)
5281 try:
5282 inject_sock.connect(sockname[:2])
5283 except (BlockingIOError, InterruptedError):
5284 pass
5285 inject_sock.setblocking(True)
5286 return sockname
5287
5288 sock1 = sock2 = None
5289 try:
5290 socket.socket.getsockname = inject_getsocketname
5291 with self.assertRaises(OSError):
5292 sock1, sock2 = socket.socketpair()
5293 finally:
5294 socket.socket.getsockname = orig_getsockname
5295 if inject_sock:
5296 inject_sock.close()
5297 if sock1: # This cleanup isn't needed on a successful test.
5298 sock1.close()
5299 if sock2:
5300 sock2.close()
5301
5302 def _test_injected_authentication_failure(self):
5303 # No-op. Exists for base class threading infrastructure to call.
5304 # We could refactor this test into its own lesser class along with the
5305 # setUp and tearDown code to construct an ideal; it is simpler to keep
5306 # it here and live with extra overhead one this _one_ failure test.
5307 pass
5308
5309
5310 class NonBlockingTCPTests(ThreadedTCPSocketTest):
5311
5312 def __init__(self, methodName='runTest'):
5313 self.event = threading.Event()
5314 ThreadedTCPSocketTest.__init__(self, methodName=methodName)
5315
5316 def assert_sock_timeout(self, sock, timeout):
5317 self.assertEqual(self.serv.gettimeout(), timeout)
5318
5319 blocking = (timeout != 0.0)
5320 self.assertEqual(sock.getblocking(), blocking)
5321
5322 if fcntl is not None:
5323 # When a Python socket has a non-zero timeout, it's switched
5324 # internally to a non-blocking mode. Later, sock.sendall(),
5325 # sock.recv(), and other socket operations use a select() call and
5326 # handle EWOULDBLOCK/EGAIN on all socket operations. That's how
5327 # timeouts are enforced.
5328 fd_blocking = (timeout is None)
5329
5330 flag = fcntl.fcntl(sock, fcntl.F_GETFL, os.O_NONBLOCK)
5331 self.assertEqual(not bool(flag & os.O_NONBLOCK), fd_blocking)
5332
5333 def testSetBlocking(self):
5334 # Test setblocking() and settimeout() methods
5335 self.serv.setblocking(True)
5336 self.assert_sock_timeout(self.serv, None)
5337
5338 self.serv.setblocking(False)
5339 self.assert_sock_timeout(self.serv, 0.0)
5340
5341 self.serv.settimeout(None)
5342 self.assert_sock_timeout(self.serv, None)
5343
5344 self.serv.settimeout(0)
5345 self.assert_sock_timeout(self.serv, 0)
5346
5347 self.serv.settimeout(10)
5348 self.assert_sock_timeout(self.serv, 10)
5349
5350 self.serv.settimeout(0)
5351 self.assert_sock_timeout(self.serv, 0)
5352
5353 def _testSetBlocking(self):
5354 pass
5355
5356 @support.cpython_only
5357 @unittest.skipIf(_testcapi is None, "requires _testcapi")
5358 def testSetBlocking_overflow(self):
5359 # Issue 15989
5360 import _testcapi
5361 if _testcapi.UINT_MAX >= _testcapi.ULONG_MAX:
5362 self.skipTest('needs UINT_MAX < ULONG_MAX')
5363
5364 self.serv.setblocking(False)
5365 self.assertEqual(self.serv.gettimeout(), 0.0)
5366
5367 self.serv.setblocking(_testcapi.UINT_MAX + 1)
5368 self.assertIsNone(self.serv.gettimeout())
5369
5370 _testSetBlocking_overflow = support.cpython_only(_testSetBlocking)
5371
5372 @unittest.skipUnless(hasattr(socket, 'SOCK_NONBLOCK'),
5373 'test needs socket.SOCK_NONBLOCK')
5374 @support.requires_linux_version(2, 6, 28)
5375 def testInitNonBlocking(self):
5376 # create a socket with SOCK_NONBLOCK
5377 self.serv.close()
5378 self.serv = socket.socket(socket.AF_INET,
5379 socket.SOCK_STREAM | socket.SOCK_NONBLOCK)
5380 self.assert_sock_timeout(self.serv, 0)
5381
5382 def _testInitNonBlocking(self):
5383 pass
5384
5385 def testInheritFlagsBlocking(self):
5386 # bpo-7995: accept() on a listening socket with a timeout and the
5387 # default timeout is None, the resulting socket must be blocking.
5388 with socket_setdefaulttimeout(None):
5389 self.serv.settimeout(10)
5390 conn, addr = self.serv.accept()
5391 self.addCleanup(conn.close)
5392 self.assertIsNone(conn.gettimeout())
5393
5394 def _testInheritFlagsBlocking(self):
5395 self.cli.connect((HOST, self.port))
5396
5397 def testInheritFlagsTimeout(self):
5398 # bpo-7995: accept() on a listening socket with a timeout and the
5399 # default timeout is None, the resulting socket must inherit
5400 # the default timeout.
5401 default_timeout = 20.0
5402 with socket_setdefaulttimeout(default_timeout):
5403 self.serv.settimeout(10)
5404 conn, addr = self.serv.accept()
5405 self.addCleanup(conn.close)
5406 self.assertEqual(conn.gettimeout(), default_timeout)
5407
5408 def _testInheritFlagsTimeout(self):
5409 self.cli.connect((HOST, self.port))
5410
5411 def testAccept(self):
5412 # Testing non-blocking accept
5413 self.serv.setblocking(False)
5414
5415 # connect() didn't start: non-blocking accept() fails
5416 start_time = time.monotonic()
5417 with self.assertRaises(BlockingIOError):
5418 conn, addr = self.serv.accept()
5419 dt = time.monotonic() - start_time
5420 self.assertLess(dt, 1.0)
5421
5422 self.event.set()
5423
5424 read, write, err = select.select([self.serv], [], [], support.LONG_TIMEOUT)
5425 if self.serv not in read:
5426 self.fail("Error trying to do accept after select.")
5427
5428 # connect() completed: non-blocking accept() doesn't block
5429 conn, addr = self.serv.accept()
5430 self.addCleanup(conn.close)
5431 self.assertIsNone(conn.gettimeout())
5432
5433 def _testAccept(self):
5434 # don't connect before event is set to check
5435 # that non-blocking accept() raises BlockingIOError
5436 self.event.wait()
5437
5438 self.cli.connect((HOST, self.port))
5439
5440 def testRecv(self):
5441 # Testing non-blocking recv
5442 conn, addr = self.serv.accept()
5443 self.addCleanup(conn.close)
5444 conn.setblocking(False)
5445
5446 # the server didn't send data yet: non-blocking recv() fails
5447 with self.assertRaises(BlockingIOError):
5448 msg = conn.recv(len(MSG))
5449
5450 self.event.set()
5451
5452 read, write, err = select.select([conn], [], [], support.LONG_TIMEOUT)
5453 if conn not in read:
5454 self.fail("Error during select call to non-blocking socket.")
5455
5456 # the server sent data yet: non-blocking recv() doesn't block
5457 msg = conn.recv(len(MSG))
5458 self.assertEqual(msg, MSG)
5459
5460 def _testRecv(self):
5461 self.cli.connect((HOST, self.port))
5462
5463 # don't send anything before event is set to check
5464 # that non-blocking recv() raises BlockingIOError
5465 self.event.wait()
5466
5467 # send data: recv() will no longer block
5468 self.cli.sendall(MSG)
5469
5470 def testLargeTimeout(self):
5471 # gh-126876: Check that a timeout larger than INT_MAX is replaced with
5472 # INT_MAX in the poll() code path. The following assertion must not
5473 # fail: assert(INT_MIN <= ms && ms <= INT_MAX).
5474 if _testcapi is not None:
5475 large_timeout = _testcapi.INT_MAX + 1
5476 else:
5477 large_timeout = 2147483648
5478
5479 # test recv() with large timeout
5480 conn, addr = self.serv.accept()
5481 self.addCleanup(conn.close)
5482 try:
5483 conn.settimeout(large_timeout)
5484 except OverflowError:
5485 # On Windows, settimeout() fails with OverflowError, whereas
5486 # we want to test recv(). Just give up silently.
5487 return
5488 msg = conn.recv(len(MSG))
5489
5490 def _testLargeTimeout(self):
5491 # test sendall() with large timeout
5492 if _testcapi is not None:
5493 large_timeout = _testcapi.INT_MAX + 1
5494 else:
5495 large_timeout = 2147483648
5496 self.cli.connect((HOST, self.port))
5497 try:
5498 self.cli.settimeout(large_timeout)
5499 except OverflowError:
5500 return
5501 self.cli.sendall(MSG)
5502
5503
5504 class FileObjectClassTestCase(SocketConnectedTest):
5505 """Unit tests for the object returned by socket.makefile()
5506
5507 self.read_file is the io object returned by makefile() on
5508 the client connection. You can read from this file to
5509 get output from the server.
5510
5511 self.write_file is the io object returned by makefile() on the
5512 server connection. You can write to this file to send output
5513 to the client.
5514 """
5515
5516 bufsize = -1 # Use default buffer size
5517 encoding = 'utf-8'
5518 errors = 'strict'
5519 newline = None
5520
5521 read_mode = 'rb'
5522 read_msg = MSG
5523 write_mode = 'wb'
5524 write_msg = MSG
5525
5526 def __init__(self, methodName='runTest'):
5527 SocketConnectedTest.__init__(self, methodName=methodName)
5528
5529 def setUp(self):
5530 self.evt1, self.evt2, self.serv_finished, self.cli_finished = [
5531 threading.Event() for i in range(4)]
5532 SocketConnectedTest.setUp(self)
5533 self.read_file = self.cli_conn.makefile(
5534 self.read_mode, self.bufsize,
5535 encoding = self.encoding,
5536 errors = self.errors,
5537 newline = self.newline)
5538
5539 def tearDown(self):
5540 self.serv_finished.set()
5541 self.read_file.close()
5542 self.assertTrue(self.read_file.closed)
5543 self.read_file = None
5544 SocketConnectedTest.tearDown(self)
5545
5546 def clientSetUp(self):
5547 SocketConnectedTest.clientSetUp(self)
5548 self.write_file = self.serv_conn.makefile(
5549 self.write_mode, self.bufsize,
5550 encoding = self.encoding,
5551 errors = self.errors,
5552 newline = self.newline)
5553
5554 def clientTearDown(self):
5555 self.cli_finished.set()
5556 self.write_file.close()
5557 self.assertTrue(self.write_file.closed)
5558 self.write_file = None
5559 SocketConnectedTest.clientTearDown(self)
5560
5561 def testReadAfterTimeout(self):
5562 # Issue #7322: A file object must disallow further reads
5563 # after a timeout has occurred.
5564 self.cli_conn.settimeout(1)
5565 self.read_file.read(3)
5566 # First read raises a timeout
5567 self.assertRaises(TimeoutError, self.read_file.read, 1)
5568 # Second read is disallowed
5569 with self.assertRaises(OSError) as ctx:
5570 self.read_file.read(1)
5571 self.assertIn("cannot read from timed out object", str(ctx.exception))
5572
5573 def _testReadAfterTimeout(self):
5574 self.write_file.write(self.write_msg[0:3])
5575 self.write_file.flush()
5576 self.serv_finished.wait()
5577
5578 def testSmallRead(self):
5579 # Performing small file read test
5580 first_seg = self.read_file.read(len(self.read_msg)-3)
5581 second_seg = self.read_file.read(3)
5582 msg = first_seg + second_seg
5583 self.assertEqual(msg, self.read_msg)
5584
5585 def _testSmallRead(self):
5586 self.write_file.write(self.write_msg)
5587 self.write_file.flush()
5588
5589 def testFullRead(self):
5590 # read until EOF
5591 msg = self.read_file.read()
5592 self.assertEqual(msg, self.read_msg)
5593
5594 def _testFullRead(self):
5595 self.write_file.write(self.write_msg)
5596 self.write_file.close()
5597
5598 def testUnbufferedRead(self):
5599 # Performing unbuffered file read test
5600 buf = type(self.read_msg)()
5601 while 1:
5602 char = self.read_file.read(1)
5603 if not char:
5604 break
5605 buf += char
5606 self.assertEqual(buf, self.read_msg)
5607
5608 def _testUnbufferedRead(self):
5609 self.write_file.write(self.write_msg)
5610 self.write_file.flush()
5611
5612 def testReadline(self):
5613 # Performing file readline test
5614 line = self.read_file.readline()
5615 self.assertEqual(line, self.read_msg)
5616
5617 def _testReadline(self):
5618 self.write_file.write(self.write_msg)
5619 self.write_file.flush()
5620
5621 def testCloseAfterMakefile(self):
5622 # The file returned by makefile should keep the socket open.
5623 self.cli_conn.close()
5624 # read until EOF
5625 msg = self.read_file.read()
5626 self.assertEqual(msg, self.read_msg)
5627
5628 def _testCloseAfterMakefile(self):
5629 self.write_file.write(self.write_msg)
5630 self.write_file.flush()
5631
5632 def testMakefileAfterMakefileClose(self):
5633 self.read_file.close()
5634 msg = self.cli_conn.recv(len(MSG))
5635 if isinstance(self.read_msg, str):
5636 msg = msg.decode()
5637 self.assertEqual(msg, self.read_msg)
5638
5639 def _testMakefileAfterMakefileClose(self):
5640 self.write_file.write(self.write_msg)
5641 self.write_file.flush()
5642
5643 def testClosedAttr(self):
5644 self.assertTrue(not self.read_file.closed)
5645
5646 def _testClosedAttr(self):
5647 self.assertTrue(not self.write_file.closed)
5648
5649 def testAttributes(self):
5650 self.assertEqual(self.read_file.mode, self.read_mode)
5651 self.assertEqual(self.read_file.name, self.cli_conn.fileno())
5652
5653 def _testAttributes(self):
5654 self.assertEqual(self.write_file.mode, self.write_mode)
5655 self.assertEqual(self.write_file.name, self.serv_conn.fileno())
5656
5657 def testRealClose(self):
5658 self.read_file.close()
5659 self.assertRaises(ValueError, self.read_file.fileno)
5660 self.cli_conn.close()
5661 self.assertRaises(OSError, self.cli_conn.getsockname)
5662
5663 def _testRealClose(self):
5664 pass
5665
5666
5667 class UnbufferedFileObjectClassTestCase(FileObjectClassTestCase):
5668
5669 """Repeat the tests from FileObjectClassTestCase with bufsize==0.
5670
5671 In this case (and in this case only), it should be possible to
5672 create a file object, read a line from it, create another file
5673 object, read another line from it, without loss of data in the
5674 first file object's buffer. Note that http.client relies on this
5675 when reading multiple requests from the same socket."""
5676
5677 bufsize = 0 # Use unbuffered mode
5678
5679 def testUnbufferedReadline(self):
5680 # Read a line, create a new file object, read another line with it
5681 line = self.read_file.readline() # first line
5682 self.assertEqual(line, b"A. " + self.write_msg) # first line
5683 self.read_file = self.cli_conn.makefile('rb', 0)
5684 line = self.read_file.readline() # second line
5685 self.assertEqual(line, b"B. " + self.write_msg) # second line
5686
5687 def _testUnbufferedReadline(self):
5688 self.write_file.write(b"A. " + self.write_msg)
5689 self.write_file.write(b"B. " + self.write_msg)
5690 self.write_file.flush()
5691
5692 def testMakefileClose(self):
5693 # The file returned by makefile should keep the socket open...
5694 self.cli_conn.close()
5695 msg = self.cli_conn.recv(1024)
5696 self.assertEqual(msg, self.read_msg)
5697 # ...until the file is itself closed
5698 self.read_file.close()
5699 self.assertRaises(OSError, self.cli_conn.recv, 1024)
5700
5701 def _testMakefileClose(self):
5702 self.write_file.write(self.write_msg)
5703 self.write_file.flush()
5704
5705 @unittest.skipUnless(hasattr(sys, 'getrefcount'),
5706 'test needs sys.getrefcount()')
5707 def testMakefileCloseSocketDestroy(self):
5708 refcount_before = sys.getrefcount(self.cli_conn)
5709 self.read_file.close()
5710 refcount_after = sys.getrefcount(self.cli_conn)
5711 self.assertEqual(refcount_before - 1, refcount_after)
5712
5713 def _testMakefileCloseSocketDestroy(self):
5714 pass
5715
5716 # Non-blocking ops
5717 # NOTE: to set `read_file` as non-blocking, we must call
5718 # `cli_conn.setblocking` and vice-versa (see setUp / clientSetUp).
5719
5720 def testSmallReadNonBlocking(self):
5721 self.cli_conn.setblocking(False)
5722 self.assertEqual(self.read_file.readinto(bytearray(10)), None)
5723 self.assertEqual(self.read_file.read(len(self.read_msg) - 3), None)
5724 self.evt1.set()
5725 self.evt2.wait(1.0)
5726 first_seg = self.read_file.read(len(self.read_msg) - 3)
5727 if first_seg is None:
5728 # Data not arrived (can happen under Windows), wait a bit
5729 time.sleep(0.5)
5730 first_seg = self.read_file.read(len(self.read_msg) - 3)
5731 buf = bytearray(10)
5732 n = self.read_file.readinto(buf)
5733 self.assertEqual(n, 3)
5734 msg = first_seg + buf[:n]
5735 self.assertEqual(msg, self.read_msg)
5736 self.assertEqual(self.read_file.readinto(bytearray(16)), None)
5737 self.assertEqual(self.read_file.read(1), None)
5738
5739 def _testSmallReadNonBlocking(self):
5740 self.evt1.wait(1.0)
5741 self.write_file.write(self.write_msg)
5742 self.write_file.flush()
5743 self.evt2.set()
5744 # Avoid closing the socket before the server test has finished,
5745 # otherwise system recv() will return 0 instead of EWOULDBLOCK.
5746 self.serv_finished.wait(5.0)
5747
5748 def testWriteNonBlocking(self):
5749 self.cli_finished.wait(5.0)
5750 # The client thread can't skip directly - the SkipTest exception
5751 # would appear as a failure.
5752 if self.serv_skipped:
5753 self.skipTest(self.serv_skipped)
5754
5755 def _testWriteNonBlocking(self):
5756 self.serv_skipped = None
5757 self.serv_conn.setblocking(False)
5758 # Try to saturate the socket buffer pipe with repeated large writes.
5759 BIG = b"x" * support.SOCK_MAX_SIZE
5760 LIMIT = 10
5761 # The first write() succeeds since a chunk of data can be buffered
5762 n = self.write_file.write(BIG)
5763 self.assertGreater(n, 0)
5764 for i in range(LIMIT):
5765 n = self.write_file.write(BIG)
5766 if n is None:
5767 # Succeeded
5768 break
5769 self.assertGreater(n, 0)
5770 else:
5771 # Let us know that this test didn't manage to establish
5772 # the expected conditions. This is not a failure in itself but,
5773 # if it happens repeatedly, the test should be fixed.
5774 self.serv_skipped = "failed to saturate the socket buffer"
5775
5776
5777 class LineBufferedFileObjectClassTestCase(FileObjectClassTestCase):
5778
5779 bufsize = 1 # Default-buffered for reading; line-buffered for writing
5780
5781
5782 class SmallBufferedFileObjectClassTestCase(FileObjectClassTestCase):
5783
5784 bufsize = 2 # Exercise the buffering code
5785
5786
5787 class UnicodeReadFileObjectClassTestCase(FileObjectClassTestCase):
5788 """Tests for socket.makefile() in text mode (rather than binary)"""
5789
5790 read_mode = 'r'
5791 read_msg = MSG.decode('utf-8')
5792 write_mode = 'wb'
5793 write_msg = MSG
5794 newline = ''
5795
5796
5797 class UnicodeWriteFileObjectClassTestCase(FileObjectClassTestCase):
5798 """Tests for socket.makefile() in text mode (rather than binary)"""
5799
5800 read_mode = 'rb'
5801 read_msg = MSG
5802 write_mode = 'w'
5803 write_msg = MSG.decode('utf-8')
5804 newline = ''
5805
5806
5807 class UnicodeReadWriteFileObjectClassTestCase(FileObjectClassTestCase):
5808 """Tests for socket.makefile() in text mode (rather than binary)"""
5809
5810 read_mode = 'r'
5811 read_msg = MSG.decode('utf-8')
5812 write_mode = 'w'
5813 write_msg = MSG.decode('utf-8')
5814 newline = ''
5815
5816
5817 class NetworkConnectionTest(object):
5818 """Prove network connection."""
5819
5820 def clientSetUp(self):
5821 # We're inherited below by BasicTCPTest2, which also inherits
5822 # BasicTCPTest, which defines self.port referenced below.
5823 self.cli = socket.create_connection((HOST, self.port))
5824 self.serv_conn = self.cli
5825
5826 class BasicTCPTest2(NetworkConnectionTest, BasicTCPTest):
5827 """Tests that NetworkConnection does not break existing TCP functionality.
5828 """
5829
5830 class NetworkConnectionNoServer(unittest.TestCase):
5831
5832 class MockSocket(socket.socket):
5833 def connect(self, *args):
5834 raise TimeoutError('timed out')
5835
5836 @contextlib.contextmanager
5837 def mocked_socket_module(self):
5838 """Return a socket which times out on connect"""
5839 old_socket = socket.socket
5840 socket.socket = self.MockSocket
5841 try:
5842 yield
5843 finally:
5844 socket.socket = old_socket
5845
5846 @socket_helper.skip_if_tcp_blackhole
5847 def test_connect(self):
5848 port = socket_helper.find_unused_port()
5849 cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
5850 self.addCleanup(cli.close)
5851 with self.assertRaises(OSError) as cm:
5852 cli.connect((HOST, port))
5853 self.assertEqual(cm.exception.errno, errno.ECONNREFUSED)
5854
5855 @socket_helper.skip_if_tcp_blackhole
5856 def test_create_connection(self):
5857 # Issue #9792: errors raised by create_connection() should have
5858 # a proper errno attribute.
5859 port = socket_helper.find_unused_port()
5860 with self.assertRaises(OSError) as cm:
5861 socket.create_connection((HOST, port))
5862
5863 # Issue #16257: create_connection() calls getaddrinfo() against
5864 # 'localhost'. This may result in an IPV6 addr being returned
5865 # as well as an IPV4 one:
5866 # >>> socket.getaddrinfo('localhost', port, 0, SOCK_STREAM)
5867 # >>> [(2, 2, 0, '', ('127.0.0.1', 41230)),
5868 # (26, 2, 0, '', ('::1', 41230, 0, 0))]
5869 #
5870 # create_connection() enumerates through all the addresses returned
5871 # and if it doesn't successfully bind to any of them, it propagates
5872 # the last exception it encountered.
5873 #
5874 # On Solaris, ENETUNREACH is returned in this circumstance instead
5875 # of ECONNREFUSED. So, if that errno exists, add it to our list of
5876 # expected errnos.
5877 expected_errnos = socket_helper.get_socket_conn_refused_errs()
5878 self.assertIn(cm.exception.errno, expected_errnos)
5879
5880 def test_create_connection_all_errors(self):
5881 port = socket_helper.find_unused_port()
5882 try:
5883 socket.create_connection((HOST, port), all_errors=True)
5884 except ExceptionGroup as e:
5885 eg = e
5886 else:
5887 self.fail('expected connection to fail')
5888
5889 self.assertIsInstance(eg, ExceptionGroup)
5890 for e in eg.exceptions:
5891 self.assertIsInstance(e, OSError)
5892
5893 addresses = socket.getaddrinfo(
5894 'localhost', port, 0, socket.SOCK_STREAM)
5895 # assert that we got an exception for each address
5896 self.assertEqual(len(addresses), len(eg.exceptions))
5897
5898 def test_create_connection_timeout(self):
5899 # Issue #9792: create_connection() should not recast timeout errors
5900 # as generic socket errors.
5901 with self.mocked_socket_module():
5902 try:
5903 socket.create_connection((HOST, 1234))
5904 except TimeoutError:
5905 pass
5906 except OSError as exc:
5907 if socket_helper.IPV6_ENABLED or exc.errno != errno.EAFNOSUPPORT:
5908 raise
5909 else:
5910 self.fail('TimeoutError not raised')
5911
5912
5913 class NetworkConnectionAttributesTest(SocketTCPTest, ThreadableTest):
5914 cli = None
5915
5916 def __init__(self, methodName='runTest'):
5917 SocketTCPTest.__init__(self, methodName=methodName)
5918 ThreadableTest.__init__(self)
5919
5920 def clientSetUp(self):
5921 self.source_port = socket_helper.find_unused_port()
5922
5923 def clientTearDown(self):
5924 if self.cli is not None:
5925 self.cli.close()
5926 self.cli = None
5927 ThreadableTest.clientTearDown(self)
5928
5929 def _justAccept(self):
5930 conn, addr = self.serv.accept()
5931 conn.close()
5932
5933 testFamily = _justAccept
5934 def _testFamily(self):
5935 self.cli = socket.create_connection((HOST, self.port),
5936 timeout=support.LOOPBACK_TIMEOUT)
5937 self.addCleanup(self.cli.close)
5938 self.assertEqual(self.cli.family, 2)
5939
5940 testSourceAddress = _justAccept
5941 def _testSourceAddress(self):
5942 self.cli = socket.create_connection((HOST, self.port),
5943 timeout=support.LOOPBACK_TIMEOUT,
5944 source_address=('', self.source_port))
5945 self.addCleanup(self.cli.close)
5946 self.assertEqual(self.cli.getsockname()[1], self.source_port)
5947 # The port number being used is sufficient to show that the bind()
5948 # call happened.
5949
5950 testTimeoutDefault = _justAccept
5951 def _testTimeoutDefault(self):
5952 # passing no explicit timeout uses socket's global default
5953 self.assertTrue(socket.getdefaulttimeout() is None)
5954 socket.setdefaulttimeout(42)
5955 try:
5956 self.cli = socket.create_connection((HOST, self.port))
5957 self.addCleanup(self.cli.close)
5958 finally:
5959 socket.setdefaulttimeout(None)
5960 self.assertEqual(self.cli.gettimeout(), 42)
5961
5962 testTimeoutNone = _justAccept
5963 def _testTimeoutNone(self):
5964 # None timeout means the same as sock.settimeout(None)
5965 self.assertTrue(socket.getdefaulttimeout() is None)
5966 socket.setdefaulttimeout(30)
5967 try:
5968 self.cli = socket.create_connection((HOST, self.port), timeout=None)
5969 self.addCleanup(self.cli.close)
5970 finally:
5971 socket.setdefaulttimeout(None)
5972 self.assertEqual(self.cli.gettimeout(), None)
5973
5974 testTimeoutValueNamed = _justAccept
5975 def _testTimeoutValueNamed(self):
5976 self.cli = socket.create_connection((HOST, self.port), timeout=30)
5977 self.assertEqual(self.cli.gettimeout(), 30)
5978
5979 testTimeoutValueNonamed = _justAccept
5980 def _testTimeoutValueNonamed(self):
5981 self.cli = socket.create_connection((HOST, self.port), 30)
5982 self.addCleanup(self.cli.close)
5983 self.assertEqual(self.cli.gettimeout(), 30)
5984
5985
5986 class NetworkConnectionBehaviourTest(SocketTCPTest, ThreadableTest):
5987
5988 def __init__(self, methodName='runTest'):
5989 SocketTCPTest.__init__(self, methodName=methodName)
5990 ThreadableTest.__init__(self)
5991
5992 def clientSetUp(self):
5993 pass
5994
5995 def clientTearDown(self):
5996 self.cli.close()
5997 self.cli = None
5998 ThreadableTest.clientTearDown(self)
5999
6000 def testInsideTimeout(self):
6001 conn, addr = self.serv.accept()
6002 self.addCleanup(conn.close)
6003 time.sleep(3)
6004 conn.send(b"done!")
6005 testOutsideTimeout = testInsideTimeout
6006
6007 def _testInsideTimeout(self):
6008 self.cli = sock = socket.create_connection((HOST, self.port))
6009 data = sock.recv(5)
6010 self.assertEqual(data, b"done!")
6011
6012 def _testOutsideTimeout(self):
6013 self.cli = sock = socket.create_connection((HOST, self.port), timeout=1)
6014 self.assertRaises(TimeoutError, lambda: sock.recv(5))
6015
6016
6017 class TCPTimeoutTest(SocketTCPTest):
6018
6019 def testTCPTimeout(self):
6020 def raise_timeout(*args, **kwargs):
6021 self.serv.settimeout(1.0)
6022 self.serv.accept()
6023 self.assertRaises(TimeoutError, raise_timeout,
6024 "Error generating a timeout exception (TCP)")
6025
6026 def testTimeoutZero(self):
6027 ok = False
6028 try:
6029 self.serv.settimeout(0.0)
6030 foo = self.serv.accept()
6031 except TimeoutError:
6032 self.fail("caught timeout instead of error (TCP)")
6033 except OSError:
6034 ok = True
6035 except:
6036 self.fail("caught unexpected exception (TCP)")
6037 if not ok:
6038 self.fail("accept() returned success when we did not expect it")
6039
6040 @unittest.skipUnless(hasattr(signal, 'alarm'),
6041 'test needs signal.alarm()')
6042 def testInterruptedTimeout(self):
6043 # XXX I don't know how to do this test on MSWindows or any other
6044 # platform that doesn't support signal.alarm() or os.kill(), though
6045 # the bug should have existed on all platforms.
6046 self.serv.settimeout(5.0) # must be longer than alarm
6047 class Alarm(Exception):
6048 pass
6049 def alarm_handler(signal, frame):
6050 raise Alarm
6051 old_alarm = signal.signal(signal.SIGALRM, alarm_handler)
6052 try:
6053 try:
6054 signal.alarm(2) # POSIX allows alarm to be up to 1 second early
6055 foo = self.serv.accept()
6056 except TimeoutError:
6057 self.fail("caught timeout instead of Alarm")
6058 except Alarm:
6059 pass
6060 except BaseException as e:
6061 self.fail("caught other exception instead of Alarm:"
6062 " %s(%s):\n%s" %
6063 (type(e), e, traceback.format_exc()))
6064 else:
6065 self.fail("nothing caught")
6066 finally:
6067 signal.alarm(0) # shut off alarm
6068 except Alarm:
6069 self.fail("got Alarm in wrong place")
6070 finally:
6071 # no alarm can be pending. Safe to restore old handler.
6072 signal.signal(signal.SIGALRM, old_alarm)
6073
6074 class UDPTimeoutTest(SocketUDPTest):
6075
6076 def testUDPTimeout(self):
6077 def raise_timeout(*args, **kwargs):
6078 self.serv.settimeout(1.0)
6079 self.serv.recv(1024)
6080 self.assertRaises(TimeoutError, raise_timeout,
6081 "Error generating a timeout exception (UDP)")
6082
6083 def testTimeoutZero(self):
6084 ok = False
6085 try:
6086 self.serv.settimeout(0.0)
6087 foo = self.serv.recv(1024)
6088 except TimeoutError:
6089 self.fail("caught timeout instead of error (UDP)")
6090 except OSError:
6091 ok = True
6092 except:
6093 self.fail("caught unexpected exception (UDP)")
6094 if not ok:
6095 self.fail("recv() returned success when we did not expect it")
6096
6097 @unittest.skipUnless(HAVE_SOCKET_UDPLITE,
6098 'UDPLITE sockets required for this test.')
6099 class UDPLITETimeoutTest(SocketUDPLITETest):
6100
6101 def testUDPLITETimeout(self):
6102 def raise_timeout(*args, **kwargs):
6103 self.serv.settimeout(1.0)
6104 self.serv.recv(1024)
6105 self.assertRaises(TimeoutError, raise_timeout,
6106 "Error generating a timeout exception (UDPLITE)")
6107
6108 def testTimeoutZero(self):
6109 ok = False
6110 try:
6111 self.serv.settimeout(0.0)
6112 foo = self.serv.recv(1024)
6113 except TimeoutError:
6114 self.fail("caught timeout instead of error (UDPLITE)")
6115 except OSError:
6116 ok = True
6117 except:
6118 self.fail("caught unexpected exception (UDPLITE)")
6119 if not ok:
6120 self.fail("recv() returned success when we did not expect it")
6121
6122 class TestExceptions(unittest.TestCase):
6123
6124 def testExceptionTree(self):
6125 self.assertIsSubclass(OSError, Exception)
6126 self.assertIsSubclass(socket.herror, OSError)
6127 self.assertIsSubclass(socket.gaierror, OSError)
6128 self.assertIsSubclass(socket.timeout, OSError)
6129 self.assertIs(socket.error, OSError)
6130 self.assertIs(socket.timeout, TimeoutError)
6131
6132 def test_setblocking_invalidfd(self):
6133 # Regression test for issue #28471
6134
6135 sock0 = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
6136 sock = socket.socket(
6137 socket.AF_INET, socket.SOCK_STREAM, 0, sock0.fileno())
6138 sock0.close()
6139 self.addCleanup(sock.detach)
6140
6141 with self.assertRaises(OSError):
6142 sock.setblocking(False)
6143
6144
6145 @unittest.skipUnless(sys.platform in ('linux', 'android'), 'Linux specific test')
6146 class TestLinuxAbstractNamespace(unittest.TestCase):
6147
6148 UNIX_PATH_MAX = 108
6149
6150 def testLinuxAbstractNamespace(self):
6151 address = b"\x00python-test-hello\x00\xff"
6152 with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s1:
6153 s1.bind(address)
6154 s1.listen()
6155 with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s2:
6156 s2.connect(s1.getsockname())
6157 with s1.accept()[0] as s3:
6158 self.assertEqual(s1.getsockname(), address)
6159 self.assertEqual(s2.getpeername(), address)
6160
6161 def testMaxName(self):
6162 address = b"\x00" + b"h" * (self.UNIX_PATH_MAX - 1)
6163 with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s:
6164 s.bind(address)
6165 self.assertEqual(s.getsockname(), address)
6166
6167 def testNameOverflow(self):
6168 address = "\x00" + "h" * self.UNIX_PATH_MAX
6169 with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s:
6170 self.assertRaises(OSError, s.bind, address)
6171
6172 def testStrName(self):
6173 # Check that an abstract name can be passed as a string.
6174 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
6175 try:
6176 s.bind("\x00python\x00test\x00")
6177 self.assertEqual(s.getsockname(), b"\x00python\x00test\x00")
6178 finally:
6179 s.close()
6180
6181 def testBytearrayName(self):
6182 # Check that an abstract name can be passed as a bytearray.
6183 with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s:
6184 s.bind(bytearray(b"\x00python\x00test\x00"))
6185 self.assertEqual(s.getsockname(), b"\x00python\x00test\x00")
6186
6187 def testAutobind(self):
6188 # Check that binding to an empty string binds to an available address
6189 # in the abstract namespace as specified in unix(7) "Autobind feature".
6190 abstract_address = b"^\0[0-9a-f]{5}"
6191 with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s1:
6192 s1.bind("")
6193 self.assertRegex(s1.getsockname(), abstract_address)
6194 # Each socket is bound to a different abstract address.
6195 with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s2:
6196 s2.bind("")
6197 self.assertRegex(s2.getsockname(), abstract_address)
6198 self.assertNotEqual(s1.getsockname(), s2.getsockname())
6199
6200
6201 @unittest.skipUnless(hasattr(socket, 'AF_UNIX'), 'test needs socket.AF_UNIX')
6202 class TestUnixDomain(unittest.TestCase):
6203
6204 def setUp(self):
6205 self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
6206
6207 def tearDown(self):
6208 self.sock.close()
6209
6210 def encoded(self, path):
6211 # Return the given path encoded in the file system encoding,
6212 # or skip the test if this is not possible.
6213 try:
6214 return os.fsencode(path)
6215 except UnicodeEncodeError:
6216 self.skipTest(
6217 "Pathname {0!a} cannot be represented in file "
6218 "system encoding {1!r}".format(
6219 path, sys.getfilesystemencoding()))
6220
6221 def bind(self, sock, path):
6222 # Bind the socket
6223 try:
6224 socket_helper.bind_unix_socket(sock, path)
6225 except OSError as e:
6226 if str(e) == "AF_UNIX path too long":
6227 self.skipTest(
6228 "Pathname {0!a} is too long to serve as an AF_UNIX path"
6229 .format(path))
6230 else:
6231 raise
6232
6233 def testUnbound(self):
6234 # Issue #30205 (note getsockname() can return None on OS X)
6235 self.assertIn(self.sock.getsockname(), ('', None))
6236
6237 def testStrAddr(self):
6238 # Test binding to and retrieving a normal string pathname.
6239 path = os.path.abspath(os_helper.TESTFN)
6240 self.bind(self.sock, path)
6241 self.addCleanup(os_helper.unlink, path)
6242 self.assertEqual(self.sock.getsockname(), path)
6243
6244 def testBytesAddr(self):
6245 # Test binding to a bytes pathname.
6246 path = os.path.abspath(os_helper.TESTFN)
6247 self.bind(self.sock, self.encoded(path))
6248 self.addCleanup(os_helper.unlink, path)
6249 self.assertEqual(self.sock.getsockname(), path)
6250
6251 def testSurrogateescapeBind(self):
6252 # Test binding to a valid non-ASCII pathname, with the
6253 # non-ASCII bytes supplied using surrogateescape encoding.
6254 path = os.path.abspath(os_helper.TESTFN_UNICODE)
6255 b = self.encoded(path)
6256 self.bind(self.sock, b.decode("ascii", "surrogateescape"))
6257 self.addCleanup(os_helper.unlink, path)
6258 self.assertEqual(self.sock.getsockname(), path)
6259
6260 def testUnencodableAddr(self):
6261 # Test binding to a pathname that cannot be encoded in the
6262 # file system encoding.
6263 if os_helper.TESTFN_UNENCODABLE is None:
6264 self.skipTest("No unencodable filename available")
6265 path = os.path.abspath(os_helper.TESTFN_UNENCODABLE)
6266 self.bind(self.sock, path)
6267 self.addCleanup(os_helper.unlink, path)
6268 self.assertEqual(self.sock.getsockname(), path)
6269
6270 @unittest.skipIf(sys.platform in ('linux', 'android'),
6271 'Linux behavior is tested by TestLinuxAbstractNamespace')
6272 def testEmptyAddress(self):
6273 # Test that binding empty address fails.
6274 self.assertRaises(OSError, self.sock.bind, "")
6275
6276
6277 class BufferIOTest(SocketConnectedTest):
6278 """
6279 Test the buffer versions of socket.recv() and socket.send().
6280 """
6281 def __init__(self, methodName='runTest'):
6282 SocketConnectedTest.__init__(self, methodName=methodName)
6283
6284 def testRecvIntoArray(self):
6285 buf = array.array("B", [0] * len(MSG))
6286 nbytes = self.cli_conn.recv_into(buf)
6287 self.assertEqual(nbytes, len(MSG))
6288 buf = buf.tobytes()
6289 msg = buf[:len(MSG)]
6290 self.assertEqual(msg, MSG)
6291
6292 def _testRecvIntoArray(self):
6293 buf = bytes(MSG)
6294 self.serv_conn.send(buf)
6295
6296 def testRecvIntoBytearray(self):
6297 buf = bytearray(1024)
6298 nbytes = self.cli_conn.recv_into(buf)
6299 self.assertEqual(nbytes, len(MSG))
6300 msg = buf[:len(MSG)]
6301 self.assertEqual(msg, MSG)
6302
6303 _testRecvIntoBytearray = _testRecvIntoArray
6304
6305 def testRecvIntoMemoryview(self):
6306 buf = bytearray(1024)
6307 nbytes = self.cli_conn.recv_into(memoryview(buf))
6308 self.assertEqual(nbytes, len(MSG))
6309 msg = buf[:len(MSG)]
6310 self.assertEqual(msg, MSG)
6311
6312 _testRecvIntoMemoryview = _testRecvIntoArray
6313
6314 def testRecvFromIntoArray(self):
6315 buf = array.array("B", [0] * len(MSG))
6316 nbytes, addr = self.cli_conn.recvfrom_into(buf)
6317 self.assertEqual(nbytes, len(MSG))
6318 buf = buf.tobytes()
6319 msg = buf[:len(MSG)]
6320 self.assertEqual(msg, MSG)
6321
6322 def _testRecvFromIntoArray(self):
6323 buf = bytes(MSG)
6324 self.serv_conn.send(buf)
6325
6326 def testRecvFromIntoBytearray(self):
6327 buf = bytearray(1024)
6328 nbytes, addr = self.cli_conn.recvfrom_into(buf)
6329 self.assertEqual(nbytes, len(MSG))
6330 msg = buf[:len(MSG)]
6331 self.assertEqual(msg, MSG)
6332
6333 _testRecvFromIntoBytearray = _testRecvFromIntoArray
6334
6335 def testRecvFromIntoMemoryview(self):
6336 buf = bytearray(1024)
6337 nbytes, addr = self.cli_conn.recvfrom_into(memoryview(buf))
6338 self.assertEqual(nbytes, len(MSG))
6339 msg = buf[:len(MSG)]
6340 self.assertEqual(msg, MSG)
6341
6342 _testRecvFromIntoMemoryview = _testRecvFromIntoArray
6343
6344 def testRecvFromIntoSmallBuffer(self):
6345 # See issue #20246.
6346 buf = bytearray(8)
6347 self.assertRaises(ValueError, self.cli_conn.recvfrom_into, buf, 1024)
6348
6349 def _testRecvFromIntoSmallBuffer(self):
6350 self.serv_conn.send(MSG)
6351
6352 def testRecvFromIntoEmptyBuffer(self):
6353 buf = bytearray()
6354 self.cli_conn.recvfrom_into(buf)
6355 self.cli_conn.recvfrom_into(buf, 0)
6356
6357 _testRecvFromIntoEmptyBuffer = _testRecvFromIntoArray
6358
6359
6360 TIPC_STYPE = 2000
6361 TIPC_LOWER = 200
6362 TIPC_UPPER = 210
6363
6364 def isTipcAvailable():
6365 """Check if the TIPC module is loaded
6366
6367 The TIPC module is not loaded automatically on Ubuntu and probably
6368 other Linux distros.
6369 """
6370 if not hasattr(socket, "AF_TIPC"):
6371 return False
6372 try:
6373 f = open("/proc/modules", encoding="utf-8")
6374 except (FileNotFoundError, IsADirectoryError, PermissionError):
6375 # It's ok if the file does not exist, is a directory or if we
6376 # have not the permission to read it.
6377 return False
6378 with f:
6379 for line in f:
6380 if line.startswith("tipc "):
6381 return True
6382 return False
6383
6384 @unittest.skipUnless(isTipcAvailable(),
6385 "TIPC module is not loaded, please 'sudo modprobe tipc'")
6386 class TIPCTest(unittest.TestCase):
6387 def testRDM(self):
6388 srv = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
6389 cli = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
6390 self.addCleanup(srv.close)
6391 self.addCleanup(cli.close)
6392
6393 srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
6394 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
6395 TIPC_LOWER, TIPC_UPPER)
6396 srv.bind(srvaddr)
6397
6398 sendaddr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
6399 TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
6400 cli.sendto(MSG, sendaddr)
6401
6402 msg, recvaddr = srv.recvfrom(1024)
6403
6404 self.assertEqual(cli.getsockname(), recvaddr)
6405 self.assertEqual(msg, MSG)
6406
6407
6408 @unittest.skipUnless(isTipcAvailable(),
6409 "TIPC module is not loaded, please 'sudo modprobe tipc'")
6410 class TIPCThreadableTest(unittest.TestCase, ThreadableTest):
6411 def __init__(self, methodName = 'runTest'):
6412 unittest.TestCase.__init__(self, methodName = methodName)
6413 ThreadableTest.__init__(self)
6414
6415 def setUp(self):
6416 self.srv = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
6417 self.addCleanup(self.srv.close)
6418 self.srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
6419 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
6420 TIPC_LOWER, TIPC_UPPER)
6421 self.srv.bind(srvaddr)
6422 self.srv.listen()
6423 self.serverExplicitReady()
6424 self.conn, self.connaddr = self.srv.accept()
6425 self.addCleanup(self.conn.close)
6426
6427 def clientSetUp(self):
6428 # There is a hittable race between serverExplicitReady() and the
6429 # accept() call; sleep a little while to avoid it, otherwise
6430 # we could get an exception
6431 time.sleep(0.1)
6432 self.cli = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
6433 self.addCleanup(self.cli.close)
6434 addr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
6435 TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
6436 self.cli.connect(addr)
6437 self.cliaddr = self.cli.getsockname()
6438
6439 def testStream(self):
6440 msg = self.conn.recv(1024)
6441 self.assertEqual(msg, MSG)
6442 self.assertEqual(self.cliaddr, self.connaddr)
6443
6444 def _testStream(self):
6445 self.cli.send(MSG)
6446 self.cli.close()
6447
6448
6449 class ContextManagersTest(ThreadedTCPSocketTest):
6450
6451 def _testSocketClass(self):
6452 # base test
6453 with socket.socket() as sock:
6454 self.assertFalse(sock._closed)
6455 self.assertTrue(sock._closed)
6456 # close inside with block
6457 with socket.socket() as sock:
6458 sock.close()
6459 self.assertTrue(sock._closed)
6460 # exception inside with block
6461 with socket.socket() as sock:
6462 self.assertRaises(OSError, sock.sendall, b'foo')
6463 self.assertTrue(sock._closed)
6464
6465 def testCreateConnectionBase(self):
6466 conn, addr = self.serv.accept()
6467 self.addCleanup(conn.close)
6468 data = conn.recv(1024)
6469 conn.sendall(data)
6470
6471 def _testCreateConnectionBase(self):
6472 address = self.serv.getsockname()
6473 with socket.create_connection(address) as sock:
6474 self.assertFalse(sock._closed)
6475 sock.sendall(b'foo')
6476 self.assertEqual(sock.recv(1024), b'foo')
6477 self.assertTrue(sock._closed)
6478
6479 def testCreateConnectionClose(self):
6480 conn, addr = self.serv.accept()
6481 self.addCleanup(conn.close)
6482 data = conn.recv(1024)
6483 conn.sendall(data)
6484
6485 def _testCreateConnectionClose(self):
6486 address = self.serv.getsockname()
6487 with socket.create_connection(address) as sock:
6488 sock.close()
6489 self.assertTrue(sock._closed)
6490 self.assertRaises(OSError, sock.sendall, b'foo')
6491
6492
6493 class InheritanceTest(unittest.TestCase):
6494 @unittest.skipUnless(hasattr(socket, "SOCK_CLOEXEC"),
6495 "SOCK_CLOEXEC not defined")
6496 @support.requires_linux_version(2, 6, 28)
6497 def test_SOCK_CLOEXEC(self):
6498 with socket.socket(socket.AF_INET,
6499 socket.SOCK_STREAM | socket.SOCK_CLOEXEC) as s:
6500 self.assertEqual(s.type, socket.SOCK_STREAM)
6501 self.assertFalse(s.get_inheritable())
6502
6503 def test_default_inheritable(self):
6504 sock = socket.socket()
6505 with sock:
6506 self.assertEqual(sock.get_inheritable(), False)
6507
6508 def test_dup(self):
6509 sock = socket.socket()
6510 with sock:
6511 newsock = sock.dup()
6512 sock.close()
6513 with newsock:
6514 self.assertEqual(newsock.get_inheritable(), False)
6515
6516 def test_set_inheritable(self):
6517 sock = socket.socket()
6518 with sock:
6519 sock.set_inheritable(True)
6520 self.assertEqual(sock.get_inheritable(), True)
6521
6522 sock.set_inheritable(False)
6523 self.assertEqual(sock.get_inheritable(), False)
6524
6525 @unittest.skipIf(fcntl is None, "need fcntl")
6526 def test_get_inheritable_cloexec(self):
6527 sock = socket.socket()
6528 with sock:
6529 fd = sock.fileno()
6530 self.assertEqual(sock.get_inheritable(), False)
6531
6532 # clear FD_CLOEXEC flag
6533 flags = fcntl.fcntl(fd, fcntl.F_GETFD)
6534 flags &= ~fcntl.FD_CLOEXEC
6535 fcntl.fcntl(fd, fcntl.F_SETFD, flags)
6536
6537 self.assertEqual(sock.get_inheritable(), True)
6538
6539 @unittest.skipIf(fcntl is None, "need fcntl")
6540 def test_set_inheritable_cloexec(self):
6541 sock = socket.socket()
6542 with sock:
6543 fd = sock.fileno()
6544 self.assertEqual(fcntl.fcntl(fd, fcntl.F_GETFD) & fcntl.FD_CLOEXEC,
6545 fcntl.FD_CLOEXEC)
6546
6547 sock.set_inheritable(True)
6548 self.assertEqual(fcntl.fcntl(fd, fcntl.F_GETFD) & fcntl.FD_CLOEXEC,
6549 0)
6550
6551
6552 def test_socketpair(self):
6553 s1, s2 = socket.socketpair()
6554 self.addCleanup(s1.close)
6555 self.addCleanup(s2.close)
6556 self.assertEqual(s1.get_inheritable(), False)
6557 self.assertEqual(s2.get_inheritable(), False)
6558
6559
6560 @unittest.skipUnless(hasattr(socket, "SOCK_NONBLOCK"),
6561 "SOCK_NONBLOCK not defined")
6562 class NonblockConstantTest(unittest.TestCase):
6563 def checkNonblock(self, s, nonblock=True, timeout=0.0):
6564 if nonblock:
6565 self.assertEqual(s.type, socket.SOCK_STREAM)
6566 self.assertEqual(s.gettimeout(), timeout)
6567 self.assertTrue(
6568 fcntl.fcntl(s, fcntl.F_GETFL, os.O_NONBLOCK) & os.O_NONBLOCK)
6569 if timeout == 0:
6570 # timeout == 0: means that getblocking() must be False.
6571 self.assertFalse(s.getblocking())
6572 else:
6573 # If timeout > 0, the socket will be in a "blocking" mode
6574 # from the standpoint of the Python API. For Python socket
6575 # object, "blocking" means that operations like 'sock.recv()'
6576 # will block. Internally, file descriptors for
6577 # "blocking" Python sockets *with timeouts* are in a
6578 # *non-blocking* mode, and 'sock.recv()' uses 'select()'
6579 # and handles EWOULDBLOCK/EAGAIN to enforce the timeout.
6580 self.assertTrue(s.getblocking())
6581 else:
6582 self.assertEqual(s.type, socket.SOCK_STREAM)
6583 self.assertEqual(s.gettimeout(), None)
6584 self.assertFalse(
6585 fcntl.fcntl(s, fcntl.F_GETFL, os.O_NONBLOCK) & os.O_NONBLOCK)
6586 self.assertTrue(s.getblocking())
6587
6588 @support.requires_linux_version(2, 6, 28)
6589 def test_SOCK_NONBLOCK(self):
6590 # a lot of it seems silly and redundant, but I wanted to test that
6591 # changing back and forth worked ok
6592 with socket.socket(socket.AF_INET,
6593 socket.SOCK_STREAM | socket.SOCK_NONBLOCK) as s:
6594 self.checkNonblock(s)
6595 s.setblocking(True)
6596 self.checkNonblock(s, nonblock=False)
6597 s.setblocking(False)
6598 self.checkNonblock(s)
6599 s.settimeout(None)
6600 self.checkNonblock(s, nonblock=False)
6601 s.settimeout(2.0)
6602 self.checkNonblock(s, timeout=2.0)
6603 s.setblocking(True)
6604 self.checkNonblock(s, nonblock=False)
6605 # defaulttimeout
6606 t = socket.getdefaulttimeout()
6607 socket.setdefaulttimeout(0.0)
6608 with socket.socket() as s:
6609 self.checkNonblock(s)
6610 socket.setdefaulttimeout(None)
6611 with socket.socket() as s:
6612 self.checkNonblock(s, False)
6613 socket.setdefaulttimeout(2.0)
6614 with socket.socket() as s:
6615 self.checkNonblock(s, timeout=2.0)
6616 socket.setdefaulttimeout(None)
6617 with socket.socket() as s:
6618 self.checkNonblock(s, False)
6619 socket.setdefaulttimeout(t)
6620
6621
6622 @unittest.skipUnless(os.name == "nt", "Windows specific")
6623 @unittest.skipUnless(multiprocessing, "need multiprocessing")
6624 class TestSocketSharing(SocketTCPTest):
6625 # This must be classmethod and not staticmethod or multiprocessing
6626 # won't be able to bootstrap it.
6627 @classmethod
6628 def remoteProcessServer(cls, q):
6629 # Recreate socket from shared data
6630 sdata = q.get()
6631 message = q.get()
6632
6633 s = socket.fromshare(sdata)
6634 s2, c = s.accept()
6635
6636 # Send the message
6637 s2.sendall(message)
6638 s2.close()
6639 s.close()
6640
6641 def testShare(self):
6642 # Transfer the listening server socket to another process
6643 # and service it from there.
6644
6645 # Create process:
6646 q = multiprocessing.Queue()
6647 p = multiprocessing.Process(target=self.remoteProcessServer, args=(q,))
6648 p.start()
6649
6650 # Get the shared socket data
6651 data = self.serv.share(p.pid)
6652
6653 # Pass the shared socket to the other process
6654 addr = self.serv.getsockname()
6655 self.serv.close()
6656 q.put(data)
6657
6658 # The data that the server will send us
6659 message = b"slapmahfro"
6660 q.put(message)
6661
6662 # Connect
6663 s = socket.create_connection(addr)
6664 # listen for the data
6665 m = []
6666 while True:
6667 data = s.recv(100)
6668 if not data:
6669 break
6670 m.append(data)
6671 s.close()
6672 received = b"".join(m)
6673 self.assertEqual(received, message)
6674 p.join()
6675
6676 def testShareLength(self):
6677 data = self.serv.share(os.getpid())
6678 self.assertRaises(ValueError, socket.fromshare, data[:-1])
6679 self.assertRaises(ValueError, socket.fromshare, data+b"foo")
6680
6681 def compareSockets(self, org, other):
6682 # socket sharing is expected to work only for blocking socket
6683 # since the internal python timeout value isn't transferred.
6684 self.assertEqual(org.gettimeout(), None)
6685 self.assertEqual(org.gettimeout(), other.gettimeout())
6686
6687 self.assertEqual(org.family, other.family)
6688 self.assertEqual(org.type, other.type)
6689 # If the user specified "0" for proto, then
6690 # internally windows will have picked the correct value.
6691 # Python introspection on the socket however will still return
6692 # 0. For the shared socket, the python value is recreated
6693 # from the actual value, so it may not compare correctly.
6694 if org.proto != 0:
6695 self.assertEqual(org.proto, other.proto)
6696
6697 def testShareLocal(self):
6698 data = self.serv.share(os.getpid())
6699 s = socket.fromshare(data)
6700 try:
6701 self.compareSockets(self.serv, s)
6702 finally:
6703 s.close()
6704
6705 def testTypes(self):
6706 families = [socket.AF_INET, socket.AF_INET6]
6707 types = [socket.SOCK_STREAM, socket.SOCK_DGRAM]
6708 for f in families:
6709 for t in types:
6710 try:
6711 source = socket.socket(f, t)
6712 except OSError:
6713 continue # This combination is not supported
6714 try:
6715 data = source.share(os.getpid())
6716 shared = socket.fromshare(data)
6717 try:
6718 self.compareSockets(source, shared)
6719 finally:
6720 shared.close()
6721 finally:
6722 source.close()
6723
6724
6725 class SendfileUsingSendTest(ThreadedTCPSocketTest):
6726 """
6727 Test the send() implementation of socket.sendfile().
6728 """
6729
6730 FILESIZE = (10 * 1024 * 1024) # 10 MiB
6731 BUFSIZE = 8192
6732 FILEDATA = b""
6733 TIMEOUT = support.LOOPBACK_TIMEOUT
6734
6735 @classmethod
6736 def setUpClass(cls):
6737 def chunks(total, step):
6738 assert total >= step
6739 while total > step:
6740 yield step
6741 total -= step
6742 if total:
6743 yield total
6744
6745 chunk = b"".join([random.choice(string.ascii_letters).encode()
6746 for i in range(cls.BUFSIZE)])
6747 with open(os_helper.TESTFN, 'wb') as f:
6748 for csize in chunks(cls.FILESIZE, cls.BUFSIZE):
6749 f.write(chunk)
6750 with open(os_helper.TESTFN, 'rb') as f:
6751 cls.FILEDATA = f.read()
6752 assert len(cls.FILEDATA) == cls.FILESIZE
6753
6754 @classmethod
6755 def tearDownClass(cls):
6756 os_helper.unlink(os_helper.TESTFN)
6757
6758 def accept_conn(self):
6759 self.serv.settimeout(support.LONG_TIMEOUT)
6760 conn, addr = self.serv.accept()
6761 conn.settimeout(self.TIMEOUT)
6762 self.addCleanup(conn.close)
6763 return conn
6764
6765 def recv_data(self, conn):
6766 received = []
6767 while True:
6768 chunk = conn.recv(self.BUFSIZE)
6769 if not chunk:
6770 break
6771 received.append(chunk)
6772 return b''.join(received)
6773
6774 def meth_from_sock(self, sock):
6775 # Depending on the mixin class being run return either send()
6776 # or sendfile() method implementation.
6777 return getattr(sock, "_sendfile_use_send")
6778
6779 # regular file
6780
6781 def _testRegularFile(self):
6782 address = self.serv.getsockname()
6783 file = open(os_helper.TESTFN, 'rb')
6784 with socket.create_connection(address) as sock, file as file:
6785 meth = self.meth_from_sock(sock)
6786 sent = meth(file)
6787 self.assertEqual(sent, self.FILESIZE)
6788 self.assertEqual(file.tell(), self.FILESIZE)
6789
6790 def testRegularFile(self):
6791 conn = self.accept_conn()
6792 data = self.recv_data(conn)
6793 self.assertEqual(len(data), self.FILESIZE)
6794 self.assertEqual(data, self.FILEDATA)
6795
6796 # non regular file
6797
6798 def _testNonRegularFile(self):
6799 address = self.serv.getsockname()
6800 file = io.BytesIO(self.FILEDATA)
6801 with socket.create_connection(address) as sock, file as file:
6802 sent = sock.sendfile(file)
6803 self.assertEqual(sent, self.FILESIZE)
6804 self.assertEqual(file.tell(), self.FILESIZE)
6805 self.assertRaises(socket._GiveupOnSendfile,
6806 sock._sendfile_use_sendfile, file)
6807
6808 def testNonRegularFile(self):
6809 conn = self.accept_conn()
6810 data = self.recv_data(conn)
6811 self.assertEqual(len(data), self.FILESIZE)
6812 self.assertEqual(data, self.FILEDATA)
6813
6814 # empty file
6815
6816 def _testEmptyFileSend(self):
6817 address = self.serv.getsockname()
6818 filename = os_helper.TESTFN + "2"
6819 with open(filename, 'wb'):
6820 self.addCleanup(os_helper.unlink, filename)
6821 file = open(filename, 'rb')
6822 with socket.create_connection(address) as sock, file as file:
6823 meth = self.meth_from_sock(sock)
6824 sent = meth(file)
6825 self.assertEqual(sent, 0)
6826 self.assertEqual(file.tell(), 0)
6827
6828 def testEmptyFileSend(self):
6829 conn = self.accept_conn()
6830 data = self.recv_data(conn)
6831 self.assertEqual(data, b"")
6832
6833 # offset
6834
6835 def _testOffset(self):
6836 address = self.serv.getsockname()
6837 file = open(os_helper.TESTFN, 'rb')
6838 with socket.create_connection(address) as sock, file as file:
6839 meth = self.meth_from_sock(sock)
6840 sent = meth(file, offset=5000)
6841 self.assertEqual(sent, self.FILESIZE - 5000)
6842 self.assertEqual(file.tell(), self.FILESIZE)
6843
6844 def testOffset(self):
6845 conn = self.accept_conn()
6846 data = self.recv_data(conn)
6847 self.assertEqual(len(data), self.FILESIZE - 5000)
6848 self.assertEqual(data, self.FILEDATA[5000:])
6849
6850 # count
6851
6852 def _testCount(self):
6853 address = self.serv.getsockname()
6854 file = open(os_helper.TESTFN, 'rb')
6855 sock = socket.create_connection(address,
6856 timeout=support.LOOPBACK_TIMEOUT)
6857 with sock, file:
6858 count = 5000007
6859 meth = self.meth_from_sock(sock)
6860 sent = meth(file, count=count)
6861 self.assertEqual(sent, count)
6862 self.assertEqual(file.tell(), count)
6863
6864 def testCount(self):
6865 count = 5000007
6866 conn = self.accept_conn()
6867 data = self.recv_data(conn)
6868 self.assertEqual(len(data), count)
6869 self.assertEqual(data, self.FILEDATA[:count])
6870
6871 # count small
6872
6873 def _testCountSmall(self):
6874 address = self.serv.getsockname()
6875 file = open(os_helper.TESTFN, 'rb')
6876 sock = socket.create_connection(address,
6877 timeout=support.LOOPBACK_TIMEOUT)
6878 with sock, file:
6879 count = 1
6880 meth = self.meth_from_sock(sock)
6881 sent = meth(file, count=count)
6882 self.assertEqual(sent, count)
6883 self.assertEqual(file.tell(), count)
6884
6885 def testCountSmall(self):
6886 count = 1
6887 conn = self.accept_conn()
6888 data = self.recv_data(conn)
6889 self.assertEqual(len(data), count)
6890 self.assertEqual(data, self.FILEDATA[:count])
6891
6892 # count + offset
6893
6894 def _testCountWithOffset(self):
6895 address = self.serv.getsockname()
6896 file = open(os_helper.TESTFN, 'rb')
6897 with socket.create_connection(address, timeout=2) as sock, file as file:
6898 count = 100007
6899 meth = self.meth_from_sock(sock)
6900 sent = meth(file, offset=2007, count=count)
6901 self.assertEqual(sent, count)
6902 self.assertEqual(file.tell(), count + 2007)
6903
6904 def testCountWithOffset(self):
6905 count = 100007
6906 conn = self.accept_conn()
6907 data = self.recv_data(conn)
6908 self.assertEqual(len(data), count)
6909 self.assertEqual(data, self.FILEDATA[2007:count+2007])
6910
6911 # non blocking sockets are not supposed to work
6912
6913 def _testNonBlocking(self):
6914 address = self.serv.getsockname()
6915 file = open(os_helper.TESTFN, 'rb')
6916 with socket.create_connection(address) as sock, file as file:
6917 sock.setblocking(False)
6918 meth = self.meth_from_sock(sock)
6919 self.assertRaises(ValueError, meth, file)
6920 self.assertRaises(ValueError, sock.sendfile, file)
6921
6922 def testNonBlocking(self):
6923 conn = self.accept_conn()
6924 if conn.recv(8192):
6925 self.fail('was not supposed to receive any data')
6926
6927 # timeout (non-triggered)
6928
6929 def _testWithTimeout(self):
6930 address = self.serv.getsockname()
6931 file = open(os_helper.TESTFN, 'rb')
6932 sock = socket.create_connection(address,
6933 timeout=support.LOOPBACK_TIMEOUT)
6934 with sock, file:
6935 meth = self.meth_from_sock(sock)
6936 sent = meth(file)
6937 self.assertEqual(sent, self.FILESIZE)
6938
6939 def testWithTimeout(self):
6940 conn = self.accept_conn()
6941 data = self.recv_data(conn)
6942 self.assertEqual(len(data), self.FILESIZE)
6943 self.assertEqual(data, self.FILEDATA)
6944
6945 # timeout (triggered)
6946
6947 def _testWithTimeoutTriggeredSend(self):
6948 address = self.serv.getsockname()
6949 with open(os_helper.TESTFN, 'rb') as file:
6950 with socket.create_connection(address) as sock:
6951 sock.settimeout(0.01)
6952 meth = self.meth_from_sock(sock)
6953 self.assertRaises(TimeoutError, meth, file)
6954
6955 def testWithTimeoutTriggeredSend(self):
6956 conn = self.accept_conn()
6957 conn.recv(88192)
6958 # bpo-45212: the wait here needs to be longer than the client-side timeout (0.01s)
6959 time.sleep(1)
6960
6961 # errors
6962
6963 def _test_errors(self):
6964 pass
6965
6966 def test_errors(self):
6967 with open(os_helper.TESTFN, 'rb') as file:
6968 with socket.socket(type=socket.SOCK_DGRAM) as s:
6969 meth = self.meth_from_sock(s)
6970 self.assertRaisesRegex(
6971 ValueError, "SOCK_STREAM", meth, file)
6972 with open(os_helper.TESTFN, encoding="utf-8") as file:
6973 with socket.socket() as s:
6974 meth = self.meth_from_sock(s)
6975 self.assertRaisesRegex(
6976 ValueError, "binary mode", meth, file)
6977 with open(os_helper.TESTFN, 'rb') as file:
6978 with socket.socket() as s:
6979 meth = self.meth_from_sock(s)
6980 self.assertRaisesRegex(TypeError, "positive integer",
6981 meth, file, count='2')
6982 self.assertRaisesRegex(TypeError, "positive integer",
6983 meth, file, count=0.1)
6984 self.assertRaisesRegex(ValueError, "positive integer",
6985 meth, file, count=0)
6986 self.assertRaisesRegex(ValueError, "positive integer",
6987 meth, file, count=-1)
6988
6989
6990 @unittest.skipUnless(hasattr(os, "sendfile"),
6991 'os.sendfile() required for this test.')
6992 class SendfileUsingSendfileTest(SendfileUsingSendTest):
6993 """
6994 Test the sendfile() implementation of socket.sendfile().
6995 """
6996 def meth_from_sock(self, sock):
6997 return getattr(sock, "_sendfile_use_sendfile")
6998
6999
7000 @unittest.skipUnless(HAVE_SOCKET_ALG, 'AF_ALG required')
7001 class LinuxKernelCryptoAPI(unittest.TestCase):
7002 # tests for AF_ALG
7003 def create_alg(self, typ, name):
7004 sock = socket.socket(socket.AF_ALG, socket.SOCK_SEQPACKET, 0)
7005 try:
7006 sock.bind((typ, name))
7007 except FileNotFoundError as e:
7008 # type / algorithm is not available
7009 sock.close()
7010 raise unittest.SkipTest(str(e), typ, name)
7011 else:
7012 return sock
7013
7014 # bpo-31705: On kernel older than 4.5, sendto() failed with ENOKEY,
7015 # at least on ppc64le architecture
7016 @support.requires_linux_version(4, 5)
7017 def test_sha256(self):
7018 expected = bytes.fromhex("ba7816bf8f01cfea414140de5dae2223b00361a396"
7019 "177a9cb410ff61f20015ad")
7020 with self.create_alg('hash', 'sha256') as algo:
7021 op, _ = algo.accept()
7022 with op:
7023 op.sendall(b"abc")
7024 self.assertEqual(op.recv(512), expected)
7025
7026 op, _ = algo.accept()
7027 with op:
7028 op.send(b'a', socket.MSG_MORE)
7029 op.send(b'b', socket.MSG_MORE)
7030 op.send(b'c', socket.MSG_MORE)
7031 op.send(b'')
7032 self.assertEqual(op.recv(512), expected)
7033
7034 def test_hmac_sha1(self):
7035 # gh-109396: In FIPS mode, Linux 6.5 requires a key
7036 # of at least 112 bits. Use a key of 152 bits.
7037 key = b"Python loves AF_ALG"
7038 data = b"what do ya want for nothing?"
7039 expected = bytes.fromhex("193dbb43c6297b47ea6277ec0ce67119a3f3aa66")
7040 with self.create_alg('hash', 'hmac(sha1)') as algo:
7041 algo.setsockopt(socket.SOL_ALG, socket.ALG_SET_KEY, key)
7042 op, _ = algo.accept()
7043 with op:
7044 op.sendall(data)
7045 self.assertEqual(op.recv(512), expected)
7046
7047 # Although it should work with 3.19 and newer the test blocks on
7048 # Ubuntu 15.10 with Kernel 4.2.0-19.
7049 @support.requires_linux_version(4, 3)
7050 def test_aes_cbc(self):
7051 key = bytes.fromhex('06a9214036b8a15b512e03d534120006')
7052 iv = bytes.fromhex('3dafba429d9eb430b422da802c9fac41')
7053 msg = b"Single block msg"
7054 ciphertext = bytes.fromhex('e353779c1079aeb82708942dbe77181a')
7055 msglen = len(msg)
7056 with self.create_alg('skcipher', 'cbc(aes)') as algo:
7057 algo.setsockopt(socket.SOL_ALG, socket.ALG_SET_KEY, key)
7058 op, _ = algo.accept()
7059 with op:
7060 op.sendmsg_afalg(op=socket.ALG_OP_ENCRYPT, iv=iv,
7061 flags=socket.MSG_MORE)
7062 op.sendall(msg)
7063 self.assertEqual(op.recv(msglen), ciphertext)
7064
7065 op, _ = algo.accept()
7066 with op:
7067 op.sendmsg_afalg([ciphertext],
7068 op=socket.ALG_OP_DECRYPT, iv=iv)
7069 self.assertEqual(op.recv(msglen), msg)
7070
7071 # long message
7072 multiplier = 1024
7073 longmsg = [msg] * multiplier
7074 op, _ = algo.accept()
7075 with op:
7076 op.sendmsg_afalg(longmsg,
7077 op=socket.ALG_OP_ENCRYPT, iv=iv)
7078 enc = op.recv(msglen * multiplier)
7079 self.assertEqual(len(enc), msglen * multiplier)
7080 self.assertEqual(enc[:msglen], ciphertext)
7081
7082 op, _ = algo.accept()
7083 with op:
7084 op.sendmsg_afalg([enc],
7085 op=socket.ALG_OP_DECRYPT, iv=iv)
7086 dec = op.recv(msglen * multiplier)
7087 self.assertEqual(len(dec), msglen * multiplier)
7088 self.assertEqual(dec, msg * multiplier)
7089
7090 @support.requires_linux_version(4, 9) # see gh-73510
7091 def test_aead_aes_gcm(self):
7092 kernel_version = support._get_kernel_version("Linux")
7093 if kernel_version is not None:
7094 if kernel_version >= (6, 16) and kernel_version < (6, 18):
7095 # See https://github.com/python/cpython/issues/139310.
7096 self.skipTest("upstream Linux kernel issue")
7097
7098 key = bytes.fromhex('c939cc13397c1d37de6ae0e1cb7c423c')
7099 iv = bytes.fromhex('b3d8cc017cbb89b39e0f67e2')
7100 plain = bytes.fromhex('c3b3c41f113a31b73d9a5cd432103069')
7101 assoc = bytes.fromhex('24825602bd12a984e0092d3e448eda5f')
7102 expected_ct = bytes.fromhex('93fe7d9e9bfd10348a5606e5cafa7354')
7103 expected_tag = bytes.fromhex('0032a1dc85f1c9786925a2e71d8272dd')
7104
7105 taglen = len(expected_tag)
7106 assoclen = len(assoc)
7107
7108 with self.create_alg('aead', 'gcm(aes)') as algo:
7109 algo.setsockopt(socket.SOL_ALG, socket.ALG_SET_KEY, key)
7110 algo.setsockopt(socket.SOL_ALG, socket.ALG_SET_AEAD_AUTHSIZE,
7111 None, taglen)
7112
7113 # send assoc, plain and tag buffer in separate steps
7114 op, _ = algo.accept()
7115 with op:
7116 op.sendmsg_afalg(op=socket.ALG_OP_ENCRYPT, iv=iv,
7117 assoclen=assoclen, flags=socket.MSG_MORE)
7118 op.sendall(assoc, socket.MSG_MORE)
7119 op.sendall(plain)
7120 res = op.recv(assoclen + len(plain) + taglen)
7121 self.assertEqual(expected_ct, res[assoclen:-taglen])
7122 self.assertEqual(expected_tag, res[-taglen:])
7123
7124 # now with msg
7125 op, _ = algo.accept()
7126 with op:
7127 msg = assoc + plain
7128 op.sendmsg_afalg([msg], op=socket.ALG_OP_ENCRYPT, iv=iv,
7129 assoclen=assoclen)
7130 res = op.recv(assoclen + len(plain) + taglen)
7131 self.assertEqual(expected_ct, res[assoclen:-taglen])
7132 self.assertEqual(expected_tag, res[-taglen:])
7133
7134 # create anc data manually
7135 pack_uint32 = struct.Struct('I').pack
7136 op, _ = algo.accept()
7137 with op:
7138 msg = assoc + plain
7139 op.sendmsg(
7140 [msg],
7141 ([socket.SOL_ALG, socket.ALG_SET_OP, pack_uint32(socket.ALG_OP_ENCRYPT)],
7142 [socket.SOL_ALG, socket.ALG_SET_IV, pack_uint32(len(iv)) + iv],
7143 [socket.SOL_ALG, socket.ALG_SET_AEAD_ASSOCLEN, pack_uint32(assoclen)],
7144 )
7145 )
7146 res = op.recv(len(msg) + taglen)
7147 self.assertEqual(expected_ct, res[assoclen:-taglen])
7148 self.assertEqual(expected_tag, res[-taglen:])
7149
7150 # decrypt and verify
7151 op, _ = algo.accept()
7152 with op:
7153 msg = assoc + expected_ct + expected_tag
7154 op.sendmsg_afalg([msg], op=socket.ALG_OP_DECRYPT, iv=iv,
7155 assoclen=assoclen)
7156 res = op.recv(len(msg) - taglen)
7157 self.assertEqual(plain, res[assoclen:])
7158
7159 @support.requires_linux_version(4, 3) # see test_aes_cbc
7160 def test_drbg_pr_sha256(self):
7161 # deterministic random bit generator, prediction resistance, sha256
7162 with self.create_alg('rng', 'drbg_pr_sha256') as algo:
7163 extra_seed = os.urandom(32)
7164 algo.setsockopt(socket.SOL_ALG, socket.ALG_SET_KEY, extra_seed)
7165 op, _ = algo.accept()
7166 with op:
7167 rn = op.recv(32)
7168 self.assertEqual(len(rn), 32)
7169
7170 def test_sendmsg_afalg_args(self):
7171 sock = socket.socket(socket.AF_ALG, socket.SOCK_SEQPACKET, 0)
7172 with sock:
7173 with self.assertRaises(TypeError):
7174 sock.sendmsg_afalg()
7175
7176 with self.assertRaises(TypeError):
7177 sock.sendmsg_afalg(op=None)
7178
7179 with self.assertRaises(TypeError):
7180 sock.sendmsg_afalg(1)
7181
7182 with self.assertRaises(TypeError):
7183 sock.sendmsg_afalg(op=socket.ALG_OP_ENCRYPT, assoclen=None)
7184
7185 with self.assertRaises(TypeError):
7186 sock.sendmsg_afalg(op=socket.ALG_OP_ENCRYPT, assoclen=-1)
7187
7188 def test_length_restriction(self):
7189 # bpo-35050, off-by-one error in length check
7190 sock = socket.socket(socket.AF_ALG, socket.SOCK_SEQPACKET, 0)
7191 self.addCleanup(sock.close)
7192
7193 # salg_type[14]
7194 with self.assertRaises(FileNotFoundError):
7195 sock.bind(("t" * 13, "name"))
7196 with self.assertRaisesRegex(ValueError, "type too long"):
7197 sock.bind(("t" * 14, "name"))
7198
7199 # salg_name[64]
7200 with self.assertRaises(FileNotFoundError):
7201 sock.bind(("type", "n" * 63))
7202 with self.assertRaisesRegex(ValueError, "name too long"):
7203 sock.bind(("type", "n" * 64))
7204
7205
7206 @unittest.skipUnless(sys.platform == 'darwin', 'macOS specific test')
7207 class TestMacOSTCPFlags(unittest.TestCase):
7208 def test_tcp_keepalive(self):
7209 self.assertTrue(socket.TCP_KEEPALIVE)
7210
7211 @unittest.skipUnless(hasattr(socket, 'TCP_QUICKACK'), 'need socket.TCP_QUICKACK')
7212 class TestQuickackFlag(unittest.TestCase):
7213 def check_set_quickack(self, sock):
7214 # quickack already true by default on some OS distributions
7215 opt = sock.getsockopt(socket.IPPROTO_TCP, socket.TCP_QUICKACK)
7216 if opt:
7217 sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_QUICKACK, 0)
7218
7219 opt = sock.getsockopt(socket.IPPROTO_TCP, socket.TCP_QUICKACK)
7220 self.assertFalse(opt)
7221
7222 sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_QUICKACK, 1)
7223
7224 opt = sock.getsockopt(socket.IPPROTO_TCP, socket.TCP_QUICKACK)
7225 self.assertTrue(opt)
7226
7227 def test_set_quickack(self):
7228 sock = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM,
7229 proto=socket.IPPROTO_TCP)
7230 with sock:
7231 self.check_set_quickack(sock)
7232
7233
7234 @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
7235 class TestMSWindowsTCPFlags(unittest.TestCase):
7236 knownTCPFlags = {
7237 # available since long time ago
7238 'TCP_MAXSEG',
7239 'TCP_NODELAY',
7240 # available starting with Windows 10 1607
7241 'TCP_FASTOPEN',
7242 # available starting with Windows 10 1703
7243 'TCP_KEEPCNT',
7244 # available starting with Windows 10 1709
7245 'TCP_KEEPIDLE',
7246 'TCP_KEEPINTVL',
7247 # available starting with Windows 7 / Server 2008 R2
7248 'TCP_QUICKACK',
7249 }
7250
7251 def test_new_tcp_flags(self):
7252 provided = [s for s in dir(socket) if s.startswith('TCP')]
7253 unknown = [s for s in provided if s not in self.knownTCPFlags]
7254
7255 self.assertEqual([], unknown,
7256 "New TCP flags were discovered. See bpo-32394 for more information")
7257
7258
7259 class CreateServerTest(unittest.TestCase):
7260
7261 def test_address(self):
7262 port = socket_helper.find_unused_port()
7263 with socket.create_server(("127.0.0.1", port)) as sock:
7264 self.assertEqual(sock.getsockname()[0], "127.0.0.1")
7265 self.assertEqual(sock.getsockname()[1], port)
7266 if socket_helper.IPV6_ENABLED:
7267 with socket.create_server(("::1", port),
7268 family=socket.AF_INET6) as sock:
7269 self.assertEqual(sock.getsockname()[0], "::1")
7270 self.assertEqual(sock.getsockname()[1], port)
7271
7272 def test_family_and_type(self):
7273 with socket.create_server(("127.0.0.1", 0)) as sock:
7274 self.assertEqual(sock.family, socket.AF_INET)
7275 self.assertEqual(sock.type, socket.SOCK_STREAM)
7276 if socket_helper.IPV6_ENABLED:
7277 with socket.create_server(("::1", 0), family=socket.AF_INET6) as s:
7278 self.assertEqual(s.family, socket.AF_INET6)
7279 self.assertEqual(sock.type, socket.SOCK_STREAM)
7280
7281 def test_reuse_port(self):
7282 if not hasattr(socket, "SO_REUSEPORT"):
7283 with self.assertRaises(ValueError):
7284 socket.create_server(("localhost", 0), reuse_port=True)
7285 else:
7286 with socket.create_server(("localhost", 0)) as sock:
7287 opt = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT)
7288 self.assertEqual(opt, 0)
7289 with socket.create_server(("localhost", 0), reuse_port=True) as sock:
7290 opt = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT)
7291 self.assertNotEqual(opt, 0)
7292
7293 @unittest.skipIf(not hasattr(_socket, 'IPPROTO_IPV6') or
7294 not hasattr(_socket, 'IPV6_V6ONLY'),
7295 "IPV6_V6ONLY option not supported")
7296 @unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test')
7297 def test_ipv6_only_default(self):
7298 with socket.create_server(("::1", 0), family=socket.AF_INET6) as sock:
7299 assert sock.getsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY)
7300
7301 @unittest.skipIf(not socket.has_dualstack_ipv6(),
7302 "dualstack_ipv6 not supported")
7303 @unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test')
7304 def test_dualstack_ipv6_family(self):
7305 with socket.create_server(("::1", 0), family=socket.AF_INET6,
7306 dualstack_ipv6=True) as sock:
7307 self.assertEqual(sock.family, socket.AF_INET6)
7308
7309
7310 class CreateServerFunctionalTest(unittest.TestCase):
7311 timeout = support.LOOPBACK_TIMEOUT
7312
7313 def echo_server(self, sock):
7314 def run(sock):
7315 with sock:
7316 conn, _ = sock.accept()
7317 with conn:
7318 event.wait(self.timeout)
7319 msg = conn.recv(1024)
7320 if not msg:
7321 return
7322 conn.sendall(msg)
7323
7324 event = threading.Event()
7325 sock.settimeout(self.timeout)
7326 thread = threading.Thread(target=run, args=(sock, ))
7327 thread.start()
7328 self.addCleanup(thread.join, self.timeout)
7329 event.set()
7330
7331 def echo_client(self, addr, family):
7332 with socket.socket(family=family) as sock:
7333 sock.settimeout(self.timeout)
7334 sock.connect(addr)
7335 sock.sendall(b'foo')
7336 self.assertEqual(sock.recv(1024), b'foo')
7337
7338 def test_tcp4(self):
7339 port = socket_helper.find_unused_port()
7340 with socket.create_server(("", port)) as sock:
7341 self.echo_server(sock)
7342 self.echo_client(("127.0.0.1", port), socket.AF_INET)
7343
7344 @unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test')
7345 def test_tcp6(self):
7346 port = socket_helper.find_unused_port()
7347 with socket.create_server(("", port),
7348 family=socket.AF_INET6) as sock:
7349 self.echo_server(sock)
7350 self.echo_client(("::1", port), socket.AF_INET6)
7351
7352 # --- dual stack tests
7353
7354 @unittest.skipIf(not socket.has_dualstack_ipv6(),
7355 "dualstack_ipv6 not supported")
7356 @unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test')
7357 def test_dual_stack_client_v4(self):
7358 port = socket_helper.find_unused_port()
7359 with socket.create_server(("", port), family=socket.AF_INET6,
7360 dualstack_ipv6=True) as sock:
7361 self.echo_server(sock)
7362 self.echo_client(("127.0.0.1", port), socket.AF_INET)
7363
7364 @unittest.skipIf(not socket.has_dualstack_ipv6(),
7365 "dualstack_ipv6 not supported")
7366 @unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test')
7367 def test_dual_stack_client_v6(self):
7368 port = socket_helper.find_unused_port()
7369 with socket.create_server(("", port), family=socket.AF_INET6,
7370 dualstack_ipv6=True) as sock:
7371 self.echo_server(sock)
7372 self.echo_client(("::1", port), socket.AF_INET6)
7373
7374 @requireAttrs(socket, "send_fds")
7375 @requireAttrs(socket, "recv_fds")
7376 @requireAttrs(socket, "AF_UNIX")
7377 class SendRecvFdsTests(unittest.TestCase):
7378 def testSendAndRecvFds(self):
7379 def close_pipes(pipes):
7380 for fd1, fd2 in pipes:
7381 os.close(fd1)
7382 os.close(fd2)
7383
7384 def close_fds(fds):
7385 for fd in fds:
7386 os.close(fd)
7387
7388 # send 10 file descriptors
7389 pipes = [os.pipe() for _ in range(10)]
7390 self.addCleanup(close_pipes, pipes)
7391 fds = [rfd for rfd, wfd in pipes]
7392
7393 # use a UNIX socket pair to exchange file descriptors locally
7394 sock1, sock2 = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
7395 with sock1, sock2:
7396 socket.send_fds(sock1, [MSG], fds)
7397 # request more data and file descriptors than expected
7398 msg, fds2, flags, addr = socket.recv_fds(sock2, len(MSG) * 2, len(fds) * 2)
7399 self.addCleanup(close_fds, fds2)
7400
7401 self.assertEqual(msg, MSG)
7402 self.assertEqual(len(fds2), len(fds))
7403 self.assertEqual(flags, 0)
7404 # don't test addr
7405
7406 # test that file descriptors are connected
7407 for index, fds in enumerate(pipes):
7408 rfd, wfd = fds
7409 os.write(wfd, str(index).encode())
7410
7411 for index, rfd in enumerate(fds2):
7412 data = os.read(rfd, 100)
7413 self.assertEqual(data, str(index).encode())
7414
7415
7416 class FreeThreadingTests(unittest.TestCase):
7417
7418 def test_close_detach_race(self):
7419 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
7420
7421 def close():
7422 for _ in range(1000):
7423 s.close()
7424
7425 def detach():
7426 for _ in range(1000):
7427 s.detach()
7428
7429 t1 = threading.Thread(target=close)
7430 t2 = threading.Thread(target=detach)
7431
7432 with threading_helper.start_threads([t1, t2]):
7433 pass
7434
7435
7436 def setUpModule():
7437 thread_info = threading_helper.threading_setup()
7438 unittest.addModuleCleanup(threading_helper.threading_cleanup, *thread_info)
7439
7440
7441 if __name__ == "__main__":
7442 unittest.main()