summaryrefslogtreecommitdiff
path: root/ipscrambling/src/main/java/foundation/e/advancedprivacy/ipscrambler/IpScramblerModule.kt
blob: d1f01a038cfad24d034082721b5c12a26423dcac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
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
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
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
/*
 * Copyright (C) 2021 E FOUNDATION
 *
 * 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 <https://www.gnu.org/licenses/>.
 */

package foundation.e.advancedprivacy.ipscrambler

import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.VpnService
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import org.torproject.android.service.OrbotConstants
import org.torproject.android.service.OrbotConstants.ACTION_STOP_FOREGROUND_TASK
import org.torproject.android.service.OrbotService
import org.torproject.android.service.util.Prefs
import java.security.InvalidParameterException

@SuppressLint("CommitPrefEdits")
class IpScramblerModule(private val context: Context) {
    interface Listener {
        fun onStatusChanged(newStatus: Status)
        fun log(message: String)
        fun onTrafficUpdate(upload: Long, download: Long, read: Long, write: Long)
    }

    enum class Status {
        OFF, ON, STARTING, STOPPING, START_DISABLED
    }
    companion object {
        const val TAG = "IpScramblerModule"

        private val EXIT_COUNTRY_CODES = setOf("DE", "AT", "SE", "CH", "IS", "CA", "US", "ES", "FR", "BG", "PL", "AU", "BR", "CZ", "DK", "FI", "GB", "HU", "NL", "JP", "RO", "RU", "SG", "SK")

        // Key where exit country is stored by orbot service.
        private const val PREFS_KEY_EXIT_NODES = "pref_exit_nodes"
        // Copy of the package private OrbotService.NOTIFY_ID value.
        // const val ORBOT_SERVICE_NOTIFY_ID_COPY = 1
    }

    private var currentStatus: Status? = null
    private val listeners = mutableSetOf<Listener>()

    private val localBroadcastReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action ?: return
            if (action == OrbotConstants.ACTION_RUNNING_SYNC) {
                try {
                    intent.getStringExtra(OrbotConstants.EXTRA_STATUS)?.let {
                        val newStatus = Status.valueOf(it)
                        currentStatus = newStatus
                    }
                } catch (e: Exception) {
                    Log.e(TAG, "Can't parse Orbot service status.")
                }
                return
            }

