Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,11 @@
android:configChanges="uiMode"
android:exported="false"
android:label="@string/meta_features" />
<activity
android:name=".WebDavSettingsActivity"
android:configChanges="uiMode"
android:exported="false"
android:label="@string/webdav_sync" />
<activity
android:name=".AccessControlActivity"
android:configChanges="uiMode"
Expand Down
2 changes: 2 additions & 0 deletions app/src/main/java/com/github/kr328/clash/SettingsActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ class SettingsActivity : BaseActivity<SettingsDesign>() {
startActivity(OverrideSettingsActivity::class.intent)
SettingsDesign.Request.StartMetaFeature ->
startActivity(MetaFeatureSettingsActivity::class.intent)
SettingsDesign.Request.StartWebDav ->
startActivity(WebDavSettingsActivity::class.intent)
}
}
}
Expand Down
131 changes: 131 additions & 0 deletions app/src/main/java/com/github/kr328/clash/WebDavSettingsActivity.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
package com.github.kr328.clash

import com.github.kr328.clash.common.log.Log
import com.github.kr328.clash.common.util.VergeBackup
import com.github.kr328.clash.common.util.WebDavClient
import com.github.kr328.clash.design.R
import com.github.kr328.clash.design.WebDavSettingsDesign
import com.github.kr328.clash.design.store.UiStore
import com.github.kr328.clash.service.model.Profile
import com.github.kr328.clash.util.withProfile
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.isActive
import kotlinx.coroutines.selects.select
import kotlinx.coroutines.withContext
import java.io.FileNotFoundException

