Blame SOURCES/00295-fix-https-behind-proxy.patch

ae2451
diff --git a/Lib/httplib.py b/Lib/httplib.py
ae2451
index 592ee57..b69145b 100644
ae2451
--- a/Lib/httplib.py
ae2451
+++ b/Lib/httplib.py
ae2451
@@ -735,25 +735,40 @@ class HTTPConnection:
ae2451
         self._tunnel_host = None
ae2451
         self._tunnel_port = None
ae2451
         self._tunnel_headers = {}
ae2451
-
ae2451
-        self._set_hostport(host, port)
ae2451
         if strict is not None:
ae2451
             self.strict = strict
ae2451
 
ae2451
+        (self.host, self.port) = self._get_hostport(host, port)
ae2451
+
ae2451
+        # This is stored as an instance variable to allow unittests
ae2451
+        # to replace with a suitable mock
ae2451
+        self._create_connection = socket.create_connection
ae2451
+
ae2451
     def set_tunnel(self, host, port=None, headers=None):
ae2451
-        """ Sets up the host and the port for the HTTP CONNECT Tunnelling.
ae2451
+        """ Set up host and port for HTTP CONNECT tunnelling.
ae2451
+
ae2451
+        In a connection that uses HTTP Connect tunneling, the host passed to the
ae2451
+        constructor is used as proxy server that relays all communication to the
ae2451
+        endpoint passed to set_tunnel. This is done by sending a HTTP CONNECT
ae2451
+        request to the proxy server when the connection is established.
ae2451
+
ae2451
+        This method must be called before the HTTP connection has been
ae2451
+        established.
ae2451
 
ae2451
         The headers argument should be a mapping of extra HTTP headers
ae2451
         to send with the CONNECT request.