            val msg = messageHandler.obtainMessage()
            msg.obj = action
            msg.data = intent.extras
            messageHandler.sendMessage(msg)
        }
    }

    private val messageHandler: Handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            val action = msg.obj as? String ?: return
            val data = msg.data
            when (action) {
                OrbotConstants.LOCAL_ACTION_LOG ->
                    data.getString(OrbotConstants.LOCAL_EXTRA_LOG)?.let { newLog(it) }

                OrbotConstants.LOCAL_ACTION_BANDWIDTH -> {
                    trafficUpdate(
                        data.getLong("up", 0),
                        data.getLong("down", 0),
                        data.getLong("written", 0),
                        data.getLong("read", 0)
                    )
                }

                OrbotConstants.LOCAL_ACTION_PORTS -> {
                    httpProxyPort = data.getInt(OrbotService.EXTRA_HTTP_PROXY_PORT, -1)
                    socksProxyPort = data.getInt(OrbotService.EXTRA_SOCKS_PROXY_PORT, -1)
                }

                OrbotConstants.LOCAL_ACTION_STATUS ->
                    data.getString(OrbotConstants.EXTRA_STATUS)?.let {
                        try {
                            val newStatus = Status.valueOf(it)
                            updateStatus(newStatus, force = true)
                        } catch (e: Exception) {
                            Log.e(TAG, "Can't parse Orbot service status.")
                        }
                    }
            }
            super.handleMessage(msg)
        }
    }

    init {
        Prefs.setContext(context)

        val lbm = LocalBroadcastManager.getInstance(context)
        lbm.registerReceiver(
            localBroadcastReceiver,
            IntentFilter(OrbotConstants.LOCAL_ACTION_STATUS)
        )
        lbm.registerReceiver(
            localBroadcastReceiver,
            IntentFilter(OrbotConstants.LOCAL_ACTION_BANDWIDTH)
        )
        lbm.registerReceiver(
            localBroadcastReceiver,
            IntentFilter(OrbotConstants.LOCAL_ACTION_LOG)
        )
        lbm.registerReceiver(
            localBroadcastReceiver,
            IntentFilter(OrbotConstants.LOCAL_ACTION_PORTS)
        )
        lbm.registerReceiver(
            localBroadcastReceiver,
            IntentFilter(OrbotConstants.ACTION_RUNNING_SYNC)
        )

        Prefs.getSharedPrefs(context).edit()
            .putInt(OrbotConstants.PREFS_DNS_PORT, OrbotConstants.TOR_DNS_PORT_DEFAULT)
            .apply()
    }

    private fun updateStatus(status: Status, force: Boolean = false) {
        if (force || status != currentStatus) {
            currentStatus = status
            listeners.forEach {
                it.onStatusChanged(status)
            }
        }
    }

    private fun isServiceRunning(): Boolean {
        // Reset status, and then ask to refresh it synchronously.
        currentStatus = Status.OFF
        LocalBroadcastManager.getInstance(context)
            .sendBroadcastSync(Intent(OrbotConstants.ACTION_CHECK_RUNNING_SYNC))
        return currentStatus != Status.OFF
    }

    private fun newLog(message: String) {
        listeners.forEach { it.log(message) }
    }

    private fun trafficUpdate(upload: Long, download: Long, read: Long, write: Long) {
        listeners.forEach { it.onTrafficUpdate(upload, download, read, write) }
    }

    private fun sendIntentToService(action: String, extra: Bundle? = null) {
        val intent = Intent(context, OrbotService::class.java)
        intent.action = action
        extra?.let { intent.putExtras(it) }
        context.startService(intent)
    }

    @SuppressLint("ApplySharedPref")
    private fun saveTorifiedApps(packageNames: Collection<String>) {
        packageNames.joinToString("|")
        Prefs.getSharedPrefs(context).edit().putString(
            OrbotConstants.PREFS_KEY_TORIFIED, packageNames.joinToString("|")
        ).commit()

        if (isServiceRunning()) {
            sendIntentToService(OrbotConstants.ACTION_RESTART_VPN)
        }
    }

    private fun getTorifiedApps(): Set<String> {
        val list = Prefs.getSharedPrefs(context).getString(OrbotConstants.PREFS_KEY_TORIFIED, "")
            ?.split("|")
        return if (list == null || list == listOf("")) {
            emptySet()
        } else {
            list.toSet()
        }
    }

    @SuppressLint("ApplySharedPref")
    private fun setExitCountryCode(countryCode: String) {
        val countryParam = when {
            countryCode.isEmpty() -> ""
            countryCode in EXIT_COUNTRY_CODES -> "{$countryCode}"
            else -> throw InvalidParameterException(
                "Only these countries are available: ${EXIT_COUNTRY_CODES.joinToString { ", " } }"
            )
        }

        if (isServiceRunning()) {
            val extra = Bundle()
            extra.putString("exit", countryParam)
            sendIntentToService(OrbotConstants.CMD_SET_EXIT, extra)
        } else {
            Prefs.getSharedPrefs(context)
                .edit().putString(PREFS_KEY_EXIT_NODES, countryParam)
                .commit()
        }
    }

    private fun getExitCountryCode(): String {
        val raw = Prefs.getExitNodes()
        return if (raw.isEmpty()) raw else raw.slice(1..2)
    }

    fun prepareAndroidVpn(): Intent? {
        return VpnService.prepare(context)
    }

    fun start(enableNotification: Boolean) {
        Prefs.enableNotification(enableNotification)
        Prefs.putUseVpn(true)
        Prefs.putStartOnBoot(true)

        sendIntentToService(OrbotConstants.ACTION_START)
        sendIntentToService(OrbotConstants.ACTION_START_VPN)
    }

    fun stop() {
        updateStatus(Status.STOPPING)

        Prefs.putUseVpn(false)
        Prefs.putStartOnBoot(false)

        sendIntentToService(OrbotConstants.ACTION_STOP_VPN)
        sendIntentToService(
            action = OrbotConstants.ACTION_STOP,
            extra = Bundle().apply { putBoolean(ACTION_STOP_FOREGROUND_TASK, true) }
        )
        stoppingWatchdog(5)
    }

    private fun stoppingWatchdog(countDown: Int) {
        Handler(Looper.getMainLooper()).postDelayed(
            {
                if (isServiceRunning() && countDown > 0) {
                    stoppingWatchdog(countDown - 1)
                } else {
                    updateStatus(Status.OFF, force = true)
                }
            },
            500
        )
    }

    fun requestStatus() {
        if (isServiceRunning()) {
            sendIntentToService(OrbotConstants.ACTION_STATUS)
        } else {
            updateStatus(Status.OFF, force = true)
        }
    }

    var appList: Set<String>
        get() = getTorifiedApps()
        set(value) = saveTorifiedApps(value)

    var exitCountry: String
        get() = getExitCountryCode()
        set(value) = setExitCountryCode(value)

    fun getAvailablesLocations(): Set<String> = EXIT_COUNTRY_CODES

    var httpProxyPort: Int = -1
        private set

    var socksProxyPort: Int = -1
        private set

    fun addListener(listener: Listener) {
        listeners.add(listener)
    }
    fun removeListener(listener: Listener) {
        listeners.remove(listener)
    }
    fun clearListeners() {
        listeners.clear()
    }

    fun onCleared() {
        LocalBroadcastManager.getInstance(context).unregisterReceiver(localBroadcastReceiver)
    }
}