TorController.kt 11.8 KB
Newer Older
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
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
364
365
366
367
368
369
370
371
372
373
374
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

package org.mozilla.fenix.tor

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.lifecycle.LifecycleCoroutineScope
import androidx.localbroadcastmanager.content.LocalBroadcastManager

import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeoutOrNull

import org.mozilla.fenix.BuildConfig

import org.torproject.android.service.TorService
import org.torproject.android.service.TorServiceConstants
import org.torproject.android.service.util.Prefs

interface TorEvents {
    fun onTorConnecting()
    fun onTorConnected()
    fun onTorStatusUpdate(entry: String?, status: String?)
    fun onTorStopped()
}

private enum class TorStatus {
    OFF,
    STARTING,
    ON,
    STOPPING,
    UNKNOWN;

    fun getStateFromString(status: String): TorStatus {
        return when (status) {
            TorServiceConstants.STATUS_ON -> ON
            TorServiceConstants.STATUS_STARTING -> STARTING
            TorServiceConstants.STATUS_STOPPING -> STOPPING
            TorServiceConstants.STATUS_OFF -> OFF
            else -> UNKNOWN
        }
    }

    fun isOff() = this == OFF
    fun isOn() = this == ON
    fun isStarting() = this == STARTING
    fun isStarted() = ((this == TorStatus.STARTING) || (this == TorStatus.ON))
    fun isStopping() = this == STOPPING
    fun isUnknown() = this == UNKNOWN
}

