forked from celzero/rethink-app
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathOneWgConfigAdapter.kt
More file actions
568 lines (510 loc) · 22.6 KB
/
Copy pathOneWgConfigAdapter.kt
File metadata and controls
568 lines (510 loc) · 22.6 KB
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
/*
* Copyright 2023 RethinkDNS and its authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.celzero.bravedns.adapter
import com.celzero.bravedns.util.Logger
import com.celzero.bravedns.util.Logger.LOG_TAG_PROXY
import android.content.Context
import android.content.Intent
import android.text.format.DateUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.view.isVisible
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.findViewTreeLifecycleOwner
import androidx.lifecycle.lifecycleScope
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.celzero.bravedns.R
import com.celzero.bravedns.customdownloader.IpInfoDownloader
import com.celzero.bravedns.database.EventSource
import com.celzero.bravedns.database.EventType
import com.celzero.bravedns.database.Severity
import com.celzero.bravedns.database.WgConfigFiles
import com.celzero.bravedns.databinding.ListItemWgOneInterfaceBinding
import com.celzero.bravedns.net.doh.Transaction
import com.celzero.bravedns.service.EventLogger
import com.celzero.bravedns.service.IpRulesManager
import com.celzero.bravedns.service.ProxyManager
import com.celzero.bravedns.service.VpnController
import com.celzero.bravedns.service.WireguardManager
import com.celzero.bravedns.service.WireguardManager.WG_UPTIME_THRESHOLD
import com.celzero.bravedns.ui.activity.WgConfigDetailActivity
import com.celzero.bravedns.ui.activity.WgConfigDetailActivity.Companion.INTENT_EXTRA_WG_TYPE
import com.celzero.bravedns.ui.activity.WgConfigEditorActivity.Companion.INTENT_EXTRA_WG_ID
import com.celzero.bravedns.util.UIUtils
import com.celzero.bravedns.util.UIUtils.fetchColor
import com.celzero.bravedns.util.Utilities
import com.celzero.firestack.backend.RouterStats
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import inet.ipaddr.HostName
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class OneWgConfigAdapter(private val context: Context, private val listener: DnsStatusListener, private val eventLogger: EventLogger) :
PagingDataAdapter<WgConfigFiles, OneWgConfigAdapter.WgInterfaceViewHolder>(DIFF_CALLBACK) {
private var lifecycleOwner: LifecycleOwner? = null
interface DnsStatusListener {
fun onDnsStatusChanged()
}
companion object {
private const val DELAY_MS = 1500L
private const val TAG = "OneWgCfgAdapter"
private val DIFF_CALLBACK =
object : DiffUtil.ItemCallback<WgConfigFiles>() {
override fun areItemsTheSame(
oldConnection: WgConfigFiles,
newConnection: WgConfigFiles
): Boolean {
return oldConnection == newConnection
}
override fun areContentsTheSame(
oldConnection: WgConfigFiles,
newConnection: WgConfigFiles
): Boolean {
return oldConnection == newConnection
}
}
}
override fun onBindViewHolder(holder: WgInterfaceViewHolder, position: Int) {
val wgConfigFiles: WgConfigFiles = getItem(position) ?: return
holder.update(wgConfigFiles)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WgInterfaceViewHolder {
val itemBinding =
ListItemWgOneInterfaceBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
if (lifecycleOwner == null) {
lifecycleOwner = parent.findViewTreeLifecycleOwner()
}
return WgInterfaceViewHolder(itemBinding)
}
override fun onViewDetachedFromWindow(holder: WgInterfaceViewHolder) {
super.onViewDetachedFromWindow(holder)
holder.cancelJobIfAny()
}
inner class WgInterfaceViewHolder(private val b: ListItemWgOneInterfaceBinding) :
RecyclerView.ViewHolder(b.root) {
private var job: Job? = null
fun update(config: WgConfigFiles) {
b.interfaceNameText.text = config.name
b.interfaceNameText.isSelected = true
b.interfaceIdText.text = context.getString(R.string.single_argument_parenthesis, config.id.toString())
val isWgActive = config.isActive && VpnController.hasTunnel()
b.oneWgCheck.isChecked = isWgActive
setupClickListeners(config)
io {
updateFlag(null, config.id)
}
if (isWgActive) {
keepStatusUpdated(config)
} else {
cancelJobIfAny()
disableInterface()
}
}
fun cancelJobIfAny() {
if (job?.isActive == true) {
job?.cancel()
}
}
private fun keepStatusUpdated(config: WgConfigFiles) {
job = io {
while (true) {
updateStatus(config)
delay(DELAY_MS)
}
}
}
private fun updateProtocolChip(pair: Pair<Boolean, Boolean>) {
if (b.protocolInfoChipGroup.isVisible) return
if (!pair.first && !pair.second) {
b.protocolInfoChipGroup.visibility = View.GONE
return
}
b.protocolInfoChipGroup.visibility = View.VISIBLE
if (pair.first) {
b.protocolInfoChipIpv4.visibility = View.VISIBLE
} else {
b.protocolInfoChipIpv4.visibility = View.GONE
}
if (pair.second) {
b.protocolInfoChipIpv6.visibility = View.VISIBLE
} else {
b.protocolInfoChipIpv6.visibility = View.GONE
}
}
private fun updateSplitTunnelChip(isSplitTunnel: Boolean) {
if (isSplitTunnel) {
b.chipSplitTunnel.visibility = View.VISIBLE
} else {
b.chipSplitTunnel.visibility = View.GONE
}
}
private suspend fun updateStatus(config: WgConfigFiles) {
// if the view is not active then cancel the job
if (
lifecycleOwner
?.lifecycle
?.currentState
?.isAtLeast(androidx.lifecycle.Lifecycle.State.STARTED) == false
) {
job?.cancel()
return
}
if (config.isActive && !VpnController.hasTunnel()) {
// Fix: disableInterface() modifies UI, must run on main thread
uiCtx { disableInterface() }
return
}
val id = ProxyManager.ID_WG_BASE + config.id
val statusPair = VpnController.getProxyStatusById(id)
val pair = VpnController.getSupportedIpVersion(id)
val c = WireguardManager.getConfigById(config.id)
val stats = VpnController.getProxyStats(id)
val addr = VpnController.getProxyAddrById(id)
val dnsStatusId = VpnController.getDnsStatus(ProxyManager.ID_WG_BASE + config.id)
val isSplitTunnel =
if (c?.getPeers()?.isNotEmpty() == true) {
VpnController.isSplitTunnelProxy(id, pair)
} else {
false
}
uiCtx {
updateStatusUi(config, statusPair, dnsStatusId, stats)
updateProtocolChip(pair)
updateSplitTunnelChip(isSplitTunnel)
if (!b.interfaceFlagText.isVisible) io { updateFlag(addr, config.id) }
}
}
private fun isDnsError(statusId: Int?): Boolean {
if (statusId == null) return true
val s = Transaction.Status.fromId(statusId)
return s == Transaction.Status.BAD_QUERY || s == Transaction.Status.BAD_RESPONSE || s == Transaction.Status.NO_RESPONSE || s == Transaction.Status.SEND_FAIL || s == Transaction.Status.CLIENT_ERROR || s == Transaction.Status.INTERNAL_ERROR || s == Transaction.Status.TRANSPORT_ERROR
}
private fun updateStatusUi(config: WgConfigFiles, statusPair: Pair<Int?, String>, dnsStatusId: Int?, stats: RouterStats?) {
if (config.isActive && VpnController.hasTunnel()) {
b.interfaceDetailCard.strokeWidth = 2
b.oneWgCheck.isChecked = true
b.interfaceAppsCount.visibility = View.VISIBLE
b.interfaceAppsCount.text = context.getString(R.string.one_wg_apps_added)
if (dnsStatusId != null) {
// check for dns failure cases and update the UI
if (isDnsError(dnsStatusId)) {
b.interfaceDetailCard.strokeColor = fetchColor(context, R.attr.chipTextNegative)
b.interfaceStatus.text =
context.getString(R.string.status_failing).replaceFirstChar(Char::titlecase)
} else {
// if dns status is not failing, then update the proxy status
updateProxyStatusUi(statusPair, stats)
}
} else {
// in one wg mode, if dns status should be available, this is a fallback case
updateProxyStatusUi(statusPair, stats)
}
b.interfaceActiveLayout.visibility = View.VISIBLE
val rxtx = getRxTx(stats)
val time = getUpTime(stats)
if (time.isNotEmpty()) {
val t = context.getString(R.string.logs_card_duration, time)
b.interfaceActiveUptime.text =
context.getString(
R.string.two_argument_space,
context.getString(R.string.lbl_active),
t
)
} else {
b.interfaceActiveUptime.text = context.getString(R.string.lbl_active)
}
b.interfaceActiveRxTx.text = rxtx
} else {
disableInterface()
}
}
private fun getStrokeColorForStatus(status: UIUtils.ProxyStatus?, stats: RouterStats?): Int{
val now = System.currentTimeMillis()
val lastOk = stats?.lastOK ?: 0L
val since = stats?.since ?: 0L
val isFailing = now - since > WG_UPTIME_THRESHOLD && lastOk == 0L
return when (status) {
UIUtils.ProxyStatus.TOK -> if (isFailing) R.attr.chipTextNeutral else R.attr.accentGood
UIUtils.ProxyStatus.TUP, UIUtils.ProxyStatus.TZZ, UIUtils.ProxyStatus.TNT -> R.attr.chipTextNeutral
else -> R.attr.chipTextNegative // TKO, TEND
}
}
private fun getStatusText(
status: UIUtils.ProxyStatus?,
handshakeTime: String? = null,
stats: RouterStats?,
errMsg: String? = null
): String {
if (status == null) {
val txt = if (errMsg != null) {
context.getString(R.string.status_waiting) + " ($errMsg)"
} else {
context.getString(R.string.status_waiting)
}
return txt.replaceFirstChar(Char::titlecase)
}
val now = System.currentTimeMillis()
val lastOk = stats?.lastOK ?: 0L
val since = stats?.since ?: 0L
if (now - since > WG_UPTIME_THRESHOLD && lastOk == 0L) {
return context.getString(R.string.status_failing).replaceFirstChar(Char::titlecase)
}
val baseText = context.getString(UIUtils.getProxyStatusStringRes(status.id))
.replaceFirstChar(Char::titlecase)
return if (stats?.lastOK != 0L && handshakeTime != null) {
context.getString(R.string.about_version_install_source, baseText, handshakeTime)
} else {
baseText
}
}
private fun updateProxyStatusUi(statusPair: Pair<Int?, String>, stats: RouterStats?) {
val status =
UIUtils.ProxyStatus.entries.find { it.id == statusPair.first } // Convert to enum
val handshakeTime = getHandshakeTime(stats).toString()
val strokeColor = getStrokeColorForStatus(status, stats)
b.interfaceDetailCard.strokeColor = fetchColor(context, strokeColor)
val statusText = getStatusText(status, handshakeTime, stats, statusPair.second)
b.interfaceStatus.text = statusText
}
private fun disableInterface() {
b.interfaceDetailCard.strokeWidth = 0
b.protocolInfoChipGroup.visibility = View.GONE
b.interfaceAppsCount.visibility = View.GONE
b.oneWgCheck.isChecked = false
b.interfaceActiveLayout.visibility = View.GONE
b.interfaceStatus.text =
context.getString(R.string.lbl_disabled).replaceFirstChar(Char::titlecase)
}
private fun stripPort(addr: String): String {
return IpRulesManager.splitHostPort(addr).first
}
private suspend fun updateFlag(addr: String?, configId: Int) {
var ip: String? = addr?.split(",")?.firstOrNull()?.trim()?.let { stripPort(it) }
if (ip.isNullOrBlank()) {
val c = WireguardManager.getConfigById(configId)
val host = c?.getPeers()?.getOrNull(0)?.getEndpoint()?.orElse(null)?.host
if (!host.isNullOrBlank() && HostName(host).asAddress() != null) {
ip = host
}
}
if (ip.isNullOrBlank()) {
uiCtx { b.interfaceFlagText.visibility = View.GONE }
return
}
val ipInfo = IpInfoDownloader.getIpInfo(ip)
uiCtx {
if (ipInfo != null && ipInfo.countryCode.isNotEmpty()) {
b.interfaceFlagText.text = Utilities.getFlag(ipInfo.countryCode)
b.interfaceFlagText.visibility = View.VISIBLE
} else {
b.interfaceFlagText.visibility = View.GONE
}
}
}
private fun getUpTime(stats: RouterStats?): CharSequence {
if (stats == null) {
return ""
}
if (stats.since <= 0L) {
return ""
}
val now = System.currentTimeMillis()
// returns a string describing 'time' as a time relative to 'now'
return DateUtils.getRelativeTimeSpanString(
stats.since,
now,
DateUtils.MINUTE_IN_MILLIS,
DateUtils.FORMAT_ABBREV_RELATIVE
)
}
private fun getRxTx(stats: RouterStats?): String {
if (stats == null) return ""
val rx =
context.getString(
R.string.symbol_download,
Utilities.humanReadableByteCount(stats.rx, true)
)
val tx =
context.getString(
R.string.symbol_upload,
Utilities.humanReadableByteCount(stats.tx, true)
)
return context.getString(R.string.two_argument_space, tx, rx)
}
private fun getHandshakeTime(stats: RouterStats?): CharSequence {
if (stats == null) {
return ""
}
if (stats.lastOK == 0L) {
return ""
}
val now = System.currentTimeMillis()
// returns a string describing 'time' as a time relative to 'now'
return DateUtils.getRelativeTimeSpanString(
stats.lastOK,
now,
DateUtils.MINUTE_IN_MILLIS,
DateUtils.FORMAT_ABBREV_RELATIVE
)
}
fun setupClickListeners(config: WgConfigFiles) {
b.interfaceDetailCard.setOnClickListener { launchConfigDetail(config.id) }
b.oneWgCheck.setOnClickListener {
val isChecked = b.oneWgCheck.isChecked
io {
if (isChecked) {
enableWgIfPossible(config)
} else {
disableWgIfPossible(config)
}
}
}
}
private suspend fun enableWgIfPossible(config: WgConfigFiles) {
if (!VpnController.hasTunnel()) {
Logger.i(LOG_TAG_PROXY, "$TAG VPN not active, cannot enable WireGuard")
uiCtx {
Utilities.showToastUiCentered(
context,
context.getString(R.string.settings_socks5_vpn_disabled_error),
Toast.LENGTH_LONG
)
// reset the check box
b.oneWgCheck.isChecked = false
}
return
}
// checks only for app mode, so show appropriate error message if not enabled
if (!WireguardManager.canEnableProxy()) {
Logger.i(LOG_TAG_PROXY, "not in DNS+Firewall mode, cannot enable WireGuard")
uiCtx {
// reset the check box
b.oneWgCheck.isChecked = false
Utilities.showToastUiCentered(
context,
context.getString(R.string.wireguard_dns_mode_conflict),
Toast.LENGTH_LONG
)
}
return
}
if (!WireguardManager.isValidConfig(config.id)) {
Logger.i(LOG_TAG_PROXY, "invalid WireGuard config")
uiCtx {
// reset the check box
b.oneWgCheck.isChecked = false
showInvalidConfigDialog()
}
return
}
// One-WireGuard is mutually exclusive: if another one-wg config is active, swap it
// out for the newly selected one rather than blocking the user with an error.
var replacedOthers = false
if (WireguardManager.isAnyOtherOneWgEnabled(config.id)) {
Logger.i(LOG_TAG_PROXY, "another one-wg config is active; replacing it")
WireguardManager.disableOtherOneWireGuardConfigs(config.id)
replacedOthers = true
}
Logger.i(LOG_TAG_PROXY, "enabling WireGuard, id: ${config.id}")
WireguardManager.updateOneWireGuardConfig(config.id, owg = true)
config.oneWireGuard = true
WireguardManager.enableConfig(config.toImmutable())
uiCtx {
listener.onDnsStatusChanged()
if (replacedOthers) {
Utilities.showToastUiCentered(
context,
context.getString(R.string.wireguard_replaced_active_config),
Toast.LENGTH_SHORT
)
}
}
logEvent("One-WireGuard enabled", "WG ID: ${config.id}")
}
// Shows an "invalid config" AlertDialog when an Activity context is
// available; otherwise falls back to a toast so the error is never silently dropped.
private fun showInvalidConfigDialog() {
val ctx = context
if (ctx is android.app.Activity && !ctx.isFinishing) {
MaterialAlertDialogBuilder(ctx, R.style.App_Dialog_NoDim)
.setTitle(R.string.wireguard_invalid_config_title)
.setMessage(R.string.wireguard_invalid_config_message)
.setCancelable(true)
.setPositiveButton(R.string.lbl_dismiss) { d, _ -> d.dismiss() }
.show()
} else {
Utilities.showToastUiCentered(
context,
context.getString(R.string.wireguard_invalid_config_message),
Toast.LENGTH_LONG
)
}
}
private suspend fun disableWgIfPossible(config: WgConfigFiles) {
if (!VpnController.hasTunnel()) {
Logger.i(LOG_TAG_PROXY, "VPN not active, cannot disable WireGuard")
uiCtx {
// reset the check box
b.oneWgCheck.isChecked = true
Utilities.showToastUiCentered(
context, context.getString(R.string.settings_socks5_vpn_disabled_error),
Toast.LENGTH_LONG
)
}
return
}
Logger.i(LOG_TAG_PROXY, "disabling WireGuard, id: ${config.id}")
WireguardManager.updateOneWireGuardConfig(config.id, owg = false)
config.oneWireGuard = false
WireguardManager.disableConfig(config.toImmutable())
uiCtx { listener.onDnsStatusChanged() }
logEvent("One-WireGuard disabled", "WG ID: ${config.id}")
}
private fun launchConfigDetail(id: Int) {
if (!VpnController.hasTunnel()) {
Utilities.showToastUiCentered(
context,
context.getString(R.string.ssv_toast_start_rethink),
Toast.LENGTH_SHORT
)
return
}
val intent = Intent(context, WgConfigDetailActivity::class.java)
intent.putExtra(INTENT_EXTRA_WG_ID, id)
intent.putExtra(INTENT_EXTRA_WG_TYPE, WgConfigDetailActivity.WgType.ONE_WG.value)
context.startActivity(intent)
}
}
private fun logEvent(msg: String, details: String) {
eventLogger.log(EventType.PROXY_SWITCH, Severity.LOW, msg, EventSource.UI, false, details)
}
private suspend fun uiCtx(f: suspend () -> Unit) {
withContext(Dispatchers.Main) { f() }
}
private fun io(f: suspend () -> Unit): Job? {
return lifecycleOwner?.lifecycleScope?.launch(Dispatchers.IO) { f() }
}
}