Skip to content

Instantly share code, notes, and snippets.

@cjavad
Created May 2, 2025 15:05
Show Gist options
  • Select an option

  • Save cjavad/b804b4fada7ff0e18cf77d43b7f731dd to your computer and use it in GitHub Desktop.

Select an option

Save cjavad/b804b4fada7ff0e18cf77d43b7f731dd to your computer and use it in GitHub Desktop.
"""
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