class WebDavSettingsActivity : BaseActivity<WebDavSettingsDesign>() {
override suspend fun main() {
val uiStore = UiStore(this)
val design = WebDavSettingsDesign(this, uiStore)

setContentDesign(design)

while (isActive) {
select<Unit> {
events.onReceive {
}
design.requests.onReceive {
when (it) {
WebDavSettingsDesign.Request.Sync -> sync(uiStore, design)
}
}
}
}
}

private suspend fun sync(uiStore: UiStore, design: WebDavSettingsDesign) {
val url = uiStore.webdavUrl.trim()

if (url.isEmpty()) {
design.showSyncFailed(getString(R.string.webdav_not_configured))
return
}

design.setSyncing(true)

try {
val client = WebDavClient(
url,
uiStore.webdavUsername.trim(),
uiStore.webdavPassword.trim()
)

val latest = withContext(Dispatchers.IO) { listLatestBackup(client) }
?: throw FileNotFoundException(getString(R.string.webdav_no_backup))

val zip = withContext(Dispatchers.IO) { client.download(latest) }

val remoteProfiles = withContext(Dispatchers.IO) { VergeBackup.parseRemoteProfiles(zip) }

if (remoteProfiles.isEmpty()) {
throw FileNotFoundException(getString(R.string.webdav_no_subscription))
}

val existing = withProfile { queryAll() }

var updated = 0
var created = 0
var failed = 0

for (remote in remoteProfiles) {
val match = existing.firstOrNull { it.name == remote.name }

try {
if (match != null) {
withProfile {
patch(match.uuid, remote.name, remote.url, match.interval, match.ageSecretKey)
}

try {
withProfile { commit(match.uuid) }
updated++
} catch (e: Exception) {
runCatching { withProfile { release(match.uuid) } }
throw e
}
} else {
val uuid = withProfile {
create(Profile.Type.Url, remote.name, remote.url, null)
}

try {
withProfile { commit(uuid) }
created++
} catch (e: Exception) {
runCatching { withProfile { delete(uuid) } }
throw e
}
}
} catch (e: Exception) {
failed++

Log.w("Sync profile ${remote.name} failed", e)
}
}

uiStore.webdavLastSync = (System.currentTimeMillis() / 1000).toInt()

design.showSyncResult(updated, created, failed)
} catch (e: Exception) {
Log.w("WebDAV sync failed", e)

design.showSyncFailed(e.message ?: e.javaClass.simpleName)
} finally {
design.setSyncing(false)
}
}

// Verge stores backups in a "clash-verge-rev-backup" subdirectory under the
// configured WebDAV URL; fall back to it when the URL itself has no backups
private fun listLatestBackup(client: WebDavClient): String? {
val root = runCatching { client.listBackupFiles() }

val files = root.getOrDefault(emptyList()).ifEmpty {
runCatching { client.listBackupFiles(VergeBackup.BACKUP_DIR) }
.getOrElse { root.getOrThrow() }
}

return files.lastOrNull()
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package com.github.kr328.clash.common.util

import java.io.ByteArrayInputStream
import java.io.FileNotFoundException
import java.util.zip.ZipInputStream

data class VergeProfile(
val name: String,
val url: String,
)

object VergeBackup {
// Directory Verge creates under the configured WebDAV URL to store backups
// (clash-verge-rev/src-tauri/src/utils/dirs.rs BACKUP_DIR)
const val BACKUP_DIR = "clash-verge-rev-backup"

fun parseRemoteProfiles(zip: ByteArray): List<VergeProfile> {
ZipInputStream(ByteArrayInputStream(zip)).use { stream ->
while (true) {
val entry = stream.nextEntry ?: break

if (entry.name == "profiles.yaml") {
return parseProfilesYaml(stream.readBytes().decodeToString())
}
}
}

throw FileNotFoundException("profiles.yaml not found in backup")
}

internal fun parseProfilesYaml(text: String): List<VergeProfile> {
val profiles = mutableListOf<VergeProfile>()

var inItems = false
var type: String? = null
var name: String? = null
var url: String? = null

fun unquote(value: String): String {
return value.trim()
.removeSurrounding("\"")
.removeSurrounding("'")
}

fun flush() {
val n = name
val u = url

if (type == "remote" && !n.isNullOrEmpty() && !u.isNullOrEmpty()) {
profiles.add(VergeProfile(n, u))
}

type = null
name = null
url = null
}

for (line in text.lines()) {
val trimmed = line.trim()

when {
!inItems && line.trimEnd() == "items:" -> inItems = true

inItems && trimmed.startsWith("- ") -> {
flush()

val kv = trimmed.removePrefix("- ")
when {
kv.startsWith("type:") -> type = unquote(kv.removePrefix("type:"))
kv.startsWith("name:") -> name = unquote(kv.removePrefix("name:")).takeIf { it != "null" }
kv.startsWith("url:") -> url = unquote(kv.removePrefix("url:"))
}
}

inItems && line.startsWith(" ") -> when {
trimmed.startsWith("type:") -> type = unquote(trimmed.removePrefix("type:"))
trimmed.startsWith("name:") -> name = unquote(trimmed.removePrefix("name:")).takeIf { it != "null" }
trimmed.startsWith("url:") -> url = unquote(trimmed.removePrefix("url:"))
}

inItems -> {
flush()
inItems = false
}
}
}

flush()

return profiles
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
package com.github.kr328.clash.common.util

import android.util.Base64
import java.io.IOException
import java.net.HttpURLConnection
import java.net.Socket
import java.net.URL
import java.net.URLDecoder
import javax.net.ssl.HttpsURLConnection
import javax.net.ssl.SSLSocket
import javax.net.ssl.SSLSocketFactory

class WebDavClient(
private val baseUrl: String,
private val username: String,
private val password: String,
) {
private fun basicAuthorization(): String {
val token = Base64.encodeToString("$username:$password".toByteArray(), Base64.NO_WRAP)

return "Basic $token"
}

// HttpURLConnection cannot send WebDAV extension methods: setRequestMethod
// rejects PROPFIND and no reflection hack survives OEM HttpURLConnection
// implementations (verified on-device: the request went out as GET, which
// jianguoyun answers with 403). Send PROPFIND over a plain socket instead.
private fun propfind(url: URL): String {
val port = url.port.takeIf { it != -1 } ?: url.defaultPort
val requestPath = url.path

val socket: Socket = if (url.protocol == "https") {
SSLSocketFactory.getDefault().createSocket(url.host, port) as SSLSocket
} else {
Socket(url.host, port)
}

socket.soTimeout = 30_000

socket.use { s ->
if (s is SSLSocket) {
s.startHandshake()

if (!HttpsURLConnection.getDefaultHostnameVerifier().verify(url.host, s.session)) {
throw IOException("hostname mismatch: ${url.host}")
}
}

val host = url.host + (if (port == url.defaultPort) "" else ":$port")

val request = buildString {
append("PROPFIND ").append(requestPath).append(" HTTP/1.1\r\n")
append("Host: ").append(host).append("\r\n")
append("Authorization: ").append(basicAuthorization()).append("\r\n")
append("Depth: 1\r\n")
append("Content-Length: 0\r\n")
append("Connection: close\r\n")
append("\r\n")
}

s.getOutputStream().apply {
write(request.toByteArray())
flush()
}

val response = s.getInputStream().readBytes().decodeToString()
val status = response.substringBefore("\r\n")
val code = status.split(" ").getOrNull(1)?.toIntOrNull()
?: throw IOException("malformed response: ${status.take(60)}")

if (code != 207) {
val body = response.substringAfter("\r\n\r\n", "")

throw IOException(
if (body.isBlank()) "HTTP $code" else "HTTP $code: ${body.take(200)}"
)
}

return response.substringAfter("\r\n\r\n", "")
}
}

private fun open(path: String): HttpURLConnection {
val url = baseUrl.trimEnd('/') + "/" + path.trimStart('/')

val connection = URL(url).openConnection() as HttpURLConnection
connection.requestMethod = "GET"
connection.connectTimeout = 15_000
connection.readTimeout = 60_000
connection.setRequestProperty("User-Agent", "ClashMetaForAndroid")
connection.setRequestProperty("Authorization", basicAuthorization())

return connection
}

fun listBackupFiles(path: String = ""): List<String> {
val dir = path.trim('/')
val url = URL(baseUrl.trimEnd('/') + (if (dir.isEmpty()) "/" else "/$dir/"))
val xml = propfind(url)

val basePath = url.path.trimEnd('/')
val prefix = if (dir.isEmpty()) "" else "$dir/"

val hrefRegex = Regex("<(?:[A-Za-z]+:)?href[^>]*>([^<]+)</(?:[A-Za-z]+:)?href>")

return hrefRegex.findAll(xml)
.mapNotNull { match ->
val href = URLDecoder.decode(match.groupValues[1], "UTF-8")

if (href.trimEnd('/') == basePath)
return@mapNotNull null // the directory itself

val name = href.trimEnd('/').removePrefix(basePath).trim('/')

name.takeIf { it.isNotEmpty() }?.let { prefix + it }
}
.filter { it.contains("-backup-") && it.endsWith(".zip") }
.distinct()
.sorted()
.toList()
}

fun download(path: String): ByteArray {
val connection = open(path)

return try {
val code = connection.responseCode

if (code !in 200..299) {
throw IOException("HTTP $code")
}

connection.inputStream.use { it.readBytes() }
} finally {
connection.disconnect()
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import com.github.kr328.clash.design.util.root

class SettingsDesign(context: Context) : Design<SettingsDesign.Request>(context) {
enum class Request {
StartApp, StartNetwork, StartOverride, StartMetaFeature,
StartApp, StartNetwork, StartOverride, StartMetaFeature, StartWebDav,
}

private val binding = DesignSettingsBinding
Expand Down
Loading