Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2afc7262eb | ||
|
|
94a0282c70 | ||
|
|
96b78829ab | ||
|
|
35d5a90b2a | ||
|
|
50d73ad498 | ||
|
|
d1f8bc3062 | ||
|
|
d3353b1aa5 | ||
|
|
cd48fb4e08 | ||
|
|
f70738ecf5 | ||
|
|
2d63466597 | ||
|
|
ecf67443fb | ||
|
|
43987ad111 | ||
|
|
5fbd6c6196 | ||
|
|
1ec7f1f7e9 | ||
|
|
c5104c241a | ||
|
|
021ba3519d | ||
|
|
119f74cd05 | ||
|
|
f0b61c9e1f | ||
|
|
a573631068 | ||
|
|
a12444b258 | ||
|
|
17257228a9 | ||
|
|
53b6a9dfc1 | ||
|
|
c45f8ddfc3 | ||
|
|
e04c9c15ff | ||
|
|
d5cb363579 | ||
|
|
0748021ffa | ||
|
|
e958e7f675 | ||
|
|
68113e694e |
No files matched your search
@@ -31,7 +31,7 @@ if applicable, add logs to help detect problem
|
||||
- Device: [e.g. Pixel 4]
|
||||
- ROM: [e.g: AOSP]
|
||||
- ROM Version:
|
||||
- Android Version [e.g. Oreo]
|
||||
- Android Version [e.g. 10]
|
||||
|
||||
**Application Info (please complete the following information):**
|
||||
|
||||
@@ -40,4 +40,4 @@ if applicable, add logs to help detect problem
|
||||
- Distribution Channel: [e.g. Google Play]
|
||||
|
||||
**Additional context**
|
||||
Add any other context about the problem here.
|
||||
Add any other context about the problem here.
|
||||
@@ -24,13 +24,12 @@ assignees: ''
|
||||
如果适用, 上传屏幕截图以帮助描述错误
|
||||
|
||||
**日志**
|
||||
|
||||
如果适用, 上传日志以帮助侦测错误
|
||||
|
||||
**设备信息 (请完成一下信息):**
|
||||
**设备信息 (请完成以下信息):**
|
||||
- 机型: [例如: Pixel 4]
|
||||
- 系统/ROM: [例如: MIUI 11]
|
||||
- Android 版本 [例如: Oreo]
|
||||
- Android 版本 [例如: 10]
|
||||
- ROM版本 [例如: 20.3.19]
|
||||
|
||||
**应用信息**
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
blank_issues_enabled: false
|
||||
@@ -16,7 +16,6 @@ import kotlinx.android.synthetic.main.activity_log_viewer.*
|
||||
import kotlinx.coroutines.*
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import java.io.File
|
||||
import kotlin.streams.toList
|
||||
|
||||
class LogViewerActivity : BaseActivity() {
|
||||
private val pauseMutex = Mutex()
|
||||
@@ -92,15 +91,15 @@ class LogViewerActivity : BaseActivity() {
|
||||
launch {
|
||||
val items = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
file.readText()
|
||||
.split("\n")
|
||||
.parallelStream()
|
||||
.map { it.trim() }
|
||||
.filter { it.isNotEmpty() && !it.startsWith("#") }
|
||||
.map { it.split(" ", limit = 3) }
|
||||
.filter { it.size == 3 }
|
||||
.map { LogEvent(LogEvent.Level.valueOf(it[1]), it[2], it[0].toLong()) }
|
||||
.toList()
|
||||
file.bufferedReader().useLines { lines ->
|
||||
lines
|
||||
.map { it.trim() }
|
||||
.filter { it.isNotEmpty() && !it.startsWith("#") }
|
||||
.map { it.split(" ", limit = 3) }
|
||||
.filter { it.size == 3 }
|
||||
.map { LogEvent(LogEvent.Level.valueOf(it[1]), it[2], it[0].toLong()) }
|
||||
.toList()
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
showSnackbarException(getString(R.string.open_log_failure), e.message)
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ import androidx.recyclerview.widget.LinearLayoutManager
|
||||
import com.github.kr328.clash.adapter.LogFileAdapter
|
||||
import com.github.kr328.clash.common.utils.intent
|
||||
import com.github.kr328.clash.common.utils.startForegroundServiceCompat
|
||||
import com.github.kr328.clash.core.event.LogEvent
|
||||
import com.github.kr328.clash.design.common.Category
|
||||
import com.github.kr328.clash.design.view.CommonUiLayout
|
||||
import com.github.kr328.clash.model.LogFile
|
||||
@@ -24,12 +25,15 @@ import kotlinx.android.synthetic.main.activity_logs.*
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.FileInputStream
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.*
|
||||
|
||||
class LogsActivity : BaseActivity() {
|
||||
companion object {
|
||||
const val REQUEST_CODE = 50000
|
||||
|
||||
private val LOG_EXPORT_DATE_FORMAT = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH)
|
||||
private val LOG_EXPORT_TIME_FORMAT = SimpleDateFormat("HH:mm:ss", Locale.ENGLISH)
|
||||
}
|
||||
|
||||
private var lastWriteFile: LogFile? = null
|
||||
@@ -102,9 +106,31 @@ class LogsActivity : BaseActivity() {
|
||||
|
||||
launch {
|
||||
withContext(Dispatchers.IO) {
|
||||
contentResolver.openOutputStream(url)?.use { output ->
|
||||
FileInputStream(logsDir.resolve(file.fileName)).use { input ->
|
||||
input.copyTo(output)
|
||||
contentResolver.openOutputStream(url)?.bufferedWriter()?.use { output ->
|
||||
output.write("# Logcat on " + LOG_EXPORT_DATE_FORMAT.format(Date(file.date)) + "\n")
|
||||
|
||||
logsDir.resolve(file.fileName).bufferedReader().useLines { lines ->
|
||||
lines.map { it.trim() }
|
||||
.filter { it.isNotEmpty() && !it.startsWith("#") }
|
||||
.map { it.split(" ", limit = 3) }
|
||||
.filter { it.size == 3 }
|
||||
.map {
|
||||
LogEvent(
|
||||
LogEvent.Level.valueOf(it[1]),
|
||||
it[2],
|
||||
it[0].toLong()
|
||||
)
|
||||
}
|
||||
.forEach {
|
||||
output.write(
|
||||
String.format(
|
||||
"%s |%s| %s\n",
|
||||
LOG_EXPORT_TIME_FORMAT.format(Date(it.time)),
|
||||
it.level.toString(),
|
||||
it.message
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,6 +27,8 @@ class ProfileEditFragment(
|
||||
private val type: Type,
|
||||
private val source: String?
|
||||
) : Fragment() {
|
||||
private var root: CommonUiLayout? = null
|
||||
|
||||
var isModified = false
|
||||
|
||||
companion object {
|
||||
@@ -46,6 +48,7 @@ class ProfileEditFragment(
|
||||
savedInstanceState: Bundle?
|
||||
): View? {
|
||||
return CommonUiLayout(requireContext()).apply {
|
||||
root = this
|
||||
layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
|
||||
|
||||
build {
|
||||
@@ -111,12 +114,14 @@ class ProfileEditFragment(
|
||||
|
||||
if (s.isBlank()) {
|
||||
content = ""
|
||||
interval = 0
|
||||
return@onTextChanged
|
||||
}
|
||||
|
||||
val value = s.toIntOrNull()
|
||||
if (value == null || value < 15) {
|
||||
content = ""
|
||||
interval = 0
|
||||
Snackbar.make(view, R.string.invalid_interval, Snackbar.LENGTH_LONG)
|
||||
.show()
|
||||
return@onTextChanged
|
||||
@@ -143,16 +148,16 @@ class ProfileEditFragment(
|
||||
if (resultCode != Activity.RESULT_OK || data == null)
|
||||
return
|
||||
|
||||
val layout = view as CommonUiLayout
|
||||
root?.apply {
|
||||
data.data?.apply {
|
||||
screen.requireElement<TextInput>(KEY_URL).content = this.toString()
|
||||
}
|
||||
|
||||
data.data?.apply {
|
||||
layout.screen.requireElement<TextInput>(KEY_URL).content = this.toString()
|
||||
}
|
||||
|
||||
data.getStringExtra(Constants.URL_PROVIDER_INTENT_EXTRA_NAME)?.also {
|
||||
layout.screen.requireElement<TextInput>(KEY_NAME).apply {
|
||||
if (content.isBlank())
|
||||
content = it
|
||||
data.getStringExtra(Constants.URL_PROVIDER_INTENT_EXTRA_NAME)?.also {
|
||||
screen.requireElement<TextInput>(KEY_NAME).apply {
|
||||
if (content.isBlank())
|
||||
content = it
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -163,7 +168,9 @@ class ProfileEditFragment(
|
||||
override fun onSaveInstanceState(outState: Bundle) {
|
||||
super.onSaveInstanceState(outState)
|
||||
|
||||
(view as CommonUiLayout?)?.screen?.saveState(outState)
|
||||
root?.apply {
|
||||
screen.saveState(outState)
|
||||
}
|
||||
}
|
||||
|
||||
private fun openUrlProvider(): Boolean {
|
||||
@@ -182,11 +189,13 @@ class ProfileEditFragment(
|
||||
else -> return false
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Snackbar.make(
|
||||
view as ViewGroup,
|
||||
R.string.start_url_provider_failure,
|
||||
Snackbar.LENGTH_LONG
|
||||
).show()
|
||||
root?.apply {
|
||||
Snackbar.make(
|
||||
this,
|
||||
R.string.start_url_provider_failure,
|
||||
Snackbar.LENGTH_LONG
|
||||
).show()
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
|
||||
@@ -10,6 +10,7 @@ import android.os.Handler
|
||||
import android.os.IBinder
|
||||
import androidx.core.content.edit
|
||||
import com.github.kr328.clash.ApkBrokenActivity
|
||||
import com.github.kr328.clash.BuildConfig
|
||||
import com.github.kr328.clash.Constants
|
||||
import com.github.kr328.clash.common.Global
|
||||
import com.github.kr328.clash.common.utils.intent
|
||||
@@ -152,6 +153,9 @@ object Remote {
|
||||
if (sp.getLong(Constants.PREFERENCE_KEY_LAST_INSTALL, 0) == pkg.lastUpdateTime)
|
||||
return true
|
||||
|
||||
if ( application.packageName != BuildConfig.APPLICATION_ID )
|
||||
return false
|
||||
|
||||
val info = application.applicationInfo
|
||||
val sources =
|
||||
info.splitSourceDirs ?: arrayOf(info.sourceDir) ?: return false
|
||||
|
||||
+3
-3
@@ -1,7 +1,7 @@
|
||||
// Top-level build file where you can add configuration options common to all sub-projects/modules.
|
||||
|
||||
buildscript {
|
||||
val kotlinVersion = "1.3.71"
|
||||
val kotlinVersion = "1.3.72"
|
||||
|
||||
rootProject.extra.apply {
|
||||
this["gBuildToolsVersion"] = "29.0.3"
|
||||
@@ -10,8 +10,8 @@ buildscript {
|
||||
this["gMinSdkVersion"] = 24
|
||||
this["gTargetSdkVersion"] = 29
|
||||
|
||||
this["gVersionCode"] = 10204
|
||||
this["gVersionName"] = "1.2.4"
|
||||
this["gVersionCode"] = 10208
|
||||
this["gVersionName"] = "1.2.8"
|
||||
|
||||
this["gKotlinVersion"] = kotlinVersion
|
||||
this["gKotlinCoroutineVersion"] = "1.3.5"
|
||||
|
||||
@@ -77,6 +77,6 @@ repositories {
|
||||
}
|
||||
|
||||
afterEvaluate {
|
||||
tasks["clean"].dependsOn(tasks["resetGolangMode"])
|
||||
tasks["clean"].dependsOn(tasks["resetGolangPathMode"])
|
||||
tasks["preBuild"].dependsOn(tasks["extractSources"], tasks["downloadGeoipDatabase"])
|
||||
}
|
||||
@@ -145,7 +145,7 @@ task("generateClashBindSources") {
|
||||
}
|
||||
}
|
||||
|
||||
task("bindClashCore") {
|
||||
task("assembleClashCore") {
|
||||
dependsOn(tasks["generateClashBindSources"])
|
||||
|
||||
onlyIf {
|
||||
@@ -169,14 +169,8 @@ task("bindClashCore") {
|
||||
}
|
||||
|
||||
task("extractSources", type = Copy::class) {
|
||||
dependsOn(tasks["bindClashCore"])
|
||||
dependsOn(tasks["assembleClashCore"])
|
||||
|
||||
doFirst {
|
||||
buildDir.resolve(Constants.OUTPUT_PATH).apply {
|
||||
resolve("jniLibs").deleteRecursively()
|
||||
resolve("classes").deleteRecursively()
|
||||
}
|
||||
}
|
||||
from(zipTree(buildDir.resolve(Constants.GOLANG_OUTPUT))) {
|
||||
include("**/*.so")
|
||||
eachFile {
|
||||
@@ -192,6 +186,8 @@ task("extractSources", type = Copy::class) {
|
||||
}
|
||||
|
||||
task("downloadGeoipDatabase") {
|
||||
dependsOn(tasks["extractSources"])
|
||||
|
||||
onlyIf {
|
||||
val file = buildDir.resolve(Constants.OUTPUT_PATH).resolve("assets/Country.mmdb")
|
||||
|
||||
@@ -211,7 +207,7 @@ task("downloadGeoipDatabase") {
|
||||
}
|
||||
}
|
||||
|
||||
task("resetGolangMode", type = Exec::class) {
|
||||
task("resetGolangPathMode", type = Exec::class) {
|
||||
onlyIf {
|
||||
!Os.isFamily(Os.FAMILY_WINDOWS)
|
||||
}
|
||||
|
||||
@@ -20,12 +20,14 @@ func init() {
|
||||
dialer.ListenConfigHook = onNewListenConfig
|
||||
}
|
||||
|
||||
func onNewDialer(dialer *net.Dialer) {
|
||||
func onNewDialer(dialer *net.Dialer) error {
|
||||
dialer.Control = onNewSocket
|
||||
return nil
|
||||
}
|
||||
|
||||
func onNewListenConfig(listen *net.ListenConfig) {
|
||||
func onNewListenConfig(listen *net.ListenConfig) error {
|
||||
listen.Control = onNewSocket
|
||||
return nil
|
||||
}
|
||||
|
||||
func onNewSocket(_, _ string, c syscall.RawConn) error {
|
||||
|
||||
Submodule core/src/main/golang/clash updated: f48ce6fc8e...7eabb6651e.
@@ -7,6 +7,7 @@ import (
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"syscall"
|
||||
|
||||
@@ -36,13 +37,22 @@ var client = &http.Client{
|
||||
},
|
||||
}
|
||||
|
||||
func fetchRemote(url string) ([]byte, error) {
|
||||
request, err := http.NewRequest("GET", url, nil)
|
||||
func fetchRemote(sUrl string) ([]byte, error) {
|
||||
uri, err := url.Parse(sUrl)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
request, err := http.NewRequest("GET", uri.String(), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
request.Header.Set("User-Agent", "ClashForAndroid/"+ApplicationVersion)
|
||||
if user := uri.User; user != nil {
|
||||
password, _ := user.Password()
|
||||
request.SetBasicAuth(user.Username(), password)
|
||||
}
|
||||
|
||||
response, err := client.Do(request)
|
||||
if err != nil {
|
||||
|
||||
@@ -4,7 +4,7 @@ go 1.13
|
||||
|
||||
require (
|
||||
github.com/Dreamacro/clash v0.0.0 // local
|
||||
github.com/kr328/tun2socket v0.0.0-20200415021819-256b721ac9a4
|
||||
github.com/kr328/tun2socket v0.0.0-20200421133501-c8848c95a7ca
|
||||
github.com/miekg/dns v1.1.29
|
||||
)
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ github.com/go-chi/render v1.0.1/go.mod h1:pq4Rr7HbnsdaeHagklXub+p6Wd16Af5l9koip1
|
||||
github.com/gofrs/uuid v3.2.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM=
|
||||
github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||
github.com/kr328/tun2socket v0.0.0-20200415021819-256b721ac9a4/go.mod h1:FWfSixjrLgtK+dHkDoN6lHMNhvER24gnjUZd/wt8Z9o=
|
||||
github.com/kr328/tun2socket v0.0.0-20200421133501-c8848c95a7ca/go.mod h1:FWfSixjrLgtK+dHkDoN6lHMNhvER24gnjUZd/wt8Z9o=
|
||||
github.com/miekg/dns v1.1.29/go.mod h1:KNUDUusw/aVsxyTYZM1oqvCicbwhgbNgztCETuNZ7xM=
|
||||
github.com/oschwald/geoip2-golang v1.4.0/go.mod h1:8QwxJvRImBH+Zl6Aa6MaIcs5YdlZSTKtzmPGzQqi9ng=
|
||||
github.com/oschwald/maxminddb-golang v1.6.0/go.mod h1:DUJFucBg2cvqx42YmDa/+xHvb0elJtOm3o4aFQ/nb/w=
|
||||
|
||||
@@ -56,7 +56,7 @@ func hijackTCPDNS(conn net.Conn, endpoint *binding.Endpoint) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
if !hijackAddress.Equal(net.IPv4zero) && !hijackAddress.Equal(net.IPv6zero) && !hijackAddress.Equal(endpoint.Target.IP) {
|
||||
if !hijackAddress.Equal(net.IPv4zero) && !hijackAddress.Equal(endpoint.Target.IP) {
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -109,7 +109,7 @@ func hijackDNS(payload []byte, endpoint *binding.Endpoint, sender redirect.UDPSe
|
||||
return false
|
||||
}
|
||||
|
||||
if !hijackAddress.Equal(net.IPv4zero) && !hijackAddress.Equal(net.IPv6zero) && !hijackAddress.Equal(endpoint.Target.IP) {
|
||||
if !hijackAddress.Equal(net.IPv4zero) && !hijackAddress.Equal(endpoint.Target.IP) {
|
||||
return false
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ package tun
|
||||
|
||||
import "github.com/Dreamacro/clash/log"
|
||||
|
||||
type ClashLogger struct {}
|
||||
type ClashLogger struct{}
|
||||
|
||||
func (c *ClashLogger) D(format string, args ...interface{}) {
|
||||
log.Debugln(format, args)
|
||||
@@ -19,4 +19,3 @@ func (c *ClashLogger) W(format string, args ...interface{}) {
|
||||
func (c *ClashLogger) E(format string, args ...interface{}) {
|
||||
log.Errorln(format, args)
|
||||
}
|
||||
|
||||
@@ -101,7 +101,8 @@ func StartTunDevice(fd, mtu int, gateway, mirror, dnsAddress string) error {
|
||||
pkt := &udpPacket{
|
||||
payload: payload,
|
||||
endpoint: endpoint,
|
||||
sender: sender,
|
||||
send: sender,
|
||||
recycle: udpRecycle,
|
||||
}
|
||||
|
||||
tunnel.AddPacket(adapters.NewPacket(addr, pkt, C.SOCKS))
|
||||
|
||||
@@ -10,7 +10,8 @@ import (
|
||||
type udpPacket struct {
|
||||
payload []byte
|
||||
endpoint *binding.Endpoint
|
||||
sender redirect.UDPSender
|
||||
send redirect.UDPSender
|
||||
recycle func([]byte)
|
||||
}
|
||||
|
||||
func (conn *udpPacket) Data() []byte {
|
||||
@@ -39,11 +40,7 @@ func (conn *udpPacket) WriteBack(b []byte, addr net.Addr) (n int, err error) {
|
||||
Target: conn.endpoint.Source,
|
||||
}
|
||||
|
||||
return len(b), conn.sender(b, ep)
|
||||
}
|
||||
|
||||
func (conn *udpPacket) Close() error {
|
||||
return nil
|
||||
return len(b), conn.send(b, ep)
|
||||
}
|
||||
|
||||
func (conn *udpPacket) LocalAddr() net.Addr {
|
||||
@@ -53,3 +50,7 @@ func (conn *udpPacket) LocalAddr() net.Addr {
|
||||
Zone: "",
|
||||
}
|
||||
}
|
||||
|
||||
func (conn *udpPacket) Drop() {
|
||||
conn.recycle(conn.payload)
|
||||
}
|
||||
+3
-1
@@ -20,4 +20,6 @@ android.enableJetifier=true
|
||||
# Kotlin code style for this project: "official" or "obsolete":
|
||||
kotlin.code.style=official
|
||||
|
||||
kapt.incremental.apt=false
|
||||
kapt.incremental.apt=false
|
||||
|
||||
org.gradle.parallel=true
|
||||
@@ -4,10 +4,7 @@ import android.content.Intent
|
||||
import android.os.Binder
|
||||
import android.os.IBinder
|
||||
import com.github.kr328.clash.service.clash.ClashRuntime
|
||||
import com.github.kr328.clash.service.clash.module.CloseModule
|
||||
import com.github.kr328.clash.service.clash.module.DynamicNotificationModule
|
||||
import com.github.kr328.clash.service.clash.module.ReloadModule
|
||||
import com.github.kr328.clash.service.clash.module.StaticNotificationModule
|
||||
import com.github.kr328.clash.service.clash.module.*
|
||||
import com.github.kr328.clash.service.settings.ServiceSettings
|
||||
import com.github.kr328.clash.service.util.broadcastClashStarted
|
||||
import com.github.kr328.clash.service.util.broadcastClashStopped
|
||||
@@ -36,9 +33,7 @@ class ClashService : BaseService() {
|
||||
runtime.install(ReloadModule(service)) {
|
||||
onLoaded {
|
||||
if (it != null) {
|
||||
reason = it.message
|
||||
|
||||
stopSelf()
|
||||
service.stopSelfForReason(it.message)
|
||||
} else {
|
||||
service.broadcastProfileLoaded()
|
||||
}
|
||||
@@ -46,9 +41,7 @@ class ClashService : BaseService() {
|
||||
}
|
||||
runtime.install(CloseModule()) {
|
||||
onClosed {
|
||||
reason = null
|
||||
|
||||
stopSelf()
|
||||
service.stopSelfForReason(null)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,4 +71,10 @@ class ClashService : BaseService() {
|
||||
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
private fun stopSelfForReason(reason: String?) {
|
||||
this.reason = reason
|
||||
|
||||
stopSelf()
|
||||
}
|
||||
}
|
||||
@@ -45,11 +45,11 @@ class ProfileReceiver : BroadcastReceiver() {
|
||||
val metadata = ProfileDao.queryById(id)?.asProfile(context) ?: return
|
||||
val service = context.getSystemService<AlarmManager>() ?: return
|
||||
|
||||
val pendingIntent = cancelNextUpdate(context, id)
|
||||
|
||||
if (metadata.interval <= 0)
|
||||
return
|
||||
|
||||
val pendingIntent = cancelNextUpdate(context, id)
|
||||
|
||||
service.set(
|
||||
AlarmManager.RTC,
|
||||
metadata.lastModified + metadata.interval,
|
||||
|
||||
@@ -83,8 +83,12 @@ class ProfileService : BaseService() {
|
||||
val clonedId = generateNextId()
|
||||
|
||||
pending[clonedId] =
|
||||
queryMetadataById(id)?.copy(id = clonedId, active = false, lastModified = 0)
|
||||
?: return@runBlocking -1L
|
||||
queryMetadataById(id)?.copy(
|
||||
id = clonedId,
|
||||
active = false,
|
||||
lastModified = 0,
|
||||
type = Profile.Type.FILE
|
||||
) ?: return@runBlocking -1L
|
||||
|
||||
clonedId
|
||||
}
|
||||
@@ -104,6 +108,8 @@ class ProfileService : BaseService() {
|
||||
ProfileDao.remove(id)
|
||||
}
|
||||
|
||||
ProfileReceiver.cancelNextUpdate(service, id)
|
||||
|
||||
service.resolveProfileFile(id).delete()
|
||||
service.resolveTempProfileFile(id).delete()
|
||||
service.resolveBaseDir(id).deleteRecursively()
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.github.kr328.clash.service
|
||||
|
||||
import android.content.Intent
|
||||
import android.net.VpnService
|
||||
import android.os.Process
|
||||
import com.github.kr328.clash.service.clash.ClashRuntime
|
||||
import com.github.kr328.clash.service.clash.module.*
|
||||
import com.github.kr328.clash.service.settings.ServiceSettings
|
||||
@@ -13,12 +14,9 @@ import kotlinx.coroutines.launch
|
||||
|
||||
class TunService : VpnService(), CoroutineScope by MainScope() {
|
||||
companion object {
|
||||
// from https://github.com/shadowsocks/shadowsocks-android/blob/master/core/src/main/java/com/github/shadowsocks/bg/VpnService.kt
|
||||
private const val VPN_MTU = 9000
|
||||
private const val PRIVATE_VLAN4_SUBNET = 30
|
||||
private const val PRIVATE_VLAN4_CLIENT = "172.31.255.253"
|
||||
private const val PRIVATE_VLAN4_MIRROR = "172.31.255.254"
|
||||
private const val PRIVATE_VLAN_DNS = "198.18.0.1"
|
||||
private const val VLAN_ANY = "0.0.0.0/0"
|
||||
}
|
||||
|
||||
private val service = this
|
||||
@@ -47,25 +45,15 @@ class TunService : VpnService(), CoroutineScope by MainScope() {
|
||||
runtime.install(ReloadModule(service)) {
|
||||
onLoaded {
|
||||
if (it != null) {
|
||||
reason = it.message
|
||||
|
||||
stopSelf()
|
||||
|
||||
TunModule.requestStop()
|
||||
service.stopSelfForReason(it.message)
|
||||
} else {
|
||||
broadcastProfileLoaded()
|
||||
service.broadcastProfileLoaded()
|
||||
}
|
||||
}
|
||||
}
|
||||
runtime.install(CloseModule()) {
|
||||
onClosed {
|
||||
launch {
|
||||
reason = null
|
||||
|
||||
stopSelf()
|
||||
|
||||
TunModule.requestStop()
|
||||
}
|
||||
service.stopSelfForReason(null)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,7 +87,7 @@ class TunService : VpnService(), CoroutineScope by MainScope() {
|
||||
}
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
broadcastClashStarted()
|
||||
service.broadcastClashStarted()
|
||||
|
||||
return super.onStartCommand(intent, flags, startId)
|
||||
}
|
||||
@@ -107,7 +95,7 @@ class TunService : VpnService(), CoroutineScope by MainScope() {
|
||||
override fun onDestroy() {
|
||||
ServiceStatusProvider.serviceRunning = false
|
||||
|
||||
broadcastClashStopped(reason)
|
||||
service.broadcastClashStopped(reason)
|
||||
|
||||
cancel()
|
||||
|
||||
@@ -115,36 +103,75 @@ class TunService : VpnService(), CoroutineScope by MainScope() {
|
||||
}
|
||||
|
||||
private inner class TunConfigure(private val settings: ServiceSettings) : TunModule.Configure {
|
||||
private val network = generateTunNetwork()
|
||||
|
||||
override val builder: Builder
|
||||
get() = Builder()
|
||||
override val mtu: Int
|
||||
get() = VPN_MTU
|
||||
override val gateway: String
|
||||
get() = "$PRIVATE_VLAN4_CLIENT/$PRIVATE_VLAN4_SUBNET"
|
||||
override val mirror: String
|
||||
get() = PRIVATE_VLAN4_MIRROR
|
||||
override val gateway: String = network.copyOf().apply {
|
||||
this[3] = (this[3] + 1).toByte()
|
||||
}.asAddressString("/30")
|
||||
override val mirror: String = network.copyOf().apply {
|
||||
this[3] = (this[3] + 2).toByte()
|
||||
}.asAddressString()
|
||||
override val route: List<String>
|
||||
get() {
|
||||
return if (settings.get(ServiceSettings.BYPASS_PRIVATE_NETWORK))
|
||||
resources.getStringArray(R.array.bypass_private_route).toList()
|
||||
else
|
||||
listOf("0.0.0.0/0")
|
||||
listOf(VLAN_ANY)
|
||||
}
|
||||
override val dnsAddress: String
|
||||
get() = PRIVATE_VLAN_DNS
|
||||
override val dnsHijacking: Boolean
|
||||
get() = settings.get(ServiceSettings.DNS_HIJACKING)
|
||||
override val allowApplications: List<String>
|
||||
override val allowApplications: Collection<String>
|
||||
get() {
|
||||
return if (settings.get(ServiceSettings.ACCESS_CONTROL_MODE) == ServiceSettings.ACCESS_CONTROL_MODE_WHITELIST) {
|
||||
(settings.get(ServiceSettings.ACCESS_CONTROL_PACKAGES) + packageName).toList()
|
||||
} else emptyList()
|
||||
(settings.get(ServiceSettings.ACCESS_CONTROL_PACKAGES) + packageName)
|
||||
} else emptySet()
|
||||
}
|
||||
override val disallowApplication: List<String>
|
||||
override val disallowApplication: Collection<String>
|
||||
get() {
|
||||
return if (settings.get(ServiceSettings.ACCESS_CONTROL_MODE) == ServiceSettings.ACCESS_CONTROL_MODE_BLACKLIST) {
|
||||
(settings.get(ServiceSettings.ACCESS_CONTROL_PACKAGES) - packageName).toList()
|
||||
} else emptyList()
|
||||
(settings.get(ServiceSettings.ACCESS_CONTROL_PACKAGES) - packageName)
|
||||
} else emptySet()
|
||||
}
|
||||
|
||||
override fun onCreateTunFailure() {
|
||||
stopSelfForReason("Start VPN rejected by the system")
|
||||
}
|
||||
|
||||
private fun generateTunNetwork(): ByteArray {
|
||||
val result = ByteArray(4)
|
||||
|
||||
// 18 bit namespace
|
||||
val offset = UserUtils.currentUserId % 0x40000
|
||||
val network = (0x3FFFF - offset) shl 2
|
||||
|
||||
result[0] = (172 or (network shr 24) and 0xFF).toByte()
|
||||
result[1] = (16 or (network shr 16) and 0xFF).toByte()
|
||||
result[2] = (0 or (network shr 8) and 0xFF).toByte()
|
||||
result[3] = (0 or (network shr 0) and 0xFF).toByte()
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
private fun ByteArray.asAddressString(suffix: String = ""): String {
|
||||
return "${this[0].toUnsignedString()}.${this[1].toUnsignedString()}.${this[2].toUnsignedString()}.${this[3].toUnsignedString()}$suffix"
|
||||
}
|
||||
|
||||
private fun Byte.toUnsignedString(): String {
|
||||
return (this.toInt() and 0xFF).toString()
|
||||
}
|
||||
}
|
||||
|
||||
private fun stopSelfForReason(reason: String?) {
|
||||
this.reason = reason
|
||||
|
||||
stopSelf()
|
||||
|
||||
TunModule.requestStop()
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
package com.github.kr328.clash.service.clash.module
|
||||
|
||||
import android.app.PendingIntent
|
||||
import android.content.Intent
|
||||
import android.net.VpnService
|
||||
import android.os.Build
|
||||
import com.github.kr328.clash.common.Global
|
||||
import com.github.kr328.clash.common.ids.PendingIds
|
||||
import com.github.kr328.clash.common.utils.Log
|
||||
import com.github.kr328.clash.core.Clash
|
||||
import com.github.kr328.clash.service.util.parseCIDR
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
@@ -20,8 +20,10 @@ class TunModule(private val service: VpnService) : Module() {
|
||||
val route: List<String>
|
||||
val dnsAddress: String
|
||||
val dnsHijacking: Boolean
|
||||
val allowApplications: List<String>
|
||||
val disallowApplication: List<String>
|
||||
val allowApplications: Collection<String>
|
||||
val disallowApplication: Collection<String>
|
||||
|
||||
fun onCreateTunFailure()
|
||||
}
|
||||
|
||||
var configure: Configure? = null
|
||||
@@ -32,6 +34,8 @@ class TunModule(private val service: VpnService) : Module() {
|
||||
|
||||
val builder = c.builder
|
||||
|
||||
Log.i("Tun start at ${c.gateway}, mirror at ${c.mirror}")
|
||||
|
||||
parseCIDR(c.gateway).let {
|
||||
builder.addAddress(it.ip, it.prefix)
|
||||
}
|
||||
@@ -62,7 +66,8 @@ class TunModule(private val service: VpnService) : Module() {
|
||||
builder.setMetered(false)
|
||||
}
|
||||
|
||||
val fd = builder.establish() ?: throw NullPointerException("Unable to create vpn")
|
||||
val fd = builder.establish()
|
||||
?: return@withContext c.onCreateTunFailure()
|
||||
|
||||
if (c.dnsHijacking) {
|
||||
Clash.startTunDevice(
|
||||
|
||||
@@ -4,9 +4,7 @@ import android.content.Context
|
||||
import androidx.room.Room
|
||||
import androidx.room.RoomDatabase
|
||||
import com.github.kr328.clash.common.Global
|
||||
import com.github.kr328.clash.service.data.DatabaseMigrations.VERSION_1_2
|
||||
import com.github.kr328.clash.service.data.DatabaseMigrations.VERSION_2_3
|
||||
import com.github.kr328.clash.service.data.DatabaseMigrations.VERSION_3_4
|
||||
import com.github.kr328.clash.service.data.migrations.MIGRATIONS
|
||||
import androidx.room.Database as DatabaseMetadata
|
||||
|
||||
@DatabaseMetadata(
|
||||
@@ -26,7 +24,7 @@ abstract class Database : RoomDatabase() {
|
||||
context.applicationContext,
|
||||
Database::class.java,
|
||||
"clash-config"
|
||||
).addMigrations(VERSION_1_2, VERSION_2_3, VERSION_3_4).build()
|
||||
).addMigrations(*MIGRATIONS).build()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,328 +0,0 @@
|
||||
package com.github.kr328.clash.service.data
|
||||
|
||||
import android.content.ContentValues
|
||||
import android.content.Context
|
||||
import android.database.sqlite.SQLiteDatabase
|
||||
import android.database.sqlite.SQLiteDatabase.CONFLICT_ABORT
|
||||
import android.database.sqlite.SQLiteDatabase.CONFLICT_REPLACE
|
||||
import androidx.core.app.NotificationManagerCompat
|
||||
import androidx.core.content.edit
|
||||
import androidx.core.database.getStringOrNull
|
||||
import androidx.room.migration.Migration
|
||||
import androidx.sqlite.db.SupportSQLiteDatabase
|
||||
import com.github.kr328.clash.common.Global
|
||||
import com.github.kr328.clash.common.utils.Log
|
||||
import com.github.kr328.clash.service.Constants
|
||||
import com.github.kr328.clash.service.settings.ServiceSettings
|
||||
import com.github.kr328.clash.service.util.resolveBaseDir
|
||||
import com.github.kr328.clash.service.util.resolveProfileFile
|
||||
import java.io.File
|
||||
|
||||
object DatabaseMigrations {
|
||||
val VERSION_1_2 = object : Migration(1, 2) {
|
||||
private fun process(database: SupportSQLiteDatabase) {
|
||||
database.execSQL("ALTER TABLE profiles RENAME TO _profiles")
|
||||
database.execSQL("ALTER TABLE profile_select_proxies RENAME TO _profile_select_proxies")
|
||||
|
||||
database.execSQL("CREATE TABLE IF NOT EXISTS `profiles` (`name` TEXT NOT NULL, `type` INTEGER NOT NULL, `uri` TEXT NOT NULL, `source` TEXT, `active` INTEGER NOT NULL, `last_update` INTEGER NOT NULL, `update_interval` INTEGER NOT NULL, `id` INTEGER NOT NULL, PRIMARY KEY(`id`))")
|
||||
database.execSQL("CREATE TABLE IF NOT EXISTS `profile_select_proxies` (`profile_id` INTEGER NOT NULL, `proxy` TEXT NOT NULL, `selected` TEXT NOT NULL, PRIMARY KEY(`profile_id`, `proxy`), FOREIGN KEY(`profile_id`) REFERENCES `profiles`(`id`) ON UPDATE CASCADE ON DELETE CASCADE )")
|
||||
|
||||
database.query("SELECT name, token, file, active, last_update, id FROM _profiles")
|
||||
.use { cursor ->
|
||||
|
||||
Global.application.filesDir.resolve(Constants.CLASH_DIR).listFiles()?.forEach {
|
||||
it.deleteRecursively()
|
||||
}
|
||||
|
||||
cursor.moveToFirst()
|
||||
while (!cursor.isAfterLast) {
|
||||
// old
|
||||
// name, token, file, active, last_update, id
|
||||
val name = cursor.getString(0)
|
||||
val token = cursor.getString(1)
|
||||
val file = cursor.getString(2)
|
||||
val active = cursor.getInt(3)
|
||||
val lastUpdate = cursor.getLong(4)
|
||||
val id = cursor.getLong(5)
|
||||
|
||||
// new
|
||||
// name, type, uri, source, active, last_update, update_interval, id
|
||||
val type = when {
|
||||
token.startsWith("url") -> ProfileEntity.TYPE_URL
|
||||
token.startsWith("file") -> ProfileEntity.TYPE_FILE
|
||||
else -> ProfileEntity.TYPE_UNKNOWN
|
||||
}
|
||||
|
||||
File(file).renameTo(Global.application.resolveProfileFile(id))
|
||||
Global.application.resolveBaseDir(id).mkdirs()
|
||||
|
||||
database.insert("profiles",
|
||||
CONFLICT_ABORT,
|
||||
ContentValues().apply {
|
||||
put("name", name)
|
||||
put("type", type)
|
||||
put("uri", token.removePrefix("url|").removePrefix("file|"))
|
||||
putNull("source")
|
||||
put("active", active)
|
||||
put("last_update", lastUpdate)
|
||||
put("update_interval", 0)
|
||||
put("id", id)
|
||||
})
|
||||
|
||||
cursor.moveToNext()
|
||||
}
|
||||
}
|
||||
|
||||
database.query("SELECT profile_id, proxy, selected FROM _profile_select_proxies ORDER BY id")
|
||||
.use { cursor ->
|
||||
cursor.moveToFirst()
|
||||
while (!cursor.isAfterLast) {
|
||||
// old
|
||||
// profile_id, proxy, selected, id
|
||||
val profileId = cursor.getLong(0)
|
||||
val proxy: String = cursor.getString(1)
|
||||
val selected = cursor.getString(2)
|
||||
|
||||
// new
|
||||
// profile_id, proxy, selected
|
||||
|
||||
database.insert("profile_select_proxies",
|
||||
CONFLICT_REPLACE,
|
||||
ContentValues().apply {
|
||||
put("profile_id", profileId)
|
||||
put("proxy", proxy)
|
||||
put("selected", selected)
|
||||
})
|
||||
|
||||
cursor.moveToNext()
|
||||
}
|
||||
}
|
||||
|
||||
database.execSQL("DROP TABLE IF EXISTS _profiles")
|
||||
database.execSQL("DROP TABLE IF EXISTS _profile_select_proxies")
|
||||
|
||||
// Migration settings
|
||||
val oldSettings = Global.application
|
||||
.getSharedPreferences("clash_service", Context.MODE_PRIVATE)
|
||||
val newSettings = ServiceSettings(
|
||||
Global.application
|
||||
.getSharedPreferences(Constants.SERVICE_SETTING_FILE_NAME, Context.MODE_PRIVATE)
|
||||
)
|
||||
|
||||
val accessMode = oldSettings
|
||||
.getInt("key_access_control_mode", 0)
|
||||
val accessPackages = oldSettings
|
||||
.getStringSet("ley_access_control_apps", emptySet())!! // just typo :)
|
||||
val dnsHijack = oldSettings
|
||||
.getBoolean("key_dns_hijacking_enabled", true)
|
||||
val bypassPrivate = oldSettings
|
||||
.getBoolean("key_bypass_private_network", true)
|
||||
|
||||
oldSettings.edit {
|
||||
clear()
|
||||
}
|
||||
|
||||
newSettings.commit {
|
||||
val newAccessMode = when (accessMode) {
|
||||
0 -> ServiceSettings.ACCESS_CONTROL_MODE_ALL
|
||||
1 -> ServiceSettings.ACCESS_CONTROL_MODE_WHITELIST
|
||||
2 -> ServiceSettings.ACCESS_CONTROL_MODE_BLACKLIST
|
||||
else -> ServiceSettings.ACCESS_CONTROL_MODE_ALL
|
||||
}
|
||||
|
||||
put(ServiceSettings.ACCESS_CONTROL_MODE, newAccessMode)
|
||||
put(ServiceSettings.ACCESS_CONTROL_PACKAGES, accessPackages)
|
||||
put(ServiceSettings.DNS_HIJACKING, dnsHijack)
|
||||
put(ServiceSettings.BYPASS_PRIVATE_NETWORK, bypassPrivate)
|
||||
}
|
||||
}
|
||||
|
||||
override fun migrate(database: SupportSQLiteDatabase) {
|
||||
try {
|
||||
process(database)
|
||||
Log.i("Database Migrated 1 -> 2")
|
||||
} catch (e: Exception) {
|
||||
Log.e("Migration failure", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val VERSION_2_3 = object : Migration(2, 3) {
|
||||
override fun migrate(database: SupportSQLiteDatabase) {
|
||||
try {
|
||||
database.execSQL("ALTER TABLE profile_select_proxies RENAME TO _selected_proxies")
|
||||
database.execSQL("ALTER TABLE profiles RENAME TO _profiles")
|
||||
|
||||
database.execSQL("CREATE TABLE IF NOT EXISTS `profiles` (`name` TEXT NOT NULL, `type` INTEGER NOT NULL, `uri` TEXT NOT NULL, `source` TEXT, `active` INTEGER NOT NULL, `interval` INTEGER NOT NULL, `id` INTEGER NOT NULL, PRIMARY KEY(`id`))")
|
||||
database.execSQL("CREATE TABLE IF NOT EXISTS `selected_proxies` (`profile_id` INTEGER NOT NULL, `proxy` TEXT NOT NULL, `selected` TEXT NOT NULL, PRIMARY KEY(`profile_id`, `proxy`), FOREIGN KEY(`profile_id`) REFERENCES `profiles`(`id`) ON UPDATE CASCADE ON DELETE CASCADE )")
|
||||
|
||||
database.query("SELECT name, type, uri, source, active, update_interval, id FROM _profiles")
|
||||
.use { cursor ->
|
||||
cursor.moveToFirst()
|
||||
while (!cursor.isAfterLast) {
|
||||
// old
|
||||
// name, type, uri, source, active, last_update, update_interval(seconds), id
|
||||
// new
|
||||
// name, type, uri, source, active, interval(millis seconds), id
|
||||
val name = cursor.getString(0)
|
||||
val type = cursor.getInt(1)
|
||||
val uri = cursor.getString(2)
|
||||
val source = cursor.getStringOrNull(3)
|
||||
val active = cursor.getInt(4)
|
||||
val interval = cursor.getLong(5)
|
||||
val id = cursor.getLong(6)
|
||||
|
||||
database.insert("profiles",
|
||||
CONFLICT_ABORT,
|
||||
ContentValues().apply {
|
||||
put("name", name)
|
||||
put("type", type)
|
||||
put("uri", uri)
|
||||
put("source", source)
|
||||
put("active", active)
|
||||
put("interval", interval * 1000)
|
||||
put("id", id)
|
||||
})
|
||||
|
||||
cursor.moveToNext()
|
||||
}
|
||||
}
|
||||
|
||||
database.query("SELECT profile_id, proxy, selected FROM _selected_proxies")
|
||||
.use { cursor ->
|
||||
cursor.moveToFirst()
|
||||
while (!cursor.isAfterLast) {
|
||||
// just copy
|
||||
// profile_id, proxy, selected
|
||||
val profileId = cursor.getLong(0)
|
||||
val proxy = cursor.getString(1)
|
||||
val selected = cursor.getString(2)
|
||||
|
||||
database.insert("selected_proxies",
|
||||
CONFLICT_REPLACE,
|
||||
ContentValues().apply {
|
||||
put("profile_id", profileId)
|
||||
put("proxy", proxy)
|
||||
put("selected", selected)
|
||||
})
|
||||
|
||||
cursor.moveToNext()
|
||||
}
|
||||
}
|
||||
|
||||
database.execSQL("DROP TABLE IF EXISTS _profiles")
|
||||
database.execSQL("DROP TABLE IF EXISTS _selected_proxies")
|
||||
|
||||
val uiSp = Global.application
|
||||
.getSharedPreferences("ui", Context.MODE_PRIVATE)
|
||||
val srvSp = Global.application
|
||||
.getSharedPreferences("service", Context.MODE_PRIVATE)
|
||||
|
||||
srvSp.edit {
|
||||
putBoolean("enable_vpn", uiSp.getBoolean("enable_vpn", true))
|
||||
}
|
||||
|
||||
NotificationManagerCompat.from(Global.application).apply {
|
||||
deleteNotificationChannel("clash_status_channel")
|
||||
deleteNotificationChannel("profile_service_status")
|
||||
deleteNotificationChannel("profile_service_result")
|
||||
}
|
||||
|
||||
Log.i("Database Migrated 2 -> 3")
|
||||
} catch (e: Exception) {
|
||||
Log.e("Migration failure", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val VERSION_3_4 = object : Migration(3, 4) {
|
||||
override fun migrate(database: SupportSQLiteDatabase) {
|
||||
try {
|
||||
val profiles = mutableListOf<ProfileEntity>()
|
||||
try {
|
||||
database.query("SELECT name, type, uri, source, active, interval, id FROM profiles")
|
||||
.use { cursor ->
|
||||
cursor.moveToFirst()
|
||||
while (!cursor.isAfterLast) {
|
||||
// old
|
||||
// name, type, uri, source, active, last_update, update_interval(seconds), id
|
||||
// new
|
||||
// name, type, uri, source, active, interval(millis seconds), id
|
||||
val name = cursor.getString(0)
|
||||
val type = cursor.getInt(1)
|
||||
val uri = cursor.getString(2)
|
||||
val source = cursor.getStringOrNull(3)
|
||||
val active = cursor.getInt(4)
|
||||
val interval = cursor.getLong(5)
|
||||
val id = cursor.getLong(6)
|
||||
|
||||
profiles.add(ProfileEntity(name, type, uri, source, active != 0, interval, id))
|
||||
|
||||
cursor.moveToNext()
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (e: Exception) {
|
||||
Log.w("Query old data failure", e)
|
||||
}
|
||||
|
||||
val selectedProxies = mutableListOf<SelectedProxyEntity>()
|
||||
|
||||
try {
|
||||
database.query("SELECT profile_id, proxy, selected FROM selected_proxies")
|
||||
.use { cursor ->
|
||||
cursor.moveToFirst()
|
||||
while (!cursor.isAfterLast) {
|
||||
// just copy
|
||||
// profile_id, proxy, selected
|
||||
val profileId = cursor.getLong(0)
|
||||
val proxy = cursor.getString(1)
|
||||
val selected = cursor.getString(2)
|
||||
|
||||
selectedProxies.add(SelectedProxyEntity(profileId, proxy, selected))
|
||||
|
||||
cursor.moveToNext()
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (e: Exception) {
|
||||
Log.w("Query old data failure", e)
|
||||
}
|
||||
|
||||
database.execSQL("DROP TABLE IF EXISTS profile_select_proxies")
|
||||
database.execSQL("DROP TABLE IF EXISTS selected_proxies")
|
||||
database.execSQL("DROP TABLE IF EXISTS profiles")
|
||||
database.execSQL("DROP TABLE IF EXISTS _profile_select_proxies")
|
||||
database.execSQL("DROP TABLE IF EXISTS _selected_proxies")
|
||||
database.execSQL("DROP TABLE IF EXISTS _profiles")
|
||||
|
||||
database.execSQL("CREATE TABLE IF NOT EXISTS `profiles` (`name` TEXT NOT NULL, `type` INTEGER NOT NULL, `uri` TEXT NOT NULL, `source` TEXT, `active` INTEGER NOT NULL, `interval` INTEGER NOT NULL, `id` INTEGER NOT NULL, PRIMARY KEY(`id`))")
|
||||
database.execSQL("CREATE TABLE IF NOT EXISTS `selected_proxies` (`profile_id` INTEGER NOT NULL, `proxy` TEXT NOT NULL, `selected` TEXT NOT NULL, PRIMARY KEY(`profile_id`, `proxy`), FOREIGN KEY(`profile_id`) REFERENCES `profiles`(`id`) ON UPDATE CASCADE ON DELETE CASCADE )")
|
||||
|
||||
profiles.forEach {
|
||||
database.insert("profiles", CONFLICT_ABORT, ContentValues().apply {
|
||||
put("name", it.name)
|
||||
put("type", it.type)
|
||||
put("uri", it.uri)
|
||||
put("source", it.source)
|
||||
put("active", it.active)
|
||||
put("interval", it.interval)
|
||||
put("id", it.id)
|
||||
})
|
||||
}
|
||||
|
||||
selectedProxies.forEach {
|
||||
database.insert("selected_proxies", CONFLICT_REPLACE, ContentValues().apply {
|
||||
put("profile_id", it.profileId)
|
||||
put("proxy", it.proxy)
|
||||
put("selected", it.selected)
|
||||
})
|
||||
}
|
||||
|
||||
Log.i("Database Migrated 3 -> 4")
|
||||
} catch (e: Exception) {
|
||||
Log.e("Migration failure", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package com.github.kr328.clash.service.data.migrations
|
||||
|
||||
import android.content.ContentValues
|
||||
import android.content.Context
|
||||
import android.database.sqlite.SQLiteDatabase
|
||||
import androidx.core.content.edit
|
||||
import androidx.room.migration.Migration
|
||||
import androidx.sqlite.db.SupportSQLiteDatabase
|
||||
import com.github.kr328.clash.common.Global
|
||||
import com.github.kr328.clash.common.utils.Log
|
||||
import com.github.kr328.clash.service.Constants
|
||||
import com.github.kr328.clash.service.data.ProfileEntity
|
||||
import com.github.kr328.clash.service.settings.ServiceSettings
|
||||
import com.github.kr328.clash.service.util.resolveBaseDir
|
||||
import com.github.kr328.clash.service.util.resolveProfileFile
|
||||
import java.io.File
|
||||
|
||||
object Migration12: Migration(1, 2) {
|
||||
private fun process(database: SupportSQLiteDatabase) {
|
||||
database.execSQL("ALTER TABLE profiles RENAME TO _profiles")
|
||||
database.execSQL("ALTER TABLE profile_select_proxies RENAME TO _profile_select_proxies")
|
||||
|
||||
database.execSQL("CREATE TABLE IF NOT EXISTS `profiles` (`name` TEXT NOT NULL, `type` INTEGER NOT NULL, `uri` TEXT NOT NULL, `source` TEXT, `active` INTEGER NOT NULL, `last_update` INTEGER NOT NULL, `update_interval` INTEGER NOT NULL, `id` INTEGER NOT NULL, PRIMARY KEY(`id`))")
|
||||
database.execSQL("CREATE TABLE IF NOT EXISTS `profile_select_proxies` (`profile_id` INTEGER NOT NULL, `proxy` TEXT NOT NULL, `selected` TEXT NOT NULL, PRIMARY KEY(`profile_id`, `proxy`), FOREIGN KEY(`profile_id`) REFERENCES `profiles`(`id`) ON UPDATE CASCADE ON DELETE CASCADE )")
|
||||
|
||||
database.query("SELECT name, token, file, active, last_update, id FROM _profiles")
|
||||
.use { cursor ->
|
||||
|
||||
Global.application.filesDir.resolve(Constants.CLASH_DIR).listFiles()?.forEach {
|
||||
it.deleteRecursively()
|
||||
}
|
||||
|
||||
cursor.moveToFirst()
|
||||
while (!cursor.isAfterLast) {
|
||||
// old
|
||||
// name, token, file, active, last_update, id
|
||||
val name = cursor.getString(0)
|
||||
val token = cursor.getString(1)
|
||||
val file = cursor.getString(2)
|
||||
val active = cursor.getInt(3)
|
||||
val lastUpdate = cursor.getLong(4)
|
||||
val id = cursor.getLong(5)
|
||||
|
||||
// new
|
||||
// name, type, uri, source, active, last_update, update_interval, id
|
||||
val type = when {
|
||||
token.startsWith("url") -> ProfileEntity.TYPE_URL
|
||||
token.startsWith("file") -> ProfileEntity.TYPE_FILE
|
||||
else -> ProfileEntity.TYPE_UNKNOWN
|
||||
}
|
||||
|
||||
File(file).renameTo(Global.application.resolveProfileFile(id))
|
||||
Global.application.resolveBaseDir(id).mkdirs()
|
||||
|
||||
database.insert("profiles",
|
||||
SQLiteDatabase.CONFLICT_ABORT,
|
||||
ContentValues().apply {
|
||||
put("name", name)
|
||||
put("type", type)
|
||||
put("uri", token.removePrefix("url|").removePrefix("file|"))
|
||||
putNull("source")
|
||||
put("active", active)
|
||||
put("last_update", lastUpdate)
|
||||
put("update_interval", 0)
|
||||
put("id", id)
|
||||
})
|
||||
|
||||
cursor.moveToNext()
|
||||
}
|
||||
}
|
||||
|
||||
database.query("SELECT profile_id, proxy, selected FROM _profile_select_proxies ORDER BY id")
|
||||
.use { cursor ->
|
||||
cursor.moveToFirst()
|
||||
while (!cursor.isAfterLast) {
|
||||
// old
|
||||
// profile_id, proxy, selected, id
|
||||
val profileId = cursor.getLong(0)
|
||||
val proxy: String = cursor.getString(1)
|
||||
val selected = cursor.getString(2)
|
||||
|
||||
// new
|
||||
// profile_id, proxy, selected
|
||||
|
||||
database.insert("profile_select_proxies",
|
||||
SQLiteDatabase.CONFLICT_REPLACE,
|
||||
ContentValues().apply {
|
||||
put("profile_id", profileId)
|
||||
put("proxy", proxy)
|
||||
put("selected", selected)
|
||||
})
|
||||
|
||||
cursor.moveToNext()
|
||||
}
|
||||
}
|
||||
|
||||
database.execSQL("DROP TABLE IF EXISTS _profiles")
|
||||
database.execSQL("DROP TABLE IF EXISTS _profile_select_proxies")
|
||||
|
||||
// Migration settings
|
||||
val oldSettings = Global.application
|
||||
.getSharedPreferences("clash_service", Context.MODE_PRIVATE)
|
||||
val newSettings = ServiceSettings(
|
||||
Global.application
|
||||
.getSharedPreferences(Constants.SERVICE_SETTING_FILE_NAME, Context.MODE_PRIVATE)
|
||||
)
|
||||
|
||||
val accessMode = oldSettings
|
||||
.getInt("key_access_control_mode", 0)
|
||||
val accessPackages = oldSettings
|
||||
.getStringSet("ley_access_control_apps", emptySet())!! // just typo :)
|
||||
val dnsHijack = oldSettings
|
||||
.getBoolean("key_dns_hijacking_enabled", true)
|
||||
val bypassPrivate = oldSettings
|
||||
.getBoolean("key_bypass_private_network", true)
|
||||
|
||||
oldSettings.edit {
|
||||
clear()
|
||||
}
|
||||
|
||||
newSettings.commit {
|
||||
val newAccessMode = when (accessMode) {
|
||||
0 -> ServiceSettings.ACCESS_CONTROL_MODE_ALL
|
||||
1 -> ServiceSettings.ACCESS_CONTROL_MODE_WHITELIST
|
||||
2 -> ServiceSettings.ACCESS_CONTROL_MODE_BLACKLIST
|
||||
else -> ServiceSettings.ACCESS_CONTROL_MODE_ALL
|
||||
}
|
||||
|
||||
put(ServiceSettings.ACCESS_CONTROL_MODE, newAccessMode)
|
||||
put(ServiceSettings.ACCESS_CONTROL_PACKAGES, accessPackages)
|
||||
put(ServiceSettings.DNS_HIJACKING, dnsHijack)
|
||||
put(ServiceSettings.BYPASS_PRIVATE_NETWORK, bypassPrivate)
|
||||
}
|
||||
}
|
||||
|
||||
override fun migrate(database: SupportSQLiteDatabase) {
|
||||
try {
|
||||
process(database)
|
||||
Log.i("Database Migrated 1 -> 2")
|
||||
} catch (e: Exception) {
|
||||
Log.e("Migration failure", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package com.github.kr328.clash.service.data.migrations
|
||||
|
||||
import android.content.ContentValues
|
||||
import android.content.Context
|
||||
import android.database.sqlite.SQLiteDatabase
|
||||
import androidx.core.app.NotificationManagerCompat
|
||||
import androidx.core.content.edit
|
||||
import androidx.core.database.getStringOrNull
|
||||
import androidx.room.migration.Migration
|
||||
import androidx.sqlite.db.SupportSQLiteDatabase
|
||||
import com.github.kr328.clash.common.Global
|
||||
import com.github.kr328.clash.common.utils.Log
|
||||
|
||||
object Migration23: Migration(2, 3) {
|
||||
override fun migrate(database: SupportSQLiteDatabase) {
|
||||
try {
|
||||
database.execSQL("ALTER TABLE profile_select_proxies RENAME TO _selected_proxies")
|
||||
database.execSQL("ALTER TABLE profiles RENAME TO _profiles")
|
||||
|
||||
database.execSQL("CREATE TABLE IF NOT EXISTS `profiles` (`name` TEXT NOT NULL, `type` INTEGER NOT NULL, `uri` TEXT NOT NULL, `source` TEXT, `active` INTEGER NOT NULL, `interval` INTEGER NOT NULL, `id` INTEGER NOT NULL, PRIMARY KEY(`id`))")
|
||||
database.execSQL("CREATE TABLE IF NOT EXISTS `selected_proxies` (`profile_id` INTEGER NOT NULL, `proxy` TEXT NOT NULL, `selected` TEXT NOT NULL, PRIMARY KEY(`profile_id`, `proxy`), FOREIGN KEY(`profile_id`) REFERENCES `profiles`(`id`) ON UPDATE CASCADE ON DELETE CASCADE )")
|
||||
|
||||
database.query("SELECT name, type, uri, source, active, update_interval, id FROM _profiles")
|
||||
.use { cursor ->
|
||||
cursor.moveToFirst()
|
||||
while (!cursor.isAfterLast) {
|
||||
// old
|
||||
// name, type, uri, source, active, last_update, update_interval(seconds), id
|
||||
// new
|
||||
// name, type, uri, source, active, interval(millis seconds), id
|
||||
val name = cursor.getString(0)
|
||||
val type = cursor.getInt(1)
|
||||
val uri = cursor.getString(2)
|
||||
val source = cursor.getStringOrNull(3)
|
||||
val active = cursor.getInt(4)
|
||||
val interval = cursor.getLong(5)
|
||||
val id = cursor.getLong(6)
|
||||
|
||||
database.insert("profiles",
|
||||
SQLiteDatabase.CONFLICT_ABORT,
|
||||
ContentValues().apply {
|
||||
put("name", name)
|
||||
put("type", type)
|
||||
put("uri", uri)
|
||||
put("source", source)
|
||||
put("active", active)
|
||||
put("interval", interval * 1000)
|
||||
put("id", id)
|
||||
})
|
||||
|
||||
cursor.moveToNext()
|
||||
}
|
||||
}
|
||||
|
||||
database.query("SELECT profile_id, proxy, selected FROM _selected_proxies")
|
||||
.use { cursor ->
|
||||
cursor.moveToFirst()
|
||||
while (!cursor.isAfterLast) {
|
||||
// just copy
|
||||
// profile_id, proxy, selected
|
||||
val profileId = cursor.getLong(0)
|
||||
val proxy = cursor.getString(1)
|
||||
val selected = cursor.getString(2)
|
||||
|
||||
database.insert("selected_proxies",
|
||||
SQLiteDatabase.CONFLICT_REPLACE,
|
||||
ContentValues().apply {
|
||||
put("profile_id", profileId)
|
||||
put("proxy", proxy)
|
||||
put("selected", selected)
|
||||
})
|
||||
|
||||
cursor.moveToNext()
|
||||
}
|
||||
}
|
||||
|
||||
database.execSQL("DROP TABLE IF EXISTS _profiles")
|
||||
database.execSQL("DROP TABLE IF EXISTS _selected_proxies")
|
||||
|
||||
val uiSp = Global.application
|
||||
.getSharedPreferences("ui", Context.MODE_PRIVATE)
|
||||
val srvSp = Global.application
|
||||
.getSharedPreferences("service", Context.MODE_PRIVATE)
|
||||
|
||||
srvSp.edit {
|
||||
putBoolean("enable_vpn", uiSp.getBoolean("enable_vpn", true))
|
||||
}
|
||||
|
||||
NotificationManagerCompat.from(Global.application).apply {
|
||||
deleteNotificationChannel("profile_service_status")
|
||||
deleteNotificationChannel("profile_service_result")
|
||||
}
|
||||
|
||||
Log.i("Database Migrated 2 -> 3")
|
||||
} catch (e: Exception) {
|
||||
Log.e("Migration failure", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package com.github.kr328.clash.service.data.migrations
|
||||
|
||||
import android.content.ContentValues
|
||||
import android.database.sqlite.SQLiteDatabase
|
||||
import androidx.core.database.getStringOrNull
|
||||
import androidx.room.migration.Migration
|
||||
import androidx.sqlite.db.SupportSQLiteDatabase
|
||||
import com.github.kr328.clash.common.utils.Log
|
||||
import com.github.kr328.clash.service.data.ProfileEntity
|
||||
import com.github.kr328.clash.service.data.SelectedProxyEntity
|
||||
|
||||
object Migration34: Migration(3, 4) {
|
||||
override fun migrate(database: SupportSQLiteDatabase) {
|
||||
try {
|
||||
val profiles = mutableListOf<ProfileEntity>()
|
||||
try {
|
||||
database.query("SELECT name, type, uri, source, active, interval, id FROM profiles")
|
||||
.use { cursor ->
|
||||
cursor.moveToFirst()
|
||||
while (!cursor.isAfterLast) {
|
||||
// old
|
||||
// name, type, uri, source, active, last_update, update_interval(seconds), id
|
||||
// new
|
||||
// name, type, uri, source, active, interval(millis seconds), id
|
||||
val name = cursor.getString(0)
|
||||
val type = cursor.getInt(1)
|
||||
val uri = cursor.getString(2)
|
||||
val source = cursor.getStringOrNull(3)
|
||||
val active = cursor.getInt(4)
|
||||
val interval = cursor.getLong(5)
|
||||
val id = cursor.getLong(6)
|
||||
|
||||
profiles.add(ProfileEntity(name, type, uri, source, active != 0, interval, id))
|
||||
|
||||
cursor.moveToNext()
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (e: Exception) {
|
||||
Log.w("Query old data failure", e)
|
||||
}
|
||||
|
||||
val selectedProxies = mutableListOf<SelectedProxyEntity>()
|
||||
|
||||
try {
|
||||
database.query("SELECT profile_id, proxy, selected FROM selected_proxies")
|
||||
.use { cursor ->
|
||||
cursor.moveToFirst()
|
||||
while (!cursor.isAfterLast) {
|
||||
// just copy
|
||||
// profile_id, proxy, selected
|
||||
val profileId = cursor.getLong(0)
|
||||
val proxy = cursor.getString(1)
|
||||
val selected = cursor.getString(2)
|
||||
|
||||
selectedProxies.add(SelectedProxyEntity(profileId, proxy, selected))
|
||||
|
||||
cursor.moveToNext()
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (e: Exception) {
|
||||
Log.w("Query old data failure", e)
|
||||
}
|
||||
|
||||
// Clean up database
|
||||
runCatching {
|
||||
database.execSQL("DROP TABLE IF EXISTS profile_select_proxies")
|
||||
database.execSQL("DROP TABLE IF EXISTS selected_proxies")
|
||||
database.execSQL("DROP TABLE IF EXISTS profiles")
|
||||
database.execSQL("DROP TABLE IF EXISTS _profile_select_proxies")
|
||||
database.execSQL("DROP TABLE IF EXISTS _selected_proxies")
|
||||
database.execSQL("DROP TABLE IF EXISTS _profiles")
|
||||
}
|
||||
runCatching {
|
||||
database.execSQL("DROP TABLE IF EXISTS profile_select_proxies")
|
||||
database.execSQL("DROP TABLE IF EXISTS selected_proxies")
|
||||
database.execSQL("DROP TABLE IF EXISTS profiles")
|
||||
database.execSQL("DROP TABLE IF EXISTS _profile_select_proxies")
|
||||
database.execSQL("DROP TABLE IF EXISTS _selected_proxies")
|
||||
database.execSQL("DROP TABLE IF EXISTS _profiles")
|
||||
}
|
||||
|
||||
database.execSQL("CREATE TABLE IF NOT EXISTS `profiles` (`name` TEXT NOT NULL, `type` INTEGER NOT NULL, `uri` TEXT NOT NULL, `source` TEXT, `active` INTEGER NOT NULL, `interval` INTEGER NOT NULL, `id` INTEGER NOT NULL, PRIMARY KEY(`id`))")
|
||||
database.execSQL("CREATE TABLE IF NOT EXISTS `selected_proxies` (`profile_id` INTEGER NOT NULL, `proxy` TEXT NOT NULL, `selected` TEXT NOT NULL, PRIMARY KEY(`profile_id`, `proxy`), FOREIGN KEY(`profile_id`) REFERENCES `profiles`(`id`) ON UPDATE CASCADE ON DELETE CASCADE )")
|
||||
|
||||
profiles.forEach {
|
||||
database.insert("profiles", SQLiteDatabase.CONFLICT_ABORT, ContentValues().apply {
|
||||
put("name", it.name)
|
||||
put("type", it.type)
|
||||
put("uri", it.uri)
|
||||
put("source", it.source)
|
||||
put("active", it.active)
|
||||
put("interval", it.interval)
|
||||
put("id", it.id)
|
||||
})
|
||||
}
|
||||
|
||||
selectedProxies.forEach {
|
||||
database.insert("selected_proxies",
|
||||
SQLiteDatabase.CONFLICT_REPLACE, ContentValues().apply {
|
||||
put("profile_id", it.profileId)
|
||||
put("proxy", it.proxy)
|
||||
put("selected", it.selected)
|
||||
})
|
||||
}
|
||||
|
||||
Log.i("Database Migrated 3 -> 4")
|
||||
} catch (e: Exception) {
|
||||
Log.e("Migration failure", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.github.kr328.clash.service.data.migrations
|
||||
|
||||
import androidx.room.migration.Migration
|
||||
|
||||
val MIGRATIONS: Array<Migration> = arrayOf(Migration12, Migration23, Migration34)
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.github.kr328.clash.service.util
|
||||
|
||||
import android.os.Process
|
||||
|
||||
object UserUtils {
|
||||
private const val PER_USER_RANGE: Int = 100000
|
||||
|
||||
val currentUserId: Int
|
||||
get() = Process.myUid() / PER_USER_RANGE
|
||||
}
|
||||
Reference in new issue
Block a user