Globals.kt 7.93 KB
Newer Older
Daniel Wolf's avatar
Daniel Wolf committed
1
2
3
package com.frostnerd.smokescreen

import android.content.Context
4
import android.content.DialogInterface
Daniel Wolf's avatar
Daniel Wolf committed
5
import android.content.pm.PackageManager
Daniel Wolf's avatar
Daniel Wolf committed
6
import android.graphics.Color
Daniel Wolf's avatar
Daniel Wolf committed
7
import android.text.Html
Daniel Wolf's avatar
Daniel Wolf committed
8
9
10
import android.text.SpannableString
import android.text.method.LinkMovementMethod
import android.text.util.Linkify
11
import android.util.AndroidRuntimeException
12
import android.view.LayoutInflater
Daniel Wolf's avatar
Daniel Wolf committed
13
import android.widget.TextView
14
import android.widget.Toast
Daniel Wolf's avatar
Daniel Wolf committed
15
import androidx.annotation.ColorInt
16
import androidx.appcompat.app.AlertDialog
Daniel Wolf's avatar
Daniel Wolf committed
17
18
import com.frostnerd.dnstunnelproxy.KnownDnsServers
import com.frostnerd.encrypteddnstunnelproxy.AbstractHttpsDNSHandle
19
import com.frostnerd.encrypteddnstunnelproxy.HttpsDnsServerInformation
20
import com.frostnerd.encrypteddnstunnelproxy.QuicEngine
Daniel Wolf's avatar
Daniel Wolf committed
21
import com.frostnerd.encrypteddnstunnelproxy.quic.AbstractQuicDnsHandle
Daniel Wolf's avatar
Daniel Wolf committed
22
import com.frostnerd.encrypteddnstunnelproxy.quic.QuicUpstreamAddress
Daniel Wolf's avatar
Daniel Wolf committed
23
import com.frostnerd.encrypteddnstunnelproxy.tls.AbstractTLSDnsHandle
24
import kotlinx.android.synthetic.main.dialog_privacypolicy.view.*
25
import okhttp3.Dns
26
27
28
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.OkHttpClient
import okhttp3.dnsoverhttps.DnsOverHttps
29
import okhttp3.internal.toHexString
30
import java.net.InetAddress
31
import java.util.*
32
33


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

53
54
fun showPrivacyPolicyDialog(context: Context) {
    val dialog = AlertDialog.Builder(context, context.getPreferences().theme.dialogStyle)
55
    dialog.setTitle(R.string.about_privacypolicy)
56
57
    val view = LayoutInflater.from(context).inflate(R.layout.dialog_privacypolicy, null, false)
    dialog.setView(view)
58
    view.webView.loadUrl("file:///android_asset/privacy_policy.html")
59
60
61
62
    dialog.setNeutralButton(R.string.all_close, null)
    dialog.show()
}

63
64
65
66
67
68
69
fun showInfoTextDialogWithClose(
    context: Context,
    title: String,
    text: String,
    withDialog: (AlertDialog.() -> Unit)? = null,
) = showInfoTextDialog(context, title, text, neutralButton = null, positiveButton = context.getString(R.string.all_close) to null, withDialog = withDialog)

Daniel Wolf's avatar
Daniel Wolf committed
70
71
72
fun showInfoTextDialog(context:Context,
                       title:String,
                       text:String,
73
74
                       positiveButton:Pair<String, ((DialogInterface, Int) -> Unit)?>? = null,
                       negativeButton:Pair<String, ((DialogInterface, Int) -> Unit)?>? = null,
75
                       neutralButton:Pair<String, ((DialogInterface, Int) -> Unit)?>? = context.getString(android.R.string.ok) to null,
Daniel Wolf's avatar
Daniel Wolf committed
76
77
                       withDialog: (AlertDialog.() -> Unit)? = null,
                        linkifyText:Boolean = false) {
78
79
    try {
        val stringWithLinks = SpannableString(text)
Daniel Wolf's avatar
Daniel Wolf committed
80

81
        val dialogBuilder = AlertDialog.Builder(context, context.getPreferences().theme.dialogStyle)
Daniel Wolf's avatar
Daniel Wolf committed
82
83
84
85
86
87
88
89
90
                            .setTitle(title)
        if(linkifyText) {
            Linkify.addLinks(stringWithLinks, Linkify.ALL)
            val span = Html.fromHtml(stringWithLinks.toString().replace("\n", "<br>"))
            dialogBuilder.setMessage(span)
        } else {
            dialogBuilder.setMessage(text)
        }

91
92
93
        if(neutralButton != null) dialogBuilder.setNeutralButton(neutralButton.first, neutralButton.second)
        if(positiveButton != null) dialogBuilder.setPositiveButton(positiveButton.first, positiveButton.second)
        if(negativeButton != null) dialogBuilder.setNegativeButton(negativeButton.first, negativeButton.second)
94

95
        val dialog = dialogBuilder.show()
Daniel Wolf's avatar
Daniel Wolf committed
96
97
98
99
100
101
        if(linkifyText) {
            val textView = dialog.findViewById<TextView>(android.R.id.message)
            textView?.movementMethod = LinkMovementMethod.getInstance()
            textView?.linksClickable = true
            textView?.setLinkTextColor(Color.parseColor("#64B5F6"))
        }
102
103
        withDialog?.invoke(dialog)
    } catch (ex: Exception) {
104
105
        if (ex is AndroidRuntimeException ||
            ex.message?.let {
106
107
                it.contains("webview", true) ||
                        it.contains("donor package", true)
108
109
            } == true
        ) Toast.makeText(context, R.string.error_webview_missing, Toast.LENGTH_LONG)
110
111
            .show()
        else throw ex
112
    }
113
114
115
116
117
118
119
}

