- By default, obtain DNS server addresses dynamically from the system.

This commit is contained in:
Juha Heinanen
2019-05-25 16:45:32 +03:00
parent d9f6d47425
commit d419304845
10 changed files with 223 additions and 53 deletions
@@ -31,5 +31,7 @@ object Api {
external fun contact_add(contact: String)
external fun contacts_remove()
external fun log_level_set(level: Int)
external fun dnsc_srv_set(servers: String): Int
external fun net_debug()
}
@@ -6,6 +6,7 @@ import android.app.Notification.VISIBILITY_PUBLIC
import android.content.*
import android.media.*
import android.net.ConnectivityManager
import android.net.LinkProperties
import android.net.wifi.WifiManager
import android.os.IBinder
import android.os.PowerManager
@@ -22,6 +23,7 @@ import android.net.NetworkRequest
import android.provider.Settings
import java.io.File
import java.net.InetAddress
import java.nio.charset.StandardCharsets
import java.util.*
import kotlin.math.roundToInt
@@ -35,6 +37,7 @@ class BaresipService: Service() {
internal lateinit var rt: Ringtone
internal lateinit var nm: NotificationManager
internal lateinit var snb: NotificationCompat.Builder
internal lateinit var cm: ConnectivityManager
internal lateinit var wakeLock: PowerManager.WakeLock
internal lateinit var fl: WifiManager.WifiLock
@@ -61,9 +64,9 @@ class BaresipService: Service() {
createNotificationChannels()
snb = NotificationCompat.Builder(this, DEFAULT_CHANNEL_ID)
val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
cm = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val builder = NetworkRequest.Builder()
connectivityManager.registerNetworkCallback(
cm.registerNetworkCallback(
builder.build(),
object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
@@ -73,12 +76,26 @@ class BaresipService: Service() {
UserAgent.register()
disconnected = false
}
if (dynDns) {
val dnsServers = cm.getLinkProperties(network).getDnsServers()
if (Config.updateDnsServers(dnsServers) != 0)
Log.w(LOG_TAG, "Failed to update DNS servers '$dnsServers")
}
}
override fun onLost(network: Network) {
super.onLost(network)
Log.d(LOG_TAG, "Network $network is lost")
disconnected = true
}
override fun onLinkPropertiesChanged(network: Network, linkProperties: LinkProperties) {
super.onLinkPropertiesChanged(network, linkProperties)
Log.d(LOG_TAG, "Network $network link properties changed")
if (dynDns) {
val dnsServers = linkProperties.getDnsServers()
if (Config.updateDnsServers(dnsServers) != 0)
Log.w(LOG_TAG, "Failed to update DNS servers '$dnsServers")
}
}
}
)
@@ -128,13 +145,31 @@ class BaresipService: Service() {
Utils.copyAssetToFile(applicationContext, a, "$filesPath/$a")
} else {
Log.d(LOG_TAG, "Asset $a already copied")
if (a == "config") Config.initialize()
if (a == "config") {
var dnsServers = listOf<InetAddress>()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val activeNetwork = cm.activeNetwork
if (activeNetwork != null) {
dnsServers = cm.getLinkProperties(activeNetwork).dnsServers
Log.d(LOG_TAG, "DNS Servers = $dnsServers")
} else {
Log.d(LOG_TAG, "No active network!")
}
}
Config.initialize(dnsServers)
}
}
}
ContactsActivity.restoreContacts(applicationContext.filesDir)
Thread(Runnable { baresipStart(filesPath) }).start()
isServiceRunning = true
showStatusNotification()
if (Config.variable("dyn_dns")[0] == "yes")
Config.remove("dns_server")
}
"Call Show", "Call Answer" -> {
@@ -397,8 +432,9 @@ class BaresipService: Service() {
am.setStreamVolume(am.mode,
(callVolume * 0.1 * am.getStreamMaxVolume(am.mode)).roundToInt(),
0)
Log.d(LOG_TAG, "Original/new call volume of stream ${am.mode} is " +
"$origCallVolume/${am.getStreamVolume(am.mode)}")
}
Log.d(LOG_TAG, "Call volume of stream ${am.mode} is ${am.getStreamVolume(am.mode)}")
}
"call verified", "call secure" -> {
val call = Call.find(callp)
@@ -765,6 +801,7 @@ class BaresipService: Service() {
var isServiceClean = false
var speakerPhone = false
var callVolume = 0
var dynDns = false
var filesPath = ""
var uas = ArrayList<UserAgent>()
@@ -2,6 +2,7 @@ package com.tutpro.baresip
import android.content.Context
import java.io.File
import java.net.InetAddress
object Config {
@@ -9,7 +10,7 @@ object Config {
private val file = File(path)
private var config = Utils.getFileContents(file)
fun initialize() {
fun initialize(dnsServers: List<InetAddress>) {
var write = false
if (!config.contains("zrtp_hash")) {
config = "${config}zrtp_hash yes\n"
@@ -52,6 +53,17 @@ object Config {
} else {
BaresipService.callVolume = variable("call_volume")[0].toInt()
}
if (!config.contains("dyn_dns")) {
config = "${config}dyn_dns no\n"
write = true
} else {
if (config.contains(Regex("dyn_dns[ ]+yes"))) {
for (dnsServer in dnsServers)
config = "${config}dns_server ${dnsServer.hostAddress}:53\n"
BaresipService.dynDns = true
write = true
}
}
if (write) {
Log.e("Baresip", "Writing '$config'")
Utils.putFileContents(file, config)
@@ -59,8 +71,8 @@ object Config {
}
fun variable(name: String): ArrayList<String> {
val lines = config.split("\n")
val result = ArrayList<String>()
val lines = config.split("\n")
for (line in lines) {
if (line.startsWith(name))
result.add((line.substring(name.length).trim()).split("# \t")[0])
@@ -69,7 +81,7 @@ object Config {
}
fun add(variable: String, value: String) {
config += "\n$variable $value\n"
config += "$variable $value\n"
}
fun remove(variable: String) {
@@ -87,8 +99,29 @@ object Config {
}
fun save() {
var result = ""
for (line in config.split("\n"))
if (line.length > 0)
result = result + line + '\n'
config = result
Utils.putFileContents(file, config)
Log.d("Baresip", "New config '$config'")
Log.d("Baresip", "New config '$result'")
// Api.reload_config()
}
}
fun updateDnsServers(dnsServers: List<InetAddress>): Int {
var servers = ""
for (dnsServer in dnsServers) {
var address = dnsServer.hostAddress
if (Utils.checkIpV4(address))
address = "${address}:53"
else
address = "[${address}]:53"
if (servers == "")
servers = address
else
servers = "${servers},${address}"
}
return Api.dnsc_srv_set(servers)
}
}
@@ -1,7 +1,10 @@
package com.tutpro.baresip
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.os.Build
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.Menu
@@ -52,10 +55,15 @@ class ConfigActivity : AppCompatActivity() {
preferIPv6.isChecked = oldPreferIPv6 == "yes"
dnsServers = findViewById(R.id.DnsServers) as EditText
val dsCv = Config.variable("dns_server")
var dsTv = ""
for (ds in dsCv) dsTv += ", $ds"
oldDnsServers = dsTv.trimStart(',').trimStart(' ')
val ddCv = Config.variable("dyn_dns")
if (ddCv[0] == "yes") {
oldDnsServers = ""
} else {
val dsCv = Config.variable("dns_server")
var dsTv = ""
for (ds in dsCv) dsTv += ", $ds"
oldDnsServers = dsTv.trimStart(',').trimStart(' ')
}
dnsServers.setText(oldDnsServers)
opusBitRate = findViewById(R.id.OpusBitRate) as EditText
@@ -144,17 +152,35 @@ class ConfigActivity : AppCompatActivity() {
restart = true
}
val dnsServers = dnsServers.text.toString().trim().toLowerCase()
val dnsServers = addMissingPorts(dnsServers.text.toString().trim().toLowerCase())
if (dnsServers != oldDnsServers) {
if (!checkDnsServers(dnsServers)) {
Utils.alertView(this, "Notice", "Invalid DNS Servers: $dnsServers")
Utils.alertView(this, "Notice",
"Invalid DNS Servers: $dnsServers")
return false
}
Config.remove("dyn_dns")
Config.remove("dns_server")
for (server in dnsServers.split(","))
Config.add("dns_server", server)
if (dnsServers.isNotEmpty()) {
for (server in dnsServers.split(","))
Config.add("dns_server", server)
Config.add("dyn_dns", "no")
if (Api.dnsc_srv_set(dnsServers) != 0) {
Utils.alertView(this, "Notice",
"Failed to set DNS servers '$dnsServers'")
return false
}
} else {
Config.add("dyn_dns", "yes")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
Config.updateDnsServers(cm.getLinkProperties(cm.activeNetwork).getDnsServers())
} else {
restart = true
}
}
Api.net_debug()
save = true
restart = true
}
val opusBitRate = opusBitRate.text.toString().trim()
@@ -267,5 +293,20 @@ class ConfigActivity : AppCompatActivity() {
return (number >=6000) && (number <= 510000)
}
private fun addMissingPorts(addressList: String): String {
if (addressList == "") return ""
var result = ""
for (addr in addressList.split(","))
if (Utils.checkIpPort(addr)) {
result = "$result,$addr"
} else {
if (Utils.checkIpV4(addr))
result = "$result,$addr:53"
else
result = "$result,[$addr]:53"
}
return result.substring(1)
}
}
@@ -87,7 +87,7 @@ object Utils {
fun removeLinesStartingWithName(string: String, name: String): String {
var result = ""
for (line in string.split("\n"))
if (!line.startsWith(name)) result += line + "\n"
if (!line.startsWith(name) && (line.length > 0)) result += line + "\n"
return result
}
@@ -171,6 +171,11 @@ object Utils {
return Regex("^(([0-9a-fA-F]{0,4}:){1,7}[0-9a-fA-F]{0,4})$").matches(ip)
}
fun checkIpv6InBrackets(bracketedIp: String): Boolean {
return bracketedIp.startsWith("[") && bracketedIp.endsWith("]") &&
checkIpV6(bracketedIp.substring(1, bracketedIp.length - 2))
}
fun checkIp(ip: String): Boolean {
return checkIpV4(ip) || checkIpV6(ip)
}
@@ -214,8 +219,12 @@ object Utils {
}
fun checkIpPort(ipPort: String): Boolean {
return checkIp(ipPort.substringBeforeLast(":")) &&
checkPort(ipPort.substringAfterLast(":"))
if (ipPort.startsWith("["))
return checkIpv6InBrackets(ipPort.substringBeforeLast(":")) &&
checkPort(ipPort.substringAfterLast(":"))
else
return checkIpV4(ipPort.substringBeforeLast(":")) &&
checkPort(ipPort.substringAfterLast(":"))
}
fun checkParams(params: String): Boolean {