* refactor go files, add headless telemost support

* js crap -> ts crap

* docker-build (#32)

Co-authored-by: Mimocro <suzumagefag@gmail.com>

* add headless telemost for creator app

* UX improvements (#39)

* Add search in split tunneling app list

* Add captcha detection

* Add autoclick settings

* headless vk joiner

* add headless telemost joiner

* refactor go modules

* redesign settings dialog

* headless option in settings

* headless joiner support in MainActivity

* display headless vk status in statusBar

* update ux for headless in creator app

* fix double log render for headless mode in creator

* unicode for cyrillic

* add socks auth

* put socksPort inf prefs, verify that port is free on start

* proxy only mode

* mask addresses in go network errors

* update docker build, add file write logic for headless

* increment release version, add make-release script

---------

Co-authored-by: kulikov <user@Mac.lan>
Co-authored-by: Mimocro <67226986+Mimocro@users.noreply.github.com>
Co-authored-by: Mimocro <suzumagefag@gmail.com>
Co-authored-by: senya <76913432+senya-sh@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2026-04-12 17:14:51 +02:00
1 parent c8e1ba444d
commit 029b536250
122 files changed
+9938 -3284

No files matched your search

@@ -2,13 +2,10 @@ package bypass.whitelist
import android.content.Intent
import android.content.pm.PackageManager
import android.net.ConnectivityManager
import android.net.VpnService
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import android.webkit.JavascriptInterface
import android.widget.Button
import android.widget.EditText
import android.widget.ImageButton
@@ -18,36 +15,29 @@ import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import bypass.whitelist.tunnel.CallPlatform
import bypass.whitelist.tunnel.RelayController
import bypass.whitelist.tunnel.TunnelMode
import bypass.whitelist.tunnel.ProxyService
import bypass.whitelist.tunnel.TunnelVpnService
import bypass.whitelist.tunnel.VpnStatus
import bypass.whitelist.ui.HeadlessTelemostFragment
import bypass.whitelist.ui.HeadlessVkFragment
import bypass.whitelist.ui.JoinFragmentHost
import bypass.whitelist.ui.JsHookJoinFragment
import bypass.whitelist.ui.LogViewController
import bypass.whitelist.ui.SettingsMenuController
import bypass.whitelist.ui.SettingsDialogFragment
import bypass.whitelist.ui.StatusBarController
import bypass.whitelist.ui.WebViewManager
import bypass.whitelist.util.LogWriter
import bypass.whitelist.util.Prefs
import bypass.whitelist.util.hideKeyboard
import bypass.whitelist.util.maskUrl
import java.net.Inet4Address
import java.net.InetAddress
class MainActivity : AppCompatActivity() {
class MainActivity : AppCompatActivity(), SettingsDialogFragment.Listener, JoinFragmentHost {
private val logWriter by lazy { LogWriter(cacheDir) }
private val relay by lazy {
RelayController(
nativeLibDir = applicationInfo.nativeLibraryDir,
onLog = { logCtrl.append(it) },
onStatus = ::onVpnStatus,
)
}
private lateinit var urlInput: EditText
private lateinit var logCtrl: LogViewController
private lateinit var statusCtrl: StatusBarController
private lateinit var settingsCtrl: SettingsMenuController
private lateinit var webViewMgr: WebViewManager
private lateinit var logContainer: View
private var previousUrl = ""
@@ -87,44 +77,21 @@ class MainActivity : AppCompatActivity() {
onDisconnect = ::fullReset,
)
settingsCtrl = SettingsMenuController(
activity = this,
onModeChanged = { mode ->
statusCtrl.tunnelMode = mode
webViewMgr.tunnelMode = mode
fullReset()
},
onShareLogs = { logCtrl.shareLogs() },
onReset = ::fullReset,
)
settingsCtrl.onShowLogsChanged = { visible ->
logContainer.visibility = if (visible) View.VISIBLE else View.GONE
}
webViewMgr = WebViewManager(
activity = this,
webView = findViewById(R.id.webView),
toggleButton = findViewById(R.id.toggleWebViewButton),
toggleArrow = findViewById(R.id.toggleWebViewArrow),
toggleLabel = findViewById(R.id.toggleWebViewLabel),
onLog = { logCtrl.append(it) },
onStatus = ::onVpnStatus,
)
webViewMgr.setup(JsBridge())
previousUrl = Prefs.lastUrl
urlInput.setText(previousUrl)
statusCtrl.tunnelMode = Prefs.tunnelMode
webViewMgr.tunnelMode = Prefs.tunnelMode
statusCtrl.setIdle()
logContainer.visibility = if (Prefs.showLogs) View.VISIBLE else View.GONE
findViewById<Button>(R.id.goButton).setOnClickListener { onGoPressed() }
findViewById<ImageButton>(R.id.shareLogsButton).setOnClickListener { logCtrl.shareLogs() }
findViewById<ImageButton>(R.id.gearButton).setOnClickListener { settingsCtrl.show(it) }
findViewById<ImageButton>(R.id.gearButton).setOnClickListener {
SettingsDialogFragment().show(supportFragmentManager, SettingsDialogFragment.TAG)
}
findViewById<View>(R.id.clearButton).setOnClickListener { urlInput.setText("") }
TunnelVpnService.onDisconnect = { runOnUiThread { resetState() } }
ProxyService.onDisconnect = { runOnUiThread { resetState() } }
VpnService.prepare(this)?.let { vpnPrepLauncher.launch(it) }
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
@@ -143,54 +110,96 @@ class MainActivity : AppCompatActivity() {
override fun onDestroy() {
TunnelVpnService.onDisconnect = null
relay.stop()
TunnelVpnService.instance?.stop()
ProxyService.onDisconnect = null
ProxyService.instance?.stop()
logCtrl.close()
super.onDestroy()
}
private fun onGoPressed() {
val url = urlInput.text.toString().trim()
if (url.isEmpty()) return
logCtrl.reset()
relay.stop()
relay.start(settingsCtrl.tunnelMode, CallPlatform.fromUrl(url))
hideKeyboard()
urlInput.clearFocus()
statusCtrl.setConnected(false)
statusCtrl.setStatus(VpnStatus.CONNECTING)
logCtrl.append("Loading: ${maskUrl(url)}")
if (previousUrl != url) {
previousUrl = url
Prefs.lastUrl = url
}
webViewMgr.loadUrl(url)
override fun onTunnelModeChanged(mode: TunnelMode) {
statusCtrl.tunnelMode = mode
fullReset()
}
private fun onVpnStatus(status: VpnStatus) {
if (!relay.isRunning) return
override fun onShowLogsChanged(visible: Boolean) {
logContainer.visibility = if (visible) View.VISIBLE else View.GONE
}
override fun onShareLogs() {
logCtrl.shareLogs()
}
override fun onReset() {
fullReset()
}
override fun appendLog(message: String) {
logCtrl.append(message)
}
override fun onJoinStatusText(text: String) {
runOnUiThread { statusCtrl.setStatusText(text) }
}
override fun onJoinStatus(status: VpnStatus) {
TunnelVpnService.instance?.updateStatus(status)
ProxyService.instance?.updateStatus(status)
runOnUiThread {
statusCtrl.setStatus(status)
if (status == VpnStatus.TUNNEL_ACTIVE) statusCtrl.setConnected(true)
}
}
private fun requestVpn() {
override fun requestVpn() {
if (Prefs.proxyOnly) {
logCtrl.append("Proxy only mode, skipping VPN")
startService(Intent(this, ProxyService::class.java))
onJoinStatus(VpnStatus.TUNNEL_ACTIVE)
return
}
val intent = VpnService.prepare(this)
if (intent != null) vpnLauncher.launch(intent) else startVpnService()
}
private fun onGoPressed() {
val url = urlInput.text.toString().trim()
if (url.isEmpty()) return
logCtrl.reset()
hideKeyboard()
urlInput.clearFocus()
statusCtrl.setConnected(false)
statusCtrl.setStatus(VpnStatus.CONNECTING)
logCtrl.append("Loading: ${maskUrl(url)}")
if (previousUrl != url) {
previousUrl = url
Prefs.lastUrl = url
}
val fragment = if (Prefs.headless) {
when (CallPlatform.fromUrl(url)) {
CallPlatform.VK -> HeadlessVkFragment.newInstance(url)
CallPlatform.TELEMOST -> HeadlessTelemostFragment.newInstance(url)
}
} else {
JsHookJoinFragment.newInstance(url)
}
supportFragmentManager.beginTransaction()
.replace(R.id.joinFragmentContainer, fragment)
.commit()
}
private fun startVpnService() {
startService(Intent(this, TunnelVpnService::class.java))
logCtrl.append("VPN started")
onVpnStatus(VpnStatus.TUNNEL_ACTIVE)
onJoinStatus(VpnStatus.TUNNEL_ACTIVE)
}
private fun resetState() {
relay.stop()
webViewMgr.loadBlank()
webViewMgr.collapse()
removeJoinFragment()
logCtrl.reset()
statusCtrl.setConnected(false)
statusCtrl.setIdle()
@@ -199,51 +208,15 @@ class MainActivity : AppCompatActivity() {
private fun fullReset() {
resetState()
TunnelVpnService.instance?.stop()
ProxyService.instance?.stop()
}
private fun getLocalIPAddress(): String {
try {
val cm = getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
val network = cm.activeNetwork ?: return ""
val props = cm.getLinkProperties(network) ?: return ""
for (addr in props.linkAddresses) {
val ip = addr.address
if (!ip.isLoopbackAddress && ip is Inet4Address) {
return ip.hostAddress ?: ""
}
}
} catch (e: Exception) {
Log.e("RELAY", "getLocalIPAddress error", e)
}
return ""
}
@Suppress("unused")
inner class JsBridge {
@JavascriptInterface
fun log(msg: String) = logCtrl.append(msg)
@JavascriptInterface
fun getLocalIP(): String = getLocalIPAddress()
@JavascriptInterface
fun resolveHost(hostname: String): String = try {
val all = InetAddress.getAllByName(hostname)
val v4 = all.firstOrNull { it is Inet4Address }
val addr = v4 ?: all.first()
val ip = addr.hostAddress ?: ""
Log.d("RELAY", "resolveHost: $hostname -> $ip (${addr.javaClass.simpleName}, ${all.size} addrs)")
ip
} catch (e: Exception) {
Log.d("RELAY", "resolveHost: $hostname -> FAILED: ${e.message}")
""
}
@JavascriptInterface
fun onTunnelReady() {
logCtrl.append("Tunnel ready, starting VPN...")
onVpnStatus(VpnStatus.TUNNEL_ACTIVE)
runOnUiThread { requestVpn() }
private fun removeJoinFragment() {
val fragment = supportFragmentManager.findFragmentById(R.id.joinFragmentContainer)
if (fragment != null) {
supportFragmentManager.beginTransaction()
.remove(fragment)
.commitNowAllowingStateLoss()
}
}
@@ -0,0 +1,129 @@
package bypass.whitelist.tunnel
import android.util.Log
import bypass.whitelist.util.ParamCallback
import bypass.whitelist.util.Ports
import bypass.whitelist.util.Prefs
import bypass.whitelist.util.SocksAuth
import java.io.BufferedWriter
import java.io.File
import java.io.OutputStreamWriter
import java.net.Inet4Address
import java.net.InetAddress
class HeadlessRelayController(
private val nativeLibDir: String,
private val relayMode: String = "vk-headless-joiner",
private val onLog: ParamCallback<String>,
private val onStatus: ParamCallback<VpnStatus>,
) {
private var process: Process? = null
private var thread: Thread? = null
private var stdinWriter: BufferedWriter? = null
@Volatile
var isRunning = false
private set
fun start() {
stop()
isRunning = true
val relayBin = File(nativeLibDir, "librelay.so")
if (!relayBin.exists()) {
onLog("Relay binary not found")
return
}
thread = Thread {
val socksPort = Prefs.socksPort
if (!PortGuard.ensurePortFree(socksPort)) {
onLog("SOCKS5 port $socksPort is busy and could not be freed")
onStatus(VpnStatus.PORT_BUSY)
isRunning = false
return@Thread
}
try {
val processBuilder = ProcessBuilder(
relayBin.absolutePath,
"--mode", relayMode,
"--ws-port", "${Ports.PION_SIGNALING}",
"--socks-port", "${Prefs.socksPort}",
"--socks-user", SocksAuth.user,
"--socks-pass", SocksAuth.pass
)
processBuilder.redirectErrorStream(true)
val proc = processBuilder.start()
synchronized(this) {
process = proc
stdinWriter = BufferedWriter(OutputStreamWriter(proc.outputStream))
}
onLog("Headless relay started (signaling :${Ports.PION_SIGNALING}, SOCKS5 ${SocksAuth.user}:${SocksAuth.pass}@127.0.0.1:${Prefs.socksPort})")
proc.inputStream.bufferedReader().forEachLine { line ->
if (line.startsWith("RESOLVE:")) {
val hostname = line.removePrefix("RESOLVE:")
try {
val all = InetAddress.getAllByName(hostname)
val address = all.firstOrNull { it is Inet4Address } ?: all.first()
val resolvedIP = address.hostAddress ?: ""
Log.d("RELAY", "Resolved $hostname -> $resolvedIP")
writeStdin(resolvedIP)
} catch (e: Exception) {
Log.e("RELAY", "DNS resolve failed for $hostname", e)
writeStdin("")
}
} else if (line.startsWith("STATUS:")) {
val status = line.removePrefix("STATUS:")
Log.d("RELAY", "status: $status")
when {
status == "READY" -> onStatus(VpnStatus.STARTING)
status == "CONNECTING" -> onStatus(VpnStatus.CONNECTING)
status == "TUNNEL_CONNECTED" -> onStatus(VpnStatus.TUNNEL_ACTIVE)
status == "TUNNEL_LOST" -> onStatus(VpnStatus.TUNNEL_LOST)
status.startsWith("ERROR:") -> onStatus(VpnStatus.CALL_FAILED)
}
} else {
Log.d("RELAY", line)
onLog(line)
}
}
proc.waitFor()
Log.d("RELAY", "Headless relay exited: ${proc.exitValue()}")
} catch (e: Exception) {
if (isRunning) {
Log.e("RELAY", "Headless relay error", e)
onLog("Relay error: ${e.message}")
}
}
}.also { it.start() }
}
fun sendJoinParams(joinJson: String) {
writeStdin("JOIN:$joinJson")
}
@Synchronized
fun stop() {
isRunning = false
process?.let {
it.destroy()
it.waitFor()
}
process = null
stdinWriter = null
thread?.interrupt()
thread = null
}
@Synchronized
private fun writeStdin(line: String) {
try {
stdinWriter?.write(line)
stdinWriter?.newLine()
stdinWriter?.flush()
} catch (e: Exception) {
Log.e("RELAY", "writeStdin error: ${e.message}")
}
}
}
@@ -0,0 +1,99 @@
package bypass.whitelist.tunnel
import android.os.Process
import android.util.Log
import java.io.File
import java.net.InetAddress
import java.net.ServerSocket
object PortGuard {
private const val TAG = "PortGuard"
fun ensurePortFree(port: Long): Boolean {
if (tryBind(port)) return true
Log.w(TAG, "Port $port is busy, killing occupying process")
killByPort(port)
for (attempt in 1..20) {
Thread.sleep(100)
if (tryBind(port)) {
Log.i(TAG, "Port $port freed after kill (attempt $attempt)")
return true
}
}
Log.e(TAG, "Port $port still busy after kill attempt")
return false
}
private fun tryBind(port: Long): Boolean {
return try {
ServerSocket(port.toInt(), 1, InetAddress.getByName("127.0.0.1")).use { true }
} catch (e: Exception) {
false
}
}
private fun killByPort(port: Long) {
try {
val hexPort = String.format("%04X", port)
val tcp = File("/proc/net/tcp")
if (!tcp.canRead()) {
Log.w(TAG, "Cannot read /proc/net/tcp")
return
}
val inodes = mutableSetOf<String>()
tcp.forEachLine { line ->
val fields = line.trim().split("\\s+".toRegex())
if (fields.size >= 10) {
val localPort = fields[1].substringAfter(":")
if (localPort.equals(hexPort, ignoreCase = true)) {
inodes.add(fields[9])
}
}
}
if (inodes.isEmpty()) {
Log.w(TAG, "No inode found for port $port")
return
}
val myPid = Process.myPid()
val procDir = File("/proc")
for (entry in procDir.listFiles() ?: emptyArray()) {
val pid = entry.name.toIntOrNull() ?: continue
if (pid == myPid) continue
val fdDir = File(entry, "fd")
if (!fdDir.canRead()) continue
for (fd in fdDir.listFiles() ?: emptyArray()) {
try {
val target = fd.canonicalPath
for (inode in inodes) {
if (target.contains("socket:[$inode]")) {
Log.w(TAG, "Killing PID $pid holding port $port (inode $inode)")
Process.killProcess(pid)
return
}
}
} catch (ignored: Exception) {
}
}
}
Log.w(TAG, "Could not find PID for port $port via /proc, trying fuser")
try {
val fuser = Runtime.getRuntime().exec(arrayOf("fuser", "$port/tcp"))
val output = fuser.inputStream.bufferedReader().readText().trim()
fuser.waitFor()
for (token in output.split("\\s+".toRegex())) {
val pid = token.toIntOrNull() ?: continue
if (pid != myPid) {
Log.w(TAG, "fuser: killing PID $pid for port $port")
Process.killProcess(pid)
return
}
}
} catch (e: Exception) {
Log.w(TAG, "fuser fallback failed: ${e.message}")
}
} catch (e: Exception) {
Log.e(TAG, "killByPort error: ${e.message}")
}
}
}
@@ -0,0 +1,107 @@
package bypass.whitelist.tunnel
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.os.Build
import android.os.IBinder
import bypass.whitelist.MainActivity
import bypass.whitelist.util.Callback
import bypass.whitelist.R
class ProxyService : Service() {
companion object {
const val CHANNEL_ID = "proxy_channel"
const val NOTIFICATION_ID = 2
const val ACTION_STOP = "bypass.whitelist.STOP_PROXY"
@Volatile var instance: ProxyService? = null
@Volatile var onDisconnect: Callback? = null
}
@Volatile var isRunning = false
private set
override fun onBind(intent: Intent?): IBinder? = null
override fun onCreate() {
super.onCreate()
instance = this
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent?.action == ACTION_STOP) {
stop()
return START_NOT_STICKY
}
start()
return START_STICKY
}
override fun onDestroy() {
stop()
super.onDestroy()
}
fun updateStatus(status: VpnStatus) {
val nm = getSystemService(NotificationManager::class.java)
nm.notify(NOTIFICATION_ID, buildNotification(getString(status.labelRes)))
}
@Synchronized
fun stop() {
if (!isRunning) return
isRunning = false
@Suppress("DEPRECATION")
stopForeground(true)
stopSelf()
onDisconnect?.invoke()
}
private fun start() {
if (isRunning) return
isRunning = true
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
CHANNEL_ID, "Proxy Tunnel", NotificationManager.IMPORTANCE_LOW
)
val nm = getSystemService(NotificationManager::class.java)
nm.createNotificationChannel(channel)
}
startForeground(NOTIFICATION_ID, buildNotification(getString(R.string.notification_proxy_title)))
}
private fun buildNotification(text: String): Notification {
val openIntent = Intent(this, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP
}
val openPending = PendingIntent.getActivity(
this, 1, openIntent, PendingIntent.FLAG_IMMUTABLE
)
val stopIntent = Intent(this, ProxyService::class.java).apply {
action = ACTION_STOP
}
val stopPending = PendingIntent.getService(
this, 0, stopIntent, PendingIntent.FLAG_IMMUTABLE
)
@Suppress("DEPRECATION")
val builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Notification.Builder(this, CHANNEL_ID)
} else {
Notification.Builder(this)
}
return builder
.setContentTitle(getString(R.string.notification_proxy_title))
.setContentText(text)
.setSmallIcon(android.R.drawable.ic_lock_lock)
.setOngoing(true)
.setContentIntent(openPending)
.addAction(Notification.Action.Builder(null, getString(R.string.notification_disconnect), stopPending).build())
.build()
}
}
@@ -1,15 +1,22 @@
package bypass.whitelist.tunnel
import android.util.Log
import bypass.whitelist.util.ParamCallback
import bypass.whitelist.util.Ports
import bypass.whitelist.util.Prefs
import bypass.whitelist.util.SocksAuth
import mobile.LogCallback
import mobile.Mobile
import java.io.BufferedWriter
import java.io.File
import java.io.OutputStreamWriter
import java.net.Inet4Address
import java.net.InetAddress
class RelayController(
private val nativeLibDir: String,
private val onLog: (String) -> Unit,
private val onStatus: (VpnStatus) -> Unit,
private val onLog: ParamCallback<String>,
private val onStatus: ParamCallback<VpnStatus>,
) {
private var dcThread: Thread? = null
private var pionThread: Thread? = null
@@ -50,13 +57,14 @@ class RelayController(
else if (msg.contains("ws read error")) onStatus(VpnStatus.TUNNEL_LOST)
}
dcThread = Thread {
if (!checkPortOrAbort()) return@Thread
try {
Mobile.startJoiner(Ports.DC_WS, Ports.SOCKS, cb)
Mobile.startJoiner(Ports.DC_WS, Prefs.socksPort, SocksAuth.user, SocksAuth.pass, cb)
} catch (e: Exception) {
if (isRunning) onLog("Relay error: ${e.message}")
}
}.also { it.start() }
onLog("Relay started DC mode (SOCKS5 :${Ports.SOCKS}, WS :${Ports.DC_WS})")
onLog("Relay started DC mode (SOCKS5 ${SocksAuth.user}:${SocksAuth.pass}@127.0.0.1:${Prefs.socksPort}, WS :${Ports.DC_WS})")
}
private fun startPion(mode: TunnelMode, platform: CallPlatform) {
@@ -67,22 +75,44 @@ class RelayController(
}
val relayMode = mode.relayMode(platform)
pionThread = Thread {
if (!checkPortOrAbort()) return@Thread
try {
val pb = ProcessBuilder(
relayBin.absolutePath,
"--mode", relayMode,
"--ws-port", "${Ports.PION_SIGNALING}",
"--socks-port", "${Ports.SOCKS}"
"--socks-port", "${Prefs.socksPort}",
"--socks-user", SocksAuth.user,
"--socks-pass", SocksAuth.pass
)
pb.redirectErrorStream(true)
val proc = pb.start()
synchronized(this) { pionProcess = proc }
onLog("Pion relay started mode=$relayMode (signaling :${Ports.PION_SIGNALING}, SOCKS5 :${Ports.SOCKS})")
onLog("Pion relay started mode=$relayMode (signaling :${Ports.PION_SIGNALING}, SOCKS5 ${SocksAuth.user}:${SocksAuth.pass}@127.0.0.1:${Prefs.socksPort})")
val stdinWriter = BufferedWriter(OutputStreamWriter(proc.outputStream))
proc.inputStream.bufferedReader().forEachLine { line ->
Log.d("RELAY", line)
onLog(line)
if (line.contains("CONNECTED")) onStatus(VpnStatus.TUNNEL_ACTIVE)
else if (line.contains("session cleaned up")) onStatus(VpnStatus.TUNNEL_LOST)
if (line.startsWith("RESOLVE:")) {
val hostname = line.removePrefix("RESOLVE:")
try {
val all = InetAddress.getAllByName(hostname)
val address = all.firstOrNull { it is Inet4Address } ?: all.first()
val resolvedIP = address.hostAddress ?: ""
Log.d("RELAY", "Resolved $hostname -> $resolvedIP")
stdinWriter.write(resolvedIP)
stdinWriter.newLine()
stdinWriter.flush()
} catch (e: Exception) {
Log.e("RELAY", "DNS resolve failed for $hostname", e)
stdinWriter.write("")
stdinWriter.newLine()
stdinWriter.flush()
}
} else {
Log.d("RELAY", line)
onLog(line)
if (line.contains("CONNECTED")) onStatus(VpnStatus.TUNNEL_ACTIVE)
else if (line.contains("session cleaned up")) onStatus(VpnStatus.TUNNEL_LOST)
}
}
onLog("Pion relay exited: ${proc.exitValue()}")
} catch (e: Exception) {
@@ -93,4 +123,13 @@ class RelayController(
}
}.also { it.start() }
}
private fun checkPortOrAbort(): Boolean {
val socksPort = Prefs.socksPort
if (PortGuard.ensurePortFree(socksPort)) return true
onLog("SOCKS5 port $socksPort is busy and could not be freed")
onStatus(VpnStatus.PORT_BUSY)
isRunning = false
return false
}
}
@@ -5,13 +5,16 @@ import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Intent
import android.net.ConnectivityManager
import android.net.VpnService
import android.os.Build
import android.os.ParcelFileDescriptor
import android.util.Log
import bypass.whitelist.MainActivity
import bypass.whitelist.util.Ports
import bypass.whitelist.R
import bypass.whitelist.util.Callback
import bypass.whitelist.util.Prefs
import bypass.whitelist.util.SocksAuth
import bypass.whitelist.util.Vpn
import mobile.Mobile
@@ -22,11 +25,11 @@ class TunnelVpnService : VpnService() {
const val CHANNEL_ID = "vpn_channel"
const val NOTIFICATION_ID = 1
const val ACTION_STOP = "bypass.whitelist.STOP_VPN"
var instance: TunnelVpnService? = null
var onDisconnect: (() -> Unit)? = null
@Volatile var instance: TunnelVpnService? = null
@Volatile var onDisconnect: Callback? = null
}
var isRunning: Boolean = false
@Volatile var isRunning: Boolean = false
private var vpnFd: ParcelFileDescriptor? = null
private var tun2socksThread: Thread? = null
@@ -54,6 +57,7 @@ class TunnelVpnService : VpnService() {
nm.notify(NOTIFICATION_ID, buildNotification(getString(status.labelRes)))
}
@Synchronized
fun stop() {
if (!isRunning) return
isRunning = false
@@ -80,10 +84,16 @@ class TunnelVpnService : VpnService() {
.setSession(Vpn.SESSION_NAME)
.addAddress(Vpn.ADDRESS, Vpn.PREFIX_LENGTH)
.addRoute(Vpn.ROUTE, 0)
.addDnsServer(Vpn.DNS_PRIMARY)
.addDnsServer(Vpn.DNS_SECONDARY)
.setMtu(Vpn.MTU)
val systemDns = getSystemDnsServers()
if (systemDns.isNotEmpty()) {
for (dns in systemDns) builder.addDnsServer(dns)
} else {
builder.addDnsServer(Vpn.DNS_PRIMARY)
builder.addDnsServer(Vpn.DNS_SECONDARY)
}
try {
when (Prefs.splitTunnelingMode) {
SplitTunnelingMode.NONE -> {
@@ -120,12 +130,12 @@ class TunnelVpnService : VpnService() {
isRunning = true
val fd = vpnFd!!.detachFd()
vpnFd = null
Log.i(TAG, "VPN established, fd=$fd")
Log.i(TAG, "VPN established, fd=$fd, SOCKS5 ${SocksAuth.user}:${SocksAuth.pass}@127.0.0.1:${Prefs.socksPort}")
updateStatus(VpnStatus.TUNNEL_ACTIVE)
tun2socksThread = Thread {
try {
Mobile.startTun2Socks(fd.toLong(), Vpn.MTU.toLong(), Ports.SOCKS)
Mobile.startTun2Socks(fd.toLong(), Vpn.MTU.toLong(), Prefs.socksPort, SocksAuth.user, SocksAuth.pass)
} catch (e: Exception) {
Log.e(TAG, "tun2socks error: ${e.message}")
isRunning = false
@@ -133,6 +143,13 @@ class TunnelVpnService : VpnService() {
}.also { it.start() }
}
private fun getSystemDnsServers(): List<String> {
val connectivityManager = getSystemService(ConnectivityManager::class.java) ?: return emptyList()
val network = connectivityManager.activeNetwork ?: return emptyList()
val linkProperties = connectivityManager.getLinkProperties(network) ?: return emptyList()
return linkProperties.dnsServers.mapNotNull { it.hostAddress }
}
private fun startForegroundNotification() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
@@ -165,12 +182,12 @@ class TunnelVpnService : VpnService() {
Notification.Builder(this)
}
return builder
.setContentTitle("VPN active")
.setContentTitle(getString(R.string.notification_vpn_title))
.setContentText(text)
.setSmallIcon(android.R.drawable.ic_lock_lock)
.setOngoing(true)
.setContentIntent(openPending)
.addAction(Notification.Action.Builder(null, "Disconnect", stopPending).build())
.addAction(Notification.Action.Builder(null, getString(R.string.notification_disconnect), stopPending).build())
.build()
}
}
@@ -12,5 +12,7 @@ enum class VpnStatus(@StringRes val labelRes: Int) {
TUNNEL_ACTIVE(R.string.vpn_tunnel_active),
TUNNEL_LOST(R.string.vpn_tunnel_lost),
CALL_DISCONNECTED(R.string.vpn_call_disconnected),
CALL_FAILED(R.string.vpn_call_failed)
CALL_FAILED(R.string.vpn_call_failed),
PORT_BUSY(R.string.vpn_port_busy),
ACTION_REQUIRED_CAPTCHA(R.string.action_required_captcha)
}
@@ -0,0 +1,73 @@
package bypass.whitelist.ui
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import bypass.whitelist.R
import bypass.whitelist.tunnel.HeadlessRelayController
import bypass.whitelist.tunnel.VpnStatus
import bypass.whitelist.util.Prefs
import org.json.JSONObject
class HeadlessTelemostFragment : Fragment() {
private lateinit var relay: HeadlessRelayController
private val host: JoinFragmentHost?
get() = activity as? JoinFragmentHost
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View = inflater.inflate(R.layout.fragment_headless_telemost, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val joinLink = requireArguments().getString(ARG_URL, "")
val displayName = Prefs.autoclickName
val tunnelMode = Prefs.tunnelMode.relayArg
relay = HeadlessRelayController(
requireContext().applicationInfo.nativeLibraryDir,
relayMode = "telemost-headless-joiner",
onLog = { host?.appendLog(it) },
onStatus = { status ->
Log.d("TM-HEADLESS", "status: $status")
host?.onJoinStatus(status)
when (status) {
VpnStatus.STARTING -> {
val params = JSONObject().apply {
put("joinLink", joinLink)
put("displayName", displayName)
put("tunnelMode", tunnelMode)
}
relay.sendJoinParams(params.toString())
}
VpnStatus.TUNNEL_ACTIVE -> activity?.runOnUiThread { host?.requestVpn() }
else -> {}
}
},
)
relay.start()
}
override fun onDestroyView() {
if (::relay.isInitialized) relay.stop()
super.onDestroyView()
}
companion object {
const val ARG_URL = "url"
fun newInstance(url: String): HeadlessTelemostFragment {
return HeadlessTelemostFragment().apply {
arguments = Bundle().apply {
putString(ARG_URL, url)
}
}
}
}
}
@@ -0,0 +1,89 @@
package bypass.whitelist.ui
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import bypass.whitelist.R
import bypass.whitelist.util.BLANK_URL
import bypass.whitelist.tunnel.HeadlessRelayController
import bypass.whitelist.tunnel.VpnStatus
import bypass.whitelist.util.Prefs
import org.json.JSONObject
class HeadlessVkFragment : Fragment() {
private lateinit var relay: HeadlessRelayController
private lateinit var captchaView: VkCaptchaWebView
private lateinit var webView: WebView
private val host: JoinFragmentHost?
get() = activity as? JoinFragmentHost
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View = inflater.inflate(R.layout.fragment_headless_vk, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
webView = view.findViewById(R.id.captchaWebView)
val url = requireArguments().getString(ARG_URL, "")
val displayName = Prefs.autoclickName
relay = HeadlessRelayController(
requireContext().applicationInfo.nativeLibraryDir,
onLog = { message ->
if (message.contains("ERROR:")) {
host?.onJoinStatusText(message)
}
host?.appendLog(message)
},
onStatus = { status ->
Log.d("HEADLESS-VK", "status: $status")
host?.onJoinStatus(status)
if (status == VpnStatus.TUNNEL_ACTIVE) {
activity?.runOnUiThread { host?.requestVpn() }
}
},
)
relay.start()
captchaView = VkCaptchaWebView(
requireActivity() as AppCompatActivity,
webView,
onStatus = { message -> host?.onJoinStatusText(message) },
) { joinJson ->
Log.d("HEADLESS-VK", "Auth complete, sending join params to relay")
val params = JSONObject(joinJson)
params.put("tunnelMode", Prefs.tunnelMode.relayArg)
relay.sendJoinParams(params.toString())
}
captchaView.setup()
captchaView.start(url, displayName)
}
override fun onDestroyView() {
webView.stopLoading()
webView.loadUrl(BLANK_URL)
webView.destroy()
relay.stop()
super.onDestroyView()
}
companion object {
const val ARG_URL = "url"
fun newInstance(url: String): HeadlessVkFragment {
return HeadlessVkFragment().apply {
arguments = Bundle().apply {
putString(ARG_URL, url)
}
}
}
}
}
@@ -0,0 +1,10 @@
package bypass.whitelist.ui
import bypass.whitelist.tunnel.VpnStatus
interface JoinFragmentHost {
fun appendLog(message: String)
fun onJoinStatus(status: VpnStatus)
fun onJoinStatusText(text: String)
fun requestVpn()
}
@@ -0,0 +1,296 @@
package bypass.whitelist.ui
import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.net.ConnectivityManager
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.ConsoleMessage
import android.webkit.JavascriptInterface
import android.webkit.PermissionRequest
import android.webkit.WebChromeClient
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
import bypass.whitelist.R
import bypass.whitelist.tunnel.CallPlatform
import bypass.whitelist.tunnel.RelayController
import bypass.whitelist.tunnel.TunnelMode
import bypass.whitelist.tunnel.VpnStatus
import bypass.whitelist.util.BLANK_URL
import bypass.whitelist.util.Ports
import bypass.whitelist.util.DESKTOP_USER_AGENT
import bypass.whitelist.util.Prefs
import bypass.whitelist.util.maskUrl
import java.net.HttpURLConnection
import java.net.Inet4Address
import java.net.InetAddress
import java.net.URL
private data class HookKey(val isPion: Boolean, val platform: CallPlatform)
class JsHookJoinFragment : Fragment() {
private lateinit var webView: WebView
private lateinit var toggleButton: View
private lateinit var toggleArrow: ImageView
private lateinit var toggleLabel: TextView
private lateinit var relay: RelayController
private var expanded = false
private var callUrl = ""
private val host: JoinFragmentHost?
get() = activity as? JoinFragmentHost
private val tunnelMode: TunnelMode
get() = Prefs.tunnelMode
private val hooks = mapOf(
HookKey(false, CallPlatform.VK) to lazy { loadAsset("dc-joiner-vk.js") },
HookKey(false, CallPlatform.TELEMOST) to lazy { loadAsset("dc-joiner-telemost.js") },
HookKey(true, CallPlatform.VK) to lazy { loadAsset("video-vk.js") },
HookKey(true, CallPlatform.TELEMOST) to lazy { loadAsset("video-telemost.js") },
)
private val autoclickers = mapOf(
CallPlatform.VK to lazy { loadAsset("autoclick-vk.js") },
CallPlatform.TELEMOST to lazy { loadAsset("autoclick-telemost.js") },
)
private val muteAudioContext by lazy { loadAsset("mute-audio-context.js") }
private fun loadAsset(name: String): String =
requireContext().assets.open(name).bufferedReader().readText()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View = inflater.inflate(R.layout.fragment_jshook_join, container, false)
@SuppressLint("SetJavaScriptEnabled")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
webView = view.findViewById(R.id.webView)
toggleButton = view.findViewById(R.id.toggleWebViewButton)
toggleArrow = view.findViewById(R.id.toggleWebViewArrow)
toggleLabel = view.findViewById(R.id.toggleWebViewLabel)
relay = RelayController(
nativeLibDir = requireContext().applicationInfo.nativeLibraryDir,
onLog = { host?.appendLog(it) },
onStatus = { status ->
if (!relay.isRunning) return@RelayController
host?.onJoinStatus(status)
},
)
val platform = CallPlatform.fromUrl(requireArguments().getString(ARG_URL, ""))
relay.start(tunnelMode, platform)
toggleButton.setOnClickListener { setExpanded(!expanded) }
webView.settings.apply {
javaScriptEnabled = true
domStorageEnabled = true
mediaPlaybackRequiresUserGesture = false
allowContentAccess = true
allowFileAccess = true
databaseEnabled = true
setSupportMultipleWindows(false)
useWideViewPort = true
loadWithOverviewMode = true
builtInZoomControls = true
displayZoomControls = false
userAgentString = DESKTOP_USER_AGENT
}
webView.addJavascriptInterface(JsBridge(), "AndroidBridge")
webView.webChromeClient = object : WebChromeClient() {
override fun onPermissionRequest(request: PermissionRequest) {
activity?.runOnUiThread { request.grant(request.resources) }
}
override fun onConsoleMessage(msg: ConsoleMessage): Boolean {
val text = msg.message()
Log.d("HOOK", text)
if (text.contains("[HOOK]")) {
host?.appendLog(text)
when {
text.contains("CALL CONNECTED") -> host?.onJoinStatus(VpnStatus.CALL_CONNECTED)
text.contains("DataChannel open") -> host?.onJoinStatus(VpnStatus.DATACHANNEL_OPEN)
text.contains("DataChannel closed") -> host?.onJoinStatus(VpnStatus.DATACHANNEL_LOST)
text.contains("WebSocket connected") -> host?.onJoinStatus(VpnStatus.TUNNEL_ACTIVE)
text.contains("WebSocket disconnected") -> host?.onJoinStatus(VpnStatus.TUNNEL_LOST)
text.contains("Connection state: connecting") -> host?.onJoinStatus(VpnStatus.CONNECTING)
text.contains("Connection state: disconnected") -> host?.onJoinStatus(VpnStatus.CALL_DISCONNECTED)
text.contains("Connection state: failed") -> host?.onJoinStatus(VpnStatus.CALL_FAILED)
}
}
return true
}
}
webView.webViewClient = object : WebViewClient() {
override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? {
val url = request.url.toString()
val platform = CallPlatform.fromUrl(url)
if (platform != CallPlatform.TELEMOST || !url.contains("/j/") || request.method != "GET") return null
return stripCsp(url, request)
}
override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
if (url.contains(BLANK_URL)) return
view.evaluateJavascript(muteAudioContext, null)
}
override fun onPageFinished(view: WebView, url: String) {
if (url.contains(BLANK_URL)) return
if (!expanded && url != callUrl) activity?.runOnUiThread { setExpanded(true) }
view.evaluateJavascript("!!window.__hookInstalled") { result ->
if (result == "true") {
Log.d("HOOK", "Hook already injected, skipping")
return@evaluateJavascript
}
val platform = CallPlatform.fromUrl(url)
host?.appendLog("Page loaded, injecting hook for ${maskUrl(url)}")
view.evaluateJavascript("window.WS_PORT=${mobile.Mobile.activeWsPort()}", null)
view.evaluateJavascript("window.PION_PORT=${Ports.PION_SIGNALING}", null)
view.evaluateJavascript(hookForPlatform(platform), null)
if (Prefs.autoclickEnabled) {
host?.appendLog("Injecting autoclick for ${maskUrl(url)}")
view.evaluateJavascript("window.autofillName='${Prefs.autoclickName}'", null)
view.evaluateJavascript(autoclickers[platform]!!.value, null)
}
}
}
}
val url = requireArguments().getString(ARG_URL, "")
if (url.isNotEmpty()) {
callUrl = url
webView.loadUrl(url)
}
}
override fun onDestroyView() {
webView.stopLoading()
webView.loadUrl(BLANK_URL)
webView.destroy()
relay.stop()
super.onDestroyView()
}
fun expand() {
setExpanded(true)
}
private fun setExpanded(value: Boolean) {
expanded = value
webView.visibility = if (value) View.VISIBLE else View.GONE
toggleArrow.rotation = if (value) 180f else 0f
toggleLabel.setText(if (value) R.string.collapse_webview else R.string.expand_webview)
}
private fun hookForPlatform(platform: CallPlatform): String =
hooks[HookKey(tunnelMode.isPion, platform)]!!.value
private fun stripCsp(url: String, request: WebResourceRequest): WebResourceResponse? {
return try {
val conn = URL(url).openConnection() as HttpURLConnection
conn.requestMethod = "GET"
request.requestHeaders?.forEach { (key, value) -> conn.setRequestProperty(key, value) }
val headers = mutableMapOf<String, String>()
conn.headerFields?.forEach { (key, values) ->
if (key != null
&& !key.equals("content-security-policy", ignoreCase = true)
&& !key.equals("content-security-policy-report-only", ignoreCase = true)
) {
headers[key] = values.joinToString(", ")
}
}
WebResourceResponse(
conn.contentType?.split(";")?.firstOrNull() ?: "text/html",
"utf-8", conn.responseCode, conn.responseMessage ?: "OK",
headers, conn.inputStream
)
} catch (_: Exception) { null }
}
private fun getLocalIPAddress(): String {
try {
val context = context ?: return ""
val connectivityManager = context.getSystemService(android.content.Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val network = connectivityManager.activeNetwork ?: return ""
val linkProperties = connectivityManager.getLinkProperties(network) ?: return ""
for (addr in linkProperties.linkAddresses) {
val ip = addr.address
if (!ip.isLoopbackAddress && ip is Inet4Address) {
return ip.hostAddress ?: ""
}
}
} catch (e: Exception) {
Log.e("RELAY", "getLocalIPAddress error", e)
}
return ""
}
@Suppress("unused")
inner class JsBridge {
@JavascriptInterface
fun log(msg: String) = host?.appendLog(msg)
@JavascriptInterface
fun getLocalIP(): String = getLocalIPAddress()
@JavascriptInterface
fun resolveHost(hostname: String): String = try {
val all = InetAddress.getAllByName(hostname)
val v4 = all.firstOrNull { it is Inet4Address }
val addr = v4 ?: all.first()
val ip = addr.hostAddress ?: ""
Log.d("RELAY", "resolveHost: $hostname -> $ip (${addr.javaClass.simpleName}, ${all.size} addrs)")
ip
} catch (e: Exception) {
Log.d("RELAY", "resolveHost: $hostname -> FAILED: ${e.message}")
""
}
@JavascriptInterface
fun onTunnelReady() {
host?.appendLog("Tunnel ready, starting VPN...")
host?.onJoinStatus(VpnStatus.TUNNEL_ACTIVE)
activity?.runOnUiThread { host?.requestVpn() }
}
@JavascriptInterface
fun onCaptchaDetected(isDone: Boolean) {
if (!isDone) {
host?.onJoinStatus(VpnStatus.ACTION_REQUIRED_CAPTCHA)
activity?.runOnUiThread { expand() }
} else {
host?.onJoinStatus(VpnStatus.CONNECTING)
}
}
}
companion object {
const val ARG_URL = "url"
fun newInstance(url: String): JsHookJoinFragment {
return JsHookJoinFragment().apply {
arguments = Bundle().apply {
putString(ARG_URL, url)
}
}
}
}
}
@@ -0,0 +1,87 @@
package bypass.whitelist.ui
import android.app.Dialog
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.CheckBox
import android.widget.EditText
import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import bypass.whitelist.R
import bypass.whitelist.util.Callback
import bypass.whitelist.util.Prefs
import bypass.whitelist.util.SocksAuthMode
class ProxySettingsDialogFragment(
private val onChanged: Callback? = null,
) : DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val view = layoutInflater.inflate(R.layout.dialog_proxy_settings, null)
val portInput = view.findViewById<EditText>(R.id.proxyPortInput)
val authModeGroup = view.findViewById<RadioGroup>(R.id.authModeGroup)
val authModeAuto = view.findViewById<RadioButton>(R.id.authModeAuto)
val authModeManual = view.findViewById<RadioButton>(R.id.authModeManual)
val manualAuthContainer = view.findViewById<View>(R.id.manualAuthContainer)
val userInput = view.findViewById<EditText>(R.id.proxyUserInput)
val passInput = view.findViewById<EditText>(R.id.proxyPassInput)
val copyButton = view.findViewById<Button>(R.id.copyProxyButton)
val proxyOnlyCheckbox = view.findViewById<CheckBox>(R.id.proxyOnlyCheckbox)
portInput.setText(Prefs.socksPort.toString())
proxyOnlyCheckbox.isChecked = Prefs.proxyOnly
when (Prefs.socksAuthMode) {
SocksAuthMode.AUTO -> authModeAuto.isChecked = true
SocksAuthMode.MANUAL -> authModeManual.isChecked = true
}
manualAuthContainer.visibility = if (Prefs.socksAuthMode == SocksAuthMode.MANUAL) View.VISIBLE else View.GONE
userInput.setText(Prefs.socksUser)
passInput.setText(Prefs.socksPass)
authModeGroup.setOnCheckedChangeListener { _, checkedId ->
manualAuthContainer.visibility = if (checkedId == R.id.authModeManual) View.VISIBLE else View.GONE
}
copyButton.setOnClickListener {
val port = portInput.text.toString()
val user = userInput.text.toString()
val pass = passInput.text.toString()
val proxyUrl = "socks5://$user:$pass@127.0.0.1:$port"
val clipboard = requireContext().getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
clipboard.setPrimaryClip(ClipData.newPlainText("proxy", proxyUrl))
Toast.makeText(requireContext(), R.string.proxy_copied, Toast.LENGTH_SHORT).show()
}
return AlertDialog.Builder(requireContext())
.setTitle(R.string.proxy_settings_title)
.setView(view)
.setPositiveButton(android.R.string.ok) { _, _ ->
val port = portInput.text.toString().toLongOrNull()
if (port != null && port in 1..65535) {
Prefs.socksPort = port
}
Prefs.socksAuthMode = if (authModeManual.isChecked) SocksAuthMode.MANUAL else SocksAuthMode.AUTO
if (authModeManual.isChecked) {
Prefs.socksUser = userInput.text.toString()
Prefs.socksPass = passInput.text.toString()
}
Prefs.proxyOnly = proxyOnlyCheckbox.isChecked
onChanged?.invoke()
}
.setNegativeButton(android.R.string.cancel, null)
.create()
}
companion object {
const val TAG = "ProxySettingsDialog"
}
}
@@ -0,0 +1,303 @@
package bypass.whitelist.ui
import android.app.Dialog
import android.content.pm.ApplicationInfo
import android.text.Editable
import android.text.TextWatcher
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.CheckBox
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.ListView
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import bypass.whitelist.R
import bypass.whitelist.tunnel.SplitTunnelingMode
import bypass.whitelist.tunnel.TunnelMode
import bypass.whitelist.tunnel.TunnelVpnService
import bypass.whitelist.util.Prefs
class SettingsDialogFragment : DialogFragment() {
interface Listener {
fun onTunnelModeChanged(mode: TunnelMode)
fun onShowLogsChanged(visible: Boolean)
fun onShareLogs()
fun onReset()
}
private var listener: Listener? = null
private var tunnelMode: TunnelMode = Prefs.tunnelMode
private var splitTunnelingMode: SplitTunnelingMode = Prefs.splitTunnelingMode
private var splitTunnelingPackages: MutableSet<String> = Prefs.splitTunnelingPackages.toMutableSet()
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val dialog = super.onCreateDialog(savedInstanceState)
dialog.setTitle(R.string.cd_settings)
return dialog
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View = inflater.inflate(R.layout.fragment_settings, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
listener = activity as? Listener
val tunnelModeItem = view.findViewById<TextView>(R.id.tunnelModeItem)
val splitTunnelingItem = view.findViewById<TextView>(R.id.splitTunnelingItem)
val splitTunnelingAppsItem = view.findViewById<TextView>(R.id.splitTunnelingAppsItem)
val proxyItem = view.findViewById<TextView>(R.id.proxyItem)
val autoclickItem = view.findViewById<TextView>(R.id.autoclickItem)
val headlessCheckbox = view.findViewById<CheckBox>(R.id.headlessCheckbox)
val reconnectCheckbox = view.findViewById<CheckBox>(R.id.reconnectOnStartCheckbox)
val showLogsCheckbox = view.findViewById<CheckBox>(R.id.showLogsCheckbox)
val shareLogsItem = view.findViewById<TextView>(R.id.shareLogsItem)
val resetItem = view.findViewById<TextView>(R.id.resetItem)
val closeButton = view.findViewById<Button>(R.id.closeButton)
updateTunnelModeLabel(tunnelModeItem)
updateSplitTunnelingLabel(splitTunnelingItem)
updateSplitTunnelingAppsEnabled(splitTunnelingAppsItem)
headlessCheckbox.isChecked = Prefs.headless
reconnectCheckbox.isChecked = Prefs.connectOnStart
showLogsCheckbox.isChecked = Prefs.showLogs
tunnelModeItem.setOnClickListener {
showModeDialog(tunnelModeItem)
}
splitTunnelingItem.setOnClickListener {
showSplitTunnelingDialog(splitTunnelingItem, splitTunnelingAppsItem)
}
splitTunnelingAppsItem.setOnClickListener {
if (splitTunnelingMode != SplitTunnelingMode.NONE) {
showSplitTunnelingAppSelection()
}
}
proxyItem.setOnClickListener {
ProxySettingsDialogFragment {
listener?.onReset()
dismiss()
}.show(childFragmentManager, ProxySettingsDialogFragment.TAG)
}
autoclickItem.setOnClickListener {
showAutoclickSettingsDialog()
}
headlessCheckbox.setOnCheckedChangeListener { _, checked ->
Prefs.headless = checked
listener?.onReset()
}
reconnectCheckbox.setOnCheckedChangeListener { _, checked ->
Prefs.connectOnStart = checked
}
showLogsCheckbox.setOnCheckedChangeListener { _, checked ->
Prefs.showLogs = checked
listener?.onShowLogsChanged(checked)
}
shareLogsItem.setOnClickListener {
listener?.onShareLogs()
dismiss()
}
resetItem.setOnClickListener {
listener?.onReset()
dismiss()
}
closeButton.setOnClickListener {
dismiss()
}
}
private fun updateTunnelModeLabel(textView: TextView) {
textView.text = getString(R.string.menu_tunnel, tunnelMode.label)
}
private fun updateSplitTunnelingLabel(textView: TextView) {
textView.text = getString(R.string.menu_split_tunneling, splitTunnelingMode.label)
}
private fun updateSplitTunnelingAppsEnabled(textView: TextView) {
val enabled = splitTunnelingMode != SplitTunnelingMode.NONE
textView.isEnabled = enabled
textView.alpha = if (enabled) 1.0f else 0.4f
}
private fun showModeDialog(tunnelModeItem: TextView) {
val modes = TunnelMode.entries
val labels = modes.map { it.label }.toTypedArray()
val current = modes.indexOf(tunnelMode)
AlertDialog.Builder(requireContext())
.setSingleChoiceItems(labels, current) { dialog, which ->
dialog.dismiss()
val mode = modes[which]
if (mode != tunnelMode) {
tunnelMode = mode
Prefs.tunnelMode = mode
updateTunnelModeLabel(tunnelModeItem)
listener?.onTunnelModeChanged(mode)
}
}
.show()
}
private fun showSplitTunnelingDialog(
splitTunnelingItem: TextView,
splitTunnelingAppsItem: TextView,
) {
val modes = SplitTunnelingMode.entries.toTypedArray()
val labels = modes.map { it.label }.toTypedArray()
val selectedIndex = modes.indexOf(splitTunnelingMode)
AlertDialog.Builder(requireContext())
.setTitle(R.string.split_tunneling_mode_prompt)
.setSingleChoiceItems(labels, selectedIndex) { dialog, which ->
splitTunnelingMode = modes[which]
Prefs.splitTunnelingMode = splitTunnelingMode
updateSplitTunnelingLabel(splitTunnelingItem)
updateSplitTunnelingAppsEnabled(splitTunnelingAppsItem)
dialog.dismiss()
if (TunnelVpnService.instance?.isRunning == true) {
Toast.makeText(requireContext(), R.string.split_tunneling_mode_changed, Toast.LENGTH_SHORT).show()
}
}
.setNegativeButton(android.R.string.cancel, null)
.show()
}
private fun showSplitTunnelingAppSelection() {
val dialogLayout = layoutInflater.inflate(R.layout.split_tunneling_app_list_dialog, null)
val loadingProgressBar = dialogLayout.findViewById<ProgressBar>(R.id.loading_progress_bar)
val appListContainer = dialogLayout.findViewById<LinearLayout>(R.id.app_list_container)
val searchEditText = dialogLayout.findViewById<EditText>(R.id.search_input)
val systemAppsCheckbox = dialogLayout.findViewById<CheckBox>(R.id.system_apps_checkbox)
val listView = dialogLayout.findViewById<ListView>(R.id.app_list_view)
AlertDialog.Builder(requireContext())
.setTitle(R.string.split_tunneling_apps_prompt)
.setView(dialogLayout)
.setPositiveButton(android.R.string.ok) { _, _ ->
Prefs.splitTunnelingMode = splitTunnelingMode
Prefs.splitTunnelingPackages = splitTunnelingPackages
if (TunnelVpnService.instance?.isRunning == true) {
Toast.makeText(requireContext(), R.string.split_tunneling_mode_changed, Toast.LENGTH_SHORT).show()
}
}
.setNegativeButton(android.R.string.cancel, null)
.show()
loadingProgressBar.visibility = View.VISIBLE
appListContainer.visibility = View.GONE
Thread {
var includeSystemApps = false
val context = requireContext()
val pm = context.packageManager
val ownPackage = context.packageName
val installedApps = pm.getInstalledApplications(PackageManager.GET_META_DATA)
.filter { it.packageName != ownPackage }
.mapNotNull { appInfo ->
val pkg = appInfo.packageName
if (pkg.isBlank()) return@mapNotNull null
val label = appInfo.loadLabel(pm).toString().takeIf { it.isNotBlank() } ?: pkg
SplitTunnelingAppItem(
pkg, label, pm.getApplicationIcon(pkg),
splitTunnelingPackages.contains(pkg),
(appInfo.flags and ApplicationInfo.FLAG_SYSTEM) == 0,
)
}
.distinctBy { it.packageName }
.sortedWith(compareByDescending<SplitTunnelingAppItem> { it.isSelected }.thenBy { it.label.lowercase() })
activity?.runOnUiThread {
loadingProgressBar.visibility = View.GONE
appListContainer.visibility = View.VISIBLE
fun buildAppList(query: String, includeSystemApps: Boolean): List<SplitTunnelingAppItem> {
val baseList = installedApps.filter { includeSystemApps || it.isUserApp }
return if (query.isBlank()) {
baseList
} else {
baseList.filter {
it.label.contains(query, ignoreCase = true) ||
it.packageName.contains(query, ignoreCase = true)
}
}
}
val adapter = SplitTunnelingAdapter(layoutInflater, splitTunnelingPackages)
adapter.items = buildAppList("", includeSystemApps)
if (adapter.items.isEmpty()) return@runOnUiThread
listView.choiceMode = ListView.CHOICE_MODE_MULTIPLE
listView.adapter = adapter
systemAppsCheckbox.isChecked = includeSystemApps
systemAppsCheckbox.setOnCheckedChangeListener { _, checked ->
includeSystemApps = checked
adapter.items = buildAppList(searchEditText.text.toString(), includeSystemApps)
}
searchEditText.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
adapter.items = buildAppList(s.toString(), includeSystemApps)
}
override fun afterTextChanged(s: Editable?) {}
})
}
}.start()
}
private fun showAutoclickSettingsDialog() {
val dialogLayout = layoutInflater.inflate(R.layout.autoclick_settings_dialog, null)
val autoclickCheckbox = dialogLayout.findViewById<CheckBox>(R.id.autoclick_checkbox)
val nameInput = dialogLayout.findViewById<EditText>(R.id.autoclick_name_input)
val generateButton = dialogLayout.findViewById<Button>(R.id.autoclick_generate_random_button)
autoclickCheckbox.isChecked = Prefs.autoclickEnabled
nameInput.setText(Prefs.autoclickName)
generateButton.setOnClickListener {
val names = requireContext().assets.open("names.txt").bufferedReader().readLines()
val randomName = names.random()
nameInput.setText(randomName)
}
AlertDialog.Builder(requireContext())
.setTitle(R.string.autoclick_settings_title)
.setView(dialogLayout)
.setPositiveButton(android.R.string.ok) { _, _ ->
Prefs.autoclickEnabled = autoclickCheckbox.isChecked
Prefs.autoclickName = nameInput.text.toString()
}
.setNegativeButton(android.R.string.cancel, null)
.show()
}
companion object {
const val TAG = "SettingsDialogFragment"
}
}
@@ -1,198 +0,0 @@
package bypass.whitelist.ui
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.view.View
import android.widget.CheckBox
import android.widget.LinearLayout
import android.widget.ListView
import android.widget.PopupMenu
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import bypass.whitelist.R
import bypass.whitelist.tunnel.SplitTunnelingMode
import bypass.whitelist.tunnel.TunnelMode
import bypass.whitelist.tunnel.TunnelVpnService
import bypass.whitelist.util.Callback
import bypass.whitelist.util.ParamCallback
import bypass.whitelist.util.Prefs
class SettingsMenuController(
private val activity: AppCompatActivity,
private val onModeChanged: ParamCallback<TunnelMode>,
private val onShareLogs: Callback,
private val onReset: Callback,
) {
var tunnelMode: TunnelMode = Prefs.tunnelMode
var splitTunnelingMode: SplitTunnelingMode = Prefs.splitTunnelingMode
var splitTunnelingPackages: MutableSet<String> = Prefs.splitTunnelingPackages.toMutableSet()
var showLogs: Boolean = Prefs.showLogs
var onShowLogsChanged: ParamCallback<Boolean> = {}
private enum class MenuItem(val id: Int, val stringRes: Int) {
MODE(99, R.string.menu_tunnel),
SPLIT_TUNNELING(98, R.string.menu_split_tunneling),
SPLIT_TUNNELING_APPS(97, R.string.menu_split_tunneling_manage),
RECONNECT_ON_START(100, R.string.menu_reconnect_on_start),
SHOW_LOGS(101, R.string.menu_show_logs),
SHARE_LOGS(102, R.string.menu_share_logs),
RESET(200, R.string.menu_reset),
}
fun show(anchor: View) {
val popup = PopupMenu(activity, anchor)
val menu = popup.menu
menu.add(0, MenuItem.MODE.id, 0, activity.getString(MenuItem.MODE.stringRes, tunnelMode.label))
menu.add(0, MenuItem.SPLIT_TUNNELING.id, 0, activity.getString(MenuItem.SPLIT_TUNNELING.stringRes, splitTunnelingMode.label))
menu.add(0, MenuItem.SPLIT_TUNNELING_APPS.id, 0, MenuItem.SPLIT_TUNNELING_APPS.stringRes).apply {
isEnabled = splitTunnelingMode != SplitTunnelingMode.NONE
}
menu.add(0, MenuItem.RECONNECT_ON_START.id, 0, MenuItem.RECONNECT_ON_START.stringRes).apply {
isCheckable = true
isChecked = Prefs.connectOnStart
}
menu.add(0, MenuItem.SHOW_LOGS.id, 0, MenuItem.SHOW_LOGS.stringRes).apply {
isCheckable = true
isChecked = showLogs
}
menu.add(0, MenuItem.SHARE_LOGS.id, 0, MenuItem.SHARE_LOGS.stringRes)
menu.add(0, MenuItem.RESET.id, 0, MenuItem.RESET.stringRes)
popup.setOnMenuItemClickListener { item ->
when (item.itemId) {
MenuItem.RECONNECT_ON_START.id -> {
Prefs.connectOnStart = !item.isChecked
true
}
MenuItem.SPLIT_TUNNELING.id -> {
showSplitTunnelingDialog()
true
}
MenuItem.SPLIT_TUNNELING_APPS.id -> {
showSplitTunnelingAppSelection()
true
}
MenuItem.SHOW_LOGS.id -> {
showLogs = !item.isChecked
Prefs.showLogs = showLogs
onShowLogsChanged(showLogs)
true
}
MenuItem.SHARE_LOGS.id -> {
onShareLogs()
true
}
MenuItem.RESET.id -> {
onReset()
true
}
MenuItem.MODE.id -> {
showModeDialog()
true
}
else -> false
}
}
popup.show()
}
private fun showModeDialog() {
val modes = TunnelMode.entries
val labels = modes.map { it.label }.toTypedArray()
val current = modes.indexOf(tunnelMode)
AlertDialog.Builder(activity)
.setSingleChoiceItems(labels, current) { dialog, which ->
dialog.dismiss()
val mode = modes[which]
if (mode != tunnelMode) {
tunnelMode = mode
Prefs.tunnelMode = mode
onModeChanged(mode)
}
}
.show()
}
private fun showSplitTunnelingDialog() {
val modes = SplitTunnelingMode.entries.toTypedArray()
val labels = modes.map { it.label }.toTypedArray()
val selectedIndex = modes.indexOf(splitTunnelingMode)
AlertDialog.Builder(activity)
.setTitle(R.string.split_tunneling_mode_prompt)
.setSingleChoiceItems(labels, selectedIndex) { dialog, which ->
splitTunnelingMode = modes[which]
Prefs.splitTunnelingMode = splitTunnelingMode
dialog.dismiss()
if (TunnelVpnService.instance?.isRunning == true) {
Toast.makeText(activity, R.string.split_tunneling_mode_changed, Toast.LENGTH_SHORT).show()
}
}
.setNegativeButton(android.R.string.cancel, null)
.show()
}
private fun showSplitTunnelingAppSelection() {
var includeSystemApps = false
val pm = activity.packageManager
val installedApps = pm.getInstalledApplications(PackageManager.GET_META_DATA)
.filter { it.packageName != activity.packageName }
.mapNotNull { appInfo ->
val pkg = appInfo.packageName
if (pkg.isBlank()) return@mapNotNull null
val label = appInfo.loadLabel(pm).toString().takeIf { it.isNotBlank() } ?: pkg
SplitTunnelingAppItem(
pkg, label, pm.getApplicationIcon(pkg),
splitTunnelingPackages.contains(pkg),
(appInfo.flags and ApplicationInfo.FLAG_SYSTEM) == 0,
)
}
.distinctBy { it.packageName }
.sortedWith(compareByDescending<SplitTunnelingAppItem> { it.isSelected }.thenBy { it.label.lowercase() })
fun buildAppList() = installedApps.filter { includeSystemApps || it.isUserApp }
val adapter = SplitTunnelingAdapter(activity.layoutInflater, splitTunnelingPackages)
adapter.items = buildAppList()
if (adapter.items.isEmpty()) return
val listView = ListView(activity).apply {
choiceMode = ListView.CHOICE_MODE_MULTIPLE
this.adapter = adapter
}
val systemAppsCheckbox = CheckBox(activity).apply {
text = activity.getString(R.string.split_tunneling_show_system_apps)
isChecked = includeSystemApps
setOnCheckedChangeListener { _, checked ->
includeSystemApps = checked
adapter.items = buildAppList()
}
}
val dialogLayout = LinearLayout(activity).apply {
orientation = LinearLayout.VERTICAL
setPadding(24, 24, 24, 24)
addView(systemAppsCheckbox)
addView(listView)
}
AlertDialog.Builder(activity)
.setTitle(R.string.split_tunneling_apps_prompt)
.setView(dialogLayout)
.setPositiveButton(android.R.string.ok) { _, _ ->
Prefs.splitTunnelingMode = splitTunnelingMode
Prefs.splitTunnelingPackages = splitTunnelingPackages
if (TunnelVpnService.instance?.isRunning == true) {
Toast.makeText(activity, R.string.split_tunneling_mode_changed, Toast.LENGTH_SHORT).show()
}
}
.setNegativeButton(android.R.string.cancel, null)
.show()
}
}
@@ -7,6 +7,7 @@ import bypass.whitelist.R
import bypass.whitelist.tunnel.TunnelMode
import bypass.whitelist.tunnel.VpnStatus
import bypass.whitelist.util.Callback
import bypass.whitelist.util.Prefs
class StatusBarController(
private val activity: AppCompatActivity,
@@ -29,21 +30,33 @@ class StatusBarController(
}
fun setStatus(status: VpnStatus) {
statusBar.text = activity.getString(R.string.status_format, tunnelMode.label, activity.getString(status.labelRes))
val label = if (status == VpnStatus.PORT_BUSY) {
activity.getString(status.labelRes, Prefs.socksPort)
} else {
activity.getString(status.labelRes)
}
statusBar.text = activity.getString(R.string.status_format, tunnelMode.label, label)
val colorRes = when (status) {
VpnStatus.TUNNEL_ACTIVE -> R.color.status_active
VpnStatus.CONNECTING,
VpnStatus.CALL_CONNECTED,
VpnStatus.DATACHANNEL_OPEN -> R.color.status_connecting
VpnStatus.TUNNEL_LOST,
VpnStatus.DATACHANNEL_LOST -> R.color.status_warning
VpnStatus.DATACHANNEL_LOST,
VpnStatus.ACTION_REQUIRED_CAPTCHA -> R.color.status_warning
VpnStatus.CALL_DISCONNECTED,
VpnStatus.CALL_FAILED -> R.color.status_error
VpnStatus.CALL_FAILED,
VpnStatus.PORT_BUSY -> R.color.status_error
VpnStatus.STARTING -> R.color.status_idle
}
statusBar.setBackgroundColor(activity.getColor(colorRes))
}
fun setStatusText(text: String) {
statusBar.text = text
statusBar.setBackgroundColor(activity.getColor(R.color.status_connecting))
}
fun setIdle() {
statusBar.text = activity.getString(R.string.status_format, tunnelMode.label, activity.getString(R.string.status_idle))
statusBar.setBackgroundColor(activity.getColor(R.color.status_idle))
@@ -0,0 +1,159 @@
package bypass.whitelist.ui
import android.annotation.SuppressLint
import android.util.Log
import android.webkit.ConsoleMessage
import android.webkit.JavascriptInterface
import android.webkit.WebChromeClient
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.appcompat.app.AppCompatActivity
import bypass.whitelist.util.DESKTOP_USER_AGENT
import bypass.whitelist.util.ParamCallback
import org.json.JSONObject
import java.net.HttpURLConnection
import java.net.URL
@SuppressLint("SetJavaScriptEnabled")
class VkCaptchaWebView(
private val activity: AppCompatActivity,
private val webView: WebView,
private val onStatus: ParamCallback<String>,
private val onToken: ParamCallback<String>,
) {
private val authScript by lazy {
activity.assets.open("headless-auth-vk.js").bufferedReader().readText()
}
private val authPageHTML = """
<!DOCTYPE html>
<html>
<body>
<iframe id="captcha" style="width:100%;height:100vh;border:none;display:none;"></iframe>
</body>
</html>
""".trimIndent()
private var pendingHTML: String? = null
private var pendingJoinLink = ""
private var pendingAnonName = ""
fun setup() {
webView.settings.apply {
javaScriptEnabled = true
domStorageEnabled = true
allowContentAccess = true
userAgentString = DESKTOP_USER_AGENT
}
webView.addJavascriptInterface(CaptchaBridge(), "AndroidBridge")
webView.addJavascriptInterface(AuthBridge(), "AndroidCaptchaBridge")
webView.webChromeClient = object : WebChromeClient() {
override fun onConsoleMessage(msg: ConsoleMessage): Boolean {
Log.d("CAPTCHA", "${msg.sourceId()?.takeLast(30)}:${msg.lineNumber()} ${msg.message()}")
return true
}
}
webView.webViewClient = object : WebViewClient() {
override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? {
val url = request.url.toString()
if (url.contains("vk.com/blank.php") && pendingHTML != null) {
val html = pendingHTML!!
pendingHTML = null
return WebResourceResponse(
"text/html", "utf-8", 200, "OK",
mapOf("Access-Control-Allow-Origin" to "*"),
html.byteInputStream()
)
}
if (url.contains("id.vk.com") || url.contains("okcdn.ru")) {
Log.d("CAPTCHA", "REQ: $url")
return stripHeaders(url, request)
}
if (url.contains("captchaNotRobot") || url.contains("captcha")) {
Log.d("CAPTCHA", "REQ: $url")
}
return null
}
override fun onPageFinished(view: WebView, url: String) {
if (!url.contains("blank.php")) return
view.evaluateJavascript("window.JOIN_LINK='${escapeJs(pendingJoinLink)}';window.ANON_NAME='${escapeJs(pendingAnonName)}';", null)
view.evaluateJavascript(authScript, null)
}
}
}
fun start(joinLink: String, anonName: String) {
pendingJoinLink = joinLink
pendingAnonName = anonName
pendingHTML = authPageHTML
webView.loadUrl("https://vk.com/blank.php")
}
@Suppress("unused")
inner class AuthBridge {
@JavascriptInterface
fun onJoined(json: String) {
Log.d("CAPTCHA", "onJoined: ${json.take(200)}")
onToken(json)
}
@JavascriptInterface
fun setStatus(message: String) {
Log.d("CAPTCHA", "status: $message")
activity.runOnUiThread { onStatus(message) }
}
}
@Suppress("unused", "FunctionName")
inner class CaptchaBridge {
@JavascriptInterface
fun VKCaptchaGetResult(json: String) {
Log.d("CAPTCHA", "VKCaptchaGetResult: ${json.take(200)}")
val token = try {
JSONObject(json).getString("token")
} catch (e: Exception) { json }
webView.post {
webView.evaluateJavascript("if(typeof retryCaptcha==='function')retryCaptcha('${token.replace("'", "\\'")}');", null)
}
}
@JavascriptInterface
fun VKCaptchaClose(json: String) {
Log.d("CAPTCHA", "VKCaptchaClose: $json")
}
}
private fun escapeJs(value: String): String =
value.replace("\\", "\\\\").replace("'", "\\'").replace("\n", "\\n")
private fun stripHeaders(url: String, request: WebResourceRequest): WebResourceResponse? {
return try {
val conn = URL(url).openConnection() as HttpURLConnection
conn.requestMethod = request.method ?: "GET"
request.requestHeaders?.forEach { (key, value) -> conn.setRequestProperty(key, value) }
val headers = mutableMapOf<String, String>()
conn.headerFields?.forEach { (key, values) ->
if (key != null
&& !key.equals("content-security-policy", ignoreCase = true)
&& !key.equals("content-security-policy-report-only", ignoreCase = true)
&& !key.equals("x-frame-options", ignoreCase = true)
) {
headers[key] = values.joinToString(", ")
}
}
headers["Access-Control-Allow-Origin"] = "*"
WebResourceResponse(
conn.contentType?.split(";")?.firstOrNull() ?: "text/html",
"utf-8", conn.responseCode, conn.responseMessage ?: "OK",
headers, conn.inputStream
)
} catch (_: Exception) { null }
}
}
@@ -1,178 +0,0 @@
package bypass.whitelist.ui
import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.util.Log
import android.view.View
import android.webkit.ConsoleMessage
import android.webkit.PermissionRequest
import android.webkit.WebChromeClient
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import bypass.whitelist.R
import bypass.whitelist.tunnel.CallPlatform
import bypass.whitelist.tunnel.TunnelMode
import bypass.whitelist.tunnel.VpnStatus
import bypass.whitelist.util.ParamCallback
import bypass.whitelist.util.maskUrl
private data class HookKey(val isPion: Boolean, val platform: CallPlatform)
class WebViewManager(
private val activity: AppCompatActivity,
private val webView: WebView,
private val toggleButton: View,
private val toggleArrow: ImageView,
private val toggleLabel: TextView,
private val onLog: ParamCallback<String>,
private val onStatus: ParamCallback<VpnStatus>,
) {
var tunnelMode: TunnelMode = TunnelMode.DC
private var expanded = false
private var callUrl = ""
private val hooks = mapOf(
HookKey(false, CallPlatform.VK) to lazy { loadAsset("dc-joiner-vk.js") },
HookKey(false, CallPlatform.TELEMOST) to lazy { loadAsset("dc-joiner-telemost.js") },
HookKey(true, CallPlatform.VK) to lazy { loadAsset("video-vk.js") },
HookKey(true, CallPlatform.TELEMOST) to lazy { loadAsset("video-telemost.js") },
)
private val autoclickers = mapOf(
CallPlatform.VK to lazy { loadAsset("autoclick-vk.js") },
CallPlatform.TELEMOST to lazy { loadAsset("autoclick-telemost.js") },
)
private val muteAudioContext by lazy { loadAsset("mute-audio-context.js") }
private fun loadAsset(name: String): String =
activity.assets.open(name).bufferedReader().readText()
private fun setExpanded(value: Boolean) {
expanded = value
webView.visibility = if (value) View.VISIBLE else View.GONE
toggleArrow.rotation = if (value) 180f else 0f
toggleLabel.setText(if (value) R.string.collapse_webview else R.string.expand_webview)
}
fun collapse() {
setExpanded(false)
}
@SuppressLint("SetJavaScriptEnabled")
fun setup(jsBridge: Any) {
toggleButton.setOnClickListener { setExpanded(!expanded) }
webView.settings.apply {
javaScriptEnabled = true
domStorageEnabled = true
mediaPlaybackRequiresUserGesture = false
allowContentAccess = true
allowFileAccess = true
databaseEnabled = true
setSupportMultipleWindows(false)
useWideViewPort = true
loadWithOverviewMode = true
builtInZoomControls = true
displayZoomControls = false
userAgentString = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
}
webView.addJavascriptInterface(jsBridge, "AndroidBridge")
webView.webChromeClient = object : WebChromeClient() {
override fun onPermissionRequest(request: PermissionRequest) {
activity.runOnUiThread { request.grant(request.resources) }
}
override fun onConsoleMessage(msg: ConsoleMessage): Boolean {
val text = msg.message()
Log.d("HOOK", text)
if (text.contains("[HOOK]")) {
onLog(text)
when {
text.contains("CALL CONNECTED") -> onStatus(VpnStatus.CALL_CONNECTED)
text.contains("DataChannel open") -> onStatus(VpnStatus.DATACHANNEL_OPEN)
text.contains("DataChannel closed") -> onStatus(VpnStatus.DATACHANNEL_LOST)
text.contains("WebSocket connected") -> onStatus(VpnStatus.TUNNEL_ACTIVE)
text.contains("WebSocket disconnected") -> onStatus(VpnStatus.TUNNEL_LOST)
text.contains("Connection state: connecting") -> onStatus(VpnStatus.CONNECTING)
text.contains("Connection state: disconnected") -> onStatus(VpnStatus.CALL_DISCONNECTED)
text.contains("Connection state: failed") -> onStatus(VpnStatus.CALL_FAILED)
}
}
return true
}
}
webView.webViewClient = object : WebViewClient() {
override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? {
val url = request.url.toString()
val platform = CallPlatform.fromUrl(url)
if (platform != CallPlatform.TELEMOST || !url.contains("/j/") || request.method != "GET") return null
return stripCsp(url, request)
}
override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
if (url.contains("about:blank")) return
view.evaluateJavascript(muteAudioContext, null)
}
override fun onPageFinished(view: WebView, url: String) {
if (url.contains("about:blank")) return
if (!expanded && url != callUrl) activity.runOnUiThread { setExpanded(true) }
view.evaluateJavascript("!!window.__hookInstalled") { result ->
if (result == "true") {
Log.d("HOOK", "Hook already injected, skipping")
return@evaluateJavascript
}
val platform = CallPlatform.fromUrl(url)
onLog("Page loaded, injecting hook for ${maskUrl(url)}")
view.evaluateJavascript("window.WS_PORT=${mobile.Mobile.activeWsPort()}", null)
view.evaluateJavascript(hookForPlatform(platform), null)
onLog("Injecting autoclick for ${maskUrl(url)}")
view.evaluateJavascript(autoclickers[platform]!!.value, null)
}
}
}
}
fun loadUrl(url: String) {
callUrl = url
webView.loadUrl(url)
}
fun loadBlank() {
callUrl = ""
webView.loadUrl("about:blank")
}
private fun hookForPlatform(platform: CallPlatform): String =
hooks[HookKey(tunnelMode.isPion, platform)]!!.value
private fun stripCsp(url: String, request: WebResourceRequest): WebResourceResponse? {
return try {
val conn = java.net.URL(url).openConnection() as java.net.HttpURLConnection
conn.requestMethod = "GET"
request.requestHeaders?.forEach { (k, v) -> conn.setRequestProperty(k, v) }
val headers = mutableMapOf<String, String>()
conn.headerFields?.forEach { (k, v) ->
if (k != null
&& !k.equals("content-security-policy", ignoreCase = true)
&& !k.equals("content-security-policy-report-only", ignoreCase = true)
) {
headers[k] = v.joinToString(", ")
}
}
WebResourceResponse(
conn.contentType?.split(";")?.firstOrNull() ?: "text/html",
"utf-8", conn.responseCode, conn.responseMessage ?: "OK",
headers, conn.inputStream
)
} catch (_: Exception) { null }
}
}
@@ -1,11 +1,36 @@
package bypass.whitelist.util
import java.security.SecureRandom
object Ports {
const val SOCKS = 1080L
const val DEFAULT_SOCKS = 1080L
const val DC_WS = 9000L
const val PION_SIGNALING = 9001L
}
enum class SocksAuthMode { AUTO, MANUAL }
object SocksAuth {
private val autoUser: String
private val autoPass: String
init {
val random = SecureRandom()
val chars = "abcdefghijklmnopqrstuvwxyz0123456789"
fun randomString(length: Int) = buildString {
repeat(length) { append(chars[random.nextInt(chars.length)]) }
}
autoUser = randomString(16)
autoPass = randomString(24)
}
val user: String
get() = if (Prefs.socksAuthMode == SocksAuthMode.MANUAL) Prefs.socksUser else autoUser
val pass: String
get() = if (Prefs.socksAuthMode == SocksAuthMode.MANUAL) Prefs.socksPass else autoPass
}
object PrefsKeys {
const val CONNECT_ON_START = "connect_on_start"
const val URL = "url"
@@ -13,8 +38,20 @@ object PrefsKeys {
const val SHOW_LOGS = "show_logs"
const val SPLIT_TUNNELING_MODE = "split_tunneling_mode"
const val SPLIT_TUNNELING_PACKAGES = "split_tunneling_packages"
const val AUTOCLICK_ENABLED = "autoclick_enabled"
const val AUTOCLICK_NAME = "autoclick_name"
const val HEADLESS = "headless"
const val SOCKS_PORT = "socks_port"
const val SOCKS_AUTH_MODE = "socks_auth_mode"
const val SOCKS_USER = "socks_user"
const val SOCKS_PASS = "socks_pass"
const val PROXY_ONLY = "proxy_only"
}
const val BLANK_URL = "about:blank"
const val DESKTOP_USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
object Vpn {
const val ADDRESS = "10.0.0.2"
const val PREFIX_LENGTH = 32
@@ -51,4 +51,43 @@ object Prefs {
var splitTunnelingPackages: Set<String>
get() = prefs.getStringSet(PrefsKeys.SPLIT_TUNNELING_PACKAGES, emptySet()) ?: emptySet()
set(value) = prefs.edit { putStringSet(PrefsKeys.SPLIT_TUNNELING_PACKAGES, value) }
var autoclickEnabled: Boolean
get() = prefs.getBoolean(PrefsKeys.AUTOCLICK_ENABLED, true)
set(value) = prefs.edit { putBoolean(PrefsKeys.AUTOCLICK_ENABLED, value) }
var autoclickName: String
get() = prefs.getString(PrefsKeys.AUTOCLICK_NAME, "Hello")!!
set(value) = prefs.edit { putString(PrefsKeys.AUTOCLICK_NAME, value) }
var headless: Boolean
get() = prefs.getBoolean(PrefsKeys.HEADLESS, true)
set(value) = prefs.edit { putBoolean(PrefsKeys.HEADLESS, value) }
var socksPort: Long
get() = prefs.getLong(PrefsKeys.SOCKS_PORT, Ports.DEFAULT_SOCKS)
set(value) = prefs.edit { putLong(PrefsKeys.SOCKS_PORT, value) }
var socksAuthMode: SocksAuthMode
get() {
val name = prefs.getString(PrefsKeys.SOCKS_AUTH_MODE, SocksAuthMode.AUTO.name)!!
return try {
SocksAuthMode.valueOf(name)
} catch (_: IllegalArgumentException) {
SocksAuthMode.AUTO
}
}
set(value) = prefs.edit { putString(PrefsKeys.SOCKS_AUTH_MODE, value.name) }
var socksUser: String
get() = prefs.getString(PrefsKeys.SOCKS_USER, "")!!
set(value) = prefs.edit { putString(PrefsKeys.SOCKS_USER, value) }
var socksPass: String
get() = prefs.getString(PrefsKeys.SOCKS_PASS, "")!!
set(value) = prefs.edit { putString(PrefsKeys.SOCKS_PASS, value) }
var proxyOnly: Boolean
get() = prefs.getBoolean(PrefsKeys.PROXY_ONLY, false)
set(value) = prefs.edit { putBoolean(PrefsKeys.PROXY_ONLY, value) }
}