fun isPackageInstalled(context: Context, packageName: String): Boolean {
    val packageManager = context.packageManager
    val intent = packageManager.getLaunchIntentForPackage(packageName) ?: return false
    val list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
    return list.size > 0
120
121
}

122
fun colorToHexString(@ColorInt color:Int):String {
123
    return String.format(Locale.ROOT, "#%06X", 0xFFFFFF and color)
124
125
126
127
128
129
130
131
}

@ColorInt
fun opaqueColor(@ColorInt color: Int, opactiy: Int): Int {
    val alpha = opactiy - opactiy % 5
    return Color.parseColor("#" + alpha.toHexString() + colorToHexString(color).replace("#", ""))
}

132
133
interface BackpressFragment {
    fun onBackPressed():Boolean
Daniel Wolf's avatar
Daniel Wolf committed
134
135
136
137
138
139
140
}

fun loadKnownDNSServers() {
    AbstractHttpsDNSHandle // Loads the known servers.
    AbstractTLSDnsHandle
    AbstractQuicDnsHandle
    KnownDnsServers
Daniel Wolf's avatar
Daniel Wolf committed
141
142
}

143
144
145
146
fun createQuicEngineIfInstalled(context: Context, quicOnly:Boolean, vararg addresses: QuicUpstreamAddress): QuicEngine? {
    return if (QuicEngineImpl.providerInstalled) {
        QuicEngineImpl(context, quicOnly, *addresses)
    } else null
147
148
}

149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
private fun httpClientWithoutDNS(): OkHttpClient {
    return OkHttpClient.Builder().dns(object: Dns {
        override fun lookup(hostname: String): List<InetAddress> {
            return emptyList()
        }
    }).build()
}

fun okhttpClientWithDoh(context: Context, forceDefaultFallback: Boolean = false): OkHttpClient {
    val fallback = context.getPreferences().fallbackDns as HttpsDnsServerInformation?

    if(fallback == null || forceDefaultFallback) {
        val dns = DnsOverHttps.Builder().client(httpClientWithoutDNS())
            .url("https://9.9.9.9/dns-query".toHttpUrl())
            .bootstrapDnsHosts(
                InetAddress.getByName("9.9.9.9"),
                InetAddress.getByName("149.112.112.112"),
                InetAddress.getByName("2620:fe::9"),
                InetAddress.getByName("2620:fe::fe")
            ).build()
        return OkHttpClient.Builder().dns(dns).build()
    } else {
        val url = fallback.servers.first().address.getUrl(false)
        val hasKnownIPAddresses = fallback.servers.first().address.hasStaticAddresses

        val dns = if(hasKnownIPAddresses) {
            val addressCreator = fallback.servers.first().address.addressCreator
Daniel Wolf's avatar
Daniel Wolf committed
176
            val addresses = addressCreator.resolveOrGetResultOrNull()?.toMutableList() ?: mutableListOf()
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
            if (addresses.isNullOrEmpty() && addressCreator.hostAddress != null) {
                addresses.add(InetAddress.getByName(addressCreator.hostAddress))
            }

            if (addresses.isNullOrEmpty()) {
                DnsOverHttps.Builder().client(okhttpClientWithDoh(context, true))
                    .url(url.toHttpUrl()).build()
            } else {
                DnsOverHttps.Builder().client(httpClientWithoutDNS()).url(url.toHttpUrl())
                    .bootstrapDnsHosts(addresses)
                    .build()
            }
        } else {
            DnsOverHttps.Builder().client(okhttpClientWithDoh(context, true)).url(url.toHttpUrl()).build()
        }
        return OkHttpClient.Builder().dns(dns).build()
    }
Daniel Wolf's avatar
Daniel Wolf committed
194
}