Commit 177510e2 authored by chenhuaqing's avatar chenhuaqing Committed by hanakeichen

remove unused code and fix packet loss rate

parent 608e9032
......@@ -9,6 +9,9 @@ data class NetState(
//丢包率
var lossRate: String,
var accNetTotal: Int = 0,
var accNetLoss: Int = 0,
var pingWifiLatency: Int = -1,
var pingWifiTotal: Int = -1,
var pingWifiLoss: Int = -1,
......
......@@ -2,20 +2,16 @@ package com.ccwangluo.accelerator.utils
import android.annotation.SuppressLint
import android.content.Context
import android.net.Network
import android.os.RemoteException
import androidx.activity.result.ActivityResultLauncher
import androidx.lifecycle.lifecycleScope
import com.ccnet.acc.NetworkAdapter
import com.ccnet.acc.aidl.NetworkMode
import com.ccwangluo.accelerator.model.Game
import com.ccwangluo.accelerator.model.GameInfo
import com.ccwangluo.accelerator.model.NetState
import com.ccwangluo.accelerator.ui.dialog.CommonDialog
import com.ccwangluo.accelerator.ui.home.AcceleratorFragment
import com.ccwangluo.accelerator.utils.datareport.DataRePortUtils
import com.ccwangluo.accelerator.utils.http.HttpGo
import com.ccwangluo.cc_quickly.utils.SettingSPUtils
import com.github.shadowsocks.Core
import com.github.shadowsocks.acl.Acl
import com.github.shadowsocks.aidl.IShadowsocksService
......@@ -31,12 +27,12 @@ import com.hjq.toast.ToastUtils
import com.xuexiang.xpage.base.XPageActivity
import com.xuexiang.xpage.base.XPageFragment
import com.xuexiang.xutil.common.StringUtils
import kotlinx.coroutines.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import timber.log.Timber
import java.net.InetSocketAddress
import java.net.Socket
import java.net.SocketAddress
import java.util.concurrent.TimeUnit
import kotlin.math.roundToInt
/**
......@@ -58,7 +54,42 @@ object AcceleratorUtils {
//游戏
var game: GameInfo? = null
private var stateListener: (BaseService.State, Long, NetState?) -> Unit = { state, l, s ->
private val stateListener: (BaseService.State) -> Unit = { state ->
networkStatsListener(state, getAccTime(), netState)
if (state == BaseService.State.Connected) {
context.lifecycleScope.launch(Dispatchers.IO) {
while (AcceleratorUtils.state == BaseService.State.Connected) {
netState.preNetDelay =
NetUtils.tcpPing(DataStore.pingAccHost, DataStore.pingAccPort)
.toInt()
Timber.d("pre acc ping : ${netState}")
LoginUtils.getUserHasTimer { haveTime ->
if (!haveTime) { //没有加速时长关闭服务
stopAccelerator()
}
}
netState.accNetDelay =
if (netState.accNetDelay > netState.preNetDelay && netState.preNetDelay != -1) {
netState.preNetDelay
} else {
netState.accNetDelay
}
netState.lossRate = if (netState.accNetTotal != 0) {
(netState.accNetLoss.toFloat() / netState.accNetTotal * 100).roundToInt().toString()
} else {
"0"
}
// netState.lossRate = if (netState.accNetDelay == -1) "100" else "0"
networkStatsListener(state, getAccTime(), netState)
delay(1000)
}
}
}
}
private var networkStatsListener: (BaseService.State, Long, NetState?) -> Unit = { _, _, _ ->
}
var vipExpireListener: () -> Unit = { ->
......@@ -106,12 +137,12 @@ object AcceleratorUtils {
if (SysUtils.isVpn(context) && state != BaseService.State.Connected) {
AuthManager.Last_ACC_TIme = 0L
CommonDialog(context).setTitle("VPN被挤占")
.setContent("请确保已关闭其他加速器,并未开起任何游戏空间等类似功能")
.setBtnLeft("取消", {
.setContent("请确保已关闭其他加速器,并未开起任何游戏空间等类似功能")
.setBtnLeft("取消") {
}).setBtnRight("我知道了", {
}.setBtnRight("我知道了") {
}).show<CommonDialog>()
}.show<CommonDialog>()
return
}
}
......@@ -121,30 +152,8 @@ object AcceleratorUtils {
initAuthProfile(xPageFragment)
val serverPort = it.boosterServer.split(":")
DataStore.pingAccHost = serverPort[0]
DataStore.pingAccHost = "104.26.1.233"
DataStore.pingAccPort = serverPort[1].toInt()
xPageFragment.lifecycleScope.launch(Dispatchers.IO) {
while (true) {
if (state == BaseService.State.Connected) {
netState.preNetDelay =
NetUtils.tcpPing(serverPort[0], serverPort[1].toInt())
.toInt()
LoginUtils.getUserHasTimer { haveTime ->
if (!haveTime) { //没有加速时长关闭服务
stopAccelerator()
}
}
netState.accNetDelay =
if (netState.accNetDelay > netState.preNetDelay && netState.preNetDelay != -1) {
netState.preNetDelay
} else {
netState.accNetDelay
}
netState.lossRate = if (netState.accNetDelay == -1) "100" else "0"
}
stateListener(state, getAccTime(), netState)
delay(1000)
}
}
}
}
......@@ -154,11 +163,11 @@ object AcceleratorUtils {
val profile = ProfileManager.getProfile(profileId) ?: Profile()
profile.proxyApps = true
val proxyGames = mutableSetOf(
// "com.android.chrome",
"com.example.myapplication",
"com.riotgames.league.wildrifttw",
"com.activision.callofduty.shooter",
"com.pubg.krmobile",
// "com.android.chrome",
"com.example.myapplication",
"com.riotgames.league.wildrifttw",
"com.activision.callofduty.shooter",
"com.pubg.krmobile",
)
game?.boosterPackageName?.split(",")?.forEach {
if (!StringUtils.isEmpty(it)) {
......@@ -185,14 +194,12 @@ object AcceleratorUtils {
}
fun registerStateListener(listener: (BaseService.State, Long, NetState?) -> Unit) {
stateListener = listener
stateListener(state, getAccTime(), null)
networkStatsListener = listener
networkStatsListener(state, getAccTime(), null)
}
fun unRegisterStateListener() {
stateListener = { state, l, net ->
}
networkStatsListener = { _, _, _ -> }
}
fun registerVipExpireListener(listener: () -> Unit) {
......@@ -213,11 +220,11 @@ object AcceleratorUtils {
private val shadowsocksConnection = object : ShadowsocksConnection.Callback {
override fun stateChanged(state: BaseService.State, profileName: String?, msg: String?) {
AcceleratorUtils.state = state
stateListener(state, getAccTime(), netState)
stateListener(state)
if (state == BaseService.State.Stopped && !msg.isNullOrBlank()) {
DataRePortUtils.report(
"st_speed_result",
mapOf("result" to 0, "cause" to 3.toString())
"st_speed_result",
mapOf("result" to 0, "cause" to 3.toString())
)
if ("vip到期".equals(msg) || (msg != null && msg.startsWith("vip已到期"))) {
vipExpireListener()
......@@ -238,7 +245,7 @@ object AcceleratorUtils {
} catch (_: RemoteException) {
BaseService.State.Idle
}
stateListener(state, getAccTime(), netState)
stateListener(state)
}
override fun onBinderDied() {
......@@ -248,6 +255,10 @@ object AcceleratorUtils {
override fun trafficUpdated(profileId: Long, stats: TrafficStats) {
netState.accNetDelay = stats.latency
netState.accNetTotal++
if (stats.latency == -1) {
netState.accNetLoss++
}
}
}
......
package com.ccwangluo.accelerator.utils
import android.net.Network
import com.github.shadowsocks.net.DefaultNetworkListener
import kotlinx.coroutines.isActive
import timber.log.Timber
import java.io.IOException
......@@ -11,20 +9,10 @@ import java.net.UnknownHostException
import kotlin.coroutines.coroutineContext
object NetUtils {
@Volatile
private var underlyingNetwork: Network? = null
suspend fun init() {
DefaultNetworkListener.start(this) {
underlyingNetwork = it
}
}
suspend fun tcpPing(url: String, port: Int, proxyPort: Int = 0): Long {
suspend fun tcpPing(url: String, port: Int): Long {
var time = -1L
for (k in 0 until 2) {
val one = socketConnectTime(url, port, proxyPort)
val one = socketConnectTime(url, port)
if (!coroutineContext.isActive) {
break
}
......@@ -35,17 +23,10 @@ object NetUtils {
return time
}
private suspend fun socketConnectTime(url: String, port: Int, proxyPort: Int): Long {
private suspend fun socketConnectTime(url: String, port: Int): Long {
try {
val socket = if (proxyPort == 0) {
Socket()
} else {
val socket = Socket()
DefaultNetworkListener.get().bindSocket(socket)
socket
// Socket(Proxy(Proxy.Type.SOCKS, InetSocketAddress("127.0.0.1", proxyPort)))
}
val socket = Socket()
val start = System.currentTimeMillis()
socket.connect(InetSocketAddress(url, port))
val time = System.currentTimeMillis() - start
......
......@@ -23,9 +23,7 @@ package com.github.shadowsocks.bg
import android.app.Service
import android.content.Intent
import android.content.pm.PackageManager
import android.net.LocalServerSocket
import android.net.LocalSocket
import android.net.LocalSocketAddress
import android.net.Network
import android.os.Build
import android.os.ParcelFileDescriptor
......@@ -51,7 +49,6 @@ import java.io.File
import java.io.FileDescriptor
import java.io.IOException
import java.net.URL
import java.nio.ByteBuffer
import kotlin.concurrent.thread
import android.net.VpnService as BaseVpnService
......@@ -75,8 +72,8 @@ class VpnService : BaseVpnService(), BaseService.Interface {
}
private inner class ProtectWorker : ConcurrentLocalSocketListener(
"ShadowsocksVpnThread",
File(Core.deviceStorage.noBackupFilesDir, "protect_path")
"ShadowsocksVpnThread",
File(Core.deviceStorage.noBackupFilesDir, "protect_path")
) {
override fun acceptInternal(socket: LocalSocket) {
if (socket.inputStream.read() == -1) return
......@@ -110,11 +107,11 @@ class VpnService : BaseVpnService(), BaseService.Interface {
override val data = BaseService.Data(this)
override val tag: String get() = "ShadowsocksVpnService"
override fun createNotification(profileName: String): ServiceNotification =
ServiceNotification(this, profileName, "service-vpn")
ServiceNotification(this, profileName, "service-vpn")
private var conn: ParcelFileDescriptor? = null
private var worker: ProtectWorker? = null
private var protectJob: Job? = null
private var protectJob: ProtectWorker? = null
private var active = false
private var metered = false
......@@ -126,10 +123,10 @@ class VpnService : BaseVpnService(), BaseService.Interface {
}
private val underlyingNetworks
get() =
// clearing underlyingNetworks makes Android 9 consider the network to be metered
// clearing underlyingNetworks makes Android 9 consider the network to be metered
if (Build.VERSION.SDK_INT == 28 && metered) null else underlyingNetwork?.let {
arrayOf(
it
it
)
}
......@@ -157,10 +154,10 @@ class VpnService : BaseVpnService(), BaseService.Interface {
if (DataStore.serviceMode == Key.modeVpn) {
if (prepare(this) != null) {
startActivity(
Intent(
this,
VpnRequestActivity::class.java
).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
Intent(
this,
VpnRequestActivity::class.java
).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
)
} else {
return super<BaseService.Interface>.onStartCommand(intent, flags, startId)
......@@ -173,8 +170,9 @@ class VpnService : BaseVpnService(), BaseService.Interface {
override suspend fun preInit() = DefaultNetworkListener.start(this) { underlyingNetwork = it }
override suspend fun rawResolver(query: ByteArray) =
// no need to listen for network here as this is only used for forwarding local DNS queries.
// retries should be attempted by client.
DnsResolverCompat.resolveRaw(underlyingNetwork ?: throw IOException("no network"), query)
// retries should be attempted by client.
DnsResolverCompat.resolveRaw(underlyingNetwork
?: throw IOException("no network"), query)
override suspend fun openConnection(url: URL) = DefaultNetworkListener.get().openConnection(url)
......@@ -190,26 +188,26 @@ class VpnService : BaseVpnService(), BaseService.Interface {
private fun startVpn(): FileDescriptor {
val profile = data.proxy!!.profile
val builder = Builder()
.setConfigureIntent(Core.configureIntent(this))
.setSession(profile.formattedName)
.setMtu(VPN_MTU)
.addAddress(PRIVATE_VLAN4_CLIENT, 30)
.addDnsServer(PUBLIC_DNS_SERVER)
.setConfigureIntent(Core.configureIntent(this))
.setSession(profile.formattedName)
.setMtu(VPN_MTU)
.addAddress(PRIVATE_VLAN4_CLIENT, 30)
.addDnsServer(PUBLIC_DNS_SERVER)
if (profile.ipv6) builder.addAddress(PRIVATE_VLAN6_CLIENT, 126)
if (profile.proxyApps) {
val me = packageName
profile.individual.split('\n')
.filter { it != me }
.forEach {
try {
if (profile.bypass) builder.addDisallowedApplication(it)
else builder.addAllowedApplication(it)
} catch (ex: PackageManager.NameNotFoundException) {
Timber.w(ex)
.filter { it != me }
.forEach {
try {
if (profile.bypass) builder.addDisallowedApplication(it)
else builder.addAllowedApplication(it)
} catch (ex: PackageManager.NameNotFoundException) {
Timber.w(ex)
}
}
}
// if (!profile.bypass) builder.addAllowedApplication(me)
}
......@@ -240,45 +238,15 @@ class VpnService : BaseVpnService(), BaseService.Interface {
this.conn = conn
data.tunFd = conn.fd
val protectPath =
File.createTempFile("leaf_vpn_socket_protect", ".sock", cacheDir).absolutePath
protectJob = GlobalScope.launch(Dispatchers.IO) {
val localSocket = LocalSocket()
localSocket.bind(
LocalSocketAddress(
protectPath,
LocalSocketAddress.Namespace.FILESYSTEM
)
)
val socket = LocalServerSocket(localSocket.fileDescriptor)
val buffer = ByteBuffer.allocate(4)
while (true) {
val stream = socket.accept()
buffer.clear()
val n = stream.inputStream.read(buffer.array())
if (n == 4) {
val fd = buffer.int
if (!super.protect(fd)) {
println("protect failed")
}
buffer.clear()
buffer.putInt(0)
} else {
buffer.clear()
buffer.putInt(1)
}
stream.outputStream.write(buffer.array())
}
}
val protectPath = ""
AccVpn.writeConfig(this, conn.fd, profile)
thread(start = true) {
AccVpnService.instance.runAcc(
AccVpn.configFile(this).absolutePath,
protectPath,
NetworkAdapter.JNI_CLAZZ_NAME,
VpnNativeDispatcher.JNI_CLAZZ_NAME,
AccVpn.configFile(this).absolutePath,
protectPath,
NetworkAdapter.JNI_CLAZZ_NAME,
VpnNativeDispatcher.JNI_CLAZZ_NAME,
)
}
// val cmd = arrayListOf(File(applicationInfo.nativeLibraryDir, Executable.TUN2SOCKS).absolutePath,
......
......@@ -117,7 +117,7 @@ object DataStore : OnPreferenceDataStoreChangeListener {
get() = privateStore.getInt(Key.pingProxyPort) ?: 0
set(value) = privateStore.putInt(Key.pingProxyPort, value)
var pingIntervalSec: Int
get() = privateStore.getInt(Key.pingIntervalSec) ?: 3
get() = privateStore.getInt(Key.pingIntervalSec) ?: 1
set(value) = privateStore.putInt(Key.pingIntervalSec, value)
var pingTimeoutMillis: Int
get() = privateStore.getInt(Key.pingTimeoutMillis) ?: 200
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment