_socket3.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065
  1. # Port of Python 3.3's socket module to gevent
  2. """
  3. Python 3 socket module.
  4. """
  5. # Our import magic sadly makes this warning useless
  6. # pylint: disable=undefined-variable
  7. # pylint: disable=too-many-statements,too-many-branches
  8. # pylint: disable=too-many-public-methods,unused-argument
  9. from __future__ import absolute_import
  10. import io
  11. import os
  12. import sys
  13. import time
  14. from gevent import _socketcommon
  15. from gevent._util import copy_globals
  16. from gevent._compat import PYPY
  17. import _socket
  18. from os import dup
  19. copy_globals(_socketcommon, globals(),
  20. names_to_ignore=_socketcommon.__extensions__,
  21. dunder_names_to_keep=())
  22. __socket__ = _socketcommon.__socket__
  23. __implements__ = _socketcommon._implements
  24. __extensions__ = _socketcommon.__extensions__
  25. __imports__ = _socketcommon.__imports__
  26. __dns__ = _socketcommon.__dns__
  27. SocketIO = __socket__.SocketIO # pylint:disable=no-member
  28. def _get_memory(data):
  29. mv = memoryview(data)
  30. if mv.shape:
  31. return mv
  32. # No shape, probably working with a ctypes object,
  33. # or something else exotic that supports the buffer interface
  34. return mv.tobytes()
  35. timeout_default = object()
  36. class _wrefsocket(_socket.socket):
  37. # Plain stdlib socket.socket objects subclass _socket.socket
  38. # and add weakref ability. The ssl module, for one, counts on this.
  39. # We don't create socket.socket objects (because they may have been
  40. # monkey patched to be the object from this module), but we still
  41. # need to make sure what we do create can be weakrefd.
  42. __slots__ = ("__weakref__", )
  43. if PYPY:
  44. # server.py unwraps the socket object to get the raw _sock;
  45. # it depends on having a timeout property alias, which PyPy does not
  46. # provide.
  47. timeout = property(lambda s: s.gettimeout(),
  48. lambda s, nv: s.settimeout(nv))
  49. class socket(object):
  50. """
  51. gevent `socket.socket <https://docs.python.org/3/library/socket.html#socket-objects>`_
  52. for Python 3.
  53. This object should have the same API as the standard library socket linked to above. Not all
  54. methods are specifically documented here; when they are they may point out a difference
  55. to be aware of or may document a method the standard library does not.
  56. """
  57. # Subclasses can set this to customize the type of the
  58. # native _socket.socket we create. It MUST be a subclass
  59. # of _wrefsocket. (gevent internal usage only)
  60. _gevent_sock_class = _wrefsocket
  61. def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None):
  62. # Take the same approach as socket2: wrap a real socket object,
  63. # don't subclass it. This lets code that needs the raw _sock (not tied to the hub)
  64. # get it. This shows up in tests like test__example_udp_server.
  65. self._sock = self._gevent_sock_class(family, type, proto, fileno)
  66. self._io_refs = 0
  67. self._closed = False
  68. _socket.socket.setblocking(self._sock, False)
  69. fileno = _socket.socket.fileno(self._sock)
  70. self.hub = get_hub()
  71. io_class = self.hub.loop.io
  72. self._read_event = io_class(fileno, 1)
  73. self._write_event = io_class(fileno, 2)
  74. self.timeout = _socket.getdefaulttimeout()
  75. def __getattr__(self, name):
  76. return getattr(self._sock, name)
  77. if hasattr(_socket, 'SOCK_NONBLOCK'):
  78. # Only defined under Linux
  79. @property
  80. def type(self):
  81. # See https://github.com/gevent/gevent/pull/399
  82. if self.timeout != 0.0:
  83. return self._sock.type & ~_socket.SOCK_NONBLOCK # pylint:disable=no-member
  84. return self._sock.type
  85. def __enter__(self):
  86. return self
  87. def __exit__(self, *args):
  88. if not self._closed:
  89. self.close()
  90. def __repr__(self):
  91. """Wrap __repr__() to reveal the real class name."""
  92. try:
  93. s = _socket.socket.__repr__(self._sock)
  94. except Exception as ex: # pylint:disable=broad-except
  95. # Observed on Windows Py3.3, printing the repr of a socket
  96. # that just sufferred a ConnectionResetError [WinError 10054]:
  97. # "OverflowError: no printf formatter to display the socket descriptor in decimal"
  98. # Not sure what the actual cause is or if there's a better way to handle this
  99. s = '<socket [%r]>' % ex
  100. if s.startswith("<socket object"):
  101. s = "<%s.%s%s%s" % (self.__class__.__module__,
  102. self.__class__.__name__,
  103. getattr(self, '_closed', False) and " [closed] " or "",
  104. s[7:])
  105. return s
  106. def __getstate__(self):
  107. raise TypeError("Cannot serialize socket object")
  108. def _get_ref(self):
  109. return self._read_event.ref or self._write_event.ref
  110. def _set_ref(self, value):
  111. self._read_event.ref = value
  112. self._write_event.ref = value
  113. ref = property(_get_ref, _set_ref)
  114. def _wait(self, watcher, timeout_exc=timeout('timed out')):
  115. """Block the current greenlet until *watcher* has pending events.
  116. If *timeout* is non-negative, then *timeout_exc* is raised after *timeout* second has passed.
  117. By default *timeout_exc* is ``socket.timeout('timed out')``.
  118. If :func:`cancel_wait` is called, raise ``socket.error(EBADF, 'File descriptor was closed in another greenlet')``.
  119. """
  120. if watcher.callback is not None:
  121. raise _socketcommon.ConcurrentObjectUseError('This socket is already used by another greenlet: %r' % (watcher.callback, ))
  122. if self.timeout is not None:
  123. timeout = Timeout.start_new(self.timeout, timeout_exc, ref=False)
  124. else:
  125. timeout = None
  126. try:
  127. self.hub.wait(watcher)
  128. finally:
  129. if timeout is not None:
  130. timeout.cancel()
  131. def dup(self):
  132. """dup() -> socket object
  133. Return a new socket object connected to the same system resource.
  134. """
  135. fd = dup(self.fileno())
  136. sock = self.__class__(self.family, self.type, self.proto, fileno=fd)
  137. sock.settimeout(self.gettimeout())
  138. return sock
  139. def accept(self):
  140. """accept() -> (socket object, address info)
  141. Wait for an incoming connection. Return a new socket
  142. representing the connection, and the address of the client.
  143. For IP sockets, the address info is a pair (hostaddr, port).
  144. """
  145. while True:
  146. try:
  147. fd, addr = self._accept()
  148. break
  149. except BlockingIOError:
  150. if self.timeout == 0.0:
  151. raise
  152. self._wait(self._read_event)
  153. sock = socket(self.family, self.type, self.proto, fileno=fd)
  154. # Python Issue #7995: if no default timeout is set and the listening
  155. # socket had a (non-zero) timeout, force the new socket in blocking
  156. # mode to override platform-specific socket flags inheritance.
  157. # XXX do we need to do this?
  158. if getdefaulttimeout() is None and self.gettimeout():
  159. sock.setblocking(True)
  160. return sock, addr
  161. def makefile(self, mode="r", buffering=None, *,
  162. encoding=None, errors=None, newline=None):
  163. """Return an I/O stream connected to the socket
  164. The arguments are as for io.open() after the filename,
  165. except the only mode characters supported are 'r', 'w' and 'b'.
  166. The semantics are similar too.
  167. """
  168. # (XXX refactor to share code?)
  169. for c in mode:
  170. if c not in {"r", "w", "b"}:
  171. raise ValueError("invalid mode %r (only r, w, b allowed)")
  172. writing = "w" in mode
  173. reading = "r" in mode or not writing
  174. assert reading or writing
  175. binary = "b" in mode
  176. rawmode = ""
  177. if reading:
  178. rawmode += "r"
  179. if writing:
  180. rawmode += "w"
  181. raw = SocketIO(self, rawmode)
  182. self._io_refs += 1
  183. if buffering is None:
  184. buffering = -1
  185. if buffering < 0:
  186. buffering = io.DEFAULT_BUFFER_SIZE
  187. if buffering == 0:
  188. if not binary:
  189. raise ValueError("unbuffered streams must be binary")
  190. return raw
  191. if reading and writing:
  192. buffer = io.BufferedRWPair(raw, raw, buffering)
  193. elif reading:
  194. buffer = io.BufferedReader(raw, buffering)
  195. else:
  196. assert writing
  197. buffer = io.BufferedWriter(raw, buffering)
  198. if binary:
  199. return buffer
  200. text = io.TextIOWrapper(buffer, encoding, errors, newline)
  201. text.mode = mode
  202. return text
  203. def _decref_socketios(self):
  204. if self._io_refs > 0:
  205. self._io_refs -= 1
  206. if self._closed:
  207. self.close()
  208. def _real_close(self, _ss=_socket.socket, cancel_wait_ex=cancel_wait_ex):
  209. # This function should not reference any globals. See Python issue #808164.
  210. self.hub.cancel_wait(self._read_event, cancel_wait_ex)
  211. self.hub.cancel_wait(self._write_event, cancel_wait_ex)
  212. _ss.close(self._sock)
  213. # Break any references to the underlying socket object. Tested
  214. # by test__refcount. (Why does this matter?). Be sure to
  215. # preserve our same family/type/proto if possible (if we
  216. # don't, we can get TypeError instead of OSError; see
  217. # test_socket.SendmsgUDP6Test.testSendmsgAfterClose)... but
  218. # this isn't always possible (see test_socket.test_unknown_socket_family_repr)
  219. # TODO: Can we use a simpler proxy, like _socket2 does?
  220. try:
  221. self._sock = self._gevent_sock_class(self.family, self.type, self.proto)
  222. except OSError:
  223. pass
  224. else:
  225. _ss.close(self._sock)
  226. def close(self):
  227. # This function should not reference any globals. See Python issue #808164.
  228. self._closed = True
  229. if self._io_refs <= 0:
  230. self._real_close()
  231. @property
  232. def closed(self):
  233. return self._closed
  234. def detach(self):
  235. """detach() -> file descriptor
  236. Close the socket object without closing the underlying file descriptor.
  237. The object cannot be used after this call, but the file descriptor
  238. can be reused for other purposes. The file descriptor is returned.
  239. """
  240. self._closed = True
  241. return self._sock.detach()
  242. def connect(self, address):
  243. if self.timeout == 0.0:
  244. return _socket.socket.connect(self._sock, address)
  245. if isinstance(address, tuple):
  246. r = getaddrinfo(address[0], address[1], self.family)
  247. address = r[0][-1]
  248. if self.timeout is not None:
  249. timer = Timeout.start_new(self.timeout, timeout('timed out'))
  250. else:
  251. timer = None
  252. try:
  253. while True:
  254. err = self.getsockopt(SOL_SOCKET, SO_ERROR)
  255. if err:
  256. raise error(err, strerror(err))
  257. result = _socket.socket.connect_ex(self._sock, address)
  258. if not result or result == EISCONN:
  259. break
  260. elif (result in (EWOULDBLOCK, EINPROGRESS, EALREADY)) or (result == EINVAL and is_windows):
  261. self._wait(self._write_event)
  262. else:
  263. raise error(result, strerror(result))
  264. finally:
  265. if timer is not None:
  266. timer.cancel()
  267. def connect_ex(self, address):
  268. try:
  269. return self.connect(address) or 0
  270. except timeout:
  271. return EAGAIN
  272. except gaierror:
  273. # gaierror/overflowerror/typerror is not silenced by connect_ex;
  274. # gaierror extends OSError (aka error) so catch it first
  275. raise
  276. except error as ex:
  277. # error is now OSError and it has various subclasses.
  278. # Only those that apply to actually connecting are silenced by
  279. # connect_ex.
  280. if ex.errno:
  281. return ex.errno
  282. raise # pragma: no cover
  283. def recv(self, *args):
  284. while True:
  285. try:
  286. return _socket.socket.recv(self._sock, *args)
  287. except error as ex:
  288. if ex.args[0] != EWOULDBLOCK or self.timeout == 0.0:
  289. raise
  290. self._wait(self._read_event)
  291. if hasattr(_socket.socket, 'sendmsg'):
  292. # Only on Unix
  293. def recvmsg(self, *args):
  294. while True:
  295. try:
  296. return _socket.socket.recvmsg(self._sock, *args)
  297. except error as ex:
  298. if ex.args[0] != EWOULDBLOCK or self.timeout == 0.0:
  299. raise
  300. self._wait(self._read_event)
  301. def recvmsg_into(self, *args):
  302. while True:
  303. try:
  304. return _socket.socket.recvmsg_into(self._sock, *args)
  305. except error as ex:
  306. if ex.args[0] != EWOULDBLOCK or self.timeout == 0.0:
  307. raise
  308. self._wait(self._read_event)
  309. def recvfrom(self, *args):
  310. while True:
  311. try:
  312. return _socket.socket.recvfrom(self._sock, *args)
  313. except error as ex:
  314. if ex.args[0] != EWOULDBLOCK or self.timeout == 0.0:
  315. raise
  316. self._wait(self._read_event)
  317. def recvfrom_into(self, *args):
  318. while True:
  319. try:
  320. return _socket.socket.recvfrom_into(self._sock, *args)
  321. except error as ex:
  322. if ex.args[0] != EWOULDBLOCK or self.timeout == 0.0:
  323. raise
  324. self._wait(self._read_event)
  325. def recv_into(self, *args):
  326. while True:
  327. try:
  328. return _socket.socket.recv_into(self._sock, *args)
  329. except error as ex:
  330. if ex.args[0] != EWOULDBLOCK or self.timeout == 0.0:
  331. raise
  332. self._wait(self._read_event)
  333. def send(self, data, flags=0, timeout=timeout_default):
  334. if timeout is timeout_default:
  335. timeout = self.timeout
  336. try:
  337. return _socket.socket.send(self._sock, data, flags)
  338. except error as ex:
  339. if ex.args[0] != EWOULDBLOCK or timeout == 0.0:
  340. raise
  341. self._wait(self._write_event)
  342. try:
  343. return _socket.socket.send(self._sock, data, flags)
  344. except error as ex2:
  345. if ex2.args[0] == EWOULDBLOCK:
  346. return 0
  347. raise
  348. def sendall(self, data, flags=0):
  349. # XXX Now that we run on PyPy3, see the notes in _socket2.py's sendall()
  350. # and implement that here if needed.
  351. # PyPy3 is not optimized for performance yet, and is known to be slower than
  352. # PyPy2, so it's possibly premature to do this. However, there is a 3.5 test case that
  353. # possibly exposes this in a severe way.
  354. data_memory = _get_memory(data)
  355. len_data_memory = len(data_memory)
  356. if not len_data_memory:
  357. # Don't try to send empty data at all, no point, and breaks ssl
  358. # See issue 719
  359. return 0
  360. if self.timeout is None:
  361. data_sent = 0
  362. while data_sent < len_data_memory:
  363. data_sent += self.send(data_memory[data_sent:], flags)
  364. else:
  365. timeleft = self.timeout
  366. end = time.time() + timeleft
  367. data_sent = 0
  368. while True:
  369. data_sent += self.send(data_memory[data_sent:], flags, timeout=timeleft)
  370. if data_sent >= len_data_memory:
  371. break
  372. timeleft = end - time.time()
  373. if timeleft <= 0:
  374. raise timeout('timed out')
  375. def sendto(self, *args):
  376. try:
  377. return _socket.socket.sendto(self._sock, *args)
  378. except error as ex:
  379. if ex.args[0] != EWOULDBLOCK or self.timeout == 0.0:
  380. raise
  381. self._wait(self._write_event)
  382. try:
  383. return _socket.socket.sendto(self._sock, *args)
  384. except error as ex2:
  385. if ex2.args[0] == EWOULDBLOCK:
  386. return 0
  387. raise
  388. if hasattr(_socket.socket, 'sendmsg'):
  389. # Only on Unix
  390. def sendmsg(self, buffers, ancdata=(), flags=0, address=None):
  391. try:
  392. return _socket.socket.sendmsg(self._sock, buffers, ancdata, flags, address)
  393. except error as ex:
  394. if flags & getattr(_socket, 'MSG_DONTWAIT', 0):
  395. # Enable non-blocking behaviour
  396. # XXX: Do all platforms that have sendmsg have MSG_DONTWAIT?
  397. raise
  398. if ex.args[0] != EWOULDBLOCK or self.timeout == 0.0:
  399. raise
  400. self._wait(self._write_event)
  401. try:
  402. return _socket.socket.sendmsg(self._sock, buffers, ancdata, flags, address)
  403. except error as ex2:
  404. if ex2.args[0] == EWOULDBLOCK:
  405. return 0
  406. raise
  407. def setblocking(self, flag):
  408. if flag:
  409. self.timeout = None
  410. else:
  411. self.timeout = 0.0
  412. def settimeout(self, howlong):
  413. if howlong is not None:
  414. try:
  415. f = howlong.__float__
  416. except AttributeError:
  417. raise TypeError('a float is required')
  418. howlong = f()
  419. if howlong < 0.0:
  420. raise ValueError('Timeout value out of range')
  421. self.__dict__['timeout'] = howlong
  422. def gettimeout(self):
  423. return self.__dict__['timeout']
  424. def shutdown(self, how):
  425. if how == 0: # SHUT_RD
  426. self.hub.cancel_wait(self._read_event, cancel_wait_ex)
  427. elif how == 1: # SHUT_WR
  428. self.hub.cancel_wait(self._write_event, cancel_wait_ex)
  429. else:
  430. self.hub.cancel_wait(self._read_event, cancel_wait_ex)
  431. self.hub.cancel_wait(self._write_event, cancel_wait_ex)
  432. self._sock.shutdown(how)
  433. # sendfile: new in 3.5. But there's no real reason to not
  434. # support it everywhere. Note that we can't use os.sendfile()
  435. # because it's not cooperative.
  436. def _sendfile_use_sendfile(self, file, offset=0, count=None):
  437. # This is called directly by tests
  438. raise __socket__._GiveupOnSendfile() # pylint:disable=no-member
  439. def _sendfile_use_send(self, file, offset=0, count=None):
  440. self._check_sendfile_params(file, offset, count)
  441. if self.gettimeout() == 0:
  442. raise ValueError("non-blocking sockets are not supported")
  443. if offset:
  444. file.seek(offset)
  445. blocksize = min(count, 8192) if count else 8192
  446. total_sent = 0
  447. # localize variable access to minimize overhead
  448. file_read = file.read
  449. sock_send = self.send
  450. try:
  451. while True:
  452. if count:
  453. blocksize = min(count - total_sent, blocksize)
  454. if blocksize <= 0:
  455. break
  456. data = memoryview(file_read(blocksize))
  457. if not data:
  458. break # EOF
  459. while True:
  460. try:
  461. sent = sock_send(data)
  462. except BlockingIOError:
  463. continue
  464. else:
  465. total_sent += sent
  466. if sent < len(data):
  467. data = data[sent:]
  468. else:
  469. break
  470. return total_sent
  471. finally:
  472. if total_sent > 0 and hasattr(file, 'seek'):
  473. file.seek(offset + total_sent)
  474. def _check_sendfile_params(self, file, offset, count):
  475. if 'b' not in getattr(file, 'mode', 'b'):
  476. raise ValueError("file should be opened in binary mode")
  477. if not self.type & SOCK_STREAM:
  478. raise ValueError("only SOCK_STREAM type sockets are supported")
  479. if count is not None:
  480. if not isinstance(count, int):
  481. raise TypeError(
  482. "count must be a positive integer (got {!r})".format(count))
  483. if count <= 0:
  484. raise ValueError(
  485. "count must be a positive integer (got {!r})".format(count))
  486. def sendfile(self, file, offset=0, count=None):
  487. """sendfile(file[, offset[, count]]) -> sent
  488. Send a file until EOF is reached by using high-performance
  489. os.sendfile() and return the total number of bytes which
  490. were sent.
  491. *file* must be a regular file object opened in binary mode.
  492. If os.sendfile() is not available (e.g. Windows) or file is
  493. not a regular file socket.send() will be used instead.
  494. *offset* tells from where to start reading the file.
  495. If specified, *count* is the total number of bytes to transmit
  496. as opposed to sending the file until EOF is reached.
  497. File position is updated on return or also in case of error in
  498. which case file.tell() can be used to figure out the number of
  499. bytes which were sent.
  500. The socket must be of SOCK_STREAM type.
  501. Non-blocking sockets are not supported.
  502. .. versionadded:: 1.1rc4
  503. Added in Python 3.5, but available under all Python 3 versions in
  504. gevent.
  505. """
  506. return self._sendfile_use_send(file, offset, count)
  507. # get/set_inheritable new in 3.4
  508. if hasattr(os, 'get_inheritable') or hasattr(os, 'get_handle_inheritable'):
  509. # pylint:disable=no-member
  510. if os.name == 'nt':
  511. def get_inheritable(self):
  512. return os.get_handle_inheritable(self.fileno())
  513. def set_inheritable(self, inheritable):
  514. os.set_handle_inheritable(self.fileno(), inheritable)
  515. else:
  516. def get_inheritable(self):
  517. return os.get_inheritable(self.fileno())
  518. def set_inheritable(self, inheritable):
  519. os.set_inheritable(self.fileno(), inheritable)
  520. _added = "\n\n.. versionadded:: 1.1rc4 Added in Python 3.4"
  521. get_inheritable.__doc__ = "Get the inheritable flag of the socket" + _added
  522. set_inheritable.__doc__ = "Set the inheritable flag of the socket" + _added
  523. del _added
  524. if sys.version_info[:2] == (3, 4) and sys.version_info[:3] <= (3, 4, 2):
  525. # Python 3.4, up to and including 3.4.2, had a bug where the
  526. # SocketType enumeration overwrote the SocketType class imported
  527. # from _socket. This was fixed in 3.4.3 (http://bugs.python.org/issue20386
  528. # and https://github.com/python/cpython/commit/0d2f85f38a9691efdfd1e7285c4262cab7f17db7).
  529. # Prior to that, if we replace SocketType with our own class, the implementation
  530. # of socket.type breaks with "OSError: [Errno 97] Address family not supported by protocol".
  531. # Therefore, on these old versions, we must preserve it as an enum; while this
  532. # seems like it could lead to non-green behaviour, code on those versions
  533. # cannot possibly be using SocketType as a class anyway.
  534. SocketType = __socket__.SocketType # pylint:disable=no-member
  535. # Fixup __all__; note that we get exec'd multiple times during unit tests
  536. if 'SocketType' in __implements__:
  537. __implements__.remove('SocketType')
  538. if 'SocketType' not in __imports__:
  539. __imports__.append('SocketType')
  540. else:
  541. SocketType = socket
  542. def fromfd(fd, family, type, proto=0):
  543. """ fromfd(fd, family, type[, proto]) -> socket object
  544. Create a socket object from a duplicate of the given file
  545. descriptor. The remaining arguments are the same as for socket().
  546. """
  547. nfd = dup(fd)
  548. return socket(family, type, proto, nfd)
  549. if hasattr(_socket.socket, "share"):
  550. def fromshare(info):
  551. """ fromshare(info) -> socket object
  552. Create a socket object from a the bytes object returned by
  553. socket.share(pid).
  554. """
  555. return socket(0, 0, 0, info)
  556. __implements__.append('fromshare')
  557. if hasattr(_socket, "socketpair"):
  558. def socketpair(family=None, type=SOCK_STREAM, proto=0):
  559. """socketpair([family[, type[, proto]]]) -> (socket object, socket object)
  560. Create a pair of socket objects from the sockets returned by the platform
  561. socketpair() function.
  562. The arguments are the same as for socket() except the default family is
  563. AF_UNIX if defined on the platform; otherwise, the default is AF_INET.
  564. .. versionchanged:: 1.2
  565. All Python 3 versions on Windows supply this function (natively
  566. supplied by Python 3.5 and above).
  567. """
  568. if family is None:
  569. try:
  570. family = AF_UNIX
  571. except NameError:
  572. family = AF_INET
  573. a, b = _socket.socketpair(family, type, proto)
  574. a = socket(family, type, proto, a.detach())
  575. b = socket(family, type, proto, b.detach())
  576. return a, b
  577. else:
  578. # Origin: https://gist.github.com/4325783, by Geert Jansen. Public domain.
  579. # gevent: taken from 3.6 release. Expected to be used only on Win. Added to Win/3.5
  580. # gevent: for < 3.5, pass the default value of 128 to lsock.listen()
  581. # (3.5+ uses this as a default and the original code passed no value)
  582. _LOCALHOST = '127.0.0.1'
  583. _LOCALHOST_V6 = '::1'
  584. def socketpair(family=AF_INET, type=SOCK_STREAM, proto=0):
  585. if family == AF_INET:
  586. host = _LOCALHOST
  587. elif family == AF_INET6:
  588. host = _LOCALHOST_V6
  589. else:
  590. raise ValueError("Only AF_INET and AF_INET6 socket address families "
  591. "are supported")
  592. if type != SOCK_STREAM:
  593. raise ValueError("Only SOCK_STREAM socket type is supported")
  594. if proto != 0:
  595. raise ValueError("Only protocol zero is supported")
  596. # We create a connected TCP socket. Note the trick with
  597. # setblocking(False) that prevents us from having to create a thread.
  598. lsock = socket(family, type, proto)
  599. try:
  600. lsock.bind((host, 0))
  601. lsock.listen(128)
  602. # On IPv6, ignore flow_info and scope_id
  603. addr, port = lsock.getsockname()[:2]
  604. csock = socket(family, type, proto)
  605. try:
  606. csock.setblocking(False)
  607. try:
  608. csock.connect((addr, port))
  609. except (BlockingIOError, InterruptedError):
  610. pass
  611. csock.setblocking(True)
  612. ssock, _ = lsock.accept()
  613. except:
  614. csock.close()
  615. raise
  616. finally:
  617. lsock.close()
  618. return (ssock, csock)
  619. if sys.version_info[:2] < (3, 5):
  620. # Not provided natively
  621. if 'socketpair' in __implements__:
  622. # Multiple imports can cause this to be missing if _socketcommon
  623. # was successfully imported, leading to subsequent imports to cause
  624. # ValueError
  625. __implements__.remove('socketpair')
  626. # PyPy needs drop and reuse
  627. def _do_reuse_or_drop(sock, methname):
  628. try:
  629. method = getattr(sock, methname)
  630. except (AttributeError, TypeError):
  631. pass
  632. else:
  633. method()
  634. from io import BytesIO
  635. class _basefileobject(object):
  636. """Faux file object attached to a socket object."""
  637. default_bufsize = 8192
  638. name = "<socket>"
  639. __slots__ = ["mode", "bufsize", "softspace",
  640. # "closed" is a property, see below
  641. "_sock", "_rbufsize", "_wbufsize", "_rbuf", "_wbuf", "_wbuf_len",
  642. "_close"]
  643. def __init__(self, sock, mode='rb', bufsize=-1, close=False):
  644. _do_reuse_or_drop(sock, '_reuse')
  645. self._sock = sock
  646. self.mode = mode # Not actually used in this version
  647. if bufsize < 0:
  648. bufsize = self.default_bufsize
  649. self.bufsize = bufsize
  650. self.softspace = False
  651. # _rbufsize is the suggested recv buffer size. It is *strictly*
  652. # obeyed within readline() for recv calls. If it is larger than
  653. # default_bufsize it will be used for recv calls within read().
  654. if bufsize == 0:
  655. self._rbufsize = 1
  656. elif bufsize == 1:
  657. self._rbufsize = self.default_bufsize
  658. else:
  659. self._rbufsize = bufsize
  660. self._wbufsize = bufsize
  661. # We use BytesIO for the read buffer to avoid holding a list
  662. # of variously sized string objects which have been known to
  663. # fragment the heap due to how they are malloc()ed and often
  664. # realloc()ed down much smaller than their original allocation.
  665. self._rbuf = BytesIO()
  666. self._wbuf = [] # A list of strings
  667. self._wbuf_len = 0
  668. self._close = close
  669. def _getclosed(self):
  670. return self._sock is None
  671. closed = property(_getclosed, doc="True if the file is closed")
  672. def close(self):
  673. try:
  674. if self._sock:
  675. self.flush()
  676. finally:
  677. s = self._sock
  678. self._sock = None
  679. if s is not None:
  680. if self._close:
  681. s.close()
  682. else:
  683. _do_reuse_or_drop(s, '_drop')
  684. def __del__(self):
  685. try:
  686. self.close()
  687. except: # pylint:disable=bare-except
  688. # close() may fail if __init__ didn't complete
  689. pass
  690. def flush(self):
  691. if self._wbuf:
  692. data = b"".join(self._wbuf)
  693. self._wbuf = []
  694. self._wbuf_len = 0
  695. buffer_size = max(self._rbufsize, self.default_bufsize)
  696. data_size = len(data)
  697. write_offset = 0
  698. view = memoryview(data)
  699. try:
  700. while write_offset < data_size:
  701. self._sock.sendall(view[write_offset:write_offset + buffer_size])
  702. write_offset += buffer_size
  703. finally:
  704. if write_offset < data_size:
  705. remainder = data[write_offset:]
  706. del view, data # explicit free
  707. self._wbuf.append(remainder)
  708. self._wbuf_len = len(remainder)
  709. def fileno(self):
  710. return self._sock.fileno()
  711. def write(self, data):
  712. if not isinstance(data, bytes):
  713. raise TypeError("Non-bytes data")
  714. if not data:
  715. return
  716. self._wbuf.append(data)
  717. self._wbuf_len += len(data)
  718. if (self._wbufsize == 0 or (self._wbufsize == 1 and b'\n' in data) or
  719. (self._wbufsize > 1 and self._wbuf_len >= self._wbufsize)):
  720. self.flush()
  721. def writelines(self, list):
  722. # XXX We could do better here for very long lists
  723. # XXX Should really reject non-string non-buffers
  724. lines = filter(None, map(str, list))
  725. self._wbuf_len += sum(map(len, lines))
  726. self._wbuf.extend(lines)
  727. if self._wbufsize <= 1 or self._wbuf_len >= self._wbufsize:
  728. self.flush()
  729. def read(self, size=-1):
  730. # Use max, disallow tiny reads in a loop as they are very inefficient.
  731. # We never leave read() with any leftover data from a new recv() call
  732. # in our internal buffer.
  733. rbufsize = max(self._rbufsize, self.default_bufsize)
  734. # Our use of BytesIO rather than lists of string objects returned by
  735. # recv() minimizes memory usage and fragmentation that occurs when
  736. # rbufsize is large compared to the typical return value of recv().
  737. buf = self._rbuf
  738. buf.seek(0, 2) # seek end
  739. if size < 0:
  740. # Read until EOF
  741. self._rbuf = BytesIO() # reset _rbuf. we consume it via buf.
  742. while True:
  743. try:
  744. data = self._sock.recv(rbufsize)
  745. except InterruptedError:
  746. continue
  747. if not data:
  748. break
  749. buf.write(data)
  750. return buf.getvalue()
  751. else:
  752. # Read until size bytes or EOF seen, whichever comes first
  753. buf_len = buf.tell()
  754. if buf_len >= size:
  755. # Already have size bytes in our buffer? Extract and return.
  756. buf.seek(0)
  757. rv = buf.read(size)
  758. self._rbuf = BytesIO()
  759. self._rbuf.write(buf.read())
  760. return rv
  761. self._rbuf = BytesIO() # reset _rbuf. we consume it via buf.
  762. while True:
  763. left = size - buf_len
  764. # recv() will malloc the amount of memory given as its
  765. # parameter even though it often returns much less data
  766. # than that. The returned data string is short lived
  767. # as we copy it into a BytesIO and free it. This avoids
  768. # fragmentation issues on many platforms.
  769. try:
  770. data = self._sock.recv(left)
  771. except InterruptedError:
  772. continue
  773. if not data:
  774. break
  775. n = len(data)
  776. if n == size and not buf_len:
  777. # Shortcut. Avoid buffer data copies when:
  778. # - We have no data in our buffer.
  779. # AND
  780. # - Our call to recv returned exactly the
  781. # number of bytes we were asked to read.
  782. return data
  783. if n == left:
  784. buf.write(data)
  785. del data # explicit free
  786. break
  787. assert n <= left, "recv(%d) returned %d bytes" % (left, n)
  788. buf.write(data)
  789. buf_len += n
  790. del data # explicit free
  791. #assert buf_len == buf.tell()
  792. return buf.getvalue()
  793. def readline(self, size=-1):
  794. # pylint:disable=too-many-return-statements
  795. buf = self._rbuf
  796. buf.seek(0, 2) # seek end
  797. if buf.tell() > 0:
  798. # check if we already have it in our buffer
  799. buf.seek(0)
  800. bline = buf.readline(size)
  801. if bline.endswith(b'\n') or len(bline) == size:
  802. self._rbuf = BytesIO()
  803. self._rbuf.write(buf.read())
  804. return bline
  805. del bline
  806. if size < 0: # pylint:disable=too-many-nested-blocks
  807. # Read until \n or EOF, whichever comes first
  808. if self._rbufsize <= 1:
  809. # Speed up unbuffered case
  810. buf.seek(0)
  811. buffers = [buf.read()]
  812. self._rbuf = BytesIO() # reset _rbuf. we consume it via buf.
  813. data = None
  814. recv = self._sock.recv
  815. while True:
  816. try:
  817. while data != b"\n":
  818. data = recv(1)
  819. if not data:
  820. break
  821. buffers.append(data)
  822. except InterruptedError:
  823. # The try..except to catch EINTR was moved outside the
  824. # recv loop to avoid the per byte overhead.
  825. continue
  826. break
  827. return b"".join(buffers)
  828. buf.seek(0, 2) # seek end
  829. self._rbuf = BytesIO() # reset _rbuf. we consume it via buf.
  830. while True:
  831. try:
  832. data = self._sock.recv(self._rbufsize)
  833. except InterruptedError:
  834. continue
  835. if not data:
  836. break
  837. nl = data.find(b'\n')
  838. if nl >= 0:
  839. nl += 1
  840. buf.write(data[:nl])
  841. self._rbuf.write(data[nl:])
  842. del data
  843. break
  844. buf.write(data)
  845. return buf.getvalue()
  846. else:
  847. # Read until size bytes or \n or EOF seen, whichever comes first
  848. buf.seek(0, 2) # seek end
  849. buf_len = buf.tell()
  850. if buf_len >= size:
  851. buf.seek(0)
  852. rv = buf.read(size)
  853. self._rbuf = BytesIO()
  854. self._rbuf.write(buf.read())
  855. return rv
  856. self._rbuf = BytesIO() # reset _rbuf. we consume it via buf.
  857. while True:
  858. try:
  859. data = self._sock.recv(self._rbufsize)
  860. except InterruptedError:
  861. continue
  862. if not data:
  863. break
  864. left = size - buf_len
  865. # did we just receive a newline?
  866. nl = data.find(b'\n', 0, left)
  867. if nl >= 0:
  868. nl += 1
  869. # save the excess data to _rbuf
  870. self._rbuf.write(data[nl:])
  871. if buf_len:
  872. buf.write(data[:nl])
  873. break
  874. else:
  875. # Shortcut. Avoid data copy through buf when returning
  876. # a substring of our first recv().
  877. return data[:nl]
  878. n = len(data)
  879. if n == size and not buf_len:
  880. # Shortcut. Avoid data copy through buf when
  881. # returning exactly all of our first recv().
  882. return data
  883. if n >= left:
  884. buf.write(data[:left])
  885. self._rbuf.write(data[left:])
  886. break
  887. buf.write(data)
  888. buf_len += n
  889. #assert buf_len == buf.tell()
  890. return buf.getvalue()
  891. def readlines(self, sizehint=0):
  892. total = 0
  893. list = []
  894. while True:
  895. line = self.readline()
  896. if not line:
  897. break
  898. list.append(line)
  899. total += len(line)
  900. if sizehint and total >= sizehint:
  901. break
  902. return list
  903. # Iterator protocols
  904. def __iter__(self):
  905. return self
  906. def next(self):
  907. line = self.readline()
  908. if not line:
  909. raise StopIteration
  910. return line
  911. __next__ = next
  912. try:
  913. from gevent.fileobject import FileObjectPosix
  914. except ImportError:
  915. # Manual implementation
  916. _fileobject = _basefileobject
  917. else:
  918. class _fileobject(FileObjectPosix):
  919. # Add the proper drop/reuse support for pypy, and match
  920. # the close=False default in the constructor
  921. def __init__(self, sock, mode='rb', bufsize=-1, close=False):
  922. _do_reuse_or_drop(sock, '_reuse')
  923. self._sock = sock
  924. FileObjectPosix.__init__(self, sock, mode, bufsize, close)
  925. def close(self):
  926. try:
  927. if self._sock:
  928. self.flush()
  929. finally:
  930. s = self._sock
  931. self._sock = None
  932. if s is not None:
  933. if self._close:
  934. FileObjectPosix.close(self)
  935. else:
  936. _do_reuse_or_drop(s, '_drop')
  937. def __del__(self):
  938. try:
  939. self.close()
  940. except: # pylint:disable=bare-except
  941. # close() may fail if __init__ didn't complete
  942. pass
  943. __all__ = __implements__ + __extensions__ + __imports__