PageRenderTime 48ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/socket.py

http://github.com/IronLanguages/main
Python | 577 lines | 558 code | 2 blank | 17 comment | 1 complexity | ece5ec00cade2b96bc8cbc145e2db876 MD5 | raw file
Possible License(s): CPL-1.0, BSD-3-Clause, ISC, GPL-2.0, MPL-2.0-no-copyleft-exception
  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. gethostname() -- return the current hostname
  13. gethostbyname() -- map a hostname to its IP number
  14. gethostbyaddr() -- map an IP number or hostname to DNS info
  15. getservbyname() -- map a service name and a protocol name to a port number
  16. getprotobyname() -- map a protocol name (e.g. 'tcp') to a number
  17. ntohs(), ntohl() -- convert 16, 32 bit int from network to host byte order
  18. htons(), htonl() -- convert 16, 32 bit int from host to network byte order
  19. inet_aton() -- convert IP addr string (123.45.67.89) to 32-bit packed format
  20. inet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89)
  21. ssl() -- secure socket layer support (only available if configured)
  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. Integer 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. Many other constants may be defined; these may be used in calls to
  35. the setsockopt() and getsockopt() methods.
  36. """
  37. import _socket
  38. from _socket import *
  39. from functools import partial
  40. from types import MethodType
  41. try:
  42. import _ssl
  43. except ImportError:
  44. # no SSL support
  45. pass
  46. else:
  47. def ssl(sock, keyfile=None, certfile=None):
  48. # we do an internal import here because the ssl
  49. # module imports the socket module
  50. import ssl as _realssl
  51. warnings.warn("socket.ssl() is deprecated. Use ssl.wrap_socket() instead.",
  52. DeprecationWarning, stacklevel=2)
  53. return _realssl.sslwrap_simple(sock, keyfile, certfile)
  54. # we need to import the same constants we used to...
  55. from _ssl import SSLError as sslerror
  56. from _ssl import \
  57. RAND_add, \
  58. RAND_status, \
  59. SSL_ERROR_ZERO_RETURN, \
  60. SSL_ERROR_WANT_READ, \
  61. SSL_ERROR_WANT_WRITE, \
  62. SSL_ERROR_WANT_X509_LOOKUP, \
  63. SSL_ERROR_SYSCALL, \
  64. SSL_ERROR_SSL, \
  65. SSL_ERROR_WANT_CONNECT, \
  66. SSL_ERROR_EOF, \
  67. SSL_ERROR_INVALID_ERROR_CODE
  68. try:
  69. from _ssl import RAND_egd
  70. except ImportError:
  71. # LibreSSL does not provide RAND_egd
  72. pass
  73. import os, sys, warnings
  74. try:
  75. from cStringIO import StringIO
  76. except ImportError:
  77. from StringIO import StringIO
  78. try:
  79. import errno
  80. except ImportError:
  81. errno = None
  82. EBADF = getattr(errno, 'EBADF', 9)
  83. EINTR = getattr(errno, 'EINTR', 4)
  84. __all__ = ["getfqdn", "create_connection"]
  85. __all__.extend(os._get_exports_list(_socket))
  86. _realsocket = socket
  87. # WSA error codes
  88. if sys.platform.lower().startswith("win"):
  89. errorTab = {}
  90. errorTab[10004] = "The operation was interrupted."
  91. errorTab[10009] = "A bad file handle was passed."
  92. errorTab[10013] = "Permission denied."
  93. errorTab[10014] = "A fault occurred on the network??" # WSAEFAULT
  94. errorTab[10022] = "An invalid operation was attempted."
  95. errorTab[10035] = "The socket operation would block"
  96. errorTab[10036] = "A blocking operation is already in progress."
  97. errorTab[10048] = "The network address is in use."
  98. errorTab[10054] = "The connection has been reset."
  99. errorTab[10058] = "The network has been shut down."
  100. errorTab[10060] = "The operation timed out."
  101. errorTab[10061] = "Connection refused."
  102. errorTab[10063] = "The name is too long."
  103. errorTab[10064] = "The host is down."
  104. errorTab[10065] = "The host is unreachable."
  105. __all__.append("errorTab")
  106. def getfqdn(name=''):
  107. """Get fully qualified domain name from name.
  108. An empty argument is interpreted as meaning the local host.
  109. First the hostname returned by gethostbyaddr() is checked, then
  110. possibly existing aliases. In case no FQDN is available, hostname
  111. from gethostname() is returned.
  112. """
  113. name = name.strip()
  114. if not name or name == '0.0.0.0':
  115. name = gethostname()
  116. try:
  117. hostname, aliases, ipaddrs = gethostbyaddr(name)
  118. except error:
  119. pass
  120. else:
  121. aliases.insert(0, hostname)
  122. for name in aliases:
  123. if '.' in name:
  124. break
  125. else:
  126. name = hostname
  127. return name
  128. _socketmethods = (
  129. 'bind', 'connect', 'connect_ex', 'fileno', 'listen',
  130. 'getpeername', 'getsockname', 'getsockopt', 'setsockopt',
  131. 'sendall', 'setblocking',
  132. 'settimeout', 'gettimeout', 'shutdown')
  133. if os.name == "nt":
  134. _socketmethods = _socketmethods + ('ioctl',)
  135. if sys.platform == "riscos":
  136. _socketmethods = _socketmethods + ('sleeptaskw',)
  137. # All the method names that must be delegated to either the real socket
  138. # object or the _closedsocket object.
  139. _delegate_methods = ("recv", "recvfrom", "recv_into", "recvfrom_into",
  140. "send", "sendto")
  141. class _closedsocket(object):
  142. __slots__ = []
  143. def _dummy(*args):
  144. raise error(EBADF, 'Bad file descriptor')
  145. # All _delegate_methods must also be initialized here.
  146. send = recv = recv_into = sendto = recvfrom = recvfrom_into = _dummy
  147. __getattr__ = _dummy
  148. # Wrapper around platform socket objects. This implements
  149. # a platform-independent dup() functionality. The
  150. # implementation currently relies on reference counting
  151. # to close the underlying socket object.
  152. class _socketobject(object):
  153. __doc__ = _realsocket.__doc__
  154. __slots__ = ["_sock", "__weakref__"] + list(_delegate_methods)
  155. def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, _sock=None):
  156. if _sock is None:
  157. _sock = _realsocket(family, type, proto)
  158. self._sock = _sock
  159. for method in _delegate_methods:
  160. setattr(self, method, getattr(_sock, method))
  161. def close(self, _closedsocket=_closedsocket,
  162. _delegate_methods=_delegate_methods, setattr=setattr):
  163. # This function should not reference any globals. See issue #808164.
  164. self._sock = _closedsocket()
  165. dummy = self._sock._dummy
  166. for method in _delegate_methods:
  167. setattr(self, method, dummy)
  168. close.__doc__ = _realsocket.close.__doc__
  169. def accept(self):
  170. sock, addr = self._sock.accept()
  171. return _socketobject(_sock=sock), addr
  172. accept.__doc__ = _realsocket.accept.__doc__
  173. def dup(self):
  174. """dup() -> socket object
  175. Return a new socket object connected to the same system resource."""
  176. return _socketobject(_sock=self._sock)
  177. def makefile(self, mode='r', bufsize=-1):
  178. """makefile([mode[, bufsize]]) -> file object
  179. Return a regular file object corresponding to the socket. The mode
  180. and bufsize arguments are as for the built-in open() function."""
  181. return _fileobject(self._sock, mode, bufsize)
  182. family = property(lambda self: self._sock.family, doc="the socket family")
  183. type = property(lambda self: self._sock.type, doc="the socket type")
  184. proto = property(lambda self: self._sock.proto, doc="the socket protocol")
  185. def meth(name,self,*args):
  186. return getattr(self._sock,name)(*args)
  187. for _m in _socketmethods:
  188. p = partial(meth,_m)
  189. p.__name__ = _m
  190. p.__doc__ = getattr(_realsocket,_m).__doc__
  191. m = MethodType(p,None,_socketobject)
  192. setattr(_socketobject,_m,m)
  193. socket = SocketType = _socketobject
  194. class _fileobject(object):
  195. """Faux file object attached to a socket object."""
  196. default_bufsize = 8192
  197. name = "<socket>"
  198. __slots__ = ["mode", "bufsize", "softspace",
  199. # "closed" is a property, see below
  200. "_sock", "_rbufsize", "_wbufsize", "_rbuf", "_wbuf", "_wbuf_len",
  201. "_close"]
  202. def __init__(self, sock, mode='rb', bufsize=-1, close=False):
  203. self._sock = sock
  204. self.mode = mode # Not actually used in this version
  205. if bufsize < 0:
  206. bufsize = self.default_bufsize
  207. self.bufsize = bufsize
  208. self.softspace = False
  209. # _rbufsize is the suggested recv buffer size. It is *strictly*
  210. # obeyed within readline() for recv calls. If it is larger than
  211. # default_bufsize it will be used for recv calls within read().
  212. if bufsize == 0:
  213. self._rbufsize = 1
  214. elif bufsize == 1:
  215. self._rbufsize = self.default_bufsize
  216. else:
  217. self._rbufsize = bufsize
  218. self._wbufsize = bufsize
  219. # We use StringIO for the read buffer to avoid holding a list
  220. # of variously sized string objects which have been known to
  221. # fragment the heap due to how they are malloc()ed and often
  222. # realloc()ed down much smaller than their original allocation.
  223. self._rbuf = StringIO()
  224. self._wbuf = [] # A list of strings
  225. self._wbuf_len = 0
  226. self._close = close
  227. def _getclosed(self):
  228. return self._sock is None
  229. closed = property(_getclosed, doc="True if the file is closed")
  230. def close(self):
  231. try:
  232. if self._sock:
  233. self.flush()
  234. finally:
  235. if self._close:
  236. self._sock.close()
  237. self._sock = None
  238. def __del__(self):
  239. try:
  240. self.close()
  241. except:
  242. # close() may fail if __init__ didn't complete
  243. pass
  244. def flush(self):
  245. if self._wbuf:
  246. data = "".join(self._wbuf)
  247. self._wbuf = []
  248. self._wbuf_len = 0
  249. buffer_size = max(self._rbufsize, self.default_bufsize)
  250. data_size = len(data)
  251. write_offset = 0
  252. view = memoryview(data)
  253. try:
  254. while write_offset < data_size:
  255. self._sock.sendall(view[write_offset:write_offset+buffer_size])
  256. write_offset += buffer_size
  257. finally:
  258. if write_offset < data_size:
  259. remainder = data[write_offset:]
  260. del view, data # explicit free
  261. self._wbuf.append(remainder)
  262. self._wbuf_len = len(remainder)
  263. def fileno(self):
  264. return self._sock.fileno()
  265. def write(self, data):
  266. data = str(data) # XXX Should really reject non-string non-buffers
  267. if not data:
  268. return
  269. self._wbuf.append(data)
  270. self._wbuf_len += len(data)
  271. if (self._wbufsize == 0 or
  272. (self._wbufsize == 1 and '\n' in data) or
  273. (self._wbufsize > 1 and self._wbuf_len >= self._wbufsize)):
  274. self.flush()
  275. def writelines(self, list):
  276. # XXX We could do better here for very long lists
  277. # XXX Should really reject non-string non-buffers
  278. lines = filter(None, map(str, list))
  279. self._wbuf_len += sum(map(len, lines))
  280. self._wbuf.extend(lines)
  281. if (self._wbufsize <= 1 or
  282. self._wbuf_len >= self._wbufsize):
  283. self.flush()
  284. def read(self, size=-1):
  285. # Use max, disallow tiny reads in a loop as they are very inefficient.
  286. # We never leave read() with any leftover data from a new recv() call
  287. # in our internal buffer.
  288. rbufsize = max(self._rbufsize, self.default_bufsize)
  289. # Our use of StringIO rather than lists of string objects returned by
  290. # recv() minimizes memory usage and fragmentation that occurs when
  291. # rbufsize is large compared to the typical return value of recv().
  292. buf = self._rbuf
  293. buf.seek(0, 2) # seek end
  294. if size < 0:
  295. # Read until EOF
  296. self._rbuf = StringIO() # reset _rbuf. we consume it via buf.
  297. while True:
  298. try:
  299. data = self._sock.recv(rbufsize)
  300. except error, e:
  301. if e.args[0] == EINTR:
  302. continue
  303. raise
  304. if not data:
  305. break
  306. buf.write(data)
  307. return buf.getvalue()
  308. else:
  309. # Read until size bytes or EOF seen, whichever comes first
  310. buf_len = buf.tell()
  311. if buf_len >= size:
  312. # Already have size bytes in our buffer? Extract and return.
  313. buf.seek(0)
  314. rv = buf.read(size)
  315. self._rbuf = StringIO()
  316. self._rbuf.write(buf.read())
  317. return rv
  318. self._rbuf = StringIO() # reset _rbuf. we consume it via buf.
  319. while True:
  320. left = size - buf_len
  321. # recv() will malloc the amount of memory given as its
  322. # parameter even though it often returns much less data
  323. # than that. The returned data string is short lived
  324. # as we copy it into a StringIO and free it. This avoids
  325. # fragmentation issues on many platforms.
  326. try:
  327. data = self._sock.recv(left)
  328. except error, e:
  329. if e.args[0] == EINTR:
  330. continue
  331. raise
  332. if not data:
  333. break
  334. n = len(data)
  335. if n == size and not buf_len:
  336. # Shortcut. Avoid buffer data copies when:
  337. # - We have no data in our buffer.
  338. # AND
  339. # - Our call to recv returned exactly the
  340. # number of bytes we were asked to read.
  341. return data
  342. if n == left:
  343. buf.write(data)
  344. del data # explicit free
  345. break
  346. assert n <= left, "recv(%d) returned %d bytes" % (left, n)
  347. buf.write(data)
  348. buf_len += n
  349. del data # explicit free
  350. #assert buf_len == buf.tell()
  351. return buf.getvalue()
  352. def readline(self, size=-1):
  353. buf = self._rbuf
  354. buf.seek(0, 2) # seek end
  355. if buf.tell() > 0:
  356. # check if we already have it in our buffer
  357. buf.seek(0)
  358. bline = buf.readline(size)
  359. if bline.endswith('\n') or len(bline) == size:
  360. self._rbuf = StringIO()
  361. self._rbuf.write(buf.read())
  362. return bline
  363. del bline
  364. if size < 0:
  365. # Read until \n or EOF, whichever comes first
  366. if self._rbufsize <= 1:
  367. # Speed up unbuffered case
  368. buf.seek(0)
  369. buffers = [buf.read()]
  370. self._rbuf = StringIO() # reset _rbuf. we consume it via buf.
  371. data = None
  372. recv = self._sock.recv
  373. while True:
  374. try:
  375. while data != "\n":
  376. data = recv(1)
  377. if not data:
  378. break
  379. buffers.append(data)
  380. except error, e:
  381. # The try..except to catch EINTR was moved outside the
  382. # recv loop to avoid the per byte overhead.
  383. if e.args[0] == EINTR:
  384. continue
  385. raise
  386. break
  387. return "".join(buffers)
  388. buf.seek(0, 2) # seek end
  389. self._rbuf = StringIO() # reset _rbuf. we consume it via buf.
  390. while True:
  391. try:
  392. data = self._sock.recv(self._rbufsize)
  393. except error, e:
  394. if e.args[0] == EINTR:
  395. continue
  396. raise
  397. if not data:
  398. break
  399. nl = data.find('\n')
  400. if nl >= 0:
  401. nl += 1
  402. buf.write(data[:nl])
  403. self._rbuf.write(data[nl:])
  404. del data
  405. break
  406. buf.write(data)
  407. return buf.getvalue()
  408. else:
  409. # Read until size bytes or \n or EOF seen, whichever comes first
  410. buf.seek(0, 2) # seek end
  411. buf_len = buf.tell()
  412. if buf_len >= size:
  413. buf.seek(0)
  414. rv = buf.read(size)
  415. self._rbuf = StringIO()
  416. self._rbuf.write(buf.read())
  417. return rv
  418. self._rbuf = StringIO() # reset _rbuf. we consume it via buf.
  419. while True:
  420. try:
  421. data = self._sock.recv(self._rbufsize)
  422. except error, e:
  423. if e.args[0] == EINTR:
  424. continue
  425. raise
  426. if not data:
  427. break
  428. left = size - buf_len
  429. # did we just receive a newline?
  430. nl = data.find('\n', 0, left)
  431. if nl >= 0:
  432. nl += 1
  433. # save the excess data to _rbuf
  434. self._rbuf.write(data[nl:])
  435. if buf_len:
  436. buf.write(data[:nl])
  437. break
  438. else:
  439. # Shortcut. Avoid data copy through buf when returning
  440. # a substring of our first recv().
  441. return data[:nl]
  442. n = len(data)
  443. if n == size and not buf_len:
  444. # Shortcut. Avoid data copy through buf when
  445. # returning exactly all of our first recv().
  446. return data
  447. if n >= left:
  448. buf.write(data[:left])
  449. self._rbuf.write(data[left:])
  450. break
  451. buf.write(data)
  452. buf_len += n
  453. #assert buf_len == buf.tell()
  454. return buf.getvalue()
  455. def readlines(self, sizehint=0):
  456. total = 0
  457. list = []
  458. while True:
  459. line = self.readline()
  460. if not line:
  461. break
  462. list.append(line)
  463. total += len(line)
  464. if sizehint and total >= sizehint:
  465. break
  466. return list
  467. # Iterator protocols
  468. def __iter__(self):
  469. return self
  470. def next(self):
  471. line = self.readline()
  472. if not line:
  473. raise StopIteration
  474. return line
  475. _GLOBAL_DEFAULT_TIMEOUT = object()
  476. def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT,
  477. source_address=None):
  478. """Connect to *address* and return the socket object.
  479. Convenience function. Connect to *address* (a 2-tuple ``(host,
  480. port)``) and return the socket object. Passing the optional
  481. *timeout* parameter will set the timeout on the socket instance
  482. before attempting to connect. If no *timeout* is supplied, the
  483. global default timeout setting returned by :func:`getdefaulttimeout`
  484. is used. If *source_address* is set it must be a tuple of (host, port)
  485. for the socket to bind as a source address before making the connection.
  486. A host of '' or port 0 tells the OS to use the default.
  487. """
  488. host, port = address
  489. err = None
  490. for res in getaddrinfo(host, port, 0, SOCK_STREAM):
  491. af, socktype, proto, canonname, sa = res
  492. sock = None
  493. try:
  494. sock = socket(af, socktype, proto)
  495. if timeout is not _GLOBAL_DEFAULT_TIMEOUT:
  496. sock.settimeout(timeout)
  497. if source_address:
  498. sock.bind(source_address)
  499. sock.connect(sa)
  500. return sock
  501. except error as _:
  502. err = _
  503. if sock is not None:
  504. sock.close()
  505. if err is not None:
  506. raise err
  507. else:
  508. raise error("getaddrinfo returns an empty list")