Set up host and port for HTTP CONNECT tunnelling. In a connection that uses HTTP CONNECT tunnelling, the host passed to the constructor is used as a proxy server that relays all communication to the endpoint passed to `set_tunnel`. This done by sending an HTTP CONNEC
(self, host, port=None, headers=None)
| 912 | self._create_connection = socket.create_connection |
| 913 | |
| 914 | def set_tunnel(self, host, port=None, headers=None): |
| 915 | """Set up host and port for HTTP CONNECT tunnelling. |
| 916 | |
| 917 | In a connection that uses HTTP CONNECT tunnelling, the host passed to |
| 918 | the constructor is used as a proxy server that relays all communication |
| 919 | to the endpoint passed to `set_tunnel`. This done by sending an HTTP |
| 920 | CONNECT request to the proxy server when the connection is established. |
| 921 | |
| 922 | This method must be called before the HTTP connection has been |
| 923 | established. |
| 924 | |
| 925 | The headers argument should be a mapping of extra HTTP headers to send |
| 926 | with the CONNECT request. |
| 927 | |
| 928 | As HTTP/1.1 is used for HTTP CONNECT tunnelling request, as per the RFC |
| 929 | (https://tools.ietf.org/html/rfc7231#section-4.3.6), a HTTP Host: |
| 930 | header must be provided, matching the authority-form of the request |
| 931 | target provided as the destination for the CONNECT request. If a |
| 932 | HTTP Host: header is not provided via the headers argument, one |
| 933 | is generated and transmitted automatically. |
| 934 | """ |
| 935 | |
| 936 | if self.sock: |
| 937 | raise RuntimeError("Can't set up tunnel for established connection") |
| 938 | |
| 939 | self._tunnel_host, self._tunnel_port = self._get_hostport(host, port) |
| 940 | if headers: |
| 941 | self._tunnel_headers = headers.copy() |
| 942 | else: |
| 943 | self._tunnel_headers.clear() |
| 944 | |
| 945 | if not any(header.lower() == "host" for header in self._tunnel_headers): |
| 946 | encoded_host = self._tunnel_host.encode("idna").decode("ascii") |
| 947 | self._tunnel_headers["Host"] = "%s:%d" % ( |
| 948 | encoded_host, self._tunnel_port) |
| 949 | |
| 950 | def _get_hostport(self, host, port): |
| 951 | if port is None: |