@SuppressWarnings("TooManyFunctions")
class TorController(
    private val context: Context
) : TorEvents {

    private val lbm: LocalBroadcastManager = LocalBroadcastManager.getInstance(context)
    private val entries = mutableListOf<Pair<String?, String?>>()
    val logEntries get() = entries

    private var torListeners = mutableListOf<TorEvents>()

    private var pendingRegisterChangeList = mutableListOf<Pair<TorEvents, Boolean>>()
    private var lockTorListenersMutation = false

    private var lastKnownStatus = TorStatus.OFF
    private var wasTorBootstrapped = false
    private var isTorRestarting = false

    // This may be a lie
    private var isTorBootstrapped = false
        get() = ((lastKnownStatus == TorStatus.ON) && wasTorBootstrapped)

    val isDebugLoggingEnabled get() =
        context
        .getSharedPreferences("org.torproject.android_preferences", Context.MODE_PRIVATE)
        .getBoolean("pref_enable_logging", false)

    val isStarting get() = lastKnownStatus.isStarting()
    val isRestarting get() = isTorRestarting
    val isBootstrapped get() = isTorBootstrapped
    val isConnected get() = (lastKnownStatus.isStarted() && !isTorRestarting)

    var bridgesEnabled: Boolean
        get() = Prefs.bridgesEnabled()
        set(value) { Prefs.putBridgesEnabled(value) }

    var bridgeTransport: TorBridgeTransportConfig
        get() {
            return TorBridgeTransportConfigUtil.getStringToBridgeTransport(
                Prefs.getBridgesList()
            )
        }
        set(value) {
            if (value == TorBridgeTransportConfig.USER_PROVIDED) {
                // Don't set the pref when the value is USER_PROVIDED because
                // "user_provided" is not a valid bridge or transport type.
                // This call should be followed by setting userProvidedBridges.
                return
            }
            Prefs.setBridgesList(value.transportName)
        }

    var userProvidedBridges: String?
        get() {
            val bridges = Prefs.getBridgesList()
            val bridgeType =
                TorBridgeTransportConfigUtil.getStringToBridgeTransport(bridges)
            return when (bridgeType) {
                TorBridgeTransportConfig.USER_PROVIDED -> bridges
                else -> null
            }
        }
        set(value) {
            Prefs.setBridgesList(value)
        }

    fun start() {
        // Register receiver
        lbm.registerReceiver(
            persistentBroadcastReceiver,
            IntentFilter(TorServiceConstants.ACTION_STATUS)
        )
        lbm.registerReceiver(
            persistentBroadcastReceiver,
            IntentFilter(TorServiceConstants.LOCAL_ACTION_LOG)
        )
    }

    fun stop() {
        lbm.unregisterReceiver(persistentBroadcastReceiver)
    }

    private val persistentBroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            if (intent.action == null ||
                (intent.action != TorServiceConstants.ACTION_STATUS &&
                intent.action != TorServiceConstants.LOCAL_ACTION_LOG)
            ) {
                    return
            }
            val action = intent.action

            val logentry: String?
            val status: String?
            if (action == TorServiceConstants.LOCAL_ACTION_LOG) {
                logentry = intent.getExtras()
                    ?.getCharSequence(TorServiceConstants.LOCAL_EXTRA_LOG) as? String?
            } else {
                logentry = null
            }

            status = intent.getExtras()
                ?.getCharSequence(TorServiceConstants.EXTRA_STATUS) as? String?

            if (logentry == null && status == null) {
                return
            }

            onTorStatusUpdate(logentry, status)

            if (status == null) {
                return
            }

            val newStatus = lastKnownStatus.getStateFromString(status)

            if (newStatus.isUnknown() && wasTorBootstrapped) {
                stopTor()
            }

            entries.add(Pair(logentry, status))

            if (logentry != null && logentry.contains(TorServiceConstants.TOR_CONTROL_PORT_MSG_BOOTSTRAP_DONE)) {
                wasTorBootstrapped = true
                onTorConnected()
            }

            if (lastKnownStatus.isStopping() && newStatus.isOff()) {
                if (isTorRestarting) {
                    initiateTorBootstrap()
                } else {
                    onTorStopped()
                }
            }

            if (lastKnownStatus.isOff() && newStatus.isStarting()) {
                isTorRestarting = false
            }

            lastKnownStatus = newStatus
        }
    }

    override fun onTorConnecting() {
        lockTorListenersMutation = true
        torListeners.forEach { it.onTorConnecting() }
        lockTorListenersMutation = false

        handlePendingRegistrationChanges()
    }

    override fun onTorConnected() {
        lockTorListenersMutation = true
        torListeners.forEach { it.onTorConnected() }
        lockTorListenersMutation = false

        handlePendingRegistrationChanges()
    }

    override fun onTorStatusUpdate(entry: String?, status: String?) {
        lockTorListenersMutation = true
        torListeners.forEach { it.onTorStatusUpdate(entry, status) }
        lockTorListenersMutation = false

        handlePendingRegistrationChanges()
    }

    override fun onTorStopped() {
        lockTorListenersMutation = true
        torListeners.forEach { it.onTorStopped() }
        lockTorListenersMutation = false

        handlePendingRegistrationChanges()
    }

    fun registerTorListener(l: TorEvents) {
        if (torListeners.contains(l)) {
            return
        }

        if (lockTorListenersMutation) {
            pendingRegisterChangeList.add(Pair(l, true))
        } else {
            torListeners.add(l)
        }
    }

    fun unregisterTorListener(l: TorEvents) {
        if (!torListeners.contains(l)) {
            return
        }

        if (lockTorListenersMutation) {
            pendingRegisterChangeList.add(Pair(l, false))
        } else {
            torListeners.remove(l)
        }
    }

    private fun handlePendingRegistrationChanges() {
        pendingRegisterChangeList.forEach {
            if (it.second) {
                registerTorListener(it.first)
            } else {
                unregisterTorListener(it.first)
            }
        }

        pendingRegisterChangeList.clear()
    }

    /**
     * Receive the current Tor status.
     *
     * Send a request for the current status and receive the response.
     * Returns true if Tor is running, false otherwise.
     *
     */
    private suspend fun checkTorIsStarted(): Boolean {
        val channel = Channel<Boolean>()

        // Register receiver
        val lbm: LocalBroadcastManager = LocalBroadcastManager.getInstance(context)
        val localBroadcastReceiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context, intent: Intent) {
                val action = intent.action ?: return
                // We only want ACTION_STATUS messages
                if (action != TorServiceConstants.ACTION_STATUS) {
                    return
                }
                // The current status has the EXTRA_STATUS key
                val currentStatus =
                    intent.getStringExtra(TorServiceConstants.EXTRA_STATUS)
                channel.offer(currentStatus === TorServiceConstants.STATUS_ON)
            }
        }
        lbm.registerReceiver(
            localBroadcastReceiver,
            IntentFilter(TorServiceConstants.ACTION_STATUS)
        )

        // Request service status
        sendServiceAction(TorServiceConstants.ACTION_STATUS)

        // Wait for response and unregister receiver
        var torIsStarted = false
        withTimeoutOrNull(torServiceResponseTimeout) {
            torIsStarted = channel.receive()
        }
        lbm.unregisterReceiver(localBroadcastReceiver)
        return torIsStarted
    }

    fun initiateTorBootstrap(lifecycleScope: LifecycleCoroutineScope? = null, withDebugLogging: Boolean = false) {
        if (BuildConfig.DISABLE_TOR) {
            return
        }

        context.getSharedPreferences("org.torproject.android_preferences", Context.MODE_PRIVATE)
            .edit().putBoolean("pref_enable_logging", withDebugLogging).apply()

        if (lifecycleScope == null) {
            sendServiceAction(TorServiceConstants.ACTION_START)
        } else {
            lifecycleScope.launch {
                val torNeedsStart = !checkTorIsStarted()
                if (torNeedsStart) {
                    sendServiceAction(TorServiceConstants.ACTION_START)
                }
            }
        }
    }

    fun stopTor() {
        if (BuildConfig.DISABLE_TOR) {
            return
        }

        val torService = Intent(context, TorService::class.java)
        context.stopService(torService)
    }

    fun setTorStopped() {
        lastKnownStatus = TorStatus.OFF
        onTorStopped()
    }

    fun restartTor() {
        // tor-android-service doesn't dynamically update the torrc file,
        // and it doesn't use SETCONF, so we completely restart the service.
        // However, don't restart if we aren't started and we weren't
        // previously started.
        if (!lastKnownStatus.isStarted() && !wasTorBootstrapped) {
            return
        }

        if (!lastKnownStatus.isStarted() && wasTorBootstrapped) {
            // If we aren't started, but we were previously bootstrapped,
            // then we handle a "restart" request as a "start" restart
            initiateTorBootstrap()
        } else {
            // |isTorRestarting| tracks the state of restart. When we receive an |OFF| state
            // from TorService in persistentBroadcastReceiver::onReceive we restart the Tor
            // service.
            isTorRestarting = true
            stopTor()
        }
    }

    private fun sendServiceAction(action: String) {
        val torServiceStatus = Intent(context, TorService::class.java)
        torServiceStatus.action = action
        context.startService(torServiceStatus)
    }

    companion object {
        const val torServiceResponseTimeout = 5000L
    }
}