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