Extensions.kt 13.9 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.KeyguardManager
Daniel Wolf's avatar
Daniel Wolf committed
5
6
7
8
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
9
import android.hardware.fingerprint.FingerprintManager
10
11
12
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
13
import android.net.Uri
14
import android.os.Build
15
import android.os.PowerManager
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
Daniel Wolf's avatar
Daniel Wolf committed
29
import com.frostnerd.smokescreen.util.preferences.AppSettings
30
31
import com.frostnerd.smokescreen.util.preferences.AppSettingsSharedPreferences
import com.frostnerd.smokescreen.util.preferences.fromSharedPreferences
32
import leakcanary.LeakSentry
33
34
import java.net.Inet4Address
import java.net.Inet6Address
35
import java.util.logging.Level
Daniel Wolf's avatar
Daniel Wolf committed
36

Daniel Wolf's avatar
Daniel Wolf committed
37
38
/*
 * Copyright (C) 2019 Daniel Wolf (Ch4t4r)
Daniel Wolf's avatar
Daniel Wolf committed
39
 *
Daniel Wolf's avatar
Daniel Wolf committed
40
41
42
43
44
45
46
47
48
49
50
51
52
53
 * 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
54
55
 */

56
fun Context.canUseFingerprintAuthentication(): Boolean {
Daniel Wolf's avatar
Daniel Wolf committed
57
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return false
58
59
    val mgr = getSystemService(Context.FINGERPRINT_SERVICE) as? FingerprintManager
    if(mgr == null || !mgr.isHardwareDetected) return false
60
61
62
63
64
65
    else if(!mgr.hasEnrolledFingerprints()) return false
    val keyguard = getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager
    if(!keyguard.isKeyguardSecure) return false
    return true
}

66
67
fun Context.registerReceiver(intentFilter: IntentFilter, receiver: (intent: Intent?) -> Unit): BroadcastReceiver {
    val actualReceiver = object : BroadcastReceiver() {
Daniel Wolf's avatar
Daniel Wolf committed
68
69
70
71
72
73
74
75
        override fun onReceive(context: Context?, intent: Intent?) {
            receiver(intent)
        }
    }
    this.registerReceiver(actualReceiver, intentFilter)
    return actualReceiver
}

76
fun Context.startForegroundServiceCompat(intent: Intent) {
77
78
79
80
81
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        startForegroundService(intent)
    } else startService(intent)
}

82
fun Context.registerReceiver(filteredActions: List<String>, receiver: (intent: Intent?) -> Unit): BroadcastReceiver {
Daniel Wolf's avatar
Daniel Wolf committed
83
84
85
86
87
    val filter = IntentFilter()
    for (filteredAction in filteredActions) {
        filter.addAction(filteredAction)
    }

88
    val actualReceiver = object : BroadcastReceiver() {
Daniel Wolf's avatar
Daniel Wolf committed
89
90
91
92
93
94
95
96
        override fun onReceive(context: Context?, intent: Intent?) {
            receiver(intent)
        }
    }
    this.registerReceiver(actualReceiver, filter)
    return actualReceiver
}

97
98
fun Context.registerLocalReceiver(intentFilter: IntentFilter, receiver: (intent: Intent?) -> Unit): BroadcastReceiver {
    val actualReceiver = object : BroadcastReceiver() {
Daniel Wolf's avatar
Daniel Wolf committed
99
100
101
102
103
104
105
106
        override fun onReceive(context: Context?, intent: Intent?) {
            receiver(intent)
        }
    }
    LocalBroadcastManager.getInstance(this).registerReceiver(actualReceiver, intentFilter)
    return actualReceiver
}

107
108
109
110
fun Context.registerLocalReceiver(
    filteredActions: List<String>,
    receiver: (intent: Intent?) -> Unit
): BroadcastReceiver {
Daniel Wolf's avatar
Daniel Wolf committed
111
112
113
114
115
    val filter = IntentFilter()
    for (filteredAction in filteredActions) {
        filter.addAction(filteredAction)
    }

116
    val actualReceiver = object : BroadcastReceiver() {
Daniel Wolf's avatar
Daniel Wolf committed
117
118
119
120
121
122
123
124
        override fun onReceive(context: Context?, intent: Intent?) {
            receiver(intent)
        }
    }
    LocalBroadcastManager.getInstance(this).registerReceiver(actualReceiver, filter)
    return actualReceiver
}