ae2451
         """
ae2451
-        self._tunnel_host = host
ae2451
-        self._tunnel_port = port
ae2451
+        # Verify if this is required.
ae2451
+        if self.sock:
ae2451
+            raise RuntimeError("Can't setup tunnel for established connection.")
ae2451
+
ae2451
+        self._tunnel_host, self._tunnel_port = self._get_hostport(host, port)
ae2451
         if headers:
ae2451
             self._tunnel_headers = headers
ae2451
         else:
ae2451
             self._tunnel_headers.clear()
ae2451
 
ae2451
-    def _set_hostport(self, host, port):
ae2451
+    def _get_hostport(self, host, port):
ae2451
         if port is None:
ae2451
             i = host.rfind(':')
ae2451
             j = host.rfind(']')         # ipv6 addresses have [...]
ae2451
@@ -770,15 +785,14 @@ class HTTPConnection:
ae2451
                 port = self.default_port
ae2451
             if host and host[0] == '[' and host[-1] == ']':
ae2451
                 host = host[1:-1]
ae2451
-        self.host = host
ae2451
-        self.port = port
ae2451
+        return (host, port)
ae2451
 
ae2451
     def set_debuglevel(self, level):
ae2451
         self.debuglevel = level
ae2451
 
ae2451
     def _tunnel(self):
ae2451
-        self._set_hostport(self._tunnel_host, self._tunnel_port)
ae2451
-        self.send("CONNECT %s:%d HTTP/1.0\r\n" % (self.host, self.port))
ae2451
+        self.send("CONNECT %s:%d HTTP/1.0\r\n" % (self._tunnel_host,
ae2451
+            self._tunnel_port))
ae2451
         for header, value in self._tunnel_headers.iteritems():
ae2451
             self.send("%s: %s\r\n" % (header, value))
ae2451
         self.send("\r\n")
ae2451
@@ -803,8 +817,8 @@ class HTTPConnection:
ae2451
 
ae2451
     def connect(self):
ae2451
         """Connect to the host and port specified in __init__."""
ae2451
-        self.sock = socket.create_connection((self.host,self.port),
ae2451
-                                             self.timeout, self.source_address)
ae2451
+        self.sock = self._create_connection((self.host,self.port),
ae2451
+                                           self.timeout, self.source_address)
ae2451
 
ae2451
         if self._tunnel_host:
ae2451
             self._tunnel()
ae2451
@@ -942,17 +956,24 @@ class HTTPConnection:
ae2451
                         netloc_enc = netloc.encode("idna")
ae2451
                     self.putheader('Host', netloc_enc)
ae2451
                 else:
ae2451
+                    if self._tunnel_host:
ae2451
+                        host = self._tunnel_host
ae2451
+                        port = self._tunnel_port
ae2451
+                    else:
ae2451
+                        host = self.host
ae2451
+                        port = self.port
ae2451
+
ae2451
                     try:
ae2451
-                        host_enc = self.host.encode("ascii")
ae2451
+                        host_enc = host.encode("ascii")
ae2451
                     except UnicodeEncodeError:
ae2451
-                        host_enc = self.host.encode("idna")
ae2451
+                        host_enc = host.encode("idna")
ae2451
                     # Wrap the IPv6 Host Header with [] (RFC 2732)
ae2451
                     if host_enc.find(':') >= 0:
ae2451
                         host_enc = "[" + host_enc + "]"
ae2451
-                    if self.port == self.default_port:
ae2451
+                    if port == self.default_port:
ae2451
                         self.putheader('Host', host_enc)
ae2451
                     else:
ae2451
-                        self.putheader('Host', "%s:%s" % (host_enc, self.port))
ae2451
+                        self.putheader('Host', "%s:%s" % (host_enc, port))
ae2451
 
ae2451
             # note: we are assuming that clients will not attempt to set these
ae2451
             #       headers since *this* library must deal with the
ae2451
@@ -1141,7 +1162,7 @@ class HTTP:
ae2451
         "Accept arguments to set the host/port, since the superclass doesn't."
ae2451
 
ae2451
         if host is not None:
ae2451
-            self._conn._set_hostport(host, port)
ae2451
+            (self._conn.host, self._conn.port) = self._conn._get_hostport(host, port)
ae2451
         self._conn.connect()
ae2451
 
ae2451
     def getfile(self):
ae2451
diff --git a/Lib/test/test_httplib.py b/Lib/test/test_httplib.py
ae2451
index 29af589..9db30cc 100644
ae2451
--- a/Lib/test/test_httplib.py
ae2451
+++ b/Lib/test/test_httplib.py
ae2451
@@ -21,10 +21,12 @@ CERT_selfsigned_pythontestdotnet = os.path.join(here, 'selfsigned_pythontestdotn
ae2451
 HOST = test_support.HOST
ae2451
 
ae2451
 class FakeSocket:
ae2451
-    def __init__(self, text, fileclass=StringIO.StringIO):
ae2451
+    def __init__(self, text, fileclass=StringIO.StringIO, host=None, port=None):
ae2451
         self.text = text
ae2451
         self.fileclass = fileclass
ae2451
         self.data = ''
ae2451
+        self.host = host
ae2451
+        self.port = port
ae2451
 
ae2451
     def sendall(self, data):
ae2451
         self.data += ''.join(data)
ae2451
@@ -34,6 +36,9 @@ class FakeSocket:
ae2451
             raise httplib.UnimplementedFileMode()
ae2451
         return self.fileclass(self.text)
ae2451
 
ae2451
+    def close(self):
ae2451
+        pass
ae2451
+
ae2451
 class EPipeSocket(FakeSocket):
ae2451
 
ae2451
     def __init__(self, text, pipe_trigger):
ae2451
@@ -487,7 +492,11 @@ class OfflineTest(TestCase):
ae2451
         self.assertEqual(httplib.responses[httplib.NOT_FOUND], "Not Found")
ae2451
 
ae2451
 
ae2451
-class SourceAddressTest(TestCase):
ae2451
+class TestServerMixin:
ae2451
+    """A limited socket server mixin.
ae2451
+
ae2451
+    This is used by test cases for testing http connection end points.
ae2451
+    """
ae2451
     def setUp(self):
ae2451
         self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ae2451
         self.port = test_support.bind_port(self.serv)
ae2451
@@ -502,6 +511,7 @@ class SourceAddressTest(TestCase):
ae2451
         self.serv.close()
ae2451
         self.serv = None
ae2451
 
ae2451
+class SourceAddressTest(TestServerMixin, TestCase):
ae2451
     def testHTTPConnectionSourceAddress(self):
ae2451
         self.conn = httplib.HTTPConnection(HOST, self.port,
ae2451
                 source_address=('', self.source_port))
ae2451
@@ -518,6 +528,24 @@ class SourceAddressTest(TestCase):
ae2451
         # for an ssl_wrapped connect() to actually return from.
ae2451
 
ae2451
 
ae2451
+class HTTPTest(TestServerMixin, TestCase):
ae2451
+    def testHTTPConnection(self):
ae2451
+        self.conn = httplib.HTTP(host=HOST, port=self.port, strict=None)
ae2451
+        self.conn.connect()
ae2451
+        self.assertEqual(self.conn._conn.host, HOST)
ae2451
+        self.assertEqual(self.conn._conn.port, self.port)
ae2451
+
ae2451
+    def testHTTPWithConnectHostPort(self):
ae2451
+        testhost = 'unreachable.test.domain'
ae2451
+        testport = '80'
ae2451
+        self.conn = httplib.HTTP(host=testhost, port=testport)
ae2451
+        self.conn.connect(host=HOST, port=self.port)
ae2451
+        self.assertNotEqual(self.conn._conn.host, testhost)
ae2451
+        self.assertNotEqual(self.conn._conn.port, testport)
ae2451
+        self.assertEqual(self.conn._conn.host, HOST)
ae2451
+        self.assertEqual(self.conn._conn.port, self.port)
ae2451
+
ae2451
+
ae2451
 class TimeoutTest(TestCase):
ae2451
     PORT = None
ae2451
 
ae2451
@@ -716,13 +744,54 @@ class HTTPSTest(TestCase):
ae2451
             c = httplib.HTTPSConnection(hp, context=context)
ae2451
             self.assertEqual(h, c.host)
ae2451
             self.assertEqual(p, c.port)
ae2451
- 
ae2451
+
ae2451
+class TunnelTests(TestCase):
ae2451
+    def test_connect(self):
ae2451
+        response_text = (
ae2451
+            'HTTP/1.0 200 OK\r\n\r\n'   # Reply to CONNECT
ae2451
+            'HTTP/1.1 200 OK\r\n'       # Reply to HEAD
ae2451
+            'Content-Length: 42\r\n\r\n'
ae2451
+        )
ae2451
+
ae2451
+        def create_connection(address, timeout=None, source_address=None):
ae2451
+            return FakeSocket(response_text, host=address[0], port=address[1])
ae2451
+
ae2451
+        conn = httplib.HTTPConnection('proxy.com')
ae2451
+        conn._create_connection = create_connection
ae2451
+
ae2451
+        # Once connected, we should not be able to tunnel anymore
ae2451
+        conn.connect()
ae2451
+        self.assertRaises(RuntimeError, conn.set_tunnel, 'destination.com')
ae2451
+
ae2451
+        # But if close the connection, we are good.
ae2451
+        conn.close()
ae2451
+        conn.set_tunnel('destination.com')
ae2451
+        conn.request('HEAD', '/', '')
ae2451
+
ae2451
+        self.assertEqual(conn.sock.host, 'proxy.com')
ae2451
+        self.assertEqual(conn.sock.port, 80)
ae2451
+        self.assertIn('CONNECT destination.com', conn.sock.data)
ae2451
+        # issue22095
ae2451
+        self.assertNotIn('Host: destination.com:None', conn.sock.data)
ae2451
+        # issue22095
ae2451
+
ae2451
+        self.assertNotIn('Host: proxy.com', conn.sock.data)
ae2451
+
ae2451
+        conn.close()
ae2451
+
ae2451
+        conn.request('PUT', '/', '')
ae2451
+        self.assertEqual(conn.sock.host, 'proxy.com')
ae2451
+        self.assertEqual(conn.sock.port, 80)
ae2451
+        self.assertTrue('CONNECT destination.com' in conn.sock.data)
ae2451
+        self.assertTrue('Host: destination.com' in conn.sock.data)
ae2451
+
ae2451
 
ae2451
 
ae2451
 @test_support.reap_threads
ae2451
 def test_main(verbose=None):
ae2451
     test_support.run_unittest(HeaderTests, OfflineTest, BasicTest, TimeoutTest,
ae2451
-                              HTTPSTest, SourceAddressTest)
ae2451
+                              HTTPTest, HTTPSTest, SourceAddressTest,
ae2451
+                               TunnelTests)
ae2451
 
ae2451
 if __name__ == '__main__':
ae2451
     test_main()