When downloading https resources with a self-signed certificate, handle python 2.7.9's API breakage

See #1402579 (Can't install calibre due "ssl.SSLError: [SSL] PEM lib (_ssl.c:2525)")
This commit is contained in:
Kovid Goyal 2014-12-15 22:45:02 +05:30
parent 6c7edef679
commit 4f6ca8d7d2
2 changed files with 9 additions and 5 deletions

View File

@ -19,6 +19,7 @@ py3 = sys.version_info[0] > 2
enc = getattr(sys.stdout, 'encoding', 'UTF-8') or 'utf-8' enc = getattr(sys.stdout, 'encoding', 'UTF-8') or 'utf-8'
calibre_version = signature = None calibre_version = signature = None
urllib = __import__('urllib.request' if py3 else 'urllib', fromlist=1) urllib = __import__('urllib.request' if py3 else 'urllib', fromlist=1)
has_ssl_verify = sys.version_info[:3] >= (2, 7, 9)
if py3: if py3:
unicode = str unicode = str
@ -467,7 +468,7 @@ def match_hostname(cert, hostname):
raise CertificateError("no appropriate commonName or " raise CertificateError("no appropriate commonName or "
"subjectAltName fields were found") "subjectAltName fields were found")
if py3: if has_ssl_verify:
class HTTPSConnection(httplib.HTTPSConnection): class HTTPSConnection(httplib.HTTPSConnection):
def __init__(self, ssl_version, *args, **kwargs): def __init__(self, ssl_version, *args, **kwargs):

View File

@ -6,11 +6,12 @@ from __future__ import (unicode_literals, division, absolute_import,
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>'
import ssl, socket, re import ssl, socket, re, sys
from contextlib import closing from contextlib import closing
from calibre import get_proxies from calibre import get_proxies
from calibre.constants import ispy3 from calibre.constants import ispy3
has_ssl_verify = sys.version_info[:3] >= (2, 7, 9)
class HTTPError(ValueError): class HTTPError(ValueError):
@ -24,6 +25,11 @@ class HTTPError(ValueError):
if ispy3: if ispy3:
from urllib.parse import urlparse from urllib.parse import urlparse
import http.client as httplib import http.client as httplib
else:
import httplib
from urlparse import urlsplit as urlparse
if has_ssl_verify:
class HTTPSConnection(httplib.HTTPSConnection): class HTTPSConnection(httplib.HTTPSConnection):
def __init__(self, ssl_version, *args, **kwargs): def __init__(self, ssl_version, *args, **kwargs):
@ -33,9 +39,6 @@ if ispy3:
context.verify_mode = ssl.CERT_REQUIRED context.verify_mode = ssl.CERT_REQUIRED
httplib.HTTPSConnection.__init__(self, *args, **kwargs) httplib.HTTPSConnection.__init__(self, *args, **kwargs)
else: else:
import httplib
from urlparse import urlsplit as urlparse
# Check certificate hostname {{{ # Check certificate hostname {{{
# Implementation taken from python 3 # Implementation taken from python 3
class CertificateError(ValueError): class CertificateError(ValueError):