socket.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924
  1. # Wrapper module for _socket, providing some additional facilities
  2. # implemented in Python.
  3. """\
  4. This module provides socket operations and some related functions.
  5. On Unix, it supports IP (Internet Protocol) and Unix domain sockets.
  6. On other systems, it only supports IP. Functions specific for a
  7. socket are available as methods of the socket object.
  8. Functions:
  9. socket() -- create a new socket object
  10. socketpair() -- create a pair of new socket objects [*]
  11. fromfd() -- create a socket object from an open file descriptor [*]
  12. fromshare() -- create a socket object from data received from socket.share() [*]
  13. gethostname() -- return the current hostname
  14. gethostbyname() -- map a hostname to its IP number
  15. gethostbyaddr() -- map an IP number or hostname to DNS info
  16. getservbyname() -- map a service name and a protocol name to a port number
  17. getprotobyname() -- map a protocol name (e.g. 'tcp') to a number
  18. ntohs(), ntohl() -- convert 16, 32 bit int from network to host byte order
  19. htons(), htonl() -- convert 16, 32 bit int from host to network byte order
  20. inet_aton() -- convert IP addr string (123.45.67.89) to 32-bit packed format
  21. inet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89)
  22. socket.getdefaulttimeout() -- get the default timeout value
  23. socket.setdefaulttimeout() -- set the default timeout value
  24. create_connection() -- connects to an address, with an optional timeout and
  25. optional source address.
  26. [*] not available on all platforms!
  27. Special objects:
  28. SocketType -- type object for socket objects
  29. error -- exception raised for I/O errors
  30. has_ipv6 -- boolean value indicating if IPv6 is supported
  31. IntEnum constants:
  32. AF_INET, AF_UNIX -- socket domains (first argument to socket() call)
  33. SOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument)
  34. Integer constants:
  35. Many other constants may be defined; these may be used in calls to
  36. the setsockopt() and getsockopt() methods.
  37. """
  38. import _socket
  39. from _socket import *
  40. import os, sys, io, selectors
  41. from enum import IntEnum, IntFlag
  42. try:
  43. import errno
  44. except ImportError:
  45. errno = None
  46. EBADF = getattr(errno, 'EBADF', 9)
  47. EAGAIN = getattr(errno, 'EAGAIN', 11)
  48. EWOULDBLOCK = getattr(errno, 'EWOULDBLOCK', 11)
  49. __all__ = ["fromfd", "getfqdn", "create_connection", "create_server",
  50. "has_dualstack_ipv6", "AddressFamily", "SocketKind"]
  51. __all__.extend(os._get_exports_list(_socket))
  52. # Set up the socket.AF_* socket.SOCK_* constants as members of IntEnums for
  53. # nicer string representations.
  54. # Note that _socket only knows about the integer values. The public interface
  55. # in this module understands the enums and translates them back from integers
  56. # where needed (e.g. .family property of a socket object).
  57. IntEnum._convert_(
  58. 'AddressFamily',
  59. __name__,
  60. lambda C: C.isupper() and C.startswith('AF_'))
  61. IntEnum._convert_(
  62. 'SocketKind',
  63. __name__,
  64. lambda C: C.isupper() and C.startswith('SOCK_'))
  65. IntFlag._convert_(
  66. 'MsgFlag',
  67. __name__,
  68. lambda C: C.isupper() and C.startswith('MSG_'))
  69. IntFlag._convert_(
  70. 'AddressInfo',
  71. __name__,
  72. lambda C: C.isupper() and C.startswith('AI_'))
  73. _LOCALHOST = '127.0.0.1'
  74. _LOCALHOST_V6 = '::1'
  75. def _intenum_converter(value, enum_klass):
  76. """Convert a numeric family value to an IntEnum member.
  77. If it's not a known member, return the numeric value itself.
  78. """
  79. try:
  80. return enum_klass(value)
  81. except ValueError:
  82. return value
  83. _realsocket = socket
  84. # WSA error codes
  85. if sys.platform.lower().startswith("win"):
  86. errorTab = {}
  87. errorTab[6] = "Specified event object handle is invalid."
  88. errorTab[8] = "Insufficient memory available."
  89. errorTab[87] = "One or more parameters are invalid."
  90. errorTab[995] = "Overlapped operation aborted."
  91. errorTab[996] = "Overlapped I/O event object not in signaled state."
  92. errorTab[997] = "Overlapped operation will complete later."
  93. errorTab[10004] = "The operation was interrupted."
  94. errorTab[10009] = "A bad file handle was passed."
  95. errorTab[10013] = "Permission denied."
  96. errorTab[10014] = "A fault occurred on the network??" # WSAEFAULT
  97. errorTab[10022] = "An invalid operation was attempted."
  98. errorTab[10024] = "Too many open files."
  99. errorTab[10035] = "The socket operation would block"
  100. errorTab[10036] = "A blocking operation is already in progress."
  101. errorTab[10037] = "Operation already in progress."
  102. errorTab[10038] = "Socket operation on nonsocket."
  103. errorTab[10039] = "Destination address required."
  104. errorTab[10040] = "Message too long."
  105. errorTab[10041] = "Protocol wrong type for socket."
  106. errorTab[10042] = "Bad protocol option."
  107. errorTab[10043] = "Protocol not supported."
  108. errorTab[10044] = "Socket type not supported."
  109. errorTab[10045] = "Operation not supported."
  110. errorTab[10046] = "Protocol family not supported."
  111. errorTab[10047] = "Address family not supported by protocol family."
  112. errorTab[10048] = "The network address is in use."
  113. errorTab[10049] = "Cannot assign requested address."
  114. errorTab[10050] = "Network is down."
  115. errorTab[10051] = "Network is unreachable."
  116. errorTab[10052] = "Network dropped connection on reset."
  117. errorTab[10053] = "Software caused connection abort."
  118. errorTab[10054] = "The connection has been reset."
  119. errorTab[10055] = "No buffer space available."
  120. errorTab[10056] = "Socket is already connected."
  121. errorTab[10057] = "Socket is not connected."
  122. errorTab[10058] = "The network has been shut down."
  123. errorTab[10059] = "Too many references."
  124. errorTab[10060] = "The operation timed out."
  125. errorTab[10061] = "Connection refused."
  126. errorTab[10062] = "Cannot translate name."
  127. errorTab[10063] = "The name is too long."
  128. errorTab[10064] = "The host is down."
  129. errorTab[10065] = "The host is unreachable."
  130. errorTab[10066] = "Directory not empty."
  131. errorTab[10067] = "Too many processes."
  132. errorTab[10068] = "User quota exceeded."
  133. errorTab[10069] = "Disk quota exceeded."
  134. errorTab[10070] = "Stale file handle reference."
  135. errorTab[10071] = "Item is remote."
  136. errorTab[10091] = "Network subsystem is unavailable."
  137. errorTab[10092] = "Winsock.dll version out of range."
  138. errorTab[10093] = "Successful WSAStartup not yet performed."
  139. errorTab[10101] = "Graceful shutdown in progress."
  140. errorTab[10102] = "No more results from WSALookupServiceNext."
  141. errorTab[10103] = "Call has been canceled."
  142. errorTab[10104] = "Procedure call table is invalid."
  143. errorTab[10105] = "Service provider is invalid."
  144. errorTab[10106] = "Service provider failed to initialize."
  145. errorTab[10107] = "System call failure."
  146. errorTab[10108] = "Service not found."
  147. errorTab[10109] = "Class type not found."
  148. errorTab[10110] = "No more results from WSALookupServiceNext."
  149. errorTab[10111] = "Call was canceled."
  150. errorTab[10112] = "Database query was refused."
  151. errorTab[11001] = "Host not found."
  152. errorTab[11002] = "Nonauthoritative host not found."
  153. errorTab[11003] = "This is a nonrecoverable error."
  154. errorTab[11004] = "Valid name, no data record requested type."
  155. errorTab[11005] = "QoS receivers."
  156. errorTab[11006] = "QoS senders."
  157. errorTab[11007] = "No QoS senders."
  158. errorTab[11008] = "QoS no receivers."
  159. errorTab[11009] = "QoS request confirmed."
  160. errorTab[11010] = "QoS admission error."
  161. errorTab[11011] = "QoS policy failure."
  162. errorTab[11012] = "QoS bad style."
  163. errorTab[11013] = "QoS bad object."
  164. errorTab[11014] = "QoS traffic control error."
  165. errorTab[11015] = "QoS generic error."
  166. errorTab[11016] = "QoS service type error."
  167. errorTab[11017] = "QoS flowspec error."
  168. errorTab[11018] = "Invalid QoS provider buffer."
  169. errorTab[11019] = "Invalid QoS filter style."
  170. errorTab[11020] = "Invalid QoS filter style."
  171. errorTab[11021] = "Incorrect QoS filter count."
  172. errorTab[11022] = "Invalid QoS object length."
  173. errorTab[11023] = "Incorrect QoS flow count."
  174. errorTab[11024] = "Unrecognized QoS object."
  175. errorTab[11025] = "Invalid QoS policy object."
  176. errorTab[11026] = "Invalid QoS flow descriptor."
  177. errorTab[11027] = "Invalid QoS provider-specific flowspec."
  178. errorTab[11028] = "Invalid QoS provider-specific filterspec."
  179. errorTab[11029] = "Invalid QoS shape discard mode object."
  180. errorTab[11030] = "Invalid QoS shaping rate object."
  181. errorTab[11031] = "Reserved policy QoS element type."
  182. __all__.append("errorTab")
  183. class _GiveupOnSendfile(Exception): pass
  184. class socket(_socket.socket):
  185. """A subclass of _socket.socket adding the makefile() method."""
  186. __slots__ = ["__weakref__", "_io_refs", "_closed"]
  187. def __init__(self, family=-1, type=-1, proto=-1, fileno=None):
  188. # For user code address family and type values are IntEnum members, but
  189. # for the underlying _socket.socket they're just integers. The
  190. # constructor of _socket.socket converts the given argument to an
  191. # integer automatically.
  192. if fileno is None:
  193. if family == -1:
  194. family = AF_INET
  195. if type == -1:
  196. type = SOCK_STREAM
  197. if proto == -1:
  198. proto = 0
  199. _socket.socket.__init__(self, family, type, proto, fileno)
  200. self._io_refs = 0
  201. self._closed = False
  202. def __enter__(self):
  203. return self
  204. def __exit__(self, *args):
  205. if not self._closed:
  206. self.close()
  207. def __repr__(self):
  208. """Wrap __repr__() to reveal the real class name and socket
  209. address(es).
  210. """
  211. closed = getattr(self, '_closed', False)
  212. s = "<%s.%s%s fd=%i, family=%s, type=%s, proto=%i" \
  213. % (self.__class__.__module__,
  214. self.__class__.__qualname__,
  215. " [closed]" if closed else "",
  216. self.fileno(),
  217. self.family,
  218. self.type,
  219. self.proto)
  220. if not closed:
  221. try:
  222. laddr = self.getsockname()
  223. if laddr:
  224. s += ", laddr=%s" % str(laddr)
  225. except error:
  226. pass
  227. try:
  228. raddr = self.getpeername()
  229. if raddr:
  230. s += ", raddr=%s" % str(raddr)
  231. except error:
  232. pass
  233. s += '>'
  234. return s
  235. def __getstate__(self):
  236. raise TypeError(f"cannot pickle {self.__class__.__name__!r} object")
  237. def dup(self):
  238. """dup() -> socket object
  239. Duplicate the socket. Return a new socket object connected to the same
  240. system resource. The new socket is non-inheritable.
  241. """
  242. fd = dup(self.fileno())
  243. sock = self.__class__(self.family, self.type, self.proto, fileno=fd)
  244. sock.settimeout(self.gettimeout())
  245. return sock
  246. def accept(self):
  247. """accept() -> (socket object, address info)
  248. Wait for an incoming connection. Return a new socket
  249. representing the connection, and the address of the client.
  250. For IP sockets, the address info is a pair (hostaddr, port).
  251. """
  252. fd, addr = self._accept()
  253. sock = socket(self.family, self.type, self.proto, fileno=fd)
  254. # Issue #7995: if no default timeout is set and the listening
  255. # socket had a (non-zero) timeout, force the new socket in blocking
  256. # mode to override platform-specific socket flags inheritance.
  257. if getdefaulttimeout() is None and self.gettimeout():
  258. sock.setblocking(True)
  259. return sock, addr
  260. def makefile(self, mode="r", buffering=None, *,
  261. encoding=None, errors=None, newline=None):
  262. """makefile(...) -> an I/O stream connected to the socket
  263. The arguments are as for io.open() after the filename, except the only
  264. supported mode values are 'r' (default), 'w' and 'b'.
  265. """
  266. # XXX refactor to share code?
  267. if not set(mode) <= {"r", "w", "b"}:
  268. raise ValueError("invalid mode %r (only r, w, b allowed)" % (mode,))
  269. writing = "w" in mode
  270. reading = "r" in mode or not writing
  271. assert reading or writing
  272. binary = "b" in mode
  273. rawmode = ""
  274. if reading:
  275. rawmode += "r"
  276. if writing:
  277. rawmode += "w"
  278. raw = SocketIO(self, rawmode)
  279. self._io_refs += 1
  280. if buffering is None:
  281. buffering = -1
  282. if buffering < 0:
  283. buffering = io.DEFAULT_BUFFER_SIZE
  284. if buffering == 0:
  285. if not binary:
  286. raise ValueError("unbuffered streams must be binary")
  287. return raw
  288. if reading and writing:
  289. buffer = io.BufferedRWPair(raw, raw, buffering)
  290. elif reading:
  291. buffer = io.BufferedReader(raw, buffering)
  292. else:
  293. assert writing
  294. buffer = io.BufferedWriter(raw, buffering)
  295. if binary:
  296. return buffer
  297. text = io.TextIOWrapper(buffer, encoding, errors, newline)
  298. text.mode = mode
  299. return text
  300. if hasattr(os, 'sendfile'):
  301. def _sendfile_use_sendfile(self, file, offset=0, count=None):
  302. self._check_sendfile_params(file, offset, count)
  303. sockno = self.fileno()
  304. try:
  305. fileno = file.fileno()
  306. except (AttributeError, io.UnsupportedOperation) as err:
  307. raise _GiveupOnSendfile(err) # not a regular file
  308. try:
  309. fsize = os.fstat(fileno).st_size
  310. except OSError as err:
  311. raise _GiveupOnSendfile(err) # not a regular file
  312. if not fsize:
  313. return 0 # empty file
  314. # Truncate to 1GiB to avoid OverflowError, see bpo-38319.
  315. blocksize = min(count or fsize, 2 ** 30)
  316. timeout = self.gettimeout()
  317. if timeout == 0:
  318. raise ValueError("non-blocking sockets are not supported")
  319. # poll/select have the advantage of not requiring any
  320. # extra file descriptor, contrarily to epoll/kqueue
  321. # (also, they require a single syscall).
  322. if hasattr(selectors, 'PollSelector'):
  323. selector = selectors.PollSelector()
  324. else:
  325. selector = selectors.SelectSelector()
  326. selector.register(sockno, selectors.EVENT_WRITE)
  327. total_sent = 0
  328. # localize variable access to minimize overhead
  329. selector_select = selector.select
  330. os_sendfile = os.sendfile
  331. try:
  332. while True:
  333. if timeout and not selector_select(timeout):
  334. raise _socket.timeout('timed out')
  335. if count:
  336. blocksize = count - total_sent
  337. if blocksize <= 0:
  338. break
  339. try:
  340. sent = os_sendfile(sockno, fileno, offset, blocksize)
  341. except BlockingIOError:
  342. if not timeout:
  343. # Block until the socket is ready to send some
  344. # data; avoids hogging CPU resources.
  345. selector_select()
  346. continue
  347. except OSError as err:
  348. if total_sent == 0:
  349. # We can get here for different reasons, the main
  350. # one being 'file' is not a regular mmap(2)-like
  351. # file, in which case we'll fall back on using
  352. # plain send().
  353. raise _GiveupOnSendfile(err)
  354. raise err from None
  355. else:
  356. if sent == 0:
  357. break # EOF
  358. offset += sent
  359. total_sent += sent
  360. return total_sent
  361. finally:
  362. if total_sent > 0 and hasattr(file, 'seek'):
  363. file.seek(offset)
  364. else:
  365. def _sendfile_use_sendfile(self, file, offset=0, count=None):
  366. raise _GiveupOnSendfile(
  367. "os.sendfile() not available on this platform")
  368. def _sendfile_use_send(self, file, offset=0, count=None):
  369. self._check_sendfile_params(file, offset, count)
  370. if self.gettimeout() == 0:
  371. raise ValueError("non-blocking sockets are not supported")
  372. if offset:
  373. file.seek(offset)
  374. blocksize = min(count, 8192) if count else 8192
  375. total_sent = 0
  376. # localize variable access to minimize overhead
  377. file_read = file.read
  378. sock_send = self.send
  379. try:
  380. while True:
  381. if count:
  382. blocksize = min(count - total_sent, blocksize)
  383. if blocksize <= 0:
  384. break
  385. data = memoryview(file_read(blocksize))
  386. if not data:
  387. break # EOF
  388. while True:
  389. try:
  390. sent = sock_send(data)
  391. except BlockingIOError:
  392. continue
  393. else:
  394. total_sent += sent
  395. if sent < len(data):
  396. data = data[sent:]
  397. else:
  398. break
  399. return total_sent
  400. finally:
  401. if total_sent > 0 and hasattr(file, 'seek'):
  402. file.seek(offset + total_sent)
  403. def _check_sendfile_params(self, file, offset, count):
  404. if 'b' not in getattr(file, 'mode', 'b'):
  405. raise ValueError("file should be opened in binary mode")
  406. if not self.type & SOCK_STREAM:
  407. raise ValueError("only SOCK_STREAM type sockets are supported")
  408. if count is not None:
  409. if not isinstance(count, int):
  410. raise TypeError(
  411. "count must be a positive integer (got {!r})".format(count))
  412. if count <= 0:
  413. raise ValueError(
  414. "count must be a positive integer (got {!r})".format(count))
  415. def sendfile(self, file, offset=0, count=None):
  416. """sendfile(file[, offset[, count]]) -> sent
  417. Send a file until EOF is reached by using high-performance
  418. os.sendfile() and return the total number of bytes which
  419. were sent.
  420. *file* must be a regular file object opened in binary mode.
  421. If os.sendfile() is not available (e.g. Windows) or file is
  422. not a regular file socket.send() will be used instead.
  423. *offset* tells from where to start reading the file.
  424. If specified, *count* is the total number of bytes to transmit
  425. as opposed to sending the file until EOF is reached.
  426. File position is updated on return or also in case of error in
  427. which case file.tell() can be used to figure out the number of
  428. bytes which were sent.
  429. The socket must be of SOCK_STREAM type.
  430. Non-blocking sockets are not supported.
  431. """
  432. try:
  433. return self._sendfile_use_sendfile(file, offset, count)
  434. except _GiveupOnSendfile:
  435. return self._sendfile_use_send(file, offset, count)
  436. def _decref_socketios(self):
  437. if self._io_refs > 0:
  438. self._io_refs -= 1
  439. if self._closed:
  440. self.close()
  441. def _real_close(self, _ss=_socket.socket):
  442. # This function should not reference any globals. See issue #808164.
  443. _ss.close(self)
  444. def close(self):
  445. # This function should not reference any globals. See issue #808164.
  446. self._closed = True
  447. if self._io_refs <= 0:
  448. self._real_close()
  449. def detach(self):
  450. """detach() -> file descriptor
  451. Close the socket object without closing the underlying file descriptor.
  452. The object cannot be used after this call, but the file descriptor
  453. can be reused for other purposes. The file descriptor is returned.
  454. """
  455. self._closed = True
  456. return super().detach()
  457. @property
  458. def family(self):
  459. """Read-only access to the address family for this socket.
  460. """
  461. return _intenum_converter(super().family, AddressFamily)
  462. @property
  463. def type(self):
  464. """Read-only access to the socket type.
  465. """
  466. return _intenum_converter(super().type, SocketKind)
  467. if os.name == 'nt':
  468. def get_inheritable(self):
  469. return os.get_handle_inheritable(self.fileno())
  470. def set_inheritable(self, inheritable):
  471. os.set_handle_inheritable(self.fileno(), inheritable)
  472. else:
  473. def get_inheritable(self):
  474. return os.get_inheritable(self.fileno())
  475. def set_inheritable(self, inheritable):
  476. os.set_inheritable(self.fileno(), inheritable)
  477. get_inheritable.__doc__ = "Get the inheritable flag of the socket"
  478. set_inheritable.__doc__ = "Set the inheritable flag of the socket"
  479. def fromfd(fd, family, type, proto=0):
  480. """ fromfd(fd, family, type[, proto]) -> socket object
  481. Create a socket object from a duplicate of the given file
  482. descriptor. The remaining arguments are the same as for socket().
  483. """
  484. nfd = dup(fd)
  485. return socket(family, type, proto, nfd)
  486. if hasattr(_socket.socket, "share"):
  487. def fromshare(info):
  488. """ fromshare(info) -> socket object
  489. Create a socket object from the bytes object returned by
  490. socket.share(pid).
  491. """
  492. return socket(0, 0, 0, info)
  493. __all__.append("fromshare")
  494. if hasattr(_socket, "socketpair"):
  495. def socketpair(family=None, type=SOCK_STREAM, proto=0):
  496. """socketpair([family[, type[, proto]]]) -> (socket object, socket object)
  497. Create a pair of socket objects from the sockets returned by the platform
  498. socketpair() function.
  499. The arguments are the same as for socket() except the default family is
  500. AF_UNIX if defined on the platform; otherwise, the default is AF_INET.
  501. """
  502. if family is None:
  503. try:
  504. family = AF_UNIX
  505. except NameError:
  506. family = AF_INET
  507. a, b = _socket.socketpair(family, type, proto)
  508. a = socket(family, type, proto, a.detach())
  509. b = socket(family, type, proto, b.detach())
  510. return a, b
  511. else:
  512. # Origin: https://gist.github.com/4325783, by Geert Jansen. Public domain.
  513. def socketpair(family=AF_INET, type=SOCK_STREAM, proto=0):
  514. if family == AF_INET:
  515. host = _LOCALHOST
  516. elif family == AF_INET6:
  517. host = _LOCALHOST_V6
  518. else:
  519. raise ValueError("Only AF_INET and AF_INET6 socket address families "
  520. "are supported")
  521. if type != SOCK_STREAM:
  522. raise ValueError("Only SOCK_STREAM socket type is supported")
  523. if proto != 0:
  524. raise ValueError("Only protocol zero is supported")
  525. # We create a connected TCP socket. Note the trick with
  526. # setblocking(False) that prevents us from having to create a thread.
  527. lsock = socket(family, type, proto)
  528. try:
  529. lsock.bind((host, 0))
  530. lsock.listen()
  531. # On IPv6, ignore flow_info and scope_id
  532. addr, port = lsock.getsockname()[:2]
  533. csock = socket(family, type, proto)
  534. try:
  535. csock.setblocking(False)
  536. try:
  537. csock.connect((addr, port))
  538. except (BlockingIOError, InterruptedError):
  539. pass
  540. csock.setblocking(True)
  541. ssock, _ = lsock.accept()
  542. except:
  543. csock.close()
  544. raise
  545. finally:
  546. lsock.close()
  547. return (ssock, csock)
  548. __all__.append("socketpair")
  549. socketpair.__doc__ = """socketpair([family[, type[, proto]]]) -> (socket object, socket object)
  550. Create a pair of socket objects from the sockets returned by the platform
  551. socketpair() function.
  552. The arguments are the same as for socket() except the default family is AF_UNIX
  553. if defined on the platform; otherwise, the default is AF_INET.
  554. """
  555. _blocking_errnos = { EAGAIN, EWOULDBLOCK }
  556. class SocketIO(io.RawIOBase):
  557. """Raw I/O implementation for stream sockets.
  558. This class supports the makefile() method on sockets. It provides
  559. the raw I/O interface on top of a socket object.
  560. """
  561. # One might wonder why not let FileIO do the job instead. There are two
  562. # main reasons why FileIO is not adapted:
  563. # - it wouldn't work under Windows (where you can't used read() and
  564. # write() on a socket handle)
  565. # - it wouldn't work with socket timeouts (FileIO would ignore the
  566. # timeout and consider the socket non-blocking)
  567. # XXX More docs
  568. def __init__(self, sock, mode):
  569. if mode not in ("r", "w", "rw", "rb", "wb", "rwb"):
  570. raise ValueError("invalid mode: %r" % mode)
  571. io.RawIOBase.__init__(self)
  572. self._sock = sock
  573. if "b" not in mode:
  574. mode += "b"
  575. self._mode = mode
  576. self._reading = "r" in mode
  577. self._writing = "w" in mode
  578. self._timeout_occurred = False
  579. def readinto(self, b):
  580. """Read up to len(b) bytes into the writable buffer *b* and return
  581. the number of bytes read. If the socket is non-blocking and no bytes
  582. are available, None is returned.
  583. If *b* is non-empty, a 0 return value indicates that the connection
  584. was shutdown at the other end.
  585. """
  586. self._checkClosed()
  587. self._checkReadable()
  588. if self._timeout_occurred:
  589. raise OSError("cannot read from timed out object")
  590. while True:
  591. try:
  592. return self._sock.recv_into(b)
  593. except timeout:
  594. self._timeout_occurred = True
  595. raise
  596. except error as e:
  597. if e.args[0] in _blocking_errnos:
  598. return None
  599. raise
  600. def write(self, b):
  601. """Write the given bytes or bytearray object *b* to the socket
  602. and return the number of bytes written. This can be less than
  603. len(b) if not all data could be written. If the socket is
  604. non-blocking and no bytes could be written None is returned.
  605. """
  606. self._checkClosed()
  607. self._checkWritable()
  608. try:
  609. return self._sock.send(b)
  610. except error as e:
  611. # XXX what about EINTR?
  612. if e.args[0] in _blocking_errnos:
  613. return None
  614. raise
  615. def readable(self):
  616. """True if the SocketIO is open for reading.
  617. """
  618. if self.closed:
  619. raise ValueError("I/O operation on closed socket.")
  620. return self._reading
  621. def writable(self):
  622. """True if the SocketIO is open for writing.
  623. """
  624. if self.closed:
  625. raise ValueError("I/O operation on closed socket.")
  626. return self._writing
  627. def seekable(self):
  628. """True if the SocketIO is open for seeking.
  629. """
  630. if self.closed:
  631. raise ValueError("I/O operation on closed socket.")
  632. return super().seekable()
  633. def fileno(self):
  634. """Return the file descriptor of the underlying socket.
  635. """
  636. self._checkClosed()
  637. return self._sock.fileno()
  638. @property
  639. def name(self):
  640. if not self.closed:
  641. return self.fileno()
  642. else:
  643. return -1
  644. @property
  645. def mode(self):
  646. return self._mode
  647. def close(self):
  648. """Close the SocketIO object. This doesn't close the underlying
  649. socket, except if all references to it have disappeared.
  650. """
  651. if self.closed:
  652. return
  653. io.RawIOBase.close(self)
  654. self._sock._decref_socketios()
  655. self._sock = None
  656. def getfqdn(name=''):
  657. """Get fully qualified domain name from name.
  658. An empty argument is interpreted as meaning the local host.
  659. First the hostname returned by gethostbyaddr() is checked, then
  660. possibly existing aliases. In case no FQDN is available, hostname
  661. from gethostname() is returned.
  662. """
  663. name = name.strip()
  664. if not name or name == '0.0.0.0':
  665. name = gethostname()
  666. try:
  667. hostname, aliases, ipaddrs = gethostbyaddr(name)
  668. except error:
  669. pass
  670. else:
  671. aliases.insert(0, hostname)
  672. for name in aliases:
  673. if '.' in name:
  674. break
  675. else:
  676. name = hostname
  677. return name
  678. _GLOBAL_DEFAULT_TIMEOUT = object()
  679. def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT,
  680. source_address=None):
  681. """Connect to *address* and return the socket object.
  682. Convenience function. Connect to *address* (a 2-tuple ``(host,
  683. port)``) and return the socket object. Passing the optional
  684. *timeout* parameter will set the timeout on the socket instance
  685. before attempting to connect. If no *timeout* is supplied, the
  686. global default timeout setting returned by :func:`getdefaulttimeout`
  687. is used. If *source_address* is set it must be a tuple of (host, port)
  688. for the socket to bind as a source address before making the connection.
  689. A host of '' or port 0 tells the OS to use the default.
  690. """
  691. host, port = address
  692. err = None
  693. for res in getaddrinfo(host, port, 0, SOCK_STREAM):
  694. af, socktype, proto, canonname, sa = res
  695. sock = None
  696. try:
  697. sock = socket(af, socktype, proto)
  698. if timeout is not _GLOBAL_DEFAULT_TIMEOUT:
  699. sock.settimeout(timeout)
  700. if source_address:
  701. sock.bind(source_address)
  702. sock.connect(sa)
  703. # Break explicitly a reference cycle
  704. err = None
  705. return sock
  706. except error as _:
  707. err = _
  708. if sock is not None:
  709. sock.close()
  710. if err is not None:
  711. try:
  712. raise err
  713. finally:
  714. # Break explicitly a reference cycle
  715. err = None
  716. else:
  717. raise error("getaddrinfo returns an empty list")
  718. def has_dualstack_ipv6():
  719. """Return True if the platform supports creating a SOCK_STREAM socket
  720. which can handle both AF_INET and AF_INET6 (IPv4 / IPv6) connections.
  721. """
  722. if not has_ipv6 \
  723. or not hasattr(_socket, 'IPPROTO_IPV6') \
  724. or not hasattr(_socket, 'IPV6_V6ONLY'):
  725. return False
  726. try:
  727. with socket(AF_INET6, SOCK_STREAM) as sock:
  728. sock.setsockopt(IPPROTO_IPV6, IPV6_V6ONLY, 0)
  729. return True
  730. except error:
  731. return False
  732. def create_server(address, *, family=AF_INET, backlog=None, reuse_port=False,
  733. dualstack_ipv6=False):
  734. """Convenience function which creates a SOCK_STREAM type socket
  735. bound to *address* (a 2-tuple (host, port)) and return the socket
  736. object.
  737. *family* should be either AF_INET or AF_INET6.
  738. *backlog* is the queue size passed to socket.listen().
  739. *reuse_port* dictates whether to use the SO_REUSEPORT socket option.
  740. *dualstack_ipv6*: if true and the platform supports it, it will
  741. create an AF_INET6 socket able to accept both IPv4 or IPv6
  742. connections. When false it will explicitly disable this option on
  743. platforms that enable it by default (e.g. Linux).
  744. >>> with create_server(('', 8000)) as server:
  745. ... while True:
  746. ... conn, addr = server.accept()
  747. ... # handle new connection
  748. """
  749. if reuse_port and not hasattr(_socket, "SO_REUSEPORT"):
  750. raise ValueError("SO_REUSEPORT not supported on this platform")
  751. if dualstack_ipv6:
  752. if not has_dualstack_ipv6():
  753. raise ValueError("dualstack_ipv6 not supported on this platform")
  754. if family != AF_INET6:
  755. raise ValueError("dualstack_ipv6 requires AF_INET6 family")
  756. sock = socket(family, SOCK_STREAM)
  757. try:
  758. # Note about Windows. We don't set SO_REUSEADDR because:
  759. # 1) It's unnecessary: bind() will succeed even in case of a
  760. # previous closed socket on the same address and still in
  761. # TIME_WAIT state.
  762. # 2) If set, another socket is free to bind() on the same
  763. # address, effectively preventing this one from accepting
  764. # connections. Also, it may set the process in a state where
  765. # it'll no longer respond to any signals or graceful kills.
  766. # See: msdn2.microsoft.com/en-us/library/ms740621(VS.85).aspx
  767. if os.name not in ('nt', 'cygwin') and \
  768. hasattr(_socket, 'SO_REUSEADDR'):
  769. try:
  770. sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
  771. except error:
  772. # Fail later on bind(), for platforms which may not
  773. # support this option.
  774. pass
  775. if reuse_port:
  776. sock.setsockopt(SOL_SOCKET, SO_REUSEPORT, 1)
  777. if has_ipv6 and family == AF_INET6:
  778. if dualstack_ipv6:
  779. sock.setsockopt(IPPROTO_IPV6, IPV6_V6ONLY, 0)
  780. elif hasattr(_socket, "IPV6_V6ONLY") and \
  781. hasattr(_socket, "IPPROTO_IPV6"):
  782. sock.setsockopt(IPPROTO_IPV6, IPV6_V6ONLY, 1)
  783. try:
  784. sock.bind(address)
  785. except error as err:
  786. msg = '%s (while attempting to bind on address %r)' % \
  787. (err.strerror, address)
  788. raise error(err.errno, msg) from None
  789. if backlog is None:
  790. sock.listen()
  791. else:
  792. sock.listen(backlog)
  793. return sock
  794. except error:
  795. sock.close()
  796. raise
  797. def getaddrinfo(host, port, family=0, type=0, proto=0, flags=0):
  798. """Resolve host and port into list of address info entries.
  799. Translate the host/port argument into a sequence of 5-tuples that contain
  800. all the necessary arguments for creating a socket connected to that service.
  801. host is a domain name, a string representation of an IPv4/v6 address or
  802. None. port is a string service name such as 'http', a numeric port number or
  803. None. By passing None as the value of host and port, you can pass NULL to
  804. the underlying C API.
  805. The family, type and proto arguments can be optionally specified in order to
  806. narrow the list of addresses returned. Passing zero as a value for each of
  807. these arguments selects the full range of results.
  808. """
  809. # We override this function since we want to translate the numeric family
  810. # and socket type values to enum constants.
  811. addrlist = []
  812. for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
  813. af, socktype, proto, canonname, sa = res
  814. addrlist.append((_intenum_converter(af, AddressFamily),
  815. _intenum_converter(socktype, SocketKind),
  816. proto, canonname, sa))
  817. return addrlist