Created
May 2, 2025 15:05
-
-
Save cjavad/b804b4fada7ff0e18cf77d43b7f731dd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| Patch out settimeout on SSL connection to allow keepalive to be set to 0. | |
| """ | |
| import socket | |
| import ssl | |
| import paho.mqtt.client as mqtt | |
| def _ssl_wrap_socket(self, tcp_sock: socket.socket) -> ssl.SSLSocket: | |
| if self._ssl_context is None: | |
| raise ValueError( | |
| "Impossible condition. _ssl_context should never be None if _ssl is True" | |
| ) | |
| verify_host = not self._tls_insecure | |
| try: | |
| # Try with server_hostname, even it's not supported in certain scenarios | |
| ssl_sock = self._ssl_context.wrap_socket( | |
| tcp_sock, | |
| server_hostname=self._host, | |
| do_handshake_on_connect=False, | |
| ) | |
| except ssl.CertificateError: | |
| # CertificateError is derived from ValueError | |
| raise | |
| except ValueError: | |
| # Python version requires SNI in order to handle server_hostname, but SNI is not available | |
| ssl_sock = self._ssl_context.wrap_socket( | |
| tcp_sock, | |
| do_handshake_on_connect=False, | |
| ) | |
| else: | |
| # If SSL context has already checked hostname, then don't need to do it again | |
| if getattr(self._ssl_context, 'check_hostname', False): # type: ignore | |
| verify_host = False | |
| # PATCH: | |
| # ssl_sock.settimeout(self._keepalive) | |
| ssl_sock.do_handshake() | |
| if verify_host: | |
| # TODO: this type error is a true error: | |
| # error: Module has no attribute "match_hostname" [attr-defined] | |
| # Python 3.12 no longer have this method. | |
| ssl.match_hostname(ssl_sock.getpeercert(), self._host) # type: ignore | |
| return ssl_sock | |
| mqtt.Client._ssl_wrap_socket = _ssl_wrap_socket |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment