Skip to content

Instantly share code, notes, and snippets.

@05nelsonm
Last active April 22, 2025 07:25
Show Gist options
  • Save 05nelsonm/8bc3fa33272fc596219a16b0eb2d217f to your computer and use it in GitHub Desktop.
Save 05nelsonm/8bc3fa33272fc596219a16b0eb2d217f to your computer and use it in GitHub Desktop.
WebViewProxyOverride

Class that uses the androidx.webkit library to override device WebView's proxy settings such that application with Tor bundled into it can connect to hidden services for serving html.

/*
 *  Copyright 2021 Matthew Nelson
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 * */
 
import android.annotation.SuppressLint
import androidx.webkit.ProxyConfig
import androidx.webkit.ProxyController
import androidx.webkit.WebViewFeature
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import java.util.concurrent.Executor

object WebViewProxyOverride {

    @Suppress("RemoveExplicitTypeArguments", "ObjectPropertyName")
    private val _proxyOverrideStateFlow: MutableStateFlow<ProxyOverrideState> by lazy {
        MutableStateFlow<ProxyOverrideState>(ProxyOverrideState.Uninitialized)
    }

    val proxyOverrideStateFlow: StateFlow<ProxyOverrideState>
        get() = _proxyOverrideStateFlow.asStateFlow()

    private class SynchronousExecutor: Executor {
        override fun execute(command: Runnable?) {
            command?.run()
        }
    }

    /**
     * Helper method for discerning if the functionality for overriding the WebView's
     * system proxy is supported for the device.
     *
     * @see [WebViewFeature.isFeatureSupported]
     * */
    fun isWebViewProxyOverrideSupported(): Boolean =
        WebViewFeature.isFeatureSupported(WebViewFeature.PROXY_OVERRIDE)

    @SuppressLint("RequiresFeature")
    fun setSocksProxy(
        socksHost: String,
        socksPort: Int,
        proxyConfigBuilder: ProxyConfig.Builder = ProxyConfig.Builder()
    ) {
        proxyConfigBuilder
            .addProxyRule("socks://${socksHost}:${socksPort}")
            .build().let { proxyConfig ->
                try {
                    ProxyController.getInstance().setProxyOverride(
                        proxyConfig,
                        SynchronousExecutor(),
                        {
                            _proxyOverrideStateFlow.value = ProxyOverrideState.ProxySet
                        }
                    )
                } catch (e: UnsupportedOperationException) {
                    _proxyOverrideStateFlow.value = ProxyOverrideState.Error.OverrideUnsupported(e)
                } catch (e: IllegalArgumentException) {
                    _proxyOverrideStateFlow.value = ProxyOverrideState.Error.InvalidConfig(e)
                }
            }
    }

    @SuppressLint("RequiresFeature")
    fun clearProxy() {
        if (
            _proxyOverrideStateFlow.value == ProxyOverrideState.ProxyCleared ||
            _proxyOverrideStateFlow.value == ProxyOverrideState.Uninitialized
        ) {
            return
        }

        try {
            ProxyController.getInstance().clearProxyOverride(
                SynchronousExecutor(),
                {
                    _proxyOverrideStateFlow.value = ProxyOverrideState.ProxyCleared
                }
            )
        } catch (e: UnsupportedOperationException) {
            _proxyOverrideStateFlow.value = ProxyOverrideState.Error.OverrideUnsupported(e)
        }
    }
}
@rdreasn
Copy link

rdreasn commented Apr 10, 2025

I've tried:
.addProxyRule("socks://127.0.0.1:9050")
but the WebView still doesn't connect to Tor network.

and I've started kmp-tor lib ofcourse:

Tor.enqueue(
    action = Action.StartDaemon,
    onFailure = OnFailure { throw it },
    onSuccess = onSuccess(),
)

Do I miss anything?

@05nelsonm
Copy link
Author

05nelsonm commented Apr 10, 2025

Probably need to wait for tor to bootstrap. Read kmp-tor documentation for Action.StartDaemon and RuntimeEvent.LISTENERS. Also, as documentation states, you should not throw exception in OnFailure callback as it will be caught and piped to RuntimeEvent.ERROR observer which, if absent, will crash (as it says in the documentation)

@rdreasn
Copy link

rdreasn commented Apr 16, 2025

Yes it works! Very useful library btw. Thanks a lot.

It turned out I have check the correct port (it's not 9050) and wait for tor bootstrap 100%.

RuntimeEvent.entries().forEach { event ->
    // ERROR observer **MUST** be present for
    // UncaughtException, otherwise may cause crash.
    if (event is RuntimeEvent.ERROR) {
        observerStatic(event, executor) { t ->
            // logs.add(event, t.stackTraceToString())
        }
    } else {
        // Just toString everything else...
        observerStatic(event, executor) { data ->
            // here I Just parse the data string to "detect" the sock's  port and the 
            // bootstrap 100%
            // ---> Is there a better way?
        }
    }
}

Would you mind showing a little snippet to do this in a more as-intended way?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment