socketutil.py 23 KB

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