Skip to content

Commit

Permalink
Added wireguard regular config parsing feature, which we discussed on…
Browse files Browse the repository at this point in the history
… issue #3497 (#3521)
  • Loading branch information
CodeWithTamim committed Aug 29, 2024
1 parent a15ab47 commit fa341c9
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -517,6 +517,13 @@ object AngConfigManager {
val key = MmkvManager.encodeServerConfig("", config)
serverRawStorage?.encode(key, server)
return 1
} else if (server.startsWith("[Interface]") && server.contains("[Peer]")) {
val config = WireguardFmt.parseWireguardConfFile(server)
?: return R.string.toast_incorrect_protocol
config.fullConfig?.remarks ?: System.currentTimeMillis().toString()
val key = MmkvManager.encodeServerConfig("", config)
serverRawStorage?.encode(key, server)
return 1
} else {
return 0
}
Expand Down
34 changes: 34 additions & 0 deletions V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/fmt/WireguardFmt.kt
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,40 @@ object WireguardFmt {
}
}

fun parseWireguardConfFile(str: String): ServerConfig? {
val config = ServerConfig.create(EConfigType.WIREGUARD)
val queryParam: MutableMap<String, String> = mutableMapOf()

var currentSection: String? = null

str.lines().forEach { line ->
val trimmedLine = line.trim()

when {
trimmedLine.startsWith("[Interface]", ignoreCase = true) -> currentSection = "Interface"
trimmedLine.startsWith("[Peer]", ignoreCase = true) -> currentSection = "Peer"
trimmedLine.isBlank() || trimmedLine.startsWith("#") -> Unit // Skip blank lines or comments
currentSection != null -> {
val (key, value) = trimmedLine.split("=").map { it.trim() }
queryParam[key.lowercase()] = value // Store the key in lowercase for case-insensitivity
}
}
}

config.outboundBean?.settings?.let { wireguard ->
wireguard.secretKey = queryParam["privatekey"].orEmpty()
wireguard.address = (queryParam["address"] ?: AppConfig.WIREGUARD_LOCAL_ADDRESS_V4).removeWhiteSpace().split(",")
wireguard.peers?.getOrNull(0)?.publicKey = queryParam["publickey"].orEmpty()
wireguard.peers?.getOrNull(0)?.endpoint = queryParam["endpoint"].orEmpty()
wireguard.mtu = Utils.parseInt(queryParam["mtu"] ?: AppConfig.WIREGUARD_LOCAL_MTU)
wireguard.reserved = (queryParam["reserved"] ?: "0,0,0").removeWhiteSpace().split(",").map { it.toInt() }
}

return config
}



fun toUri(config: ServerConfig): String {
val outbound = config.getProxyOutbound() ?: return ""

Expand Down

0 comments on commit fa341c9

Please sign in to comment.