def __init__(self, cookie): """Initialize this tunnel instance.""" self.tunnels = [] self.cookie = cookie self.server = QTcpServer(QCoreApplication.instance()) self.server.newConnection.connect(self.new_connection) self.server.listen(QHostAddress.LocalHost, 0) logger.info("Starting tunnel server at port %d", self.port)
def headers_done(self): """An empty line was received, start connecting and switch mode.""" try: self.verify_cookie() try: logger.info("Connecting once") self.client = self.client_class(self) yield self.client.connect(self.hostport) except ProxyAuthenticationError: if not self.proxy_domain: logger.info("No proxy domain defined") raise credentials = yield Keyring().get_credentials(str(self.proxy_domain)) if "username" in credentials: self.proxy_credentials = credentials logger.info("Connecting again with keyring credentials") self.client = self.client_class(self) yield self.client.connect(self.hostport) logger.info("Connected with keyring credentials") response_headers = {"Server": "%s proxy tunnel" % NAME} self.write_transport( "HTTP/1.0 200 Proxy connection established" + CRLF + self.format_headers(response_headers) + CRLF ) except ConnectionError as e: logger.exception("Connection error") self.error_response(e.code, e.description) except Exception: logger.exception("Unhandled problem while connecting")
def check_proxy_enabled(host, port): """Check if the proxy is enabled.""" port = int(port) if sys.platform.startswith("linux"): settings = gsettings.get_proxy_settings() enabled = len(settings) > 0 if enabled: proxy = build_proxy(settings) QNetworkProxy.setApplicationProxy(proxy) else: logger.info("Proxy is disabled.") return enabled else: QNetworkProxyFactory.setUseSystemConfiguration(True) query = QNetworkProxyQuery(host, port) proxies = QNetworkProxyFactory.systemProxyForQuery(query) return len(proxies) and proxies[0].type() != QNetworkProxy.NoProxy
def proxy_auth_required(self, proxy, authenticator): """Proxy authentication is required.""" logger.info("auth_required %r, %r", proxy.hostName(), self.proxy_domain) if self.proxy_credentials and proxy.hostName() == self.proxy_domain: logger.info("Credentials added to authenticator.") authenticator.setUser(self.proxy_credentials["username"]) authenticator.setPassword(self.proxy_credentials["password"]) else: logger.info("Credentials needed, but none available.") self.proxy_domain = proxy.hostName()
def new_connection(self): """On a new connection create a new tunnel instance.""" logger.info("New connection made") local_socket = self.server.nextPendingConnection() tunnel = Tunnel(local_socket, self.cookie) self.tunnels.append(tunnel)