socketutil.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. """
  2. Low level socket utilities.
  3. Pyro - Python Remote Objects. Copyright by Irmen de Jong (irmen@razorvine.net).
  4. """
  5. import socket
  6. import errno
  7. import time
  8. import sys
  9. import select
  10. import Pyro4.constants
  11. from Pyro4.errors import CommunicationError, TimeoutError, ConnectionClosedError
  12. try:
  13. InterruptedError() # new since Python 3.4
  14. except NameError:
  15. class InterruptedError(Exception):
  16. pass
  17. # Note: other interesting errnos are EPERM, ENOBUFS, EMFILE
  18. # but it seems to me that all these signify an unrecoverable situation.
  19. # So I didn't include them in the list of retryable errors.
  20. ERRNO_RETRIES = [errno.EINTR, errno.EAGAIN, errno.EWOULDBLOCK, errno.EINPROGRESS]
  21. if hasattr(errno, "WSAEINTR"):
  22. ERRNO_RETRIES.append(errno.WSAEINTR)
  23. if hasattr(errno, "WSAEWOULDBLOCK"):
  24. ERRNO_RETRIES.append(errno.WSAEWOULDBLOCK)
  25. if hasattr(errno, "WSAEINPROGRESS"):
  26. ERRNO_RETRIES.append(errno.WSAEINPROGRESS)
  27. ERRNO_BADF = [errno.EBADF]
  28. if hasattr(errno, "WSAEBADF"):
  29. ERRNO_BADF.append(errno.WSAEBADF)
  30. ERRNO_ENOTSOCK = [errno.ENOTSOCK]
  31. if hasattr(errno, "WSAENOTSOCK"):
  32. ERRNO_ENOTSOCK.append(errno.WSAENOTSOCK)
  33. if not hasattr(socket, "SOL_TCP"):
  34. socket.SOL_TCP = socket.IPPROTO_TCP
  35. ERRNO_EADDRNOTAVAIL = [errno.EADDRNOTAVAIL]
  36. if hasattr(errno, "WSAEADDRNOTAVAIL"):
  37. ERRNO_EADDRNOTAVAIL.append(errno.WSAEADDRNOTAVAIL)
  38. ERRNO_EADDRINUSE = [errno.EADDRINUSE]
  39. if hasattr(errno, "WSAEADDRINUSE"):
  40. ERRNO_EADDRINUSE.append(errno.WSAEADDRINUSE)
  41. if sys.version_info >= (3, 0):
  42. basestring = str
  43. def getIpVersion(hostnameOrAddress):
  44. """
  45. Determine what the IP version is of the given hostname or ip address (4 or 6).
  46. First, it resolves the hostname or address to get an IP address.
  47. Then, if the resolved IP contains a ':' it is considered to be an ipv6 address,
  48. and if it contains a '.', it is ipv4.
  49. """
  50. address = getIpAddress(hostnameOrAddress)
  51. if "." in address:
  52. return 4
  53. elif ":" in address:
  54. return 6
  55. else:
  56. raise CommunicationError("Unknown IP address format" + address)
  57. def getIpAddress(hostname, workaround127=False, ipVersion=None):
  58. """
  59. Returns the IP address for the given host. If you enable the workaround,
  60. it will use a little hack if the ip address is found to be the loopback address.
  61. The hack tries to discover an externally visible ip address instead (this only works for ipv4 addresses).
  62. Set ipVersion=6 to return ipv6 addresses, 4 to return ipv4, 0 to let OS choose the best one or None to use Pyro4.config.PREFER_IP_VERSION.
  63. """
  64. def getaddr(ipVersion):
  65. if ipVersion == 6:
  66. family = socket.AF_INET6
  67. elif ipVersion == 4:
  68. family = socket.AF_INET
  69. elif ipVersion == 0:
  70. family = socket.AF_UNSPEC
  71. else:
  72. raise ValueError("unknown value for argument ipVersion.")
  73. ip = socket.getaddrinfo(hostname or socket.gethostname(), 80, family, socket.SOCK_STREAM, socket.SOL_TCP)[0][4][0]
  74. if workaround127 and (ip.startswith("127.") or ip == "0.0.0.0"):
  75. ip = getInterfaceAddress("4.2.2.2")
  76. return ip
  77. try:
  78. if hostname and ':' in hostname and ipVersion is None:
  79. ipVersion = 0
  80. return getaddr(Pyro4.config.PREFER_IP_VERSION) if ipVersion is None else getaddr(ipVersion)
  81. except socket.gaierror:
  82. if ipVersion == 6 or (ipVersion is None and Pyro4.config.PREFER_IP_VERSION == 6):
  83. raise socket.error("unable to determine IPV6 address")
  84. return getaddr(0)
  85. def getInterfaceAddress(ip_address):
  86. """tries to find the ip address of the interface that connects to the given host's address"""
  87. family = socket.AF_INET if getIpVersion(ip_address) == 4 else socket.AF_INET6
  88. sock = socket.socket(family, socket.SOCK_DGRAM)
  89. try:
  90. sock.connect((ip_address, 53)) # 53=dns
  91. return sock.getsockname()[0]
  92. finally:
  93. sock.close()
  94. def __nextRetrydelay(delay):
  95. # first try a few very short delays,
  96. # if that doesn't work, increase by 0.1 sec every time
  97. if delay == 0.0:
  98. return 0.001
  99. if delay == 0.001:
  100. return 0.01
  101. return delay + 0.1
  102. def receiveData(sock, size):
  103. """Retrieve a given number of bytes from a socket.
  104. It is expected the socket is able to supply that number of bytes.
  105. If it isn't, an exception is raised (you will not get a zero length result
  106. or a result that is smaller than what you asked for). The partial data that
  107. has been received however is stored in the 'partialData' attribute of
  108. the exception object."""
  109. try:
  110. retrydelay = 0.0
  111. msglen = 0
  112. chunks = []
  113. if Pyro4.config.USE_MSG_WAITALL:
  114. # waitall is very convenient and if a socket error occurs,
  115. # we can assume the receive has failed. No need for a loop,
  116. # unless it is a retryable error.
  117. # Some systems have an erratic MSG_WAITALL and sometimes still return
  118. # less bytes than asked. In that case, we drop down into the normal
  119. # receive loop to finish the task.
  120. while True:
  121. try:
  122. data = sock.recv(size, socket.MSG_WAITALL)
  123. if len(data) == size:
  124. return data
  125. # less data than asked, drop down into normal receive loop to finish
  126. msglen = len(data)
  127. chunks = [data]
  128. break
  129. except socket.timeout:
  130. raise TimeoutError("receiving: timeout")
  131. except socket.error:
  132. x = sys.exc_info()[1]
  133. err = getattr(x, "errno", x.args[0])
  134. if err not in ERRNO_RETRIES:
  135. raise ConnectionClosedError("receiving: connection lost: " + str(x))
  136. time.sleep(0.00001 + retrydelay) # a slight delay to wait before retrying
  137. retrydelay = __nextRetrydelay(retrydelay)
  138. # old fashioned recv loop, we gather chunks until the message is complete
  139. while True:
  140. try:
  141. while msglen < size:
  142. # 60k buffer limit avoids problems on certain OSes like VMS, Windows
  143. chunk = sock.recv(min(60000, size - msglen))
  144. if not chunk:
  145. break
  146. chunks.append(chunk)
  147. msglen += len(chunk)
  148. data = b"".join(chunks)
  149. del chunks
  150. if len(data) != size:
  151. err = ConnectionClosedError("receiving: not enough data")
  152. err.partialData = data # store the message that was received until now
  153. raise err
  154. return data # yay, complete
  155. except socket.timeout:
  156. raise TimeoutError("receiving: timeout")
  157. except socket.error:
  158. x = sys.exc_info()[1]
  159. err = getattr(x, "errno", x.args[0])
  160. if err not in ERRNO_RETRIES:
  161. raise ConnectionClosedError("receiving: connection lost: " + str(x))
  162. time.sleep(0.00001 + retrydelay) # a slight delay to wait before retrying
  163. retrydelay = __nextRetrydelay(retrydelay)
  164. except socket.timeout:
  165. raise TimeoutError("receiving: timeout")
  166. def sendData(sock, data):
  167. """
  168. Send some data over a socket.
  169. Some systems have problems with ``sendall()`` when the socket is in non-blocking mode.
  170. For instance, Mac OS X seems to be happy to throw EAGAIN errors too often.
  171. This function falls back to using a regular send loop if needed.
  172. """
  173. if sock.gettimeout() is None:
  174. # socket is in blocking mode, we can use sendall normally.
  175. try:
  176. sock.sendall(data)
  177. return
  178. except socket.timeout:
  179. raise TimeoutError("sending: timeout")
  180. except socket.error:
  181. x = sys.exc_info()[1]
  182. raise ConnectionClosedError("sending: connection lost: " + str(x))
  183. else:
  184. # Socket is in non-blocking mode, use regular send loop.
  185. retrydelay = 0.0
  186. while data:
  187. try:
  188. sent = sock.send(data)
  189. data = data[sent:]
  190. except socket.timeout:
  191. raise TimeoutError("sending: timeout")
  192. except socket.error:
  193. x = sys.exc_info()[1]
  194. err = getattr(x, "errno", x.args[0])
  195. if err not in ERRNO_RETRIES:
  196. raise ConnectionClosedError("sending: connection lost: " + str(x))
  197. time.sleep(0.00001 + retrydelay) # a slight delay to wait before retrying
  198. retrydelay = __nextRetrydelay(retrydelay)
  199. _GLOBAL_DEFAULT_TIMEOUT = object()
  200. def createSocket(bind=None, connect=None, reuseaddr=False, keepalive=True, timeout=_GLOBAL_DEFAULT_TIMEOUT, noinherit=False, ipv6=False, nodelay=True):
  201. """
  202. Create a socket. Default socket options are keepalive and IPv4 family, and nodelay (nagle disabled).
  203. If 'bind' or 'connect' is a string, it is assumed a Unix domain socket is requested.
  204. Otherwise, a normal tcp/ip socket is used.
  205. Set ipv6=True to create an IPv6 socket rather than IPv4.
  206. Set ipv6=None to use the PREFER_IP_VERSION config setting.
  207. """
  208. if bind and connect:
  209. raise ValueError("bind and connect cannot both be specified at the same time")
  210. forceIPv6 = ipv6 or (ipv6 is None and Pyro4.config.PREFER_IP_VERSION == 6)
  211. if isinstance(bind, basestring) or isinstance(connect, basestring):
  212. family = socket.AF_UNIX
  213. elif not bind and not connect:
  214. family = socket.AF_INET6 if forceIPv6 else socket.AF_INET
  215. elif type(bind) is tuple:
  216. if not bind[0]:
  217. family = socket.AF_INET6 if forceIPv6 else socket.AF_INET
  218. else:
  219. if getIpVersion(bind[0]) == 4:
  220. if forceIPv6:
  221. raise ValueError("IPv4 address is used bind argument with forceIPv6 argument:" + bind[0] + ".")
  222. family = socket.AF_INET
  223. elif getIpVersion(bind[0]) == 6:
  224. family = socket.AF_INET6
  225. # replace bind addresses by their ipv6 counterparts (4-tuple)
  226. bind = (bind[0], bind[1], 0, 0)
  227. else:
  228. raise ValueError("unknown bind format.")
  229. elif type(connect) is tuple:
  230. if not connect[0]:
  231. family = socket.AF_INET6 if forceIPv6 else socket.AF_INET
  232. else:
  233. if getIpVersion(connect[0]) == 4:
  234. if forceIPv6:
  235. raise ValueError("IPv4 address is used in connect argument with forceIPv6 argument:" + bind[0] + ".")
  236. family = socket.AF_INET
  237. elif getIpVersion(connect[0]) == 6:
  238. family = socket.AF_INET6
  239. # replace connect addresses by their ipv6 counterparts (4-tuple)
  240. connect = (connect[0], connect[1], 0, 0)
  241. else:
  242. raise ValueError("unknown connect format.")
  243. else:
  244. raise ValueError("unknown bind or connect format.")
  245. sock = socket.socket(family, socket.SOCK_STREAM)
  246. if nodelay:
  247. setNoDelay(sock)
  248. if reuseaddr:
  249. setReuseAddr(sock)
  250. if noinherit:
  251. setNoInherit(sock)
  252. if timeout == 0:
  253. timeout = None
  254. if timeout is not _GLOBAL_DEFAULT_TIMEOUT:
  255. sock.settimeout(timeout)
  256. if bind:
  257. if type(bind) is tuple and bind[1] == 0:
  258. bindOnUnusedPort(sock, bind[0])
  259. else:
  260. sock.bind(bind)
  261. try:
  262. sock.listen(100)
  263. except Exception:
  264. pass
  265. if connect:
  266. try:
  267. sock.connect(connect)
  268. except socket.error:
  269. # This can happen when the socket is in non-blocking mode (or has a timeout configured).
  270. # We check if it is a retryable errno (usually EINPROGRESS).
  271. # If so, we use select() to wait until the socket is in writable state,
  272. # essentially rebuilding a blocking connect() call.
  273. xv = sys.exc_info()[1]
  274. errno = getattr(xv, "errno", 0)
  275. if errno in ERRNO_RETRIES:
  276. if timeout is _GLOBAL_DEFAULT_TIMEOUT or timeout < 0.1:
  277. timeout = 0.1
  278. while True:
  279. try:
  280. sr, sw, se = select.select([], [sock], [sock], timeout)
  281. except InterruptedError:
  282. continue
  283. if sock in sw:
  284. break # yay, writable now, connect() completed
  285. elif sock in se:
  286. sock.close() # close the socket that refused to connect
  287. raise socket.error("connect failed")
  288. else:
  289. sock.close() # close the socket that refused to connect
  290. raise
  291. if keepalive:
  292. setKeepalive(sock)
  293. return sock
  294. def createBroadcastSocket(bind=None, reuseaddr=False, timeout=_GLOBAL_DEFAULT_TIMEOUT, ipv6=False):
  295. """
  296. Create a udp broadcast socket.
  297. Set ipv6=True to create an IPv6 socket rather than IPv4.
  298. Set ipv6=None to use the PREFER_IP_VERSION config setting.
  299. """
  300. forceIPv6 = ipv6 or (ipv6 is None and Pyro4.config.PREFER_IP_VERSION == 6)
  301. if not bind:
  302. family = socket.AF_INET6 if forceIPv6 else socket.AF_INET
  303. elif type(bind) is tuple:
  304. if not bind[0]:
  305. family = socket.AF_INET6 if forceIPv6 else socket.AF_INET
  306. else:
  307. if getIpVersion(bind[0]) == 4:
  308. if forceIPv6:
  309. raise ValueError("IPv4 address is used with forceIPv6 option:" + bind[0] + ".")
  310. family = socket.AF_INET
  311. elif getIpVersion(bind[0]) == 6:
  312. family = socket.AF_INET6
  313. bind = (bind[0], bind[1], 0, 0)
  314. else:
  315. raise ValueError("unknown bind format: %r" % (bind,))
  316. else:
  317. raise ValueError("unknown bind format: %r" % (bind,))
  318. sock = socket.socket(family, socket.SOCK_DGRAM)
  319. if family == socket.AF_INET:
  320. sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
  321. if reuseaddr:
  322. setReuseAddr(sock)
  323. if timeout is None:
  324. sock.settimeout(None)
  325. else:
  326. if timeout is not _GLOBAL_DEFAULT_TIMEOUT:
  327. sock.settimeout(timeout)
  328. if bind:
  329. host = bind[0] or ""
  330. port = bind[1]
  331. if port == 0:
  332. bindOnUnusedPort(sock, host)
  333. else:
  334. if len(bind) == 2:
  335. sock.bind((host, port)) # ipv4
  336. elif len(bind) == 4:
  337. sock.bind((host, port, 0, 0)) # ipv6
  338. else:
  339. raise ValueError("bind must be None, 2-tuple or 4-tuple")
  340. return sock
  341. def setReuseAddr(sock):
  342. """sets the SO_REUSEADDR option on the socket, if possible."""
  343. try:
  344. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  345. except Exception:
  346. pass
  347. def setNoDelay(sock):
  348. """sets the TCP_NODELAY option on the socket (to disable Nagle's algorithm), if possible."""
  349. try:
  350. sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
  351. except Exception:
  352. pass
  353. def setKeepalive(sock):
  354. """sets the SO_KEEPALIVE option on the socket, if possible."""
  355. try:
  356. sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
  357. except Exception:
  358. pass
  359. try:
  360. import fcntl
  361. def setNoInherit(sock):
  362. """Mark the given socket fd as non-inheritable to child processes"""
  363. fd = sock.fileno()
  364. flags = fcntl.fcntl(fd, fcntl.F_GETFD)
  365. fcntl.fcntl(fd, fcntl.F_SETFD, flags | fcntl.FD_CLOEXEC)
  366. except ImportError:
  367. # no fcntl available, try the windows version
  368. try:
  369. if sys.platform == "cli":
  370. raise NotImplementedError("IronPython can't obtain a proper HANDLE from a socket")
  371. from ctypes import windll, WinError, wintypes
  372. # help ctypes to set the proper args for this kernel32 call on 64-bit pythons
  373. _SetHandleInformation = windll.kernel32.SetHandleInformation
  374. _SetHandleInformation.argtypes = [wintypes.HANDLE, wintypes.DWORD, wintypes.DWORD]
  375. _SetHandleInformation.restype = wintypes.BOOL # don't need this, but might as well
  376. def setNoInherit(sock):
  377. """Mark the given socket fd as non-inheritable to child processes"""
  378. if not _SetHandleInformation(sock.fileno(), 1, 0):
  379. raise WinError()
  380. except (ImportError, NotImplementedError):
  381. # nothing available, define a dummy function
  382. def setNoInherit(sock):
  383. """Mark the given socket fd as non-inheritable to child processes (dummy)"""
  384. pass
  385. class SocketConnection(object):
  386. """A wrapper class for plain sockets, containing various methods such as :meth:`send` and :meth:`recv`"""
  387. __slots__ = ["sock", "objectId", "pyroInstances"]
  388. def __init__(self, sock, objectId=None):
  389. self.sock = sock
  390. self.objectId = objectId
  391. self.pyroInstances = {} # pyro objects for instance_mode=session
  392. def __del__(self):
  393. self.close()
  394. def __enter__(self):
  395. return self
  396. def __exit__(self, exc_type, exc_val, exc_tb):
  397. self.close()
  398. def send(self, data):
  399. sendData(self.sock, data)
  400. def recv(self, size):
  401. return receiveData(self.sock, size)
  402. def close(self):
  403. try:
  404. self.sock.shutdown(socket.SHUT_RDWR)
  405. except:
  406. pass
  407. try:
  408. self.sock.close()
  409. except:
  410. pass
  411. self.pyroInstances = {} # force releasing the session instances
  412. def fileno(self):
  413. return self.sock.fileno()
  414. def setTimeout(self, timeout):
  415. self.sock.settimeout(timeout)
  416. def getTimeout(self):
  417. return self.sock.gettimeout()
  418. timeout = property(getTimeout, setTimeout)
  419. def findProbablyUnusedPort(family=socket.AF_INET, socktype=socket.SOCK_STREAM):
  420. """Returns an unused port that should be suitable for binding (likely, but not guaranteed).
  421. This code is copied from the stdlib's test.test_support module."""
  422. tempsock = socket.socket(family, socktype)
  423. try:
  424. port = bindOnUnusedPort(tempsock)
  425. if sys.platform == "cli":
  426. return port + 1 # the actual port is somehow still in use by the socket when using IronPython
  427. return port
  428. finally:
  429. tempsock.close()
  430. def bindOnUnusedPort(sock, host='localhost'):
  431. """Bind the socket to a free port and return the port number.
  432. This code is based on the code in the stdlib's test.test_support module."""
  433. if sock.family in (socket.AF_INET, socket.AF_INET6) and sock.type == socket.SOCK_STREAM:
  434. if hasattr(socket, "SO_EXCLUSIVEADDRUSE"):
  435. try:
  436. sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
  437. except socket.error:
  438. pass
  439. if sock.family == socket.AF_INET:
  440. if host == 'localhost':
  441. sock.bind(('127.0.0.1', 0))
  442. else:
  443. sock.bind((host, 0))
  444. elif sock.family == socket.AF_INET6:
  445. if host == 'localhost':
  446. sock.bind(('::1', 0, 0, 0))
  447. else:
  448. sock.bind((host, 0, 0, 0))
  449. else:
  450. raise CommunicationError("unsupported socket family: " + sock.family)
  451. return sock.getsockname()[1]
  452. def interruptSocket(address):
  453. """bit of a hack to trigger a blocking server to get out of the loop, useful at clean shutdowns"""
  454. try:
  455. sock = createSocket(connect=address, keepalive=False, timeout=None)
  456. try:
  457. sock.sendall(b"!" * 16)
  458. except (socket.error, AttributeError):
  459. pass
  460. try:
  461. sock.shutdown(socket.SHUT_RDWR)
  462. except (OSError, socket.error):
  463. pass
  464. sock.close()
  465. except socket.error:
  466. pass