socket.py 36 KB

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