[PATCH 6 of 6] sslutil: turn validator into a function

Gregory Szorc gregory.szorc at gmail.com
Mon Mar 28 02:21:35 EDT 2016


# HG changeset patch
# User Gregory Szorc <gregory.szorc at gmail.com>
# Date 1459115387 25200
#      Sun Mar 27 14:49:47 2016 -0700
# Node ID 7836c7bdec418c484c1a48d78aef58c3d9465ccd
# Parent  dca2139096ad8c263eaa1cfe589814259d92f3b7
sslutil: turn validator into a function

There used to be multiple consumers and having it a class kinda/sorta
made sense. This is no longer the case. Turn it into a regular
function.

diff --git a/mercurial/sslutil.py b/mercurial/sslutil.py
--- a/mercurial/sslutil.py
+++ b/mercurial/sslutil.py
@@ -193,18 +193,18 @@ def wrapsocket(sock, keyfile, certfile, 
 
     sslsocket = sslcontext.wrap_socket(sock, server_hostname=serverhostname)
     # check if wrap_socket failed silently because socket had been
     # closed
     # - see http://bugs.python.org/issue13721
     if not sslsocket.cipher():
         raise error.Abort(_('ssl connection failed'))
 
-    verifier = validator(ui, serverhostname)
-    verifier(sslsocket, strict=requirefingerprintwhennocacerts)
+    validatesocket(ui, serverhostname, sslsocket,
+                   strict=requirefingerprintwhennocacerts)
 
     return sslsocket
 
 def _verifycert(cert, hostname):
     '''Verify that cert (in socket.getpeercert() format) matches hostname.
     CRLs is not handled.
 
     Returns error message if any problems are found and None on success.
@@ -262,61 +262,56 @@ def _defaultcacerts():
     if _plainapplepython():
         dummycert = os.path.join(os.path.dirname(__file__), 'dummycert.pem')
         if os.path.exists(dummycert):
             return dummycert
     if _canloaddefaultcerts:
         return None
     return '!'
 
-class validator(object):
-    def __init__(self, ui, host):
-        self.ui = ui
-        self.host = host
+def validatesocket(ui, host, sock, strict=False):
+    """Validate that a SSL socket matches expectations."""
+    cacerts = ui.config('web', 'cacerts')
+    hostfingerprints = ui.configlist('hostfingerprints', host)
 
-    def __call__(self, sock, strict=False):
-        host = self.host
-        cacerts = self.ui.config('web', 'cacerts')
-        hostfingerprints = self.ui.configlist('hostfingerprints', host)
+    try:
+        peercert = sock.getpeercert(True)
+        peercert2 = sock.getpeercert()
+    except AttributeError:
+        raise error.Abort(_('%s ssl connection error') % host)
 
-        try:
-            peercert = sock.getpeercert(True)
-            peercert2 = sock.getpeercert()
-        except AttributeError:
-            raise error.Abort(_('%s ssl connection error') % host)
-
-        if not peercert:
-            raise error.Abort(_('%s certificate error: '
-                               'no certificate received') % host)
-        peerfingerprint = util.sha1(peercert).hexdigest()
-        nicefingerprint = ":".join([peerfingerprint[x:x + 2]
-            for x in xrange(0, len(peerfingerprint), 2)])
-        if hostfingerprints:
-            fingerprintmatch = False
-            for hostfingerprint in hostfingerprints:
-                if peerfingerprint.lower() == \
-                        hostfingerprint.replace(':', '').lower():
-                    fingerprintmatch = True
-                    break
-            if not fingerprintmatch:
-                raise error.Abort(_('certificate for %s has unexpected '
-                                   'fingerprint %s') % (host, nicefingerprint),
-                                 hint=_('check hostfingerprint configuration'))
-            self.ui.debug('%s certificate matched fingerprint %s\n' %
-                          (host, nicefingerprint))
-        elif cacerts != '!':
-            msg = _verifycert(peercert2, host)
-            if msg:
-                raise error.Abort(_('%s certificate error: %s') % (host, msg),
-                                 hint=_('configure hostfingerprint %s or use '
-                                        '--insecure to connect insecurely') %
-                                      nicefingerprint)
-            self.ui.debug('%s certificate successfully verified\n' % host)
-        elif strict:
-            raise error.Abort(_('%s certificate with fingerprint %s not '
-                               'verified') % (host, nicefingerprint),
-                             hint=_('check hostfingerprints or web.cacerts '
-                                     'config setting'))
-        else:
-            self.ui.warn(_('warning: %s certificate with fingerprint %s not '
-                           'verified (check hostfingerprints or web.cacerts '
-                           'config setting)\n') %
-                         (host, nicefingerprint))
+    if not peercert:
+        raise error.Abort(_('%s certificate error: '
+                           'no certificate received') % host)
+    peerfingerprint = util.sha1(peercert).hexdigest()
+    nicefingerprint = ":".join([peerfingerprint[x:x + 2]
+        for x in xrange(0, len(peerfingerprint), 2)])
+    if hostfingerprints:
+        fingerprintmatch = False
+        for hostfingerprint in hostfingerprints:
+            if peerfingerprint.lower() == \
+                    hostfingerprint.replace(':', '').lower():
+                fingerprintmatch = True
+                break
+        if not fingerprintmatch:
+            raise error.Abort(_('certificate for %s has unexpected '
+                               'fingerprint %s') % (host, nicefingerprint),
+                             hint=_('check hostfingerprint configuration'))
+        ui.debug('%s certificate matched fingerprint %s\n' %
+                 (host, nicefingerprint))
+    elif cacerts != '!':
+        msg = _verifycert(peercert2, host)
+        if msg:
+            raise error.Abort(_('%s certificate error: %s') % (host, msg),
+                             hint=_('configure hostfingerprint %s or use '
+                                    '--insecure to connect insecurely') %
+                                  nicefingerprint)
+        ui.debug('%s certificate successfully verified\n' % host)
+    elif strict:
+        raise error.Abort(_('%s certificate with fingerprint %s not '
+                           'verified') % (host, nicefingerprint),
+                         hint=_('check hostfingerprints or web.cacerts '
+                                 'config setting'))
+    else:
+        ui.warn(_('warning: %s certificate with fingerprint %s not '
+                  'verified (check hostfingerprints or web.cacerts '
+                  'config setting)\n') %
+                (host, nicefingerprint))


More information about the Mercurial-devel mailing list