Extensions.kt 16.4 KB
Newer Older
Daniel Wolf's avatar
Daniel Wolf committed
1
2
package com.frostnerd.smokescreen

Daniel Wolf's avatar
Daniel Wolf committed
3
import android.app.Activity
4
import android.app.AlarmManager
5
import android.app.KeyguardManager
6
import android.app.PendingIntent
7
import android.content.*
8
import android.hardware.fingerprint.FingerprintManager
9
10
11
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
12
import android.net.Uri
13
import android.os.Build
14
import android.os.PowerManager
15
import android.widget.Toast
16
import androidx.appcompat.app.AppCompatActivity
17
import androidx.fragment.app.Fragment
18
19
20
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
Daniel Wolf's avatar
Daniel Wolf committed
21
import androidx.localbroadcastmanager.content.LocalBroadcastManager
22
23
import com.frostnerd.dnstunnelproxy.Decision
import com.frostnerd.dnstunnelproxy.DnsServerConfiguration
Daniel Wolf's avatar
Daniel Wolf committed
24
import com.frostnerd.dnstunnelproxy.DnsServerInformation
25
26
27
import com.frostnerd.dnstunnelproxy.DnsServerInformationTypeAdapter
import com.frostnerd.encrypteddnstunnelproxy.*
import com.frostnerd.encrypteddnstunnelproxy.tls.TLS
Daniel Wolf's avatar
Daniel Wolf committed
28
import com.frostnerd.encrypteddnstunnelproxy.tls.TLSUpstreamAddress
29
import com.frostnerd.smokescreen.util.RequestCodes
30
31
import com.frostnerd.general.service.isServiceRunning
import com.frostnerd.smokescreen.service.DnsVpnService
Daniel Wolf's avatar
Daniel Wolf committed
32
import com.frostnerd.smokescreen.util.preferences.AppSettings
33
import com.frostnerd.smokescreen.util.preferences.AppSettingsSharedPreferences
34
import com.frostnerd.smokescreen.util.preferences.VpnServiceState
35
import com.frostnerd.smokescreen.util.preferences.fromSharedPreferences
36
import com.frostnerd.smokescreen.util.proxy.IpTablesPacketRedirector
37
38
39
import io.sentry.android.core.BuildInfoProvider
import io.sentry.android.core.util.RootChecker
import io.sentry.core.NoOpLogger
40
import leakcanary.LeakSentry
41
42
import java.net.Inet4Address
import java.net.Inet6Address
43
import java.util.logging.Level
Daniel Wolf's avatar
Daniel Wolf committed
44

Daniel Wolf's avatar
Daniel Wolf committed
45
46
/*
 * Copyright (C) 2019 Daniel Wolf (Ch4t4r)
Daniel Wolf's avatar
Daniel Wolf committed
47
 *
Daniel Wolf's avatar
Daniel Wolf committed
48
49
50
51
52
53
54
55
56
57
58
59
60
61
 * 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/>.
 *
 * You can contact the developer at daniel.wolf@frostnerd.com.
Daniel Wolf's avatar
Daniel Wolf committed
62
63
 */

64
fun Context.canUseFingerprintAuthentication(): Boolean {
Daniel Wolf's avatar
Daniel Wolf committed
65
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return false
66
67
    val mgr = getSystemService(Context.FINGERPRINT_SERVICE) as? FingerprintManager
    if(mgr == null || !mgr.isHardwareDetected) return false
68
69
70
71
72
73
    else if(!mgr.hasEnrolledFingerprints()) return false
    val keyguard = getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager
    if(!keyguard.isKeyguardSecure) return false
    return true
}

74
75
fun Context.registerReceiver(intentFilter: IntentFilter, receiver: (intent: Intent?) -> Unit): BroadcastReceiver {
    val actualReceiver = object : BroadcastReceiver() {
Daniel Wolf's avatar
Daniel Wolf committed
76
77
78
79
80
81
82
83
        override fun onReceive(context: Context?, intent: Intent?) {
            receiver(intent)
        }
    }
    this.registerReceiver(actualReceiver, intentFilter)
    return actualReceiver
}

84
fun Context.startForegroundServiceCompat(intent: Intent) {
85
86
87
88
89
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        startForegroundService(intent)
    } else startService(intent)
}

90
91
92
93
94
95
96
fun Context.tryUnregisterReceiver(receiver: BroadcastReceiver) {
    try {
        unregisterReceiver(receiver)
    } catch (e: Exception) {
    }
}

97
fun Context.registerReceiver(filteredActions: List<String>, receiver: (intent: Intent?) -> Unit): BroadcastReceiver {
Daniel Wolf's avatar
Daniel Wolf committed
98
99
100
101
102
    val filter = IntentFilter()
    for (filteredAction in filteredActions) {
        filter.addAction(filteredAction)
    }

103
    val actualReceiver = object : BroadcastReceiver() {
Daniel Wolf's avatar
Daniel Wolf committed
104
105
106
107
108
109
110
111
        override fun onReceive(context: Context?, intent: Intent?) {
            receiver(intent)
        }
    }
    this.registerReceiver(actualReceiver, filter)
    return actualReceiver
}

112
113
fun Context.registerLocalReceiver(intentFilter: IntentFilter, receiver: (intent: Intent?) -> Unit): BroadcastReceiver {
    val actualReceiver = object : BroadcastReceiver() {
Daniel Wolf's avatar
Daniel Wolf committed
114
115
116
117
118
119
120
121
        override fun onReceive(context: Context?, intent: Intent?) {
            receiver(intent)
        }
    }
    LocalBroadcastManager.getInstance(this).registerReceiver(actualReceiver, intentFilter)
    return actualReceiver
}

122
123
124
125
fun Context.registerLocalReceiver(
    filteredActions: List<String>,
    receiver: (intent: Intent?) -> Unit
): BroadcastReceiver {
Daniel Wolf's avatar
Daniel Wolf committed
126
127
128
129
130
    val filter = IntentFilter()
    for (filteredAction in filteredActions) {
        filter.addAction(filteredAction)
    }

131
    val actualReceiver = object : BroadcastReceiver() {
Daniel Wolf's avatar
Daniel Wolf committed
132
133
134
135
136
137
138
139
        override fun onReceive(context: Context?, intent: Intent?) {
            receiver(intent)
        }
    }
    LocalBroadcastManager.getInstance(this).registerReceiver(actualReceiver, filter)
    return actualReceiver
}

140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
fun AppCompatActivity.registerLocalReceiver(
    filteredActions: List<String>,
    unregisterOnDestroy:Boolean,
    receiver: (intent: Intent?) -> Unit
): BroadcastReceiver {
    val filter = IntentFilter()
    for (filteredAction in filteredActions) {
        filter.addAction(filteredAction)
    }

    val actualReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            receiver(intent)
        }
    }
    val mgr = LocalBroadcastManager.getInstance(this)
    mgr.registerReceiver(actualReceiver, filter)
    if(unregisterOnDestroy) lifecycle.addObserver(object:LifecycleObserver {
        @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
        fun onDestroy() {
            mgr.unregisterReceiver(actualReceiver)
        }
    })
    return actualReceiver
}

166
167
168
169
170
171
fun Context.sendLocalBroadcast(intent: Intent) {
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent)
}

fun Context.unregisterLocalReceiver(receiver: BroadcastReceiver?) {
    if(receiver != null) LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver)
Daniel Wolf's avatar
Daniel Wolf committed
172
173
}

174
175
fun Context.getPreferences(): AppSettingsSharedPreferences {
    return AppSettings.fromSharedPreferences(this)
Daniel Wolf's avatar
Daniel Wolf committed
176
177
}

178
179
180
181
fun Fragment.getPreferences(): AppSettingsSharedPreferences {
    return AppSettings.fromSharedPreferences(context!!)
}

182
183
184
185
186
187
fun Context.isAppBatteryOptimized(): Boolean {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return false
    val pwrm = getSystemService(Context.POWER_SERVICE) as PowerManager
    return !pwrm.isIgnoringBatteryOptimizations(packageName)
}

188
fun <T:Activity>Activity.restart(activityClass:Class<T>? = null, exitProcess:Boolean = false) {
189
    val intent = (if(activityClass != null) Intent(this, activityClass) else intent)
190
191
192
193
194
195
196
197
198
199
        .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_NO_ANIMATION or Intent.FLAG_ACTIVITY_CLEAR_TASK)
    if(exitProcess) {
        finish()
        val pendingIntent = PendingIntent.getActivity(this, RequestCodes.RESTART_WHOLE_APP, intent, PendingIntent.FLAG_CANCEL_CURRENT)
        (getSystemService(Context.ALARM_SERVICE) as AlarmManager).setExact(AlarmManager.RTC, System.currentTimeMillis() + 800, pendingIntent)
        kotlin.system.exitProcess(0)
    } else {
        finish()
        startActivity(intent)
    }
200
201
202
203
204
205
206
207
}

fun Context.showEmailChooser(chooserTitle: String, subject: String, recipent: String, text: String) {
    val intent = Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", recipent, null))
    intent.putExtra(Intent.EXTRA_SUBJECT, subject)
    intent.putExtra(Intent.EXTRA_EMAIL, recipent)
    intent.putExtra(Intent.EXTRA_TEXT, text)
    startActivity(Intent.createChooser(intent, chooserTitle))
208
209
210
211
212
}

fun ConnectivityManager.isVpnNetwork(network: Network): Boolean {
    val capabilities = getNetworkCapabilities(network)
    return capabilities != null && capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN)
213
214
}

215
216
fun Context.hasDeviceIpv4Address(): Boolean {
    val mgr = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
217
    var hasNetwork = false
218
219
    for (network in mgr.allNetworks) {
        if(network == null) continue
220
221
222
223
224
225
226
        val info = try {
            mgr.getNetworkInfo(network)
        } catch (ex:NullPointerException) {
            // Android seems to love to throw NullPointerException with getNetworkInfo() - completely out of our control.
            log("Exception when trying to determine IPv4 capability: $ex")
            null
        } ?: continue
227
228
229
        val capabilities = mgr.getNetworkCapabilities(network) ?: continue
        if (info.isConnected && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN)) {
            val linkProperties = mgr.getLinkProperties(network) ?: continue
230
            hasNetwork = true
231
232
233
234
235
236
237
238
239
240
            log("Checking for IPv4 address in connected non-VPN network ${info.typeName}")
            for (linkAddress in linkProperties.linkAddresses) {
                if (linkAddress.address is Inet4Address && !linkAddress.address.isLoopbackAddress) {
                    log("IPv4 address found.")
                    return true
                }
            }
        }
    }
    log("No IPv4 addresses found.")
241
    return !hasNetwork
242
243
244
245
}

fun Context.hasDeviceIpv6Address(): Boolean {
    val mgr = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
246
    var hasNetwork = false
247
248
    for (network in mgr.allNetworks) {
        if(network == null) continue
249
250
251
252
253
254
255
        val info =  try {
            mgr.getNetworkInfo(network)
        } catch (ex:NullPointerException) {
            // Android seems to love to throw NullPointerException with getNetworkInfo() - completely out of our control.
            log("Exception when trying to determine IPv6 capability: $ex")
            null
        } ?: continue
256
257
258
        val capabilities = mgr.getNetworkCapabilities(network) ?: continue
        if (info.isConnected && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN)) {
            val linkProperties = mgr.getLinkProperties(network) ?: continue
259
            hasNetwork = true
260
261
262
263
264
265
266
267
268
269
            log("Checking for IPv6 address in connected non-VPN network ${info.typeName}")
            for (linkAddress in linkProperties.linkAddresses) {
                if (linkAddress.address is Inet6Address && !linkAddress.address.isLoopbackAddress) {
                    log("IPv6 address found.")
                    return true
                }
            }
        }
    }
    log("No IPv6 addresses found.")
270
    return !hasNetwork
271
272
}

273
274
275
276
fun Context.isDeviceRooted():Boolean {
    return RootChecker(this, BuildInfoProvider(), NoOpLogger.getInstance()).isDeviceRooted
}

277
fun Context.clearPreviousIptablesRedirect(forceClear:Boolean = false) {
278
279
280
281
282
283
284
285
    if(forceClear || !isServiceRunning(DnsVpnService::class.java) || getPreferences().vpnServiceState == VpnServiceState.STOPPED) {
        val ipv4 = getPreferences().lastIptablesRedirectAddress?.split(":")?.let {
            it[0] to it[1].toInt()
        }
        val ipv6 = getPreferences().lastIptablesRedirectAddressIPv6?.split("]:")?.let {
            it[0].subSequence(1, it[0].length).toString() to it[1].toInt()
        }
        val port = ipv4?.second ?: ipv6?.second ?: return  // Neither IPv4 nor IPv6 present if null
286
287
        // Always pass true for disableIpv6IfIp6TablesFails to always drop the rule
        IpTablesPacketRedirector(port, ipv4?.first, ipv6?.first, true, logger).endForward()
288
289
290
291
292
293
        getPreferences().apply {
            edit {
                lastIptablesRedirectAddress = null
                lastIptablesRedirectAddressIPv6 = null
            }
        }
294
295
296
    }
}

297
298
operator fun Level.compareTo(otherLevel:Level):Int {
    return this.intValue() - otherLevel.intValue()
Daniel Wolf's avatar
Daniel Wolf committed
299
300
301
302
303
304
305
306
307
308
309
310
}

fun DnsServerInformation<*>.hasTlsServer():Boolean {
    return this.servers.any {
        it.address is TLSUpstreamAddress
    }
}

fun DnsServerInformation<*>.hasHttpsServer():Boolean {
    return this.servers.any {
        it is HttpsUpstreamAddress
    }
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
}

fun DnsServerInformation<*>.toJson():String {
    return if(hasTlsServer()) {
        DnsServerInformationTypeAdapter().toJson(this)
    } else {
        HttpsDnsServerInformationTypeAdapter().toJson(this as HttpsDnsServerInformation)
    }
}

fun HttpsDnsServerInformation.Companion.fromServerUrls(primaryUrl:String, secondaryUrl:String?): HttpsDnsServerInformation {
    val serverInfo = mutableListOf<HttpsDnsServerConfiguration>()
    val requestType = mapOf(RequestType.WIREFORMAT_POST to ResponseType.WIREFORMAT)
    serverInfo.add(
        HttpsDnsServerConfiguration(address = createHttpsUpstreamAddress(primaryUrl), experimental = false, requestTypes = requestType)
    )
    if(secondaryUrl != null)
        serverInfo.add(
            HttpsDnsServerConfiguration(address = createHttpsUpstreamAddress(secondaryUrl), experimental = false, requestTypes = requestType)
        )
    return HttpsDnsServerInformation(
        "shortcutServer",
        specification = HttpsDnsServerSpecification(
            Decision.UNKNOWN,
            Decision.UNKNOWN,
            Decision.UNKNOWN,
            Decision.UNKNOWN
        ),
        servers = serverInfo,
        capabilities = emptyList()
    )
}

Daniel Wolf's avatar
Daniel Wolf committed
344
fun tlsServerFromHosts(primaryHost:String, secondaryHost:String?): DnsServerInformation<TLSUpstreamAddress> {
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
    val serverInfo = mutableListOf<DnsServerConfiguration<TLSUpstreamAddress>>()
    serverInfo.add(
        DnsServerConfiguration(address = createTlsUpstreamAddress(primaryHost), experimental = false, preferredProtocol = TLS, supportedProtocols = listOf(TLS))
    )
    if(secondaryHost != null)
        serverInfo.add(
            DnsServerConfiguration(address = createTlsUpstreamAddress(secondaryHost), experimental = false, preferredProtocol = TLS, supportedProtocols = listOf(TLS))
        )
    return DnsServerInformation(
        "shortcutServer",
        specification = HttpsDnsServerSpecification(
            Decision.UNKNOWN,
            Decision.UNKNOWN,
            Decision.UNKNOWN,
            Decision.UNKNOWN
        ),
        servers = serverInfo,
        capabilities = emptyList()
    )
}

private fun createHttpsUpstreamAddress(url: String): HttpsUpstreamAddress {
    var host = ""
    var port: Int? = null
    var path: String? = null
    if (url.contains(":")) {
        host = url.split(":")[0]
        port = url.split(":")[1].split("/")[0].toInt()
        if (port > 65535) port = null
    }
    if (url.contains("/")) {
        path = url.split("/")[1]
        if (host == "") host = url.split("/")[0]
    }
    if (host == "") host = url
    return if (port != null && path != null) HttpsUpstreamAddress(host, port, path)
    else if (port != null) HttpsUpstreamAddress(host, port)
    else if (path != null) HttpsUpstreamAddress(host, urlPath = path)
    else HttpsUpstreamAddress(host)
}

private fun createTlsUpstreamAddress(host: String): TLSUpstreamAddress {
    var parsedHost = ""
    var port: Int? = null
    if (host.contains(":")) {
        parsedHost = host.split(":")[0]
        port = host.split(":")[1].split("/")[0].toInt()
        if (port > 65535) port = null
    } else parsedHost = host
    return if (port != null) TLSUpstreamAddress(parsedHost, port)
    else TLSUpstreamAddress(parsedHost)
396
397
398
399
400
401
402
403
404
405
406
407
}

fun LeakSentry.watchIfEnabled(watchedInstance: Any) {
    if(BuildConfig.LEAK_DETECTION) {
        refWatcher.watch(watchedInstance)
    }
}

fun LeakSentry.watchIfEnabled(watchedInstance: Any, name:String) {
    if(BuildConfig.LEAK_DETECTION) {
        refWatcher.watch(watchedInstance, name)
    }
408
409
410
411
412
413
}

fun String.equalsAny(vararg options:String, ignoreCase:Boolean = false):Boolean {
    return options.any {
        it.equals(this, ignoreCase)
    }
414
415
416
417
418
419
420
421
422
423
}

val Context.isPrivateDnsActive: Boolean
    get() = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
        false
    } else {
        (getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).let {
            if (it.activeNetwork == null) false
            else it.getLinkProperties(it.activeNetwork)?.isPrivateDnsActive ?: false
        }
424
425
426
427
428
429
430
431
432
433
434
435
436
437
    }

fun Context.tryOpenBrowser(withLink:String) {
    try {
        startActivity(
            Intent(
                Intent.ACTION_VIEW,
                Uri.parse(withLink)
            )
        )
    } catch (e: ActivityNotFoundException) {
        Toast.makeText(this, R.string.error_no_webbrowser_installed, Toast.LENGTH_LONG).show()
    }
}