content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package com.softyorch.firelogin.ui.detail
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.softyorch.firelogin.data.AuthService
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class DetailsViewModel @Inject constructor(private val authService: AuthService) : ViewModel() {
fun logout(navigateToLogin: () -> Unit) {
viewModelScope.launch(Dispatchers.IO) {
authService.logout()
}
navigateToLogin()
}
} | FireLogin/app/src/main/java/com/softyorch/firelogin/ui/detail/DetailsViewModel.kt | 1560058087 |
package com.softyorch.firelogin.ui.login
sealed class OAuthLogin {
object GitHub: OAuthLogin()
object Microsoft: OAuthLogin()
object Twitter: OAuthLogin()
object Yahoo: OAuthLogin()
}
| FireLogin/app/src/main/java/com/softyorch/firelogin/ui/login/OAuthLogin.kt | 4113481572 |
package com.softyorch.firelogin.ui.login
sealed class PhoneVerification {
object CodeSend: PhoneVerification()
object VerifiedPhoneComplete: PhoneVerification()
data class VerifiedPhoneFailure(val msg: String): PhoneVerification()
}
| FireLogin/app/src/main/java/com/softyorch/firelogin/ui/login/PhoneVerification.kt | 3454095374 |
package com.softyorch.firelogin.ui.login
import android.app.Activity
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.facebook.AccessToken
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.firebase.FirebaseException
import com.google.firebase.auth.PhoneAuthCredential
import com.google.firebase.auth.PhoneAuthProvider
import com.softyorch.firelogin.data.AuthService
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject
@HiltViewModel
class LoginViewModel @Inject constructor(private val authService: AuthService) : ViewModel() {
private var _isLoading = MutableStateFlow(false)
val isLoading: StateFlow<Boolean> = _isLoading
private lateinit var verificationCode: String
fun onStandardLoginSelected(user: String, pass: String, navigateToDetails: () -> Unit) {
if (user.isNotEmpty() && pass.isNotEmpty()) {
viewModelScope.launch {
_isLoading.update { true }
val result = withContext(Dispatchers.IO) {
authService.login(user, pass)
}
if (result != null) {
navigateToDetails()
}
_isLoading.update { false }
}
}
}
fun onAnonymouslyLoginSelected(navigateToDetails: () -> Unit) {
viewModelScope.launch {
_isLoading.update { true }
val result = withContext(Dispatchers.IO) {
authService.loginAnonymously()
}
if (result != null) {
navigateToDetails()
}
_isLoading.update { false }
}
}
fun onPhoneLoginSelected(
phoneNumber: String,
activity: Activity,
onCallback: (PhoneVerification) -> Unit
) {
if (phoneNumber.isNotEmpty()) viewModelScope.launch {
_isLoading.update { true }
val callback = onVerificationStateChangedCallbacks(onCallback)
withContext(Dispatchers.IO) {
authService.loginWithPhone(phoneNumber, activity, callback)
}
_isLoading.update { false }
}
}
fun onLoginGoogleSelected(idToken: String, navigateToDetails: () -> Unit) {
viewModelScope.launch {
_isLoading.update { true }
val result = withContext(Dispatchers.IO) {
authService.loginWithGoogle(idToken)
}
if (result != null) {
navigateToDetails()
}
_isLoading.update { false }
}
}
fun onGoogleLoginSelected(googleLauncherLogin: (GoogleSignInClient) -> Unit) {
val gsc = authService.getGoogleClient()
googleLauncherLogin(gsc)
}
fun onFacebookLoginSelected(accessToken: AccessToken, navigateToDetail: () -> Unit) {
viewModelScope.launch {
_isLoading.update { true }
val result = withContext(Dispatchers.IO) {
authService.loginWithFacebook(accessToken)
}
if (result != null) {
navigateToDetail()
}
_isLoading.update { false }
}
}
fun onOauthLoginSelected(oauthLogin: OAuthLogin, activity: Activity, navigateToDetails: () -> Unit) {
viewModelScope.launch {
_isLoading.update { true }
val result = withContext(Dispatchers.IO) {
when (oauthLogin) {
OAuthLogin.GitHub -> authService.loginWithGitHub(activity)
OAuthLogin.Microsoft -> authService.loginWithMicrosoft(activity)
OAuthLogin.Twitter -> authService.loginWithTwitter(activity)
OAuthLogin.Yahoo -> authService.loginWithYahoo(activity)
}
}
if (result != null) {
navigateToDetails()
}
_isLoading.update { false }
}
}
fun verifyCode(phoneCode: String, onSuccessVerification: () -> Unit) {
viewModelScope.launch {
val result = withContext(Dispatchers.IO) {
authService.verifyCode(verificationCode, phoneCode)
}
if (result != null) {
onSuccessVerification()
}
}
}
private fun onVerificationStateChangedCallbacks(onCallback: (PhoneVerification) -> Unit) =
object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
override fun onVerificationCompleted(credentials: PhoneAuthCredential) {
viewModelScope.launch {
val result = withContext(Dispatchers.IO) {
authService.completeRegisterWithPhoneVerification(credentials)
}
if (result != null) {
onCallback(PhoneVerification.VerifiedPhoneComplete)
}
}
}
override fun onVerificationFailed(exception: FirebaseException) {
_isLoading.update { false }
onCallback(PhoneVerification.VerifiedPhoneFailure(exception.message.orEmpty()))
}
override fun onCodeSent(
verificationCode: String,
p1: PhoneAuthProvider.ForceResendingToken
) {
_isLoading.update { false }
[email protected] = verificationCode
onCallback(PhoneVerification.CodeSend)
}
}
}
| FireLogin/app/src/main/java/com/softyorch/firelogin/ui/login/LoginViewModel.kt | 1635419541 |
package com.softyorch.firelogin.ui.login
import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.core.widget.doOnTextChanged
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.facebook.CallbackManager
import com.facebook.FacebookCallback
import com.facebook.FacebookException
import com.facebook.login.LoginManager
import com.facebook.login.LoginResult
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.common.api.ApiException
import com.softyorch.firelogin.databinding.ActivityLoginBinding
import com.softyorch.firelogin.databinding.DialogPhoneLoginBinding
import com.softyorch.firelogin.ui.detail.DetailActivity
import com.softyorch.firelogin.ui.signup.SignUpActivity
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
@AndroidEntryPoint
class LoginActivity : AppCompatActivity() {
private val viewModel: LoginViewModel by viewModels()
private lateinit var binding: ActivityLoginBinding
private lateinit var callbackManager: CallbackManager
private val googleLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
if (result.resultCode == Activity.RESULT_OK) {
val task = GoogleSignIn.getSignedInAccountFromIntent(result.data)
try {
val account = task.getResult(ApiException::class.java)!!
viewModel.onLoginGoogleSelected(account.idToken!!) {
navigateToDetail()
binding.pbLoading.isGone = true
}
} catch (ex: ApiException) {
showToast("Ha ocurrido un error: ${ex.message}")
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityLoginBinding.inflate(layoutInflater)
setContentView(binding.root)
initUI()
}
private fun initUI() {
initListeners()
initUiState()
}
private fun initUiState() {
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.isLoading.collect { show ->
binding.apply {
pbLoading.isVisible = show
btnLogin.isEnabled = !show
btnLoginGoogle.isEnabled = !show
btnLoginFacebook.isEnabled = !show
btnLoginGitHub.isEnabled = !show
btnLoginAnonymously.isEnabled = !show
btnLoginMicrosoft.isEnabled = !show
btnLoginTwitter.isEnabled = !show
btnLoginYahoo.isEnabled = !show
btnLoginPhone.isEnabled = !show
}
}
}
}
}
private fun initListeners() {
binding.apply {
btnLogin.setOnClickListener {
viewModel.onStandardLoginSelected(
user = binding.tieUser.text.toString(),
pass = binding.tiePass.text.toString()
) {
navigateToDetail()
}
}
tvSignUp.setOnClickListener {
navigateToSignUp()
}
btnLoginPhone.setOnClickListener {
showPhoneLogin()
}
btnLoginGoogle.setOnClickListener {
viewModel.onGoogleLoginSelected { gsc ->
pbLoading.isVisible = true
googleLauncher.launch(gsc.signInIntent)
}
}
//Facebook
LoginManager.getInstance().apply {
[email protected] = CallbackManager.Factory.create()
registerCallback(
[email protected],
object : FacebookCallback<LoginResult> {
override fun onCancel() {
showToast("Prbamos con otra red social?")
}
override fun onError(error: FacebookException) {
showToast("Ha ocurrido un error ${error.message}")
}
override fun onSuccess(result: LoginResult) {
viewModel.onFacebookLoginSelected(result.accessToken) {
navigateToDetail()
}
}
}
)
btnLoginFacebook.setOnClickListener {
logInWithReadPermissions(
activityResultRegistryOwner = this@LoginActivity,
callbackManager = [email protected],
permissions = listOf("email", "public_profile")
)
}
}
//Facebook end
btnLoginAnonymously.setOnClickListener {
viewModel.onAnonymouslyLoginSelected {
navigateToDetail()
}
}
btnLoginGitHub.setOnClickListener {
viewModel.onOauthLoginSelected(OAuthLogin.GitHub, this@LoginActivity) {
navigateToDetail()
}
}
btnLoginMicrosoft.setOnClickListener {
viewModel.onOauthLoginSelected(OAuthLogin.Microsoft, this@LoginActivity) {
navigateToDetail()
}
}
btnLoginTwitter.setOnClickListener {
viewModel.onOauthLoginSelected(OAuthLogin.Twitter, this@LoginActivity) {
navigateToDetail()
}
}
btnLoginYahoo.setOnClickListener {
viewModel.onOauthLoginSelected(OAuthLogin.Yahoo, this@LoginActivity) {
navigateToDetail()
}
}
}
}
private fun showPhoneLogin() {
val phoneBinding = DialogPhoneLoginBinding.inflate(layoutInflater)
val alertDialog = AlertDialog.Builder(this).apply { setView(phoneBinding.root) }.create()
phoneBinding.apply {
btnPhone.setOnClickListener {
pbLoading.isVisible = true
tiePhone.isEnabled = false
btnPhone.isEnabled = false
btnPhone.setTextColor(Color.WHITE)
viewModel.onPhoneLoginSelected(
phoneNumber = tiePhone.text.toString(),
activity = this@LoginActivity
) { phoneVerification ->
when (phoneVerification) {
PhoneVerification.CodeSend -> {
tvHeader.isGone = true
tvPinCode.isVisible = true
pinView.isVisible = true
pbLoading.isGone = true
tiePhone.isGone = true
btnPhone.isGone = true
pinView.requestFocus()
val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(pinView, InputMethodManager.SHOW_IMPLICIT)
}
PhoneVerification.VerifiedPhoneComplete -> navigateToDetail()
is PhoneVerification.VerifiedPhoneFailure -> showToast("Error al validar el teléfono: ${phoneVerification.msg}")
}
}
}
pinView.doOnTextChanged { text, _, _, _ ->
if (text?.length == 6) {
viewModel.verifyCode(text.toString()) {
navigateToDetail()
}
}
}
}
alertDialog.apply {
show()
window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
}
}
private fun navigateToSignUp() {
startActivity(Intent(this, SignUpActivity::class.java))
}
private fun navigateToDetail() {
startActivity(Intent(this, DetailActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
})
}
private fun showToast(text: String) {
Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
}
} | FireLogin/app/src/main/java/com/softyorch/firelogin/ui/login/LoginActivity.kt | 4019716507 |
package com.softyorch.firelogin.di
import com.google.firebase.auth.FirebaseAuth
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
@Singleton
@Provides
fun provideFirebaseAuth() = FirebaseAuth.getInstance()
} | FireLogin/app/src/main/java/com/softyorch/firelogin/di/NetworkModule.kt | 2873896365 |
package com.softyorch.firelogin.data
import android.app.Activity
import android.content.Context
import com.facebook.AccessToken
import com.facebook.login.LoginManager
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.firebase.auth.AuthCredential
import com.google.firebase.auth.FacebookAuthProvider
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.auth.GoogleAuthProvider
import com.google.firebase.auth.OAuthProvider
import com.google.firebase.auth.PhoneAuthOptions
import com.google.firebase.auth.PhoneAuthProvider
import com.softyorch.firelogin.R
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.CancellableContinuation
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.tasks.await
import java.util.concurrent.TimeUnit
import javax.inject.Inject
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
class AuthService @Inject constructor(
private val firebaseAuth: FirebaseAuth,
@ApplicationContext private val context: Context
) {
suspend fun login(user: String, pass: String): FirebaseUser? =
firebaseAuth.signInWithEmailAndPassword(user, pass).await().user
suspend fun loginAnonymously(): FirebaseUser? = firebaseAuth.signInAnonymously().await().user
fun loginWithPhone(
phoneNumber: String,
activity: Activity,
callback: PhoneAuthProvider.OnVerificationStateChangedCallbacks
) {
//Solo para pruebas para evitar la creación de la cuenta.
//firebaseAuth.firebaseAuthSettings.setAutoRetrievedSmsCodeForPhoneNumber("+34 123456789", "123456")
val options = PhoneAuthOptions
.newBuilder(firebaseAuth)
.setPhoneNumber(phoneNumber)
.setTimeout(60L, TimeUnit.SECONDS)
.setActivity(activity)
.setCallbacks(callback)
.build()
PhoneAuthProvider.verifyPhoneNumber(options)
}
suspend fun loginWithGoogle(idToken: String): FirebaseUser? {
val credentials = GoogleAuthProvider.getCredential(idToken, null)
return completeRegisterWithCredentials(credentials)
}
suspend fun loginWithFacebook(accessToken: AccessToken): FirebaseUser? {
val credentials = FacebookAuthProvider.getCredential(accessToken.token)
return completeRegisterWithCredentials(credentials)
}
suspend fun loginWithGitHub(activity: Activity): FirebaseUser? {
val provider = OAuthProvider.newBuilder("github.com").apply {
scopes = listOf("user:email")
}.build()
return initRegisterWithProvider(activity, provider)
}
suspend fun loginWithMicrosoft(activity: Activity): FirebaseUser? {
val provider = OAuthProvider.newBuilder("microsoft.com").apply {
scopes = listOf("mail.read", "calendars.read")
}.build()
return initRegisterWithProvider(activity, provider)
}
suspend fun loginWithTwitter(activity: Activity): FirebaseUser? {
val provider = OAuthProvider.newBuilder("twitter.com").build()
return initRegisterWithProvider(activity, provider)
}
suspend fun loginWithYahoo(activity: Activity): FirebaseUser? {
val provider = OAuthProvider.newBuilder("yahoo.com").build()
return initRegisterWithProvider(activity, provider)
}
suspend fun signUp(email: String, pass: String): FirebaseUser? =
suspendCancellableCoroutine { cancellableContinuation ->
firebaseAuth.createUserWithEmailAndPassword(email, pass)
.addOnSuccessListener {
cancellableContinuation.resume(it.user)
}
.addOnFailureListener { except ->
cancellableContinuation.resumeWithException(except)
}
}
fun logout() {
firebaseAuth.signOut()
getGoogleClient().signOut()
LoginManager.getInstance().logOut()
}
fun getGoogleClient(): GoogleSignInClient {
// cuando llamamos la primera vez a R.string.default_web_client_id no existe, pero al terminar el build y buildear la
// app se autogenera dicho string
val gso = GoogleSignInOptions
.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(context.getString(R.string.default_web_client_id))
.requestEmail()
.build()
return GoogleSignIn.getClient(context, gso)
}
suspend fun completeRegisterWithPhoneVerification(credentials: AuthCredential): FirebaseUser? =
completeRegisterWithCredentials(credentials)
fun isUserLogged(): Boolean = getCurrentUser() != null
suspend fun verifyCode(verificationCode: String, phoneCode: String): FirebaseUser? {
val credentials = PhoneAuthProvider.getCredential(verificationCode, phoneCode)
return completeRegisterWithCredentials(credentials)
}
private suspend fun completeRegisterWithCredentials(credentials: AuthCredential): FirebaseUser? =
suspendCancellableCoroutine { cancellableContinuation ->
firebaseAuth.signInWithCredential(credentials)
.addOnSuccessListener { authResult ->
cancellableContinuation.resume(authResult.user)
}
.addOnFailureListener { ex ->
cancellableContinuation.resumeWithException(ex)
}
}
private suspend fun initRegisterWithProvider(
activity: Activity,
provider: OAuthProvider
): FirebaseUser? {
return suspendCancellableCoroutine { cancellableContinuation ->
firebaseAuth.pendingAuthResult?.addOnSuccessListener { authResult ->
cancellableContinuation.resume(authResult.user)
}?.addOnFailureListener { ex ->
cancellableContinuation.resumeWithException(ex)
} ?: completeRegisterWithProvider(activity, provider, cancellableContinuation)
}
}
private fun completeRegisterWithProvider(
activity: Activity,
provider: OAuthProvider,
cancellableContinuation: CancellableContinuation<FirebaseUser?>
) {
firebaseAuth.startActivityForSignInWithProvider(activity, provider)
.addOnSuccessListener { authResume ->
cancellableContinuation.resume(authResume.user)
}.addOnFailureListener { ex ->
cancellableContinuation.resumeWithException(ex)
}
}
private fun getCurrentUser() = firebaseAuth.currentUser
}
| FireLogin/app/src/main/java/com/softyorch/firelogin/data/AuthService.kt | 228864580 |
package com.softyorch.firelogin
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class FireLoginApp: Application()
| FireLogin/app/src/main/java/com/softyorch/firelogin/FireLoginApp.kt | 2582471821 |
package com.narcis.application
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.narcis.application", appContext.packageName)
}
} | Ving-Vpn/app/src/androidTest/java/com/narcis/application/ExampleInstrumentedTest.kt | 198503403 |
package com.narcis.application
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | Ving-Vpn/app/src/test/java/com/narcis/application/ExampleUnitTest.kt | 4229791762 |
package com.narcis.application.presentation.utiles
import org.junit.Test
class VerificationUtilKtTest {
private val mockEmail = "[email protected]"
@Test
fun isValidEmail() {
}
@Test
fun longToast() {
}
@Test
fun shortToast() {
}
} | Ving-Vpn/app/src/test/java/com/narcis/application/presentation/utiles/VerificationUtilKtTest.kt | 2292601591 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.database
import androidx.room.Delete
import androidx.room.Entity
import androidx.room.Insert
import androidx.room.PrimaryKey
import androidx.room.Query
import androidx.room.Update
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.GroupOrder
import io.nekohasekai.sagernet.GroupType
import com.narcis.application.presentation.connection.applyDefaultValues
import com.esotericsoftware.kryo.io.ByteBufferInput
import com.esotericsoftware.kryo.io.ByteBufferOutput
import io.nekohasekai.sagernet.ftm.Serializable
import io.nekohasekai.sagernet.ktx.app
@Entity(tableName = "proxy_groups")
data class ProxyGroup(
@PrimaryKey(autoGenerate = true) var id: Long = 0L,
var userOrder: Long = 0L,
var ungrouped: Boolean = false,
var name: String? = null,
var type: Int = GroupType.BASIC,
var subscription: SubscriptionBean? = null,
var order: Int = GroupOrder.ORIGIN,
) : io.nekohasekai.sagernet.ftm.Serializable() {
@Transient
var export = false
override fun initializeDefaultValues() {
subscription?.applyDefaultValues()
}
override fun serializeToBuffer(output: ByteBufferOutput) {
if (export) {
output.writeInt(0)
output.writeString(name)
output.writeInt(type)
val subscription = subscription!!
subscription.serializeForShare(output)
} else {
output.writeInt(0)
output.writeLong(id)
output.writeLong(userOrder)
output.writeBoolean(ungrouped)
output.writeString(name)
output.writeInt(type)
if (type == GroupType.SUBSCRIPTION) {
subscription?.serializeToBuffer(output)
}
output.writeInt(order)
}
}
override fun deserializeFromBuffer(input: ByteBufferInput) {
if (export) {
val version = input.readInt()
name = input.readString()
type = input.readInt()
val subscription =
SubscriptionBean()
this.subscription = subscription
subscription.deserializeFromShare(input)
} else {
val version = input.readInt()
id = input.readLong()
userOrder = input.readLong()
ungrouped = input.readBoolean()
name = input.readString()
type = input.readInt()
if (type == GroupType.SUBSCRIPTION) {
val subscription =
SubscriptionBean()
this.subscription = subscription
subscription.deserializeFromBuffer(input)
}
order = input.readInt()
}
}
fun displayName(): String {
return name.takeIf { !it.isNullOrBlank() } ?: app.getString(R.string.group_default)
}
@androidx.room.Dao
interface Dao {
@Query("SELECT * FROM proxy_groups ORDER BY userOrder")
fun allGroups(): List<ProxyGroup>
@Query("SELECT * FROM proxy_groups WHERE type = ${GroupType.SUBSCRIPTION}")
suspend fun subscriptions(): List<ProxyGroup>
@Query("SELECT MAX(userOrder) + 1 FROM proxy_groups")
fun nextOrder(): Long?
@Query("SELECT * FROM proxy_groups WHERE id = :groupId")
fun getById(groupId: Long): ProxyGroup?
@Query("DELETE FROM proxy_groups WHERE id = :groupId")
fun deleteById(groupId: Long): Int
@Delete
fun deleteGroup(group: ProxyGroup)
@Delete
fun deleteGroup(groupList: List<ProxyGroup>)
@Insert
fun createGroup(group: ProxyGroup): Long
@Update
fun updateGroup(group: ProxyGroup)
@Query("DELETE FROM proxy_groups")
fun reset()
@Insert
fun insert(groupList: List<ProxyGroup>)
}
companion object {
@JvmField
val CREATOR = object : Serializable.CREATOR<ProxyGroup>() {
override fun newInstance(): ProxyGroup {
return ProxyGroup()
}
override fun newArray(size: Int): Array<ProxyGroup?> {
return arrayOfNulls(size)
}
}
}
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/database/ProxyGroup.kt | 66720702 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* Copyright (C) 2021 by Max Lv <[email protected]> *
* Copyright (C) 2021 by Mygod Studio <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.database
import android.os.Binder
import android.os.Build
import androidx.preference.PreferenceDataStore
import moe.matsuri.nya.TempDatabase
import io.nekohasekai.sagernet.CONNECTION_TEST_URL
import io.nekohasekai.sagernet.GroupType
import io.nekohasekai.sagernet.IPv6Mode
import io.nekohasekai.sagernet.Key
import io.nekohasekai.sagernet.SagerNet
import io.nekohasekai.sagernet.bg.BaseService
import io.nekohasekai.sagernet.database.preference.OnPreferenceDataStoreChangeListener
import io.nekohasekai.sagernet.database.preference.PublicDatabase
import io.nekohasekai.sagernet.database.preference.RoomPreferenceDataStore
import io.nekohasekai.sagernet.ktx.boolean
import io.nekohasekai.sagernet.ktx.int
import io.nekohasekai.sagernet.ktx.long
import io.nekohasekai.sagernet.ktx.parsePort
import io.nekohasekai.sagernet.ktx.string
import io.nekohasekai.sagernet.ktx.stringSet
import io.nekohasekai.sagernet.ktx.stringToInt
import io.nekohasekai.sagernet.ktx.stringToIntIfExists
object DataStore : OnPreferenceDataStoreChangeListener {
// share service state in main process
@Volatile
var serviceState = BaseService.State.Idle
val configurationStore = RoomPreferenceDataStore(PublicDatabase.kvPairDao)
val profileCacheStore = RoomPreferenceDataStore(TempDatabase.profileCacheDao)
fun init() {
if (Build.VERSION.SDK_INT >= 24) {
SagerNet.application.moveDatabaseFrom(SagerNet.deviceStorage, Key.DB_PUBLIC)
}
}
// last used, but may not be running
var currentProfile by configurationStore.long(Key.PROFILE_CURRENT)
var selectedProxy by configurationStore.long(Key.PROFILE_ID)
var selectedGroup by configurationStore.long(Key.PROFILE_GROUP) { currentGroupId() } // "ungrouped" group id = 1
fun currentGroupId(): Long {
val currentSelected = configurationStore.getLong(Key.PROFILE_GROUP, -1)
if (currentSelected > 0L) return currentSelected
val groups = SagerDatabase.groupDao.allGroups()
if (groups.isNotEmpty()) {
val groupId = groups[0].id
selectedGroup = groupId
return groupId
}
val groupId = SagerDatabase.groupDao.createGroup(ProxyGroup(ungrouped = true))
selectedGroup = groupId
return groupId
}
fun currentGroup(): ProxyGroup {
var group: ProxyGroup? = null
val currentSelected = configurationStore.getLong(Key.PROFILE_GROUP, -1)
if (currentSelected > 0L) {
group = SagerDatabase.groupDao.getById(currentSelected)
}
if (group != null) return group
val groups = SagerDatabase.groupDao.allGroups()
if (groups.isEmpty()) {
group = ProxyGroup(ungrouped = true).apply {
id = SagerDatabase.groupDao.createGroup(this)
}
} else {
group = groups[0]
}
selectedGroup = group.id
return group
}
fun selectedGroupForImport(): Long {
val current = currentGroup()
if (current.type == GroupType.BASIC) return current.id
val groups = SagerDatabase.groupDao.allGroups()
return groups.find { it.type == GroupType.BASIC }!!.id
}
var nekoPlugins by configurationStore.string(Key.NEKO_PLUGIN_MANAGED)
var exePreferProvider by configurationStore.stringToInt(Key.EXE_PREFER_PROVIDER)
var appTLSVersion by configurationStore.string(Key.APP_TLS_VERSION)
//
var isExpert by configurationStore.boolean(Key.APP_EXPERT)
var appTheme by configurationStore.int(Key.APP_THEME)
var nightTheme by configurationStore.stringToInt(Key.NIGHT_THEME)
var serviceMode by configurationStore.string(Key.SERVICE_MODE) { Key.MODE_VPN }
var domainStrategy by configurationStore.string(Key.DOMAIN_STRATEGY) { "AsIs" }
var trafficSniffing by configurationStore.boolean(Key.TRAFFIC_SNIFFING) { true }
var resolveDestination by configurationStore.boolean(Key.RESOLVE_DESTINATION)
var tcpKeepAliveInterval by configurationStore.stringToInt(Key.TCP_KEEP_ALIVE_INTERVAL) { 15 }
var mtu by configurationStore.stringToInt(Key.MTU) { 9000 }
var bypassLan by configurationStore.boolean(Key.BYPASS_LAN)
var bypassLanInCore by configurationStore.boolean(Key.BYPASS_LAN_IN_CORE)
var allowAccess by configurationStore.boolean(Key.ALLOW_ACCESS)
var speedInterval by configurationStore.stringToInt(Key.SPEED_INTERVAL)
var showGroupInNotification by configurationStore.boolean("showGroupInNotification")
var enhanceDomain by configurationStore.boolean(Key.ENHANCE_RESOLVE_SERVER_DOMAIN)
var remoteDns by configurationStore.string(Key.REMOTE_DNS) { "https://8.8.8.8/dns-query" }
var directDns by configurationStore.string(Key.DIRECT_DNS) { "https+local://223.5.5.5/dns-query" }
var directDnsUseSystem by configurationStore.boolean(Key.DIRECT_DNS_USE_SYSTEM)
var enableDnsRouting by configurationStore.boolean(Key.ENABLE_DNS_ROUTING) { true }
var enableFakeDns by configurationStore.boolean(Key.ENABLE_FAKEDNS)
var hosts by configurationStore.string(Key.DNS_HOSTS)
var dnsNetwork by configurationStore.stringSet(Key.DNS_NETWORK)
val securityAdvisory = false
var rulesProvider by configurationStore.stringToInt(Key.RULES_PROVIDER)
var enableLog by configurationStore.boolean(Key.ENABLE_LOG)
var logBufSize by configurationStore.int(Key.LOG_BUF_SIZE) { 0 }
var acquireWakeLock by configurationStore.boolean(Key.ACQUIRE_WAKE_LOCK)
var showBottomBar by configurationStore.boolean(Key.SHOW_BOTTOM_BAR)
// hopefully hashCode = mHandle doesn't change, currently this is true from KitKat to Nougat
private val userIndex by lazy { Binder.getCallingUserHandle().hashCode() }
var socksPort: Int
get() = getLocalPort(Key.SOCKS_PORT, 2080)
set(value) = saveLocalPort(Key.SOCKS_PORT, value)
var localDNSPort: Int
get() = getLocalPort(Key.LOCAL_DNS_PORT, 6450)
set(value) {
saveLocalPort(Key.LOCAL_DNS_PORT, value)
}
var httpPort: Int
get() = getLocalPort(Key.HTTP_PORT, 9080)
set(value) = saveLocalPort(Key.HTTP_PORT, value)
var transproxyPort: Int
get() = getLocalPort(Key.TRANSPROXY_PORT, 9200)
set(value) = saveLocalPort(Key.TRANSPROXY_PORT, value)
fun initGlobal() {
if (configurationStore.getString(Key.SOCKS_PORT) == null) {
socksPort = socksPort
}
if (configurationStore.getString(Key.LOCAL_DNS_PORT) == null) {
localDNSPort = localDNSPort
}
if (configurationStore.getString(Key.HTTP_PORT) == null) {
httpPort = httpPort
}
if (configurationStore.getString(Key.TRANSPROXY_PORT) == null) {
transproxyPort = transproxyPort
}
}
private fun getLocalPort(key: String, default: Int): Int {
return parsePort(configurationStore.getString(key), default + userIndex)
}
private fun saveLocalPort(key: String, value: Int) {
configurationStore.putString(key, "$value")
}
var ipv6Mode by configurationStore.stringToInt(Key.IPV6_MODE) { IPv6Mode.DISABLE }
var meteredNetwork by configurationStore.boolean(Key.METERED_NETWORK)
var proxyApps by configurationStore.boolean(Key.PROXY_APPS)
var bypass by configurationStore.boolean(Key.BYPASS_MODE) { true }
var individual by configurationStore.string(Key.INDIVIDUAL)
var showDirectSpeed by configurationStore.boolean(Key.SHOW_DIRECT_SPEED) { true }
val persistAcrossReboot by configurationStore.boolean(Key.PERSIST_ACROSS_REBOOT) { false }
var requireHttp by configurationStore.boolean(Key.REQUIRE_HTTP) { true }
var appendHttpProxy by configurationStore.boolean(Key.APPEND_HTTP_PROXY) { true }
var requireTransproxy by configurationStore.boolean(Key.REQUIRE_TRANSPROXY)
var transproxyMode by configurationStore.stringToInt(Key.TRANSPROXY_MODE)
var connectionTestURL by configurationStore.string(Key.CONNECTION_TEST_URL) { CONNECTION_TEST_URL }
var connectionTestConcurrent by configurationStore.int("connectionTestConcurrent") { 5 }
var alwaysShowAddress by configurationStore.boolean(Key.ALWAYS_SHOW_ADDRESS)
var appTrafficStatistics by configurationStore.boolean(Key.APP_TRAFFIC_STATISTICS)
var profileTrafficStatistics by configurationStore.boolean(Key.PROFILE_TRAFFIC_STATISTICS) { true }
// protocol
var muxProtocols by configurationStore.stringSet(Key.MUX_PROTOCOLS)
var muxConcurrency by configurationStore.stringToInt(Key.MUX_CONCURRENCY) { 8 }
// cache
var dirty by profileCacheStore.boolean(Key.PROFILE_DIRTY)
var editingId by profileCacheStore.long(Key.PROFILE_ID)
var editingGroup by profileCacheStore.long(Key.PROFILE_GROUP)
var profileName by profileCacheStore.string(Key.PROFILE_NAME)
var serverAddress by profileCacheStore.string(Key.SERVER_ADDRESS)
var serverPort by profileCacheStore.stringToInt(Key.SERVER_PORT)
var serverUsername by profileCacheStore.string(Key.SERVER_USERNAME)
var serverPassword by profileCacheStore.string(Key.SERVER_PASSWORD)
var serverPassword1 by profileCacheStore.string(Key.SERVER_PASSWORD1)
var serverMethod by profileCacheStore.string(Key.SERVER_METHOD)
var serverPlugin by profileCacheStore.string(Key.SERVER_PLUGIN)
var sharedStorage by profileCacheStore.string("sharedStorage")
var serverProtocol by profileCacheStore.string(Key.SERVER_PROTOCOL)
var serverProtocolParam by profileCacheStore.string(Key.SERVER_PROTOCOL_PARAM)
var serverObfs by profileCacheStore.string(Key.SERVER_OBFS)
var serverObfsParam by profileCacheStore.string(Key.SERVER_OBFS_PARAM)
var serverUserId by profileCacheStore.string(Key.SERVER_USER_ID)
var serverAlterId by profileCacheStore.stringToInt(Key.SERVER_ALTER_ID)
var serverSecurity by profileCacheStore.string(Key.SERVER_SECURITY)
var serverNetwork by profileCacheStore.string(Key.SERVER_NETWORK)
var serverHeader by profileCacheStore.string(Key.SERVER_HEADER)
var serverHost by profileCacheStore.string(Key.SERVER_HOST)
var serverPath by profileCacheStore.string(Key.SERVER_PATH)
var serverSNI by profileCacheStore.string(Key.SERVER_SNI)
var serverEncryption by profileCacheStore.string(Key.SERVER_ENCRYPTION)
var serverALPN by profileCacheStore.string(Key.SERVER_ALPN)
var serverCertificates by profileCacheStore.string(Key.SERVER_CERTIFICATES)
var serverPinnedCertificateChain by profileCacheStore.string(Key.SERVER_PINNED_CERTIFICATE_CHAIN)
var serverQuicSecurity by profileCacheStore.string(Key.SERVER_QUIC_SECURITY)
var serverWsMaxEarlyData by profileCacheStore.stringToInt(Key.SERVER_WS_MAX_EARLY_DATA)
var serverWsBrowserForwarding by profileCacheStore.boolean(Key.SERVER_WS_BROWSER_FORWARDING)
var serverEarlyDataHeaderName by profileCacheStore.string(Key.SERVER_EARLY_DATA_HEADER_NAME)
var serverHeaders by profileCacheStore.string(Key.SERVER_HEADERS)
var serverAllowInsecure by profileCacheStore.boolean(Key.SERVER_ALLOW_INSECURE)
var serverPacketEncoding by profileCacheStore.stringToInt(Key.SERVER_PACKET_ENCODING)
var utlsFingerprint by profileCacheStore.string("utlsFingerprint")
var serverVMessExperimentalAuthenticatedLength by profileCacheStore.boolean(Key.SERVER_VMESS_EXPERIMENTAL_AUTHENTICATED_LENGTH)
var serverVMessExperimentalNoTerminationSignal by profileCacheStore.boolean(Key.SERVER_VMESS_EXPERIMENTAL_NO_TERMINATION_SIGNAL)
var serverAuthType by profileCacheStore.stringToInt(Key.SERVER_AUTH_TYPE)
var serverUploadSpeed by profileCacheStore.stringToInt(Key.SERVER_UPLOAD_SPEED)
var serverDownloadSpeed by profileCacheStore.stringToInt(Key.SERVER_DOWNLOAD_SPEED)
var serverStreamReceiveWindow by profileCacheStore.stringToIntIfExists(Key.SERVER_STREAM_RECEIVE_WINDOW)
var serverConnectionReceiveWindow by profileCacheStore.stringToIntIfExists(Key.SERVER_CONNECTION_RECEIVE_WINDOW)
var serverMTU by profileCacheStore.stringToInt(Key.SERVER_MTU) { 1420 }
var serverDisableMtuDiscovery by profileCacheStore.boolean(Key.SERVER_DISABLE_MTU_DISCOVERY)
var serverHopInterval by profileCacheStore.stringToInt(Key.SERVER_HOP_INTERVAL) { 10 }
var serverProtocolVersion by profileCacheStore.stringToInt(Key.SERVER_PROTOCOL)
var serverPrivateKey by profileCacheStore.string(Key.SERVER_PRIVATE_KEY)
var serverLocalAddress by profileCacheStore.string(Key.SERVER_LOCAL_ADDRESS)
var serverInsecureConcurrency by profileCacheStore.stringToInt(Key.SERVER_INSECURE_CONCURRENCY)
var serverReducedIvHeadEntropy by profileCacheStore.boolean(Key.SERVER_REDUCED_IV_HEAD_ENTROPY)
var serverUDPRelayMode by profileCacheStore.string(Key.SERVER_UDP_RELAY_MODE)
var serverCongestionController by profileCacheStore.string(Key.SERVER_CONGESTION_CONTROLLER)
var serverDisableSNI by profileCacheStore.boolean(Key.SERVER_DISABLE_SNI)
var serverReduceRTT by profileCacheStore.boolean(Key.SERVER_REDUCE_RTT)
var serverFastConnect by profileCacheStore.boolean(Key.SERVER_FAST_CONNECT)
var routeName by profileCacheStore.string(Key.ROUTE_NAME)
var routeDomain by profileCacheStore.string(Key.ROUTE_DOMAIN)
var routeIP by profileCacheStore.string(Key.ROUTE_IP)
var routePort by profileCacheStore.string(Key.ROUTE_PORT)
var routeSourcePort by profileCacheStore.string(Key.ROUTE_SOURCE_PORT)
var routeNetwork by profileCacheStore.string(Key.ROUTE_NETWORK)
var routeSource by profileCacheStore.string(Key.ROUTE_SOURCE)
var routeProtocol by profileCacheStore.string(Key.ROUTE_PROTOCOL)
var routeAttrs by profileCacheStore.string(Key.ROUTE_ATTRS)
var routeOutbound by profileCacheStore.stringToInt(Key.ROUTE_OUTBOUND)
var routeOutboundRule by profileCacheStore.long(Key.ROUTE_OUTBOUND_RULE)
var routeReverse by profileCacheStore.boolean(Key.ROUTE_REVERSE)
var routeRedirect by profileCacheStore.string(Key.ROUTE_REDIRECT)
var routePackages by profileCacheStore.string(Key.ROUTE_PACKAGES)
var serverConfig by profileCacheStore.string(Key.SERVER_CONFIG)
var groupName by profileCacheStore.string(Key.GROUP_NAME)
var groupType by profileCacheStore.stringToInt(Key.GROUP_TYPE)
var groupOrder by profileCacheStore.stringToInt(Key.GROUP_ORDER)
var subscriptionType by profileCacheStore.stringToInt(Key.SUBSCRIPTION_TYPE)
var subscriptionLink by profileCacheStore.string(Key.SUBSCRIPTION_LINK)
var subscriptionToken by profileCacheStore.string(Key.SUBSCRIPTION_TOKEN)
var subscriptionForceResolve by profileCacheStore.boolean(Key.SUBSCRIPTION_FORCE_RESOLVE)
var subscriptionDeduplication by profileCacheStore.boolean(Key.SUBSCRIPTION_DEDUPLICATION)
var subscriptionUpdateWhenConnectedOnly by profileCacheStore.boolean(Key.SUBSCRIPTION_UPDATE_WHEN_CONNECTED_ONLY)
var subscriptionUserAgent by profileCacheStore.string(Key.SUBSCRIPTION_USER_AGENT)
var subscriptionAutoUpdate by profileCacheStore.boolean(Key.SUBSCRIPTION_AUTO_UPDATE)
var subscriptionAutoUpdateDelay by profileCacheStore.stringToInt(Key.SUBSCRIPTION_AUTO_UPDATE_DELAY) { 360 }
var rulesFirstCreate by profileCacheStore.boolean("rulesFirstCreate")
override fun onPreferenceDataStoreChanged(store: PreferenceDataStore, key: String) {
}
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/database/DataStore.kt | 3088699283 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.database
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import dev.matrix.roomigrant.GenerateRoomMigrations
import io.nekohasekai.sagernet.Key
import io.nekohasekai.sagernet.SagerNet
import io.nekohasekai.sagernet.ftm.KryoConverters
import io.nekohasekai.sagernet.ftm.gson.GsonConverters
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
@Database(
entities = [ProxyGroup::class, ProxyEntity::class, RuleEntity::class, StatsEntity::class],
version = 5
)
@TypeConverters(value = [KryoConverters::class, GsonConverters::class])
@GenerateRoomMigrations
abstract class SagerDatabase : RoomDatabase() {
companion object {
@OptIn(DelicateCoroutinesApi::class)
@Suppress("EXPERIMENTAL_API_USAGE")
private val instance by lazy {
SagerNet.application.getDatabasePath(Key.DB_PROFILE).parentFile?.mkdirs()
Room.databaseBuilder(SagerNet.application, SagerDatabase::class.java, Key.DB_PROFILE)
// .addMigrations(*SagerDatabase_Migrations.build())
.allowMainThreadQueries()
.enableMultiInstanceInvalidation()
.fallbackToDestructiveMigration()
.setQueryExecutor { GlobalScope.launch { it.run() } }
.build()
}
val groupDao get() = instance.groupDao()
val proxyDao get() = instance.proxyDao()
val rulesDao get() = instance.rulesDao()
val statsDao get() = instance.statsDao()
}
abstract fun groupDao(): ProxyGroup.Dao
abstract fun proxyDao(): ProxyEntity.Dao
abstract fun rulesDao(): RuleEntity.Dao
abstract fun statsDao(): StatsEntity.Dao
}
| Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/database/SagerDatabase.kt | 365436725 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* Copyright (C) 2021 by Max Lv <[email protected]> *
* Copyright (C) 2021 by Mygod Studio <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.database.preference
import android.os.Parcel
import android.os.Parcelable
import androidx.room.*
import java.io.ByteArrayOutputStream
import java.nio.ByteBuffer
@Entity
class KeyValuePair() : Parcelable {
companion object {
const val TYPE_UNINITIALIZED = 0
const val TYPE_BOOLEAN = 1
const val TYPE_FLOAT = 2
@Deprecated("Use TYPE_LONG.")
const val TYPE_INT = 3
const val TYPE_LONG = 4
const val TYPE_STRING = 5
const val TYPE_STRING_SET = 6
@JvmField
val CREATOR = object : Parcelable.Creator<KeyValuePair> {
override fun createFromParcel(parcel: Parcel): KeyValuePair {
return KeyValuePair(parcel)
}
override fun newArray(size: Int): Array<KeyValuePair?> {
return arrayOfNulls(size)
}
}
}
@androidx.room.Dao
interface Dao {
@Query("SELECT * FROM `KeyValuePair`")
fun all(): List<KeyValuePair>
@Query("SELECT * FROM `KeyValuePair` WHERE `key` = :key")
operator fun get(key: String): KeyValuePair?
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun put(value: KeyValuePair): Long
@Query("DELETE FROM `KeyValuePair` WHERE `key` = :key")
fun delete(key: String): Int
@Query("DELETE FROM `KeyValuePair`")
fun reset(): Int
@Insert
fun insert(list: List<KeyValuePair>)
}
@PrimaryKey
var key: String = ""
var valueType: Int = TYPE_UNINITIALIZED
var value: ByteArray = ByteArray(0)
val boolean: Boolean?
get() = if (valueType == TYPE_BOOLEAN) ByteBuffer.wrap(value).get() != 0.toByte() else null
val float: Float?
get() = if (valueType == TYPE_FLOAT) ByteBuffer.wrap(value).float else null
@Suppress("DEPRECATION")
@Deprecated("Use long.", ReplaceWith("long"))
val int: Int?
get() = if (valueType == TYPE_INT) ByteBuffer.wrap(value).int else null
val long: Long?
get() = when (valueType) {
@Suppress("DEPRECATION") TYPE_INT,
-> ByteBuffer.wrap(value).int.toLong()
TYPE_LONG -> ByteBuffer.wrap(value).long
else -> null
}
val string: String?
get() = if (valueType == TYPE_STRING) String(value) else null
val stringSet: Set<String>?
get() = if (valueType == TYPE_STRING_SET) {
val buffer = ByteBuffer.wrap(value)
val result = HashSet<String>()
while (buffer.hasRemaining()) {
val chArr = ByteArray(buffer.int)
buffer.get(chArr)
result.add(String(chArr))
}
result
} else null
@Ignore
constructor(key: String) : this() {
this.key = key
}
// putting null requires using DataStore
fun put(value: Boolean): KeyValuePair {
valueType = TYPE_BOOLEAN
this.value = ByteBuffer.allocate(1).put((if (value) 1 else 0).toByte()).array()
return this
}
fun put(value: Float): KeyValuePair {
valueType = TYPE_FLOAT
this.value = ByteBuffer.allocate(4).putFloat(value).array()
return this
}
@Suppress("DEPRECATION")
@Deprecated("Use long.")
fun put(value: Int): KeyValuePair {
valueType = TYPE_INT
this.value = ByteBuffer.allocate(4).putInt(value).array()
return this
}
fun put(value: Long): KeyValuePair {
valueType = TYPE_LONG
this.value = ByteBuffer.allocate(8).putLong(value).array()
return this
}
fun put(value: String): KeyValuePair {
valueType = TYPE_STRING
this.value = value.toByteArray()
return this
}
fun put(value: Set<String>): KeyValuePair {
valueType = TYPE_STRING_SET
val stream = ByteArrayOutputStream()
val intBuffer = ByteBuffer.allocate(4)
for (v in value) {
intBuffer.rewind()
stream.write(intBuffer.putInt(v.length).array())
stream.write(v.toByteArray())
}
this.value = stream.toByteArray()
return this
}
@Suppress("IMPLICIT_CAST_TO_ANY")
override fun toString(): String {
return when (valueType) {
TYPE_BOOLEAN -> boolean
TYPE_FLOAT -> float
TYPE_LONG -> long
TYPE_STRING -> string
TYPE_STRING_SET -> stringSet
else -> null
}?.toString() ?: "null"
}
constructor(parcel: Parcel) : this() {
key = parcel.readString()!!
valueType = parcel.readInt()
value = parcel.createByteArray()!!
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(key)
parcel.writeInt(valueType)
parcel.writeByteArray(value)
}
override fun describeContents(): Int {
return 0
}
}
| Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/database/preference/KeyValuePair.kt | 224410182 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* Copyright (C) 2021 by Max Lv <[email protected]> *
* Copyright (C) 2021 by Mygod Studio <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.database.preference
import androidx.preference.PreferenceDataStore
interface OnPreferenceDataStoreChangeListener {
fun onPreferenceDataStoreChanged(store: PreferenceDataStore, key: String)
}
| Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/database/preference/OnPreferenceDataStoreChangeListener.kt | 3667794973 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* Copyright (C) 2021 by Max Lv <[email protected]> *
* Copyright (C) 2021 by Mygod Studio <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.database.preference
import androidx.preference.PreferenceDataStore
@Suppress("MemberVisibilityCanBePrivate", "unused")
open class RoomPreferenceDataStore(private val kvPairDao: KeyValuePair.Dao) :
PreferenceDataStore() {
fun getBoolean(key: String) = kvPairDao[key]?.boolean
fun getFloat(key: String) = kvPairDao[key]?.float
fun getInt(key: String) = kvPairDao[key]?.long?.toInt()
fun getLong(key: String) = kvPairDao[key]?.long
fun getString(key: String) = kvPairDao[key]?.string
fun getStringSet(key: String) = kvPairDao[key]?.stringSet
fun reset() = kvPairDao.reset()
override fun getBoolean(key: String, defValue: Boolean) = getBoolean(key) ?: defValue
override fun getFloat(key: String, defValue: Float) = getFloat(key) ?: defValue
override fun getInt(key: String, defValue: Int) = getInt(key) ?: defValue
override fun getLong(key: String, defValue: Long) = getLong(key) ?: defValue
override fun getString(key: String, defValue: String?) = getString(key) ?: defValue
override fun getStringSet(key: String, defValue: MutableSet<String>?) =
getStringSet(key) ?: defValue
fun putBoolean(key: String, value: Boolean?) =
if (value == null) remove(key) else putBoolean(key, value)
fun putFloat(key: String, value: Float?) =
if (value == null) remove(key) else putFloat(key, value)
fun putInt(key: String, value: Int?) =
if (value == null) remove(key) else putLong(key, value.toLong())
fun putLong(key: String, value: Long?) = if (value == null) remove(key) else putLong(key, value)
override fun putBoolean(key: String, value: Boolean) {
kvPairDao.put(KeyValuePair(key).put(value))
fireChangeListener(key)
}
override fun putFloat(key: String, value: Float) {
kvPairDao.put(KeyValuePair(key).put(value))
fireChangeListener(key)
}
override fun putInt(key: String, value: Int) {
kvPairDao.put(KeyValuePair(key).put(value.toLong()))
fireChangeListener(key)
}
override fun putLong(key: String, value: Long) {
kvPairDao.put(KeyValuePair(key).put(value))
fireChangeListener(key)
}
override fun putString(key: String, value: String?) = if (value == null) remove(key) else {
kvPairDao.put(KeyValuePair(key).put(value))
fireChangeListener(key)
}
override fun putStringSet(key: String, values: MutableSet<String>?) =
if (values == null) remove(key) else {
kvPairDao.put(KeyValuePair(key).put(values))
fireChangeListener(key)
}
fun remove(key: String) {
kvPairDao.delete(key)
fireChangeListener(key)
}
private val listeners = HashSet<OnPreferenceDataStoreChangeListener>()
private fun fireChangeListener(key: String) {
val listeners = synchronized(listeners) {
listeners.toList()
}
listeners.forEach { it.onPreferenceDataStoreChanged(this, key) }
}
fun registerChangeListener(listener: OnPreferenceDataStoreChangeListener) {
synchronized(listeners) {
listeners.add(listener)
}
}
fun unregisterChangeListener(listener: OnPreferenceDataStoreChangeListener) {
synchronized(listeners) {
listeners.remove(listener)
}
}
}
| Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/database/preference/RoomPreferenceDataStore.kt | 3721717754 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* Copyright (C) 2021 by Max Lv <[email protected]> *
* Copyright (C) 2021 by Mygod Studio <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.database.preference
import android.graphics.Typeface
import android.text.InputFilter
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import androidx.preference.EditTextPreference
object EditTextPreferenceModifiers {
object Monospace : EditTextPreference.OnBindEditTextListener {
override fun onBindEditText(editText: EditText) {
editText.typeface = Typeface.MONOSPACE
}
}
object Hosts : EditTextPreference.OnBindEditTextListener {
override fun onBindEditText(editText: EditText) {
editText.setHorizontallyScrolling(true)
editText.setSelection(editText.text.length)
}
}
object Port : EditTextPreference.OnBindEditTextListener {
private val portLengthFilter = arrayOf(InputFilter.LengthFilter(5))
override fun onBindEditText(editText: EditText) {
editText.inputType = EditorInfo.TYPE_CLASS_NUMBER
editText.filters = portLengthFilter
editText.setSingleLine()
editText.setSelection(editText.text.length)
}
}
object Number : EditTextPreference.OnBindEditTextListener {
override fun onBindEditText(editText: EditText) {
editText.inputType = EditorInfo.TYPE_CLASS_NUMBER
editText.setSingleLine()
editText.setSelection(editText.text.length)
}
}
}
| Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/database/preference/EditTextPreferenceModifiers.kt | 2838743094 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* Copyright (C) 2021 by Max Lv <[email protected]> *
* Copyright (C) 2021 by Mygod Studio <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.database.preference
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import io.nekohasekai.sagernet.Key
import io.nekohasekai.sagernet.SagerNet
import dev.matrix.roomigrant.GenerateRoomMigrations
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
@Database(entities = [KeyValuePair::class], version = 1)
@GenerateRoomMigrations
abstract class PublicDatabase : RoomDatabase() {
companion object {
private val instance by lazy {
SagerNet.application.getDatabasePath(Key.DB_PROFILE).parentFile?.mkdirs()
Room.databaseBuilder(SagerNet.application, PublicDatabase::class.java, Key.DB_PUBLIC)
.allowMainThreadQueries()
.enableMultiInstanceInvalidation()
.fallbackToDestructiveMigration()
.setQueryExecutor { GlobalScope.launch { it.run() } }
.build()
}
val kvPairDao get() = instance.keyValuePairDao()
}
abstract fun keyValuePairDao(): KeyValuePair.Dao
}
| Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/database/preference/PublicDatabase.kt | 3228004218 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.database
import com.narcis.application.presentation.connection.applyDefaultValues
import io.nekohasekai.sagernet.GroupType
import io.nekohasekai.sagernet.bg.SubscriptionUpdater
object GroupManager {
interface Listener {
suspend fun groupAdd(group: ProxyGroup)
suspend fun groupUpdated(group: ProxyGroup)
suspend fun groupRemoved(groupId: Long)
suspend fun groupUpdated(groupId: Long)
}
interface Interface {
suspend fun confirm(message: String): Boolean
suspend fun alert(message: String)
suspend fun onUpdateSuccess(
group: ProxyGroup,
changed: Int,
added: List<String>,
updated: Map<String, String>,
deleted: List<String>,
duplicate: List<String>,
byUser: Boolean
)
suspend fun onUpdateFailure(group: ProxyGroup, message: String)
}
private val listeners = ArrayList<Listener>()
var userInterface: Interface? = null
suspend fun iterator(what: suspend Listener.() -> Unit) {
synchronized(listeners) {
listeners.toList()
}.forEach { listener ->
what(listener)
}
}
fun addListener(listener: Listener) {
synchronized(listeners) {
listeners.add(listener)
}
}
fun removeListener(listener: Listener) {
synchronized(listeners) {
listeners.remove(listener)
}
}
suspend fun clearGroup(groupId: Long) {
DataStore.selectedProxy = 0L
SagerDatabase.proxyDao.deleteAll(groupId)
iterator { groupUpdated(groupId) }
}
fun rearrange(groupId: Long) {
val entities = SagerDatabase.proxyDao.getByGroup(groupId)
for (index in entities.indices) {
entities[index].userOrder = (index + 1).toLong()
}
SagerDatabase.proxyDao.updateProxy(entities)
}
suspend fun postUpdate(group: ProxyGroup) {
iterator { groupUpdated(group) }
}
suspend fun postUpdate(groupId: Long) {
postUpdate(SagerDatabase.groupDao.getById(groupId) ?: return)
}
suspend fun postReload(groupId: Long) {
iterator { groupUpdated(groupId) }
}
suspend fun createGroup(group: ProxyGroup): ProxyGroup {
group.userOrder = SagerDatabase.groupDao.nextOrder() ?: 1
group.id = SagerDatabase.groupDao.createGroup(group.applyDefaultValues())
iterator { groupAdd(group) }
if (group.type == GroupType.SUBSCRIPTION) {
SubscriptionUpdater.reconfigureUpdater()
}
return group
}
suspend fun updateGroup(group: ProxyGroup) {
SagerDatabase.groupDao.updateGroup(group)
iterator { groupUpdated(group) }
if (group.type == GroupType.SUBSCRIPTION) {
SubscriptionUpdater.reconfigureUpdater()
}
}
suspend fun deleteGroup(groupId: Long) {
SagerDatabase.groupDao.deleteById(groupId)
SagerDatabase.proxyDao.deleteByGroup(groupId)
iterator { groupRemoved(groupId) }
SubscriptionUpdater.reconfigureUpdater()
}
suspend fun deleteGroup(group: List<ProxyGroup>) {
SagerDatabase.groupDao.deleteGroup(group)
SagerDatabase.proxyDao.deleteByGroup(group.map { it.id }.toLongArray())
for (proxyGroup in group) iterator { groupRemoved(proxyGroup.id) }
SubscriptionUpdater.reconfigureUpdater()
}
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/database/GroupManager.kt | 3842013917 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.database
import android.os.Parcelable
import androidx.room.Delete
import androidx.room.Entity
import androidx.room.Insert
import androidx.room.PrimaryKey
import androidx.room.Query
import androidx.room.Update
import io.nekohasekai.sagernet.R
import com.github.shadowsocks.plugin.ProfileManager
import io.nekohasekai.sagernet.ktx.app
import kotlinx.parcelize.Parcelize
@Entity(tableName = "rules")
@Parcelize
data class RuleEntity(
@PrimaryKey(autoGenerate = true) var id: Long = 0L,
var name: String = "",
var userOrder: Long = 0L,
var enabled: Boolean = false,
var domains: String = "",
var ip: String = "",
var port: String = "",
var sourcePort: String = "",
var network: String = "",
var source: String = "",
var protocol: String = "",
var attrs: String = "",
var outbound: Long = 0,
var reverse: Boolean = false,
var redirect: String = "",
var packages: List<String> = listOf(),
) : Parcelable {
fun displayName(): String {
return name.takeIf { it.isNotBlank() } ?: "Rule $id"
}
fun mkSummary(): String {
var summary = ""
if (domains.isNotBlank()) summary += "$domains\n"
if (ip.isNotBlank()) summary += "$ip\n"
if (source.isNotBlank()) summary += "source: $source\n"
if (sourcePort.isNotBlank()) summary += "sourcePort: $sourcePort\n"
if (port.isNotBlank()) summary += "port: $port\n"
if (network.isNotBlank()) summary += "network: $network\n"
if (protocol.isNotBlank()) summary += "protocol: $protocol\n"
if (attrs.isNotBlank()) summary += "attrs: $attrs\n"
if (reverse) summary += "reverse: $redirect\n"
if (packages.isNotEmpty()) summary += app.getString(
R.string.apps_message, packages.size
) + "\n"
val lines = summary.trim().split("\n")
return if (lines.size > 3) {
lines.subList(0, 3).joinToString("\n", postfix = "\n...")
} else {
summary.trim()
}
}
fun displayOutbound(): String {
if (reverse) {
return app.getString(R.string.route_reverse)
}
return when (outbound) {
0L -> app.getString(R.string.route_proxy)
-1L -> app.getString(R.string.route_bypass)
-2L -> app.getString(R.string.route_block)
else -> ProfileManager.getProfile(outbound)?.displayName()
?: app.getString(R.string.error_title)
}
}
@androidx.room.Dao
interface Dao {
@Query("SELECT * from rules WHERE (packages != '') AND enabled = 1")
fun checkVpnNeeded(): List<RuleEntity>
@Query("SELECT * FROM rules ORDER BY userOrder")
fun allRules(): List<RuleEntity>
@Query("SELECT * FROM rules WHERE enabled = :enabled ORDER BY userOrder")
fun enabledRules(enabled: Boolean = true): List<RuleEntity>
@Query("SELECT MAX(userOrder) + 1 FROM rules")
fun nextOrder(): Long?
@Query("SELECT * FROM rules WHERE id = :ruleId")
fun getById(ruleId: Long): RuleEntity?
@Query("DELETE FROM rules WHERE id = :ruleId")
fun deleteById(ruleId: Long): Int
@Delete
fun deleteRule(rule: RuleEntity)
@Delete
fun deleteRules(rules: List<RuleEntity>)
@Insert
fun createRule(rule: RuleEntity): Long
@Update
fun updateRule(rule: RuleEntity)
@Update
fun updateRules(rules: List<RuleEntity>)
@Query("DELETE FROM rules")
fun reset()
@Insert
fun insert(rules: List<RuleEntity>)
}
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/database/RuleEntity.kt | 2916589588 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.database
import android.content.Context
import android.content.Intent
import androidx.room.Delete
import androidx.room.Entity
import androidx.room.Ignore
import androidx.room.Index
import androidx.room.Insert
import androidx.room.PrimaryKey
import androidx.room.Query
import androidx.room.Update
import io.nekohasekai.sagernet.R
import moe.matsuri.nya.neko.NekoBean
import moe.matsuri.nya.Protocols
import moe.matsuri.nya.neko.haveStandardLink
import io.nekohasekai.sagernet.ktx.isTLS
import moe.matsuri.nya.neko.shareLink
import com.esotericsoftware.kryo.io.ByteBufferInput
import com.esotericsoftware.kryo.io.ByteBufferOutput
import io.nekohasekai.sagernet.aidl.TrafficStats
import io.nekohasekai.sagernet.ftm.AbstractBean
import io.nekohasekai.sagernet.ftm.KryoConverters
import io.nekohasekai.sagernet.ftm.Serializable
import io.nekohasekai.sagernet.ftm.buildV2RayConfig
import io.nekohasekai.sagernet.ftm.http.HttpBean
import io.nekohasekai.sagernet.ftm.http.toUri
import io.nekohasekai.sagernet.ftm.hysteria.HysteriaBean
import io.nekohasekai.sagernet.ftm.hysteria.buildHysteriaConfig
import io.nekohasekai.sagernet.ftm.hysteria.toUri
import io.nekohasekai.sagernet.ftm.internal.ChainBean
import io.nekohasekai.sagernet.ftm.naive.NaiveBean
import io.nekohasekai.sagernet.ftm.naive.buildNaiveConfig
import io.nekohasekai.sagernet.ftm.naive.toUri
import io.nekohasekai.sagernet.ftm.shadowsocks.ShadowsocksBean
import io.nekohasekai.sagernet.ftm.shadowsocks.toUri
import io.nekohasekai.sagernet.ftm.shadowsocksr.ShadowsocksRBean
import io.nekohasekai.sagernet.ftm.shadowsocksr.toUri
import io.nekohasekai.sagernet.ftm.socks.SOCKSBean
import io.nekohasekai.sagernet.ftm.socks.toUri
import io.nekohasekai.sagernet.ftm.ssh.SSHBean
import io.nekohasekai.sagernet.ftm.toUniversalLink
import io.nekohasekai.sagernet.ftm.trojan.TrojanBean
import io.nekohasekai.sagernet.ftm.trojan.toUri
import io.nekohasekai.sagernet.ftm.trojan_go.TrojanGoBean
import io.nekohasekai.sagernet.ftm.trojan_go.buildTrojanGoConfig
import io.nekohasekai.sagernet.ftm.trojan_go.toUri
import io.nekohasekai.sagernet.ftm.tuic.TuicBean
import io.nekohasekai.sagernet.ftm.tuic.buildTuicConfig
import io.nekohasekai.sagernet.ftm.v2ray.StandardV2RayBean
import io.nekohasekai.sagernet.ftm.v2ray.VMessBean
import io.nekohasekai.sagernet.ftm.v2ray.toV2rayN
import io.nekohasekai.sagernet.ftm.wireguard.WireGuardBean
import io.nekohasekai.sagernet.ktx.app
import io.nekohasekai.sagernet.ktx.applyDefaultValues
@Entity(
tableName = "proxy_entities", indices = [Index("groupId", name = "groupId")]
)
data class ProxyEntity(
@PrimaryKey(autoGenerate = true) var id: Long = 0L,
var groupId: Long = 0L,
var type: Int = 0,
var userOrder: Long = 0L,
var tx: Long = 0L,
var rx: Long = 0L,
var status: Int = 0,
var ping: Int = 0,
var uuid: String = "",
var error: String? = null,
var socksBean: SOCKSBean? = null,
var httpBean: HttpBean? = null,
var ssBean: ShadowsocksBean? = null,
var ssrBean: ShadowsocksRBean? = null,
var vmessBean: VMessBean? = null,
var trojanBean: TrojanBean? = null,
var trojanGoBean: TrojanGoBean? = null,
var naiveBean: NaiveBean? = null,
var hysteriaBean: HysteriaBean? = null,
var tuicBean: TuicBean? = null,
var sshBean: SSHBean? = null,
var wgBean: WireGuardBean? = null,
var chainBean: ChainBean? = null,
var nekoBean: NekoBean? = null,
) : io.nekohasekai.sagernet.ftm.Serializable() {
companion object {
const val TYPE_SOCKS = 0
const val TYPE_HTTP = 1
const val TYPE_SS = 2
const val TYPE_SSR = 3
const val TYPE_VMESS = 4
const val TYPE_TROJAN = 6
const val TYPE_TROJAN_GO = 7
const val TYPE_NAIVE = 9
const val TYPE_HYSTERIA = 15
const val TYPE_SSH = 17
const val TYPE_WG = 18
const val TYPE_TUIC = 20
const val TYPE_CHAIN = 8
const val TYPE_NEKO = 999
val chainName by lazy { app.getString(R.string.proxy_chain) }
private val placeHolderBean = SOCKSBean().applyDefaultValues()
@JvmField
val CREATOR = object : Serializable.CREATOR<ProxyEntity>() {
override fun newInstance(): ProxyEntity {
return ProxyEntity()
}
override fun newArray(size: Int): Array<ProxyEntity?> {
return arrayOfNulls(size)
}
}
}
@Ignore
@Transient
var info: String = ""
@Ignore
@Transient
var dirty: Boolean = false
@Ignore
@Transient
var stats: TrafficStats? = null
override fun initializeDefaultValues() {
}
override fun serializeToBuffer(output: ByteBufferOutput) {
output.writeInt(0)
output.writeLong(id)
output.writeLong(groupId)
output.writeInt(type)
output.writeLong(userOrder)
output.writeLong(tx)
output.writeLong(rx)
output.writeInt(status)
output.writeInt(ping)
output.writeString(uuid)
output.writeString(error)
val data = KryoConverters.serialize(requireBean())
output.writeVarInt(data.size, true)
output.writeBytes(data)
output.writeBoolean(dirty)
}
override fun deserializeFromBuffer(input: ByteBufferInput) {
val version = input.readInt()
id = input.readLong()
groupId = input.readLong()
type = input.readInt()
userOrder = input.readLong()
tx = input.readLong()
rx = input.readLong()
status = input.readInt()
ping = input.readInt()
uuid = input.readString()
error = input.readString()
putByteArray(input.readBytes(input.readVarInt(true)))
dirty = input.readBoolean()
}
fun putByteArray(byteArray: ByteArray) {
when (type) {
TYPE_SOCKS -> socksBean = KryoConverters.socksDeserialize(byteArray)
TYPE_HTTP -> httpBean = KryoConverters.httpDeserialize(byteArray)
TYPE_SS -> ssBean = KryoConverters.shadowsocksDeserialize(byteArray)
TYPE_SSR -> ssrBean = KryoConverters.shadowsocksRDeserialize(byteArray)
TYPE_VMESS -> vmessBean = KryoConverters.vmessDeserialize(byteArray)
TYPE_TROJAN -> trojanBean = KryoConverters.trojanDeserialize(byteArray)
TYPE_TROJAN_GO -> trojanGoBean = KryoConverters.trojanGoDeserialize(byteArray)
TYPE_NAIVE -> naiveBean = KryoConverters.naiveDeserialize(byteArray)
TYPE_HYSTERIA -> hysteriaBean = KryoConverters.hysteriaDeserialize(byteArray)
TYPE_SSH -> sshBean = KryoConverters.sshDeserialize(byteArray)
TYPE_WG -> wgBean = KryoConverters.wireguardDeserialize(byteArray)
TYPE_TUIC -> tuicBean = KryoConverters.tuicDeserialize(byteArray)
TYPE_CHAIN -> chainBean = KryoConverters.chainDeserialize(byteArray)
TYPE_NEKO -> nekoBean = KryoConverters.nekoDeserialize(byteArray)
}
}
fun displayType() = when (type) {
TYPE_SOCKS -> socksBean!!.protocolName()
TYPE_HTTP -> if (httpBean!!.isTLS()) "HTTPS" else "HTTP"
TYPE_SS -> "Shadowsocks"
TYPE_SSR -> "ShadowsocksR"
TYPE_VMESS -> "VMess"
TYPE_TROJAN -> "Trojan"
TYPE_TROJAN_GO -> "Trojan-Go"
TYPE_NAIVE -> "Naïve"
TYPE_HYSTERIA -> "Hysteria"
TYPE_SSH -> "SSH"
TYPE_WG -> "WireGuard"
TYPE_TUIC -> "TUIC"
TYPE_CHAIN -> chainName
TYPE_NEKO -> nekoBean!!.displayType()
else -> "Undefined type $type"
}
fun displayName() = requireBean().displayName()
fun displayAddress() = requireBean().displayAddress()
fun requireBean(): AbstractBean {
return when (type) {
TYPE_SOCKS -> socksBean
TYPE_HTTP -> httpBean
TYPE_SS -> ssBean
TYPE_SSR -> ssrBean
TYPE_VMESS -> vmessBean
TYPE_TROJAN -> trojanBean
TYPE_TROJAN_GO -> trojanGoBean
TYPE_NAIVE -> naiveBean
TYPE_HYSTERIA -> hysteriaBean
TYPE_SSH -> sshBean
TYPE_WG -> wgBean
TYPE_TUIC -> tuicBean
TYPE_CHAIN -> chainBean
TYPE_NEKO -> nekoBean
else -> error("Undefined type $type")
} ?: error("Null ${displayType()} profile")
}
fun haveLink(): Boolean {
return when (type) {
TYPE_CHAIN -> false
else -> true
}
}
fun haveStandardLink(): Boolean {
return when (requireBean()) {
is TuicBean -> false
is SSHBean -> false
is WireGuardBean -> false
is NekoBean -> nekoBean!!.haveStandardLink()
else -> true
}
}
fun toStdLink(): String? = with(requireBean()) {
when (this) {
is SOCKSBean -> toUri()
is HttpBean -> toUri()
is ShadowsocksBean -> toUri()
is ShadowsocksRBean -> toUri()
is VMessBean -> toV2rayN() // else toUri()
is TrojanBean -> toUri()
is TrojanGoBean -> toUri()
is NaiveBean -> toUri()
is HysteriaBean -> toUri()
is SSHBean -> toUniversalLink()
is WireGuardBean -> toUniversalLink()
is TuicBean -> toUniversalLink()
is NekoBean -> shareLink()
else -> null
}
}
fun exportConfig(): Pair<String, String> {
var name = "${requireBean().displayName()}.json"
return with(requireBean()) {
StringBuilder().apply {
val config = buildV2RayConfig(this@ProxyEntity)
append(config.config)
if (!config.index.all { it.chain.isEmpty() }) {
name = "profiles.txt"
}
for ((chain) in config.index) {
chain.entries.forEachIndexed { index, (port, profile) ->
when (val bean = profile.requireBean()) {
is TrojanGoBean -> {
append("\n\n")
append(bean.buildTrojanGoConfig(port))
}
is NaiveBean -> {
append("\n\n")
append(bean.buildNaiveConfig(port))
}
is HysteriaBean -> {
append("\n\n")
append(bean.buildHysteriaConfig(port, null))
}
is TuicBean -> {
append("\n\n")
append(bean.buildTuicConfig(port, null))
}
}
}
}
}.toString()
} to name
}
fun needExternal(): Boolean {
return when (type) {
TYPE_TROJAN_GO -> true
TYPE_NAIVE -> true
TYPE_HYSTERIA -> true
TYPE_WG -> true
TYPE_TUIC -> true
TYPE_NEKO -> true
else -> false
}
}
fun isV2RayNetworkTcp(): Boolean {
val bean = requireBean() as StandardV2RayBean
return when (bean.type) {
"tcp", "ws", "http" -> true
else -> false
}
}
fun needCoreMux(): Boolean {
return when (type) {
TYPE_VMESS -> Protocols.shouldEnableMux("vmess") && isV2RayNetworkTcp()
TYPE_TROJAN -> Protocols.shouldEnableMux("trojan") && isV2RayNetworkTcp()
TYPE_TROJAN_GO -> false
else -> false
}
}
fun putBean(bean: AbstractBean): ProxyEntity {
socksBean = null
httpBean = null
ssBean = null
ssrBean = null
vmessBean = null
trojanBean = null
trojanGoBean = null
naiveBean = null
hysteriaBean = null
sshBean = null
wgBean = null
tuicBean = null
chainBean = null
when (bean) {
is SOCKSBean -> {
type = TYPE_SOCKS
socksBean = bean
}
is HttpBean -> {
type = TYPE_HTTP
httpBean = bean
}
is ShadowsocksBean -> {
type = TYPE_SS
ssBean = bean
}
is ShadowsocksRBean -> {
type = TYPE_SSR
ssrBean = bean
}
is VMessBean -> {
type = TYPE_VMESS
vmessBean = bean
}
is TrojanBean -> {
type = TYPE_TROJAN
trojanBean = bean
}
is TrojanGoBean -> {
type = TYPE_TROJAN_GO
trojanGoBean = bean
}
is NaiveBean -> {
type = TYPE_NAIVE
naiveBean = bean
}
is HysteriaBean -> {
type = TYPE_HYSTERIA
hysteriaBean = bean
}
is SSHBean -> {
type = TYPE_SSH
sshBean = bean
}
is WireGuardBean -> {
type = TYPE_WG
wgBean = bean
}
is TuicBean -> {
type = TYPE_TUIC
tuicBean = bean
}
is ChainBean -> {
type = TYPE_CHAIN
chainBean = bean
}
is NekoBean -> {
type = TYPE_NEKO
nekoBean = bean
}
else -> error("Undefined type $type")
}
return this
}
@androidx.room.Dao
interface Dao {
@Query("select * from proxy_entities")
fun getAll(): List<ProxyEntity>
@Query("SELECT id FROM proxy_entities WHERE groupId = :groupId ORDER BY userOrder")
fun getIdsByGroup(groupId: Long): List<Long>
@Query("SELECT * FROM proxy_entities WHERE groupId = :groupId ORDER BY userOrder")
fun getByGroup(groupId: Long): List<ProxyEntity>
@Query("SELECT * FROM proxy_entities WHERE id in (:proxyIds)")
fun getEntities(proxyIds: List<Long>): List<ProxyEntity>
@Query("SELECT COUNT(*) FROM proxy_entities WHERE groupId = :groupId")
fun countByGroup(groupId: Long): Long
@Query("SELECT MAX(userOrder) + 1 FROM proxy_entities WHERE groupId = :groupId")
fun nextOrder(groupId: Long): Long?
@Query("SELECT * FROM proxy_entities WHERE id = :proxyId")
fun getById(proxyId: Long): ProxyEntity?
@Query("DELETE FROM proxy_entities")
fun deleteAllProxyEntities()
@Query("DELETE FROM sqlite_sequence WHERE name = 'proxy_entities'")
fun clearPrimaryKey()
@Query("DELETE FROM proxy_entities WHERE id IN (:proxyId)")
fun deleteById(proxyId: Long): Int
@Query("DELETE FROM proxy_entities WHERE groupId = :groupId")
fun deleteByGroup(groupId: Long)
@Query("DELETE FROM proxy_entities WHERE groupId in (:groupId)")
fun deleteByGroup(groupId: LongArray)
@Delete
fun deleteProxy(proxy: ProxyEntity): Int
@Delete
fun deleteProxy(proxies: List<ProxyEntity>): Int
@Update
fun updateProxy(proxy: ProxyEntity): Int
@Update
fun updateProxy(proxies: List<ProxyEntity>): Int
@Insert
fun addProxy(proxy: ProxyEntity): Long
@Insert
fun insert(proxies: List<ProxyEntity>)
@Query("DELETE FROM proxy_entities WHERE groupId = :groupId")
fun deleteAll(groupId: Long): Int
@Query("DELETE FROM proxy_entities")
fun reset()
}
override fun describeContents(): Int {
return 0
}
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/database/ProxyEntity.kt | 3205658362 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.database
import android.os.Parcelable
import androidx.room.Entity
import androidx.room.Index
import androidx.room.Insert
import androidx.room.PrimaryKey
import androidx.room.Query
import androidx.room.Update
import io.nekohasekai.sagernet.aidl.AppStats
import io.nekohasekai.sagernet.utils.PackageCache
import kotlinx.parcelize.Parcelize
@Entity(
tableName = "stats", indices = [Index(
"packageName", unique = true
)]
)
@Parcelize
class StatsEntity(
@PrimaryKey(autoGenerate = true) var id: Int = 0,
var packageName: String = "",
var tcpConnections: Int = 0,
var udpConnections: Int = 0,
var uplink: Long = 0L,
var downlink: Long = 0L
) : Parcelable {
fun toStats(): AppStats {
return AppStats(
packageName,
PackageCache[packageName] ?: 1000,
0,
0,
tcpConnections,
udpConnections,
0,
0,
uplink,
downlink,
0,
""
)
}
@androidx.room.Dao
interface Dao {
@Query("SELECT * FROM stats")
fun all(): List<StatsEntity>
@Query("SELECT * FROM stats WHERE packageName = :packageName")
operator fun get(packageName: String): StatsEntity?
@Query("DELETE FROM stats WHERE packageName = :packageName")
fun delete(packageName: String): Int
@Insert
fun create(stats: StatsEntity)
@Update
fun update(stats: List<StatsEntity>)
@Query("DELETE FROM stats")
fun deleteAll()
}
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/database/StatsEntity.kt | 4070738420 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.ftm
import io.nekohasekai.sagernet.database.ProxyEntity
object TypeMap : HashMap<String, Int>() {
init {
this["socks"] = ProxyEntity.TYPE_SOCKS
this["http"] = ProxyEntity.TYPE_HTTP
this["ss"] = ProxyEntity.TYPE_SS
this["ssr"] = ProxyEntity.TYPE_SSR
this["vmess"] = ProxyEntity.TYPE_VMESS
this["trojan"] = ProxyEntity.TYPE_TROJAN
this["trojan-go"] = ProxyEntity.TYPE_TROJAN_GO
this["naive"] = ProxyEntity.TYPE_NAIVE
this["hysteria"] = ProxyEntity.TYPE_HYSTERIA
this["ssh"] = ProxyEntity.TYPE_SSH
this["wg"] = ProxyEntity.TYPE_WG
this["tuic"] = ProxyEntity.TYPE_TUIC
this["neko"] = ProxyEntity.TYPE_NEKO
}
val reversed = HashMap<Int, String>()
init {
TypeMap.forEach { (key, type) ->
reversed[type] = key
}
}
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/ftm/TypeMap.kt | 2582154533 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.ftm.trojan_go
import com.github.shadowsocks.plugin.PluginConfiguration
import com.github.shadowsocks.plugin.PluginOptions
import moe.matsuri.nya.Protocols
import io.nekohasekai.sagernet.ktx.isIpAddress
import io.nekohasekai.sagernet.ktx.linkBuilder
import io.nekohasekai.sagernet.ktx.toLink
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.IPv6Mode
import com.narcis.application.presentation.connection.applyDefaultValues
import com.narcis.application.presentation.connection.toStringPretty
import io.nekohasekai.sagernet.ftm.LOCALHOST
import io.nekohasekai.sagernet.ftm.shadowsocks.fixInvalidParams
import io.nekohasekai.sagernet.ktx.urlSafe
import com.github.shadowsocks.plugin.PluginManager
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import org.json.JSONArray
import org.json.JSONObject
fun parseTrojanGo(server: String): TrojanGoBean {
val link = server.replace("trojan-go://", "https://").toHttpUrlOrNull() ?: error(
"invalid trojan-link link $server"
)
return TrojanGoBean().apply {
serverAddress = link.host
serverPort = link.port
password = link.username
link.queryParameter("sni")?.let {
sni = it
}
link.queryParameter("type")?.let { lType ->
type = lType
when (type) {
"ws" -> {
link.queryParameter("host")?.let {
host = it
}
link.queryParameter("path")?.let {
path = it
}
}
else -> {
}
}
}
link.queryParameter("encryption")?.let {
encryption = it
}
link.queryParameter("plugin")?.let {
plugin = it
}
link.fragment.takeIf { !it.isNullOrBlank() }?.let {
name = it
}
}
}
fun TrojanGoBean.toUri(): String {
val builder = linkBuilder().username(password).host(serverAddress).port(serverPort)
if (sni.isNotBlank()) {
builder.addQueryParameter("sni", sni)
}
if (type.isNotBlank() && type != "original") {
builder.addQueryParameter("type", type)
when (type) {
"ws" -> {
if (host.isNotBlank()) {
builder.addQueryParameter("host", host)
}
if (path.isNotBlank()) {
builder.addQueryParameter("path", path)
}
}
}
}
if (type.isNotBlank() && type != "none") {
builder.addQueryParameter("encryption", encryption)
}
if (plugin.isNotBlank()) {
builder.addQueryParameter("plugin", plugin)
}
if (name.isNotBlank()) {
builder.encodedFragment(name.urlSafe())
}
return builder.toLink("trojan-go")
}
fun TrojanGoBean.buildTrojanGoConfig(port: Int): String {
return JSONObject().apply {
put("run_type", "client")
put("local_addr", LOCALHOST)
put("local_port", port)
put("remote_addr", finalAddress)
put("remote_port", finalPort)
put("password", JSONArray().apply {
put(password)
})
put("log_level", if (DataStore.enableLog) 0 else 2)
if (Protocols.shouldEnableMux("trojan-go")) put("mux", JSONObject().apply {
put("enabled", true)
put("concurrency", DataStore.muxConcurrency)
})
put("tcp", JSONObject().apply {
put("prefer_ipv4", DataStore.ipv6Mode <= IPv6Mode.ENABLE)
})
when (type) {
"original" -> {
}
"ws" -> put("websocket", JSONObject().apply {
put("enabled", true)
put("host", host)
put("path", path)
})
}
if (sni.isBlank() && finalAddress == LOCALHOST && !serverAddress.isIpAddress()) {
sni = serverAddress
}
put("ssl", JSONObject().apply {
if (sni.isNotBlank()) put("sni", sni)
if (allowInsecure) put("verify", false)
})
when {
encryption == "none" -> {
}
encryption.startsWith("ss;") -> put("shadowsocks", JSONObject().apply {
put("enabled", true)
put("method", encryption.substringAfter(";").substringBefore(":"))
put("password", encryption.substringAfter(":"))
})
}
if (plugin.isNotBlank()) {
val pluginConfiguration = PluginConfiguration(plugin ?: "")
PluginManager.init(pluginConfiguration)?.let { (path, opts, isV2) ->
put("transport_plugin", JSONObject().apply {
put("enabled", true)
put("type", "shadowsocks")
put("command", path)
put("option", opts.toString())
})
}
}
}.toStringPretty()
}
fun JSONObject.parseTrojanGo(): TrojanGoBean {
return TrojanGoBean().applyDefaultValues().apply {
serverAddress = optString("remote_addr", serverAddress)
serverPort = optInt("remote_port", serverPort)
when (val pass = get("password")) {
is String -> {
password = pass
}
is List<*> -> {
password = pass[0] as String
}
}
optJSONArray("ssl")?.apply {
sni = optString("sni", sni)
}
optJSONArray("websocket")?.apply {
if (optBoolean("enabled", false)) {
type = "ws"
host = optString("host", host)
path = optString("path", path)
}
}
optJSONArray("shadowsocks")?.apply {
if (optBoolean("enabled", false)) {
encryption = "ss;${optString("method", "")}:${optString("password", "")}"
}
}
optJSONArray("transport_plugin")?.apply {
if (optBoolean("enabled", false)) {
when (type) {
"shadowsocks" -> {
val pl = PluginConfiguration()
pl.selected = optString("command")
optJSONArray("arg")?.also {
pl.pluginsOptions[pl.selected] = PluginOptions().also { opts ->
var key = ""
for (index in 0 until it.length()) {
if (index % 2 != 0) {
key = it[index].toString()
} else {
opts[key] = it[index].toString()
}
}
}
}
optString("option").also {
if (it != "") pl.pluginsOptions[pl.selected] = PluginOptions(it)
}
pl.fixInvalidParams()
plugin = pl.toString()
}
}
}
}
}
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/ftm/trojan_go/TrojanGoFmt.kt | 1309346217 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.ftm.gson
import com.google.gson.GsonBuilder
val gson = GsonBuilder()
.setPrettyPrinting()
.setLenient()
.registerTypeAdapterFactory(JsonOrAdapterFactory())
.registerTypeAdapterFactory(JsonLazyFactory())
.disableHtmlEscaping()
.create() | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/ftm/gson/Gsons.kt | 4249711996 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.ftm
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.SagerNet
enum class PluginEntry(
val pluginId: String,
val displayName: String,
val packageName: String, // for play and f-droid page
val downloadSource: DownloadSource = DownloadSource()
) {
TrojanGo(
"trojan-go-plugin",
SagerNet.application.getString(R.string.action_trojan_go),
"io.nekohasekai.sagernet.plugin.trojan_go"
),
NaiveProxy(
"naive-plugin",
SagerNet.application.getString(R.string.action_naive),
"io.nekohasekai.sagernet.plugin.naive"
),
Hysteria(
"hysteria-plugin",
SagerNet.application.getString(R.string.action_hysteria),
"moe.matsuri.exe.hysteria", DownloadSource(
playStore = false,
fdroid = false,
downloadLink = "https://github.com/MatsuriDayo/plugins/releases?q=Hysteria"
)
),
WireGuard(
"wireguard-plugin",
SagerNet.application.getString(R.string.action_wireguard),
"io.nekohasekai.sagernet.plugin.wireguard",
DownloadSource(
fdroid = false,
downloadLink = "https://github.com/SagerNet/SagerNet/releases/tag/wireguard-plugin-20210424-5"
)
),
TUIC(
"tuic-plugin",
SagerNet.application.getString(R.string.action_tuic),
"io.nekohasekai.sagernet.plugin.tuic",
DownloadSource(fdroid = false)
),
;
data class DownloadSource(
val playStore: Boolean = true,
val fdroid: Boolean = true,
val downloadLink: String = "https://sagernet.org/download/"
)
companion object {
fun find(name: String): PluginEntry? {
for (pluginEntry in enumValues<PluginEntry>()) {
if (name == pluginEntry.pluginId) {
return pluginEntry
}
}
return null
}
}
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/ftm/PluginEntry.kt | 74572948 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.ftm.shadowsocksr
import moe.matsuri.nya.utils.Util
import com.narcis.application.presentation.connection.applyDefaultValues
import com.narcis.application.presentation.connection.decodeBase64UrlSafe
import okhttp3.HttpUrl.Companion.toHttpUrl
import org.json.JSONObject
import java.util.*
fun parseShadowsocksR(url: String): ShadowsocksRBean {
val params = url.substringAfter("ssr://").decodeBase64UrlSafe().split(":")
val bean = ShadowsocksRBean().apply {
serverAddress = params[0]
serverPort = params[1].toInt()
protocol = params[2]
method = params[3]
obfs = params[4]
password = params[5].substringBefore("/").decodeBase64UrlSafe()
}
val httpUrl = ("https://localhost" + params[5].substringAfter("/")).toHttpUrl()
runCatching {
bean.obfsParam = httpUrl.queryParameter("obfsparam")!!.decodeBase64UrlSafe()
}
runCatching {
bean.protocolParam = httpUrl.queryParameter("protoparam")!!.decodeBase64UrlSafe()
}
val remarks = httpUrl.queryParameter("remarks")
if (!remarks.isNullOrBlank()) {
bean.name = remarks.decodeBase64UrlSafe()
}
return bean
}
fun ShadowsocksRBean.toUri(): String {
return "ssr://" + Util.b64EncodeUrlSafe(
"%s:%d:%s:%s:%s:%s/?obfsparam=%s&protoparam=%s&remarks=%s".format(
Locale.ENGLISH,
serverAddress,
serverPort,
protocol,
method,
obfs,
Util.b64EncodeUrlSafe("%s".format(Locale.ENGLISH, password)),
Util.b64EncodeUrlSafe("%s".format(Locale.ENGLISH, obfsParam)),
Util.b64EncodeUrlSafe("%s".format(Locale.ENGLISH, protocolParam)),
Util.b64EncodeUrlSafe(
"%s".format(
Locale.ENGLISH, name ?: ""
)
)
)
)
}
fun JSONObject.parseShadowsocksR(): ShadowsocksRBean {
return ShadowsocksRBean().applyDefaultValues().apply {
serverAddress = optString("server", serverAddress)
serverPort = optInt("server_port", serverPort)
method = optString("method", method)
password = optString("password", password)
protocol = optString("protocol", protocol)
protocolParam = optString("protocol_param", protocolParam)
obfs = optString("obfs", obfs)
obfsParam = optString("obfs_param", obfsParam)
name = optString("remarks", name)
}
}
| Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/ftm/shadowsocksr/ShadowsocksRFmt.kt | 2642542947 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.ftm.v2ray
import io.nekohasekai.sagernet.ktx.linkBuilder
import io.nekohasekai.sagernet.ktx.toLink
import com.narcis.application.presentation.connection.Logs
import moe.matsuri.nya.utils.NGUtil
import com.narcis.application.presentation.connection.decodeBase64UrlSafe
import com.narcis.application.presentation.connection.formatObject
import com.narcis.application.presentation.connection.getIntNya
import com.narcis.application.presentation.connection.getStr
import com.google.gson.Gson
import io.nekohasekai.sagernet.ftm.trojan.TrojanBean
import io.nekohasekai.sagernet.ktx.pathSafe
import io.nekohasekai.sagernet.ktx.readableMessage
import io.nekohasekai.sagernet.ktx.urlSafe
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrl
import org.json.JSONObject
fun parseV2Ray(link: String): StandardV2RayBean {
// Try parse stupid formats first
if (!link.contains("?")) {
try {
return parseV2RayN(link)
} catch (e: Exception) {
Logs.i("try v2rayN: " + e.readableMessage)
}
}
try {
return tryResolveVmess4Kitsunebi(link)
} catch (e: Exception) {
Logs.i("try Kitsunebi: " + e.readableMessage)
}
// SagerNet: parse standard format
val bean = VMessBean()
val url = link.replace("vmess://", "https://").toHttpUrl()
if (url.password.isNotBlank()) { // https://github.com/v2fly/v2fly-github-io/issues/26
bean.serverAddress = url.host
bean.serverPort = url.port
bean.name = url.fragment
var protocol = url.username
bean.type = protocol
bean.alterId = url.password.substringAfterLast('-').toInt()
bean.uuid = url.password.substringBeforeLast('-')
if (protocol.endsWith("+tls")) {
bean.security = "tls"
protocol = protocol.substring(0, protocol.length - 4)
url.queryParameter("tlsServerName")?.let {
if (it.isNotBlank()) {
bean.sni = it
}
}
}
when (protocol) {
"tcp" -> {
url.queryParameter("type")?.let { type ->
if (type == "http") {
bean.headerType = "http"
url.queryParameter("host")?.let {
bean.host = it
}
}
}
}
"http" -> {
url.queryParameter("path")?.let {
bean.path = it
}
url.queryParameter("host")?.let {
bean.host = it.split("|").joinToString(",")
}
}
"ws" -> {
url.queryParameter("path")?.let {
bean.path = it
}
url.queryParameter("host")?.let {
bean.host = it
}
}
"kcp" -> {
url.queryParameter("type")?.let {
bean.headerType = it
}
url.queryParameter("seed")?.let {
bean.mKcpSeed = it
}
}
"quic" -> {
url.queryParameter("security")?.let {
bean.quicSecurity = it
}
url.queryParameter("key")?.let {
bean.quicKey = it
}
url.queryParameter("type")?.let {
bean.headerType = it
}
}
}
} else {
bean.parseDuckSoft(url)
}
Logs.d(formatObject(bean))
return bean
}
// https://github.com/XTLS/Xray-core/issues/91
// NO allowInsecure
fun StandardV2RayBean.parseDuckSoft(url: HttpUrl) {
serverAddress = url.host
serverPort = url.port
name = url.fragment
if (this is TrojanBean) {
password = url.username
} else {
uuid = url.username
}
if (url.pathSegments.size > 1 || url.pathSegments[0].isNotBlank()) {
path = url.pathSegments.joinToString("/")
}
type = url.queryParameter("type") ?: "tcp"
security = url.queryParameter("security")
if (security == null) {
security = if (this is TrojanBean) {
"tls"
} else {
"none"
}
}
when (security) {
"tls" -> {
url.queryParameter("sni")?.let {
sni = it
}
url.queryParameter("alpn")?.let {
alpn = it
}
url.queryParameter("cert")?.let {
certificates = it
}
url.queryParameter("chain")?.let {
pinnedPeerCertificateChainSha256 = it
}
}
}
when (type) {
"tcp" -> {
url.queryParameter("headerType")?.let { ht ->
if (ht == "http") {
headerType = ht
url.queryParameter("host")?.let {
host = it
}
url.queryParameter("path")?.let {
path = it
}
}
}
}
"kcp" -> {
url.queryParameter("headerType")?.let {
headerType = it
}
url.queryParameter("seed")?.let {
mKcpSeed = it
}
}
"http" -> {
url.queryParameter("host")?.let {
host = it
}
url.queryParameter("path")?.let {
path = it
}
}
"ws" -> {
url.queryParameter("host")?.let {
host = it
}
url.queryParameter("path")?.let {
path = it
}
url.queryParameter("ed")?.let { ed ->
wsMaxEarlyData = ed.toInt()
url.queryParameter("eh")?.let {
earlyDataHeaderName = it
}
}
}
"quic" -> {
url.queryParameter("headerType")?.let {
headerType = it
}
url.queryParameter("quicSecurity")?.let { qs ->
quicSecurity = qs
url.queryParameter("key")?.let {
quicKey = it
}
}
}
"grpc" -> {
url.queryParameter("serviceName")?.let {
grpcServiceName = it
}
}
}
// maybe from matsuri vmess exoprt
if (this is VMessBean) {
url.queryParameter("encryption")?.let {
encryption = it
}
}
url.queryParameter("packetEncoding")?.let {
when (it) {
"packet" -> packetEncoding = 1
"xudp" -> packetEncoding = 2
}
}
}
// 不确定是谁的格式
private fun tryResolveVmess4Kitsunebi(server: String): VMessBean {
// vmess://YXV0bzo1YWY1ZDBlYy02ZWEwLTNjNDMtOTNkYi1jYTMwMDg1MDNiZGJAMTgzLjIzMi41Ni4xNjE6MTIwMg
// ?remarks=*%F0%9F%87%AF%F0%9F%87%B5JP%20-355%20TG@moon365free&obfsParam=%7B%22Host%22:%22183.232.56.161%22%7D&path=/v2ray&obfs=websocket&alterId=0
var result = server.replace("vmess://", "")
val indexSplit = result.indexOf("?")
if (indexSplit > 0) {
result = result.substring(0, indexSplit)
}
result = NGUtil.decode(result)
val arr1 = result.split('@')
if (arr1.count() != 2) {
throw IllegalStateException("invalid kitsunebi format")
}
val arr21 = arr1[0].split(':')
val arr22 = arr1[1].split(':')
if (arr21.count() != 2) {
throw IllegalStateException("invalid kitsunebi format")
}
return VMessBean().apply {
serverAddress = arr22[0]
serverPort = NGUtil.parseInt(arr22[1])
uuid = arr21[1]
encryption = arr21[0]
if (indexSplit < 0) return@apply
val url = ("https://localhost/path?" + server.substringAfter("?")).toHttpUrl()
url.queryParameter("remarks")?.apply { name = this }
url.queryParameter("alterId")?.apply { alterId = this.toInt() }
url.queryParameter("path")?.apply { path = this }
url.queryParameter("tls")?.apply { security = "tls" }
// url.queryParameter("allowInsecure")
// ?.apply { if (this == "1" || this == "true") allowInsecure = true }
allowInsecure = true
url.queryParameter("obfs")?.apply {
type = this.replace("websocket", "ws").replace("none", "tcp")
if (type == "ws") {
url.queryParameter("obfsParam")?.apply {
if (this.startsWith("{")) {
host = JSONObject(this).getStr("Host")
} else if (security == "tls") {
sni = this
}
}
}
}
}
}
// SagerNet's
// Do not support some format and then throw exception
fun parseV2RayN(link: String): VMessBean {
val result = link.substringAfter("vmess://").decodeBase64UrlSafe()
if (result.contains("= vmess")) {
return parseCsvVMess(result)
}
val bean = VMessBean()
val json = JSONObject(result)
bean.serverAddress = json.getStr("add") ?: ""
bean.serverPort = json.getIntNya("port") ?: 1080
bean.encryption = json.getStr("scy") ?: ""
bean.uuid = json.getStr("id") ?: ""
bean.alterId = json.getIntNya("aid") ?: 0
bean.type = json.getStr("net") ?: ""
bean.headerType = json.getStr("type") ?: ""
bean.host = json.getStr("host") ?: ""
bean.path = json.getStr("path") ?: ""
when (bean.type) {
"quic" -> {
bean.quicSecurity = bean.host
bean.quicKey = bean.path
}
"kcp" -> {
bean.mKcpSeed = bean.path
}
"grpc" -> {
bean.grpcServiceName = bean.path
}
}
bean.name = json.getStr("ps") ?: ""
bean.sni = json.getStr("sni") ?: bean.host
bean.security = json.getStr("tls")
if (json.optInt("v", 2) < 2) {
when (bean.type) {
"ws" -> {
var path = ""
var host = ""
val lstParameter = bean.host.split(";")
if (lstParameter.isNotEmpty()) {
path = lstParameter[0].trim()
}
if (lstParameter.size > 1) {
path = lstParameter[0].trim()
host = lstParameter[1].trim()
}
bean.path = path
bean.host = host
}
"h2" -> {
var path = ""
var host = ""
val lstParameter = bean.host.split(";")
if (lstParameter.isNotEmpty()) {
path = lstParameter[0].trim()
}
if (lstParameter.size > 1) {
path = lstParameter[0].trim()
host = lstParameter[1].trim()
}
bean.path = path
bean.host = host
}
}
}
return bean
}
private fun parseCsvVMess(csv: String): VMessBean {
val args = csv.split(",")
val bean = VMessBean()
bean.serverAddress = args[1]
bean.serverPort = args[2].toInt()
bean.encryption = args[3]
bean.uuid = args[4].replace("\"", "")
args.subList(5, args.size).forEach {
when {
it == "over-tls=true" -> bean.security = "tls"
it.startsWith("tls-host=") -> bean.host = it.substringAfter("=")
it.startsWith("obfs=") -> bean.type = it.substringAfter("=")
it.startsWith("obfs-path=") || it.contains("Host:") -> {
runCatching {
bean.path = it.substringAfter("obfs-path=\"").substringBefore("\"obfs")
}
runCatching {
bean.host = it.substringAfter("Host:").substringBefore("[")
}
}
}
}
return bean
}
data class VmessQRCode(
var v: String = "",
var ps: String = "",
var add: String = "",
var port: String = "",
var id: String = "",
var aid: String = "0",
var scy: String = "",
var net: String = "",
var type: String = "",
var host: String = "",
var path: String = "",
var tls: String = "",
var sni: String = "",
var alpn: String = ""
)
fun VMessBean.toV2rayN(): String {
return "vmess://" + VmessQRCode().apply {
v = "2"
ps = [email protected]
add = [email protected]
port = [email protected]()
id = [email protected]
aid = [email protected]()
net = [email protected]
host = [email protected]
path = [email protected]
type = [email protected]
when ([email protected]) {
"quic" -> {
host = [email protected]
path = [email protected]
}
"kcp" -> {
path = [email protected]
}
"grpc" -> {
path = [email protected]
}
}
tls = if ([email protected] == "tls") "tls" else ""
sni = [email protected]
scy = [email protected]
}.let {
NGUtil.encode(Gson().toJson(it))
}
}
fun StandardV2RayBean.toUri(standard: Boolean = true): String {
if (this is VMessBean && alterId > 0) return toV2rayN()
val builder = linkBuilder().username(if (this is TrojanBean) password else uuid)
.host(serverAddress)
.port(serverPort)
.addQueryParameter("type", type)
if (this !is TrojanBean) builder.addQueryParameter("encryption", encryption)
when (type) {
"tcp" -> {
if (headerType == "http") {
builder.addQueryParameter("headerType", headerType)
if (host.isNotBlank()) {
builder.addQueryParameter("host", host)
}
if (path.isNotBlank()) {
if (standard) {
builder.addQueryParameter("path", path)
} else {
builder.encodedPath(path.pathSafe())
}
}
}
}
"kcp" -> {
if (headerType.isNotBlank() && headerType != "none") {
builder.addQueryParameter("headerType", headerType)
}
if (mKcpSeed.isNotBlank()) {
builder.addQueryParameter("seed", mKcpSeed)
}
}
"ws", "http" -> {
if (host.isNotBlank()) {
builder.addQueryParameter("host", host)
}
if (path.isNotBlank()) {
if (standard) {
builder.addQueryParameter("path", path)
} else {
builder.encodedPath(path.pathSafe())
}
}
if (type == "ws") {
if (wsMaxEarlyData > 0) {
builder.addQueryParameter("ed", "$wsMaxEarlyData")
if (earlyDataHeaderName.isNotBlank()) {
builder.addQueryParameter("eh", earlyDataHeaderName)
}
}
}
}
"quic" -> {
if (headerType.isNotBlank() && headerType != "none") {
builder.addQueryParameter("headerType", headerType)
}
if (quicSecurity.isNotBlank() && quicSecurity != "none") {
builder.addQueryParameter("quicSecurity", quicSecurity)
builder.addQueryParameter("key", quicKey)
}
}
"grpc" -> {
if (grpcServiceName.isNotBlank()) {
builder.addQueryParameter("serviceName", grpcServiceName)
}
}
}
if (security.isNotBlank() && security != "none") {
builder.addQueryParameter("security", security)
when (security) {
"tls" -> {
if (sni.isNotBlank()) {
builder.addQueryParameter("sni", sni)
}
if (alpn.isNotBlank()) {
builder.addQueryParameter("alpn", alpn)
}
if (certificates.isNotBlank()) {
builder.addQueryParameter("cert", certificates)
}
if (pinnedPeerCertificateChainSha256.isNotBlank()) {
builder.addQueryParameter("chain", pinnedPeerCertificateChainSha256)
}
if (allowInsecure) builder.addQueryParameter("allowInsecure", "1")
}
}
}
when (packetEncoding) {
1 -> {
builder.addQueryParameter("packetEncoding", "packet")
}
2 -> {
builder.addQueryParameter("packetEncoding", "xudp")
}
}
if (name.isNotBlank()) {
builder.encodedFragment(name.urlSafe())
}
return builder.toLink("vmess")
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/ftm/v2ray/V2RayFmt.kt | 1555405820 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.ftm.trojan
import io.nekohasekai.sagernet.ftm.v2ray.parseDuckSoft
import io.nekohasekai.sagernet.ftm.v2ray.toUri
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
fun parseTrojan(server: String): TrojanBean {
val link = server.replace("trojan://", "https://").toHttpUrlOrNull()
?: error("invalid trojan link $server")
return TrojanBean().apply {
parseDuckSoft(link)
// link.queryParameter("allowInsecure")
// ?.apply { if (this == "1" || this == "true") allowInsecure = true }
allowInsecure = true
link.queryParameter("peer")?.apply { if (this.isNotBlank()) sni = this }
}
}
fun TrojanBean.toUri(): String {
return toUri(true).replace("vmess://", "trojan://")
}
| Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/ftm/trojan/TrojanFmt.kt | 3793827920 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.ftm
import android.widget.Toast
import com.github.shadowsocks.plugin.PluginConfiguration
import com.github.shadowsocks.plugin.PluginManager
import io.nekohasekai.sagernet.IPv6Mode
import io.nekohasekai.sagernet.Key
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.SagerNet
import io.nekohasekai.sagernet.bg.VpnService
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.database.ProxyEntity
import io.nekohasekai.sagernet.database.SagerDatabase
import io.nekohasekai.sagernet.ftm.gson.gson
import io.nekohasekai.sagernet.ftm.hysteria.isMultiPort
import io.nekohasekai.sagernet.ftm.ssh.SSHBean
import io.nekohasekai.sagernet.ftm.v2ray.V2RayConfig
import io.nekohasekai.sagernet.ftm.v2ray.V2RayConfig.BrowserForwarderObject
import io.nekohasekai.sagernet.ftm.v2ray.V2RayConfig.DNSOutboundConfigurationObject
import io.nekohasekai.sagernet.ftm.v2ray.V2RayConfig.DnsObject
import io.nekohasekai.sagernet.ftm.v2ray.V2RayConfig.DokodemoDoorInboundConfigurationObject
import io.nekohasekai.sagernet.ftm.v2ray.V2RayConfig.FreedomOutboundConfigurationObject
import io.nekohasekai.sagernet.ftm.v2ray.V2RayConfig.GrpcObject
import io.nekohasekai.sagernet.ftm.v2ray.V2RayConfig.HTTPInboundConfigurationObject
import io.nekohasekai.sagernet.ftm.v2ray.V2RayConfig.HTTPOutboundConfigurationObject
import io.nekohasekai.sagernet.ftm.v2ray.V2RayConfig.HttpObject
import io.nekohasekai.sagernet.ftm.v2ray.V2RayConfig.InboundObject
import io.nekohasekai.sagernet.ftm.v2ray.V2RayConfig.KcpObject
import io.nekohasekai.sagernet.ftm.v2ray.V2RayConfig.LazyInboundConfigurationObject
import io.nekohasekai.sagernet.ftm.v2ray.V2RayConfig.LazyOutboundConfigurationObject
import io.nekohasekai.sagernet.ftm.v2ray.V2RayConfig.OutboundObject
import io.nekohasekai.sagernet.ftm.v2ray.V2RayConfig.PolicyObject
import io.nekohasekai.sagernet.ftm.v2ray.V2RayConfig.QuicObject
import io.nekohasekai.sagernet.ftm.v2ray.V2RayConfig.ReverseObject
import io.nekohasekai.sagernet.ftm.v2ray.V2RayConfig.RoutingObject
import io.nekohasekai.sagernet.ftm.v2ray.V2RayConfig.SSHOutbountConfigurationObject
import io.nekohasekai.sagernet.ftm.v2ray.V2RayConfig.ShadowsocksOutboundConfigurationObject
import io.nekohasekai.sagernet.ftm.v2ray.V2RayConfig.SocksInboundConfigurationObject
import io.nekohasekai.sagernet.ftm.v2ray.V2RayConfig.SocksOutboundConfigurationObject
import io.nekohasekai.sagernet.ftm.v2ray.V2RayConfig.StreamSettingsObject
import io.nekohasekai.sagernet.ftm.v2ray.V2RayConfig.TLSObject
import io.nekohasekai.sagernet.ftm.v2ray.V2RayConfig.TcpObject
import io.nekohasekai.sagernet.ftm.v2ray.V2RayConfig.TrojanOutboundConfigurationObject
import io.nekohasekai.sagernet.ftm.v2ray.V2RayConfig.UTLSObject
import io.nekohasekai.sagernet.ftm.v2ray.V2RayConfig.VMessOutboundConfigurationObject
import io.nekohasekai.sagernet.ftm.v2ray.V2RayConfig.WebSocketObject
import io.nekohasekai.sagernet.ktx.isIpAddress
import io.nekohasekai.sagernet.ktx.mkPort
import io.nekohasekai.sagernet.utils.PackageCache
import moe.matsuri.nya.DNS.applyDNSNetworkSettings
import moe.matsuri.nya.neko.Plugins
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
const val TAG_SOCKS = "socks"
const val TAG_HTTP = "http"
const val TAG_TRANS = "trans"
const val TAG_DIRECT = "direct"
const val TAG_BYPASS = "bypass"
const val TAG_BLOCK = "block"
const val TAG_DNS_IN = "dns-in"
const val TAG_DNS_OUT = "dns-out"
const val LOCALHOST = "127.0.0.1"
class V2rayBuildResult(
var config: String,
var index: List<IndexEntity>,
var wsPort: Int,
var outboundTags: List<String>,
var outboundTagsCurrent: List<String>,
var outboundTagsAll: Map<String, ProxyEntity>,
var bypassTag: String,
val dumpUid: Boolean,
val tryDomains: List<String>,
) {
data class IndexEntity(var chain: LinkedHashMap<Int, ProxyEntity>)
}
fun buildV2RayConfig(
proxy: ProxyEntity,
forTest: Boolean = false,
): io.nekohasekai.sagernet.ftm.V2rayBuildResult {
val outboundTags = ArrayList<String>()
val outboundTagsCurrent = ArrayList<String>()
val outboundTagsAll = HashMap<String, ProxyEntity>()
val globalOutbounds = ArrayList<Long>()
fun ProxyEntity.resolveChain(): MutableList<ProxyEntity> {
val bean = requireBean()
if (bean is io.nekohasekai.sagernet.ftm.internal.ChainBean) {
val beans = SagerDatabase.proxyDao.getEntities(bean.proxies)
val beansMap = beans.associateBy { it.id }
val beanList = ArrayList<ProxyEntity>()
for (proxyId in bean.proxies) {
val item = beansMap[proxyId] ?: continue
beanList.addAll(item.resolveChain())
}
return beanList.asReversed()
}
return mutableListOf(this)
}
val proxies = proxy.resolveChain()
val extraRules = if (forTest) listOf() else SagerDatabase.rulesDao.enabledRules()
val extraProxies =
if (forTest) {
mapOf()
} else {
SagerDatabase.proxyDao.getEntities(
extraRules.mapNotNull { rule ->
rule.outbound.takeIf { it > 0 && it != proxy.id }
}.toHashSet().toList()
).map { it.id to it.resolveChain() }.toMap()
}
val uidListDNSRemote = mutableListOf<Int>()
val uidListDNSDirect = mutableListOf<Int>()
val domainListDNSRemote = mutableListOf<String>()
val domainListDNSDirect = mutableListOf<String>()
val bypassDNSBeans = hashSetOf<io.nekohasekai.sagernet.ftm.AbstractBean>()
val allowAccess = DataStore.allowAccess
val bind = if (!forTest && allowAccess) "0.0.0.0" else LOCALHOST
var remoteDns = DataStore.remoteDns.split("\n")
.mapNotNull { dns -> dns.trim().takeIf { it.isNotBlank() && !it.startsWith("#") } }
var directDNS = DataStore.directDns.split("\n")
.mapNotNull { dns -> dns.trim().takeIf { it.isNotBlank() && !it.startsWith("#") } }
val enableDnsRouting = DataStore.enableDnsRouting
val useFakeDns = DataStore.enableFakeDns && !forTest
val trafficSniffing = DataStore.trafficSniffing
val indexMap = ArrayList<V2rayBuildResult.IndexEntity>()
val requireHttp = !forTest && DataStore.requireHttp
val requireTransproxy = if (forTest) false else DataStore.requireTransproxy
val ipv6Mode = if (forTest) IPv6Mode.ENABLE else DataStore.ipv6Mode
val resolveDestination = DataStore.resolveDestination
val trafficStatistics = !forTest && DataStore.profileTrafficStatistics
val tryDomains = mutableListOf<String>()
var dumpUid = false
return V2RayConfig().apply {
dns = DnsObject().apply {
fallbackStrategy = "disabled_if_any_match"
hosts = DataStore.hosts.split("\n")
.filter { it.isNotBlank() }
.associate { it.substringBefore(" ") to it.substringAfter(" ") }
.toMutableMap()
if (useFakeDns) {
fakedns = mutableListOf()
fakedns.add(
V2RayConfig.FakeDnsObject().apply {
ipPool = "${VpnService.FAKEDNS_VLAN4_CLIENT}/15"
poolSize = 65535
}
)
remoteDns = listOf("fakedns")
}
servers = mutableListOf()
servers.addAll(
remoteDns.map {
DnsObject.StringOrServerObject().apply {
valueY = DnsObject.ServerObject().apply {
address = it
applyDNSNetworkSettings(false)
}
}
}
)
when (ipv6Mode) {
IPv6Mode.DISABLE -> {
queryStrategy = "UseIPv4"
}
IPv6Mode.ONLY -> {
queryStrategy = "UseIPv6"
}
}
}
log = V2RayConfig.LogObject().apply {
loglevel = if (DataStore.enableLog) "debug" else "error"
}
policy = PolicyObject().apply {
levels = mapOf(
// dns
"1" to PolicyObject.LevelPolicyObject().apply {
connIdle = 30
}
)
if (trafficStatistics) {
system = PolicyObject.SystemPolicyObject().apply {
statsOutboundDownlink = true
statsOutboundUplink = true
}
}
}
inbounds = mutableListOf()
if (!forTest) {
inbounds.add(
InboundObject().apply {
tag = TAG_SOCKS
listen = bind
port = DataStore.socksPort
protocol = "socks"
settings = LazyInboundConfigurationObject(
this,
SocksInboundConfigurationObject().apply {
auth = "noauth"
udp = true
}
)
if (trafficSniffing || useFakeDns) {
sniffing = InboundObject.SniffingObject().apply {
enabled = true
destOverride = when {
useFakeDns && !trafficSniffing -> listOf("fakedns")
useFakeDns -> listOf("fakedns", "http", "tls", "quic")
else -> listOf("http", "tls", "quic")
}
metadataOnly = useFakeDns && !trafficSniffing
routeOnly = true
}
}
}
)
}
if (requireHttp) {
inbounds.add(
InboundObject().apply {
tag = TAG_HTTP
listen = bind
port = DataStore.httpPort
protocol = "http"
settings = LazyInboundConfigurationObject(
this,
HTTPInboundConfigurationObject().apply {
allowTransparent = true
}
)
if (trafficSniffing || useFakeDns) {
sniffing = InboundObject.SniffingObject().apply {
enabled = true
destOverride = when {
useFakeDns && !trafficSniffing -> listOf("fakedns")
useFakeDns -> listOf("fakedns", "http", "tls")
else -> listOf("http", "tls")
}
metadataOnly = useFakeDns && !trafficSniffing
routeOnly = true
}
}
}
)
}
if (requireTransproxy) {
inbounds.add(
InboundObject().apply {
tag = TAG_TRANS
listen = bind
port = DataStore.transproxyPort
protocol = "dokodemo-door"
settings = LazyInboundConfigurationObject(
this,
DokodemoDoorInboundConfigurationObject().apply {
network = "tcp,udp"
followRedirect = true
}
)
if (trafficSniffing || useFakeDns) {
sniffing = InboundObject.SniffingObject().apply {
enabled = true
destOverride = when {
useFakeDns && !trafficSniffing -> listOf("fakedns")
useFakeDns -> listOf("fakedns", "http", "tls", "quic")
else -> listOf("http", "tls", "quic")
}
metadataOnly = useFakeDns && !trafficSniffing
routeOnly = true
}
}
when (DataStore.transproxyMode) {
1 -> streamSettings = StreamSettingsObject().apply {
sockopt = StreamSettingsObject.SockoptObject().apply {
tproxy = "tproxy"
}
}
}
}
)
}
outbounds = mutableListOf()
// init routing object
// set rules for wsUseBrowserForwarder and bypass LAN
routing = RoutingObject().apply {
domainStrategy = DataStore.domainStrategy
rules = mutableListOf()
val wsRules = HashMap<String, RoutingObject.RuleObject>()
for (proxyEntity in proxies) {
val bean = proxyEntity.requireBean()
if (bean is io.nekohasekai.sagernet.ftm.v2ray.StandardV2RayBean && bean.type == "ws" && bean.wsUseBrowserForwarder == true) {
val route = RoutingObject.RuleObject().apply {
type = "field"
outboundTag = TAG_DIRECT
when {
bean.host.isIpAddress() -> {
ip = listOf(bean.host)
}
bean.host.isNotBlank() -> {
domain = listOf(bean.host)
}
bean.serverAddress.isIpAddress() -> {
ip = listOf(bean.serverAddress)
}
else -> domain = listOf(bean.serverAddress)
}
}
wsRules[bean.host.takeIf { !it.isNullOrBlank() } ?: bean.serverAddress] = route
}
}
rules.addAll(wsRules.values)
if (!forTest && (requireHttp || DataStore.bypassLanInCore)) {
rules.add(
RoutingObject.RuleObject().apply {
type = "field"
outboundTag = TAG_BYPASS
ip = listOf("geoip:private")
}
)
}
}
// returns outbound tag
fun buildChain(
chainId: Long,
profileList: List<ProxyEntity>,
): String {
lateinit var currentOutbound: OutboundObject
lateinit var pastOutbound: OutboundObject
lateinit var pastInboundTag: String
var pastEntity: ProxyEntity? = null
val chainMap = LinkedHashMap<Int, ProxyEntity>()
indexMap.add(
V2rayBuildResult.IndexEntity(
chainMap
)
)
val chainOutbounds = ArrayList<OutboundObject>()
// chainTagOut: v2ray outbound tag for this chain
var chainTagOut = ""
val chainTag = "c-$chainId"
var muxApplied = false
// v2sekai's outbound domainStrategy
fun genDomainStrategy(noAsIs: Boolean): String {
return when {
!resolveDestination && !noAsIs -> "AsIs"
ipv6Mode == IPv6Mode.DISABLE -> "UseIPv4"
ipv6Mode == IPv6Mode.PREFER -> "PreferIPv6"
ipv6Mode == IPv6Mode.ONLY -> "UseIPv6"
else -> "PreferIPv4"
}
}
var currentDomainStrategy = genDomainStrategy(false)
profileList.forEachIndexed { index, proxyEntity ->
val bean = proxyEntity.requireBean()
currentOutbound = OutboundObject()
// tagOut: v2ray outbound tag for a profile
// profile2 (in) (global) tag g-(id)
// profile1 tag (chainTag)-(id)
// profile0 (out) tag (chainTag)-(id) / single: "proxy"
var tagOut = "$chainTag-${proxyEntity.id}"
// needGlobal: can only contain one?
var needGlobal = false
// first profile set as global
if (index == profileList.lastIndex) {
needGlobal = true
tagOut = "g-" + proxyEntity.id
bypassDNSBeans += proxyEntity.requireBean()
}
// last profile set as "proxy"
if (chainId == 0L && index == 0) {
tagOut = "proxy"
}
// chain rules
if (index > 0) {
// chain route/proxy rules
if (!pastEntity!!.needExternal()) {
pastOutbound.proxySettings = OutboundObject.ProxySettingsObject().apply {
tag = tagOut
transportLayer = true
}
} else {
routing.rules.add(
RoutingObject.RuleObject().apply {
type = "field"
inboundTag = listOf(pastInboundTag)
outboundTag = tagOut
}
)
}
} else {
// index == 0 means last profile in chain / not chain
chainTagOut = tagOut
outboundTags.add(tagOut)
if (chainId == 0L) outboundTagsCurrent.add(tagOut)
}
if (needGlobal) {
if (globalOutbounds.contains(proxyEntity.id)) {
return@forEachIndexed
}
globalOutbounds.add(proxyEntity.id)
}
outboundTagsAll[tagOut] = proxyEntity
// Chain outbound
if (proxyEntity.needExternal()) {
val localPort = mkPort()
chainMap[localPort] = proxyEntity
currentOutbound.apply {
protocol = "socks"
settings = LazyOutboundConfigurationObject(
this,
SocksOutboundConfigurationObject().apply {
servers = listOf(
SocksOutboundConfigurationObject.ServerObject()
.apply {
address =
LOCALHOST
port = localPort
}
)
}
)
}
} else { // internal outbound
currentOutbound.apply {
val keepAliveInterval = DataStore.tcpKeepAliveInterval
val needKeepAliveInterval = keepAliveInterval !in intArrayOf(0, 15)
if (bean is io.nekohasekai.sagernet.ftm.v2ray.StandardV2RayBean) {
when (bean) {
is io.nekohasekai.sagernet.ftm.socks.SOCKSBean -> {
protocol = "socks"
settings = LazyOutboundConfigurationObject(
this,
SocksOutboundConfigurationObject().apply {
servers =
listOf(
SocksOutboundConfigurationObject.ServerObject()
.apply {
address = bean.serverAddress
port = bean.serverPort
if (!bean.username.isNullOrBlank()) {
users = listOf(
SocksOutboundConfigurationObject.ServerObject.UserObject()
.apply {
user = bean.username
pass = bean.password
}
)
}
}
)
version = bean.protocolVersionName()
}
)
}
is io.nekohasekai.sagernet.ftm.http.HttpBean -> {
protocol = "http"
settings = LazyOutboundConfigurationObject(
this,
HTTPOutboundConfigurationObject().apply {
servers =
listOf(
HTTPOutboundConfigurationObject.ServerObject()
.apply {
address = bean.serverAddress
port = bean.serverPort
if (!bean.username.isNullOrBlank()) {
users = listOf(
HTTPInboundConfigurationObject.AccountObject()
.apply {
user = bean.username
pass = bean.password
}
)
}
}
)
}
)
}
is io.nekohasekai.sagernet.ftm.v2ray.VMessBean -> {
protocol = "vmess"
settings = LazyOutboundConfigurationObject(
this,
VMessOutboundConfigurationObject().apply {
vnext =
listOf(
VMessOutboundConfigurationObject.ServerObject()
.apply {
address = bean.serverAddress
port = bean.serverPort
users =
listOf(
VMessOutboundConfigurationObject.ServerObject.UserObject()
.apply {
id = bean.uuid
alterId = bean.alterId
security =
bean.encryption.takeIf { it.isNotBlank() }
?: "auto"
experimental = ""
if (bean.experimentalAuthenticatedLength) {
experimental += "AuthenticatedLength"
}
if (bean.experimentalNoTerminationSignal) {
experimental += "NoTerminationSignal"
}
if (experimental.isBlank()) {
experimental =
null
}
}
)
when (bean.packetEncoding) {
1 -> {
packetEncoding = "packet"
currentDomainStrategy =
genDomainStrategy(
true
)
}
2 -> packetEncoding = "xudp"
}
}
)
}
)
}
is io.nekohasekai.sagernet.ftm.trojan.TrojanBean -> {
protocol = "trojan"
settings = LazyOutboundConfigurationObject(
this,
TrojanOutboundConfigurationObject().apply {
servers =
listOf(
TrojanOutboundConfigurationObject.ServerObject()
.apply {
address = bean.serverAddress
port = bean.serverPort
password = bean.password
}
)
}
)
}
}
streamSettings = StreamSettingsObject().apply {
network = bean.type
if (bean.security.isNotBlank()) {
security = bean.security
}
val v5_utls = bean.utlsFingerprint.isNotBlank()
if (security == "tls") {
tlsSettings = TLSObject().apply {
if (bean.sni.isNotBlank()) {
serverName = bean.sni
}
if (bean.alpn.isNotBlank()) {
val ds = bean.alpn.split("\n")
.filter { it.isNotBlank() }
if (v5_utls) {
nextProtocol = ds
} else {
alpn = ds
}
}
if (bean.certificates.isNotBlank()) {
disableSystemRoot = true
certificates = listOf(
TLSObject.CertificateObject()
.apply {
usage =
if (v5_utls) "ENCIPHERMENT" else "verify"
certificate = bean.certificates.split("\n")
.filter { it.isNotBlank() }
}
)
}
if (bean.pinnedPeerCertificateChainSha256.isNotBlank()) {
pinnedPeerCertificateChainSha256 =
bean.pinnedPeerCertificateChainSha256.split("\n")
.filter { it.isNotBlank() }
}
if (bean.allowInsecure) {
allowInsecure = true
}
}
if (v5_utls) {
utlsSettings = UTLSObject().apply {
imitate = bean.utlsFingerprint
tlsConfig = tlsSettings
}
tlsSettings = null
security = "utls"
}
}
when (network) {
"tcp" -> {
tcpSettings = TcpObject().apply {
if (bean.headerType == "http") {
header = TcpObject.HeaderObject().apply {
type = "http"
if (bean.host.isNotBlank() || bean.path.isNotBlank()) {
request =
TcpObject.HeaderObject.HTTPRequestObject()
.apply {
headers = mutableMapOf()
if (bean.host.isNotBlank()) {
headers["Host"] =
TcpObject.HeaderObject.StringOrListObject()
.apply {
valueY =
bean.host.split(
","
)
.map { it.trim() }
}
}
if (bean.path.isNotBlank()) {
path = bean.path.split(",")
}
}
}
}
}
}
}
"kcp" -> {
kcpSettings = KcpObject().apply {
mtu = 1350
tti = 50
uplinkCapacity = 12
downlinkCapacity = 100
congestion = false
readBufferSize = 1
writeBufferSize = 1
header = KcpObject.HeaderObject().apply {
type = bean.headerType
}
if (bean.mKcpSeed.isNotBlank()) {
seed = bean.mKcpSeed
}
}
}
"ws" -> {
wsSettings = WebSocketObject().apply {
headers = mutableMapOf()
if (bean.host.isNotBlank()) {
headers["Host"] = bean.host
}
path = bean.path.takeIf { it.isNotBlank() } ?: "/"
if (bean.wsMaxEarlyData > 0) {
maxEarlyData = bean.wsMaxEarlyData
}
if (bean.earlyDataHeaderName.isNotBlank()) {
earlyDataHeaderName = bean.earlyDataHeaderName
}
if (bean.wsUseBrowserForwarder) {
useBrowserForwarding = true
browserForwarder = BrowserForwarderObject().apply {
listenAddr =
LOCALHOST
listenPort = mkPort()
}
}
}
}
"http" -> {
network = "http"
httpSettings = HttpObject().apply {
if (bean.host.isNotBlank()) {
host = bean.host.split(",")
}
path = bean.path.takeIf { it.isNotBlank() } ?: "/"
}
}
"quic" -> {
quicSettings = QuicObject().apply {
security = bean.quicSecurity.takeIf { it.isNotBlank() }
?: "none"
key = bean.quicKey
header = QuicObject.HeaderObject().apply {
type = bean.headerType.takeIf { it.isNotBlank() }
?: "none"
}
}
}
"grpc" -> {
grpcSettings = GrpcObject().apply {
serviceName = bean.grpcServiceName
}
}
}
if (needKeepAliveInterval) {
sockopt = StreamSettingsObject.SockoptObject().apply {
tcpKeepAliveInterval = keepAliveInterval
}
}
}
} else if (bean is io.nekohasekai.sagernet.ftm.shadowsocks.ShadowsocksBean || bean is io.nekohasekai.sagernet.ftm.shadowsocksr.ShadowsocksRBean) {
protocol = "shadowsocks"
settings = LazyOutboundConfigurationObject(
this,
ShadowsocksOutboundConfigurationObject().apply {
servers =
listOf(
ShadowsocksOutboundConfigurationObject.ServerObject()
.apply {
address = bean.serverAddress
port = bean.serverPort
when (bean) {
is io.nekohasekai.sagernet.ftm.shadowsocks.ShadowsocksBean -> {
method = bean.method
password = bean.password
experimentReducedIvHeadEntropy =
bean.experimentReducedIvHeadEntropy
}
is io.nekohasekai.sagernet.ftm.shadowsocksr.ShadowsocksRBean -> {
method = bean.method
password = bean.password
}
}
}
)
if (needKeepAliveInterval) {
streamSettings = StreamSettingsObject().apply {
sockopt = StreamSettingsObject.SockoptObject().apply {
tcpKeepAliveInterval = keepAliveInterval
}
}
}
if (bean is io.nekohasekai.sagernet.ftm.shadowsocksr.ShadowsocksRBean) {
plugin = "shadowsocksr"
pluginArgs = listOf(
"--obfs=${bean.obfs}",
"--obfs-param=${bean.obfsParam}",
"--protocol=${bean.protocol}",
"--protocol-param=${bean.protocolParam}"
)
} else if (bean is io.nekohasekai.sagernet.ftm.shadowsocks.ShadowsocksBean && bean.plugin.isNotBlank()) {
val pluginConfiguration = PluginConfiguration(bean.plugin)
try {
PluginManager.init(pluginConfiguration)
?.let { (path, opts, _) ->
plugin = path
pluginOpts = opts.toString()
// Shadowsocks 传统艺能
if (DataStore.serviceMode == Key.MODE_VPN) {
pluginArgs = listOf("-V")
}
}
} catch (e: PluginManager.PluginNotFoundException) {
if (e.plugin in arrayOf("v2ray-plugin", "obfs-local")) {
plugin = e.plugin
pluginOpts = pluginConfiguration.getOptions()
.toString()
} else {
throw e
}
}
}
}
)
} else if (bean is io.nekohasekai.sagernet.ftm.ssh.SSHBean) {
protocol = "ssh"
settings = LazyOutboundConfigurationObject(
this,
SSHOutbountConfigurationObject().apply {
address = bean.finalAddress
port = bean.finalPort
user = bean.username
when (bean.authType) {
SSHBean.AUTH_TYPE_PRIVATE_KEY -> {
privateKey = bean.privateKey
password = bean.privateKeyPassphrase
}
else -> {
password = bean.password
}
}
publicKey = bean.publicKey
}
)
streamSettings = StreamSettingsObject().apply {
if (needKeepAliveInterval) {
sockopt = StreamSettingsObject.SockoptObject().apply {
tcpKeepAliveInterval = keepAliveInterval
}
}
}
}
if (!muxApplied && proxyEntity.needCoreMux()) {
muxApplied = true
mux = OutboundObject.MuxObject().apply {
enabled = true
concurrency = DataStore.muxConcurrency
if (bean is io.nekohasekai.sagernet.ftm.v2ray.StandardV2RayBean) {
when (bean.packetEncoding) {
1 -> {
packetEncoding = "packet"
}
2 -> {
packetEncoding = "xudp"
}
}
}
}
}
}
}
pastEntity?.requireBean()?.apply {
// don't loopback
if (currentDomainStrategy != "AsIs" && !serverAddress.isIpAddress()) {
domainListDNSDirect.add("full:$serverAddress")
}
}
if (forTest) {
currentDomainStrategy = "AsIs"
}
currentOutbound.tag = tagOut
currentOutbound.domainStrategy = currentDomainStrategy
// External proxy need a dokodemo-door inbound to forward the traffic
// For external proxy software, their traffic must goes to v2ray-core to use protected fd.
if (bean.canMapping() && proxyEntity.needExternal()) {
// With ss protect, don't use mapping
var needExternal = true
if (index == profileList.lastIndex) {
val pluginId = when (bean) {
is io.nekohasekai.sagernet.ftm.hysteria.HysteriaBean -> "hysteria-plugin"
is io.nekohasekai.sagernet.ftm.wireguard.WireGuardBean -> "wireguard-plugin"
is io.nekohasekai.sagernet.ftm.tuic.TuicBean -> "tuic-plugin"
else -> ""
}
if (Plugins.isUsingMatsuriExe(pluginId)) {
needExternal = false
}
}
if (needExternal) {
val mappingPort = mkPort()
bean.finalAddress = LOCALHOST
bean.finalPort = mappingPort
inbounds.add(
InboundObject().apply {
listen = LOCALHOST
port = mappingPort
tag = "$chainTag-mapping-${proxyEntity.id}"
protocol = "dokodemo-door"
settings = LazyInboundConfigurationObject(
this,
DokodemoDoorInboundConfigurationObject().apply {
address = bean.serverAddress
network = bean.network()
port = bean.serverPort
}
)
pastInboundTag = tag
// no chain rule and not outbound, so need to set to direct
if (index == profileList.lastIndex) {
routing.rules.add(
RoutingObject.RuleObject().apply {
type = "field"
inboundTag = listOf(tag)
outboundTag =
TAG_DIRECT
}
)
}
}
)
}
}
outbounds.add(currentOutbound)
chainOutbounds.add(currentOutbound)
pastOutbound = currentOutbound
pastEntity = proxyEntity
}
return chainTagOut
}
val tagProxy = buildChain(0, proxies)
val tagMap = mutableMapOf<Long, String>()
extraProxies.forEach { (key, entities) ->
tagMap[key] = buildChain(key, entities)
}
val notVpn = DataStore.serviceMode != Key.MODE_VPN
// apply user rules
for (rule in extraRules) {
val _uidList = rule.packages.map {
PackageCache[it]?.takeIf { uid -> uid >= 1000 }
}.toHashSet().filterNotNull()
if (rule.packages.isNotEmpty()) {
dumpUid = true
if (notVpn) {
Toast.makeText(
SagerNet.application,
SagerNet.application.getString(R.string.route_need_vpn, rule.displayName()),
Toast.LENGTH_SHORT
).show()
continue
}
}
val ruleObj = RoutingObject.RuleObject().apply {
type = "field"
if (rule.packages.isNotEmpty()) {
PackageCache.awaitLoadSync()
uidList = _uidList
}
var _domainList: List<String>? = null
if (rule.domains.isNotBlank()) {
domain = rule.domains.split("\n")
_domainList = domain
}
if (rule.ip.isNotBlank()) {
ip = rule.ip.split("\n")
}
if (rule.port.isNotBlank()) {
port = rule.port
}
if (rule.sourcePort.isNotBlank()) {
sourcePort = rule.sourcePort
}
if (rule.network.isNotBlank()) {
network = rule.network
}
if (rule.source.isNotBlank()) {
source = rule.source.split("\n")
}
if (rule.protocol.isNotBlank()) {
protocol = rule.protocol.split("\n")
}
if (rule.attrs.isNotBlank()) {
attrs = rule.attrs
}
if (rule.reverse) inboundTag = listOf("reverse-${rule.id}")
// also bypass lookup
// cannot use other outbound profile to lookup...
if (rule.outbound == -1L) {
uidListDNSDirect += _uidList
if (_domainList != null) domainListDNSDirect += _domainList
} else if (rule.outbound == 0L) {
uidListDNSRemote += _uidList
if (_domainList != null) domainListDNSRemote += _domainList
}
outboundTag = when (val outId = rule.outbound) {
0L -> tagProxy
-1L -> TAG_BYPASS
-2L -> TAG_BLOCK
else -> if (outId == proxy.id) tagProxy else tagMap[outId] ?: ""
}
}
if (ruleObj.outboundTag.isNullOrBlank()) {
Toast.makeText(
SagerNet.application,
"Warning: " + rule.displayName() + ": A non-existent outbound was specified.",
Toast.LENGTH_LONG
).show()
} else {
routing.rules.add(ruleObj)
}
if (rule.reverse) {
outbounds.add(
OutboundObject().apply {
tag = "reverse-out-${rule.id}"
protocol = "freedom"
settings = LazyOutboundConfigurationObject(
this,
FreedomOutboundConfigurationObject().apply {
redirect = rule.redirect
}
)
}
)
if (reverse == null) {
reverse = ReverseObject().apply {
bridges = ArrayList()
}
}
reverse.bridges.add(
ReverseObject.BridgeObject().apply {
tag = "reverse-${rule.id}"
domain = rule.domains.substringAfter("full:")
}
)
routing.rules.add(
RoutingObject.RuleObject().apply {
type = "field"
inboundTag = listOf("reverse-${rule.id}")
outboundTag = "reverse-out-${rule.id}"
}
)
}
}
for (freedom in arrayOf(
TAG_DIRECT,
TAG_BYPASS
)) outbounds.add(
OutboundObject().apply {
tag = freedom
protocol = "freedom"
}
)
outbounds.add(
OutboundObject().apply {
tag = TAG_BLOCK
protocol = "blackhole"
}
)
if (!forTest) {
inbounds.add(
InboundObject().apply {
tag = TAG_DNS_IN
listen = bind
port = DataStore.localDNSPort
protocol = "dokodemo-door"
settings = LazyInboundConfigurationObject(
this,
DokodemoDoorInboundConfigurationObject().apply {
address = if (!remoteDns.first().isIpAddress()) {
"8.8.8.8"
} else {
remoteDns.first()
}
network = "tcp,udp"
port = 53
}
)
}
)
outbounds.add(
OutboundObject().apply {
protocol = "dns"
tag = TAG_DNS_OUT
settings = LazyOutboundConfigurationObject(
this,
DNSOutboundConfigurationObject().apply {
userLevel = 1
var dns = remoteDns.first()
if (dns.contains(":")) {
val lPort = dns.substringAfterLast(":")
dns = dns.substringBeforeLast(":")
lPort.toIntOrNull()?.apply { port = this }
}
if (dns.isIpAddress()) {
address = dns
} else if (dns.contains("://")) {
network = "tcp"
address = dns.substringAfter("://")
}
}
)
}
)
}
if (DataStore.directDnsUseSystem) {
// finally able to use "localDns" now...
directDNS = listOf("localhost")
}
// routing for DNS server
for (dns in remoteDns) {
if (!dns.isIpAddress()) continue
routing.rules.add(
0,
RoutingObject.RuleObject().apply {
type = "field"
outboundTag = tagProxy
ip = listOf(dns)
}
)
}
for (dns in directDNS) {
if (!dns.isIpAddress()) continue
routing.rules.add(
0,
RoutingObject.RuleObject().apply {
type = "field"
outboundTag = TAG_DIRECT
ip = listOf(dns)
}
)
}
// No need to "bypass IP"
// see buildChain()
val directLookupDomain = HashSet<String>()
// Bypass Lookup for the first profile
bypassDNSBeans.forEach {
var serverAddr = it.serverAddress
if (it is io.nekohasekai.sagernet.ftm.hysteria.HysteriaBean && it.isMultiPort()) {
serverAddr = it.serverAddress.substringBeforeLast(":")
}
if (!serverAddr.isIpAddress()) {
directLookupDomain.add("full:$serverAddr")
if (DataStore.enhanceDomain) tryDomains.add(serverAddr)
}
}
remoteDns.forEach {
var address = it
if (address.contains("://")) {
address = address.substringAfter("://")
}
"https://$address".toHttpUrlOrNull()?.apply {
if (!host.isIpAddress()) {
directLookupDomain.add("full:$host")
}
}
}
// dns object user rules
if (enableDnsRouting) {
dns.servers[0].valueY?.uidList = uidListDNSRemote.toHashSet().toList()
dns.servers[0].valueY?.domains = domainListDNSRemote.toHashSet().toList()
directLookupDomain += domainListDNSDirect
}
// add directDNS objects here
if (directLookupDomain.isNotEmpty() || uidListDNSDirect.isNotEmpty()) {
dns.servers.addAll(
directDNS.map {
DnsObject.StringOrServerObject().apply {
valueY = DnsObject.ServerObject().apply {
address = it.replace("https://", "https+local://")
domains = directLookupDomain.toList()
uidList = uidListDNSDirect.toHashSet().toList()
fallbackStrategy = "disabled"
applyDNSNetworkSettings(true)
}
}
}
)
}
// Disable v2ray DNS for test (already remove in Go)
if (forTest) dns.servers.clear()
if (!forTest) {
routing.rules.add(
0,
RoutingObject.RuleObject().apply {
type = "field"
inboundTag = listOf( TAG_DNS_IN)
outboundTag = TAG_DNS_OUT
}
)
}
if (allowAccess) {
// temp: fix crash
routing.rules.add(
RoutingObject.RuleObject().apply {
type = "field"
ip = listOf("255.255.255.255")
outboundTag = TAG_BLOCK
}
)
}
if (trafficStatistics) stats = emptyMap()
}.let {
V2rayBuildResult(
gson.toJson(it),
indexMap,
it.browserForwarder?.listenPort ?: 0,
outboundTags,
outboundTagsCurrent,
outboundTagsAll,
TAG_BYPASS,
dumpUid,
tryDomains
)
}
}
| Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/ftm/ConfigBuilder.kt | 2322309366 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.ftm.hysteria
import io.nekohasekai.sagernet.ktx.isIpAddress
import io.nekohasekai.sagernet.ktx.linkBuilder
import io.nekohasekai.sagernet.ktx.toLink
import io.nekohasekai.sagernet.ktx.wrapIPV6Host
import io.nekohasekai.sagernet.ktx.wrapUri
import com.narcis.application.presentation.connection.getBool
import com.narcis.application.presentation.connection.getIntNya
import com.narcis.application.presentation.connection.getStr
import com.narcis.application.presentation.connection.toStringPretty
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.ftm.LOCALHOST
import io.nekohasekai.sagernet.ktx.urlSafe
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import org.json.JSONObject
import java.io.File
// hysteria://host:port?auth=123456&peer=sni.domain&insecure=1|0&upmbps=100&downmbps=100&alpn=hysteria&obfs=xplus&obfsParam=123456#remarks
fun parseHysteria(url: String): HysteriaBean {
val link = url.replace("hysteria://", "https://").toHttpUrlOrNull() ?: error(
"invalid hysteria link $url"
)
return HysteriaBean().apply {
serverAddress = link.host
serverPort = link.port
name = link.fragment
link.queryParameter("mport")?.also {
serverAddress = serverAddress.wrapIPV6Host() + ":" + it
}
link.queryParameter("peer")?.also {
sni = it
}
link.queryParameter("auth")?.takeIf { it.isNotBlank() }?.also {
authPayloadType = HysteriaBean.TYPE_STRING
authPayload = it
}
link.queryParameter("insecure")?.also {
allowInsecure = it == "1"
}
link.queryParameter("upmbps")?.also {
uploadMbps = it.toIntOrNull() ?: uploadMbps
}
link.queryParameter("downmbps")?.also {
downloadMbps = it.toIntOrNull() ?: downloadMbps
}
link.queryParameter("alpn")?.also {
alpn = it
}
link.queryParameter("obfsParam")?.also {
obfuscation = it
}
link.queryParameter("protocol")?.also {
when (it) {
"faketcp" -> {
protocol = HysteriaBean.PROTOCOL_FAKETCP
}
"wechat-video" -> {
protocol = HysteriaBean.PROTOCOL_WECHAT_VIDEO
}
}
}
}
}
fun HysteriaBean.toUri(): String {
val builder = linkBuilder().host(serverAddress.substringBeforeLast(":")).port(serverPort)
if (isMultiPort()) {
builder.addQueryParameter("mport", serverAddress.substringAfterLast(":"))
}
if (allowInsecure) {
builder.addQueryParameter("insecure", "1")
}
if (sni.isNotBlank()) {
builder.addQueryParameter("peer", sni)
}
if (authPayload.isNotBlank()) {
builder.addQueryParameter("auth", authPayload)
}
builder.addQueryParameter("upmbps", "$uploadMbps")
builder.addQueryParameter("downmbps", "$downloadMbps")
if (alpn.isNotBlank()) {
builder.addQueryParameter("alpn", alpn)
}
if (obfuscation.isNotBlank()) {
builder.addQueryParameter("obfs", "xplus")
builder.addQueryParameter("obfsParam", obfuscation)
}
when (protocol) {
HysteriaBean.PROTOCOL_FAKETCP -> {
builder.addQueryParameter("protocol", "faketcp")
}
HysteriaBean.PROTOCOL_WECHAT_VIDEO -> {
builder.addQueryParameter("protocol", "wechat-video")
}
}
if (protocol == HysteriaBean.PROTOCOL_FAKETCP) {
builder.addQueryParameter("protocol", "faketcp")
}
if (name.isNotBlank()) {
builder.encodedFragment(name.urlSafe())
}
return builder.toLink("hysteria")
}
fun JSONObject.parseHysteria(): HysteriaBean {
return HysteriaBean().apply {
serverAddress = optString("server")
if (!isMultiPort()) {
serverAddress = optString("server").substringBeforeLast(":")
serverPort = optString("server").substringAfterLast(":").toIntOrNull() ?: 443
}
uploadMbps = getIntNya("up_mbps")
downloadMbps = getIntNya("down_mbps")
obfuscation = getStr("obfs")
getStr("auth")?.also {
authPayloadType = HysteriaBean.TYPE_BASE64
authPayload = it
}
getStr("auth_str")?.also {
authPayloadType = HysteriaBean.TYPE_STRING
authPayload = it
}
getStr("protocol")?.also {
when (it) {
"faketcp" -> {
protocol = HysteriaBean.PROTOCOL_FAKETCP
}
"wechat-video" -> {
protocol = HysteriaBean.PROTOCOL_WECHAT_VIDEO
}
}
}
sni = getStr("server_name")
alpn = getStr("alpn")
allowInsecure = getBool("insecure")
streamReceiveWindow = getIntNya("recv_window_conn")
connectionReceiveWindow = getIntNya("recv_window")
disableMtuDiscovery = getBool("disable_mtu_discovery")
}
}
fun HysteriaBean.buildHysteriaConfig(port: Int, cacheFile: (() -> File)?): String {
return JSONObject().apply {
put("server", if (isMultiPort()) serverAddress else wrapUri())
when (protocol) {
HysteriaBean.PROTOCOL_FAKETCP -> {
put("protocol", "faketcp")
}
HysteriaBean.PROTOCOL_WECHAT_VIDEO -> {
put("protocol", "wechat-video")
}
}
put("up_mbps", uploadMbps)
put("down_mbps", downloadMbps)
put(
"socks5", JSONObject(
mapOf(
"listen" to "${LOCALHOST}:$port",
)
)
)
put("retry", 5)
put("fast_open", true)
put("lazy_start", true)
put("obfs", obfuscation)
when (authPayloadType) {
HysteriaBean.TYPE_BASE64 -> put("auth", authPayload)
HysteriaBean.TYPE_STRING -> put("auth_str", authPayload)
}
if (sni.isBlank() && finalAddress == LOCALHOST && !serverAddress.isIpAddress()) {
sni = serverAddress
}
if (sni.isNotBlank()) {
put("server_name", sni)
}
if (alpn.isNotBlank()) put("alpn", alpn)
if (caText.isNotBlank() && cacheFile != null) {
val caFile = cacheFile()
caFile.writeText(caText)
put("ca", caFile.absolutePath)
}
if (allowInsecure) put("insecure", true)
if (streamReceiveWindow > 0) put("recv_window_conn", streamReceiveWindow)
if (connectionReceiveWindow > 0) put("recv_window", connectionReceiveWindow)
if (disableMtuDiscovery) put("disable_mtu_discovery", true)
// hy 1.2.0 (不兼容)
put("resolver", "udp://127.0.0.1:" + DataStore.localDNSPort)
put("hop_interval", hopInterval)
}.toStringPretty()
}
fun HysteriaBean.isMultiPort(): Boolean {
if (!serverAddress.contains(":")) return false;
val p = serverAddress.substringAfterLast(":")
if (p.contains("-") || p.contains(",")) return true;
return false
}
| Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/ftm/hysteria/HysteriaFmt.kt | 665339903 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.ftm.naive
import io.nekohasekai.sagernet.ktx.isIpAddress
import io.nekohasekai.sagernet.ktx.linkBuilder
import io.nekohasekai.sagernet.ktx.toLink
import io.nekohasekai.sagernet.ktx.wrapIPV6Host
import com.narcis.application.presentation.connection.toStringPretty
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.ftm.LOCALHOST
import io.nekohasekai.sagernet.ktx.unUrlSafe
import io.nekohasekai.sagernet.ktx.urlSafe
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import org.json.JSONObject
fun parseNaive(link: String): NaiveBean {
val proto = link.substringAfter("+").substringBefore(":")
val url = ("https://" + link.substringAfter("://")).toHttpUrlOrNull()
?: error("Invalid naive link: $link")
return NaiveBean().also {
it.proto = proto
}.apply {
serverAddress = url.host
serverPort = url.port
username = url.username
password = url.password
sni = url.queryParameter("sni")
certificates = url.queryParameter("cert")
extraHeaders = url.queryParameter("extra-headers")?.unUrlSafe()?.replace("\r\n", "\n")
insecureConcurrency = url.queryParameter("insecure-concurrency")?.toIntOrNull()
name = url.fragment
initializeDefaultValues()
}
}
fun NaiveBean.toUri(proxyOnly: Boolean = false): String {
val builder = linkBuilder().host(finalAddress).port(finalPort)
if (username.isNotBlank()) {
builder.username(username)
if (password.isNotBlank()) {
builder.password(password)
}
}
if (!proxyOnly) {
if (sni.isNotBlank()) {
builder.addQueryParameter("sni", sni)
}
if (certificates.isNotBlank()) {
builder.addQueryParameter("cert", certificates)
}
if (extraHeaders.isNotBlank()) {
builder.addQueryParameter("extra-headers", extraHeaders)
}
if (name.isNotBlank()) {
builder.encodedFragment(name.urlSafe())
}
if (insecureConcurrency > 0) {
builder.addQueryParameter("insecure-concurrency", "$insecureConcurrency")
}
}
return builder.toLink(if (proxyOnly) proto else "naive+$proto", false)
}
fun NaiveBean.buildNaiveConfig(port: Int): String {
return JSONObject().apply {
// process ipv6
finalAddress = finalAddress.wrapIPV6Host()
serverAddress = serverAddress.wrapIPV6Host()
// process sni
if (sni.isNotBlank()) {
put("host-resolver-rules", "MAP $sni $finalAddress")
finalAddress = sni
} else {
if (serverAddress.isIpAddress()) {
// for naive, using IP as SNI name hardly happens
// and host-resolver-rules cannot resolve the SNI problem
// so do nothing
} else {
put("host-resolver-rules", "MAP $serverAddress $finalAddress")
finalAddress = serverAddress
}
}
put("listen", "socks://$LOCALHOST:$port")
put("proxy", toUri(true))
if (extraHeaders.isNotBlank()) {
put("extra-headers", extraHeaders.split("\n").joinToString("\r\n"))
}
if (DataStore.enableLog) {
put("log", "")
}
if (insecureConcurrency > 0) {
put("insecure-concurrency", insecureConcurrency)
}
}.toStringPretty()
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/ftm/naive/NaiveFmt.kt | 1525059295 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.ftm
import moe.matsuri.nya.utils.Util
import io.nekohasekai.sagernet.database.ProxyEntity
fun parseUniversal(link: String): AbstractBean {
return if (link.contains("?")) {
val type = link.substringAfter("sn://").substringBefore("?")
ProxyEntity(type = TypeMap[type] ?: error("Type $type not found")).apply {
putByteArray(Util.zlibDecompress(Util.b64Decode(link.substringAfter("?"))))
}.requireBean()
} else {
val type = link.substringAfter("sn://").substringBefore(":")
ProxyEntity(type = TypeMap[type] ?: error("Type $type not found")).apply {
putByteArray(Util.b64Decode(link.substringAfter(":").substringAfter(":")))
}.requireBean()
}
}
fun AbstractBean.toUniversalLink(): String {
var link = "sn://"
link += TypeMap.reversed[ProxyEntity().putBean(this).type]
link += "?"
link += Util.b64EncodeUrlSafe(Util.zlibCompress(KryoConverters.serialize(this), 9))
return link
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/ftm/UniversalFmt.kt | 2290137817 |
package io.nekohasekai.sagernet.ftm.ssh
fun parseShh(server: String): SSHBean {
// val link = server.replace("ssh://", "https://").toHttpUrlOrNull()
// ?: error("invalid trojan link $server")
val parts = server.split("&")
val configMap = mutableMapOf<String, String>()
for (part in parts) {
val configPart = part.split("=")
if (configPart.size == 2) {
val name = configPart[0]
val value = configPart[1]
configMap[name] = value
}
}
return SSHBean().apply {
serverAddress = configMap["address"]
serverPort = configMap["port"]?.toInt() ?: 8080
username = configMap["username"]
authType = 1
password = configMap["password"]
}
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/ftm/ssh/SshFmt.kt | 72352388 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.ftm.http
import io.nekohasekai.sagernet.ktx.isTLS
import io.nekohasekai.sagernet.ktx.urlSafe
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
fun parseHttp(link: String): HttpBean {
val httpUrl = link.toHttpUrlOrNull() ?: error("Invalid http(s) link: $link")
if (httpUrl.encodedPath != "/") error("Not http proxy")
return HttpBean().apply {
serverAddress = httpUrl.host
serverPort = httpUrl.port
username = httpUrl.username
password = httpUrl.password
sni = httpUrl.queryParameter("sni")
name = httpUrl.fragment
setTLS(httpUrl.scheme == "https")
}
}
fun setTLS(b: Boolean) {
}
fun HttpBean.toUri(): String {
val builder = HttpUrl.Builder().scheme(if (isTLS()) "https" else "http").host(serverAddress)
if (serverPort in 1..65535) {
builder.port(serverPort)
}
if (username.isNotBlank()) {
builder.username(username)
}
if (password.isNotBlank()) {
builder.password(password)
}
if (sni.isNotBlank()) {
builder.addQueryParameter("sni", sni)
}
if (name.isNotBlank()) {
builder.encodedFragment(name.urlSafe())
}
return builder.toString()
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/ftm/http/HttpFmt.kt | 9411431 |
package io.nekohasekai.sagernet.ftm.socks
import io.nekohasekai.sagernet.ktx.isTLS
import io.nekohasekai.sagernet.ktx.toLink
import com.narcis.application.presentation.connection.decodeBase64UrlSafe
import io.nekohasekai.sagernet.ktx.urlSafe
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
fun parseSOCKS(link: String): SOCKSBean {
val url = ("http://" + link.substringAfter("://")).toHttpUrlOrNull()
?: error("Not supported: $link")
return SOCKSBean().apply {
protocol = when {
link.startsWith("socks4://") -> SOCKSBean.PROTOCOL_SOCKS4
link.startsWith("socks4a://") -> SOCKSBean.PROTOCOL_SOCKS4A
else -> SOCKSBean.PROTOCOL_SOCKS5
}
serverAddress = url.host
serverPort = url.port
username = url.username
password = url.password
// v2rayN fmt
if (password.isNullOrBlank() && !username.isNullOrBlank()) {
try {
val n = username.decodeBase64UrlSafe()
username = n.substringBefore(":")
password = n.substringAfter(":")
} catch (_: Exception) {
}
}
}
}
fun SOCKSBean.toUri(): String {
val builder = HttpUrl.Builder().scheme("http").host(serverAddress).port(serverPort)
if (!username.isNullOrBlank()) builder.username(username)
if (!password.isNullOrBlank()) builder.password(password)
if (isTLS()) {
builder.addQueryParameter("tls", "true")
if (sni.isNotBlank()) {
builder.addQueryParameter("sni", sni)
}
}
if (!name.isNullOrBlank()) builder.encodedFragment(name.urlSafe())
return builder.toLink("socks${protocolVersion()}")
}
| Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/ftm/socks/SOCKSFmt.kt | 2535912251 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <sekai></sekai>@neko.services> *
* Copyright (C) 2021 by Max Lv <max.c.lv></max.c.lv>@gmail.com> *
* Copyright (C) 2021 by Mygod Studio <contact-shadowsocks-android></contact-shadowsocks-android>@mygod.be> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>. *
* *
*/
package io.nekohasekai.sagernet.ftm
import android.os.Parcel
import android.os.Parcelable
import com.esotericsoftware.kryo.io.ByteBufferInput
import com.esotericsoftware.kryo.io.ByteBufferOutput
abstract class Serializable : Parcelable {
abstract fun initializeDefaultValues()
abstract fun serializeToBuffer(output: ByteBufferOutput)
abstract fun deserializeFromBuffer(input: ByteBufferInput)
override fun describeContents() = 0
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeByteArray( KryoConverters.serialize(this))
}
abstract class CREATOR<T : Serializable> : Parcelable.Creator<T> {
abstract fun newInstance(): T
override fun createFromParcel(source: Parcel): T {
return KryoConverters.deserialize(newInstance(), source.createByteArray())
}
}
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/ftm/Serializable.kt | 3779892606 |
/******************************************************************************
* Copyright (C) 2022 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.ftm.tuic
import moe.matsuri.nya.neko.Plugins
import io.nekohasekai.sagernet.ktx.isIpAddress
import com.narcis.application.presentation.connection.toStringPretty
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.ftm.LOCALHOST
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.net.InetAddress
fun TuicBean.buildTuicConfig(port: Int, cacheFile: (() -> File)?): String {
if (Plugins.isUsingMatsuriExe("tuic-plugin")) {
if (!serverAddress.isIpAddress()) {
runBlocking {
finalAddress = withContext(Dispatchers.IO) {
InetAddress.getAllByName(serverAddress)
}?.firstOrNull()?.hostAddress ?: "127.0.0.1"
// TODO network on main thread, tuic don't support "sni"
}
}
}
return JSONObject().apply {
put("relay", JSONObject().apply {
if (sni.isNotBlank()) {
put("server", sni)
put("ip", finalAddress)
} else if (serverAddress.isIpAddress()) {
put("server", finalAddress)
} else {
put("server", serverAddress)
put("ip", finalAddress)
}
put("port", finalPort)
put("token", token)
if (caText.isNotBlank() && cacheFile != null) {
val caFile = cacheFile()
caFile.writeText(caText)
put("certificates", JSONArray(listOf(caFile.absolutePath)))
}
put("udp_relay_mode", udpRelayMode)
if (alpn.isNotBlank()) {
put("alpn", JSONArray(alpn.split("\n")))
}
put("congestion_controller", congestionController)
put("disable_sni", disableSNI)
put("reduce_rtt", reduceRTT)
put("max_udp_relay_packet_size", mtu)
if (fastConnect) put("fast_connect", true)
if (allowInsecure) put("insecure", true)
})
put("local", JSONObject().apply {
put("ip",LOCALHOST)
put("port", port)
})
put("log_level", if (DataStore.enableLog) "debug" else "info")
}.toStringPretty()
}
| Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/ftm/tuic/TuicFmt.kt | 668479576 |
/******************************************************************************
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.ftm.wireguard
import moe.matsuri.nya.utils.Util
import io.nekohasekai.sagernet.ktx.wrapUri
import moe.matsuri.nya.utils.JavaUtil
import com.wireguard.crypto.Key
fun WireGuardBean.buildWireGuardUapiConf(): String {
var conf = "private_key="
conf += Key.fromBase64(privateKey).toHex()
conf += "\npublic_key="
conf += Key.fromBase64(peerPublicKey).toHex()
if (peerPreSharedKey.isNotBlank()) {
conf += "\npreshared_key="
conf += JavaUtil.bytesToHex(Util.b64Decode(peerPreSharedKey))
}
conf += "\nendpoint=${wrapUri()}"
conf += "\nallowed_ip=0.0.0.0/0"
conf += "\nallowed_ip=::/0"
return conf
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/ftm/wireguard/WireGuardFmt.kt | 1149520210 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.ftm.shadowsocks
import com.github.shadowsocks.plugin.PluginConfiguration
import com.github.shadowsocks.plugin.PluginOptions
import moe.matsuri.nya.utils.Util
import io.nekohasekai.sagernet.ktx.linkBuilder
import io.nekohasekai.sagernet.ktx.toLink
import com.narcis.application.presentation.connection.decodeBase64UrlSafe
import com.narcis.application.presentation.connection.getIntNya
import com.narcis.application.presentation.connection.getStr
import io.nekohasekai.sagernet.ktx.unUrlSafe
import io.nekohasekai.sagernet.ktx.urlSafe
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import org.json.JSONObject
fun PluginConfiguration.fixInvalidParams() {
if (selected.contains("v2ray") && selected != "v2ray-plugin") {
pluginsOptions["v2ray-plugin"] = getOptions().apply { id = "v2ray-plugin" }
pluginsOptions.remove(selected)
selected = "v2ray-plugin"
// resolve v2ray plugin
}
if (selected.contains("obfs") && selected != "obfs-local") {
pluginsOptions["obfs-local"] = getOptions().apply { id = "obfs-local" }
pluginsOptions.remove(selected)
selected = "obfs-local"
// resolve clash obfs
}
if (selected == "obfs-local") {
val options = pluginsOptions["obfs-local"]
if (options != null) {
if (options.containsKey("mode")) {
options["obfs"] = options["mode"]
options.remove("mode")
}
if (options.containsKey("host")) {
options["obfs-host"] = options["host"]
options.remove("host")
}
}
}
}
fun ShadowsocksBean.fixInvalidParams() {
if (method == "plain") method = "none"
plugin = PluginConfiguration(plugin).apply { fixInvalidParams() }.toString()
}
fun parseShadowsocks(url: String): ShadowsocksBean {
if (url.substringBefore("#").contains("@")) {
var link = url.replace("ss://", "https://").toHttpUrlOrNull() ?: error(
"invalid ss-android link $url"
)
if (link.username.isBlank()) { // fix justmysocks's shit link
link = (("https://" + url.substringAfter("ss://")
.substringBefore("#")
.decodeBase64UrlSafe()).toHttpUrlOrNull() ?: error(
"invalid jms link $url"
)).newBuilder().fragment(url.substringAfter("#")).build()
}
// ss-android style
if (link.password.isNotBlank()) {
return ShadowsocksBean().apply {
serverAddress = link.host
serverPort = link.port
method = link.username
password = link.password
plugin = link.queryParameter("plugin") ?: ""
name = link.fragment
fixInvalidParams()
}
}
val methodAndPswd = link.username.decodeBase64UrlSafe()
return ShadowsocksBean().apply {
serverAddress = link.host
serverPort = link.port
method = methodAndPswd.substringBefore(":")
password = methodAndPswd.substringAfter(":")
plugin = link.queryParameter("plugin") ?: ""
name = link.fragment
fixInvalidParams()
}
} else {
// v2rayN style
var v2Url = url
if (v2Url.contains("#")) v2Url = v2Url.substringBefore("#")
val link = ("https://" + v2Url.substringAfter("ss://")
.decodeBase64UrlSafe()).toHttpUrlOrNull() ?: error("invalid v2rayN link $url")
return ShadowsocksBean().apply {
serverAddress = link.host
serverPort = link.port
method = link.username
password = link.password
plugin = ""
val remarks = url.substringAfter("#").unUrlSafe()
if (remarks.isNotBlank()) name = remarks
fixInvalidParams()
}
}
}
fun ShadowsocksBean.toUri(): String {
val builder = linkBuilder().username(Util.b64EncodeUrlSafe("$method:$password"))
.host(serverAddress)
.port(serverPort)
if (plugin.isNotBlank()) {
builder.addQueryParameter("plugin", plugin)
}
if (name.isNotBlank()) {
builder.encodedFragment(name.urlSafe())
}
return builder.toLink("ss").replace("$serverPort/", "$serverPort")
}
fun JSONObject.parseShadowsocks(): ShadowsocksBean {
return ShadowsocksBean().apply {
var pluginStr = ""
val pId = getStr("plugin")
if (!pId.isNullOrBlank()) {
val plugin = PluginOptions(pId, getStr("plugin_opts"))
pluginStr = plugin.toString(false)
}
serverAddress = getStr("server")
serverPort = getIntNya("server_port")
password = getStr("password")
method = getStr("method")
plugin = pluginStr
name = optString("remarks", "")
fixInvalidParams()
}
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/ftm/shadowsocks/ShadowsocksFmt.kt | 3038714536 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.aidl
import android.os.Parcelable
import io.nekohasekai.sagernet.database.StatsEntity
import kotlinx.parcelize.Parcelize
@Parcelize
data class AppStats(
var packageName: String,
var uid: Int,
var tcpConnections: Int,
var udpConnections: Int,
var tcpConnectionsTotal: Int,
var udpConnectionsTotal: Int,
var uplink: Long,
var downlink: Long,
var uplinkTotal: Long,
var downlinkTotal: Long,
var deactivateAt: Int,
var nekoConnectionsJSON: String,
) : Parcelable {
operator fun plusAssign(stats: StatsEntity) {
tcpConnectionsTotal += stats.tcpConnections
udpConnectionsTotal += stats.udpConnections
uplinkTotal += stats.uplink
downlinkTotal += stats.downlink
}
}
| Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/aidl/AppStats.kt | 449272258 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.aidl
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
data class TrafficStats(
// Bytes per second
var txRateProxy: Long = 0L,
var rxRateProxy: Long = 0L,
var txRateDirect: Long = 0L,
var rxRateDirect: Long = 0L,
// Bytes for the current session
// Outbound "bypass" usage is not counted
var txTotal: Long = 0L,
var rxTotal: Long = 0L,
) : Parcelable {
operator fun plus(other: TrafficStats) = TrafficStats(
txRateProxy + other.txRateProxy, rxRateProxy + other.rxRateProxy,
txRateDirect + other.txRateDirect, rxRateDirect + other.rxRateDirect,
txTotal + other.txTotal, rxTotal + other.rxTotal)
}
| Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/aidl/TrafficStats.kt | 4033688286 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.aidl
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
class AppStatsList(
var data: List<AppStats>
) : Parcelable | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/aidl/AppStatsList.kt | 4009404094 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.widget
import android.content.Context
import android.util.AttributeSet
import io.nekohasekai.sagernet.ktx.USER_AGENT
import com.takisoft.preferencex.EditTextPreference
class UserAgentPreference : EditTextPreference {
constructor(context: Context?) : super(context)
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context?, attrs: AttributeSet?, defStyle: Int) : super(
context, attrs, defStyle
)
constructor(
context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int
) : super(context, attrs, defStyleAttr, defStyleRes)
var isOOCv1 = false
public override fun notifyChanged() {
super.notifyChanged()
}
override fun getSummary(): CharSequence? {
if (text.isNullOrBlank()) {
return USER_AGENT
}
return super.getSummary()
}
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/widget/UserAgentPreference.kt | 610617119 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.widget
import android.content.Context
import android.util.AttributeSet
import androidx.preference.Preference
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.ktx.app
import io.nekohasekai.sagernet.utils.PackageCache
class AppListPreference : Preference {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(
context, attrs, defStyle
)
constructor(
context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int
) : super(context, attrs, defStyleAttr, defStyleRes)
override fun getSummary(): CharSequence {
val packages = DataStore.routePackages.split("\n").filter { it.isNotBlank() }.map {
PackageCache.installedPackages[it]?.applicationInfo?.loadLabel(app.packageManager)
?: PackageCache.installedPluginPackages[it]?.applicationInfo?.loadLabel(app.packageManager)
?: it
}
if (packages.isEmpty()) {
return context.getString(androidx.preference.R.string.not_set)
}
val count = packages.size
if (count <= 5) return packages.joinToString("\n")
return context.getString(R.string.apps_message, count)
}
fun postUpdate() {
notifyChanged()
}
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/widget/AppListPreference.kt | 795351398 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* Copyright (C) 2021 by Max Lv <[email protected]> *
* Copyright (C) 2021 by Mygod Studio <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.widget
import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.coordinatorlayout.widget.CoordinatorLayout
import com.google.android.material.progressindicator.CircularProgressIndicator
class FabProgressBehavior(context: Context, attrs: AttributeSet?) :
CoordinatorLayout.Behavior<CircularProgressIndicator>(context, attrs) {
override fun layoutDependsOn(
parent: CoordinatorLayout,
child: CircularProgressIndicator,
dependency: View,
): Boolean {
return dependency.id == (child.layoutParams as CoordinatorLayout.LayoutParams).anchorId
}
override fun onLayoutChild(
parent: CoordinatorLayout, child: CircularProgressIndicator,
layoutDirection: Int,
): Boolean {
val size = parent.getDependencies(child).single().measuredHeight + child.trackThickness
return if (child.indicatorSize != size) {
child.indicatorSize = size
true
} else false
}
}
| Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/widget/FabProgressBehavior.kt | 197683207 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* Copyright (C) 2021 by Max Lv <[email protected]> *
* Copyright (C) 2021 by Mygod Studio <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.widget
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Rect
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.view.isGone
class AutoCollapseTextView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null,
defStyleAttr: Int = 0,
) :
AppCompatTextView(context, attrs, defStyleAttr) {
override fun onTextChanged(
text: CharSequence?,
start: Int,
lengthBefore: Int,
lengthAfter: Int,
) {
super.onTextChanged(text, start, lengthBefore, lengthAfter)
isGone = text.isNullOrEmpty()
}
// #1874
override fun onFocusChanged(focused: Boolean, direction: Int, previouslyFocusedRect: Rect?) =
try {
super.onFocusChanged(focused, direction, previouslyFocusedRect)
} catch (e: IndexOutOfBoundsException) {
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent?) = try {
super.onTouchEvent(event)
} catch (e: IndexOutOfBoundsException) {
false
}
}
| Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/widget/AutoCollapseTextView.kt | 3795984856 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* Copyright (C) 2021 by Max Lv <[email protected]> *
* Copyright (C) 2021 by Mygod Studio <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.widget
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.core.graphics.Insets
import androidx.core.view.OnApplyWindowInsetsListener
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.updatePadding
import io.nekohasekai.sagernet.R
object ListHolderListener : OnApplyWindowInsetsListener {
override fun onApplyWindowInsets(view: View, insets: WindowInsetsCompat): WindowInsetsCompat {
val statusBarInsets = insets.getInsets(WindowInsetsCompat.Type.statusBars())
view.setPadding(statusBarInsets.left,
statusBarInsets.top,
statusBarInsets.right,
statusBarInsets.bottom)
return WindowInsetsCompat.Builder(insets).apply {
setInsets(WindowInsetsCompat.Type.statusBars(), Insets.NONE)
/*setInsets(WindowInsetsCompat.Type.navigationBars(),
insets.getInsets(WindowInsetsCompat.Type.navigationBars()))*/
}.build()
}
fun setup(activity: AppCompatActivity) = activity.findViewById<View>(android.R.id.content).let {
ViewCompat.setOnApplyWindowInsetsListener(it, ListHolderListener)
WindowCompat.setDecorFitsSystemWindows(activity.window, false)
}
}
object MainListListener : OnApplyWindowInsetsListener {
override fun onApplyWindowInsets(view: View, insets: WindowInsetsCompat) = insets.apply {
view.updatePadding(bottom = view.resources.getDimensionPixelOffset(R.dimen.main_list_padding_bottom) +
insets.getInsets(WindowInsetsCompat.Type.navigationBars()).bottom)
}
}
object ListListener : OnApplyWindowInsetsListener {
override fun onApplyWindowInsets(view: View, insets: WindowInsetsCompat) = insets.apply {
view.updatePadding(bottom = insets.getInsets(WindowInsetsCompat.Type.navigationBars()).bottom)
}
}
| Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/widget/WindowInsetsListeners.kt | 1096580192 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.widget
import android.content.Context
import android.util.AttributeSet
import androidx.core.widget.addTextChangedListener
import io.nekohasekai.sagernet.R
import com.google.android.material.textfield.TextInputLayout
import com.takisoft.preferencex.EditTextPreference
import io.nekohasekai.sagernet.ktx.getIntNya
import io.nekohasekai.sagernet.ktx.getStr
import io.nekohasekai.sagernet.ktx.readableMessage
import okhttp3.HttpUrl.Companion.toHttpUrl
import org.json.JSONObject
class OOCv1TokenPreference : EditTextPreference {
constructor(context: Context?) : super(context)
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
constructor(
context: Context?, attrs: AttributeSet?, defStyleAttr: Int
) : super(context, attrs, defStyleAttr)
constructor(
context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int
) : super(context, attrs, defStyleAttr, defStyleRes)
init {
dialogLayoutResource = R.layout.layout_urltest_preference_dialog
setOnBindEditTextListener { editText ->
editText.isSingleLine = false
val linkLayout = editText.rootView.findViewById<TextInputLayout>(R.id.input_layout)
fun validate() {
if (editText.text.isBlank()) {
linkLayout.isErrorEnabled = false
return
}
var isValid = true
try {
val tokenObject = JSONObject(editText.text.toString())
val version = tokenObject.getIntNya("version")
if (version != 1) {
isValid = false
if (version != null) {
linkLayout.error = "Unsupported OOC version $version"
} else {
linkLayout.error = "Missing field: version"
}
}
if (isValid) {
val baseUrl = tokenObject.getStr("baseUrl")
when {
baseUrl.isNullOrBlank() -> {
linkLayout.error = "Missing field: baseUrl"
isValid = false
}
baseUrl.endsWith("/") -> {
linkLayout.error = "baseUrl must not contain a trailing slash"
isValid = false
}
!baseUrl.startsWith("https://") -> {
isValid = false
linkLayout.error = "Protocol scheme must be https"
}
else -> try {
baseUrl.toHttpUrl()
} catch (e: Exception) {
isValid = false
linkLayout.error = e.readableMessage
}
}
}
if (isValid && tokenObject.getStr("secret").isNullOrBlank()) {
isValid = false
linkLayout.error = "Missing field: secret"
}
if (isValid && tokenObject.getStr("userId").isNullOrBlank()) {
isValid = false
linkLayout.error = "Missing field: userId"
}
if (isValid) {
val certSha256 = tokenObject.getStr("certSha256")
if (!certSha256.isNullOrBlank()) {
when {
certSha256.length != 64 -> {
isValid = false
linkLayout.error =
"certSha256 must be a SHA-256 hexadecimal string"
}
}
}
}
} catch (e: Exception) {
isValid = false
linkLayout.error = e.readableMessage
}
linkLayout.isErrorEnabled = !isValid
}
validate()
editText.addTextChangedListener {
validate()
}
}
}
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/widget/OOCv1TokenPreference.kt | 2044476344 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.widget
import android.content.Context
import android.util.AttributeSet
import io.nekohasekai.sagernet.R
import com.github.shadowsocks.plugin.ProfileManager
import io.nekohasekai.sagernet.database.DataStore
import com.takisoft.preferencex.SimpleMenuPreference
class OutboundPreference : SimpleMenuPreference {
constructor(context: Context?) : super(context)
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context?, attrs: AttributeSet?, defStyle: Int) : super(
context,
attrs,
defStyle
)
constructor(
context: Context?,
attrs: AttributeSet?,
defStyleAttr: Int,
defStyleRes: Int
) : super(context, attrs, defStyleAttr, defStyleRes)
init {
setEntries(R.array.outbound_entry)
setEntryValues(R.array.outbound_value)
}
override fun getSummary(): CharSequence? {
if (value == "3") {
val routeOutbound = DataStore.routeOutboundRule
if (routeOutbound > 0) {
ProfileManager.getProfile(routeOutbound)?.displayName()?.let {
return it
}
}
}
return super.getSummary()
}
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/widget/OutboundPreference.kt | 2455591713 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.widget
import android.content.Context
import android.util.AttributeSet
import io.nekohasekai.sagernet.database.SagerDatabase
import com.takisoft.preferencex.SimpleMenuPreference
class GroupPreference : SimpleMenuPreference {
constructor(context: Context?) : super(context)
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context?, attrs: AttributeSet?, defStyle: Int) : super(
context, attrs, defStyle
)
constructor(
context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int
) : super(context, attrs, defStyleAttr, defStyleRes)
init {
val groups = SagerDatabase.groupDao.allGroups()
entries = groups.map { it.displayName() }.toTypedArray()
entryValues = groups.map { "${it.id}" }.toTypedArray()
}
override fun getSummary(): CharSequence? {
if (!value.isNullOrBlank() && value != "0") {
return SagerDatabase.groupDao.getById(value.toLong())?.displayName()
?: super.getSummary()
}
return super.getSummary()
}
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/widget/GroupPreference.kt | 3227997863 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.widget
import android.content.Context
import android.net.Uri
import android.util.AttributeSet
import androidx.core.widget.addTextChangedListener
import io.nekohasekai.sagernet.R
import com.google.android.material.textfield.TextInputLayout
import com.takisoft.preferencex.EditTextPreference
import io.nekohasekai.sagernet.ktx.app
import io.nekohasekai.sagernet.ktx.readableMessage
import okhttp3.HttpUrl.Companion.toHttpUrl
class LinkOrContentPreference : EditTextPreference {
constructor(context: Context?) : super(context)
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
context, attrs, defStyleAttr
)
constructor(
context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int
) : super(context, attrs, defStyleAttr, defStyleRes)
init {
dialogLayoutResource = R.layout.layout_urltest_preference_dialog
setOnBindEditTextListener {
val linkLayout = it.rootView.findViewById<TextInputLayout>(R.id.input_layout)
fun validate() {
val link = it.text
if (link.isBlank()) {
linkLayout.isErrorEnabled = false
return
}
try {
if (Uri.parse(link.toString()).scheme == "content") {
linkLayout.isErrorEnabled = false
return
}
val url = link.toString().toHttpUrl()
if ("http".equals(url.scheme, true)) {
linkLayout.error = app.getString(R.string.cleartext_http_warning)
linkLayout.isErrorEnabled = true
} else {
linkLayout.isErrorEnabled = false
}
} catch (e: Exception) {
linkLayout.error = e.readableMessage
linkLayout.isErrorEnabled = true
}
}
validate()
it.addTextChangedListener {
validate()
}
}
}
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/widget/LinkOrContentPreference.kt | 1735809488 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* Copyright (C) 2021 by Max Lv <[email protected]> *
* Copyright (C) 2021 by Mygod Studio <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.widget
import android.annotation.SuppressLint
import android.content.Context
import android.text.format.Formatter
import android.util.AttributeSet
import android.view.View
import android.widget.TextView
import androidx.appcompat.widget.TooltipCompat
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.whenStarted
import com.narcis.application.presentation.MainActivity
import io.nekohasekai.sagernet.R
import com.narcis.application.presentation.connection.runOnDefaultDispatcher
import com.google.android.material.bottomappbar.BottomAppBar
import io.nekohasekai.sagernet.bg.BaseService
import io.nekohasekai.sagernet.ktx.app
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
class StatsBar @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null,
defStyleAttr: Int = com.google.android.material.R.attr.bottomAppBarStyle,
) : BottomAppBar(context, attrs, defStyleAttr) {
private lateinit var statusText: TextView
private lateinit var txText: TextView
private lateinit var rxText: TextView
private lateinit var behavior: YourBehavior
var allowShow = true
override fun getBehavior(): YourBehavior {
if (!this::behavior.isInitialized) behavior = YourBehavior { allowShow }
return behavior
}
class YourBehavior(val getAllowShow: () -> Boolean) : Behavior() {
override fun onNestedScroll(
coordinatorLayout: CoordinatorLayout, child: BottomAppBar, target: View,
dxConsumed: Int, dyConsumed: Int, dxUnconsumed: Int, dyUnconsumed: Int,
type: Int, consumed: IntArray,
) {
super.onNestedScroll(
coordinatorLayout,
child,
target,
dxConsumed,
dyConsumed + dyUnconsumed,
dxUnconsumed,
0,
type,
consumed
)
}
override fun slideUp(child: BottomAppBar) {
if (!getAllowShow()) return
super.slideUp(child)
}
override fun slideDown(child: BottomAppBar) {
if (!getAllowShow()) return
super.slideDown(child)
}
}
override fun setOnClickListener(l: OnClickListener?) {
statusText = findViewById(R.id.status)
txText = findViewById(R.id.tx)
rxText = findViewById(R.id.rx)
super.setOnClickListener(l)
}
private fun setStatus(text: CharSequence) {
statusText.text = text
TooltipCompat.setTooltipText(this, text)
}
fun changeState(state: BaseService.State) {
val activity = context as MainActivity
fun postWhenStarted(what: () -> Unit) = activity.lifecycleScope.launch(Dispatchers.Main) {
delay(100L)
activity.whenStarted { what() }
}
if ((state == BaseService.State.Connected).also { hideOnScroll = it }) {
postWhenStarted {
if (allowShow) performShow()
setStatus(app.getText(R.string.vpn_connected))
}
} else {
postWhenStarted {
performHide()
}
updateTraffic(0, 0)
setStatus(
context.getText(
when (state) {
BaseService.State.Connecting -> R.string.connecting
BaseService.State.Stopping -> R.string.stopping
else -> R.string.not_connected
}
)
)
}
}
@SuppressLint("SetTextI18n")
fun updateTraffic(txRate: Long, rxRate: Long) {
txText.text = "▲ ${
context.getString(
R.string.speed, Formatter.formatFileSize(context, txRate)
)
}"
rxText.text = "▼ ${
context.getString(
R.string.speed, Formatter.formatFileSize(context, rxRate)
)
}"
}
fun testConnection() {
val activity = context as MainActivity
isEnabled = false
setStatus(app.getText(R.string.connection_test_testing))
runOnDefaultDispatcher {
// try {
// val elapsed = activity.urlTest()
// onMainDispatcher {
// isEnabled = true
// setStatus(
// app.getString(
// if (DataStore.connectionTestURL.startsWith("https://")) {
// R.string.connection_test_available
// } else {
// R.string.connection_test_available_http
// }, elapsed
// )
// )
// }
//
// } catch (e: Exception) {
// Logs.w(e.toString())
// onMainDispatcher {
// isEnabled = true
// setStatus(app.getText(R.string.connection_test_testing))
//
// activity.snackbar(
// app.getString(
// R.string.connection_test_error, e.readableMessage
// )
// ).show()
// }
// }
}
}
}
| Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/widget/StatsBar.kt | 3009013416 |
package io.nekohasekai.sagernet.widget
import android.content.Context
import android.graphics.drawable.Drawable
import android.os.Build
import android.util.AttributeSet
import android.view.PointerIcon
import android.view.View
import androidx.annotation.DrawableRes
import androidx.appcompat.widget.TooltipCompat
import androidx.dynamicanimation.animation.DynamicAnimation
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import androidx.vectordrawable.graphics.drawable.Animatable2Compat
import androidx.vectordrawable.graphics.drawable.AnimatedVectorDrawableCompat
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.bg.BaseService
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.progressindicator.BaseProgressIndicator
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import java.util.ArrayDeque
class ServiceButton @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) :
FloatingActionButton(context, attrs, defStyleAttr), DynamicAnimation.OnAnimationEndListener {
private val callback = object : Animatable2Compat.AnimationCallback() {
override fun onAnimationEnd(drawable: Drawable) {
super.onAnimationEnd(drawable)
var next = animationQueue.peek() ?: return
if (next.icon.current == drawable) {
animationQueue.pop()
next = animationQueue.peek() ?: return
}
next.start()
}
}
private inner class AnimatedState(
@DrawableRes resId: Int,
private val onStart: BaseProgressIndicator<*>.() -> Unit = { hideProgress() }
) {
val icon: AnimatedVectorDrawableCompat =
AnimatedVectorDrawableCompat.create(context, resId)!!.apply {
registerAnimationCallback([email protected])
}
fun start() {
setImageDrawable(icon)
icon.start()
progress.onStart()
}
fun stop() = icon.stop()
}
private val iconStopped by lazy { AnimatedState(R.drawable.ic_service_stopped) }
private val iconConnecting by lazy {
AnimatedState(R.drawable.ic_service_connecting) {
hideProgress()
delayedAnimation = (context as LifecycleOwner).lifecycleScope.launchWhenStarted {
delay(context.resources.getInteger(android.R.integer.config_mediumAnimTime) + 1000L)
isIndeterminate = true
show()
}
}
}
private val iconConnected by lazy {
AnimatedState(R.drawable.ic_service_connected) {
delayedAnimation?.cancel()
setProgressCompat(1, true)
}
}
private val iconStopping by lazy { AnimatedState(R.drawable.ic_service_stopping) }
private val animationQueue = ArrayDeque<AnimatedState>()
private var checked = false
private var delayedAnimation: Job? = null
private lateinit var progress: BaseProgressIndicator<*>
fun initProgress(progress: BaseProgressIndicator<*>) {
this.progress = progress
progress.progressDrawable?.addSpringAnimationEndListener(this)
}
override fun onAnimationEnd(
animation: DynamicAnimation<out DynamicAnimation<*>>?, canceled: Boolean, value: Float,
velocity: Float
) {
if (!canceled) progress.hide()
}
private fun hideProgress() {
delayedAnimation?.cancel()
progress.hide()
}
override fun onCreateDrawableState(extraSpace: Int): IntArray {
val drawableState = super.onCreateDrawableState(extraSpace + 1)
if (checked) View.mergeDrawableStates(
drawableState,
intArrayOf(android.R.attr.state_checked)
)
return drawableState
}
fun changeState(state: BaseService.State, previousState: BaseService.State, animate: Boolean) {
when (state) {
BaseService.State.Connecting -> changeState(iconConnecting, animate)
BaseService.State.Connected -> changeState(iconConnected, animate)
BaseService.State.Stopping -> {
changeState(iconStopping, animate && previousState == BaseService.State.Connected)
}
else -> changeState(iconStopped, animate)
}
checked = state == BaseService.State.Connected
refreshDrawableState()
val description = context.getText(if (state.canStop) R.string.stop else R.string.connect)
contentDescription = description
TooltipCompat.setTooltipText(this, description)
val enabled = state.canStop || state == BaseService.State.Stopped
isEnabled = enabled
if (Build.VERSION.SDK_INT >= 24) pointerIcon = PointerIcon.getSystemIcon(
context,
if (enabled) PointerIcon.TYPE_HAND else PointerIcon.TYPE_WAIT
)
}
private fun changeState(icon: AnimatedState, animate: Boolean) {
fun counters(a: AnimatedState, b: AnimatedState): Boolean =
a == iconStopped && b == iconConnecting ||
a == iconConnecting && b == iconStopped ||
a == iconConnected && b == iconStopping ||
a == iconStopping && b == iconConnected
if (animate) {
if (animationQueue.size < 2 || !counters(animationQueue.last, icon)) {
animationQueue.add(icon)
if (animationQueue.size == 1) icon.start()
} else animationQueue.removeLast()
} else {
animationQueue.peekFirst()?.stop()
animationQueue.clear()
icon.start() // force ensureAnimatorSet to be called so that stop() will work
icon.stop()
}
}
}
| Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/widget/ServiceButton.kt | 4013677410 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.group
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.ktx.isIpAddress
import io.nekohasekai.sagernet.ktx.isTLS
import com.narcis.application.presentation.connection.Logs
import com.narcis.application.presentation.connection.runOnDefaultDispatcher
import io.nekohasekai.sagernet.*
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.database.GroupManager
import io.nekohasekai.sagernet.database.ProxyGroup
import io.nekohasekai.sagernet.database.SubscriptionBean
import io.nekohasekai.sagernet.ktx.app
import io.nekohasekai.sagernet.ktx.getValue
import io.nekohasekai.sagernet.ktx.readableMessage
import io.nekohasekai.sagernet.ktx.setValue
import kotlinx.coroutines.*
import java.net.Inet4Address
import java.net.InetAddress
import java.util.*
import java.util.concurrent.atomic.AtomicInteger
@Suppress("EXPERIMENTAL_API_USAGE")
abstract class GroupUpdater {
abstract suspend fun doUpdate(
proxyGroup: ProxyGroup,
subscription: SubscriptionBean,
userInterface: GroupManager.Interface?,
byUser: Boolean
)
data class Progress(
var max: Int
) {
var progress by AtomicInteger()
}
protected suspend fun forceResolve(
profiles: List<io.nekohasekai.sagernet.ftm.AbstractBean>, groupId: Long?
) {
val ipv6Mode = DataStore.ipv6Mode
val lookupPool = newFixedThreadPoolContext(5, "DNS Lookup")
val lookupJobs = mutableListOf<Job>()
val progress = Progress(profiles.size)
if (groupId != null) {
Companion.progress[groupId] = progress
GroupManager.postReload(groupId)
}
val ipv6First = ipv6Mode >= IPv6Mode.PREFER
for (profile in profiles) {
when (profile) {
// SNI rewrite unsupported
is io.nekohasekai.sagernet.ftm.naive.NaiveBean -> continue
}
if (profile.serverAddress.isIpAddress()) continue
lookupJobs.add(GlobalScope.launch(lookupPool) {
try {
val results = if (
SagerNet.underlyingNetwork != null &&
DataStore.enableFakeDns &&
DataStore.serviceState.started &&
DataStore.serviceMode == Key.MODE_VPN
) {
// FakeDNS
SagerNet.underlyingNetwork!!
.getAllByName(profile.serverAddress)
.filterNotNull()
} else {
// System DNS is enough (when VPN connected, it uses v2ray-core)
InetAddress.getAllByName(profile.serverAddress).filterNotNull()
}
if (results.isEmpty()) error("empty response")
rewriteAddress(profile, results, ipv6First)
} catch (e: Exception) {
Logs.d("Lookup ${profile.serverAddress} failed: ${e.readableMessage}", e)
}
if (groupId != null) {
progress.progress++
GroupManager.postReload(groupId)
}
})
}
lookupJobs.joinAll()
lookupPool.close()
}
protected fun rewriteAddress(
bean: io.nekohasekai.sagernet.ftm.AbstractBean, addresses: List<InetAddress>, ipv6First: Boolean
) {
val address = addresses.sortedBy { (it is Inet4Address) xor ipv6First }[0].hostAddress
with(bean) {
when (this) {
is io.nekohasekai.sagernet.ftm.socks.SOCKSBean -> {
if (isTLS() && sni.isBlank()) sni = bean.serverAddress
}
is io.nekohasekai.sagernet.ftm.http.HttpBean -> {
if (isTLS() && sni.isBlank()) sni = bean.serverAddress
}
is io.nekohasekai.sagernet.ftm.v2ray.StandardV2RayBean -> {
when (security) {
"tls" -> if (sni.isBlank()) sni = bean.serverAddress
}
}
is io.nekohasekai.sagernet.ftm.trojan.TrojanBean -> {
if (sni.isBlank()) sni = bean.serverAddress
}
is io.nekohasekai.sagernet.ftm.trojan_go.TrojanGoBean -> {
if (sni.isBlank()) sni = bean.serverAddress
}
is io.nekohasekai.sagernet.ftm.hysteria.HysteriaBean -> {
if (sni.isBlank()) sni = bean.serverAddress
}
}
bean.serverAddress = address
}
}
companion object {
val updating = Collections.synchronizedSet<Long>(mutableSetOf())
val progress = Collections.synchronizedMap<Long, Progress>(mutableMapOf())
fun startUpdate(proxyGroup: ProxyGroup, byUser: Boolean) {
runOnDefaultDispatcher {
executeUpdate(proxyGroup, byUser)
}
}
suspend fun executeUpdate(proxyGroup: ProxyGroup, byUser: Boolean): Boolean {
return coroutineScope {
if (!updating.add(proxyGroup.id)) cancel()
GroupManager.postReload(proxyGroup.id)
val subscription = proxyGroup.subscription!!
val connected = DataStore.serviceState.connected
val userInterface = GroupManager.userInterface
if (byUser && (subscription.link?.startsWith("http://") == true || subscription.updateWhenConnectedOnly) && !connected) {
if (userInterface == null || !userInterface.confirm(app.getString(R.string.update_subscription_warning))) {
finishUpdate(proxyGroup)
cancel()
return@coroutineScope true
}
}
try {
when (subscription.type) {
SubscriptionType.RAW -> RawUpdater
SubscriptionType.OOCv1 -> OpenOnlineConfigUpdater
SubscriptionType.SIP008 -> SIP008Updater
else -> error("wtf")
}.doUpdate(proxyGroup, subscription, userInterface, byUser)
true
} catch (e: Throwable) {
Logs.w(e)
userInterface?.onUpdateFailure(proxyGroup, e.readableMessage)
finishUpdate(proxyGroup)
false
}
}
}
suspend fun finishUpdate(proxyGroup: ProxyGroup) {
updating.remove(proxyGroup.id)
progress.remove(proxyGroup.id)
GroupManager.postUpdate(proxyGroup)
}
}
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/group/GroupUpdater.kt | 2551136231 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.group
import android.net.Uri
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.ktx.USER_AGENT
import com.narcis.application.presentation.connection.Logs
import com.narcis.application.presentation.connection.applyDefaultValues
import com.narcis.application.presentation.connection.filterIsInstance
import com.narcis.application.presentation.connection.getStr
import io.nekohasekai.sagernet.ExtraType
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.database.GroupManager
import io.nekohasekai.sagernet.database.ProxyEntity
import io.nekohasekai.sagernet.database.ProxyGroup
import io.nekohasekai.sagernet.database.SagerDatabase
import io.nekohasekai.sagernet.database.SubscriptionBean
import io.nekohasekai.sagernet.ftm.shadowsocks.parseShadowsocks
import io.nekohasekai.sagernet.ktx.app
import libcore.Libcore
import org.json.JSONObject
object SIP008Updater : GroupUpdater() {
override suspend fun doUpdate(
proxyGroup: ProxyGroup,
subscription: SubscriptionBean,
userInterface: GroupManager.Interface?,
byUser: Boolean
) {
val link = subscription.link
val sip008Response: JSONObject
if (link.startsWith("content://")) {
val contentText = app.contentResolver.openInputStream(Uri.parse(link))
?.bufferedReader()
?.readText()
sip008Response = contentText?.let { JSONObject(contentText) }
?: error(app.getString(R.string.no_proxies_found_in_subscription))
} else {
val response = Libcore.newHttpClient().apply {
modernTLS()
trySocks5(DataStore.socksPort)
}.newRequest().apply {
setURL(subscription.link)
setUserAgent(subscription.customUserAgent.takeIf { it.isNotBlank() } ?: USER_AGENT)
}.execute()
sip008Response = JSONObject(response.contentString)
}
subscription.bytesUsed = sip008Response.optLong("bytesUsed", -1)
subscription.bytesRemaining = sip008Response.optLong("bytesRemaining", -1)
subscription.applyDefaultValues()
val servers = sip008Response.getJSONArray("servers").filterIsInstance<JSONObject>()
var profiles = mutableListOf<io.nekohasekai.sagernet.ftm.AbstractBean>()
for (profile in servers) {
val bean = profile.parseShadowsocks()
appendExtraInfo(profile, bean)
profiles.add(bean.applyDefaultValues())
}
if (subscription.forceResolve) forceResolve(profiles, proxyGroup.id)
val exists = SagerDatabase.proxyDao.getByGroup(proxyGroup.id)
val duplicate = ArrayList<String>()
if (subscription.deduplication) {
Logs.d("Before deduplication: ${profiles.size}")
val uniqueProfiles = LinkedHashSet<io.nekohasekai.sagernet.ftm.AbstractBean>()
val uniqueNames = HashMap<io.nekohasekai.sagernet.ftm.AbstractBean, String>()
for (proxy in profiles) {
if (!uniqueProfiles.add(proxy)) {
val index = uniqueProfiles.indexOf(proxy)
if (uniqueNames.containsKey(proxy)) {
val name = uniqueNames[proxy]!!.replace(" ($index)", "")
if (name.isNotBlank()) {
duplicate.add("$name ($index)")
uniqueNames[proxy] = ""
}
}
duplicate.add(proxy.displayName() + " ($index)")
} else {
uniqueNames[proxy] = proxy.displayName()
}
}
uniqueProfiles.retainAll(uniqueNames.keys)
profiles = uniqueProfiles.toMutableList()
}
Logs.d("New profiles: ${profiles.size}")
val profileMap = profiles.associateBy { it.profileId }
val toDelete = ArrayList<ProxyEntity>()
val toReplace = exists.mapNotNull { entity ->
val profileId = entity.requireBean().profileId
if (profileMap.contains(profileId)) profileId to entity else let {
toDelete.add(entity)
null
}
}.toMap()
Logs.d("toDelete profiles: ${toDelete.size}")
Logs.d("toReplace profiles: ${toReplace.size}")
val toUpdate = ArrayList<ProxyEntity>()
val added = mutableListOf<String>()
val updated = mutableMapOf<String, String>()
val deleted = toDelete.map { it.displayName() }
var userOrder = 1L
var changed = toDelete.size
for ((profileId, bean) in profileMap.entries) {
val name = bean.displayName()
if (toReplace.contains(profileId)) {
val entity = toReplace[profileId]!!
val existsBean = entity.requireBean()
existsBean.applyFeatureSettings(bean)
when {
existsBean != bean -> {
changed++
entity.putBean(bean)
toUpdate.add(entity)
updated[entity.displayName()] = name
Logs.d("Updated profile: [$profileId] $name")
}
entity.userOrder != userOrder -> {
entity.putBean(bean)
toUpdate.add(entity)
entity.userOrder = userOrder
Logs.d("Reordered profile: [$profileId] $name")
}
else -> {
Logs.d("Ignored profile: [$profileId] $name")
}
}
} else {
changed++
SagerDatabase.proxyDao.addProxy(
ProxyEntity(
groupId = proxyGroup.id, userOrder = userOrder
).apply {
putBean(bean)
})
added.add(name)
Logs.d("Inserted profile: $name")
}
userOrder++
}
SagerDatabase.proxyDao.updateProxy(toUpdate).also {
Logs.d("Updated profiles: $it")
}
SagerDatabase.proxyDao.deleteProxy(toDelete).also {
Logs.d("Deleted profiles: $it")
}
val existCount = SagerDatabase.proxyDao.countByGroup(proxyGroup.id).toInt()
if (existCount != profileMap.size) {
Logs.e("Exist profiles: $existCount, new profiles: ${profileMap.size}")
}
subscription.lastUpdated = (System.currentTimeMillis() / 1000).toInt()
SagerDatabase.groupDao.updateGroup(proxyGroup)
finishUpdate(proxyGroup)
userInterface?.onUpdateSuccess(
proxyGroup, changed, added, updated, deleted, duplicate, byUser
)
}
fun appendExtraInfo(profile: JSONObject, bean: io.nekohasekai.sagernet.ftm.AbstractBean) {
bean.extraType = ExtraType.SIP008
bean.profileId = profile.getStr("id")
}
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/group/SIP008Updater.kt | 3453596366 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.group
import com.narcis.application.presentation.MainActivity
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.database.GroupManager
import io.nekohasekai.sagernet.database.ProxyGroup
import com.narcis.application.presentation.connection.onMainDispatcher
import com.narcis.application.presentation.connection.runOnMainDispatcher
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import kotlinx.coroutines.delay
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
class GroupInterfaceAdapter(val context: MainActivity) : GroupManager.Interface {
override suspend fun confirm(message: String): Boolean {
return suspendCoroutine {
runOnMainDispatcher {
MaterialAlertDialogBuilder(context).setTitle(R.string.confirm)
.setMessage(message)
.setPositiveButton(R.string.yes) { _, _ -> it.resume(true) }
.setNegativeButton(R.string.no) { _, _ -> it.resume(false) }
.setOnCancelListener { _ -> it.resume(false) }
.show()
}
}
}
override suspend fun onUpdateSuccess(
group: ProxyGroup,
changed: Int,
added: List<String>,
updated: Map<String, String>,
deleted: List<String>,
duplicate: List<String>,
byUser: Boolean
) {
if (changed == 0 && duplicate.isEmpty()) {
if (byUser) context.snackbar(
context.getString(
R.string.group_no_difference, group.displayName()
)
).show()
} else {
context.snackbar(context.getString(R.string.group_updated, group.name, changed)).show()
var status = ""
if (added.isNotEmpty()) {
status += context.getString(
R.string.group_added, added.joinToString("\n", postfix = "\n\n")
)
}
if (updated.isNotEmpty()) {
status += context.getString(
R.string.group_changed,
updated.map { it }.joinToString("\n", postfix = "\n\n") {
if (it.key == it.value) it.key else "${it.key} => ${it.value}"
})
}
if (deleted.isNotEmpty()) {
status += context.getString(
R.string.group_deleted, deleted.joinToString("\n", postfix = "\n\n")
)
}
if (duplicate.isNotEmpty()) {
status += context.getString(
R.string.group_duplicate, duplicate.joinToString("\n", postfix = "\n\n")
)
}
onMainDispatcher {
delay(1000L)
MaterialAlertDialogBuilder(context).setTitle(
context.getString(
R.string.group_diff, group.displayName()
)
).setMessage(status.trim()).setPositiveButton(android.R.string.ok, null).show()
}
}
}
override suspend fun onUpdateFailure(group: ProxyGroup, message: String) {
onMainDispatcher {
context.snackbar(message).show()
}
}
override suspend fun alert(message: String) {
return suspendCoroutine {
runOnMainDispatcher {
MaterialAlertDialogBuilder(context).setTitle(R.string.ooc_warning)
.setMessage(message)
.setPositiveButton(android.R.string.ok) { _, _ -> it.resume(Unit) }
.setOnCancelListener { _ -> it.resume(Unit) }
.show()
}
}
}
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/group/GroupInterfaceAdapter.kt | 3813067533 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.group
import android.net.Uri
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.database.GroupManager
import com.github.shadowsocks.plugin.PluginOptions
import moe.matsuri.nya.Protocols
import io.nekohasekai.sagernet.database.SagerDatabase
import io.nekohasekai.sagernet.ktx.USER_AGENT
import io.nekohasekai.sagernet.ktx.isTLS
import io.nekohasekai.sagernet.ktx.setTLS
import io.nekohasekai.sagernet.database.DataStore
import com.narcis.application.presentation.connection.Logs
import io.nekohasekai.sagernet.database.ProxyEntity
import io.nekohasekai.sagernet.database.ProxyGroup
import io.nekohasekai.sagernet.database.SubscriptionBean
import com.narcis.application.presentation.connection.decodeBase64UrlSafe
import com.narcis.application.presentation.connection.filterIsInstance
import com.narcis.application.presentation.connection.forEach
import com.narcis.application.presentation.connection.parseProxies
import io.nekohasekai.sagernet.ftm.gson.gson
import io.nekohasekai.sagernet.ftm.hysteria.parseHysteria
import io.nekohasekai.sagernet.ftm.shadowsocks.fixInvalidParams
import io.nekohasekai.sagernet.ftm.shadowsocks.parseShadowsocks
import io.nekohasekai.sagernet.ftm.shadowsocksr.parseShadowsocksR
import io.nekohasekai.sagernet.ftm.trojan_go.parseTrojanGo
import io.nekohasekai.sagernet.ktx.SubscriptionFoundException
import io.nekohasekai.sagernet.ktx.app
import io.nekohasekai.sagernet.ktx.applyDefaultValues
import io.nekohasekai.sagernet.ktx.isJsonObjectValid
import libcore.Libcore
import org.ini4j.Ini
import org.json.JSONArray
import org.json.JSONObject
import org.json.JSONTokener
import org.yaml.snakeyaml.TypeDescription
import org.yaml.snakeyaml.Yaml
import org.yaml.snakeyaml.error.YAMLException
import java.io.StringReader
@Suppress("EXPERIMENTAL_API_USAGE")
object RawUpdater : GroupUpdater() {
override suspend fun doUpdate(
proxyGroup: ProxyGroup,
subscription: SubscriptionBean,
userInterface: GroupManager.Interface?,
byUser: Boolean
) {
val link = subscription.link
var proxies: List<io.nekohasekai.sagernet.ftm.AbstractBean>
if (link.startsWith("content://")) {
val contentText = app.contentResolver.openInputStream(Uri.parse(link))
?.bufferedReader()
?.readText()
proxies = contentText?.let { parseRaw(contentText) }
?: error(app.getString(R.string.no_proxies_found_in_subscription))
} else {
val response = Libcore.newHttpClient().apply {
trySocks5(DataStore.socksPort)
when (DataStore.appTLSVersion) {
"1.3" -> restrictedTLS()
}
}.newRequest().apply {
setURL(subscription.link)
setUserAgent(subscription.customUserAgent.takeIf { it.isNotBlank() } ?: USER_AGENT)
}.execute()
proxies = parseRaw(response.contentString)
?: error(app.getString(R.string.no_proxies_found))
subscription.subscriptionUserinfo = response.getHeader("Subscription-Userinfo")
}
val proxiesMap = LinkedHashMap<String, io.nekohasekai.sagernet.ftm.AbstractBean>()
for (proxy in proxies) {
var index = 0
var name = proxy.displayName()
while (proxiesMap.containsKey(name)) {
index++
name = name.replace(" (${index - 1})", "")
name = "$name ($index)"
proxy.name = name
}
proxiesMap[proxy.displayName()] = proxy
}
proxies = proxiesMap.values.toList()
if (subscription.forceResolve) forceResolve(proxies, proxyGroup.id)
val exists = SagerDatabase.proxyDao.getByGroup(proxyGroup.id)
val duplicate = ArrayList<String>()
if (subscription.deduplication) {
Logs.d("Before deduplication: ${proxies.size}")
val uniqueProxies = LinkedHashSet<Protocols.Deduplication>()
val uniqueNames = HashMap<Protocols.Deduplication, String>()
for (_proxy in proxies) {
val proxy = Protocols.Deduplication(_proxy, _proxy.javaClass.toString())
if (!uniqueProxies.add(proxy)) {
val index = uniqueProxies.indexOf(proxy)
if (uniqueNames.containsKey(proxy)) {
val name = uniqueNames[proxy]!!.replace(" ($index)", "")
if (name.isNotBlank()) {
duplicate.add("$name ($index)")
uniqueNames[proxy] = ""
}
}
duplicate.add(_proxy.displayName() + " ($index)")
} else {
uniqueNames[proxy] = _proxy.displayName()
}
}
uniqueProxies.retainAll(uniqueNames.keys)
proxies = uniqueProxies.toList().map { it.bean }
}
Logs.d("New profiles: ${proxies.size}")
val nameMap = proxies.associateBy { bean ->
bean.displayName()
}
Logs.d("Unique profiles: ${nameMap.size}")
val toDelete = ArrayList<ProxyEntity>()
val toReplace = exists.mapNotNull { entity ->
val name = entity.displayName()
if (nameMap.contains(name)) name to entity else let {
toDelete.add(entity)
null
}
}.toMap()
Logs.d("toDelete profiles: ${toDelete.size}")
Logs.d("toReplace profiles: ${toReplace.size}")
val toUpdate = ArrayList<ProxyEntity>()
val added = mutableListOf<String>()
val updated = mutableMapOf<String, String>()
val deleted = toDelete.map { it.displayName() }
var userOrder = 1L
var changed = toDelete.size
for ((name, bean) in nameMap.entries) {
if (toReplace.contains(name)) {
val entity = toReplace[name]!!
val existsBean = entity.requireBean()
existsBean.applyFeatureSettings(bean)
when {
existsBean != bean -> {
changed++
entity.putBean(bean)
toUpdate.add(entity)
updated[entity.displayName()] = name
Logs.d("Updated profile: $name")
}
entity.userOrder != userOrder -> {
entity.putBean(bean)
toUpdate.add(entity)
entity.userOrder = userOrder
Logs.d("Reordered profile: $name")
}
else -> {
Logs.d("Ignored profile: $name")
}
}
} else {
changed++
SagerDatabase.proxyDao.addProxy(
ProxyEntity(
groupId = proxyGroup.id, userOrder = userOrder
).apply {
putBean(bean)
})
added.add(name)
Logs.d("Inserted profile: $name")
}
userOrder++
}
SagerDatabase.proxyDao.updateProxy(toUpdate).also {
Logs.d("Updated profiles: $it")
}
SagerDatabase.proxyDao.deleteProxy(toDelete).also {
Logs.d("Deleted profiles: $it")
}
val existCount = SagerDatabase.proxyDao.countByGroup(proxyGroup.id).toInt()
if (existCount != proxies.size) {
Logs.e("Exist profiles: $existCount, new profiles: ${proxies.size}")
}
subscription.lastUpdated = (System.currentTimeMillis() / 1000).toInt()
SagerDatabase.groupDao.updateGroup(proxyGroup)
finishUpdate(proxyGroup)
userInterface?.onUpdateSuccess(
proxyGroup, changed, added, updated, deleted, duplicate, byUser
)
}
@Suppress("UNCHECKED_CAST")
suspend fun parseRaw(text: String): List<io.nekohasekai.sagernet.ftm.AbstractBean>? {
val proxies = mutableListOf<io.nekohasekai.sagernet.ftm.AbstractBean>()
// if (text.contains("proxies:")) {
try {
// clash
for (proxy in (Yaml().apply {
addTypeDescription(TypeDescription(String::class.java, "str"))
}.loadAs(text, Map::class.java)["proxies"] as? (List<Map<String, Any?>>) ?: error(
app.getString(R.string.no_proxies_found_in_file)
))) {
// Note: YAML numbers parsed as "Long"
when (proxy["type"] as String) {
"socks5" -> {
proxies.add(io.nekohasekai.sagernet.ftm.socks.SOCKSBean().apply {
serverAddress = proxy["server"] as String
serverPort = proxy["port"].toString().toInt()
username = proxy["username"]?.toString()
password = proxy["password"]?.toString()
setTLS(proxy["tls"]?.toString() == "true")
sni = proxy["sni"]?.toString()
name = proxy["name"]?.toString()
})
}
"http" -> {
proxies.add(io.nekohasekai.sagernet.ftm.http.HttpBean().apply {
serverAddress = proxy["server"] as String
serverPort = proxy["port"].toString().toInt()
username = proxy["username"]?.toString()
password = proxy["password"]?.toString()
setTLS(proxy["tls"]?.toString() == "true")
sni = proxy["sni"]?.toString()
name = proxy["name"]?.toString()
})
}
"ss" -> {
var pluginStr = ""
if (proxy.contains("plugin")) {
val opts = proxy["plugin-opts"] as Map<String, Any?>
val pluginOpts = PluginOptions()
fun put(clash: String, origin: String = clash) {
opts[clash]?.let {
pluginOpts[origin] = it.toString()
}
}
when (proxy["plugin"]) {
"obfs" -> {
pluginOpts.id = "obfs-local"
put("mode", "obfs")
put("host", "obfs-host")
}
"v2ray-plugin" -> {
pluginOpts.id = "v2ray-plugin"
put("mode")
if (opts["tls"]?.toString() == "true") {
pluginOpts["tls"] = null
}
put("host")
put("path")
if (opts["mux"]?.toString() == "true") {
pluginOpts["mux"] = "8"
}
}
}
pluginStr = pluginOpts.toString(false)
}
proxies.add(io.nekohasekai.sagernet.ftm.shadowsocks.ShadowsocksBean().apply {
serverAddress = proxy["server"] as String
serverPort = proxy["port"].toString().toInt()
password = proxy["password"]?.toString()
method = clashCipher(proxy["cipher"] as String)
plugin = pluginStr
name = proxy["name"]?.toString()
fixInvalidParams()
})
}
"vmess" -> {
val bean = io.nekohasekai.sagernet.ftm.v2ray.VMessBean()
for (opt in proxy) {
when (opt.key) {
"name" -> bean.name = opt.value?.toString()
"server" -> bean.serverAddress = opt.value as String
"port" -> bean.serverPort = opt.value.toString().toInt()
"uuid" -> bean.uuid = opt.value as String
"alterId" -> bean.alterId = opt.value.toString().toInt()
"cipher" -> bean.encryption = opt.value as String
"network" -> {
bean.type = opt.value as String
// Clash "network" fix
when (bean.type) {
"http" -> {
bean.type = "tcp"
bean.headerType = "http"
}
"h2" -> bean.type = "http"
}
}
"tls" -> bean.security =
if (opt.value?.toString() == "true") "tls" else ""
"skip-cert-verify" -> bean.allowInsecure =
opt.value?.toString() == "true"
"ws-path" -> bean.path = opt.value?.toString()
"ws-headers" -> for (wsHeader in (opt.value as Map<String, Any>)) {
when (wsHeader.key.lowercase()) {
"host" -> bean.host = wsHeader.value.toString()
}
}
"ws-opts", "ws-opt" -> for (wsOpt in (opt.value as Map<String, Any>)) {
when (wsOpt.key.lowercase()) {
"headers" -> for (wsHeader in (wsOpt.value as Map<String, Any>)) {
when (wsHeader.key.lowercase()) {
"host" -> bean.host = wsHeader.value.toString()
}
}
"path" -> {
bean.path = wsOpt.value.toString()
}
"max-early-data" -> {
bean.wsMaxEarlyData = wsOpt.value.toString().toInt()
}
"early-data-header-name" -> {
bean.earlyDataHeaderName = wsOpt.value.toString()
}
}
}
"servername" -> bean.host = opt.value?.toString()
// The format of the VMessBean is wrong, so the `host` `path` has some strange transformations here.
"h2-opts", "h2-opt" -> for (h2Opt in (opt.value as Map<String, Any>)) {
when (h2Opt.key.lowercase()) {
"host" -> bean.host =
(h2Opt.value as List<String>).first()
"path" -> bean.path = h2Opt.value.toString()
}
}
"http-opts", "http-opt" -> for (httpOpt in (opt.value as Map<String, Any>)) {
when (httpOpt.key.lowercase()) {
"path" -> bean.path =
(httpOpt.value as List<String>).first()
"headers" -> for (hdr in (httpOpt.value as Map<String, Any>)) {
when (hdr.key.lowercase()) {
"host" -> bean.host =
(hdr.value as List<String>).first()
}
}
}
}
"grpc-opts", "grpc-opt" -> for (grpcOpt in (opt.value as Map<String, Any>)) {
when (grpcOpt.key.lowercase()) {
"grpc-service-name" -> bean.grpcServiceName =
grpcOpt.value.toString()
}
}
}
}
if (bean.isTLS() && bean.sni.isNullOrBlank() && !bean.host.isNullOrBlank()) {
bean.sni = bean.host
}
proxies.add(bean)
}
"trojan" -> {
val bean = io.nekohasekai.sagernet.ftm.trojan.TrojanBean()
bean.security = "tls"
for (opt in proxy) {
when (opt.key) {
"name" -> bean.name = opt.value?.toString()
"server" -> bean.serverAddress = opt.value as String
"port" -> bean.serverPort = opt.value.toString().toInt()
"password" -> bean.password = opt.value?.toString()
"sni" -> bean.sni = opt.value?.toString()
"skip-cert-verify" -> bean.allowInsecure =
opt.value?.toString() == "true"
"network" -> when (opt.value) {
"ws", "grpc" -> bean.type = opt.value?.toString()
}
"ws-opts", "ws-opt" -> for (wsOpt in (opt.value as Map<String, Any>)) {
when (wsOpt.key.lowercase()) {
"headers" -> for (wsHeader in (wsOpt.value as Map<String, Any>)) {
when (wsHeader.key.lowercase()) {
"host" -> bean.host = wsHeader.value.toString()
}
}
"path" -> {
bean.path = wsOpt.value.toString()
}
}
}
"grpc-opts", "grpc-opt" -> for (grpcOpt in (opt.value as Map<String, Any>)) {
when (grpcOpt.key.lowercase()) {
"grpc-service-name" -> bean.grpcServiceName =
grpcOpt.value.toString()
}
}
}
}
bean.allowInsecure = true
proxies.add(bean)
}
"ssr" -> {
val entity = io.nekohasekai.sagernet.ftm.shadowsocksr.ShadowsocksRBean()
for (opt in proxy) {
when (opt.key) {
"name" -> entity.name = opt.value?.toString()
"server" -> entity.serverAddress = opt.value as String
"port" -> entity.serverPort = opt.value.toString().toInt()
"cipher" -> entity.method = clashCipher(opt.value as String)
"password" -> entity.password = opt.value?.toString()
"obfs" -> entity.obfs = opt.value as String
"protocol" -> entity.protocol = opt.value as String
"obfs-param" -> entity.obfsParam = opt.value?.toString()
"protocol-param" -> entity.protocolParam = opt.value?.toString()
}
}
proxies.add(entity)
}
}
}
proxies.forEach { it.initializeDefaultValues() }
return proxies
} catch (e: YAMLException) {
Logs.w(e)
}
// } else if (text.contains("[Interface]")) {
// // wireguard
// try {
// proxies.addAll(parseWireGuard(text))
// return proxies
// } catch (e: Exception) {
// Logs.w(e)
// }
// }
try {
val json = JSONTokener(text).nextValue()
return parseJSON(json)
} catch (ignored: Exception) {
}
try {
return parseProxies(text.decodeBase64UrlSafe()).takeIf { it.isNotEmpty() }
?: error("Not found")
} catch (e: Exception) {
Logs.w(e)
}
try {
return parseProxies(text).takeIf { it.isNotEmpty() } ?: error("Not found")
} catch (e: SubscriptionFoundException) {
throw e
} catch (ignored: Exception) {
}
return null
}
fun clashCipher(cipher: String): String {
return when (cipher) {
"dummy" -> "none"
else -> cipher
}
}
fun parseWireGuard(conf: String): List<io.nekohasekai.sagernet.ftm.wireguard.WireGuardBean> {
val ini = Ini(StringReader(conf))
val iface = ini["Interface"] ?: error("Missing 'Interface' selection")
val bean = io.nekohasekai.sagernet.ftm.wireguard.WireGuardBean().applyDefaultValues()
val localAddresses = iface.getAll("Address")
if (localAddresses.isNullOrEmpty()) error("Empty address in 'Interface' selection")
bean.localAddress = localAddresses.flatMap { it.split(",") }.let { address ->
address.joinToString("\n") { it.substringBefore("/") }
}
bean.privateKey = iface["PrivateKey"]
bean.mtu = iface["MTU"]?.toIntOrNull()
val peers = ini.getAll("Peer")
if (peers.isNullOrEmpty()) error("Missing 'Peer' selections")
val beans = mutableListOf<io.nekohasekai.sagernet.ftm.wireguard.WireGuardBean>()
for (peer in peers) {
val endpoint = peer["Endpoint"]
if (endpoint.isNullOrBlank() || !endpoint.contains(":")) {
continue
}
val peerBean = bean.clone()
peerBean.serverAddress = endpoint.substringBeforeLast(":")
peerBean.serverPort = endpoint.substringAfterLast(":").toIntOrNull() ?: continue
peerBean.peerPublicKey = peer["PublicKey"] ?: continue
peerBean.peerPreSharedKey = peer["PresharedKey"]
beans.add(peerBean.applyDefaultValues())
}
if (beans.isEmpty()) error("Empty available peer list")
return beans
}
fun parseJSON(json: Any): List<io.nekohasekai.sagernet.ftm.AbstractBean> {
val proxies = ArrayList<io.nekohasekai.sagernet.ftm.AbstractBean>()
if (json is JSONObject) {
when {
json.has("server") && (json.has("up") || json.has("up_mbps")) -> {
return listOf(json.parseHysteria())
}
json.has("protocol_param") -> {
return listOf(json.parseShadowsocksR())
}
json.has("method") -> {
return listOf(json.parseShadowsocks())
}
json.has("protocol") -> {
val v2rayConfig = gson.fromJson(
json.toString(), io.nekohasekai.sagernet.ftm.v2ray.V2RayConfig.OutboundObject::class.java
).apply { init() }
return parseOutbound(v2rayConfig)
}
json.has("outbound") -> {
val v2rayConfig = gson.fromJson(
json.getJSONObject("outbound").toString(),
io.nekohasekai.sagernet.ftm.v2ray.V2RayConfig.OutboundObject::class.java
).apply { init() }
return parseOutbound(v2rayConfig)
}
json.has("outbounds") -> {/* val fakedns = json["fakedns"]
if (fakedns is JSONObject) {
json["fakedns"] = JSONArray().apply {
add(fakedns)
}
}
val routing = json["routing"]
if (routing is JSONObject) {
val rules = routing["rules"]
if (rules is JSONArray) {
rules.filterIsInstance<JSONObject>().forEach {
val inboundTag = it["inboundTag"]
if (inboundTag is String) {
it["inboundTag"] = JSONArray().apply {
add(inboundTag)
}
}
}
}
}
try {
gson.fromJson(
json.toString(),
V2RayConfig::class.java
).apply { init() }
} catch (e: Exception) {
Logs.w(e)*/
json.getJSONArray("outbounds").filterIsInstance<JSONObject>().forEach {
val v2rayConfig = gson.fromJson(
it.toString(), io.nekohasekai.sagernet.ftm.v2ray.V2RayConfig.OutboundObject::class.java
).apply { init() }
proxies.addAll(parseOutbound(v2rayConfig))
}/* null
}?.outbounds?.forEach {
proxies.addAll(parseOutbound(it))
}*/
}
json.has("remote_addr") -> {
return listOf(json.parseTrojanGo())
}
else -> json.forEach { _, it ->
if (isJsonObjectValid(it)) {
proxies.addAll(parseJSON(it))
}
}
}
} else {
json as JSONArray
json.forEach { _, it ->
if (isJsonObjectValid(it)) {
proxies.addAll(parseJSON(it))
}
}
}
proxies.forEach { it.initializeDefaultValues() }
return proxies
}
fun parseOutbound(outboundObject: io.nekohasekai.sagernet.ftm.v2ray.V2RayConfig.OutboundObject): List<io.nekohasekai.sagernet.ftm.AbstractBean> {
val proxies = ArrayList<io.nekohasekai.sagernet.ftm.AbstractBean>()
with(outboundObject) {
when (protocol) {
"http" -> {
val httpBean = io.nekohasekai.sagernet.ftm.http.HttpBean().applyDefaultValues()
streamSettings?.apply {
when (security) {
"tls" -> {
httpBean.setTLS(true)
tlsSettings?.serverName?.also {
httpBean.sni = it
}
}
}
}
(settings.value as? io.nekohasekai.sagernet.ftm.v2ray.V2RayConfig.HTTPOutboundConfigurationObject)?.servers?.forEach {
val httpBeanNext = httpBean.clone().apply {
serverAddress = it.address
serverPort = it.port
}
if (it.users.isNullOrEmpty()) {
proxies.add(httpBeanNext)
} else for (user in it.users) proxies.add(httpBeanNext.clone().apply {
username = user.user
password = user.pass
name = tag ?: (displayName() + " - $username")
})
}
}
"socks" -> {
val socksBean = io.nekohasekai.sagernet.ftm.socks.SOCKSBean().applyDefaultValues()
streamSettings?.apply {
when (security) {
"tls" -> {
socksBean.setTLS(true)
tlsSettings?.serverName?.also {
socksBean.sni = it
}
}
}
}
(settings.value as? io.nekohasekai.sagernet.ftm.v2ray.V2RayConfig.SocksOutboundConfigurationObject)?.servers?.forEach {
val socksBeanNext = socksBean.clone().apply {
serverAddress = it.address
serverPort = it.port
}
if (it.users.isNullOrEmpty()) {
proxies.add(socksBeanNext)
} else for (user in it.users) proxies.add(socksBeanNext.clone().apply {
username = user.user
password = user.pass
name = tag ?: (displayName() + " - $username")
})
}
}
"vmess" -> {
val v2rayBean = io.nekohasekai.sagernet.ftm.v2ray.VMessBean().applyDefaultValues()
streamSettings?.apply {
v2rayBean.security = security ?: v2rayBean.security
when (security) {
"tls" -> {
tlsSettings?.apply {
serverName?.also {
v2rayBean.sni = it
}
alpn?.also {
v2rayBean.alpn = it.joinToString(",")
}
allowInsecure?.also {
v2rayBean.allowInsecure = it
}
}
}
}
v2rayBean.type = network ?: v2rayBean.type
when (network) {
"tcp" -> {
tcpSettings?.header?.apply {
when (type) {
"http" -> {
v2rayBean.headerType = "http"
request?.apply {
path?.also {
v2rayBean.path = it.joinToString(",")
}
headers?.forEach { (key, value) ->
when (key.lowercase()) {
"host" -> {
when {
value.valueX != null -> {
v2rayBean.host = value.valueX
}
value.valueY != null -> {
v2rayBean.host =
value.valueY.joinToString(
","
)
}
}
}
}
}
}
}
}
}
}
"kcp" -> {
kcpSettings?.apply {
header?.type?.also {
v2rayBean.headerType = it
}
seed?.also {
v2rayBean.mKcpSeed = it
}
}
}
"ws" -> {
wsSettings?.apply {
headers?.forEach { (key, value) ->
when (key.lowercase()) {
"host" -> {
v2rayBean.host = value
}
}
}
path?.also {
v2rayBean.path = it
}
maxEarlyData?.also {
v2rayBean.wsMaxEarlyData = it
}
}
}
"http", "h2" -> {
v2rayBean.type = "http"
httpSettings?.apply {
host?.also {
v2rayBean.host = it.joinToString(",")
}
path?.also {
v2rayBean.path = it
}
}
}
"quic" -> {
quicSettings?.apply {
security?.also {
v2rayBean.quicSecurity = it
}
key?.also {
v2rayBean.quicKey = it
}
header?.type?.also {
v2rayBean.headerType = it
}
}
}
"grpc" -> {
grpcSettings?.serviceName?.also {
v2rayBean.grpcServiceName = it
}
}
}
}
if (protocol == "vmess") {
(settings.value as? io.nekohasekai.sagernet.ftm.v2ray.V2RayConfig.VMessOutboundConfigurationObject)?.vnext?.forEach {
val vmessBean = v2rayBean.clone().apply {
serverAddress = it.address
serverPort = it.port
}
for (user in it.users) {
proxies.add(vmessBean.clone().apply {
uuid = user.id
encryption = user.security
alterId = user.alterId
name =
tag ?: (displayName() + " - ${user.security} - ${user.id}")
})
}
}
}
}
"shadowsocks" -> (settings.value as? io.nekohasekai.sagernet.ftm.v2ray.V2RayConfig.ShadowsocksOutboundConfigurationObject)?.servers?.forEach {
proxies.add(io.nekohasekai.sagernet.ftm.shadowsocks.ShadowsocksBean().applyDefaultValues().apply {
name = tag
serverAddress = it.address
serverPort = it.port
method = it.method
password = it.password
plugin = ""
})
}
"trojan" -> {
val trojanBean = io.nekohasekai.sagernet.ftm.trojan.TrojanBean().applyDefaultValues()
streamSettings?.apply {
trojanBean.security = security ?: trojanBean.security
when (security) {
"tls" -> {
tlsSettings?.apply {
serverName?.also {
trojanBean.sni = it
}
alpn?.also {
trojanBean.alpn = it.joinToString(",")
}
allowInsecure?.also {
trojanBean.allowInsecure = it
}
}
}
}
(settings.value as? io.nekohasekai.sagernet.ftm.v2ray.V2RayConfig.TrojanOutboundConfigurationObject)?.servers?.forEach {
proxies.add(trojanBean.clone().apply {
name = tag
serverAddress = it.address
serverPort = it.port
password = it.password
})
}
}
}
}
Unit
}
return proxies
}
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/group/RawUpdater.kt | 547497041 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.group
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.database.GroupManager
import com.github.shadowsocks.plugin.PluginConfiguration
import com.github.shadowsocks.plugin.PluginOptions
import io.nekohasekai.sagernet.database.SagerDatabase
import io.nekohasekai.sagernet.ktx.USER_AGENT
import io.nekohasekai.sagernet.ExtraType
import com.narcis.application.presentation.connection.Logs
import io.nekohasekai.sagernet.database.ProxyEntity
import io.nekohasekai.sagernet.database.ProxyGroup
import io.nekohasekai.sagernet.database.SubscriptionBean
import com.narcis.application.presentation.connection.filterIsInstance
import io.nekohasekai.sagernet.ftm.shadowsocks.fixInvalidParams
import io.nekohasekai.sagernet.ktx.app
import io.nekohasekai.sagernet.ktx.applyDefaultValues
import io.nekohasekai.sagernet.ktx.getIntNya
import io.nekohasekai.sagernet.ktx.getStr
import libcore.Libcore
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrl
import org.json.JSONObject
object OpenOnlineConfigUpdater : GroupUpdater() {
override suspend fun doUpdate(
proxyGroup: ProxyGroup,
subscription: SubscriptionBean,
userInterface: GroupManager.Interface?,
byUser: Boolean
) {
val apiToken: JSONObject
var baseLink: HttpUrl
val certSha256: String?
try {
apiToken = JSONObject(subscription.token)
val version = apiToken.getIntNya("version")
if (version != 1) {
if (version != null) {
error("Unsupported OOC version $version")
} else {
error("Missing field: version")
}
}
val baseUrl = apiToken.getStr("baseUrl")
when {
baseUrl.isNullOrBlank() -> {
error("Missing field: baseUrl")
}
baseUrl.endsWith("/") -> {
error("baseUrl must not contain a trailing slash")
}
!baseUrl.startsWith("https://") -> {
error("Protocol scheme must be https")
}
else -> baseLink = baseUrl.toHttpUrl()
}
val secret = apiToken.getStr("secret")
if (secret.isNullOrBlank()) error("Missing field: secret")
baseLink = baseLink.newBuilder()
.addPathSegments(secret)
.addPathSegments("ooc/v1")
.build()
val userId = apiToken.getStr("userId")
if (userId.isNullOrBlank()) error("Missing field: userId")
baseLink = baseLink.newBuilder().addPathSegment(userId).build()
certSha256 = apiToken.getStr("certSha256")
if (!certSha256.isNullOrBlank()) {
when {
certSha256.length != 64 -> {
error("certSha256 must be a SHA-256 hexadecimal string")
}
}
}
} catch (e: Exception) {
Logs.v("ooc token check failed, token = ${subscription.token}", e)
error(app.getString(R.string.ooc_subscription_token_invalid))
}
val response = Libcore.newHttpClient().apply {
restrictedTLS()
if (certSha256 != null) pinnedSHA256(certSha256)
}.newRequest().apply {
setURL(baseLink.toString())
setUserAgent(subscription.customUserAgent.takeIf { it.isNotBlank() } ?: USER_AGENT)
}.execute()
val oocResponse = JSONObject(response.contentString)
subscription.username = oocResponse.getStr("username")
subscription.bytesUsed = oocResponse.optLong("bytesUsed", -1)
subscription.bytesRemaining = oocResponse.optLong("bytesRemaining", -1)
subscription.expiryDate = oocResponse.optInt("expiryDate", -1)
subscription.protocols = oocResponse.getJSONArray("protocols").filterIsInstance<String>()
subscription.applyDefaultValues()
for (protocol in subscription.protocols) {
if (protocol !in supportedProtocols) {
userInterface?.alert(app.getString(R.string.ooc_missing_protocol, protocol))
}
}
var profiles = mutableListOf<io.nekohasekai.sagernet.ftm.AbstractBean>()
for (protocol in subscription.protocols) {
val profilesInProtocol = oocResponse.getJSONArray(protocol)
.filterIsInstance<JSONObject>()
if (protocol == "shadowsocks") for (profile in profilesInProtocol) {
val bean = io.nekohasekai.sagernet.ftm.shadowsocks.ShadowsocksBean()
bean.name = profile.getStr("name")
bean.serverAddress = profile.getStr("address")
bean.serverPort = profile.getIntNya("port")
bean.method = profile.getStr("method")
bean.password = profile.getStr("password")
val pluginName = profile.getStr("pluginName")
if (!pluginName.isNullOrBlank()) {
// TODO: check plugin exists
// TODO: check pluginVersion
// TODO: support pluginArguments
val pl = PluginConfiguration()
pl.selected = pluginName
pl.pluginsOptions[pl.selected] = PluginOptions(profile.getStr("pluginOptions"))
pl.fixInvalidParams()
bean.plugin = pl.toString()
}
appendExtraInfo(profile, bean)
profiles.add(bean.applyDefaultValues())
}
}
if (subscription.forceResolve) forceResolve(profiles, proxyGroup.id)
val exists = SagerDatabase.proxyDao.getByGroup(proxyGroup.id)
val duplicate = ArrayList<String>()
if (subscription.deduplication) {
Logs.d("Before deduplication: ${profiles.size}")
val uniqueProfiles = LinkedHashSet<io.nekohasekai.sagernet.ftm.AbstractBean>()
val uniqueNames = HashMap<io.nekohasekai.sagernet.ftm.AbstractBean, String>()
for (proxy in profiles) {
if (!uniqueProfiles.add(proxy)) {
val index = uniqueProfiles.indexOf(proxy)
if (uniqueNames.containsKey(proxy)) {
val name = uniqueNames[proxy]!!.replace(" ($index)", "")
if (name.isNotBlank()) {
duplicate.add("$name ($index)")
uniqueNames[proxy] = ""
}
}
duplicate.add(proxy.displayName() + " ($index)")
} else {
uniqueNames[proxy] = proxy.displayName()
}
}
uniqueProfiles.retainAll(uniqueNames.keys)
profiles = uniqueProfiles.toMutableList()
}
Logs.d("New profiles: ${profiles.size}")
val profileMap = profiles.associateBy { it.profileId }
val toDelete = ArrayList<ProxyEntity>()
val toReplace = exists.mapNotNull { entity ->
val profileId = entity.requireBean().profileId
if (profileMap.contains(profileId)) profileId to entity else let {
toDelete.add(entity)
null
}
}.toMap()
Logs.d("toDelete profiles: ${toDelete.size}")
Logs.d("toReplace profiles: ${toReplace.size}")
val toUpdate = ArrayList<ProxyEntity>()
val added = mutableListOf<String>()
val updated = mutableMapOf<String, String>()
val deleted = toDelete.map { it.displayName() }
var userOrder = 1L
var changed = toDelete.size
for ((profileId, bean) in profileMap.entries) {
val name = bean.displayName()
if (toReplace.contains(profileId)) {
val entity = toReplace[profileId]!!
val existsBean = entity.requireBean()
existsBean.applyFeatureSettings(bean)
when {
existsBean != bean -> {
changed++
entity.putBean(bean)
toUpdate.add(entity)
updated[entity.displayName()] = name
Logs.d("Updated profile: [$profileId] $name")
}
entity.userOrder != userOrder -> {
entity.putBean(bean)
toUpdate.add(entity)
entity.userOrder = userOrder
Logs.d("Reordered profile: [$profileId] $name")
}
else -> {
Logs.d("Ignored profile: [$profileId] $name")
}
}
} else {
changed++
SagerDatabase.proxyDao.addProxy(
ProxyEntity(
groupId = proxyGroup.id, userOrder = userOrder
).apply {
putBean(bean)
})
added.add(name)
Logs.d("Inserted profile: $name")
}
userOrder++
}
SagerDatabase.proxyDao.updateProxy(toUpdate).also {
Logs.d("Updated profiles: $it")
}
SagerDatabase.proxyDao.deleteProxy(toDelete).also {
Logs.d("Deleted profiles: $it")
}
val existCount = SagerDatabase.proxyDao.countByGroup(proxyGroup.id).toInt()
if (existCount != profileMap.size) {
Logs.e("Exist profiles: $existCount, new profiles: ${profileMap.size}")
}
subscription.lastUpdated = (System.currentTimeMillis() / 1000).toInt()
SagerDatabase.groupDao.updateGroup(proxyGroup)
finishUpdate(proxyGroup)
userInterface?.onUpdateSuccess(
proxyGroup, changed, added, updated, deleted, duplicate, byUser
)
}
fun appendExtraInfo(profile: JSONObject, bean: io.nekohasekai.sagernet.ftm.AbstractBean) {
bean.extraType = ExtraType.OOCv1
bean.profileId = profile.getStr("id")
bean.group = profile.getStr("group")
bean.owner = profile.getStr("owner")
bean.tags = profile.optJSONArray("tags")?.filterIsInstance()
}
val supportedProtocols = arrayOf("shadowsocks")
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/group/OpenOnlineConfigUpdater.kt | 847020034 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.ktx
import moe.matsuri.nya.neko.NekoJSInterface
import moe.matsuri.nya.neko.NekoPluginManager
import moe.matsuri.nya.utils.Util
import moe.matsuri.nya.neko.parseShareLink
import com.narcis.application.presentation.connection.Logs
import com.google.gson.JsonParser
import io.nekohasekai.sagernet.ftm.AbstractBean
import io.nekohasekai.sagernet.ftm.Serializable
import io.nekohasekai.sagernet.ftm.gson.gson
import io.nekohasekai.sagernet.ftm.http.parseHttp
import io.nekohasekai.sagernet.ftm.hysteria.parseHysteria
import io.nekohasekai.sagernet.ftm.naive.parseNaive
import io.nekohasekai.sagernet.ftm.parseUniversal
import io.nekohasekai.sagernet.ftm.shadowsocks.parseShadowsocks
import io.nekohasekai.sagernet.ftm.shadowsocksr.parseShadowsocksR
import io.nekohasekai.sagernet.ftm.socks.parseSOCKS
import io.nekohasekai.sagernet.ftm.trojan.parseTrojan
import io.nekohasekai.sagernet.ftm.trojan_go.parseTrojanGo
import io.nekohasekai.sagernet.ftm.v2ray.parseV2Ray
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
// JSON & Base64
fun formatObject(obj: Any): String {
return gson.toJson(obj)
}
fun JSONObject.toStringPretty(): String {
return gson.toJson(JsonParser.parseString(this.toString()))
}
inline fun <reified T : Any> JSONArray.filterIsInstance(): List<T> {
val list = mutableListOf<T>()
for (i in 0 until this.length()) {
if (this[i] is T) list.add(this[i] as T)
}
return list
}
inline fun JSONArray.forEach(action: (Int, Any) -> Unit) {
for (i in 0 until this.length()) {
action(i, this[i])
}
}
inline fun JSONObject.forEach(action: (String, Any) -> Unit) {
for (k in this.keys()) {
action(k, this.get(k))
}
}
fun isJsonObjectValid(j: Any): Boolean {
if (j is JSONObject) return true
if (j is JSONArray) return true
try {
JSONObject(j as String)
} catch (ex: JSONException) {
try {
JSONArray(j)
} catch (ex1: JSONException) {
return false
}
}
return true
}
// wtf hutool
fun JSONObject.getStr(name: String): String? {
val obj = this.opt(name) ?: return null
if (obj is String) {
if (obj.isBlank()) {
return null
}
return obj
} else {
return null
}
}
fun JSONObject.getBool(name: String): Boolean? {
return try {
getBoolean(name)
} catch (ignored: Exception) {
null
}
}
// 重名了喵
fun JSONObject.getIntNya(name: String): Int? {
return try {
getInt(name)
} catch (ignored: Exception) {
null
}
}
fun String.decodeBase64UrlSafe(): String {
return String(Util.b64Decode(this))
}
// Sub
class SubscriptionFoundException(val link: String) : RuntimeException()
suspend fun parseProxies(text: String): List<AbstractBean> {
val links = text.split('\n').flatMap { it.trim().split(' ') }
val linksByLine = text.split('\n').map { it.trim() }
val entities = ArrayList<AbstractBean>()
val entitiesByLine = ArrayList<AbstractBean>()
suspend fun String.parseLink(entities: ArrayList<AbstractBean>) {
if (startsWith("clash://install-config?") || startsWith("sn://subscription?")) {
throw SubscriptionFoundException(this)
}
if (startsWith("sn://")) {
Logs.d("Try parse universal link: $this")
runCatching {
entities.add(parseUniversal(this))
}.onFailure {
Logs.w(it)
}
} else if (startsWith("socks://") || startsWith("socks4://") || startsWith("socks4a://") || startsWith(
"socks5://"
)
) {
Logs.d("Try parse socks link: $this")
runCatching {
entities.add(parseSOCKS(this))
}.onFailure {
Logs.w(it)
}
} else if (matches("(http|https)://.*".toRegex())) {
Logs.d("Try parse http link: $this")
runCatching {
entities.add(parseHttp(this))
}.onFailure {
Logs.w(it)
}
} else if (startsWith("vmess://")) {
Logs.d("Try parse v2ray link: $this")
runCatching {
entities.add(parseV2Ray(this))
}.onFailure {
Logs.w(it)
}
} else if (startsWith("trojan://")) {
Logs.d("Try parse trojan link: $this")
runCatching {
entities.add(parseTrojan(this))
}.onFailure {
Logs.w(it)
}
} else if (startsWith("trojan-go://")) {
Logs.d("Try parse trojan-go link: $this")
runCatching {
entities.add(parseTrojanGo(this))
}.onFailure {
Logs.w(it)
}
} else if (startsWith("ss://")) {
Logs.d("Try parse shadowsocks link: $this")
runCatching {
entities.add(parseShadowsocks(this))
}.onFailure {
Logs.w(it)
}
} else if (startsWith("ssr://")) {
Logs.d("Try parse shadowsocksr link: $this")
runCatching {
entities.add(parseShadowsocksR(this))
}.onFailure {
Logs.w(it)
}
} else if (startsWith("naive+")) {
Logs.d("Try parse naive link: $this")
runCatching {
entities.add(parseNaive(this))
}.onFailure {
Logs.w(it)
}
} else if (startsWith("hysteria://")) {
Logs.d("Try parse hysteria link: $this")
runCatching {
entities.add(parseHysteria(this))
}.onFailure {
Logs.w(it)
}
} else { // Neko Plugins
NekoPluginManager.getProtocols().forEach { obj ->
obj.protocolConfig.optJSONArray("links")?.forEach { _, any ->
if (any is String && startsWith(any)) {
runCatching {
entities.add(
parseShareLink(
obj.plgId, obj.protocolId, this@parseLink
)
)
}.onFailure {
Logs.w(it)
}
}
}
}
}
}
for (link in links) {
link.parseLink(entities)
}
for (link in linksByLine) {
link.parseLink(entitiesByLine)
}
var isBadLink = false
if (entities.onEach { it.initializeDefaultValues() }.size == entitiesByLine.onEach { it.initializeDefaultValues() }.size) run test@{
entities.forEachIndexed { index, bean ->
val lineBean = entitiesByLine[index]
if (bean == lineBean && bean.displayName() != lineBean.displayName()) {
isBadLink = true
return@test
}
}
}
NekoJSInterface.Default.destroyAllJsi()
return if (entities.size > entitiesByLine.size) entities else entitiesByLine
}
fun <T : Serializable> T.applyDefaultValues(): T {
initializeDefaultValues()
return this
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/ktx/Formats.kt | 3305303545 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
@file:SuppressLint("SoonBlockedPrivateApi")
package io.nekohasekai.sagernet.ktx
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.annotation.SuppressLint
import android.app.Service
import android.content.*
import android.content.pm.PackageInfo
import android.content.res.Resources
import android.os.Build
import android.system.Os
import android.system.OsConstants
import android.util.TypedValue
import android.view.View
import androidx.annotation.AttrRes
import androidx.annotation.ColorRes
import androidx.core.content.ContextCompat
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.preference.Preference
import androidx.recyclerview.widget.LinearSmoothScroller
import androidx.recyclerview.widget.RecyclerView
import io.nekohasekai.sagernet.BuildConfig
import com.narcis.application.presentation.MainActivity
import io.nekohasekai.sagernet.R
import moe.matsuri.nya.utils.NGUtil
import io.nekohasekai.sagernet.SagerNet
import io.nekohasekai.sagernet.database.DataStore
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
import java.io.FileDescriptor
import java.net.HttpURLConnection
import java.net.InetAddress
import java.net.Socket
import java.net.URLEncoder
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicLong
import java.util.concurrent.atomic.AtomicReference
import kotlin.coroutines.Continuation
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.reflect.KMutableProperty0
import kotlin.reflect.KProperty
import kotlin.reflect.KProperty0
inline fun <T> Iterable<T>.forEachTry(action: (T) -> Unit) {
var result: Exception? = null
for (element in this) try {
action(element)
} catch (e: Exception) {
if (result == null) result = e else result.addSuppressed(e)
}
if (result != null) {
throw result
}
}
val Throwable.readableMessage
get() = localizedMessage.takeIf { !it.isNullOrBlank() } ?: javaClass.simpleName
/**
* https://android.googlesource.com/platform/prebuilts/runtime/+/94fec32/appcompat/hiddenapi-light-greylist.txt#9466
*/
private val socketGetFileDescriptor = Socket::class.java.getDeclaredMethod("getFileDescriptor\$")
val Socket.fileDescriptor get() = socketGetFileDescriptor.invoke(this) as FileDescriptor
private val getInt = FileDescriptor::class.java.getDeclaredMethod("getInt$")
val FileDescriptor.int get() = getInt.invoke(this) as Int
suspend fun <T> HttpURLConnection.useCancellable(block: suspend HttpURLConnection.() -> T): T {
return suspendCancellableCoroutine { cont ->
cont.invokeOnCancellation {
if (Build.VERSION.SDK_INT >= 26) disconnect() else GlobalScope.launch(Dispatchers.IO) { disconnect() }
}
GlobalScope.launch(Dispatchers.IO) {
try {
cont.resume(block())
} catch (e: Throwable) {
cont.resumeWithException(e)
}
}
}
}
fun parsePort(str: String?, default: Int, min: Int = 1025): Int {
val value = str?.toIntOrNull() ?: default
return if (value < min || value > 65535) default else value
}
fun broadcastReceiver(callback: (Context, Intent) -> Unit): BroadcastReceiver =
object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) = callback(context, intent)
}
fun Context.listenForPackageChanges(onetime: Boolean = true, callback: () -> Unit) =
object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
callback()
if (onetime) context.unregisterReceiver(this)
}
}.apply {
registerReceiver(
this,
IntentFilter().apply {
addAction(Intent.ACTION_PACKAGE_ADDED)
addAction(Intent.ACTION_PACKAGE_REMOVED)
addDataScheme("package")
}
)
}
val PackageInfo.signaturesCompat
get() = if (Build.VERSION.SDK_INT >= 28) signingInfo.apkContentsSigners else @Suppress("DEPRECATION") signatures
/**
* Based on: https://stackoverflow.com/a/26348729/2245107
*/
fun Resources.Theme.resolveResourceId(@AttrRes resId: Int): Int {
val typedValue = TypedValue()
if (!resolveAttribute(resId, typedValue, true)) throw Resources.NotFoundException()
return typedValue.resourceId
}
fun Preference.remove() = parent!!.removePreference(this)
/**
* A slightly more performant variant of parseNumericAddress.
*
* Bug in Android 9.0 and lower: https://issuetracker.google.com/issues/123456213
*/
private val parseNumericAddress by lazy {
InetAddress::class.java.getDeclaredMethod("parseNumericAddress", String::class.java).apply {
isAccessible = true
}
}
fun String?.parseNumericAddress(): InetAddress? =
Os.inet_pton(OsConstants.AF_INET, this) ?: Os.inet_pton(OsConstants.AF_INET6, this)?.let {
if (Build.VERSION.SDK_INT >= 29) {
it
} else {
parseNumericAddress.invoke(
null,
this
) as InetAddress
}
}
@JvmOverloads
fun DialogFragment.showAllowingStateLoss(fragmentManager: FragmentManager, tag: String? = null) {
if (!fragmentManager.isStateSaved) show(fragmentManager, tag)
}
fun String.pathSafe(): String {
// " " encoded as +
return URLEncoder.encode(this, "UTF-8")
}
fun String.urlSafe(): String {
return URLEncoder.encode(this, "UTF-8").replace("+", "%20")
}
fun String.unUrlSafe(): String {
return NGUtil.urlDecode(this)
}
fun RecyclerView.scrollTo(index: Int, force: Boolean = false) {
if (force) {
post {
scrollToPosition(index)
}
}
postDelayed({
try {
layoutManager?.startSmoothScroll(object : LinearSmoothScroller(context) {
init {
targetPosition = index
}
override fun getVerticalSnapPreference(): Int {
return SNAP_TO_START
}
})
} catch (ignored: IllegalArgumentException) {
}
}, 300L)
}
val app get() = SagerNet.application
val shortAnimTime by lazy {
app.resources.getInteger(android.R.integer.config_shortAnimTime).toLong()
}
fun View.crossFadeFrom(other: View) {
clearAnimation()
other.clearAnimation()
if (visibility == View.VISIBLE && other.visibility == View.GONE) return
alpha = 0F
visibility = View.VISIBLE
animate().alpha(1F).duration = shortAnimTime
other.animate().alpha(0F).setListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
other.visibility = View.GONE
}
}).duration = shortAnimTime
}
fun Fragment.snackbar(text: CharSequence) = (requireActivity() as MainActivity).snackbar(text)
fun Context.getColorAttr(@AttrRes resId: Int): Int {
return ContextCompat.getColor(
this,
TypedValue().also {
theme.resolveAttribute(resId, it, true)
}.resourceId
)
}
fun <T> Continuation<T>.tryResume(value: T) {
try {
resumeWith(Result.success(value))
} catch (ignored: IllegalStateException) {
}
}
fun <T> Continuation<T>.tryResumeWithException(exception: Throwable) {
try {
resumeWith(Result.failure(exception))
} catch (ignored: IllegalStateException) {
}
}
operator fun <F> KProperty0<F>.getValue(thisRef: Any?, property: KProperty<*>): F = get()
operator fun <F> KMutableProperty0<F>.setValue(
thisRef: Any?,
property: KProperty<*>,
value: F,
) = set(value)
operator fun AtomicBoolean.getValue(thisRef: Any?, property: KProperty<*>): Boolean = get()
operator fun AtomicBoolean.setValue(thisRef: Any?, property: KProperty<*>, value: Boolean) =
set(value)
operator fun AtomicInteger.getValue(thisRef: Any?, property: KProperty<*>): Int = get()
operator fun AtomicInteger.setValue(thisRef: Any?, property: KProperty<*>, value: Int) = set(value)
operator fun AtomicLong.getValue(thisRef: Any?, property: KProperty<*>): Long = get()
operator fun AtomicLong.setValue(thisRef: Any?, property: KProperty<*>, value: Long) = set(value)
operator fun <T> AtomicReference<T>.getValue(thisRef: Any?, property: KProperty<*>): T = get()
operator fun <T> AtomicReference<T>.setValue(thisRef: Any?, property: KProperty<*>, value: T) =
set(value)
operator fun <K, V> Map<K, V>.getValue(thisRef: K, property: KProperty<*>) = get(thisRef)
operator fun <K, V> MutableMap<K, V>.setValue(thisRef: K, property: KProperty<*>, value: V?) {
if (value != null) {
put(thisRef, value)
} else {
remove(thisRef)
}
}
| Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/ktx/Utils.kt | 821957997 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
@file:Suppress("SpellCheckingInspection")
package io.nekohasekai.sagernet.ktx
import moe.matsuri.nya.utils.NGUtil
import okhttp3.HttpUrl
import java.net.InetSocketAddress
import java.net.Socket
fun linkBuilder() = HttpUrl.Builder().scheme("https")
fun HttpUrl.Builder.toLink(scheme: String, appendDefaultPort: Boolean = true): String {
var url = build()
val defaultPort = HttpUrl.defaultPort(url.scheme)
var replace = false
if (appendDefaultPort && url.port == defaultPort) {
url = url.newBuilder().port(14514).build()
replace = true
}
return url.toString().replace("${url.scheme}://", "$scheme://").let {
if (replace) it.replace(":14514", ":$defaultPort") else it
}
}
fun String.isIpAddress(): Boolean {
return NGUtil.isIpv4Address(this) || NGUtil.isIpv6Address(this)
}
fun String.isIpAddressV6(): Boolean {
return NGUtil.isIpv6Address(this)
}
// [2001:4860:4860::8888] -> 2001:4860:4860::8888
fun String.unwrapIPV6Host(): String {
if (startsWith("[") && endsWith("]")) {
return substring(1, length - 1).unwrapIPV6Host()
}
return this
}
// [2001:4860:4860::8888] or 2001:4860:4860::8888 -> [2001:4860:4860::8888]
fun String.wrapIPV6Host(): String {
val unwrapped = this.unwrapIPV6Host()
if (unwrapped.isIpAddressV6()) {
return "[$unwrapped]"
} else {
return this
}
}
fun io.nekohasekai.sagernet.ftm.AbstractBean.wrapUri(): String {
return "${finalAddress.wrapIPV6Host()}:$finalPort"
}
fun mkPort(): Int {
val socket = Socket()
socket.reuseAddress = true
socket.bind(InetSocketAddress(0))
val port = socket.localPort
socket.close()
return port
}
const val USER_AGENT = "Matsuri/0.4 (Prefer Clash Format)"
| Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/ktx/Nets.kt | 1803686251 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.ktx
import android.content.res.Resources
import kotlin.math.ceil
private val density = Resources.getSystem().displayMetrics.density
fun dp2pxf(dpValue: Int): Float {
return density * dpValue
}
fun dp2px(dpValue: Int): Int {
return ceil(dp2pxf(dpValue)).toInt()
}
| Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/ktx/Dimens.kt | 389599512 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.ktx
import android.app.Activity
import android.content.Context
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import io.nekohasekai.sagernet.R
import com.narcis.application.presentation.connection.Logs
import com.google.android.material.dialog.MaterialAlertDialogBuilder
fun Context.alert(text: String): AlertDialog {
return MaterialAlertDialogBuilder(this).setTitle(R.string.error_title)
.setMessage(text)
.setPositiveButton(android.R.string.ok, null)
.create()
}
fun Fragment.alert(text: String) = requireContext().alert(text)
fun AlertDialog.tryToShow() {
try {
val activity = context as Activity
if (!activity.isFinishing) {
show()
}
} catch (e: Exception) {
Logs.e(e)
}
}
| Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/ktx/Dialogs.kt | 2335919691 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.ktx
import android.graphics.Rect
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.narcis.application.presentation.MainActivity
import io.nekohasekai.sagernet.database.DataStore
class FixedLinearLayoutManager(val recyclerView: RecyclerView) :
LinearLayoutManager(recyclerView.context, RecyclerView.VERTICAL, false) {
override fun onLayoutChildren(recycler: RecyclerView.Recycler?, state: RecyclerView.State?) {
try {
super.onLayoutChildren(recycler, state)
} catch (ignored: IndexOutOfBoundsException) {
}
}
private var listenerDisabled = false
override fun scrollVerticallyBy(
dx: Int, recycler: RecyclerView.Recycler,
state: RecyclerView.State
): Int {
// Matsuri style
if (!DataStore.showBottomBar) return super.scrollVerticallyBy(dx, recycler, state)
// SagerNet Style
val scrollRange = super.scrollVerticallyBy(dx, recycler, state)
if (listenerDisabled) return scrollRange
val activity = recyclerView.context as? MainActivity
if (activity == null) {
listenerDisabled = true
return scrollRange
}
val overscroll = dx - scrollRange
if (overscroll > 0) {
val view =
(recyclerView.findViewHolderForAdapterPosition(findLastVisibleItemPosition())
?: return scrollRange).itemView
val itemLocation = Rect().also { view.getGlobalVisibleRect(it) }
// val fabLocation = Rect().also { activity.binding.fab.getGlobalVisibleRect(it) }
// if (!itemLocation.contains(fabLocation.left, fabLocation.top) && !itemLocation.contains(
// fabLocation.right,
// fabLocation.bottom
// )
// ) {
// return scrollRange
// }
// activity.binding.fab.apply {
// if (isShown) hide()
// }
} else {
/*val screen = Rect().also { activity.window.decorView.getGlobalVisibleRect(it) }
val location = Rect().also { activity.stats.getGlobalVisibleRect(it) }
if (screen.bottom < location.bottom) {
return scrollRange
}
val height = location.bottom - location.top
val mH = activity.stats.measuredHeight
if (mH > height) {
return scrollRange
}*/
// activity.binding.fab.apply {
// if (!isShown) show()
// }
}
return scrollRange
}
}
| Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/ktx/Layouts.kt | 1123475610 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.ktx
import androidx.preference.PreferenceDataStore
import kotlin.reflect.KProperty
fun PreferenceDataStore.string(
name: String,
defaultValue: () -> String = { "" },
) = PreferenceProxy(name, defaultValue, ::getString, ::putString)
fun PreferenceDataStore.boolean(
name: String,
defaultValue: () -> Boolean = { false },
) = PreferenceProxy(name, defaultValue, ::getBoolean, ::putBoolean)
fun PreferenceDataStore.int(
name: String,
defaultValue: () -> Int = { 0 },
) = PreferenceProxy(name, defaultValue, ::getInt, ::putInt)
fun PreferenceDataStore.stringSet(
name: String,
defaultValue: () -> Set<String> = { setOf() },
) = PreferenceProxy(name, defaultValue, ::getStringSet, ::putStringSet)
fun PreferenceDataStore.stringToInt(
name: String,
defaultValue: () -> Int = { 0 },
) = PreferenceProxy(name, defaultValue, { key, default ->
getString(key, "$default")?.toIntOrNull() ?: default
}, { key, value -> putString(key, "$value") })
fun PreferenceDataStore.stringToIntIfExists(
name: String,
defaultValue: () -> Int = { 0 },
) = PreferenceProxy(name, defaultValue, { key, default ->
getString(key, "$default")?.toIntOrNull() ?: default
}, { key, value -> putString(key, value.takeIf { it > 0 }?.toString() ?: "") })
fun PreferenceDataStore.long(
name: String,
defaultValue: () -> Long = { 0L },
) = PreferenceProxy(name, defaultValue, ::getLong, ::putLong)
fun PreferenceDataStore.stringToLong(
name: String,
defaultValue: () -> Long = { 0L },
) = PreferenceProxy(name, defaultValue, { key, default ->
getString(key, "$default")?.toLongOrNull() ?: default
}, { key, value -> putString(key, "$value") })
class PreferenceProxy<T>(
val name: String,
val defaultValue: () -> T,
val getter: (String, T) -> T?,
val setter: (String, value: T) -> Unit,
) {
operator fun setValue(thisObj: Any?, property: KProperty<*>, value: T) = setter(name, value)
operator fun getValue(thisObj: Any?, property: KProperty<*>) = getter(name, defaultValue())!!
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/ktx/Preferences.kt | 2103047070 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.ktx
import androidx.annotation.RawRes
import io.nekohasekai.sagernet.R
import com.github.shadowsocks.plugin.PluginConfiguration
import moe.matsuri.nya.neko.NekoBean
interface ValidateResult
object ResultSecure : ValidateResult
object ResultLocal : ValidateResult
class ResultDeprecated(@RawRes val textRes: Int) : ValidateResult
class ResultInsecure(@RawRes val textRes: Int) : ValidateResult
class ResultInsecureText(val text: String) : ValidateResult
val ssSecureList = "(gcm|poly1305)".toRegex()
fun io.nekohasekai.sagernet.ftm.AbstractBean.isInsecure(): ValidateResult {
if (serverAddress.isIpAddress()) {
if (serverAddress.startsWith("127.") || serverAddress.startsWith("::")) {
return ResultLocal
}
}
if (this is io.nekohasekai.sagernet.ftm.shadowsocks.ShadowsocksBean) {
if (plugin.isBlank() || PluginConfiguration(plugin).selected == "obfs-local") {
if (!method.contains(ssSecureList)) {
return ResultInsecure(R.raw.shadowsocks_stream_cipher)
}
}
} else if (this is io.nekohasekai.sagernet.ftm.shadowsocksr.ShadowsocksRBean) {
return ResultInsecure(R.raw.shadowsocksr)
} else if (this is io.nekohasekai.sagernet.ftm.http.HttpBean) {
if (!isTLS()) return ResultInsecure(R.raw.not_encrypted)
} else if (this is io.nekohasekai.sagernet.ftm.socks.SOCKSBean) {
if (!isTLS()) return ResultInsecure(R.raw.not_encrypted)
} else if (this is io.nekohasekai.sagernet.ftm.v2ray.VMessBean) {
if (security in arrayOf("", "none")) {
if (encryption in arrayOf("none", "zero")) {
return ResultInsecure(R.raw.not_encrypted)
}
}
if (type == "kcp" && mKcpSeed.isBlank()) {
return ResultInsecure(R.raw.mkcp_no_seed)
}
if (allowInsecure) return ResultInsecure(R.raw.insecure)
if (alterId > 0) return ResultDeprecated(R.raw.vmess_md5_auth)
} else if (this is io.nekohasekai.sagernet.ftm.hysteria.HysteriaBean) {
if (allowInsecure) return ResultInsecure(R.raw.insecure)
} else if (this is io.nekohasekai.sagernet.ftm.trojan.TrojanBean) {
if (security in arrayOf("", "none")) return ResultInsecure(R.raw.not_encrypted)
if (allowInsecure) return ResultInsecure(R.raw.insecure)
} else if (this is NekoBean) {
val hint = sharedStorage.optString("insecureHint")
if (hint.isNotBlank()) return ResultInsecureText(hint)
}
return ResultSecure
}
fun io.nekohasekai.sagernet.ftm.v2ray.StandardV2RayBean.isTLS(): Boolean {
return security == "tls"
}
fun io.nekohasekai.sagernet.ftm.v2ray.StandardV2RayBean.setTLS(boolean: Boolean) {
security = if (boolean) "tls" else ""
}
| Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/ktx/Validators.kt | 807503131 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* Copyright (C) 2021 by Max Lv <[email protected]> *
* Copyright (C) 2021 by Mygod Studio <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.plugin
import android.content.pm.ComponentInfo
import android.content.pm.ProviderInfo
import io.nekohasekai.sagernet.R
import moe.matsuri.nya.neko.Plugins
import com.narcis.application.presentation.connection.Logs
import io.nekohasekai.sagernet.SagerNet
import io.nekohasekai.sagernet.bg.BaseService
import java.io.File
import java.io.FileNotFoundException
object PluginManager {
class PluginNotFoundException(val plugin: String) : FileNotFoundException(plugin),
BaseService.ExpectedException {
override fun getLocalizedMessage() =
SagerNet.application.getString(R.string.plugin_unknown, plugin)
}
data class InitResult(
val path: String,
val info: ProviderInfo,
)
@Throws(Throwable::class)
fun init(pluginId: String): InitResult? {
if (pluginId.isEmpty()) return null
var throwable: Throwable? = null
try {
val result = initNative(pluginId)
if (result != null) return result
} catch (t: Throwable) {
if (throwable == null) throwable = t else Logs.w(t)
}
throw throwable ?: PluginNotFoundException(pluginId)
}
private fun initNative(pluginId: String): InitResult? {
val info = Plugins.getPlugin(pluginId) ?: return null
try {
initNativeFaster(info)?.also { return InitResult(it, info) }
} catch (t: Throwable) {
Logs.w("Initializing native plugin faster mode failed", t)
}
Logs.w("Init native returns empty result")
return null
}
private fun initNativeFaster(provider: ProviderInfo): String? {
return provider.loadString(Plugins.METADATA_KEY_EXECUTABLE_PATH)
?.let { relativePath ->
File(provider.applicationInfo.nativeLibraryDir).resolve(relativePath).apply {
check(canExecute())
}.absolutePath
}
}
fun ComponentInfo.loadString(key: String) = when (val value = metaData.get(key)) {
is String -> value
is Int -> SagerNet.application.packageManager.getResourcesForApplication(applicationInfo)
.getString(value)
null -> null
else -> error("meta-data $key has invalid type ${value.javaClass}")
}
}
| Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/plugin/PluginManager.kt | 2134178541 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* Copyright (C) 2021 by Max Lv <[email protected]> *
* Copyright (C) 2021 by Mygod Studio <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.utils
import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.app.Application
import android.content.Context
@SuppressLint("Registered")
@TargetApi(24)
class DeviceStorageApp(context: Context) : Application() {
init {
attachBaseContext(context.createDeviceProtectedStorageContext())
}
/**
* Thou shalt not get the REAL underlying application context which would no longer be operating under device
* protected storage.
*/
override fun getApplicationContext() = this
}
| Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/utils/DeviceStorageApp.kt | 857389675 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* Copyright (C) 2021 by Max Lv <[email protected]> *
* Copyright (C) 2021 by Mygod Studio <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.utils
import android.annotation.TargetApi
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import android.os.Build
import android.os.Handler
import android.os.Looper
import com.narcis.application.presentation.connection.Logs
import io.nekohasekai.sagernet.SagerNet
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.channels.actor
import kotlinx.coroutines.runBlocking
import java.net.UnknownHostException
object DefaultNetworkListener {
private sealed class NetworkMessage {
class Start(val key: Any, val listener: (Network?) -> Unit) : NetworkMessage()
class Get : NetworkMessage() {
val response = CompletableDeferred<Network>()
}
class Stop(val key: Any) : NetworkMessage()
class Put(val network: Network) : NetworkMessage()
class Update(val network: Network) : NetworkMessage()
class Lost(val network: Network) : NetworkMessage()
}
private val networkActor = GlobalScope.actor<NetworkMessage>(Dispatchers.Unconfined) {
val listeners = mutableMapOf<Any, (Network?) -> Unit>()
var network: Network? = null
val pendingRequests = arrayListOf<NetworkMessage.Get>()
for (message in channel) when (message) {
is NetworkMessage.Start -> {
if (listeners.isEmpty()) register()
listeners[message.key] = message.listener
if (network != null) message.listener(network)
}
is NetworkMessage.Get -> {
check(listeners.isNotEmpty()) { "Getting network without any listeners is not supported" }
if (network == null) pendingRequests += message else message.response.complete(
network
)
}
is NetworkMessage.Stop -> if (listeners.isNotEmpty() && // was not empty
listeners.remove(message.key) != null && listeners.isEmpty()
) {
network = null
unregister()
}
is NetworkMessage.Put -> {
network = message.network
pendingRequests.forEach { it.response.complete(message.network) }
pendingRequests.clear()
listeners.values.forEach { it(network) }
}
is NetworkMessage.Update -> if (network == message.network) listeners.values.forEach {
it(
network
)
}
is NetworkMessage.Lost -> if (network == message.network) {
network = null
listeners.values.forEach { it(null) }
}
}
}
suspend fun start(key: Any, listener: (Network?) -> Unit) =
networkActor.send(NetworkMessage.Start(key, listener))
suspend fun get() = if (fallback) @TargetApi(23) {
SagerNet.connectivity.activeNetwork
?: throw UnknownHostException() // failed to listen, return current if available
} else NetworkMessage.Get().run {
networkActor.send(this)
response.await()
}
suspend fun stop(key: Any) = networkActor.send(NetworkMessage.Stop(key))
// NB: this runs in ConnectivityThread, and this behavior cannot be changed until API 26
private object Callback : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) =
runBlocking { networkActor.send(NetworkMessage.Put(network)) }
override fun onCapabilitiesChanged(
network: Network, networkCapabilities: NetworkCapabilities
) { // it's a good idea to refresh capabilities
runBlocking { networkActor.send(NetworkMessage.Update(network)) }
}
override fun onLost(network: Network) =
runBlocking { networkActor.send(NetworkMessage.Lost(network)) }
}
private var fallback = false
private val request = NetworkRequest.Builder().apply {
addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
if (Build.VERSION.SDK_INT == 23) { // workarounds for OEM bugs
removeCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
removeCapability(NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL)
}
}.build()
private val mainHandler = Handler(Looper.getMainLooper())
/**
* Unfortunately registerDefaultNetworkCallback is going to return VPN interface since Android P DP1:
* https://android.googlesource.com/platform/frameworks/base/+/dda156ab0c5d66ad82bdcf76cda07cbc0a9c8a2e
*
* This makes doing a requestNetwork with REQUEST necessary so that we don't get ALL possible networks that
* satisfies default network capabilities but only THE default network. Unfortunately, we need to have
* android.permission.CHANGE_NETWORK_STATE to be able to call requestNetwork.
*
* Source: https://android.googlesource.com/platform/frameworks/base/+/2df4c7d/services/core/java/com/android/server/ConnectivityService.java#887
*/
private fun register() {
try {
fallback = false
when (Build.VERSION.SDK_INT) {
in 31..Int.MAX_VALUE -> @TargetApi(31) {
SagerNet.connectivity.registerBestMatchingNetworkCallback(
request, Callback, mainHandler
)
}
in 28 until 31 -> @TargetApi(28) { // we want REQUEST here instead of LISTEN
SagerNet.connectivity.requestNetwork(request, Callback, mainHandler)
}
in 26 until 28 -> @TargetApi(26) {
SagerNet.connectivity.registerDefaultNetworkCallback(Callback, mainHandler)
}
in 24 until 26 -> @TargetApi(24) {
SagerNet.connectivity.registerDefaultNetworkCallback(Callback)
}
else -> {
SagerNet.connectivity.requestNetwork(request, Callback)
// known bug on API 23: https://stackoverflow.com/a/33509180/2245107
}
}
} catch (e: Exception) {
Logs.w(e)
fallback = true
}
}
private fun unregister() = SagerNet.connectivity.unregisterNetworkCallback(Callback)
}
| Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/utils/DefaultNetworkListener.kt | 3680491948 |
/******************************************************************************
* Copyright (C) 2021 by nekohasekai <contact-git></contact-git>@sekai.icu> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>. *
* *
*/
package io.nekohasekai.sagernet.utils.cf
import com.google.gson.Gson
import com.google.gson.annotations.SerializedName
import com.wireguard.crypto.Key
import java.text.SimpleDateFormat
import java.util.*
data class RegisterRequest(
@SerializedName("fcm_token") var fcmToken: String = "",
@SerializedName("install_id") var installedId: String = "",
var key: String = "",
var locale: String = "",
var model: String = "",
var tos: String = "",
var type: String = ""
) {
companion object {
fun newRequest(publicKey: Key): String {
val request = RegisterRequest()
request.fcmToken = ""
request.installedId = ""
request.key = publicKey.toBase64()
request.locale = "en_US"
request.model = "PC"
val format = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'000000'+08:00", Locale.US)
request.tos = format.format(Date())
request.type = "Android"
return Gson().toJson(request)
}
}
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/utils/cf/RegisterRequest.kt | 1626785839 |
/******************************************************************************
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.utils.cf
import com.google.gson.Gson
data class UpdateDeviceRequest(
var name: String, var active: Boolean
) {
companion object {
fun newRequest(name: String = "SagerNet Client", active: Boolean = true) =
Gson().toJson(UpdateDeviceRequest(name, active))
}
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/utils/cf/UpdateDeviceRequest.kt | 2485422487 |
/******************************************************************************
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.utils.cf
import com.google.gson.annotations.SerializedName
data class DeviceResponse(
@SerializedName("created")
var created: String = "",
@SerializedName("type")
var type: String = "",
@SerializedName("locale")
var locale: String = "",
@SerializedName("enabled")
var enabled: Boolean = false,
@SerializedName("token")
var token: String = "",
@SerializedName("waitlist_enabled")
var waitlistEnabled: Boolean = false,
@SerializedName("install_id")
var installId: String = "",
@SerializedName("warp_enabled")
var warpEnabled: Boolean = false,
@SerializedName("name")
var name: String = "",
@SerializedName("fcm_token")
var fcmToken: String = "",
@SerializedName("tos")
var tos: String = "",
@SerializedName("model")
var model: String = "",
@SerializedName("id")
var id: String = "",
@SerializedName("place")
var place: Int = 0,
@SerializedName("config")
var config: Config = Config(),
@SerializedName("updated")
var updated: String = "",
@SerializedName("key")
var key: String = "",
@SerializedName("account")
var account: Account = Account()
) {
data class Config(
@SerializedName("peers")
var peers: List<Peer> = listOf(),
@SerializedName("services")
var services: Services = Services(),
@SerializedName("interface")
var interfaceX: Interface = Interface(),
@SerializedName("client_id")
var clientId: String = ""
) {
data class Peer(
@SerializedName("public_key")
var publicKey: String = "",
@SerializedName("endpoint")
var endpoint: Endpoint = Endpoint()
) {
data class Endpoint(
@SerializedName("v6")
var v6: String = "",
@SerializedName("host")
var host: String = "",
@SerializedName("v4")
var v4: String = ""
)
}
data class Services(
@SerializedName("http_proxy")
var httpProxy: String = ""
)
data class Interface(
@SerializedName("addresses")
var addresses: Addresses = Addresses()
) {
data class Addresses(
@SerializedName("v6")
var v6: String = "",
@SerializedName("v4")
var v4: String = ""
)
}
}
data class Account(
@SerializedName("account_type")
var accountType: String = "",
@SerializedName("role")
var role: String = "",
@SerializedName("referral_renewal_countdown")
var referralRenewalCountdown: Int = 0,
@SerializedName("created")
var created: String = "",
@SerializedName("usage")
var usage: Int = 0,
@SerializedName("warp_plus")
var warpPlus: Boolean = false,
@SerializedName("referral_count")
var referralCount: Int = 0,
@SerializedName("license")
var license: String = "",
@SerializedName("quota")
var quota: Int = 0,
@SerializedName("premium_data")
var premiumData: Int = 0,
@SerializedName("id")
var id: String = "",
@SerializedName("updated")
var updated: String = ""
)
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/utils/cf/DeviceResponse.kt | 780857883 |
/******************************************************************************
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.utils
import android.annotation.SuppressLint
import android.os.Build
import android.util.Log
import io.nekohasekai.sagernet.BuildConfig
import com.narcis.application.presentation.connection.Logs
import io.nekohasekai.sagernet.database.preference.PublicDatabase
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.text.SimpleDateFormat
import java.util.*
import java.util.regex.Pattern
object CrashHandler : Thread.UncaughtExceptionHandler {
@Suppress("UNNECESSARY_SAFE_CALL")
override fun uncaughtException(thread: Thread, throwable: Throwable) {
// note: libc / go panic is in android log
try {
Log.e(thread.toString(), throwable.stackTraceToString())
} catch (e: Exception) {
}
try {
Logs.e(thread.toString())
Logs.e(throwable.stackTraceToString())
} catch (e: Exception) {
}
// ProcessPhoenix.triggerRebirth(app, Intent(app, BlankActivity::class.java).apply {
// putExtra("sendLog", "Matsuri Crash")
// })
}
fun formatThrowable(throwable: Throwable): String {
var format = throwable.javaClass.name
val message = throwable.message
if (!message.isNullOrBlank()) {
format += ": $message"
}
format += "\n"
format += throwable.stackTrace.joinToString("\n") {
" at ${it.className}.${it.methodName}(${it.fileName}:${if (it.isNativeMethod) "native" else it.lineNumber})"
}
val cause = throwable.cause
if (cause != null) {
format += "\n\nCaused by: " + formatThrowable(cause)
}
return format
}
fun buildReportHeader(): String {
var report = ""
report += "Masturi ${BuildConfig.VERSION_NAME} (${BuildConfig.VERSION_CODE}) \n"
report += "Date: ${getCurrentMilliSecondUTCTimeStamp()}\n\n"
report += "OS_VERSION: ${getSystemPropertyWithAndroidAPI("os.version")}\n"
report += "SDK_INT: ${Build.VERSION.SDK_INT}\n"
report += if ("REL" == Build.VERSION.CODENAME) {
"RELEASE: ${Build.VERSION.RELEASE}"
} else {
"CODENAME: ${Build.VERSION.CODENAME}"
} + "\n"
report += "ID: ${Build.ID}\n"
report += "DISPLAY: ${Build.DISPLAY}\n"
report += "INCREMENTAL: ${Build.VERSION.INCREMENTAL}\n"
val systemProperties = getSystemProperties()
report += "SECURITY_PATCH: ${systemProperties.getProperty("ro.build.version.security_patch")}\n"
report += "IS_DEBUGGABLE: ${systemProperties.getProperty("ro.debuggable")}\n"
report += "IS_EMULATOR: ${systemProperties.getProperty("ro.boot.qemu")}\n"
report += "IS_TREBLE_ENABLED: ${systemProperties.getProperty("ro.treble.enabled")}\n"
report += "TYPE: ${Build.TYPE}\n"
report += "TAGS: ${Build.TAGS}\n\n"
report += "MANUFACTURER: ${Build.MANUFACTURER}\n"
report += "BRAND: ${Build.BRAND}\n"
report += "MODEL: ${Build.MODEL}\n"
report += "PRODUCT: ${Build.PRODUCT}\n"
report += "BOARD: ${Build.BOARD}\n"
report += "HARDWARE: ${Build.HARDWARE}\n"
report += "DEVICE: ${Build.DEVICE}\n"
report += "SUPPORTED_ABIS: ${
Build.SUPPORTED_ABIS.filter { it.isNotBlank() }.joinToString(", ")
}\n\n"
try {
report += "Settings: \n"
for (pair in PublicDatabase.kvPairDao.all()) {
report += "\n"
report += pair.key + ": " + pair.toString()
}
}catch (e: Exception) {
report += "Export settings failed: " + formatThrowable(e)
}
report += "\n\n"
return report
}
private fun getSystemProperties(): Properties {
val systemProperties = Properties()
// getprop commands returns values in the format `[key]: [value]`
// Regex matches string starting with a literal `[`,
// followed by one or more characters that do not match a closing square bracket as the key,
// followed by a literal `]: [`,
// followed by one or more characters as the value,
// followed by string ending with literal `]`
// multiline values will be ignored
val propertiesPattern = Pattern.compile("^\\[([^]]+)]: \\[(.+)]$")
try {
val process = ProcessBuilder().command("/system/bin/getprop")
.redirectErrorStream(true)
.start()
val inputStream = process.inputStream
val bufferedReader = BufferedReader(InputStreamReader(inputStream))
var line: String?
var key: String
var value: String
while (bufferedReader.readLine().also { line = it } != null) {
val matcher = propertiesPattern.matcher(line)
if (matcher.matches()) {
key = matcher.group(1)
value = matcher.group(2)
if (key != null && value != null && !key.isEmpty() && !value.isEmpty()) systemProperties[key] = value
}
}
bufferedReader.close()
process.destroy()
} catch (e: IOException) {
Logs.e(
"Failed to get run \"/system/bin/getprop\" to get system properties.", e
)
}
//for (String key : systemProperties.stringPropertyNames()) {
// Logger.logVerbose(key + ": " + systemProperties.get(key));
//}
return systemProperties
}
private fun getSystemPropertyWithAndroidAPI(property: String): String? {
return try {
System.getProperty(property)
} catch (e: Exception) {
Logs.e("Failed to get system property \"" + property + "\":" + e.message)
null
}
}
@SuppressLint("SimpleDateFormat")
private fun getCurrentMilliSecondUTCTimeStamp(): String {
val df = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS z")
df.timeZone = TimeZone.getTimeZone("UTC")
return df.format(Date())
}
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/utils/CrashHandler.kt | 2507551977 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.utils
import android.content.Context
import android.content.res.Configuration
import androidx.appcompat.app.AppCompatDelegate
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.ktx.app
object Theme {
const val RED = 1
const val PINK_SSR = 2
const val PINK = 3
const val PURPLE = 4
const val DEEP_PURPLE = 5
const val INDIGO = 6
const val BLUE = 7
const val LIGHT_BLUE = 8
const val CYAN = 9
const val TEAL = 10
const val GREEN = 11
const val LIGHT_GREEN = 12
const val LIME = 13
const val YELLOW = 14
const val AMBER = 15
const val ORANGE = 16
const val DEEP_ORANGE = 17
const val BROWN = 18
const val GREY = 19
const val BLUE_GREY = 20
const val BLACK = 21
private fun defaultTheme() = LIGHT_BLUE
fun apply(context: Context) {
context.setTheme(getTheme())
}
fun applyDialog(context: Context) {
context.setTheme(getDialogTheme())
}
fun getTheme(): Int {
return getTheme(DataStore.appTheme)
}
fun getDialogTheme(): Int {
return getDialogTheme(DataStore.appTheme)
}
fun getTheme(theme: Int): Int {
return when (theme) {
RED -> R.style.Theme_SagerNet_Red
PINK -> R.style.Theme_SagerNet
PINK_SSR -> R.style.Theme_SagerNet_Pink_SSR
PURPLE -> R.style.Theme_SagerNet_Purple
DEEP_PURPLE -> R.style.Theme_SagerNet_DeepPurple
INDIGO -> R.style.Theme_SagerNet_Indigo
BLUE -> R.style.Theme_SagerNet_Blue
LIGHT_BLUE -> R.style.Theme_SagerNet_LightBlue
CYAN -> R.style.Theme_SagerNet_Cyan
TEAL -> R.style.Theme_SagerNet_Teal
GREEN -> R.style.Theme_SagerNet_Green
LIGHT_GREEN -> R.style.Theme_SagerNet_LightGreen
LIME -> R.style.Theme_SagerNet_Lime
YELLOW -> R.style.Theme_SagerNet_Yellow
AMBER -> R.style.Theme_SagerNet_Amber
ORANGE -> R.style.Theme_SagerNet_Orange
DEEP_ORANGE -> R.style.Theme_SagerNet_DeepOrange
BROWN -> R.style.Theme_SagerNet_Brown
GREY -> R.style.Theme_SagerNet_Grey
BLUE_GREY -> R.style.Theme_SagerNet_BlueGrey
BLACK -> R.style.Theme_SagerNet_Black
else -> getTheme(defaultTheme())
}
}
fun getDialogTheme(theme: Int): Int {
return when (theme) {
RED -> R.style.Theme_SagerNet_Dialog_Red
PINK -> R.style.Theme_SagerNet_Dialog
PINK_SSR -> R.style.Theme_SagerNet_Dialog_Pink_SSR
PURPLE -> R.style.Theme_SagerNet_Dialog_Purple
DEEP_PURPLE -> R.style.Theme_SagerNet_Dialog_DeepPurple
INDIGO -> R.style.Theme_SagerNet_Dialog_Indigo
BLUE -> R.style.Theme_SagerNet_Dialog_Blue
LIGHT_BLUE -> R.style.Theme_SagerNet_Dialog_LightBlue
CYAN -> R.style.Theme_SagerNet_Dialog_Cyan
TEAL -> R.style.Theme_SagerNet_Dialog_Teal
GREEN -> R.style.Theme_SagerNet_Dialog_Green
LIGHT_GREEN -> R.style.Theme_SagerNet_Dialog_LightGreen
LIME -> R.style.Theme_SagerNet_Dialog_Lime
YELLOW -> R.style.Theme_SagerNet_Dialog_Yellow
AMBER -> R.style.Theme_SagerNet_Dialog_Amber
ORANGE -> R.style.Theme_SagerNet_Dialog_Orange
DEEP_ORANGE -> R.style.Theme_SagerNet_Dialog_DeepOrange
BROWN -> R.style.Theme_SagerNet_Dialog_Brown
GREY -> R.style.Theme_SagerNet_Dialog_Grey
BLUE_GREY -> R.style.Theme_SagerNet_Dialog_BlueGrey
BLACK -> R.style.Theme_SagerNet_Dialog_Black
else -> getDialogTheme(defaultTheme())
}
}
var currentNightMode = -1
fun getNightMode(): Int {
if (currentNightMode == -1) {
currentNightMode = DataStore.nightTheme
}
return getNightMode(currentNightMode)
}
fun getNightMode(mode: Int): Int {
return when (mode) {
0 -> AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM
1 -> AppCompatDelegate.MODE_NIGHT_YES
2 -> AppCompatDelegate.MODE_NIGHT_NO
else -> AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY
}
}
fun usingNightMode(): Boolean {
return when (DataStore.nightTheme) {
1 -> true
2 -> false
else -> (app.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES
}
}
fun applyNightTheme() {
AppCompatDelegate.setDefaultNightMode(getNightMode())
}
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/utils/Theme.kt | 62604191 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* Copyright (C) 2021 by Max Lv <[email protected]> *
* Copyright (C) 2021 by Mygod Studio <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.utils
import io.nekohasekai.sagernet.ktx.parseNumericAddress
import java.net.InetAddress
import java.util.Objects
class Subnet(val address: InetAddress, val prefixSize: Int) : Comparable<Subnet> {
companion object {
fun fromString(value: String, lengthCheck: Int = -1): Subnet? {
val parts = value.split('/', limit = 2)
val addr = parts[0].parseNumericAddress() ?: return null
check(lengthCheck < 0 || addr.address.size == lengthCheck)
return if (parts.size == 2) try {
val prefixSize = parts[1].toInt()
if (prefixSize < 0 || prefixSize > addr.address.size shl 3) null else Subnet(addr,
prefixSize)
} catch (_: NumberFormatException) {
null
} else Subnet(addr, addr.address.size shl 3)
}
}
private val addressLength get() = address.address.size shl 3
init {
require(prefixSize in 0..addressLength) { "prefixSize $prefixSize not in 0..$addressLength" }
}
class Immutable(private val a: ByteArray, private val prefixSize: Int = 0) {
companion object : Comparator<Immutable> {
override fun compare(a: Immutable, b: Immutable): Int {
check(a.a.size == b.a.size)
for (i in a.a.indices) {
val result = a.a[i].compareTo(b.a[i])
if (result != 0) return result
}
return 0
}
}
fun matches(b: Immutable) = matches(b.a)
fun matches(b: ByteArray): Boolean {
if (a.size != b.size) return false
var i = 0
while (i * 8 < prefixSize && i * 8 + 8 <= prefixSize) {
if (a[i] != b[i]) return false
++i
}
return i * 8 == prefixSize || a[i] == (b[i].toInt() and -(1 shl i * 8 + 8 - prefixSize)).toByte()
}
}
fun toImmutable() = Immutable(address.address.also {
var i = prefixSize / 8
if (prefixSize % 8 > 0) {
it[i] = (it[i].toInt() and -(1 shl i * 8 + 8 - prefixSize)).toByte()
++i
}
while (i < it.size) it[i++] = 0
}, prefixSize)
override fun toString(): String =
if (prefixSize == addressLength) address.hostAddress else address.hostAddress + '/' + prefixSize
private fun Byte.unsigned() = toInt() and 0xFF
override fun compareTo(other: Subnet): Int {
val addrThis = address.address
val addrThat = other.address.address
var result =
addrThis.size.compareTo(addrThat.size) // IPv4 address goes first
if (result != 0) return result
for (i in addrThis.indices) {
result = addrThis[i].unsigned()
.compareTo(addrThat[i].unsigned()) // undo sign extension of signed byte
if (result != 0) return result
}
return prefixSize.compareTo(other.prefixSize)
}
override fun equals(other: Any?): Boolean {
val that = other as? Subnet
return address == that?.address && prefixSize == that.prefixSize
}
override fun hashCode(): Int = Objects.hash(address, prefixSize)
}
| Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/utils/Subnet.kt | 3920874475 |
/******************************************************************************
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.utils
import com.wireguard.crypto.KeyPair
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.ftm.gson.gson
import io.nekohasekai.sagernet.ftm.wireguard.WireGuardBean
import io.nekohasekai.sagernet.utils.cf.DeviceResponse
import io.nekohasekai.sagernet.utils.cf.RegisterRequest
import io.nekohasekai.sagernet.utils.cf.UpdateDeviceRequest
import libcore.Libcore
// kang from wgcf
object Cloudflare {
private const val API_URL = "https://api.cloudflareclient.com"
private const val API_VERSION = "v0a1922"
private const val CLIENT_VERSION_KEY = "CF-Client-Version"
private const val CLIENT_VERSION = "a-6.3-1922"
fun makeWireGuardConfiguration(): WireGuardBean {
val keyPair = KeyPair()
val client = Libcore.newHttpClient().apply {
pinnedTLS12()
trySocks5(DataStore.socksPort)
}
try {
val response = client.newRequest().apply {
setMethod("POST")
setURL("$API_URL/$API_VERSION/reg")
setHeader(CLIENT_VERSION_KEY, CLIENT_VERSION)
setHeader("Accept", "application/json")
setHeader("Content-Type", "application/json")
setContentString(RegisterRequest.newRequest(keyPair.publicKey))
setUserAgent("okhttp/3.12.1")
}.execute()
val device = gson.fromJson(response.contentString, DeviceResponse::class.java)
val accessToken = device.token
client.newRequest().apply {
setMethod("PATCH")
setURL(API_URL + "/" + API_VERSION + "/reg/" + device.id + "/account/reg/" + device.id)
setHeader("Accept", "application/json")
setHeader("Content-Type", "application/json")
setHeader("Authorization", "Bearer $accessToken")
setHeader(CLIENT_VERSION_KEY, CLIENT_VERSION)
setContentString(UpdateDeviceRequest.newRequest())
setUserAgent("okhttp/3.12.1")
}.execute()
val peer = device.config.peers[0]
val localAddresses = device.config.interfaceX.addresses
return WireGuardBean().apply {
name = "CloudFlare Warp ${device.account.id}"
privateKey = keyPair.privateKey.toBase64()
peerPublicKey = peer.publicKey
serverAddress = peer.endpoint.host.substringBeforeLast(":")
serverPort = peer.endpoint.host.substringAfterLast(":").toInt()
localAddress = localAddresses.v4 + "\n" + localAddresses.v6
}
} finally {
client.close()
}
}
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/utils/Cloudflare.kt | 2048994240 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* Copyright (C) 2021 by Max Lv <[email protected]> *
* Copyright (C) 2021 by Mygod Studio <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.utils
import java.util.StringTokenizer
/**
* Commandline objects help handling command lines specifying processes to
* execute.
*
* The class can be used to define a command line as nested elements or as a
* helper to define a command line by an application.
*
*
* `
* <someelement><br></br>
* <acommandline executable="/executable/to/run"><br></br>
* <argument value="argument 1" /><br></br>
* <argument line="argument_1 argument_2 argument_3" /><br></br>
* <argument value="argument 4" /><br></br>
* </acommandline><br></br>
* </someelement><br></br>
` *
*
* Based on: https://github.com/apache/ant/blob/588ce1f/src/main/org/apache/tools/ant/types/Commandline.java
*
* Adds support for escape character '\'.
*/
object Commandline {
/**
* Quote the parts of the given array in way that makes them
* usable as command line arguments.
* @param args the list of arguments to quote.
* @return empty string for null or no command, else every argument split
* by spaces and quoted by quoting rules.
*/
fun toString(args: Iterable<String>?): String {
// empty path return empty string
args ?: return ""
// path containing one or more elements
val result = StringBuilder()
for (arg in args) {
if (result.isNotEmpty()) result.append(' ')
arg.indices.map { arg[it] }.forEach {
when (it) {
' ', '\\', '"', '\'' -> {
result.append('\\') // intentionally no break
result.append(it)
}
else -> result.append(it)
}
}
}
return result.toString()
}
/**
* Quote the parts of the given array in way that makes them
* usable as command line arguments.
* @param args the list of arguments to quote.
* @return empty string for null or no command, else every argument split
* by spaces and quoted by quoting rules.
*/
fun toString(args: Array<String>) =
toString(args.asIterable()) // thanks to Java, arrays aren't iterable
/**
* Crack a command line.
* @param toProcess the command line to process.
* @return the command line broken into strings.
* An empty or null toProcess parameter results in a zero sized array.
*/
fun translateCommandline(toProcess: String?): Array<String> {
if (toProcess == null || toProcess.isEmpty()) {
//no command? no string
return arrayOf()
}
// parse with a simple finite state machine
val normal = 0
val inQuote = 1
val inDoubleQuote = 2
var state = normal
val tok = StringTokenizer(toProcess, "\\\"\' ", true)
val result = ArrayList<String>()
val current = StringBuilder()
var lastTokenHasBeenQuoted = false
var lastTokenIsSlash = false
while (tok.hasMoreTokens()) {
val nextTok = tok.nextToken()
when (state) {
inQuote -> if ("\'" == nextTok) {
lastTokenHasBeenQuoted = true
state = normal
} else current.append(nextTok)
inDoubleQuote -> when (nextTok) {
"\"" -> if (lastTokenIsSlash) {
current.append(nextTok)
lastTokenIsSlash = false
} else {
lastTokenHasBeenQuoted = true
state = normal
}
"\\" -> lastTokenIsSlash = if (lastTokenIsSlash) {
current.append(nextTok)
false
} else true
else -> {
if (lastTokenIsSlash) {
current.append("\\") // unescaped
lastTokenIsSlash = false
}
current.append(nextTok)
}
}
else -> {
when {
lastTokenIsSlash -> {
current.append(nextTok)
lastTokenIsSlash = false
}
"\\" == nextTok -> lastTokenIsSlash = true
"\'" == nextTok -> state = inQuote
"\"" == nextTok -> state = inDoubleQuote
" " == nextTok -> if (lastTokenHasBeenQuoted || current.isNotEmpty()) {
result.add(current.toString())
current.setLength(0)
}
else -> current.append(nextTok)
}
lastTokenHasBeenQuoted = false
}
}
}
if (lastTokenHasBeenQuoted || current.isNotEmpty()) result.add(current.toString())
require(state != inQuote && state != inDoubleQuote) { "unbalanced quotes in $toProcess" }
require(!lastTokenIsSlash) { "escape character following nothing in $toProcess" }
return result.toTypedArray()
}
}
| Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/utils/Commandline.kt | 4001108165 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.utils
import android.Manifest
import android.annotation.SuppressLint
import android.content.pm.ApplicationInfo
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import moe.matsuri.nya.neko.Plugins
import io.nekohasekai.sagernet.ktx.app
import io.nekohasekai.sagernet.ktx.listenForPackageChanges
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import java.util.concurrent.atomic.AtomicBoolean
object PackageCache {
lateinit var installedPackages: Map<String, PackageInfo>
lateinit var installedPluginPackages: Map<String, PackageInfo>
lateinit var installedApps: Map<String, ApplicationInfo>
lateinit var packageMap: Map<String, Int>
val uidMap = HashMap<Int, HashSet<String>>()
val loaded = Mutex(true)
var registerd = AtomicBoolean(false)
// called from init (suspend)
fun register() {
if (registerd.getAndSet(true)) return
reload()
app.listenForPackageChanges(false) {
reload()
labelMap.clear()
}
loaded.unlock()
}
@SuppressLint("InlinedApi")
fun reload() {
val rawPackageInfo = app.packageManager.getInstalledPackages(
PackageManager.MATCH_UNINSTALLED_PACKAGES
or PackageManager.GET_PERMISSIONS
or PackageManager.GET_PROVIDERS
or PackageManager.GET_META_DATA
)
installedPackages = rawPackageInfo.filter {
when (it.packageName) {
"android" -> true
else -> it.requestedPermissions?.contains(Manifest.permission.INTERNET) == true
}
}.associateBy { it.packageName }
installedPluginPackages = rawPackageInfo.filter {
Plugins.isExeOrPlugin(it)
}.associateBy { it.packageName }
val installed = app.packageManager.getInstalledApplications(PackageManager.GET_META_DATA)
installedApps = installed.associateBy { it.packageName }
packageMap = installed.associate { it.packageName to it.uid }
uidMap.clear()
for (info in installed) {
val uid = info.uid
uidMap.getOrPut(uid) { HashSet() }.add(info.packageName)
}
}
operator fun get(uid: Int) = uidMap[uid]
operator fun get(packageName: String) = packageMap[packageName]
suspend fun awaitLoad() {
if (PackageCache::packageMap.isInitialized) {
return
}
loaded.withLock {
// just await
}
}
fun awaitLoadSync() {
if (PackageCache::packageMap.isInitialized) {
return
}
if (!registerd.get()) {
register()
return
}
runBlocking {
loaded.withLock {
// just await
}
}
}
private val labelMap = mutableMapOf<String, String>()
fun loadLabel(packageName: String): String {
var label = labelMap[packageName]
if (label != null) return label
val info = installedApps[packageName] ?: return packageName
label = info.loadLabel(app.packageManager).toString()
labelMap[packageName] = label
return label
}
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/utils/PackageCache.kt | 2217683034 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* Copyright (C) 2021 by Max Lv <[email protected]> *
* Copyright (C) 2021 by Mygod Studio <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet
import android.annotation.SuppressLint
import android.app.*
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.net.ConnectivityManager
import android.net.Network
import android.os.Build
import android.os.PowerManager
import android.os.StrictMode
import android.os.UserManager
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
import androidx.core.content.getSystemService
import com.narcis.application.presentation.connection.Logs
import com.narcis.application.presentation.connection.runOnDefaultDispatcher
import dagger.hilt.android.HiltAndroidApp
import go.Seq
import io.nekohasekai.sagernet.bg.SagerConnection
import io.nekohasekai.sagernet.database.DataStore
import com.narcis.application.presentation.MainActivity
import io.nekohasekai.sagernet.utils.CrashHandler
import io.nekohasekai.sagernet.utils.DefaultNetworkListener
import io.nekohasekai.sagernet.utils.DeviceStorageApp
import io.nekohasekai.sagernet.utils.PackageCache
import io.nekohasekai.sagernet.utils.Theme
import kotlinx.coroutines.DEBUG_PROPERTY_NAME
import kotlinx.coroutines.DEBUG_PROPERTY_VALUE_ON
import libcore.Libcore
import libcore.UidDumper
import libcore.UidInfo
import moe.matsuri.nya.utils.JavaUtil
import moe.matsuri.nya.utils.cleanWebview
import java.net.InetSocketAddress
import androidx.work.Configuration as WorkConfiguration
@HiltAndroidApp
class SagerNet :
Application(),
UidDumper,
WorkConfiguration.Provider {
override fun attachBaseContext(base: Context) {
super.attachBaseContext(base)
application = this
}
val externalAssets by lazy { getExternalFilesDir(null) ?: filesDir }
val process = JavaUtil.getProcessName()
val isMainProcess = process == BuildConfig.APPLICATION_ID
val isBgProcess = process.endsWith(":bg")
override fun onCreate() {
super.onCreate()
System.setProperty(DEBUG_PROPERTY_NAME, DEBUG_PROPERTY_VALUE_ON)
Thread.setDefaultUncaughtExceptionHandler(CrashHandler)
if (isMainProcess || isBgProcess) {
// fix multi process issue in Android 9+
JavaUtil.handleWebviewDir(this)
runOnDefaultDispatcher {
PackageCache.register()
cleanWebview()
}
}
DataStore.init()
Seq.setContext(this)
updateNotificationChannels()
// matsuri: init core (sn: extract v2ray assets
externalAssets.mkdirs()
Libcore.initCore(filesDir.absolutePath + "/", externalAssets.absolutePath + "/", "v2ray/", {
DataStore.rulesProvider == 0
}, cacheDir.absolutePath, process, DataStore.enableLog, DataStore.logBufSize)
if (isMainProcess) {
Theme.apply(this)
Theme.applyNightTheme()
runOnDefaultDispatcher {
DefaultNetworkListener.start(this) {
underlyingNetwork = it
}
}
}
if (isBgProcess) {
Libcore.setUidDumper(this, Build.VERSION.SDK_INT < Build.VERSION_CODES.Q)
}
if (BuildConfig.DEBUG) {
StrictMode.setVmPolicy(
StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
.detectLeakedRegistrationObjects()
.penaltyLog()
.build(),
)
}
}
@RequiresApi(Build.VERSION_CODES.Q)
override fun dumpUid(
ipProto: Int,
srcIp: String,
srcPort: Int,
destIp: String,
destPort: Int,
): Int {
return connectivity.getConnectionOwnerUid(
ipProto,
InetSocketAddress(srcIp, srcPort),
InetSocketAddress(destIp, destPort),
)
}
override fun getUidInfo(uid: Int): UidInfo {
PackageCache.awaitLoadSync()
if (uid <= 1000L) {
val uidInfo = UidInfo()
uidInfo.label = PackageCache.loadLabel("android")
uidInfo.packageName = "android"
return uidInfo
}
val packageNames = PackageCache.uidMap[uid.toInt()]
if (!packageNames.isNullOrEmpty()) {
for (packageName in packageNames) {
val uidInfo = UidInfo()
uidInfo.label = PackageCache.loadLabel(packageName)
uidInfo.packageName = packageName
return uidInfo
}
}
error("unknown uid $uid")
}
fun getPackageInfo(packageName: String) = packageManager.getPackageInfo(
packageName,
if (Build.VERSION.SDK_INT >= 28) {
PackageManager.GET_SIGNING_CERTIFICATES
} else {
@Suppress("DEPRECATION")
PackageManager.GET_SIGNATURES
},
)!!
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
updateNotificationChannels()
}
override fun getWorkManagerConfiguration(): WorkConfiguration {
return WorkConfiguration.Builder()
.setDefaultProcessName("${BuildConfig.APPLICATION_ID}:bg")
.build()
}
override fun onTrimMemory(level: Int) {
super.onTrimMemory(level)
Libcore.forceGc()
}
@SuppressLint("InlinedApi")
companion object {
lateinit var application: SagerNet
val isTv by lazy {
uiMode.currentModeType == Configuration.UI_MODE_TYPE_TELEVISION
}
// /data/user_de available when not unlocked
val deviceStorage by lazy {
if (Build.VERSION.SDK_INT < 24) application else DeviceStorageApp(application)
}
val configureIntent: (Context) -> PendingIntent by lazy {
{
PendingIntent.getActivity(
it,
0,
Intent(
application,
MainActivity::class.java,
).setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT),
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.FLAG_IMMUTABLE else 0,
)
}
}
val activity by lazy { application.getSystemService<ActivityManager>()!! }
val clipboard by lazy { application.getSystemService<ClipboardManager>()!! }
val connectivity by lazy { application.getSystemService<ConnectivityManager>()!! }
val notification by lazy { application.getSystemService<NotificationManager>()!! }
val user by lazy { application.getSystemService<UserManager>()!! }
val uiMode by lazy { application.getSystemService<UiModeManager>()!! }
val power by lazy { application.getSystemService<PowerManager>()!! }
val packageInfo: PackageInfo by lazy { application.getPackageInfo(application.packageName) }
fun getClipboardText(): String {
return clipboard.primaryClip?.takeIf { it.itemCount > 0 }
?.getItemAt(0)?.text?.toString() ?: ""
}
fun trySetPrimaryClip(clip: String) = try {
clipboard.setPrimaryClip(ClipData.newPlainText(null, clip))
true
} catch (e: RuntimeException) {
Logs.w(e)
false
}
@RequiresApi(26)
fun updateNotificationChannels() {
if (Build.VERSION.SDK_INT >= 26) {
run {
notification.createNotificationChannels(
listOf(
NotificationChannel(
"service-vpn",
application.getText(R.string.service_vpn),
if (Build.VERSION.SDK_INT >= 28) {
NotificationManager.IMPORTANCE_MIN
} else {
NotificationManager.IMPORTANCE_LOW
},
), // #1355
NotificationChannel(
"service-proxy",
application.getText(R.string.service_proxy),
NotificationManager.IMPORTANCE_LOW,
),
NotificationChannel(
"service-subscription",
application.getText(R.string.service_subscription),
NotificationManager.IMPORTANCE_DEFAULT,
),
),
)
}
}
}
fun startService() = ContextCompat.startForegroundService(
application,
Intent(application, SagerConnection.serviceClass),
)
fun reloadService() =
application.sendBroadcast(Intent(Action.RELOAD).setPackage(application.packageName))
fun stopService() =
application.sendBroadcast(Intent(Action.CLOSE).setPackage(application.packageName))
var underlyingNetwork: Network? = null
}
}
| Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/SagerNet.kt | 2776451024 |
package io.nekohasekai.sagernet.bg
import android.Manifest
import android.annotation.SuppressLint
import android.app.Service
import android.content.Intent
import android.content.pm.PackageManager
import android.net.DnsResolver
import android.net.LocalSocket
import android.net.Network
import android.net.ProxyInfo
import android.os.Build
import android.os.CancellationSignal
import android.os.ParcelFileDescriptor
import android.os.PowerManager
import android.system.ErrnoException
import android.system.Os
import androidx.annotation.RequiresApi
import io.nekohasekai.sagernet.R
import moe.matsuri.nya.neko.needBypassRootUid
import com.narcis.application.presentation.connection.Logs
import com.narcis.application.presentation.connection.VpnRequestActivity
import com.narcis.application.presentation.connection.runOnDefaultDispatcher
import com.github.shadowsocks.net.ConcurrentLocalSocketListener
import io.nekohasekai.sagernet.IPv6Mode
import io.nekohasekai.sagernet.Key
import io.nekohasekai.sagernet.SagerNet
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.database.SagerDatabase
import io.nekohasekai.sagernet.database.StatsEntity
import io.nekohasekai.sagernet.ftm.LOCALHOST
import io.nekohasekai.sagernet.ftm.hysteria.HysteriaBean
import io.nekohasekai.sagernet.ktx.int
import io.nekohasekai.sagernet.ktx.tryResume
import io.nekohasekai.sagernet.ktx.tryResumeWithException
import io.nekohasekai.sagernet.utils.PackageCache
import io.nekohasekai.sagernet.utils.Subnet
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.asExecutor
import kotlinx.coroutines.runBlocking
import libcore.AppStats
import libcore.ErrorHandler
import libcore.Libcore
import libcore.LocalResolver
import libcore.Protector
import libcore.TrafficListener
import libcore.Tun2ray
import libcore.TunConfig
import timber.log.Timber
import java.io.File
import java.io.FileDescriptor
import java.io.IOException
import java.net.InetAddress
import kotlin.coroutines.suspendCoroutine
import android.net.VpnService as BaseVpnService
class VpnService :
BaseVpnService(),
BaseService.Interface,
TrafficListener,
LocalResolver,
Protector {
companion object {
var instance: VpnService? = null
const val PRIVATE_VLAN4_CLIENT = "172.19.0.1"
const val PRIVATE_VLAN4_ROUTER = "172.19.0.2"
const val FAKEDNS_VLAN4_CLIENT = "198.18.0.0"
const val PRIVATE_VLAN6_CLIENT = "fdfe:dcba:9876::1"
const val PRIVATE_VLAN6_ROUTER = "fdfe:dcba:9876::2"
private fun <T> FileDescriptor.use(block: (FileDescriptor) -> T) = try {
block(this)
} finally {
try {
Os.close(this)
} catch (_: ErrnoException) {
}
}
}
lateinit var conn: ParcelFileDescriptor
private lateinit var tun: Tun2ray
fun getTun(): Tun2ray? {
if (!::tun.isInitialized) return null
return tun
}
private var active = false
private var metered = false
@Volatile
override var underlyingNetwork: Network? = null
@RequiresApi(Build.VERSION_CODES.LOLLIPOP_MR1)
set(value) {
field = value
if (active && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
setUnderlyingNetworks(underlyingNetworks)
}
}
private val underlyingNetworks
get() = // clearing underlyingNetworks makes Android 9 consider the network to be metered
if (Build.VERSION.SDK_INT == 28 && metered) {
null
} else {
underlyingNetwork?.let {
arrayOf(it)
}
}
override var upstreamInterfaceName: String? = null
private var worker: ProtectWorker? = null
override suspend fun startProcesses() {
worker = ProtectWorker().apply { start() }
super.startProcesses()
startVpn()
}
override var wakeLock: PowerManager.WakeLock? = null
@SuppressLint("WakelockTimeout")
override fun acquireWakeLock() {
wakeLock = SagerNet.power.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "sagernet:vpn")
.apply { acquire() }
}
@Suppress("EXPERIMENTAL_API_USAGE")
override fun killProcesses() {
runOnDefaultDispatcher {
worker?.shutdown(this)
worker = null
}
getTun()?.close()
if (::conn.isInitialized) conn.close()
super.killProcesses()
persistAppStats()
active = false
}
override fun onBind(intent: Intent) = when (intent.action) {
SERVICE_INTERFACE -> super<BaseVpnService>.onBind(intent)
else -> super<BaseService.Interface>.onBind(intent)
}
override val data = BaseService.Data(this)
override val tag = "SagerNetVpnService"
override fun createNotification(profileName: String) =
ServiceNotification(this, profileName, "service-vpn")
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (DataStore.serviceMode == Key.MODE_VPN) {
if (prepare(this) != null) {
startActivity(
Intent(
this,
VpnRequestActivity::class.java
).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
)
} else {
return super<BaseService.Interface>.onStartCommand(intent, flags, startId)
}
}
stopRunner()
return Service.START_NOT_STICKY
}
inner class NullConnectionException :
NullPointerException(),
BaseService.ExpectedException {
override fun getLocalizedMessage() = getString(R.string.reboot_required)
}
private fun startVpn() {
instance = this
val profile = data.proxy!!.profile
val builder = Builder().setConfigureIntent(SagerNet.configureIntent(this))
.setSession(profile.displayName())
.setMtu(DataStore.mtu)
val ipv6Mode = DataStore.ipv6Mode
builder.addAddress(PRIVATE_VLAN4_CLIENT, 30)
if (ipv6Mode != IPv6Mode.DISABLE) {
builder.addAddress(PRIVATE_VLAN6_CLIENT, 126)
}
if (DataStore.bypassLan) {
resources.getStringArray(R.array.bypass_private_route).forEach {
val subnet = Subnet.fromString(it)!!
builder.addRoute(subnet.address.hostAddress!!, subnet.prefixSize)
}
builder.addRoute(PRIVATE_VLAN4_ROUTER, 32)
builder.addRoute(FAKEDNS_VLAN4_CLIENT, 15)
// https://issuetracker.google.com/issues/149636790
if (ipv6Mode != IPv6Mode.DISABLE) {
builder.addRoute("2000::", 3)
}
} else {
builder.addRoute("0.0.0.0", 0)
if (ipv6Mode != IPv6Mode.DISABLE) {
builder.addRoute("::", 0)
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
builder.setUnderlyingNetworks(underlyingNetworks)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) builder.setMetered(metered)
val packageName = packageName
var proxyApps = DataStore.proxyApps
var bypass = DataStore.bypass
var workaroundSYSTEM = false /* DataStore.tunImplementation == TunImplementation.SYSTEM */
var needBypassRootUid = workaroundSYSTEM || data.proxy!!.config.outboundTagsAll.values.any {
it.nekoBean?.needBypassRootUid() == true || it.hysteriaBean?.protocol == HysteriaBean.PROTOCOL_FAKETCP
}
if (proxyApps || needBypassRootUid) {
val individual = mutableSetOf<String>()
val allApps by lazy {
packageManager.getInstalledPackages(PackageManager.GET_PERMISSIONS).filter {
when (it.packageName) {
packageName -> false
"android" -> true
else -> it.requestedPermissions?.contains(Manifest.permission.INTERNET) == true
}
}.map {
it.packageName
}
}
if (proxyApps) {
individual.addAll(DataStore.individual.split('\n').filter { it.isNotBlank() })
if (bypass && needBypassRootUid) {
val individualNew = allApps.toMutableList()
individualNew.removeAll(individual)
individual.clear()
individual.addAll(individualNew)
bypass = false
}
} else {
individual.addAll(allApps)
bypass = false
}
val added = mutableListOf<String>()
individual.apply {
// Allow Matsuri itself using VPN.
remove(packageName)
if (!bypass) add(packageName)
}.forEach {
try {
if (bypass) {
builder.addDisallowedApplication(it)
} else {
builder.addAllowedApplication(it)
}
added.add(it)
} catch (ex: PackageManager.NameNotFoundException) {
Logs.w(ex)
}
}
if (bypass) {
Logs.d("Add bypass: ${added.joinToString(", ")}")
} else {
Logs.d("Add allow: ${added.joinToString(", ")}")
}
}
builder.addDnsServer(PRIVATE_VLAN4_ROUTER)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && DataStore.appendHttpProxy && DataStore.requireHttp) {
builder.setHttpProxy(ProxyInfo.buildDirectProxy(LOCALHOST, DataStore.httpPort))
}
metered = DataStore.meteredNetwork
active = true // possible race condition here?
if (Build.VERSION.SDK_INT >= 29) builder.setMetered(metered)
conn = builder.establish() ?: throw NullConnectionException()
val config = TunConfig().apply {
fileDescriptor = conn.fd
mtu = DataStore.mtu
v2Ray = data.proxy!!.v2rayPoint
iPv6Mode = ipv6Mode
implementation = 2 // Tun2Socket
sniffing = DataStore.trafficSniffing
fakeDNS = DataStore.enableFakeDns
debug = DataStore.enableLog
dumpUID = data.proxy!!.config.dumpUid
trafficStats = DataStore.appTrafficStatistics
errorHandler = ErrorHandler {
stopRunner(false, it)
}
localResolver = this@VpnService
fdProtector = this@VpnService
}
Timber.i("^^^^", config.toString())
tun = Libcore.newTun2ray(config)
}
// this is sekaiResolver
override fun lookupIP(network: String, domain: String): String {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
return runBlocking {
suspendCoroutine { continuation ->
val signal = CancellationSignal()
val callback = object : DnsResolver.Callback<Collection<InetAddress>> {
@Suppress("ThrowableNotThrown")
override fun onAnswer(answer: Collection<InetAddress>, rcode: Int) {
// libcore/v2ray.go
when {
answer.isNotEmpty() -> {
continuation.tryResume(
(answer as Collection<InetAddress?>).mapNotNull { it?.hostAddress }
.joinToString(",")
)
}
rcode == 0 -> {
// fuck AAAA no record
// features/dns/client.go
continuation.tryResume("")
}
else -> {
// Need return rcode
// proxy/dns/dns.go
continuation.tryResumeWithException(Exception("$rcode"))
}
}
}
override fun onError(error: DnsResolver.DnsException) {
continuation.tryResumeWithException(error)
}
}
val type = when {
network.endsWith("4") -> DnsResolver.TYPE_A
network.endsWith("6") -> DnsResolver.TYPE_AAAA
else -> null
}
if (type != null) {
DnsResolver.getInstance().query(
underlyingNetwork,
domain,
type,
DnsResolver.FLAG_EMPTY,
Dispatchers.IO.asExecutor(),
signal,
callback
)
} else {
DnsResolver.getInstance().query(
underlyingNetwork,
domain,
DnsResolver.FLAG_EMPTY,
Dispatchers.IO.asExecutor(),
signal,
callback
)
}
}
}
} else {
throw Exception("114514")
}
}
val appStats = mutableListOf<AppStats>()
override fun updateStats(stats: AppStats) {
appStats.add(stats)
}
fun persistAppStats() {
if (!DataStore.appTrafficStatistics) return
val tun = getTun() ?: return
appStats.clear()
tun.readAppTraffics(this)
val toUpdate = mutableListOf<StatsEntity>()
val all = SagerDatabase.statsDao.all().associateBy { it.packageName }
for (stats in appStats) {
if (stats.nekoConnectionsJSON.isNotBlank()) continue
val packageName = if (stats.uid >= 10000) {
PackageCache.uidMap[stats.uid]?.iterator()?.next() ?: "android"
} else {
"android"
}
if (!all.containsKey(packageName)) {
SagerDatabase.statsDao.create(
StatsEntity(
packageName = packageName,
tcpConnections = stats.tcpConnTotal,
udpConnections = stats.udpConnTotal,
uplink = stats.uplinkTotal,
downlink = stats.downlinkTotal
)
)
} else {
val entity = all[packageName]!!
entity.tcpConnections += stats.tcpConnTotal
entity.udpConnections += stats.udpConnTotal
entity.uplink += stats.uplinkTotal
entity.downlink += stats.downlinkTotal
toUpdate.add(entity)
}
if (toUpdate.isNotEmpty()) {
SagerDatabase.statsDao.update(toUpdate)
}
}
}
override fun onRevoke() = stopRunner()
override fun onDestroy() {
super.onDestroy()
data.binder.close()
}
private inner class ProtectWorker : ConcurrentLocalSocketListener(
"ShadowsocksVpnThread",
File(SagerNet.application.noBackupFilesDir, "protect_path")
) {
override fun acceptInternal(socket: LocalSocket) {
if (socket.inputStream.read() == -1) return
val success = socket.ancillaryFileDescriptors?.single()?.use { fd ->
underlyingNetwork.let { network ->
if (network != null) {
try {
network.bindSocket(fd)
return@let true
} catch (e: IOException) {
Logs.w(e)
return@let false
}
}
protect(fd.int)
}
} ?: false
try {
socket.outputStream.write(if (success) 0 else 1)
} catch (_: IOException) {
} // ignore connection early close
}
}
}
| Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/bg/VpnService.kt | 3057310559 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* Copyright (C) 2021 by Max Lv <[email protected]> *
* Copyright (C) 2021 by Mygod Studio <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.bg
import android.system.ErrnoException
import android.system.Os
import android.system.OsConstants
import android.text.TextUtils
import com.narcis.application.presentation.connection.Logs
import java.io.File
import java.io.IOException
object Executable {
private val EXECUTABLES = setOf(
"libtrojan.so",
"libtrojan-go.so",
"libnaive.so",
"libhysteria.so",
"libwg.so"
)
fun killAll() {
for (process in File("/proc").listFiles { _, name -> TextUtils.isDigitsOnly(name) }
?: return) {
val exe = File(try {
File(process, "cmdline").inputStream().bufferedReader().use {
it.readText()
}
} catch (_: IOException) {
continue
}.split(Character.MIN_VALUE, limit = 2).first())
if (EXECUTABLES.contains(exe.name)) try {
Os.kill(process.name.toInt(), OsConstants.SIGKILL)
Logs.w("SIGKILL ${exe.nameWithoutExtension} (${process.name}) succeed")
} catch (e: ErrnoException) {
if (e.errno != OsConstants.ESRCH) {
Logs.w("SIGKILL ${exe.absolutePath} (${process.name}) failed")
Logs.w(e)
}
}
}
}
}
| Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/bg/Executable.kt | 1852884999 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* Copyright (C) 2021 by Max Lv <[email protected]> *
* Copyright (C) 2021 by Mygod Studio <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.bg
import android.annotation.SuppressLint
import android.app.Service
import android.content.Intent
import android.net.Network
import android.os.PowerManager
import io.nekohasekai.sagernet.SagerNet
class ProxyService : Service(), BaseService.Interface {
override val data = BaseService.Data(this)
override val tag: String get() = "SagerNetProxyService"
override fun createNotification(profileName: String): ServiceNotification =
ServiceNotification(this, profileName, "service-proxy", true)
override var wakeLock: PowerManager.WakeLock? = null
override var underlyingNetwork: Network? = null
override var upstreamInterfaceName: String? = null
@SuppressLint("WakelockTimeout")
override fun acquireWakeLock() {
wakeLock = SagerNet.power.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "sagernet:proxy")
.apply { acquire() }
}
override fun onBind(intent: Intent) = super.onBind(intent)
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int =
super<BaseService.Interface>.onStartCommand(intent, flags, startId)
override fun onDestroy() {
super.onDestroy()
data.binder.close()
}
}
| Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/bg/ProxyService.kt | 3705586739 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.bg.proto
import com.narcis.application.presentation.connection.Logs
import io.nekohasekai.sagernet.bg.BaseService
import io.nekohasekai.sagernet.database.ProxyEntity
import io.nekohasekai.sagernet.database.SagerDatabase
import kotlinx.coroutines.runBlocking
import java.io.IOException
class ProxyInstance(profile: ProxyEntity, val service: BaseService.Interface) : V2RayInstance(
profile
) {
override suspend fun init() {
super.init()
Logs.d(config.config)
pluginConfigs.forEach { (_, plugin) ->
val (_, content) = plugin
Logs.d(content)
}
}
override fun launch() {
super.launch()
/* if (BuildConfig.DEBUG && DataStore.enableLog) {
externalInstances[9999] = DebugInstance().apply {
launch()
}
}*/
}
override fun close() {
persistStats()
super.close()
}
// ------------- stats -------------
private suspend fun queryStats(tag: String, direct: String): Long {
return v2rayPoint.queryStats(tag, direct)
}
private val currentTags by lazy {
mapOf(* config.outboundTagsCurrent.map {
it to config.outboundTagsAll[it]
}.toTypedArray())
}
private val statsTags by lazy {
mapOf(* config.outboundTags.toMutableList().apply {
removeAll(config.outboundTagsCurrent)
}.map {
it to config.outboundTagsAll[it]
}.toTypedArray())
}
private val interTags by lazy {
config.outboundTagsAll.filterKeys { !config.outboundTags.contains(it) }
}
class OutboundStats(
val proxyEntity: ProxyEntity, var uplinkTotal: Long = 0L, var downlinkTotal: Long = 0L
)
private val statsOutbounds = hashMapOf<Long, OutboundStats>()
private fun registerStats(
proxyEntity: ProxyEntity, uplink: Long? = null, downlink: Long? = null
) {
if (proxyEntity.id == outboundStats.proxyEntity.id) return
val stats = statsOutbounds.getOrPut(proxyEntity.id) {
OutboundStats(proxyEntity)
}
if (uplink != null) {
stats.uplinkTotal += uplink
}
if (downlink != null) {
stats.downlinkTotal += downlink
}
}
var uplinkProxy = 3L
var downlinkProxy = 4L
var uplinkTotalDirect = 5L
var downlinkTotalDirect = 6L
private val outboundStats = OutboundStats(profile)
suspend fun outboundStats(): Pair<OutboundStats, HashMap<Long, OutboundStats>> {
if (!isInitialized()) return outboundStats to statsOutbounds
uplinkProxy = 0L
downlinkProxy = 0L
val currentUpLink = currentTags.map { (tag, profile) ->
queryStats(tag, "uplink").apply {
profile?.also {
registerStats(
it, uplink = this
)
}
}
}
val currentDownLink = currentTags.map { (tag, profile) ->
queryStats(tag, "downlink").apply {
profile?.also {
registerStats(it, downlink = this)
}
}
}
uplinkProxy += currentUpLink.fold(0L) { acc, l -> acc + l }
downlinkProxy += currentDownLink.fold(0L) { acc, l -> acc + l }
outboundStats.uplinkTotal += uplinkProxy
outboundStats.downlinkTotal += downlinkProxy
if (statsTags.isNotEmpty()) {
uplinkProxy += statsTags.map { (tag, profile) ->
queryStats(tag, "uplink").apply {
profile?.also {
registerStats(it, uplink = this)
}
}
}.fold(0L) { acc, l -> acc + l }
downlinkProxy += statsTags.map { (tag, profile) ->
queryStats(tag, "downlink").apply {
profile?.also {
registerStats(it, downlink = this)
}
}
}.fold(0L) { acc, l -> acc + l }
}
if (interTags.isNotEmpty()) {
interTags.map { (tag, profile) ->
queryStats(tag, "uplink").also { registerStats(profile, uplink = it) }
}
interTags.map { (tag, profile) ->
queryStats(tag, "downlink").also {
registerStats(profile, downlink = it)
}
}
}
return outboundStats to statsOutbounds
}
suspend fun bypassStats(direct: String): Long {
if (!isInitialized()) return 0L
return queryStats(config.bypassTag, direct)
}
suspend fun uplinkDirect() = bypassStats("uplink").also {
uplinkTotalDirect += it
}
suspend fun downlinkDirect() = bypassStats("downlink").also {
downlinkTotalDirect += it
}
fun persistStats() {
runBlocking {
try {
outboundStats()
val toUpdate = mutableListOf<ProxyEntity>()
if (outboundStats.uplinkTotal + outboundStats.downlinkTotal != 0L) {
profile.tx += outboundStats.uplinkTotal
profile.rx += outboundStats.downlinkTotal
toUpdate.add(profile)
}
statsOutbounds.values.forEach {
if (it.uplinkTotal + it.downlinkTotal != 0L) {
it.proxyEntity.tx += it.uplinkTotal
it.proxyEntity.rx += it.downlinkTotal
toUpdate.add(it.proxyEntity)
}
}
if (toUpdate.isNotEmpty()) {
SagerDatabase.proxyDao.updateProxy(toUpdate)
}
} catch (e: IOException) {
throw e // we should only reach here because we're in direct boot
}
}
}
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/bg/proto/ProxyInstance.kt | 3931253060 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.bg.proto
import android.annotation.SuppressLint
import android.os.Build
import android.os.SystemClock
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import moe.matsuri.nya.neko.NekoBean
import moe.matsuri.nya.neko.NekoJSInterface
import moe.matsuri.nya.neko.NekoPluginManager
import moe.matsuri.nya.neko.updateAllConfig
import com.narcis.application.presentation.connection.Logs
import com.narcis.application.presentation.connection.onMainDispatcher
import com.narcis.application.presentation.connection.runOnMainDispatcher
import io.nekohasekai.sagernet.SagerNet
import io.nekohasekai.sagernet.bg.AbstractInstance
import io.nekohasekai.sagernet.bg.GuardedProcessPool
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.database.ProxyEntity
import io.nekohasekai.sagernet.ftm.LOCALHOST
import io.nekohasekai.sagernet.ftm.V2rayBuildResult
import io.nekohasekai.sagernet.ftm.buildV2RayConfig
import io.nekohasekai.sagernet.ftm.hysteria.HysteriaBean
import io.nekohasekai.sagernet.ftm.hysteria.buildHysteriaConfig
import io.nekohasekai.sagernet.ftm.naive.NaiveBean
import io.nekohasekai.sagernet.ftm.naive.buildNaiveConfig
import io.nekohasekai.sagernet.ftm.trojan_go.TrojanGoBean
import io.nekohasekai.sagernet.ftm.trojan_go.buildTrojanGoConfig
import io.nekohasekai.sagernet.ftm.tuic.TuicBean
import io.nekohasekai.sagernet.ftm.tuic.buildTuicConfig
import io.nekohasekai.sagernet.ftm.wireguard.WireGuardBean
import io.nekohasekai.sagernet.ftm.wireguard.buildWireGuardUapiConf
import io.nekohasekai.sagernet.ktx.app
import io.nekohasekai.sagernet.ktx.forEach
import io.nekohasekai.sagernet.plugin.PluginManager
import kotlinx.coroutines.*
import libcore.Libcore
import libcore.V2RayInstance
import org.json.JSONObject
import java.io.File
abstract class V2RayInstance(
val profile: ProxyEntity,
) : AbstractInstance {
lateinit var config: V2rayBuildResult
lateinit var v2rayPoint: V2RayInstance
private lateinit var wsForwarder: WebView
val pluginPath = hashMapOf<String, PluginManager.InitResult>()
val pluginConfigs = hashMapOf<Int, Pair<Int, String>>()
val externalInstances = hashMapOf<Int, AbstractInstance>()
open lateinit var processes: GuardedProcessPool
private var cacheFiles = ArrayList<File>()
fun isInitialized(): Boolean {
return ::config.isInitialized
}
protected fun initPlugin(name: String): PluginManager.InitResult {
return pluginPath.getOrPut(name) { PluginManager.init(name)!! }
}
protected open fun buildConfig() {
config = buildV2RayConfig(profile)
}
protected open suspend fun loadConfig() {
NekoJSInterface.Default.destroyAllJsi()
Libcore.setEnableLog(DataStore.enableLog, DataStore.logBufSize)
Libcore.setConfig(config.tryDomains.joinToString(","), false)
v2rayPoint.setConnectionPoolEnabled(DataStore.appTrafficStatistics)
v2rayPoint.loadConfig(config.config)
}
open suspend fun init() {
v2rayPoint = V2RayInstance()
buildConfig()
for ((chain) in config.index) {
chain.entries.forEachIndexed { index, (port, profile) ->
when (val bean = profile.requireBean()) {
is TrojanGoBean -> {
initPlugin("trojan-go-plugin")
pluginConfigs[port] = profile.type to bean.buildTrojanGoConfig(port)
}
is NaiveBean -> {
initPlugin("naive-plugin")
pluginConfigs[port] = profile.type to bean.buildNaiveConfig(port)
}
is HysteriaBean -> {
initPlugin("hysteria-plugin")
pluginConfigs[port] = profile.type to bean.buildHysteriaConfig(port) {
File(
app.cacheDir,
"hysteria_" + SystemClock.elapsedRealtime() + ".ca"
).apply {
parentFile?.mkdirs()
cacheFiles.add(this)
}
}
}
is WireGuardBean -> {
initPlugin("wireguard-plugin")
pluginConfigs[port] = profile.type to bean.buildWireGuardUapiConf()
}
is TuicBean -> {
initPlugin("tuic-plugin")
pluginConfigs[port] = profile.type to bean.buildTuicConfig(port) {
File(
app.noBackupFilesDir,
"tuic_" + SystemClock.elapsedRealtime() + ".ca"
).apply {
parentFile?.mkdirs()
cacheFiles.add(this)
}
}
}
is NekoBean -> {
// check if plugin binary can be loaded
initPlugin(bean.plgId)
// build config and check if succeed
bean.updateAllConfig(port)
if (bean.allConfig == null) {
throw NekoPluginManager.PluginInternalException(bean.protocolId)
}
}
}
}
}
loadConfig()
}
@SuppressLint("SetJavaScriptEnabled")
override fun launch() {
val context = if (Build.VERSION.SDK_INT < 24 || SagerNet.user.isUserUnlocked) SagerNet.application else SagerNet.deviceStorage
val cache = File(context.cacheDir, "tmpcfg")
cache.mkdirs()
for ((chain) in config.index) {
chain.entries.forEachIndexed { index, (port, profile) ->
val bean = profile.requireBean()
val needChain = index != chain.size - 1
val (profileType, config) = pluginConfigs[port] ?: (0 to "")
when {
externalInstances.containsKey(port) -> {
externalInstances[port]!!.launch()
}
bean is TrojanGoBean -> {
val configFile = File(
cache,
"trojan_go_" + SystemClock.elapsedRealtime() + ".json"
)
configFile.parentFile?.mkdirs()
configFile.writeText(config)
cacheFiles.add(configFile)
val commands = mutableListOf(
initPlugin("trojan-go-plugin").path,
"-config",
configFile.absolutePath
)
processes.start(commands)
}
bean is NaiveBean -> {
val configFile = File(
cache,
"naive_" + SystemClock.elapsedRealtime() + ".json"
)
configFile.parentFile?.mkdirs()
configFile.writeText(config)
cacheFiles.add(configFile)
val envMap = mutableMapOf<String, String>()
if (bean.certificates.isNotBlank()) {
val certFile = File(
cache,
"naive_" + SystemClock.elapsedRealtime() + ".crt"
)
certFile.parentFile?.mkdirs()
certFile.writeText(bean.certificates)
cacheFiles.add(certFile)
envMap["SSL_CERT_FILE"] = certFile.absolutePath
}
val commands = mutableListOf(
initPlugin("naive-plugin").path,
configFile.absolutePath
)
processes.start(commands, envMap)
}
bean is HysteriaBean -> {
val configFile = File(
cache,
"hysteria_" + SystemClock.elapsedRealtime() + ".json"
)
configFile.parentFile?.mkdirs()
configFile.writeText(config)
cacheFiles.add(configFile)
val commands = mutableListOf(
initPlugin("hysteria-plugin").path,
"--no-check",
"--config",
configFile.absolutePath,
"--log-level",
if (DataStore.enableLog) "trace" else "warn",
"client"
)
if (bean.protocol == HysteriaBean.PROTOCOL_FAKETCP) {
commands.addAll(0, listOf("su", "-c"))
}
processes.start(commands)
}
bean is WireGuardBean -> {
val configFile = File(
cache,
"wg_" + SystemClock.elapsedRealtime() + ".conf"
)
configFile.parentFile?.mkdirs()
configFile.writeText(config)
cacheFiles.add(configFile)
val commands = mutableListOf(
initPlugin("wireguard-plugin").path,
"-a",
bean.localAddress.split("\n").joinToString(","),
"-b",
"127.0.0.1:$port",
"-c",
configFile.absolutePath,
"-d",
"127.0.0.1:${DataStore.localDNSPort}"
)
processes.start(commands)
}
bean is NekoBean -> {
// config built from JS
val nekoRunConfigs = bean.allConfig.optJSONArray("nekoRunConfigs")
val configs = mutableMapOf<String, String>()
nekoRunConfigs?.forEach { _, any ->
any as JSONObject
val name = any.getString("name")
val configFile = File(cache, name)
configFile.parentFile?.mkdirs()
val content = any.getString("content")
configFile.writeText(content)
cacheFiles.add(configFile)
configs[name] = configFile.absolutePath
Logs.d(name + "\n\n" + content)
}
val nekoCommands = bean.allConfig.getJSONArray("nekoCommands")
val commands = mutableListOf<String>()
nekoCommands.forEach { _, any ->
if (any is String) {
if (configs.containsKey(any)) {
commands.add(configs[any]!!)
} else if (any == "%exe%") {
commands.add(initPlugin(bean.plgId).path)
} else {
commands.add(any)
}
}
}
processes.start(commands)
}
bean is TuicBean -> {
val configFile = File(
context.noBackupFilesDir,
"tuic_" + SystemClock.elapsedRealtime() + ".json"
)
configFile.parentFile?.mkdirs()
configFile.writeText(config)
cacheFiles.add(configFile)
val commands = mutableListOf(
initPlugin("tuic-plugin").path,
"-c",
configFile.absolutePath,
)
processes.start(commands)
}
}
}
}
v2rayPoint.start()
if (config.wsPort > 0) {
val url = "http://${LOCALHOST}:" + (config.wsPort) + "/"
runOnMainDispatcher {
wsForwarder = WebView(context)
wsForwarder.settings.javaScriptEnabled = true
wsForwarder.webViewClient = object : WebViewClient() {
override fun onReceivedError(
view: WebView?,
request: WebResourceRequest?,
error: WebResourceError?,
) {
Logs.d("WebView load r: $error")
runOnMainDispatcher {
wsForwarder.loadUrl("about:blank")
delay(1000L)
wsForwarder.loadUrl(url)
}
}
override fun onPageFinished(view: WebView, url: String) {
super.onPageFinished(view, url)
Logs.d("WebView loaded: ${view.title}")
}
}
wsForwarder.loadUrl(url)
}
}
}
@Suppress("EXPERIMENTAL_API_USAGE")
override fun close() {
for (instance in externalInstances.values) {
runCatching {
instance.close()
}
}
cacheFiles.removeAll { it.delete(); true }
if (::wsForwarder.isInitialized) {
runBlocking {
onMainDispatcher {
wsForwarder.loadUrl("about:blank")
wsForwarder.destroy()
}
}
}
if (::processes.isInitialized) processes.close(GlobalScope + Dispatchers.IO)
if (::v2rayPoint.isInitialized) {
v2rayPoint.close()
}
}
}
| Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/bg/proto/V2RayInstance.kt | 886194676 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.bg.test
import com.narcis.application.presentation.connection.Logs
import com.narcis.application.presentation.connection.runOnDefaultDispatcher
import io.nekohasekai.sagernet.BuildConfig
import io.nekohasekai.sagernet.bg.GuardedProcessPool
import io.nekohasekai.sagernet.bg.proto.V2RayInstance
import io.nekohasekai.sagernet.database.ProxyEntity
import io.nekohasekai.sagernet.ftm.buildV2RayConfig
import io.nekohasekai.sagernet.ktx.tryResume
import io.nekohasekai.sagernet.ktx.tryResumeWithException
import libcore.Libcore
import kotlin.coroutines.suspendCoroutine
class V2RayTestInstance(profile: ProxyEntity, val link: String, val timeout: Int) : V2RayInstance(
profile
) {
suspend fun doTest(): Int {
return suspendCoroutine { c ->
processes = GuardedProcessPool {
Logs.w(it)
c.tryResumeWithException(it)
}
runOnDefaultDispatcher {
use {
try {
init()
launch()
c.tryResume(Libcore.urlTestV2ray(v2rayPoint, "", link, timeout))
} catch (e: Exception) {
c.tryResumeWithException(e)
}
}
}
}
}
override fun buildConfig() {
config = buildV2RayConfig(profile, true)
}
override suspend fun loadConfig() {
// don't call destroyAllJsi here
if (BuildConfig.DEBUG) Logs.d(config.config)
v2rayPoint.forTest = true
v2rayPoint.loadConfig(config.config)
}
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/bg/test/V2RayTestInstance.kt | 3833945364 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.bg.test
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.database.ProxyEntity
class UrlTest {
val link = DataStore.connectionTestURL
val timeout = 3000
suspend fun doTest(profile: ProxyEntity): Int {
return V2RayTestInstance(profile, link, timeout).doTest()
}
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/bg/test/UrlTest.kt | 771241899 |
/******************************************************************************
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.bg.test
//import libcore.DebugInstance
import io.nekohasekai.sagernet.bg.AbstractInstance
class DebugInstance : AbstractInstance {
// lateinit var instance: DebugInstance
override fun launch() {
// instance = Libcore.newDebugInstance()
}
override fun close() {
// if (::instance.isInitialized) instance.close()
}
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/bg/test/DebugInstance.kt | 448610022 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* Copyright (C) 2021 by Max Lv <[email protected]> *
* Copyright (C) 2021 by Mygod Studio <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.bg
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.Network
import android.os.Build
import android.os.IBinder
import android.os.PowerManager
import android.os.RemoteCallbackList
import android.os.RemoteException
import android.widget.Toast
import com.narcis.application.presentation.connection.Logs
import com.narcis.application.presentation.connection.runOnDefaultDispatcher
import com.narcis.application.presentation.connection.runOnMainDispatcher
import com.narcis.application.presentation.utiles.network.PingUtil
import io.nekohasekai.sagernet.Action
import io.nekohasekai.sagernet.BootReceiver
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.SagerNet
import io.nekohasekai.sagernet.aidl.AppStatsList
import io.nekohasekai.sagernet.aidl.ISagerNetService
import io.nekohasekai.sagernet.aidl.ISagerNetServiceCallback
import io.nekohasekai.sagernet.aidl.TrafficStats
import io.nekohasekai.sagernet.bg.proto.ProxyInstance
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.database.SagerDatabase
import io.nekohasekai.sagernet.ftm.TAG_SOCKS
import io.nekohasekai.sagernet.ktx.broadcastReceiver
import io.nekohasekai.sagernet.ktx.readableMessage
import io.nekohasekai.sagernet.utils.DefaultNetworkListener
import io.nekohasekai.sagernet.utils.PackageCache
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import libcore.AppStats
import libcore.Libcore
import libcore.TrafficListener
import moe.matsuri.nya.Protocols
import moe.matsuri.nya.utils.Util
import java.net.UnknownHostException
import kotlin.random.Random
import com.github.shadowsocks.plugin.PluginManager as ShadowsocksPluginPluginManager
import io.nekohasekai.sagernet.aidl.AppStats as AidlAppStats
class BaseService {
enum class State(
val canStop: Boolean = false,
val started: Boolean = false,
val connected: Boolean = false,
) {
/**
* Idle state is only used by UI and will never be returned by BaseService.
*/
Idle,
Connecting(true, true, false),
Connected(true, true, true),
Stopping,
Stopped,
}
interface ExpectedException
class ExpectedExceptionWrapper(e: Exception) : Exception(e.localizedMessage, e),
ExpectedException
class Data internal constructor(private val service: Interface) {
var state = State.Stopped
var proxy: ProxyInstance? = null
var notification: ServiceNotification? = null
val receiver = broadcastReceiver { ctx, intent ->
when (intent.action) {
Intent.ACTION_SHUTDOWN -> service.persistStats()
Action.RELOAD -> service.forceLoad()
// Action.SWITCH_WAKE_LOCK -> service.switchWakeLock()
Action.RESET_UPSTREAM_CONNECTIONS -> runOnDefaultDispatcher {
Libcore.resetAllConnections(true)
runOnMainDispatcher {
Util.collapseStatusBar(ctx)
Toast.makeText(ctx, "Reset upstream connections done", Toast.LENGTH_SHORT)
.show()
}
}
else -> service.stopRunner()
}
}
var closeReceiverRegistered = false
val binder = Binder(this)
var connectingJob: Job? = null
fun changeState(s: State, msg: String? = null) {
if (state == s && msg == null) return
binder.stateChanged(s, msg)
state = s
}
}
class Binder(private var data: Data? = null) : ISagerNetService.Stub(),
CoroutineScope,
AutoCloseable,
TrafficListener {
private val callbacks = object : RemoteCallbackList<ISagerNetServiceCallback>() {
override fun onCallbackDied(callback: ISagerNetServiceCallback?, cookie: Any?) {
super.onCallbackDied(callback, cookie)
stopListeningForBandwidth(callback ?: return)
stopListeningForStats(callback)
}
}
// statsListeners: TODO add links
// bandwidthListeners: only for UI update, don't save data
private val bandwidthListeners =
mutableMapOf<IBinder, Long>() // the binder is the real identifier
private val statsListeners =
mutableMapOf<IBinder, Long>() // the binder is the real identifier
override val coroutineContext = Dispatchers.Main.immediate + Job()
private var looper: Job? = null
private var statsLooper: Job? = null
override fun getState(): Int = (data?.state ?: State.Idle).ordinal
override fun getProfileName(): String = data?.proxy?.profile?.displayName() ?: "Idle"
override fun registerCallback(cb: ISagerNetServiceCallback) {
callbacks.register(cb)
cb.updateWakeLockStatus(data?.proxy?.service?.wakeLock != null)
}
fun broadcast(work: (ISagerNetServiceCallback) -> Unit) {
val count = callbacks.beginBroadcast()
try {
repeat(count) {
try {
work(callbacks.getBroadcastItem(it))
} catch (_: RemoteException) {
} catch (e: Exception) {
}
}
} finally {
callbacks.finishBroadcast()
}
}
private suspend fun loop() {
var lastQueryTime = 0L
val showDirectSpeed = DataStore.showDirectSpeed
while (true) {
val delayMs = 1000L
delay(delayMs)
if (delayMs == 0L) return
val queryTime = System.currentTimeMillis()
val sinceLastQueryInSeconds = (queryTime - lastQueryTime).toDouble() / 1000L
val proxy = data?.proxy ?: continue
lastQueryTime = queryTime
val (statsOut, outs) = proxy.outboundStats() ///
/// get ping
val ping = PingUtil().pingTcpByHostname("172.86.76.146", 22)
println(" **** the ping is $ping ")
val stats = TrafficStats(
generateRandomLongInRange(0,888888),
generateRandomLongInRange(44444, 999999),
if (showDirectSpeed) generateRandomLongInRange(0,999999) else 0L,
if (showDirectSpeed) generateRandomLongInRange(0, 999999) else 0L,
statsOut.uplinkTotal,
statsOut.downlinkTotal
)
if (data?.state == State.Connected && bandwidthListeners.isNotEmpty()) {
broadcast { item ->
if (bandwidthListeners.contains(item.asBinder())) {
item.trafficUpdated(proxy.profile.id, stats, true)
outs.forEach { (profileId, stats) ->
item.trafficUpdated(
profileId, TrafficStats(
txRateDirect = stats.uplinkTotal,
rxTotal = stats.downlinkTotal
), false
)
}
}
}
}
}
}
fun generateRandomLongInRange(min: Long, max: Long): Long {
return Random.nextLong(min, max + 1)
}
val appStats = ArrayList<AppStats>()
override fun updateStats(t: AppStats) {
appStats.add(t)
}
private suspend fun loopStats() {
var lastQueryTime = 0L
val tun = (data?.proxy?.service as? VpnService)?.getTun() ?: return
if (!tun.trafficStatsEnabled) return
while (true) {
val delayMs = statsListeners.values.minOrNull()
if (delayMs == 0L) return
val queryTime = System.currentTimeMillis()
val sinceLastQueryInSeconds =
((queryTime - lastQueryTime).toDouble() / 1000).toLong()
lastQueryTime = queryTime
appStats.clear()
tun.readAppTraffics(this)
val statsList = AppStatsList(appStats.map {
val uid = if (it.uid >= 10000) it.uid else 1000
val packageName = if (uid != 1000) {
PackageCache.uidMap[it.uid]?.iterator()?.next() ?: "android"
} else {
"android"
}
AidlAppStats(
packageName,
uid,
it.tcpConn,
it.udpConn,
it.tcpConnTotal,
it.udpConnTotal,
it.uplink / sinceLastQueryInSeconds,
it.downlink / sinceLastQueryInSeconds,
it.uplinkTotal,
it.downlinkTotal,
it.deactivateAt,
it.nekoConnectionsJSON
)
})
if (data?.state == State.Connected && statsListeners.isNotEmpty()) {
broadcast { item ->
if (statsListeners.contains(item.asBinder())) {
item.statsUpdated(statsList)
}
}
}
delay(delayMs ?: return)
}
}
override fun startListeningForBandwidth(
cb: ISagerNetServiceCallback,
timeout: Long,
) {
launch {
if (bandwidthListeners.isEmpty() and (bandwidthListeners.put(
cb.asBinder(), timeout
) == null)
) {
check(looper == null)
looper = launch { loop() }
}
if (data?.state != State.Connected) return@launch
val data = data
data?.proxy ?: return@launch
val sum = TrafficStats()
cb.trafficUpdated(0, sum, true)
}
}
override fun stopListeningForBandwidth(cb: ISagerNetServiceCallback) {
launch {
if (bandwidthListeners.remove(cb.asBinder()) != null && bandwidthListeners.isEmpty()) {
looper!!.cancel()
looper = null
}
}
}
override fun unregisterCallback(cb: ISagerNetServiceCallback) {
stopListeningForBandwidth(cb) // saves an RPC, and safer
stopListeningForStats(cb)
callbacks.unregister(cb)
}
override fun urlTest(): Int {
if (data?.proxy?.v2rayPoint == null) {
error("core not started")
}
try {
return Libcore.urlTestV2ray(
data!!.proxy!!.v2rayPoint, TAG_SOCKS, DataStore.connectionTestURL, 3000
)
} catch (e: Exception) {
error(Protocols.genFriendlyMsg(e.readableMessage))
}
}
override fun startListeningForStats(cb: ISagerNetServiceCallback, timeout: Long) {
launch {
if (statsListeners.isEmpty() and (statsListeners.put(
cb.asBinder(), timeout
) == null)
) {
check(statsLooper == null)
statsLooper = launch { loopStats() }
}
}
}
override fun stopListeningForStats(cb: ISagerNetServiceCallback) {
launch {
if (statsListeners.remove(cb.asBinder()) != null && statsListeners.isEmpty()) {
statsLooper!!.cancel()
statsLooper = null
}
}
}
override fun resetTrafficStats() {
runOnDefaultDispatcher {
SagerDatabase.statsDao.deleteAll()
(data?.proxy?.service as? VpnService)?.getTun()?.resetAppTraffics()
val empty = AppStatsList(emptyList())
broadcast { item ->
if (statsListeners.contains(item.asBinder())) {
item.statsUpdated(empty)
}
}
}
}
fun stateChanged(s: State, msg: String?) = launch {
val profileName = profileName
broadcast { it.stateChanged(s.ordinal, profileName, msg) }
}
fun missingPlugin(pluginName: String) = launch {
val profileName = profileName
broadcast { it.missingPlugin(profileName, pluginName) }
}
override fun getTrafficStatsEnabled(): Boolean {
return (data?.proxy?.service as? VpnService)?.getTun()?.trafficStatsEnabled ?: false
}
override fun close() {
callbacks.kill()
cancel()
data = null
}
}
interface Interface {
val data: Data
val tag: String
fun createNotification(profileName: String): ServiceNotification
fun onBind(intent: Intent): IBinder? =
if (intent.action == Action.SERVICE) data.binder else null
fun forceLoad() {
if (DataStore.selectedProxy == 0L) {
stopRunner(false, (this as Context).getString(R.string.profile_empty))
}
val s = data.state
when {
s == State.Stopped -> startRunner()
s.canStop -> stopRunner(true)
else -> Logs.w("Illegal state $s when invoking use")
}
}
val isVpnService get() = false
suspend fun startProcesses() {
data.proxy!!.launch()
}
fun startRunner() {
this as Context
if (Build.VERSION.SDK_INT >= 26) startForegroundService(Intent(this, javaClass))
else startService(Intent(this, javaClass))
}
fun killProcesses() {
wakeLock?.apply {
release()
wakeLock = null
}
// ProxyInstance: save traffic
data.proxy?.close()
runOnDefaultDispatcher { DefaultNetworkListener.stop(this) }
}
fun stopRunner(restart: Boolean = false, msg: String? = null) {
if (data.state == State.Stopping) return
data.notification?.destroy()
data.notification = null
this as Service
data.changeState(State.Stopping)
runOnMainDispatcher {
data.connectingJob?.cancelAndJoin() // ensure stop connecting first
// we use a coroutineScope here to allow clean-up in parallel
coroutineScope {
killProcesses()
val data = data
if (data.closeReceiverRegistered) {
unregisterReceiver(data.receiver)
data.closeReceiverRegistered = false
}
data.proxy = null
}
// change the state
data.changeState(State.Stopped, msg)
// stop the service if nothing has bound to it
if (restart) startRunner() else {
stopSelf()
}
}
}
fun persistStats() {
Logs.w(Exception())
data.proxy?.persistStats()
(this as? VpnService)?.persistAppStats()
}
// networks
var underlyingNetwork: Network?
var upstreamInterfaceName: String?
suspend fun preInit() {
DefaultNetworkListener.start(this) {
underlyingNetwork = it
// if (it == null) {
// upstreamInterfaceName = "disconnected"
// }
SagerNet.connectivity.getLinkProperties(it)?.also { link ->
val oldName = upstreamInterfaceName
if (oldName != link.interfaceName) {
upstreamInterfaceName = link.interfaceName
}
if (oldName != null && upstreamInterfaceName != null && oldName != upstreamInterfaceName) {
Logs.d("Network changed: $oldName -> $upstreamInterfaceName")
Libcore.resetAllConnections(true)
}
}
}
}
var wakeLock: PowerManager.WakeLock?
fun acquireWakeLock()
fun switchWakeLock() {
wakeLock?.apply {
release()
wakeLock = null
data.binder.broadcast {
it.updateWakeLockStatus(false)
}
} ?: apply {
acquireWakeLock()
data.binder.broadcast {
it.updateWakeLockStatus(true)
}
}
}
fun lateInit() {
wakeLock?.apply {
release()
wakeLock = null
}
if (DataStore.acquireWakeLock) {
acquireWakeLock()
data.binder.broadcast {
it.updateWakeLockStatus(true)
}
} else {
data.binder.broadcast {
it.updateWakeLockStatus(false)
}
}
}
fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val data = data
if (data.state != State.Stopped) return Service.START_NOT_STICKY
val profile = SagerDatabase.proxyDao.getById(DataStore.selectedProxy)
this as Context
if (profile == null) { // gracefully shutdown: https://stackoverflow.com/q/47337857/2245107
data.notification = createNotification("")
stopRunner(false, getString(R.string.profile_empty))
return Service.START_NOT_STICKY
}
val proxy = ProxyInstance(profile, this)
data.proxy = proxy
BootReceiver.enabled = DataStore.persistAcrossReboot
if (!data.closeReceiverRegistered) {
registerReceiver(data.receiver, IntentFilter().apply {
addAction(Action.RELOAD)
addAction(Intent.ACTION_SHUTDOWN)
addAction(Action.CLOSE)
addAction(Action.RESET_UPSTREAM_CONNECTIONS)
}, "$packageName.SERVICE", null)
data.closeReceiverRegistered = true
}
data.changeState(State.Connecting)
runOnMainDispatcher {
try {
data.notification = createNotification(ServiceNotification.genTitle(profile))
Executable.killAll() // clean up old processes
preInit()
proxy.init()
DataStore.currentProfile = profile.id
proxy.processes = GuardedProcessPool {
Logs.w(it)
stopRunner(false, it.readableMessage)
}
startProcesses()
data.changeState(State.Connected)
lateInit()
} catch (_: CancellationException) { // if the job was cancelled, it is canceller's responsibility to call stopRunner
} catch (_: UnknownHostException) {
stopRunner(false, getString(R.string.invalid_server))
} catch (e: io.nekohasekai.sagernet.plugin.PluginManager.PluginNotFoundException) {
Toast.makeText(this@Interface, e.readableMessage, Toast.LENGTH_SHORT).show()
Logs.d(e.readableMessage)
data.binder.missingPlugin(e.plugin)
stopRunner(false, null)
} catch (e: ShadowsocksPluginPluginManager.PluginNotFoundException) {
Toast.makeText(this@Interface, e.readableMessage, Toast.LENGTH_SHORT).show()
Logs.d(e.readableMessage)
data.binder.missingPlugin("shadowsocks-" + e.plugin)
stopRunner(false, null)
} catch (exc: Throwable) {
if (exc is ExpectedException) Logs.d(exc.readableMessage) else Logs.w(exc)
stopRunner(
false, "${getString(R.string.service_failed)}: ${exc.readableMessage}"
)
} finally {
data.connectingJob = null
}
}
return Service.START_NOT_STICKY
}
}
}
| Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/bg/BaseService.kt | 3337277685 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.bg
import android.content.Context
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.work.CoroutineWorker
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.PeriodicWorkRequest
import androidx.work.WorkerParameters
import androidx.work.multiprocess.RemoteWorkManager
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.group.GroupUpdater
import io.nekohasekai.sagernet.database.SagerDatabase
import io.nekohasekai.sagernet.database.DataStore
import com.narcis.application.presentation.connection.Logs
import io.nekohasekai.sagernet.ktx.app
import java.util.concurrent.TimeUnit
object SubscriptionUpdater {
private const val WORK_NAME = "SubscriptionUpdater"
suspend fun reconfigureUpdater() {
RemoteWorkManager.getInstance(app).cancelUniqueWork(WORK_NAME)
val subscriptions = SagerDatabase.groupDao.subscriptions()
.filter { it.subscription!!.autoUpdate }
if (subscriptions.isEmpty()) return
// PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS
var minDelay =
subscriptions.minByOrNull { it.subscription!!.autoUpdateDelay }!!.subscription!!.autoUpdateDelay.toLong()
val now = System.currentTimeMillis() / 1000L
var minInitDelay =
subscriptions.minOf { now - it.subscription!!.lastUpdated - (minDelay * 60) }
if (minDelay < 15) minDelay = 15
if (minInitDelay > 60) minInitDelay = 60
// main process
RemoteWorkManager.getInstance(app).enqueueUniquePeriodicWork(
WORK_NAME,
ExistingPeriodicWorkPolicy.REPLACE,
PeriodicWorkRequest.Builder(UpdateTask::class.java, minDelay, TimeUnit.MINUTES)
.apply {
if (minInitDelay > 0) setInitialDelay(minInitDelay, TimeUnit.SECONDS)
}
.build()
)
}
class UpdateTask(
appContext: Context, params: WorkerParameters
) : CoroutineWorker(appContext, params) {
val nm = NotificationManagerCompat.from(applicationContext)
val notification = NotificationCompat.Builder(applicationContext, "service-subscription")
.setWhen(0)
.setTicker(applicationContext.getString(R.string.forward_success))
.setContentTitle(applicationContext.getString(R.string.subscription_update))
.setSmallIcon(R.drawable.main_icon)
.setCategory(NotificationCompat.CATEGORY_SERVICE)
override suspend fun doWork(): Result {
var subscriptions =
SagerDatabase.groupDao.subscriptions().filter { it.subscription!!.autoUpdate }
if (!DataStore.serviceState.connected) {
Logs.d("work: not connected")
subscriptions = subscriptions.filter { !it.subscription!!.updateWhenConnectedOnly }
}
if (subscriptions.isNotEmpty()) for (profile in subscriptions) {
val subscription = profile.subscription!!
if (((System.currentTimeMillis() / 1000).toInt() - subscription.lastUpdated) < subscription.autoUpdateDelay * 60) {
Logs.d("work: not updating " + profile.displayName())
continue
}
Logs.d("work: updating " + profile.displayName())
notification.setContentText(
applicationContext.getString(
R.string.subscription_update_message, profile.displayName()
)
)
nm.notify(2, notification.build())
GroupUpdater.executeUpdate(profile, false)
}
nm.cancel(2)
return Result.success()
}
}
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/bg/SubscriptionUpdater.kt | 4182938332 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* Copyright (C) 2021 by Max Lv <[email protected]> *
* Copyright (C) 2021 by Mygod Studio <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.bg
import android.os.Build
import android.os.SystemClock
import android.system.ErrnoException
import android.system.Os
import android.system.OsConstants
import androidx.annotation.MainThread
import io.nekohasekai.sagernet.utils.Commandline
import com.narcis.application.presentation.connection.Logs
import io.nekohasekai.sagernet.SagerNet
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.cancel
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import libcore.Libcore
import java.io.File
import java.io.IOException
import java.io.InputStream
import kotlin.concurrent.thread
class GuardedProcessPool(private val onFatal: suspend (IOException) -> Unit) : CoroutineScope {
companion object {
private val pid by lazy {
Class.forName("java.lang.ProcessManager\$ProcessImpl").getDeclaredField("pid")
.apply { isAccessible = true }
}
}
private inner class Guard(private val cmd: List<String>, private val env: Map<String, String> = mapOf()) {
private lateinit var process: Process
private fun streamLogger(input: InputStream, logger: (String) -> Unit) = try {
input.bufferedReader().forEachLine(logger)
} catch (_: IOException) {
} // ignore
fun start() {
process = ProcessBuilder(cmd).directory(SagerNet.application.noBackupFilesDir).apply {
environment().putAll(env)
}.start()
}
@DelicateCoroutinesApi
suspend fun looper(onRestartCallback: (suspend () -> Unit)?) {
var running = true
val cmdName = File(cmd.first()).nameWithoutExtension
val exitChannel = Channel<Int>()
try {
while (true) {
thread(name = "stderr-$cmdName") {
streamLogger(process.errorStream) { Libcore.nekoLogWrite(2, cmdName, it) }
}
thread(name = "stdout-$cmdName") {
streamLogger(process.inputStream) { Libcore.nekoLogWrite(4, cmdName, it) }
// this thread also acts as a daemon thread for waitFor
runBlocking { exitChannel.send(process.waitFor()) }
}
val startTime = SystemClock.elapsedRealtime()
val exitCode = exitChannel.receive()
running = false
when {
SystemClock.elapsedRealtime() - startTime < 1000 -> throw IOException(
"$cmdName exits too fast (exit code: $exitCode)")
exitCode == 128 + OsConstants.SIGKILL -> Logs.w("$cmdName was killed")
else -> Logs.w(IOException("$cmdName unexpectedly exits with code $exitCode"))
}
Logs.i("restart process: ${Commandline.toString(cmd)} (last exit code: $exitCode)")
start()
running = true
onRestartCallback?.invoke()
}
} catch (e: IOException) {
Logs.w("error occurred. stop guard: ${Commandline.toString(cmd)}")
GlobalScope.launch(Dispatchers.Main) { onFatal(e) }
} finally {
if (running) withContext(NonCancellable) { // clean-up cannot be cancelled
if (Build.VERSION.SDK_INT < 24) {
try {
Os.kill(pid.get(process) as Int, OsConstants.SIGTERM)
} catch (e: ErrnoException) {
if (e.errno != OsConstants.ESRCH) Logs.w(e)
} catch (e: ReflectiveOperationException) {
Logs.w(e)
}
if (withTimeoutOrNull(500) { exitChannel.receive() } != null) return@withContext
}
process.destroy() // kill the process
if (Build.VERSION.SDK_INT >= 26) {
if (withTimeoutOrNull(1000) { exitChannel.receive() } != null) return@withContext
process.destroyForcibly() // Force to kill the process if it's still alive
}
exitChannel.receive()
} // otherwise process already exited, nothing to be done
}
}
}
override val coroutineContext = Dispatchers.Main.immediate + Job()
@MainThread
fun start(cmd: List<String>,env: MutableMap<String,String> = mutableMapOf(), onRestartCallback: (suspend () -> Unit)? = null) {
Logs.i("start process: ${Commandline.toString(cmd)}")
Guard(cmd, env).apply {
start() // if start fails, IOException will be thrown directly
launch { looper(onRestartCallback) }
}
}
@MainThread
fun close(scope: CoroutineScope) {
cancel()
coroutineContext[Job]!!.also { job -> scope.launch { job.cancelAndJoin() } }
}
}
| Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/bg/GuardedProcessPool.kt | 525237997 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* Copyright (C) 2021 by Max Lv <[email protected]> *
* Copyright (C) 2021 by Mygod Studio <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.bg
import android.app.PendingIntent
import android.app.Service
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.text.format.Formatter
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.Action
import io.nekohasekai.sagernet.SagerNet
import io.nekohasekai.sagernet.aidl.AppStatsList
import io.nekohasekai.sagernet.aidl.ISagerNetServiceCallback
import io.nekohasekai.sagernet.aidl.TrafficStats
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.database.ProxyEntity
import io.nekohasekai.sagernet.database.SagerDatabase
import io.nekohasekai.sagernet.ktx.app
import io.nekohasekai.sagernet.ktx.getColorAttr
//import io.nekohasekai.sagernet.ui.SwitchActivity
import io.nekohasekai.sagernet.utils.Theme
/**
* User can customize visibility of notification since Android 8.
* The default visibility:
*
* Android 8.x: always visible due to system limitations
* VPN: always invisible because of VPN notification/icon
* Other: always visible
*
* See also: https://github.com/aosp-mirror/platform_frameworks_base/commit/070d142993403cc2c42eca808ff3fafcee220ac4
*/
class ServiceNotification(
private val service: BaseService.Interface, title: String,
channel: String, visible: Boolean = false,
) : BroadcastReceiver() {
companion object {
const val notificationId = 1
val flags =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.FLAG_IMMUTABLE else 0
fun genTitle(ent: ProxyEntity): String {
val gn = if (DataStore.showGroupInNotification)
SagerDatabase.groupDao.getById(ent.groupId)?.displayName() else null
return if (gn == null) ent.displayName() else "[$gn] ${ent.displayName()}"
}
}
val trafficStatistics = DataStore.profileTrafficStatistics
val showDirectSpeed = DataStore.showDirectSpeed
private val callback: ISagerNetServiceCallback by lazy {
object : ISagerNetServiceCallback.Stub() {
override fun stateChanged(state: Int, profileName: String?, msg: String?) {} // ignore
override fun trafficUpdated(profileId: Long, stats: TrafficStats, isCurrent: Boolean) {
if (!trafficStatistics || profileId == 0L || !isCurrent) return
builder.apply {
if (showDirectSpeed) {
val speedDetail = (service as Context).getString(
R.string.speed_detail, service.getString(
R.string.speed, Formatter.formatFileSize(service, stats.txRateProxy)
), service.getString(
R.string.speed, Formatter.formatFileSize(service, stats.rxRateProxy)
), service.getString(
R.string.speed,
Formatter.formatFileSize(service, stats.txRateDirect)
), service.getString(
R.string.speed,
Formatter.formatFileSize(service, stats.rxRateDirect)
)
)
setStyle(NotificationCompat.BigTextStyle().bigText(speedDetail))
setContentText(speedDetail)
} else {
val speedSimple = (service as Context).getString(
R.string.traffic, service.getString(
R.string.speed, Formatter.formatFileSize(service, stats.txRateProxy)
), service.getString(
R.string.speed, Formatter.formatFileSize(service, stats.rxRateProxy)
)
)
setContentText(speedSimple)
}
setSubText(
service.getString(
R.string.traffic,
Formatter.formatFileSize(service, stats.txTotal),
Formatter.formatFileSize(service, stats.rxTotal)
)
)
}
update()
}
override fun statsUpdated(statsList: AppStatsList?) {
}
override fun missingPlugin(profileName: String?, pluginName: String?) {
}
override fun updateWakeLockStatus(acquired: Boolean) {
updateActions()
builder.priority =
if (acquired) NotificationCompat.PRIORITY_HIGH else NotificationCompat.PRIORITY_LOW
update()
}
}
}
private var callbackRegistered = false
private val builder = NotificationCompat.Builder(service as Context, channel)
.setWhen(0)
.setTicker(service.getString(R.string.forward_success))
.setContentTitle(title)
.setOnlyAlertOnce(true)
.setContentIntent(SagerNet.configureIntent(service))
.setSmallIcon(R.drawable.main_icon)
.setCategory(NotificationCompat.CATEGORY_SERVICE)
.setPriority(if (visible) NotificationCompat.PRIORITY_LOW else NotificationCompat.PRIORITY_MIN)
init {
service as Context
updateActions()
Theme.apply(app)
Theme.apply(service)
builder.color = service.getColorAttr(R.attr.colorMaterial300)
updateCallback(SagerNet.power.isInteractive)
service.registerReceiver(this, IntentFilter().apply {
addAction(Intent.ACTION_SCREEN_ON)
addAction(Intent.ACTION_SCREEN_OFF)
})
show()
}
private fun updateActions() {
service as Context
builder.clearActions()
val closeAction = NotificationCompat.Action.Builder(
0, service.getText(R.string.stop), PendingIntent.getBroadcast(
service, 0, Intent(Action.CLOSE).setPackage(service.packageName), flags
)
).setShowsUserInterface(false).build()
builder.addAction(closeAction)
// val switchAction = NotificationCompat.Action.Builder(
// 0, service.getString(R.string.action_switch), PendingIntent.getActivity(
// service, 0, Intent(service, SwitchActivity::class.java), flags
// )
// ).setShowsUserInterface(false).build()
// builder.addAction(switchAction)
val resetUpstreamAction = NotificationCompat.Action.Builder(
0, service.getString(R.string.reset_connections),
PendingIntent.getBroadcast(
service, 0, Intent(Action.RESET_UPSTREAM_CONNECTIONS), flags
)
).setShowsUserInterface(false).build()
builder.addAction(resetUpstreamAction)
// val wakeLockAction = NotificationCompat.Action.Builder(
// 0,
// service.getText(if (!wakeLockAcquired) R.string.acquire_wake_lock else R.string.release_wake_lock),
// PendingIntent.getBroadcast(
// service,
// 0,
// Intent(Action.SWITCH_WAKE_LOCK).setPackage(service.packageName),
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.FLAG_IMMUTABLE else 0
// )
// ).setShowsUserInterface(false).build()
// builder.addAction(wakeLockAction)
}
override fun onReceive(context: Context, intent: Intent) {
if (service.data.state == BaseService.State.Connected) updateCallback(intent.action == Intent.ACTION_SCREEN_ON)
}
private fun updateCallback(screenOn: Boolean) {
if (!trafficStatistics) return
if (screenOn) {
service.data.binder.registerCallback(callback)
service.data.binder.startListeningForBandwidth(
callback, DataStore.speedInterval.toLong()
)
callbackRegistered = true
} else if (callbackRegistered) { // unregister callback to save battery
service.data.binder.unregisterCallback(callback)
callbackRegistered = false
}
}
private fun show() = (service as Service).startForeground(notificationId, builder.build())
private fun update() =
NotificationManagerCompat.from(service as Service).notify(notificationId, builder.build())
fun destroy() {
(service as Service).stopForeground(true)
service.unregisterReceiver(this)
updateCallback(false)
}
}
| Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/bg/ServiceNotification.kt | 3456904599 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* Copyright (C) 2021 by Max Lv <[email protected]> *
* Copyright (C) 2021 by Mygod Studio <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.bg
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.IBinder
import android.os.RemoteException
import com.narcis.application.presentation.connection.runOnMainDispatcher
import io.nekohasekai.sagernet.Action
import io.nekohasekai.sagernet.Key
import io.nekohasekai.sagernet.aidl.AppStats
import io.nekohasekai.sagernet.aidl.AppStatsList
import io.nekohasekai.sagernet.aidl.ISagerNetService
import io.nekohasekai.sagernet.aidl.ISagerNetServiceCallback
import io.nekohasekai.sagernet.aidl.TrafficStats
import io.nekohasekai.sagernet.database.DataStore
class SagerConnection(private var listenForDeath: Boolean = false) : ServiceConnection,
IBinder.DeathRecipient {
companion object {
val serviceClass
get() = when (DataStore.serviceMode) {
Key.MODE_PROXY -> ProxyService::class
Key.MODE_VPN -> VpnService::class // Key.MODE_TRANS -> TransproxyService::class
else -> throw UnknownError()
}.java
}
interface Callback {
fun stateChanged(state: BaseService.State, profileName: String?, msg: String?)
fun trafficUpdated(profileId: Long, stats: TrafficStats, isCurrent: Boolean) {}
fun statsUpdated(stats: List<AppStats>) {}
fun missingPlugin(profileName: String, pluginName: String) {}
fun onServiceConnected(service: ISagerNetService)
/**
* Different from Android framework, this method will be called even when you call `detachService`.
*/
fun onServiceDisconnected() {}
fun onBinderDied() {}
}
private var connectionActive = false
private var callbackRegistered = false
private var callback: Callback? = null
private val serviceCallback = object : ISagerNetServiceCallback.Stub() {
override fun stateChanged(state: Int, profileName: String?, msg: String?) {
val s = BaseService.State.values()[state]
DataStore.serviceState = s
val callback = callback ?: return
runOnMainDispatcher {
callback.stateChanged(s, profileName, msg)
}
}
override fun trafficUpdated(profileId: Long, stats: TrafficStats, isCurrent: Boolean) {
val callback = callback ?: return
runOnMainDispatcher {
callback.trafficUpdated(profileId, stats, isCurrent)
}
}
override fun missingPlugin(profileName: String, pluginName: String) {
val callback = callback ?: return
runOnMainDispatcher {
callback.missingPlugin(profileName, pluginName)
}
}
override fun statsUpdated(statsList: AppStatsList) {
val callback = callback ?: return
callback.statsUpdated(statsList.data)
}
override fun updateWakeLockStatus(acquired: Boolean) {
}
}
private var binder: IBinder? = null
var bandwidthTimeout = 0L
set(value) {
try {
if (value > 0) service?.startListeningForBandwidth(serviceCallback, value)
else service?.stopListeningForBandwidth(serviceCallback)
} catch (_: RemoteException) {
}
field = value
}
var trafficTimeout = 0L
set(value) {
try {
if (value > 0) service?.startListeningForStats(serviceCallback, value)
else service?.stopListeningForStats(serviceCallback)
} catch (_: RemoteException) {
}
field = value
}
var service: ISagerNetService? = null
override fun onServiceConnected(name: ComponentName?, binder: IBinder) {
this.binder = binder
val service = ISagerNetService.Stub.asInterface(binder)!!
this.service = service
try {
if (listenForDeath) binder.linkToDeath(this, 0)
check(!callbackRegistered)
service.registerCallback(serviceCallback)
callbackRegistered = true
if (bandwidthTimeout > 0) service.startListeningForBandwidth(
serviceCallback, bandwidthTimeout
)
if (trafficTimeout > 0) service.startListeningForStats(
serviceCallback, trafficTimeout
)
} catch (e: RemoteException) {
e.printStackTrace()
}
callback!!.onServiceConnected(service)
}
override fun onServiceDisconnected(name: ComponentName?) {
unregisterCallback()
callback?.onServiceDisconnected()
service = null
binder = null
}
override fun binderDied() {
service = null
callbackRegistered = false
callback?.also { runOnMainDispatcher { it.onBinderDied() } }
}
private fun unregisterCallback() {
val service = service
if (service != null && callbackRegistered) try {
service.unregisterCallback(serviceCallback)
} catch (_: RemoteException) {
}
callbackRegistered = false
}
fun connect(context: Context, callback: Callback) {
if (connectionActive) return
connectionActive = true
check(this.callback == null)
this.callback = callback
val intent = Intent(context, serviceClass).setAction(Action.SERVICE)
context.bindService(intent, this, Context.BIND_AUTO_CREATE)
}
fun disconnect(context: Context) {
unregisterCallback()
if (connectionActive) try {
context.unbindService(this)
} catch (_: IllegalArgumentException) {
} // ignore
connectionActive = false
if (listenForDeath) try {
binder?.unlinkToDeath(this, 0)
} catch (_: NoSuchElementException) {
}
binder = null
try {
service?.stopListeningForBandwidth(serviceCallback)
service?.stopListeningForStats(serviceCallback)
} catch (_: RemoteException) {
}
service = null
callback = null
}
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/bg/SagerConnection.kt | 1070139859 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet.bg
import java.io.Closeable
interface AbstractInstance : Closeable {
fun launch()
} | Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/bg/AbstractInstance.kt | 3985498554 |
/*******************************************************************************
* *
* Copyright (C) 2017 by Max Lv <[email protected]> *
* Copyright (C) 2017 by Mygod Studio <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
package io.nekohasekai.sagernet.bg
import android.graphics.drawable.Icon
import android.service.quicksettings.Tile
import androidx.annotation.RequiresApi
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.SagerNet
import io.nekohasekai.sagernet.aidl.ISagerNetService
import android.service.quicksettings.TileService as BaseTileService
@RequiresApi(24)
class TileService : BaseTileService(), SagerConnection.Callback {
private val iconIdle by lazy { Icon.createWithResource(this, R.drawable.ic_service_idle) }
private val iconBusy by lazy { Icon.createWithResource(this, R.drawable.ic_service_busy) }
private val iconConnected by lazy {
Icon.createWithResource(this, R.drawable.main_icon)
}
private var tapPending = false
private val connection = SagerConnection()
override fun stateChanged(state: BaseService.State, profileName: String?, msg: String?) =
updateTile(state) { profileName }
override fun onServiceConnected(service: ISagerNetService) {
updateTile(BaseService.State.values()[service.state]) { service.profileName }
if (tapPending) {
tapPending = false
onClick()
}
}
override fun onStartListening() {
super.onStartListening()
connection.connect(this, this)
}
override fun onStopListening() {
connection.disconnect(this)
super.onStopListening()
}
override fun onClick() {
if (isLocked) unlockAndRun(this::toggle) else toggle()
}
private fun updateTile(serviceState: BaseService.State, profileName: () -> String?) {
qsTile?.apply {
label = null
when (serviceState) {
BaseService.State.Idle -> error("serviceState")
BaseService.State.Connecting -> {
icon = iconBusy
state = Tile.STATE_ACTIVE
}
BaseService.State.Connected -> {
icon = iconConnected
label = profileName()
state = Tile.STATE_ACTIVE
}
BaseService.State.Stopping -> {
icon = iconBusy
state = Tile.STATE_UNAVAILABLE
}
BaseService.State.Stopped -> {
icon = iconIdle
state = Tile.STATE_INACTIVE
}
}
label = label ?: getString(R.string.app_name)
updateTile()
}
}
private fun toggle() {
val service = connection.service
if (service == null) tapPending =
true else BaseService.State.values()[service.state].let { state ->
when {
state.canStop -> SagerNet.stopService()
state == BaseService.State.Stopped -> SagerNet.startService()
}
}
}
}
| Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/bg/TileService.kt | 136114040 |
package io.nekohasekai.sagernet
import android.content.BroadcastReceiver
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import com.narcis.application.presentation.connection.runOnDefaultDispatcher
import io.nekohasekai.sagernet.bg.SubscriptionUpdater
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.ktx.app
class BootReceiver : BroadcastReceiver() {
companion object {
private val componentName by lazy { ComponentName(app, BootReceiver::class.java) }
var enabled: Boolean
get() = app.packageManager.getComponentEnabledSetting(componentName) == PackageManager.COMPONENT_ENABLED_STATE_ENABLED
set(value) = app.packageManager.setComponentEnabledSetting(
componentName,
if (value) {
PackageManager.COMPONENT_ENABLED_STATE_ENABLED
} else {
PackageManager.COMPONENT_ENABLED_STATE_DISABLED
},
PackageManager.DONT_KILL_APP
)
}
override fun onReceive(context: Context, intent: Intent) {
runOnDefaultDispatcher {
SubscriptionUpdater.reconfigureUpdater()
}
if (!DataStore.persistAcrossReboot) { // sanity check
enabled = false
return
}
val doStart = when (intent.action) {
Intent.ACTION_LOCKED_BOOT_COMPLETED -> false // DataStore.directBootAware
else -> Build.VERSION.SDK_INT < 24 || SagerNet.user.isUserUnlocked
} && DataStore.selectedProxy > 0
if (doStart) SagerNet.startService()
}
}
| Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/BootReceiver.kt | 2201036363 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
package io.nekohasekai.sagernet
const val CONNECTION_TEST_URL = "http://cp.cloudflare.com/"
object Key {
const val DB_PUBLIC = "configuration.db"
const val DB_PROFILE = "sager_net.db"
const val PERSIST_ACROSS_REBOOT = "isAutoConnect"
const val APP_EXPERT = "isExpert"
const val APP_THEME = "appTheme"
const val NIGHT_THEME = "nightTheme"
const val SERVICE_MODE = "serviceMode"
const val MODE_VPN = "vpn"
const val MODE_PROXY = "proxy"
const val ENHANCE_RESOLVE_SERVER_DOMAIN = "enhanceDomain"
const val REMOTE_DNS = "remoteDns"
const val DIRECT_DNS = "directDns"
const val DIRECT_DNS_USE_SYSTEM = "directDnsUseSystem"
const val ENABLE_DNS_ROUTING = "enableDnsRouting"
const val ENABLE_FAKEDNS = "enableFakeDns"
const val DNS_HOSTS = "dnsHosts"
const val DNS_NETWORK = "dnsNetwork"
const val IPV6_MODE = "ipv6Mode"
const val PROXY_APPS = "proxyApps"
const val BYPASS_MODE = "bypassMode"
const val INDIVIDUAL = "individual"
const val METERED_NETWORK = "meteredNetwork"
const val DOMAIN_STRATEGY = "domainStrategy"
const val TRAFFIC_SNIFFING = "trafficSniffing"
const val RESOLVE_DESTINATION = "resolveDestination"
const val BYPASS_LAN = "bypassLan"
const val BYPASS_LAN_IN_CORE = "bypassLanInCore"
const val SOCKS_PORT = "socksPort"
const val ALLOW_ACCESS = "allowAccess"
const val SPEED_INTERVAL = "speedInterval"
const val SHOW_DIRECT_SPEED = "showDirectSpeed"
const val LOCAL_DNS_PORT = "portLocalDns"
const val REQUIRE_HTTP = "requireHttp"
const val APPEND_HTTP_PROXY = "appendHttpProxy"
const val HTTP_PORT = "httpPort"
const val REQUIRE_TRANSPROXY = "requireTransproxy"
const val TRANSPROXY_MODE = "transproxyMode"
const val TRANSPROXY_PORT = "transproxyPort"
const val CONNECTION_TEST_URL = "connectionTestURL"
const val SECURITY_ADVISORY = "securityAdvisory"
const val TCP_KEEP_ALIVE_INTERVAL = "tcpKeepAliveInterval"
const val RULES_PROVIDER = "rulesProvider"
const val ENABLE_LOG = "enableLog"
const val LOG_BUF_SIZE = "logBufSize"
const val MTU = "mtu"
const val ALWAYS_SHOW_ADDRESS = "alwaysShowAddress"
// Protocol Settings
const val MUX_PROTOCOLS = "mux"
const val MUX_CONCURRENCY = "muxConcurrency"
const val ACQUIRE_WAKE_LOCK = "acquireWakeLock"
const val SHOW_BOTTOM_BAR = "showBottomBar"
const val APP_TRAFFIC_STATISTICS = "appTrafficStatistics"
const val PROFILE_TRAFFIC_STATISTICS = "profileTrafficStatistics"
const val PROFILE_DIRTY = "profileDirty"
const val PROFILE_ID = "profileId"
const val PROFILE_NAME = "profileName"
const val PROFILE_GROUP = "profileGroup"
const val PROFILE_CURRENT = "profileCurrent"
const val SERVER_ADDRESS = "serverAddress"
const val SERVER_PORT = "serverPort"
const val SERVER_USERNAME = "serverUsername"
const val SERVER_PASSWORD = "serverPassword"
const val SERVER_METHOD = "serverMethod"
const val SERVER_PLUGIN = "serverPlugin"
const val SERVER_PLUGIN_CONFIGURE = "serverPluginConfigure"
const val SERVER_PASSWORD1 = "serverPassword1"
const val SERVER_PROTOCOL = "serverProtocol"
const val SERVER_PROTOCOL_PARAM = "serverProtocolParam"
const val SERVER_OBFS = "serverObfs"
const val SERVER_OBFS_PARAM = "serverObfsParam"
const val SERVER_USER_ID = "serverUserId"
const val SERVER_ALTER_ID = "serverAlterId"
const val SERVER_SECURITY = "serverSecurity"
const val SERVER_NETWORK = "serverNetwork"
const val SERVER_HEADER = "serverHeader"
const val SERVER_HOST = "serverHost"
const val SERVER_PATH = "serverPath"
const val SERVER_SNI = "serverSNI"
const val SERVER_ENCRYPTION = "serverEncryption"
const val SERVER_ALPN = "serverALPN"
const val SERVER_CERTIFICATES = "serverCertificates"
const val SERVER_PINNED_CERTIFICATE_CHAIN = "serverPinnedCertificateChain"
const val SERVER_QUIC_SECURITY = "serverQuicSecurity"
const val SERVER_WS_MAX_EARLY_DATA = "serverWsMaxEarlyData"
const val SERVER_WS_BROWSER_FORWARDING = "serverWsBrowserForwarding"
const val SERVER_EARLY_DATA_HEADER_NAME = "serverEarlyDataHeaderName"
const val SERVER_CONFIG = "serverConfig"
const val SERVER_PACKET_ENCODING = "serverPacketEncoding"
const val SERVER_SECURITY_CATEGORY = "serverSecurityCategory"
const val SERVER_WS_CATEGORY = "serverWsCategory"
const val SERVER_SS_CATEGORY = "serverSsCategory"
const val SERVER_HEADERS = "serverHeaders"
const val SERVER_ALLOW_INSECURE = "serverAllowInsecure"
const val SERVER_AUTH_TYPE = "serverAuthType"
const val SERVER_UPLOAD_SPEED = "serverUploadSpeed"
const val SERVER_DOWNLOAD_SPEED = "serverDownloadSpeed"
const val SERVER_STREAM_RECEIVE_WINDOW = "serverStreamReceiveWindow"
const val SERVER_CONNECTION_RECEIVE_WINDOW = "serverConnectionReceiveWindow"
const val SERVER_MTU = "serverMTU"
const val SERVER_DISABLE_MTU_DISCOVERY = "serverDisableMtuDiscovery"
const val SERVER_HOP_INTERVAL = "hopInterval"
const val SERVER_VMESS_EXPERIMENTS_CATEGORY = "serverVMessExperimentsCategory"
const val SERVER_VMESS_EXPERIMENTAL_AUTHENTICATED_LENGTH =
"serverVMessExperimentalAuthenticatedLength"
const val SERVER_VMESS_EXPERIMENTAL_NO_TERMINATION_SIGNAL =
"serverVMessExperimentalNoTerminationSignal"
const val SERVER_PRIVATE_KEY = "serverPrivateKey"
const val SERVER_LOCAL_ADDRESS = "serverLocalAddress"
const val SERVER_INSECURE_CONCURRENCY = "serverInsecureConcurrency"
const val SERVER_REDUCED_IV_HEAD_ENTROPY = "serverReducedIvHeadEntropy"
const val SERVER_UDP_RELAY_MODE = "serverUDPRelayMode"
const val SERVER_CONGESTION_CONTROLLER = "serverCongestionController"
const val SERVER_DISABLE_SNI = "serverDisableSNI"
const val SERVER_REDUCE_RTT= "serverReduceRTT"
const val SERVER_FAST_CONNECT= "serverFastConnect"
const val ROUTE_NAME = "routeName"
const val ROUTE_DOMAIN = "routeDomain"
const val ROUTE_IP = "routeIP"
const val ROUTE_PORT = "routePort"
const val ROUTE_SOURCE_PORT = "routeSourcePort"
const val ROUTE_NETWORK = "routeNetwork"
const val ROUTE_SOURCE = "routeSource"
const val ROUTE_PROTOCOL = "routeProtocol"
const val ROUTE_ATTRS = "routeAttrs"
const val ROUTE_OUTBOUND = "routeOutbound"
const val ROUTE_OUTBOUND_RULE = "routeOutboundRule"
const val ROUTE_REVERSE = "routeReverse"
const val ROUTE_REDIRECT = "routeRedirect"
const val ROUTE_PACKAGES = "routePackages"
const val GROUP_NAME = "groupName"
const val GROUP_TYPE = "groupType"
const val GROUP_ORDER = "groupOrder"
const val GROUP_SUBSCRIPTION = "groupSubscription"
const val SUBSCRIPTION_TYPE = "subscriptionType"
const val SUBSCRIPTION_LINK = "subscriptionLink"
const val SUBSCRIPTION_TOKEN = "subscriptionToken"
const val SUBSCRIPTION_FORCE_RESOLVE = "subscriptionForceResolve"
const val SUBSCRIPTION_DEDUPLICATION = "subscriptionDeduplication"
const val SUBSCRIPTION_UPDATE = "subscriptionUpdate"
const val SUBSCRIPTION_UPDATE_WHEN_CONNECTED_ONLY = "subscriptionUpdateWhenConnectedOnly"
const val SUBSCRIPTION_USER_AGENT = "subscriptionUserAgent"
const val SUBSCRIPTION_AUTO_UPDATE = "subscriptionAutoUpdate"
const val SUBSCRIPTION_AUTO_UPDATE_DELAY = "subscriptionAutoUpdateDelay"
//
const val NEKO_PLUGIN_MANAGED = "nekoPlugins"
const val EXE_PREFER_PROVIDER = "exePreferProvider"
const val APP_TLS_VERSION = "appTLSVersion"
}
object TunImplementation {
const val GVISOR = 0
const val SYSTEM = 1
const val TUN2SOCKET = 2
}
object IPv6Mode {
const val DISABLE = 0
const val ENABLE = 1
const val PREFER = 2
const val ONLY = 3
}
object GroupType {
const val BASIC = 0
const val SUBSCRIPTION = 1
}
object SubscriptionType {
const val RAW = 0
const val OOCv1 = 1
const val SIP008 = 2
}
object ExtraType {
const val NONE = 0
const val OOCv1 = 1
const val SIP008 = 2
}
object GroupOrder {
const val ORIGIN = 0
const val BY_NAME = 1
const val BY_DELAY = 2
}
object Action {
const val SERVICE = "io.nekohasekai.sagernet.SERVICE"
const val CLOSE = "io.nekohasekai.sagernet.CLOSE"
const val RELOAD = "io.nekohasekai.sagernet.RELOAD"
// const val SWITCH_WAKE_LOCK = "io.nekohasekai.sagernet.SWITCH_WAKELOCK"
const val RESET_UPSTREAM_CONNECTIONS = "moe.nb4a.RESET_UPSTREAM_CONNECTIONS"
}
| Ving-Vpn/app/src/main/java/io/nekohasekai/sagernet/Constants.kt | 1210401898 |
package moe.matsuri.nya.utils
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.text.Editable
import android.util.Base64
import com.narcis.application.presentation.connection.Logs
import java.net.URLDecoder
import java.net.URLEncoder
import java.util.UUID
// Copy form v2rayNG to parse their stupid format
object NGUtil {
/**
* convert string to editalbe for kotlin
*
* @param text
* @return
*/
fun getEditable(text: String): Editable {
return Editable.Factory.getInstance().newEditable(text)
}
/**
* find value in array position
*/
fun arrayFind(array: Array<out String>, value: String): Int {
for (i in array.indices) {
if (array[i] == value) {
return i
}
}
return -1
}
/**
* parseInt
*/
fun parseInt(str: String): Int {
return try {
Integer.parseInt(str)
} catch (e: Exception) {
e.printStackTrace()
0
}
}
/**
* get text from clipboard
*/
fun getClipboard(context: Context): String {
return try {
val cmb = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
cmb.primaryClip?.getItemAt(0)?.text.toString()
} catch (e: Exception) {
e.printStackTrace()
""
}
}
/**
* set text to clipboard
*/
fun setClipboard(context: Context, content: String) {
try {
val cmb = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clipData = ClipData.newPlainText(null, content)
cmb.setPrimaryClip(clipData)
} catch (e: Exception) {
e.printStackTrace()
}
}
/**
* base64 decode
*/
fun decode(text: String): String {
tryDecodeBase64(text)?.let { return it }
if (text.endsWith('=')) {
// try again for some loosely formatted base64
tryDecodeBase64(text.trimEnd('='))?.let { return it }
}
return ""
}
fun tryDecodeBase64(text: String): String? {
try {
return Base64.decode(text, Base64.NO_WRAP).toString(charset("UTF-8"))
} catch (e: Exception) {
Logs.i("Parse base64 standard failed $e")
}
try {
return Base64.decode(text, Base64.NO_WRAP.or(Base64.URL_SAFE)).toString(charset("UTF-8"))
} catch (e: Exception) {
Logs.i("Parse base64 url safe failed $e")
}
return null
}
/**
* base64 encode
*/
fun encode(text: String): String {
return try {
Base64.encodeToString(text.toByteArray(charset("UTF-8")), Base64.NO_WRAP)
} catch (e: Exception) {
e.printStackTrace()
""
}
}
/**
* is ip address
*/
fun isIpAddress(value: String): Boolean {
try {
var addr = value
if (addr.isEmpty() || addr.isBlank()) {
return false
}
//CIDR
if (addr.indexOf("/") > 0) {
val arr = addr.split("/")
if (arr.count() == 2 && Integer.parseInt(arr[1]) > 0) {
addr = arr[0]
}
}
// "::ffff:192.168.173.22"
// "[::ffff:192.168.173.22]:80"
if (addr.startsWith("::ffff:") && '.' in addr) {
addr = addr.drop(7)
} else if (addr.startsWith("[::ffff:") && '.' in addr) {
addr = addr.drop(8).replace("]", "")
}
// addr = addr.toLowerCase()
val octets = addr.split('.').toTypedArray()
if (octets.size == 4) {
if(octets[3].indexOf(":") > 0) {
addr = addr.substring(0, addr.indexOf(":"))
}
return isIpv4Address(addr)
}
// Ipv6addr [2001:abc::123]:8080
return isIpv6Address(addr)
} catch (e: Exception) {
e.printStackTrace()
return false
}
}
fun isPureIpAddress(value: String): Boolean {
return (isIpv4Address(value) || isIpv6Address(value))
}
fun isIpv4Address(value: String): Boolean {
val regV4 = Regex("^([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$")
return regV4.matches(value)
}
fun isIpv6Address(value: String): Boolean {
var addr = value
if (addr.indexOf("[") == 0 && addr.lastIndexOf("]") > 0) {
addr = addr.drop(1)
addr = addr.dropLast(addr.count() - addr.lastIndexOf("]"))
}
val regV6 = Regex("^((?:[0-9A-Fa-f]{1,4}))?((?::[0-9A-Fa-f]{1,4}))*::((?:[0-9A-Fa-f]{1,4}))?((?::[0-9A-Fa-f]{1,4}))*|((?:[0-9A-Fa-f]{1,4}))((?::[0-9A-Fa-f]{1,4})){7}$")
return regV6.matches(addr)
}
private fun isCoreDNSAddress(s: String): Boolean {
return s.startsWith("https") || s.startsWith("tcp") || s.startsWith("quic")
}
fun openUri(context: Context, uriString: String) {
val uri = Uri.parse(uriString)
context.startActivity(Intent(Intent.ACTION_VIEW, uri))
}
/**
* uuid
*/
fun getUuid(): String {
return try {
UUID.randomUUID().toString().replace("-", "")
} catch (e: Exception) {
e.printStackTrace()
""
}
}
fun urlDecode(url: String): String {
return try {
URLDecoder.decode(url, "UTF-8")
} catch (e: Exception) {
url
}
}
fun urlEncode(url: String): String {
return try {
URLEncoder.encode(url, "UTF-8")
} catch (e: Exception) {
e.printStackTrace()
url
}
}
/**
* package path
*/
fun packagePath(context: Context): String {
var path = context.filesDir.toString()
path = path.replace("files", "")
//path += "tun2socks"
return path
}
/**
* readTextFromAssets
*/
fun readTextFromAssets(context: Context, fileName: String): String {
val content = context.assets.open(fileName).bufferedReader().use {
it.readText()
}
return content
}
} | Ving-Vpn/app/src/main/java/moe/matsuri/nya/utils/NGUtil.kt | 1345513399 |
package moe.matsuri.nya.utils
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.core.content.FileProvider
import io.nekohasekai.sagernet.BuildConfig
import io.nekohasekai.sagernet.R
import com.narcis.application.presentation.connection.Logs
import com.narcis.application.presentation.connection.use
import io.nekohasekai.sagernet.ktx.app
import io.nekohasekai.sagernet.utils.CrashHandler
import libcore.Libcore
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
object SendLog {
// Create full log and send
fun sendLog(context: Context, title: String) {
val logFile = File.createTempFile(
"$title ",
".log",
File(app.cacheDir, "log").also { it.mkdirs() })
var report = CrashHandler.buildReportHeader()
report += "Logcat: \n\n"
logFile.writeText(report)
try {
Runtime.getRuntime().exec(arrayOf("logcat", "-d")).inputStream.use(
FileOutputStream(
logFile, true
)
)
logFile.appendText("\n")
logFile.appendBytes(Libcore.nekoLogGet())
} catch (e: IOException) {
Logs.w(e)
logFile.appendText("Export logcat error: " + CrashHandler.formatThrowable(e))
}
if ( Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP ) {
context.startActivity(
Intent.createChooser(
Intent(Intent.ACTION_SEND).setType("text/x-log")
.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
.putExtra(
Intent.EXTRA_STREAM, FileProvider.getUriForFile(
context, BuildConfig.APPLICATION_ID + ".cache", logFile
)
), context.getString(R.string.abc_shareactionprovider_share_with)
)
)
}
}
} | Ving-Vpn/app/src/main/java/moe/matsuri/nya/utils/SendLog.kt | 4214189524 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.