125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
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
}

151
152
153
154
155
156
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
157
158
}

159
160
fun Context.getPreferences(): AppSettingsSharedPreferences {
    return AppSettings.fromSharedPreferences(this)
Daniel Wolf's avatar
Daniel Wolf committed
161
162
}

163
164
165
166
fun Fragment.getPreferences(): AppSettingsSharedPreferences {
    return AppSettings.fromSharedPreferences(context!!)
}

167
168
169
170
171
172
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)
}

173
fun Array<*>.toStringArray(): Array<String> {
Daniel Wolf's avatar
Daniel Wolf committed
174
175
176
177
178
179
180
    val stringArray = arrayOfNulls<String>(size)
    for ((index, value) in withIndex()) {
        stringArray[index] = value.toString()
    }
    return stringArray as Array<String>
}

181
fun IntArray.toStringArray(): Array<String> {
Daniel Wolf's avatar
Daniel Wolf committed
182
183
184
185
186
187
    val stringArray = arrayOfNulls<String>(size)
    for ((index, value) in withIndex()) {
        stringArray[index] = value.toString()
    }
    return stringArray as Array<String>
}
Daniel Wolf's avatar
Daniel Wolf committed
188

189
190
fun <T:Activity>Activity.restart(activityClass:Class<T>? = null) {
    val intent = (if(activityClass != null) Intent(this, activityClass) else intent)
Daniel Wolf's avatar
Daniel Wolf committed
191
192
193
        .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_NO_ANIMATION)
    finish()
    startActivity(intent)
194
195
196
197
198
199
200
201
}

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))
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
}

fun ConnectivityManager.isMobileNetwork(network: Network): Boolean {
    val capabilities = getNetworkCapabilities(network)
    return capabilities != null && capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
}

fun ConnectivityManager.isWifiNetwork(network: Network): Boolean {
    val capabilities = getNetworkCapabilities(network)
    return capabilities != null && capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
}

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

219
220
fun Context.hasDeviceIpv4Address(): Boolean {
    val mgr = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
221
    var hasNetwork = false
222
223
224
225
226
227
    for (network in mgr.allNetworks) {
        if(network == null) continue
        val info = mgr.getNetworkInfo(network) ?: continue
        val capabilities = mgr.getNetworkCapabilities(network) ?: continue
        if (info.isConnected && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN)) {
            val linkProperties = mgr.getLinkProperties(network) ?: continue
228
            hasNetwork = true
229
230
231
232
233
234
235
236
237
238
            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.")
239
    return !hasNetwork
240
241
242
243
}

fun Context.hasDeviceIpv6Address(): Boolean {
    val mgr = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
244
    var hasNetwork = false
245
246
247
248
249
250
    for (network in mgr.allNetworks) {
        if(network == null) continue
        val info = mgr.getNetworkInfo(network) ?: continue
        val capabilities = mgr.getNetworkCapabilities(network) ?: continue
        if (info.isConnected && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN)) {
            val linkProperties = mgr.getLinkProperties(network) ?: continue
251
            hasNetwork = true
252
253
254
255
256
257
258
259
260
261
            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.")
262
    return !hasNetwork
263
264
}

265
266
operator fun Level.compareTo(otherLevel:Level):Int {
    return this.intValue() - otherLevel.intValue()
Daniel Wolf's avatar
Daniel Wolf committed
267
268
269
270
271
272
273
274
275
276
277
278
}

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

fun DnsServerInformation<*>.hasHttpsServer():Boolean {
    return this.servers.any {
        it is HttpsUpstreamAddress
    }
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
}

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()
    )
}

fun DnsServerInformation.Companion.tlsServerFromHosts(primaryHost:String, secondaryHost:String?): DnsServerInformation<TLSUpstreamAddress> {
    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)
364
365
366
367
368
369
370
371
372
373
374
375
}

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)
    }
Daniel Wolf's avatar
Daniel Wolf committed
376
}